blob: 6901079b9b060d6d85af83b8faff8fbb2c31c0c1 [file] [log] [blame]
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001// Copyright 2009 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
29#include "v8.h"
kmillikin@chromium.orgd2c22f02011-01-10 08:15:37 +000030#include "debug.h"
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000031#include "debug-agent.h"
32
ager@chromium.org65dad4b2009-04-23 08:48:43 +000033#ifdef ENABLE_DEBUGGER_SUPPORT
kmillikin@chromium.orgd2c22f02011-01-10 08:15:37 +000034
kasperl@chromium.org71affb52009-05-26 05:44:31 +000035namespace v8 {
36namespace internal {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000037
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000038// Public V8 debugger API message handler function. This function just delegates
39// to the debugger agent through it's data parameter.
ager@chromium.org5ec48922009-05-05 07:25:34 +000040void DebuggerAgentMessageHandler(const v8::Debug::Message& message) {
41 DebuggerAgent::instance_->DebuggerMessage(message);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000042}
43
ager@chromium.org65dad4b2009-04-23 08:48:43 +000044// static
45DebuggerAgent* DebuggerAgent::instance_ = NULL;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000046
47// Debugger agent main thread.
48void DebuggerAgent::Run() {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000049 const int kOneSecondInMicros = 1000000;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000050
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000051 // Allow this socket to reuse port even if still in TIME_WAIT.
52 server_->SetReuseAddress(true);
53
54 // First bind the socket to the requested port.
55 bool bound = false;
56 while (!bound && !terminate_) {
57 bound = server_->Bind(port_);
58
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +000059 // If an error occurred wait a bit before retrying. The most common error
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000060 // would be that the port is already in use so this avoids a busy loop and
61 // make the agent take over the port when it becomes free.
62 if (!bound) {
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +000063 PrintF("Failed to open socket on port %d, "
64 "waiting %d ms before retrying\n", port_, kOneSecondInMicros / 1000);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000065 terminate_now_->Wait(kOneSecondInMicros);
66 }
67 }
68
69 // Accept connections on the bound port.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000070 while (!terminate_) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000071 bool ok = server_->Listen(1);
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +000072 listening_->Signal();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000073 if (ok) {
74 // Accept the new connection.
75 Socket* client = server_->Accept();
76 ok = client != NULL;
77 if (ok) {
78 // Create and start a new session.
79 CreateSession(client);
80 }
81 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000082 }
83}
84
85
86void DebuggerAgent::Shutdown() {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000087 // Set the termination flag.
88 terminate_ = true;
89
90 // Signal termination and make the server exit either its listen call or its
91 // binding loop. This makes sure that no new sessions can be established.
92 terminate_now_->Signal();
93 server_->Shutdown();
94 Join();
95
96 // Close existing session if any.
97 CloseSession();
kasperl@chromium.org7be3c992009-03-12 07:19:55 +000098}
99
100
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +0000101void DebuggerAgent::WaitUntilListening() {
102 listening_->Wait();
103}
104
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000105void DebuggerAgent::CreateSession(Socket* client) {
106 ScopedLock with(session_access_);
107
108 // If another session is already established terminate this one.
109 if (session_ != NULL) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000110 static const char* message = "Remote debugging session already active\r\n";
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000111
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000112 client->Send(message, StrLength(message));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000113 delete client;
114 return;
115 }
116
117 // Create a new session and hook up the debug message handler.
118 session_ = new DebuggerAgentSession(this, client);
ager@chromium.org5ec48922009-05-05 07:25:34 +0000119 v8::Debug::SetMessageHandler2(DebuggerAgentMessageHandler);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000120 session_->Start();
121}
122
123
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000124void DebuggerAgent::CloseSession() {
125 ScopedLock with(session_access_);
126
127 // Terminate the session.
128 if (session_ != NULL) {
129 session_->Shutdown();
130 session_->Join();
131 delete session_;
132 session_ = NULL;
133 }
134}
135
136
ager@chromium.org5ec48922009-05-05 07:25:34 +0000137void DebuggerAgent::DebuggerMessage(const v8::Debug::Message& message) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000138 ScopedLock with(session_access_);
139
140 // Forward the message handling to the session.
141 if (session_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +0000142 v8::String::Value val(message.GetJSON());
143 session_->DebuggerMessage(Vector<uint16_t>(const_cast<uint16_t*>(*val),
144 val.length()));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000145 }
146}
147
148
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000149void DebuggerAgent::OnSessionClosed(DebuggerAgentSession* session) {
150 // Don't do anything during termination.
151 if (terminate_) {
152 return;
153 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000154
155 // Terminate the session.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000156 ScopedLock with(session_access_);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000157 ASSERT(session == session_);
158 if (session == session_) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000159 CloseSession();
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000160 }
161}
162
163
164void DebuggerAgentSession::Run() {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000165 // Send the hello message.
166 bool ok = DebuggerAgentUtil::SendConnectMessage(client_, *agent_->name_);
167 if (!ok) return;
168
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000169 while (true) {
170 // Read data from the debugger front end.
171 SmartPointer<char> message = DebuggerAgentUtil::ReceiveMessage(client_);
kmillikin@chromium.orgd2c22f02011-01-10 08:15:37 +0000172
173 const char* msg = *message;
174 bool is_closing_session = (msg == NULL);
175
176 if (msg == NULL) {
177 // If we lost the connection, then simulate a disconnect msg:
178 msg = "{\"seq\":1,\"type\":\"request\",\"command\":\"disconnect\"}";
179
180 } else {
181 // Check if we're getting a disconnect request:
182 const char* disconnectRequestStr =
183 "\"type\":\"request\",\"command\":\"disconnect\"}";
184 const char* result = strstr(msg, disconnectRequestStr);
185 if (result != NULL) {
186 is_closing_session = true;
187 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000188 }
189
190 // Convert UTF-8 to UTF-16.
kmillikin@chromium.orgd2c22f02011-01-10 08:15:37 +0000191 unibrow::Utf8InputBuffer<> buf(msg, StrLength(msg));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000192 int len = 0;
193 while (buf.has_more()) {
194 buf.GetNext();
195 len++;
196 }
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000197 ScopedVector<int16_t> temp(len + 1);
kmillikin@chromium.orgd2c22f02011-01-10 08:15:37 +0000198 buf.Reset(msg, StrLength(msg));
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000199 for (int i = 0; i < len; i++) {
200 temp[i] = buf.GetNext();
201 }
202
203 // Send the request received to the debugger.
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000204 v8::Debug::SendCommand(reinterpret_cast<const uint16_t *>(temp.start()),
205 len);
kmillikin@chromium.orgd2c22f02011-01-10 08:15:37 +0000206
207 if (is_closing_session) {
208 // Session is closed.
209 agent_->OnSessionClosed(this);
210 return;
211 }
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000212 }
213}
214
215
216void DebuggerAgentSession::DebuggerMessage(Vector<uint16_t> message) {
217 DebuggerAgentUtil::SendMessage(client_, message);
218}
219
220
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000221void DebuggerAgentSession::Shutdown() {
222 // Shutdown the socket to end the blocking receive.
223 client_->Shutdown();
224}
225
226
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000227const char* DebuggerAgentUtil::kContentLength = "Content-Length";
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000228int DebuggerAgentUtil::kContentLengthSize =
229 StrLength(kContentLength);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000230
231
232SmartPointer<char> DebuggerAgentUtil::ReceiveMessage(const Socket* conn) {
233 int received;
234
235 // Read header.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000236 int content_length = 0;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000237 while (true) {
238 const int kHeaderBufferSize = 80;
239 char header_buffer[kHeaderBufferSize];
240 int header_buffer_position = 0;
241 char c = '\0'; // One character receive buffer.
242 char prev_c = '\0'; // Previous character.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000243
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000244 // Read until CRLF.
245 while (!(c == '\n' && prev_c == '\r')) {
246 prev_c = c;
247 received = conn->Receive(&c, 1);
248 if (received <= 0) {
249 PrintF("Error %d\n", Socket::LastError());
250 return SmartPointer<char>();
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000251 }
252
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000253 // Add character to header buffer.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000254 if (header_buffer_position < kHeaderBufferSize) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000255 header_buffer[header_buffer_position++] = c;
256 }
257 }
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000258
259 // Check for end of header (empty header line).
260 if (header_buffer_position == 2) { // Receive buffer contains CRLF.
261 break;
262 }
263
264 // Terminate header.
265 ASSERT(header_buffer_position > 1); // At least CRLF is received.
266 ASSERT(header_buffer_position <= kHeaderBufferSize);
267 header_buffer[header_buffer_position - 2] = '\0';
268
269 // Split header.
270 char* key = header_buffer;
271 char* value = NULL;
272 for (int i = 0; header_buffer[i] != '\0'; i++) {
273 if (header_buffer[i] == ':') {
274 header_buffer[i] = '\0';
275 value = header_buffer + i + 1;
276 while (*value == ' ') {
277 value++;
278 }
279 break;
280 }
281 }
282
283 // Check that key is Content-Length.
284 if (strcmp(key, kContentLength) == 0) {
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +0000285 // Get the content length value if present and within a sensible range.
286 if (value == NULL || strlen(value) > 7) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000287 return SmartPointer<char>();
288 }
289 for (int i = 0; value[i] != '\0'; i++) {
290 // Bail out if illegal data.
291 if (value[i] < '0' || value[i] > '9') {
292 return SmartPointer<char>();
293 }
294 content_length = 10 * content_length + (value[i] - '0');
295 }
296 } else {
297 // For now just print all other headers than Content-Length.
298 PrintF("%s: %s\n", key, value != NULL ? value : "(no value)");
299 }
300 }
301
302 // Return now if no body.
303 if (content_length == 0) {
304 return SmartPointer<char>();
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000305 }
306
307 // Read body.
308 char* buffer = NewArray<char>(content_length + 1);
309 received = ReceiveAll(conn, buffer, content_length);
310 if (received < content_length) {
311 PrintF("Error %d\n", Socket::LastError());
312 return SmartPointer<char>();
313 }
314 buffer[content_length] = '\0';
315
316 return SmartPointer<char>(buffer);
317}
318
319
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000320bool DebuggerAgentUtil::SendConnectMessage(const Socket* conn,
321 const char* embedding_host) {
322 static const int kBufferSize = 80;
323 char buffer[kBufferSize]; // Sending buffer.
324 bool ok;
325 int len;
326
327 // Send the header.
328 len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
329 "Type: connect\r\n");
330 ok = conn->Send(buffer, len);
331 if (!ok) return false;
332
333 len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
334 "V8-Version: %s\r\n", v8::V8::GetVersion());
335 ok = conn->Send(buffer, len);
336 if (!ok) return false;
337
338 len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
339 "Protocol-Version: 1\r\n");
340 ok = conn->Send(buffer, len);
341 if (!ok) return false;
342
343 if (embedding_host != NULL) {
344 len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
345 "Embedding-Host: %s\r\n", embedding_host);
346 ok = conn->Send(buffer, len);
347 if (!ok) return false;
348 }
349
350 len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
351 "%s: 0\r\n", kContentLength);
352 ok = conn->Send(buffer, len);
353 if (!ok) return false;
354
355 // Terminate header with empty line.
356 len = OS::SNPrintF(Vector<char>(buffer, kBufferSize), "\r\n");
357 ok = conn->Send(buffer, len);
358 if (!ok) return false;
359
360 // No body for connect message.
361
362 return true;
363}
364
365
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000366bool DebuggerAgentUtil::SendMessage(const Socket* conn,
367 const Vector<uint16_t> message) {
368 static const int kBufferSize = 80;
369 char buffer[kBufferSize]; // Sending buffer both for header and body.
370
371 // Calculate the message size in UTF-8 encoding.
372 int utf8_len = 0;
373 for (int i = 0; i < message.length(); i++) {
374 utf8_len += unibrow::Utf8::Length(message[i]);
375 }
376
377 // Send the header.
378 int len;
379 len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000380 "%s: %d\r\n", kContentLength, utf8_len);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000381 conn->Send(buffer, len);
382
383 // Terminate header with empty line.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000384 len = OS::SNPrintF(Vector<char>(buffer, kBufferSize), "\r\n");
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000385 conn->Send(buffer, len);
386
387 // Send message body as UTF-8.
388 int buffer_position = 0; // Current buffer position.
389 for (int i = 0; i < message.length(); i++) {
390 // Write next UTF-8 encoded character to buffer.
391 buffer_position +=
392 unibrow::Utf8::Encode(buffer + buffer_position, message[i]);
393 ASSERT(buffer_position < kBufferSize);
394
395 // Send buffer if full or last character is encoded.
396 if (kBufferSize - buffer_position < 3 || i == message.length() - 1) {
397 conn->Send(buffer, buffer_position);
398 buffer_position = 0;
399 }
400 }
401
402 return true;
403}
404
405
406bool DebuggerAgentUtil::SendMessage(const Socket* conn,
407 const v8::Handle<v8::String> request) {
408 static const int kBufferSize = 80;
409 char buffer[kBufferSize]; // Sending buffer both for header and body.
410
411 // Convert the request to UTF-8 encoding.
412 v8::String::Utf8Value utf8_request(request);
413
414 // Send the header.
415 int len;
416 len = OS::SNPrintF(Vector<char>(buffer, kBufferSize),
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000417 "Content-Length: %d\r\n", utf8_request.length());
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000418 conn->Send(buffer, len);
419
420 // Terminate header with empty line.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000421 len = OS::SNPrintF(Vector<char>(buffer, kBufferSize), "\r\n");
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000422 conn->Send(buffer, len);
423
424 // Send message body as UTF-8.
425 conn->Send(*utf8_request, utf8_request.length());
426
427 return true;
428}
429
430
431// Receive the full buffer before returning unless an error occours.
432int DebuggerAgentUtil::ReceiveAll(const Socket* conn, char* data, int len) {
433 int total_received = 0;
434 while (total_received < len) {
435 int received = conn->Receive(data + total_received, len - total_received);
436 if (received <= 0) {
437 return total_received;
438 }
439 total_received += received;
440 }
441 return total_received;
442}
443
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000444} } // namespace v8::internal
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000445
446#endif // ENABLE_DEBUGGER_SUPPORT