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/DumpDataExtractor.h"
21 #include "lldb/Core/State.h"
22 #include "lldb/Host/Host.h"
23 #include "lldb/Target/Process.h"
24 #include "lldb/Utility/DataBufferHeap.h"
25 #include "lldb/Utility/DataExtractor.h"
26 #include "lldb/Utility/FileSpec.h"
27 #include "lldb/Utility/Log.h"
28 #include "lldb/Utility/UUID.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,
111                 std::chrono::microseconds(GetPacketTimeout()).count())) {
112           offset = 0;
113           const uint8_t reply_command = reply_packet.GetU8(&offset);
114           const uint8_t reply_sequence_id = reply_packet.GetU8(&offset);
115           if (request_sequence_id == reply_sequence_id) {
116             // The sequent ID was correct, now verify we got the response we
117             // were looking for
118             if ((reply_command & eCommandTypeMask) == command) {
119               // Success
120               if (command == KDP_RESUMECPUS)
121                 m_is_running.SetValue(true, eBroadcastAlways);
122               return true;
123             } else {
124               // Failed to get the correct response, bail
125               reply_packet.Clear();
126               return false;
127             }
128           } else if (reply_sequence_id > request_sequence_id) {
129             // Sequence ID was greater than the sequence ID of the packet we
130             // sent, something
131             // is really wrong...
132             reply_packet.Clear();
133             return false;
134           } else {
135             // The reply sequence ID was less than our current packet's sequence
136             // ID
137             // so we should keep trying to get a response because this was a
138             // response
139             // for a previous packet that we must have retried.
140           }
141         } else {
142           // Break and retry sending the packet as we didn't get a response due
143           // to timeout
144           break;
145         }
146       }
147     }
148   }
149   reply_packet.Clear();
150   return false;
151 }
152 
153 bool CommunicationKDP::SendRequestPacketNoLock(
154     const PacketStreamType &request_packet) {
155   if (IsConnected()) {
156     const char *packet_data = request_packet.GetData();
157     const size_t packet_size = request_packet.GetSize();
158 
159     Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PACKETS));
160     if (log) {
161       PacketStreamType log_strm;
162       DumpPacket(log_strm, packet_data, packet_size);
163       log->Printf("%.*s", (uint32_t)log_strm.GetSize(), log_strm.GetData());
164     }
165     ConnectionStatus status = eConnectionStatusSuccess;
166 
167     size_t bytes_written = Write(packet_data, packet_size, status, NULL);
168 
169     if (bytes_written == packet_size)
170       return true;
171 
172     if (log)
173       log->Printf("error: failed to send packet entire packet %" PRIu64
174                   " of %" PRIu64 " bytes sent",
175                   (uint64_t)bytes_written, (uint64_t)packet_size);
176   }
177   return false;
178 }
179 
180 bool CommunicationKDP::GetSequenceMutex(
181     std::unique_lock<std::recursive_mutex> &lock) {
182   return (lock = std::unique_lock<std::recursive_mutex>(m_sequence_mutex,
183                                                         std::try_to_lock))
184       .owns_lock();
185 }
186 
187 bool CommunicationKDP::WaitForNotRunningPrivate(
188     const std::chrono::microseconds &timeout) {
189   return m_is_running.WaitForValueEqualTo(false, timeout, NULL);
190 }
191 
192 size_t
193 CommunicationKDP::WaitForPacketWithTimeoutMicroSeconds(DataExtractor &packet,
194                                                        uint32_t timeout_usec) {
195   std::lock_guard<std::recursive_mutex> guard(m_sequence_mutex);
196   return WaitForPacketWithTimeoutMicroSecondsNoLock(packet, timeout_usec);
197 }
198 
199 size_t CommunicationKDP::WaitForPacketWithTimeoutMicroSecondsNoLock(
200     DataExtractor &packet, uint32_t timeout_usec) {
201   uint8_t buffer[8192];
202   Error error;
203 
204   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PACKETS));
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 = Read(buffer, sizeof(buffer),
214                              timeout_usec == UINT32_MAX
215                                  ? Timeout<std::micro>(llvm::None)
216                                  : std::chrono::microseconds(timeout_usec),
217                              status, &error);
218 
219     LLDB_LOGV(log,
220       "Read (buffer, sizeof(buffer), timeout_usec = 0x{0:x}, "
221                   "status = {1}, error = {2}) => bytes_read = {4}",
222                   timeout_usec,
223                   Communication::ConnectionStatusAsCString(status),
224                   error, bytes_read);
225 
226     if (bytes_read > 0) {
227       if (CheckForPacket(buffer, bytes_read, packet))
228         return packet.GetByteSize();
229     } else {
230       switch (status) {
231       case eConnectionStatusInterrupted:
232       case eConnectionStatusTimedOut:
233         timed_out = true;
234         break;
235       case eConnectionStatusSuccess:
236         // printf ("status = success but error = %s\n",
237         // error.AsCString("<invalid>"));
238         break;
239 
240       case eConnectionStatusEndOfFile:
241       case eConnectionStatusNoConnection:
242       case eConnectionStatusLostConnection:
243       case eConnectionStatusError:
244         Disconnect();
245         break;
246       }
247     }
248   }
249   packet.Clear();
250   return 0;
251 }
252 
253 bool CommunicationKDP::CheckForPacket(const uint8_t *src, size_t src_len,
254                                       DataExtractor &packet) {
255   // Put the packet data into the buffer in a thread safe fashion
256   std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
257 
258   Log *log(ProcessKDPLog::GetLogIfAllCategoriesSet(KDP_LOG_PACKETS));
259 
260   if (src && src_len > 0) {
261     if (log && log->GetVerbose()) {
262       PacketStreamType log_strm;
263       DumpHexBytes(&log_strm, src, src_len, UINT32_MAX, 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             DumpDataExtractor(packet,
863                               &s,                      // Stream to dump to
864                               offset,                  // Offset within "packet"
865                               eFormatBytesWithASCII,   // Format to use
866                               1,                       // Size of each item
867                                                        // in bytes
868                               count,                   // Number of items
869                               16,                      // Number per line
870                               m_last_read_memory_addr, // Don't show addresses
871                                                        // before each line
872                               0, 0);                   // No bitfields
873         } break;
874 
875         case KDP_READREGS: {
876           const uint32_t error = packet.GetU32(&offset);
877           const uint32_t count = packet.GetByteSize() - offset;
878           s.Printf(" (error = 0x%8.8x regs:\n", error);
879           if (count > 0)
880             DumpDataExtractor(packet,
881                               &s,                       // Stream to dump to
882                               offset,                   // Offset within "packet"
883                               eFormatHex,               // Format to use
884                               m_addr_byte_size,         // Size of each item
885                                                         // in bytes
886                               count / m_addr_byte_size, // Number of items
887                               16 / m_addr_byte_size,    // Number per line
888                               LLDB_INVALID_ADDRESS,
889                                                         // Don't
890                                                         // show addresses before
891                                                         // each line
892                               0, 0);                    // No bitfields
893         } break;
894 
895         case KDP_KERNELVERSION: {
896           const char *kernel_version = packet.PeekCStr(8);
897           s.Printf(" (version = \"%s\")", kernel_version);
898         } break;
899 
900         case KDP_MAXBYTES: {
901           const uint32_t max_bytes = packet.GetU32(&offset);
902           s.Printf(" (max_bytes = 0x%8.8x (%u))", max_bytes, max_bytes);
903         } break;
904         case KDP_IMAGEPATH: {
905           const char *path = packet.GetCStr(&offset);
906           s.Printf(" (path = \"%s\")", path);
907         } break;
908 
909         case KDP_READIOPORT:
910         case KDP_READMSR64: {
911           const uint32_t error = packet.GetU32(&offset);
912           const uint32_t count = packet.GetByteSize() - offset;
913           s.Printf(" (error = 0x%8.8x io:\n", error);
914           if (count > 0)
915             DumpDataExtractor(packet,
916                               &s,                   // Stream to dump to
917                               offset,               // Offset within "packet"
918                               eFormatHex,           // Format to use
919                               1,                    // Size of each item in bytes
920                               count,                // Number of items
921                               16,                   // Number per line
922                               LLDB_INVALID_ADDRESS, // Don't show addresses
923                                                     // before each line
924                               0, 0);                // No bitfields
925         } break;
926         case KDP_DUMPINFO: {
927           const uint32_t count = packet.GetByteSize() - offset;
928           s.Printf(" (count = %u, bytes = \n", count);
929           if (count > 0)
930             DumpDataExtractor(packet,
931                               &s,                   // Stream to dump to
932                               offset,               // Offset within "packet"
933                               eFormatHex,           // Format to use
934                               1,                    // Size of each item in
935                                                     // bytes
936                               count,                // Number of items
937                               16,                   // Number per line
938                               LLDB_INVALID_ADDRESS, // Don't show addresses
939                                                     // before each line
940                               0, 0);                // No bitfields
941 
942         } break;
943 
944         default:
945           s.Printf(" (add support for dumping this packet reply!!!");
946           break;
947         }
948       } else {
949         // Dump request packets
950         switch (command) {
951         case KDP_CONNECT: {
952           const uint16_t reply_port = ntohs(packet.GetU16(&offset));
953           const uint16_t exc_port = ntohs(packet.GetU16(&offset));
954           s.Printf(" (reply_port = %u, exc_port = %u, greeting = \"%s\")",
955                    reply_port, exc_port, packet.GetCStr(&offset));
956         } break;
957 
958         case KDP_DISCONNECT:
959         case KDP_HOSTREBOOT:
960         case KDP_HOSTINFO:
961         case KDP_VERSION:
962         case KDP_REGIONS:
963         case KDP_KERNELVERSION:
964         case KDP_MAXBYTES:
965         case KDP_IMAGEPATH:
966         case KDP_SUSPEND:
967           // No args, just the header in the request...
968           s.PutCString(" ()");
969           break;
970 
971         case KDP_RESUMECPUS: {
972           const uint32_t cpu_mask = packet.GetU32(&offset);
973           s.Printf(" (cpu_mask = 0x%8.8x)", cpu_mask);
974         } break;
975 
976         case KDP_READMEM: {
977           const uint32_t addr = packet.GetU32(&offset);
978           const uint32_t size = packet.GetU32(&offset);
979           s.Printf(" (addr = 0x%8.8x, size = %u)", addr, size);
980           m_last_read_memory_addr = addr;
981         } break;
982 
983         case KDP_WRITEMEM: {
984           const uint32_t addr = packet.GetU32(&offset);
985           const uint32_t size = packet.GetU32(&offset);
986           s.Printf(" (addr = 0x%8.8x, size = %u, bytes = \n", addr, size);
987           if (size > 0)
988             DumpHexBytes(&s, packet.GetData(&offset, size), size, 32, addr);
989         } break;
990 
991         case KDP_READMEM64: {
992           const uint64_t addr = packet.GetU64(&offset);
993           const uint32_t size = packet.GetU32(&offset);
994           s.Printf(" (addr = 0x%16.16" PRIx64 ", size = %u)", addr, size);
995           m_last_read_memory_addr = addr;
996         } break;
997 
998         case KDP_READPHYSMEM64: {
999           const uint64_t addr = packet.GetU64(&offset);
1000           const uint32_t size = packet.GetU32(&offset);
1001           const uint32_t lcpu = packet.GetU16(&offset);
1002           s.Printf(" (addr = 0x%16.16llx, size = %u, lcpu = %u)", addr, size,
1003                    lcpu);
1004           m_last_read_memory_addr = addr;
1005         } break;
1006 
1007         case KDP_WRITEMEM64: {
1008           const uint64_t addr = packet.GetU64(&offset);
1009           const uint32_t size = packet.GetU32(&offset);
1010           s.Printf(" (addr = 0x%16.16" PRIx64 ", size = %u, bytes = \n", addr,
1011                    size);
1012           if (size > 0)
1013             DumpHexBytes(&s, packet.GetData(&offset, size), size, 32, addr);
1014         } break;
1015 
1016         case KDP_WRITEPHYSMEM64: {
1017           const uint64_t addr = packet.GetU64(&offset);
1018           const uint32_t size = packet.GetU32(&offset);
1019           const uint32_t lcpu = packet.GetU16(&offset);
1020           s.Printf(" (addr = 0x%16.16llx, size = %u, lcpu = %u, bytes = \n",
1021                    addr, size, lcpu);
1022           if (size > 0)
1023             DumpHexBytes(&s, packet.GetData(&offset, size), size, 32, addr);
1024         } break;
1025 
1026         case KDP_READREGS: {
1027           const uint32_t cpu = packet.GetU32(&offset);
1028           const uint32_t flavor = packet.GetU32(&offset);
1029           s.Printf(" (cpu = %u, flavor = %u)", cpu, flavor);
1030         } break;
1031 
1032         case KDP_WRITEREGS: {
1033           const uint32_t cpu = packet.GetU32(&offset);
1034           const uint32_t flavor = packet.GetU32(&offset);
1035           const uint32_t nbytes = packet.GetByteSize() - offset;
1036           s.Printf(" (cpu = %u, flavor = %u, regs = \n", cpu, flavor);
1037           if (nbytes > 0)
1038             DumpDataExtractor(packet,
1039                               &s,                        // Stream to dump to
1040                               offset,                    // Offset within
1041                                                          // "packet"
1042                               eFormatHex,                // Format to use
1043                               m_addr_byte_size,          // Size of each item in
1044                                                          // bytes
1045                               nbytes / m_addr_byte_size, // Number of items
1046                               16 / m_addr_byte_size,     // Number per line
1047                               LLDB_INVALID_ADDRESS,      // Don't show addresses
1048                                                          // before each line
1049                               0, 0);                // No bitfields
1050         } break;
1051 
1052         case KDP_BREAKPOINT_SET:
1053         case KDP_BREAKPOINT_REMOVE: {
1054           const uint32_t addr = packet.GetU32(&offset);
1055           s.Printf(" (addr = 0x%8.8x)", addr);
1056         } break;
1057 
1058         case KDP_BREAKPOINT_SET64:
1059         case KDP_BREAKPOINT_REMOVE64: {
1060           const uint64_t addr = packet.GetU64(&offset);
1061           s.Printf(" (addr = 0x%16.16" PRIx64 ")", addr);
1062         } break;
1063 
1064         case KDP_LOAD: {
1065           const char *path = packet.GetCStr(&offset);
1066           s.Printf(" (path = \"%s\")", path);
1067         } break;
1068 
1069         case KDP_EXCEPTION: {
1070           const uint32_t count = packet.GetU32(&offset);
1071 
1072           for (uint32_t i = 0; i < count; ++i) {
1073             const uint32_t cpu = packet.GetU32(&offset);
1074             const uint32_t exc = packet.GetU32(&offset);
1075             const uint32_t code = packet.GetU32(&offset);
1076             const uint32_t subcode = packet.GetU32(&offset);
1077             const char *exc_cstr = NULL;
1078             switch (exc) {
1079             case 1:
1080               exc_cstr = "EXC_BAD_ACCESS";
1081               break;
1082             case 2:
1083               exc_cstr = "EXC_BAD_INSTRUCTION";
1084               break;
1085             case 3:
1086               exc_cstr = "EXC_ARITHMETIC";
1087               break;
1088             case 4:
1089               exc_cstr = "EXC_EMULATION";
1090               break;
1091             case 5:
1092               exc_cstr = "EXC_SOFTWARE";
1093               break;
1094             case 6:
1095               exc_cstr = "EXC_BREAKPOINT";
1096               break;
1097             case 7:
1098               exc_cstr = "EXC_SYSCALL";
1099               break;
1100             case 8:
1101               exc_cstr = "EXC_MACH_SYSCALL";
1102               break;
1103             case 9:
1104               exc_cstr = "EXC_RPC_ALERT";
1105               break;
1106             case 10:
1107               exc_cstr = "EXC_CRASH";
1108               break;
1109             default:
1110               break;
1111             }
1112 
1113             s.Printf("{ cpu = 0x%8.8x, exc = %s (%u), code = %u (0x%8.8x), "
1114                      "subcode = %u (0x%8.8x)} ",
1115                      cpu, exc_cstr, exc, code, code, subcode, subcode);
1116           }
1117         } break;
1118 
1119         case KDP_TERMINATION: {
1120           const uint32_t term_code = packet.GetU32(&offset);
1121           const uint32_t exit_code = packet.GetU32(&offset);
1122           s.Printf(" (term_code = 0x%8.8x (%u), exit_code = 0x%8.8x (%u))",
1123                    term_code, term_code, exit_code, exit_code);
1124         } break;
1125 
1126         case KDP_REATTACH: {
1127           const uint16_t reply_port = ntohs(packet.GetU16(&offset));
1128           s.Printf(" (reply_port = %u)", reply_port);
1129         } break;
1130 
1131         case KDP_READMSR64: {
1132           const uint32_t address = packet.GetU32(&offset);
1133           const uint16_t lcpu = packet.GetU16(&offset);
1134           s.Printf(" (address=0x%8.8x, lcpu=0x%4.4x)", address, lcpu);
1135         } break;
1136 
1137         case KDP_WRITEMSR64: {
1138           const uint32_t address = packet.GetU32(&offset);
1139           const uint16_t lcpu = packet.GetU16(&offset);
1140           const uint32_t nbytes = packet.GetByteSize() - offset;
1141           s.Printf(" (address=0x%8.8x, lcpu=0x%4.4x, nbytes=0x%8.8x)", lcpu,
1142                    address, nbytes);
1143           if (nbytes > 0)
1144             DumpDataExtractor(packet,
1145                               &s,                   // Stream to dump to
1146                               offset,               // Offset within "packet"
1147                               eFormatHex,           // Format to use
1148                               1,                    // Size of each item in
1149                                                     // bytes
1150                               nbytes,               // Number of items
1151                               16,                   // Number per line
1152                               LLDB_INVALID_ADDRESS, // Don't show addresses
1153                                                     // before each line
1154                               0, 0);                // No bitfields
1155         } break;
1156 
1157         case KDP_READIOPORT: {
1158           const uint16_t lcpu = packet.GetU16(&offset);
1159           const uint16_t address = packet.GetU16(&offset);
1160           const uint16_t nbytes = packet.GetU16(&offset);
1161           s.Printf(" (lcpu=0x%4.4x, address=0x%4.4x, nbytes=%u)", lcpu, address,
1162                    nbytes);
1163         } break;
1164 
1165         case KDP_WRITEIOPORT: {
1166           const uint16_t lcpu = packet.GetU16(&offset);
1167           const uint16_t address = packet.GetU16(&offset);
1168           const uint16_t nbytes = packet.GetU16(&offset);
1169           s.Printf(" (lcpu = %u, addr = 0x%4.4x, nbytes = %u, bytes = \n", lcpu,
1170                    address, nbytes);
1171           if (nbytes > 0)
1172             DumpDataExtractor(packet,
1173                               &s,                   // Stream to dump to
1174                               offset,               // Offset within "packet"
1175                               eFormatHex,           // Format to use
1176                               1,                    // Size of each item in
1177                                                     // bytes
1178                               nbytes,               // Number of items
1179                               16,                   // Number per line
1180                               LLDB_INVALID_ADDRESS, // Don't show addresses
1181                                                     // before each line
1182                               0, 0);                // No bitfields
1183         } break;
1184 
1185         case KDP_DUMPINFO: {
1186           const uint32_t count = packet.GetByteSize() - offset;
1187           s.Printf(" (count = %u, bytes = \n", count);
1188           if (count > 0)
1189             DumpDataExtractor(packet,
1190                 &s,                   // Stream to dump to
1191                 offset,               // Offset within "packet"
1192                 eFormatHex,           // Format to use
1193                 1,                    // Size of each item in bytes
1194                 count,                // Number of items
1195                 16,                   // Number per line
1196                 LLDB_INVALID_ADDRESS, // Don't show addresses before each line
1197                 0, 0);                // No bitfields
1198 
1199         } break;
1200         }
1201       }
1202     } else {
1203       error_desc = "error: invalid packet command: ";
1204     }
1205   }
1206 
1207   if (error_desc) {
1208     s.PutCString(error_desc);
1209 
1210     DumpDataExtractor(packet,
1211                       &s,                   // Stream to dump to
1212                       0,                    // Offset into "packet"
1213                       eFormatBytes,         // Dump as hex bytes
1214                       1,                    // Size of each item is 1 for
1215                                             // single bytes
1216                       packet.GetByteSize(), // Number of bytes
1217                       UINT32_MAX,           // Num bytes per line
1218                       LLDB_INVALID_ADDRESS, // Base address
1219                       0, 0);                // Bitfield info set to not do
1220                                             // anything bitfield related
1221   }
1222 }
1223 
1224 uint32_t CommunicationKDP::SendRequestReadRegisters(uint32_t cpu,
1225                                                     uint32_t flavor, void *dst,
1226                                                     uint32_t dst_len,
1227                                                     Error &error) {
1228   PacketStreamType request_packet(Stream::eBinary, m_addr_byte_size,
1229                                   m_byte_order);
1230   const CommandType command = KDP_READREGS;
1231   // Size is header + 4 byte cpu and 4 byte flavor
1232   const uint32_t command_length = 8 + 4 + 4;
1233   MakeRequestPacketHeader(command, request_packet, command_length);
1234   request_packet.PutHex32(cpu);
1235   request_packet.PutHex32(flavor);
1236   DataExtractor reply_packet;
1237   if (SendRequestAndGetReply(command, request_packet, reply_packet)) {
1238     lldb::offset_t offset = 8;
1239     uint32_t kdp_error = reply_packet.GetU32(&offset);
1240     uint32_t src_len = reply_packet.GetByteSize() - 12;
1241 
1242     if (src_len > 0) {
1243       const uint32_t bytes_to_copy = std::min<uint32_t>(src_len, dst_len);
1244       const void *src = reply_packet.GetData(&offset, bytes_to_copy);
1245       if (src) {
1246         ::memcpy(dst, src, bytes_to_copy);
1247         error.Clear();
1248         // Return the number of bytes we could have returned regardless if
1249         // we copied them or not, just so we know when things don't match up
1250         return src_len;
1251       }
1252     }
1253     if (kdp_error)
1254       error.SetErrorStringWithFormat(
1255           "failed to read kdp registers for cpu %u flavor %u (error %u)", cpu,
1256           flavor, kdp_error);
1257     else
1258       error.SetErrorStringWithFormat(
1259           "failed to read kdp registers for cpu %u flavor %u", cpu, flavor);
1260   } else {
1261     error.SetErrorString("failed to send packet");
1262   }
1263   return 0;
1264 }
1265 
1266 uint32_t CommunicationKDP::SendRequestWriteRegisters(uint32_t cpu,
1267                                                      uint32_t flavor,
1268                                                      const void *src,
1269                                                      uint32_t src_len,
1270                                                      Error &error) {
1271   PacketStreamType request_packet(Stream::eBinary, m_addr_byte_size,
1272                                   m_byte_order);
1273   const CommandType command = KDP_WRITEREGS;
1274   // Size is header + 4 byte cpu and 4 byte flavor
1275   const uint32_t command_length = 8 + 4 + 4 + src_len;
1276   MakeRequestPacketHeader(command, request_packet, command_length);
1277   request_packet.PutHex32(cpu);
1278   request_packet.PutHex32(flavor);
1279   request_packet.Write(src, src_len);
1280   DataExtractor reply_packet;
1281   if (SendRequestAndGetReply(command, request_packet, reply_packet)) {
1282     lldb::offset_t offset = 8;
1283     uint32_t kdp_error = reply_packet.GetU32(&offset);
1284     if (kdp_error == 0)
1285       return src_len;
1286     error.SetErrorStringWithFormat(
1287         "failed to read kdp registers for cpu %u flavor %u (error %u)", cpu,
1288         flavor, kdp_error);
1289   } else {
1290     error.SetErrorString("failed to send packet");
1291   }
1292   return 0;
1293 }
1294 
1295 bool CommunicationKDP::SendRequestResume() {
1296   PacketStreamType request_packet(Stream::eBinary, m_addr_byte_size,
1297                                   m_byte_order);
1298   const CommandType command = KDP_RESUMECPUS;
1299   const uint32_t command_length = 12;
1300   MakeRequestPacketHeader(command, request_packet, command_length);
1301   request_packet.PutHex32(GetCPUMask());
1302 
1303   DataExtractor reply_packet;
1304   if (SendRequestAndGetReply(command, request_packet, reply_packet))
1305     return true;
1306   return false;
1307 }
1308 
1309 bool CommunicationKDP::SendRequestBreakpoint(bool set, addr_t addr) {
1310   PacketStreamType request_packet(Stream::eBinary, m_addr_byte_size,
1311                                   m_byte_order);
1312   bool use_64 = (GetVersion() >= 11);
1313   uint32_t command_addr_byte_size = use_64 ? 8 : 4;
1314   const CommandType command =
1315       set ? (use_64 ? KDP_BREAKPOINT_SET64 : KDP_BREAKPOINT_SET)
1316           : (use_64 ? KDP_BREAKPOINT_REMOVE64 : KDP_BREAKPOINT_REMOVE);
1317 
1318   const uint32_t command_length = 8 + command_addr_byte_size;
1319   MakeRequestPacketHeader(command, request_packet, command_length);
1320   request_packet.PutMaxHex64(addr, command_addr_byte_size);
1321 
1322   DataExtractor reply_packet;
1323   if (SendRequestAndGetReply(command, request_packet, reply_packet)) {
1324     lldb::offset_t offset = 8;
1325     uint32_t kdp_error = reply_packet.GetU32(&offset);
1326     if (kdp_error == 0)
1327       return true;
1328   }
1329   return false;
1330 }
1331 
1332 bool CommunicationKDP::SendRequestSuspend() {
1333   PacketStreamType request_packet(Stream::eBinary, m_addr_byte_size,
1334                                   m_byte_order);
1335   const CommandType command = KDP_SUSPEND;
1336   const uint32_t command_length = 8;
1337   MakeRequestPacketHeader(command, request_packet, command_length);
1338   DataExtractor reply_packet;
1339   if (SendRequestAndGetReply(command, request_packet, reply_packet))
1340     return true;
1341   return false;
1342 }
1343