blob: 093f38ee50ad804b880fb457acbf866ad5e52d26 [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"
Ben Murdochb0fe1622011-05-05 13:52:32 +010038#include "deoptimizer.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000039#include "execution.h"
40#include "global-handles.h"
41#include "ic.h"
42#include "ic-inl.h"
Steve Block6ded16b2010-05-10 14:33:55 +010043#include "messages.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000044#include "natives.h"
45#include "stub-cache.h"
46#include "log.h"
47
48#include "../include/v8-debug.h"
49
50namespace v8 {
51namespace internal {
52
53#ifdef ENABLE_DEBUGGER_SUPPORT
Steve Block44f0eee2011-05-26 01:26:41 +010054
55
56Debug::Debug(Isolate* isolate)
57 : has_break_points_(false),
58 script_cache_(NULL),
59 debug_info_list_(NULL),
60 disable_break_(false),
61 break_on_exception_(false),
62 break_on_uncaught_exception_(false),
63 debug_break_return_(NULL),
64 debug_break_slot_(NULL),
65 isolate_(isolate) {
66 memset(registers_, 0, sizeof(JSCallerSavedBuffer));
67}
68
69
70Debug::~Debug() {
71}
72
73
Steve Blocka7e24c12009-10-30 11:49:00 +000074static void PrintLn(v8::Local<v8::Value> value) {
75 v8::Local<v8::String> s = value->ToString();
Kristian Monsen25f61362010-05-21 11:50:48 +010076 ScopedVector<char> data(s->Length() + 1);
77 if (data.start() == NULL) {
Steve Blocka7e24c12009-10-30 11:49:00 +000078 V8::FatalProcessOutOfMemory("PrintLn");
79 return;
80 }
Kristian Monsen25f61362010-05-21 11:50:48 +010081 s->WriteAscii(data.start());
82 PrintF("%s\n", data.start());
Steve Blocka7e24c12009-10-30 11:49:00 +000083}
84
85
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010086static Handle<Code> ComputeCallDebugBreak(int argc, Code::Kind kind) {
Steve Block44f0eee2011-05-26 01:26:41 +010087 Isolate* isolate = Isolate::Current();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010088 CALL_HEAP_FUNCTION(
Steve Block44f0eee2011-05-26 01:26:41 +010089 isolate,
90 isolate->stub_cache()->ComputeCallDebugBreak(argc, kind),
91 Code);
Steve Blocka7e24c12009-10-30 11:49:00 +000092}
93
94
Steve Block44f0eee2011-05-26 01:26:41 +010095static Handle<Code> ComputeCallDebugPrepareStepIn(int argc, Code::Kind kind) {
96 Isolate* isolate = Isolate::Current();
97 CALL_HEAP_FUNCTION(
98 isolate,
99 isolate->stub_cache()->ComputeCallDebugPrepareStepIn(argc, kind),
100 Code);
101}
102
103
104static v8::Handle<v8::Context> GetDebugEventContext(Isolate* isolate) {
105 Handle<Context> context = isolate->debug()->debugger_entry()->GetContext();
106 // Isolate::context() may have been NULL when "script collected" event
107 // occured.
108 if (context.is_null()) return v8::Local<v8::Context>();
Leon Clarkef7060e22010-06-03 12:02:55 +0100109 Handle<Context> global_context(context->global_context());
110 return v8::Utils::ToLocal(global_context);
111}
112
113
Steve Blocka7e24c12009-10-30 11:49:00 +0000114BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
115 BreakLocatorType type) {
116 debug_info_ = debug_info;
117 type_ = type;
Steve Blocka7e24c12009-10-30 11:49:00 +0000118 reloc_iterator_ = NULL;
119 reloc_iterator_original_ = NULL;
120 Reset(); // Initialize the rest of the member variables.
121}
122
123
124BreakLocationIterator::~BreakLocationIterator() {
125 ASSERT(reloc_iterator_ != NULL);
126 ASSERT(reloc_iterator_original_ != NULL);
127 delete reloc_iterator_;
128 delete reloc_iterator_original_;
129}
130
131
132void BreakLocationIterator::Next() {
133 AssertNoAllocation nogc;
134 ASSERT(!RinfoDone());
135
136 // Iterate through reloc info for code and original code stopping at each
137 // breakable code target.
138 bool first = break_point_ == -1;
139 while (!RinfoDone()) {
140 if (!first) RinfoNext();
141 first = false;
142 if (RinfoDone()) return;
143
144 // Whenever a statement position or (plain) position is passed update the
145 // current value of these.
146 if (RelocInfo::IsPosition(rmode())) {
147 if (RelocInfo::IsStatementPosition(rmode())) {
Steve Blockd0582a62009-12-15 09:54:21 +0000148 statement_position_ = static_cast<int>(
149 rinfo()->data() - debug_info_->shared()->start_position());
Steve Blocka7e24c12009-10-30 11:49:00 +0000150 }
151 // Always update the position as we don't want that to be before the
152 // statement position.
Steve Blockd0582a62009-12-15 09:54:21 +0000153 position_ = static_cast<int>(
154 rinfo()->data() - debug_info_->shared()->start_position());
Steve Blocka7e24c12009-10-30 11:49:00 +0000155 ASSERT(position_ >= 0);
156 ASSERT(statement_position_ >= 0);
157 }
158
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100159 if (IsDebugBreakSlot()) {
160 // There is always a possible break point at a debug break slot.
161 break_point_++;
162 return;
163 } else if (RelocInfo::IsCodeTarget(rmode())) {
164 // Check for breakable code target. Look in the original code as setting
165 // break points can cause the code targets in the running (debugged) code
166 // to be of a different kind than in the original code.
Steve Blocka7e24c12009-10-30 11:49:00 +0000167 Address target = original_rinfo()->target_address();
168 Code* code = Code::GetCodeFromTargetAddress(target);
Steve Block6ded16b2010-05-10 14:33:55 +0100169 if ((code->is_inline_cache_stub() &&
Ben Murdochb0fe1622011-05-05 13:52:32 +0100170 !code->is_type_recording_binary_op_stub() &&
171 !code->is_compare_ic_stub()) ||
Steve Block6ded16b2010-05-10 14:33:55 +0100172 RelocInfo::IsConstructCall(rmode())) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000173 break_point_++;
174 return;
175 }
176 if (code->kind() == Code::STUB) {
177 if (IsDebuggerStatement()) {
178 break_point_++;
179 return;
180 }
181 if (type_ == ALL_BREAK_LOCATIONS) {
182 if (Debug::IsBreakStub(code)) {
183 break_point_++;
184 return;
185 }
186 } else {
187 ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
188 if (Debug::IsSourceBreakStub(code)) {
189 break_point_++;
190 return;
191 }
192 }
193 }
194 }
195
196 // Check for break at return.
197 if (RelocInfo::IsJSReturn(rmode())) {
198 // Set the positions to the end of the function.
199 if (debug_info_->shared()->HasSourceCode()) {
200 position_ = debug_info_->shared()->end_position() -
Ben Murdochbb769b22010-08-11 14:56:33 +0100201 debug_info_->shared()->start_position() - 1;
Steve Blocka7e24c12009-10-30 11:49:00 +0000202 } else {
203 position_ = 0;
204 }
205 statement_position_ = position_;
206 break_point_++;
207 return;
208 }
209 }
210}
211
212
213void BreakLocationIterator::Next(int count) {
214 while (count > 0) {
215 Next();
216 count--;
217 }
218}
219
220
221// Find the break point closest to the supplied address.
222void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
223 // Run through all break points to locate the one closest to the address.
224 int closest_break_point = 0;
225 int distance = kMaxInt;
226 while (!Done()) {
227 // Check if this break point is closer that what was previously found.
228 if (this->pc() < pc && pc - this->pc() < distance) {
229 closest_break_point = break_point();
Steve Blockd0582a62009-12-15 09:54:21 +0000230 distance = static_cast<int>(pc - this->pc());
Steve Blocka7e24c12009-10-30 11:49:00 +0000231 // Check whether we can't get any closer.
232 if (distance == 0) break;
233 }
234 Next();
235 }
236
237 // Move to the break point found.
238 Reset();
239 Next(closest_break_point);
240}
241
242
243// Find the break point closest to the supplied source position.
244void BreakLocationIterator::FindBreakLocationFromPosition(int position) {
245 // Run through all break points to locate the one closest to the source
246 // position.
247 int closest_break_point = 0;
248 int distance = kMaxInt;
249 while (!Done()) {
250 // Check if this break point is closer that what was previously found.
251 if (position <= statement_position() &&
252 statement_position() - position < distance) {
253 closest_break_point = break_point();
254 distance = statement_position() - position;
255 // Check whether we can't get any closer.
256 if (distance == 0) break;
257 }
258 Next();
259 }
260
261 // Move to the break point found.
262 Reset();
263 Next(closest_break_point);
264}
265
266
267void BreakLocationIterator::Reset() {
268 // Create relocation iterators for the two code objects.
269 if (reloc_iterator_ != NULL) delete reloc_iterator_;
270 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
271 reloc_iterator_ = new RelocIterator(debug_info_->code());
272 reloc_iterator_original_ = new RelocIterator(debug_info_->original_code());
273
274 // Position at the first break point.
275 break_point_ = -1;
276 position_ = 1;
277 statement_position_ = 1;
278 Next();
279}
280
281
282bool BreakLocationIterator::Done() const {
283 return RinfoDone();
284}
285
286
287void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
288 // If there is not already a real break point here patch code with debug
289 // break.
290 if (!HasBreakPoint()) {
291 SetDebugBreak();
292 }
293 ASSERT(IsDebugBreak() || IsDebuggerStatement());
294 // Set the break point information.
295 DebugInfo::SetBreakPoint(debug_info_, code_position(),
296 position(), statement_position(),
297 break_point_object);
298}
299
300
301void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
302 // Clear the break point information.
303 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
304 // If there are no more break points here remove the debug break.
305 if (!HasBreakPoint()) {
306 ClearDebugBreak();
307 ASSERT(!IsDebugBreak());
308 }
309}
310
311
312void BreakLocationIterator::SetOneShot() {
313 // Debugger statement always calls debugger. No need to modify it.
314 if (IsDebuggerStatement()) {
315 return;
316 }
317
318 // If there is a real break point here no more to do.
319 if (HasBreakPoint()) {
320 ASSERT(IsDebugBreak());
321 return;
322 }
323
324 // Patch code with debug break.
325 SetDebugBreak();
326}
327
328
329void BreakLocationIterator::ClearOneShot() {
330 // Debugger statement always calls debugger. No need to modify it.
331 if (IsDebuggerStatement()) {
332 return;
333 }
334
335 // If there is a real break point here no more to do.
336 if (HasBreakPoint()) {
337 ASSERT(IsDebugBreak());
338 return;
339 }
340
341 // Patch code removing debug break.
342 ClearDebugBreak();
343 ASSERT(!IsDebugBreak());
344}
345
346
347void BreakLocationIterator::SetDebugBreak() {
348 // Debugger statement always calls debugger. No need to modify it.
349 if (IsDebuggerStatement()) {
350 return;
351 }
352
353 // If there is already a break point here just return. This might happen if
354 // the same code is flooded with break points twice. Flooding the same
355 // function twice might happen when stepping in a function with an exception
356 // handler as the handler and the function is the same.
357 if (IsDebugBreak()) {
358 return;
359 }
360
361 if (RelocInfo::IsJSReturn(rmode())) {
362 // Patch the frame exit code with a break point.
363 SetDebugBreakAtReturn();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100364 } else if (IsDebugBreakSlot()) {
365 // Patch the code in the break slot.
366 SetDebugBreakAtSlot();
Steve Blocka7e24c12009-10-30 11:49:00 +0000367 } else {
368 // Patch the IC call.
369 SetDebugBreakAtIC();
370 }
371 ASSERT(IsDebugBreak());
372}
373
374
375void BreakLocationIterator::ClearDebugBreak() {
376 // Debugger statement always calls debugger. No need to modify it.
377 if (IsDebuggerStatement()) {
378 return;
379 }
380
381 if (RelocInfo::IsJSReturn(rmode())) {
382 // Restore the frame exit code.
383 ClearDebugBreakAtReturn();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100384 } else if (IsDebugBreakSlot()) {
385 // Restore the code in the break slot.
386 ClearDebugBreakAtSlot();
Steve Blocka7e24c12009-10-30 11:49:00 +0000387 } else {
388 // Patch the IC call.
389 ClearDebugBreakAtIC();
390 }
391 ASSERT(!IsDebugBreak());
392}
393
394
395void BreakLocationIterator::PrepareStepIn() {
396 HandleScope scope;
397
398 // Step in can only be prepared if currently positioned on an IC call,
399 // construct call or CallFunction stub call.
400 Address target = rinfo()->target_address();
401 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100402 if (code->is_call_stub() || code->is_keyed_call_stub()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000403 // Step in through IC call is handled by the runtime system. Therefore make
404 // sure that the any current IC is cleared and the runtime system is
405 // called. If the executing code has a debug break at the location change
406 // the call in the original code as it is the code there that will be
407 // executed in place of the debug break call.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100408 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count(),
409 code->kind());
Steve Blocka7e24c12009-10-30 11:49:00 +0000410 if (IsDebugBreak()) {
411 original_rinfo()->set_target_address(stub->entry());
412 } else {
413 rinfo()->set_target_address(stub->entry());
414 }
415 } else {
416#ifdef DEBUG
417 // All the following stuff is needed only for assertion checks so the code
418 // is wrapped in ifdef.
419 Handle<Code> maybe_call_function_stub = code;
420 if (IsDebugBreak()) {
421 Address original_target = original_rinfo()->target_address();
422 maybe_call_function_stub =
423 Handle<Code>(Code::GetCodeFromTargetAddress(original_target));
424 }
425 bool is_call_function_stub =
426 (maybe_call_function_stub->kind() == Code::STUB &&
427 maybe_call_function_stub->major_key() == CodeStub::CallFunction);
428
429 // Step in through construct call requires no changes to the running code.
430 // Step in through getters/setters should already be prepared as well
431 // because caller of this function (Debug::PrepareStep) is expected to
432 // flood the top frame's function with one shot breakpoints.
433 // Step in through CallFunction stub should also be prepared by caller of
434 // this function (Debug::PrepareStep) which should flood target function
435 // with breakpoints.
436 ASSERT(RelocInfo::IsConstructCall(rmode()) || code->is_inline_cache_stub()
437 || is_call_function_stub);
438#endif
439 }
440}
441
442
443// Check whether the break point is at a position which will exit the function.
444bool BreakLocationIterator::IsExit() const {
445 return (RelocInfo::IsJSReturn(rmode()));
446}
447
448
449bool BreakLocationIterator::HasBreakPoint() {
450 return debug_info_->HasBreakPoint(code_position());
451}
452
453
454// Check whether there is a debug break at the current position.
455bool BreakLocationIterator::IsDebugBreak() {
456 if (RelocInfo::IsJSReturn(rmode())) {
457 return IsDebugBreakAtReturn();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100458 } else if (IsDebugBreakSlot()) {
459 return IsDebugBreakAtSlot();
Steve Blocka7e24c12009-10-30 11:49:00 +0000460 } else {
461 return Debug::IsDebugBreak(rinfo()->target_address());
462 }
463}
464
465
466void BreakLocationIterator::SetDebugBreakAtIC() {
467 // Patch the original code with the current address as the current address
468 // might have changed by the inline caching since the code was copied.
469 original_rinfo()->set_target_address(rinfo()->target_address());
470
471 RelocInfo::Mode mode = rmode();
472 if (RelocInfo::IsCodeTarget(mode)) {
473 Address target = rinfo()->target_address();
474 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
475
476 // Patch the code to invoke the builtin debug break function matching the
477 // calling convention used by the call site.
478 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(code, mode));
479 rinfo()->set_target_address(dbgbrk_code->entry());
Steve Block053d10c2011-06-13 19:13:29 +0100480
481 // For stubs that refer back to an inlined version clear the cached map for
482 // the inlined case to always go through the IC. As long as the break point
483 // is set the patching performed by the runtime system will take place in
484 // the code copy and will therefore have no effect on the running code
485 // keeping it from using the inlined code.
486 if (code->is_keyed_load_stub()) {
487 KeyedLoadIC::ClearInlinedVersion(pc());
488 } else if (code->is_keyed_store_stub()) {
489 KeyedStoreIC::ClearInlinedVersion(pc());
490 } else if (code->is_load_stub()) {
491 LoadIC::ClearInlinedVersion(pc());
492 } else if (code->is_store_stub()) {
493 StoreIC::ClearInlinedVersion(pc());
494 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000495 }
496}
497
498
499void BreakLocationIterator::ClearDebugBreakAtIC() {
500 // Patch the code to the original invoke.
501 rinfo()->set_target_address(original_rinfo()->target_address());
Steve Block053d10c2011-06-13 19:13:29 +0100502
503 RelocInfo::Mode mode = rmode();
504 if (RelocInfo::IsCodeTarget(mode)) {
505 AssertNoAllocation nogc;
506 Address target = original_rinfo()->target_address();
507 Code* code = Code::GetCodeFromTargetAddress(target);
508
509 // Restore the inlined version of keyed stores to get back to the
510 // fast case. We need to patch back the keyed store because no
511 // patching happens when running normally. For keyed loads, the
512 // map check will get patched back when running normally after ICs
513 // have been cleared at GC.
514 if (code->is_keyed_store_stub()) KeyedStoreIC::RestoreInlinedVersion(pc());
515 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000516}
517
518
519bool BreakLocationIterator::IsDebuggerStatement() {
Andrei Popescu402d9372010-02-26 13:31:12 +0000520 return RelocInfo::DEBUG_BREAK == rmode();
Steve Blocka7e24c12009-10-30 11:49:00 +0000521}
522
523
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100524bool BreakLocationIterator::IsDebugBreakSlot() {
525 return RelocInfo::DEBUG_BREAK_SLOT == rmode();
526}
527
528
Steve Blocka7e24c12009-10-30 11:49:00 +0000529Object* BreakLocationIterator::BreakPointObjects() {
530 return debug_info_->GetBreakPointObjects(code_position());
531}
532
533
534// Clear out all the debug break code. This is ONLY supposed to be used when
535// shutting down the debugger as it will leave the break point information in
536// DebugInfo even though the code is patched back to the non break point state.
537void BreakLocationIterator::ClearAllDebugBreak() {
538 while (!Done()) {
539 ClearDebugBreak();
540 Next();
541 }
542}
543
544
545bool BreakLocationIterator::RinfoDone() const {
546 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
547 return reloc_iterator_->done();
548}
549
550
551void BreakLocationIterator::RinfoNext() {
552 reloc_iterator_->next();
553 reloc_iterator_original_->next();
554#ifdef DEBUG
555 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
556 if (!reloc_iterator_->done()) {
557 ASSERT(rmode() == original_rmode());
558 }
559#endif
560}
561
562
Steve Blocka7e24c12009-10-30 11:49:00 +0000563// Threading support.
564void Debug::ThreadInit() {
565 thread_local_.break_count_ = 0;
566 thread_local_.break_id_ = 0;
567 thread_local_.break_frame_id_ = StackFrame::NO_ID;
568 thread_local_.last_step_action_ = StepNone;
569 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
570 thread_local_.step_count_ = 0;
571 thread_local_.last_fp_ = 0;
572 thread_local_.step_into_fp_ = 0;
573 thread_local_.step_out_fp_ = 0;
574 thread_local_.after_break_target_ = 0;
Steve Block44f0eee2011-05-26 01:26:41 +0100575 // TODO(isolates): frames_are_dropped_?
Steve Blocka7e24c12009-10-30 11:49:00 +0000576 thread_local_.debugger_entry_ = NULL;
577 thread_local_.pending_interrupts_ = 0;
Iain Merrick75681382010-08-19 15:07:18 +0100578 thread_local_.restarter_frame_function_pointer_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000579}
580
581
Steve Blocka7e24c12009-10-30 11:49:00 +0000582char* Debug::ArchiveDebug(char* storage) {
583 char* to = storage;
584 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
585 to += sizeof(ThreadLocal);
586 memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
587 ThreadInit();
588 ASSERT(to <= storage + ArchiveSpacePerThread());
589 return storage + ArchiveSpacePerThread();
590}
591
592
593char* Debug::RestoreDebug(char* storage) {
594 char* from = storage;
595 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
596 from += sizeof(ThreadLocal);
597 memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
598 ASSERT(from <= storage + ArchiveSpacePerThread());
599 return storage + ArchiveSpacePerThread();
600}
601
602
603int Debug::ArchiveSpacePerThread() {
Steve Block44f0eee2011-05-26 01:26:41 +0100604 return sizeof(ThreadLocal) + sizeof(JSCallerSavedBuffer);
Steve Blocka7e24c12009-10-30 11:49:00 +0000605}
606
607
Iain Merrick75681382010-08-19 15:07:18 +0100608// Frame structure (conforms InternalFrame structure):
609// -- code
610// -- SMI maker
611// -- function (slot is called "context")
612// -- frame base
613Object** Debug::SetUpFrameDropperFrame(StackFrame* bottom_js_frame,
614 Handle<Code> code) {
615 ASSERT(bottom_js_frame->is_java_script());
616
617 Address fp = bottom_js_frame->fp();
618
619 // Move function pointer into "context" slot.
620 Memory::Object_at(fp + StandardFrameConstants::kContextOffset) =
621 Memory::Object_at(fp + JavaScriptFrameConstants::kFunctionOffset);
622
623 Memory::Object_at(fp + InternalFrameConstants::kCodeOffset) = *code;
624 Memory::Object_at(fp + StandardFrameConstants::kMarkerOffset) =
625 Smi::FromInt(StackFrame::INTERNAL);
626
627 return reinterpret_cast<Object**>(&Memory::Object_at(
628 fp + StandardFrameConstants::kContextOffset));
629}
630
631const int Debug::kFrameDropperFrameSize = 4;
632
633
Steve Blocka7e24c12009-10-30 11:49:00 +0000634void ScriptCache::Add(Handle<Script> script) {
Steve Block44f0eee2011-05-26 01:26:41 +0100635 GlobalHandles* global_handles = Isolate::Current()->global_handles();
Steve Blocka7e24c12009-10-30 11:49:00 +0000636 // Create an entry in the hash map for the script.
637 int id = Smi::cast(script->id())->value();
638 HashMap::Entry* entry =
639 HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
640 if (entry->value != NULL) {
641 ASSERT(*script == *reinterpret_cast<Script**>(entry->value));
642 return;
643 }
644
645 // Globalize the script object, make it weak and use the location of the
646 // global handle as the value in the hash map.
647 Handle<Script> script_ =
Steve Block44f0eee2011-05-26 01:26:41 +0100648 Handle<Script>::cast(
649 (global_handles->Create(*script)));
650 global_handles->MakeWeak(
651 reinterpret_cast<Object**>(script_.location()),
652 this,
653 ScriptCache::HandleWeakScript);
Steve Blocka7e24c12009-10-30 11:49:00 +0000654 entry->value = script_.location();
655}
656
657
658Handle<FixedArray> ScriptCache::GetScripts() {
Steve Block44f0eee2011-05-26 01:26:41 +0100659 Handle<FixedArray> instances = FACTORY->NewFixedArray(occupancy());
Steve Blocka7e24c12009-10-30 11:49:00 +0000660 int count = 0;
661 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
662 ASSERT(entry->value != NULL);
663 if (entry->value != NULL) {
664 instances->set(count, *reinterpret_cast<Script**>(entry->value));
665 count++;
666 }
667 }
668 return instances;
669}
670
671
672void ScriptCache::ProcessCollectedScripts() {
Steve Block44f0eee2011-05-26 01:26:41 +0100673 Debugger* debugger = Isolate::Current()->debugger();
Steve Blocka7e24c12009-10-30 11:49:00 +0000674 for (int i = 0; i < collected_scripts_.length(); i++) {
Steve Block44f0eee2011-05-26 01:26:41 +0100675 debugger->OnScriptCollected(collected_scripts_[i]);
Steve Blocka7e24c12009-10-30 11:49:00 +0000676 }
677 collected_scripts_.Clear();
678}
679
680
681void ScriptCache::Clear() {
Steve Block44f0eee2011-05-26 01:26:41 +0100682 GlobalHandles* global_handles = Isolate::Current()->global_handles();
Steve Blocka7e24c12009-10-30 11:49:00 +0000683 // Iterate the script cache to get rid of all the weak handles.
684 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
685 ASSERT(entry != NULL);
686 Object** location = reinterpret_cast<Object**>(entry->value);
687 ASSERT((*location)->IsScript());
Steve Block44f0eee2011-05-26 01:26:41 +0100688 global_handles->ClearWeakness(location);
689 global_handles->Destroy(location);
Steve Blocka7e24c12009-10-30 11:49:00 +0000690 }
691 // Clear the content of the hash map.
692 HashMap::Clear();
693}
694
695
696void ScriptCache::HandleWeakScript(v8::Persistent<v8::Value> obj, void* data) {
697 ScriptCache* script_cache = reinterpret_cast<ScriptCache*>(data);
698 // Find the location of the global handle.
699 Script** location =
700 reinterpret_cast<Script**>(Utils::OpenHandle(*obj).location());
701 ASSERT((*location)->IsScript());
702
703 // Remove the entry from the cache.
704 int id = Smi::cast((*location)->id())->value();
705 script_cache->Remove(reinterpret_cast<void*>(id), Hash(id));
706 script_cache->collected_scripts_.Add(id);
707
708 // Clear the weak handle.
709 obj.Dispose();
710 obj.Clear();
711}
712
713
714void Debug::Setup(bool create_heap_objects) {
715 ThreadInit();
716 if (create_heap_objects) {
717 // Get code to handle debug break on return.
718 debug_break_return_ =
Steve Block44f0eee2011-05-26 01:26:41 +0100719 isolate_->builtins()->builtin(Builtins::kReturn_DebugBreak);
Steve Blocka7e24c12009-10-30 11:49:00 +0000720 ASSERT(debug_break_return_->IsCode());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100721 // Get code to handle debug break in debug break slots.
722 debug_break_slot_ =
Steve Block44f0eee2011-05-26 01:26:41 +0100723 isolate_->builtins()->builtin(Builtins::kSlot_DebugBreak);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100724 ASSERT(debug_break_slot_->IsCode());
Steve Blocka7e24c12009-10-30 11:49:00 +0000725 }
726}
727
728
729void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
Steve Block44f0eee2011-05-26 01:26:41 +0100730 Debug* debug = Isolate::Current()->debug();
Steve Blocka7e24c12009-10-30 11:49:00 +0000731 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
Steve Block8defd9f2010-07-08 12:39:36 +0100732 // We need to clear all breakpoints associated with the function to restore
733 // original code and avoid patching the code twice later because
734 // the function will live in the heap until next gc, and can be found by
735 // Runtime::FindSharedFunctionInfoInScript.
736 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
737 it.ClearAllDebugBreak();
Steve Block44f0eee2011-05-26 01:26:41 +0100738 debug->RemoveDebugInfo(node->debug_info());
Steve Blocka7e24c12009-10-30 11:49:00 +0000739#ifdef DEBUG
Steve Block44f0eee2011-05-26 01:26:41 +0100740 node = debug->debug_info_list_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000741 while (node != NULL) {
742 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
743 node = node->next();
744 }
745#endif
746}
747
748
749DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
Steve Block44f0eee2011-05-26 01:26:41 +0100750 GlobalHandles* global_handles = Isolate::Current()->global_handles();
Steve Blocka7e24c12009-10-30 11:49:00 +0000751 // Globalize the request debug info object and make it weak.
Steve Block44f0eee2011-05-26 01:26:41 +0100752 debug_info_ = Handle<DebugInfo>::cast(
753 (global_handles->Create(debug_info)));
754 global_handles->MakeWeak(
755 reinterpret_cast<Object**>(debug_info_.location()),
756 this,
757 Debug::HandleWeakDebugInfo);
Steve Blocka7e24c12009-10-30 11:49:00 +0000758}
759
760
761DebugInfoListNode::~DebugInfoListNode() {
Steve Block44f0eee2011-05-26 01:26:41 +0100762 Isolate::Current()->global_handles()->Destroy(
763 reinterpret_cast<Object**>(debug_info_.location()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000764}
765
766
767bool Debug::CompileDebuggerScript(int index) {
Steve Block44f0eee2011-05-26 01:26:41 +0100768 Isolate* isolate = Isolate::Current();
769 Factory* factory = isolate->factory();
770 HandleScope scope(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +0000771
772 // Bail out if the index is invalid.
773 if (index == -1) {
774 return false;
775 }
776
777 // Find source and name for the requested script.
Steve Block44f0eee2011-05-26 01:26:41 +0100778 Handle<String> source_code =
779 isolate->bootstrapper()->NativesSourceLookup(index);
Steve Blocka7e24c12009-10-30 11:49:00 +0000780 Vector<const char> name = Natives::GetScriptName(index);
Steve Block44f0eee2011-05-26 01:26:41 +0100781 Handle<String> script_name = factory->NewStringFromAscii(name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000782
783 // Compile the script.
Steve Block6ded16b2010-05-10 14:33:55 +0100784 Handle<SharedFunctionInfo> function_info;
785 function_info = Compiler::Compile(source_code,
786 script_name,
787 0, 0, NULL, NULL,
788 Handle<String>::null(),
789 NATIVES_CODE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000790
791 // Silently ignore stack overflows during compilation.
Steve Block6ded16b2010-05-10 14:33:55 +0100792 if (function_info.is_null()) {
Steve Block44f0eee2011-05-26 01:26:41 +0100793 ASSERT(isolate->has_pending_exception());
794 isolate->clear_pending_exception();
Steve Blocka7e24c12009-10-30 11:49:00 +0000795 return false;
796 }
797
Steve Block6ded16b2010-05-10 14:33:55 +0100798 // Execute the shared function in the debugger context.
Steve Block44f0eee2011-05-26 01:26:41 +0100799 Handle<Context> context = isolate->global_context();
Steve Blocka7e24c12009-10-30 11:49:00 +0000800 bool caught_exception = false;
801 Handle<JSFunction> function =
Steve Block44f0eee2011-05-26 01:26:41 +0100802 factory->NewFunctionFromSharedFunctionInfo(function_info, context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000803 Handle<Object> result =
804 Execution::TryCall(function, Handle<Object>(context->global()),
805 0, NULL, &caught_exception);
806
807 // Check for caught exceptions.
808 if (caught_exception) {
809 Handle<Object> message = MessageHandler::MakeMessageObject(
810 "error_loading_debugger", NULL, Vector<Handle<Object> >::empty(),
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100811 Handle<String>(), Handle<JSArray>());
Ben Murdoch8b112d22011-06-08 16:22:53 +0100812 MessageHandler::ReportMessage(Isolate::Current(), NULL, message);
Steve Blocka7e24c12009-10-30 11:49:00 +0000813 return false;
814 }
815
816 // Mark this script as native and return successfully.
817 Handle<Script> script(Script::cast(function->shared()->script()));
Steve Block6ded16b2010-05-10 14:33:55 +0100818 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
Steve Blocka7e24c12009-10-30 11:49:00 +0000819 return true;
820}
821
822
823bool Debug::Load() {
824 // Return if debugger is already loaded.
825 if (IsLoaded()) return true;
826
Steve Block44f0eee2011-05-26 01:26:41 +0100827 ASSERT(Isolate::Current() == isolate_);
828 Debugger* debugger = isolate_->debugger();
829
Steve Blocka7e24c12009-10-30 11:49:00 +0000830 // Bail out if we're already in the process of compiling the native
831 // JavaScript source code for the debugger.
Steve Block44f0eee2011-05-26 01:26:41 +0100832 if (debugger->compiling_natives() ||
833 debugger->is_loading_debugger())
Steve Blocka7e24c12009-10-30 11:49:00 +0000834 return false;
Steve Block44f0eee2011-05-26 01:26:41 +0100835 debugger->set_loading_debugger(true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000836
837 // Disable breakpoints and interrupts while compiling and running the
838 // debugger scripts including the context creation code.
839 DisableBreak disable(true);
Steve Block44f0eee2011-05-26 01:26:41 +0100840 PostponeInterruptsScope postpone(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000841
842 // Create the debugger context.
Steve Block44f0eee2011-05-26 01:26:41 +0100843 HandleScope scope(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000844 Handle<Context> context =
Steve Block44f0eee2011-05-26 01:26:41 +0100845 isolate_->bootstrapper()->CreateEnvironment(
846 Handle<Object>::null(),
847 v8::Handle<ObjectTemplate>(),
848 NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000849
850 // Use the debugger context.
Steve Block44f0eee2011-05-26 01:26:41 +0100851 SaveContext save(isolate_);
852 isolate_->set_context(*context);
Steve Blocka7e24c12009-10-30 11:49:00 +0000853
854 // Expose the builtins object in the debugger context.
Steve Block44f0eee2011-05-26 01:26:41 +0100855 Handle<String> key = isolate_->factory()->LookupAsciiSymbol("builtins");
Steve Blocka7e24c12009-10-30 11:49:00 +0000856 Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
Steve Block1e0659c2011-05-24 12:43:12 +0100857 RETURN_IF_EMPTY_HANDLE_VALUE(
Steve Block44f0eee2011-05-26 01:26:41 +0100858 isolate_,
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100859 SetProperty(global, key, Handle<Object>(global->builtins()),
860 NONE, kNonStrictMode),
Steve Block1e0659c2011-05-24 12:43:12 +0100861 false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000862
863 // Compile the JavaScript for the debugger in the debugger context.
Steve Block44f0eee2011-05-26 01:26:41 +0100864 debugger->set_compiling_natives(true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000865 bool caught_exception =
866 !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
867 !CompileDebuggerScript(Natives::GetIndex("debug"));
Steve Block6ded16b2010-05-10 14:33:55 +0100868
869 if (FLAG_enable_liveedit) {
870 caught_exception = caught_exception ||
871 !CompileDebuggerScript(Natives::GetIndex("liveedit"));
872 }
873
Steve Block44f0eee2011-05-26 01:26:41 +0100874 debugger->set_compiling_natives(false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000875
876 // Make sure we mark the debugger as not loading before we might
877 // return.
Steve Block44f0eee2011-05-26 01:26:41 +0100878 debugger->set_loading_debugger(false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000879
880 // Check for caught exceptions.
881 if (caught_exception) return false;
882
883 // Debugger loaded.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100884 debug_context_ = context;
Steve Blocka7e24c12009-10-30 11:49:00 +0000885
886 return true;
887}
888
889
890void Debug::Unload() {
891 // Return debugger is not loaded.
892 if (!IsLoaded()) {
893 return;
894 }
895
896 // Clear the script cache.
897 DestroyScriptCache();
898
899 // Clear debugger context global handle.
Steve Block44f0eee2011-05-26 01:26:41 +0100900 Isolate::Current()->global_handles()->Destroy(
901 reinterpret_cast<Object**>(debug_context_.location()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000902 debug_context_ = Handle<Context>();
903}
904
905
906// Set the flag indicating that preemption happened during debugging.
907void Debug::PreemptionWhileInDebugger() {
908 ASSERT(InDebugger());
909 Debug::set_interrupts_pending(PREEMPT);
910}
911
912
913void Debug::Iterate(ObjectVisitor* v) {
Iain Merrick75681382010-08-19 15:07:18 +0100914 v->VisitPointer(BitCast<Object**>(&(debug_break_return_)));
915 v->VisitPointer(BitCast<Object**>(&(debug_break_slot_)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000916}
917
918
Ben Murdoch8b112d22011-06-08 16:22:53 +0100919Object* Debug::Break(Arguments args) {
920 Heap* heap = isolate_->heap();
921 HandleScope scope(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000922 ASSERT(args.length() == 0);
923
Ben Murdoch8b112d22011-06-08 16:22:53 +0100924 thread_local_.frame_drop_mode_ = FRAMES_UNTOUCHED;
Steve Block6ded16b2010-05-10 14:33:55 +0100925
Steve Blocka7e24c12009-10-30 11:49:00 +0000926 // Get the top-most JavaScript frame.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100927 JavaScriptFrameIterator it(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000928 JavaScriptFrame* frame = it.frame();
929
930 // Just continue if breaks are disabled or debugger cannot be loaded.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100931 if (disable_break() || !Load()) {
932 SetAfterBreakTarget(frame);
Steve Block44f0eee2011-05-26 01:26:41 +0100933 return heap->undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000934 }
935
936 // Enter the debugger.
937 EnterDebugger debugger;
938 if (debugger.FailedToEnter()) {
Steve Block44f0eee2011-05-26 01:26:41 +0100939 return heap->undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000940 }
941
942 // Postpone interrupt during breakpoint processing.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100943 PostponeInterruptsScope postpone(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000944
945 // Get the debug info (create it if it does not exist).
946 Handle<SharedFunctionInfo> shared =
947 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
948 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
949
950 // Find the break point where execution has stopped.
951 BreakLocationIterator break_location_iterator(debug_info,
952 ALL_BREAK_LOCATIONS);
953 break_location_iterator.FindBreakLocationFromAddress(frame->pc());
954
955 // Check whether step next reached a new statement.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100956 if (!StepNextContinue(&break_location_iterator, frame)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000957 // Decrease steps left if performing multiple steps.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100958 if (thread_local_.step_count_ > 0) {
959 thread_local_.step_count_--;
Steve Blocka7e24c12009-10-30 11:49:00 +0000960 }
961 }
962
963 // If there is one or more real break points check whether any of these are
964 // triggered.
Steve Block44f0eee2011-05-26 01:26:41 +0100965 Handle<Object> break_points_hit(heap->undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +0000966 if (break_location_iterator.HasBreakPoint()) {
967 Handle<Object> break_point_objects =
968 Handle<Object>(break_location_iterator.BreakPointObjects());
Ben Murdoch8b112d22011-06-08 16:22:53 +0100969 break_points_hit = CheckBreakPoints(break_point_objects);
Steve Blocka7e24c12009-10-30 11:49:00 +0000970 }
971
972 // If step out is active skip everything until the frame where we need to step
973 // out to is reached, unless real breakpoint is hit.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100974 if (StepOutActive() && frame->fp() != step_out_fp() &&
Steve Blocka7e24c12009-10-30 11:49:00 +0000975 break_points_hit->IsUndefined() ) {
976 // Step count should always be 0 for StepOut.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100977 ASSERT(thread_local_.step_count_ == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000978 } else if (!break_points_hit->IsUndefined() ||
Ben Murdoch8b112d22011-06-08 16:22:53 +0100979 (thread_local_.last_step_action_ != StepNone &&
980 thread_local_.step_count_ == 0)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000981 // Notify debugger if a real break point is triggered or if performing
982 // single stepping with no more steps to perform. Otherwise do another step.
983
984 // Clear all current stepping setup.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100985 ClearStepping();
Steve Blocka7e24c12009-10-30 11:49:00 +0000986
987 // Notify the debug event listeners.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100988 isolate_->debugger()->OnDebugBreak(break_points_hit, false);
989 } else if (thread_local_.last_step_action_ != StepNone) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000990 // Hold on to last step action as it is cleared by the call to
991 // ClearStepping.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100992 StepAction step_action = thread_local_.last_step_action_;
993 int step_count = thread_local_.step_count_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000994
995 // Clear all current stepping setup.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100996 ClearStepping();
Steve Blocka7e24c12009-10-30 11:49:00 +0000997
998 // Set up for the remaining steps.
Ben Murdoch8b112d22011-06-08 16:22:53 +0100999 PrepareStep(step_action, step_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00001000 }
1001
Ben Murdoch8b112d22011-06-08 16:22:53 +01001002 if (thread_local_.frame_drop_mode_ == FRAMES_UNTOUCHED) {
1003 SetAfterBreakTarget(frame);
1004 } else if (thread_local_.frame_drop_mode_ ==
Steve Block44f0eee2011-05-26 01:26:41 +01001005 FRAME_DROPPED_IN_IC_CALL) {
Steve Block8defd9f2010-07-08 12:39:36 +01001006 // We must have been calling IC stub. Do not go there anymore.
Ben Murdoch8b112d22011-06-08 16:22:53 +01001007 Code* plain_return = isolate_->builtins()->builtin(
1008 Builtins::kPlainReturn_LiveEdit);
1009 thread_local_.after_break_target_ = plain_return->entry();
1010 } else if (thread_local_.frame_drop_mode_ ==
Steve Block8defd9f2010-07-08 12:39:36 +01001011 FRAME_DROPPED_IN_DEBUG_SLOT_CALL) {
1012 // Debug break slot stub does not return normally, instead it manually
1013 // cleans the stack and jumps. We should patch the jump address.
Ben Murdoch8b112d22011-06-08 16:22:53 +01001014 Code* plain_return = isolate_->builtins()->builtin(
Steve Block44f0eee2011-05-26 01:26:41 +01001015 Builtins::kFrameDropper_LiveEdit);
Ben Murdoch8b112d22011-06-08 16:22:53 +01001016 thread_local_.after_break_target_ = plain_return->entry();
1017 } else if (thread_local_.frame_drop_mode_ ==
Steve Block44f0eee2011-05-26 01:26:41 +01001018 FRAME_DROPPED_IN_DIRECT_CALL) {
Steve Block8defd9f2010-07-08 12:39:36 +01001019 // Nothing to do, after_break_target is not used here.
Steve Block6ded16b2010-05-10 14:33:55 +01001020 } else {
Steve Block8defd9f2010-07-08 12:39:36 +01001021 UNREACHABLE();
Steve Block6ded16b2010-05-10 14:33:55 +01001022 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001023
Steve Block44f0eee2011-05-26 01:26:41 +01001024 return heap->undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001025}
1026
1027
Ben Murdoch8b112d22011-06-08 16:22:53 +01001028RUNTIME_FUNCTION(Object*, Debug_Break) {
1029 return isolate->debug()->Break(args);
1030}
1031
1032
Steve Blocka7e24c12009-10-30 11:49:00 +00001033// Check the break point objects for whether one or more are actually
1034// triggered. This function returns a JSArray with the break point objects
1035// which is triggered.
1036Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
Steve Block44f0eee2011-05-26 01:26:41 +01001037 Factory* factory = isolate_->factory();
Steve Blocka7e24c12009-10-30 11:49:00 +00001038
Steve Block44f0eee2011-05-26 01:26:41 +01001039 // Count the number of break points hit. If there are multiple break points
1040 // they are in a FixedArray.
1041 Handle<FixedArray> break_points_hit;
1042 int break_points_hit_count = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00001043 ASSERT(!break_point_objects->IsUndefined());
1044 if (break_point_objects->IsFixedArray()) {
1045 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
Steve Block44f0eee2011-05-26 01:26:41 +01001046 break_points_hit = factory->NewFixedArray(array->length());
Steve Blocka7e24c12009-10-30 11:49:00 +00001047 for (int i = 0; i < array->length(); i++) {
1048 Handle<Object> o(array->get(i));
1049 if (CheckBreakPoint(o)) {
Steve Block44f0eee2011-05-26 01:26:41 +01001050 break_points_hit->set(break_points_hit_count++, *o);
Steve Blocka7e24c12009-10-30 11:49:00 +00001051 }
1052 }
1053 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01001054 break_points_hit = factory->NewFixedArray(1);
Steve Blocka7e24c12009-10-30 11:49:00 +00001055 if (CheckBreakPoint(break_point_objects)) {
Steve Block44f0eee2011-05-26 01:26:41 +01001056 break_points_hit->set(break_points_hit_count++, *break_point_objects);
Steve Blocka7e24c12009-10-30 11:49:00 +00001057 }
1058 }
1059
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001060 // Return undefined if no break points were triggered.
Steve Blocka7e24c12009-10-30 11:49:00 +00001061 if (break_points_hit_count == 0) {
Steve Block44f0eee2011-05-26 01:26:41 +01001062 return factory->undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001063 }
Steve Block44f0eee2011-05-26 01:26:41 +01001064 // Return break points hit as a JSArray.
1065 Handle<JSArray> result = factory->NewJSArrayWithElements(break_points_hit);
1066 result->set_length(Smi::FromInt(break_points_hit_count));
1067 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00001068}
1069
1070
1071// Check whether a single break point object is triggered.
1072bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
Steve Block44f0eee2011-05-26 01:26:41 +01001073 ASSERT(Isolate::Current() == isolate_);
1074 Factory* factory = isolate_->factory();
1075 HandleScope scope(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001076
1077 // Ignore check if break point object is not a JSObject.
1078 if (!break_point_object->IsJSObject()) return true;
1079
Steve Block44f0eee2011-05-26 01:26:41 +01001080 // Get the function IsBreakPointTriggered (defined in debug-debugger.js).
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001081 Handle<String> is_break_point_triggered_symbol =
Steve Block44f0eee2011-05-26 01:26:41 +01001082 factory->LookupAsciiSymbol("IsBreakPointTriggered");
Steve Blocka7e24c12009-10-30 11:49:00 +00001083 Handle<JSFunction> check_break_point =
1084 Handle<JSFunction>(JSFunction::cast(
John Reck59135872010-11-02 12:39:01 -07001085 debug_context()->global()->GetPropertyNoExceptionThrown(
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001086 *is_break_point_triggered_symbol)));
Steve Blocka7e24c12009-10-30 11:49:00 +00001087
1088 // Get the break id as an object.
Steve Block44f0eee2011-05-26 01:26:41 +01001089 Handle<Object> break_id = factory->NewNumberFromInt(Debug::break_id());
Steve Blocka7e24c12009-10-30 11:49:00 +00001090
1091 // Call HandleBreakPointx.
1092 bool caught_exception = false;
1093 const int argc = 2;
1094 Object** argv[argc] = {
1095 break_id.location(),
1096 reinterpret_cast<Object**>(break_point_object.location())
1097 };
1098 Handle<Object> result = Execution::TryCall(check_break_point,
Steve Block44f0eee2011-05-26 01:26:41 +01001099 isolate_->js_builtins_object(), argc, argv, &caught_exception);
Steve Blocka7e24c12009-10-30 11:49:00 +00001100
1101 // If exception or non boolean result handle as not triggered
1102 if (caught_exception || !result->IsBoolean()) {
1103 return false;
1104 }
1105
1106 // Return whether the break point is triggered.
Steve Block44f0eee2011-05-26 01:26:41 +01001107 ASSERT(!result.is_null());
1108 return (*result)->IsTrue();
Steve Blocka7e24c12009-10-30 11:49:00 +00001109}
1110
1111
1112// Check whether the function has debug information.
1113bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
1114 return !shared->debug_info()->IsUndefined();
1115}
1116
1117
1118// Return the debug info for this function. EnsureDebugInfo must be called
1119// prior to ensure the debug info has been generated for shared.
1120Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
1121 ASSERT(HasDebugInfo(shared));
1122 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
1123}
1124
1125
1126void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001127 Handle<Object> break_point_object,
1128 int* source_position) {
Steve Block44f0eee2011-05-26 01:26:41 +01001129 HandleScope scope(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001130
1131 if (!EnsureDebugInfo(shared)) {
1132 // Return if retrieving debug info failed.
1133 return;
1134 }
1135
1136 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1137 // Source positions starts with zero.
1138 ASSERT(source_position >= 0);
1139
1140 // Find the break point and change it.
1141 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001142 it.FindBreakLocationFromPosition(*source_position);
Steve Blocka7e24c12009-10-30 11:49:00 +00001143 it.SetBreakPoint(break_point_object);
1144
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001145 *source_position = it.position();
1146
Steve Blocka7e24c12009-10-30 11:49:00 +00001147 // At least one active break point now.
1148 ASSERT(debug_info->GetBreakPointCount() > 0);
1149}
1150
1151
1152void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
Steve Block44f0eee2011-05-26 01:26:41 +01001153 HandleScope scope(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001154
1155 DebugInfoListNode* node = debug_info_list_;
1156 while (node != NULL) {
1157 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
1158 break_point_object);
1159 if (!result->IsUndefined()) {
1160 // Get information in the break point.
1161 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
1162 Handle<DebugInfo> debug_info = node->debug_info();
1163 Handle<SharedFunctionInfo> shared(debug_info->shared());
1164 int source_position = break_point_info->statement_position()->value();
1165
1166 // Source positions starts with zero.
1167 ASSERT(source_position >= 0);
1168
1169 // Find the break point and clear it.
1170 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1171 it.FindBreakLocationFromPosition(source_position);
1172 it.ClearBreakPoint(break_point_object);
1173
1174 // If there are no more break points left remove the debug info for this
1175 // function.
1176 if (debug_info->GetBreakPointCount() == 0) {
1177 RemoveDebugInfo(debug_info);
1178 }
1179
1180 return;
1181 }
1182 node = node->next();
1183 }
1184}
1185
1186
1187void Debug::ClearAllBreakPoints() {
1188 DebugInfoListNode* node = debug_info_list_;
1189 while (node != NULL) {
1190 // Remove all debug break code.
1191 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1192 it.ClearAllDebugBreak();
1193 node = node->next();
1194 }
1195
1196 // Remove all debug info.
1197 while (debug_info_list_ != NULL) {
1198 RemoveDebugInfo(debug_info_list_->debug_info());
1199 }
1200}
1201
1202
1203void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
1204 // Make sure the function has setup the debug info.
1205 if (!EnsureDebugInfo(shared)) {
1206 // Return if we failed to retrieve the debug info.
1207 return;
1208 }
1209
1210 // Flood the function with break points.
1211 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
1212 while (!it.Done()) {
1213 it.SetOneShot();
1214 it.Next();
1215 }
1216}
1217
1218
1219void Debug::FloodHandlerWithOneShot() {
1220 // Iterate through the JavaScript stack looking for handlers.
1221 StackFrame::Id id = break_frame_id();
1222 if (id == StackFrame::NO_ID) {
1223 // If there is no JavaScript stack don't do anything.
1224 return;
1225 }
Ben Murdoch8b112d22011-06-08 16:22:53 +01001226 for (JavaScriptFrameIterator it(isolate_, id); !it.done(); it.Advance()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001227 JavaScriptFrame* frame = it.frame();
1228 if (frame->HasHandler()) {
1229 Handle<SharedFunctionInfo> shared =
1230 Handle<SharedFunctionInfo>(
1231 JSFunction::cast(frame->function())->shared());
1232 // Flood the function with the catch block with break points
1233 FloodWithOneShot(shared);
1234 return;
1235 }
1236 }
1237}
1238
1239
1240void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
1241 if (type == BreakUncaughtException) {
1242 break_on_uncaught_exception_ = enable;
1243 } else {
1244 break_on_exception_ = enable;
1245 }
1246}
1247
1248
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001249bool Debug::IsBreakOnException(ExceptionBreakType type) {
1250 if (type == BreakUncaughtException) {
1251 return break_on_uncaught_exception_;
1252 } else {
1253 return break_on_exception_;
1254 }
1255}
1256
1257
Steve Blocka7e24c12009-10-30 11:49:00 +00001258void Debug::PrepareStep(StepAction step_action, int step_count) {
Steve Block44f0eee2011-05-26 01:26:41 +01001259 ASSERT(Isolate::Current() == isolate_);
1260 HandleScope scope(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001261 ASSERT(Debug::InDebugger());
1262
1263 // Remember this step action and count.
1264 thread_local_.last_step_action_ = step_action;
1265 if (step_action == StepOut) {
1266 // For step out target frame will be found on the stack so there is no need
1267 // to set step counter for it. It's expected to always be 0 for StepOut.
1268 thread_local_.step_count_ = 0;
1269 } else {
1270 thread_local_.step_count_ = step_count;
1271 }
1272
1273 // Get the frame where the execution has stopped and skip the debug frame if
1274 // any. The debug frame will only be present if execution was stopped due to
1275 // hitting a break point. In other situations (e.g. unhandled exception) the
1276 // debug frame is not present.
1277 StackFrame::Id id = break_frame_id();
1278 if (id == StackFrame::NO_ID) {
1279 // If there is no JavaScript stack don't do anything.
1280 return;
1281 }
Ben Murdoch8b112d22011-06-08 16:22:53 +01001282 JavaScriptFrameIterator frames_it(isolate_, id);
Steve Blocka7e24c12009-10-30 11:49:00 +00001283 JavaScriptFrame* frame = frames_it.frame();
1284
1285 // First of all ensure there is one-shot break points in the top handler
1286 // if any.
1287 FloodHandlerWithOneShot();
1288
1289 // If the function on the top frame is unresolved perform step out. This will
1290 // be the case when calling unknown functions and having the debugger stopped
1291 // in an unhandled exception.
1292 if (!frame->function()->IsJSFunction()) {
1293 // Step out: Find the calling JavaScript frame and flood it with
1294 // breakpoints.
1295 frames_it.Advance();
1296 // Fill the function to return to with one-shot break points.
1297 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1298 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1299 return;
1300 }
1301
1302 // Get the debug info (create it if it does not exist).
1303 Handle<SharedFunctionInfo> shared =
1304 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
1305 if (!EnsureDebugInfo(shared)) {
1306 // Return if ensuring debug info failed.
1307 return;
1308 }
1309 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1310
1311 // Find the break location where execution has stopped.
1312 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1313 it.FindBreakLocationFromAddress(frame->pc());
1314
1315 // Compute whether or not the target is a call target.
Steve Blocka7e24c12009-10-30 11:49:00 +00001316 bool is_load_or_store = false;
1317 bool is_inline_cache_stub = false;
Ben Murdochbb769b22010-08-11 14:56:33 +01001318 bool is_at_restarted_function = false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001319 Handle<Code> call_function_stub;
Steve Blocka7e24c12009-10-30 11:49:00 +00001320
Ben Murdochbb769b22010-08-11 14:56:33 +01001321 if (thread_local_.restarter_frame_function_pointer_ == NULL) {
1322 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
1323 bool is_call_target = false;
1324 Address target = it.rinfo()->target_address();
1325 Code* code = Code::GetCodeFromTargetAddress(target);
1326 if (code->is_call_stub() || code->is_keyed_call_stub()) {
1327 is_call_target = true;
1328 }
1329 if (code->is_inline_cache_stub()) {
1330 is_inline_cache_stub = true;
1331 is_load_or_store = !is_call_target;
1332 }
1333
1334 // Check if target code is CallFunction stub.
1335 Code* maybe_call_function_stub = code;
1336 // If there is a breakpoint at this line look at the original code to
1337 // check if it is a CallFunction stub.
1338 if (it.IsDebugBreak()) {
1339 Address original_target = it.original_rinfo()->target_address();
1340 maybe_call_function_stub =
1341 Code::GetCodeFromTargetAddress(original_target);
1342 }
1343 if (maybe_call_function_stub->kind() == Code::STUB &&
1344 maybe_call_function_stub->major_key() == CodeStub::CallFunction) {
1345 // Save reference to the code as we may need it to find out arguments
1346 // count for 'step in' later.
1347 call_function_stub = Handle<Code>(maybe_call_function_stub);
1348 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001349 }
Ben Murdochbb769b22010-08-11 14:56:33 +01001350 } else {
1351 is_at_restarted_function = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00001352 }
1353
1354 // If this is the last break code target step out is the only possibility.
1355 if (it.IsExit() || step_action == StepOut) {
1356 if (step_action == StepOut) {
1357 // Skip step_count frames starting with the current one.
1358 while (step_count-- > 0 && !frames_it.done()) {
1359 frames_it.Advance();
1360 }
1361 } else {
1362 ASSERT(it.IsExit());
1363 frames_it.Advance();
1364 }
1365 // Skip builtin functions on the stack.
1366 while (!frames_it.done() &&
1367 JSFunction::cast(frames_it.frame()->function())->IsBuiltin()) {
1368 frames_it.Advance();
1369 }
1370 // Step out: If there is a JavaScript caller frame, we need to
1371 // flood it with breakpoints.
1372 if (!frames_it.done()) {
1373 // Fill the function to return to with one-shot break points.
1374 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1375 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1376 // Set target frame pointer.
1377 ActivateStepOut(frames_it.frame());
1378 }
1379 } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) ||
Ben Murdochbb769b22010-08-11 14:56:33 +01001380 !call_function_stub.is_null() || is_at_restarted_function)
Steve Blocka7e24c12009-10-30 11:49:00 +00001381 || step_action == StepNext || step_action == StepMin) {
1382 // Step next or step min.
1383
1384 // Fill the current function with one-shot break points.
1385 FloodWithOneShot(shared);
1386
1387 // Remember source position and frame to handle step next.
1388 thread_local_.last_statement_position_ =
1389 debug_info->code()->SourceStatementPosition(frame->pc());
1390 thread_local_.last_fp_ = frame->fp();
1391 } else {
Ben Murdochbb769b22010-08-11 14:56:33 +01001392 // If there's restarter frame on top of the stack, just get the pointer
1393 // to function which is going to be restarted.
1394 if (is_at_restarted_function) {
1395 Handle<JSFunction> restarted_function(
1396 JSFunction::cast(*thread_local_.restarter_frame_function_pointer_));
1397 Handle<SharedFunctionInfo> restarted_shared(
1398 restarted_function->shared());
1399 FloodWithOneShot(restarted_shared);
1400 } else if (!call_function_stub.is_null()) {
1401 // If it's CallFunction stub ensure target function is compiled and flood
1402 // it with one shot breakpoints.
1403
Steve Blocka7e24c12009-10-30 11:49:00 +00001404 // Find out number of arguments from the stub minor key.
1405 // Reverse lookup required as the minor key cannot be retrieved
1406 // from the code object.
1407 Handle<Object> obj(
Steve Block44f0eee2011-05-26 01:26:41 +01001408 isolate_->heap()->code_stubs()->SlowReverseLookup(
1409 *call_function_stub));
1410 ASSERT(!obj.is_null());
1411 ASSERT(!(*obj)->IsUndefined());
Steve Blocka7e24c12009-10-30 11:49:00 +00001412 ASSERT(obj->IsSmi());
1413 // Get the STUB key and extract major and minor key.
1414 uint32_t key = Smi::cast(*obj)->value();
1415 // Argc in the stub is the number of arguments passed - not the
1416 // expected arguments of the called function.
Leon Clarkee46be812010-01-19 14:06:41 +00001417 int call_function_arg_count =
1418 CallFunctionStub::ExtractArgcFromMinorKey(
1419 CodeStub::MinorKeyFromKey(key));
Steve Blocka7e24c12009-10-30 11:49:00 +00001420 ASSERT(call_function_stub->major_key() ==
1421 CodeStub::MajorKeyFromKey(key));
1422
1423 // Find target function on the expression stack.
Leon Clarkee46be812010-01-19 14:06:41 +00001424 // Expression stack looks like this (top to bottom):
Steve Blocka7e24c12009-10-30 11:49:00 +00001425 // argN
1426 // ...
1427 // arg0
1428 // Receiver
1429 // Function to call
1430 int expressions_count = frame->ComputeExpressionsCount();
1431 ASSERT(expressions_count - 2 - call_function_arg_count >= 0);
1432 Object* fun = frame->GetExpression(
1433 expressions_count - 2 - call_function_arg_count);
1434 if (fun->IsJSFunction()) {
1435 Handle<JSFunction> js_function(JSFunction::cast(fun));
1436 // Don't step into builtins.
1437 if (!js_function->IsBuiltin()) {
1438 // It will also compile target function if it's not compiled yet.
1439 FloodWithOneShot(Handle<SharedFunctionInfo>(js_function->shared()));
1440 }
1441 }
1442 }
1443
1444 // Fill the current function with one-shot break points even for step in on
1445 // a call target as the function called might be a native function for
1446 // which step in will not stop. It also prepares for stepping in
1447 // getters/setters.
1448 FloodWithOneShot(shared);
1449
1450 if (is_load_or_store) {
1451 // Remember source position and frame to handle step in getter/setter. If
1452 // there is a custom getter/setter it will be handled in
1453 // Object::Get/SetPropertyWithCallback, otherwise the step action will be
1454 // propagated on the next Debug::Break.
1455 thread_local_.last_statement_position_ =
1456 debug_info->code()->SourceStatementPosition(frame->pc());
1457 thread_local_.last_fp_ = frame->fp();
1458 }
1459
1460 // Step in or Step in min
1461 it.PrepareStepIn();
1462 ActivateStepIn(frame);
1463 }
1464}
1465
1466
1467// Check whether the current debug break should be reported to the debugger. It
1468// is used to have step next and step in only report break back to the debugger
1469// if on a different frame or in a different statement. In some situations
1470// there will be several break points in the same statement when the code is
1471// flooded with one-shot break points. This function helps to perform several
1472// steps before reporting break back to the debugger.
1473bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
1474 JavaScriptFrame* frame) {
1475 // If the step last action was step next or step in make sure that a new
1476 // statement is hit.
1477 if (thread_local_.last_step_action_ == StepNext ||
1478 thread_local_.last_step_action_ == StepIn) {
1479 // Never continue if returning from function.
1480 if (break_location_iterator->IsExit()) return false;
1481
1482 // Continue if we are still on the same frame and in the same statement.
1483 int current_statement_position =
1484 break_location_iterator->code()->SourceStatementPosition(frame->pc());
1485 return thread_local_.last_fp_ == frame->fp() &&
1486 thread_local_.last_statement_position_ == current_statement_position;
1487 }
1488
1489 // No step next action - don't continue.
1490 return false;
1491}
1492
1493
1494// Check whether the code object at the specified address is a debug break code
1495// object.
1496bool Debug::IsDebugBreak(Address addr) {
1497 Code* code = Code::GetCodeFromTargetAddress(addr);
1498 return code->ic_state() == DEBUG_BREAK;
1499}
1500
1501
1502// Check whether a code stub with the specified major key is a possible break
1503// point location when looking for source break locations.
1504bool Debug::IsSourceBreakStub(Code* code) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001505 CodeStub::Major major_key = CodeStub::GetMajorKey(code);
Steve Blocka7e24c12009-10-30 11:49:00 +00001506 return major_key == CodeStub::CallFunction;
1507}
1508
1509
1510// Check whether a code stub with the specified major key is a possible break
1511// location.
1512bool Debug::IsBreakStub(Code* code) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001513 CodeStub::Major major_key = CodeStub::GetMajorKey(code);
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001514 return major_key == CodeStub::CallFunction;
Steve Blocka7e24c12009-10-30 11:49:00 +00001515}
1516
1517
1518// Find the builtin to use for invoking the debug break
1519Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) {
1520 // Find the builtin debug break function matching the calling convention
1521 // used by the call site.
1522 if (code->is_inline_cache_stub()) {
Steve Block6ded16b2010-05-10 14:33:55 +01001523 switch (code->kind()) {
1524 case Code::CALL_IC:
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001525 case Code::KEYED_CALL_IC:
1526 return ComputeCallDebugBreak(code->arguments_count(), code->kind());
Steve Block6ded16b2010-05-10 14:33:55 +01001527
1528 case Code::LOAD_IC:
Steve Block44f0eee2011-05-26 01:26:41 +01001529 return Isolate::Current()->builtins()->LoadIC_DebugBreak();
Steve Block6ded16b2010-05-10 14:33:55 +01001530
1531 case Code::STORE_IC:
Steve Block44f0eee2011-05-26 01:26:41 +01001532 return Isolate::Current()->builtins()->StoreIC_DebugBreak();
Steve Block6ded16b2010-05-10 14:33:55 +01001533
1534 case Code::KEYED_LOAD_IC:
Steve Block44f0eee2011-05-26 01:26:41 +01001535 return Isolate::Current()->builtins()->KeyedLoadIC_DebugBreak();
Steve Block6ded16b2010-05-10 14:33:55 +01001536
1537 case Code::KEYED_STORE_IC:
Steve Block44f0eee2011-05-26 01:26:41 +01001538 return Isolate::Current()->builtins()->KeyedStoreIC_DebugBreak();
Steve Block6ded16b2010-05-10 14:33:55 +01001539
1540 default:
1541 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +00001542 }
1543 }
1544 if (RelocInfo::IsConstructCall(mode)) {
1545 Handle<Code> result =
Steve Block44f0eee2011-05-26 01:26:41 +01001546 Isolate::Current()->builtins()->ConstructCall_DebugBreak();
Steve Blocka7e24c12009-10-30 11:49:00 +00001547 return result;
1548 }
1549 if (code->kind() == Code::STUB) {
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08001550 ASSERT(code->major_key() == CodeStub::CallFunction);
Steve Blocka7e24c12009-10-30 11:49:00 +00001551 Handle<Code> result =
Steve Block44f0eee2011-05-26 01:26:41 +01001552 Isolate::Current()->builtins()->StubNoRegisters_DebugBreak();
Steve Blocka7e24c12009-10-30 11:49:00 +00001553 return result;
1554 }
1555
1556 UNREACHABLE();
1557 return Handle<Code>::null();
1558}
1559
1560
1561// Simple function for returning the source positions for active break points.
1562Handle<Object> Debug::GetSourceBreakLocations(
1563 Handle<SharedFunctionInfo> shared) {
Steve Block44f0eee2011-05-26 01:26:41 +01001564 Isolate* isolate = Isolate::Current();
1565 Heap* heap = isolate->heap();
1566 if (!HasDebugInfo(shared)) return Handle<Object>(heap->undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +00001567 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1568 if (debug_info->GetBreakPointCount() == 0) {
Steve Block44f0eee2011-05-26 01:26:41 +01001569 return Handle<Object>(heap->undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +00001570 }
1571 Handle<FixedArray> locations =
Steve Block44f0eee2011-05-26 01:26:41 +01001572 isolate->factory()->NewFixedArray(debug_info->GetBreakPointCount());
Steve Blocka7e24c12009-10-30 11:49:00 +00001573 int count = 0;
1574 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1575 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1576 BreakPointInfo* break_point_info =
1577 BreakPointInfo::cast(debug_info->break_points()->get(i));
1578 if (break_point_info->GetBreakPointCount() > 0) {
1579 locations->set(count++, break_point_info->statement_position());
1580 }
1581 }
1582 }
1583 return locations;
1584}
1585
1586
1587void Debug::NewBreak(StackFrame::Id break_frame_id) {
1588 thread_local_.break_frame_id_ = break_frame_id;
1589 thread_local_.break_id_ = ++thread_local_.break_count_;
1590}
1591
1592
1593void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
1594 thread_local_.break_frame_id_ = break_frame_id;
1595 thread_local_.break_id_ = break_id;
1596}
1597
1598
1599// Handle stepping into a function.
1600void Debug::HandleStepIn(Handle<JSFunction> function,
1601 Handle<Object> holder,
1602 Address fp,
1603 bool is_constructor) {
1604 // If the frame pointer is not supplied by the caller find it.
1605 if (fp == 0) {
1606 StackFrameIterator it;
1607 it.Advance();
1608 // For constructor functions skip another frame.
1609 if (is_constructor) {
1610 ASSERT(it.frame()->is_construct());
1611 it.Advance();
1612 }
1613 fp = it.frame()->fp();
1614 }
1615
1616 // Flood the function with one-shot break points if it is called from where
1617 // step into was requested.
Steve Block44f0eee2011-05-26 01:26:41 +01001618 if (fp == step_in_fp()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001619 // Don't allow step into functions in the native context.
1620 if (!function->IsBuiltin()) {
1621 if (function->shared()->code() ==
Steve Block44f0eee2011-05-26 01:26:41 +01001622 Isolate::Current()->builtins()->builtin(Builtins::kFunctionApply) ||
Steve Blocka7e24c12009-10-30 11:49:00 +00001623 function->shared()->code() ==
Steve Block44f0eee2011-05-26 01:26:41 +01001624 Isolate::Current()->builtins()->builtin(Builtins::kFunctionCall)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001625 // Handle function.apply and function.call separately to flood the
1626 // function to be called and not the code for Builtins::FunctionApply or
1627 // Builtins::FunctionCall. The receiver of call/apply is the target
1628 // function.
1629 if (!holder.is_null() && holder->IsJSFunction() &&
1630 !JSFunction::cast(*holder)->IsBuiltin()) {
1631 Handle<SharedFunctionInfo> shared_info(
1632 JSFunction::cast(*holder)->shared());
1633 Debug::FloodWithOneShot(shared_info);
1634 }
1635 } else {
1636 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1637 }
1638 }
1639 }
1640}
1641
1642
1643void Debug::ClearStepping() {
1644 // Clear the various stepping setup.
1645 ClearOneShot();
1646 ClearStepIn();
1647 ClearStepOut();
1648 ClearStepNext();
1649
1650 // Clear multiple step counter.
1651 thread_local_.step_count_ = 0;
1652}
1653
1654// Clears all the one-shot break points that are currently set. Normally this
1655// function is called each time a break point is hit as one shot break points
1656// are used to support stepping.
1657void Debug::ClearOneShot() {
1658 // The current implementation just runs through all the breakpoints. When the
1659 // last break point for a function is removed that function is automatically
1660 // removed from the list.
1661
1662 DebugInfoListNode* node = debug_info_list_;
1663 while (node != NULL) {
1664 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1665 while (!it.Done()) {
1666 it.ClearOneShot();
1667 it.Next();
1668 }
1669 node = node->next();
1670 }
1671}
1672
1673
1674void Debug::ActivateStepIn(StackFrame* frame) {
1675 ASSERT(!StepOutActive());
1676 thread_local_.step_into_fp_ = frame->fp();
1677}
1678
1679
1680void Debug::ClearStepIn() {
1681 thread_local_.step_into_fp_ = 0;
1682}
1683
1684
1685void Debug::ActivateStepOut(StackFrame* frame) {
1686 ASSERT(!StepInActive());
1687 thread_local_.step_out_fp_ = frame->fp();
1688}
1689
1690
1691void Debug::ClearStepOut() {
1692 thread_local_.step_out_fp_ = 0;
1693}
1694
1695
1696void Debug::ClearStepNext() {
1697 thread_local_.last_step_action_ = StepNone;
1698 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
1699 thread_local_.last_fp_ = 0;
1700}
1701
1702
Steve Blocka7e24c12009-10-30 11:49:00 +00001703// Ensures the debug information is present for shared.
1704bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1705 // Return if we already have the debug info for shared.
1706 if (HasDebugInfo(shared)) return true;
1707
1708 // Ensure shared in compiled. Return false if this failed.
Leon Clarke4515c472010-02-03 11:58:03 +00001709 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001710
Ben Murdochb0fe1622011-05-05 13:52:32 +01001711 // If preparing for the first break point make sure to deoptimize all
1712 // functions as debugging does not work with optimized code.
1713 if (!has_break_points_) {
1714 Deoptimizer::DeoptimizeAll();
1715 }
1716
Steve Blocka7e24c12009-10-30 11:49:00 +00001717 // Create the debug info object.
Steve Block44f0eee2011-05-26 01:26:41 +01001718 Handle<DebugInfo> debug_info = FACTORY->NewDebugInfo(shared);
Steve Blocka7e24c12009-10-30 11:49:00 +00001719
1720 // Add debug info to the list.
1721 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1722 node->set_next(debug_info_list_);
1723 debug_info_list_ = node;
1724
1725 // Now there is at least one break point.
1726 has_break_points_ = true;
1727
1728 return true;
1729}
1730
1731
1732void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1733 ASSERT(debug_info_list_ != NULL);
1734 // Run through the debug info objects to find this one and remove it.
1735 DebugInfoListNode* prev = NULL;
1736 DebugInfoListNode* current = debug_info_list_;
1737 while (current != NULL) {
1738 if (*current->debug_info() == *debug_info) {
1739 // Unlink from list. If prev is NULL we are looking at the first element.
1740 if (prev == NULL) {
1741 debug_info_list_ = current->next();
1742 } else {
1743 prev->set_next(current->next());
1744 }
Steve Block44f0eee2011-05-26 01:26:41 +01001745 current->debug_info()->shared()->set_debug_info(
1746 isolate_->heap()->undefined_value());
Steve Blocka7e24c12009-10-30 11:49:00 +00001747 delete current;
1748
1749 // If there are no more debug info objects there are not more break
1750 // points.
1751 has_break_points_ = debug_info_list_ != NULL;
1752
1753 return;
1754 }
1755 // Move to next in list.
1756 prev = current;
1757 current = current->next();
1758 }
1759 UNREACHABLE();
1760}
1761
1762
1763void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
Steve Block44f0eee2011-05-26 01:26:41 +01001764 ASSERT(Isolate::Current() == isolate_);
1765 HandleScope scope(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001766
1767 // Get the executing function in which the debug break occurred.
1768 Handle<SharedFunctionInfo> shared =
1769 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
1770 if (!EnsureDebugInfo(shared)) {
1771 // Return if we failed to retrieve the debug info.
1772 return;
1773 }
1774 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1775 Handle<Code> code(debug_info->code());
1776 Handle<Code> original_code(debug_info->original_code());
1777#ifdef DEBUG
1778 // Get the code which is actually executing.
Ben Murdoch8b112d22011-06-08 16:22:53 +01001779 Handle<Code> frame_code(frame->LookupCode());
Steve Blocka7e24c12009-10-30 11:49:00 +00001780 ASSERT(frame_code.is_identical_to(code));
1781#endif
1782
1783 // Find the call address in the running code. This address holds the call to
1784 // either a DebugBreakXXX or to the debug break return entry code if the
1785 // break point is still active after processing the break point.
1786 Address addr = frame->pc() - Assembler::kCallTargetAddressOffset;
1787
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001788 // Check if the location is at JS exit or debug break slot.
Steve Blocka7e24c12009-10-30 11:49:00 +00001789 bool at_js_return = false;
1790 bool break_at_js_return_active = false;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001791 bool at_debug_break_slot = false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001792 RelocIterator it(debug_info->code());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001793 while (!it.done() && !at_js_return && !at_debug_break_slot) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001794 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
1795 at_js_return = (it.rinfo()->pc() ==
1796 addr - Assembler::kPatchReturnSequenceAddressOffset);
Steve Block3ce2e202009-11-05 08:53:23 +00001797 break_at_js_return_active = it.rinfo()->IsPatchedReturnSequence();
Steve Blocka7e24c12009-10-30 11:49:00 +00001798 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001799 if (RelocInfo::IsDebugBreakSlot(it.rinfo()->rmode())) {
1800 at_debug_break_slot = (it.rinfo()->pc() ==
1801 addr - Assembler::kPatchDebugBreakSlotAddressOffset);
1802 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001803 it.next();
1804 }
1805
1806 // Handle the jump to continue execution after break point depending on the
1807 // break location.
1808 if (at_js_return) {
1809 // If the break point as return is still active jump to the corresponding
1810 // place in the original code. If not the break point was removed during
1811 // break point processing.
1812 if (break_at_js_return_active) {
1813 addr += original_code->instruction_start() - code->instruction_start();
1814 }
1815
1816 // Move back to where the call instruction sequence started.
1817 thread_local_.after_break_target_ =
1818 addr - Assembler::kPatchReturnSequenceAddressOffset;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001819 } else if (at_debug_break_slot) {
1820 // Address of where the debug break slot starts.
1821 addr = addr - Assembler::kPatchDebugBreakSlotAddressOffset;
Steve Blocka7e24c12009-10-30 11:49:00 +00001822
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001823 // Continue just after the slot.
1824 thread_local_.after_break_target_ = addr + Assembler::kDebugBreakSlotLength;
1825 } else if (IsDebugBreak(Assembler::target_address_at(addr))) {
1826 // We now know that there is still a debug break call at the target address,
1827 // so the break point is still there and the original code will hold the
1828 // address to jump to in order to complete the call which is replaced by a
1829 // call to DebugBreakXXX.
1830
1831 // Find the corresponding address in the original code.
1832 addr += original_code->instruction_start() - code->instruction_start();
Steve Blocka7e24c12009-10-30 11:49:00 +00001833
1834 // Install jump to the call address in the original code. This will be the
1835 // call which was overwritten by the call to DebugBreakXXX.
1836 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001837 } else {
1838 // There is no longer a break point present. Don't try to look in the
1839 // original code as the running code will have the right address. This takes
1840 // care of the case where the last break point is removed from the function
1841 // and therefore no "original code" is available.
1842 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
Steve Blocka7e24c12009-10-30 11:49:00 +00001843 }
1844}
1845
1846
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001847bool Debug::IsBreakAtReturn(JavaScriptFrame* frame) {
Steve Block44f0eee2011-05-26 01:26:41 +01001848 HandleScope scope(isolate_);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001849
1850 // Get the executing function in which the debug break occurred.
1851 Handle<SharedFunctionInfo> shared =
1852 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
1853 if (!EnsureDebugInfo(shared)) {
1854 // Return if we failed to retrieve the debug info.
1855 return false;
1856 }
1857 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1858 Handle<Code> code(debug_info->code());
1859#ifdef DEBUG
1860 // Get the code which is actually executing.
Ben Murdoch8b112d22011-06-08 16:22:53 +01001861 Handle<Code> frame_code(frame->LookupCode());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001862 ASSERT(frame_code.is_identical_to(code));
1863#endif
1864
1865 // Find the call address in the running code.
1866 Address addr = frame->pc() - Assembler::kCallTargetAddressOffset;
1867
1868 // Check if the location is at JS return.
1869 RelocIterator it(debug_info->code());
1870 while (!it.done()) {
1871 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
1872 return (it.rinfo()->pc() ==
1873 addr - Assembler::kPatchReturnSequenceAddressOffset);
1874 }
1875 it.next();
1876 }
1877 return false;
1878}
1879
1880
Steve Block8defd9f2010-07-08 12:39:36 +01001881void Debug::FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
Ben Murdochbb769b22010-08-11 14:56:33 +01001882 FrameDropMode mode,
1883 Object** restarter_frame_function_pointer) {
Steve Block8defd9f2010-07-08 12:39:36 +01001884 thread_local_.frame_drop_mode_ = mode;
Steve Block6ded16b2010-05-10 14:33:55 +01001885 thread_local_.break_frame_id_ = new_break_frame_id;
Ben Murdochbb769b22010-08-11 14:56:33 +01001886 thread_local_.restarter_frame_function_pointer_ =
1887 restarter_frame_function_pointer;
Steve Block6ded16b2010-05-10 14:33:55 +01001888}
1889
1890
Steve Blocka7e24c12009-10-30 11:49:00 +00001891bool Debug::IsDebugGlobal(GlobalObject* global) {
Steve Block44f0eee2011-05-26 01:26:41 +01001892 return IsLoaded() && global == debug_context()->global();
Steve Blocka7e24c12009-10-30 11:49:00 +00001893}
1894
1895
1896void Debug::ClearMirrorCache() {
Steve Block44f0eee2011-05-26 01:26:41 +01001897 ASSERT(Isolate::Current() == isolate_);
1898 PostponeInterruptsScope postpone(isolate_);
1899 HandleScope scope(isolate_);
1900 ASSERT(isolate_->context() == *Debug::debug_context());
Steve Blocka7e24c12009-10-30 11:49:00 +00001901
1902 // Clear the mirror cache.
1903 Handle<String> function_name =
Steve Block44f0eee2011-05-26 01:26:41 +01001904 isolate_->factory()->LookupSymbol(CStrVector("ClearMirrorCache"));
1905 Handle<Object> fun(Isolate::Current()->global()->GetPropertyNoExceptionThrown(
John Reck59135872010-11-02 12:39:01 -07001906 *function_name));
Steve Blocka7e24c12009-10-30 11:49:00 +00001907 ASSERT(fun->IsJSFunction());
1908 bool caught_exception;
1909 Handle<Object> js_object = Execution::TryCall(
1910 Handle<JSFunction>::cast(fun),
1911 Handle<JSObject>(Debug::debug_context()->global()),
1912 0, NULL, &caught_exception);
1913}
1914
1915
Steve Blocka7e24c12009-10-30 11:49:00 +00001916void Debug::CreateScriptCache() {
Steve Block44f0eee2011-05-26 01:26:41 +01001917 ASSERT(Isolate::Current() == isolate_);
1918 Heap* heap = isolate_->heap();
1919 HandleScope scope(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001920
1921 // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
1922 // rid of all the cached script wrappers and the second gets rid of the
Andrei Popescu31002712010-02-23 13:46:05 +00001923 // scripts which are no longer referenced.
Steve Block44f0eee2011-05-26 01:26:41 +01001924 heap->CollectAllGarbage(false);
1925 heap->CollectAllGarbage(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00001926
1927 ASSERT(script_cache_ == NULL);
1928 script_cache_ = new ScriptCache();
1929
1930 // Scan heap for Script objects.
1931 int count = 0;
1932 HeapIterator iterator;
Leon Clarked91b9f72010-01-27 17:25:45 +00001933 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
Steve Block3ce2e202009-11-05 08:53:23 +00001934 if (obj->IsScript() && Script::cast(obj)->HasValidSource()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001935 script_cache_->Add(Handle<Script>(Script::cast(obj)));
1936 count++;
1937 }
1938 }
1939}
1940
1941
1942void Debug::DestroyScriptCache() {
1943 // Get rid of the script cache if it was created.
1944 if (script_cache_ != NULL) {
1945 delete script_cache_;
1946 script_cache_ = NULL;
1947 }
1948}
1949
1950
1951void Debug::AddScriptToScriptCache(Handle<Script> script) {
1952 if (script_cache_ != NULL) {
1953 script_cache_->Add(script);
1954 }
1955}
1956
1957
1958Handle<FixedArray> Debug::GetLoadedScripts() {
Steve Block44f0eee2011-05-26 01:26:41 +01001959 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00001960 // Create and fill the script cache when the loaded scripts is requested for
1961 // the first time.
1962 if (script_cache_ == NULL) {
1963 CreateScriptCache();
1964 }
1965
1966 // If the script cache is not active just return an empty array.
1967 ASSERT(script_cache_ != NULL);
1968 if (script_cache_ == NULL) {
Steve Block44f0eee2011-05-26 01:26:41 +01001969 isolate_->factory()->NewFixedArray(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001970 }
1971
1972 // Perform GC to get unreferenced scripts evicted from the cache before
1973 // returning the content.
Steve Block44f0eee2011-05-26 01:26:41 +01001974 isolate_->heap()->CollectAllGarbage(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00001975
1976 // Get the scripts from the cache.
1977 return script_cache_->GetScripts();
1978}
1979
1980
1981void Debug::AfterGarbageCollection() {
1982 // Generate events for collected scripts.
1983 if (script_cache_ != NULL) {
1984 script_cache_->ProcessCollectedScripts();
1985 }
1986}
1987
1988
Steve Block44f0eee2011-05-26 01:26:41 +01001989Debugger::Debugger()
1990 : debugger_access_(OS::CreateMutex()),
1991 event_listener_(Handle<Object>()),
1992 event_listener_data_(Handle<Object>()),
1993 compiling_natives_(false),
1994 is_loading_debugger_(false),
1995 never_unload_debugger_(false),
1996 message_handler_(NULL),
1997 debugger_unload_pending_(false),
1998 host_dispatch_handler_(NULL),
1999 dispatch_handler_access_(OS::CreateMutex()),
2000 debug_message_dispatch_handler_(NULL),
2001 message_dispatch_helper_thread_(NULL),
2002 host_dispatch_micros_(100 * 1000),
2003 agent_(NULL),
2004 command_queue_(kQueueInitialSize),
2005 command_received_(OS::CreateSemaphore(0)),
2006 event_command_queue_(kQueueInitialSize) {
2007}
2008
2009
2010Debugger::~Debugger() {
2011 delete debugger_access_;
2012 debugger_access_ = 0;
2013 delete dispatch_handler_access_;
2014 dispatch_handler_access_ = 0;
2015 delete command_received_;
2016 command_received_ = 0;
2017}
Steve Blocka7e24c12009-10-30 11:49:00 +00002018
2019
2020Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
2021 int argc, Object*** argv,
2022 bool* caught_exception) {
Steve Block44f0eee2011-05-26 01:26:41 +01002023 ASSERT(Isolate::Current() == isolate_);
2024 ASSERT(isolate_->context() == *isolate_->debug()->debug_context());
Steve Blocka7e24c12009-10-30 11:49:00 +00002025
2026 // Create the execution state object.
Steve Block44f0eee2011-05-26 01:26:41 +01002027 Handle<String> constructor_str =
2028 isolate_->factory()->LookupSymbol(constructor_name);
2029 Handle<Object> constructor(
2030 isolate_->global()->GetPropertyNoExceptionThrown(*constructor_str));
Steve Blocka7e24c12009-10-30 11:49:00 +00002031 ASSERT(constructor->IsJSFunction());
2032 if (!constructor->IsJSFunction()) {
2033 *caught_exception = true;
Steve Block44f0eee2011-05-26 01:26:41 +01002034 return isolate_->factory()->undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002035 }
2036 Handle<Object> js_object = Execution::TryCall(
2037 Handle<JSFunction>::cast(constructor),
Steve Block44f0eee2011-05-26 01:26:41 +01002038 Handle<JSObject>(isolate_->debug()->debug_context()->global()),
2039 argc, argv, caught_exception);
Steve Blocka7e24c12009-10-30 11:49:00 +00002040 return js_object;
2041}
2042
2043
2044Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
Steve Block44f0eee2011-05-26 01:26:41 +01002045 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002046 // Create the execution state object.
Steve Block44f0eee2011-05-26 01:26:41 +01002047 Handle<Object> break_id = isolate_->factory()->NewNumberFromInt(
2048 isolate_->debug()->break_id());
Steve Blocka7e24c12009-10-30 11:49:00 +00002049 const int argc = 1;
2050 Object** argv[argc] = { break_id.location() };
2051 return MakeJSObject(CStrVector("MakeExecutionState"),
2052 argc, argv, caught_exception);
2053}
2054
2055
2056Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
2057 Handle<Object> break_points_hit,
2058 bool* caught_exception) {
Steve Block44f0eee2011-05-26 01:26:41 +01002059 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002060 // Create the new break event object.
2061 const int argc = 2;
2062 Object** argv[argc] = { exec_state.location(),
2063 break_points_hit.location() };
2064 return MakeJSObject(CStrVector("MakeBreakEvent"),
2065 argc,
2066 argv,
2067 caught_exception);
2068}
2069
2070
2071Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
2072 Handle<Object> exception,
2073 bool uncaught,
2074 bool* caught_exception) {
Steve Block44f0eee2011-05-26 01:26:41 +01002075 ASSERT(Isolate::Current() == isolate_);
2076 Factory* factory = isolate_->factory();
Steve Blocka7e24c12009-10-30 11:49:00 +00002077 // Create the new exception event object.
2078 const int argc = 3;
2079 Object** argv[argc] = { exec_state.location(),
2080 exception.location(),
Steve Block44f0eee2011-05-26 01:26:41 +01002081 uncaught ? factory->true_value().location() :
2082 factory->false_value().location()};
Steve Blocka7e24c12009-10-30 11:49:00 +00002083 return MakeJSObject(CStrVector("MakeExceptionEvent"),
2084 argc, argv, caught_exception);
2085}
2086
2087
2088Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
2089 bool* caught_exception) {
Steve Block44f0eee2011-05-26 01:26:41 +01002090 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002091 // Create the new function event object.
2092 const int argc = 1;
2093 Object** argv[argc] = { function.location() };
2094 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
2095 argc, argv, caught_exception);
2096}
2097
2098
2099Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
2100 bool before,
2101 bool* caught_exception) {
Steve Block44f0eee2011-05-26 01:26:41 +01002102 ASSERT(Isolate::Current() == isolate_);
2103 Factory* factory = isolate_->factory();
Steve Blocka7e24c12009-10-30 11:49:00 +00002104 // Create the compile event object.
2105 Handle<Object> exec_state = MakeExecutionState(caught_exception);
2106 Handle<Object> script_wrapper = GetScriptWrapper(script);
2107 const int argc = 3;
2108 Object** argv[argc] = { exec_state.location(),
2109 script_wrapper.location(),
Steve Block44f0eee2011-05-26 01:26:41 +01002110 before ? factory->true_value().location() :
2111 factory->false_value().location() };
Steve Blocka7e24c12009-10-30 11:49:00 +00002112
2113 return MakeJSObject(CStrVector("MakeCompileEvent"),
2114 argc,
2115 argv,
2116 caught_exception);
2117}
2118
2119
2120Handle<Object> Debugger::MakeScriptCollectedEvent(int id,
2121 bool* caught_exception) {
Steve Block44f0eee2011-05-26 01:26:41 +01002122 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002123 // Create the script collected event object.
2124 Handle<Object> exec_state = MakeExecutionState(caught_exception);
2125 Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id));
2126 const int argc = 2;
2127 Object** argv[argc] = { exec_state.location(), id_object.location() };
2128
2129 return MakeJSObject(CStrVector("MakeScriptCollectedEvent"),
2130 argc,
2131 argv,
2132 caught_exception);
2133}
2134
2135
2136void Debugger::OnException(Handle<Object> exception, bool uncaught) {
Steve Block44f0eee2011-05-26 01:26:41 +01002137 ASSERT(Isolate::Current() == isolate_);
2138 HandleScope scope(isolate_);
2139 Debug* debug = isolate_->debug();
Steve Blocka7e24c12009-10-30 11:49:00 +00002140
2141 // Bail out based on state or if there is no listener for this event
Steve Block44f0eee2011-05-26 01:26:41 +01002142 if (debug->InDebugger()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002143 if (!Debugger::EventActive(v8::Exception)) return;
2144
2145 // Bail out if exception breaks are not active
2146 if (uncaught) {
2147 // Uncaught exceptions are reported by either flags.
Steve Block44f0eee2011-05-26 01:26:41 +01002148 if (!(debug->break_on_uncaught_exception() ||
2149 debug->break_on_exception())) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002150 } else {
2151 // Caught exceptions are reported is activated.
Steve Block44f0eee2011-05-26 01:26:41 +01002152 if (!debug->break_on_exception()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002153 }
2154
2155 // Enter the debugger.
2156 EnterDebugger debugger;
2157 if (debugger.FailedToEnter()) return;
2158
2159 // Clear all current stepping setup.
Steve Block44f0eee2011-05-26 01:26:41 +01002160 debug->ClearStepping();
Steve Blocka7e24c12009-10-30 11:49:00 +00002161 // Create the event data object.
2162 bool caught_exception = false;
2163 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2164 Handle<Object> event_data;
2165 if (!caught_exception) {
2166 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
2167 &caught_exception);
2168 }
2169 // Bail out and don't call debugger if exception.
2170 if (caught_exception) {
2171 return;
2172 }
2173
2174 // Process debug event.
2175 ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
2176 // Return to continue execution from where the exception was thrown.
2177}
2178
2179
2180void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
2181 bool auto_continue) {
Steve Block44f0eee2011-05-26 01:26:41 +01002182 ASSERT(Isolate::Current() == isolate_);
2183 HandleScope scope(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002184
2185 // Debugger has already been entered by caller.
Steve Block44f0eee2011-05-26 01:26:41 +01002186 ASSERT(isolate_->context() == *isolate_->debug()->debug_context());
Steve Blocka7e24c12009-10-30 11:49:00 +00002187
2188 // Bail out if there is no listener for this event
2189 if (!Debugger::EventActive(v8::Break)) return;
2190
2191 // Debugger must be entered in advance.
Steve Block44f0eee2011-05-26 01:26:41 +01002192 ASSERT(Isolate::Current()->context() == *isolate_->debug()->debug_context());
Steve Blocka7e24c12009-10-30 11:49:00 +00002193
2194 // Create the event data object.
2195 bool caught_exception = false;
2196 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2197 Handle<Object> event_data;
2198 if (!caught_exception) {
2199 event_data = MakeBreakEvent(exec_state, break_points_hit,
2200 &caught_exception);
2201 }
2202 // Bail out and don't call debugger if exception.
2203 if (caught_exception) {
2204 return;
2205 }
2206
2207 // Process debug event.
2208 ProcessDebugEvent(v8::Break,
2209 Handle<JSObject>::cast(event_data),
2210 auto_continue);
2211}
2212
2213
2214void Debugger::OnBeforeCompile(Handle<Script> script) {
Steve Block44f0eee2011-05-26 01:26:41 +01002215 ASSERT(Isolate::Current() == isolate_);
2216 HandleScope scope(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002217
2218 // Bail out based on state or if there is no listener for this event
Steve Block44f0eee2011-05-26 01:26:41 +01002219 if (isolate_->debug()->InDebugger()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002220 if (compiling_natives()) return;
2221 if (!EventActive(v8::BeforeCompile)) return;
2222
2223 // Enter the debugger.
2224 EnterDebugger debugger;
2225 if (debugger.FailedToEnter()) return;
2226
2227 // Create the event data object.
2228 bool caught_exception = false;
2229 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
2230 // Bail out and don't call debugger if exception.
2231 if (caught_exception) {
2232 return;
2233 }
2234
2235 // Process debug event.
2236 ProcessDebugEvent(v8::BeforeCompile,
2237 Handle<JSObject>::cast(event_data),
2238 true);
2239}
2240
2241
2242// Handle debugger actions when a new script is compiled.
Steve Block6ded16b2010-05-10 14:33:55 +01002243void Debugger::OnAfterCompile(Handle<Script> script,
2244 AfterCompileFlags after_compile_flags) {
Steve Block44f0eee2011-05-26 01:26:41 +01002245 ASSERT(Isolate::Current() == isolate_);
2246 HandleScope scope(isolate_);
2247 Debug* debug = isolate_->debug();
Steve Blocka7e24c12009-10-30 11:49:00 +00002248
2249 // Add the newly compiled script to the script cache.
Steve Block44f0eee2011-05-26 01:26:41 +01002250 debug->AddScriptToScriptCache(script);
Steve Blocka7e24c12009-10-30 11:49:00 +00002251
2252 // No more to do if not debugging.
2253 if (!IsDebuggerActive()) return;
2254
2255 // No compile events while compiling natives.
2256 if (compiling_natives()) return;
2257
2258 // Store whether in debugger before entering debugger.
Steve Block44f0eee2011-05-26 01:26:41 +01002259 bool in_debugger = debug->InDebugger();
Steve Blocka7e24c12009-10-30 11:49:00 +00002260
2261 // Enter the debugger.
2262 EnterDebugger debugger;
2263 if (debugger.FailedToEnter()) return;
2264
2265 // If debugging there might be script break points registered for this
2266 // script. Make sure that these break points are set.
2267
Andrei Popescu31002712010-02-23 13:46:05 +00002268 // Get the function UpdateScriptBreakPoints (defined in debug-debugger.js).
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002269 Handle<String> update_script_break_points_symbol =
Steve Block44f0eee2011-05-26 01:26:41 +01002270 isolate_->factory()->LookupAsciiSymbol("UpdateScriptBreakPoints");
Steve Blocka7e24c12009-10-30 11:49:00 +00002271 Handle<Object> update_script_break_points =
Steve Block44f0eee2011-05-26 01:26:41 +01002272 Handle<Object>(debug->debug_context()->global()->
John Reck59135872010-11-02 12:39:01 -07002273 GetPropertyNoExceptionThrown(*update_script_break_points_symbol));
Steve Blocka7e24c12009-10-30 11:49:00 +00002274 if (!update_script_break_points->IsJSFunction()) {
2275 return;
2276 }
2277 ASSERT(update_script_break_points->IsJSFunction());
2278
2279 // Wrap the script object in a proper JS object before passing it
2280 // to JavaScript.
2281 Handle<JSValue> wrapper = GetScriptWrapper(script);
2282
2283 // Call UpdateScriptBreakPoints expect no exceptions.
2284 bool caught_exception = false;
2285 const int argc = 1;
2286 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
2287 Handle<Object> result = Execution::TryCall(
2288 Handle<JSFunction>::cast(update_script_break_points),
Steve Block44f0eee2011-05-26 01:26:41 +01002289 Isolate::Current()->js_builtins_object(), argc, argv,
Steve Blocka7e24c12009-10-30 11:49:00 +00002290 &caught_exception);
2291 if (caught_exception) {
2292 return;
2293 }
2294 // Bail out based on state or if there is no listener for this event
Steve Block6ded16b2010-05-10 14:33:55 +01002295 if (in_debugger && (after_compile_flags & SEND_WHEN_DEBUGGING) == 0) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002296 if (!Debugger::EventActive(v8::AfterCompile)) return;
2297
2298 // Create the compile state object.
2299 Handle<Object> event_data = MakeCompileEvent(script,
2300 false,
2301 &caught_exception);
2302 // Bail out and don't call debugger if exception.
2303 if (caught_exception) {
2304 return;
2305 }
2306 // Process debug event.
2307 ProcessDebugEvent(v8::AfterCompile,
2308 Handle<JSObject>::cast(event_data),
2309 true);
2310}
2311
2312
Steve Blocka7e24c12009-10-30 11:49:00 +00002313void Debugger::OnScriptCollected(int id) {
Steve Block44f0eee2011-05-26 01:26:41 +01002314 ASSERT(Isolate::Current() == isolate_);
2315 HandleScope scope(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002316
2317 // No more to do if not debugging.
2318 if (!IsDebuggerActive()) return;
2319 if (!Debugger::EventActive(v8::ScriptCollected)) return;
2320
2321 // Enter the debugger.
2322 EnterDebugger debugger;
2323 if (debugger.FailedToEnter()) return;
2324
2325 // Create the script collected state object.
2326 bool caught_exception = false;
2327 Handle<Object> event_data = MakeScriptCollectedEvent(id,
2328 &caught_exception);
2329 // Bail out and don't call debugger if exception.
2330 if (caught_exception) {
2331 return;
2332 }
2333
2334 // Process debug event.
2335 ProcessDebugEvent(v8::ScriptCollected,
2336 Handle<JSObject>::cast(event_data),
2337 true);
2338}
2339
2340
2341void Debugger::ProcessDebugEvent(v8::DebugEvent event,
2342 Handle<JSObject> event_data,
2343 bool auto_continue) {
Steve Block44f0eee2011-05-26 01:26:41 +01002344 ASSERT(Isolate::Current() == isolate_);
2345 HandleScope scope(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002346
2347 // Clear any pending debug break if this is a real break.
2348 if (!auto_continue) {
Steve Block44f0eee2011-05-26 01:26:41 +01002349 isolate_->debug()->clear_interrupt_pending(DEBUGBREAK);
Steve Blocka7e24c12009-10-30 11:49:00 +00002350 }
2351
2352 // Create the execution state.
2353 bool caught_exception = false;
2354 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2355 if (caught_exception) {
2356 return;
2357 }
2358 // First notify the message handler if any.
2359 if (message_handler_ != NULL) {
2360 NotifyMessageHandler(event,
2361 Handle<JSObject>::cast(exec_state),
2362 event_data,
2363 auto_continue);
2364 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002365 // Notify registered debug event listener. This can be either a C or
2366 // a JavaScript function. Don't call event listener for v8::Break
2367 // here, if it's only a debug command -- they will be processed later.
2368 if ((event != v8::Break || !auto_continue) && !event_listener_.is_null()) {
2369 CallEventCallback(event, exec_state, event_data, NULL);
2370 }
2371 // Process pending debug commands.
2372 if (event == v8::Break) {
2373 while (!event_command_queue_.IsEmpty()) {
2374 CommandMessage command = event_command_queue_.Get();
2375 if (!event_listener_.is_null()) {
2376 CallEventCallback(v8::BreakForCommand,
2377 exec_state,
2378 event_data,
2379 command.client_data());
2380 }
2381 command.Dispose();
Steve Blocka7e24c12009-10-30 11:49:00 +00002382 }
2383 }
2384}
2385
2386
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002387void Debugger::CallEventCallback(v8::DebugEvent event,
2388 Handle<Object> exec_state,
2389 Handle<Object> event_data,
2390 v8::Debug::ClientData* client_data) {
2391 if (event_listener_->IsProxy()) {
2392 CallCEventCallback(event, exec_state, event_data, client_data);
2393 } else {
2394 CallJSEventCallback(event, exec_state, event_data);
2395 }
2396}
2397
2398
2399void Debugger::CallCEventCallback(v8::DebugEvent event,
2400 Handle<Object> exec_state,
2401 Handle<Object> event_data,
2402 v8::Debug::ClientData* client_data) {
2403 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
2404 v8::Debug::EventCallback2 callback =
2405 FUNCTION_CAST<v8::Debug::EventCallback2>(callback_obj->proxy());
2406 EventDetailsImpl event_details(
2407 event,
2408 Handle<JSObject>::cast(exec_state),
2409 Handle<JSObject>::cast(event_data),
2410 event_listener_data_,
2411 client_data);
2412 callback(event_details);
2413}
2414
2415
2416void Debugger::CallJSEventCallback(v8::DebugEvent event,
2417 Handle<Object> exec_state,
2418 Handle<Object> event_data) {
2419 ASSERT(event_listener_->IsJSFunction());
Steve Block44f0eee2011-05-26 01:26:41 +01002420 ASSERT(Isolate::Current() == isolate_);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002421 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
2422
2423 // Invoke the JavaScript debug event listener.
2424 const int argc = 4;
2425 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
2426 exec_state.location(),
2427 Handle<Object>::cast(event_data).location(),
2428 event_listener_data_.location() };
2429 bool caught_exception = false;
Steve Block44f0eee2011-05-26 01:26:41 +01002430 Execution::TryCall(fun, isolate_->global(), argc, argv, &caught_exception);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002431 // Silently ignore exceptions from debug event listeners.
2432}
2433
2434
Steve Block6ded16b2010-05-10 14:33:55 +01002435Handle<Context> Debugger::GetDebugContext() {
Steve Block44f0eee2011-05-26 01:26:41 +01002436 ASSERT(Isolate::Current() == isolate_);
2437 never_unload_debugger_ = true;
2438 EnterDebugger debugger;
2439 return isolate_->debug()->debug_context();
Steve Block6ded16b2010-05-10 14:33:55 +01002440}
2441
2442
Steve Blocka7e24c12009-10-30 11:49:00 +00002443void Debugger::UnloadDebugger() {
Steve Block44f0eee2011-05-26 01:26:41 +01002444 ASSERT(Isolate::Current() == isolate_);
2445 Debug* debug = isolate_->debug();
2446
Steve Blocka7e24c12009-10-30 11:49:00 +00002447 // Make sure that there are no breakpoints left.
Steve Block44f0eee2011-05-26 01:26:41 +01002448 debug->ClearAllBreakPoints();
Steve Blocka7e24c12009-10-30 11:49:00 +00002449
2450 // Unload the debugger if feasible.
2451 if (!never_unload_debugger_) {
Steve Block44f0eee2011-05-26 01:26:41 +01002452 debug->Unload();
Steve Blocka7e24c12009-10-30 11:49:00 +00002453 }
2454
2455 // Clear the flag indicating that the debugger should be unloaded.
2456 debugger_unload_pending_ = false;
2457}
2458
2459
2460void Debugger::NotifyMessageHandler(v8::DebugEvent event,
2461 Handle<JSObject> exec_state,
2462 Handle<JSObject> event_data,
2463 bool auto_continue) {
Steve Block44f0eee2011-05-26 01:26:41 +01002464 ASSERT(Isolate::Current() == isolate_);
2465 HandleScope scope(isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002466
Steve Block44f0eee2011-05-26 01:26:41 +01002467 if (!isolate_->debug()->Load()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002468
2469 // Process the individual events.
2470 bool sendEventMessage = false;
2471 switch (event) {
2472 case v8::Break:
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002473 case v8::BreakForCommand:
Steve Blocka7e24c12009-10-30 11:49:00 +00002474 sendEventMessage = !auto_continue;
2475 break;
2476 case v8::Exception:
2477 sendEventMessage = true;
2478 break;
2479 case v8::BeforeCompile:
2480 break;
2481 case v8::AfterCompile:
2482 sendEventMessage = true;
2483 break;
2484 case v8::ScriptCollected:
2485 sendEventMessage = true;
2486 break;
2487 case v8::NewFunction:
2488 break;
2489 default:
2490 UNREACHABLE();
2491 }
2492
2493 // The debug command interrupt flag might have been set when the command was
2494 // added. It should be enough to clear the flag only once while we are in the
2495 // debugger.
Steve Block44f0eee2011-05-26 01:26:41 +01002496 ASSERT(isolate_->debug()->InDebugger());
2497 isolate_->stack_guard()->Continue(DEBUGCOMMAND);
Steve Blocka7e24c12009-10-30 11:49:00 +00002498
2499 // Notify the debugger that a debug event has occurred unless auto continue is
2500 // active in which case no event is send.
2501 if (sendEventMessage) {
2502 MessageImpl message = MessageImpl::NewEvent(
2503 event,
2504 auto_continue,
2505 Handle<JSObject>::cast(exec_state),
2506 Handle<JSObject>::cast(event_data));
2507 InvokeMessageHandler(message);
2508 }
2509
2510 // If auto continue don't make the event cause a break, but process messages
2511 // in the queue if any. For script collected events don't even process
2512 // messages in the queue as the execution state might not be what is expected
2513 // by the client.
2514 if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) {
2515 return;
2516 }
2517
Steve Blocka7e24c12009-10-30 11:49:00 +00002518 v8::TryCatch try_catch;
Steve Block3ce2e202009-11-05 08:53:23 +00002519
2520 // DebugCommandProcessor goes here.
2521 v8::Local<v8::Object> cmd_processor;
2522 {
2523 v8::Local<v8::Object> api_exec_state =
2524 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
2525 v8::Local<v8::String> fun_name =
2526 v8::String::New("debugCommandProcessor");
2527 v8::Local<v8::Function> fun =
2528 v8::Function::Cast(*api_exec_state->Get(fun_name));
2529
2530 v8::Handle<v8::Boolean> running =
2531 auto_continue ? v8::True() : v8::False();
2532 static const int kArgc = 1;
2533 v8::Handle<Value> argv[kArgc] = { running };
2534 cmd_processor = v8::Object::Cast(*fun->Call(api_exec_state, kArgc, argv));
2535 if (try_catch.HasCaught()) {
2536 PrintLn(try_catch.Exception());
2537 return;
2538 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002539 }
2540
Steve Block3ce2e202009-11-05 08:53:23 +00002541 bool running = auto_continue;
2542
Steve Blocka7e24c12009-10-30 11:49:00 +00002543 // Process requests from the debugger.
2544 while (true) {
2545 // Wait for new command in the queue.
2546 if (Debugger::host_dispatch_handler_) {
2547 // In case there is a host dispatch - do periodic dispatches.
2548 if (!command_received_->Wait(host_dispatch_micros_)) {
2549 // Timout expired, do the dispatch.
2550 Debugger::host_dispatch_handler_();
2551 continue;
2552 }
2553 } else {
2554 // In case there is no host dispatch - just wait.
2555 command_received_->Wait();
2556 }
2557
2558 // Get the command from the queue.
2559 CommandMessage command = command_queue_.Get();
Steve Block44f0eee2011-05-26 01:26:41 +01002560 LOGGER->DebugTag("Got request from command queue, in interactive loop.");
Steve Blocka7e24c12009-10-30 11:49:00 +00002561 if (!Debugger::IsDebuggerActive()) {
2562 // Delete command text and user data.
2563 command.Dispose();
2564 return;
2565 }
2566
2567 // Invoke JavaScript to process the debug request.
2568 v8::Local<v8::String> fun_name;
2569 v8::Local<v8::Function> fun;
2570 v8::Local<v8::Value> request;
2571 v8::TryCatch try_catch;
2572 fun_name = v8::String::New("processDebugRequest");
2573 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2574
2575 request = v8::String::New(command.text().start(),
2576 command.text().length());
2577 static const int kArgc = 1;
2578 v8::Handle<Value> argv[kArgc] = { request };
2579 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
2580
2581 // Get the response.
2582 v8::Local<v8::String> response;
Steve Blocka7e24c12009-10-30 11:49:00 +00002583 if (!try_catch.HasCaught()) {
2584 // Get response string.
2585 if (!response_val->IsUndefined()) {
2586 response = v8::String::Cast(*response_val);
2587 } else {
2588 response = v8::String::New("");
2589 }
2590
2591 // Log the JSON request/response.
2592 if (FLAG_trace_debug_json) {
2593 PrintLn(request);
2594 PrintLn(response);
2595 }
2596
2597 // Get the running state.
2598 fun_name = v8::String::New("isRunning");
2599 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2600 static const int kArgc = 1;
2601 v8::Handle<Value> argv[kArgc] = { response };
2602 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
2603 if (!try_catch.HasCaught()) {
2604 running = running_val->ToBoolean()->Value();
2605 }
2606 } else {
2607 // In case of failure the result text is the exception text.
2608 response = try_catch.Exception()->ToString();
2609 }
2610
2611 // Return the result.
2612 MessageImpl message = MessageImpl::NewResponse(
2613 event,
2614 running,
2615 Handle<JSObject>::cast(exec_state),
2616 Handle<JSObject>::cast(event_data),
2617 Handle<String>(Utils::OpenHandle(*response)),
2618 command.client_data());
2619 InvokeMessageHandler(message);
2620 command.Dispose();
2621
2622 // Return from debug event processing if either the VM is put into the
2623 // runnning state (through a continue command) or auto continue is active
2624 // and there are no more commands queued.
Steve Block3ce2e202009-11-05 08:53:23 +00002625 if (running && !HasCommands()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002626 return;
2627 }
2628 }
2629}
2630
2631
2632void Debugger::SetEventListener(Handle<Object> callback,
2633 Handle<Object> data) {
Steve Block44f0eee2011-05-26 01:26:41 +01002634 ASSERT(Isolate::Current() == isolate_);
2635 HandleScope scope(isolate_);
2636 GlobalHandles* global_handles = isolate_->global_handles();
Steve Blocka7e24c12009-10-30 11:49:00 +00002637
2638 // Clear the global handles for the event listener and the event listener data
2639 // object.
2640 if (!event_listener_.is_null()) {
Steve Block44f0eee2011-05-26 01:26:41 +01002641 global_handles->Destroy(
Steve Blocka7e24c12009-10-30 11:49:00 +00002642 reinterpret_cast<Object**>(event_listener_.location()));
2643 event_listener_ = Handle<Object>();
2644 }
2645 if (!event_listener_data_.is_null()) {
Steve Block44f0eee2011-05-26 01:26:41 +01002646 global_handles->Destroy(
Steve Blocka7e24c12009-10-30 11:49:00 +00002647 reinterpret_cast<Object**>(event_listener_data_.location()));
2648 event_listener_data_ = Handle<Object>();
2649 }
2650
2651 // If there is a new debug event listener register it together with its data
2652 // object.
2653 if (!callback->IsUndefined() && !callback->IsNull()) {
Steve Block44f0eee2011-05-26 01:26:41 +01002654 event_listener_ = Handle<Object>::cast(
2655 global_handles->Create(*callback));
Steve Blocka7e24c12009-10-30 11:49:00 +00002656 if (data.is_null()) {
Steve Block44f0eee2011-05-26 01:26:41 +01002657 data = isolate_->factory()->undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002658 }
Steve Block44f0eee2011-05-26 01:26:41 +01002659 event_listener_data_ = Handle<Object>::cast(
2660 global_handles->Create(*data));
Steve Blocka7e24c12009-10-30 11:49:00 +00002661 }
2662
2663 ListenersChanged();
2664}
2665
2666
2667void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) {
Steve Block44f0eee2011-05-26 01:26:41 +01002668 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002669 ScopedLock with(debugger_access_);
2670
2671 message_handler_ = handler;
2672 ListenersChanged();
2673 if (handler == NULL) {
2674 // Send an empty command to the debugger if in a break to make JavaScript
2675 // run again if the debugger is closed.
Steve Block44f0eee2011-05-26 01:26:41 +01002676 if (isolate_->debug()->InDebugger()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002677 ProcessCommand(Vector<const uint16_t>::empty());
2678 }
2679 }
2680}
2681
2682
2683void Debugger::ListenersChanged() {
Steve Block44f0eee2011-05-26 01:26:41 +01002684 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002685 if (IsDebuggerActive()) {
2686 // Disable the compilation cache when the debugger is active.
Steve Block44f0eee2011-05-26 01:26:41 +01002687 isolate_->compilation_cache()->Disable();
Leon Clarkee46be812010-01-19 14:06:41 +00002688 debugger_unload_pending_ = false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002689 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01002690 isolate_->compilation_cache()->Enable();
Steve Blocka7e24c12009-10-30 11:49:00 +00002691 // Unload the debugger if event listener and message handler cleared.
Leon Clarkee46be812010-01-19 14:06:41 +00002692 // Schedule this for later, because we may be in non-V8 thread.
2693 debugger_unload_pending_ = true;
Steve Blocka7e24c12009-10-30 11:49:00 +00002694 }
2695}
2696
2697
2698void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
2699 int period) {
Steve Block44f0eee2011-05-26 01:26:41 +01002700 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002701 host_dispatch_handler_ = handler;
2702 host_dispatch_micros_ = period * 1000;
2703}
2704
2705
Steve Blockd0582a62009-12-15 09:54:21 +00002706void Debugger::SetDebugMessageDispatchHandler(
Leon Clarkee46be812010-01-19 14:06:41 +00002707 v8::Debug::DebugMessageDispatchHandler handler, bool provide_locker) {
Steve Block44f0eee2011-05-26 01:26:41 +01002708 ASSERT(Isolate::Current() == isolate_);
Leon Clarkee46be812010-01-19 14:06:41 +00002709 ScopedLock with(dispatch_handler_access_);
Steve Blockd0582a62009-12-15 09:54:21 +00002710 debug_message_dispatch_handler_ = handler;
Leon Clarkee46be812010-01-19 14:06:41 +00002711
2712 if (provide_locker && message_dispatch_helper_thread_ == NULL) {
Steve Block44f0eee2011-05-26 01:26:41 +01002713 message_dispatch_helper_thread_ = new MessageDispatchHelperThread(isolate_);
Leon Clarkee46be812010-01-19 14:06:41 +00002714 message_dispatch_helper_thread_->Start();
2715 }
Steve Blockd0582a62009-12-15 09:54:21 +00002716}
2717
2718
Steve Blocka7e24c12009-10-30 11:49:00 +00002719// Calls the registered debug message handler. This callback is part of the
2720// public API.
2721void Debugger::InvokeMessageHandler(MessageImpl message) {
Steve Block44f0eee2011-05-26 01:26:41 +01002722 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002723 ScopedLock with(debugger_access_);
2724
2725 if (message_handler_ != NULL) {
2726 message_handler_(message);
2727 }
2728}
2729
2730
2731// Puts a command coming from the public API on the queue. Creates
2732// a copy of the command string managed by the debugger. Up to this
2733// point, the command data was managed by the API client. Called
2734// by the API client thread.
2735void Debugger::ProcessCommand(Vector<const uint16_t> command,
2736 v8::Debug::ClientData* client_data) {
Steve Block44f0eee2011-05-26 01:26:41 +01002737 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002738 // Need to cast away const.
2739 CommandMessage message = CommandMessage::New(
2740 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
2741 command.length()),
2742 client_data);
Steve Block44f0eee2011-05-26 01:26:41 +01002743 LOGGER->DebugTag("Put command on command_queue.");
Steve Blocka7e24c12009-10-30 11:49:00 +00002744 command_queue_.Put(message);
2745 command_received_->Signal();
2746
2747 // Set the debug command break flag to have the command processed.
Steve Block44f0eee2011-05-26 01:26:41 +01002748 if (!isolate_->debug()->InDebugger()) {
2749 isolate_->stack_guard()->DebugCommand();
Steve Blocka7e24c12009-10-30 11:49:00 +00002750 }
Steve Blockd0582a62009-12-15 09:54:21 +00002751
Leon Clarkee46be812010-01-19 14:06:41 +00002752 MessageDispatchHelperThread* dispatch_thread;
2753 {
2754 ScopedLock with(dispatch_handler_access_);
2755 dispatch_thread = message_dispatch_helper_thread_;
2756 }
2757
2758 if (dispatch_thread == NULL) {
2759 CallMessageDispatchHandler();
2760 } else {
2761 dispatch_thread->Schedule();
Steve Blockd0582a62009-12-15 09:54:21 +00002762 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002763}
2764
2765
2766bool Debugger::HasCommands() {
Steve Block44f0eee2011-05-26 01:26:41 +01002767 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002768 return !command_queue_.IsEmpty();
2769}
2770
2771
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002772void Debugger::EnqueueDebugCommand(v8::Debug::ClientData* client_data) {
Steve Block44f0eee2011-05-26 01:26:41 +01002773 ASSERT(Isolate::Current() == isolate_);
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002774 CommandMessage message = CommandMessage::New(Vector<uint16_t>(), client_data);
2775 event_command_queue_.Put(message);
2776
2777 // Set the debug command break flag to have the command processed.
Steve Block44f0eee2011-05-26 01:26:41 +01002778 if (!isolate_->debug()->InDebugger()) {
2779 isolate_->stack_guard()->DebugCommand();
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002780 }
2781}
2782
2783
Steve Blocka7e24c12009-10-30 11:49:00 +00002784bool Debugger::IsDebuggerActive() {
Steve Block44f0eee2011-05-26 01:26:41 +01002785 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002786 ScopedLock with(debugger_access_);
2787
2788 return message_handler_ != NULL || !event_listener_.is_null();
2789}
2790
2791
2792Handle<Object> Debugger::Call(Handle<JSFunction> fun,
2793 Handle<Object> data,
2794 bool* pending_exception) {
Steve Block44f0eee2011-05-26 01:26:41 +01002795 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002796 // When calling functions in the debugger prevent it from beeing unloaded.
2797 Debugger::never_unload_debugger_ = true;
2798
2799 // Enter the debugger.
2800 EnterDebugger debugger;
Steve Block6ded16b2010-05-10 14:33:55 +01002801 if (debugger.FailedToEnter()) {
Steve Block44f0eee2011-05-26 01:26:41 +01002802 return isolate_->factory()->undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002803 }
2804
2805 // Create the execution state.
2806 bool caught_exception = false;
2807 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2808 if (caught_exception) {
Steve Block44f0eee2011-05-26 01:26:41 +01002809 return isolate_->factory()->undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002810 }
2811
2812 static const int kArgc = 2;
2813 Object** argv[kArgc] = { exec_state.location(), data.location() };
Steve Block6ded16b2010-05-10 14:33:55 +01002814 Handle<Object> result = Execution::Call(
2815 fun,
Steve Block44f0eee2011-05-26 01:26:41 +01002816 Handle<Object>(isolate_->debug()->debug_context_->global_proxy()),
Steve Block6ded16b2010-05-10 14:33:55 +01002817 kArgc,
2818 argv,
2819 pending_exception);
Steve Blocka7e24c12009-10-30 11:49:00 +00002820 return result;
2821}
2822
2823
Leon Clarkee46be812010-01-19 14:06:41 +00002824static void StubMessageHandler2(const v8::Debug::Message& message) {
2825 // Simply ignore message.
2826}
2827
2828
2829bool Debugger::StartAgent(const char* name, int port,
2830 bool wait_for_connection) {
Steve Block44f0eee2011-05-26 01:26:41 +01002831 ASSERT(Isolate::Current() == isolate_);
Leon Clarkee46be812010-01-19 14:06:41 +00002832 if (wait_for_connection) {
2833 // Suspend V8 if it is already running or set V8 to suspend whenever
2834 // it starts.
2835 // Provide stub message handler; V8 auto-continues each suspend
2836 // when there is no message handler; we doesn't need it.
2837 // Once become suspended, V8 will stay so indefinitely long, until remote
2838 // debugger connects and issues "continue" command.
2839 Debugger::message_handler_ = StubMessageHandler2;
2840 v8::Debug::DebugBreak();
2841 }
2842
Steve Blocka7e24c12009-10-30 11:49:00 +00002843 if (Socket::Setup()) {
Ben Murdoch086aeea2011-05-13 15:57:08 +01002844 if (agent_ == NULL) {
Steve Block44f0eee2011-05-26 01:26:41 +01002845 agent_ = new DebuggerAgent(isolate_, name, port);
Ben Murdoch086aeea2011-05-13 15:57:08 +01002846 agent_->Start();
2847 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002848 return true;
2849 }
2850
2851 return false;
2852}
2853
2854
2855void Debugger::StopAgent() {
Steve Block44f0eee2011-05-26 01:26:41 +01002856 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002857 if (agent_ != NULL) {
2858 agent_->Shutdown();
2859 agent_->Join();
2860 delete agent_;
2861 agent_ = NULL;
2862 }
2863}
2864
2865
2866void Debugger::WaitForAgent() {
Steve Block44f0eee2011-05-26 01:26:41 +01002867 ASSERT(Isolate::Current() == isolate_);
Steve Blocka7e24c12009-10-30 11:49:00 +00002868 if (agent_ != NULL)
2869 agent_->WaitUntilListening();
2870}
2871
Leon Clarkee46be812010-01-19 14:06:41 +00002872
2873void Debugger::CallMessageDispatchHandler() {
Steve Block44f0eee2011-05-26 01:26:41 +01002874 ASSERT(Isolate::Current() == isolate_);
Leon Clarkee46be812010-01-19 14:06:41 +00002875 v8::Debug::DebugMessageDispatchHandler handler;
2876 {
2877 ScopedLock with(dispatch_handler_access_);
2878 handler = Debugger::debug_message_dispatch_handler_;
2879 }
2880 if (handler != NULL) {
2881 handler();
2882 }
2883}
2884
2885
Steve Blocka7e24c12009-10-30 11:49:00 +00002886MessageImpl MessageImpl::NewEvent(DebugEvent event,
2887 bool running,
2888 Handle<JSObject> exec_state,
2889 Handle<JSObject> event_data) {
2890 MessageImpl message(true, event, running,
2891 exec_state, event_data, Handle<String>(), NULL);
2892 return message;
2893}
2894
2895
2896MessageImpl MessageImpl::NewResponse(DebugEvent event,
2897 bool running,
2898 Handle<JSObject> exec_state,
2899 Handle<JSObject> event_data,
2900 Handle<String> response_json,
2901 v8::Debug::ClientData* client_data) {
2902 MessageImpl message(false, event, running,
2903 exec_state, event_data, response_json, client_data);
2904 return message;
2905}
2906
2907
2908MessageImpl::MessageImpl(bool is_event,
2909 DebugEvent event,
2910 bool running,
2911 Handle<JSObject> exec_state,
2912 Handle<JSObject> event_data,
2913 Handle<String> response_json,
2914 v8::Debug::ClientData* client_data)
2915 : is_event_(is_event),
2916 event_(event),
2917 running_(running),
2918 exec_state_(exec_state),
2919 event_data_(event_data),
2920 response_json_(response_json),
2921 client_data_(client_data) {}
2922
2923
2924bool MessageImpl::IsEvent() const {
2925 return is_event_;
2926}
2927
2928
2929bool MessageImpl::IsResponse() const {
2930 return !is_event_;
2931}
2932
2933
2934DebugEvent MessageImpl::GetEvent() const {
2935 return event_;
2936}
2937
2938
2939bool MessageImpl::WillStartRunning() const {
2940 return running_;
2941}
2942
2943
2944v8::Handle<v8::Object> MessageImpl::GetExecutionState() const {
2945 return v8::Utils::ToLocal(exec_state_);
2946}
2947
2948
2949v8::Handle<v8::Object> MessageImpl::GetEventData() const {
2950 return v8::Utils::ToLocal(event_data_);
2951}
2952
2953
2954v8::Handle<v8::String> MessageImpl::GetJSON() const {
2955 v8::HandleScope scope;
2956
2957 if (IsEvent()) {
2958 // Call toJSONProtocol on the debug event object.
2959 Handle<Object> fun = GetProperty(event_data_, "toJSONProtocol");
2960 if (!fun->IsJSFunction()) {
2961 return v8::Handle<v8::String>();
2962 }
2963 bool caught_exception;
2964 Handle<Object> json = Execution::TryCall(Handle<JSFunction>::cast(fun),
2965 event_data_,
2966 0, NULL, &caught_exception);
2967 if (caught_exception || !json->IsString()) {
2968 return v8::Handle<v8::String>();
2969 }
2970 return scope.Close(v8::Utils::ToLocal(Handle<String>::cast(json)));
2971 } else {
2972 return v8::Utils::ToLocal(response_json_);
2973 }
2974}
2975
2976
2977v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
Steve Block44f0eee2011-05-26 01:26:41 +01002978 Isolate* isolate = Isolate::Current();
2979 v8::Handle<v8::Context> context = GetDebugEventContext(isolate);
2980 // Isolate::context() may be NULL when "script collected" event occures.
Leon Clarkef7060e22010-06-03 12:02:55 +01002981 ASSERT(!context.IsEmpty() || event_ == v8::ScriptCollected);
Steve Block44f0eee2011-05-26 01:26:41 +01002982 return GetDebugEventContext(isolate);
Steve Blocka7e24c12009-10-30 11:49:00 +00002983}
2984
2985
2986v8::Debug::ClientData* MessageImpl::GetClientData() const {
2987 return client_data_;
2988}
2989
2990
Leon Clarkef7060e22010-06-03 12:02:55 +01002991EventDetailsImpl::EventDetailsImpl(DebugEvent event,
2992 Handle<JSObject> exec_state,
2993 Handle<JSObject> event_data,
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002994 Handle<Object> callback_data,
2995 v8::Debug::ClientData* client_data)
Leon Clarkef7060e22010-06-03 12:02:55 +01002996 : event_(event),
2997 exec_state_(exec_state),
2998 event_data_(event_data),
Ben Murdoch3bec4d22010-07-22 14:51:16 +01002999 callback_data_(callback_data),
3000 client_data_(client_data) {}
Leon Clarkef7060e22010-06-03 12:02:55 +01003001
3002
3003DebugEvent EventDetailsImpl::GetEvent() const {
3004 return event_;
3005}
3006
3007
3008v8::Handle<v8::Object> EventDetailsImpl::GetExecutionState() const {
3009 return v8::Utils::ToLocal(exec_state_);
3010}
3011
3012
3013v8::Handle<v8::Object> EventDetailsImpl::GetEventData() const {
3014 return v8::Utils::ToLocal(event_data_);
3015}
3016
3017
3018v8::Handle<v8::Context> EventDetailsImpl::GetEventContext() const {
Steve Block44f0eee2011-05-26 01:26:41 +01003019 return GetDebugEventContext(Isolate::Current());
Leon Clarkef7060e22010-06-03 12:02:55 +01003020}
3021
3022
3023v8::Handle<v8::Value> EventDetailsImpl::GetCallbackData() const {
3024 return v8::Utils::ToLocal(callback_data_);
3025}
3026
3027
Ben Murdoch3bec4d22010-07-22 14:51:16 +01003028v8::Debug::ClientData* EventDetailsImpl::GetClientData() const {
3029 return client_data_;
3030}
3031
3032
Steve Blocka7e24c12009-10-30 11:49:00 +00003033CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
3034 client_data_(NULL) {
3035}
3036
3037
3038CommandMessage::CommandMessage(const Vector<uint16_t>& text,
3039 v8::Debug::ClientData* data)
3040 : text_(text),
3041 client_data_(data) {
3042}
3043
3044
3045CommandMessage::~CommandMessage() {
3046}
3047
3048
3049void CommandMessage::Dispose() {
3050 text_.Dispose();
3051 delete client_data_;
3052 client_data_ = NULL;
3053}
3054
3055
3056CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
3057 v8::Debug::ClientData* data) {
3058 return CommandMessage(command.Clone(), data);
3059}
3060
3061
3062CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
3063 size_(size) {
3064 messages_ = NewArray<CommandMessage>(size);
3065}
3066
3067
3068CommandMessageQueue::~CommandMessageQueue() {
3069 while (!IsEmpty()) {
3070 CommandMessage m = Get();
3071 m.Dispose();
3072 }
3073 DeleteArray(messages_);
3074}
3075
3076
3077CommandMessage CommandMessageQueue::Get() {
3078 ASSERT(!IsEmpty());
3079 int result = start_;
3080 start_ = (start_ + 1) % size_;
3081 return messages_[result];
3082}
3083
3084
3085void CommandMessageQueue::Put(const CommandMessage& message) {
3086 if ((end_ + 1) % size_ == start_) {
3087 Expand();
3088 }
3089 messages_[end_] = message;
3090 end_ = (end_ + 1) % size_;
3091}
3092
3093
3094void CommandMessageQueue::Expand() {
3095 CommandMessageQueue new_queue(size_ * 2);
3096 while (!IsEmpty()) {
3097 new_queue.Put(Get());
3098 }
3099 CommandMessage* array_to_free = messages_;
3100 *this = new_queue;
3101 new_queue.messages_ = array_to_free;
3102 // Make the new_queue empty so that it doesn't call Dispose on any messages.
3103 new_queue.start_ = new_queue.end_;
3104 // Automatic destructor called on new_queue, freeing array_to_free.
3105}
3106
3107
3108LockingCommandMessageQueue::LockingCommandMessageQueue(int size)
3109 : queue_(size) {
3110 lock_ = OS::CreateMutex();
3111}
3112
3113
3114LockingCommandMessageQueue::~LockingCommandMessageQueue() {
3115 delete lock_;
3116}
3117
3118
3119bool LockingCommandMessageQueue::IsEmpty() const {
3120 ScopedLock sl(lock_);
3121 return queue_.IsEmpty();
3122}
3123
3124
3125CommandMessage LockingCommandMessageQueue::Get() {
3126 ScopedLock sl(lock_);
3127 CommandMessage result = queue_.Get();
Steve Block44f0eee2011-05-26 01:26:41 +01003128 LOGGER->DebugEvent("Get", result.text());
Steve Blocka7e24c12009-10-30 11:49:00 +00003129 return result;
3130}
3131
3132
3133void LockingCommandMessageQueue::Put(const CommandMessage& message) {
3134 ScopedLock sl(lock_);
3135 queue_.Put(message);
Steve Block44f0eee2011-05-26 01:26:41 +01003136 LOGGER->DebugEvent("Put", message.text());
Steve Blocka7e24c12009-10-30 11:49:00 +00003137}
3138
3139
3140void LockingCommandMessageQueue::Clear() {
3141 ScopedLock sl(lock_);
3142 queue_.Clear();
3143}
3144
Leon Clarkee46be812010-01-19 14:06:41 +00003145
Steve Block44f0eee2011-05-26 01:26:41 +01003146MessageDispatchHelperThread::MessageDispatchHelperThread(Isolate* isolate)
3147 : Thread(isolate, "v8:MsgDispHelpr"),
Steve Block9fac8402011-05-12 15:51:54 +01003148 sem_(OS::CreateSemaphore(0)), mutex_(OS::CreateMutex()),
Leon Clarkee46be812010-01-19 14:06:41 +00003149 already_signalled_(false) {
3150}
3151
3152
3153MessageDispatchHelperThread::~MessageDispatchHelperThread() {
3154 delete mutex_;
3155 delete sem_;
3156}
3157
3158
3159void MessageDispatchHelperThread::Schedule() {
3160 {
3161 ScopedLock lock(mutex_);
3162 if (already_signalled_) {
3163 return;
3164 }
3165 already_signalled_ = true;
3166 }
3167 sem_->Signal();
3168}
3169
3170
3171void MessageDispatchHelperThread::Run() {
3172 while (true) {
3173 sem_->Wait();
3174 {
3175 ScopedLock lock(mutex_);
3176 already_signalled_ = false;
3177 }
3178 {
3179 Locker locker;
Steve Block44f0eee2011-05-26 01:26:41 +01003180 Isolate::Current()->debugger()->CallMessageDispatchHandler();
Leon Clarkee46be812010-01-19 14:06:41 +00003181 }
3182 }
3183}
3184
Steve Blocka7e24c12009-10-30 11:49:00 +00003185#endif // ENABLE_DEBUGGER_SUPPORT
3186
3187} } // namespace v8::internal