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