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