blob: 64f98c7609bd26125b6d1bfb795111e0bf4762d1 [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.
1304 if (function->context()->global() != Top::context()->builtins()) {
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.
1313 if (!holder.is_null() && holder->IsJSFunction()) {
1314 Handle<SharedFunctionInfo> shared_info(
1315 JSFunction::cast(*holder)->shared());
1316 Debug::FloodWithOneShot(shared_info);
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001317 }
1318 } else {
1319 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1320 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001321 }
1322 }
1323}
1324
1325
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001326void Debug::ClearStepping() {
1327 // Clear the various stepping setup.
1328 ClearOneShot();
1329 ClearStepIn();
1330 ClearStepNext();
1331
1332 // Clear multiple step counter.
1333 thread_local_.step_count_ = 0;
1334}
1335
1336// Clears all the one-shot break points that are currently set. Normally this
1337// function is called each time a break point is hit as one shot break points
1338// are used to support stepping.
1339void Debug::ClearOneShot() {
1340 // The current implementation just runs through all the breakpoints. When the
v8.team.kasperl727e9952008-09-02 14:56:44 +00001341 // last break point for a function is removed that function is automatically
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001342 // removed from the list.
1343
1344 DebugInfoListNode* node = debug_info_list_;
1345 while (node != NULL) {
1346 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1347 while (!it.Done()) {
1348 it.ClearOneShot();
1349 it.Next();
1350 }
1351 node = node->next();
1352 }
1353}
1354
1355
1356void Debug::ActivateStepIn(StackFrame* frame) {
1357 thread_local_.step_into_fp_ = frame->fp();
1358}
1359
1360
1361void Debug::ClearStepIn() {
1362 thread_local_.step_into_fp_ = 0;
1363}
1364
1365
1366void Debug::ClearStepNext() {
1367 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +00001368 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001369 thread_local_.last_fp_ = 0;
1370}
1371
1372
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001373bool Debug::EnsureCompiled(Handle<SharedFunctionInfo> shared) {
1374 if (shared->is_compiled()) return true;
ager@chromium.org3bf7b912008-11-17 09:09:45 +00001375 return CompileLazyShared(shared, CLEAR_EXCEPTION, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001376}
1377
1378
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001379// Ensures the debug information is present for shared.
1380bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1381 // Return if we already have the debug info for shared.
1382 if (HasDebugInfo(shared)) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001383
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001384 // Ensure shared in compiled. Return false if this failed.
1385 if (!EnsureCompiled(shared)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001386
1387 // Create the debug info object.
v8.team.kasperl727e9952008-09-02 14:56:44 +00001388 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001389
1390 // Add debug info to the list.
1391 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1392 node->set_next(debug_info_list_);
1393 debug_info_list_ = node;
1394
1395 // Now there is at least one break point.
1396 has_break_points_ = true;
1397
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001398 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001399}
1400
1401
1402void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1403 ASSERT(debug_info_list_ != NULL);
1404 // Run through the debug info objects to find this one and remove it.
1405 DebugInfoListNode* prev = NULL;
1406 DebugInfoListNode* current = debug_info_list_;
1407 while (current != NULL) {
1408 if (*current->debug_info() == *debug_info) {
1409 // Unlink from list. If prev is NULL we are looking at the first element.
1410 if (prev == NULL) {
1411 debug_info_list_ = current->next();
1412 } else {
1413 prev->set_next(current->next());
1414 }
1415 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1416 delete current;
1417
1418 // If there are no more debug info objects there are not more break
1419 // points.
1420 has_break_points_ = debug_info_list_ != NULL;
1421
1422 return;
1423 }
1424 // Move to next in list.
1425 prev = current;
1426 current = current->next();
1427 }
1428 UNREACHABLE();
1429}
1430
1431
1432void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001433 HandleScope scope;
1434
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001435 // Get the executing function in which the debug break occurred.
1436 Handle<SharedFunctionInfo> shared =
1437 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001438 if (!EnsureDebugInfo(shared)) {
1439 // Return if we failed to retrieve the debug info.
1440 return;
1441 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001442 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1443 Handle<Code> code(debug_info->code());
1444 Handle<Code> original_code(debug_info->original_code());
1445#ifdef DEBUG
1446 // Get the code which is actually executing.
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001447 Handle<Code> frame_code(frame->code());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001448 ASSERT(frame_code.is_identical_to(code));
1449#endif
1450
1451 // Find the call address in the running code. This address holds the call to
1452 // either a DebugBreakXXX or to the debug break return entry code if the
1453 // break point is still active after processing the break point.
1454 Address addr = frame->pc() - Assembler::kTargetAddrToReturnAddrDist;
1455
1456 // Check if the location is at JS exit.
1457 bool at_js_exit = false;
1458 RelocIterator it(debug_info->code());
1459 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001460 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001461 at_js_exit = it.rinfo()->pc() == addr - 1;
1462 }
1463 it.next();
1464 }
1465
1466 // Handle the jump to continue execution after break point depending on the
1467 // break location.
1468 if (at_js_exit) {
1469 // First check if the call in the code is still the debug break return
1470 // entry code. If it is the break point is still active. If not the break
1471 // point was removed during break point processing.
1472 if (Assembler::target_address_at(addr) ==
1473 debug_break_return_entry()->entry()) {
1474 // Break point still active. Jump to the corresponding place in the
1475 // original code.
1476 addr += original_code->instruction_start() - code->instruction_start();
1477 }
1478
1479 // Move one byte back to where the call instruction was placed.
1480 thread_local_.after_break_target_ = addr - 1;
1481 } else {
1482 // Check if there still is a debug break call at the target address. If the
1483 // break point has been removed it will have disappeared. If it have
1484 // disappeared don't try to look in the original code as the running code
1485 // will have the right address. This takes care of the case where the last
1486 // break point is removed from the function and therefore no "original code"
1487 // is available. If the debug break call is still there find the address in
1488 // the original code.
1489 if (IsDebugBreak(Assembler::target_address_at(addr))) {
1490 // If the break point is still there find the call address which was
1491 // overwritten in the original code by the call to DebugBreakXXX.
1492
1493 // Find the corresponding address in the original code.
1494 addr += original_code->instruction_start() - code->instruction_start();
1495 }
1496
1497 // Install jump to the call address in the original code. This will be the
1498 // call which was overwritten by the call to DebugBreakXXX.
1499 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1500 }
1501}
1502
1503
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001504bool Debug::IsDebugGlobal(GlobalObject* global) {
1505 return IsLoaded() && global == Debug::debug_context()->global();
1506}
1507
1508
ager@chromium.org32912102009-01-16 10:38:43 +00001509void Debug::ClearMirrorCache() {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001510 HandleScope scope;
ager@chromium.org32912102009-01-16 10:38:43 +00001511 ASSERT(Top::context() == *Debug::debug_context());
1512
1513 // Clear the mirror cache.
1514 Handle<String> function_name =
1515 Factory::LookupSymbol(CStrVector("ClearMirrorCache"));
1516 Handle<Object> fun(Top::global()->GetProperty(*function_name));
1517 ASSERT(fun->IsJSFunction());
1518 bool caught_exception;
1519 Handle<Object> js_object = Execution::TryCall(
1520 Handle<JSFunction>::cast(fun),
1521 Handle<JSObject>(Debug::debug_context()->global()),
1522 0, NULL, &caught_exception);
1523}
1524
1525
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001526// If an object given is an external string, check that the underlying
1527// resource is accessible. For other kinds of objects, always return true.
1528static bool IsExternalStringValid(Object* str) {
1529 if (!str->IsString() || !StringShape(String::cast(str)).IsExternal()) {
1530 return true;
1531 }
1532 if (String::cast(str)->IsAsciiRepresentation()) {
1533 return ExternalAsciiString::cast(str)->resource() != NULL;
1534 } else if (String::cast(str)->IsTwoByteRepresentation()) {
1535 return ExternalTwoByteString::cast(str)->resource() != NULL;
1536 } else {
1537 return true;
1538 }
1539}
1540
1541
1542void Debug::CreateScriptCache() {
1543 HandleScope scope;
1544
1545 // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
1546 // rid of all the cached script wrappers and the second gets rid of the
1547 // scripts which is no longer referenced.
1548 Heap::CollectAllGarbage();
1549 Heap::CollectAllGarbage();
1550
1551 ASSERT(script_cache_ == NULL);
1552 script_cache_ = new ScriptCache();
1553
1554 // Scan heap for Script objects.
1555 int count = 0;
1556 HeapIterator iterator;
1557 while (iterator.has_next()) {
1558 HeapObject* obj = iterator.next();
1559 ASSERT(obj != NULL);
1560 if (obj->IsScript() && IsExternalStringValid(Script::cast(obj)->source())) {
1561 script_cache_->Add(Handle<Script>(Script::cast(obj)));
1562 count++;
1563 }
1564 }
1565}
1566
1567
1568void Debug::DestroyScriptCache() {
1569 // Get rid of the script cache if it was created.
1570 if (script_cache_ != NULL) {
1571 delete script_cache_;
1572 script_cache_ = NULL;
1573 }
1574}
1575
1576
1577void Debug::AddScriptToScriptCache(Handle<Script> script) {
1578 if (script_cache_ != NULL) {
1579 script_cache_->Add(script);
1580 }
1581}
1582
1583
1584Handle<FixedArray> Debug::GetLoadedScripts() {
1585 // Create and fill the script cache when the loaded scripts is requested for
1586 // the first time.
1587 if (script_cache_ == NULL) {
1588 CreateScriptCache();
1589 }
1590
1591 // If the script cache is not active just return an empty array.
1592 ASSERT(script_cache_ != NULL);
1593 if (script_cache_ == NULL) {
1594 Factory::NewFixedArray(0);
1595 }
1596
1597 // Perform GC to get unreferenced scripts evicted from the cache before
1598 // returning the content.
1599 Heap::CollectAllGarbage();
1600
1601 // Get the scripts from the cache.
1602 return script_cache_->GetScripts();
1603}
1604
1605
1606void Debug::AfterGarbageCollection() {
1607 // Generate events for collected scripts.
1608 if (script_cache_ != NULL) {
1609 script_cache_->ProcessCollectedScripts();
1610 }
1611}
1612
1613
ager@chromium.org71daaf62009-04-01 07:22:49 +00001614Mutex* Debugger::debugger_access_ = OS::CreateMutex();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001615Handle<Object> Debugger::event_listener_ = Handle<Object>();
1616Handle<Object> Debugger::event_listener_data_ = Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001617bool Debugger::compiling_natives_ = false;
mads.s.agercbaa0602008-08-14 13:41:48 +00001618bool Debugger::is_loading_debugger_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001619bool Debugger::never_unload_debugger_ = false;
ager@chromium.org5ec48922009-05-05 07:25:34 +00001620v8::Debug::MessageHandler2 Debugger::message_handler_ = NULL;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001621bool Debugger::debugger_unload_pending_ = false;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001622v8::Debug::HostDispatchHandler Debugger::host_dispatch_handler_ = NULL;
1623int Debugger::host_dispatch_micros_ = 100 * 1000;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001624DebuggerAgent* Debugger::agent_ = NULL;
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001625LockingCommandMessageQueue Debugger::command_queue_(kQueueInitialSize);
ager@chromium.org41826e72009-03-30 13:30:57 +00001626Semaphore* Debugger::command_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001627
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001628
1629Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1630 int argc, Object*** argv,
1631 bool* caught_exception) {
1632 ASSERT(Top::context() == *Debug::debug_context());
1633
1634 // Create the execution state object.
1635 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1636 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1637 ASSERT(constructor->IsJSFunction());
1638 if (!constructor->IsJSFunction()) {
1639 *caught_exception = true;
1640 return Factory::undefined_value();
1641 }
1642 Handle<Object> js_object = Execution::TryCall(
1643 Handle<JSFunction>::cast(constructor),
1644 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1645 caught_exception);
1646 return js_object;
1647}
1648
1649
1650Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1651 // Create the execution state object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001652 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001653 const int argc = 1;
1654 Object** argv[argc] = { break_id.location() };
1655 return MakeJSObject(CStrVector("MakeExecutionState"),
1656 argc, argv, caught_exception);
1657}
1658
1659
1660Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1661 Handle<Object> break_points_hit,
1662 bool* caught_exception) {
1663 // Create the new break event object.
1664 const int argc = 2;
1665 Object** argv[argc] = { exec_state.location(),
1666 break_points_hit.location() };
1667 return MakeJSObject(CStrVector("MakeBreakEvent"),
1668 argc,
1669 argv,
1670 caught_exception);
1671}
1672
1673
1674Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1675 Handle<Object> exception,
1676 bool uncaught,
1677 bool* caught_exception) {
1678 // Create the new exception event object.
1679 const int argc = 3;
1680 Object** argv[argc] = { exec_state.location(),
1681 exception.location(),
1682 uncaught ? Factory::true_value().location() :
1683 Factory::false_value().location()};
1684 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1685 argc, argv, caught_exception);
1686}
1687
1688
1689Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1690 bool* caught_exception) {
1691 // Create the new function event object.
1692 const int argc = 1;
1693 Object** argv[argc] = { function.location() };
1694 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1695 argc, argv, caught_exception);
1696}
1697
1698
1699Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001700 bool before,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001701 bool* caught_exception) {
1702 // Create the compile event object.
1703 Handle<Object> exec_state = MakeExecutionState(caught_exception);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001704 Handle<Object> script_wrapper = GetScriptWrapper(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001705 const int argc = 3;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001706 Object** argv[argc] = { exec_state.location(),
1707 script_wrapper.location(),
1708 before ? Factory::true_value().location() :
1709 Factory::false_value().location() };
1710
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001711 return MakeJSObject(CStrVector("MakeCompileEvent"),
1712 argc,
1713 argv,
1714 caught_exception);
1715}
1716
1717
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001718Handle<Object> Debugger::MakeScriptCollectedEvent(int id,
1719 bool* caught_exception) {
1720 // Create the script collected event object.
1721 Handle<Object> exec_state = MakeExecutionState(caught_exception);
1722 Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id));
1723 const int argc = 2;
1724 Object** argv[argc] = { exec_state.location(), id_object.location() };
1725
1726 return MakeJSObject(CStrVector("MakeScriptCollectedEvent"),
1727 argc,
1728 argv,
1729 caught_exception);
1730}
1731
1732
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001733void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1734 HandleScope scope;
1735
1736 // Bail out based on state or if there is no listener for this event
1737 if (Debug::InDebugger()) return;
1738 if (!Debugger::EventActive(v8::Exception)) return;
1739
1740 // Bail out if exception breaks are not active
1741 if (uncaught) {
1742 // Uncaught exceptions are reported by either flags.
1743 if (!(Debug::break_on_uncaught_exception() ||
1744 Debug::break_on_exception())) return;
1745 } else {
1746 // Caught exceptions are reported is activated.
1747 if (!Debug::break_on_exception()) return;
1748 }
1749
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001750 // Enter the debugger.
1751 EnterDebugger debugger;
1752 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001753
1754 // Clear all current stepping setup.
1755 Debug::ClearStepping();
1756 // Create the event data object.
1757 bool caught_exception = false;
1758 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1759 Handle<Object> event_data;
1760 if (!caught_exception) {
1761 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1762 &caught_exception);
1763 }
1764 // Bail out and don't call debugger if exception.
1765 if (caught_exception) {
1766 return;
1767 }
1768
ager@chromium.org5ec48922009-05-05 07:25:34 +00001769 // Process debug event.
1770 ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001771 // Return to continue execution from where the exception was thrown.
1772}
1773
1774
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001775void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
1776 bool auto_continue) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001777 HandleScope scope;
1778
kasper.lund212ac232008-07-16 07:07:30 +00001779 // Debugger has already been entered by caller.
1780 ASSERT(Top::context() == *Debug::debug_context());
1781
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001782 // Bail out if there is no listener for this event
1783 if (!Debugger::EventActive(v8::Break)) return;
1784
1785 // Debugger must be entered in advance.
1786 ASSERT(Top::context() == *Debug::debug_context());
1787
1788 // Create the event data object.
1789 bool caught_exception = false;
1790 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1791 Handle<Object> event_data;
1792 if (!caught_exception) {
1793 event_data = MakeBreakEvent(exec_state, break_points_hit,
1794 &caught_exception);
1795 }
1796 // Bail out and don't call debugger if exception.
1797 if (caught_exception) {
1798 return;
1799 }
1800
ager@chromium.org5ec48922009-05-05 07:25:34 +00001801 // Process debug event.
1802 ProcessDebugEvent(v8::Break,
1803 Handle<JSObject>::cast(event_data),
1804 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001805}
1806
1807
1808void Debugger::OnBeforeCompile(Handle<Script> script) {
1809 HandleScope scope;
1810
1811 // Bail out based on state or if there is no listener for this event
1812 if (Debug::InDebugger()) return;
1813 if (compiling_natives()) return;
1814 if (!EventActive(v8::BeforeCompile)) return;
1815
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001816 // Enter the debugger.
1817 EnterDebugger debugger;
1818 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001819
1820 // Create the event data object.
1821 bool caught_exception = false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001822 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001823 // Bail out and don't call debugger if exception.
1824 if (caught_exception) {
1825 return;
1826 }
1827
ager@chromium.org5ec48922009-05-05 07:25:34 +00001828 // Process debug event.
1829 ProcessDebugEvent(v8::BeforeCompile,
1830 Handle<JSObject>::cast(event_data),
1831 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001832}
1833
1834
1835// Handle debugger actions when a new script is compiled.
1836void Debugger::OnAfterCompile(Handle<Script> script, Handle<JSFunction> fun) {
kasper.lund212ac232008-07-16 07:07:30 +00001837 HandleScope scope;
1838
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001839 // Add the newly compiled script to the script cache.
1840 Debug::AddScriptToScriptCache(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001841
1842 // No more to do if not debugging.
ager@chromium.org71daaf62009-04-01 07:22:49 +00001843 if (!IsDebuggerActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001844
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001845 // No compile events while compiling natives.
1846 if (compiling_natives()) return;
1847
iposva@chromium.org245aa852009-02-10 00:49:54 +00001848 // Store whether in debugger before entering debugger.
1849 bool in_debugger = Debug::InDebugger();
1850
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001851 // Enter the debugger.
1852 EnterDebugger debugger;
1853 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001854
1855 // If debugging there might be script break points registered for this
1856 // script. Make sure that these break points are set.
1857
1858 // Get the function UpdateScriptBreakPoints (defined in debug-delay.js).
1859 Handle<Object> update_script_break_points =
1860 Handle<Object>(Debug::debug_context()->global()->GetProperty(
1861 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
1862 if (!update_script_break_points->IsJSFunction()) {
1863 return;
1864 }
1865 ASSERT(update_script_break_points->IsJSFunction());
1866
1867 // Wrap the script object in a proper JS object before passing it
1868 // to JavaScript.
1869 Handle<JSValue> wrapper = GetScriptWrapper(script);
1870
1871 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00001872 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001873 const int argc = 1;
1874 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
1875 Handle<Object> result = Execution::TryCall(
1876 Handle<JSFunction>::cast(update_script_break_points),
1877 Top::builtins(), argc, argv,
1878 &caught_exception);
1879 if (caught_exception) {
1880 return;
1881 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001882 // Bail out based on state or if there is no listener for this event
iposva@chromium.org245aa852009-02-10 00:49:54 +00001883 if (in_debugger) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001884 if (!Debugger::EventActive(v8::AfterCompile)) return;
1885
1886 // Create the compile state object.
1887 Handle<Object> event_data = MakeCompileEvent(script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001888 false,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001889 &caught_exception);
1890 // Bail out and don't call debugger if exception.
1891 if (caught_exception) {
1892 return;
1893 }
ager@chromium.org5ec48922009-05-05 07:25:34 +00001894 // Process debug event.
1895 ProcessDebugEvent(v8::AfterCompile,
1896 Handle<JSObject>::cast(event_data),
1897 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001898}
1899
1900
1901void Debugger::OnNewFunction(Handle<JSFunction> function) {
1902 return;
1903 HandleScope scope;
1904
1905 // Bail out based on state or if there is no listener for this event
1906 if (Debug::InDebugger()) return;
1907 if (compiling_natives()) return;
1908 if (!Debugger::EventActive(v8::NewFunction)) return;
1909
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001910 // Enter the debugger.
1911 EnterDebugger debugger;
1912 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001913
1914 // Create the event object.
1915 bool caught_exception = false;
1916 Handle<Object> event_data = MakeNewFunctionEvent(function, &caught_exception);
1917 // Bail out and don't call debugger if exception.
1918 if (caught_exception) {
1919 return;
1920 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001921 // Process debug event.
ager@chromium.org5ec48922009-05-05 07:25:34 +00001922 ProcessDebugEvent(v8::NewFunction, Handle<JSObject>::cast(event_data), true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001923}
1924
1925
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001926void Debugger::OnScriptCollected(int id) {
1927 HandleScope scope;
1928
1929 // No more to do if not debugging.
1930 if (!IsDebuggerActive()) return;
1931 if (!Debugger::EventActive(v8::ScriptCollected)) return;
1932
1933 // Enter the debugger.
1934 EnterDebugger debugger;
1935 if (debugger.FailedToEnter()) return;
1936
1937 // Create the script collected state object.
1938 bool caught_exception = false;
1939 Handle<Object> event_data = MakeScriptCollectedEvent(id,
1940 &caught_exception);
1941 // Bail out and don't call debugger if exception.
1942 if (caught_exception) {
1943 return;
1944 }
1945
1946 // Process debug event.
1947 ProcessDebugEvent(v8::ScriptCollected,
1948 Handle<JSObject>::cast(event_data),
1949 true);
1950}
1951
1952
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001953void Debugger::ProcessDebugEvent(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00001954 Handle<JSObject> event_data,
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001955 bool auto_continue) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001956 HandleScope scope;
1957
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00001958 // Clear any pending debug break if this is a real break.
1959 if (!auto_continue) {
1960 Debug::clear_interrupt_pending(DEBUGBREAK);
1961 }
1962
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001963 // Create the execution state.
1964 bool caught_exception = false;
1965 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1966 if (caught_exception) {
1967 return;
1968 }
ager@chromium.org41826e72009-03-30 13:30:57 +00001969 // First notify the message handler if any.
1970 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00001971 NotifyMessageHandler(event,
1972 Handle<JSObject>::cast(exec_state),
1973 event_data,
1974 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001975 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001976 // Notify registered debug event listener. This can be either a C or a
1977 // JavaScript function.
1978 if (!event_listener_.is_null()) {
1979 if (event_listener_->IsProxy()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001980 // C debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00001981 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001982 v8::Debug::EventCallback callback =
1983 FUNCTION_CAST<v8::Debug::EventCallback>(callback_obj->proxy());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001984 callback(event,
1985 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state)),
ager@chromium.org5ec48922009-05-05 07:25:34 +00001986 v8::Utils::ToLocal(event_data),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001987 v8::Utils::ToLocal(Handle<Object>::cast(event_listener_data_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001988 } else {
1989 // JavaScript debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00001990 ASSERT(event_listener_->IsJSFunction());
1991 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001992
1993 // Invoke the JavaScript debug event listener.
1994 const int argc = 4;
1995 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
1996 exec_state.location(),
ager@chromium.org5ec48922009-05-05 07:25:34 +00001997 Handle<Object>::cast(event_data).location(),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001998 event_listener_data_.location() };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001999 Handle<Object> result = Execution::TryCall(fun, Top::global(),
2000 argc, argv, &caught_exception);
2001 if (caught_exception) {
2002 // Silently ignore exceptions from debug event listeners.
2003 }
2004 }
2005 }
2006}
2007
2008
ager@chromium.org71daaf62009-04-01 07:22:49 +00002009void Debugger::UnloadDebugger() {
2010 // Make sure that there are no breakpoints left.
2011 Debug::ClearAllBreakPoints();
2012
2013 // Unload the debugger if feasible.
2014 if (!never_unload_debugger_) {
2015 Debug::Unload();
2016 }
2017
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002018 // Clear the flag indicating that the debugger should be unloaded.
2019 debugger_unload_pending_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00002020}
2021
2022
ager@chromium.org41826e72009-03-30 13:30:57 +00002023void Debugger::NotifyMessageHandler(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002024 Handle<JSObject> exec_state,
2025 Handle<JSObject> event_data,
ager@chromium.org41826e72009-03-30 13:30:57 +00002026 bool auto_continue) {
2027 HandleScope scope;
2028
2029 if (!Debug::Load()) return;
2030
2031 // Process the individual events.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002032 bool sendEventMessage = false;
ager@chromium.org41826e72009-03-30 13:30:57 +00002033 switch (event) {
2034 case v8::Break:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002035 sendEventMessage = !auto_continue;
ager@chromium.org41826e72009-03-30 13:30:57 +00002036 break;
2037 case v8::Exception:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002038 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002039 break;
2040 case v8::BeforeCompile:
2041 break;
2042 case v8::AfterCompile:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002043 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002044 break;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002045 case v8::ScriptCollected:
2046 sendEventMessage = true;
2047 break;
ager@chromium.org41826e72009-03-30 13:30:57 +00002048 case v8::NewFunction:
2049 break;
2050 default:
2051 UNREACHABLE();
2052 }
2053
ager@chromium.org5ec48922009-05-05 07:25:34 +00002054 // The debug command interrupt flag might have been set when the command was
2055 // added. It should be enough to clear the flag only once while we are in the
2056 // debugger.
2057 ASSERT(Debug::InDebugger());
2058 StackGuard::Continue(DEBUGCOMMAND);
2059
2060 // Notify the debugger that a debug event has occurred unless auto continue is
2061 // active in which case no event is send.
2062 if (sendEventMessage) {
2063 MessageImpl message = MessageImpl::NewEvent(
2064 event,
2065 auto_continue,
2066 Handle<JSObject>::cast(exec_state),
2067 Handle<JSObject>::cast(event_data));
2068 InvokeMessageHandler(message);
2069 }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002070
2071 // If auto continue don't make the event cause a break, but process messages
2072 // in the queue if any. For script collected events don't even process
2073 // messages in the queue as the execution state might not be what is expected
2074 // by the client.
ager@chromium.org6ffc2172009-05-29 19:20:16 +00002075 if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002076 return;
2077 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002078
2079 // Get the DebugCommandProcessor.
2080 v8::Local<v8::Object> api_exec_state =
2081 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
2082 v8::Local<v8::String> fun_name =
2083 v8::String::New("debugCommandProcessor");
2084 v8::Local<v8::Function> fun =
2085 v8::Function::Cast(*api_exec_state->Get(fun_name));
2086 v8::TryCatch try_catch;
2087 v8::Local<v8::Object> cmd_processor =
2088 v8::Object::Cast(*fun->Call(api_exec_state, 0, NULL));
2089 if (try_catch.HasCaught()) {
2090 PrintLn(try_catch.Exception());
2091 return;
2092 }
2093
ager@chromium.org41826e72009-03-30 13:30:57 +00002094 // Process requests from the debugger.
2095 while (true) {
2096 // Wait for new command in the queue.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002097 if (Debugger::host_dispatch_handler_) {
2098 // In case there is a host dispatch - do periodic dispatches.
2099 if (!command_received_->Wait(host_dispatch_micros_)) {
2100 // Timout expired, do the dispatch.
2101 Debugger::host_dispatch_handler_();
2102 continue;
2103 }
2104 } else {
2105 // In case there is no host dispatch - just wait.
2106 command_received_->Wait();
2107 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002108
ager@chromium.org41826e72009-03-30 13:30:57 +00002109 // Get the command from the queue.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002110 CommandMessage command = command_queue_.Get();
ager@chromium.org41826e72009-03-30 13:30:57 +00002111 Logger::DebugTag("Got request from command queue, in interactive loop.");
ager@chromium.org71daaf62009-04-01 07:22:49 +00002112 if (!Debugger::IsDebuggerActive()) {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002113 // Delete command text and user data.
2114 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002115 return;
2116 }
2117
ager@chromium.org41826e72009-03-30 13:30:57 +00002118 // Invoke JavaScript to process the debug request.
2119 v8::Local<v8::String> fun_name;
2120 v8::Local<v8::Function> fun;
2121 v8::Local<v8::Value> request;
2122 v8::TryCatch try_catch;
2123 fun_name = v8::String::New("processDebugRequest");
2124 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002125
2126 request = v8::String::New(command.text().start(),
2127 command.text().length());
ager@chromium.org41826e72009-03-30 13:30:57 +00002128 static const int kArgc = 1;
2129 v8::Handle<Value> argv[kArgc] = { request };
2130 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
2131
2132 // Get the response.
2133 v8::Local<v8::String> response;
2134 bool running = false;
2135 if (!try_catch.HasCaught()) {
2136 // Get response string.
2137 if (!response_val->IsUndefined()) {
2138 response = v8::String::Cast(*response_val);
2139 } else {
2140 response = v8::String::New("");
2141 }
2142
2143 // Log the JSON request/response.
2144 if (FLAG_trace_debug_json) {
2145 PrintLn(request);
2146 PrintLn(response);
2147 }
2148
2149 // Get the running state.
2150 fun_name = v8::String::New("isRunning");
2151 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2152 static const int kArgc = 1;
2153 v8::Handle<Value> argv[kArgc] = { response };
2154 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
2155 if (!try_catch.HasCaught()) {
2156 running = running_val->ToBoolean()->Value();
2157 }
2158 } else {
2159 // In case of failure the result text is the exception text.
2160 response = try_catch.Exception()->ToString();
2161 }
2162
ager@chromium.org41826e72009-03-30 13:30:57 +00002163 // Return the result.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002164 MessageImpl message = MessageImpl::NewResponse(
2165 event,
2166 running,
2167 Handle<JSObject>::cast(exec_state),
2168 Handle<JSObject>::cast(event_data),
2169 Handle<String>(Utils::OpenHandle(*response)),
2170 command.client_data());
2171 InvokeMessageHandler(message);
2172 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002173
2174 // Return from debug event processing if either the VM is put into the
2175 // runnning state (through a continue command) or auto continue is active
2176 // and there are no more commands queued.
2177 if (running || (auto_continue && !HasCommands())) {
2178 return;
2179 }
2180 }
2181}
2182
2183
iposva@chromium.org245aa852009-02-10 00:49:54 +00002184void Debugger::SetEventListener(Handle<Object> callback,
2185 Handle<Object> data) {
2186 HandleScope scope;
2187
2188 // Clear the global handles for the event listener and the event listener data
2189 // object.
2190 if (!event_listener_.is_null()) {
2191 GlobalHandles::Destroy(
2192 reinterpret_cast<Object**>(event_listener_.location()));
2193 event_listener_ = Handle<Object>();
2194 }
2195 if (!event_listener_data_.is_null()) {
2196 GlobalHandles::Destroy(
2197 reinterpret_cast<Object**>(event_listener_data_.location()));
2198 event_listener_data_ = Handle<Object>();
2199 }
2200
2201 // If there is a new debug event listener register it together with its data
2202 // object.
2203 if (!callback->IsUndefined() && !callback->IsNull()) {
2204 event_listener_ = Handle<Object>::cast(GlobalHandles::Create(*callback));
2205 if (data.is_null()) {
2206 data = Factory::undefined_value();
2207 }
2208 event_listener_data_ = Handle<Object>::cast(GlobalHandles::Create(*data));
2209 }
2210
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002211 ListenersChanged();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002212}
2213
2214
ager@chromium.org5ec48922009-05-05 07:25:34 +00002215void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002216 ScopedLock with(debugger_access_);
2217
ager@chromium.org381abbb2009-02-25 13:23:22 +00002218 message_handler_ = handler;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002219 ListenersChanged();
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002220 if (handler == NULL) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002221 // Send an empty command to the debugger if in a break to make JavaScript
2222 // run again if the debugger is closed.
2223 if (Debug::InDebugger()) {
2224 ProcessCommand(Vector<const uint16_t>::empty());
2225 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002226 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002227}
2228
2229
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002230void Debugger::ListenersChanged() {
2231 if (IsDebuggerActive()) {
2232 // Disable the compilation cache when the debugger is active.
2233 CompilationCache::Disable();
2234 } else {
2235 CompilationCache::Enable();
2236
2237 // Unload the debugger if event listener and message handler cleared.
2238 if (Debug::InDebugger()) {
2239 // If we are in debugger set the flag to unload the debugger when last
2240 // EnterDebugger on the current stack is destroyed.
2241 debugger_unload_pending_ = true;
2242 } else {
2243 UnloadDebugger();
2244 }
2245 }
2246}
2247
2248
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002249void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
2250 int period) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002251 host_dispatch_handler_ = handler;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002252 host_dispatch_micros_ = period * 1000;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002253}
2254
2255
ager@chromium.org41826e72009-03-30 13:30:57 +00002256// Calls the registered debug message handler. This callback is part of the
ager@chromium.org5ec48922009-05-05 07:25:34 +00002257// public API.
2258void Debugger::InvokeMessageHandler(MessageImpl message) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002259 ScopedLock with(debugger_access_);
2260
ager@chromium.org381abbb2009-02-25 13:23:22 +00002261 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002262 message_handler_(message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002263 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002264}
2265
2266
2267// Puts a command coming from the public API on the queue. Creates
2268// a copy of the command string managed by the debugger. Up to this
2269// point, the command data was managed by the API client. Called
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002270// by the API client thread.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002271void Debugger::ProcessCommand(Vector<const uint16_t> command,
2272 v8::Debug::ClientData* client_data) {
2273 // Need to cast away const.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002274 CommandMessage message = CommandMessage::New(
ager@chromium.org41826e72009-03-30 13:30:57 +00002275 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002276 command.length()),
2277 client_data);
ager@chromium.org41826e72009-03-30 13:30:57 +00002278 Logger::DebugTag("Put command on command_queue.");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002279 command_queue_.Put(message);
ager@chromium.org41826e72009-03-30 13:30:57 +00002280 command_received_->Signal();
sgjesse@chromium.org3afc1582009-04-16 22:31:44 +00002281
2282 // Set the debug command break flag to have the command processed.
ager@chromium.org41826e72009-03-30 13:30:57 +00002283 if (!Debug::InDebugger()) {
2284 StackGuard::DebugCommand();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002285 }
2286}
2287
2288
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002289bool Debugger::HasCommands() {
ager@chromium.org41826e72009-03-30 13:30:57 +00002290 return !command_queue_.IsEmpty();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002291}
2292
2293
ager@chromium.org71daaf62009-04-01 07:22:49 +00002294bool Debugger::IsDebuggerActive() {
2295 ScopedLock with(debugger_access_);
2296
2297 return message_handler_ != NULL || !event_listener_.is_null();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002298}
2299
2300
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002301Handle<Object> Debugger::Call(Handle<JSFunction> fun,
2302 Handle<Object> data,
2303 bool* pending_exception) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002304 // When calling functions in the debugger prevent it from beeing unloaded.
2305 Debugger::never_unload_debugger_ = true;
2306
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002307 // Enter the debugger.
2308 EnterDebugger debugger;
2309 if (debugger.FailedToEnter() || !debugger.HasJavaScriptFrames()) {
2310 return Factory::undefined_value();
2311 }
2312
2313 // Create the execution state.
2314 bool caught_exception = false;
2315 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2316 if (caught_exception) {
2317 return Factory::undefined_value();
2318 }
2319
2320 static const int kArgc = 2;
2321 Object** argv[kArgc] = { exec_state.location(), data.location() };
2322 Handle<Object> result = Execution::Call(fun, Factory::undefined_value(),
2323 kArgc, argv, pending_exception);
2324 return result;
2325}
2326
2327
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002328bool Debugger::StartAgent(const char* name, int port) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002329 if (Socket::Setup()) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002330 agent_ = new DebuggerAgent(name, port);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002331 agent_->Start();
2332 return true;
2333 }
2334
2335 return false;
2336}
2337
2338
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002339void Debugger::StopAgent() {
2340 if (agent_ != NULL) {
2341 agent_->Shutdown();
2342 agent_->Join();
2343 delete agent_;
2344 agent_ = NULL;
2345 }
2346}
2347
2348
ager@chromium.org5ec48922009-05-05 07:25:34 +00002349MessageImpl MessageImpl::NewEvent(DebugEvent event,
2350 bool running,
2351 Handle<JSObject> exec_state,
2352 Handle<JSObject> event_data) {
2353 MessageImpl message(true, event, running,
2354 exec_state, event_data, Handle<String>(), NULL);
2355 return message;
2356}
2357
2358
2359MessageImpl MessageImpl::NewResponse(DebugEvent event,
2360 bool running,
2361 Handle<JSObject> exec_state,
2362 Handle<JSObject> event_data,
2363 Handle<String> response_json,
2364 v8::Debug::ClientData* client_data) {
2365 MessageImpl message(false, event, running,
2366 exec_state, event_data, response_json, client_data);
2367 return message;
2368}
2369
2370
2371MessageImpl::MessageImpl(bool is_event,
2372 DebugEvent event,
2373 bool running,
2374 Handle<JSObject> exec_state,
2375 Handle<JSObject> event_data,
2376 Handle<String> response_json,
2377 v8::Debug::ClientData* client_data)
2378 : is_event_(is_event),
2379 event_(event),
2380 running_(running),
2381 exec_state_(exec_state),
2382 event_data_(event_data),
2383 response_json_(response_json),
2384 client_data_(client_data) {}
2385
2386
2387bool MessageImpl::IsEvent() const {
2388 return is_event_;
2389}
2390
2391
2392bool MessageImpl::IsResponse() const {
2393 return !is_event_;
2394}
2395
2396
2397DebugEvent MessageImpl::GetEvent() const {
2398 return event_;
2399}
2400
2401
2402bool MessageImpl::WillStartRunning() const {
2403 return running_;
2404}
2405
2406
2407v8::Handle<v8::Object> MessageImpl::GetExecutionState() const {
2408 return v8::Utils::ToLocal(exec_state_);
2409}
2410
2411
2412v8::Handle<v8::Object> MessageImpl::GetEventData() const {
2413 return v8::Utils::ToLocal(event_data_);
2414}
2415
2416
2417v8::Handle<v8::String> MessageImpl::GetJSON() const {
2418 v8::HandleScope scope;
2419
2420 if (IsEvent()) {
2421 // Call toJSONProtocol on the debug event object.
2422 Handle<Object> fun = GetProperty(event_data_, "toJSONProtocol");
2423 if (!fun->IsJSFunction()) {
2424 return v8::Handle<v8::String>();
2425 }
2426 bool caught_exception;
2427 Handle<Object> json = Execution::TryCall(Handle<JSFunction>::cast(fun),
2428 event_data_,
2429 0, NULL, &caught_exception);
2430 if (caught_exception || !json->IsString()) {
2431 return v8::Handle<v8::String>();
2432 }
2433 return scope.Close(v8::Utils::ToLocal(Handle<String>::cast(json)));
2434 } else {
2435 return v8::Utils::ToLocal(response_json_);
2436 }
2437}
2438
2439
2440v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002441 Handle<Context> context = Debug::debugger_entry()->GetContext();
2442 // Top::context() may have been NULL when "script collected" event occured.
2443 if (*context == NULL) {
2444 ASSERT(event_ == v8::ScriptCollected);
2445 return v8::Local<v8::Context>();
2446 }
2447 Handle<Context> global_context(context->global_context());
2448 return v8::Utils::ToLocal(global_context);
ager@chromium.org5ec48922009-05-05 07:25:34 +00002449}
2450
2451
2452v8::Debug::ClientData* MessageImpl::GetClientData() const {
2453 return client_data_;
2454}
2455
2456
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002457CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
2458 client_data_(NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002459}
2460
2461
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002462CommandMessage::CommandMessage(const Vector<uint16_t>& text,
2463 v8::Debug::ClientData* data)
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002464 : text_(text),
2465 client_data_(data) {
2466}
2467
2468
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002469CommandMessage::~CommandMessage() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002470}
2471
2472
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002473void CommandMessage::Dispose() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002474 text_.Dispose();
2475 delete client_data_;
2476 client_data_ = NULL;
2477}
2478
2479
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002480CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
2481 v8::Debug::ClientData* data) {
2482 return CommandMessage(command.Clone(), data);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002483}
2484
2485
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002486CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
2487 size_(size) {
2488 messages_ = NewArray<CommandMessage>(size);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002489}
2490
2491
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002492CommandMessageQueue::~CommandMessageQueue() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002493 while (!IsEmpty()) {
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002494 CommandMessage m = Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002495 m.Dispose();
2496 }
kasper.lund7276f142008-07-30 08:49:36 +00002497 DeleteArray(messages_);
2498}
2499
2500
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002501CommandMessage CommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002502 ASSERT(!IsEmpty());
2503 int result = start_;
2504 start_ = (start_ + 1) % size_;
2505 return messages_[result];
2506}
2507
2508
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002509void CommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002510 if ((end_ + 1) % size_ == start_) {
2511 Expand();
2512 }
2513 messages_[end_] = message;
2514 end_ = (end_ + 1) % size_;
2515}
2516
2517
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002518void CommandMessageQueue::Expand() {
2519 CommandMessageQueue new_queue(size_ * 2);
kasper.lund7276f142008-07-30 08:49:36 +00002520 while (!IsEmpty()) {
2521 new_queue.Put(Get());
2522 }
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002523 CommandMessage* array_to_free = messages_;
kasper.lund7276f142008-07-30 08:49:36 +00002524 *this = new_queue;
2525 new_queue.messages_ = array_to_free;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002526 // Make the new_queue empty so that it doesn't call Dispose on any messages.
2527 new_queue.start_ = new_queue.end_;
kasper.lund7276f142008-07-30 08:49:36 +00002528 // Automatic destructor called on new_queue, freeing array_to_free.
2529}
2530
2531
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002532LockingCommandMessageQueue::LockingCommandMessageQueue(int size)
2533 : queue_(size) {
kasper.lund7276f142008-07-30 08:49:36 +00002534 lock_ = OS::CreateMutex();
2535}
2536
2537
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002538LockingCommandMessageQueue::~LockingCommandMessageQueue() {
kasper.lund7276f142008-07-30 08:49:36 +00002539 delete lock_;
2540}
2541
2542
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002543bool LockingCommandMessageQueue::IsEmpty() const {
kasper.lund7276f142008-07-30 08:49:36 +00002544 ScopedLock sl(lock_);
2545 return queue_.IsEmpty();
2546}
2547
2548
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002549CommandMessage LockingCommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002550 ScopedLock sl(lock_);
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002551 CommandMessage result = queue_.Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002552 Logger::DebugEvent("Get", result.text());
kasper.lund7276f142008-07-30 08:49:36 +00002553 return result;
2554}
2555
2556
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002557void LockingCommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002558 ScopedLock sl(lock_);
2559 queue_.Put(message);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002560 Logger::DebugEvent("Put", message.text());
kasper.lund7276f142008-07-30 08:49:36 +00002561}
2562
2563
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002564void LockingCommandMessageQueue::Clear() {
kasper.lund7276f142008-07-30 08:49:36 +00002565 ScopedLock sl(lock_);
2566 queue_.Clear();
2567}
2568
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002569#endif // ENABLE_DEBUGGER_SUPPORT
kasper.lund7276f142008-07-30 08:49:36 +00002570
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002571} } // namespace v8::internal