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 // C++ Includes
15 // Other libraries and framework includes
16 #include "lldb/Core/Args.h"
17 #include "lldb/Core/ConnectionFileDescriptor.h"
18 #include "lldb/Core/Log.h"
19 #include "lldb/Core/State.h"
20 #include "lldb/Core/StreamString.h"
21 #include "lldb/Host/TimeValue.h"
22 
23 // Project includes
24 #include "StringExtractorGDBRemote.h"
25 #include "ProcessGDBRemote.h"
26 #include "ProcessGDBRemoteLog.h"
27 
28 using namespace lldb;
29 using namespace lldb_private;
30 
31 //----------------------------------------------------------------------
32 // GDBRemoteCommunication constructor
33 //----------------------------------------------------------------------
34 GDBRemoteCommunication::GDBRemoteCommunication() :
35     Communication("gdb-remote.packets"),
36     m_send_acks (true),
37     m_rx_packet_listener ("gdbremote.rx_packet"),
38     m_sequence_mutex (Mutex::eMutexTypeRecursive),
39     m_is_running (false),
40     m_async_mutex (Mutex::eMutexTypeRecursive),
41     m_async_packet_predicate (false),
42     m_async_packet (),
43     m_async_response (),
44     m_async_timeout (UINT32_MAX),
45     m_async_signal (-1),
46     m_arch(),
47     m_os(),
48     m_vendor(),
49     m_byte_order(eByteOrderHost),
50     m_pointer_byte_size(0)
51 {
52     m_rx_packet_listener.StartListeningForEvents(this,
53                                                  Communication::eBroadcastBitPacketAvailable  |
54                                                  Communication::eBroadcastBitReadThreadDidExit);
55 }
56 
57 //----------------------------------------------------------------------
58 // Destructor
59 //----------------------------------------------------------------------
60 GDBRemoteCommunication::~GDBRemoteCommunication()
61 {
62     m_rx_packet_listener.StopListeningForEvents(this,
63                                                 Communication::eBroadcastBitPacketAvailable  |
64                                                 Communication::eBroadcastBitReadThreadDidExit);
65     if (IsConnected())
66     {
67         StopReadThread();
68         Disconnect();
69     }
70 }
71 
72 
73 char
74 GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length)
75 {
76     int checksum = 0;
77 
78     // We only need to compute the checksum if we are sending acks
79     if (m_send_acks)
80     {
81         for (int i = 0; i < payload_length; ++i)
82             checksum += payload[i];
83     }
84     return checksum & 255;
85 }
86 
87 size_t
88 GDBRemoteCommunication::SendAck (char ack_char)
89 {
90     Mutex::Locker locker(m_sequence_mutex);
91     ProcessGDBRemoteLog::LogIf (GDBR_LOG_PACKETS, "send packet: %c", ack_char);
92     ConnectionStatus status = eConnectionStatusSuccess;
93     return Write (&ack_char, 1, status, NULL) == 1;
94 }
95 
96 size_t
97 GDBRemoteCommunication::SendPacketAndWaitForResponse
98 (
99     const char *payload,
100     StringExtractorGDBRemote &response,
101     uint32_t timeout_seconds,
102     bool send_async
103 )
104 {
105     return SendPacketAndWaitForResponse (payload,
106                                          ::strlen (payload),
107                                          response,
108                                          timeout_seconds,
109                                          send_async);
110 }
111 
112 size_t
113 GDBRemoteCommunication::SendPacketAndWaitForResponse
114 (
115     const char *payload,
116     size_t payload_length,
117     StringExtractorGDBRemote &response,
118     uint32_t timeout_seconds,
119     bool send_async
120 )
121 {
122     Mutex::Locker locker;
123     TimeValue timeout_time;
124     timeout_time = TimeValue::Now();
125     timeout_time.OffsetWithSeconds (timeout_seconds);
126 
127     if (locker.TryLock (m_sequence_mutex.GetMutex()))
128     {
129         if (SendPacketNoLock (payload, strlen(payload)))
130             return WaitForPacketNoLock (response, &timeout_time);
131     }
132     else
133     {
134         if (send_async)
135         {
136             Mutex::Locker async_locker (m_async_mutex);
137             m_async_packet.assign(payload, payload_length);
138             m_async_timeout = timeout_seconds;
139             m_async_packet_predicate.SetValue (true, eBroadcastNever);
140 
141             bool timed_out = false;
142             if (SendInterrupt(1, &timed_out))
143             {
144                 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
145                 {
146                     response = m_async_response;
147                     return response.GetStringRef().size();
148                 }
149             }
150 //            if (timed_out)
151 //                m_error.SetErrorString("Timeout.");
152 //            else
153 //                m_error.SetErrorString("Unknown error.");
154         }
155         else
156         {
157 //            m_error.SetErrorString("Sequence mutex is locked.");
158         }
159     }
160     return 0;
161 }
162 
163 //template<typename _Tp>
164 //class ScopedValueChanger
165 //{
166 //public:
167 //    // Take a value reference and the value to assing it to when this class
168 //    // instance goes out of scope.
169 //    ScopedValueChanger (_Tp &value_ref, _Tp value) :
170 //        m_value_ref (value_ref),
171 //        m_value (value)
172 //    {
173 //    }
174 //
175 //    // This object is going out of scope, change the value pointed to by
176 //    // m_value_ref to the value we got during construction which was stored in
177 //    // m_value;
178 //    ~ScopedValueChanger ()
179 //    {
180 //        m_value_ref = m_value;
181 //    }
182 //protected:
183 //    _Tp &m_value_ref;   // A reference to the value we wil change when this object destructs
184 //    _Tp m_value;        // The value to assign to m_value_ref when this goes out of scope.
185 //};
186 
187 StateType
188 GDBRemoteCommunication::SendContinuePacketAndWaitForResponse
189 (
190     ProcessGDBRemote *process,
191     const char *payload,
192     size_t packet_length,
193     StringExtractorGDBRemote &response
194 )
195 {
196     Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS);
197     if (log)
198         log->Printf ("GDBRemoteCommunication::%s ()", __FUNCTION__);
199 
200     Mutex::Locker locker(m_sequence_mutex);
201     m_is_running.SetValue (true, eBroadcastNever);
202 
203 //    ScopedValueChanger<bool> restore_running_to_false (m_is_running, false);
204     StateType state = eStateRunning;
205 
206     if (SendPacket(payload, packet_length) == 0)
207         state = eStateInvalid;
208 
209     while (state == eStateRunning)
210     {
211         if (log)
212             log->Printf ("GDBRemoteCommunication::%s () WaitForPacket(...)", __FUNCTION__);
213 
214         if (WaitForPacket (response, (TimeValue*)NULL))
215         {
216             if (response.Empty())
217                 state = eStateInvalid;
218             else
219             {
220                 const char stop_type = response.GetChar();
221                 if (log)
222                     log->Printf ("GDBRemoteCommunication::%s () got '%c' packet", __FUNCTION__, stop_type);
223                 switch (stop_type)
224                 {
225                 case 'T':
226                 case 'S':
227                     if (m_async_signal != -1)
228                     {
229                         // Save off the async signal we are supposed to send
230                         const int async_signal = m_async_signal;
231                         // Clear the async signal member so we don't end up
232                         // sending the signal multiple times...
233                         m_async_signal = -1;
234                         // Check which signal we stopped with
235                         uint8_t signo = response.GetHexU8(255);
236                         if (signo == async_signal)
237                         {
238                             // We already stopped with a signal that we wanted
239                             // to stop with, so we are done
240                             response.SetFilePos (0);
241                         }
242                         else
243                         {
244                             // We stopped with a different signal that the one
245                             // we wanted to stop with, so now we must resume
246                             // with the signal we want
247                             char signal_packet[32];
248                             int signal_packet_len = 0;
249                             signal_packet_len = ::snprintf (signal_packet,
250                                                             sizeof (signal_packet),
251                                                             "C%2.2x",
252                                                             async_signal);
253 
254                             if (SendPacket(signal_packet, signal_packet_len) == 0)
255                             {
256                                 state = eStateInvalid;
257                                 break;
258                             }
259                             else
260                                 continue;
261                         }
262                     }
263                     else if (m_async_packet_predicate.GetValue())
264                     {
265                         // We are supposed to send an asynchronous packet while
266                         // we are running.
267                         m_async_response.Clear();
268                         if (!m_async_packet.empty())
269                         {
270                             SendPacketAndWaitForResponse (m_async_packet.data(),
271                                                           m_async_packet.size(),
272                                                           m_async_response,
273                                                           m_async_timeout,
274                                                           false);
275                         }
276                         // Let the other thread that was trying to send the async
277                         // packet know that the packet has been sent.
278                         m_async_packet_predicate.SetValue(false, eBroadcastAlways);
279 
280                         // Continue again
281                         if (SendPacket("c", 1) == 0)
282                         {
283                             state = eStateInvalid;
284                             break;
285                         }
286                         else
287                             continue;
288                     }
289                     // Stop with signal and thread info
290                     state = eStateStopped;
291                     break;
292 
293                 case 'W':
294                     // process exited
295                     state = eStateExited;
296                     break;
297 
298                 case 'O':
299                     // STDOUT
300                     {
301                         std::string inferior_stdout;
302                         inferior_stdout.reserve(response.GetBytesLeft () / 2);
303                         char ch;
304                         while ((ch = response.GetHexU8()) != '\0')
305                             inferior_stdout.append(1, ch);
306                         process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
307                     }
308                     break;
309 
310                 case 'E':
311                     // ERROR
312                     state = eStateInvalid;
313                     break;
314 
315                 default:
316                     if (log)
317                         log->Printf ("GDBRemoteCommunication::%s () got unrecognized async packet: '%s'", __FUNCTION__, stop_type);
318                     break;
319                 }
320             }
321         }
322         else
323         {
324             if (log)
325                 log->Printf ("GDBRemoteCommunication::%s () WaitForPacket(...) => false", __FUNCTION__);
326             state = eStateInvalid;
327         }
328     }
329     if (log)
330         log->Printf ("GDBRemoteCommunication::%s () => %s", __FUNCTION__, StateAsCString(state));
331     response.SetFilePos(0);
332     m_is_running.SetValue (false, eBroadcastOnChange);
333     return state;
334 }
335 
336 size_t
337 GDBRemoteCommunication::SendPacket (const char *payload)
338 {
339     Mutex::Locker locker(m_sequence_mutex);
340     return SendPacketNoLock (payload, ::strlen (payload));
341 }
342 
343 size_t
344 GDBRemoteCommunication::SendPacket (const char *payload, size_t payload_length)
345 {
346     Mutex::Locker locker(m_sequence_mutex);
347     return SendPacketNoLock (payload, payload_length);
348 }
349 
350 size_t
351 GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length)
352 {
353     if (IsConnected())
354     {
355         StreamString packet(0, 4, eByteOrderBig);
356 
357         packet.PutChar('$');
358         packet.Write (payload, payload_length);
359         packet.PutChar('#');
360         packet.PutHex8(CalculcateChecksum (payload, payload_length));
361 
362         ProcessGDBRemoteLog::LogIf (GDBR_LOG_PACKETS, "send packet: %s", packet.GetData());
363         ConnectionStatus status = eConnectionStatusSuccess;
364         size_t bytes_written = Write (packet.GetData(), packet.GetSize(), status, NULL);
365         if (bytes_written == packet.GetSize())
366         {
367             if (m_send_acks)
368                 GetAck (1) == '+';
369         }
370         return bytes_written;
371    }
372     //m_error.SetErrorString("Not connected.");
373     return 0;
374 }
375 
376 char
377 GDBRemoteCommunication::GetAck (uint32_t timeout_seconds)
378 {
379     StringExtractorGDBRemote response;
380     if (WaitForPacket (response, timeout_seconds) == 1)
381         return response.GetChar();
382     return 0;
383 }
384 
385 bool
386 GDBRemoteCommunication::GetSequenceMutex (Mutex::Locker& locker)
387 {
388     return locker.TryLock (m_sequence_mutex.GetMutex());
389 }
390 
391 bool
392 GDBRemoteCommunication::SendAsyncSignal (int signo)
393 {
394     m_async_signal = signo;
395     bool timed_out = false;
396     if (SendInterrupt(1, &timed_out))
397         return true;
398     m_async_signal = -1;
399     return false;
400 }
401 
402 bool
403 GDBRemoteCommunication::SendInterrupt (uint32_t seconds_to_wait_for_stop, bool *timed_out)
404 {
405     if (timed_out)
406         *timed_out = false;
407 
408     if (IsConnected() && IsRunning())
409     {
410         // Only send an interrupt if our debugserver is running...
411         if (m_sequence_mutex.TryLock() != 0)
412         {
413             // Someone has the mutex locked waiting for a response or for the
414             // inferior to stop, so send the interrupt on the down low...
415             char ctrl_c = '\x03';
416             ConnectionStatus status = eConnectionStatusSuccess;
417             TimeValue timeout;
418             if (seconds_to_wait_for_stop)
419             {
420                 timeout = TimeValue::Now();
421                 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
422             }
423             ProcessGDBRemoteLog::LogIf (GDBR_LOG_PACKETS, "send packet: \\x03");
424             if (Write (&ctrl_c, 1, status, NULL) > 0)
425             {
426                 if (seconds_to_wait_for_stop)
427                     m_is_running.WaitForValueEqualTo (false, &timeout, timed_out);
428                 return true;
429             }
430         }
431     }
432     return false;
433 }
434 
435 size_t
436 GDBRemoteCommunication::WaitForPacket (StringExtractorGDBRemote &response, uint32_t timeout_seconds)
437 {
438     TimeValue timeout_time;
439     timeout_time = TimeValue::Now();
440     timeout_time.OffsetWithSeconds (timeout_seconds);
441     return WaitForPacketNoLock (response, &timeout_time);
442 }
443 
444 size_t
445 GDBRemoteCommunication::WaitForPacket (StringExtractorGDBRemote &response, TimeValue* timeout_time_ptr)
446 {
447     Mutex::Locker locker(m_sequence_mutex);
448     return WaitForPacketNoLock (response, timeout_time_ptr);
449 }
450 
451 size_t
452 GDBRemoteCommunication::WaitForPacketNoLock (StringExtractorGDBRemote &response, TimeValue* timeout_time_ptr)
453 {
454     bool checksum_error = false;
455     response.Clear ();
456 
457     EventSP event_sp;
458 
459     if (m_rx_packet_listener.WaitForEvent (timeout_time_ptr, event_sp))
460     {
461         const uint32_t event_type = event_sp->GetType();
462         if (event_type | Communication::eBroadcastBitPacketAvailable)
463         {
464             const EventDataBytes *event_bytes = EventDataBytes::GetEventDataFromEvent(event_sp.get());
465             if (event_bytes)
466             {
467                 const char * packet_data =  (const char *)event_bytes->GetBytes();
468                 ProcessGDBRemoteLog::LogIf (GDBR_LOG_PACKETS, "read packet: %s", packet_data);
469                 const size_t packet_size =  event_bytes->GetByteSize();
470                 if (packet_data && packet_size > 0)
471                 {
472                     std::string &response_str = response.GetStringRef();
473                     if (packet_data[0] == '$')
474                     {
475                         assert (packet_size >= 4);  // Must have at least '$#CC' where CC is checksum
476                         assert (packet_data[packet_size-3] == '#');
477                         assert (::isxdigit (packet_data[packet_size-2]));  // Must be checksum hex byte
478                         assert (::isxdigit (packet_data[packet_size-1]));  // Must be checksum hex byte
479                         response_str.assign (packet_data + 1, packet_size - 4);
480                         if (m_send_acks)
481                         {
482                             char packet_checksum = strtol (&packet_data[packet_size-2], NULL, 16);
483                             char actual_checksum = CalculcateChecksum (response_str.data(), response_str.size());
484                             checksum_error = packet_checksum != actual_checksum;
485                             // Send the ack or nack if needed
486                             if (checksum_error)
487                                 SendAck('-');
488                             else
489                                 SendAck('+');
490                         }
491                     }
492                     else
493                     {
494                         response_str.assign (packet_data, packet_size);
495                     }
496                     return response_str.size();
497                 }
498             }
499         }
500         else if (Communication::eBroadcastBitReadThreadDidExit)
501         {
502             // Our read thread exited on us so just fall through and return zero...
503         }
504     }
505     return 0;
506 }
507 
508 void
509 GDBRemoteCommunication::AppendBytesToCache (const uint8_t *src, size_t src_len, bool broadcast)
510 {
511     // Put the packet data into the buffer in a thread safe fashion
512     Mutex::Locker locker(m_bytes_mutex);
513     m_bytes.append ((const char *)src, src_len);
514 
515     // Parse up the packets into gdb remote packets
516     while (!m_bytes.empty())
517     {
518         // end_idx must be one past the last valid packet byte. Start
519         // it off with an invalid value that is the same as the current
520         // index.
521         size_t end_idx = 0;
522 
523         switch (m_bytes[0])
524         {
525             case '+':       // Look for ack
526             case '-':       // Look for cancel
527             case '\x03':    // ^C to halt target
528                 end_idx = 1;  // The command is one byte long...
529                 break;
530 
531             case '$':
532                 // Look for a standard gdb packet?
533                 end_idx = m_bytes.find('#');
534                 if (end_idx != std::string::npos)
535                 {
536                     if (end_idx + 2 < m_bytes.size())
537                     {
538                         end_idx += 3;
539                     }
540                     else
541                     {
542                         // Checksum bytes aren't all here yet
543                         end_idx = std::string::npos;
544                     }
545                 }
546                 break;
547 
548             default:
549                 break;
550         }
551 
552         if (end_idx == std::string::npos)
553         {
554             //ProcessGDBRemoteLog::LogIf (GDBR_LOG_PACKETS | GDBR_LOG_VERBOSE, "GDBRemoteCommunication::%s packet not yet complete: '%s'",__FUNCTION__, m_bytes.c_str());
555             return;
556         }
557         else if (end_idx > 0)
558         {
559             // We have a valid packet...
560             assert (end_idx <= m_bytes.size());
561             std::auto_ptr<EventDataBytes> event_bytes_ap (new EventDataBytes (&m_bytes[0], end_idx));
562             ProcessGDBRemoteLog::LogIf (GDBR_LOG_COMM, "got full packet: %s", event_bytes_ap->GetBytes());
563             BroadcastEvent (eBroadcastBitPacketAvailable, event_bytes_ap.release());
564             m_bytes.erase(0, end_idx);
565         }
566         else
567         {
568             assert (1 <= m_bytes.size());
569             ProcessGDBRemoteLog::LogIf (GDBR_LOG_COMM, "GDBRemoteCommunication::%s tossing junk byte at %c",__FUNCTION__, m_bytes[0]);
570             m_bytes.erase(0, 1);
571         }
572     }
573 }
574 
575 lldb::pid_t
576 GDBRemoteCommunication::GetCurrentProcessID (uint32_t timeout_seconds)
577 {
578     StringExtractorGDBRemote response;
579     if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, timeout_seconds, false))
580     {
581         if (response.GetChar() == 'Q')
582             if (response.GetChar() == 'C')
583                 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
584     }
585     return LLDB_INVALID_PROCESS_ID;
586 }
587 
588 bool
589 GDBRemoteCommunication::GetLaunchSuccess (uint32_t timeout_seconds, std::string &error_str)
590 {
591     error_str.clear();
592     StringExtractorGDBRemote response;
593     if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, timeout_seconds, false))
594     {
595         if (response.IsOKPacket())
596             return true;
597         if (response.GetChar() == 'E')
598         {
599             // A string the describes what failed when launching...
600             error_str = response.GetStringRef().substr(1);
601         }
602         else
603         {
604             error_str.assign ("unknown error occurred launching process");
605         }
606     }
607     else
608     {
609         error_str.assign ("failed to send the qLaunchSuccess packet");
610     }
611     return false;
612 }
613 
614 int
615 GDBRemoteCommunication::SendArgumentsPacket (char const *argv[], uint32_t timeout_seconds)
616 {
617     if (argv && argv[0])
618     {
619         StreamString packet;
620         packet.PutChar('A');
621         const char *arg;
622         for (uint32_t i = 0; (arg = argv[i]) != NULL; ++i)
623         {
624             const int arg_len = strlen(arg);
625             if (i > 0)
626                 packet.PutChar(',');
627             packet.Printf("%i,%i,", arg_len * 2, i);
628             packet.PutBytesAsRawHex8(arg, arg_len, eByteOrderHost, eByteOrderHost);
629         }
630 
631         StringExtractorGDBRemote response;
632         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, timeout_seconds, false))
633         {
634             if (response.IsOKPacket())
635                 return 0;
636             uint8_t error = response.GetError();
637             if (error)
638                 return error;
639         }
640     }
641     return -1;
642 }
643 
644 int
645 GDBRemoteCommunication::SendEnvironmentPacket (char const *name_equal_value, uint32_t timeout_seconds)
646 {
647     if (name_equal_value && name_equal_value[0])
648     {
649         StreamString packet;
650         packet.Printf("QEnvironment:%s", name_equal_value);
651         StringExtractorGDBRemote response;
652         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, timeout_seconds, false))
653         {
654             if (response.IsOKPacket())
655                 return 0;
656             uint8_t error = response.GetError();
657             if (error)
658                 return error;
659         }
660     }
661     return -1;
662 }
663 
664 bool
665 GDBRemoteCommunication::GetHostInfo (uint32_t timeout_seconds)
666 {
667     m_arch.Clear();
668     m_os.Clear();
669     m_vendor.Clear();
670     m_byte_order = eByteOrderHost;
671     m_pointer_byte_size = 0;
672 
673     StringExtractorGDBRemote response;
674     if (SendPacketAndWaitForResponse ("qHostInfo", response, timeout_seconds, false))
675     {
676         if (response.IsUnsupportedPacket())
677             return false;
678 
679 
680         std::string name;
681         std::string value;
682         while (response.GetNameColonValue(name, value))
683         {
684             if (name.compare("cputype") == 0)
685             {
686                 // exception type in big endian hex
687                 m_arch.SetCPUType(Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0));
688             }
689             else if (name.compare("cpusubtype") == 0)
690             {
691                 // exception count in big endian hex
692                 m_arch.SetCPUSubtype(Args::StringToUInt32 (value.c_str(), 0, 0));
693             }
694             else if (name.compare("ostype") == 0)
695             {
696                 // exception data in big endian hex
697                 m_os.SetCString(value.c_str());
698             }
699             else if (name.compare("vendor") == 0)
700             {
701                 m_vendor.SetCString(value.c_str());
702             }
703             else if (name.compare("endian") == 0)
704             {
705                 if (value.compare("little") == 0)
706                     m_byte_order = eByteOrderLittle;
707                 else if (value.compare("big") == 0)
708                     m_byte_order = eByteOrderBig;
709                 else if (value.compare("pdp") == 0)
710                     m_byte_order = eByteOrderPDP;
711             }
712             else if (name.compare("ptrsize") == 0)
713             {
714                 m_pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
715             }
716         }
717     }
718     return HostInfoIsValid();
719 }
720 
721 int
722 GDBRemoteCommunication::SendAttach
723 (
724     lldb::pid_t pid,
725     uint32_t timeout_seconds,
726     StringExtractorGDBRemote& response
727 )
728 {
729     if (pid != LLDB_INVALID_PROCESS_ID)
730     {
731         StreamString packet;
732         packet.Printf("vAttach;%x", pid);
733 
734         if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, timeout_seconds, false))
735         {
736             if (response.IsErrorPacket())
737                 return response.GetError();
738             return 0;
739         }
740     }
741     return -1;
742 }
743 
744 const lldb_private::ArchSpec &
745 GDBRemoteCommunication::GetHostArchitecture ()
746 {
747     if (!HostInfoIsValid ())
748         GetHostInfo (1);
749     return m_arch;
750 }
751 
752 const lldb_private::ConstString &
753 GDBRemoteCommunication::GetOSString ()
754 {
755     if (!HostInfoIsValid ())
756         GetHostInfo (1);
757     return m_os;
758 }
759 
760 const lldb_private::ConstString &
761 GDBRemoteCommunication::GetVendorString()
762 {
763     if (!HostInfoIsValid ())
764         GetHostInfo (1);
765     return m_vendor;
766 }
767 
768 lldb::ByteOrder
769 GDBRemoteCommunication::GetByteOrder ()
770 {
771     if (!HostInfoIsValid ())
772         GetHostInfo (1);
773     return m_byte_order;
774 }
775 
776 uint32_t
777 GDBRemoteCommunication::GetAddressByteSize ()
778 {
779     if (!HostInfoIsValid ())
780         GetHostInfo (1);
781     return m_pointer_byte_size;
782 }
783 
784 addr_t
785 GDBRemoteCommunication::AllocateMemory (size_t size, uint32_t permissions, uint32_t timeout_seconds)
786 {
787     char packet[64];
788     ::snprintf (packet, sizeof(packet), "_M%zx,%s%s%s", size,
789                 permissions & lldb::ePermissionsReadable ? "r" : "",
790                 permissions & lldb::ePermissionsWritable ? "w" : "",
791                 permissions & lldb::ePermissionsExecutable ? "x" : "");
792     StringExtractorGDBRemote response;
793     if (SendPacketAndWaitForResponse (packet, response, timeout_seconds, false))
794     {
795         if (!response.IsErrorPacket())
796             return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
797     }
798     return LLDB_INVALID_ADDRESS;
799 }
800 
801 bool
802 GDBRemoteCommunication::DeallocateMemory (addr_t addr, uint32_t timeout_seconds)
803 {
804     char packet[64];
805     snprintf(packet, sizeof(packet), "_m%llx", (uint64_t)addr);
806     StringExtractorGDBRemote response;
807     if (SendPacketAndWaitForResponse (packet, response, timeout_seconds, false))
808     {
809         if (!response.IsOKPacket())
810             return true;
811     }
812     return false;
813 }
814