blob: c2c9ddf3bfbb752196537ce535f06ac76c462011 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- GDBRemoteCommunication.cpp ------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10
11#include "GDBRemoteCommunication.h"
12
13// C Includes
Johnny Chenf3878232011-05-13 20:07:25 +000014#include <limits.h>
Stephen Wilson50daf772011-03-25 18:16:28 +000015#include <string.h>
16
Chris Lattner24943d22010-06-08 16:52:24 +000017// C++ Includes
18// Other libraries and framework includes
Chris Lattner24943d22010-06-08 16:52:24 +000019#include "lldb/Core/Log.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/StreamString.h"
Greg Claytonb72d0f02011-04-12 05:54:46 +000021#include "lldb/Host/FileSpec.h"
22#include "lldb/Host/Host.h"
Chris Lattner24943d22010-06-08 16:52:24 +000023#include "lldb/Host/TimeValue.h"
Greg Claytonb72d0f02011-04-12 05:54:46 +000024#include "lldb/Target/Process.h"
Chris Lattner24943d22010-06-08 16:52:24 +000025
26// Project includes
Chris Lattner24943d22010-06-08 16:52:24 +000027#include "ProcessGDBRemoteLog.h"
28
Greg Claytonb72d0f02011-04-12 05:54:46 +000029#define DEBUGSERVER_BASENAME "debugserver"
30
Chris Lattner24943d22010-06-08 16:52:24 +000031using namespace lldb;
32using namespace lldb_private;
33
34//----------------------------------------------------------------------
35// GDBRemoteCommunication constructor
36//----------------------------------------------------------------------
Greg Claytonb72d0f02011-04-12 05:54:46 +000037GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
38 const char *listener_name,
39 bool is_platform) :
Greg Clayton61d043b2011-03-22 04:00:09 +000040 Communication(comm_name),
Greg Clayton24bc5d92011-03-30 18:16:51 +000041 m_packet_timeout (60),
Chris Lattner24943d22010-06-08 16:52:24 +000042 m_sequence_mutex (Mutex::eMutexTypeRecursive),
Greg Claytoncecf3482011-01-20 07:53:45 +000043 m_public_is_running (false),
Greg Clayton58e26e02011-03-24 04:28:38 +000044 m_private_is_running (false),
Greg Claytonb72d0f02011-04-12 05:54:46 +000045 m_send_acks (true),
46 m_is_platform (is_platform)
Chris Lattner24943d22010-06-08 16:52:24 +000047{
Chris Lattner24943d22010-06-08 16:52:24 +000048}
49
50//----------------------------------------------------------------------
51// Destructor
52//----------------------------------------------------------------------
53GDBRemoteCommunication::~GDBRemoteCommunication()
54{
Chris Lattner24943d22010-06-08 16:52:24 +000055 if (IsConnected())
56 {
Chris Lattner24943d22010-06-08 16:52:24 +000057 Disconnect();
58 }
59}
60
Chris Lattner24943d22010-06-08 16:52:24 +000061char
62GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length)
63{
64 int checksum = 0;
65
66 // We only need to compute the checksum if we are sending acks
Greg Claytonc1f45872011-02-12 06:28:37 +000067 if (GetSendAcks ())
Chris Lattner24943d22010-06-08 16:52:24 +000068 {
Greg Clayton54e7afa2010-07-09 20:39:50 +000069 for (size_t i = 0; i < payload_length; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +000070 checksum += payload[i];
71 }
72 return checksum & 255;
73}
74
75size_t
Greg Claytona4881d02011-01-22 07:12:45 +000076GDBRemoteCommunication::SendAck ()
Chris Lattner24943d22010-06-08 16:52:24 +000077{
Greg Clayton0bfda0b2011-02-05 02:25:06 +000078 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
79 if (log)
80 log->Printf ("send packet: +");
Chris Lattner24943d22010-06-08 16:52:24 +000081 ConnectionStatus status = eConnectionStatusSuccess;
Greg Claytona4881d02011-01-22 07:12:45 +000082 char ack_char = '+';
Greg Clayton24bc5d92011-03-30 18:16:51 +000083 return Write (&ack_char, 1, status, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +000084}
85
86size_t
Greg Claytona4881d02011-01-22 07:12:45 +000087GDBRemoteCommunication::SendNack ()
88{
Greg Clayton0bfda0b2011-02-05 02:25:06 +000089 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
90 if (log)
91 log->Printf ("send packet: -");
Greg Claytona4881d02011-01-22 07:12:45 +000092 ConnectionStatus status = eConnectionStatusSuccess;
93 char nack_char = '-';
Greg Clayton24bc5d92011-03-30 18:16:51 +000094 return Write (&nack_char, 1, status, NULL);
95}
96
97size_t
98GDBRemoteCommunication::SendPacket (lldb_private::StreamString &payload)
99{
100 Mutex::Locker locker(m_sequence_mutex);
101 const std::string &p (payload.GetString());
102 return SendPacketNoLock (p.c_str(), p.size());
Greg Claytona4881d02011-01-22 07:12:45 +0000103}
104
Chris Lattner24943d22010-06-08 16:52:24 +0000105size_t
106GDBRemoteCommunication::SendPacket (const char *payload)
107{
108 Mutex::Locker locker(m_sequence_mutex);
109 return SendPacketNoLock (payload, ::strlen (payload));
110}
111
112size_t
113GDBRemoteCommunication::SendPacket (const char *payload, size_t payload_length)
114{
115 Mutex::Locker locker(m_sequence_mutex);
116 return SendPacketNoLock (payload, payload_length);
117}
118
119size_t
120GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length)
121{
122 if (IsConnected())
123 {
124 StreamString packet(0, 4, eByteOrderBig);
125
126 packet.PutChar('$');
127 packet.Write (payload, payload_length);
128 packet.PutChar('#');
129 packet.PutHex8(CalculcateChecksum (payload, payload_length));
130
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000131 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
132 if (log)
Greg Clayton139da722011-05-20 03:15:54 +0000133 log->Printf ("send packet: %.*s", (int)packet.GetSize(), packet.GetData());
Chris Lattner24943d22010-06-08 16:52:24 +0000134 ConnectionStatus status = eConnectionStatusSuccess;
135 size_t bytes_written = Write (packet.GetData(), packet.GetSize(), status, NULL);
136 if (bytes_written == packet.GetSize())
137 {
Greg Claytonc1f45872011-02-12 06:28:37 +0000138 if (GetSendAcks ())
Greg Clayton54e7afa2010-07-09 20:39:50 +0000139 {
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000140 if (GetAck () != '+')
Greg Clayton58e26e02011-03-24 04:28:38 +0000141 {
142 printf("get ack failed...");
Greg Clayton54e7afa2010-07-09 20:39:50 +0000143 return 0;
Greg Clayton58e26e02011-03-24 04:28:38 +0000144 }
Greg Clayton54e7afa2010-07-09 20:39:50 +0000145 }
Chris Lattner24943d22010-06-08 16:52:24 +0000146 }
Johnny Chen515ea542010-09-14 22:10:43 +0000147 else
148 {
Greg Clayton0bfda0b2011-02-05 02:25:06 +0000149 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
150 if (log)
Greg Clayton139da722011-05-20 03:15:54 +0000151 log->Printf ("error: failed to send packet: %.*s", (int)packet.GetSize(), packet.GetData());
Johnny Chen515ea542010-09-14 22:10:43 +0000152 }
Chris Lattner24943d22010-06-08 16:52:24 +0000153 return bytes_written;
Greg Claytoneea26402010-09-14 23:36:40 +0000154 }
Chris Lattner24943d22010-06-08 16:52:24 +0000155 return 0;
156}
157
158char
Greg Claytonc97bfdb2011-03-10 02:26:48 +0000159GDBRemoteCommunication::GetAck ()
Chris Lattner24943d22010-06-08 16:52:24 +0000160{
Greg Clayton61d043b2011-03-22 04:00:09 +0000161 StringExtractorGDBRemote packet;
Greg Clayton63afdb02011-06-17 01:22:15 +0000162 if (WaitForPacketWithTimeoutMicroSeconds (packet, GetPacketTimeoutInMicroSeconds ()) == 1)
Greg Clayton61d043b2011-03-22 04:00:09 +0000163 return packet.GetChar();
Chris Lattner24943d22010-06-08 16:52:24 +0000164 return 0;
165}
166
167bool
168GDBRemoteCommunication::GetSequenceMutex (Mutex::Locker& locker)
169{
170 return locker.TryLock (m_sequence_mutex.GetMutex());
171}
172
Chris Lattner24943d22010-06-08 16:52:24 +0000173
Greg Clayton72e1c782011-01-22 23:43:18 +0000174bool
Greg Clayton72e1c782011-01-22 23:43:18 +0000175GDBRemoteCommunication::WaitForNotRunningPrivate (const TimeValue *timeout_ptr)
176{
177 return m_private_is_running.WaitForValueEqualTo (false, timeout_ptr, NULL);
178}
179
Chris Lattner24943d22010-06-08 16:52:24 +0000180size_t
Greg Clayton63afdb02011-06-17 01:22:15 +0000181GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSeconds (StringExtractorGDBRemote &packet, uint32_t timeout_usec)
Chris Lattner24943d22010-06-08 16:52:24 +0000182{
Greg Claytoncecf3482011-01-20 07:53:45 +0000183 Mutex::Locker locker(m_sequence_mutex);
Greg Clayton63afdb02011-06-17 01:22:15 +0000184 return WaitForPacketWithTimeoutMicroSecondsNoLock (packet, timeout_usec);
Chris Lattner24943d22010-06-08 16:52:24 +0000185}
186
187size_t
Greg Clayton63afdb02011-06-17 01:22:15 +0000188GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSecondsNoLock (StringExtractorGDBRemote &packet, uint32_t timeout_usec)
Chris Lattner24943d22010-06-08 16:52:24 +0000189{
Greg Clayton63afdb02011-06-17 01:22:15 +0000190 uint8_t buffer[8192];
191 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +0000192
Greg Clayton63afdb02011-06-17 01:22:15 +0000193 // Check for a packet from our cache first without trying any reading...
194 if (CheckForPacket (NULL, 0, packet))
195 return packet.GetStringRef().size();
Chris Lattner24943d22010-06-08 16:52:24 +0000196
Greg Clayton63afdb02011-06-17 01:22:15 +0000197 bool timed_out = false;
198 while (IsConnected() && !timed_out)
Chris Lattner24943d22010-06-08 16:52:24 +0000199 {
Greg Clayton63afdb02011-06-17 01:22:15 +0000200 lldb::ConnectionStatus status;
201 size_t bytes_read = Read (buffer, sizeof(buffer), timeout_usec, status, &error);
202 if (bytes_read > 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000203 {
Greg Clayton63afdb02011-06-17 01:22:15 +0000204 if (CheckForPacket (buffer, bytes_read, packet))
205 return packet.GetStringRef().size();
206 }
207 else
208 {
209 switch (status)
Chris Lattner24943d22010-06-08 16:52:24 +0000210 {
Greg Clayton63afdb02011-06-17 01:22:15 +0000211 case eConnectionStatusSuccess:
212 break;
213
214 case eConnectionStatusEndOfFile:
215 case eConnectionStatusNoConnection:
216 case eConnectionStatusLostConnection:
217 case eConnectionStatusError:
218 Disconnect();
219 break;
220
221 case eConnectionStatusTimedOut:
222 timed_out = true;
223 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000224 }
225 }
Chris Lattner24943d22010-06-08 16:52:24 +0000226 }
Greg Clayton63afdb02011-06-17 01:22:15 +0000227 packet.Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +0000228 return 0;
229}
230
Greg Clayton63afdb02011-06-17 01:22:15 +0000231bool
232GDBRemoteCommunication::CheckForPacket (const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
Chris Lattner24943d22010-06-08 16:52:24 +0000233{
234 // Put the packet data into the buffer in a thread safe fashion
235 Mutex::Locker locker(m_bytes_mutex);
Greg Clayton63afdb02011-06-17 01:22:15 +0000236 if (src && src_len > 0)
237 m_bytes.append ((const char *)src, src_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000238
239 // Parse up the packets into gdb remote packets
240 while (!m_bytes.empty())
241 {
242 // end_idx must be one past the last valid packet byte. Start
243 // it off with an invalid value that is the same as the current
244 // index.
Greg Clayton63afdb02011-06-17 01:22:15 +0000245 size_t content_start = 0;
246 size_t content_length = 0;
247 size_t total_length = 0;
248 size_t checksum_idx = std::string::npos;
Chris Lattner24943d22010-06-08 16:52:24 +0000249
250 switch (m_bytes[0])
251 {
252 case '+': // Look for ack
253 case '-': // Look for cancel
254 case '\x03': // ^C to halt target
Greg Clayton63afdb02011-06-17 01:22:15 +0000255 content_length = total_length = 1; // The command is one byte long...
Chris Lattner24943d22010-06-08 16:52:24 +0000256 break;
257
258 case '$':
259 // Look for a standard gdb packet?
Chris Lattner24943d22010-06-08 16:52:24 +0000260 {
Greg Clayton63afdb02011-06-17 01:22:15 +0000261 size_t hash_pos = m_bytes.find('#');
262 if (hash_pos != std::string::npos)
Chris Lattner24943d22010-06-08 16:52:24 +0000263 {
Greg Clayton63afdb02011-06-17 01:22:15 +0000264 if (hash_pos + 2 < m_bytes.size())
265 {
266 checksum_idx = hash_pos + 1;
267 // Skip the dollar sign
268 content_start = 1;
269 // Don't include the # in the content or the $ in the content length
270 content_length = hash_pos - 1;
271
272 total_length = hash_pos + 3; // Skip the # and the two hex checksum bytes
273 }
274 else
275 {
276 // Checksum bytes aren't all here yet
277 content_length = std::string::npos;
278 }
Chris Lattner24943d22010-06-08 16:52:24 +0000279 }
280 }
281 break;
282
283 default:
284 break;
285 }
286
Greg Clayton63afdb02011-06-17 01:22:15 +0000287 LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
288 if (content_length == std::string::npos)
Chris Lattner24943d22010-06-08 16:52:24 +0000289 {
Greg Clayton63afdb02011-06-17 01:22:15 +0000290 packet.Clear();
291 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000292 }
Greg Clayton63afdb02011-06-17 01:22:15 +0000293 else if (content_length > 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000294 {
Greg Clayton63afdb02011-06-17 01:22:15 +0000295
Chris Lattner24943d22010-06-08 16:52:24 +0000296 // We have a valid packet...
Greg Clayton63afdb02011-06-17 01:22:15 +0000297 assert (content_length <= m_bytes.size());
298 assert (total_length <= m_bytes.size());
299 assert (content_length <= total_length);
300
301 bool success = true;
302 std::string &packet_str = packet.GetStringRef();
303 packet_str.assign (m_bytes, content_start, content_length);
304 if (m_bytes[0] == '$')
305 {
306 assert (checksum_idx < m_bytes.size());
307 if (::isxdigit (m_bytes[checksum_idx+0]) ||
308 ::isxdigit (m_bytes[checksum_idx+1]))
309 {
310 if (GetSendAcks ())
311 {
312 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
313 char packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
314 char actual_checksum = CalculcateChecksum (packet_str.c_str(), packet_str.size());
315 success = packet_checksum == actual_checksum;
316 if (!success)
317 {
318 if (log)
319 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
320 (int)(total_length),
321 m_bytes.c_str(),
322 (uint8_t)packet_checksum,
323 (uint8_t)actual_checksum);
324 }
325 // Send the ack or nack if needed
326 if (!success)
327 SendNack();
328 else
329 SendAck();
330 }
331 if (success)
332 {
333 if (log)
334 log->Printf ("read packet: %.*s", (int)(total_length), m_bytes.c_str());
335 }
336 }
337 else
338 {
339 success = false;
340 if (log)
341 log->Printf ("error: invalid checksum in packet: '%s'\n", (int)(total_length), m_bytes.c_str());
342 }
343 }
344 m_bytes.erase(0, total_length);
345 packet.SetFilePos(0);
346 return success;
Chris Lattner24943d22010-06-08 16:52:24 +0000347 }
348 else
349 {
Greg Clayton63afdb02011-06-17 01:22:15 +0000350 if (log)
351 log->Printf ("GDBRemoteCommunication::%s tossing junk byte at %c",__FUNCTION__, m_bytes[0]);
Chris Lattner24943d22010-06-08 16:52:24 +0000352 m_bytes.erase(0, 1);
353 }
354 }
Greg Clayton63afdb02011-06-17 01:22:15 +0000355 packet.Clear();
356 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000357}
358
Greg Claytonb72d0f02011-04-12 05:54:46 +0000359Error
360GDBRemoteCommunication::StartDebugserverProcess (const char *debugserver_url,
361 const char *unix_socket_name, // For handshaking
362 lldb_private::ProcessLaunchInfo &launch_info)
363{
364 Error error;
365 // If we locate debugserver, keep that located version around
366 static FileSpec g_debugserver_file_spec;
367
368 // This function will fill in the launch information for the debugserver
369 // instance that gets launched.
370 launch_info.Clear();
371
372 char debugserver_path[PATH_MAX];
373 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
374
375 // Always check to see if we have an environment override for the path
376 // to the debugserver to use and use it if we do.
377 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
378 if (env_debugserver_path)
379 debugserver_file_spec.SetFile (env_debugserver_path, false);
380 else
381 debugserver_file_spec = g_debugserver_file_spec;
382 bool debugserver_exists = debugserver_file_spec.Exists();
383 if (!debugserver_exists)
384 {
385 // The debugserver binary is in the LLDB.framework/Resources
386 // directory.
387 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
388 {
389 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
390 debugserver_exists = debugserver_file_spec.Exists();
391 if (debugserver_exists)
392 {
393 g_debugserver_file_spec = debugserver_file_spec;
394 }
395 else
396 {
397 g_debugserver_file_spec.Clear();
398 debugserver_file_spec.Clear();
399 }
400 }
401 }
402
403 if (debugserver_exists)
404 {
405 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
406
407 Args &debugserver_args = launch_info.GetArguments();
408 debugserver_args.Clear();
409 char arg_cstr[PATH_MAX];
410
411 // Start args with "debugserver /file/path -r --"
412 debugserver_args.AppendArgument(debugserver_path);
413 debugserver_args.AppendArgument(debugserver_url);
414 // use native registers, not the GDB registers
415 debugserver_args.AppendArgument("--native-regs");
416 // make debugserver run in its own session so signals generated by
417 // special terminal key sequences (^C) don't affect debugserver
418 debugserver_args.AppendArgument("--setsid");
419
420 if (unix_socket_name && unix_socket_name[0])
421 {
422 debugserver_args.AppendArgument("--unix-socket");
423 debugserver_args.AppendArgument(unix_socket_name);
424 }
425
426 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
427 if (env_debugserver_log_file)
428 {
429 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
430 debugserver_args.AppendArgument(arg_cstr);
431 }
432
433 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
434 if (env_debugserver_log_flags)
435 {
436 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
437 debugserver_args.AppendArgument(arg_cstr);
438 }
439 // debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
440 // debugserver_args.AppendArgument("--log-flags=0x802e0e");
441
442 // We currently send down all arguments, attach pids, or attach
443 // process names in dedicated GDB server packets, so we don't need
444 // to pass them as arguments. This is currently because of all the
445 // things we need to setup prior to launching: the environment,
446 // current working dir, file actions, etc.
447#if 0
448 // Now append the program arguments
449 if (inferior_argv)
450 {
451 // Terminate the debugserver args so we can now append the inferior args
452 debugserver_args.AppendArgument("--");
453
454 for (int i = 0; inferior_argv[i] != NULL; ++i)
455 debugserver_args.AppendArgument (inferior_argv[i]);
456 }
457 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
458 {
459 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
460 debugserver_args.AppendArgument (arg_cstr);
461 }
462 else if (attach_name && attach_name[0])
463 {
464 if (wait_for_launch)
465 debugserver_args.AppendArgument ("--waitfor");
466 else
467 debugserver_args.AppendArgument ("--attach");
468 debugserver_args.AppendArgument (attach_name);
469 }
470#endif
471
472 // Close STDIN, STDOUT and STDERR. We might need to redirect them
473 // to "/dev/null" if we run into any problems.
474// launch_info.AppendCloseFileAction (STDIN_FILENO);
475// launch_info.AppendCloseFileAction (STDOUT_FILENO);
476// launch_info.AppendCloseFileAction (STDERR_FILENO);
477
478 error = Host::LaunchProcess(launch_info);
479 }
480 else
481 {
482 error.SetErrorStringWithFormat ("Unable to locate " DEBUGSERVER_BASENAME ".\n");
483 }
484 return error;
485}
486