1 //===-- CommunicationKDP.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 "CommunicationKDP.h"
12 
13 // C Includes
14 #include <errno.h>
15 #include <limits.h>
16 #include <string.h>
17 
18 // C++ Includes
19 #include "llvm/Support/MachO.h"
20 
21 // Other libraries and framework includes
22 #include "lldb/Core/DataBufferHeap.h"
23 #include "lldb/Core/DataExtractor.h"
24 #include "lldb/Core/Log.h"
25 #include "lldb/Core/State.h"
26 #include "lldb/Core/UUID.h"
27 #include "lldb/Host/FileSpec.h"
28 #include "lldb/Host/Host.h"
29 #include "lldb/Host/TimeValue.h"
30 #include "lldb/Target/Process.h"
31 
32 // Project includes
33 #include "ProcessKDPLog.h"
34 
35 using namespace lldb;
36 using namespace lldb_private;
37 
38 //----------------------------------------------------------------------
39 // CommunicationKDP constructor
40 //----------------------------------------------------------------------
41 CommunicationKDP::CommunicationKDP (const char *comm_name) :
42     Communication(comm_name),
43     m_addr_byte_size (4),
44     m_byte_order (eByteOrderLittle),
45     m_packet_timeout (1),
46     m_sequence_mutex (Mutex::eMutexTypeRecursive),
47     m_is_running (false),
48     m_session_key (0u),
49     m_request_sequence_id (0u),
50     m_exception_sequence_id (0u),
51     m_kdp_version_version (0u),
52     m_kdp_version_feature (0u),
53     m_kdp_hostinfo_cpu_mask (0u),
54     m_kdp_hostinfo_cpu_type (0u),
55     m_kdp_hostinfo_cpu_subtype (0u)
56 {
57 }
58 
59 //----------------------------------------------------------------------
60 // Destructor
61 //----------------------------------------------------------------------
62 CommunicationKDP::~CommunicationKDP()
63 {
64     if (IsConnected())
65     {
66         Disconnect();
67     }
68 }
69 
70 bool
71 CommunicationKDP::SendRequestPacket (const PacketStreamType &request_packet)
72 {
73     Mutex::Locker locker(m_sequence_mutex);
74     return SendRequestPacketNoLock (request_packet);
75 }
76 
77 #if 0
78 typedef struct {
79 	uint8_t     request;	// Either: CommandType | ePacketTypeRequest, or CommandType | ePacketTypeReply
80 	uint8_t     sequence;
81 	uint16_t    length;		// Length of entire packet including this header
82 	uint32_t	key;		// Session key
83 } kdp_hdr_t;
84 #endif
85 
86 void
87 CommunicationKDP::MakeRequestPacketHeader (CommandType request_type,
88                                            PacketStreamType &request_packet,
89                                            uint16_t request_length)
90 {
91     request_packet.Clear();
92     request_packet.PutHex8 (request_type | ePacketTypeRequest); // Set the request type
93     request_packet.PutHex8 (m_request_sequence_id++);           // Sequence number
94     request_packet.PutHex16 (request_length);                   // Length of the packet including this header
95     request_packet.PutHex32 (m_session_key);                    // Session key
96 }
97 
98 bool
99 CommunicationKDP::SendRequestAndGetReply (const CommandType command,
100                                           const PacketStreamType &request_packet,
101                                           DataExtractor &reply_packet)
102 {
103     if (IsRunning())
104     {
105         Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PACKETS));
106         if (log)
107         {
108             PacketStreamType log_strm;
109             DumpPacket (log_strm, request_packet.GetData(), request_packet.GetSize());
110             log->Printf("error: kdp running, not sending packet: %.*s", (uint32_t)log_strm.GetSize(), log_strm.GetData());
111         }
112         return false;
113     }
114 
115     Mutex::Locker locker(m_sequence_mutex);
116 #ifdef LLDB_CONFIGURATION_DEBUG
117     // NOTE: this only works for packets that are in native endian byte order
118     assert (request_packet.GetSize() == *((uint16_t *)(request_packet.GetData() + 2)));
119 #endif
120     lldb::offset_t offset = 1;
121     const uint32_t num_retries = 3;
122     for (uint32_t i=0; i<num_retries; ++i)
123     {
124         if (SendRequestPacketNoLock(request_packet))
125         {
126             const uint8_t request_sequence_id = (uint8_t)request_packet.GetData()[1];
127             if (WaitForPacketWithTimeoutMicroSecondsNoLock (reply_packet, GetPacketTimeoutInMicroSeconds ()))
128             {
129                 offset = 0;
130                 const uint8_t reply_command = reply_packet.GetU8 (&offset);
131                 const uint8_t reply_sequence_id = reply_packet.GetU8 (&offset);
132                 if ((reply_command & eCommandTypeMask) == command)
133                 {
134                     if (request_sequence_id == reply_sequence_id)
135                     {
136                         if (command == KDP_RESUMECPUS)
137                             m_is_running.SetValue(true, eBroadcastAlways);
138                         return true;
139                     }
140                 }
141             }
142         }
143     }
144     reply_packet.Clear();
145     return false;
146 }
147 
148 bool
149 CommunicationKDP::SendRequestPacketNoLock (const PacketStreamType &request_packet)
150 {
151     if (IsConnected())
152     {
153         const char *packet_data = request_packet.GetData();
154         const size_t packet_size = request_packet.GetSize();
155 
156         Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PACKETS));
157         if (log)
158         {
159             PacketStreamType log_strm;
160             DumpPacket (log_strm, packet_data, packet_size);
161             log->Printf("%.*s", (uint32_t)log_strm.GetSize(), log_strm.GetData());
162         }
163         ConnectionStatus status = eConnectionStatusSuccess;
164 
165         size_t bytes_written = Write (packet_data,
166                                       packet_size,
167                                       status,
168                                       NULL);
169 
170         if (bytes_written == packet_size)
171             return true;
172 
173         if (log)
174             log->Printf ("error: failed to send packet entire packet %" PRIu64 " of %" PRIu64 " bytes sent", (uint64_t)bytes_written, (uint64_t)packet_size);
175     }
176     return false;
177 }
178 
179 bool
180 CommunicationKDP::GetSequenceMutex (Mutex::Locker& locker)
181 {
182     return locker.TryLock (m_sequence_mutex);
183 }
184 
185 
186 bool
187 CommunicationKDP::WaitForNotRunningPrivate (const TimeValue *timeout_ptr)
188 {
189     return m_is_running.WaitForValueEqualTo (false, timeout_ptr, NULL);
190 }
191 
192 size_t
193 CommunicationKDP::WaitForPacketWithTimeoutMicroSeconds (DataExtractor &packet, uint32_t timeout_usec)
194 {
195     Mutex::Locker locker(m_sequence_mutex);
196     return WaitForPacketWithTimeoutMicroSecondsNoLock (packet, timeout_usec);
197 }
198 
199 size_t
200 CommunicationKDP::WaitForPacketWithTimeoutMicroSecondsNoLock (DataExtractor &packet, uint32_t timeout_usec)
201 {
202     uint8_t buffer[8192];
203     Error error;
204 
205     Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PACKETS | KDP_LOG_VERBOSE));
206 
207     // Check for a packet from our cache first without trying any reading...
208     if (CheckForPacket (NULL, 0, packet))
209         return packet.GetByteSize();
210 
211     bool timed_out = false;
212     while (IsConnected() && !timed_out)
213     {
214         lldb::ConnectionStatus status = eConnectionStatusNoConnection;
215         size_t bytes_read = Read (buffer, sizeof(buffer), timeout_usec, status, &error);
216 
217         if (log)
218             log->Printf ("%s: Read (buffer, (sizeof(buffer), timeout_usec = 0x%x, status = %s, error = %s) => bytes_read = %" PRIu64,
219                          __PRETTY_FUNCTION__,
220                          timeout_usec,
221                          Communication::ConnectionStatusAsCString (status),
222                          error.AsCString(),
223                          (uint64_t)bytes_read);
224 
225         if (bytes_read > 0)
226         {
227             if (CheckForPacket (buffer, bytes_read, packet))
228                 return packet.GetByteSize();
229         }
230         else
231         {
232             switch (status)
233             {
234             case eConnectionStatusTimedOut:
235                 timed_out = true;
236                 break;
237             case eConnectionStatusSuccess:
238                 //printf ("status = success but error = %s\n", error.AsCString("<invalid>"));
239                 break;
240 
241             case eConnectionStatusEndOfFile:
242             case eConnectionStatusNoConnection:
243             case eConnectionStatusLostConnection:
244             case eConnectionStatusError:
245                 Disconnect();
246                 break;
247             }
248         }
249     }
250     packet.Clear ();
251     return 0;
252 }
253 
254 bool
255 CommunicationKDP::CheckForPacket (const uint8_t *src, size_t src_len, DataExtractor &packet)
256 {
257     // Put the packet data into the buffer in a thread safe fashion
258     Mutex::Locker locker(m_bytes_mutex);
259 
260     Log *log (ProcessKDPLog::GetLogIfAllCategoriesSet (KDP_LOG_PACKETS));
261 
262     if (src && src_len > 0)
263     {
264         if (log && log->GetVerbose())
265         {
266             PacketStreamType log_strm;
267             DataExtractor::DumpHexBytes (&log_strm, src, src_len, UINT32_MAX, LLDB_INVALID_ADDRESS);
268             log->Printf ("CommunicationKDP::%s adding %u bytes: %s",
269                          __FUNCTION__,
270                          (uint32_t)src_len,
271                          log_strm.GetData());
272         }
273         m_bytes.append ((const char *)src, src_len);
274     }
275 
276     // Make sure we at least have enough bytes for a packet header
277     const size_t bytes_available = m_bytes.size();
278     if (bytes_available >= 8)
279     {
280         packet.SetData (&m_bytes[0], bytes_available, m_byte_order);
281         lldb::offset_t offset = 0;
282         uint8_t reply_command = packet.GetU8(&offset);
283         switch (reply_command)
284         {
285         case ePacketTypeRequest | KDP_EXCEPTION:
286         case ePacketTypeRequest | KDP_TERMINATION:
287             // We got an exception request, so be sure to send an ACK
288             {
289                 PacketStreamType request_ack_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
290                 // Set the reply but and make the ACK packet
291                 request_ack_packet.PutHex8 (reply_command | ePacketTypeReply);
292                 request_ack_packet.PutHex8 (packet.GetU8(&offset));
293                 request_ack_packet.PutHex16 (packet.GetU16(&offset));
294                 request_ack_packet.PutHex32 (packet.GetU32(&offset));
295                 m_is_running.SetValue(false, eBroadcastAlways);
296                 // Ack to the exception or termination
297                 SendRequestPacketNoLock (request_ack_packet);
298             }
299             // Fall through to case below to get packet contents
300         case ePacketTypeReply | KDP_CONNECT:
301         case ePacketTypeReply | KDP_DISCONNECT:
302         case ePacketTypeReply | KDP_HOSTINFO:
303         case ePacketTypeReply | KDP_VERSION:
304         case ePacketTypeReply | KDP_MAXBYTES:
305         case ePacketTypeReply | KDP_READMEM:
306         case ePacketTypeReply | KDP_WRITEMEM:
307         case ePacketTypeReply | KDP_READREGS:
308         case ePacketTypeReply | KDP_WRITEREGS:
309         case ePacketTypeReply | KDP_LOAD:
310         case ePacketTypeReply | KDP_IMAGEPATH:
311         case ePacketTypeReply | KDP_SUSPEND:
312         case ePacketTypeReply | KDP_RESUMECPUS:
313         case ePacketTypeReply | KDP_BREAKPOINT_SET:
314         case ePacketTypeReply | KDP_BREAKPOINT_REMOVE:
315         case ePacketTypeReply | KDP_REGIONS:
316         case ePacketTypeReply | KDP_REATTACH:
317         case ePacketTypeReply | KDP_HOSTREBOOT:
318         case ePacketTypeReply | KDP_READMEM64:
319         case ePacketTypeReply | KDP_WRITEMEM64:
320         case ePacketTypeReply | KDP_BREAKPOINT_SET64:
321         case ePacketTypeReply | KDP_BREAKPOINT_REMOVE64:
322         case ePacketTypeReply | KDP_KERNELVERSION:
323         case ePacketTypeReply | KDP_READPHYSMEM64:
324         case ePacketTypeReply | KDP_WRITEPHYSMEM64:
325         case ePacketTypeReply | KDP_READIOPORT:
326         case ePacketTypeReply | KDP_WRITEIOPORT:
327         case ePacketTypeReply | KDP_READMSR64:
328         case ePacketTypeReply | KDP_WRITEMSR64:
329         case ePacketTypeReply | KDP_DUMPINFO:
330             {
331                 offset = 2;
332                 const uint16_t length = packet.GetU16 (&offset);
333                 if (length <= bytes_available)
334                 {
335                     // We have an entire packet ready, we need to copy the data
336                     // bytes into a buffer that will be owned by the packet and
337                     // erase the bytes from our communcation buffer "m_bytes"
338                     packet.SetData (DataBufferSP (new DataBufferHeap (&m_bytes[0], length)));
339                     m_bytes.erase (0, length);
340 
341                     if (log)
342                     {
343                         PacketStreamType log_strm;
344                         DumpPacket (log_strm, packet);
345 
346                         log->Printf("%.*s", (uint32_t)log_strm.GetSize(), log_strm.GetData());
347                     }
348                     return true;
349                 }
350             }
351             break;
352 
353         default:
354             // Unrecognized reply command byte, erase this byte and try to get back on track
355             if (log)
356                 log->Printf ("CommunicationKDP::%s: tossing junk byte: 0x%2.2x",
357                              __FUNCTION__,
358                              (uint8_t)m_bytes[0]);
359             m_bytes.erase(0, 1);
360             break;
361         }
362     }
363     packet.Clear();
364     return false;
365 }
366 
367 
368 bool
369 CommunicationKDP::SendRequestConnect (uint16_t reply_port,
370                                       uint16_t exc_port,
371                                       const char *greeting)
372 {
373     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
374     if (greeting == NULL)
375         greeting = "";
376 
377     const CommandType command = KDP_CONNECT;
378     // Length is 82 uint16_t and the length of the greeting C string with the terminating NULL
379     const uint32_t command_length = 8 + 2 + 2 + ::strlen(greeting) + 1;
380     MakeRequestPacketHeader (command, request_packet, command_length);
381     // Always send connect ports as little endian
382     request_packet.SetByteOrder (eByteOrderLittle);
383     request_packet.PutHex16 (reply_port);
384     request_packet.PutHex16 (exc_port);
385     request_packet.SetByteOrder (m_byte_order);
386     request_packet.PutCString (greeting);
387     DataExtractor reply_packet;
388     return SendRequestAndGetReply (command, request_packet, reply_packet);
389 }
390 
391 void
392 CommunicationKDP::ClearKDPSettings ()
393 {
394     m_request_sequence_id = 0;
395     m_kdp_version_version = 0;
396     m_kdp_version_feature = 0;
397     m_kdp_hostinfo_cpu_mask = 0;
398     m_kdp_hostinfo_cpu_type = 0;
399     m_kdp_hostinfo_cpu_subtype = 0;
400 }
401 
402 bool
403 CommunicationKDP::SendRequestReattach (uint16_t reply_port)
404 {
405     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
406     const CommandType command = KDP_REATTACH;
407     // Length is 8 bytes for the header plus 2 bytes for the reply UDP port
408     const uint32_t command_length = 8 + 2;
409     MakeRequestPacketHeader (command, request_packet, command_length);
410     // Always send connect ports as little endian
411     request_packet.SetByteOrder (eByteOrderLittle);
412     request_packet.PutHex16(reply_port);
413     request_packet.SetByteOrder (m_byte_order);
414     DataExtractor reply_packet;
415     if (SendRequestAndGetReply (command, request_packet, reply_packet))
416     {
417         // Reset the sequence ID to zero for reattach
418         ClearKDPSettings ();
419         lldb::offset_t offset = 4;
420         m_session_key = reply_packet.GetU32 (&offset);
421         return true;
422     }
423     return false;
424 }
425 
426 uint32_t
427 CommunicationKDP::GetVersion ()
428 {
429     if (!VersionIsValid())
430         SendRequestVersion();
431     return m_kdp_version_version;
432 }
433 
434 uint32_t
435 CommunicationKDP::GetFeatureFlags ()
436 {
437     if (!VersionIsValid())
438         SendRequestVersion();
439     return m_kdp_version_feature;
440 }
441 
442 bool
443 CommunicationKDP::SendRequestVersion ()
444 {
445     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
446     const CommandType command = KDP_VERSION;
447     const uint32_t command_length = 8;
448     MakeRequestPacketHeader (command, request_packet, command_length);
449     DataExtractor reply_packet;
450     if (SendRequestAndGetReply (command, request_packet, reply_packet))
451     {
452         lldb::offset_t offset = 8;
453         m_kdp_version_version = reply_packet.GetU32 (&offset);
454         m_kdp_version_feature = reply_packet.GetU32 (&offset);
455         return true;
456     }
457     return false;
458 }
459 
460 #if 0 // Disable KDP_IMAGEPATH for now, it seems to hang the KDP connection...
461 const char *
462 CommunicationKDP::GetImagePath ()
463 {
464     if (m_image_path.empty())
465         SendRequestImagePath();
466     return m_image_path.c_str();
467 }
468 
469 bool
470 CommunicationKDP::SendRequestImagePath ()
471 {
472     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
473     const CommandType command = KDP_IMAGEPATH;
474     const uint32_t command_length = 8;
475     MakeRequestPacketHeader (command, request_packet, command_length);
476     DataExtractor reply_packet;
477     if (SendRequestAndGetReply (command, request_packet, reply_packet))
478     {
479         const char *path = reply_packet.PeekCStr(8);
480         if (path && path[0])
481             m_kernel_version.assign (path);
482         return true;
483     }
484     return false;
485 }
486 #endif
487 
488 uint32_t
489 CommunicationKDP::GetCPUMask ()
490 {
491     if (!HostInfoIsValid())
492         SendRequestHostInfo();
493     return m_kdp_hostinfo_cpu_mask;
494 }
495 
496 uint32_t
497 CommunicationKDP::GetCPUType ()
498 {
499     if (!HostInfoIsValid())
500         SendRequestHostInfo();
501     return m_kdp_hostinfo_cpu_type;
502 }
503 
504 uint32_t
505 CommunicationKDP::GetCPUSubtype ()
506 {
507     if (!HostInfoIsValid())
508         SendRequestHostInfo();
509     return m_kdp_hostinfo_cpu_subtype;
510 }
511 
512 lldb_private::UUID
513 CommunicationKDP::GetUUID ()
514 {
515     UUID uuid;
516     if (GetKernelVersion() == NULL)
517         return uuid;
518 
519     if (m_kernel_version.find("UUID=") == std::string::npos)
520         return uuid;
521 
522     size_t p = m_kernel_version.find("UUID=") + strlen ("UUID=");
523     std::string uuid_str = m_kernel_version.substr(p, 36);
524     if (uuid_str.size() < 32)
525         return uuid;
526 
527     if (uuid.SetFromCString (uuid_str.c_str()) == 0)
528     {
529         UUID invalid_uuid;
530         return invalid_uuid;
531     }
532 
533     return uuid;
534 }
535 
536 bool
537 CommunicationKDP::RemoteIsEFI ()
538 {
539     if (GetKernelVersion() == NULL)
540         return false;
541     if (strncmp (m_kernel_version.c_str(), "EFI", 3) == 0)
542         return true;
543     else
544         return false;
545 }
546 
547 lldb::addr_t
548 CommunicationKDP::GetLoadAddress ()
549 {
550     if (GetKernelVersion() == NULL)
551         return LLDB_INVALID_ADDRESS;
552 
553     if (m_kernel_version.find("stext=") == std::string::npos)
554         return LLDB_INVALID_ADDRESS;
555     size_t p = m_kernel_version.find("stext=") + strlen ("stext=");
556     if (m_kernel_version[p] != '0' || m_kernel_version[p + 1] != 'x')
557         return LLDB_INVALID_ADDRESS;
558 
559     addr_t kernel_load_address;
560     errno = 0;
561     kernel_load_address = ::strtoul (m_kernel_version.c_str() + p, NULL, 16);
562     if (errno != 0 || kernel_load_address == 0)
563         return LLDB_INVALID_ADDRESS;
564 
565     return kernel_load_address;
566 }
567 
568 bool
569 CommunicationKDP::SendRequestHostInfo ()
570 {
571     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
572     const CommandType command = KDP_HOSTINFO;
573     const uint32_t command_length = 8;
574     MakeRequestPacketHeader (command, request_packet, command_length);
575     DataExtractor reply_packet;
576     if (SendRequestAndGetReply (command, request_packet, reply_packet))
577     {
578         lldb::offset_t offset = 8;
579         m_kdp_hostinfo_cpu_mask     = reply_packet.GetU32 (&offset);
580         m_kdp_hostinfo_cpu_type     = reply_packet.GetU32 (&offset);
581         m_kdp_hostinfo_cpu_subtype  = reply_packet.GetU32 (&offset);
582 
583         ArchSpec kernel_arch;
584         kernel_arch.SetArchitecture (eArchTypeMachO,
585                                      m_kdp_hostinfo_cpu_type,
586                                      m_kdp_hostinfo_cpu_subtype);
587 
588         m_addr_byte_size = kernel_arch.GetAddressByteSize();
589         m_byte_order = kernel_arch.GetByteOrder();
590         return true;
591     }
592     return false;
593 }
594 
595 const char *
596 CommunicationKDP::GetKernelVersion ()
597 {
598     if (m_kernel_version.empty())
599         SendRequestKernelVersion ();
600     return m_kernel_version.c_str();
601 }
602 
603 bool
604 CommunicationKDP::SendRequestKernelVersion ()
605 {
606     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
607     const CommandType command = KDP_KERNELVERSION;
608     const uint32_t command_length = 8;
609     MakeRequestPacketHeader (command, request_packet, command_length);
610     DataExtractor reply_packet;
611     if (SendRequestAndGetReply (command, request_packet, reply_packet))
612     {
613         const char *kernel_version_cstr = reply_packet.PeekCStr(8);
614         if (kernel_version_cstr && kernel_version_cstr[0])
615             m_kernel_version.assign (kernel_version_cstr);
616         return true;
617     }
618     return false;
619 }
620 
621 bool
622 CommunicationKDP::SendRequestDisconnect ()
623 {
624     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
625     const CommandType command = KDP_DISCONNECT;
626     const uint32_t command_length = 8;
627     MakeRequestPacketHeader (command, request_packet, command_length);
628     DataExtractor reply_packet;
629     if (SendRequestAndGetReply (command, request_packet, reply_packet))
630     {
631         // Are we supposed to get a reply for disconnect?
632     }
633     ClearKDPSettings ();
634     return true;
635 }
636 
637 uint32_t
638 CommunicationKDP::SendRequestReadMemory (lldb::addr_t addr,
639                                          void *dst,
640                                          uint32_t dst_len,
641                                          Error &error)
642 {
643     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
644     bool use_64 = (GetVersion() >= 11);
645     uint32_t command_addr_byte_size = use_64 ? 8 : 4;
646     const CommandType command = use_64 ? KDP_READMEM64 : KDP_READMEM;
647     // Size is header + address size + uint32_t length
648     const uint32_t command_length = 8 + command_addr_byte_size + 4;
649     MakeRequestPacketHeader (command, request_packet, command_length);
650     request_packet.PutMaxHex64 (addr, command_addr_byte_size);
651     request_packet.PutHex32 (dst_len);
652     DataExtractor reply_packet;
653     if (SendRequestAndGetReply (command, request_packet, reply_packet))
654     {
655         lldb::offset_t offset = 8;
656         uint32_t kdp_error = reply_packet.GetU32 (&offset);
657         uint32_t src_len = reply_packet.GetByteSize() - 12;
658 
659         if (src_len > 0)
660         {
661             const void *src = reply_packet.GetData(&offset, src_len);
662             if (src)
663             {
664                 ::memcpy (dst, src, src_len);
665                 error.Clear();
666                 return src_len;
667             }
668         }
669         if (kdp_error)
670             error.SetErrorStringWithFormat ("kdp read memory failed (error %u)", kdp_error);
671         else
672             error.SetErrorString ("kdp read memory failed");
673     }
674     else
675     {
676         error.SetErrorString ("failed to send packet");
677     }
678     return 0;
679 }
680 
681 
682 uint32_t
683 CommunicationKDP::SendRequestWriteMemory (lldb::addr_t addr,
684                                           const void *src,
685                                           uint32_t src_len,
686                                           Error &error)
687 {
688     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
689     bool use_64 = (GetVersion() >= 11);
690     uint32_t command_addr_byte_size = use_64 ? 8 : 4;
691     const CommandType command = use_64 ? KDP_WRITEMEM64 : KDP_WRITEMEM;
692     // Size is header + address size + uint32_t length
693     const uint32_t command_length = 8 + command_addr_byte_size + 4 + src_len;
694     MakeRequestPacketHeader (command, request_packet, command_length);
695     request_packet.PutMaxHex64 (addr, command_addr_byte_size);
696     request_packet.PutHex32 (src_len);
697     request_packet.PutRawBytes(src, src_len);
698 
699     DataExtractor reply_packet;
700     if (SendRequestAndGetReply (command, request_packet, reply_packet))
701     {
702         lldb::offset_t offset = 8;
703         uint32_t kdp_error = reply_packet.GetU32 (&offset);
704         if (kdp_error)
705             error.SetErrorStringWithFormat ("kdp write memory failed (error %u)", kdp_error);
706         else
707         {
708             error.Clear();
709             return src_len;
710         }
711     }
712     else
713     {
714         error.SetErrorString ("failed to send packet");
715     }
716     return 0;
717 }
718 
719 bool
720 CommunicationKDP::SendRawRequest (uint8_t command_byte,
721                                   const void *src,  // Raw packet payload bytes
722                                   uint32_t src_len, // Raw packet payload length
723                                   DataExtractor &reply_packet,
724                                   Error &error)
725 {
726     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
727     // Size is header + address size + uint32_t length
728     const uint32_t command_length = 8 + src_len;
729     const CommandType command = (CommandType)command_byte;
730     MakeRequestPacketHeader (command, request_packet, command_length);
731     request_packet.PutRawBytes(src, src_len);
732 
733     if (SendRequestAndGetReply (command, request_packet, reply_packet))
734     {
735         lldb::offset_t offset = 8;
736         uint32_t kdp_error = reply_packet.GetU32 (&offset);
737         if (kdp_error  && (command_byte != KDP_DUMPINFO))
738             error.SetErrorStringWithFormat ("request packet 0x%8.8x failed (error %u)", command_byte, kdp_error);
739         else
740         {
741             error.Clear();
742             return true;
743         }
744     }
745     else
746     {
747         error.SetErrorString ("failed to send packet");
748     }
749     return false;
750 }
751 
752 
753 const char *
754 CommunicationKDP::GetCommandAsCString (uint8_t command)
755 {
756     switch (command)
757     {
758     case KDP_CONNECT:               return "KDP_CONNECT";
759     case KDP_DISCONNECT:            return "KDP_DISCONNECT";
760     case KDP_HOSTINFO:              return "KDP_HOSTINFO";
761     case KDP_VERSION:               return "KDP_VERSION";
762     case KDP_MAXBYTES:              return "KDP_MAXBYTES";
763     case KDP_READMEM:               return "KDP_READMEM";
764     case KDP_WRITEMEM:              return "KDP_WRITEMEM";
765     case KDP_READREGS:              return "KDP_READREGS";
766     case KDP_WRITEREGS:             return "KDP_WRITEREGS";
767     case KDP_LOAD:                  return "KDP_LOAD";
768     case KDP_IMAGEPATH:             return "KDP_IMAGEPATH";
769     case KDP_SUSPEND:               return "KDP_SUSPEND";
770     case KDP_RESUMECPUS:            return "KDP_RESUMECPUS";
771     case KDP_EXCEPTION:             return "KDP_EXCEPTION";
772     case KDP_TERMINATION:           return "KDP_TERMINATION";
773     case KDP_BREAKPOINT_SET:        return "KDP_BREAKPOINT_SET";
774     case KDP_BREAKPOINT_REMOVE:     return "KDP_BREAKPOINT_REMOVE";
775     case KDP_REGIONS:               return "KDP_REGIONS";
776     case KDP_REATTACH:              return "KDP_REATTACH";
777     case KDP_HOSTREBOOT:            return "KDP_HOSTREBOOT";
778     case KDP_READMEM64:             return "KDP_READMEM64";
779     case KDP_WRITEMEM64:            return "KDP_WRITEMEM64";
780     case KDP_BREAKPOINT_SET64:      return "KDP_BREAKPOINT64_SET";
781     case KDP_BREAKPOINT_REMOVE64:   return "KDP_BREAKPOINT64_REMOVE";
782     case KDP_KERNELVERSION:         return "KDP_KERNELVERSION";
783     case KDP_READPHYSMEM64:         return "KDP_READPHYSMEM64";
784     case KDP_WRITEPHYSMEM64:        return "KDP_WRITEPHYSMEM64";
785     case KDP_READIOPORT:            return "KDP_READIOPORT";
786     case KDP_WRITEIOPORT:           return "KDP_WRITEIOPORT";
787     case KDP_READMSR64:             return "KDP_READMSR64";
788     case KDP_WRITEMSR64:            return "KDP_WRITEMSR64";
789     case KDP_DUMPINFO:              return "KDP_DUMPINFO";
790     }
791     return NULL;
792 }
793 
794 void
795 CommunicationKDP::DumpPacket (Stream &s, const void *data, uint32_t data_len)
796 {
797     DataExtractor extractor (data, data_len, m_byte_order, m_addr_byte_size);
798     DumpPacket (s, extractor);
799 }
800 
801 void
802 CommunicationKDP::DumpPacket (Stream &s, const DataExtractor& packet)
803 {
804     const char *error_desc = NULL;
805     if (packet.GetByteSize() < 8)
806     {
807         error_desc = "error: invalid packet (too short): ";
808     }
809     else
810     {
811         lldb::offset_t offset = 0;
812         const uint8_t first_packet_byte = packet.GetU8 (&offset);
813         const uint8_t sequence_id = packet.GetU8 (&offset);
814         const uint16_t length = packet.GetU16 (&offset);
815         const uint32_t key = packet.GetU32 (&offset);
816         const CommandType command = ExtractCommand (first_packet_byte);
817         const char *command_name = GetCommandAsCString (command);
818         if (command_name)
819         {
820             const bool is_reply = ExtractIsReply(first_packet_byte);
821             s.Printf ("(running=%i) %s %24s: 0x%2.2x 0x%2.2x 0x%4.4x 0x%8.8x ",
822                       IsRunning(),
823                       is_reply ? "<--" : "-->",
824                       command_name,
825                       first_packet_byte,
826                       sequence_id,
827                       length,
828                       key);
829 
830             if (is_reply)
831             {
832                 // Dump request reply packets
833                 switch (command)
834                 {
835                     // Commands that return a single 32 bit error
836                     case KDP_CONNECT:
837                     case KDP_WRITEMEM:
838                     case KDP_WRITEMEM64:
839                     case KDP_BREAKPOINT_SET:
840                     case KDP_BREAKPOINT_REMOVE:
841                     case KDP_BREAKPOINT_SET64:
842                     case KDP_BREAKPOINT_REMOVE64:
843                     case KDP_WRITEREGS:
844                     case KDP_LOAD:
845                     case KDP_WRITEIOPORT:
846                     case KDP_WRITEMSR64:
847                         {
848                             const uint32_t error = packet.GetU32 (&offset);
849                             s.Printf(" (error=0x%8.8x)", error);
850                         }
851                         break;
852 
853                     case KDP_DISCONNECT:
854                     case KDP_REATTACH:
855                     case KDP_HOSTREBOOT:
856                     case KDP_SUSPEND:
857                     case KDP_RESUMECPUS:
858                     case KDP_EXCEPTION:
859                     case KDP_TERMINATION:
860                         // No return value for the reply, just the header to ack
861                         s.PutCString(" ()");
862                         break;
863 
864                     case KDP_HOSTINFO:
865                         {
866                             const uint32_t cpu_mask = packet.GetU32 (&offset);
867                             const uint32_t cpu_type = packet.GetU32 (&offset);
868                             const uint32_t cpu_subtype = packet.GetU32 (&offset);
869                             s.Printf(" (cpu_mask=0x%8.8x, cpu_type=0x%8.8x, cpu_subtype=0x%8.8x)", cpu_mask, cpu_type, cpu_subtype);
870                         }
871                         break;
872 
873                     case KDP_VERSION:
874                         {
875                             const uint32_t version = packet.GetU32 (&offset);
876                             const uint32_t feature = packet.GetU32 (&offset);
877                             s.Printf(" (version=0x%8.8x, feature=0x%8.8x)", version, feature);
878                         }
879                         break;
880 
881                     case KDP_REGIONS:
882                         {
883                             const uint32_t region_count = packet.GetU32 (&offset);
884                             s.Printf(" (count = %u", region_count);
885                             for (uint32_t i=0; i<region_count; ++i)
886                             {
887                                 const addr_t region_addr = packet.GetPointer (&offset);
888                                 const uint32_t region_size = packet.GetU32 (&offset);
889                                 const uint32_t region_prot = packet.GetU32 (&offset);
890                                 s.Printf("\n\tregion[%" PRIu64 "] = { range = [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 "), size = 0x%8.8x, prot = %s }", region_addr, region_addr, region_addr + region_size, region_size, GetPermissionsAsCString (region_prot));
891                             }
892                         }
893                         break;
894 
895                     case KDP_READMEM:
896                     case KDP_READMEM64:
897                     case KDP_READPHYSMEM64:
898                         {
899                             const uint32_t error = packet.GetU32 (&offset);
900                             const uint32_t count = packet.GetByteSize() - offset;
901                             s.Printf(" (error = 0x%8.8x:\n", error);
902                             if (count > 0)
903                                 packet.Dump (&s,                        // Stream to dump to
904                                              offset,                    // Offset within "packet"
905                                              eFormatBytesWithASCII,     // Format to use
906                                              1,                         // Size of each item in bytes
907                                              count,                     // Number of items
908                                              16,                        // Number per line
909                                              m_last_read_memory_addr,   // Don't show addresses before each line
910                                              0, 0);                     // No bitfields
911                         }
912                         break;
913 
914                     case KDP_READREGS:
915                         {
916                             const uint32_t error = packet.GetU32 (&offset);
917                             const uint32_t count = packet.GetByteSize() - offset;
918                             s.Printf(" (error = 0x%8.8x regs:\n", error);
919                             if (count > 0)
920                                 packet.Dump (&s,                        // Stream to dump to
921                                              offset,                    // Offset within "packet"
922                                              eFormatHex,                // Format to use
923                                              m_addr_byte_size,          // Size of each item in bytes
924                                              count / m_addr_byte_size,  // Number of items
925                                              16 / m_addr_byte_size,     // Number per line
926                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
927                                              0, 0);                     // No bitfields
928                         }
929                         break;
930 
931                     case KDP_KERNELVERSION:
932                         {
933                             const char *kernel_version = packet.PeekCStr(8);
934                             s.Printf(" (version = \"%s\")", kernel_version);
935                         }
936                         break;
937 
938                     case KDP_MAXBYTES:
939                         {
940                             const uint32_t max_bytes = packet.GetU32 (&offset);
941                             s.Printf(" (max_bytes = 0x%8.8x (%u))", max_bytes, max_bytes);
942                         }
943                         break;
944                     case KDP_IMAGEPATH:
945                         {
946                             const char *path = packet.GetCStr(&offset);
947                             s.Printf(" (path = \"%s\")", path);
948                         }
949                         break;
950 
951                     case KDP_READIOPORT:
952                     case KDP_READMSR64:
953                         {
954                             const uint32_t error = packet.GetU32 (&offset);
955                             const uint32_t count = packet.GetByteSize() - offset;
956                             s.Printf(" (error = 0x%8.8x io:\n", error);
957                             if (count > 0)
958                                 packet.Dump (&s,                        // Stream to dump to
959                                              offset,                    // Offset within "packet"
960                                              eFormatHex,                // Format to use
961                                              1,                         // Size of each item in bytes
962                                              count,                     // Number of items
963                                              16,                        // Number per line
964                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
965                                              0, 0);                     // No bitfields
966                         }
967                         break;
968                     case KDP_DUMPINFO:
969                         {
970                             const uint32_t count = packet.GetByteSize() - offset;
971                             s.Printf(" (count = %u, bytes = \n", count);
972                             if (count > 0)
973                                 packet.Dump (&s,                        // Stream to dump to
974                                              offset,                    // Offset within "packet"
975                                              eFormatHex,                // Format to use
976                                              1,                         // Size of each item in bytes
977                                              count,                     // Number of items
978                                              16,                        // Number per line
979                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
980                                              0, 0);                     // No bitfields
981 
982                         }
983                         break;
984 
985                     default:
986                         s.Printf(" (add support for dumping this packet reply!!!");
987                         break;
988 
989                 }
990             }
991             else
992             {
993                 // Dump request packets
994                 switch (command)
995                 {
996                     case KDP_CONNECT:
997                         {
998                             const uint16_t reply_port = packet.GetU16 (&offset);
999                             const uint16_t exc_port = packet.GetU16 (&offset);
1000                             s.Printf(" (reply_port = %u, exc_port = %u, greeting = \"%s\")", reply_port, exc_port, packet.GetCStr(&offset));
1001                         }
1002                         break;
1003 
1004                     case KDP_DISCONNECT:
1005                     case KDP_HOSTREBOOT:
1006                     case KDP_HOSTINFO:
1007                     case KDP_VERSION:
1008                     case KDP_REGIONS:
1009                     case KDP_KERNELVERSION:
1010                     case KDP_MAXBYTES:
1011                     case KDP_IMAGEPATH:
1012                     case KDP_SUSPEND:
1013                         // No args, just the header in the request...
1014                         s.PutCString(" ()");
1015                         break;
1016 
1017                     case KDP_RESUMECPUS:
1018                         {
1019                             const uint32_t cpu_mask = packet.GetU32 (&offset);
1020                             s.Printf(" (cpu_mask = 0x%8.8x)", cpu_mask);
1021                         }
1022                         break;
1023 
1024                     case KDP_READMEM:
1025                         {
1026                             const uint32_t addr = packet.GetU32 (&offset);
1027                             const uint32_t size = packet.GetU32 (&offset);
1028                             s.Printf(" (addr = 0x%8.8x, size = %u)", addr, size);
1029                             m_last_read_memory_addr = addr;
1030                         }
1031                         break;
1032 
1033                     case KDP_WRITEMEM:
1034                         {
1035                             const uint32_t addr = packet.GetU32 (&offset);
1036                             const uint32_t size = packet.GetU32 (&offset);
1037                             s.Printf(" (addr = 0x%8.8x, size = %u, bytes = \n", addr, size);
1038                             if (size > 0)
1039                                 DataExtractor::DumpHexBytes(&s, packet.GetData(&offset, size), size, 32, addr);
1040                         }
1041                         break;
1042 
1043                     case KDP_READMEM64:
1044                         {
1045                             const uint64_t addr = packet.GetU64 (&offset);
1046                             const uint32_t size = packet.GetU32 (&offset);
1047                             s.Printf(" (addr = 0x%16.16" PRIx64 ", size = %u)", addr, size);
1048                             m_last_read_memory_addr = addr;
1049                         }
1050                         break;
1051 
1052                     case KDP_READPHYSMEM64:
1053                         {
1054                             const uint64_t addr = packet.GetU64 (&offset);
1055                             const uint32_t size = packet.GetU32 (&offset);
1056                             const uint32_t lcpu = packet.GetU16 (&offset);
1057                             s.Printf(" (addr = 0x%16.16llx, size = %u, lcpu = %u)", addr, size, lcpu);
1058                             m_last_read_memory_addr = addr;
1059                         }
1060                         break;
1061 
1062                     case KDP_WRITEMEM64:
1063                         {
1064                             const uint64_t addr = packet.GetU64 (&offset);
1065                             const uint32_t size = packet.GetU32 (&offset);
1066                             s.Printf(" (addr = 0x%16.16" PRIx64 ", size = %u, bytes = \n", addr, size);
1067                             if (size > 0)
1068                                 DataExtractor::DumpHexBytes(&s, packet.GetData(&offset, size), size, 32, addr);
1069                         }
1070                         break;
1071 
1072                     case KDP_WRITEPHYSMEM64:
1073                         {
1074                             const uint64_t addr = packet.GetU64 (&offset);
1075                             const uint32_t size = packet.GetU32 (&offset);
1076                             const uint32_t lcpu = packet.GetU16 (&offset);
1077                             s.Printf(" (addr = 0x%16.16llx, size = %u, lcpu = %u, bytes = \n", addr, size, lcpu);
1078                             if (size > 0)
1079                                 DataExtractor::DumpHexBytes(&s, packet.GetData(&offset, size), size, 32, addr);
1080                         }
1081                         break;
1082 
1083                     case KDP_READREGS:
1084                         {
1085                             const uint32_t cpu = packet.GetU32 (&offset);
1086                             const uint32_t flavor = packet.GetU32 (&offset);
1087                             s.Printf(" (cpu = %u, flavor = %u)", cpu, flavor);
1088                         }
1089                         break;
1090 
1091                     case KDP_WRITEREGS:
1092                         {
1093                             const uint32_t cpu = packet.GetU32 (&offset);
1094                             const uint32_t flavor = packet.GetU32 (&offset);
1095                             const uint32_t nbytes = packet.GetByteSize() - offset;
1096                             s.Printf(" (cpu = %u, flavor = %u, regs = \n", cpu, flavor);
1097                             if (nbytes > 0)
1098                                 packet.Dump (&s,                        // Stream to dump to
1099                                              offset,                    // Offset within "packet"
1100                                              eFormatHex,                // Format to use
1101                                              m_addr_byte_size,          // Size of each item in bytes
1102                                              nbytes / m_addr_byte_size, // Number of items
1103                                              16 / m_addr_byte_size,     // Number per line
1104                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
1105                                              0, 0);                     // No bitfields
1106                         }
1107                         break;
1108 
1109 
1110                     case KDP_BREAKPOINT_SET:
1111                     case KDP_BREAKPOINT_REMOVE:
1112                         {
1113                             const uint32_t addr = packet.GetU32 (&offset);
1114                             s.Printf(" (addr = 0x%8.8x)", addr);
1115                         }
1116                         break;
1117 
1118                     case KDP_BREAKPOINT_SET64:
1119                     case KDP_BREAKPOINT_REMOVE64:
1120                         {
1121                             const uint64_t addr = packet.GetU64 (&offset);
1122                             s.Printf(" (addr = 0x%16.16" PRIx64 ")", addr);
1123                         }
1124                         break;
1125 
1126 
1127                     case KDP_LOAD:
1128                         {
1129                             const char *path = packet.GetCStr(&offset);
1130                             s.Printf(" (path = \"%s\")", path);
1131                         }
1132                         break;
1133 
1134                     case KDP_EXCEPTION:
1135                         {
1136                             const uint32_t count = packet.GetU32 (&offset);
1137 
1138                             for (uint32_t i=0; i<count; ++i)
1139                             {
1140                                 const uint32_t cpu = packet.GetU32 (&offset);
1141                                 const uint32_t exc = packet.GetU32 (&offset);
1142                                 const uint32_t code = packet.GetU32 (&offset);
1143                                 const uint32_t subcode = packet.GetU32 (&offset);
1144                                 const char *exc_cstr = NULL;
1145                                 switch (exc)
1146                                 {
1147                                     case 1:  exc_cstr = "EXC_BAD_ACCESS"; break;
1148                                     case 2:  exc_cstr = "EXC_BAD_INSTRUCTION"; break;
1149                                     case 3:  exc_cstr = "EXC_ARITHMETIC"; break;
1150                                     case 4:  exc_cstr = "EXC_EMULATION"; break;
1151                                     case 5:  exc_cstr = "EXC_SOFTWARE"; break;
1152                                     case 6:  exc_cstr = "EXC_BREAKPOINT"; break;
1153                                     case 7:  exc_cstr = "EXC_SYSCALL"; break;
1154                                     case 8:  exc_cstr = "EXC_MACH_SYSCALL"; break;
1155                                     case 9:  exc_cstr = "EXC_RPC_ALERT"; break;
1156                                     case 10: exc_cstr = "EXC_CRASH"; break;
1157                                     default:
1158                                         break;
1159                                 }
1160 
1161                                 s.Printf ("{ cpu = 0x%8.8x, exc = %s (%u), code = %u (0x%8.8x), subcode = %u (0x%8.8x)} ",
1162                                           cpu, exc_cstr, exc, code, code, subcode, subcode);
1163                             }
1164                         }
1165                         break;
1166 
1167                     case KDP_TERMINATION:
1168                         {
1169                             const uint32_t term_code = packet.GetU32 (&offset);
1170                             const uint32_t exit_code = packet.GetU32 (&offset);
1171                             s.Printf(" (term_code = 0x%8.8x (%u), exit_code = 0x%8.8x (%u))", term_code, term_code, exit_code, exit_code);
1172                         }
1173                         break;
1174 
1175                     case KDP_REATTACH:
1176                         {
1177                             const uint16_t reply_port = packet.GetU16 (&offset);
1178                             s.Printf(" (reply_port = %u)", reply_port);
1179                         }
1180                         break;
1181 
1182                     case KDP_READMSR64:
1183                         {
1184                             const uint32_t address = packet.GetU32 (&offset);
1185                             const uint16_t lcpu = packet.GetU16 (&offset);
1186                             s.Printf(" (address=0x%8.8x, lcpu=0x%4.4x)", address, lcpu);
1187                         }
1188                         break;
1189 
1190                     case KDP_WRITEMSR64:
1191                         {
1192                             const uint32_t address = packet.GetU32 (&offset);
1193                             const uint16_t lcpu = packet.GetU16 (&offset);
1194                             const uint32_t nbytes = packet.GetByteSize() - offset;
1195                             s.Printf(" (address=0x%8.8x, lcpu=0x%4.4x, nbytes=0x%8.8x)", lcpu, address, nbytes);
1196                             if (nbytes > 0)
1197                                 packet.Dump (&s,                        // Stream to dump to
1198                                              offset,                    // Offset within "packet"
1199                                              eFormatHex,                // Format to use
1200                                              1,                         // Size of each item in bytes
1201                                              nbytes,                    // Number of items
1202                                              16,                        // Number per line
1203                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
1204                                              0, 0);                     // No bitfields
1205                         }
1206                         break;
1207 
1208                     case KDP_READIOPORT:
1209                         {
1210                             const uint16_t lcpu = packet.GetU16 (&offset);
1211                             const uint16_t address = packet.GetU16 (&offset);
1212                             const uint16_t nbytes = packet.GetU16 (&offset);
1213                             s.Printf(" (lcpu=0x%4.4x, address=0x%4.4x, nbytes=%u)", lcpu, address, nbytes);
1214                         }
1215                         break;
1216 
1217                     case KDP_WRITEIOPORT:
1218                          {
1219                             const uint16_t lcpu = packet.GetU16 (&offset);
1220                             const uint16_t address = packet.GetU16 (&offset);
1221                             const uint16_t nbytes = packet.GetU16 (&offset);
1222                             s.Printf(" (lcpu = %u, addr = 0x%4.4x, nbytes = %u, bytes = \n", lcpu, address, nbytes);
1223                             if (nbytes > 0)
1224                                 packet.Dump (&s,                        // Stream to dump to
1225                                              offset,                    // Offset within "packet"
1226                                              eFormatHex,                // Format to use
1227                                              1,                         // Size of each item in bytes
1228                                              nbytes,                    // Number of items
1229                                              16,                        // Number per line
1230                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
1231                                              0, 0);                     // No bitfields
1232                         }
1233                         break;
1234 
1235                     case KDP_DUMPINFO:
1236                         {
1237                             const uint32_t count = packet.GetByteSize() - offset;
1238                             s.Printf(" (count = %u, bytes = \n", count);
1239                             if (count > 0)
1240                                 packet.Dump (&s,                        // Stream to dump to
1241                                              offset,                    // Offset within "packet"
1242                                              eFormatHex,                // Format to use
1243                                              1,                         // Size of each item in bytes
1244                                              count,                     // Number of items
1245                                              16,                        // Number per line
1246                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
1247                                              0, 0);                     // No bitfields
1248 
1249                         }
1250                         break;
1251 
1252                }
1253             }
1254         }
1255         else
1256         {
1257             error_desc = "error: invalid packet command: ";
1258         }
1259     }
1260 
1261     if (error_desc)
1262     {
1263         s.PutCString (error_desc);
1264 
1265         packet.Dump (&s,                    // Stream to dump to
1266                      0,                     // Offset into "packet"
1267                      eFormatBytes,          // Dump as hex bytes
1268                      1,                     // Size of each item is 1 for single bytes
1269                      packet.GetByteSize(),  // Number of bytes
1270                      UINT32_MAX,            // Num bytes per line
1271                      LLDB_INVALID_ADDRESS,  // Base address
1272                      0, 0);                 // Bitfield info set to not do anything bitfield related
1273     }
1274 }
1275 
1276 uint32_t
1277 CommunicationKDP::SendRequestReadRegisters (uint32_t cpu,
1278                                             uint32_t flavor,
1279                                             void *dst,
1280                                             uint32_t dst_len,
1281                                             Error &error)
1282 {
1283     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
1284     const CommandType command = KDP_READREGS;
1285     // Size is header + 4 byte cpu and 4 byte flavor
1286     const uint32_t command_length = 8 + 4 + 4;
1287     MakeRequestPacketHeader (command, request_packet, command_length);
1288     request_packet.PutHex32 (cpu);
1289     request_packet.PutHex32 (flavor);
1290     DataExtractor reply_packet;
1291     if (SendRequestAndGetReply (command, request_packet, reply_packet))
1292     {
1293         lldb::offset_t offset = 8;
1294         uint32_t kdp_error = reply_packet.GetU32 (&offset);
1295         uint32_t src_len = reply_packet.GetByteSize() - 12;
1296 
1297         if (src_len > 0)
1298         {
1299             const uint32_t bytes_to_copy = std::min<uint32_t>(src_len, dst_len);
1300             const void *src = reply_packet.GetData(&offset, bytes_to_copy);
1301             if (src)
1302             {
1303                 ::memcpy (dst, src, bytes_to_copy);
1304                 error.Clear();
1305                 // Return the number of bytes we could have returned regardless if
1306                 // we copied them or not, just so we know when things don't match up
1307                 return src_len;
1308             }
1309         }
1310         if (kdp_error)
1311             error.SetErrorStringWithFormat("failed to read kdp registers for cpu %u flavor %u (error %u)", cpu, flavor, kdp_error);
1312         else
1313             error.SetErrorStringWithFormat("failed to read kdp registers for cpu %u flavor %u", cpu, flavor);
1314     }
1315     else
1316     {
1317         error.SetErrorString ("failed to send packet");
1318     }
1319     return 0;
1320 }
1321 
1322 uint32_t
1323 CommunicationKDP::SendRequestWriteRegisters (uint32_t cpu,
1324                                              uint32_t flavor,
1325                                              const void *src,
1326                                              uint32_t src_len,
1327                                              Error &error)
1328 {
1329     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
1330     const CommandType command = KDP_WRITEREGS;
1331     // Size is header + 4 byte cpu and 4 byte flavor
1332     const uint32_t command_length = 8 + 4 + 4 + src_len;
1333     MakeRequestPacketHeader (command, request_packet, command_length);
1334     request_packet.PutHex32 (cpu);
1335     request_packet.PutHex32 (flavor);
1336     request_packet.Write(src, src_len);
1337     DataExtractor reply_packet;
1338     if (SendRequestAndGetReply (command, request_packet, reply_packet))
1339     {
1340         lldb::offset_t offset = 8;
1341         uint32_t kdp_error = reply_packet.GetU32 (&offset);
1342         if (kdp_error == 0)
1343             return src_len;
1344         error.SetErrorStringWithFormat("failed to read kdp registers for cpu %u flavor %u (error %u)", cpu, flavor, kdp_error);
1345     }
1346     else
1347     {
1348         error.SetErrorString ("failed to send packet");
1349     }
1350     return 0;
1351 }
1352 
1353 
1354 bool
1355 CommunicationKDP::SendRequestResume ()
1356 {
1357     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
1358     const CommandType command = KDP_RESUMECPUS;
1359     const uint32_t command_length = 12;
1360     MakeRequestPacketHeader (command, request_packet, command_length);
1361     request_packet.PutHex32(GetCPUMask());
1362 
1363     DataExtractor reply_packet;
1364     if (SendRequestAndGetReply (command, request_packet, reply_packet))
1365         return true;
1366     return false;
1367 }
1368 
1369 bool
1370 CommunicationKDP::SendRequestBreakpoint (bool set, addr_t addr)
1371 {
1372     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
1373     bool use_64 = (GetVersion() >= 11);
1374     uint32_t command_addr_byte_size = use_64 ? 8 : 4;
1375     const CommandType command = set ? (use_64 ? KDP_BREAKPOINT_SET64    : KDP_BREAKPOINT_SET   ):
1376                                       (use_64 ? KDP_BREAKPOINT_REMOVE64 : KDP_BREAKPOINT_REMOVE);
1377 
1378     const uint32_t command_length = 8 + command_addr_byte_size;
1379     MakeRequestPacketHeader (command, request_packet, command_length);
1380     request_packet.PutMaxHex64 (addr, command_addr_byte_size);
1381 
1382     DataExtractor reply_packet;
1383     if (SendRequestAndGetReply (command, request_packet, reply_packet))
1384     {
1385         lldb::offset_t offset = 8;
1386         uint32_t kdp_error = reply_packet.GetU32 (&offset);
1387         if (kdp_error == 0)
1388             return true;
1389     }
1390     return false;
1391 }
1392 
1393 bool
1394 CommunicationKDP::SendRequestSuspend ()
1395 {
1396     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
1397     const CommandType command = KDP_SUSPEND;
1398     const uint32_t command_length = 8;
1399     MakeRequestPacketHeader (command, request_packet, command_length);
1400     DataExtractor reply_packet;
1401     if (SendRequestAndGetReply (command, request_packet, reply_packet))
1402         return true;
1403     return false;
1404 }
1405 
1406