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