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 bool
548 CommunicationKDP::RemoteIsDarwinKernel ()
549 {
550     if (GetKernelVersion() == NULL)
551         return false;
552     if (m_kernel_version.find("Darwin Kernel") != std::string::npos)
553         return true;
554     else
555         return false;
556 }
557 
558 lldb::addr_t
559 CommunicationKDP::GetLoadAddress ()
560 {
561     if (GetKernelVersion() == NULL)
562         return LLDB_INVALID_ADDRESS;
563 
564     if (m_kernel_version.find("stext=") == std::string::npos)
565         return LLDB_INVALID_ADDRESS;
566     size_t p = m_kernel_version.find("stext=") + strlen ("stext=");
567     if (m_kernel_version[p] != '0' || m_kernel_version[p + 1] != 'x')
568         return LLDB_INVALID_ADDRESS;
569 
570     addr_t kernel_load_address;
571     errno = 0;
572     kernel_load_address = ::strtoul (m_kernel_version.c_str() + p, NULL, 16);
573     if (errno != 0 || kernel_load_address == 0)
574         return LLDB_INVALID_ADDRESS;
575 
576     return kernel_load_address;
577 }
578 
579 bool
580 CommunicationKDP::SendRequestHostInfo ()
581 {
582     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
583     const CommandType command = KDP_HOSTINFO;
584     const uint32_t command_length = 8;
585     MakeRequestPacketHeader (command, request_packet, command_length);
586     DataExtractor reply_packet;
587     if (SendRequestAndGetReply (command, request_packet, reply_packet))
588     {
589         lldb::offset_t offset = 8;
590         m_kdp_hostinfo_cpu_mask     = reply_packet.GetU32 (&offset);
591         m_kdp_hostinfo_cpu_type     = reply_packet.GetU32 (&offset);
592         m_kdp_hostinfo_cpu_subtype  = reply_packet.GetU32 (&offset);
593 
594         ArchSpec kernel_arch;
595         kernel_arch.SetArchitecture (eArchTypeMachO,
596                                      m_kdp_hostinfo_cpu_type,
597                                      m_kdp_hostinfo_cpu_subtype);
598 
599         m_addr_byte_size = kernel_arch.GetAddressByteSize();
600         m_byte_order = kernel_arch.GetByteOrder();
601         return true;
602     }
603     return false;
604 }
605 
606 const char *
607 CommunicationKDP::GetKernelVersion ()
608 {
609     if (m_kernel_version.empty())
610         SendRequestKernelVersion ();
611     return m_kernel_version.c_str();
612 }
613 
614 bool
615 CommunicationKDP::SendRequestKernelVersion ()
616 {
617     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
618     const CommandType command = KDP_KERNELVERSION;
619     const uint32_t command_length = 8;
620     MakeRequestPacketHeader (command, request_packet, command_length);
621     DataExtractor reply_packet;
622     if (SendRequestAndGetReply (command, request_packet, reply_packet))
623     {
624         const char *kernel_version_cstr = reply_packet.PeekCStr(8);
625         if (kernel_version_cstr && kernel_version_cstr[0])
626             m_kernel_version.assign (kernel_version_cstr);
627         return true;
628     }
629     return false;
630 }
631 
632 bool
633 CommunicationKDP::SendRequestDisconnect ()
634 {
635     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
636     const CommandType command = KDP_DISCONNECT;
637     const uint32_t command_length = 8;
638     MakeRequestPacketHeader (command, request_packet, command_length);
639     DataExtractor reply_packet;
640     if (SendRequestAndGetReply (command, request_packet, reply_packet))
641     {
642         // Are we supposed to get a reply for disconnect?
643     }
644     ClearKDPSettings ();
645     return true;
646 }
647 
648 uint32_t
649 CommunicationKDP::SendRequestReadMemory (lldb::addr_t addr,
650                                          void *dst,
651                                          uint32_t dst_len,
652                                          Error &error)
653 {
654     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
655     bool use_64 = (GetVersion() >= 11);
656     uint32_t command_addr_byte_size = use_64 ? 8 : 4;
657     const CommandType command = use_64 ? KDP_READMEM64 : KDP_READMEM;
658     // Size is header + address size + uint32_t length
659     const uint32_t command_length = 8 + command_addr_byte_size + 4;
660     MakeRequestPacketHeader (command, request_packet, command_length);
661     request_packet.PutMaxHex64 (addr, command_addr_byte_size);
662     request_packet.PutHex32 (dst_len);
663     DataExtractor reply_packet;
664     if (SendRequestAndGetReply (command, request_packet, reply_packet))
665     {
666         lldb::offset_t offset = 8;
667         uint32_t kdp_error = reply_packet.GetU32 (&offset);
668         uint32_t src_len = reply_packet.GetByteSize() - 12;
669 
670         if (src_len > 0)
671         {
672             const void *src = reply_packet.GetData(&offset, src_len);
673             if (src)
674             {
675                 ::memcpy (dst, src, src_len);
676                 error.Clear();
677                 return src_len;
678             }
679         }
680         if (kdp_error)
681             error.SetErrorStringWithFormat ("kdp read memory failed (error %u)", kdp_error);
682         else
683             error.SetErrorString ("kdp read memory failed");
684     }
685     else
686     {
687         error.SetErrorString ("failed to send packet");
688     }
689     return 0;
690 }
691 
692 
693 uint32_t
694 CommunicationKDP::SendRequestWriteMemory (lldb::addr_t addr,
695                                           const void *src,
696                                           uint32_t src_len,
697                                           Error &error)
698 {
699     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
700     bool use_64 = (GetVersion() >= 11);
701     uint32_t command_addr_byte_size = use_64 ? 8 : 4;
702     const CommandType command = use_64 ? KDP_WRITEMEM64 : KDP_WRITEMEM;
703     // Size is header + address size + uint32_t length
704     const uint32_t command_length = 8 + command_addr_byte_size + 4 + src_len;
705     MakeRequestPacketHeader (command, request_packet, command_length);
706     request_packet.PutMaxHex64 (addr, command_addr_byte_size);
707     request_packet.PutHex32 (src_len);
708     request_packet.PutRawBytes(src, src_len);
709 
710     DataExtractor reply_packet;
711     if (SendRequestAndGetReply (command, request_packet, reply_packet))
712     {
713         lldb::offset_t offset = 8;
714         uint32_t kdp_error = reply_packet.GetU32 (&offset);
715         if (kdp_error)
716             error.SetErrorStringWithFormat ("kdp write memory failed (error %u)", kdp_error);
717         else
718         {
719             error.Clear();
720             return src_len;
721         }
722     }
723     else
724     {
725         error.SetErrorString ("failed to send packet");
726     }
727     return 0;
728 }
729 
730 bool
731 CommunicationKDP::SendRawRequest (uint8_t command_byte,
732                                   const void *src,  // Raw packet payload bytes
733                                   uint32_t src_len, // Raw packet payload length
734                                   DataExtractor &reply_packet,
735                                   Error &error)
736 {
737     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
738     // Size is header + address size + uint32_t length
739     const uint32_t command_length = 8 + src_len;
740     const CommandType command = (CommandType)command_byte;
741     MakeRequestPacketHeader (command, request_packet, command_length);
742     request_packet.PutRawBytes(src, src_len);
743 
744     if (SendRequestAndGetReply (command, request_packet, reply_packet))
745     {
746         lldb::offset_t offset = 8;
747         uint32_t kdp_error = reply_packet.GetU32 (&offset);
748         if (kdp_error  && (command_byte != KDP_DUMPINFO))
749             error.SetErrorStringWithFormat ("request packet 0x%8.8x failed (error %u)", command_byte, kdp_error);
750         else
751         {
752             error.Clear();
753             return true;
754         }
755     }
756     else
757     {
758         error.SetErrorString ("failed to send packet");
759     }
760     return false;
761 }
762 
763 
764 const char *
765 CommunicationKDP::GetCommandAsCString (uint8_t command)
766 {
767     switch (command)
768     {
769     case KDP_CONNECT:               return "KDP_CONNECT";
770     case KDP_DISCONNECT:            return "KDP_DISCONNECT";
771     case KDP_HOSTINFO:              return "KDP_HOSTINFO";
772     case KDP_VERSION:               return "KDP_VERSION";
773     case KDP_MAXBYTES:              return "KDP_MAXBYTES";
774     case KDP_READMEM:               return "KDP_READMEM";
775     case KDP_WRITEMEM:              return "KDP_WRITEMEM";
776     case KDP_READREGS:              return "KDP_READREGS";
777     case KDP_WRITEREGS:             return "KDP_WRITEREGS";
778     case KDP_LOAD:                  return "KDP_LOAD";
779     case KDP_IMAGEPATH:             return "KDP_IMAGEPATH";
780     case KDP_SUSPEND:               return "KDP_SUSPEND";
781     case KDP_RESUMECPUS:            return "KDP_RESUMECPUS";
782     case KDP_EXCEPTION:             return "KDP_EXCEPTION";
783     case KDP_TERMINATION:           return "KDP_TERMINATION";
784     case KDP_BREAKPOINT_SET:        return "KDP_BREAKPOINT_SET";
785     case KDP_BREAKPOINT_REMOVE:     return "KDP_BREAKPOINT_REMOVE";
786     case KDP_REGIONS:               return "KDP_REGIONS";
787     case KDP_REATTACH:              return "KDP_REATTACH";
788     case KDP_HOSTREBOOT:            return "KDP_HOSTREBOOT";
789     case KDP_READMEM64:             return "KDP_READMEM64";
790     case KDP_WRITEMEM64:            return "KDP_WRITEMEM64";
791     case KDP_BREAKPOINT_SET64:      return "KDP_BREAKPOINT64_SET";
792     case KDP_BREAKPOINT_REMOVE64:   return "KDP_BREAKPOINT64_REMOVE";
793     case KDP_KERNELVERSION:         return "KDP_KERNELVERSION";
794     case KDP_READPHYSMEM64:         return "KDP_READPHYSMEM64";
795     case KDP_WRITEPHYSMEM64:        return "KDP_WRITEPHYSMEM64";
796     case KDP_READIOPORT:            return "KDP_READIOPORT";
797     case KDP_WRITEIOPORT:           return "KDP_WRITEIOPORT";
798     case KDP_READMSR64:             return "KDP_READMSR64";
799     case KDP_WRITEMSR64:            return "KDP_WRITEMSR64";
800     case KDP_DUMPINFO:              return "KDP_DUMPINFO";
801     }
802     return NULL;
803 }
804 
805 void
806 CommunicationKDP::DumpPacket (Stream &s, const void *data, uint32_t data_len)
807 {
808     DataExtractor extractor (data, data_len, m_byte_order, m_addr_byte_size);
809     DumpPacket (s, extractor);
810 }
811 
812 void
813 CommunicationKDP::DumpPacket (Stream &s, const DataExtractor& packet)
814 {
815     const char *error_desc = NULL;
816     if (packet.GetByteSize() < 8)
817     {
818         error_desc = "error: invalid packet (too short): ";
819     }
820     else
821     {
822         lldb::offset_t offset = 0;
823         const uint8_t first_packet_byte = packet.GetU8 (&offset);
824         const uint8_t sequence_id = packet.GetU8 (&offset);
825         const uint16_t length = packet.GetU16 (&offset);
826         const uint32_t key = packet.GetU32 (&offset);
827         const CommandType command = ExtractCommand (first_packet_byte);
828         const char *command_name = GetCommandAsCString (command);
829         if (command_name)
830         {
831             const bool is_reply = ExtractIsReply(first_packet_byte);
832             s.Printf ("(running=%i) %s %24s: 0x%2.2x 0x%2.2x 0x%4.4x 0x%8.8x ",
833                       IsRunning(),
834                       is_reply ? "<--" : "-->",
835                       command_name,
836                       first_packet_byte,
837                       sequence_id,
838                       length,
839                       key);
840 
841             if (is_reply)
842             {
843                 // Dump request reply packets
844                 switch (command)
845                 {
846                     // Commands that return a single 32 bit error
847                     case KDP_CONNECT:
848                     case KDP_WRITEMEM:
849                     case KDP_WRITEMEM64:
850                     case KDP_BREAKPOINT_SET:
851                     case KDP_BREAKPOINT_REMOVE:
852                     case KDP_BREAKPOINT_SET64:
853                     case KDP_BREAKPOINT_REMOVE64:
854                     case KDP_WRITEREGS:
855                     case KDP_LOAD:
856                     case KDP_WRITEIOPORT:
857                     case KDP_WRITEMSR64:
858                         {
859                             const uint32_t error = packet.GetU32 (&offset);
860                             s.Printf(" (error=0x%8.8x)", error);
861                         }
862                         break;
863 
864                     case KDP_DISCONNECT:
865                     case KDP_REATTACH:
866                     case KDP_HOSTREBOOT:
867                     case KDP_SUSPEND:
868                     case KDP_RESUMECPUS:
869                     case KDP_EXCEPTION:
870                     case KDP_TERMINATION:
871                         // No return value for the reply, just the header to ack
872                         s.PutCString(" ()");
873                         break;
874 
875                     case KDP_HOSTINFO:
876                         {
877                             const uint32_t cpu_mask = packet.GetU32 (&offset);
878                             const uint32_t cpu_type = packet.GetU32 (&offset);
879                             const uint32_t cpu_subtype = packet.GetU32 (&offset);
880                             s.Printf(" (cpu_mask=0x%8.8x, cpu_type=0x%8.8x, cpu_subtype=0x%8.8x)", cpu_mask, cpu_type, cpu_subtype);
881                         }
882                         break;
883 
884                     case KDP_VERSION:
885                         {
886                             const uint32_t version = packet.GetU32 (&offset);
887                             const uint32_t feature = packet.GetU32 (&offset);
888                             s.Printf(" (version=0x%8.8x, feature=0x%8.8x)", version, feature);
889                         }
890                         break;
891 
892                     case KDP_REGIONS:
893                         {
894                             const uint32_t region_count = packet.GetU32 (&offset);
895                             s.Printf(" (count = %u", region_count);
896                             for (uint32_t i=0; i<region_count; ++i)
897                             {
898                                 const addr_t region_addr = packet.GetPointer (&offset);
899                                 const uint32_t region_size = packet.GetU32 (&offset);
900                                 const uint32_t region_prot = packet.GetU32 (&offset);
901                                 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));
902                             }
903                         }
904                         break;
905 
906                     case KDP_READMEM:
907                     case KDP_READMEM64:
908                     case KDP_READPHYSMEM64:
909                         {
910                             const uint32_t error = packet.GetU32 (&offset);
911                             const uint32_t count = packet.GetByteSize() - offset;
912                             s.Printf(" (error = 0x%8.8x:\n", error);
913                             if (count > 0)
914                                 packet.Dump (&s,                        // Stream to dump to
915                                              offset,                    // Offset within "packet"
916                                              eFormatBytesWithASCII,     // Format to use
917                                              1,                         // Size of each item in bytes
918                                              count,                     // Number of items
919                                              16,                        // Number per line
920                                              m_last_read_memory_addr,   // Don't show addresses before each line
921                                              0, 0);                     // No bitfields
922                         }
923                         break;
924 
925                     case KDP_READREGS:
926                         {
927                             const uint32_t error = packet.GetU32 (&offset);
928                             const uint32_t count = packet.GetByteSize() - offset;
929                             s.Printf(" (error = 0x%8.8x regs:\n", error);
930                             if (count > 0)
931                                 packet.Dump (&s,                        // Stream to dump to
932                                              offset,                    // Offset within "packet"
933                                              eFormatHex,                // Format to use
934                                              m_addr_byte_size,          // Size of each item in bytes
935                                              count / m_addr_byte_size,  // Number of items
936                                              16 / m_addr_byte_size,     // Number per line
937                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
938                                              0, 0);                     // No bitfields
939                         }
940                         break;
941 
942                     case KDP_KERNELVERSION:
943                         {
944                             const char *kernel_version = packet.PeekCStr(8);
945                             s.Printf(" (version = \"%s\")", kernel_version);
946                         }
947                         break;
948 
949                     case KDP_MAXBYTES:
950                         {
951                             const uint32_t max_bytes = packet.GetU32 (&offset);
952                             s.Printf(" (max_bytes = 0x%8.8x (%u))", max_bytes, max_bytes);
953                         }
954                         break;
955                     case KDP_IMAGEPATH:
956                         {
957                             const char *path = packet.GetCStr(&offset);
958                             s.Printf(" (path = \"%s\")", path);
959                         }
960                         break;
961 
962                     case KDP_READIOPORT:
963                     case KDP_READMSR64:
964                         {
965                             const uint32_t error = packet.GetU32 (&offset);
966                             const uint32_t count = packet.GetByteSize() - offset;
967                             s.Printf(" (error = 0x%8.8x io:\n", error);
968                             if (count > 0)
969                                 packet.Dump (&s,                        // Stream to dump to
970                                              offset,                    // Offset within "packet"
971                                              eFormatHex,                // Format to use
972                                              1,                         // Size of each item in bytes
973                                              count,                     // Number of items
974                                              16,                        // Number per line
975                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
976                                              0, 0);                     // No bitfields
977                         }
978                         break;
979                     case KDP_DUMPINFO:
980                         {
981                             const uint32_t count = packet.GetByteSize() - offset;
982                             s.Printf(" (count = %u, bytes = \n", count);
983                             if (count > 0)
984                                 packet.Dump (&s,                        // Stream to dump to
985                                              offset,                    // Offset within "packet"
986                                              eFormatHex,                // Format to use
987                                              1,                         // Size of each item in bytes
988                                              count,                     // Number of items
989                                              16,                        // Number per line
990                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
991                                              0, 0);                     // No bitfields
992 
993                         }
994                         break;
995 
996                     default:
997                         s.Printf(" (add support for dumping this packet reply!!!");
998                         break;
999 
1000                 }
1001             }
1002             else
1003             {
1004                 // Dump request packets
1005                 switch (command)
1006                 {
1007                     case KDP_CONNECT:
1008                         {
1009                             const uint16_t reply_port = packet.GetU16 (&offset);
1010                             const uint16_t exc_port = packet.GetU16 (&offset);
1011                             s.Printf(" (reply_port = %u, exc_port = %u, greeting = \"%s\")", reply_port, exc_port, packet.GetCStr(&offset));
1012                         }
1013                         break;
1014 
1015                     case KDP_DISCONNECT:
1016                     case KDP_HOSTREBOOT:
1017                     case KDP_HOSTINFO:
1018                     case KDP_VERSION:
1019                     case KDP_REGIONS:
1020                     case KDP_KERNELVERSION:
1021                     case KDP_MAXBYTES:
1022                     case KDP_IMAGEPATH:
1023                     case KDP_SUSPEND:
1024                         // No args, just the header in the request...
1025                         s.PutCString(" ()");
1026                         break;
1027 
1028                     case KDP_RESUMECPUS:
1029                         {
1030                             const uint32_t cpu_mask = packet.GetU32 (&offset);
1031                             s.Printf(" (cpu_mask = 0x%8.8x)", cpu_mask);
1032                         }
1033                         break;
1034 
1035                     case KDP_READMEM:
1036                         {
1037                             const uint32_t addr = packet.GetU32 (&offset);
1038                             const uint32_t size = packet.GetU32 (&offset);
1039                             s.Printf(" (addr = 0x%8.8x, size = %u)", addr, size);
1040                             m_last_read_memory_addr = addr;
1041                         }
1042                         break;
1043 
1044                     case KDP_WRITEMEM:
1045                         {
1046                             const uint32_t addr = packet.GetU32 (&offset);
1047                             const uint32_t size = packet.GetU32 (&offset);
1048                             s.Printf(" (addr = 0x%8.8x, size = %u, bytes = \n", addr, size);
1049                             if (size > 0)
1050                                 DataExtractor::DumpHexBytes(&s, packet.GetData(&offset, size), size, 32, addr);
1051                         }
1052                         break;
1053 
1054                     case KDP_READMEM64:
1055                         {
1056                             const uint64_t addr = packet.GetU64 (&offset);
1057                             const uint32_t size = packet.GetU32 (&offset);
1058                             s.Printf(" (addr = 0x%16.16" PRIx64 ", size = %u)", addr, size);
1059                             m_last_read_memory_addr = addr;
1060                         }
1061                         break;
1062 
1063                     case KDP_READPHYSMEM64:
1064                         {
1065                             const uint64_t addr = packet.GetU64 (&offset);
1066                             const uint32_t size = packet.GetU32 (&offset);
1067                             const uint32_t lcpu = packet.GetU16 (&offset);
1068                             s.Printf(" (addr = 0x%16.16llx, size = %u, lcpu = %u)", addr, size, lcpu);
1069                             m_last_read_memory_addr = addr;
1070                         }
1071                         break;
1072 
1073                     case KDP_WRITEMEM64:
1074                         {
1075                             const uint64_t addr = packet.GetU64 (&offset);
1076                             const uint32_t size = packet.GetU32 (&offset);
1077                             s.Printf(" (addr = 0x%16.16" PRIx64 ", size = %u, bytes = \n", addr, size);
1078                             if (size > 0)
1079                                 DataExtractor::DumpHexBytes(&s, packet.GetData(&offset, size), size, 32, addr);
1080                         }
1081                         break;
1082 
1083                     case KDP_WRITEPHYSMEM64:
1084                         {
1085                             const uint64_t addr = packet.GetU64 (&offset);
1086                             const uint32_t size = packet.GetU32 (&offset);
1087                             const uint32_t lcpu = packet.GetU16 (&offset);
1088                             s.Printf(" (addr = 0x%16.16llx, size = %u, lcpu = %u, bytes = \n", addr, size, lcpu);
1089                             if (size > 0)
1090                                 DataExtractor::DumpHexBytes(&s, packet.GetData(&offset, size), size, 32, addr);
1091                         }
1092                         break;
1093 
1094                     case KDP_READREGS:
1095                         {
1096                             const uint32_t cpu = packet.GetU32 (&offset);
1097                             const uint32_t flavor = packet.GetU32 (&offset);
1098                             s.Printf(" (cpu = %u, flavor = %u)", cpu, flavor);
1099                         }
1100                         break;
1101 
1102                     case KDP_WRITEREGS:
1103                         {
1104                             const uint32_t cpu = packet.GetU32 (&offset);
1105                             const uint32_t flavor = packet.GetU32 (&offset);
1106                             const uint32_t nbytes = packet.GetByteSize() - offset;
1107                             s.Printf(" (cpu = %u, flavor = %u, regs = \n", cpu, flavor);
1108                             if (nbytes > 0)
1109                                 packet.Dump (&s,                        // Stream to dump to
1110                                              offset,                    // Offset within "packet"
1111                                              eFormatHex,                // Format to use
1112                                              m_addr_byte_size,          // Size of each item in bytes
1113                                              nbytes / m_addr_byte_size, // Number of items
1114                                              16 / m_addr_byte_size,     // Number per line
1115                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
1116                                              0, 0);                     // No bitfields
1117                         }
1118                         break;
1119 
1120 
1121                     case KDP_BREAKPOINT_SET:
1122                     case KDP_BREAKPOINT_REMOVE:
1123                         {
1124                             const uint32_t addr = packet.GetU32 (&offset);
1125                             s.Printf(" (addr = 0x%8.8x)", addr);
1126                         }
1127                         break;
1128 
1129                     case KDP_BREAKPOINT_SET64:
1130                     case KDP_BREAKPOINT_REMOVE64:
1131                         {
1132                             const uint64_t addr = packet.GetU64 (&offset);
1133                             s.Printf(" (addr = 0x%16.16" PRIx64 ")", addr);
1134                         }
1135                         break;
1136 
1137 
1138                     case KDP_LOAD:
1139                         {
1140                             const char *path = packet.GetCStr(&offset);
1141                             s.Printf(" (path = \"%s\")", path);
1142                         }
1143                         break;
1144 
1145                     case KDP_EXCEPTION:
1146                         {
1147                             const uint32_t count = packet.GetU32 (&offset);
1148 
1149                             for (uint32_t i=0; i<count; ++i)
1150                             {
1151                                 const uint32_t cpu = packet.GetU32 (&offset);
1152                                 const uint32_t exc = packet.GetU32 (&offset);
1153                                 const uint32_t code = packet.GetU32 (&offset);
1154                                 const uint32_t subcode = packet.GetU32 (&offset);
1155                                 const char *exc_cstr = NULL;
1156                                 switch (exc)
1157                                 {
1158                                     case 1:  exc_cstr = "EXC_BAD_ACCESS"; break;
1159                                     case 2:  exc_cstr = "EXC_BAD_INSTRUCTION"; break;
1160                                     case 3:  exc_cstr = "EXC_ARITHMETIC"; break;
1161                                     case 4:  exc_cstr = "EXC_EMULATION"; break;
1162                                     case 5:  exc_cstr = "EXC_SOFTWARE"; break;
1163                                     case 6:  exc_cstr = "EXC_BREAKPOINT"; break;
1164                                     case 7:  exc_cstr = "EXC_SYSCALL"; break;
1165                                     case 8:  exc_cstr = "EXC_MACH_SYSCALL"; break;
1166                                     case 9:  exc_cstr = "EXC_RPC_ALERT"; break;
1167                                     case 10: exc_cstr = "EXC_CRASH"; break;
1168                                     default:
1169                                         break;
1170                                 }
1171 
1172                                 s.Printf ("{ cpu = 0x%8.8x, exc = %s (%u), code = %u (0x%8.8x), subcode = %u (0x%8.8x)} ",
1173                                           cpu, exc_cstr, exc, code, code, subcode, subcode);
1174                             }
1175                         }
1176                         break;
1177 
1178                     case KDP_TERMINATION:
1179                         {
1180                             const uint32_t term_code = packet.GetU32 (&offset);
1181                             const uint32_t exit_code = packet.GetU32 (&offset);
1182                             s.Printf(" (term_code = 0x%8.8x (%u), exit_code = 0x%8.8x (%u))", term_code, term_code, exit_code, exit_code);
1183                         }
1184                         break;
1185 
1186                     case KDP_REATTACH:
1187                         {
1188                             const uint16_t reply_port = packet.GetU16 (&offset);
1189                             s.Printf(" (reply_port = %u)", reply_port);
1190                         }
1191                         break;
1192 
1193                     case KDP_READMSR64:
1194                         {
1195                             const uint32_t address = packet.GetU32 (&offset);
1196                             const uint16_t lcpu = packet.GetU16 (&offset);
1197                             s.Printf(" (address=0x%8.8x, lcpu=0x%4.4x)", address, lcpu);
1198                         }
1199                         break;
1200 
1201                     case KDP_WRITEMSR64:
1202                         {
1203                             const uint32_t address = packet.GetU32 (&offset);
1204                             const uint16_t lcpu = packet.GetU16 (&offset);
1205                             const uint32_t nbytes = packet.GetByteSize() - offset;
1206                             s.Printf(" (address=0x%8.8x, lcpu=0x%4.4x, nbytes=0x%8.8x)", lcpu, address, nbytes);
1207                             if (nbytes > 0)
1208                                 packet.Dump (&s,                        // Stream to dump to
1209                                              offset,                    // Offset within "packet"
1210                                              eFormatHex,                // Format to use
1211                                              1,                         // Size of each item in bytes
1212                                              nbytes,                    // Number of items
1213                                              16,                        // Number per line
1214                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
1215                                              0, 0);                     // No bitfields
1216                         }
1217                         break;
1218 
1219                     case KDP_READIOPORT:
1220                         {
1221                             const uint16_t lcpu = packet.GetU16 (&offset);
1222                             const uint16_t address = packet.GetU16 (&offset);
1223                             const uint16_t nbytes = packet.GetU16 (&offset);
1224                             s.Printf(" (lcpu=0x%4.4x, address=0x%4.4x, nbytes=%u)", lcpu, address, nbytes);
1225                         }
1226                         break;
1227 
1228                     case KDP_WRITEIOPORT:
1229                          {
1230                             const uint16_t lcpu = packet.GetU16 (&offset);
1231                             const uint16_t address = packet.GetU16 (&offset);
1232                             const uint16_t nbytes = packet.GetU16 (&offset);
1233                             s.Printf(" (lcpu = %u, addr = 0x%4.4x, nbytes = %u, bytes = \n", lcpu, address, nbytes);
1234                             if (nbytes > 0)
1235                                 packet.Dump (&s,                        // Stream to dump to
1236                                              offset,                    // Offset within "packet"
1237                                              eFormatHex,                // Format to use
1238                                              1,                         // Size of each item in bytes
1239                                              nbytes,                    // Number of items
1240                                              16,                        // Number per line
1241                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
1242                                              0, 0);                     // No bitfields
1243                         }
1244                         break;
1245 
1246                     case KDP_DUMPINFO:
1247                         {
1248                             const uint32_t count = packet.GetByteSize() - offset;
1249                             s.Printf(" (count = %u, bytes = \n", count);
1250                             if (count > 0)
1251                                 packet.Dump (&s,                        // Stream to dump to
1252                                              offset,                    // Offset within "packet"
1253                                              eFormatHex,                // Format to use
1254                                              1,                         // Size of each item in bytes
1255                                              count,                     // Number of items
1256                                              16,                        // Number per line
1257                                              LLDB_INVALID_ADDRESS,      // Don't show addresses before each line
1258                                              0, 0);                     // No bitfields
1259 
1260                         }
1261                         break;
1262 
1263                }
1264             }
1265         }
1266         else
1267         {
1268             error_desc = "error: invalid packet command: ";
1269         }
1270     }
1271 
1272     if (error_desc)
1273     {
1274         s.PutCString (error_desc);
1275 
1276         packet.Dump (&s,                    // Stream to dump to
1277                      0,                     // Offset into "packet"
1278                      eFormatBytes,          // Dump as hex bytes
1279                      1,                     // Size of each item is 1 for single bytes
1280                      packet.GetByteSize(),  // Number of bytes
1281                      UINT32_MAX,            // Num bytes per line
1282                      LLDB_INVALID_ADDRESS,  // Base address
1283                      0, 0);                 // Bitfield info set to not do anything bitfield related
1284     }
1285 }
1286 
1287 uint32_t
1288 CommunicationKDP::SendRequestReadRegisters (uint32_t cpu,
1289                                             uint32_t flavor,
1290                                             void *dst,
1291                                             uint32_t dst_len,
1292                                             Error &error)
1293 {
1294     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
1295     const CommandType command = KDP_READREGS;
1296     // Size is header + 4 byte cpu and 4 byte flavor
1297     const uint32_t command_length = 8 + 4 + 4;
1298     MakeRequestPacketHeader (command, request_packet, command_length);
1299     request_packet.PutHex32 (cpu);
1300     request_packet.PutHex32 (flavor);
1301     DataExtractor reply_packet;
1302     if (SendRequestAndGetReply (command, request_packet, reply_packet))
1303     {
1304         lldb::offset_t offset = 8;
1305         uint32_t kdp_error = reply_packet.GetU32 (&offset);
1306         uint32_t src_len = reply_packet.GetByteSize() - 12;
1307 
1308         if (src_len > 0)
1309         {
1310             const uint32_t bytes_to_copy = std::min<uint32_t>(src_len, dst_len);
1311             const void *src = reply_packet.GetData(&offset, bytes_to_copy);
1312             if (src)
1313             {
1314                 ::memcpy (dst, src, bytes_to_copy);
1315                 error.Clear();
1316                 // Return the number of bytes we could have returned regardless if
1317                 // we copied them or not, just so we know when things don't match up
1318                 return src_len;
1319             }
1320         }
1321         if (kdp_error)
1322             error.SetErrorStringWithFormat("failed to read kdp registers for cpu %u flavor %u (error %u)", cpu, flavor, kdp_error);
1323         else
1324             error.SetErrorStringWithFormat("failed to read kdp registers for cpu %u flavor %u", cpu, flavor);
1325     }
1326     else
1327     {
1328         error.SetErrorString ("failed to send packet");
1329     }
1330     return 0;
1331 }
1332 
1333 uint32_t
1334 CommunicationKDP::SendRequestWriteRegisters (uint32_t cpu,
1335                                              uint32_t flavor,
1336                                              const void *src,
1337                                              uint32_t src_len,
1338                                              Error &error)
1339 {
1340     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
1341     const CommandType command = KDP_WRITEREGS;
1342     // Size is header + 4 byte cpu and 4 byte flavor
1343     const uint32_t command_length = 8 + 4 + 4 + src_len;
1344     MakeRequestPacketHeader (command, request_packet, command_length);
1345     request_packet.PutHex32 (cpu);
1346     request_packet.PutHex32 (flavor);
1347     request_packet.Write(src, src_len);
1348     DataExtractor reply_packet;
1349     if (SendRequestAndGetReply (command, request_packet, reply_packet))
1350     {
1351         lldb::offset_t offset = 8;
1352         uint32_t kdp_error = reply_packet.GetU32 (&offset);
1353         if (kdp_error == 0)
1354             return src_len;
1355         error.SetErrorStringWithFormat("failed to read kdp registers for cpu %u flavor %u (error %u)", cpu, flavor, kdp_error);
1356     }
1357     else
1358     {
1359         error.SetErrorString ("failed to send packet");
1360     }
1361     return 0;
1362 }
1363 
1364 
1365 bool
1366 CommunicationKDP::SendRequestResume ()
1367 {
1368     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
1369     const CommandType command = KDP_RESUMECPUS;
1370     const uint32_t command_length = 12;
1371     MakeRequestPacketHeader (command, request_packet, command_length);
1372     request_packet.PutHex32(GetCPUMask());
1373 
1374     DataExtractor reply_packet;
1375     if (SendRequestAndGetReply (command, request_packet, reply_packet))
1376         return true;
1377     return false;
1378 }
1379 
1380 bool
1381 CommunicationKDP::SendRequestBreakpoint (bool set, addr_t addr)
1382 {
1383     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
1384     bool use_64 = (GetVersion() >= 11);
1385     uint32_t command_addr_byte_size = use_64 ? 8 : 4;
1386     const CommandType command = set ? (use_64 ? KDP_BREAKPOINT_SET64    : KDP_BREAKPOINT_SET   ):
1387                                       (use_64 ? KDP_BREAKPOINT_REMOVE64 : KDP_BREAKPOINT_REMOVE);
1388 
1389     const uint32_t command_length = 8 + command_addr_byte_size;
1390     MakeRequestPacketHeader (command, request_packet, command_length);
1391     request_packet.PutMaxHex64 (addr, command_addr_byte_size);
1392 
1393     DataExtractor reply_packet;
1394     if (SendRequestAndGetReply (command, request_packet, reply_packet))
1395     {
1396         lldb::offset_t offset = 8;
1397         uint32_t kdp_error = reply_packet.GetU32 (&offset);
1398         if (kdp_error == 0)
1399             return true;
1400     }
1401     return false;
1402 }
1403 
1404 bool
1405 CommunicationKDP::SendRequestSuspend ()
1406 {
1407     PacketStreamType request_packet (Stream::eBinary, m_addr_byte_size, m_byte_order);
1408     const CommandType command = KDP_SUSPEND;
1409     const uint32_t command_length = 8;
1410     MakeRequestPacketHeader (command, request_packet, command_length);
1411     DataExtractor reply_packet;
1412     if (SendRequestAndGetReply (command, request_packet, reply_packet))
1413         return true;
1414     return false;
1415 }
1416 
1417