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/Log.h"
21 #include "lldb/Core/StreamFile.h"
22 #include "lldb/Core/StreamString.h"
23 #include "lldb/Host/ConnectionFileDescriptor.h"
24 #include "lldb/Host/FileSpec.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/HostInfo.h"
27 #include "lldb/Host/Pipe.h"
28 #include "lldb/Host/Socket.h"
29 #include "lldb/Host/ThreadLauncher.h"
30 #include "lldb/Host/TimeValue.h"
31 #include "lldb/Target/Process.h"
34 #include "ProcessGDBRemoteLog.h"
36 #if defined(__APPLE__)
37 # define DEBUGSERVER_BASENAME "debugserver"
39 # define DEBUGSERVER_BASENAME "lldb-gdbserver"
43 using namespace lldb_private;
45 GDBRemoteCommunication::History::History (uint32_t size) :
48 m_total_packet_count (0),
49 m_dumped_to_log (false)
51 m_packets.resize(size);
54 GDBRemoteCommunication::History::~History ()
59 GDBRemoteCommunication::History::AddPacket (char packet_char,
61 uint32_t bytes_transmitted)
63 const size_t size = m_packets.size();
66 const uint32_t idx = GetNextIndex();
67 m_packets[idx].packet.assign (1, packet_char);
68 m_packets[idx].type = type;
69 m_packets[idx].bytes_transmitted = bytes_transmitted;
70 m_packets[idx].packet_idx = m_total_packet_count;
71 m_packets[idx].tid = Host::GetCurrentThreadID();
76 GDBRemoteCommunication::History::AddPacket (const std::string &src,
79 uint32_t bytes_transmitted)
81 const size_t size = m_packets.size();
84 const uint32_t idx = GetNextIndex();
85 m_packets[idx].packet.assign (src, 0, src_len);
86 m_packets[idx].type = type;
87 m_packets[idx].bytes_transmitted = bytes_transmitted;
88 m_packets[idx].packet_idx = m_total_packet_count;
89 m_packets[idx].tid = Host::GetCurrentThreadID();
94 GDBRemoteCommunication::History::Dump (lldb_private::Stream &strm) const
96 const uint32_t size = GetNumPacketsInHistory ();
97 const uint32_t first_idx = GetFirstSavedPacketIndex ();
98 const uint32_t stop_idx = m_curr_idx + size;
99 for (uint32_t i = first_idx; i < stop_idx; ++i)
101 const uint32_t idx = NormalizeIndex (i);
102 const Entry &entry = m_packets[idx];
103 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
105 strm.Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s\n",
108 entry.bytes_transmitted,
109 (entry.type == ePacketTypeSend) ? "send" : "read",
110 entry.packet.c_str());
115 GDBRemoteCommunication::History::Dump (lldb_private::Log *log) const
117 if (log && !m_dumped_to_log)
119 m_dumped_to_log = true;
120 const uint32_t size = GetNumPacketsInHistory ();
121 const uint32_t first_idx = GetFirstSavedPacketIndex ();
122 const uint32_t stop_idx = m_curr_idx + size;
123 for (uint32_t i = first_idx; i < stop_idx; ++i)
125 const uint32_t idx = NormalizeIndex (i);
126 const Entry &entry = m_packets[idx];
127 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
129 log->Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s",
132 entry.bytes_transmitted,
133 (entry.type == ePacketTypeSend) ? "send" : "read",
134 entry.packet.c_str());
139 //----------------------------------------------------------------------
140 // GDBRemoteCommunication constructor
141 //----------------------------------------------------------------------
142 GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
143 const char *listener_name,
145 Communication(comm_name),
146 #ifdef LLDB_CONFIGURATION_DEBUG
147 m_packet_timeout (1000),
149 m_packet_timeout (1),
151 m_sequence_mutex (Mutex::eMutexTypeRecursive),
152 m_public_is_running (false),
153 m_private_is_running (false),
156 m_is_platform (is_platform),
161 //----------------------------------------------------------------------
163 //----------------------------------------------------------------------
164 GDBRemoteCommunication::~GDBRemoteCommunication()
173 GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length)
177 for (size_t i = 0; i < payload_length; ++i)
178 checksum += payload[i];
180 return checksum & 255;
184 GDBRemoteCommunication::SendAck ()
186 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
187 ConnectionStatus status = eConnectionStatusSuccess;
189 const size_t bytes_written = Write (&ch, 1, status, NULL);
191 log->Printf ("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
192 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
193 return bytes_written;
197 GDBRemoteCommunication::SendNack ()
199 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
200 ConnectionStatus status = eConnectionStatusSuccess;
202 const size_t bytes_written = Write (&ch, 1, status, NULL);
204 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
205 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
206 return bytes_written;
209 GDBRemoteCommunication::PacketResult
210 GDBRemoteCommunication::SendPacket (const char *payload, size_t payload_length)
212 Mutex::Locker locker(m_sequence_mutex);
213 return SendPacketNoLock (payload, payload_length);
216 GDBRemoteCommunication::PacketResult
217 GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length)
221 StreamString packet(0, 4, eByteOrderBig);
224 packet.Write (payload, payload_length);
226 packet.PutHex8(CalculcateChecksum (payload, payload_length));
228 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
229 ConnectionStatus status = eConnectionStatusSuccess;
230 const char *packet_data = packet.GetData();
231 const size_t packet_length = packet.GetSize();
232 size_t bytes_written = Write (packet_data, packet_length, status, NULL);
235 size_t binary_start_offset = 0;
236 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) == 0)
238 const char *first_comma = strchr(packet_data, ',');
241 const char *second_comma = strchr(first_comma + 1, ',');
243 binary_start_offset = second_comma - packet_data + 1;
247 // If logging was just enabled and we have history, then dump out what
248 // we have to the log so we get the historical context. The Dump() call that
249 // logs all of the packet will set a boolean so that we don't dump this more
251 if (!m_history.DidDumpToLog ())
252 m_history.Dump (log);
254 if (binary_start_offset)
257 // Print non binary data header
258 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)binary_start_offset, packet_data);
260 // Print binary data exactly as sent
261 for (p = (uint8_t*)packet_data + binary_start_offset; *p != '#'; ++p)
262 strm.Printf("\\x%2.2x", *p);
263 // Print the checksum
264 strm.Printf("%*s", (int)3, p);
265 log->PutCString(strm.GetString().c_str());
268 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)packet_length, packet_data);
271 m_history.AddPacket (packet.GetString(), packet_length, History::ePacketTypeSend, bytes_written);
274 if (bytes_written == packet_length)
279 return PacketResult::Success;
284 log->Printf ("error: failed to send packet: %.*s", (int)packet_length, packet_data);
287 return PacketResult::ErrorSendFailed;
290 GDBRemoteCommunication::PacketResult
291 GDBRemoteCommunication::GetAck ()
293 StringExtractorGDBRemote packet;
294 PacketResult result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, GetPacketTimeoutInMicroSeconds ());
295 if (result == PacketResult::Success)
297 if (packet.GetResponseType() == StringExtractorGDBRemote::ResponseType::eAck)
298 return PacketResult::Success;
300 return PacketResult::ErrorSendAck;
306 GDBRemoteCommunication::GetSequenceMutex (Mutex::Locker& locker, const char *failure_message)
309 return locker.TryLock (m_sequence_mutex, failure_message);
311 locker.Lock (m_sequence_mutex);
317 GDBRemoteCommunication::WaitForNotRunningPrivate (const TimeValue *timeout_ptr)
319 return m_private_is_running.WaitForValueEqualTo (false, timeout_ptr, NULL);
322 GDBRemoteCommunication::PacketResult
323 GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSecondsNoLock (StringExtractorGDBRemote &packet, uint32_t timeout_usec)
325 uint8_t buffer[8192];
328 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS | GDBR_LOG_VERBOSE));
330 // Check for a packet from our cache first without trying any reading...
331 if (CheckForPacket (NULL, 0, packet))
332 return PacketResult::Success;
334 bool timed_out = false;
335 bool disconnected = false;
336 while (IsConnected() && !timed_out)
338 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
339 size_t bytes_read = Read (buffer, sizeof(buffer), timeout_usec, status, &error);
342 log->Printf ("%s: Read (buffer, (sizeof(buffer), timeout_usec = 0x%x, status = %s, error = %s) => bytes_read = %" PRIu64,
345 Communication::ConnectionStatusAsCString (status),
347 (uint64_t)bytes_read);
351 if (CheckForPacket (buffer, bytes_read, packet))
352 return PacketResult::Success;
358 case eConnectionStatusTimedOut:
359 case eConnectionStatusInterrupted:
362 case eConnectionStatusSuccess:
363 //printf ("status = success but error = %s\n", error.AsCString("<invalid>"));
366 case eConnectionStatusEndOfFile:
367 case eConnectionStatusNoConnection:
368 case eConnectionStatusLostConnection:
369 case eConnectionStatusError:
378 return PacketResult::ErrorDisconnected;
380 return PacketResult::ErrorReplyTimeout;
382 return PacketResult::ErrorReplyFailed;
386 GDBRemoteCommunication::CheckForPacket (const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
388 // Put the packet data into the buffer in a thread safe fashion
389 Mutex::Locker locker(m_bytes_mutex);
391 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
393 if (src && src_len > 0)
395 if (log && log->GetVerbose())
398 log->Printf ("GDBRemoteCommunication::%s adding %u bytes: %.*s",
404 m_bytes.append ((const char *)src, src_len);
407 // Parse up the packets into gdb remote packets
408 if (!m_bytes.empty())
410 // end_idx must be one past the last valid packet byte. Start
411 // it off with an invalid value that is the same as the current
413 size_t content_start = 0;
414 size_t content_length = 0;
415 size_t total_length = 0;
416 size_t checksum_idx = std::string::npos;
420 case '+': // Look for ack
421 case '-': // Look for cancel
422 case '\x03': // ^C to halt target
423 content_length = total_length = 1; // The command is one byte long...
427 // Look for a standard gdb packet?
429 size_t hash_pos = m_bytes.find('#');
430 if (hash_pos != std::string::npos)
432 if (hash_pos + 2 < m_bytes.size())
434 checksum_idx = hash_pos + 1;
435 // Skip the dollar sign
437 // Don't include the # in the content or the $ in the content length
438 content_length = hash_pos - 1;
440 total_length = hash_pos + 3; // Skip the # and the two hex checksum bytes
444 // Checksum bytes aren't all here yet
445 content_length = std::string::npos;
453 // We have an unexpected byte and we need to flush all bad
454 // data that is in m_bytes, so we need to find the first
455 // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt),
456 // or '$' character (start of packet header) or of course,
457 // the end of the data in m_bytes...
458 const size_t bytes_len = m_bytes.size();
461 for (idx = 1; !done && idx < bytes_len; ++idx)
463 switch (m_bytes[idx])
477 log->Printf ("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
478 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
479 m_bytes.erase(0, idx - 1);
484 if (content_length == std::string::npos)
489 else if (total_length > 0)
492 // We have a valid packet...
493 assert (content_length <= m_bytes.size());
494 assert (total_length <= m_bytes.size());
495 assert (content_length <= total_length);
496 const size_t content_end = content_start + content_length;
499 std::string &packet_str = packet.GetStringRef();
504 // If logging was just enabled and we have history, then dump out what
505 // we have to the log so we get the historical context. The Dump() call that
506 // logs all of the packet will set a boolean so that we don't dump this more
508 if (!m_history.DidDumpToLog ())
509 m_history.Dump (log);
512 // Only detect binary for packets that start with a '$' and have a '#CC' checksum
513 if (m_bytes[0] == '$' && total_length > 4)
515 for (size_t i=0; !binary && i<total_length; ++i)
517 if (isprint(m_bytes[i]) == 0)
525 strm.Printf("<%4" PRIu64 "> read packet: %c", (uint64_t)total_length, m_bytes[0]);
526 for (size_t i=content_start; i<content_end; ++i)
528 // Remove binary escaped bytes when displaying the packet...
529 const char ch = m_bytes[i];
532 // 0x7d is the escape character. The next character is to
533 // be XOR'd with 0x20.
534 const char escapee = m_bytes[++i] ^ 0x20;
535 strm.Printf("%2.2x", escapee);
539 strm.Printf("%2.2x", (uint8_t)ch);
543 strm.Printf("%c%c%c", m_bytes[total_length-3], m_bytes[total_length-2], m_bytes[total_length-1]);
544 log->PutCString(strm.GetString().c_str());
548 log->Printf("<%4" PRIu64 "> read packet: %.*s", (uint64_t)total_length, (int)(total_length), m_bytes.c_str());
552 m_history.AddPacket (m_bytes.c_str(), total_length, History::ePacketTypeRecv, total_length);
554 // Clear packet_str in case there is some existing data in it.
556 // Copy the packet from m_bytes to packet_str expanding the
557 // run-length encoding in the process.
558 // Reserve enough byte for the most common case (no RLE used)
559 packet_str.reserve(m_bytes.length());
560 for (std::string::const_iterator c = m_bytes.begin() + content_start; c != m_bytes.begin() + content_end; ++c)
564 // '*' indicates RLE. Next character will give us the
565 // repeat count and previous character is what is to be
567 char char_to_repeat = packet_str.back();
568 // Number of time the previous character is repeated
569 int repeat_count = *++c + 3 - ' ';
570 // We have the char_to_repeat and repeat_count. Now push
572 for (int i = 0; i < repeat_count; ++i)
573 packet_str.push_back(char_to_repeat);
577 // 0x7d is the escape character. The next character is to
578 // be XOR'd with 0x20.
579 char escapee = *++c ^ 0x20;
580 packet_str.push_back(escapee);
584 packet_str.push_back(*c);
588 if (m_bytes[0] == '$')
590 assert (checksum_idx < m_bytes.size());
591 if (::isxdigit (m_bytes[checksum_idx+0]) ||
592 ::isxdigit (m_bytes[checksum_idx+1]))
596 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
597 char packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
598 char actual_checksum = CalculcateChecksum (packet_str.c_str(), packet_str.size());
599 success = packet_checksum == actual_checksum;
603 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
606 (uint8_t)packet_checksum,
607 (uint8_t)actual_checksum);
609 // Send the ack or nack if needed
620 log->Printf ("error: invalid checksum in packet: '%s'\n", m_bytes.c_str());
624 m_bytes.erase(0, total_length);
625 packet.SetFilePos(0);
634 GDBRemoteCommunication::StartListenThread (const char *hostname, uint16_t port)
637 if (m_listen_thread.IsJoinable())
639 error.SetErrorString("listen thread already running");
643 char listen_url[512];
644 if (hostname && hostname[0])
645 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
647 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
648 m_listen_url = listen_url;
649 SetConnection(new ConnectionFileDescriptor());
650 m_listen_thread = ThreadLauncher::LaunchThread(listen_url, GDBRemoteCommunication::ListenThread, this, &error);
656 GDBRemoteCommunication::JoinListenThread ()
658 if (m_listen_thread.IsJoinable())
659 m_listen_thread.Join(nullptr);
663 lldb::thread_result_t
664 GDBRemoteCommunication::ListenThread (lldb::thread_arg_t arg)
666 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
668 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)comm->GetConnection ();
672 // Do the listen on another thread so we can continue on...
673 if (connection->Connect(comm->m_listen_url.c_str(), &error) != eConnectionStatusSuccess)
674 comm->SetConnection(NULL);
680 GDBRemoteCommunication::StartDebugserverProcess (const char *hostname,
682 lldb_private::ProcessLaunchInfo &launch_info,
685 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
687 log->Printf ("GDBRemoteCommunication::%s(hostname=%s, in_port=%" PRIu16 ", out_port=%" PRIu16, __FUNCTION__, hostname ? hostname : "<empty>", in_port, out_port);
691 // If we locate debugserver, keep that located version around
692 static FileSpec g_debugserver_file_spec;
694 char debugserver_path[PATH_MAX];
695 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
697 // Always check to see if we have an environment override for the path
698 // to the debugserver to use and use it if we do.
699 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
700 if (env_debugserver_path)
702 debugserver_file_spec.SetFile (env_debugserver_path, false);
704 log->Printf ("GDBRemoteCommunication::%s() gdb-remote stub exe path set from environment variable: %s", __FUNCTION__, env_debugserver_path);
707 debugserver_file_spec = g_debugserver_file_spec;
708 bool debugserver_exists = debugserver_file_spec.Exists();
709 if (!debugserver_exists)
711 // The debugserver binary is in the LLDB.framework/Resources
713 if (HostInfo::GetLLDBPath(ePathTypeSupportExecutableDir, debugserver_file_spec))
715 debugserver_file_spec.AppendPathComponent (DEBUGSERVER_BASENAME);
716 debugserver_exists = debugserver_file_spec.Exists();
717 if (debugserver_exists)
720 log->Printf ("GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
722 g_debugserver_file_spec = debugserver_file_spec;
727 log->Printf ("GDBRemoteCommunication::%s() could not find gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
729 g_debugserver_file_spec.Clear();
730 debugserver_file_spec.Clear();
735 if (debugserver_exists)
737 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
739 Args &debugserver_args = launch_info.GetArguments();
740 debugserver_args.Clear();
741 char arg_cstr[PATH_MAX];
743 // Start args with "debugserver /file/path -r --"
744 debugserver_args.AppendArgument(debugserver_path);
746 // If a host and port is supplied then use it
747 char host_and_port[128];
750 snprintf (host_and_port, sizeof(host_and_port), "%s:%u", hostname, in_port);
751 debugserver_args.AppendArgument(host_and_port);
755 host_and_port[0] = '\0';
758 // use native registers, not the GDB registers
759 debugserver_args.AppendArgument("--native-regs");
760 // make debugserver run in its own session so signals generated by
761 // special terminal key sequences (^C) don't affect debugserver
762 debugserver_args.AppendArgument("--setsid");
764 char named_pipe_path[PATH_MAX];
765 named_pipe_path[0] = '\0';
766 Pipe port_named_pipe;
769 if (host_and_port[0])
771 // Create a temporary file to get the stdout/stderr and redirect the
772 // output of the command into this file. We will later read this file
773 // if all goes well and fill the data into "command_output_ptr"
777 // Binding to port zero, we need to figure out what port it ends up
778 // using using a named pipe...
779 FileSpec tmpdir_file_spec;
780 if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
782 tmpdir_file_spec.AppendPathComponent("debugserver-named-pipe.XXXXXX");
783 strncpy(named_pipe_path, tmpdir_file_spec.GetPath().c_str(), sizeof(named_pipe_path));
787 strncpy(named_pipe_path, "/tmp/debugserver-named-pipe.XXXXXX", sizeof(named_pipe_path));
790 if (::mktemp (named_pipe_path))
792 error = port_named_pipe.CreateNew(named_pipe_path, false);
795 debugserver_args.AppendArgument("--named-pipe");
796 debugserver_args.AppendArgument(named_pipe_path);
806 // No host and port given, so lets listen on our end and make the debugserver
808 error = StartListenThread ("127.0.0.1", 0);
812 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)GetConnection ();
813 // Wait for 10 seconds to resolve the bound port
814 out_port = connection->GetListeningPort(10);
818 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", out_port);
819 // Send the host and port down that debugserver and specify an option
820 // so that it connects back to the port we are listening to in this process
821 debugserver_args.AppendArgument("--reverse-connect");
822 debugserver_args.AppendArgument(port_cstr);
826 error.SetErrorString ("failed to bind to port 0 on 127.0.0.1");
831 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
832 if (env_debugserver_log_file)
834 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
835 debugserver_args.AppendArgument(arg_cstr);
838 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
839 if (env_debugserver_log_flags)
841 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
842 debugserver_args.AppendArgument(arg_cstr);
845 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an env var doesn't come back.
846 uint32_t env_var_index = 1;
850 char env_var_name[64];
851 snprintf (env_var_name, sizeof (env_var_name), "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
852 const char *extra_arg = getenv(env_var_name);
853 has_env_var = extra_arg != nullptr;
857 debugserver_args.AppendArgument (extra_arg);
859 log->Printf ("GDBRemoteCommunication::%s adding env var %s contents to stub command line (%s)", __FUNCTION__, env_var_name, extra_arg);
861 } while (has_env_var);
863 // Close STDIN, STDOUT and STDERR.
864 launch_info.AppendCloseFileAction (STDIN_FILENO);
865 launch_info.AppendCloseFileAction (STDOUT_FILENO);
866 launch_info.AppendCloseFileAction (STDERR_FILENO);
868 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
869 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
870 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
871 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
873 error = Host::LaunchProcess(launch_info);
875 if (error.Success() && launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
877 if (named_pipe_path[0])
879 error = port_named_pipe.OpenAsReader(named_pipe_path, false);
884 size_t num_bytes = sizeof(port_cstr);
885 // Read port from pipe with 10 second timeout.
886 error = port_named_pipe.ReadWithTimeout(port_cstr, num_bytes, std::chrono::microseconds(10 * 1000000), num_bytes);
889 assert (num_bytes > 0 && port_cstr[num_bytes-1] == '\0');
890 out_port = Args::StringToUInt32(port_cstr, 0);
892 log->Printf("GDBRemoteCommunication::%s() debugserver listens %u port", __FUNCTION__, out_port);
897 log->Printf("GDBRemoteCommunication::%s() failed to read a port value from named pipe %s: %s", __FUNCTION__, named_pipe_path, error.AsCString());
900 port_named_pipe.Close();
905 log->Printf("GDBRemoteCommunication::%s() failed to open named pipe %s for reading: %s", __FUNCTION__, named_pipe_path, error.AsCString());
907 const auto err = port_named_pipe.Delete(named_pipe_path);
911 log->Printf ("GDBRemoteCommunication::%s failed to delete pipe %s: %s", __FUNCTION__, named_pipe_path, err.AsCString());
920 // Make sure we actually connect with the debugserver...
927 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME );
933 GDBRemoteCommunication::DumpHistory(Stream &strm)
935 m_history.Dump (strm);