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 
17 // C++ Includes
18 // Other libraries and framework includes
19 #include "lldb/Core/Log.h"
20 #include "lldb/Core/StreamFile.h"
21 #include "lldb/Core/StreamString.h"
22 #include "lldb/Host/FileSpec.h"
23 #include "lldb/Host/Host.h"
24 #include "lldb/Host/TimeValue.h"
25 #include "lldb/Target/Process.h"
26 
27 // Project includes
28 #include "ProcessGDBRemoteLog.h"
29 
30 #define DEBUGSERVER_BASENAME    "debugserver"
31 
32 using namespace lldb;
33 using namespace lldb_private;
34 
35 GDBRemoteCommunication::History::History (uint32_t size) :
36     m_packets(),
37     m_curr_idx (0),
38     m_total_packet_count (0),
39     m_dumped_to_log (false)
40 {
41     m_packets.resize(size);
42 }
43 
44 GDBRemoteCommunication::History::~History ()
45 {
46 }
47 
48 void
49 GDBRemoteCommunication::History::AddPacket (char packet_char,
50                                             PacketType type,
51                                             uint32_t bytes_transmitted)
52 {
53     const size_t size = m_packets.size();
54     if (size > 0)
55     {
56         const uint32_t idx = GetNextIndex();
57         m_packets[idx].packet.assign (1, packet_char);
58         m_packets[idx].type = type;
59         m_packets[idx].bytes_transmitted = bytes_transmitted;
60         m_packets[idx].packet_idx = m_total_packet_count;
61         m_packets[idx].tid = Host::GetCurrentThreadID();
62     }
63 }
64 
65 void
66 GDBRemoteCommunication::History::AddPacket (const std::string &src,
67                                             uint32_t src_len,
68                                             PacketType type,
69                                             uint32_t bytes_transmitted)
70 {
71     const size_t size = m_packets.size();
72     if (size > 0)
73     {
74         const uint32_t idx = GetNextIndex();
75         m_packets[idx].packet.assign (src, 0, src_len);
76         m_packets[idx].type = type;
77         m_packets[idx].bytes_transmitted = bytes_transmitted;
78         m_packets[idx].packet_idx = m_total_packet_count;
79         m_packets[idx].tid = Host::GetCurrentThreadID();
80     }
81 }
82 
83 void
84 GDBRemoteCommunication::History::Dump (lldb_private::Stream &strm) const
85 {
86     const uint32_t size = GetNumPacketsInHistory ();
87     const uint32_t first_idx = GetFirstSavedPacketIndex ();
88     const uint32_t stop_idx = m_curr_idx + size;
89     for (uint32_t i = first_idx;  i < stop_idx; ++i)
90     {
91         const uint32_t idx = NormalizeIndex (i);
92         const Entry &entry = m_packets[idx];
93         if (entry.type == ePacketTypeInvalid || entry.packet.empty())
94             break;
95         strm.Printf ("history[%u] tid=0x%4.4llx <%4u> %s packet: %s\n",
96                      entry.packet_idx,
97                      entry.tid,
98                      entry.bytes_transmitted,
99                      (entry.type == ePacketTypeSend) ? "send" : "read",
100                      entry.packet.c_str());
101     }
102 }
103 
104 void
105 GDBRemoteCommunication::History::Dump (lldb_private::Log *log) const
106 {
107     if (log && !m_dumped_to_log)
108     {
109         m_dumped_to_log = true;
110         const uint32_t size = GetNumPacketsInHistory ();
111         const uint32_t first_idx = GetFirstSavedPacketIndex ();
112         const uint32_t stop_idx = m_curr_idx + size;
113         for (uint32_t i = first_idx;  i < stop_idx; ++i)
114         {
115             const uint32_t idx = NormalizeIndex (i);
116             const Entry &entry = m_packets[idx];
117             if (entry.type == ePacketTypeInvalid || entry.packet.empty())
118                 break;
119             log->Printf ("history[%u] tid=0x%4.4llx <%4u> %s packet: %s",
120                          entry.packet_idx,
121                          entry.tid,
122                          entry.bytes_transmitted,
123                          (entry.type == ePacketTypeSend) ? "send" : "read",
124                          entry.packet.c_str());
125         }
126     }
127 }
128 
129 //----------------------------------------------------------------------
130 // GDBRemoteCommunication constructor
131 //----------------------------------------------------------------------
132 GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
133                                                const char *listener_name,
134                                                bool is_platform) :
135     Communication(comm_name),
136     m_packet_timeout (1),
137     m_sequence_mutex (Mutex::eMutexTypeRecursive),
138     m_public_is_running (false),
139     m_private_is_running (false),
140     m_history (512),
141     m_send_acks (true),
142     m_is_platform (is_platform)
143 {
144 }
145 
146 //----------------------------------------------------------------------
147 // Destructor
148 //----------------------------------------------------------------------
149 GDBRemoteCommunication::~GDBRemoteCommunication()
150 {
151     if (IsConnected())
152     {
153         Disconnect();
154     }
155 }
156 
157 char
158 GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length)
159 {
160     int checksum = 0;
161 
162     // We only need to compute the checksum if we are sending acks
163     if (GetSendAcks ())
164     {
165         for (size_t i = 0; i < payload_length; ++i)
166             checksum += payload[i];
167     }
168     return checksum & 255;
169 }
170 
171 size_t
172 GDBRemoteCommunication::SendAck ()
173 {
174     LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
175     ConnectionStatus status = eConnectionStatusSuccess;
176     char ch = '+';
177     const size_t bytes_written = Write (&ch, 1, status, NULL);
178     if (log)
179         log->Printf ("<%4zu> send packet: %c", bytes_written, ch);
180     m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
181     return bytes_written;
182 }
183 
184 size_t
185 GDBRemoteCommunication::SendNack ()
186 {
187     LogSP 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 ("<%4zu> send packet: %c", bytes_written, ch);
193     m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
194     return bytes_written;
195 }
196 
197 size_t
198 GDBRemoteCommunication::SendPacket (const char *payload, size_t payload_length)
199 {
200     Mutex::Locker locker(m_sequence_mutex);
201     return SendPacketNoLock (payload, payload_length);
202 }
203 
204 size_t
205 GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length)
206 {
207     if (IsConnected())
208     {
209         StreamString packet(0, 4, eByteOrderBig);
210 
211         packet.PutChar('$');
212         packet.Write (payload, payload_length);
213         packet.PutChar('#');
214         packet.PutHex8(CalculcateChecksum (payload, payload_length));
215 
216         LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
217         ConnectionStatus status = eConnectionStatusSuccess;
218         size_t bytes_written = Write (packet.GetData(), packet.GetSize(), status, NULL);
219         if (log)
220         {
221             // If logging was just enabled and we have history, then dump out what
222             // we have to the log so we get the historical context. The Dump() call that
223             // logs all of the packet will set a boolean so that we don't dump this more
224             // than once
225             if (!m_history.DidDumpToLog ())
226                 m_history.Dump (log.get());
227 
228             log->Printf ("<%4zu> send packet: %.*s", bytes_written, (int)packet.GetSize(), packet.GetData());
229         }
230 
231         m_history.AddPacket (packet.GetString(), packet.GetSize(), History::ePacketTypeSend, bytes_written);
232 
233 
234         if (bytes_written == packet.GetSize())
235         {
236             if (GetSendAcks ())
237             {
238                 if (GetAck () != '+')
239                 {
240                     printf("get ack failed...");
241                     return 0;
242                 }
243             }
244         }
245         else
246         {
247             if (log)
248                 log->Printf ("error: failed to send packet: %.*s", (int)packet.GetSize(), packet.GetData());
249         }
250         return bytes_written;
251     }
252     return 0;
253 }
254 
255 char
256 GDBRemoteCommunication::GetAck ()
257 {
258     StringExtractorGDBRemote packet;
259     if (WaitForPacketWithTimeoutMicroSecondsNoLock (packet, GetPacketTimeoutInMicroSeconds ()) == 1)
260         return packet.GetChar();
261     return 0;
262 }
263 
264 bool
265 GDBRemoteCommunication::GetSequenceMutex (Mutex::Locker& locker)
266 {
267     return locker.TryLock (m_sequence_mutex.GetMutex());
268 }
269 
270 
271 bool
272 GDBRemoteCommunication::WaitForNotRunningPrivate (const TimeValue *timeout_ptr)
273 {
274     return m_private_is_running.WaitForValueEqualTo (false, timeout_ptr, NULL);
275 }
276 
277 size_t
278 GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSecondsNoLock (StringExtractorGDBRemote &packet, uint32_t timeout_usec)
279 {
280     uint8_t buffer[8192];
281     Error error;
282 
283     LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS | GDBR_LOG_VERBOSE));
284 
285     // Check for a packet from our cache first without trying any reading...
286     if (CheckForPacket (NULL, 0, packet))
287         return packet.GetStringRef().size();
288 
289     bool timed_out = false;
290     while (IsConnected() && !timed_out)
291     {
292         lldb::ConnectionStatus status = eConnectionStatusNoConnection;
293         size_t bytes_read = Read (buffer, sizeof(buffer), timeout_usec, status, &error);
294 
295         if (log)
296             log->Printf ("%s: Read (buffer, (sizeof(buffer), timeout_usec = 0x%x, status = %s, error = %s) => bytes_read = %zu",
297                          __PRETTY_FUNCTION__,
298                          timeout_usec,
299                          Communication::ConnectionStatusAsCString (status),
300                          error.AsCString(),
301                          bytes_read);
302 
303         if (bytes_read > 0)
304         {
305             if (CheckForPacket (buffer, bytes_read, packet))
306                 return packet.GetStringRef().size();
307         }
308         else
309         {
310             switch (status)
311             {
312             case eConnectionStatusTimedOut:
313                 timed_out = true;
314                 break;
315             case eConnectionStatusSuccess:
316                 //printf ("status = success but error = %s\n", error.AsCString("<invalid>"));
317                 break;
318 
319             case eConnectionStatusEndOfFile:
320             case eConnectionStatusNoConnection:
321             case eConnectionStatusLostConnection:
322             case eConnectionStatusError:
323                 Disconnect();
324                 break;
325             }
326         }
327     }
328     packet.Clear ();
329     return 0;
330 }
331 
332 bool
333 GDBRemoteCommunication::CheckForPacket (const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
334 {
335     // Put the packet data into the buffer in a thread safe fashion
336     Mutex::Locker locker(m_bytes_mutex);
337 
338     LogSP log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
339 
340     if (src && src_len > 0)
341     {
342         if (log && log->GetVerbose())
343         {
344             StreamString s;
345             log->Printf ("GDBRemoteCommunication::%s adding %u bytes: %.*s",
346                          __FUNCTION__,
347                          (uint32_t)src_len,
348                          (uint32_t)src_len,
349                          src);
350         }
351         m_bytes.append ((const char *)src, src_len);
352     }
353 
354     // Parse up the packets into gdb remote packets
355     if (!m_bytes.empty())
356     {
357         // end_idx must be one past the last valid packet byte. Start
358         // it off with an invalid value that is the same as the current
359         // index.
360         size_t content_start = 0;
361         size_t content_length = 0;
362         size_t total_length = 0;
363         size_t checksum_idx = std::string::npos;
364 
365         switch (m_bytes[0])
366         {
367             case '+':       // Look for ack
368             case '-':       // Look for cancel
369             case '\x03':    // ^C to halt target
370                 content_length = total_length = 1;  // The command is one byte long...
371                 break;
372 
373             case '$':
374                 // Look for a standard gdb packet?
375                 {
376                     size_t hash_pos = m_bytes.find('#');
377                     if (hash_pos != std::string::npos)
378                     {
379                         if (hash_pos + 2 < m_bytes.size())
380                         {
381                             checksum_idx = hash_pos + 1;
382                             // Skip the dollar sign
383                             content_start = 1;
384                             // Don't include the # in the content or the $ in the content length
385                             content_length = hash_pos - 1;
386 
387                             total_length = hash_pos + 3; // Skip the # and the two hex checksum bytes
388                         }
389                         else
390                         {
391                             // Checksum bytes aren't all here yet
392                             content_length = std::string::npos;
393                         }
394                     }
395                 }
396                 break;
397 
398             default:
399                 {
400                     // We have an unexpected byte and we need to flush all bad
401                     // data that is in m_bytes, so we need to find the first
402                     // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt),
403                     // or '$' character (start of packet header) or of course,
404                     // the end of the data in m_bytes...
405                     const size_t bytes_len = m_bytes.size();
406                     bool done = false;
407                     uint32_t idx;
408                     for (idx = 1; !done && idx < bytes_len; ++idx)
409                     {
410                         switch (m_bytes[idx])
411                         {
412                         case '+':
413                         case '-':
414                         case '\x03':
415                         case '$':
416                             done = true;
417                             break;
418 
419                         default:
420                             break;
421                         }
422                     }
423                     if (log)
424                         log->Printf ("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
425                                      __FUNCTION__, idx, idx, m_bytes.c_str());
426                     m_bytes.erase(0, idx);
427                 }
428                 break;
429         }
430 
431         if (content_length == std::string::npos)
432         {
433             packet.Clear();
434             return false;
435         }
436         else if (total_length > 0)
437         {
438 
439             // We have a valid packet...
440             assert (content_length <= m_bytes.size());
441             assert (total_length <= m_bytes.size());
442             assert (content_length <= total_length);
443 
444             bool success = true;
445             std::string &packet_str = packet.GetStringRef();
446 
447 
448             if (log)
449             {
450                 // If logging was just enabled and we have history, then dump out what
451                 // we have to the log so we get the historical context. The Dump() call that
452                 // logs all of the packet will set a boolean so that we don't dump this more
453                 // than once
454                 if (!m_history.DidDumpToLog ())
455                     m_history.Dump (log.get());
456 
457                 log->Printf ("<%4zu> read packet: %.*s", total_length, (int)(total_length), m_bytes.c_str());
458             }
459 
460             m_history.AddPacket (m_bytes.c_str(), total_length, History::ePacketTypeRecv, total_length);
461 
462             packet_str.assign (m_bytes, content_start, content_length);
463 
464             if (m_bytes[0] == '$')
465             {
466                 assert (checksum_idx < m_bytes.size());
467                 if (::isxdigit (m_bytes[checksum_idx+0]) ||
468                     ::isxdigit (m_bytes[checksum_idx+1]))
469                 {
470                     if (GetSendAcks ())
471                     {
472                         const char *packet_checksum_cstr = &m_bytes[checksum_idx];
473                         char packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
474                         char actual_checksum = CalculcateChecksum (packet_str.c_str(), packet_str.size());
475                         success = packet_checksum == actual_checksum;
476                         if (!success)
477                         {
478                             if (log)
479                                 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
480                                              (int)(total_length),
481                                              m_bytes.c_str(),
482                                              (uint8_t)packet_checksum,
483                                              (uint8_t)actual_checksum);
484                         }
485                         // Send the ack or nack if needed
486                         if (!success)
487                             SendNack();
488                         else
489                             SendAck();
490                     }
491                 }
492                 else
493                 {
494                     success = false;
495                     if (log)
496                         log->Printf ("error: invalid checksum in packet: '%s'\n", m_bytes.c_str());
497                 }
498             }
499 
500             m_bytes.erase(0, total_length);
501             packet.SetFilePos(0);
502             return success;
503         }
504     }
505     packet.Clear();
506     return false;
507 }
508 
509 Error
510 GDBRemoteCommunication::StartDebugserverProcess (const char *debugserver_url,
511                                                  const char *unix_socket_name,  // For handshaking
512                                                  lldb_private::ProcessLaunchInfo &launch_info)
513 {
514     Error error;
515     // If we locate debugserver, keep that located version around
516     static FileSpec g_debugserver_file_spec;
517 
518     // This function will fill in the launch information for the debugserver
519     // instance that gets launched.
520     launch_info.Clear();
521 
522     char debugserver_path[PATH_MAX];
523     FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
524 
525     // Always check to see if we have an environment override for the path
526     // to the debugserver to use and use it if we do.
527     const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
528     if (env_debugserver_path)
529         debugserver_file_spec.SetFile (env_debugserver_path, false);
530     else
531         debugserver_file_spec = g_debugserver_file_spec;
532     bool debugserver_exists = debugserver_file_spec.Exists();
533     if (!debugserver_exists)
534     {
535         // The debugserver binary is in the LLDB.framework/Resources
536         // directory.
537         if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
538         {
539             debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
540             debugserver_exists = debugserver_file_spec.Exists();
541             if (debugserver_exists)
542             {
543                 g_debugserver_file_spec = debugserver_file_spec;
544             }
545             else
546             {
547                 g_debugserver_file_spec.Clear();
548                 debugserver_file_spec.Clear();
549             }
550         }
551     }
552 
553     if (debugserver_exists)
554     {
555         debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
556 
557         Args &debugserver_args = launch_info.GetArguments();
558         debugserver_args.Clear();
559         char arg_cstr[PATH_MAX];
560 
561         // Start args with "debugserver /file/path -r --"
562         debugserver_args.AppendArgument(debugserver_path);
563         debugserver_args.AppendArgument(debugserver_url);
564         // use native registers, not the GDB registers
565         debugserver_args.AppendArgument("--native-regs");
566         // make debugserver run in its own session so signals generated by
567         // special terminal key sequences (^C) don't affect debugserver
568         debugserver_args.AppendArgument("--setsid");
569 
570         if (unix_socket_name && unix_socket_name[0])
571         {
572             debugserver_args.AppendArgument("--unix-socket");
573             debugserver_args.AppendArgument(unix_socket_name);
574         }
575 
576         const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
577         if (env_debugserver_log_file)
578         {
579             ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
580             debugserver_args.AppendArgument(arg_cstr);
581         }
582 
583         const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
584         if (env_debugserver_log_flags)
585         {
586             ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
587             debugserver_args.AppendArgument(arg_cstr);
588         }
589         //            debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
590         //            debugserver_args.AppendArgument("--log-flags=0x802e0e");
591 
592         // We currently send down all arguments, attach pids, or attach
593         // process names in dedicated GDB server packets, so we don't need
594         // to pass them as arguments. This is currently because of all the
595         // things we need to setup prior to launching: the environment,
596         // current working dir, file actions, etc.
597 #if 0
598         // Now append the program arguments
599         if (inferior_argv)
600         {
601             // Terminate the debugserver args so we can now append the inferior args
602             debugserver_args.AppendArgument("--");
603 
604             for (int i = 0; inferior_argv[i] != NULL; ++i)
605                 debugserver_args.AppendArgument (inferior_argv[i]);
606         }
607         else if (attach_pid != LLDB_INVALID_PROCESS_ID)
608         {
609             ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
610             debugserver_args.AppendArgument (arg_cstr);
611         }
612         else if (attach_name && attach_name[0])
613         {
614             if (wait_for_launch)
615                 debugserver_args.AppendArgument ("--waitfor");
616             else
617                 debugserver_args.AppendArgument ("--attach");
618             debugserver_args.AppendArgument (attach_name);
619         }
620 #endif
621 
622         // Close STDIN, STDOUT and STDERR. We might need to redirect them
623         // to "/dev/null" if we run into any problems.
624 //        launch_info.AppendCloseFileAction (STDIN_FILENO);
625 //        launch_info.AppendCloseFileAction (STDOUT_FILENO);
626 //        launch_info.AppendCloseFileAction (STDERR_FILENO);
627 
628         error = Host::LaunchProcess(launch_info);
629     }
630     else
631     {
632         error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME );
633     }
634     return error;
635 }
636 
637 void
638 GDBRemoteCommunication::DumpHistory(Stream &strm)
639 {
640     m_history.Dump (strm);
641 }
642