blob: 18536f5c7a9fe6cba3403d4cf98546db41c4143e [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"
kasperl@chromium.org71affb52009-05-26 05:44:31 +000034#include "compilation-cache.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035#include "compiler.h"
36#include "debug.h"
37#include "execution.h"
38#include "global-handles.h"
ager@chromium.org65dad4b2009-04-23 08:48:43 +000039#include "ic.h"
40#include "ic-inl.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000041#include "natives.h"
42#include "stub-cache.h"
kasper.lund7276f142008-07-30 08:49:36 +000043#include "log.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000044
ager@chromium.org5ec48922009-05-05 07:25:34 +000045#include "../include/v8-debug.h"
46
kasperl@chromium.org71affb52009-05-26 05:44:31 +000047namespace v8 {
48namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000049
ager@chromium.org65dad4b2009-04-23 08:48:43 +000050#ifdef ENABLE_DEBUGGER_SUPPORT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000051static void PrintLn(v8::Local<v8::Value> value) {
52 v8::Local<v8::String> s = value->ToString();
53 char* data = NewArray<char>(s->Length() + 1);
54 if (data == NULL) {
55 V8::FatalProcessOutOfMemory("PrintLn");
56 return;
57 }
58 s->WriteAscii(data);
59 PrintF("%s\n", data);
60 DeleteArray(data);
61}
62
63
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000064static Handle<Code> ComputeCallDebugBreak(int argc) {
65 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugBreak(argc), Code);
66}
67
68
69static Handle<Code> ComputeCallDebugPrepareStepIn(int argc) {
70 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugPrepareStepIn(argc), Code);
71}
72
73
74BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
75 BreakLocatorType type) {
76 debug_info_ = debug_info;
77 type_ = type;
78 reloc_iterator_ = NULL;
79 reloc_iterator_original_ = NULL;
80 Reset(); // Initialize the rest of the member variables.
81}
82
83
84BreakLocationIterator::~BreakLocationIterator() {
85 ASSERT(reloc_iterator_ != NULL);
86 ASSERT(reloc_iterator_original_ != NULL);
87 delete reloc_iterator_;
88 delete reloc_iterator_original_;
89}
90
91
92void BreakLocationIterator::Next() {
93 AssertNoAllocation nogc;
94 ASSERT(!RinfoDone());
95
96 // Iterate through reloc info for code and original code stopping at each
97 // breakable code target.
98 bool first = break_point_ == -1;
99 while (!RinfoDone()) {
100 if (!first) RinfoNext();
101 first = false;
102 if (RinfoDone()) return;
103
ager@chromium.org236ad962008-09-25 09:45:57 +0000104 // Whenever a statement position or (plain) position is passed update the
105 // current value of these.
106 if (RelocInfo::IsPosition(rmode())) {
107 if (RelocInfo::IsStatementPosition(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000108 statement_position_ =
109 rinfo()->data() - debug_info_->shared()->start_position();
110 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000111 // Always update the position as we don't want that to be before the
112 // statement position.
113 position_ = rinfo()->data() - debug_info_->shared()->start_position();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000114 ASSERT(position_ >= 0);
115 ASSERT(statement_position_ >= 0);
116 }
117
118 // Check for breakable code target. Look in the original code as setting
119 // break points can cause the code targets in the running (debugged) code to
120 // be of a different kind than in the original code.
ager@chromium.org236ad962008-09-25 09:45:57 +0000121 if (RelocInfo::IsCodeTarget(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000122 Address target = original_rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000123 Code* code = Code::GetCodeFromTargetAddress(target);
ager@chromium.org236ad962008-09-25 09:45:57 +0000124 if (code->is_inline_cache_stub() || RelocInfo::IsConstructCall(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000125 break_point_++;
126 return;
127 }
128 if (code->kind() == Code::STUB) {
129 if (type_ == ALL_BREAK_LOCATIONS) {
130 if (Debug::IsBreakStub(code)) {
131 break_point_++;
132 return;
133 }
134 } else {
135 ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
136 if (Debug::IsSourceBreakStub(code)) {
137 break_point_++;
138 return;
139 }
140 }
141 }
142 }
143
144 // Check for break at return.
ager@chromium.org236ad962008-09-25 09:45:57 +0000145 if (RelocInfo::IsJSReturn(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000146 // Set the positions to the end of the function.
147 if (debug_info_->shared()->HasSourceCode()) {
148 position_ = debug_info_->shared()->end_position() -
149 debug_info_->shared()->start_position();
150 } else {
151 position_ = 0;
152 }
153 statement_position_ = position_;
154 break_point_++;
155 return;
156 }
157 }
158}
159
160
161void BreakLocationIterator::Next(int count) {
162 while (count > 0) {
163 Next();
164 count--;
165 }
166}
167
168
169// Find the break point closest to the supplied address.
170void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
171 // Run through all break points to locate the one closest to the address.
172 int closest_break_point = 0;
173 int distance = kMaxInt;
174 while (!Done()) {
175 // Check if this break point is closer that what was previously found.
176 if (this->pc() < pc && pc - this->pc() < distance) {
177 closest_break_point = break_point();
178 distance = pc - this->pc();
179 // Check whether we can't get any closer.
180 if (distance == 0) break;
181 }
182 Next();
183 }
184
185 // Move to the break point found.
186 Reset();
187 Next(closest_break_point);
188}
189
190
191// Find the break point closest to the supplied source position.
192void BreakLocationIterator::FindBreakLocationFromPosition(int position) {
193 // Run through all break points to locate the one closest to the source
194 // position.
195 int closest_break_point = 0;
196 int distance = kMaxInt;
197 while (!Done()) {
198 // Check if this break point is closer that what was previously found.
199 if (position <= statement_position() &&
200 statement_position() - position < distance) {
201 closest_break_point = break_point();
202 distance = statement_position() - position;
203 // Check whether we can't get any closer.
204 if (distance == 0) break;
205 }
206 Next();
207 }
208
209 // Move to the break point found.
210 Reset();
211 Next(closest_break_point);
212}
213
214
215void BreakLocationIterator::Reset() {
216 // Create relocation iterators for the two code objects.
217 if (reloc_iterator_ != NULL) delete reloc_iterator_;
218 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
219 reloc_iterator_ = new RelocIterator(debug_info_->code());
220 reloc_iterator_original_ = new RelocIterator(debug_info_->original_code());
221
222 // Position at the first break point.
223 break_point_ = -1;
224 position_ = 1;
225 statement_position_ = 1;
226 Next();
227}
228
229
230bool BreakLocationIterator::Done() const {
231 return RinfoDone();
232}
233
234
235void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
236 // If there is not already a real break point here patch code with debug
237 // break.
238 if (!HasBreakPoint()) {
239 SetDebugBreak();
240 }
241 ASSERT(IsDebugBreak());
242 // Set the break point information.
243 DebugInfo::SetBreakPoint(debug_info_, code_position(),
244 position(), statement_position(),
245 break_point_object);
246}
247
248
249void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
250 // Clear the break point information.
251 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
252 // If there are no more break points here remove the debug break.
253 if (!HasBreakPoint()) {
254 ClearDebugBreak();
255 ASSERT(!IsDebugBreak());
256 }
257}
258
259
260void BreakLocationIterator::SetOneShot() {
261 // If there is a real break point here no more to do.
262 if (HasBreakPoint()) {
263 ASSERT(IsDebugBreak());
264 return;
265 }
266
267 // Patch code with debug break.
268 SetDebugBreak();
269}
270
271
272void BreakLocationIterator::ClearOneShot() {
273 // If there is a real break point here no more to do.
274 if (HasBreakPoint()) {
275 ASSERT(IsDebugBreak());
276 return;
277 }
278
279 // Patch code removing debug break.
280 ClearDebugBreak();
281 ASSERT(!IsDebugBreak());
282}
283
284
285void BreakLocationIterator::SetDebugBreak() {
286 // If there is already a break point here just return. This might happen if
v8.team.kasperl727e9952008-09-02 14:56:44 +0000287 // the same code is flooded with break points twice. Flooding the same
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000288 // function twice might happen when stepping in a function with an exception
289 // handler as the handler and the function is the same.
290 if (IsDebugBreak()) {
291 return;
292 }
293
ager@chromium.org236ad962008-09-25 09:45:57 +0000294 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000295 // Patch the frame exit code with a break point.
296 SetDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000297 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000298 // Patch the IC call.
299 SetDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000300 }
301 ASSERT(IsDebugBreak());
302}
303
304
305void BreakLocationIterator::ClearDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000306 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000307 // Restore the frame exit code.
308 ClearDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000309 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000310 // Patch the IC call.
311 ClearDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000312 }
313 ASSERT(!IsDebugBreak());
314}
315
316
317void BreakLocationIterator::PrepareStepIn() {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000318 HandleScope scope;
319
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000320 // Step in can only be prepared if currently positioned on an IC call or
321 // construct call.
322 Address target = rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000323 Code* code = Code::GetCodeFromTargetAddress(target);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000324 if (code->is_call_stub()) {
325 // Step in through IC call is handled by the runtime system. Therefore make
326 // sure that the any current IC is cleared and the runtime system is
327 // called. If the executing code has a debug break at the location change
328 // the call in the original code as it is the code there that will be
329 // executed in place of the debug break call.
330 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count());
331 if (IsDebugBreak()) {
332 original_rinfo()->set_target_address(stub->entry());
333 } else {
334 rinfo()->set_target_address(stub->entry());
335 }
336 } else {
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000337 // Step in through construct call requires no changes to the running code.
338 // Step in through getters/setters should already be prepared as well
339 // because caller of this function (Debug::PrepareStep) is expected to
340 // flood the top frame's function with one shot breakpoints.
341 ASSERT(RelocInfo::IsConstructCall(rmode()) || code->is_inline_cache_stub());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000342 }
343}
344
345
346// Check whether the break point is at a position which will exit the function.
347bool BreakLocationIterator::IsExit() const {
ager@chromium.org236ad962008-09-25 09:45:57 +0000348 return (RelocInfo::IsJSReturn(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000349}
350
351
352bool BreakLocationIterator::HasBreakPoint() {
353 return debug_info_->HasBreakPoint(code_position());
354}
355
356
357// Check whether there is a debug break at the current position.
358bool BreakLocationIterator::IsDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000359 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000360 return IsDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000361 } else {
362 return Debug::IsDebugBreak(rinfo()->target_address());
363 }
364}
365
366
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000367void BreakLocationIterator::SetDebugBreakAtIC() {
368 // Patch the original code with the current address as the current address
369 // might have changed by the inline caching since the code was copied.
370 original_rinfo()->set_target_address(rinfo()->target_address());
371
372 RelocInfo::Mode mode = rmode();
373 if (RelocInfo::IsCodeTarget(mode)) {
374 Address target = rinfo()->target_address();
375 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
376
377 // Patch the code to invoke the builtin debug break function matching the
378 // calling convention used by the call site.
379 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(code, mode));
380 rinfo()->set_target_address(dbgbrk_code->entry());
381
382 // For stubs that refer back to an inlined version clear the cached map for
383 // the inlined case to always go through the IC. As long as the break point
384 // is set the patching performed by the runtime system will take place in
385 // the code copy and will therefore have no effect on the running code
386 // keeping it from using the inlined code.
ager@chromium.org5ec48922009-05-05 07:25:34 +0000387 if (code->is_keyed_load_stub()) KeyedLoadIC::ClearInlinedVersion(pc());
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000388 if (code->is_keyed_store_stub()) KeyedStoreIC::ClearInlinedVersion(pc());
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000389 }
390}
391
392
393void BreakLocationIterator::ClearDebugBreakAtIC() {
394 // Patch the code to the original invoke.
395 rinfo()->set_target_address(original_rinfo()->target_address());
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000396
397 RelocInfo::Mode mode = rmode();
398 if (RelocInfo::IsCodeTarget(mode)) {
399 Address target = original_rinfo()->target_address();
400 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
401
402 // Restore the inlined version of keyed stores to get back to the
403 // fast case. We need to patch back the keyed store because no
404 // patching happens when running normally. For keyed loads, the
405 // map check will get patched back when running normally after ICs
406 // have been cleared at GC.
407 if (code->is_keyed_store_stub()) KeyedStoreIC::RestoreInlinedVersion(pc());
408 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000409}
410
411
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000412Object* BreakLocationIterator::BreakPointObjects() {
413 return debug_info_->GetBreakPointObjects(code_position());
414}
415
416
ager@chromium.org381abbb2009-02-25 13:23:22 +0000417// Clear out all the debug break code. This is ONLY supposed to be used when
418// shutting down the debugger as it will leave the break point information in
419// DebugInfo even though the code is patched back to the non break point state.
420void BreakLocationIterator::ClearAllDebugBreak() {
421 while (!Done()) {
422 ClearDebugBreak();
423 Next();
424 }
425}
426
427
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000428bool BreakLocationIterator::RinfoDone() const {
429 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
430 return reloc_iterator_->done();
431}
432
433
434void BreakLocationIterator::RinfoNext() {
435 reloc_iterator_->next();
436 reloc_iterator_original_->next();
437#ifdef DEBUG
438 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
439 if (!reloc_iterator_->done()) {
440 ASSERT(rmode() == original_rmode());
441 }
442#endif
443}
444
445
446bool Debug::has_break_points_ = false;
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000447ScriptCache* Debug::script_cache_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000448DebugInfoListNode* Debug::debug_info_list_ = NULL;
449
450
451// Threading support.
452void Debug::ThreadInit() {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000453 thread_local_.break_count_ = 0;
454 thread_local_.break_id_ = 0;
455 thread_local_.break_frame_id_ = StackFrame::NO_ID;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000456 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +0000457 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000458 thread_local_.step_count_ = 0;
459 thread_local_.last_fp_ = 0;
460 thread_local_.step_into_fp_ = 0;
461 thread_local_.after_break_target_ = 0;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000462 thread_local_.debugger_entry_ = NULL;
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000463 thread_local_.pending_interrupts_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000464}
465
466
467JSCallerSavedBuffer Debug::registers_;
468Debug::ThreadLocal Debug::thread_local_;
469
470
471char* Debug::ArchiveDebug(char* storage) {
472 char* to = storage;
473 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
474 to += sizeof(ThreadLocal);
475 memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
476 ThreadInit();
477 ASSERT(to <= storage + ArchiveSpacePerThread());
478 return storage + ArchiveSpacePerThread();
479}
480
481
482char* Debug::RestoreDebug(char* storage) {
483 char* from = storage;
484 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
485 from += sizeof(ThreadLocal);
486 memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
487 ASSERT(from <= storage + ArchiveSpacePerThread());
488 return storage + ArchiveSpacePerThread();
489}
490
491
492int Debug::ArchiveSpacePerThread() {
493 return sizeof(ThreadLocal) + sizeof(registers_);
494}
495
496
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000497// Default break enabled.
498bool Debug::disable_break_ = false;
499
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000500// Default call debugger on uncaught exception.
501bool Debug::break_on_exception_ = false;
502bool Debug::break_on_uncaught_exception_ = true;
503
504Handle<Context> Debug::debug_context_ = Handle<Context>();
505Code* Debug::debug_break_return_entry_ = NULL;
506Code* Debug::debug_break_return_ = NULL;
507
508
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000509void ScriptCache::Add(Handle<Script> script) {
510 // Create an entry in the hash map for the script.
511 int id = Smi::cast(script->id())->value();
512 HashMap::Entry* entry =
513 HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
514 if (entry->value != NULL) {
515 ASSERT(*script == *reinterpret_cast<Script**>(entry->value));
516 return;
517 }
518
519 // Globalize the script object, make it weak and use the location of the
520 // global handle as the value in the hash map.
521 Handle<Script> script_ =
522 Handle<Script>::cast((GlobalHandles::Create(*script)));
523 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(script_.location()),
524 this, ScriptCache::HandleWeakScript);
525 entry->value = script_.location();
526}
527
528
529Handle<FixedArray> ScriptCache::GetScripts() {
530 Handle<FixedArray> instances = Factory::NewFixedArray(occupancy());
531 int count = 0;
532 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
533 ASSERT(entry->value != NULL);
534 if (entry->value != NULL) {
535 instances->set(count, *reinterpret_cast<Script**>(entry->value));
536 count++;
537 }
538 }
539 return instances;
540}
541
542
543void ScriptCache::ProcessCollectedScripts() {
544 for (int i = 0; i < collected_scripts_.length(); i++) {
545 Debugger::OnScriptCollected(collected_scripts_[i]);
546 }
547 collected_scripts_.Clear();
548}
549
550
551void ScriptCache::Clear() {
552 // Iterate the script cache to get rid of all the weak handles.
553 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
554 ASSERT(entry != NULL);
555 Object** location = reinterpret_cast<Object**>(entry->value);
556 ASSERT((*location)->IsScript());
557 GlobalHandles::ClearWeakness(location);
558 GlobalHandles::Destroy(location);
559 }
560 // Clear the content of the hash map.
561 HashMap::Clear();
562}
563
564
565void ScriptCache::HandleWeakScript(v8::Persistent<v8::Value> obj, void* data) {
566 ScriptCache* script_cache = reinterpret_cast<ScriptCache*>(data);
567 // Find the location of the global handle.
568 Script** location =
569 reinterpret_cast<Script**>(Utils::OpenHandle(*obj).location());
570 ASSERT((*location)->IsScript());
571
572 // Remove the entry from the cache.
573 int id = Smi::cast((*location)->id())->value();
574 script_cache->Remove(reinterpret_cast<void*>(id), Hash(id));
575 script_cache->collected_scripts_.Add(id);
576
577 // Clear the weak handle.
578 obj.Dispose();
579 obj.Clear();
580}
581
582
583void Debug::Setup(bool create_heap_objects) {
584 ThreadInit();
585 if (create_heap_objects) {
586 // Get code to handle entry to debug break on return.
587 debug_break_return_entry_ =
588 Builtins::builtin(Builtins::Return_DebugBreakEntry);
589 ASSERT(debug_break_return_entry_->IsCode());
590
591 // Get code to handle debug break on return.
592 debug_break_return_ =
593 Builtins::builtin(Builtins::Return_DebugBreak);
594 ASSERT(debug_break_return_->IsCode());
595 }
596}
597
598
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000599void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000600 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
601 RemoveDebugInfo(node->debug_info());
602#ifdef DEBUG
603 node = Debug::debug_info_list_;
604 while (node != NULL) {
605 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
606 node = node->next();
607 }
608#endif
609}
610
611
612DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
613 // Globalize the request debug info object and make it weak.
614 debug_info_ = Handle<DebugInfo>::cast((GlobalHandles::Create(debug_info)));
615 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
616 this, Debug::HandleWeakDebugInfo);
617}
618
619
620DebugInfoListNode::~DebugInfoListNode() {
621 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
622}
623
624
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000625bool Debug::CompileDebuggerScript(int index) {
626 HandleScope scope;
627
kasper.lund44510672008-07-25 07:37:58 +0000628 // Bail out if the index is invalid.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000629 if (index == -1) {
630 return false;
631 }
kasper.lund44510672008-07-25 07:37:58 +0000632
633 // Find source and name for the requested script.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000634 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
635 Vector<const char> name = Natives::GetScriptName(index);
636 Handle<String> script_name = Factory::NewStringFromAscii(name);
637
638 // Compile the script.
639 bool allow_natives_syntax = FLAG_allow_natives_syntax;
640 FLAG_allow_natives_syntax = true;
641 Handle<JSFunction> boilerplate;
642 boilerplate = Compiler::Compile(source_code, script_name, 0, 0, NULL, NULL);
643 FLAG_allow_natives_syntax = allow_natives_syntax;
644
645 // Silently ignore stack overflows during compilation.
646 if (boilerplate.is_null()) {
647 ASSERT(Top::has_pending_exception());
648 Top::clear_pending_exception();
649 return false;
650 }
651
kasper.lund44510672008-07-25 07:37:58 +0000652 // Execute the boilerplate function in the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000653 Handle<Context> context = Top::global_context();
kasper.lund44510672008-07-25 07:37:58 +0000654 bool caught_exception = false;
655 Handle<JSFunction> function =
656 Factory::NewFunctionFromBoilerplate(boilerplate, context);
657 Handle<Object> result =
658 Execution::TryCall(function, Handle<Object>(context->global()),
659 0, NULL, &caught_exception);
660
661 // Check for caught exceptions.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000662 if (caught_exception) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000663 Handle<Object> message = MessageHandler::MakeMessageObject(
664 "error_loading_debugger", NULL, HandleVector<Object>(&result, 1),
665 Handle<String>());
666 MessageHandler::ReportMessage(NULL, message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000667 return false;
668 }
669
kasper.lund44510672008-07-25 07:37:58 +0000670 // Mark this script as native and return successfully.
671 Handle<Script> script(Script::cast(function->shared()->script()));
ager@chromium.orge2902be2009-06-08 12:21:35 +0000672 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000673 return true;
674}
675
676
677bool Debug::Load() {
678 // Return if debugger is already loaded.
kasper.lund212ac232008-07-16 07:07:30 +0000679 if (IsLoaded()) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000680
kasper.lund44510672008-07-25 07:37:58 +0000681 // Bail out if we're already in the process of compiling the native
682 // JavaScript source code for the debugger.
mads.s.agercbaa0602008-08-14 13:41:48 +0000683 if (Debugger::compiling_natives() || Debugger::is_loading_debugger())
684 return false;
685 Debugger::set_loading_debugger(true);
kasper.lund44510672008-07-25 07:37:58 +0000686
687 // Disable breakpoints and interrupts while compiling and running the
688 // debugger scripts including the context creation code.
689 DisableBreak disable(true);
690 PostponeInterruptsScope postpone;
691
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000692 // Create the debugger context.
693 HandleScope scope;
kasper.lund44510672008-07-25 07:37:58 +0000694 Handle<Context> context =
695 Bootstrapper::CreateEnvironment(Handle<Object>::null(),
696 v8::Handle<ObjectTemplate>(),
697 NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000698
kasper.lund44510672008-07-25 07:37:58 +0000699 // Use the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000700 SaveContext save;
kasper.lund44510672008-07-25 07:37:58 +0000701 Top::set_context(*context);
kasper.lund44510672008-07-25 07:37:58 +0000702
703 // Expose the builtins object in the debugger context.
704 Handle<String> key = Factory::LookupAsciiSymbol("builtins");
705 Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
706 SetProperty(global, key, Handle<Object>(global->builtins()), NONE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000707
708 // Compile the JavaScript for the debugger in the debugger context.
709 Debugger::set_compiling_natives(true);
kasper.lund44510672008-07-25 07:37:58 +0000710 bool caught_exception =
711 !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
712 !CompileDebuggerScript(Natives::GetIndex("debug"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000713 Debugger::set_compiling_natives(false);
714
mads.s.agercbaa0602008-08-14 13:41:48 +0000715 // Make sure we mark the debugger as not loading before we might
716 // return.
717 Debugger::set_loading_debugger(false);
718
kasper.lund44510672008-07-25 07:37:58 +0000719 // Check for caught exceptions.
720 if (caught_exception) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000721
722 // Debugger loaded.
kasper.lund44510672008-07-25 07:37:58 +0000723 debug_context_ = Handle<Context>::cast(GlobalHandles::Create(*context));
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000724
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000725 return true;
726}
727
728
729void Debug::Unload() {
730 // Return debugger is not loaded.
731 if (!IsLoaded()) {
732 return;
733 }
734
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000735 // Clear the script cache.
736 DestroyScriptCache();
737
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000738 // Clear debugger context global handle.
739 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_context_.location()));
740 debug_context_ = Handle<Context>();
741}
742
743
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000744// Set the flag indicating that preemption happened during debugging.
745void Debug::PreemptionWhileInDebugger() {
746 ASSERT(InDebugger());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000747 Debug::set_interrupts_pending(PREEMPT);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000748}
749
750
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000751void Debug::Iterate(ObjectVisitor* v) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000752 v->VisitPointer(bit_cast<Object**, Code**>(&(debug_break_return_entry_)));
753 v->VisitPointer(bit_cast<Object**, Code**>(&(debug_break_return_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000754}
755
756
757Object* Debug::Break(Arguments args) {
758 HandleScope scope;
mads.s.ager31e71382008-08-13 09:32:07 +0000759 ASSERT(args.length() == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000760
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000761 // Get the top-most JavaScript frame.
762 JavaScriptFrameIterator it;
763 JavaScriptFrame* frame = it.frame();
764
765 // Just continue if breaks are disabled or debugger cannot be loaded.
766 if (disable_break() || !Load()) {
767 SetAfterBreakTarget(frame);
mads.s.ager31e71382008-08-13 09:32:07 +0000768 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000769 }
770
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000771 // Enter the debugger.
772 EnterDebugger debugger;
773 if (debugger.FailedToEnter()) {
774 return Heap::undefined_value();
775 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000776
kasper.lund44510672008-07-25 07:37:58 +0000777 // Postpone interrupt during breakpoint processing.
778 PostponeInterruptsScope postpone;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000779
780 // Get the debug info (create it if it does not exist).
781 Handle<SharedFunctionInfo> shared =
782 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
783 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
784
785 // Find the break point where execution has stopped.
786 BreakLocationIterator break_location_iterator(debug_info,
787 ALL_BREAK_LOCATIONS);
788 break_location_iterator.FindBreakLocationFromAddress(frame->pc());
789
790 // Check whether step next reached a new statement.
791 if (!StepNextContinue(&break_location_iterator, frame)) {
792 // Decrease steps left if performing multiple steps.
793 if (thread_local_.step_count_ > 0) {
794 thread_local_.step_count_--;
795 }
796 }
797
798 // If there is one or more real break points check whether any of these are
799 // triggered.
800 Handle<Object> break_points_hit(Heap::undefined_value());
801 if (break_location_iterator.HasBreakPoint()) {
802 Handle<Object> break_point_objects =
803 Handle<Object>(break_location_iterator.BreakPointObjects());
804 break_points_hit = CheckBreakPoints(break_point_objects);
805 }
806
807 // Notify debugger if a real break point is triggered or if performing single
808 // stepping with no more steps to perform. Otherwise do another step.
809 if (!break_points_hit->IsUndefined() ||
810 (thread_local_.last_step_action_ != StepNone &&
811 thread_local_.step_count_ == 0)) {
812 // Clear all current stepping setup.
813 ClearStepping();
814
815 // Notify the debug event listeners.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000816 Debugger::OnDebugBreak(break_points_hit, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000817 } else if (thread_local_.last_step_action_ != StepNone) {
818 // Hold on to last step action as it is cleared by the call to
819 // ClearStepping.
820 StepAction step_action = thread_local_.last_step_action_;
821 int step_count = thread_local_.step_count_;
822
823 // Clear all current stepping setup.
824 ClearStepping();
825
826 // Set up for the remaining steps.
827 PrepareStep(step_action, step_count);
828 }
829
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000830 // Install jump to the call address which was overwritten.
831 SetAfterBreakTarget(frame);
832
mads.s.ager31e71382008-08-13 09:32:07 +0000833 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000834}
835
836
837// Check the break point objects for whether one or more are actually
838// triggered. This function returns a JSArray with the break point objects
839// which is triggered.
840Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
841 int break_points_hit_count = 0;
842 Handle<JSArray> break_points_hit = Factory::NewJSArray(1);
843
v8.team.kasperl727e9952008-09-02 14:56:44 +0000844 // If there are multiple break points they are in a FixedArray.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000845 ASSERT(!break_point_objects->IsUndefined());
846 if (break_point_objects->IsFixedArray()) {
847 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
848 for (int i = 0; i < array->length(); i++) {
849 Handle<Object> o(array->get(i));
850 if (CheckBreakPoint(o)) {
851 break_points_hit->SetElement(break_points_hit_count++, *o);
852 }
853 }
854 } else {
855 if (CheckBreakPoint(break_point_objects)) {
856 break_points_hit->SetElement(break_points_hit_count++,
857 *break_point_objects);
858 }
859 }
860
861 // Return undefined if no break points where triggered.
862 if (break_points_hit_count == 0) {
863 return Factory::undefined_value();
864 }
865 return break_points_hit;
866}
867
868
869// Check whether a single break point object is triggered.
870bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000871 HandleScope scope;
872
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000873 // Ignore check if break point object is not a JSObject.
874 if (!break_point_object->IsJSObject()) return true;
875
876 // Get the function CheckBreakPoint (defined in debug.js).
877 Handle<JSFunction> check_break_point =
878 Handle<JSFunction>(JSFunction::cast(
879 debug_context()->global()->GetProperty(
880 *Factory::LookupAsciiSymbol("IsBreakPointTriggered"))));
881
882 // Get the break id as an object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000883 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000884
885 // Call HandleBreakPointx.
886 bool caught_exception = false;
887 const int argc = 2;
888 Object** argv[argc] = {
889 break_id.location(),
890 reinterpret_cast<Object**>(break_point_object.location())
891 };
892 Handle<Object> result = Execution::TryCall(check_break_point,
893 Top::builtins(), argc, argv,
894 &caught_exception);
895
896 // If exception or non boolean result handle as not triggered
897 if (caught_exception || !result->IsBoolean()) {
898 return false;
899 }
900
901 // Return whether the break point is triggered.
902 return *result == Heap::true_value();
903}
904
905
906// Check whether the function has debug information.
907bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
908 return !shared->debug_info()->IsUndefined();
909}
910
911
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000912// Return the debug info for this function. EnsureDebugInfo must be called
913// prior to ensure the debug info has been generated for shared.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000914Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000915 ASSERT(HasDebugInfo(shared));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000916 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
917}
918
919
920void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
921 int source_position,
922 Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000923 HandleScope scope;
924
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000925 if (!EnsureDebugInfo(shared)) {
926 // Return if retrieving debug info failed.
927 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000928 }
929
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000930 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000931 // Source positions starts with zero.
932 ASSERT(source_position >= 0);
933
934 // Find the break point and change it.
935 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
936 it.FindBreakLocationFromPosition(source_position);
937 it.SetBreakPoint(break_point_object);
938
939 // At least one active break point now.
940 ASSERT(debug_info->GetBreakPointCount() > 0);
941}
942
943
944void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000945 HandleScope scope;
946
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000947 DebugInfoListNode* node = debug_info_list_;
948 while (node != NULL) {
949 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
950 break_point_object);
951 if (!result->IsUndefined()) {
952 // Get information in the break point.
953 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
954 Handle<DebugInfo> debug_info = node->debug_info();
955 Handle<SharedFunctionInfo> shared(debug_info->shared());
956 int source_position = break_point_info->statement_position()->value();
957
958 // Source positions starts with zero.
959 ASSERT(source_position >= 0);
960
961 // Find the break point and clear it.
962 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
963 it.FindBreakLocationFromPosition(source_position);
964 it.ClearBreakPoint(break_point_object);
965
966 // If there are no more break points left remove the debug info for this
967 // function.
968 if (debug_info->GetBreakPointCount() == 0) {
969 RemoveDebugInfo(debug_info);
970 }
971
972 return;
973 }
974 node = node->next();
975 }
976}
977
978
ager@chromium.org381abbb2009-02-25 13:23:22 +0000979void Debug::ClearAllBreakPoints() {
980 DebugInfoListNode* node = debug_info_list_;
981 while (node != NULL) {
982 // Remove all debug break code.
983 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
984 it.ClearAllDebugBreak();
985 node = node->next();
986 }
987
988 // Remove all debug info.
989 while (debug_info_list_ != NULL) {
990 RemoveDebugInfo(debug_info_list_->debug_info());
991 }
992}
993
994
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000995void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000996 // Make sure the function has setup the debug info.
997 if (!EnsureDebugInfo(shared)) {
998 // Return if we failed to retrieve the debug info.
999 return;
1000 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001001
1002 // Flood the function with break points.
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001003 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001004 while (!it.Done()) {
1005 it.SetOneShot();
1006 it.Next();
1007 }
1008}
1009
1010
1011void Debug::FloodHandlerWithOneShot() {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001012 // Iterate through the JavaScript stack looking for handlers.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001013 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001014 if (id == StackFrame::NO_ID) {
1015 // If there is no JavaScript stack don't do anything.
1016 return;
1017 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001018 for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) {
1019 JavaScriptFrame* frame = it.frame();
1020 if (frame->HasHandler()) {
1021 Handle<SharedFunctionInfo> shared =
1022 Handle<SharedFunctionInfo>(
1023 JSFunction::cast(frame->function())->shared());
1024 // Flood the function with the catch block with break points
1025 FloodWithOneShot(shared);
1026 return;
1027 }
1028 }
1029}
1030
1031
1032void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
1033 if (type == BreakUncaughtException) {
1034 break_on_uncaught_exception_ = enable;
1035 } else {
1036 break_on_exception_ = enable;
1037 }
1038}
1039
1040
1041void Debug::PrepareStep(StepAction step_action, int step_count) {
1042 HandleScope scope;
1043 ASSERT(Debug::InDebugger());
1044
1045 // Remember this step action and count.
1046 thread_local_.last_step_action_ = step_action;
1047 thread_local_.step_count_ = step_count;
1048
1049 // Get the frame where the execution has stopped and skip the debug frame if
1050 // any. The debug frame will only be present if execution was stopped due to
1051 // hitting a break point. In other situations (e.g. unhandled exception) the
1052 // debug frame is not present.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001053 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001054 if (id == StackFrame::NO_ID) {
1055 // If there is no JavaScript stack don't do anything.
1056 return;
1057 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001058 JavaScriptFrameIterator frames_it(id);
1059 JavaScriptFrame* frame = frames_it.frame();
1060
1061 // First of all ensure there is one-shot break points in the top handler
1062 // if any.
1063 FloodHandlerWithOneShot();
1064
1065 // If the function on the top frame is unresolved perform step out. This will
1066 // be the case when calling unknown functions and having the debugger stopped
1067 // in an unhandled exception.
1068 if (!frame->function()->IsJSFunction()) {
1069 // Step out: Find the calling JavaScript frame and flood it with
1070 // breakpoints.
1071 frames_it.Advance();
1072 // Fill the function to return to with one-shot break points.
1073 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1074 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1075 return;
1076 }
1077
1078 // Get the debug info (create it if it does not exist).
1079 Handle<SharedFunctionInfo> shared =
1080 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001081 if (!EnsureDebugInfo(shared)) {
1082 // Return if ensuring debug info failed.
1083 return;
1084 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001085 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1086
1087 // Find the break location where execution has stopped.
1088 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1089 it.FindBreakLocationFromAddress(frame->pc());
1090
1091 // Compute whether or not the target is a call target.
1092 bool is_call_target = false;
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001093 bool is_load_or_store = false;
1094 bool is_inline_cache_stub = false;
ager@chromium.org236ad962008-09-25 09:45:57 +00001095 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001096 Address target = it.rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001097 Code* code = Code::GetCodeFromTargetAddress(target);
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001098 if (code->is_call_stub()) {
1099 is_call_target = true;
1100 }
1101 if (code->is_inline_cache_stub()) {
1102 is_inline_cache_stub = true;
1103 is_load_or_store = !is_call_target;
1104 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001105 }
1106
v8.team.kasperl727e9952008-09-02 14:56:44 +00001107 // If this is the last break code target step out is the only possibility.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001108 if (it.IsExit() || step_action == StepOut) {
1109 // Step out: If there is a JavaScript caller frame, we need to
1110 // flood it with breakpoints.
1111 frames_it.Advance();
1112 if (!frames_it.done()) {
1113 // Fill the function to return to with one-shot break points.
1114 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1115 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1116 }
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001117 } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()))
1118 || step_action == StepNext || step_action == StepMin) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001119 // Step next or step min.
1120
1121 // Fill the current function with one-shot break points.
1122 FloodWithOneShot(shared);
1123
1124 // Remember source position and frame to handle step next.
1125 thread_local_.last_statement_position_ =
1126 debug_info->code()->SourceStatementPosition(frame->pc());
1127 thread_local_.last_fp_ = frame->fp();
1128 } else {
1129 // Fill the current function with one-shot break points even for step in on
1130 // a call target as the function called might be a native function for
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001131 // which step in will not stop. It also prepares for stepping in
1132 // getters/setters.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001133 FloodWithOneShot(shared);
1134
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001135 if (is_load_or_store) {
1136 // Remember source position and frame to handle step in getter/setter. If
1137 // there is a custom getter/setter it will be handled in
1138 // Object::Get/SetPropertyWithCallback, otherwise the step action will be
1139 // propagated on the next Debug::Break.
1140 thread_local_.last_statement_position_ =
1141 debug_info->code()->SourceStatementPosition(frame->pc());
1142 thread_local_.last_fp_ = frame->fp();
1143 }
1144
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001145 // Step in or Step in min
1146 it.PrepareStepIn();
1147 ActivateStepIn(frame);
1148 }
1149}
1150
1151
1152// Check whether the current debug break should be reported to the debugger. It
1153// is used to have step next and step in only report break back to the debugger
1154// if on a different frame or in a different statement. In some situations
1155// there will be several break points in the same statement when the code is
v8.team.kasperl727e9952008-09-02 14:56:44 +00001156// flooded with one-shot break points. This function helps to perform several
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001157// steps before reporting break back to the debugger.
1158bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
1159 JavaScriptFrame* frame) {
1160 // If the step last action was step next or step in make sure that a new
1161 // statement is hit.
1162 if (thread_local_.last_step_action_ == StepNext ||
1163 thread_local_.last_step_action_ == StepIn) {
1164 // Never continue if returning from function.
1165 if (break_location_iterator->IsExit()) return false;
1166
1167 // Continue if we are still on the same frame and in the same statement.
1168 int current_statement_position =
1169 break_location_iterator->code()->SourceStatementPosition(frame->pc());
1170 return thread_local_.last_fp_ == frame->fp() &&
ager@chromium.org236ad962008-09-25 09:45:57 +00001171 thread_local_.last_statement_position_ == current_statement_position;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001172 }
1173
1174 // No step next action - don't continue.
1175 return false;
1176}
1177
1178
1179// Check whether the code object at the specified address is a debug break code
1180// object.
1181bool Debug::IsDebugBreak(Address addr) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001182 Code* code = Code::GetCodeFromTargetAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +00001183 return code->ic_state() == DEBUG_BREAK;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001184}
1185
1186
1187// Check whether a code stub with the specified major key is a possible break
1188// point location when looking for source break locations.
1189bool Debug::IsSourceBreakStub(Code* code) {
1190 CodeStub::Major major_key = code->major_key();
1191 return major_key == CodeStub::CallFunction;
1192}
1193
1194
1195// Check whether a code stub with the specified major key is a possible break
1196// location.
1197bool Debug::IsBreakStub(Code* code) {
1198 CodeStub::Major major_key = code->major_key();
1199 return major_key == CodeStub::CallFunction ||
1200 major_key == CodeStub::StackCheck;
1201}
1202
1203
1204// Find the builtin to use for invoking the debug break
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001205Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001206 // Find the builtin debug break function matching the calling convention
1207 // used by the call site.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001208 if (code->is_inline_cache_stub()) {
1209 if (code->is_call_stub()) {
1210 return ComputeCallDebugBreak(code->arguments_count());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001211 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001212 if (code->is_load_stub()) {
1213 return Handle<Code>(Builtins::builtin(Builtins::LoadIC_DebugBreak));
1214 }
1215 if (code->is_store_stub()) {
1216 return Handle<Code>(Builtins::builtin(Builtins::StoreIC_DebugBreak));
1217 }
1218 if (code->is_keyed_load_stub()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001219 Handle<Code> result =
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001220 Handle<Code>(Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001221 return result;
1222 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001223 if (code->is_keyed_store_stub()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001224 Handle<Code> result =
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001225 Handle<Code>(Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001226 return result;
1227 }
1228 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001229 if (RelocInfo::IsConstructCall(mode)) {
1230 Handle<Code> result =
1231 Handle<Code>(Builtins::builtin(Builtins::ConstructCall_DebugBreak));
1232 return result;
1233 }
1234 if (code->kind() == Code::STUB) {
1235 ASSERT(code->major_key() == CodeStub::CallFunction ||
1236 code->major_key() == CodeStub::StackCheck);
1237 Handle<Code> result =
1238 Handle<Code>(Builtins::builtin(Builtins::StubNoRegisters_DebugBreak));
1239 return result;
1240 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001241
1242 UNREACHABLE();
1243 return Handle<Code>::null();
1244}
1245
1246
1247// Simple function for returning the source positions for active break points.
1248Handle<Object> Debug::GetSourceBreakLocations(
1249 Handle<SharedFunctionInfo> shared) {
1250 if (!HasDebugInfo(shared)) return Handle<Object>(Heap::undefined_value());
1251 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1252 if (debug_info->GetBreakPointCount() == 0) {
1253 return Handle<Object>(Heap::undefined_value());
1254 }
1255 Handle<FixedArray> locations =
1256 Factory::NewFixedArray(debug_info->GetBreakPointCount());
1257 int count = 0;
1258 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1259 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1260 BreakPointInfo* break_point_info =
1261 BreakPointInfo::cast(debug_info->break_points()->get(i));
1262 if (break_point_info->GetBreakPointCount() > 0) {
1263 locations->set(count++, break_point_info->statement_position());
1264 }
1265 }
1266 }
1267 return locations;
1268}
1269
1270
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001271void Debug::NewBreak(StackFrame::Id break_frame_id) {
1272 thread_local_.break_frame_id_ = break_frame_id;
1273 thread_local_.break_id_ = ++thread_local_.break_count_;
1274}
1275
1276
1277void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
1278 thread_local_.break_frame_id_ = break_frame_id;
1279 thread_local_.break_id_ = break_id;
1280}
1281
1282
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001283// Handle stepping into a function.
1284void Debug::HandleStepIn(Handle<JSFunction> function,
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001285 Handle<Object> holder,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001286 Address fp,
1287 bool is_constructor) {
1288 // If the frame pointer is not supplied by the caller find it.
1289 if (fp == 0) {
1290 StackFrameIterator it;
1291 it.Advance();
1292 // For constructor functions skip another frame.
1293 if (is_constructor) {
1294 ASSERT(it.frame()->is_construct());
1295 it.Advance();
1296 }
1297 fp = it.frame()->fp();
1298 }
1299
1300 // Flood the function with one-shot break points if it is called from where
1301 // step into was requested.
1302 if (fp == Debug::step_in_fp()) {
1303 // Don't allow step into functions in the native context.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001304 if (!function->IsBuiltin()) {
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001305 if (function->shared()->code() ==
1306 Builtins::builtin(Builtins::FunctionApply) ||
1307 function->shared()->code() ==
1308 Builtins::builtin(Builtins::FunctionCall)) {
1309 // Handle function.apply and function.call separately to flood the
1310 // function to be called and not the code for Builtins::FunctionApply or
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001311 // Builtins::FunctionCall. The receiver of call/apply is the target
1312 // function.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001313 if (!holder.is_null() && holder->IsJSFunction() &&
1314 !JSFunction::cast(*holder)->IsBuiltin()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001315 Handle<SharedFunctionInfo> shared_info(
1316 JSFunction::cast(*holder)->shared());
1317 Debug::FloodWithOneShot(shared_info);
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001318 }
1319 } else {
1320 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1321 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001322 }
1323 }
1324}
1325
1326
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001327void Debug::ClearStepping() {
1328 // Clear the various stepping setup.
1329 ClearOneShot();
1330 ClearStepIn();
1331 ClearStepNext();
1332
1333 // Clear multiple step counter.
1334 thread_local_.step_count_ = 0;
1335}
1336
1337// Clears all the one-shot break points that are currently set. Normally this
1338// function is called each time a break point is hit as one shot break points
1339// are used to support stepping.
1340void Debug::ClearOneShot() {
1341 // The current implementation just runs through all the breakpoints. When the
v8.team.kasperl727e9952008-09-02 14:56:44 +00001342 // last break point for a function is removed that function is automatically
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001343 // removed from the list.
1344
1345 DebugInfoListNode* node = debug_info_list_;
1346 while (node != NULL) {
1347 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1348 while (!it.Done()) {
1349 it.ClearOneShot();
1350 it.Next();
1351 }
1352 node = node->next();
1353 }
1354}
1355
1356
1357void Debug::ActivateStepIn(StackFrame* frame) {
1358 thread_local_.step_into_fp_ = frame->fp();
1359}
1360
1361
1362void Debug::ClearStepIn() {
1363 thread_local_.step_into_fp_ = 0;
1364}
1365
1366
1367void Debug::ClearStepNext() {
1368 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +00001369 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001370 thread_local_.last_fp_ = 0;
1371}
1372
1373
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001374bool Debug::EnsureCompiled(Handle<SharedFunctionInfo> shared) {
1375 if (shared->is_compiled()) return true;
ager@chromium.org3bf7b912008-11-17 09:09:45 +00001376 return CompileLazyShared(shared, CLEAR_EXCEPTION, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001377}
1378
1379
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001380// Ensures the debug information is present for shared.
1381bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1382 // Return if we already have the debug info for shared.
1383 if (HasDebugInfo(shared)) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001384
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001385 // Ensure shared in compiled. Return false if this failed.
1386 if (!EnsureCompiled(shared)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001387
1388 // Create the debug info object.
v8.team.kasperl727e9952008-09-02 14:56:44 +00001389 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001390
1391 // Add debug info to the list.
1392 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1393 node->set_next(debug_info_list_);
1394 debug_info_list_ = node;
1395
1396 // Now there is at least one break point.
1397 has_break_points_ = true;
1398
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001399 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001400}
1401
1402
1403void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1404 ASSERT(debug_info_list_ != NULL);
1405 // Run through the debug info objects to find this one and remove it.
1406 DebugInfoListNode* prev = NULL;
1407 DebugInfoListNode* current = debug_info_list_;
1408 while (current != NULL) {
1409 if (*current->debug_info() == *debug_info) {
1410 // Unlink from list. If prev is NULL we are looking at the first element.
1411 if (prev == NULL) {
1412 debug_info_list_ = current->next();
1413 } else {
1414 prev->set_next(current->next());
1415 }
1416 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1417 delete current;
1418
1419 // If there are no more debug info objects there are not more break
1420 // points.
1421 has_break_points_ = debug_info_list_ != NULL;
1422
1423 return;
1424 }
1425 // Move to next in list.
1426 prev = current;
1427 current = current->next();
1428 }
1429 UNREACHABLE();
1430}
1431
1432
1433void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001434 HandleScope scope;
1435
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001436 // Get the executing function in which the debug break occurred.
1437 Handle<SharedFunctionInfo> shared =
1438 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001439 if (!EnsureDebugInfo(shared)) {
1440 // Return if we failed to retrieve the debug info.
1441 return;
1442 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001443 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1444 Handle<Code> code(debug_info->code());
1445 Handle<Code> original_code(debug_info->original_code());
1446#ifdef DEBUG
1447 // Get the code which is actually executing.
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001448 Handle<Code> frame_code(frame->code());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001449 ASSERT(frame_code.is_identical_to(code));
1450#endif
1451
1452 // Find the call address in the running code. This address holds the call to
1453 // either a DebugBreakXXX or to the debug break return entry code if the
1454 // break point is still active after processing the break point.
1455 Address addr = frame->pc() - Assembler::kTargetAddrToReturnAddrDist;
1456
1457 // Check if the location is at JS exit.
1458 bool at_js_exit = false;
1459 RelocIterator it(debug_info->code());
1460 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001461 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001462 at_js_exit = it.rinfo()->pc() == addr - 1;
1463 }
1464 it.next();
1465 }
1466
1467 // Handle the jump to continue execution after break point depending on the
1468 // break location.
1469 if (at_js_exit) {
1470 // First check if the call in the code is still the debug break return
1471 // entry code. If it is the break point is still active. If not the break
1472 // point was removed during break point processing.
1473 if (Assembler::target_address_at(addr) ==
1474 debug_break_return_entry()->entry()) {
1475 // Break point still active. Jump to the corresponding place in the
1476 // original code.
1477 addr += original_code->instruction_start() - code->instruction_start();
1478 }
1479
1480 // Move one byte back to where the call instruction was placed.
1481 thread_local_.after_break_target_ = addr - 1;
1482 } else {
1483 // Check if there still is a debug break call at the target address. If the
1484 // break point has been removed it will have disappeared. If it have
1485 // disappeared don't try to look in the original code as the running code
1486 // will have the right address. This takes care of the case where the last
1487 // break point is removed from the function and therefore no "original code"
1488 // is available. If the debug break call is still there find the address in
1489 // the original code.
1490 if (IsDebugBreak(Assembler::target_address_at(addr))) {
1491 // If the break point is still there find the call address which was
1492 // overwritten in the original code by the call to DebugBreakXXX.
1493
1494 // Find the corresponding address in the original code.
1495 addr += original_code->instruction_start() - code->instruction_start();
1496 }
1497
1498 // Install jump to the call address in the original code. This will be the
1499 // call which was overwritten by the call to DebugBreakXXX.
1500 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1501 }
1502}
1503
1504
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001505bool Debug::IsDebugGlobal(GlobalObject* global) {
1506 return IsLoaded() && global == Debug::debug_context()->global();
1507}
1508
1509
ager@chromium.org32912102009-01-16 10:38:43 +00001510void Debug::ClearMirrorCache() {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001511 HandleScope scope;
ager@chromium.org32912102009-01-16 10:38:43 +00001512 ASSERT(Top::context() == *Debug::debug_context());
1513
1514 // Clear the mirror cache.
1515 Handle<String> function_name =
1516 Factory::LookupSymbol(CStrVector("ClearMirrorCache"));
1517 Handle<Object> fun(Top::global()->GetProperty(*function_name));
1518 ASSERT(fun->IsJSFunction());
1519 bool caught_exception;
1520 Handle<Object> js_object = Execution::TryCall(
1521 Handle<JSFunction>::cast(fun),
1522 Handle<JSObject>(Debug::debug_context()->global()),
1523 0, NULL, &caught_exception);
1524}
1525
1526
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001527// If an object given is an external string, check that the underlying
1528// resource is accessible. For other kinds of objects, always return true.
1529static bool IsExternalStringValid(Object* str) {
1530 if (!str->IsString() || !StringShape(String::cast(str)).IsExternal()) {
1531 return true;
1532 }
1533 if (String::cast(str)->IsAsciiRepresentation()) {
1534 return ExternalAsciiString::cast(str)->resource() != NULL;
1535 } else if (String::cast(str)->IsTwoByteRepresentation()) {
1536 return ExternalTwoByteString::cast(str)->resource() != NULL;
1537 } else {
1538 return true;
1539 }
1540}
1541
1542
1543void Debug::CreateScriptCache() {
1544 HandleScope scope;
1545
1546 // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
1547 // rid of all the cached script wrappers and the second gets rid of the
1548 // scripts which is no longer referenced.
1549 Heap::CollectAllGarbage();
1550 Heap::CollectAllGarbage();
1551
1552 ASSERT(script_cache_ == NULL);
1553 script_cache_ = new ScriptCache();
1554
1555 // Scan heap for Script objects.
1556 int count = 0;
1557 HeapIterator iterator;
1558 while (iterator.has_next()) {
1559 HeapObject* obj = iterator.next();
1560 ASSERT(obj != NULL);
1561 if (obj->IsScript() && IsExternalStringValid(Script::cast(obj)->source())) {
1562 script_cache_->Add(Handle<Script>(Script::cast(obj)));
1563 count++;
1564 }
1565 }
1566}
1567
1568
1569void Debug::DestroyScriptCache() {
1570 // Get rid of the script cache if it was created.
1571 if (script_cache_ != NULL) {
1572 delete script_cache_;
1573 script_cache_ = NULL;
1574 }
1575}
1576
1577
1578void Debug::AddScriptToScriptCache(Handle<Script> script) {
1579 if (script_cache_ != NULL) {
1580 script_cache_->Add(script);
1581 }
1582}
1583
1584
1585Handle<FixedArray> Debug::GetLoadedScripts() {
1586 // Create and fill the script cache when the loaded scripts is requested for
1587 // the first time.
1588 if (script_cache_ == NULL) {
1589 CreateScriptCache();
1590 }
1591
1592 // If the script cache is not active just return an empty array.
1593 ASSERT(script_cache_ != NULL);
1594 if (script_cache_ == NULL) {
1595 Factory::NewFixedArray(0);
1596 }
1597
1598 // Perform GC to get unreferenced scripts evicted from the cache before
1599 // returning the content.
1600 Heap::CollectAllGarbage();
1601
1602 // Get the scripts from the cache.
1603 return script_cache_->GetScripts();
1604}
1605
1606
1607void Debug::AfterGarbageCollection() {
1608 // Generate events for collected scripts.
1609 if (script_cache_ != NULL) {
1610 script_cache_->ProcessCollectedScripts();
1611 }
1612}
1613
1614
ager@chromium.org71daaf62009-04-01 07:22:49 +00001615Mutex* Debugger::debugger_access_ = OS::CreateMutex();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001616Handle<Object> Debugger::event_listener_ = Handle<Object>();
1617Handle<Object> Debugger::event_listener_data_ = Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001618bool Debugger::compiling_natives_ = false;
mads.s.agercbaa0602008-08-14 13:41:48 +00001619bool Debugger::is_loading_debugger_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001620bool Debugger::never_unload_debugger_ = false;
ager@chromium.org5ec48922009-05-05 07:25:34 +00001621v8::Debug::MessageHandler2 Debugger::message_handler_ = NULL;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001622bool Debugger::debugger_unload_pending_ = false;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001623v8::Debug::HostDispatchHandler Debugger::host_dispatch_handler_ = NULL;
1624int Debugger::host_dispatch_micros_ = 100 * 1000;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001625DebuggerAgent* Debugger::agent_ = NULL;
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001626LockingCommandMessageQueue Debugger::command_queue_(kQueueInitialSize);
ager@chromium.org41826e72009-03-30 13:30:57 +00001627Semaphore* Debugger::command_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001628
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001629
1630Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1631 int argc, Object*** argv,
1632 bool* caught_exception) {
1633 ASSERT(Top::context() == *Debug::debug_context());
1634
1635 // Create the execution state object.
1636 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1637 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1638 ASSERT(constructor->IsJSFunction());
1639 if (!constructor->IsJSFunction()) {
1640 *caught_exception = true;
1641 return Factory::undefined_value();
1642 }
1643 Handle<Object> js_object = Execution::TryCall(
1644 Handle<JSFunction>::cast(constructor),
1645 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1646 caught_exception);
1647 return js_object;
1648}
1649
1650
1651Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1652 // Create the execution state object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001653 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001654 const int argc = 1;
1655 Object** argv[argc] = { break_id.location() };
1656 return MakeJSObject(CStrVector("MakeExecutionState"),
1657 argc, argv, caught_exception);
1658}
1659
1660
1661Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1662 Handle<Object> break_points_hit,
1663 bool* caught_exception) {
1664 // Create the new break event object.
1665 const int argc = 2;
1666 Object** argv[argc] = { exec_state.location(),
1667 break_points_hit.location() };
1668 return MakeJSObject(CStrVector("MakeBreakEvent"),
1669 argc,
1670 argv,
1671 caught_exception);
1672}
1673
1674
1675Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1676 Handle<Object> exception,
1677 bool uncaught,
1678 bool* caught_exception) {
1679 // Create the new exception event object.
1680 const int argc = 3;
1681 Object** argv[argc] = { exec_state.location(),
1682 exception.location(),
1683 uncaught ? Factory::true_value().location() :
1684 Factory::false_value().location()};
1685 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1686 argc, argv, caught_exception);
1687}
1688
1689
1690Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1691 bool* caught_exception) {
1692 // Create the new function event object.
1693 const int argc = 1;
1694 Object** argv[argc] = { function.location() };
1695 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1696 argc, argv, caught_exception);
1697}
1698
1699
1700Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001701 bool before,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001702 bool* caught_exception) {
1703 // Create the compile event object.
1704 Handle<Object> exec_state = MakeExecutionState(caught_exception);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001705 Handle<Object> script_wrapper = GetScriptWrapper(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001706 const int argc = 3;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001707 Object** argv[argc] = { exec_state.location(),
1708 script_wrapper.location(),
1709 before ? Factory::true_value().location() :
1710 Factory::false_value().location() };
1711
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001712 return MakeJSObject(CStrVector("MakeCompileEvent"),
1713 argc,
1714 argv,
1715 caught_exception);
1716}
1717
1718
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001719Handle<Object> Debugger::MakeScriptCollectedEvent(int id,
1720 bool* caught_exception) {
1721 // Create the script collected event object.
1722 Handle<Object> exec_state = MakeExecutionState(caught_exception);
1723 Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id));
1724 const int argc = 2;
1725 Object** argv[argc] = { exec_state.location(), id_object.location() };
1726
1727 return MakeJSObject(CStrVector("MakeScriptCollectedEvent"),
1728 argc,
1729 argv,
1730 caught_exception);
1731}
1732
1733
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001734void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1735 HandleScope scope;
1736
1737 // Bail out based on state or if there is no listener for this event
1738 if (Debug::InDebugger()) return;
1739 if (!Debugger::EventActive(v8::Exception)) return;
1740
1741 // Bail out if exception breaks are not active
1742 if (uncaught) {
1743 // Uncaught exceptions are reported by either flags.
1744 if (!(Debug::break_on_uncaught_exception() ||
1745 Debug::break_on_exception())) return;
1746 } else {
1747 // Caught exceptions are reported is activated.
1748 if (!Debug::break_on_exception()) return;
1749 }
1750
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001751 // Enter the debugger.
1752 EnterDebugger debugger;
1753 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001754
1755 // Clear all current stepping setup.
1756 Debug::ClearStepping();
1757 // Create the event data object.
1758 bool caught_exception = false;
1759 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1760 Handle<Object> event_data;
1761 if (!caught_exception) {
1762 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1763 &caught_exception);
1764 }
1765 // Bail out and don't call debugger if exception.
1766 if (caught_exception) {
1767 return;
1768 }
1769
ager@chromium.org5ec48922009-05-05 07:25:34 +00001770 // Process debug event.
1771 ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001772 // Return to continue execution from where the exception was thrown.
1773}
1774
1775
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001776void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
1777 bool auto_continue) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001778 HandleScope scope;
1779
kasper.lund212ac232008-07-16 07:07:30 +00001780 // Debugger has already been entered by caller.
1781 ASSERT(Top::context() == *Debug::debug_context());
1782
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001783 // Bail out if there is no listener for this event
1784 if (!Debugger::EventActive(v8::Break)) return;
1785
1786 // Debugger must be entered in advance.
1787 ASSERT(Top::context() == *Debug::debug_context());
1788
1789 // Create the event data object.
1790 bool caught_exception = false;
1791 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1792 Handle<Object> event_data;
1793 if (!caught_exception) {
1794 event_data = MakeBreakEvent(exec_state, break_points_hit,
1795 &caught_exception);
1796 }
1797 // Bail out and don't call debugger if exception.
1798 if (caught_exception) {
1799 return;
1800 }
1801
ager@chromium.org5ec48922009-05-05 07:25:34 +00001802 // Process debug event.
1803 ProcessDebugEvent(v8::Break,
1804 Handle<JSObject>::cast(event_data),
1805 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001806}
1807
1808
1809void Debugger::OnBeforeCompile(Handle<Script> script) {
1810 HandleScope scope;
1811
1812 // Bail out based on state or if there is no listener for this event
1813 if (Debug::InDebugger()) return;
1814 if (compiling_natives()) return;
1815 if (!EventActive(v8::BeforeCompile)) return;
1816
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001817 // Enter the debugger.
1818 EnterDebugger debugger;
1819 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001820
1821 // Create the event data object.
1822 bool caught_exception = false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001823 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001824 // Bail out and don't call debugger if exception.
1825 if (caught_exception) {
1826 return;
1827 }
1828
ager@chromium.org5ec48922009-05-05 07:25:34 +00001829 // Process debug event.
1830 ProcessDebugEvent(v8::BeforeCompile,
1831 Handle<JSObject>::cast(event_data),
1832 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001833}
1834
1835
1836// Handle debugger actions when a new script is compiled.
1837void Debugger::OnAfterCompile(Handle<Script> script, Handle<JSFunction> fun) {
kasper.lund212ac232008-07-16 07:07:30 +00001838 HandleScope scope;
1839
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001840 // Add the newly compiled script to the script cache.
1841 Debug::AddScriptToScriptCache(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001842
1843 // No more to do if not debugging.
ager@chromium.org71daaf62009-04-01 07:22:49 +00001844 if (!IsDebuggerActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001845
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001846 // No compile events while compiling natives.
1847 if (compiling_natives()) return;
1848
iposva@chromium.org245aa852009-02-10 00:49:54 +00001849 // Store whether in debugger before entering debugger.
1850 bool in_debugger = Debug::InDebugger();
1851
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001852 // Enter the debugger.
1853 EnterDebugger debugger;
1854 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001855
1856 // If debugging there might be script break points registered for this
1857 // script. Make sure that these break points are set.
1858
1859 // Get the function UpdateScriptBreakPoints (defined in debug-delay.js).
1860 Handle<Object> update_script_break_points =
1861 Handle<Object>(Debug::debug_context()->global()->GetProperty(
1862 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
1863 if (!update_script_break_points->IsJSFunction()) {
1864 return;
1865 }
1866 ASSERT(update_script_break_points->IsJSFunction());
1867
1868 // Wrap the script object in a proper JS object before passing it
1869 // to JavaScript.
1870 Handle<JSValue> wrapper = GetScriptWrapper(script);
1871
1872 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00001873 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001874 const int argc = 1;
1875 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
1876 Handle<Object> result = Execution::TryCall(
1877 Handle<JSFunction>::cast(update_script_break_points),
1878 Top::builtins(), argc, argv,
1879 &caught_exception);
1880 if (caught_exception) {
1881 return;
1882 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001883 // Bail out based on state or if there is no listener for this event
iposva@chromium.org245aa852009-02-10 00:49:54 +00001884 if (in_debugger) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001885 if (!Debugger::EventActive(v8::AfterCompile)) return;
1886
1887 // Create the compile state object.
1888 Handle<Object> event_data = MakeCompileEvent(script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001889 false,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001890 &caught_exception);
1891 // Bail out and don't call debugger if exception.
1892 if (caught_exception) {
1893 return;
1894 }
ager@chromium.org5ec48922009-05-05 07:25:34 +00001895 // Process debug event.
1896 ProcessDebugEvent(v8::AfterCompile,
1897 Handle<JSObject>::cast(event_data),
1898 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001899}
1900
1901
1902void Debugger::OnNewFunction(Handle<JSFunction> function) {
1903 return;
1904 HandleScope scope;
1905
1906 // Bail out based on state or if there is no listener for this event
1907 if (Debug::InDebugger()) return;
1908 if (compiling_natives()) return;
1909 if (!Debugger::EventActive(v8::NewFunction)) return;
1910
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001911 // Enter the debugger.
1912 EnterDebugger debugger;
1913 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001914
1915 // Create the event object.
1916 bool caught_exception = false;
1917 Handle<Object> event_data = MakeNewFunctionEvent(function, &caught_exception);
1918 // Bail out and don't call debugger if exception.
1919 if (caught_exception) {
1920 return;
1921 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001922 // Process debug event.
ager@chromium.org5ec48922009-05-05 07:25:34 +00001923 ProcessDebugEvent(v8::NewFunction, Handle<JSObject>::cast(event_data), true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001924}
1925
1926
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001927void Debugger::OnScriptCollected(int id) {
1928 HandleScope scope;
1929
1930 // No more to do if not debugging.
1931 if (!IsDebuggerActive()) return;
1932 if (!Debugger::EventActive(v8::ScriptCollected)) return;
1933
1934 // Enter the debugger.
1935 EnterDebugger debugger;
1936 if (debugger.FailedToEnter()) return;
1937
1938 // Create the script collected state object.
1939 bool caught_exception = false;
1940 Handle<Object> event_data = MakeScriptCollectedEvent(id,
1941 &caught_exception);
1942 // Bail out and don't call debugger if exception.
1943 if (caught_exception) {
1944 return;
1945 }
1946
1947 // Process debug event.
1948 ProcessDebugEvent(v8::ScriptCollected,
1949 Handle<JSObject>::cast(event_data),
1950 true);
1951}
1952
1953
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001954void Debugger::ProcessDebugEvent(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00001955 Handle<JSObject> event_data,
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001956 bool auto_continue) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001957 HandleScope scope;
1958
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001959 // Clear any pending debug break if this is a real break.
1960 if (!auto_continue) {
1961 Debug::clear_interrupt_pending(DEBUGBREAK);
1962 }
1963
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001964 // Create the execution state.
1965 bool caught_exception = false;
1966 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1967 if (caught_exception) {
1968 return;
1969 }
ager@chromium.org41826e72009-03-30 13:30:57 +00001970 // First notify the message handler if any.
1971 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001972 NotifyMessageHandler(event,
1973 Handle<JSObject>::cast(exec_state),
1974 event_data,
1975 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001976 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001977 // Notify registered debug event listener. This can be either a C or a
1978 // JavaScript function.
1979 if (!event_listener_.is_null()) {
1980 if (event_listener_->IsProxy()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001981 // C debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00001982 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001983 v8::Debug::EventCallback callback =
1984 FUNCTION_CAST<v8::Debug::EventCallback>(callback_obj->proxy());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001985 callback(event,
1986 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state)),
ager@chromium.org5ec48922009-05-05 07:25:34 +00001987 v8::Utils::ToLocal(event_data),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001988 v8::Utils::ToLocal(Handle<Object>::cast(event_listener_data_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001989 } else {
1990 // JavaScript debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00001991 ASSERT(event_listener_->IsJSFunction());
1992 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001993
1994 // Invoke the JavaScript debug event listener.
1995 const int argc = 4;
1996 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
1997 exec_state.location(),
ager@chromium.org5ec48922009-05-05 07:25:34 +00001998 Handle<Object>::cast(event_data).location(),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001999 event_listener_data_.location() };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002000 Handle<Object> result = Execution::TryCall(fun, Top::global(),
2001 argc, argv, &caught_exception);
2002 if (caught_exception) {
2003 // Silently ignore exceptions from debug event listeners.
2004 }
2005 }
2006 }
2007}
2008
2009
ager@chromium.org71daaf62009-04-01 07:22:49 +00002010void Debugger::UnloadDebugger() {
2011 // Make sure that there are no breakpoints left.
2012 Debug::ClearAllBreakPoints();
2013
2014 // Unload the debugger if feasible.
2015 if (!never_unload_debugger_) {
2016 Debug::Unload();
2017 }
2018
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002019 // Clear the flag indicating that the debugger should be unloaded.
2020 debugger_unload_pending_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00002021}
2022
2023
ager@chromium.org41826e72009-03-30 13:30:57 +00002024void Debugger::NotifyMessageHandler(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002025 Handle<JSObject> exec_state,
2026 Handle<JSObject> event_data,
ager@chromium.org41826e72009-03-30 13:30:57 +00002027 bool auto_continue) {
2028 HandleScope scope;
2029
2030 if (!Debug::Load()) return;
2031
2032 // Process the individual events.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002033 bool sendEventMessage = false;
ager@chromium.org41826e72009-03-30 13:30:57 +00002034 switch (event) {
2035 case v8::Break:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002036 sendEventMessage = !auto_continue;
ager@chromium.org41826e72009-03-30 13:30:57 +00002037 break;
2038 case v8::Exception:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002039 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002040 break;
2041 case v8::BeforeCompile:
2042 break;
2043 case v8::AfterCompile:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002044 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002045 break;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002046 case v8::ScriptCollected:
2047 sendEventMessage = true;
2048 break;
ager@chromium.org41826e72009-03-30 13:30:57 +00002049 case v8::NewFunction:
2050 break;
2051 default:
2052 UNREACHABLE();
2053 }
2054
ager@chromium.org5ec48922009-05-05 07:25:34 +00002055 // The debug command interrupt flag might have been set when the command was
2056 // added. It should be enough to clear the flag only once while we are in the
2057 // debugger.
2058 ASSERT(Debug::InDebugger());
2059 StackGuard::Continue(DEBUGCOMMAND);
2060
2061 // Notify the debugger that a debug event has occurred unless auto continue is
2062 // active in which case no event is send.
2063 if (sendEventMessage) {
2064 MessageImpl message = MessageImpl::NewEvent(
2065 event,
2066 auto_continue,
2067 Handle<JSObject>::cast(exec_state),
2068 Handle<JSObject>::cast(event_data));
2069 InvokeMessageHandler(message);
2070 }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002071
2072 // If auto continue don't make the event cause a break, but process messages
2073 // in the queue if any. For script collected events don't even process
2074 // messages in the queue as the execution state might not be what is expected
2075 // by the client.
ager@chromium.org6ffc2172009-05-29 19:20:16 +00002076 if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002077 return;
2078 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002079
2080 // Get the DebugCommandProcessor.
2081 v8::Local<v8::Object> api_exec_state =
2082 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
2083 v8::Local<v8::String> fun_name =
2084 v8::String::New("debugCommandProcessor");
2085 v8::Local<v8::Function> fun =
2086 v8::Function::Cast(*api_exec_state->Get(fun_name));
2087 v8::TryCatch try_catch;
2088 v8::Local<v8::Object> cmd_processor =
2089 v8::Object::Cast(*fun->Call(api_exec_state, 0, NULL));
2090 if (try_catch.HasCaught()) {
2091 PrintLn(try_catch.Exception());
2092 return;
2093 }
2094
ager@chromium.org41826e72009-03-30 13:30:57 +00002095 // Process requests from the debugger.
2096 while (true) {
2097 // Wait for new command in the queue.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002098 if (Debugger::host_dispatch_handler_) {
2099 // In case there is a host dispatch - do periodic dispatches.
2100 if (!command_received_->Wait(host_dispatch_micros_)) {
2101 // Timout expired, do the dispatch.
2102 Debugger::host_dispatch_handler_();
2103 continue;
2104 }
2105 } else {
2106 // In case there is no host dispatch - just wait.
2107 command_received_->Wait();
2108 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002109
ager@chromium.org41826e72009-03-30 13:30:57 +00002110 // Get the command from the queue.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002111 CommandMessage command = command_queue_.Get();
ager@chromium.org41826e72009-03-30 13:30:57 +00002112 Logger::DebugTag("Got request from command queue, in interactive loop.");
ager@chromium.org71daaf62009-04-01 07:22:49 +00002113 if (!Debugger::IsDebuggerActive()) {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002114 // Delete command text and user data.
2115 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002116 return;
2117 }
2118
ager@chromium.org41826e72009-03-30 13:30:57 +00002119 // Invoke JavaScript to process the debug request.
2120 v8::Local<v8::String> fun_name;
2121 v8::Local<v8::Function> fun;
2122 v8::Local<v8::Value> request;
2123 v8::TryCatch try_catch;
2124 fun_name = v8::String::New("processDebugRequest");
2125 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002126
2127 request = v8::String::New(command.text().start(),
2128 command.text().length());
ager@chromium.org41826e72009-03-30 13:30:57 +00002129 static const int kArgc = 1;
2130 v8::Handle<Value> argv[kArgc] = { request };
2131 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
2132
2133 // Get the response.
2134 v8::Local<v8::String> response;
2135 bool running = false;
2136 if (!try_catch.HasCaught()) {
2137 // Get response string.
2138 if (!response_val->IsUndefined()) {
2139 response = v8::String::Cast(*response_val);
2140 } else {
2141 response = v8::String::New("");
2142 }
2143
2144 // Log the JSON request/response.
2145 if (FLAG_trace_debug_json) {
2146 PrintLn(request);
2147 PrintLn(response);
2148 }
2149
2150 // Get the running state.
2151 fun_name = v8::String::New("isRunning");
2152 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2153 static const int kArgc = 1;
2154 v8::Handle<Value> argv[kArgc] = { response };
2155 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
2156 if (!try_catch.HasCaught()) {
2157 running = running_val->ToBoolean()->Value();
2158 }
2159 } else {
2160 // In case of failure the result text is the exception text.
2161 response = try_catch.Exception()->ToString();
2162 }
2163
ager@chromium.org41826e72009-03-30 13:30:57 +00002164 // Return the result.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002165 MessageImpl message = MessageImpl::NewResponse(
2166 event,
2167 running,
2168 Handle<JSObject>::cast(exec_state),
2169 Handle<JSObject>::cast(event_data),
2170 Handle<String>(Utils::OpenHandle(*response)),
2171 command.client_data());
2172 InvokeMessageHandler(message);
2173 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002174
2175 // Return from debug event processing if either the VM is put into the
2176 // runnning state (through a continue command) or auto continue is active
2177 // and there are no more commands queued.
2178 if (running || (auto_continue && !HasCommands())) {
2179 return;
2180 }
2181 }
2182}
2183
2184
iposva@chromium.org245aa852009-02-10 00:49:54 +00002185void Debugger::SetEventListener(Handle<Object> callback,
2186 Handle<Object> data) {
2187 HandleScope scope;
2188
2189 // Clear the global handles for the event listener and the event listener data
2190 // object.
2191 if (!event_listener_.is_null()) {
2192 GlobalHandles::Destroy(
2193 reinterpret_cast<Object**>(event_listener_.location()));
2194 event_listener_ = Handle<Object>();
2195 }
2196 if (!event_listener_data_.is_null()) {
2197 GlobalHandles::Destroy(
2198 reinterpret_cast<Object**>(event_listener_data_.location()));
2199 event_listener_data_ = Handle<Object>();
2200 }
2201
2202 // If there is a new debug event listener register it together with its data
2203 // object.
2204 if (!callback->IsUndefined() && !callback->IsNull()) {
2205 event_listener_ = Handle<Object>::cast(GlobalHandles::Create(*callback));
2206 if (data.is_null()) {
2207 data = Factory::undefined_value();
2208 }
2209 event_listener_data_ = Handle<Object>::cast(GlobalHandles::Create(*data));
2210 }
2211
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002212 ListenersChanged();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002213}
2214
2215
ager@chromium.org5ec48922009-05-05 07:25:34 +00002216void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002217 ScopedLock with(debugger_access_);
2218
ager@chromium.org381abbb2009-02-25 13:23:22 +00002219 message_handler_ = handler;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002220 ListenersChanged();
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002221 if (handler == NULL) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002222 // Send an empty command to the debugger if in a break to make JavaScript
2223 // run again if the debugger is closed.
2224 if (Debug::InDebugger()) {
2225 ProcessCommand(Vector<const uint16_t>::empty());
2226 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002227 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002228}
2229
2230
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002231void Debugger::ListenersChanged() {
2232 if (IsDebuggerActive()) {
2233 // Disable the compilation cache when the debugger is active.
2234 CompilationCache::Disable();
2235 } else {
2236 CompilationCache::Enable();
2237
2238 // Unload the debugger if event listener and message handler cleared.
2239 if (Debug::InDebugger()) {
2240 // If we are in debugger set the flag to unload the debugger when last
2241 // EnterDebugger on the current stack is destroyed.
2242 debugger_unload_pending_ = true;
2243 } else {
2244 UnloadDebugger();
2245 }
2246 }
2247}
2248
2249
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002250void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
2251 int period) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002252 host_dispatch_handler_ = handler;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002253 host_dispatch_micros_ = period * 1000;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002254}
2255
2256
ager@chromium.org41826e72009-03-30 13:30:57 +00002257// Calls the registered debug message handler. This callback is part of the
ager@chromium.org5ec48922009-05-05 07:25:34 +00002258// public API.
2259void Debugger::InvokeMessageHandler(MessageImpl message) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002260 ScopedLock with(debugger_access_);
2261
ager@chromium.org381abbb2009-02-25 13:23:22 +00002262 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002263 message_handler_(message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002264 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002265}
2266
2267
2268// Puts a command coming from the public API on the queue. Creates
2269// a copy of the command string managed by the debugger. Up to this
2270// point, the command data was managed by the API client. Called
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002271// by the API client thread.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002272void Debugger::ProcessCommand(Vector<const uint16_t> command,
2273 v8::Debug::ClientData* client_data) {
2274 // Need to cast away const.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002275 CommandMessage message = CommandMessage::New(
ager@chromium.org41826e72009-03-30 13:30:57 +00002276 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002277 command.length()),
2278 client_data);
ager@chromium.org41826e72009-03-30 13:30:57 +00002279 Logger::DebugTag("Put command on command_queue.");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002280 command_queue_.Put(message);
ager@chromium.org41826e72009-03-30 13:30:57 +00002281 command_received_->Signal();
sgjesse@chromium.org3afc1582009-04-16 22:31:44 +00002282
2283 // Set the debug command break flag to have the command processed.
ager@chromium.org41826e72009-03-30 13:30:57 +00002284 if (!Debug::InDebugger()) {
2285 StackGuard::DebugCommand();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002286 }
2287}
2288
2289
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002290bool Debugger::HasCommands() {
ager@chromium.org41826e72009-03-30 13:30:57 +00002291 return !command_queue_.IsEmpty();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002292}
2293
2294
ager@chromium.org71daaf62009-04-01 07:22:49 +00002295bool Debugger::IsDebuggerActive() {
2296 ScopedLock with(debugger_access_);
2297
2298 return message_handler_ != NULL || !event_listener_.is_null();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002299}
2300
2301
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002302Handle<Object> Debugger::Call(Handle<JSFunction> fun,
2303 Handle<Object> data,
2304 bool* pending_exception) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002305 // When calling functions in the debugger prevent it from beeing unloaded.
2306 Debugger::never_unload_debugger_ = true;
2307
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002308 // Enter the debugger.
2309 EnterDebugger debugger;
2310 if (debugger.FailedToEnter() || !debugger.HasJavaScriptFrames()) {
2311 return Factory::undefined_value();
2312 }
2313
2314 // Create the execution state.
2315 bool caught_exception = false;
2316 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2317 if (caught_exception) {
2318 return Factory::undefined_value();
2319 }
2320
2321 static const int kArgc = 2;
2322 Object** argv[kArgc] = { exec_state.location(), data.location() };
2323 Handle<Object> result = Execution::Call(fun, Factory::undefined_value(),
2324 kArgc, argv, pending_exception);
2325 return result;
2326}
2327
2328
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002329bool Debugger::StartAgent(const char* name, int port) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002330 if (Socket::Setup()) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002331 agent_ = new DebuggerAgent(name, port);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002332 agent_->Start();
2333 return true;
2334 }
2335
2336 return false;
2337}
2338
2339
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002340void Debugger::StopAgent() {
2341 if (agent_ != NULL) {
2342 agent_->Shutdown();
2343 agent_->Join();
2344 delete agent_;
2345 agent_ = NULL;
2346 }
2347}
2348
2349
ager@chromium.org5ec48922009-05-05 07:25:34 +00002350MessageImpl MessageImpl::NewEvent(DebugEvent event,
2351 bool running,
2352 Handle<JSObject> exec_state,
2353 Handle<JSObject> event_data) {
2354 MessageImpl message(true, event, running,
2355 exec_state, event_data, Handle<String>(), NULL);
2356 return message;
2357}
2358
2359
2360MessageImpl MessageImpl::NewResponse(DebugEvent event,
2361 bool running,
2362 Handle<JSObject> exec_state,
2363 Handle<JSObject> event_data,
2364 Handle<String> response_json,
2365 v8::Debug::ClientData* client_data) {
2366 MessageImpl message(false, event, running,
2367 exec_state, event_data, response_json, client_data);
2368 return message;
2369}
2370
2371
2372MessageImpl::MessageImpl(bool is_event,
2373 DebugEvent event,
2374 bool running,
2375 Handle<JSObject> exec_state,
2376 Handle<JSObject> event_data,
2377 Handle<String> response_json,
2378 v8::Debug::ClientData* client_data)
2379 : is_event_(is_event),
2380 event_(event),
2381 running_(running),
2382 exec_state_(exec_state),
2383 event_data_(event_data),
2384 response_json_(response_json),
2385 client_data_(client_data) {}
2386
2387
2388bool MessageImpl::IsEvent() const {
2389 return is_event_;
2390}
2391
2392
2393bool MessageImpl::IsResponse() const {
2394 return !is_event_;
2395}
2396
2397
2398DebugEvent MessageImpl::GetEvent() const {
2399 return event_;
2400}
2401
2402
2403bool MessageImpl::WillStartRunning() const {
2404 return running_;
2405}
2406
2407
2408v8::Handle<v8::Object> MessageImpl::GetExecutionState() const {
2409 return v8::Utils::ToLocal(exec_state_);
2410}
2411
2412
2413v8::Handle<v8::Object> MessageImpl::GetEventData() const {
2414 return v8::Utils::ToLocal(event_data_);
2415}
2416
2417
2418v8::Handle<v8::String> MessageImpl::GetJSON() const {
2419 v8::HandleScope scope;
2420
2421 if (IsEvent()) {
2422 // Call toJSONProtocol on the debug event object.
2423 Handle<Object> fun = GetProperty(event_data_, "toJSONProtocol");
2424 if (!fun->IsJSFunction()) {
2425 return v8::Handle<v8::String>();
2426 }
2427 bool caught_exception;
2428 Handle<Object> json = Execution::TryCall(Handle<JSFunction>::cast(fun),
2429 event_data_,
2430 0, NULL, &caught_exception);
2431 if (caught_exception || !json->IsString()) {
2432 return v8::Handle<v8::String>();
2433 }
2434 return scope.Close(v8::Utils::ToLocal(Handle<String>::cast(json)));
2435 } else {
2436 return v8::Utils::ToLocal(response_json_);
2437 }
2438}
2439
2440
2441v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002442 Handle<Context> context = Debug::debugger_entry()->GetContext();
2443 // Top::context() may have been NULL when "script collected" event occured.
2444 if (*context == NULL) {
2445 ASSERT(event_ == v8::ScriptCollected);
2446 return v8::Local<v8::Context>();
2447 }
2448 Handle<Context> global_context(context->global_context());
2449 return v8::Utils::ToLocal(global_context);
ager@chromium.org5ec48922009-05-05 07:25:34 +00002450}
2451
2452
2453v8::Debug::ClientData* MessageImpl::GetClientData() const {
2454 return client_data_;
2455}
2456
2457
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002458CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
2459 client_data_(NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002460}
2461
2462
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002463CommandMessage::CommandMessage(const Vector<uint16_t>& text,
2464 v8::Debug::ClientData* data)
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002465 : text_(text),
2466 client_data_(data) {
2467}
2468
2469
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002470CommandMessage::~CommandMessage() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002471}
2472
2473
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002474void CommandMessage::Dispose() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002475 text_.Dispose();
2476 delete client_data_;
2477 client_data_ = NULL;
2478}
2479
2480
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002481CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
2482 v8::Debug::ClientData* data) {
2483 return CommandMessage(command.Clone(), data);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002484}
2485
2486
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002487CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
2488 size_(size) {
2489 messages_ = NewArray<CommandMessage>(size);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002490}
2491
2492
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002493CommandMessageQueue::~CommandMessageQueue() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002494 while (!IsEmpty()) {
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002495 CommandMessage m = Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002496 m.Dispose();
2497 }
kasper.lund7276f142008-07-30 08:49:36 +00002498 DeleteArray(messages_);
2499}
2500
2501
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002502CommandMessage CommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002503 ASSERT(!IsEmpty());
2504 int result = start_;
2505 start_ = (start_ + 1) % size_;
2506 return messages_[result];
2507}
2508
2509
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002510void CommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002511 if ((end_ + 1) % size_ == start_) {
2512 Expand();
2513 }
2514 messages_[end_] = message;
2515 end_ = (end_ + 1) % size_;
2516}
2517
2518
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002519void CommandMessageQueue::Expand() {
2520 CommandMessageQueue new_queue(size_ * 2);
kasper.lund7276f142008-07-30 08:49:36 +00002521 while (!IsEmpty()) {
2522 new_queue.Put(Get());
2523 }
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002524 CommandMessage* array_to_free = messages_;
kasper.lund7276f142008-07-30 08:49:36 +00002525 *this = new_queue;
2526 new_queue.messages_ = array_to_free;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002527 // Make the new_queue empty so that it doesn't call Dispose on any messages.
2528 new_queue.start_ = new_queue.end_;
kasper.lund7276f142008-07-30 08:49:36 +00002529 // Automatic destructor called on new_queue, freeing array_to_free.
2530}
2531
2532
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002533LockingCommandMessageQueue::LockingCommandMessageQueue(int size)
2534 : queue_(size) {
kasper.lund7276f142008-07-30 08:49:36 +00002535 lock_ = OS::CreateMutex();
2536}
2537
2538
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002539LockingCommandMessageQueue::~LockingCommandMessageQueue() {
kasper.lund7276f142008-07-30 08:49:36 +00002540 delete lock_;
2541}
2542
2543
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002544bool LockingCommandMessageQueue::IsEmpty() const {
kasper.lund7276f142008-07-30 08:49:36 +00002545 ScopedLock sl(lock_);
2546 return queue_.IsEmpty();
2547}
2548
2549
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002550CommandMessage LockingCommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002551 ScopedLock sl(lock_);
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002552 CommandMessage result = queue_.Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002553 Logger::DebugEvent("Get", result.text());
kasper.lund7276f142008-07-30 08:49:36 +00002554 return result;
2555}
2556
2557
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002558void LockingCommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002559 ScopedLock sl(lock_);
2560 queue_.Put(message);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002561 Logger::DebugEvent("Put", message.text());
kasper.lund7276f142008-07-30 08:49:36 +00002562}
2563
2564
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002565void LockingCommandMessageQueue::Clear() {
kasper.lund7276f142008-07-30 08:49:36 +00002566 ScopedLock sl(lock_);
2567 queue_.Clear();
2568}
2569
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002570#endif // ENABLE_DEBUGGER_SUPPORT
kasper.lund7276f142008-07-30 08:49:36 +00002571
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002572} } // namespace v8::internal