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