v8  3.25.30(node0.11.13)
V8 is Google's open source JavaScript engine
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
d8-debug.cc
Go to the documentation of this file.
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
4 // met:
5 //
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
15 //
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 
28 #ifdef ENABLE_DEBUGGER_SUPPORT
29 
30 #include "d8.h"
31 #include "d8-debug.h"
32 #include "debug-agent.h"
33 #include "platform/socket.h"
34 
35 
36 namespace v8 {
37 
38 static bool was_running = true;
39 
40 void PrintPrompt(bool is_running) {
41  const char* prompt = is_running? "> " : "dbg> ";
42  was_running = is_running;
43  printf("%s", prompt);
44  fflush(stdout);
45 }
46 
47 
48 void PrintPrompt() {
49  PrintPrompt(was_running);
50 }
51 
52 
53 void HandleDebugEvent(const Debug::EventDetails& event_details) {
54  // TODO(svenpanne) There should be a way to retrieve this in the callback.
55  Isolate* isolate = Isolate::GetCurrent();
56  HandleScope scope(isolate);
57 
58  DebugEvent event = event_details.GetEvent();
59  // Check for handled event.
60  if (event != Break && event != Exception && event != AfterCompile) {
61  return;
62  }
63 
64  TryCatch try_catch;
65 
66  // Get the toJSONProtocol function on the event and get the JSON format.
67  Local<String> to_json_fun_name =
68  String::NewFromUtf8(isolate, "toJSONProtocol");
69  Handle<Object> event_data = event_details.GetEventData();
70  Local<Function> to_json_fun =
71  Local<Function>::Cast(event_data->Get(to_json_fun_name));
72  Local<Value> event_json = to_json_fun->Call(event_data, 0, NULL);
73  if (try_catch.HasCaught()) {
74  Shell::ReportException(isolate, &try_catch);
75  return;
76  }
77 
78  // Print the event details.
79  Handle<Object> details =
80  Shell::DebugMessageDetails(isolate, Handle<String>::Cast(event_json));
81  if (try_catch.HasCaught()) {
82  Shell::ReportException(isolate, &try_catch);
83  return;
84  }
85  String::Utf8Value str(details->Get(String::NewFromUtf8(isolate, "text")));
86  if (str.length() == 0) {
87  // Empty string is used to signal not to process this event.
88  return;
89  }
90  printf("%s\n", *str);
91 
92  // Get the debug command processor.
93  Local<String> fun_name =
94  String::NewFromUtf8(isolate, "debugCommandProcessor");
95  Handle<Object> exec_state = event_details.GetExecutionState();
96  Local<Function> fun = Local<Function>::Cast(exec_state->Get(fun_name));
97  Local<Object> cmd_processor =
98  Local<Object>::Cast(fun->Call(exec_state, 0, NULL));
99  if (try_catch.HasCaught()) {
100  Shell::ReportException(isolate, &try_catch);
101  return;
102  }
103 
104  static const int kBufferSize = 256;
105  bool running = false;
106  while (!running) {
107  char command[kBufferSize];
108  PrintPrompt(running);
109  char* str = fgets(command, kBufferSize, stdin);
110  if (str == NULL) break;
111 
112  // Ignore empty commands.
113  if (strlen(command) == 0) continue;
114 
115  TryCatch try_catch;
116 
117  // Convert the debugger command to a JSON debugger request.
118  Handle<Value> request = Shell::DebugCommandToJSONRequest(
119  isolate, String::NewFromUtf8(isolate, command));
120  if (try_catch.HasCaught()) {
121  Shell::ReportException(isolate, &try_catch);
122  continue;
123  }
124 
125  // If undefined is returned the command was handled internally and there is
126  // no JSON to send.
127  if (request->IsUndefined()) {
128  continue;
129  }
130 
131  Handle<String> fun_name;
132  Handle<Function> fun;
133  // All the functions used below take one argument.
134  static const int kArgc = 1;
135  Handle<Value> args[kArgc];
136 
137  // Invoke the JavaScript to convert the debug command line to a JSON
138  // request, invoke the JSON request and convert the JSON respose to a text
139  // representation.
140  fun_name = String::NewFromUtf8(isolate, "processDebugRequest");
141  fun = Handle<Function>::Cast(cmd_processor->Get(fun_name));
142  args[0] = request;
143  Handle<Value> response_val = fun->Call(cmd_processor, kArgc, args);
144  if (try_catch.HasCaught()) {
145  Shell::ReportException(isolate, &try_catch);
146  continue;
147  }
148  Handle<String> response = Handle<String>::Cast(response_val);
149 
150  // Convert the debugger response into text details and the running state.
151  Handle<Object> response_details =
152  Shell::DebugMessageDetails(isolate, response);
153  if (try_catch.HasCaught()) {
154  Shell::ReportException(isolate, &try_catch);
155  continue;
156  }
157  String::Utf8Value text_str(
158  response_details->Get(String::NewFromUtf8(isolate, "text")));
159  if (text_str.length() > 0) {
160  printf("%s\n", *text_str);
161  }
162  running = response_details->Get(String::NewFromUtf8(isolate, "running"))
163  ->ToBoolean()
164  ->Value();
165  }
166 }
167 
168 
169 void RunRemoteDebugger(Isolate* isolate, int port) {
170  RemoteDebugger debugger(isolate, port);
171  debugger.Run();
172 }
173 
174 
175 void RemoteDebugger::Run() {
176  bool ok;
177 
178  // Connect to the debugger agent.
179  conn_ = new i::Socket;
180  static const int kPortStrSize = 6;
181  char port_str[kPortStrSize];
182  i::OS::SNPrintF(i::Vector<char>(port_str, kPortStrSize), "%d", port_);
183  ok = conn_->Connect("localhost", port_str);
184  if (!ok) {
185  printf("Unable to connect to debug agent %d\n", i::Socket::GetLastError());
186  return;
187  }
188 
189  // Start the receiver thread.
190  ReceiverThread receiver(this);
191  receiver.Start();
192 
193  // Start the keyboard thread.
194  KeyboardThread keyboard(this);
195  keyboard.Start();
196  PrintPrompt();
197 
198  // Process events received from debugged VM and from the keyboard.
199  bool terminate = false;
200  while (!terminate) {
201  event_available_.Wait();
202  RemoteDebuggerEvent* event = GetEvent();
203  switch (event->type()) {
205  HandleMessageReceived(event->data());
206  break;
208  HandleKeyboardCommand(event->data());
209  break;
211  terminate = true;
212  break;
213 
214  default:
215  UNREACHABLE();
216  }
217  delete event;
218  }
219 
220  delete conn_;
221  conn_ = NULL;
222  // Wait for the receiver thread to end.
223  receiver.Join();
224 }
225 
226 
228  RemoteDebuggerEvent* event =
229  new RemoteDebuggerEvent(RemoteDebuggerEvent::kMessage, message);
230  AddEvent(event);
231 }
232 
233 
235  RemoteDebuggerEvent* event =
236  new RemoteDebuggerEvent(RemoteDebuggerEvent::kKeyboard, command);
237  AddEvent(event);
238 }
239 
240 
242  RemoteDebuggerEvent* event =
243  new RemoteDebuggerEvent(RemoteDebuggerEvent::kDisconnect,
245  AddEvent(event);
246 }
247 
248 
249 void RemoteDebugger::AddEvent(RemoteDebuggerEvent* event) {
250  i::LockGuard<i::Mutex> lock_guard(&event_access_);
251  if (head_ == NULL) {
252  ASSERT(tail_ == NULL);
253  head_ = event;
254  tail_ = event;
255  } else {
256  ASSERT(tail_ != NULL);
257  tail_->set_next(event);
258  tail_ = event;
259  }
260  event_available_.Signal();
261 }
262 
263 
264 RemoteDebuggerEvent* RemoteDebugger::GetEvent() {
265  i::LockGuard<i::Mutex> lock_guard(&event_access_);
266  ASSERT(head_ != NULL);
267  RemoteDebuggerEvent* result = head_;
268  head_ = head_->next();
269  if (head_ == NULL) {
270  ASSERT(tail_ == result);
271  tail_ = NULL;
272  }
273  return result;
274 }
275 
276 
277 void RemoteDebugger::HandleMessageReceived(char* message) {
278  Locker lock(isolate_);
279  HandleScope scope(isolate_);
280 
281  // Print the event details.
282  TryCatch try_catch;
283  Handle<Object> details = Shell::DebugMessageDetails(
284  isolate_, Handle<String>::Cast(String::NewFromUtf8(isolate_, message)));
285  if (try_catch.HasCaught()) {
286  Shell::ReportException(isolate_, &try_catch);
287  PrintPrompt();
288  return;
289  }
290  String::Utf8Value str(details->Get(String::NewFromUtf8(isolate_, "text")));
291  if (str.length() == 0) {
292  // Empty string is used to signal not to process this event.
293  return;
294  }
295  if (*str != NULL) {
296  printf("%s\n", *str);
297  } else {
298  printf("???\n");
299  }
300 
301  bool is_running = details->Get(String::NewFromUtf8(isolate_, "running"))
302  ->ToBoolean()
303  ->Value();
304  PrintPrompt(is_running);
305 }
306 
307 
308 void RemoteDebugger::HandleKeyboardCommand(char* command) {
309  Locker lock(isolate_);
310  HandleScope scope(isolate_);
311 
312  // Convert the debugger command to a JSON debugger request.
313  TryCatch try_catch;
314  Handle<Value> request = Shell::DebugCommandToJSONRequest(
315  isolate_, String::NewFromUtf8(isolate_, command));
316  if (try_catch.HasCaught()) {
317  Shell::ReportException(isolate_, &try_catch);
318  PrintPrompt();
319  return;
320  }
321 
322  // If undefined is returned the command was handled internally and there is
323  // no JSON to send.
324  if (request->IsUndefined()) {
325  PrintPrompt();
326  return;
327  }
328 
329  // Send the JSON debugger request.
330  i::DebuggerAgentUtil::SendMessage(conn_, Handle<String>::Cast(request));
331 }
332 
333 
334 void ReceiverThread::Run() {
335  // Receive the connect message (with empty body).
337  i::DebuggerAgentUtil::ReceiveMessage(remote_debugger_->conn());
338  ASSERT(message.get() == NULL);
339 
340  while (true) {
341  // Receive a message.
343  i::DebuggerAgentUtil::ReceiveMessage(remote_debugger_->conn());
344  if (message.get() == NULL) {
345  remote_debugger_->ConnectionClosed();
346  return;
347  }
348 
349  // Pass the message to the main thread.
350  remote_debugger_->MessageReceived(message);
351  }
352 }
353 
354 
355 void KeyboardThread::Run() {
356  static const int kBufferSize = 256;
357  while (true) {
358  // read keyboard input.
359  char command[kBufferSize];
360  char* str = fgets(command, kBufferSize, stdin);
361  if (str == NULL) {
362  break;
363  }
364 
365  // Pass the keyboard command to the main thread.
366  remote_debugger_->KeyboardCommand(
368  }
369 }
370 
371 
372 } // namespace v8
373 
374 #endif // ENABLE_DEBUGGER_SUPPORT
static Isolate * GetCurrent()
Definition: api.cc:6580
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter NULL
friend class ReceiverThread
Definition: d8-debug.h:92
static const int kDisconnect
Definition: d8-debug.h:136
DebugEvent
Definition: v8-debug.h:39
static void ReportException(Isolate *isolate, TryCatch *try_catch)
Definition: d8.cc:562
#define ASSERT(condition)
Definition: checks.h:329
static const int kMessage
Definition: d8-debug.h:134
enable upcoming ES6 features enable harmony block scoping enable harmony enable harmony proxies enable harmony generators enable harmony numeric enable harmony string enable harmony math functions harmony_scoping harmony_symbols harmony_collections harmony_iteration harmony_strings harmony_scoping harmony_maths tracks arrays with only smi values Optimize object Array DOM strings and string pretenure call new trace pretenuring decisions of HAllocate instructions track fields with only smi values track fields with heap values track_fields track_fields Enables optimizations which favor memory size over execution speed use string slices optimization filter maximum number of GVN fix point iterations use function inlining use allocation folding eliminate write barriers targeting allocations in optimized code maximum source size in bytes considered for a single inlining maximum cumulative number of AST nodes considered for inlining crankshaft harvests type feedback from stub cache trace check elimination phase hydrogen tracing filter trace hydrogen to given file name trace inlining decisions trace store elimination trace all use positions trace global value numbering trace hydrogen escape analysis trace the tracking of allocation sites trace map generalization environment for every instruction deoptimize every n garbage collections put a break point before deoptimizing deoptimize uncommon cases use on stack replacement trace array bounds check elimination perform array index dehoisting use load elimination use store elimination use constant folding eliminate unreachable code number of stress runs when picking a function to watch for shared function not JSFunction itself flushes the cache of optimized code for closures on every GC functions with arguments object maximum number of escape analysis fix point iterations allow uint32 values on optimize frames if they are used only in safe operations track concurrent recompilation artificial compilation delay in ms concurrent on stack replacement do not emit check maps for constant values that have a leaf deoptimize the optimized code if the layout of the maps changes number of stack frames inspected by the profiler percentage of ICs that must have type info to allow optimization extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of VFP3 instructions if available enable use of NEON instructions if enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of d16 d31 registers on ARM this requires VFP3 force all emitted branches to be in long expose natives in global object expose freeBuffer extension expose gc extension under the specified name expose externalize string extension number of stack frames to capture disable builtin natives files print name of functions for which code is generated use random jit cookie to mask large constants trace lazy optimization use adaptive optimizations always try to OSR functions trace optimize function deoptimization minimum length for automatic enable preparsing maximum number of optimization attempts before giving up cache prototype transitions trace debugging JSON request response trace out of bounds accesses to external arrays trace_js_array_abuse automatically set the debug break flag when debugger commands are in the queue abort by crashing maximum length of function source code printed in a stack trace max size of the new max size of the old max size of executable always perform global GCs print one trace line following each garbage collection do not print trace line after scavenger collection print statistics of the maximum memory committed for the heap in only print modified registers Don t break for ASM_UNIMPLEMENTED_BREAK macros print stack trace when an illegal exception is thrown randomize hashes to avoid predictable hash Fixed seed to use to hash property Print the time it takes to deserialize the snapshot testing_bool_flag testing_int_flag string flag tmp file in which to serialize heap Print the time it takes to lazily compile hydrogen code stubs concurrent_recompilation concurrent_sweeping Print usage message
void RunRemoteDebugger(Isolate *isolate, int port)
#define UNREACHABLE()
Definition: checks.h:52
void HandleDebugEvent(const Debug::EventDetails &event_details)
void KeyboardCommand(i::SmartArrayPointer< char > command)
static const int kKeyboard
Definition: d8-debug.h:135
static V8_INLINE Handle< String > Cast(Handle< S > that)
Definition: v8.h:297
static V8_INLINE Local< T > Cast(Local< S > that)
Definition: v8.h:372
static int SNPrintF(Vector< char > str, const char *format,...)
char * StrDup(const char *str)
Definition: allocation.cc:89
void MessageReceived(i::SmartArrayPointer< char > message)
static Local< String > NewFromUtf8(Isolate *isolate, const char *data, NewStringType type=kNormalString, int length=-1)
Definition: api.cc:5417