xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp (revision 9aa2da0025bb8ad821a84b20edd130a33c536159)
1 //===-- 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
14 #include <limits.h>
15 #include <string.h>
16 #include <sys/stat.h>
17 
18 // C++ Includes
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/StringConvert.h"
30 #include "lldb/Host/ThreadLauncher.h"
31 #include "lldb/Host/TimeValue.h"
32 #include "lldb/Target/Process.h"
33 #include "llvm/ADT/SmallString.h"
34 
35 // Project includes
36 #include "ProcessGDBRemoteLog.h"
37 
38 #if defined(__APPLE__)
39 # define DEBUGSERVER_BASENAME    "debugserver"
40 #else
41 # define DEBUGSERVER_BASENAME    "lldb-server"
42 #endif
43 
44 using namespace lldb;
45 using namespace lldb_private;
46 using namespace lldb_private::process_gdb_remote;
47 
48 GDBRemoteCommunication::History::History (uint32_t size) :
49     m_packets(),
50     m_curr_idx (0),
51     m_total_packet_count (0),
52     m_dumped_to_log (false)
53 {
54     m_packets.resize(size);
55 }
56 
57 GDBRemoteCommunication::History::~History ()
58 {
59 }
60 
61 void
62 GDBRemoteCommunication::History::AddPacket (char packet_char,
63                                             PacketType type,
64                                             uint32_t bytes_transmitted)
65 {
66     const size_t size = m_packets.size();
67     if (size > 0)
68     {
69         const uint32_t idx = GetNextIndex();
70         m_packets[idx].packet.assign (1, packet_char);
71         m_packets[idx].type = type;
72         m_packets[idx].bytes_transmitted = bytes_transmitted;
73         m_packets[idx].packet_idx = m_total_packet_count;
74         m_packets[idx].tid = Host::GetCurrentThreadID();
75     }
76 }
77 
78 void
79 GDBRemoteCommunication::History::AddPacket (const std::string &src,
80                                             uint32_t src_len,
81                                             PacketType type,
82                                             uint32_t bytes_transmitted)
83 {
84     const size_t size = m_packets.size();
85     if (size > 0)
86     {
87         const uint32_t idx = GetNextIndex();
88         m_packets[idx].packet.assign (src, 0, src_len);
89         m_packets[idx].type = type;
90         m_packets[idx].bytes_transmitted = bytes_transmitted;
91         m_packets[idx].packet_idx = m_total_packet_count;
92         m_packets[idx].tid = Host::GetCurrentThreadID();
93     }
94 }
95 
96 void
97 GDBRemoteCommunication::History::Dump (Stream &strm) const
98 {
99     const uint32_t size = GetNumPacketsInHistory ();
100     const uint32_t first_idx = GetFirstSavedPacketIndex ();
101     const uint32_t stop_idx = m_curr_idx + size;
102     for (uint32_t i = first_idx;  i < stop_idx; ++i)
103     {
104         const uint32_t idx = NormalizeIndex (i);
105         const Entry &entry = m_packets[idx];
106         if (entry.type == ePacketTypeInvalid || entry.packet.empty())
107             break;
108         strm.Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s\n",
109                      entry.packet_idx,
110                      entry.tid,
111                      entry.bytes_transmitted,
112                      (entry.type == ePacketTypeSend) ? "send" : "read",
113                      entry.packet.c_str());
114     }
115 }
116 
117 void
118 GDBRemoteCommunication::History::Dump (Log *log) const
119 {
120     if (log && !m_dumped_to_log)
121     {
122         m_dumped_to_log = true;
123         const uint32_t size = GetNumPacketsInHistory ();
124         const uint32_t first_idx = GetFirstSavedPacketIndex ();
125         const uint32_t stop_idx = m_curr_idx + size;
126         for (uint32_t i = first_idx;  i < stop_idx; ++i)
127         {
128             const uint32_t idx = NormalizeIndex (i);
129             const Entry &entry = m_packets[idx];
130             if (entry.type == ePacketTypeInvalid || entry.packet.empty())
131                 break;
132             log->Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s",
133                          entry.packet_idx,
134                          entry.tid,
135                          entry.bytes_transmitted,
136                          (entry.type == ePacketTypeSend) ? "send" : "read",
137                          entry.packet.c_str());
138         }
139     }
140 }
141 
142 //----------------------------------------------------------------------
143 // GDBRemoteCommunication constructor
144 //----------------------------------------------------------------------
145 GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
146                                                const char *listener_name) :
147     Communication(comm_name),
148 #ifdef LLDB_CONFIGURATION_DEBUG
149     m_packet_timeout (1000),
150 #else
151     m_packet_timeout (1),
152 #endif
153     m_sequence_mutex (Mutex::eMutexTypeRecursive),
154     m_public_is_running (false),
155     m_private_is_running (false),
156     m_history (512),
157     m_send_acks (true),
158     m_listen_url ()
159 {
160 }
161 
162 //----------------------------------------------------------------------
163 // Destructor
164 //----------------------------------------------------------------------
165 GDBRemoteCommunication::~GDBRemoteCommunication()
166 {
167     if (IsConnected())
168     {
169         Disconnect();
170     }
171 }
172 
173 char
174 GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length)
175 {
176     int checksum = 0;
177 
178     for (size_t i = 0; i < payload_length; ++i)
179         checksum += payload[i];
180 
181     return checksum & 255;
182 }
183 
184 size_t
185 GDBRemoteCommunication::SendAck ()
186 {
187     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
188     ConnectionStatus status = eConnectionStatusSuccess;
189     char ch = '+';
190     const size_t bytes_written = Write (&ch, 1, status, NULL);
191     if (log)
192         log->Printf ("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
193     m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
194     return bytes_written;
195 }
196 
197 size_t
198 GDBRemoteCommunication::SendNack ()
199 {
200     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
201     ConnectionStatus status = eConnectionStatusSuccess;
202     char ch = '-';
203     const size_t bytes_written = Write (&ch, 1, status, NULL);
204     if (log)
205         log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
206     m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
207     return bytes_written;
208 }
209 
210 GDBRemoteCommunication::PacketResult
211 GDBRemoteCommunication::SendPacket (const char *payload, size_t payload_length)
212 {
213     Mutex::Locker locker(m_sequence_mutex);
214     return SendPacketNoLock (payload, payload_length);
215 }
216 
217 GDBRemoteCommunication::PacketResult
218 GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length)
219 {
220     if (IsConnected())
221     {
222         StreamString packet(0, 4, eByteOrderBig);
223 
224         packet.PutChar('$');
225         packet.Write (payload, payload_length);
226         packet.PutChar('#');
227         packet.PutHex8(CalculcateChecksum (payload, payload_length));
228 
229         Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
230         ConnectionStatus status = eConnectionStatusSuccess;
231         const char *packet_data = packet.GetData();
232         const size_t packet_length = packet.GetSize();
233         size_t bytes_written = Write (packet_data, packet_length, status, NULL);
234         if (log)
235         {
236             size_t binary_start_offset = 0;
237             if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) == 0)
238             {
239                 const char *first_comma = strchr(packet_data, ',');
240                 if (first_comma)
241                 {
242                     const char *second_comma = strchr(first_comma + 1, ',');
243                     if (second_comma)
244                         binary_start_offset = second_comma - packet_data + 1;
245                 }
246             }
247 
248             // If logging was just enabled and we have history, then dump out what
249             // we have to the log so we get the historical context. The Dump() call that
250             // logs all of the packet will set a boolean so that we don't dump this more
251             // than once
252             if (!m_history.DidDumpToLog ())
253                 m_history.Dump (log);
254 
255             if (binary_start_offset)
256             {
257                 StreamString strm;
258                 // Print non binary data header
259                 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)binary_start_offset, packet_data);
260                 const uint8_t *p;
261                 // Print binary data exactly as sent
262                 for (p = (const uint8_t*)packet_data + binary_start_offset; *p != '#'; ++p)
263                     strm.Printf("\\x%2.2x", *p);
264                 // Print the checksum
265                 strm.Printf("%*s", (int)3, p);
266                 log->PutCString(strm.GetString().c_str());
267             }
268             else
269                 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)packet_length, packet_data);
270         }
271 
272         m_history.AddPacket (packet.GetString(), packet_length, History::ePacketTypeSend, bytes_written);
273 
274 
275         if (bytes_written == packet_length)
276         {
277             if (GetSendAcks ())
278                 return GetAck ();
279             else
280                 return PacketResult::Success;
281         }
282         else
283         {
284             if (log)
285                 log->Printf ("error: failed to send packet: %.*s", (int)packet_length, packet_data);
286         }
287     }
288     return PacketResult::ErrorSendFailed;
289 }
290 
291 GDBRemoteCommunication::PacketResult
292 GDBRemoteCommunication::GetAck ()
293 {
294     StringExtractorGDBRemote packet;
295     PacketResult result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, GetPacketTimeoutInMicroSeconds ());
296     if (result == PacketResult::Success)
297     {
298         if (packet.GetResponseType() == StringExtractorGDBRemote::ResponseType::eAck)
299             return PacketResult::Success;
300         else
301             return PacketResult::ErrorSendAck;
302     }
303     return result;
304 }
305 
306 bool
307 GDBRemoteCommunication::GetSequenceMutex (Mutex::Locker& locker, const char *failure_message)
308 {
309     if (IsRunning())
310         return locker.TryLock (m_sequence_mutex, failure_message);
311 
312     locker.Lock (m_sequence_mutex);
313     return true;
314 }
315 
316 
317 bool
318 GDBRemoteCommunication::WaitForNotRunningPrivate (const TimeValue *timeout_ptr)
319 {
320     return m_private_is_running.WaitForValueEqualTo (false, timeout_ptr, NULL);
321 }
322 
323 GDBRemoteCommunication::PacketResult
324 GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSecondsNoLock (StringExtractorGDBRemote &packet, uint32_t timeout_usec)
325 {
326     uint8_t buffer[8192];
327     Error error;
328 
329     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS | GDBR_LOG_VERBOSE));
330 
331     // Check for a packet from our cache first without trying any reading...
332     if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
333         return PacketResult::Success;
334 
335     bool timed_out = false;
336     bool disconnected = false;
337     while (IsConnected() && !timed_out)
338     {
339         lldb::ConnectionStatus status = eConnectionStatusNoConnection;
340         size_t bytes_read = Read (buffer, sizeof(buffer), timeout_usec, status, &error);
341 
342         if (log)
343             log->Printf ("%s: Read (buffer, (sizeof(buffer), timeout_usec = 0x%x, status = %s, error = %s) => bytes_read = %" PRIu64,
344                          __PRETTY_FUNCTION__,
345                          timeout_usec,
346                          Communication::ConnectionStatusAsCString (status),
347                          error.AsCString(),
348                          (uint64_t)bytes_read);
349 
350         if (bytes_read > 0)
351         {
352             if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
353                 return PacketResult::Success;
354         }
355         else
356         {
357             switch (status)
358             {
359             case eConnectionStatusTimedOut:
360             case eConnectionStatusInterrupted:
361                 timed_out = true;
362                 break;
363             case eConnectionStatusSuccess:
364                 //printf ("status = success but error = %s\n", error.AsCString("<invalid>"));
365                 break;
366 
367             case eConnectionStatusEndOfFile:
368             case eConnectionStatusNoConnection:
369             case eConnectionStatusLostConnection:
370             case eConnectionStatusError:
371                 disconnected = true;
372                 Disconnect();
373                 break;
374             }
375         }
376     }
377     packet.Clear ();
378     if (disconnected)
379         return PacketResult::ErrorDisconnected;
380     if (timed_out)
381         return PacketResult::ErrorReplyTimeout;
382     else
383         return PacketResult::ErrorReplyFailed;
384 }
385 
386 GDBRemoteCommunication::PacketType
387 GDBRemoteCommunication::CheckForPacket (const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
388 {
389     // Put the packet data into the buffer in a thread safe fashion
390     Mutex::Locker locker(m_bytes_mutex);
391 
392     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
393 
394     if (src && src_len > 0)
395     {
396         if (log && log->GetVerbose())
397         {
398             StreamString s;
399             log->Printf ("GDBRemoteCommunication::%s adding %u bytes: %.*s",
400                          __FUNCTION__,
401                          (uint32_t)src_len,
402                          (uint32_t)src_len,
403                          src);
404         }
405         m_bytes.append ((const char *)src, src_len);
406     }
407 
408     bool isNotifyPacket = false;
409 
410     // Parse up the packets into gdb remote packets
411     if (!m_bytes.empty())
412     {
413         // end_idx must be one past the last valid packet byte. Start
414         // it off with an invalid value that is the same as the current
415         // index.
416         size_t content_start = 0;
417         size_t content_length = 0;
418         size_t total_length = 0;
419         size_t checksum_idx = std::string::npos;
420 
421         switch (m_bytes[0])
422         {
423             case '+':       // Look for ack
424             case '-':       // Look for cancel
425             case '\x03':    // ^C to halt target
426                 content_length = total_length = 1;  // The command is one byte long...
427                 break;
428 
429             case '%': // Async notify packet
430                 isNotifyPacket = true;
431                 // Intentional fall through
432 
433             case '$':
434                 // Look for a standard gdb packet?
435                 {
436                     size_t hash_pos = m_bytes.find('#');
437                     if (hash_pos != std::string::npos)
438                     {
439                         if (hash_pos + 2 < m_bytes.size())
440                         {
441                             checksum_idx = hash_pos + 1;
442                             // Skip the dollar sign
443                             content_start = 1;
444                             // Don't include the # in the content or the $ in the content length
445                             content_length = hash_pos - 1;
446 
447                             total_length = hash_pos + 3; // Skip the # and the two hex checksum bytes
448                         }
449                         else
450                         {
451                             // Checksum bytes aren't all here yet
452                             content_length = std::string::npos;
453                         }
454                     }
455                 }
456                 break;
457 
458             default:
459                 {
460                     // We have an unexpected byte and we need to flush all bad
461                     // data that is in m_bytes, so we need to find the first
462                     // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt),
463                     // or '$' character (start of packet header) or of course,
464                     // the end of the data in m_bytes...
465                     const size_t bytes_len = m_bytes.size();
466                     bool done = false;
467                     uint32_t idx;
468                     for (idx = 1; !done && idx < bytes_len; ++idx)
469                     {
470                         switch (m_bytes[idx])
471                         {
472                         case '+':
473                         case '-':
474                         case '\x03':
475                         case '%':
476                         case '$':
477                             done = true;
478                             break;
479 
480                         default:
481                             break;
482                         }
483                     }
484                     if (log)
485                         log->Printf ("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
486                                      __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
487                     m_bytes.erase(0, idx - 1);
488                 }
489                 break;
490         }
491 
492         if (content_length == std::string::npos)
493         {
494             packet.Clear();
495             return GDBRemoteCommunication::PacketType::Invalid;
496         }
497         else if (total_length > 0)
498         {
499 
500             // We have a valid packet...
501             assert (content_length <= m_bytes.size());
502             assert (total_length <= m_bytes.size());
503             assert (content_length <= total_length);
504             const size_t content_end = content_start + content_length;
505 
506             bool success = true;
507             std::string &packet_str = packet.GetStringRef();
508 
509 
510             if (log)
511             {
512                 // If logging was just enabled and we have history, then dump out what
513                 // we have to the log so we get the historical context. The Dump() call that
514                 // logs all of the packet will set a boolean so that we don't dump this more
515                 // than once
516                 if (!m_history.DidDumpToLog ())
517                     m_history.Dump (log);
518 
519                 bool binary = false;
520                 // Only detect binary for packets that start with a '$' and have a '#CC' checksum
521                 if (m_bytes[0] == '$' && total_length > 4)
522                 {
523                     for (size_t i=0; !binary && i<total_length; ++i)
524                     {
525                         if (isprint(m_bytes[i]) == 0)
526                             binary = true;
527                     }
528                 }
529                 if (binary)
530                 {
531                     StreamString strm;
532                     // Packet header...
533                     strm.Printf("<%4" PRIu64 "> read packet: %c", (uint64_t)total_length, m_bytes[0]);
534                     for (size_t i=content_start; i<content_end; ++i)
535                     {
536                         // Remove binary escaped bytes when displaying the packet...
537                         const char ch = m_bytes[i];
538                         if (ch == 0x7d)
539                         {
540                             // 0x7d is the escape character.  The next character is to
541                             // be XOR'd with 0x20.
542                             const char escapee = m_bytes[++i] ^ 0x20;
543                             strm.Printf("%2.2x", escapee);
544                         }
545                         else
546                         {
547                             strm.Printf("%2.2x", (uint8_t)ch);
548                         }
549                     }
550                     // Packet footer...
551                     strm.Printf("%c%c%c", m_bytes[total_length-3], m_bytes[total_length-2], m_bytes[total_length-1]);
552                     log->PutCString(strm.GetString().c_str());
553                 }
554                 else
555                 {
556                     log->Printf("<%4" PRIu64 "> read packet: %.*s", (uint64_t)total_length, (int)(total_length), m_bytes.c_str());
557                 }
558             }
559 
560             m_history.AddPacket (m_bytes.c_str(), total_length, History::ePacketTypeRecv, total_length);
561 
562             // Clear packet_str in case there is some existing data in it.
563             packet_str.clear();
564             // Copy the packet from m_bytes to packet_str expanding the
565             // run-length encoding in the process.
566             // Reserve enough byte for the most common case (no RLE used)
567             packet_str.reserve(m_bytes.length());
568             for (std::string::const_iterator c = m_bytes.begin() + content_start; c != m_bytes.begin() + content_end; ++c)
569             {
570                 if (*c == '*')
571                 {
572                     // '*' indicates RLE. Next character will give us the
573                     // repeat count and previous character is what is to be
574                     // repeated.
575                     char char_to_repeat = packet_str.back();
576                     // Number of time the previous character is repeated
577                     int repeat_count = *++c + 3 - ' ';
578                     // We have the char_to_repeat and repeat_count. Now push
579                     // it in the packet.
580                     for (int i = 0; i < repeat_count; ++i)
581                         packet_str.push_back(char_to_repeat);
582                 }
583                 else if (*c == 0x7d)
584                 {
585                     // 0x7d is the escape character.  The next character is to
586                     // be XOR'd with 0x20.
587                     char escapee = *++c ^ 0x20;
588                     packet_str.push_back(escapee);
589                 }
590                 else
591                 {
592                     packet_str.push_back(*c);
593                 }
594             }
595 
596             if (m_bytes[0] == '$' || m_bytes[0] == '%')
597             {
598                 assert (checksum_idx < m_bytes.size());
599                 if (::isxdigit (m_bytes[checksum_idx+0]) ||
600                     ::isxdigit (m_bytes[checksum_idx+1]))
601                 {
602                     if (GetSendAcks ())
603                     {
604                         const char *packet_checksum_cstr = &m_bytes[checksum_idx];
605                         char packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
606                         char actual_checksum = CalculcateChecksum (packet_str.c_str(), packet_str.size());
607                         success = packet_checksum == actual_checksum;
608                         if (!success)
609                         {
610                             if (log)
611                                 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
612                                              (int)(total_length),
613                                              m_bytes.c_str(),
614                                              (uint8_t)packet_checksum,
615                                              (uint8_t)actual_checksum);
616                         }
617                         // Send the ack or nack if needed
618                         if (!success)
619                             SendNack();
620                         else
621                             SendAck();
622                     }
623                 }
624                 else
625                 {
626                     success = false;
627                     if (log)
628                         log->Printf ("error: invalid checksum in packet: '%s'\n", m_bytes.c_str());
629                 }
630             }
631 
632             m_bytes.erase(0, total_length);
633             packet.SetFilePos(0);
634 
635             if (isNotifyPacket)
636                 return GDBRemoteCommunication::PacketType::Notify;
637             else
638                 return GDBRemoteCommunication::PacketType::Standard;
639         }
640     }
641     packet.Clear();
642     return GDBRemoteCommunication::PacketType::Invalid;
643 }
644 
645 Error
646 GDBRemoteCommunication::StartListenThread (const char *hostname, uint16_t port)
647 {
648     Error error;
649     if (m_listen_thread.IsJoinable())
650     {
651         error.SetErrorString("listen thread already running");
652     }
653     else
654     {
655         char listen_url[512];
656         if (hostname && hostname[0])
657             snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
658         else
659             snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
660         m_listen_url = listen_url;
661         SetConnection(new ConnectionFileDescriptor());
662         m_listen_thread = ThreadLauncher::LaunchThread(listen_url, GDBRemoteCommunication::ListenThread, this, &error);
663     }
664     return error;
665 }
666 
667 bool
668 GDBRemoteCommunication::JoinListenThread ()
669 {
670     if (m_listen_thread.IsJoinable())
671         m_listen_thread.Join(nullptr);
672     return true;
673 }
674 
675 lldb::thread_result_t
676 GDBRemoteCommunication::ListenThread (lldb::thread_arg_t arg)
677 {
678     GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
679     Error error;
680     ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)comm->GetConnection ();
681 
682     if (connection)
683     {
684         // Do the listen on another thread so we can continue on...
685         if (connection->Connect(comm->m_listen_url.c_str(), &error) != eConnectionStatusSuccess)
686             comm->SetConnection(NULL);
687     }
688     return NULL;
689 }
690 
691 Error
692 GDBRemoteCommunication::StartDebugserverProcess (const char *hostname,
693                                                  uint16_t in_port,
694                                                  ProcessLaunchInfo &launch_info,
695                                                  uint16_t &out_port)
696 {
697     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
698     if (log)
699         log->Printf ("GDBRemoteCommunication::%s(hostname=%s, in_port=%" PRIu16 ", out_port=%" PRIu16, __FUNCTION__, hostname ? hostname : "<empty>", in_port, out_port);
700 
701     out_port = in_port;
702     Error error;
703     // If we locate debugserver, keep that located version around
704     static FileSpec g_debugserver_file_spec;
705 
706     char debugserver_path[PATH_MAX];
707     FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
708 
709     // Always check to see if we have an environment override for the path
710     // to the debugserver to use and use it if we do.
711     const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
712     if (env_debugserver_path)
713     {
714         debugserver_file_spec.SetFile (env_debugserver_path, false);
715         if (log)
716             log->Printf ("GDBRemoteCommunication::%s() gdb-remote stub exe path set from environment variable: %s", __FUNCTION__, env_debugserver_path);
717     }
718     else
719         debugserver_file_spec = g_debugserver_file_spec;
720     bool debugserver_exists = debugserver_file_spec.Exists();
721     if (!debugserver_exists)
722     {
723         // The debugserver binary is in the LLDB.framework/Resources
724         // directory.
725         if (HostInfo::GetLLDBPath(ePathTypeSupportExecutableDir, debugserver_file_spec))
726         {
727             debugserver_file_spec.AppendPathComponent (DEBUGSERVER_BASENAME);
728             debugserver_exists = debugserver_file_spec.Exists();
729             if (debugserver_exists)
730             {
731                 if (log)
732                     log->Printf ("GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
733 
734                 g_debugserver_file_spec = debugserver_file_spec;
735             }
736             else
737             {
738                 if (log)
739                     log->Printf ("GDBRemoteCommunication::%s() could not find gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
740 
741                 g_debugserver_file_spec.Clear();
742                 debugserver_file_spec.Clear();
743             }
744         }
745     }
746 
747     if (debugserver_exists)
748     {
749         debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
750 
751         Args &debugserver_args = launch_info.GetArguments();
752         debugserver_args.Clear();
753         char arg_cstr[PATH_MAX];
754 
755         // Start args with "debugserver /file/path -r --"
756         debugserver_args.AppendArgument(debugserver_path);
757 
758 #if !defined(__APPLE__)
759         // First argument to lldb-server must be mode in which to run.
760         debugserver_args.AppendArgument("gdbserver");
761 #endif
762 
763         // If a host and port is supplied then use it
764         char host_and_port[128];
765         if (hostname)
766         {
767             snprintf (host_and_port, sizeof(host_and_port), "%s:%u", hostname, in_port);
768             debugserver_args.AppendArgument(host_and_port);
769         }
770         else
771         {
772             host_and_port[0] = '\0';
773         }
774 
775         // use native registers, not the GDB registers
776         debugserver_args.AppendArgument("--native-regs");
777 
778         if (launch_info.GetLaunchInSeparateProcessGroup())
779         {
780             debugserver_args.AppendArgument("--setsid");
781         }
782 
783         llvm::SmallString<PATH_MAX> named_pipe_path;
784         Pipe port_pipe;
785 
786         if (host_and_port[0] && in_port == 0)
787         {
788             // Create a temporary file to get the stdout/stderr and redirect the
789             // output of the command into this file. We will later read this file
790             // if all goes well and fill the data into "command_output_ptr"
791 
792             // Binding to port zero, we need to figure out what port it ends up
793             // using using a named pipe...
794             error = port_pipe.CreateWithUniqueName("debugserver-named-pipe", false, named_pipe_path);
795             if (error.Success())
796             {
797                 debugserver_args.AppendArgument("--named-pipe");
798                 debugserver_args.AppendArgument(named_pipe_path.c_str());
799             }
800             else
801             {
802                 if (log)
803                     log->Printf("GDBRemoteCommunication::%s() "
804                             "named pipe creation failed: %s",
805                             __FUNCTION__, error.AsCString());
806                 // let's try an unnamed pipe
807                 error = port_pipe.CreateNew(true);
808                 if (error.Fail())
809                 {
810                     if (log)
811                         log->Printf("GDBRemoteCommunication::%s() "
812                                 "unnamed pipe creation failed: %s",
813                                 __FUNCTION__, error.AsCString());
814                     return error;
815                 }
816                 int write_fd = port_pipe.GetWriteFileDescriptor();
817                 debugserver_args.AppendArgument("--pipe");
818                 debugserver_args.AppendArgument(std::to_string(write_fd).c_str());
819                 launch_info.AppendCloseFileAction(port_pipe.GetReadFileDescriptor());
820             }
821         }
822         else
823         {
824             // No host and port given, so lets listen on our end and make the debugserver
825             // connect to us..
826             error = StartListenThread ("127.0.0.1", 0);
827             if (error.Fail())
828             {
829                 if (log)
830                     log->Printf ("GDBRemoteCommunication::%s() unable to start listen thread: %s", __FUNCTION__, error.AsCString());
831                 return error;
832             }
833 
834             ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)GetConnection ();
835             // Wait for 10 seconds to resolve the bound port
836             out_port = connection->GetListeningPort(10);
837             if (out_port > 0)
838             {
839                 char port_cstr[32];
840                 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", out_port);
841                 // Send the host and port down that debugserver and specify an option
842                 // so that it connects back to the port we are listening to in this process
843                 debugserver_args.AppendArgument("--reverse-connect");
844                 debugserver_args.AppendArgument(port_cstr);
845             }
846             else
847             {
848                 error.SetErrorString ("failed to bind to port 0 on 127.0.0.1");
849                 if (log)
850                     log->Printf ("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__, error.AsCString());
851                 return error;
852             }
853         }
854 
855         const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
856         if (env_debugserver_log_file)
857         {
858             ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
859             debugserver_args.AppendArgument(arg_cstr);
860         }
861 
862 #if defined(__APPLE__)
863         const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
864         if (env_debugserver_log_flags)
865         {
866             ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
867             debugserver_args.AppendArgument(arg_cstr);
868         }
869 #else
870         const char *env_debugserver_log_channels = getenv("LLDB_SERVER_LOG_CHANNELS");
871         if (env_debugserver_log_channels)
872         {
873             ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-channels=%s", env_debugserver_log_channels);
874             debugserver_args.AppendArgument(arg_cstr);
875         }
876 #endif
877 
878         // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an env var doesn't come back.
879         uint32_t env_var_index = 1;
880         bool has_env_var;
881         do
882         {
883             char env_var_name[64];
884             snprintf (env_var_name, sizeof (env_var_name), "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
885             const char *extra_arg = getenv(env_var_name);
886             has_env_var = extra_arg != nullptr;
887 
888             if (has_env_var)
889             {
890                 debugserver_args.AppendArgument (extra_arg);
891                 if (log)
892                     log->Printf ("GDBRemoteCommunication::%s adding env var %s contents to stub command line (%s)", __FUNCTION__, env_var_name, extra_arg);
893             }
894         } while (has_env_var);
895 
896         // Close STDIN, STDOUT and STDERR.
897         launch_info.AppendCloseFileAction (STDIN_FILENO);
898         launch_info.AppendCloseFileAction (STDOUT_FILENO);
899         launch_info.AppendCloseFileAction (STDERR_FILENO);
900 
901         // Redirect STDIN, STDOUT and STDERR to "/dev/null".
902         launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
903         launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
904         launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
905 
906         error = Host::LaunchProcess(launch_info);
907 
908         if (error.Success() && launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
909         {
910             if (named_pipe_path.size() > 0)
911             {
912                 error = port_pipe.OpenAsReader(named_pipe_path, false);
913                 if (error.Fail())
914                     if (log)
915                         log->Printf("GDBRemoteCommunication::%s() "
916                                 "failed to open named pipe %s for reading: %s",
917                                 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
918             }
919 
920             if (port_pipe.CanWrite())
921                 port_pipe.CloseWriteFileDescriptor();
922             if (port_pipe.CanRead())
923             {
924                 char port_cstr[256];
925                 port_cstr[0] = '\0';
926                 size_t num_bytes = sizeof(port_cstr);
927                 // Read port from pipe with 10 second timeout.
928                 error = port_pipe.ReadWithTimeout(port_cstr, num_bytes,
929                         std::chrono::seconds{10}, num_bytes);
930                 if (error.Success())
931                 {
932                     assert(num_bytes > 0 && port_cstr[num_bytes-1] == '\0');
933                     out_port = StringConvert::ToUInt32(port_cstr, 0);
934                     if (log)
935                         log->Printf("GDBRemoteCommunication::%s() "
936                                 "debugserver listens %u port",
937                                 __FUNCTION__, out_port);
938                 }
939                 else
940                 {
941                     if (log)
942                         log->Printf("GDBRemoteCommunication::%s() "
943                                 "failed to read a port value from pipe %s: %s",
944                                 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
945 
946                 }
947                 port_pipe.Close();
948             }
949 
950             if (named_pipe_path.size() > 0)
951             {
952                 const auto err = port_pipe.Delete(named_pipe_path);
953                 if (err.Fail())
954                 {
955                     if (log)
956                         log->Printf ("GDBRemoteCommunication::%s failed to delete pipe %s: %s",
957                                 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
958                 }
959             }
960 
961             // Make sure we actually connect with the debugserver...
962             JoinListenThread();
963         }
964     }
965     else
966     {
967         error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME );
968     }
969 
970     if (error.Fail())
971     {
972         if (log)
973             log->Printf ("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__, error.AsCString());
974     }
975 
976     return error;
977 }
978 
979 void
980 GDBRemoteCommunication::DumpHistory(Stream &strm)
981 {
982     m_history.Dump (strm);
983 }
984 
985 GDBRemoteCommunication::ScopedTimeout::ScopedTimeout (GDBRemoteCommunication& gdb_comm,
986                                                       uint32_t timeout) :
987     m_gdb_comm (gdb_comm)
988 {
989     m_saved_timeout = m_gdb_comm.SetPacketTimeout (timeout);
990 }
991 
992 GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout ()
993 {
994     m_gdb_comm.SetPacketTimeout (m_saved_timeout);
995 }
996