1 //===-- GDBRemoteCommunication.cpp ------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include "GDBRemoteCommunication.h"
19 // Other libraries and framework includes
20 #include "lldb/Core/ConnectionFileDescriptor.h"
21 #include "lldb/Core/Log.h"
22 #include "lldb/Core/StreamFile.h"
23 #include "lldb/Core/StreamString.h"
24 #include "lldb/Host/FileSpec.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/TimeValue.h"
27 #include "lldb/Target/Process.h"
30 #include "ProcessGDBRemoteLog.h"
32 #define DEBUGSERVER_BASENAME "debugserver"
35 using namespace lldb_private;
37 GDBRemoteCommunication::History::History (uint32_t size) :
40 m_total_packet_count (0),
41 m_dumped_to_log (false)
43 m_packets.resize(size);
46 GDBRemoteCommunication::History::~History ()
51 GDBRemoteCommunication::History::AddPacket (char packet_char,
53 uint32_t bytes_transmitted)
55 const size_t size = m_packets.size();
58 const uint32_t idx = GetNextIndex();
59 m_packets[idx].packet.assign (1, packet_char);
60 m_packets[idx].type = type;
61 m_packets[idx].bytes_transmitted = bytes_transmitted;
62 m_packets[idx].packet_idx = m_total_packet_count;
63 m_packets[idx].tid = Host::GetCurrentThreadID();
68 GDBRemoteCommunication::History::AddPacket (const std::string &src,
71 uint32_t bytes_transmitted)
73 const size_t size = m_packets.size();
76 const uint32_t idx = GetNextIndex();
77 m_packets[idx].packet.assign (src, 0, src_len);
78 m_packets[idx].type = type;
79 m_packets[idx].bytes_transmitted = bytes_transmitted;
80 m_packets[idx].packet_idx = m_total_packet_count;
81 m_packets[idx].tid = Host::GetCurrentThreadID();
86 GDBRemoteCommunication::History::Dump (lldb_private::Stream &strm) const
88 const uint32_t size = GetNumPacketsInHistory ();
89 const uint32_t first_idx = GetFirstSavedPacketIndex ();
90 const uint32_t stop_idx = m_curr_idx + size;
91 for (uint32_t i = first_idx; i < stop_idx; ++i)
93 const uint32_t idx = NormalizeIndex (i);
94 const Entry &entry = m_packets[idx];
95 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
97 strm.Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s\n",
100 entry.bytes_transmitted,
101 (entry.type == ePacketTypeSend) ? "send" : "read",
102 entry.packet.c_str());
107 GDBRemoteCommunication::History::Dump (lldb_private::Log *log) const
109 if (log && !m_dumped_to_log)
111 m_dumped_to_log = true;
112 const uint32_t size = GetNumPacketsInHistory ();
113 const uint32_t first_idx = GetFirstSavedPacketIndex ();
114 const uint32_t stop_idx = m_curr_idx + size;
115 for (uint32_t i = first_idx; i < stop_idx; ++i)
117 const uint32_t idx = NormalizeIndex (i);
118 const Entry &entry = m_packets[idx];
119 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
121 log->Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s",
124 entry.bytes_transmitted,
125 (entry.type == ePacketTypeSend) ? "send" : "read",
126 entry.packet.c_str());
131 //----------------------------------------------------------------------
132 // GDBRemoteCommunication constructor
133 //----------------------------------------------------------------------
134 GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
135 const char *listener_name,
137 Communication(comm_name),
138 #ifdef LLDB_CONFIGURATION_DEBUG
139 m_packet_timeout (1000),
141 m_packet_timeout (1),
143 m_sequence_mutex (Mutex::eMutexTypeRecursive),
144 m_public_is_running (false),
145 m_private_is_running (false),
148 m_is_platform (is_platform),
149 m_listen_thread (LLDB_INVALID_HOST_THREAD),
154 //----------------------------------------------------------------------
156 //----------------------------------------------------------------------
157 GDBRemoteCommunication::~GDBRemoteCommunication()
166 GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length)
170 for (size_t i = 0; i < payload_length; ++i)
171 checksum += payload[i];
173 return checksum & 255;
177 GDBRemoteCommunication::SendAck ()
179 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
180 ConnectionStatus status = eConnectionStatusSuccess;
182 const size_t bytes_written = Write (&ch, 1, status, NULL);
184 log->Printf ("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
185 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
186 return bytes_written;
190 GDBRemoteCommunication::SendNack ()
192 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
193 ConnectionStatus status = eConnectionStatusSuccess;
195 const size_t bytes_written = Write (&ch, 1, status, NULL);
197 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
198 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
199 return bytes_written;
202 GDBRemoteCommunication::PacketResult
203 GDBRemoteCommunication::SendPacket (const char *payload, size_t payload_length)
205 Mutex::Locker locker(m_sequence_mutex);
206 return SendPacketNoLock (payload, payload_length);
209 GDBRemoteCommunication::PacketResult
210 GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length)
214 StreamString packet(0, 4, eByteOrderBig);
217 packet.Write (payload, payload_length);
219 packet.PutHex8(CalculcateChecksum (payload, payload_length));
221 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
222 ConnectionStatus status = eConnectionStatusSuccess;
223 size_t bytes_written = Write (packet.GetData(), packet.GetSize(), status, NULL);
226 // If logging was just enabled and we have history, then dump out what
227 // we have to the log so we get the historical context. The Dump() call that
228 // logs all of the packet will set a boolean so that we don't dump this more
230 if (!m_history.DidDumpToLog ())
231 m_history.Dump (log);
233 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)packet.GetSize(), packet.GetData());
236 m_history.AddPacket (packet.GetString(), packet.GetSize(), History::ePacketTypeSend, bytes_written);
239 if (bytes_written == packet.GetSize())
244 return PacketResult::Success;
249 log->Printf ("error: failed to send packet: %.*s", (int)packet.GetSize(), packet.GetData());
252 return PacketResult::ErrorSendFailed;
255 GDBRemoteCommunication::PacketResult
256 GDBRemoteCommunication::GetAck ()
258 StringExtractorGDBRemote packet;
259 PacketResult result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, GetPacketTimeoutInMicroSeconds ());
260 if (result == PacketResult::Success)
262 if (packet.GetResponseType() == StringExtractorGDBRemote::ResponseType::eAck)
263 return PacketResult::Success;
265 return PacketResult::ErrorSendAck;
271 GDBRemoteCommunication::GetSequenceMutex (Mutex::Locker& locker, const char *failure_message)
274 return locker.TryLock (m_sequence_mutex, failure_message);
276 locker.Lock (m_sequence_mutex);
282 GDBRemoteCommunication::WaitForNotRunningPrivate (const TimeValue *timeout_ptr)
284 return m_private_is_running.WaitForValueEqualTo (false, timeout_ptr, NULL);
287 GDBRemoteCommunication::PacketResult
288 GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSecondsNoLock (StringExtractorGDBRemote &packet, uint32_t timeout_usec)
290 uint8_t buffer[8192];
293 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS | GDBR_LOG_VERBOSE));
295 // Check for a packet from our cache first without trying any reading...
296 if (CheckForPacket (NULL, 0, packet))
297 return PacketResult::Success;
299 bool timed_out = false;
300 bool disconnected = false;
301 while (IsConnected() && !timed_out)
303 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
304 size_t bytes_read = Read (buffer, sizeof(buffer), timeout_usec, status, &error);
307 log->Printf ("%s: Read (buffer, (sizeof(buffer), timeout_usec = 0x%x, status = %s, error = %s) => bytes_read = %" PRIu64,
310 Communication::ConnectionStatusAsCString (status),
312 (uint64_t)bytes_read);
316 if (CheckForPacket (buffer, bytes_read, packet))
317 return PacketResult::Success;
323 case eConnectionStatusTimedOut:
326 case eConnectionStatusSuccess:
327 //printf ("status = success but error = %s\n", error.AsCString("<invalid>"));
330 case eConnectionStatusEndOfFile:
331 case eConnectionStatusNoConnection:
332 case eConnectionStatusLostConnection:
333 case eConnectionStatusError:
342 return PacketResult::ErrorDisconnected;
344 return PacketResult::ErrorReplyTimeout;
346 return PacketResult::ErrorReplyFailed;
350 GDBRemoteCommunication::CheckForPacket (const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
352 // Put the packet data into the buffer in a thread safe fashion
353 Mutex::Locker locker(m_bytes_mutex);
355 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
357 if (src && src_len > 0)
359 if (log && log->GetVerbose())
362 log->Printf ("GDBRemoteCommunication::%s adding %u bytes: %.*s",
368 m_bytes.append ((const char *)src, src_len);
371 // Parse up the packets into gdb remote packets
372 if (!m_bytes.empty())
374 // end_idx must be one past the last valid packet byte. Start
375 // it off with an invalid value that is the same as the current
377 size_t content_start = 0;
378 size_t content_length = 0;
379 size_t total_length = 0;
380 size_t checksum_idx = std::string::npos;
384 case '+': // Look for ack
385 case '-': // Look for cancel
386 case '\x03': // ^C to halt target
387 content_length = total_length = 1; // The command is one byte long...
391 // Look for a standard gdb packet?
393 size_t hash_pos = m_bytes.find('#');
394 if (hash_pos != std::string::npos)
396 if (hash_pos + 2 < m_bytes.size())
398 checksum_idx = hash_pos + 1;
399 // Skip the dollar sign
401 // Don't include the # in the content or the $ in the content length
402 content_length = hash_pos - 1;
404 total_length = hash_pos + 3; // Skip the # and the two hex checksum bytes
408 // Checksum bytes aren't all here yet
409 content_length = std::string::npos;
417 // We have an unexpected byte and we need to flush all bad
418 // data that is in m_bytes, so we need to find the first
419 // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt),
420 // or '$' character (start of packet header) or of course,
421 // the end of the data in m_bytes...
422 const size_t bytes_len = m_bytes.size();
425 for (idx = 1; !done && idx < bytes_len; ++idx)
427 switch (m_bytes[idx])
441 log->Printf ("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
442 __FUNCTION__, idx, idx, m_bytes.c_str());
443 m_bytes.erase(0, idx);
448 if (content_length == std::string::npos)
453 else if (total_length > 0)
456 // We have a valid packet...
457 assert (content_length <= m_bytes.size());
458 assert (total_length <= m_bytes.size());
459 assert (content_length <= total_length);
462 std::string &packet_str = packet.GetStringRef();
467 // If logging was just enabled and we have history, then dump out what
468 // we have to the log so we get the historical context. The Dump() call that
469 // logs all of the packet will set a boolean so that we don't dump this more
471 if (!m_history.DidDumpToLog ())
472 m_history.Dump (log);
474 log->Printf("<%4" PRIu64 "> read packet: %.*s", (uint64_t)total_length, (int)(total_length), m_bytes.c_str());
477 m_history.AddPacket (m_bytes.c_str(), total_length, History::ePacketTypeRecv, total_length);
479 // Clear packet_str in case there is some existing data in it.
481 // Copy the packet from m_bytes to packet_str expanding the
482 // run-length encoding in the process.
483 // Reserve enough byte for the most common case (no RLE used)
484 packet_str.reserve(m_bytes.length());
485 for (std::string::const_iterator c = m_bytes.begin() + content_start; c != m_bytes.begin() + content_start + content_length; ++c)
489 // '*' indicates RLE. Next character will give us the
490 // repeat count and previous character is what is to be
492 char char_to_repeat = packet_str.back();
493 // Number of time the previous character is repeated
494 int repeat_count = *++c + 3 - ' ';
495 // We have the char_to_repeat and repeat_count. Now push
497 for (int i = 0; i < repeat_count; ++i)
498 packet_str.push_back(char_to_repeat);
502 // 0x7d is the escape character. The next character is to
503 // be XOR'd with 0x20.
504 char escapee = *++c ^ 0x20;
505 packet_str.push_back(escapee);
509 packet_str.push_back(*c);
513 if (m_bytes[0] == '$')
515 assert (checksum_idx < m_bytes.size());
516 if (::isxdigit (m_bytes[checksum_idx+0]) ||
517 ::isxdigit (m_bytes[checksum_idx+1]))
521 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
522 char packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
523 char actual_checksum = CalculcateChecksum (packet_str.c_str(), packet_str.size());
524 success = packet_checksum == actual_checksum;
528 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
531 (uint8_t)packet_checksum,
532 (uint8_t)actual_checksum);
534 // Send the ack or nack if needed
545 log->Printf ("error: invalid checksum in packet: '%s'\n", m_bytes.c_str());
549 m_bytes.erase(0, total_length);
550 packet.SetFilePos(0);
559 GDBRemoteCommunication::StartListenThread (const char *hostname, uint16_t port)
562 if (IS_VALID_LLDB_HOST_THREAD(m_listen_thread))
564 error.SetErrorString("listen thread already running");
568 char listen_url[512];
569 if (hostname && hostname[0])
570 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
572 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
573 m_listen_url = listen_url;
574 SetConnection(new ConnectionFileDescriptor());
575 m_listen_thread = Host::ThreadCreate (listen_url, GDBRemoteCommunication::ListenThread, this, &error);
581 GDBRemoteCommunication::JoinListenThread ()
583 if (IS_VALID_LLDB_HOST_THREAD(m_listen_thread))
585 Host::ThreadJoin(m_listen_thread, NULL, NULL);
586 m_listen_thread = LLDB_INVALID_HOST_THREAD;
591 lldb::thread_result_t
592 GDBRemoteCommunication::ListenThread (lldb::thread_arg_t arg)
594 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
596 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)comm->GetConnection ();
600 // Do the listen on another thread so we can continue on...
601 if (connection->Connect(comm->m_listen_url.c_str(), &error) != eConnectionStatusSuccess)
602 comm->SetConnection(NULL);
608 GDBRemoteCommunication::StartDebugserverProcess (const char *hostname,
610 lldb_private::ProcessLaunchInfo &launch_info,
615 // If we locate debugserver, keep that located version around
616 static FileSpec g_debugserver_file_spec;
618 char debugserver_path[PATH_MAX];
619 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
621 // Always check to see if we have an environment override for the path
622 // to the debugserver to use and use it if we do.
623 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
624 if (env_debugserver_path)
625 debugserver_file_spec.SetFile (env_debugserver_path, false);
627 debugserver_file_spec = g_debugserver_file_spec;
628 bool debugserver_exists = debugserver_file_spec.Exists();
629 if (!debugserver_exists)
631 // The debugserver binary is in the LLDB.framework/Resources
633 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
635 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
636 debugserver_exists = debugserver_file_spec.Exists();
637 if (debugserver_exists)
639 g_debugserver_file_spec = debugserver_file_spec;
643 g_debugserver_file_spec.Clear();
644 debugserver_file_spec.Clear();
649 if (debugserver_exists)
651 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
653 Args &debugserver_args = launch_info.GetArguments();
654 debugserver_args.Clear();
655 char arg_cstr[PATH_MAX];
657 // Start args with "debugserver /file/path -r --"
658 debugserver_args.AppendArgument(debugserver_path);
660 // If a host and port is supplied then use it
661 char host_and_port[128];
664 snprintf (host_and_port, sizeof(host_and_port), "%s:%u", hostname, in_port);
665 debugserver_args.AppendArgument(host_and_port);
669 host_and_port[0] = '\0';
672 // use native registers, not the GDB registers
673 debugserver_args.AppendArgument("--native-regs");
674 // make debugserver run in its own session so signals generated by
675 // special terminal key sequences (^C) don't affect debugserver
676 debugserver_args.AppendArgument("--setsid");
678 char named_pipe_path[PATH_MAX];
679 named_pipe_path[0] = '\0';
682 if (host_and_port[0])
684 // Create a temporary file to get the stdout/stderr and redirect the
685 // output of the command into this file. We will later read this file
686 // if all goes well and fill the data into "command_output_ptr"
690 // Binding to port zero, we need to figure out what port it ends up
691 // using using a named pipe...
692 FileSpec tmpdir_file_spec;
693 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
695 tmpdir_file_spec.GetFilename().SetCString("debugserver-named-pipe.XXXXXX");
696 strncpy(named_pipe_path, tmpdir_file_spec.GetPath().c_str(), sizeof(named_pipe_path));
700 strncpy(named_pipe_path, "/tmp/debugserver-named-pipe.XXXXXX", sizeof(named_pipe_path));
703 if (::mktemp (named_pipe_path))
705 #if defined(_MSC_VER)
708 if (::mkfifo(named_pipe_path, 0600) == 0)
711 debugserver_args.AppendArgument("--named-pipe");
712 debugserver_args.AppendArgument(named_pipe_path);
723 // No host and port given, so lets listen on our end and make the debugserver
725 error = StartListenThread ("localhost", 0);
729 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)GetConnection ();
730 out_port = connection->GetBoundPort(3);
731 assert (out_port != 0);
733 snprintf(port_cstr, sizeof(port_cstr), "localhost:%i", out_port);
734 // Send the host and port down that debugserver and specify an option
735 // so that it connects back to the port we are listening to in this process
736 debugserver_args.AppendArgument("--reverse-connect");
737 debugserver_args.AppendArgument(port_cstr);
741 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
742 if (env_debugserver_log_file)
744 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
745 debugserver_args.AppendArgument(arg_cstr);
748 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
749 if (env_debugserver_log_flags)
751 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
752 debugserver_args.AppendArgument(arg_cstr);
755 // Close STDIN, STDOUT and STDERR. We might need to redirect them
756 // to "/dev/null" if we run into any problems.
757 launch_info.AppendCloseFileAction (STDIN_FILENO);
758 launch_info.AppendCloseFileAction (STDOUT_FILENO);
759 launch_info.AppendCloseFileAction (STDERR_FILENO);
761 error = Host::LaunchProcess(launch_info);
763 if (named_pipe_path[0])
766 error = name_pipe_file.Open(named_pipe_path, File::eOpenOptionRead);
771 size_t num_bytes = sizeof(port_cstr);
772 error = name_pipe_file.Read(port_cstr, num_bytes);
773 assert (error.Success());
774 assert (num_bytes > 0 && port_cstr[num_bytes-1] == '\0');
775 out_port = Args::StringToUInt32(port_cstr, 0);
776 name_pipe_file.Close();
778 Host::Unlink(named_pipe_path);
786 // Make sure we actually connect with the debugserver...
792 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME );
798 GDBRemoteCommunication::DumpHistory(Stream &strm)
800 m_history.Dump (strm);