blob: 1374c1568f3a77e3e2de3166fdc872c005b70b11 [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "api.h"
31#include "arguments.h"
32#include "bootstrapper.h"
33#include "code-stubs.h"
34#include "compiler.h"
35#include "debug.h"
36#include "execution.h"
37#include "global-handles.h"
38#include "natives.h"
39#include "stub-cache.h"
kasper.lund7276f142008-07-30 08:49:36 +000040#include "log.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000041
42namespace v8 { namespace internal {
43
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000044static void PrintLn(v8::Local<v8::Value> value) {
45 v8::Local<v8::String> s = value->ToString();
46 char* data = NewArray<char>(s->Length() + 1);
47 if (data == NULL) {
48 V8::FatalProcessOutOfMemory("PrintLn");
49 return;
50 }
51 s->WriteAscii(data);
52 PrintF("%s\n", data);
53 DeleteArray(data);
54}
55
56
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000057static Handle<Code> ComputeCallDebugBreak(int argc) {
58 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugBreak(argc), Code);
59}
60
61
62static Handle<Code> ComputeCallDebugPrepareStepIn(int argc) {
63 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugPrepareStepIn(argc), Code);
64}
65
66
67BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
68 BreakLocatorType type) {
69 debug_info_ = debug_info;
70 type_ = type;
71 reloc_iterator_ = NULL;
72 reloc_iterator_original_ = NULL;
73 Reset(); // Initialize the rest of the member variables.
74}
75
76
77BreakLocationIterator::~BreakLocationIterator() {
78 ASSERT(reloc_iterator_ != NULL);
79 ASSERT(reloc_iterator_original_ != NULL);
80 delete reloc_iterator_;
81 delete reloc_iterator_original_;
82}
83
84
85void BreakLocationIterator::Next() {
86 AssertNoAllocation nogc;
87 ASSERT(!RinfoDone());
88
89 // Iterate through reloc info for code and original code stopping at each
90 // breakable code target.
91 bool first = break_point_ == -1;
92 while (!RinfoDone()) {
93 if (!first) RinfoNext();
94 first = false;
95 if (RinfoDone()) return;
96
ager@chromium.org236ad962008-09-25 09:45:57 +000097 // Whenever a statement position or (plain) position is passed update the
98 // current value of these.
99 if (RelocInfo::IsPosition(rmode())) {
100 if (RelocInfo::IsStatementPosition(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000101 statement_position_ =
102 rinfo()->data() - debug_info_->shared()->start_position();
103 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000104 // Always update the position as we don't want that to be before the
105 // statement position.
106 position_ = rinfo()->data() - debug_info_->shared()->start_position();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000107 ASSERT(position_ >= 0);
108 ASSERT(statement_position_ >= 0);
109 }
110
111 // Check for breakable code target. Look in the original code as setting
112 // break points can cause the code targets in the running (debugged) code to
113 // be of a different kind than in the original code.
ager@chromium.org236ad962008-09-25 09:45:57 +0000114 if (RelocInfo::IsCodeTarget(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000115 Address target = original_rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000116 Code* code = Code::GetCodeFromTargetAddress(target);
ager@chromium.org236ad962008-09-25 09:45:57 +0000117 if (code->is_inline_cache_stub() || RelocInfo::IsConstructCall(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000118 break_point_++;
119 return;
120 }
121 if (code->kind() == Code::STUB) {
122 if (type_ == ALL_BREAK_LOCATIONS) {
123 if (Debug::IsBreakStub(code)) {
124 break_point_++;
125 return;
126 }
127 } else {
128 ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
129 if (Debug::IsSourceBreakStub(code)) {
130 break_point_++;
131 return;
132 }
133 }
134 }
135 }
136
137 // Check for break at return.
ager@chromium.org236ad962008-09-25 09:45:57 +0000138 if (RelocInfo::IsJSReturn(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000139 // Set the positions to the end of the function.
140 if (debug_info_->shared()->HasSourceCode()) {
141 position_ = debug_info_->shared()->end_position() -
142 debug_info_->shared()->start_position();
143 } else {
144 position_ = 0;
145 }
146 statement_position_ = position_;
147 break_point_++;
148 return;
149 }
150 }
151}
152
153
154void BreakLocationIterator::Next(int count) {
155 while (count > 0) {
156 Next();
157 count--;
158 }
159}
160
161
162// Find the break point closest to the supplied address.
163void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
164 // Run through all break points to locate the one closest to the address.
165 int closest_break_point = 0;
166 int distance = kMaxInt;
167 while (!Done()) {
168 // Check if this break point is closer that what was previously found.
169 if (this->pc() < pc && pc - this->pc() < distance) {
170 closest_break_point = break_point();
171 distance = pc - this->pc();
172 // Check whether we can't get any closer.
173 if (distance == 0) break;
174 }
175 Next();
176 }
177
178 // Move to the break point found.
179 Reset();
180 Next(closest_break_point);
181}
182
183
184// Find the break point closest to the supplied source position.
185void BreakLocationIterator::FindBreakLocationFromPosition(int position) {
186 // Run through all break points to locate the one closest to the source
187 // position.
188 int closest_break_point = 0;
189 int distance = kMaxInt;
190 while (!Done()) {
191 // Check if this break point is closer that what was previously found.
192 if (position <= statement_position() &&
193 statement_position() - position < distance) {
194 closest_break_point = break_point();
195 distance = statement_position() - position;
196 // Check whether we can't get any closer.
197 if (distance == 0) break;
198 }
199 Next();
200 }
201
202 // Move to the break point found.
203 Reset();
204 Next(closest_break_point);
205}
206
207
208void BreakLocationIterator::Reset() {
209 // Create relocation iterators for the two code objects.
210 if (reloc_iterator_ != NULL) delete reloc_iterator_;
211 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
212 reloc_iterator_ = new RelocIterator(debug_info_->code());
213 reloc_iterator_original_ = new RelocIterator(debug_info_->original_code());
214
215 // Position at the first break point.
216 break_point_ = -1;
217 position_ = 1;
218 statement_position_ = 1;
219 Next();
220}
221
222
223bool BreakLocationIterator::Done() const {
224 return RinfoDone();
225}
226
227
228void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
229 // If there is not already a real break point here patch code with debug
230 // break.
231 if (!HasBreakPoint()) {
232 SetDebugBreak();
233 }
234 ASSERT(IsDebugBreak());
235 // Set the break point information.
236 DebugInfo::SetBreakPoint(debug_info_, code_position(),
237 position(), statement_position(),
238 break_point_object);
239}
240
241
242void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
243 // Clear the break point information.
244 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
245 // If there are no more break points here remove the debug break.
246 if (!HasBreakPoint()) {
247 ClearDebugBreak();
248 ASSERT(!IsDebugBreak());
249 }
250}
251
252
253void BreakLocationIterator::SetOneShot() {
254 // If there is a real break point here no more to do.
255 if (HasBreakPoint()) {
256 ASSERT(IsDebugBreak());
257 return;
258 }
259
260 // Patch code with debug break.
261 SetDebugBreak();
262}
263
264
265void BreakLocationIterator::ClearOneShot() {
266 // If there is a real break point here no more to do.
267 if (HasBreakPoint()) {
268 ASSERT(IsDebugBreak());
269 return;
270 }
271
272 // Patch code removing debug break.
273 ClearDebugBreak();
274 ASSERT(!IsDebugBreak());
275}
276
277
278void BreakLocationIterator::SetDebugBreak() {
279 // If there is already a break point here just return. This might happen if
v8.team.kasperl727e9952008-09-02 14:56:44 +0000280 // the same code is flooded with break points twice. Flooding the same
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000281 // function twice might happen when stepping in a function with an exception
282 // handler as the handler and the function is the same.
283 if (IsDebugBreak()) {
284 return;
285 }
286
ager@chromium.org236ad962008-09-25 09:45:57 +0000287 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000288 // Patch the frame exit code with a break point.
289 SetDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000290 } else {
291 // Patch the original code with the current address as the current address
292 // might have changed by the inline caching since the code was copied.
293 original_rinfo()->set_target_address(rinfo()->target_address());
294
295 // Patch the code to invoke the builtin debug break function matching the
296 // calling convention used by the call site.
297 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(rinfo()));
298 rinfo()->set_target_address(dbgbrk_code->entry());
299 }
300 ASSERT(IsDebugBreak());
301}
302
303
304void BreakLocationIterator::ClearDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000305 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000306 // Restore the frame exit code.
307 ClearDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000308 } else {
309 // Patch the code to the original invoke.
310 rinfo()->set_target_address(original_rinfo()->target_address());
311 }
312 ASSERT(!IsDebugBreak());
313}
314
315
316void BreakLocationIterator::PrepareStepIn() {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000317 HandleScope scope;
318
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000319 // Step in can only be prepared if currently positioned on an IC call or
320 // construct call.
321 Address target = rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000322 Code* code = Code::GetCodeFromTargetAddress(target);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000323 if (code->is_call_stub()) {
324 // Step in through IC call is handled by the runtime system. Therefore make
325 // sure that the any current IC is cleared and the runtime system is
326 // called. If the executing code has a debug break at the location change
327 // the call in the original code as it is the code there that will be
328 // executed in place of the debug break call.
329 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count());
330 if (IsDebugBreak()) {
331 original_rinfo()->set_target_address(stub->entry());
332 } else {
333 rinfo()->set_target_address(stub->entry());
334 }
335 } else {
v8.team.kasperl727e9952008-09-02 14:56:44 +0000336 // Step in through constructs call requires no changes to the running code.
ager@chromium.org236ad962008-09-25 09:45:57 +0000337 ASSERT(RelocInfo::IsConstructCall(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000338 }
339}
340
341
342// Check whether the break point is at a position which will exit the function.
343bool BreakLocationIterator::IsExit() const {
ager@chromium.org236ad962008-09-25 09:45:57 +0000344 return (RelocInfo::IsJSReturn(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000345}
346
347
348bool BreakLocationIterator::HasBreakPoint() {
349 return debug_info_->HasBreakPoint(code_position());
350}
351
352
353// Check whether there is a debug break at the current position.
354bool BreakLocationIterator::IsDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000355 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000356 return IsDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000357 } else {
358 return Debug::IsDebugBreak(rinfo()->target_address());
359 }
360}
361
362
363Object* BreakLocationIterator::BreakPointObjects() {
364 return debug_info_->GetBreakPointObjects(code_position());
365}
366
367
ager@chromium.org381abbb2009-02-25 13:23:22 +0000368// Clear out all the debug break code. This is ONLY supposed to be used when
369// shutting down the debugger as it will leave the break point information in
370// DebugInfo even though the code is patched back to the non break point state.
371void BreakLocationIterator::ClearAllDebugBreak() {
372 while (!Done()) {
373 ClearDebugBreak();
374 Next();
375 }
376}
377
378
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000379bool BreakLocationIterator::RinfoDone() const {
380 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
381 return reloc_iterator_->done();
382}
383
384
385void BreakLocationIterator::RinfoNext() {
386 reloc_iterator_->next();
387 reloc_iterator_original_->next();
388#ifdef DEBUG
389 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
390 if (!reloc_iterator_->done()) {
391 ASSERT(rmode() == original_rmode());
392 }
393#endif
394}
395
396
397bool Debug::has_break_points_ = false;
398DebugInfoListNode* Debug::debug_info_list_ = NULL;
399
400
401// Threading support.
402void Debug::ThreadInit() {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000403 thread_local_.break_count_ = 0;
404 thread_local_.break_id_ = 0;
405 thread_local_.break_frame_id_ = StackFrame::NO_ID;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000406 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +0000407 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000408 thread_local_.step_count_ = 0;
409 thread_local_.last_fp_ = 0;
410 thread_local_.step_into_fp_ = 0;
411 thread_local_.after_break_target_ = 0;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000412 thread_local_.debugger_entry_ = NULL;
413 thread_local_.preemption_pending_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000414}
415
416
417JSCallerSavedBuffer Debug::registers_;
418Debug::ThreadLocal Debug::thread_local_;
419
420
421char* Debug::ArchiveDebug(char* storage) {
422 char* to = storage;
423 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
424 to += sizeof(ThreadLocal);
425 memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
426 ThreadInit();
427 ASSERT(to <= storage + ArchiveSpacePerThread());
428 return storage + ArchiveSpacePerThread();
429}
430
431
432char* Debug::RestoreDebug(char* storage) {
433 char* from = storage;
434 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
435 from += sizeof(ThreadLocal);
436 memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
437 ASSERT(from <= storage + ArchiveSpacePerThread());
438 return storage + ArchiveSpacePerThread();
439}
440
441
442int Debug::ArchiveSpacePerThread() {
443 return sizeof(ThreadLocal) + sizeof(registers_);
444}
445
446
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000447// Default break enabled.
448bool Debug::disable_break_ = false;
449
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000450// Default call debugger on uncaught exception.
451bool Debug::break_on_exception_ = false;
452bool Debug::break_on_uncaught_exception_ = true;
453
454Handle<Context> Debug::debug_context_ = Handle<Context>();
455Code* Debug::debug_break_return_entry_ = NULL;
456Code* Debug::debug_break_return_ = NULL;
457
458
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000459void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000460 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
461 RemoveDebugInfo(node->debug_info());
462#ifdef DEBUG
463 node = Debug::debug_info_list_;
464 while (node != NULL) {
465 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
466 node = node->next();
467 }
468#endif
469}
470
471
472DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
473 // Globalize the request debug info object and make it weak.
474 debug_info_ = Handle<DebugInfo>::cast((GlobalHandles::Create(debug_info)));
475 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
476 this, Debug::HandleWeakDebugInfo);
477}
478
479
480DebugInfoListNode::~DebugInfoListNode() {
481 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
482}
483
484
485void Debug::Setup(bool create_heap_objects) {
486 ThreadInit();
487 if (create_heap_objects) {
488 // Get code to handle entry to debug break on return.
489 debug_break_return_entry_ =
490 Builtins::builtin(Builtins::Return_DebugBreakEntry);
491 ASSERT(debug_break_return_entry_->IsCode());
492
493 // Get code to handle debug break on return.
494 debug_break_return_ =
495 Builtins::builtin(Builtins::Return_DebugBreak);
496 ASSERT(debug_break_return_->IsCode());
497 }
498}
499
500
501bool Debug::CompileDebuggerScript(int index) {
502 HandleScope scope;
503
kasper.lund44510672008-07-25 07:37:58 +0000504 // Bail out if the index is invalid.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000505 if (index == -1) {
506 return false;
507 }
kasper.lund44510672008-07-25 07:37:58 +0000508
509 // Find source and name for the requested script.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000510 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
511 Vector<const char> name = Natives::GetScriptName(index);
512 Handle<String> script_name = Factory::NewStringFromAscii(name);
513
514 // Compile the script.
515 bool allow_natives_syntax = FLAG_allow_natives_syntax;
516 FLAG_allow_natives_syntax = true;
517 Handle<JSFunction> boilerplate;
518 boilerplate = Compiler::Compile(source_code, script_name, 0, 0, NULL, NULL);
519 FLAG_allow_natives_syntax = allow_natives_syntax;
520
521 // Silently ignore stack overflows during compilation.
522 if (boilerplate.is_null()) {
523 ASSERT(Top::has_pending_exception());
524 Top::clear_pending_exception();
525 return false;
526 }
527
kasper.lund44510672008-07-25 07:37:58 +0000528 // Execute the boilerplate function in the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000529 Handle<Context> context = Top::global_context();
kasper.lund44510672008-07-25 07:37:58 +0000530 bool caught_exception = false;
531 Handle<JSFunction> function =
532 Factory::NewFunctionFromBoilerplate(boilerplate, context);
533 Handle<Object> result =
534 Execution::TryCall(function, Handle<Object>(context->global()),
535 0, NULL, &caught_exception);
536
537 // Check for caught exceptions.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000538 if (caught_exception) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000539 Handle<Object> message = MessageHandler::MakeMessageObject(
540 "error_loading_debugger", NULL, HandleVector<Object>(&result, 1),
541 Handle<String>());
542 MessageHandler::ReportMessage(NULL, message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000543 return false;
544 }
545
kasper.lund44510672008-07-25 07:37:58 +0000546 // Mark this script as native and return successfully.
547 Handle<Script> script(Script::cast(function->shared()->script()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000548 script->set_type(Smi::FromInt(SCRIPT_TYPE_NATIVE));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000549 return true;
550}
551
552
553bool Debug::Load() {
554 // Return if debugger is already loaded.
kasper.lund212ac232008-07-16 07:07:30 +0000555 if (IsLoaded()) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000556
kasper.lund44510672008-07-25 07:37:58 +0000557 // Bail out if we're already in the process of compiling the native
558 // JavaScript source code for the debugger.
mads.s.agercbaa0602008-08-14 13:41:48 +0000559 if (Debugger::compiling_natives() || Debugger::is_loading_debugger())
560 return false;
561 Debugger::set_loading_debugger(true);
kasper.lund44510672008-07-25 07:37:58 +0000562
563 // Disable breakpoints and interrupts while compiling and running the
564 // debugger scripts including the context creation code.
565 DisableBreak disable(true);
566 PostponeInterruptsScope postpone;
567
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000568 // Create the debugger context.
569 HandleScope scope;
kasper.lund44510672008-07-25 07:37:58 +0000570 Handle<Context> context =
571 Bootstrapper::CreateEnvironment(Handle<Object>::null(),
572 v8::Handle<ObjectTemplate>(),
573 NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000574
kasper.lund44510672008-07-25 07:37:58 +0000575 // Use the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000576 SaveContext save;
kasper.lund44510672008-07-25 07:37:58 +0000577 Top::set_context(*context);
kasper.lund44510672008-07-25 07:37:58 +0000578
579 // Expose the builtins object in the debugger context.
580 Handle<String> key = Factory::LookupAsciiSymbol("builtins");
581 Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
582 SetProperty(global, key, Handle<Object>(global->builtins()), NONE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000583
584 // Compile the JavaScript for the debugger in the debugger context.
585 Debugger::set_compiling_natives(true);
kasper.lund44510672008-07-25 07:37:58 +0000586 bool caught_exception =
587 !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
588 !CompileDebuggerScript(Natives::GetIndex("debug"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000589 Debugger::set_compiling_natives(false);
590
mads.s.agercbaa0602008-08-14 13:41:48 +0000591 // Make sure we mark the debugger as not loading before we might
592 // return.
593 Debugger::set_loading_debugger(false);
594
kasper.lund44510672008-07-25 07:37:58 +0000595 // Check for caught exceptions.
596 if (caught_exception) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000597
598 // Debugger loaded.
kasper.lund44510672008-07-25 07:37:58 +0000599 debug_context_ = Handle<Context>::cast(GlobalHandles::Create(*context));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000600 return true;
601}
602
603
604void Debug::Unload() {
605 // Return debugger is not loaded.
606 if (!IsLoaded()) {
607 return;
608 }
609
610 // Clear debugger context global handle.
611 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_context_.location()));
612 debug_context_ = Handle<Context>();
613}
614
615
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000616// Set the flag indicating that preemption happened during debugging.
617void Debug::PreemptionWhileInDebugger() {
618 ASSERT(InDebugger());
619 Debug::set_preemption_pending(true);
620}
621
622
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000623void Debug::Iterate(ObjectVisitor* v) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000624 v->VisitPointer(bit_cast<Object**, Code**>(&(debug_break_return_entry_)));
625 v->VisitPointer(bit_cast<Object**, Code**>(&(debug_break_return_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000626}
627
628
629Object* Debug::Break(Arguments args) {
630 HandleScope scope;
mads.s.ager31e71382008-08-13 09:32:07 +0000631 ASSERT(args.length() == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000632
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000633 // Get the top-most JavaScript frame.
634 JavaScriptFrameIterator it;
635 JavaScriptFrame* frame = it.frame();
636
637 // Just continue if breaks are disabled or debugger cannot be loaded.
638 if (disable_break() || !Load()) {
639 SetAfterBreakTarget(frame);
mads.s.ager31e71382008-08-13 09:32:07 +0000640 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000641 }
642
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000643 // Enter the debugger.
644 EnterDebugger debugger;
645 if (debugger.FailedToEnter()) {
646 return Heap::undefined_value();
647 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000648
kasper.lund44510672008-07-25 07:37:58 +0000649 // Postpone interrupt during breakpoint processing.
650 PostponeInterruptsScope postpone;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000651
652 // Get the debug info (create it if it does not exist).
653 Handle<SharedFunctionInfo> shared =
654 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
655 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
656
657 // Find the break point where execution has stopped.
658 BreakLocationIterator break_location_iterator(debug_info,
659 ALL_BREAK_LOCATIONS);
660 break_location_iterator.FindBreakLocationFromAddress(frame->pc());
661
662 // Check whether step next reached a new statement.
663 if (!StepNextContinue(&break_location_iterator, frame)) {
664 // Decrease steps left if performing multiple steps.
665 if (thread_local_.step_count_ > 0) {
666 thread_local_.step_count_--;
667 }
668 }
669
670 // If there is one or more real break points check whether any of these are
671 // triggered.
672 Handle<Object> break_points_hit(Heap::undefined_value());
673 if (break_location_iterator.HasBreakPoint()) {
674 Handle<Object> break_point_objects =
675 Handle<Object>(break_location_iterator.BreakPointObjects());
676 break_points_hit = CheckBreakPoints(break_point_objects);
677 }
678
679 // Notify debugger if a real break point is triggered or if performing single
680 // stepping with no more steps to perform. Otherwise do another step.
681 if (!break_points_hit->IsUndefined() ||
682 (thread_local_.last_step_action_ != StepNone &&
683 thread_local_.step_count_ == 0)) {
684 // Clear all current stepping setup.
685 ClearStepping();
686
687 // Notify the debug event listeners.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000688 Debugger::OnDebugBreak(break_points_hit, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000689 } else if (thread_local_.last_step_action_ != StepNone) {
690 // Hold on to last step action as it is cleared by the call to
691 // ClearStepping.
692 StepAction step_action = thread_local_.last_step_action_;
693 int step_count = thread_local_.step_count_;
694
695 // Clear all current stepping setup.
696 ClearStepping();
697
698 // Set up for the remaining steps.
699 PrepareStep(step_action, step_count);
700 }
701
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000702 // Install jump to the call address which was overwritten.
703 SetAfterBreakTarget(frame);
704
mads.s.ager31e71382008-08-13 09:32:07 +0000705 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000706}
707
708
709// Check the break point objects for whether one or more are actually
710// triggered. This function returns a JSArray with the break point objects
711// which is triggered.
712Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
713 int break_points_hit_count = 0;
714 Handle<JSArray> break_points_hit = Factory::NewJSArray(1);
715
v8.team.kasperl727e9952008-09-02 14:56:44 +0000716 // If there are multiple break points they are in a FixedArray.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000717 ASSERT(!break_point_objects->IsUndefined());
718 if (break_point_objects->IsFixedArray()) {
719 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
720 for (int i = 0; i < array->length(); i++) {
721 Handle<Object> o(array->get(i));
722 if (CheckBreakPoint(o)) {
723 break_points_hit->SetElement(break_points_hit_count++, *o);
724 }
725 }
726 } else {
727 if (CheckBreakPoint(break_point_objects)) {
728 break_points_hit->SetElement(break_points_hit_count++,
729 *break_point_objects);
730 }
731 }
732
733 // Return undefined if no break points where triggered.
734 if (break_points_hit_count == 0) {
735 return Factory::undefined_value();
736 }
737 return break_points_hit;
738}
739
740
741// Check whether a single break point object is triggered.
742bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000743 HandleScope scope;
744
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000745 // Ignore check if break point object is not a JSObject.
746 if (!break_point_object->IsJSObject()) return true;
747
748 // Get the function CheckBreakPoint (defined in debug.js).
749 Handle<JSFunction> check_break_point =
750 Handle<JSFunction>(JSFunction::cast(
751 debug_context()->global()->GetProperty(
752 *Factory::LookupAsciiSymbol("IsBreakPointTriggered"))));
753
754 // Get the break id as an object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000755 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000756
757 // Call HandleBreakPointx.
758 bool caught_exception = false;
759 const int argc = 2;
760 Object** argv[argc] = {
761 break_id.location(),
762 reinterpret_cast<Object**>(break_point_object.location())
763 };
764 Handle<Object> result = Execution::TryCall(check_break_point,
765 Top::builtins(), argc, argv,
766 &caught_exception);
767
768 // If exception or non boolean result handle as not triggered
769 if (caught_exception || !result->IsBoolean()) {
770 return false;
771 }
772
773 // Return whether the break point is triggered.
774 return *result == Heap::true_value();
775}
776
777
778// Check whether the function has debug information.
779bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
780 return !shared->debug_info()->IsUndefined();
781}
782
783
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000784// Return the debug info for this function. EnsureDebugInfo must be called
785// prior to ensure the debug info has been generated for shared.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000786Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000787 ASSERT(HasDebugInfo(shared));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000788 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
789}
790
791
792void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
793 int source_position,
794 Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000795 HandleScope scope;
796
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000797 if (!EnsureDebugInfo(shared)) {
798 // Return if retrieving debug info failed.
799 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000800 }
801
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000802 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000803 // Source positions starts with zero.
804 ASSERT(source_position >= 0);
805
806 // Find the break point and change it.
807 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
808 it.FindBreakLocationFromPosition(source_position);
809 it.SetBreakPoint(break_point_object);
810
811 // At least one active break point now.
812 ASSERT(debug_info->GetBreakPointCount() > 0);
813}
814
815
816void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000817 HandleScope scope;
818
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000819 DebugInfoListNode* node = debug_info_list_;
820 while (node != NULL) {
821 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
822 break_point_object);
823 if (!result->IsUndefined()) {
824 // Get information in the break point.
825 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
826 Handle<DebugInfo> debug_info = node->debug_info();
827 Handle<SharedFunctionInfo> shared(debug_info->shared());
828 int source_position = break_point_info->statement_position()->value();
829
830 // Source positions starts with zero.
831 ASSERT(source_position >= 0);
832
833 // Find the break point and clear it.
834 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
835 it.FindBreakLocationFromPosition(source_position);
836 it.ClearBreakPoint(break_point_object);
837
838 // If there are no more break points left remove the debug info for this
839 // function.
840 if (debug_info->GetBreakPointCount() == 0) {
841 RemoveDebugInfo(debug_info);
842 }
843
844 return;
845 }
846 node = node->next();
847 }
848}
849
850
ager@chromium.org381abbb2009-02-25 13:23:22 +0000851void Debug::ClearAllBreakPoints() {
852 DebugInfoListNode* node = debug_info_list_;
853 while (node != NULL) {
854 // Remove all debug break code.
855 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
856 it.ClearAllDebugBreak();
857 node = node->next();
858 }
859
860 // Remove all debug info.
861 while (debug_info_list_ != NULL) {
862 RemoveDebugInfo(debug_info_list_->debug_info());
863 }
864}
865
866
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000867void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000868 // Make sure the function has setup the debug info.
869 if (!EnsureDebugInfo(shared)) {
870 // Return if we failed to retrieve the debug info.
871 return;
872 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000873
874 // Flood the function with break points.
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000875 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000876 while (!it.Done()) {
877 it.SetOneShot();
878 it.Next();
879 }
880}
881
882
883void Debug::FloodHandlerWithOneShot() {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000884 // Iterate through the JavaScript stack looking for handlers.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000885 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000886 if (id == StackFrame::NO_ID) {
887 // If there is no JavaScript stack don't do anything.
888 return;
889 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000890 for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) {
891 JavaScriptFrame* frame = it.frame();
892 if (frame->HasHandler()) {
893 Handle<SharedFunctionInfo> shared =
894 Handle<SharedFunctionInfo>(
895 JSFunction::cast(frame->function())->shared());
896 // Flood the function with the catch block with break points
897 FloodWithOneShot(shared);
898 return;
899 }
900 }
901}
902
903
904void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
905 if (type == BreakUncaughtException) {
906 break_on_uncaught_exception_ = enable;
907 } else {
908 break_on_exception_ = enable;
909 }
910}
911
912
913void Debug::PrepareStep(StepAction step_action, int step_count) {
914 HandleScope scope;
915 ASSERT(Debug::InDebugger());
916
917 // Remember this step action and count.
918 thread_local_.last_step_action_ = step_action;
919 thread_local_.step_count_ = step_count;
920
921 // Get the frame where the execution has stopped and skip the debug frame if
922 // any. The debug frame will only be present if execution was stopped due to
923 // hitting a break point. In other situations (e.g. unhandled exception) the
924 // debug frame is not present.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000925 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000926 if (id == StackFrame::NO_ID) {
927 // If there is no JavaScript stack don't do anything.
928 return;
929 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000930 JavaScriptFrameIterator frames_it(id);
931 JavaScriptFrame* frame = frames_it.frame();
932
933 // First of all ensure there is one-shot break points in the top handler
934 // if any.
935 FloodHandlerWithOneShot();
936
937 // If the function on the top frame is unresolved perform step out. This will
938 // be the case when calling unknown functions and having the debugger stopped
939 // in an unhandled exception.
940 if (!frame->function()->IsJSFunction()) {
941 // Step out: Find the calling JavaScript frame and flood it with
942 // breakpoints.
943 frames_it.Advance();
944 // Fill the function to return to with one-shot break points.
945 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
946 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
947 return;
948 }
949
950 // Get the debug info (create it if it does not exist).
951 Handle<SharedFunctionInfo> shared =
952 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000953 if (!EnsureDebugInfo(shared)) {
954 // Return if ensuring debug info failed.
955 return;
956 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000957 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
958
959 // Find the break location where execution has stopped.
960 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
961 it.FindBreakLocationFromAddress(frame->pc());
962
963 // Compute whether or not the target is a call target.
964 bool is_call_target = false;
ager@chromium.org236ad962008-09-25 09:45:57 +0000965 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000966 Address target = it.rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000967 Code* code = Code::GetCodeFromTargetAddress(target);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000968 if (code->is_call_stub()) is_call_target = true;
969 }
970
v8.team.kasperl727e9952008-09-02 14:56:44 +0000971 // If this is the last break code target step out is the only possibility.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000972 if (it.IsExit() || step_action == StepOut) {
973 // Step out: If there is a JavaScript caller frame, we need to
974 // flood it with breakpoints.
975 frames_it.Advance();
976 if (!frames_it.done()) {
977 // Fill the function to return to with one-shot break points.
978 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
979 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
980 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000981 } else if (!(is_call_target || RelocInfo::IsConstructCall(it.rmode())) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000982 step_action == StepNext || step_action == StepMin) {
983 // Step next or step min.
984
985 // Fill the current function with one-shot break points.
986 FloodWithOneShot(shared);
987
988 // Remember source position and frame to handle step next.
989 thread_local_.last_statement_position_ =
990 debug_info->code()->SourceStatementPosition(frame->pc());
991 thread_local_.last_fp_ = frame->fp();
992 } else {
993 // Fill the current function with one-shot break points even for step in on
994 // a call target as the function called might be a native function for
995 // which step in will not stop.
996 FloodWithOneShot(shared);
997
998 // Step in or Step in min
999 it.PrepareStepIn();
1000 ActivateStepIn(frame);
1001 }
1002}
1003
1004
1005// Check whether the current debug break should be reported to the debugger. It
1006// is used to have step next and step in only report break back to the debugger
1007// if on a different frame or in a different statement. In some situations
1008// there will be several break points in the same statement when the code is
v8.team.kasperl727e9952008-09-02 14:56:44 +00001009// flooded with one-shot break points. This function helps to perform several
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001010// steps before reporting break back to the debugger.
1011bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
1012 JavaScriptFrame* frame) {
1013 // If the step last action was step next or step in make sure that a new
1014 // statement is hit.
1015 if (thread_local_.last_step_action_ == StepNext ||
1016 thread_local_.last_step_action_ == StepIn) {
1017 // Never continue if returning from function.
1018 if (break_location_iterator->IsExit()) return false;
1019
1020 // Continue if we are still on the same frame and in the same statement.
1021 int current_statement_position =
1022 break_location_iterator->code()->SourceStatementPosition(frame->pc());
1023 return thread_local_.last_fp_ == frame->fp() &&
ager@chromium.org236ad962008-09-25 09:45:57 +00001024 thread_local_.last_statement_position_ == current_statement_position;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001025 }
1026
1027 // No step next action - don't continue.
1028 return false;
1029}
1030
1031
1032// Check whether the code object at the specified address is a debug break code
1033// object.
1034bool Debug::IsDebugBreak(Address addr) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001035 Code* code = Code::GetCodeFromTargetAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +00001036 return code->ic_state() == DEBUG_BREAK;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001037}
1038
1039
1040// Check whether a code stub with the specified major key is a possible break
1041// point location when looking for source break locations.
1042bool Debug::IsSourceBreakStub(Code* code) {
1043 CodeStub::Major major_key = code->major_key();
1044 return major_key == CodeStub::CallFunction;
1045}
1046
1047
1048// Check whether a code stub with the specified major key is a possible break
1049// location.
1050bool Debug::IsBreakStub(Code* code) {
1051 CodeStub::Major major_key = code->major_key();
1052 return major_key == CodeStub::CallFunction ||
1053 major_key == CodeStub::StackCheck;
1054}
1055
1056
1057// Find the builtin to use for invoking the debug break
1058Handle<Code> Debug::FindDebugBreak(RelocInfo* rinfo) {
1059 // Find the builtin debug break function matching the calling convention
1060 // used by the call site.
ager@chromium.org236ad962008-09-25 09:45:57 +00001061 RelocInfo::Mode mode = rinfo->rmode();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001062
ager@chromium.org236ad962008-09-25 09:45:57 +00001063 if (RelocInfo::IsCodeTarget(mode)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001064 Address target = rinfo->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001065 Code* code = Code::GetCodeFromTargetAddress(target);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001066 if (code->is_inline_cache_stub()) {
1067 if (code->is_call_stub()) {
1068 return ComputeCallDebugBreak(code->arguments_count());
1069 }
1070 if (code->is_load_stub()) {
1071 return Handle<Code>(Builtins::builtin(Builtins::LoadIC_DebugBreak));
1072 }
1073 if (code->is_store_stub()) {
1074 return Handle<Code>(Builtins::builtin(Builtins::StoreIC_DebugBreak));
1075 }
1076 if (code->is_keyed_load_stub()) {
1077 Handle<Code> result =
1078 Handle<Code>(Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak));
1079 return result;
1080 }
1081 if (code->is_keyed_store_stub()) {
1082 Handle<Code> result =
1083 Handle<Code>(Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak));
1084 return result;
1085 }
1086 }
ager@chromium.org236ad962008-09-25 09:45:57 +00001087 if (RelocInfo::IsConstructCall(mode)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001088 Handle<Code> result =
1089 Handle<Code>(Builtins::builtin(Builtins::ConstructCall_DebugBreak));
1090 return result;
1091 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001092 if (code->kind() == Code::STUB) {
1093 ASSERT(code->major_key() == CodeStub::CallFunction ||
1094 code->major_key() == CodeStub::StackCheck);
1095 Handle<Code> result =
1096 Handle<Code>(Builtins::builtin(Builtins::StubNoRegisters_DebugBreak));
1097 return result;
1098 }
1099 }
1100
1101 UNREACHABLE();
1102 return Handle<Code>::null();
1103}
1104
1105
1106// Simple function for returning the source positions for active break points.
1107Handle<Object> Debug::GetSourceBreakLocations(
1108 Handle<SharedFunctionInfo> shared) {
1109 if (!HasDebugInfo(shared)) return Handle<Object>(Heap::undefined_value());
1110 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1111 if (debug_info->GetBreakPointCount() == 0) {
1112 return Handle<Object>(Heap::undefined_value());
1113 }
1114 Handle<FixedArray> locations =
1115 Factory::NewFixedArray(debug_info->GetBreakPointCount());
1116 int count = 0;
1117 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1118 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1119 BreakPointInfo* break_point_info =
1120 BreakPointInfo::cast(debug_info->break_points()->get(i));
1121 if (break_point_info->GetBreakPointCount() > 0) {
1122 locations->set(count++, break_point_info->statement_position());
1123 }
1124 }
1125 }
1126 return locations;
1127}
1128
1129
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001130void Debug::NewBreak(StackFrame::Id break_frame_id) {
1131 thread_local_.break_frame_id_ = break_frame_id;
1132 thread_local_.break_id_ = ++thread_local_.break_count_;
1133}
1134
1135
1136void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
1137 thread_local_.break_frame_id_ = break_frame_id;
1138 thread_local_.break_id_ = break_id;
1139}
1140
1141
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001142// Handle stepping into a function.
1143void Debug::HandleStepIn(Handle<JSFunction> function,
1144 Address fp,
1145 bool is_constructor) {
1146 // If the frame pointer is not supplied by the caller find it.
1147 if (fp == 0) {
1148 StackFrameIterator it;
1149 it.Advance();
1150 // For constructor functions skip another frame.
1151 if (is_constructor) {
1152 ASSERT(it.frame()->is_construct());
1153 it.Advance();
1154 }
1155 fp = it.frame()->fp();
1156 }
1157
1158 // Flood the function with one-shot break points if it is called from where
1159 // step into was requested.
1160 if (fp == Debug::step_in_fp()) {
1161 // Don't allow step into functions in the native context.
1162 if (function->context()->global() != Top::context()->builtins()) {
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001163 if (function->shared()->code() ==
1164 Builtins::builtin(Builtins::FunctionApply) ||
1165 function->shared()->code() ==
1166 Builtins::builtin(Builtins::FunctionCall)) {
1167 // Handle function.apply and function.call separately to flood the
1168 // function to be called and not the code for Builtins::FunctionApply or
1169 // Builtins::FunctionCall. At the point of the call IC to call either
1170 // Builtins::FunctionApply or Builtins::FunctionCall the expression
1171 // stack has the following content:
1172 // symbol "apply" or "call"
1173 // function apply or call was called on
1174 // receiver for apply or call (first parameter to apply or call)
1175 // ... further arguments to apply or call.
1176 JavaScriptFrameIterator it;
1177 ASSERT(it.frame()->fp() == fp);
1178 ASSERT(it.frame()->GetExpression(1)->IsJSFunction());
1179 if (it.frame()->GetExpression(1)->IsJSFunction()) {
1180 Handle<JSFunction>
1181 actual_function(JSFunction::cast(it.frame()->GetExpression(1)));
1182 Handle<SharedFunctionInfo> actual_shared(actual_function->shared());
1183 Debug::FloodWithOneShot(actual_shared);
1184 }
1185 } else {
1186 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1187 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001188 }
1189 }
1190}
1191
1192
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001193void Debug::ClearStepping() {
1194 // Clear the various stepping setup.
1195 ClearOneShot();
1196 ClearStepIn();
1197 ClearStepNext();
1198
1199 // Clear multiple step counter.
1200 thread_local_.step_count_ = 0;
1201}
1202
1203// Clears all the one-shot break points that are currently set. Normally this
1204// function is called each time a break point is hit as one shot break points
1205// are used to support stepping.
1206void Debug::ClearOneShot() {
1207 // The current implementation just runs through all the breakpoints. When the
v8.team.kasperl727e9952008-09-02 14:56:44 +00001208 // last break point for a function is removed that function is automatically
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001209 // removed from the list.
1210
1211 DebugInfoListNode* node = debug_info_list_;
1212 while (node != NULL) {
1213 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1214 while (!it.Done()) {
1215 it.ClearOneShot();
1216 it.Next();
1217 }
1218 node = node->next();
1219 }
1220}
1221
1222
1223void Debug::ActivateStepIn(StackFrame* frame) {
1224 thread_local_.step_into_fp_ = frame->fp();
1225}
1226
1227
1228void Debug::ClearStepIn() {
1229 thread_local_.step_into_fp_ = 0;
1230}
1231
1232
1233void Debug::ClearStepNext() {
1234 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +00001235 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001236 thread_local_.last_fp_ = 0;
1237}
1238
1239
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001240bool Debug::EnsureCompiled(Handle<SharedFunctionInfo> shared) {
1241 if (shared->is_compiled()) return true;
ager@chromium.org3bf7b912008-11-17 09:09:45 +00001242 return CompileLazyShared(shared, CLEAR_EXCEPTION, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001243}
1244
1245
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001246// Ensures the debug information is present for shared.
1247bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1248 // Return if we already have the debug info for shared.
1249 if (HasDebugInfo(shared)) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001250
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001251 // Ensure shared in compiled. Return false if this failed.
1252 if (!EnsureCompiled(shared)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001253
1254 // Create the debug info object.
v8.team.kasperl727e9952008-09-02 14:56:44 +00001255 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001256
1257 // Add debug info to the list.
1258 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1259 node->set_next(debug_info_list_);
1260 debug_info_list_ = node;
1261
1262 // Now there is at least one break point.
1263 has_break_points_ = true;
1264
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001265 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001266}
1267
1268
1269void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1270 ASSERT(debug_info_list_ != NULL);
1271 // Run through the debug info objects to find this one and remove it.
1272 DebugInfoListNode* prev = NULL;
1273 DebugInfoListNode* current = debug_info_list_;
1274 while (current != NULL) {
1275 if (*current->debug_info() == *debug_info) {
1276 // Unlink from list. If prev is NULL we are looking at the first element.
1277 if (prev == NULL) {
1278 debug_info_list_ = current->next();
1279 } else {
1280 prev->set_next(current->next());
1281 }
1282 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1283 delete current;
1284
1285 // If there are no more debug info objects there are not more break
1286 // points.
1287 has_break_points_ = debug_info_list_ != NULL;
1288
1289 return;
1290 }
1291 // Move to next in list.
1292 prev = current;
1293 current = current->next();
1294 }
1295 UNREACHABLE();
1296}
1297
1298
1299void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001300 HandleScope scope;
1301
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001302 // Get the executing function in which the debug break occurred.
1303 Handle<SharedFunctionInfo> shared =
1304 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001305 if (!EnsureDebugInfo(shared)) {
1306 // Return if we failed to retrieve the debug info.
1307 return;
1308 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001309 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1310 Handle<Code> code(debug_info->code());
1311 Handle<Code> original_code(debug_info->original_code());
1312#ifdef DEBUG
1313 // Get the code which is actually executing.
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001314 Handle<Code> frame_code(frame->code());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001315 ASSERT(frame_code.is_identical_to(code));
1316#endif
1317
1318 // Find the call address in the running code. This address holds the call to
1319 // either a DebugBreakXXX or to the debug break return entry code if the
1320 // break point is still active after processing the break point.
1321 Address addr = frame->pc() - Assembler::kTargetAddrToReturnAddrDist;
1322
1323 // Check if the location is at JS exit.
1324 bool at_js_exit = false;
1325 RelocIterator it(debug_info->code());
1326 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001327 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001328 at_js_exit = it.rinfo()->pc() == addr - 1;
1329 }
1330 it.next();
1331 }
1332
1333 // Handle the jump to continue execution after break point depending on the
1334 // break location.
1335 if (at_js_exit) {
1336 // First check if the call in the code is still the debug break return
1337 // entry code. If it is the break point is still active. If not the break
1338 // point was removed during break point processing.
1339 if (Assembler::target_address_at(addr) ==
1340 debug_break_return_entry()->entry()) {
1341 // Break point still active. Jump to the corresponding place in the
1342 // original code.
1343 addr += original_code->instruction_start() - code->instruction_start();
1344 }
1345
1346 // Move one byte back to where the call instruction was placed.
1347 thread_local_.after_break_target_ = addr - 1;
1348 } else {
1349 // Check if there still is a debug break call at the target address. If the
1350 // break point has been removed it will have disappeared. If it have
1351 // disappeared don't try to look in the original code as the running code
1352 // will have the right address. This takes care of the case where the last
1353 // break point is removed from the function and therefore no "original code"
1354 // is available. If the debug break call is still there find the address in
1355 // the original code.
1356 if (IsDebugBreak(Assembler::target_address_at(addr))) {
1357 // If the break point is still there find the call address which was
1358 // overwritten in the original code by the call to DebugBreakXXX.
1359
1360 // Find the corresponding address in the original code.
1361 addr += original_code->instruction_start() - code->instruction_start();
1362 }
1363
1364 // Install jump to the call address in the original code. This will be the
1365 // call which was overwritten by the call to DebugBreakXXX.
1366 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1367 }
1368}
1369
1370
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001371bool Debug::IsDebugGlobal(GlobalObject* global) {
1372 return IsLoaded() && global == Debug::debug_context()->global();
1373}
1374
1375
ager@chromium.org32912102009-01-16 10:38:43 +00001376void Debug::ClearMirrorCache() {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001377 HandleScope scope;
ager@chromium.org32912102009-01-16 10:38:43 +00001378 ASSERT(Top::context() == *Debug::debug_context());
1379
1380 // Clear the mirror cache.
1381 Handle<String> function_name =
1382 Factory::LookupSymbol(CStrVector("ClearMirrorCache"));
1383 Handle<Object> fun(Top::global()->GetProperty(*function_name));
1384 ASSERT(fun->IsJSFunction());
1385 bool caught_exception;
1386 Handle<Object> js_object = Execution::TryCall(
1387 Handle<JSFunction>::cast(fun),
1388 Handle<JSObject>(Debug::debug_context()->global()),
1389 0, NULL, &caught_exception);
1390}
1391
1392
ager@chromium.org71daaf62009-04-01 07:22:49 +00001393Mutex* Debugger::debugger_access_ = OS::CreateMutex();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001394Handle<Object> Debugger::event_listener_ = Handle<Object>();
1395Handle<Object> Debugger::event_listener_data_ = Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001396bool Debugger::compiling_natives_ = false;
mads.s.agercbaa0602008-08-14 13:41:48 +00001397bool Debugger::is_loading_debugger_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001398bool Debugger::never_unload_debugger_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001399DebugMessageThread* Debugger::message_thread_ = NULL;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001400v8::DebugMessageHandler Debugger::message_handler_ = NULL;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001401bool Debugger::message_handler_cleared_ = false;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001402void* Debugger::message_handler_data_ = NULL;
1403v8::DebugHostDispatchHandler Debugger::host_dispatch_handler_ = NULL;
1404void* Debugger::host_dispatch_handler_data_ = NULL;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001405DebuggerAgent* Debugger::agent_ = NULL;
ager@chromium.org41826e72009-03-30 13:30:57 +00001406LockingMessageQueue Debugger::command_queue_(kQueueInitialSize);
1407LockingMessageQueue Debugger::message_queue_(kQueueInitialSize);
1408Semaphore* Debugger::command_received_ = OS::CreateSemaphore(0);
1409Semaphore* Debugger::message_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001410
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001411
1412Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1413 int argc, Object*** argv,
1414 bool* caught_exception) {
1415 ASSERT(Top::context() == *Debug::debug_context());
1416
1417 // Create the execution state object.
1418 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1419 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1420 ASSERT(constructor->IsJSFunction());
1421 if (!constructor->IsJSFunction()) {
1422 *caught_exception = true;
1423 return Factory::undefined_value();
1424 }
1425 Handle<Object> js_object = Execution::TryCall(
1426 Handle<JSFunction>::cast(constructor),
1427 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1428 caught_exception);
1429 return js_object;
1430}
1431
1432
1433Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1434 // Create the execution state object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001435 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001436 const int argc = 1;
1437 Object** argv[argc] = { break_id.location() };
1438 return MakeJSObject(CStrVector("MakeExecutionState"),
1439 argc, argv, caught_exception);
1440}
1441
1442
1443Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1444 Handle<Object> break_points_hit,
1445 bool* caught_exception) {
1446 // Create the new break event object.
1447 const int argc = 2;
1448 Object** argv[argc] = { exec_state.location(),
1449 break_points_hit.location() };
1450 return MakeJSObject(CStrVector("MakeBreakEvent"),
1451 argc,
1452 argv,
1453 caught_exception);
1454}
1455
1456
1457Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1458 Handle<Object> exception,
1459 bool uncaught,
1460 bool* caught_exception) {
1461 // Create the new exception event object.
1462 const int argc = 3;
1463 Object** argv[argc] = { exec_state.location(),
1464 exception.location(),
1465 uncaught ? Factory::true_value().location() :
1466 Factory::false_value().location()};
1467 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1468 argc, argv, caught_exception);
1469}
1470
1471
1472Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1473 bool* caught_exception) {
1474 // Create the new function event object.
1475 const int argc = 1;
1476 Object** argv[argc] = { function.location() };
1477 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1478 argc, argv, caught_exception);
1479}
1480
1481
1482Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001483 bool before,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001484 bool* caught_exception) {
1485 // Create the compile event object.
1486 Handle<Object> exec_state = MakeExecutionState(caught_exception);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001487 Handle<Object> script_wrapper = GetScriptWrapper(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001488 const int argc = 3;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001489 Object** argv[argc] = { exec_state.location(),
1490 script_wrapper.location(),
1491 before ? Factory::true_value().location() :
1492 Factory::false_value().location() };
1493
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001494 return MakeJSObject(CStrVector("MakeCompileEvent"),
1495 argc,
1496 argv,
1497 caught_exception);
1498}
1499
1500
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001501void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1502 HandleScope scope;
1503
1504 // Bail out based on state or if there is no listener for this event
1505 if (Debug::InDebugger()) return;
1506 if (!Debugger::EventActive(v8::Exception)) return;
1507
1508 // Bail out if exception breaks are not active
1509 if (uncaught) {
1510 // Uncaught exceptions are reported by either flags.
1511 if (!(Debug::break_on_uncaught_exception() ||
1512 Debug::break_on_exception())) return;
1513 } else {
1514 // Caught exceptions are reported is activated.
1515 if (!Debug::break_on_exception()) return;
1516 }
1517
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001518 // Enter the debugger.
1519 EnterDebugger debugger;
1520 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001521
1522 // Clear all current stepping setup.
1523 Debug::ClearStepping();
1524 // Create the event data object.
1525 bool caught_exception = false;
1526 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1527 Handle<Object> event_data;
1528 if (!caught_exception) {
1529 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1530 &caught_exception);
1531 }
1532 // Bail out and don't call debugger if exception.
1533 if (caught_exception) {
1534 return;
1535 }
1536
1537 // Process debug event
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001538 ProcessDebugEvent(v8::Exception, event_data, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001539 // Return to continue execution from where the exception was thrown.
1540}
1541
1542
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001543void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
1544 bool auto_continue) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001545 HandleScope scope;
1546
kasper.lund212ac232008-07-16 07:07:30 +00001547 // Debugger has already been entered by caller.
1548 ASSERT(Top::context() == *Debug::debug_context());
1549
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001550 // Bail out if there is no listener for this event
1551 if (!Debugger::EventActive(v8::Break)) return;
1552
1553 // Debugger must be entered in advance.
1554 ASSERT(Top::context() == *Debug::debug_context());
1555
1556 // Create the event data object.
1557 bool caught_exception = false;
1558 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1559 Handle<Object> event_data;
1560 if (!caught_exception) {
1561 event_data = MakeBreakEvent(exec_state, break_points_hit,
1562 &caught_exception);
1563 }
1564 // Bail out and don't call debugger if exception.
1565 if (caught_exception) {
1566 return;
1567 }
1568
1569 // Process debug event
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001570 ProcessDebugEvent(v8::Break, event_data, auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001571}
1572
1573
1574void Debugger::OnBeforeCompile(Handle<Script> script) {
1575 HandleScope scope;
1576
1577 // Bail out based on state or if there is no listener for this event
1578 if (Debug::InDebugger()) return;
1579 if (compiling_natives()) return;
1580 if (!EventActive(v8::BeforeCompile)) return;
1581
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001582 // Enter the debugger.
1583 EnterDebugger debugger;
1584 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001585
1586 // Create the event data object.
1587 bool caught_exception = false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001588 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001589 // Bail out and don't call debugger if exception.
1590 if (caught_exception) {
1591 return;
1592 }
1593
1594 // Process debug event
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001595 ProcessDebugEvent(v8::BeforeCompile, event_data, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001596}
1597
1598
1599// Handle debugger actions when a new script is compiled.
1600void Debugger::OnAfterCompile(Handle<Script> script, Handle<JSFunction> fun) {
kasper.lund212ac232008-07-16 07:07:30 +00001601 HandleScope scope;
1602
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001603 // No compile events while compiling natives.
1604 if (compiling_natives()) return;
1605
1606 // No more to do if not debugging.
ager@chromium.org71daaf62009-04-01 07:22:49 +00001607 if (!IsDebuggerActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001608
iposva@chromium.org245aa852009-02-10 00:49:54 +00001609 // Store whether in debugger before entering debugger.
1610 bool in_debugger = Debug::InDebugger();
1611
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001612 // Enter the debugger.
1613 EnterDebugger debugger;
1614 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001615
1616 // If debugging there might be script break points registered for this
1617 // script. Make sure that these break points are set.
1618
1619 // Get the function UpdateScriptBreakPoints (defined in debug-delay.js).
1620 Handle<Object> update_script_break_points =
1621 Handle<Object>(Debug::debug_context()->global()->GetProperty(
1622 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
1623 if (!update_script_break_points->IsJSFunction()) {
1624 return;
1625 }
1626 ASSERT(update_script_break_points->IsJSFunction());
1627
1628 // Wrap the script object in a proper JS object before passing it
1629 // to JavaScript.
1630 Handle<JSValue> wrapper = GetScriptWrapper(script);
1631
1632 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00001633 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001634 const int argc = 1;
1635 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
1636 Handle<Object> result = Execution::TryCall(
1637 Handle<JSFunction>::cast(update_script_break_points),
1638 Top::builtins(), argc, argv,
1639 &caught_exception);
1640 if (caught_exception) {
1641 return;
1642 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001643 // Bail out based on state or if there is no listener for this event
iposva@chromium.org245aa852009-02-10 00:49:54 +00001644 if (in_debugger) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001645 if (!Debugger::EventActive(v8::AfterCompile)) return;
1646
1647 // Create the compile state object.
1648 Handle<Object> event_data = MakeCompileEvent(script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001649 false,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001650 &caught_exception);
1651 // Bail out and don't call debugger if exception.
1652 if (caught_exception) {
1653 return;
1654 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001655 // Process debug event
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001656 ProcessDebugEvent(v8::AfterCompile, event_data, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001657}
1658
1659
1660void Debugger::OnNewFunction(Handle<JSFunction> function) {
1661 return;
1662 HandleScope scope;
1663
1664 // Bail out based on state or if there is no listener for this event
1665 if (Debug::InDebugger()) return;
1666 if (compiling_natives()) return;
1667 if (!Debugger::EventActive(v8::NewFunction)) return;
1668
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001669 // Enter the debugger.
1670 EnterDebugger debugger;
1671 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001672
1673 // Create the event object.
1674 bool caught_exception = false;
1675 Handle<Object> event_data = MakeNewFunctionEvent(function, &caught_exception);
1676 // Bail out and don't call debugger if exception.
1677 if (caught_exception) {
1678 return;
1679 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001680 // Process debug event.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001681 ProcessDebugEvent(v8::NewFunction, event_data, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001682}
1683
1684
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001685void Debugger::ProcessDebugEvent(v8::DebugEvent event,
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001686 Handle<Object> event_data,
1687 bool auto_continue) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001688 HandleScope scope;
1689
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001690 // Create the execution state.
1691 bool caught_exception = false;
1692 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1693 if (caught_exception) {
1694 return;
1695 }
ager@chromium.org41826e72009-03-30 13:30:57 +00001696 // First notify the message handler if any.
1697 if (message_handler_ != NULL) {
1698 NotifyMessageHandler(event, exec_state, event_data, auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001699 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001700 // Notify registered debug event listener. This can be either a C or a
1701 // JavaScript function.
1702 if (!event_listener_.is_null()) {
1703 if (event_listener_->IsProxy()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001704 // C debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00001705 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001706 v8::DebugEventCallback callback =
1707 FUNCTION_CAST<v8::DebugEventCallback>(callback_obj->proxy());
1708 callback(event,
1709 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state)),
1710 v8::Utils::ToLocal(Handle<JSObject>::cast(event_data)),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001711 v8::Utils::ToLocal(Handle<Object>::cast(event_listener_data_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001712 } else {
1713 // JavaScript debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00001714 ASSERT(event_listener_->IsJSFunction());
1715 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001716
1717 // Invoke the JavaScript debug event listener.
1718 const int argc = 4;
1719 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
1720 exec_state.location(),
1721 event_data.location(),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001722 event_listener_data_.location() };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001723 Handle<Object> result = Execution::TryCall(fun, Top::global(),
1724 argc, argv, &caught_exception);
1725 if (caught_exception) {
1726 // Silently ignore exceptions from debug event listeners.
1727 }
1728 }
1729 }
ager@chromium.org32912102009-01-16 10:38:43 +00001730
1731 // Clear the mirror cache.
1732 Debug::ClearMirrorCache();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001733}
1734
1735
ager@chromium.org71daaf62009-04-01 07:22:49 +00001736void Debugger::UnloadDebugger() {
1737 // Make sure that there are no breakpoints left.
1738 Debug::ClearAllBreakPoints();
1739
1740 // Unload the debugger if feasible.
1741 if (!never_unload_debugger_) {
1742 Debug::Unload();
1743 }
1744
1745 // Clear the flag indicating that the message handler was recently cleared.
1746 message_handler_cleared_ = false;
1747}
1748
1749
ager@chromium.org41826e72009-03-30 13:30:57 +00001750void Debugger::NotifyMessageHandler(v8::DebugEvent event,
1751 Handle<Object> exec_state,
1752 Handle<Object> event_data,
1753 bool auto_continue) {
1754 HandleScope scope;
1755
1756 if (!Debug::Load()) return;
1757
1758 // Process the individual events.
1759 bool interactive = false;
1760 switch (event) {
1761 case v8::Break:
1762 interactive = true; // Break event is always interactive
1763 break;
1764 case v8::Exception:
1765 interactive = true; // Exception event is always interactive
1766 break;
1767 case v8::BeforeCompile:
1768 break;
1769 case v8::AfterCompile:
1770 break;
1771 case v8::NewFunction:
1772 break;
1773 default:
1774 UNREACHABLE();
1775 }
1776
1777 // Done if not interactive.
1778 if (!interactive) return;
1779
1780 // Get the DebugCommandProcessor.
1781 v8::Local<v8::Object> api_exec_state =
1782 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
1783 v8::Local<v8::String> fun_name =
1784 v8::String::New("debugCommandProcessor");
1785 v8::Local<v8::Function> fun =
1786 v8::Function::Cast(*api_exec_state->Get(fun_name));
1787 v8::TryCatch try_catch;
1788 v8::Local<v8::Object> cmd_processor =
1789 v8::Object::Cast(*fun->Call(api_exec_state, 0, NULL));
1790 if (try_catch.HasCaught()) {
1791 PrintLn(try_catch.Exception());
1792 return;
1793 }
1794
1795 // Notify the debugger that a debug event has occurred unless auto continue is
1796 // active in which case no event is send.
1797 if (!auto_continue) {
1798 bool success = SendEventMessage(event_data);
1799 if (!success) {
1800 // If failed to notify debugger just continue running.
1801 return;
1802 }
1803 }
1804
1805 // Process requests from the debugger.
1806 while (true) {
1807 // Wait for new command in the queue.
1808 command_received_->Wait();
1809
1810 // The debug command interrupt flag might have been set when the command was
1811 // added.
1812 StackGuard::Continue(DEBUGCOMMAND);
1813
1814 // Get the command from the queue.
1815 Vector<uint16_t> command = command_queue_.Get();
1816 Logger::DebugTag("Got request from command queue, in interactive loop.");
ager@chromium.org71daaf62009-04-01 07:22:49 +00001817 if (!Debugger::IsDebuggerActive()) {
ager@chromium.org41826e72009-03-30 13:30:57 +00001818 return;
1819 }
1820
1821 // Check if the command is a host dispatch.
1822 if (command[0] == 0) {
1823 if (Debugger::host_dispatch_handler_) {
1824 int32_t dispatch = (command[1] << 16) | command[2];
1825 Debugger::host_dispatch_handler_(reinterpret_cast<void*>(dispatch),
1826 Debugger::host_dispatch_handler_data_);
1827 }
1828 continue;
1829 }
1830
1831 // Invoke JavaScript to process the debug request.
1832 v8::Local<v8::String> fun_name;
1833 v8::Local<v8::Function> fun;
1834 v8::Local<v8::Value> request;
1835 v8::TryCatch try_catch;
1836 fun_name = v8::String::New("processDebugRequest");
1837 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
1838 request = v8::String::New(reinterpret_cast<uint16_t*>(command.start()),
1839 command.length());
1840 static const int kArgc = 1;
1841 v8::Handle<Value> argv[kArgc] = { request };
1842 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
1843
1844 // Get the response.
1845 v8::Local<v8::String> response;
1846 bool running = false;
1847 if (!try_catch.HasCaught()) {
1848 // Get response string.
1849 if (!response_val->IsUndefined()) {
1850 response = v8::String::Cast(*response_val);
1851 } else {
1852 response = v8::String::New("");
1853 }
1854
1855 // Log the JSON request/response.
1856 if (FLAG_trace_debug_json) {
1857 PrintLn(request);
1858 PrintLn(response);
1859 }
1860
1861 // Get the running state.
1862 fun_name = v8::String::New("isRunning");
1863 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
1864 static const int kArgc = 1;
1865 v8::Handle<Value> argv[kArgc] = { response };
1866 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
1867 if (!try_catch.HasCaught()) {
1868 running = running_val->ToBoolean()->Value();
1869 }
1870 } else {
1871 // In case of failure the result text is the exception text.
1872 response = try_catch.Exception()->ToString();
1873 }
1874
1875 // Convert text result to C string.
1876 v8::String::Value val(response);
1877 Vector<uint16_t> str(reinterpret_cast<uint16_t*>(*val),
1878 response->Length());
1879
1880 // Return the result.
1881 SendMessage(str);
1882
1883 // Return from debug event processing if either the VM is put into the
1884 // runnning state (through a continue command) or auto continue is active
1885 // and there are no more commands queued.
1886 if (running || (auto_continue && !HasCommands())) {
1887 return;
1888 }
1889 }
1890}
1891
1892
iposva@chromium.org245aa852009-02-10 00:49:54 +00001893void Debugger::SetEventListener(Handle<Object> callback,
1894 Handle<Object> data) {
1895 HandleScope scope;
1896
1897 // Clear the global handles for the event listener and the event listener data
1898 // object.
1899 if (!event_listener_.is_null()) {
1900 GlobalHandles::Destroy(
1901 reinterpret_cast<Object**>(event_listener_.location()));
1902 event_listener_ = Handle<Object>();
1903 }
1904 if (!event_listener_data_.is_null()) {
1905 GlobalHandles::Destroy(
1906 reinterpret_cast<Object**>(event_listener_data_.location()));
1907 event_listener_data_ = Handle<Object>();
1908 }
1909
1910 // If there is a new debug event listener register it together with its data
1911 // object.
1912 if (!callback->IsUndefined() && !callback->IsNull()) {
1913 event_listener_ = Handle<Object>::cast(GlobalHandles::Create(*callback));
1914 if (data.is_null()) {
1915 data = Factory::undefined_value();
1916 }
1917 event_listener_data_ = Handle<Object>::cast(GlobalHandles::Create(*data));
1918 }
1919
ager@chromium.org71daaf62009-04-01 07:22:49 +00001920 // Unload the debugger if event listener cleared.
1921 if (callback->IsUndefined()) {
1922 UnloadDebugger();
1923 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001924}
1925
1926
ager@chromium.org41826e72009-03-30 13:30:57 +00001927void Debugger::SetMessageHandler(v8::DebugMessageHandler handler, void* data,
1928 bool message_handler_thread) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00001929 ScopedLock with(debugger_access_);
1930
ager@chromium.org381abbb2009-02-25 13:23:22 +00001931 message_handler_ = handler;
1932 message_handler_data_ = data;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001933 if (handler != NULL) {
1934 if (!message_thread_ && message_handler_thread) {
1935 message_thread_ = new DebugMessageThread();
1936 message_thread_->Start();
1937 }
1938 } else {
1939 // Indicate that the message handler was recently cleared.
1940 message_handler_cleared_ = true;
1941
1942 // Send an empty command to the debugger if in a break to make JavaScript
1943 // run again if the debugger is closed.
1944 if (Debug::InDebugger()) {
1945 ProcessCommand(Vector<const uint16_t>::empty());
1946 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001947 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001948}
1949
1950
ager@chromium.org381abbb2009-02-25 13:23:22 +00001951void Debugger::SetHostDispatchHandler(v8::DebugHostDispatchHandler handler,
1952 void* data) {
1953 host_dispatch_handler_ = handler;
1954 host_dispatch_handler_data_ = data;
1955}
1956
1957
ager@chromium.org41826e72009-03-30 13:30:57 +00001958// Calls the registered debug message handler. This callback is part of the
1959// public API. Messages are kept internally as Vector<uint16_t> strings, which
1960// are allocated in various places and deallocated by the calling function
1961// sometime after this call.
1962void Debugger::InvokeMessageHandler(Vector<uint16_t> message) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00001963 ScopedLock with(debugger_access_);
1964
ager@chromium.org381abbb2009-02-25 13:23:22 +00001965 if (message_handler_ != NULL) {
1966 message_handler_(message.start(), message.length(), message_handler_data_);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001967 }
1968}
1969
1970
ager@chromium.org41826e72009-03-30 13:30:57 +00001971void Debugger::SendMessage(Vector<uint16_t> message) {
1972 if (message_thread_ == NULL) {
1973 // If there is no message thread just invoke the message handler from the
1974 // V8 thread.
1975 InvokeMessageHandler(message);
1976 } else {
1977 // Put a copy of the message coming from V8 on the queue. The new copy of
1978 // the event string is destroyed by the message thread.
1979 Vector<uint16_t> message_copy = message.Clone();
1980 Logger::DebugTag("Put message on event message_queue.");
1981 message_queue_.Put(message_copy);
1982 message_received_->Signal();
1983 }
1984}
1985
1986
1987bool Debugger::SendEventMessage(Handle<Object> event_data) {
1988 v8::HandleScope scope;
1989 // Call toJSONProtocol on the debug event object.
1990 v8::Local<v8::Object> api_event_data =
1991 v8::Utils::ToLocal(Handle<JSObject>::cast(event_data));
1992 v8::Local<v8::String> fun_name = v8::String::New("toJSONProtocol");
1993 v8::Local<v8::Function> fun =
1994 v8::Function::Cast(*api_event_data->Get(fun_name));
1995 v8::TryCatch try_catch;
1996 v8::Local<v8::Value> json_event = *fun->Call(api_event_data, 0, NULL);
1997 v8::Local<v8::String> json_event_string;
1998 if (!try_catch.HasCaught()) {
1999 if (!json_event->IsUndefined()) {
2000 json_event_string = json_event->ToString();
2001 if (FLAG_trace_debug_json) {
2002 PrintLn(json_event_string);
2003 }
2004 v8::String::Value val(json_event_string);
2005 Vector<uint16_t> str(reinterpret_cast<uint16_t*>(*val),
2006 json_event_string->Length());
2007 SendMessage(str);
2008 } else {
2009 SendMessage(Vector<uint16_t>::empty());
2010 }
2011 } else {
2012 PrintLn(try_catch.Exception());
2013 return false;
2014 }
2015 return true;
2016}
2017
2018
2019// Puts a command coming from the public API on the queue. Creates
2020// a copy of the command string managed by the debugger. Up to this
2021// point, the command data was managed by the API client. Called
2022// by the API client thread. This is where the API client hands off
2023// processing of the command to the DebugMessageThread thread.
2024// The new copy of the command is destroyed in HandleCommand().
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002025void Debugger::ProcessCommand(Vector<const uint16_t> command) {
ager@chromium.org41826e72009-03-30 13:30:57 +00002026 // Make a copy of the command. Need to cast away const for Clone to work.
2027 Vector<uint16_t> command_copy =
2028 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
2029 command.length()).Clone();
2030 Logger::DebugTag("Put command on command_queue.");
2031 command_queue_.Put(command_copy);
2032 command_received_->Signal();
2033 if (!Debug::InDebugger()) {
2034 StackGuard::DebugCommand();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002035 }
2036}
2037
2038
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002039bool Debugger::HasCommands() {
ager@chromium.org41826e72009-03-30 13:30:57 +00002040 return !command_queue_.IsEmpty();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002041}
2042
2043
ager@chromium.org381abbb2009-02-25 13:23:22 +00002044void Debugger::ProcessHostDispatch(void* dispatch) {
ager@chromium.org41826e72009-03-30 13:30:57 +00002045// Puts a host dispatch comming from the public API on the queue.
2046 uint16_t hack[3];
2047 hack[0] = 0;
2048 hack[1] = reinterpret_cast<uint32_t>(dispatch) >> 16;
2049 hack[2] = reinterpret_cast<uint32_t>(dispatch) & 0xFFFF;
2050 Logger::DebugTag("Put dispatch on command_queue.");
2051 command_queue_.Put(Vector<uint16_t>(hack, 3).Clone());
2052 command_received_->Signal();
ager@chromium.org381abbb2009-02-25 13:23:22 +00002053}
2054
2055
ager@chromium.org71daaf62009-04-01 07:22:49 +00002056bool Debugger::IsDebuggerActive() {
2057 ScopedLock with(debugger_access_);
2058
2059 return message_handler_ != NULL || !event_listener_.is_null();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002060}
2061
2062
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002063Handle<Object> Debugger::Call(Handle<JSFunction> fun,
2064 Handle<Object> data,
2065 bool* pending_exception) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002066 // When calling functions in the debugger prevent it from beeing unloaded.
2067 Debugger::never_unload_debugger_ = true;
2068
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002069 // Enter the debugger.
2070 EnterDebugger debugger;
2071 if (debugger.FailedToEnter() || !debugger.HasJavaScriptFrames()) {
2072 return Factory::undefined_value();
2073 }
2074
2075 // Create the execution state.
2076 bool caught_exception = false;
2077 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2078 if (caught_exception) {
2079 return Factory::undefined_value();
2080 }
2081
2082 static const int kArgc = 2;
2083 Object** argv[kArgc] = { exec_state.location(), data.location() };
2084 Handle<Object> result = Execution::Call(fun, Factory::undefined_value(),
2085 kArgc, argv, pending_exception);
2086 return result;
2087}
2088
2089
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002090bool Debugger::StartAgent(const char* name, int port) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002091 if (Socket::Setup()) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002092 agent_ = new DebuggerAgent(name, port);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002093 agent_->Start();
2094 return true;
2095 }
2096
2097 return false;
2098}
2099
2100
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002101void Debugger::StopAgent() {
2102 if (agent_ != NULL) {
2103 agent_->Shutdown();
2104 agent_->Join();
2105 delete agent_;
2106 agent_ = NULL;
2107 }
2108}
2109
2110
ager@chromium.org41826e72009-03-30 13:30:57 +00002111void Debugger::TearDown() {
2112 if (message_thread_ != NULL) {
2113 message_thread_->Stop();
2114 delete message_thread_;
2115 message_thread_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002116 }
2117}
2118
2119
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002120void DebugMessageThread::Run() {
kasper.lund7276f142008-07-30 08:49:36 +00002121 // Sends debug events to an installed debugger message callback.
ager@chromium.org41826e72009-03-30 13:30:57 +00002122 while (keep_running_) {
kasper.lund7276f142008-07-30 08:49:36 +00002123 // Wait and Get are paired so that semaphore count equals queue length.
ager@chromium.org41826e72009-03-30 13:30:57 +00002124 Debugger::message_received_->Wait();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002125 Logger::DebugTag("Get message from event message_queue.");
ager@chromium.org41826e72009-03-30 13:30:57 +00002126 Vector<uint16_t> message = Debugger::message_queue_.Get();
kasper.lund7276f142008-07-30 08:49:36 +00002127 if (message.length() > 0) {
ager@chromium.org41826e72009-03-30 13:30:57 +00002128 Debugger::InvokeMessageHandler(message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002129 }
2130 }
2131}
2132
2133
ager@chromium.org41826e72009-03-30 13:30:57 +00002134void DebugMessageThread::Stop() {
2135 keep_running_ = false;
2136 Debugger::SendMessage(Vector<uint16_t>(NULL, 0));
2137 Join();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002138}
2139
kasper.lund7276f142008-07-30 08:49:36 +00002140
2141MessageQueue::MessageQueue(int size) : start_(0), end_(0), size_(size) {
2142 messages_ = NewArray<Vector<uint16_t> >(size);
2143}
2144
2145
2146MessageQueue::~MessageQueue() {
2147 DeleteArray(messages_);
2148}
2149
2150
2151Vector<uint16_t> MessageQueue::Get() {
2152 ASSERT(!IsEmpty());
2153 int result = start_;
2154 start_ = (start_ + 1) % size_;
2155 return messages_[result];
2156}
2157
2158
2159void MessageQueue::Put(const Vector<uint16_t>& message) {
2160 if ((end_ + 1) % size_ == start_) {
2161 Expand();
2162 }
2163 messages_[end_] = message;
2164 end_ = (end_ + 1) % size_;
2165}
2166
2167
2168void MessageQueue::Expand() {
2169 MessageQueue new_queue(size_ * 2);
2170 while (!IsEmpty()) {
2171 new_queue.Put(Get());
2172 }
2173 Vector<uint16_t>* array_to_free = messages_;
2174 *this = new_queue;
2175 new_queue.messages_ = array_to_free;
2176 // Automatic destructor called on new_queue, freeing array_to_free.
2177}
2178
2179
2180LockingMessageQueue::LockingMessageQueue(int size) : queue_(size) {
2181 lock_ = OS::CreateMutex();
2182}
2183
2184
2185LockingMessageQueue::~LockingMessageQueue() {
2186 delete lock_;
2187}
2188
2189
2190bool LockingMessageQueue::IsEmpty() const {
2191 ScopedLock sl(lock_);
2192 return queue_.IsEmpty();
2193}
2194
2195
2196Vector<uint16_t> LockingMessageQueue::Get() {
2197 ScopedLock sl(lock_);
2198 Vector<uint16_t> result = queue_.Get();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002199 Logger::DebugEvent("Get", result);
kasper.lund7276f142008-07-30 08:49:36 +00002200 return result;
2201}
2202
2203
2204void LockingMessageQueue::Put(const Vector<uint16_t>& message) {
2205 ScopedLock sl(lock_);
2206 queue_.Put(message);
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002207 Logger::DebugEvent("Put", message);
kasper.lund7276f142008-07-30 08:49:36 +00002208}
2209
2210
2211void LockingMessageQueue::Clear() {
2212 ScopedLock sl(lock_);
2213 queue_.Clear();
2214}
2215
2216
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002217} } // namespace v8::internal