blob: 98e366c7bc220ba55fff450e697592004db6a420 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
2// 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"
Andrei Popescu402d9372010-02-26 13:31:12 +000034#include "codegen.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000035#include "compilation-cache.h"
36#include "compiler.h"
37#include "debug.h"
38#include "execution.h"
39#include "global-handles.h"
40#include "ic.h"
41#include "ic-inl.h"
Steve Block6ded16b2010-05-10 14:33:55 +010042#include "messages.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000043#include "natives.h"
44#include "stub-cache.h"
45#include "log.h"
46
47#include "../include/v8-debug.h"
48
49namespace v8 {
50namespace internal {
51
52#ifdef ENABLE_DEBUGGER_SUPPORT
53static void PrintLn(v8::Local<v8::Value> value) {
54 v8::Local<v8::String> s = value->ToString();
Kristian Monsen25f61362010-05-21 11:50:48 +010055 ScopedVector<char> data(s->Length() + 1);
56 if (data.start() == NULL) {
Steve Blocka7e24c12009-10-30 11:49:00 +000057 V8::FatalProcessOutOfMemory("PrintLn");
58 return;
59 }
Kristian Monsen25f61362010-05-21 11:50:48 +010060 s->WriteAscii(data.start());
61 PrintF("%s\n", data.start());
Steve Blocka7e24c12009-10-30 11:49:00 +000062}
63
64
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010065static Handle<Code> ComputeCallDebugBreak(int argc, Code::Kind kind) {
66 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugBreak(argc, kind), Code);
Steve Blocka7e24c12009-10-30 11:49:00 +000067}
68
69
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010070static Handle<Code> ComputeCallDebugPrepareStepIn(int argc, Code::Kind kind) {
71 CALL_HEAP_FUNCTION(
72 StubCache::ComputeCallDebugPrepareStepIn(argc, kind), Code);
Steve Blocka7e24c12009-10-30 11:49:00 +000073}
74
75
Leon Clarkef7060e22010-06-03 12:02:55 +010076static v8::Handle<v8::Context> GetDebugEventContext() {
77 Handle<Context> context = Debug::debugger_entry()->GetContext();
78 // Top::context() may have been NULL when "script collected" event occured.
79 if (*context == NULL) {
80 return v8::Local<v8::Context>();
81 }
82 Handle<Context> global_context(context->global_context());
83 return v8::Utils::ToLocal(global_context);
84}
85
86
Steve Blocka7e24c12009-10-30 11:49:00 +000087BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
88 BreakLocatorType type) {
89 debug_info_ = debug_info;
90 type_ = type;
Steve Blocka7e24c12009-10-30 11:49:00 +000091 reloc_iterator_ = NULL;
92 reloc_iterator_original_ = NULL;
93 Reset(); // Initialize the rest of the member variables.
94}
95
96
97BreakLocationIterator::~BreakLocationIterator() {
98 ASSERT(reloc_iterator_ != NULL);
99 ASSERT(reloc_iterator_original_ != NULL);
100 delete reloc_iterator_;
101 delete reloc_iterator_original_;
102}
103
104
105void BreakLocationIterator::Next() {
106 AssertNoAllocation nogc;
107 ASSERT(!RinfoDone());
108
109 // Iterate through reloc info for code and original code stopping at each
110 // breakable code target.
111 bool first = break_point_ == -1;
112 while (!RinfoDone()) {
113 if (!first) RinfoNext();
114 first = false;
115 if (RinfoDone()) return;
116
117 // Whenever a statement position or (plain) position is passed update the
118 // current value of these.
119 if (RelocInfo::IsPosition(rmode())) {
120 if (RelocInfo::IsStatementPosition(rmode())) {
Steve Blockd0582a62009-12-15 09:54:21 +0000121 statement_position_ = static_cast<int>(
122 rinfo()->data() - debug_info_->shared()->start_position());
Steve Blocka7e24c12009-10-30 11:49:00 +0000123 }
124 // Always update the position as we don't want that to be before the
125 // statement position.
Steve Blockd0582a62009-12-15 09:54:21 +0000126 position_ = static_cast<int>(
127 rinfo()->data() - debug_info_->shared()->start_position());
Steve Blocka7e24c12009-10-30 11:49:00 +0000128 ASSERT(position_ >= 0);
129 ASSERT(statement_position_ >= 0);
130 }
131
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100132 if (IsDebugBreakSlot()) {
133 // There is always a possible break point at a debug break slot.
134 break_point_++;
135 return;
136 } else if (RelocInfo::IsCodeTarget(rmode())) {
137 // Check for breakable code target. Look in the original code as setting
138 // break points can cause the code targets in the running (debugged) code
139 // to be of a different kind than in the original code.
Steve Blocka7e24c12009-10-30 11:49:00 +0000140 Address target = original_rinfo()->target_address();
141 Code* code = Code::GetCodeFromTargetAddress(target);
Steve Block6ded16b2010-05-10 14:33:55 +0100142 if ((code->is_inline_cache_stub() &&
143 code->kind() != Code::BINARY_OP_IC) ||
144 RelocInfo::IsConstructCall(rmode())) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000145 break_point_++;
146 return;
147 }
148 if (code->kind() == Code::STUB) {
149 if (IsDebuggerStatement()) {
150 break_point_++;
151 return;
152 }
153 if (type_ == ALL_BREAK_LOCATIONS) {
154 if (Debug::IsBreakStub(code)) {
155 break_point_++;
156 return;
157 }
158 } else {
159 ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
160 if (Debug::IsSourceBreakStub(code)) {
161 break_point_++;
162 return;
163 }
164 }
165 }
166 }
167
168 // Check for break at return.
169 if (RelocInfo::IsJSReturn(rmode())) {
170 // Set the positions to the end of the function.
171 if (debug_info_->shared()->HasSourceCode()) {
172 position_ = debug_info_->shared()->end_position() -
173 debug_info_->shared()->start_position();
174 } else {
175 position_ = 0;
176 }
177 statement_position_ = position_;
178 break_point_++;
179 return;
180 }
181 }
182}
183
184
185void BreakLocationIterator::Next(int count) {
186 while (count > 0) {
187 Next();
188 count--;
189 }
190}
191
192
193// Find the break point closest to the supplied address.
194void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
195 // Run through all break points to locate the one closest to the address.
196 int closest_break_point = 0;
197 int distance = kMaxInt;
198 while (!Done()) {
199 // Check if this break point is closer that what was previously found.
200 if (this->pc() < pc && pc - this->pc() < distance) {
201 closest_break_point = break_point();
Steve Blockd0582a62009-12-15 09:54:21 +0000202 distance = static_cast<int>(pc - this->pc());
Steve Blocka7e24c12009-10-30 11:49:00 +0000203 // Check whether we can't get any closer.
204 if (distance == 0) break;
205 }
206 Next();
207 }
208
209 // Move to the break point found.
210 Reset();
211 Next(closest_break_point);
212}
213
214
215// Find the break point closest to the supplied source position.
216void BreakLocationIterator::FindBreakLocationFromPosition(int position) {
217 // Run through all break points to locate the one closest to the source
218 // position.
219 int closest_break_point = 0;
220 int distance = kMaxInt;
221 while (!Done()) {
222 // Check if this break point is closer that what was previously found.
223 if (position <= statement_position() &&
224 statement_position() - position < distance) {
225 closest_break_point = break_point();
226 distance = statement_position() - position;
227 // Check whether we can't get any closer.
228 if (distance == 0) break;
229 }
230 Next();
231 }
232
233 // Move to the break point found.
234 Reset();
235 Next(closest_break_point);
236}
237
238
239void BreakLocationIterator::Reset() {
240 // Create relocation iterators for the two code objects.
241 if (reloc_iterator_ != NULL) delete reloc_iterator_;
242 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
243 reloc_iterator_ = new RelocIterator(debug_info_->code());
244 reloc_iterator_original_ = new RelocIterator(debug_info_->original_code());
245
246 // Position at the first break point.
247 break_point_ = -1;
248 position_ = 1;
249 statement_position_ = 1;
250 Next();
251}
252
253
254bool BreakLocationIterator::Done() const {
255 return RinfoDone();
256}
257
258
259void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
260 // If there is not already a real break point here patch code with debug
261 // break.
262 if (!HasBreakPoint()) {
263 SetDebugBreak();
264 }
265 ASSERT(IsDebugBreak() || IsDebuggerStatement());
266 // Set the break point information.
267 DebugInfo::SetBreakPoint(debug_info_, code_position(),
268 position(), statement_position(),
269 break_point_object);
270}
271
272
273void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
274 // Clear the break point information.
275 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
276 // If there are no more break points here remove the debug break.
277 if (!HasBreakPoint()) {
278 ClearDebugBreak();
279 ASSERT(!IsDebugBreak());
280 }
281}
282
283
284void BreakLocationIterator::SetOneShot() {
285 // Debugger statement always calls debugger. No need to modify it.
286 if (IsDebuggerStatement()) {
287 return;
288 }
289
290 // If there is a real break point here no more to do.
291 if (HasBreakPoint()) {
292 ASSERT(IsDebugBreak());
293 return;
294 }
295
296 // Patch code with debug break.
297 SetDebugBreak();
298}
299
300
301void BreakLocationIterator::ClearOneShot() {
302 // Debugger statement always calls debugger. No need to modify it.
303 if (IsDebuggerStatement()) {
304 return;
305 }
306
307 // If there is a real break point here no more to do.
308 if (HasBreakPoint()) {
309 ASSERT(IsDebugBreak());
310 return;
311 }
312
313 // Patch code removing debug break.
314 ClearDebugBreak();
315 ASSERT(!IsDebugBreak());
316}
317
318
319void BreakLocationIterator::SetDebugBreak() {
320 // Debugger statement always calls debugger. No need to modify it.
321 if (IsDebuggerStatement()) {
322 return;
323 }
324
325 // If there is already a break point here just return. This might happen if
326 // the same code is flooded with break points twice. Flooding the same
327 // function twice might happen when stepping in a function with an exception
328 // handler as the handler and the function is the same.
329 if (IsDebugBreak()) {
330 return;
331 }
332
333 if (RelocInfo::IsJSReturn(rmode())) {
334 // Patch the frame exit code with a break point.
335 SetDebugBreakAtReturn();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100336 } else if (IsDebugBreakSlot()) {
337 // Patch the code in the break slot.
338 SetDebugBreakAtSlot();
Steve Blocka7e24c12009-10-30 11:49:00 +0000339 } else {
340 // Patch the IC call.
341 SetDebugBreakAtIC();
342 }
343 ASSERT(IsDebugBreak());
344}
345
346
347void BreakLocationIterator::ClearDebugBreak() {
348 // Debugger statement always calls debugger. No need to modify it.
349 if (IsDebuggerStatement()) {
350 return;
351 }
352
353 if (RelocInfo::IsJSReturn(rmode())) {
354 // Restore the frame exit code.
355 ClearDebugBreakAtReturn();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100356 } else if (IsDebugBreakSlot()) {
357 // Restore the code in the break slot.
358 ClearDebugBreakAtSlot();
Steve Blocka7e24c12009-10-30 11:49:00 +0000359 } else {
360 // Patch the IC call.
361 ClearDebugBreakAtIC();
362 }
363 ASSERT(!IsDebugBreak());
364}
365
366
367void BreakLocationIterator::PrepareStepIn() {
368 HandleScope scope;
369
370 // Step in can only be prepared if currently positioned on an IC call,
371 // construct call or CallFunction stub call.
372 Address target = rinfo()->target_address();
373 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100374 if (code->is_call_stub() || code->is_keyed_call_stub()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000375 // Step in through IC call is handled by the runtime system. Therefore make
376 // sure that the any current IC is cleared and the runtime system is
377 // called. If the executing code has a debug break at the location change
378 // the call in the original code as it is the code there that will be
379 // executed in place of the debug break call.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100380 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count(),
381 code->kind());
Steve Blocka7e24c12009-10-30 11:49:00 +0000382 if (IsDebugBreak()) {
383 original_rinfo()->set_target_address(stub->entry());
384 } else {
385 rinfo()->set_target_address(stub->entry());
386 }
387 } else {
388#ifdef DEBUG
389 // All the following stuff is needed only for assertion checks so the code
390 // is wrapped in ifdef.
391 Handle<Code> maybe_call_function_stub = code;
392 if (IsDebugBreak()) {
393 Address original_target = original_rinfo()->target_address();
394 maybe_call_function_stub =
395 Handle<Code>(Code::GetCodeFromTargetAddress(original_target));
396 }
397 bool is_call_function_stub =
398 (maybe_call_function_stub->kind() == Code::STUB &&
399 maybe_call_function_stub->major_key() == CodeStub::CallFunction);
400
401 // Step in through construct call requires no changes to the running code.
402 // Step in through getters/setters should already be prepared as well
403 // because caller of this function (Debug::PrepareStep) is expected to
404 // flood the top frame's function with one shot breakpoints.
405 // Step in through CallFunction stub should also be prepared by caller of
406 // this function (Debug::PrepareStep) which should flood target function
407 // with breakpoints.
408 ASSERT(RelocInfo::IsConstructCall(rmode()) || code->is_inline_cache_stub()
409 || is_call_function_stub);
410#endif
411 }
412}
413
414
415// Check whether the break point is at a position which will exit the function.
416bool BreakLocationIterator::IsExit() const {
417 return (RelocInfo::IsJSReturn(rmode()));
418}
419
420
421bool BreakLocationIterator::HasBreakPoint() {
422 return debug_info_->HasBreakPoint(code_position());
423}
424
425
426// Check whether there is a debug break at the current position.
427bool BreakLocationIterator::IsDebugBreak() {
428 if (RelocInfo::IsJSReturn(rmode())) {
429 return IsDebugBreakAtReturn();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100430 } else if (IsDebugBreakSlot()) {
431 return IsDebugBreakAtSlot();
Steve Blocka7e24c12009-10-30 11:49:00 +0000432 } else {
433 return Debug::IsDebugBreak(rinfo()->target_address());
434 }
435}
436
437
438void BreakLocationIterator::SetDebugBreakAtIC() {
439 // Patch the original code with the current address as the current address
440 // might have changed by the inline caching since the code was copied.
441 original_rinfo()->set_target_address(rinfo()->target_address());
442
443 RelocInfo::Mode mode = rmode();
444 if (RelocInfo::IsCodeTarget(mode)) {
445 Address target = rinfo()->target_address();
446 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
447
448 // Patch the code to invoke the builtin debug break function matching the
449 // calling convention used by the call site.
450 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(code, mode));
451 rinfo()->set_target_address(dbgbrk_code->entry());
452
453 // For stubs that refer back to an inlined version clear the cached map for
454 // the inlined case to always go through the IC. As long as the break point
455 // is set the patching performed by the runtime system will take place in
456 // the code copy and will therefore have no effect on the running code
457 // keeping it from using the inlined code.
Kristian Monsen25f61362010-05-21 11:50:48 +0100458 if (code->is_keyed_load_stub()) {
459 KeyedLoadIC::ClearInlinedVersion(pc());
460 } else if (code->is_keyed_store_stub()) {
461 KeyedStoreIC::ClearInlinedVersion(pc());
462 } else if (code->is_load_stub()) {
463 LoadIC::ClearInlinedVersion(pc());
464 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000465 }
466}
467
468
469void BreakLocationIterator::ClearDebugBreakAtIC() {
470 // Patch the code to the original invoke.
471 rinfo()->set_target_address(original_rinfo()->target_address());
472
473 RelocInfo::Mode mode = rmode();
474 if (RelocInfo::IsCodeTarget(mode)) {
475 Address target = original_rinfo()->target_address();
476 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
477
478 // Restore the inlined version of keyed stores to get back to the
479 // fast case. We need to patch back the keyed store because no
480 // patching happens when running normally. For keyed loads, the
481 // map check will get patched back when running normally after ICs
482 // have been cleared at GC.
483 if (code->is_keyed_store_stub()) KeyedStoreIC::RestoreInlinedVersion(pc());
484 }
485}
486
487
488bool BreakLocationIterator::IsDebuggerStatement() {
Andrei Popescu402d9372010-02-26 13:31:12 +0000489 return RelocInfo::DEBUG_BREAK == rmode();
Steve Blocka7e24c12009-10-30 11:49:00 +0000490}
491
492
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100493bool BreakLocationIterator::IsDebugBreakSlot() {
494 return RelocInfo::DEBUG_BREAK_SLOT == rmode();
495}
496
497
Steve Blocka7e24c12009-10-30 11:49:00 +0000498Object* BreakLocationIterator::BreakPointObjects() {
499 return debug_info_->GetBreakPointObjects(code_position());
500}
501
502
503// Clear out all the debug break code. This is ONLY supposed to be used when
504// shutting down the debugger as it will leave the break point information in
505// DebugInfo even though the code is patched back to the non break point state.
506void BreakLocationIterator::ClearAllDebugBreak() {
507 while (!Done()) {
508 ClearDebugBreak();
509 Next();
510 }
511}
512
513
514bool BreakLocationIterator::RinfoDone() const {
515 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
516 return reloc_iterator_->done();
517}
518
519
520void BreakLocationIterator::RinfoNext() {
521 reloc_iterator_->next();
522 reloc_iterator_original_->next();
523#ifdef DEBUG
524 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
525 if (!reloc_iterator_->done()) {
526 ASSERT(rmode() == original_rmode());
527 }
528#endif
529}
530
531
532bool Debug::has_break_points_ = false;
533ScriptCache* Debug::script_cache_ = NULL;
534DebugInfoListNode* Debug::debug_info_list_ = NULL;
535
536
537// Threading support.
538void Debug::ThreadInit() {
539 thread_local_.break_count_ = 0;
540 thread_local_.break_id_ = 0;
541 thread_local_.break_frame_id_ = StackFrame::NO_ID;
542 thread_local_.last_step_action_ = StepNone;
543 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
544 thread_local_.step_count_ = 0;
545 thread_local_.last_fp_ = 0;
546 thread_local_.step_into_fp_ = 0;
547 thread_local_.step_out_fp_ = 0;
548 thread_local_.after_break_target_ = 0;
549 thread_local_.debugger_entry_ = NULL;
550 thread_local_.pending_interrupts_ = 0;
551}
552
553
554JSCallerSavedBuffer Debug::registers_;
555Debug::ThreadLocal Debug::thread_local_;
556
557
558char* Debug::ArchiveDebug(char* storage) {
559 char* to = storage;
560 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
561 to += sizeof(ThreadLocal);
562 memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
563 ThreadInit();
564 ASSERT(to <= storage + ArchiveSpacePerThread());
565 return storage + ArchiveSpacePerThread();
566}
567
568
569char* Debug::RestoreDebug(char* storage) {
570 char* from = storage;
571 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
572 from += sizeof(ThreadLocal);
573 memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
574 ASSERT(from <= storage + ArchiveSpacePerThread());
575 return storage + ArchiveSpacePerThread();
576}
577
578
579int Debug::ArchiveSpacePerThread() {
580 return sizeof(ThreadLocal) + sizeof(registers_);
581}
582
583
584// Default break enabled.
585bool Debug::disable_break_ = false;
586
587// Default call debugger on uncaught exception.
588bool Debug::break_on_exception_ = false;
589bool Debug::break_on_uncaught_exception_ = true;
590
591Handle<Context> Debug::debug_context_ = Handle<Context>();
592Code* Debug::debug_break_return_ = NULL;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100593Code* Debug::debug_break_slot_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000594
595
596void ScriptCache::Add(Handle<Script> script) {
597 // Create an entry in the hash map for the script.
598 int id = Smi::cast(script->id())->value();
599 HashMap::Entry* entry =
600 HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
601 if (entry->value != NULL) {
602 ASSERT(*script == *reinterpret_cast<Script**>(entry->value));
603 return;
604 }
605
606 // Globalize the script object, make it weak and use the location of the
607 // global handle as the value in the hash map.
608 Handle<Script> script_ =
609 Handle<Script>::cast((GlobalHandles::Create(*script)));
610 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(script_.location()),
611 this, ScriptCache::HandleWeakScript);
612 entry->value = script_.location();
613}
614
615
616Handle<FixedArray> ScriptCache::GetScripts() {
617 Handle<FixedArray> instances = Factory::NewFixedArray(occupancy());
618 int count = 0;
619 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
620 ASSERT(entry->value != NULL);
621 if (entry->value != NULL) {
622 instances->set(count, *reinterpret_cast<Script**>(entry->value));
623 count++;
624 }
625 }
626 return instances;
627}
628
629
630void ScriptCache::ProcessCollectedScripts() {
631 for (int i = 0; i < collected_scripts_.length(); i++) {
632 Debugger::OnScriptCollected(collected_scripts_[i]);
633 }
634 collected_scripts_.Clear();
635}
636
637
638void ScriptCache::Clear() {
639 // Iterate the script cache to get rid of all the weak handles.
640 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
641 ASSERT(entry != NULL);
642 Object** location = reinterpret_cast<Object**>(entry->value);
643 ASSERT((*location)->IsScript());
644 GlobalHandles::ClearWeakness(location);
645 GlobalHandles::Destroy(location);
646 }
647 // Clear the content of the hash map.
648 HashMap::Clear();
649}
650
651
652void ScriptCache::HandleWeakScript(v8::Persistent<v8::Value> obj, void* data) {
653 ScriptCache* script_cache = reinterpret_cast<ScriptCache*>(data);
654 // Find the location of the global handle.
655 Script** location =
656 reinterpret_cast<Script**>(Utils::OpenHandle(*obj).location());
657 ASSERT((*location)->IsScript());
658
659 // Remove the entry from the cache.
660 int id = Smi::cast((*location)->id())->value();
661 script_cache->Remove(reinterpret_cast<void*>(id), Hash(id));
662 script_cache->collected_scripts_.Add(id);
663
664 // Clear the weak handle.
665 obj.Dispose();
666 obj.Clear();
667}
668
669
670void Debug::Setup(bool create_heap_objects) {
671 ThreadInit();
672 if (create_heap_objects) {
673 // Get code to handle debug break on return.
674 debug_break_return_ =
675 Builtins::builtin(Builtins::Return_DebugBreak);
676 ASSERT(debug_break_return_->IsCode());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100677 // Get code to handle debug break in debug break slots.
678 debug_break_slot_ =
679 Builtins::builtin(Builtins::Slot_DebugBreak);
680 ASSERT(debug_break_slot_->IsCode());
Steve Blocka7e24c12009-10-30 11:49:00 +0000681 }
682}
683
684
685void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
686 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
687 RemoveDebugInfo(node->debug_info());
688#ifdef DEBUG
689 node = Debug::debug_info_list_;
690 while (node != NULL) {
691 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
692 node = node->next();
693 }
694#endif
695}
696
697
698DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
699 // Globalize the request debug info object and make it weak.
700 debug_info_ = Handle<DebugInfo>::cast((GlobalHandles::Create(debug_info)));
701 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
702 this, Debug::HandleWeakDebugInfo);
703}
704
705
706DebugInfoListNode::~DebugInfoListNode() {
707 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
708}
709
710
711bool Debug::CompileDebuggerScript(int index) {
712 HandleScope scope;
713
714 // Bail out if the index is invalid.
715 if (index == -1) {
716 return false;
717 }
718
719 // Find source and name for the requested script.
720 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
721 Vector<const char> name = Natives::GetScriptName(index);
722 Handle<String> script_name = Factory::NewStringFromAscii(name);
723
724 // Compile the script.
725 bool allow_natives_syntax = FLAG_allow_natives_syntax;
726 FLAG_allow_natives_syntax = true;
Steve Block6ded16b2010-05-10 14:33:55 +0100727 Handle<SharedFunctionInfo> function_info;
728 function_info = Compiler::Compile(source_code,
729 script_name,
730 0, 0, NULL, NULL,
731 Handle<String>::null(),
732 NATIVES_CODE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000733 FLAG_allow_natives_syntax = allow_natives_syntax;
734
735 // Silently ignore stack overflows during compilation.
Steve Block6ded16b2010-05-10 14:33:55 +0100736 if (function_info.is_null()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000737 ASSERT(Top::has_pending_exception());
738 Top::clear_pending_exception();
739 return false;
740 }
741
Steve Block6ded16b2010-05-10 14:33:55 +0100742 // Execute the shared function in the debugger context.
Steve Blocka7e24c12009-10-30 11:49:00 +0000743 Handle<Context> context = Top::global_context();
744 bool caught_exception = false;
745 Handle<JSFunction> function =
Steve Block6ded16b2010-05-10 14:33:55 +0100746 Factory::NewFunctionFromSharedFunctionInfo(function_info, context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000747 Handle<Object> result =
748 Execution::TryCall(function, Handle<Object>(context->global()),
749 0, NULL, &caught_exception);
750
751 // Check for caught exceptions.
752 if (caught_exception) {
753 Handle<Object> message = MessageHandler::MakeMessageObject(
754 "error_loading_debugger", NULL, Vector<Handle<Object> >::empty(),
755 Handle<String>());
756 MessageHandler::ReportMessage(NULL, message);
757 return false;
758 }
759
760 // Mark this script as native and return successfully.
761 Handle<Script> script(Script::cast(function->shared()->script()));
Steve Block6ded16b2010-05-10 14:33:55 +0100762 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
Steve Blocka7e24c12009-10-30 11:49:00 +0000763 return true;
764}
765
766
767bool Debug::Load() {
768 // Return if debugger is already loaded.
769 if (IsLoaded()) return true;
770
771 // Bail out if we're already in the process of compiling the native
772 // JavaScript source code for the debugger.
773 if (Debugger::compiling_natives() || Debugger::is_loading_debugger())
774 return false;
775 Debugger::set_loading_debugger(true);
776
777 // Disable breakpoints and interrupts while compiling and running the
778 // debugger scripts including the context creation code.
779 DisableBreak disable(true);
780 PostponeInterruptsScope postpone;
781
782 // Create the debugger context.
783 HandleScope scope;
784 Handle<Context> context =
785 Bootstrapper::CreateEnvironment(Handle<Object>::null(),
786 v8::Handle<ObjectTemplate>(),
787 NULL);
788
789 // Use the debugger context.
790 SaveContext save;
791 Top::set_context(*context);
792
793 // Expose the builtins object in the debugger context.
794 Handle<String> key = Factory::LookupAsciiSymbol("builtins");
795 Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
796 SetProperty(global, key, Handle<Object>(global->builtins()), NONE);
797
798 // Compile the JavaScript for the debugger in the debugger context.
799 Debugger::set_compiling_natives(true);
800 bool caught_exception =
801 !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
802 !CompileDebuggerScript(Natives::GetIndex("debug"));
Steve Block6ded16b2010-05-10 14:33:55 +0100803
804 if (FLAG_enable_liveedit) {
805 caught_exception = caught_exception ||
806 !CompileDebuggerScript(Natives::GetIndex("liveedit"));
807 }
808
Steve Blocka7e24c12009-10-30 11:49:00 +0000809 Debugger::set_compiling_natives(false);
810
811 // Make sure we mark the debugger as not loading before we might
812 // return.
813 Debugger::set_loading_debugger(false);
814
815 // Check for caught exceptions.
816 if (caught_exception) return false;
817
818 // Debugger loaded.
819 debug_context_ = Handle<Context>::cast(GlobalHandles::Create(*context));
820
821 return true;
822}
823
824
825void Debug::Unload() {
826 // Return debugger is not loaded.
827 if (!IsLoaded()) {
828 return;
829 }
830
831 // Clear the script cache.
832 DestroyScriptCache();
833
834 // Clear debugger context global handle.
835 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_context_.location()));
836 debug_context_ = Handle<Context>();
837}
838
839
840// Set the flag indicating that preemption happened during debugging.
841void Debug::PreemptionWhileInDebugger() {
842 ASSERT(InDebugger());
843 Debug::set_interrupts_pending(PREEMPT);
844}
845
846
847void Debug::Iterate(ObjectVisitor* v) {
Steve Block6ded16b2010-05-10 14:33:55 +0100848 v->VisitPointer(BitCast<Object**, Code**>(&(debug_break_return_)));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100849 v->VisitPointer(BitCast<Object**, Code**>(&(debug_break_slot_)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000850}
851
852
853Object* Debug::Break(Arguments args) {
854 HandleScope scope;
855 ASSERT(args.length() == 0);
856
Steve Block6ded16b2010-05-10 14:33:55 +0100857 thread_local_.frames_are_dropped_ = false;
858
Steve Blocka7e24c12009-10-30 11:49:00 +0000859 // Get the top-most JavaScript frame.
860 JavaScriptFrameIterator it;
861 JavaScriptFrame* frame = it.frame();
862
863 // Just continue if breaks are disabled or debugger cannot be loaded.
864 if (disable_break() || !Load()) {
865 SetAfterBreakTarget(frame);
866 return Heap::undefined_value();
867 }
868
869 // Enter the debugger.
870 EnterDebugger debugger;
871 if (debugger.FailedToEnter()) {
872 return Heap::undefined_value();
873 }
874
875 // Postpone interrupt during breakpoint processing.
876 PostponeInterruptsScope postpone;
877
878 // Get the debug info (create it if it does not exist).
879 Handle<SharedFunctionInfo> shared =
880 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
881 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
882
883 // Find the break point where execution has stopped.
884 BreakLocationIterator break_location_iterator(debug_info,
885 ALL_BREAK_LOCATIONS);
886 break_location_iterator.FindBreakLocationFromAddress(frame->pc());
887
888 // Check whether step next reached a new statement.
889 if (!StepNextContinue(&break_location_iterator, frame)) {
890 // Decrease steps left if performing multiple steps.
891 if (thread_local_.step_count_ > 0) {
892 thread_local_.step_count_--;
893 }
894 }
895
896 // If there is one or more real break points check whether any of these are
897 // triggered.
898 Handle<Object> break_points_hit(Heap::undefined_value());
899 if (break_location_iterator.HasBreakPoint()) {
900 Handle<Object> break_point_objects =
901 Handle<Object>(break_location_iterator.BreakPointObjects());
902 break_points_hit = CheckBreakPoints(break_point_objects);
903 }
904
905 // If step out is active skip everything until the frame where we need to step
906 // out to is reached, unless real breakpoint is hit.
907 if (Debug::StepOutActive() && frame->fp() != Debug::step_out_fp() &&
908 break_points_hit->IsUndefined() ) {
909 // Step count should always be 0 for StepOut.
910 ASSERT(thread_local_.step_count_ == 0);
911 } else if (!break_points_hit->IsUndefined() ||
912 (thread_local_.last_step_action_ != StepNone &&
913 thread_local_.step_count_ == 0)) {
914 // Notify debugger if a real break point is triggered or if performing
915 // single stepping with no more steps to perform. Otherwise do another step.
916
917 // Clear all current stepping setup.
918 ClearStepping();
919
920 // Notify the debug event listeners.
921 Debugger::OnDebugBreak(break_points_hit, false);
922 } else if (thread_local_.last_step_action_ != StepNone) {
923 // Hold on to last step action as it is cleared by the call to
924 // ClearStepping.
925 StepAction step_action = thread_local_.last_step_action_;
926 int step_count = thread_local_.step_count_;
927
928 // Clear all current stepping setup.
929 ClearStepping();
930
931 // Set up for the remaining steps.
932 PrepareStep(step_action, step_count);
933 }
934
Steve Block6ded16b2010-05-10 14:33:55 +0100935 if (thread_local_.frames_are_dropped_) {
936 // We must have been calling IC stub. Do not return there anymore.
937 Code* plain_return = Builtins::builtin(Builtins::PlainReturn_LiveEdit);
938 thread_local_.after_break_target_ = plain_return->entry();
939 } else {
940 SetAfterBreakTarget(frame);
941 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000942
943 return Heap::undefined_value();
944}
945
946
947// Check the break point objects for whether one or more are actually
948// triggered. This function returns a JSArray with the break point objects
949// which is triggered.
950Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
951 int break_points_hit_count = 0;
952 Handle<JSArray> break_points_hit = Factory::NewJSArray(1);
953
954 // If there are multiple break points they are in a FixedArray.
955 ASSERT(!break_point_objects->IsUndefined());
956 if (break_point_objects->IsFixedArray()) {
957 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
958 for (int i = 0; i < array->length(); i++) {
959 Handle<Object> o(array->get(i));
960 if (CheckBreakPoint(o)) {
961 break_points_hit->SetElement(break_points_hit_count++, *o);
962 }
963 }
964 } else {
965 if (CheckBreakPoint(break_point_objects)) {
966 break_points_hit->SetElement(break_points_hit_count++,
967 *break_point_objects);
968 }
969 }
970
971 // Return undefined if no break points where triggered.
972 if (break_points_hit_count == 0) {
973 return Factory::undefined_value();
974 }
975 return break_points_hit;
976}
977
978
979// Check whether a single break point object is triggered.
980bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
981 HandleScope scope;
982
983 // Ignore check if break point object is not a JSObject.
984 if (!break_point_object->IsJSObject()) return true;
985
986 // Get the function CheckBreakPoint (defined in debug.js).
987 Handle<JSFunction> check_break_point =
988 Handle<JSFunction>(JSFunction::cast(
989 debug_context()->global()->GetProperty(
990 *Factory::LookupAsciiSymbol("IsBreakPointTriggered"))));
991
992 // Get the break id as an object.
993 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
994
995 // Call HandleBreakPointx.
996 bool caught_exception = false;
997 const int argc = 2;
998 Object** argv[argc] = {
999 break_id.location(),
1000 reinterpret_cast<Object**>(break_point_object.location())
1001 };
1002 Handle<Object> result = Execution::TryCall(check_break_point,
1003 Top::builtins(), argc, argv,
1004 &caught_exception);
1005
1006 // If exception or non boolean result handle as not triggered
1007 if (caught_exception || !result->IsBoolean()) {
1008 return false;
1009 }
1010
1011 // Return whether the break point is triggered.
1012 return *result == Heap::true_value();
1013}
1014
1015
1016// Check whether the function has debug information.
1017bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
1018 return !shared->debug_info()->IsUndefined();
1019}
1020
1021
1022// Return the debug info for this function. EnsureDebugInfo must be called
1023// prior to ensure the debug info has been generated for shared.
1024Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
1025 ASSERT(HasDebugInfo(shared));
1026 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
1027}
1028
1029
1030void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
1031 int source_position,
1032 Handle<Object> break_point_object) {
1033 HandleScope scope;
1034
1035 if (!EnsureDebugInfo(shared)) {
1036 // Return if retrieving debug info failed.
1037 return;
1038 }
1039
1040 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1041 // Source positions starts with zero.
1042 ASSERT(source_position >= 0);
1043
1044 // Find the break point and change it.
1045 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1046 it.FindBreakLocationFromPosition(source_position);
1047 it.SetBreakPoint(break_point_object);
1048
1049 // At least one active break point now.
1050 ASSERT(debug_info->GetBreakPointCount() > 0);
1051}
1052
1053
1054void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
1055 HandleScope scope;
1056
1057 DebugInfoListNode* node = debug_info_list_;
1058 while (node != NULL) {
1059 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
1060 break_point_object);
1061 if (!result->IsUndefined()) {
1062 // Get information in the break point.
1063 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
1064 Handle<DebugInfo> debug_info = node->debug_info();
1065 Handle<SharedFunctionInfo> shared(debug_info->shared());
1066 int source_position = break_point_info->statement_position()->value();
1067
1068 // Source positions starts with zero.
1069 ASSERT(source_position >= 0);
1070
1071 // Find the break point and clear it.
1072 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1073 it.FindBreakLocationFromPosition(source_position);
1074 it.ClearBreakPoint(break_point_object);
1075
1076 // If there are no more break points left remove the debug info for this
1077 // function.
1078 if (debug_info->GetBreakPointCount() == 0) {
1079 RemoveDebugInfo(debug_info);
1080 }
1081
1082 return;
1083 }
1084 node = node->next();
1085 }
1086}
1087
1088
1089void Debug::ClearAllBreakPoints() {
1090 DebugInfoListNode* node = debug_info_list_;
1091 while (node != NULL) {
1092 // Remove all debug break code.
1093 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1094 it.ClearAllDebugBreak();
1095 node = node->next();
1096 }
1097
1098 // Remove all debug info.
1099 while (debug_info_list_ != NULL) {
1100 RemoveDebugInfo(debug_info_list_->debug_info());
1101 }
1102}
1103
1104
1105void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
1106 // Make sure the function has setup the debug info.
1107 if (!EnsureDebugInfo(shared)) {
1108 // Return if we failed to retrieve the debug info.
1109 return;
1110 }
1111
1112 // Flood the function with break points.
1113 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
1114 while (!it.Done()) {
1115 it.SetOneShot();
1116 it.Next();
1117 }
1118}
1119
1120
1121void Debug::FloodHandlerWithOneShot() {
1122 // Iterate through the JavaScript stack looking for handlers.
1123 StackFrame::Id id = break_frame_id();
1124 if (id == StackFrame::NO_ID) {
1125 // If there is no JavaScript stack don't do anything.
1126 return;
1127 }
1128 for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) {
1129 JavaScriptFrame* frame = it.frame();
1130 if (frame->HasHandler()) {
1131 Handle<SharedFunctionInfo> shared =
1132 Handle<SharedFunctionInfo>(
1133 JSFunction::cast(frame->function())->shared());
1134 // Flood the function with the catch block with break points
1135 FloodWithOneShot(shared);
1136 return;
1137 }
1138 }
1139}
1140
1141
1142void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
1143 if (type == BreakUncaughtException) {
1144 break_on_uncaught_exception_ = enable;
1145 } else {
1146 break_on_exception_ = enable;
1147 }
1148}
1149
1150
1151void Debug::PrepareStep(StepAction step_action, int step_count) {
1152 HandleScope scope;
1153 ASSERT(Debug::InDebugger());
1154
1155 // Remember this step action and count.
1156 thread_local_.last_step_action_ = step_action;
1157 if (step_action == StepOut) {
1158 // For step out target frame will be found on the stack so there is no need
1159 // to set step counter for it. It's expected to always be 0 for StepOut.
1160 thread_local_.step_count_ = 0;
1161 } else {
1162 thread_local_.step_count_ = step_count;
1163 }
1164
1165 // Get the frame where the execution has stopped and skip the debug frame if
1166 // any. The debug frame will only be present if execution was stopped due to
1167 // hitting a break point. In other situations (e.g. unhandled exception) the
1168 // debug frame is not present.
1169 StackFrame::Id id = break_frame_id();
1170 if (id == StackFrame::NO_ID) {
1171 // If there is no JavaScript stack don't do anything.
1172 return;
1173 }
1174 JavaScriptFrameIterator frames_it(id);
1175 JavaScriptFrame* frame = frames_it.frame();
1176
1177 // First of all ensure there is one-shot break points in the top handler
1178 // if any.
1179 FloodHandlerWithOneShot();
1180
1181 // If the function on the top frame is unresolved perform step out. This will
1182 // be the case when calling unknown functions and having the debugger stopped
1183 // in an unhandled exception.
1184 if (!frame->function()->IsJSFunction()) {
1185 // Step out: Find the calling JavaScript frame and flood it with
1186 // breakpoints.
1187 frames_it.Advance();
1188 // Fill the function to return to with one-shot break points.
1189 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1190 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1191 return;
1192 }
1193
1194 // Get the debug info (create it if it does not exist).
1195 Handle<SharedFunctionInfo> shared =
1196 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
1197 if (!EnsureDebugInfo(shared)) {
1198 // Return if ensuring debug info failed.
1199 return;
1200 }
1201 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1202
1203 // Find the break location where execution has stopped.
1204 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1205 it.FindBreakLocationFromAddress(frame->pc());
1206
1207 // Compute whether or not the target is a call target.
1208 bool is_call_target = false;
1209 bool is_load_or_store = false;
1210 bool is_inline_cache_stub = false;
1211 Handle<Code> call_function_stub;
1212 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
1213 Address target = it.rinfo()->target_address();
1214 Code* code = Code::GetCodeFromTargetAddress(target);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001215 if (code->is_call_stub() || code->is_keyed_call_stub()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001216 is_call_target = true;
1217 }
1218 if (code->is_inline_cache_stub()) {
1219 is_inline_cache_stub = true;
1220 is_load_or_store = !is_call_target;
1221 }
1222
1223 // Check if target code is CallFunction stub.
1224 Code* maybe_call_function_stub = code;
1225 // If there is a breakpoint at this line look at the original code to
1226 // check if it is a CallFunction stub.
1227 if (it.IsDebugBreak()) {
1228 Address original_target = it.original_rinfo()->target_address();
1229 maybe_call_function_stub =
1230 Code::GetCodeFromTargetAddress(original_target);
1231 }
1232 if (maybe_call_function_stub->kind() == Code::STUB &&
1233 maybe_call_function_stub->major_key() == CodeStub::CallFunction) {
1234 // Save reference to the code as we may need it to find out arguments
1235 // count for 'step in' later.
1236 call_function_stub = Handle<Code>(maybe_call_function_stub);
1237 }
1238 }
1239
1240 // If this is the last break code target step out is the only possibility.
1241 if (it.IsExit() || step_action == StepOut) {
1242 if (step_action == StepOut) {
1243 // Skip step_count frames starting with the current one.
1244 while (step_count-- > 0 && !frames_it.done()) {
1245 frames_it.Advance();
1246 }
1247 } else {
1248 ASSERT(it.IsExit());
1249 frames_it.Advance();
1250 }
1251 // Skip builtin functions on the stack.
1252 while (!frames_it.done() &&
1253 JSFunction::cast(frames_it.frame()->function())->IsBuiltin()) {
1254 frames_it.Advance();
1255 }
1256 // Step out: If there is a JavaScript caller frame, we need to
1257 // flood it with breakpoints.
1258 if (!frames_it.done()) {
1259 // Fill the function to return to with one-shot break points.
1260 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1261 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1262 // Set target frame pointer.
1263 ActivateStepOut(frames_it.frame());
1264 }
1265 } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) ||
1266 !call_function_stub.is_null())
1267 || step_action == StepNext || step_action == StepMin) {
1268 // Step next or step min.
1269
1270 // Fill the current function with one-shot break points.
1271 FloodWithOneShot(shared);
1272
1273 // Remember source position and frame to handle step next.
1274 thread_local_.last_statement_position_ =
1275 debug_info->code()->SourceStatementPosition(frame->pc());
1276 thread_local_.last_fp_ = frame->fp();
1277 } else {
1278 // If it's CallFunction stub ensure target function is compiled and flood
1279 // it with one shot breakpoints.
1280 if (!call_function_stub.is_null()) {
1281 // Find out number of arguments from the stub minor key.
1282 // Reverse lookup required as the minor key cannot be retrieved
1283 // from the code object.
1284 Handle<Object> obj(
1285 Heap::code_stubs()->SlowReverseLookup(*call_function_stub));
1286 ASSERT(*obj != Heap::undefined_value());
1287 ASSERT(obj->IsSmi());
1288 // Get the STUB key and extract major and minor key.
1289 uint32_t key = Smi::cast(*obj)->value();
1290 // Argc in the stub is the number of arguments passed - not the
1291 // expected arguments of the called function.
Leon Clarkee46be812010-01-19 14:06:41 +00001292 int call_function_arg_count =
1293 CallFunctionStub::ExtractArgcFromMinorKey(
1294 CodeStub::MinorKeyFromKey(key));
Steve Blocka7e24c12009-10-30 11:49:00 +00001295 ASSERT(call_function_stub->major_key() ==
1296 CodeStub::MajorKeyFromKey(key));
1297
1298 // Find target function on the expression stack.
Leon Clarkee46be812010-01-19 14:06:41 +00001299 // Expression stack looks like this (top to bottom):
Steve Blocka7e24c12009-10-30 11:49:00 +00001300 // argN
1301 // ...
1302 // arg0
1303 // Receiver
1304 // Function to call
1305 int expressions_count = frame->ComputeExpressionsCount();
1306 ASSERT(expressions_count - 2 - call_function_arg_count >= 0);
1307 Object* fun = frame->GetExpression(
1308 expressions_count - 2 - call_function_arg_count);
1309 if (fun->IsJSFunction()) {
1310 Handle<JSFunction> js_function(JSFunction::cast(fun));
1311 // Don't step into builtins.
1312 if (!js_function->IsBuiltin()) {
1313 // It will also compile target function if it's not compiled yet.
1314 FloodWithOneShot(Handle<SharedFunctionInfo>(js_function->shared()));
1315 }
1316 }
1317 }
1318
1319 // Fill the current function with one-shot break points even for step in on
1320 // a call target as the function called might be a native function for
1321 // which step in will not stop. It also prepares for stepping in
1322 // getters/setters.
1323 FloodWithOneShot(shared);
1324
1325 if (is_load_or_store) {
1326 // Remember source position and frame to handle step in getter/setter. If
1327 // there is a custom getter/setter it will be handled in
1328 // Object::Get/SetPropertyWithCallback, otherwise the step action will be
1329 // propagated on the next Debug::Break.
1330 thread_local_.last_statement_position_ =
1331 debug_info->code()->SourceStatementPosition(frame->pc());
1332 thread_local_.last_fp_ = frame->fp();
1333 }
1334
1335 // Step in or Step in min
1336 it.PrepareStepIn();
1337 ActivateStepIn(frame);
1338 }
1339}
1340
1341
1342// Check whether the current debug break should be reported to the debugger. It
1343// is used to have step next and step in only report break back to the debugger
1344// if on a different frame or in a different statement. In some situations
1345// there will be several break points in the same statement when the code is
1346// flooded with one-shot break points. This function helps to perform several
1347// steps before reporting break back to the debugger.
1348bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
1349 JavaScriptFrame* frame) {
1350 // If the step last action was step next or step in make sure that a new
1351 // statement is hit.
1352 if (thread_local_.last_step_action_ == StepNext ||
1353 thread_local_.last_step_action_ == StepIn) {
1354 // Never continue if returning from function.
1355 if (break_location_iterator->IsExit()) return false;
1356
1357 // Continue if we are still on the same frame and in the same statement.
1358 int current_statement_position =
1359 break_location_iterator->code()->SourceStatementPosition(frame->pc());
1360 return thread_local_.last_fp_ == frame->fp() &&
1361 thread_local_.last_statement_position_ == current_statement_position;
1362 }
1363
1364 // No step next action - don't continue.
1365 return false;
1366}
1367
1368
1369// Check whether the code object at the specified address is a debug break code
1370// object.
1371bool Debug::IsDebugBreak(Address addr) {
1372 Code* code = Code::GetCodeFromTargetAddress(addr);
1373 return code->ic_state() == DEBUG_BREAK;
1374}
1375
1376
1377// Check whether a code stub with the specified major key is a possible break
1378// point location when looking for source break locations.
1379bool Debug::IsSourceBreakStub(Code* code) {
1380 CodeStub::Major major_key = code->major_key();
1381 return major_key == CodeStub::CallFunction;
1382}
1383
1384
1385// Check whether a code stub with the specified major key is a possible break
1386// location.
1387bool Debug::IsBreakStub(Code* code) {
1388 CodeStub::Major major_key = code->major_key();
1389 return major_key == CodeStub::CallFunction ||
1390 major_key == CodeStub::StackCheck;
1391}
1392
1393
1394// Find the builtin to use for invoking the debug break
1395Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) {
1396 // Find the builtin debug break function matching the calling convention
1397 // used by the call site.
1398 if (code->is_inline_cache_stub()) {
Steve Block6ded16b2010-05-10 14:33:55 +01001399 switch (code->kind()) {
1400 case Code::CALL_IC:
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001401 case Code::KEYED_CALL_IC:
1402 return ComputeCallDebugBreak(code->arguments_count(), code->kind());
Steve Block6ded16b2010-05-10 14:33:55 +01001403
1404 case Code::LOAD_IC:
1405 return Handle<Code>(Builtins::builtin(Builtins::LoadIC_DebugBreak));
1406
1407 case Code::STORE_IC:
1408 return Handle<Code>(Builtins::builtin(Builtins::StoreIC_DebugBreak));
1409
1410 case Code::KEYED_LOAD_IC:
1411 return Handle<Code>(
1412 Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak));
1413
1414 case Code::KEYED_STORE_IC:
1415 return Handle<Code>(
1416 Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak));
1417
1418 default:
1419 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +00001420 }
1421 }
1422 if (RelocInfo::IsConstructCall(mode)) {
1423 Handle<Code> result =
1424 Handle<Code>(Builtins::builtin(Builtins::ConstructCall_DebugBreak));
1425 return result;
1426 }
1427 if (code->kind() == Code::STUB) {
1428 ASSERT(code->major_key() == CodeStub::CallFunction ||
1429 code->major_key() == CodeStub::StackCheck);
1430 Handle<Code> result =
1431 Handle<Code>(Builtins::builtin(Builtins::StubNoRegisters_DebugBreak));
1432 return result;
1433 }
1434
1435 UNREACHABLE();
1436 return Handle<Code>::null();
1437}
1438
1439
1440// Simple function for returning the source positions for active break points.
1441Handle<Object> Debug::GetSourceBreakLocations(
1442 Handle<SharedFunctionInfo> shared) {
1443 if (!HasDebugInfo(shared)) return Handle<Object>(Heap::undefined_value());
1444 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1445 if (debug_info->GetBreakPointCount() == 0) {
1446 return Handle<Object>(Heap::undefined_value());
1447 }
1448 Handle<FixedArray> locations =
1449 Factory::NewFixedArray(debug_info->GetBreakPointCount());
1450 int count = 0;
1451 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1452 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1453 BreakPointInfo* break_point_info =
1454 BreakPointInfo::cast(debug_info->break_points()->get(i));
1455 if (break_point_info->GetBreakPointCount() > 0) {
1456 locations->set(count++, break_point_info->statement_position());
1457 }
1458 }
1459 }
1460 return locations;
1461}
1462
1463
1464void Debug::NewBreak(StackFrame::Id break_frame_id) {
1465 thread_local_.break_frame_id_ = break_frame_id;
1466 thread_local_.break_id_ = ++thread_local_.break_count_;
1467}
1468
1469
1470void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
1471 thread_local_.break_frame_id_ = break_frame_id;
1472 thread_local_.break_id_ = break_id;
1473}
1474
1475
1476// Handle stepping into a function.
1477void Debug::HandleStepIn(Handle<JSFunction> function,
1478 Handle<Object> holder,
1479 Address fp,
1480 bool is_constructor) {
1481 // If the frame pointer is not supplied by the caller find it.
1482 if (fp == 0) {
1483 StackFrameIterator it;
1484 it.Advance();
1485 // For constructor functions skip another frame.
1486 if (is_constructor) {
1487 ASSERT(it.frame()->is_construct());
1488 it.Advance();
1489 }
1490 fp = it.frame()->fp();
1491 }
1492
1493 // Flood the function with one-shot break points if it is called from where
1494 // step into was requested.
1495 if (fp == Debug::step_in_fp()) {
1496 // Don't allow step into functions in the native context.
1497 if (!function->IsBuiltin()) {
1498 if (function->shared()->code() ==
1499 Builtins::builtin(Builtins::FunctionApply) ||
1500 function->shared()->code() ==
1501 Builtins::builtin(Builtins::FunctionCall)) {
1502 // Handle function.apply and function.call separately to flood the
1503 // function to be called and not the code for Builtins::FunctionApply or
1504 // Builtins::FunctionCall. The receiver of call/apply is the target
1505 // function.
1506 if (!holder.is_null() && holder->IsJSFunction() &&
1507 !JSFunction::cast(*holder)->IsBuiltin()) {
1508 Handle<SharedFunctionInfo> shared_info(
1509 JSFunction::cast(*holder)->shared());
1510 Debug::FloodWithOneShot(shared_info);
1511 }
1512 } else {
1513 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1514 }
1515 }
1516 }
1517}
1518
1519
1520void Debug::ClearStepping() {
1521 // Clear the various stepping setup.
1522 ClearOneShot();
1523 ClearStepIn();
1524 ClearStepOut();
1525 ClearStepNext();
1526
1527 // Clear multiple step counter.
1528 thread_local_.step_count_ = 0;
1529}
1530
1531// Clears all the one-shot break points that are currently set. Normally this
1532// function is called each time a break point is hit as one shot break points
1533// are used to support stepping.
1534void Debug::ClearOneShot() {
1535 // The current implementation just runs through all the breakpoints. When the
1536 // last break point for a function is removed that function is automatically
1537 // removed from the list.
1538
1539 DebugInfoListNode* node = debug_info_list_;
1540 while (node != NULL) {
1541 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1542 while (!it.Done()) {
1543 it.ClearOneShot();
1544 it.Next();
1545 }
1546 node = node->next();
1547 }
1548}
1549
1550
1551void Debug::ActivateStepIn(StackFrame* frame) {
1552 ASSERT(!StepOutActive());
1553 thread_local_.step_into_fp_ = frame->fp();
1554}
1555
1556
1557void Debug::ClearStepIn() {
1558 thread_local_.step_into_fp_ = 0;
1559}
1560
1561
1562void Debug::ActivateStepOut(StackFrame* frame) {
1563 ASSERT(!StepInActive());
1564 thread_local_.step_out_fp_ = frame->fp();
1565}
1566
1567
1568void Debug::ClearStepOut() {
1569 thread_local_.step_out_fp_ = 0;
1570}
1571
1572
1573void Debug::ClearStepNext() {
1574 thread_local_.last_step_action_ = StepNone;
1575 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
1576 thread_local_.last_fp_ = 0;
1577}
1578
1579
Steve Blocka7e24c12009-10-30 11:49:00 +00001580// Ensures the debug information is present for shared.
1581bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1582 // Return if we already have the debug info for shared.
1583 if (HasDebugInfo(shared)) return true;
1584
1585 // Ensure shared in compiled. Return false if this failed.
Leon Clarke4515c472010-02-03 11:58:03 +00001586 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001587
1588 // Create the debug info object.
1589 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
1590
1591 // Add debug info to the list.
1592 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1593 node->set_next(debug_info_list_);
1594 debug_info_list_ = node;
1595
1596 // Now there is at least one break point.
1597 has_break_points_ = true;
1598
1599 return true;
1600}
1601
1602
1603void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1604 ASSERT(debug_info_list_ != NULL);
1605 // Run through the debug info objects to find this one and remove it.
1606 DebugInfoListNode* prev = NULL;
1607 DebugInfoListNode* current = debug_info_list_;
1608 while (current != NULL) {
1609 if (*current->debug_info() == *debug_info) {
1610 // Unlink from list. If prev is NULL we are looking at the first element.
1611 if (prev == NULL) {
1612 debug_info_list_ = current->next();
1613 } else {
1614 prev->set_next(current->next());
1615 }
1616 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1617 delete current;
1618
1619 // If there are no more debug info objects there are not more break
1620 // points.
1621 has_break_points_ = debug_info_list_ != NULL;
1622
1623 return;
1624 }
1625 // Move to next in list.
1626 prev = current;
1627 current = current->next();
1628 }
1629 UNREACHABLE();
1630}
1631
1632
1633void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
1634 HandleScope scope;
1635
1636 // Get the executing function in which the debug break occurred.
1637 Handle<SharedFunctionInfo> shared =
1638 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
1639 if (!EnsureDebugInfo(shared)) {
1640 // Return if we failed to retrieve the debug info.
1641 return;
1642 }
1643 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1644 Handle<Code> code(debug_info->code());
1645 Handle<Code> original_code(debug_info->original_code());
1646#ifdef DEBUG
1647 // Get the code which is actually executing.
1648 Handle<Code> frame_code(frame->code());
1649 ASSERT(frame_code.is_identical_to(code));
1650#endif
1651
1652 // Find the call address in the running code. This address holds the call to
1653 // either a DebugBreakXXX or to the debug break return entry code if the
1654 // break point is still active after processing the break point.
1655 Address addr = frame->pc() - Assembler::kCallTargetAddressOffset;
1656
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001657 // Check if the location is at JS exit or debug break slot.
Steve Blocka7e24c12009-10-30 11:49:00 +00001658 bool at_js_return = false;
1659 bool break_at_js_return_active = false;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001660 bool at_debug_break_slot = false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001661 RelocIterator it(debug_info->code());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001662 while (!it.done() && !at_js_return && !at_debug_break_slot) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001663 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
1664 at_js_return = (it.rinfo()->pc() ==
1665 addr - Assembler::kPatchReturnSequenceAddressOffset);
Steve Block3ce2e202009-11-05 08:53:23 +00001666 break_at_js_return_active = it.rinfo()->IsPatchedReturnSequence();
Steve Blocka7e24c12009-10-30 11:49:00 +00001667 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001668 if (RelocInfo::IsDebugBreakSlot(it.rinfo()->rmode())) {
1669 at_debug_break_slot = (it.rinfo()->pc() ==
1670 addr - Assembler::kPatchDebugBreakSlotAddressOffset);
1671 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001672 it.next();
1673 }
1674
1675 // Handle the jump to continue execution after break point depending on the
1676 // break location.
1677 if (at_js_return) {
1678 // If the break point as return is still active jump to the corresponding
1679 // place in the original code. If not the break point was removed during
1680 // break point processing.
1681 if (break_at_js_return_active) {
1682 addr += original_code->instruction_start() - code->instruction_start();
1683 }
1684
1685 // Move back to where the call instruction sequence started.
1686 thread_local_.after_break_target_ =
1687 addr - Assembler::kPatchReturnSequenceAddressOffset;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001688 } else if (at_debug_break_slot) {
1689 // Address of where the debug break slot starts.
1690 addr = addr - Assembler::kPatchDebugBreakSlotAddressOffset;
Steve Blocka7e24c12009-10-30 11:49:00 +00001691
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001692 // Continue just after the slot.
1693 thread_local_.after_break_target_ = addr + Assembler::kDebugBreakSlotLength;
1694 } else if (IsDebugBreak(Assembler::target_address_at(addr))) {
1695 // We now know that there is still a debug break call at the target address,
1696 // so the break point is still there and the original code will hold the
1697 // address to jump to in order to complete the call which is replaced by a
1698 // call to DebugBreakXXX.
1699
1700 // Find the corresponding address in the original code.
1701 addr += original_code->instruction_start() - code->instruction_start();
Steve Blocka7e24c12009-10-30 11:49:00 +00001702
1703 // Install jump to the call address in the original code. This will be the
1704 // call which was overwritten by the call to DebugBreakXXX.
1705 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001706 } else {
1707 // There is no longer a break point present. Don't try to look in the
1708 // original code as the running code will have the right address. This takes
1709 // care of the case where the last break point is removed from the function
1710 // and therefore no "original code" is available.
1711 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
Steve Blocka7e24c12009-10-30 11:49:00 +00001712 }
1713}
1714
1715
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001716bool Debug::IsBreakAtReturn(JavaScriptFrame* frame) {
1717 HandleScope scope;
1718
1719 // Get the executing function in which the debug break occurred.
1720 Handle<SharedFunctionInfo> shared =
1721 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
1722 if (!EnsureDebugInfo(shared)) {
1723 // Return if we failed to retrieve the debug info.
1724 return false;
1725 }
1726 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1727 Handle<Code> code(debug_info->code());
1728#ifdef DEBUG
1729 // Get the code which is actually executing.
1730 Handle<Code> frame_code(frame->code());
1731 ASSERT(frame_code.is_identical_to(code));
1732#endif
1733
1734 // Find the call address in the running code.
1735 Address addr = frame->pc() - Assembler::kCallTargetAddressOffset;
1736
1737 // Check if the location is at JS return.
1738 RelocIterator it(debug_info->code());
1739 while (!it.done()) {
1740 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
1741 return (it.rinfo()->pc() ==
1742 addr - Assembler::kPatchReturnSequenceAddressOffset);
1743 }
1744 it.next();
1745 }
1746 return false;
1747}
1748
1749
Steve Block6ded16b2010-05-10 14:33:55 +01001750void Debug::FramesHaveBeenDropped(StackFrame::Id new_break_frame_id) {
1751 thread_local_.frames_are_dropped_ = true;
1752 thread_local_.break_frame_id_ = new_break_frame_id;
1753}
1754
1755
Steve Blocka7e24c12009-10-30 11:49:00 +00001756bool Debug::IsDebugGlobal(GlobalObject* global) {
1757 return IsLoaded() && global == Debug::debug_context()->global();
1758}
1759
1760
1761void Debug::ClearMirrorCache() {
1762 HandleScope scope;
1763 ASSERT(Top::context() == *Debug::debug_context());
1764
1765 // Clear the mirror cache.
1766 Handle<String> function_name =
1767 Factory::LookupSymbol(CStrVector("ClearMirrorCache"));
1768 Handle<Object> fun(Top::global()->GetProperty(*function_name));
1769 ASSERT(fun->IsJSFunction());
1770 bool caught_exception;
1771 Handle<Object> js_object = Execution::TryCall(
1772 Handle<JSFunction>::cast(fun),
1773 Handle<JSObject>(Debug::debug_context()->global()),
1774 0, NULL, &caught_exception);
1775}
1776
1777
Steve Blocka7e24c12009-10-30 11:49:00 +00001778void Debug::CreateScriptCache() {
1779 HandleScope scope;
1780
1781 // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
1782 // rid of all the cached script wrappers and the second gets rid of the
Andrei Popescu31002712010-02-23 13:46:05 +00001783 // scripts which are no longer referenced.
Steve Blocka7e24c12009-10-30 11:49:00 +00001784 Heap::CollectAllGarbage(false);
1785 Heap::CollectAllGarbage(false);
1786
1787 ASSERT(script_cache_ == NULL);
1788 script_cache_ = new ScriptCache();
1789
1790 // Scan heap for Script objects.
1791 int count = 0;
1792 HeapIterator iterator;
Leon Clarked91b9f72010-01-27 17:25:45 +00001793 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
Steve Block3ce2e202009-11-05 08:53:23 +00001794 if (obj->IsScript() && Script::cast(obj)->HasValidSource()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001795 script_cache_->Add(Handle<Script>(Script::cast(obj)));
1796 count++;
1797 }
1798 }
1799}
1800
1801
1802void Debug::DestroyScriptCache() {
1803 // Get rid of the script cache if it was created.
1804 if (script_cache_ != NULL) {
1805 delete script_cache_;
1806 script_cache_ = NULL;
1807 }
1808}
1809
1810
1811void Debug::AddScriptToScriptCache(Handle<Script> script) {
1812 if (script_cache_ != NULL) {
1813 script_cache_->Add(script);
1814 }
1815}
1816
1817
1818Handle<FixedArray> Debug::GetLoadedScripts() {
1819 // Create and fill the script cache when the loaded scripts is requested for
1820 // the first time.
1821 if (script_cache_ == NULL) {
1822 CreateScriptCache();
1823 }
1824
1825 // If the script cache is not active just return an empty array.
1826 ASSERT(script_cache_ != NULL);
1827 if (script_cache_ == NULL) {
1828 Factory::NewFixedArray(0);
1829 }
1830
1831 // Perform GC to get unreferenced scripts evicted from the cache before
1832 // returning the content.
1833 Heap::CollectAllGarbage(false);
1834
1835 // Get the scripts from the cache.
1836 return script_cache_->GetScripts();
1837}
1838
1839
1840void Debug::AfterGarbageCollection() {
1841 // Generate events for collected scripts.
1842 if (script_cache_ != NULL) {
1843 script_cache_->ProcessCollectedScripts();
1844 }
1845}
1846
1847
1848Mutex* Debugger::debugger_access_ = OS::CreateMutex();
1849Handle<Object> Debugger::event_listener_ = Handle<Object>();
1850Handle<Object> Debugger::event_listener_data_ = Handle<Object>();
1851bool Debugger::compiling_natives_ = false;
1852bool Debugger::is_loading_debugger_ = false;
1853bool Debugger::never_unload_debugger_ = false;
1854v8::Debug::MessageHandler2 Debugger::message_handler_ = NULL;
1855bool Debugger::debugger_unload_pending_ = false;
1856v8::Debug::HostDispatchHandler Debugger::host_dispatch_handler_ = NULL;
Leon Clarkee46be812010-01-19 14:06:41 +00001857Mutex* Debugger::dispatch_handler_access_ = OS::CreateMutex();
Steve Blockd0582a62009-12-15 09:54:21 +00001858v8::Debug::DebugMessageDispatchHandler
1859 Debugger::debug_message_dispatch_handler_ = NULL;
Leon Clarkee46be812010-01-19 14:06:41 +00001860MessageDispatchHelperThread* Debugger::message_dispatch_helper_thread_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00001861int Debugger::host_dispatch_micros_ = 100 * 1000;
1862DebuggerAgent* Debugger::agent_ = NULL;
1863LockingCommandMessageQueue Debugger::command_queue_(kQueueInitialSize);
1864Semaphore* Debugger::command_received_ = OS::CreateSemaphore(0);
1865
1866
1867Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1868 int argc, Object*** argv,
1869 bool* caught_exception) {
1870 ASSERT(Top::context() == *Debug::debug_context());
1871
1872 // Create the execution state object.
1873 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1874 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1875 ASSERT(constructor->IsJSFunction());
1876 if (!constructor->IsJSFunction()) {
1877 *caught_exception = true;
1878 return Factory::undefined_value();
1879 }
1880 Handle<Object> js_object = Execution::TryCall(
1881 Handle<JSFunction>::cast(constructor),
1882 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1883 caught_exception);
1884 return js_object;
1885}
1886
1887
1888Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1889 // Create the execution state object.
1890 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
1891 const int argc = 1;
1892 Object** argv[argc] = { break_id.location() };
1893 return MakeJSObject(CStrVector("MakeExecutionState"),
1894 argc, argv, caught_exception);
1895}
1896
1897
1898Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1899 Handle<Object> break_points_hit,
1900 bool* caught_exception) {
1901 // Create the new break event object.
1902 const int argc = 2;
1903 Object** argv[argc] = { exec_state.location(),
1904 break_points_hit.location() };
1905 return MakeJSObject(CStrVector("MakeBreakEvent"),
1906 argc,
1907 argv,
1908 caught_exception);
1909}
1910
1911
1912Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1913 Handle<Object> exception,
1914 bool uncaught,
1915 bool* caught_exception) {
1916 // Create the new exception event object.
1917 const int argc = 3;
1918 Object** argv[argc] = { exec_state.location(),
1919 exception.location(),
1920 uncaught ? Factory::true_value().location() :
1921 Factory::false_value().location()};
1922 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1923 argc, argv, caught_exception);
1924}
1925
1926
1927Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1928 bool* caught_exception) {
1929 // Create the new function event object.
1930 const int argc = 1;
1931 Object** argv[argc] = { function.location() };
1932 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1933 argc, argv, caught_exception);
1934}
1935
1936
1937Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
1938 bool before,
1939 bool* caught_exception) {
1940 // Create the compile event object.
1941 Handle<Object> exec_state = MakeExecutionState(caught_exception);
1942 Handle<Object> script_wrapper = GetScriptWrapper(script);
1943 const int argc = 3;
1944 Object** argv[argc] = { exec_state.location(),
1945 script_wrapper.location(),
1946 before ? Factory::true_value().location() :
1947 Factory::false_value().location() };
1948
1949 return MakeJSObject(CStrVector("MakeCompileEvent"),
1950 argc,
1951 argv,
1952 caught_exception);
1953}
1954
1955
1956Handle<Object> Debugger::MakeScriptCollectedEvent(int id,
1957 bool* caught_exception) {
1958 // Create the script collected event object.
1959 Handle<Object> exec_state = MakeExecutionState(caught_exception);
1960 Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id));
1961 const int argc = 2;
1962 Object** argv[argc] = { exec_state.location(), id_object.location() };
1963
1964 return MakeJSObject(CStrVector("MakeScriptCollectedEvent"),
1965 argc,
1966 argv,
1967 caught_exception);
1968}
1969
1970
1971void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1972 HandleScope scope;
1973
1974 // Bail out based on state or if there is no listener for this event
1975 if (Debug::InDebugger()) return;
1976 if (!Debugger::EventActive(v8::Exception)) return;
1977
1978 // Bail out if exception breaks are not active
1979 if (uncaught) {
1980 // Uncaught exceptions are reported by either flags.
1981 if (!(Debug::break_on_uncaught_exception() ||
1982 Debug::break_on_exception())) return;
1983 } else {
1984 // Caught exceptions are reported is activated.
1985 if (!Debug::break_on_exception()) return;
1986 }
1987
1988 // Enter the debugger.
1989 EnterDebugger debugger;
1990 if (debugger.FailedToEnter()) return;
1991
1992 // Clear all current stepping setup.
1993 Debug::ClearStepping();
1994 // Create the event data object.
1995 bool caught_exception = false;
1996 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1997 Handle<Object> event_data;
1998 if (!caught_exception) {
1999 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
2000 &caught_exception);
2001 }
2002 // Bail out and don't call debugger if exception.
2003 if (caught_exception) {
2004 return;
2005 }
2006
2007 // Process debug event.
2008 ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
2009 // Return to continue execution from where the exception was thrown.
2010}
2011
2012
2013void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
2014 bool auto_continue) {
2015 HandleScope scope;
2016
2017 // Debugger has already been entered by caller.
2018 ASSERT(Top::context() == *Debug::debug_context());
2019
2020 // Bail out if there is no listener for this event
2021 if (!Debugger::EventActive(v8::Break)) return;
2022
2023 // Debugger must be entered in advance.
2024 ASSERT(Top::context() == *Debug::debug_context());
2025
2026 // Create the event data object.
2027 bool caught_exception = false;
2028 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2029 Handle<Object> event_data;
2030 if (!caught_exception) {
2031 event_data = MakeBreakEvent(exec_state, break_points_hit,
2032 &caught_exception);
2033 }
2034 // Bail out and don't call debugger if exception.
2035 if (caught_exception) {
2036 return;
2037 }
2038
2039 // Process debug event.
2040 ProcessDebugEvent(v8::Break,
2041 Handle<JSObject>::cast(event_data),
2042 auto_continue);
2043}
2044
2045
2046void Debugger::OnBeforeCompile(Handle<Script> script) {
2047 HandleScope scope;
2048
2049 // Bail out based on state or if there is no listener for this event
2050 if (Debug::InDebugger()) return;
2051 if (compiling_natives()) return;
2052 if (!EventActive(v8::BeforeCompile)) return;
2053
2054 // Enter the debugger.
2055 EnterDebugger debugger;
2056 if (debugger.FailedToEnter()) return;
2057
2058 // Create the event data object.
2059 bool caught_exception = false;
2060 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
2061 // Bail out and don't call debugger if exception.
2062 if (caught_exception) {
2063 return;
2064 }
2065
2066 // Process debug event.
2067 ProcessDebugEvent(v8::BeforeCompile,
2068 Handle<JSObject>::cast(event_data),
2069 true);
2070}
2071
2072
2073// Handle debugger actions when a new script is compiled.
Steve Block6ded16b2010-05-10 14:33:55 +01002074void Debugger::OnAfterCompile(Handle<Script> script,
2075 AfterCompileFlags after_compile_flags) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002076 HandleScope scope;
2077
2078 // Add the newly compiled script to the script cache.
2079 Debug::AddScriptToScriptCache(script);
2080
2081 // No more to do if not debugging.
2082 if (!IsDebuggerActive()) return;
2083
2084 // No compile events while compiling natives.
2085 if (compiling_natives()) return;
2086
2087 // Store whether in debugger before entering debugger.
2088 bool in_debugger = Debug::InDebugger();
2089
2090 // Enter the debugger.
2091 EnterDebugger debugger;
2092 if (debugger.FailedToEnter()) return;
2093
2094 // If debugging there might be script break points registered for this
2095 // script. Make sure that these break points are set.
2096
Andrei Popescu31002712010-02-23 13:46:05 +00002097 // Get the function UpdateScriptBreakPoints (defined in debug-debugger.js).
Steve Blocka7e24c12009-10-30 11:49:00 +00002098 Handle<Object> update_script_break_points =
2099 Handle<Object>(Debug::debug_context()->global()->GetProperty(
2100 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
2101 if (!update_script_break_points->IsJSFunction()) {
2102 return;
2103 }
2104 ASSERT(update_script_break_points->IsJSFunction());
2105
2106 // Wrap the script object in a proper JS object before passing it
2107 // to JavaScript.
2108 Handle<JSValue> wrapper = GetScriptWrapper(script);
2109
2110 // Call UpdateScriptBreakPoints expect no exceptions.
2111 bool caught_exception = false;
2112 const int argc = 1;
2113 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
2114 Handle<Object> result = Execution::TryCall(
2115 Handle<JSFunction>::cast(update_script_break_points),
2116 Top::builtins(), argc, argv,
2117 &caught_exception);
2118 if (caught_exception) {
2119 return;
2120 }
2121 // Bail out based on state or if there is no listener for this event
Steve Block6ded16b2010-05-10 14:33:55 +01002122 if (in_debugger && (after_compile_flags & SEND_WHEN_DEBUGGING) == 0) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002123 if (!Debugger::EventActive(v8::AfterCompile)) return;
2124
2125 // Create the compile state object.
2126 Handle<Object> event_data = MakeCompileEvent(script,
2127 false,
2128 &caught_exception);
2129 // Bail out and don't call debugger if exception.
2130 if (caught_exception) {
2131 return;
2132 }
2133 // Process debug event.
2134 ProcessDebugEvent(v8::AfterCompile,
2135 Handle<JSObject>::cast(event_data),
2136 true);
2137}
2138
2139
Steve Blocka7e24c12009-10-30 11:49:00 +00002140void Debugger::OnScriptCollected(int id) {
2141 HandleScope scope;
2142
2143 // No more to do if not debugging.
2144 if (!IsDebuggerActive()) return;
2145 if (!Debugger::EventActive(v8::ScriptCollected)) return;
2146
2147 // Enter the debugger.
2148 EnterDebugger debugger;
2149 if (debugger.FailedToEnter()) return;
2150
2151 // Create the script collected state object.
2152 bool caught_exception = false;
2153 Handle<Object> event_data = MakeScriptCollectedEvent(id,
2154 &caught_exception);
2155 // Bail out and don't call debugger if exception.
2156 if (caught_exception) {
2157 return;
2158 }
2159
2160 // Process debug event.
2161 ProcessDebugEvent(v8::ScriptCollected,
2162 Handle<JSObject>::cast(event_data),
2163 true);
2164}
2165
2166
2167void Debugger::ProcessDebugEvent(v8::DebugEvent event,
2168 Handle<JSObject> event_data,
2169 bool auto_continue) {
2170 HandleScope scope;
2171
2172 // Clear any pending debug break if this is a real break.
2173 if (!auto_continue) {
2174 Debug::clear_interrupt_pending(DEBUGBREAK);
2175 }
2176
2177 // Create the execution state.
2178 bool caught_exception = false;
2179 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2180 if (caught_exception) {
2181 return;
2182 }
2183 // First notify the message handler if any.
2184 if (message_handler_ != NULL) {
2185 NotifyMessageHandler(event,
2186 Handle<JSObject>::cast(exec_state),
2187 event_data,
2188 auto_continue);
2189 }
2190 // Notify registered debug event listener. This can be either a C or a
2191 // JavaScript function.
2192 if (!event_listener_.is_null()) {
2193 if (event_listener_->IsProxy()) {
2194 // C debug event listener.
2195 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
Leon Clarkef7060e22010-06-03 12:02:55 +01002196 v8::Debug::EventCallback2 callback =
2197 FUNCTION_CAST<v8::Debug::EventCallback2>(callback_obj->proxy());
2198 EventDetailsImpl event_details(
2199 event,
2200 Handle<JSObject>::cast(exec_state),
2201 event_data,
2202 event_listener_data_);
2203 callback(event_details);
Steve Blocka7e24c12009-10-30 11:49:00 +00002204 } else {
2205 // JavaScript debug event listener.
2206 ASSERT(event_listener_->IsJSFunction());
2207 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
2208
2209 // Invoke the JavaScript debug event listener.
2210 const int argc = 4;
2211 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
2212 exec_state.location(),
2213 Handle<Object>::cast(event_data).location(),
2214 event_listener_data_.location() };
2215 Handle<Object> result = Execution::TryCall(fun, Top::global(),
2216 argc, argv, &caught_exception);
2217 // Silently ignore exceptions from debug event listeners.
2218 }
2219 }
2220}
2221
2222
Steve Block6ded16b2010-05-10 14:33:55 +01002223Handle<Context> Debugger::GetDebugContext() {
2224 never_unload_debugger_ = true;
2225 EnterDebugger debugger;
2226 return Debug::debug_context();
2227}
2228
2229
Steve Blocka7e24c12009-10-30 11:49:00 +00002230void Debugger::UnloadDebugger() {
2231 // Make sure that there are no breakpoints left.
2232 Debug::ClearAllBreakPoints();
2233
2234 // Unload the debugger if feasible.
2235 if (!never_unload_debugger_) {
2236 Debug::Unload();
2237 }
2238
2239 // Clear the flag indicating that the debugger should be unloaded.
2240 debugger_unload_pending_ = false;
2241}
2242
2243
2244void Debugger::NotifyMessageHandler(v8::DebugEvent event,
2245 Handle<JSObject> exec_state,
2246 Handle<JSObject> event_data,
2247 bool auto_continue) {
2248 HandleScope scope;
2249
2250 if (!Debug::Load()) return;
2251
2252 // Process the individual events.
2253 bool sendEventMessage = false;
2254 switch (event) {
2255 case v8::Break:
2256 sendEventMessage = !auto_continue;
2257 break;
2258 case v8::Exception:
2259 sendEventMessage = true;
2260 break;
2261 case v8::BeforeCompile:
2262 break;
2263 case v8::AfterCompile:
2264 sendEventMessage = true;
2265 break;
2266 case v8::ScriptCollected:
2267 sendEventMessage = true;
2268 break;
2269 case v8::NewFunction:
2270 break;
2271 default:
2272 UNREACHABLE();
2273 }
2274
2275 // The debug command interrupt flag might have been set when the command was
2276 // added. It should be enough to clear the flag only once while we are in the
2277 // debugger.
2278 ASSERT(Debug::InDebugger());
2279 StackGuard::Continue(DEBUGCOMMAND);
2280
2281 // Notify the debugger that a debug event has occurred unless auto continue is
2282 // active in which case no event is send.
2283 if (sendEventMessage) {
2284 MessageImpl message = MessageImpl::NewEvent(
2285 event,
2286 auto_continue,
2287 Handle<JSObject>::cast(exec_state),
2288 Handle<JSObject>::cast(event_data));
2289 InvokeMessageHandler(message);
2290 }
2291
2292 // If auto continue don't make the event cause a break, but process messages
2293 // in the queue if any. For script collected events don't even process
2294 // messages in the queue as the execution state might not be what is expected
2295 // by the client.
2296 if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) {
2297 return;
2298 }
2299
Steve Blocka7e24c12009-10-30 11:49:00 +00002300 v8::TryCatch try_catch;
Steve Block3ce2e202009-11-05 08:53:23 +00002301
2302 // DebugCommandProcessor goes here.
2303 v8::Local<v8::Object> cmd_processor;
2304 {
2305 v8::Local<v8::Object> api_exec_state =
2306 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
2307 v8::Local<v8::String> fun_name =
2308 v8::String::New("debugCommandProcessor");
2309 v8::Local<v8::Function> fun =
2310 v8::Function::Cast(*api_exec_state->Get(fun_name));
2311
2312 v8::Handle<v8::Boolean> running =
2313 auto_continue ? v8::True() : v8::False();
2314 static const int kArgc = 1;
2315 v8::Handle<Value> argv[kArgc] = { running };
2316 cmd_processor = v8::Object::Cast(*fun->Call(api_exec_state, kArgc, argv));
2317 if (try_catch.HasCaught()) {
2318 PrintLn(try_catch.Exception());
2319 return;
2320 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002321 }
2322
Steve Block3ce2e202009-11-05 08:53:23 +00002323 bool running = auto_continue;
2324
Steve Blocka7e24c12009-10-30 11:49:00 +00002325 // Process requests from the debugger.
2326 while (true) {
2327 // Wait for new command in the queue.
2328 if (Debugger::host_dispatch_handler_) {
2329 // In case there is a host dispatch - do periodic dispatches.
2330 if (!command_received_->Wait(host_dispatch_micros_)) {
2331 // Timout expired, do the dispatch.
2332 Debugger::host_dispatch_handler_();
2333 continue;
2334 }
2335 } else {
2336 // In case there is no host dispatch - just wait.
2337 command_received_->Wait();
2338 }
2339
2340 // Get the command from the queue.
2341 CommandMessage command = command_queue_.Get();
2342 Logger::DebugTag("Got request from command queue, in interactive loop.");
2343 if (!Debugger::IsDebuggerActive()) {
2344 // Delete command text and user data.
2345 command.Dispose();
2346 return;
2347 }
2348
2349 // Invoke JavaScript to process the debug request.
2350 v8::Local<v8::String> fun_name;
2351 v8::Local<v8::Function> fun;
2352 v8::Local<v8::Value> request;
2353 v8::TryCatch try_catch;
2354 fun_name = v8::String::New("processDebugRequest");
2355 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2356
2357 request = v8::String::New(command.text().start(),
2358 command.text().length());
2359 static const int kArgc = 1;
2360 v8::Handle<Value> argv[kArgc] = { request };
2361 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
2362
2363 // Get the response.
2364 v8::Local<v8::String> response;
Steve Blocka7e24c12009-10-30 11:49:00 +00002365 if (!try_catch.HasCaught()) {
2366 // Get response string.
2367 if (!response_val->IsUndefined()) {
2368 response = v8::String::Cast(*response_val);
2369 } else {
2370 response = v8::String::New("");
2371 }
2372
2373 // Log the JSON request/response.
2374 if (FLAG_trace_debug_json) {
2375 PrintLn(request);
2376 PrintLn(response);
2377 }
2378
2379 // Get the running state.
2380 fun_name = v8::String::New("isRunning");
2381 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2382 static const int kArgc = 1;
2383 v8::Handle<Value> argv[kArgc] = { response };
2384 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
2385 if (!try_catch.HasCaught()) {
2386 running = running_val->ToBoolean()->Value();
2387 }
2388 } else {
2389 // In case of failure the result text is the exception text.
2390 response = try_catch.Exception()->ToString();
2391 }
2392
2393 // Return the result.
2394 MessageImpl message = MessageImpl::NewResponse(
2395 event,
2396 running,
2397 Handle<JSObject>::cast(exec_state),
2398 Handle<JSObject>::cast(event_data),
2399 Handle<String>(Utils::OpenHandle(*response)),
2400 command.client_data());
2401 InvokeMessageHandler(message);
2402 command.Dispose();
2403
2404 // Return from debug event processing if either the VM is put into the
2405 // runnning state (through a continue command) or auto continue is active
2406 // and there are no more commands queued.
Steve Block3ce2e202009-11-05 08:53:23 +00002407 if (running && !HasCommands()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002408 return;
2409 }
2410 }
2411}
2412
2413
2414void Debugger::SetEventListener(Handle<Object> callback,
2415 Handle<Object> data) {
2416 HandleScope scope;
2417
2418 // Clear the global handles for the event listener and the event listener data
2419 // object.
2420 if (!event_listener_.is_null()) {
2421 GlobalHandles::Destroy(
2422 reinterpret_cast<Object**>(event_listener_.location()));
2423 event_listener_ = Handle<Object>();
2424 }
2425 if (!event_listener_data_.is_null()) {
2426 GlobalHandles::Destroy(
2427 reinterpret_cast<Object**>(event_listener_data_.location()));
2428 event_listener_data_ = Handle<Object>();
2429 }
2430
2431 // If there is a new debug event listener register it together with its data
2432 // object.
2433 if (!callback->IsUndefined() && !callback->IsNull()) {
2434 event_listener_ = Handle<Object>::cast(GlobalHandles::Create(*callback));
2435 if (data.is_null()) {
2436 data = Factory::undefined_value();
2437 }
2438 event_listener_data_ = Handle<Object>::cast(GlobalHandles::Create(*data));
2439 }
2440
2441 ListenersChanged();
2442}
2443
2444
2445void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) {
2446 ScopedLock with(debugger_access_);
2447
2448 message_handler_ = handler;
2449 ListenersChanged();
2450 if (handler == NULL) {
2451 // Send an empty command to the debugger if in a break to make JavaScript
2452 // run again if the debugger is closed.
2453 if (Debug::InDebugger()) {
2454 ProcessCommand(Vector<const uint16_t>::empty());
2455 }
2456 }
2457}
2458
2459
2460void Debugger::ListenersChanged() {
2461 if (IsDebuggerActive()) {
2462 // Disable the compilation cache when the debugger is active.
2463 CompilationCache::Disable();
Leon Clarkee46be812010-01-19 14:06:41 +00002464 debugger_unload_pending_ = false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002465 } else {
2466 CompilationCache::Enable();
Steve Blocka7e24c12009-10-30 11:49:00 +00002467 // Unload the debugger if event listener and message handler cleared.
Leon Clarkee46be812010-01-19 14:06:41 +00002468 // Schedule this for later, because we may be in non-V8 thread.
2469 debugger_unload_pending_ = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00002470 }
2471}
2472
2473
2474void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
2475 int period) {
2476 host_dispatch_handler_ = handler;
2477 host_dispatch_micros_ = period * 1000;
2478}
2479
2480
Steve Blockd0582a62009-12-15 09:54:21 +00002481void Debugger::SetDebugMessageDispatchHandler(
Leon Clarkee46be812010-01-19 14:06:41 +00002482 v8::Debug::DebugMessageDispatchHandler handler, bool provide_locker) {
2483 ScopedLock with(dispatch_handler_access_);
Steve Blockd0582a62009-12-15 09:54:21 +00002484 debug_message_dispatch_handler_ = handler;
Leon Clarkee46be812010-01-19 14:06:41 +00002485
2486 if (provide_locker && message_dispatch_helper_thread_ == NULL) {
2487 message_dispatch_helper_thread_ = new MessageDispatchHelperThread;
2488 message_dispatch_helper_thread_->Start();
2489 }
Steve Blockd0582a62009-12-15 09:54:21 +00002490}
2491
2492
Steve Blocka7e24c12009-10-30 11:49:00 +00002493// Calls the registered debug message handler. This callback is part of the
2494// public API.
2495void Debugger::InvokeMessageHandler(MessageImpl message) {
2496 ScopedLock with(debugger_access_);
2497
2498 if (message_handler_ != NULL) {
2499 message_handler_(message);
2500 }
2501}
2502
2503
2504// Puts a command coming from the public API on the queue. Creates
2505// a copy of the command string managed by the debugger. Up to this
2506// point, the command data was managed by the API client. Called
2507// by the API client thread.
2508void Debugger::ProcessCommand(Vector<const uint16_t> command,
2509 v8::Debug::ClientData* client_data) {
2510 // Need to cast away const.
2511 CommandMessage message = CommandMessage::New(
2512 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
2513 command.length()),
2514 client_data);
2515 Logger::DebugTag("Put command on command_queue.");
2516 command_queue_.Put(message);
2517 command_received_->Signal();
2518
2519 // Set the debug command break flag to have the command processed.
2520 if (!Debug::InDebugger()) {
2521 StackGuard::DebugCommand();
2522 }
Steve Blockd0582a62009-12-15 09:54:21 +00002523
Leon Clarkee46be812010-01-19 14:06:41 +00002524 MessageDispatchHelperThread* dispatch_thread;
2525 {
2526 ScopedLock with(dispatch_handler_access_);
2527 dispatch_thread = message_dispatch_helper_thread_;
2528 }
2529
2530 if (dispatch_thread == NULL) {
2531 CallMessageDispatchHandler();
2532 } else {
2533 dispatch_thread->Schedule();
Steve Blockd0582a62009-12-15 09:54:21 +00002534 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002535}
2536
2537
2538bool Debugger::HasCommands() {
2539 return !command_queue_.IsEmpty();
2540}
2541
2542
2543bool Debugger::IsDebuggerActive() {
2544 ScopedLock with(debugger_access_);
2545
2546 return message_handler_ != NULL || !event_listener_.is_null();
2547}
2548
2549
2550Handle<Object> Debugger::Call(Handle<JSFunction> fun,
2551 Handle<Object> data,
2552 bool* pending_exception) {
2553 // When calling functions in the debugger prevent it from beeing unloaded.
2554 Debugger::never_unload_debugger_ = true;
2555
2556 // Enter the debugger.
2557 EnterDebugger debugger;
Steve Block6ded16b2010-05-10 14:33:55 +01002558 if (debugger.FailedToEnter()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002559 return Factory::undefined_value();
2560 }
2561
2562 // Create the execution state.
2563 bool caught_exception = false;
2564 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2565 if (caught_exception) {
2566 return Factory::undefined_value();
2567 }
2568
2569 static const int kArgc = 2;
2570 Object** argv[kArgc] = { exec_state.location(), data.location() };
Steve Block6ded16b2010-05-10 14:33:55 +01002571 Handle<Object> result = Execution::Call(
2572 fun,
2573 Handle<Object>(Debug::debug_context_->global_proxy()),
2574 kArgc,
2575 argv,
2576 pending_exception);
Steve Blocka7e24c12009-10-30 11:49:00 +00002577 return result;
2578}
2579
2580
Leon Clarkee46be812010-01-19 14:06:41 +00002581static void StubMessageHandler2(const v8::Debug::Message& message) {
2582 // Simply ignore message.
2583}
2584
2585
2586bool Debugger::StartAgent(const char* name, int port,
2587 bool wait_for_connection) {
2588 if (wait_for_connection) {
2589 // Suspend V8 if it is already running or set V8 to suspend whenever
2590 // it starts.
2591 // Provide stub message handler; V8 auto-continues each suspend
2592 // when there is no message handler; we doesn't need it.
2593 // Once become suspended, V8 will stay so indefinitely long, until remote
2594 // debugger connects and issues "continue" command.
2595 Debugger::message_handler_ = StubMessageHandler2;
2596 v8::Debug::DebugBreak();
2597 }
2598
Steve Blocka7e24c12009-10-30 11:49:00 +00002599 if (Socket::Setup()) {
2600 agent_ = new DebuggerAgent(name, port);
2601 agent_->Start();
2602 return true;
2603 }
2604
2605 return false;
2606}
2607
2608
2609void Debugger::StopAgent() {
2610 if (agent_ != NULL) {
2611 agent_->Shutdown();
2612 agent_->Join();
2613 delete agent_;
2614 agent_ = NULL;
2615 }
2616}
2617
2618
2619void Debugger::WaitForAgent() {
2620 if (agent_ != NULL)
2621 agent_->WaitUntilListening();
2622}
2623
Leon Clarkee46be812010-01-19 14:06:41 +00002624
2625void Debugger::CallMessageDispatchHandler() {
2626 v8::Debug::DebugMessageDispatchHandler handler;
2627 {
2628 ScopedLock with(dispatch_handler_access_);
2629 handler = Debugger::debug_message_dispatch_handler_;
2630 }
2631 if (handler != NULL) {
2632 handler();
2633 }
2634}
2635
2636
Steve Blocka7e24c12009-10-30 11:49:00 +00002637MessageImpl MessageImpl::NewEvent(DebugEvent event,
2638 bool running,
2639 Handle<JSObject> exec_state,
2640 Handle<JSObject> event_data) {
2641 MessageImpl message(true, event, running,
2642 exec_state, event_data, Handle<String>(), NULL);
2643 return message;
2644}
2645
2646
2647MessageImpl MessageImpl::NewResponse(DebugEvent event,
2648 bool running,
2649 Handle<JSObject> exec_state,
2650 Handle<JSObject> event_data,
2651 Handle<String> response_json,
2652 v8::Debug::ClientData* client_data) {
2653 MessageImpl message(false, event, running,
2654 exec_state, event_data, response_json, client_data);
2655 return message;
2656}
2657
2658
2659MessageImpl::MessageImpl(bool is_event,
2660 DebugEvent event,
2661 bool running,
2662 Handle<JSObject> exec_state,
2663 Handle<JSObject> event_data,
2664 Handle<String> response_json,
2665 v8::Debug::ClientData* client_data)
2666 : is_event_(is_event),
2667 event_(event),
2668 running_(running),
2669 exec_state_(exec_state),
2670 event_data_(event_data),
2671 response_json_(response_json),
2672 client_data_(client_data) {}
2673
2674
2675bool MessageImpl::IsEvent() const {
2676 return is_event_;
2677}
2678
2679
2680bool MessageImpl::IsResponse() const {
2681 return !is_event_;
2682}
2683
2684
2685DebugEvent MessageImpl::GetEvent() const {
2686 return event_;
2687}
2688
2689
2690bool MessageImpl::WillStartRunning() const {
2691 return running_;
2692}
2693
2694
2695v8::Handle<v8::Object> MessageImpl::GetExecutionState() const {
2696 return v8::Utils::ToLocal(exec_state_);
2697}
2698
2699
2700v8::Handle<v8::Object> MessageImpl::GetEventData() const {
2701 return v8::Utils::ToLocal(event_data_);
2702}
2703
2704
2705v8::Handle<v8::String> MessageImpl::GetJSON() const {
2706 v8::HandleScope scope;
2707
2708 if (IsEvent()) {
2709 // Call toJSONProtocol on the debug event object.
2710 Handle<Object> fun = GetProperty(event_data_, "toJSONProtocol");
2711 if (!fun->IsJSFunction()) {
2712 return v8::Handle<v8::String>();
2713 }
2714 bool caught_exception;
2715 Handle<Object> json = Execution::TryCall(Handle<JSFunction>::cast(fun),
2716 event_data_,
2717 0, NULL, &caught_exception);
2718 if (caught_exception || !json->IsString()) {
2719 return v8::Handle<v8::String>();
2720 }
2721 return scope.Close(v8::Utils::ToLocal(Handle<String>::cast(json)));
2722 } else {
2723 return v8::Utils::ToLocal(response_json_);
2724 }
2725}
2726
2727
2728v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
Leon Clarkef7060e22010-06-03 12:02:55 +01002729 v8::Handle<v8::Context> context = GetDebugEventContext();
2730 // Top::context() may be NULL when "script collected" event occures.
2731 ASSERT(!context.IsEmpty() || event_ == v8::ScriptCollected);
2732 return GetDebugEventContext();
Steve Blocka7e24c12009-10-30 11:49:00 +00002733}
2734
2735
2736v8::Debug::ClientData* MessageImpl::GetClientData() const {
2737 return client_data_;
2738}
2739
2740
Leon Clarkef7060e22010-06-03 12:02:55 +01002741EventDetailsImpl::EventDetailsImpl(DebugEvent event,
2742 Handle<JSObject> exec_state,
2743 Handle<JSObject> event_data,
2744 Handle<Object> callback_data)
2745 : event_(event),
2746 exec_state_(exec_state),
2747 event_data_(event_data),
2748 callback_data_(callback_data) {}
2749
2750
2751DebugEvent EventDetailsImpl::GetEvent() const {
2752 return event_;
2753}
2754
2755
2756v8::Handle<v8::Object> EventDetailsImpl::GetExecutionState() const {
2757 return v8::Utils::ToLocal(exec_state_);
2758}
2759
2760
2761v8::Handle<v8::Object> EventDetailsImpl::GetEventData() const {
2762 return v8::Utils::ToLocal(event_data_);
2763}
2764
2765
2766v8::Handle<v8::Context> EventDetailsImpl::GetEventContext() const {
2767 return GetDebugEventContext();
2768}
2769
2770
2771v8::Handle<v8::Value> EventDetailsImpl::GetCallbackData() const {
2772 return v8::Utils::ToLocal(callback_data_);
2773}
2774
2775
Steve Blocka7e24c12009-10-30 11:49:00 +00002776CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
2777 client_data_(NULL) {
2778}
2779
2780
2781CommandMessage::CommandMessage(const Vector<uint16_t>& text,
2782 v8::Debug::ClientData* data)
2783 : text_(text),
2784 client_data_(data) {
2785}
2786
2787
2788CommandMessage::~CommandMessage() {
2789}
2790
2791
2792void CommandMessage::Dispose() {
2793 text_.Dispose();
2794 delete client_data_;
2795 client_data_ = NULL;
2796}
2797
2798
2799CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
2800 v8::Debug::ClientData* data) {
2801 return CommandMessage(command.Clone(), data);
2802}
2803
2804
2805CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
2806 size_(size) {
2807 messages_ = NewArray<CommandMessage>(size);
2808}
2809
2810
2811CommandMessageQueue::~CommandMessageQueue() {
2812 while (!IsEmpty()) {
2813 CommandMessage m = Get();
2814 m.Dispose();
2815 }
2816 DeleteArray(messages_);
2817}
2818
2819
2820CommandMessage CommandMessageQueue::Get() {
2821 ASSERT(!IsEmpty());
2822 int result = start_;
2823 start_ = (start_ + 1) % size_;
2824 return messages_[result];
2825}
2826
2827
2828void CommandMessageQueue::Put(const CommandMessage& message) {
2829 if ((end_ + 1) % size_ == start_) {
2830 Expand();
2831 }
2832 messages_[end_] = message;
2833 end_ = (end_ + 1) % size_;
2834}
2835
2836
2837void CommandMessageQueue::Expand() {
2838 CommandMessageQueue new_queue(size_ * 2);
2839 while (!IsEmpty()) {
2840 new_queue.Put(Get());
2841 }
2842 CommandMessage* array_to_free = messages_;
2843 *this = new_queue;
2844 new_queue.messages_ = array_to_free;
2845 // Make the new_queue empty so that it doesn't call Dispose on any messages.
2846 new_queue.start_ = new_queue.end_;
2847 // Automatic destructor called on new_queue, freeing array_to_free.
2848}
2849
2850
2851LockingCommandMessageQueue::LockingCommandMessageQueue(int size)
2852 : queue_(size) {
2853 lock_ = OS::CreateMutex();
2854}
2855
2856
2857LockingCommandMessageQueue::~LockingCommandMessageQueue() {
2858 delete lock_;
2859}
2860
2861
2862bool LockingCommandMessageQueue::IsEmpty() const {
2863 ScopedLock sl(lock_);
2864 return queue_.IsEmpty();
2865}
2866
2867
2868CommandMessage LockingCommandMessageQueue::Get() {
2869 ScopedLock sl(lock_);
2870 CommandMessage result = queue_.Get();
2871 Logger::DebugEvent("Get", result.text());
2872 return result;
2873}
2874
2875
2876void LockingCommandMessageQueue::Put(const CommandMessage& message) {
2877 ScopedLock sl(lock_);
2878 queue_.Put(message);
2879 Logger::DebugEvent("Put", message.text());
2880}
2881
2882
2883void LockingCommandMessageQueue::Clear() {
2884 ScopedLock sl(lock_);
2885 queue_.Clear();
2886}
2887
Leon Clarkee46be812010-01-19 14:06:41 +00002888
2889MessageDispatchHelperThread::MessageDispatchHelperThread()
2890 : sem_(OS::CreateSemaphore(0)), mutex_(OS::CreateMutex()),
2891 already_signalled_(false) {
2892}
2893
2894
2895MessageDispatchHelperThread::~MessageDispatchHelperThread() {
2896 delete mutex_;
2897 delete sem_;
2898}
2899
2900
2901void MessageDispatchHelperThread::Schedule() {
2902 {
2903 ScopedLock lock(mutex_);
2904 if (already_signalled_) {
2905 return;
2906 }
2907 already_signalled_ = true;
2908 }
2909 sem_->Signal();
2910}
2911
2912
2913void MessageDispatchHelperThread::Run() {
2914 while (true) {
2915 sem_->Wait();
2916 {
2917 ScopedLock lock(mutex_);
2918 already_signalled_ = false;
2919 }
2920 {
2921 Locker locker;
2922 Debugger::CallMessageDispatchHandler();
2923 }
2924 }
2925}
2926
Steve Blocka7e24c12009-10-30 11:49:00 +00002927#endif // ENABLE_DEBUGGER_SUPPORT
2928
2929} } // namespace v8::internal