1 
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  Created by Greg Clayton on 12/12/07.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLDB_TOOLS_DEBUGSERVER_SOURCE_RNBREMOTE_H
14 #define LLDB_TOOLS_DEBUGSERVER_SOURCE_RNBREMOTE_H
15 
16 #include "DNB.h"
17 #include "PThreadMutex.h"
18 #include "RNBContext.h"
19 #include "RNBDefs.h"
20 #include "RNBSocket.h"
21 #include <deque>
22 #include <map>
23 #include <string>
24 #include <vector>
25 
26 class RNBSocket;
27 class RNBContext;
28 class PThreadEvents;
29 
30 enum event_loop_mode { debug_nub, gdb_remote_protocol, done };
31 
32 enum class compression_types { zlib_deflate, lz4, lzma, lzfse, none };
33 
34 class RNBRemote {
35 public:
36   enum PacketEnum {
37     invalid_packet = 0,
38     ack,                           // '+'
39     nack,                          // '-'
40     halt,                          // ^C  (async halt)
41     use_extended_mode,             // '!'
42     why_halted,                    // '?'
43     set_argv,                      // 'A'
44     set_bp,                        // 'B'
45     cont,                          // 'c'
46     continue_with_sig,             // 'C'
47     detach,                        // 'D'
48     read_general_regs,             // 'g'
49     write_general_regs,            // 'G'
50     set_thread,                    // 'H'
51     step_inferior_one_cycle,       // 'i'
52     signal_and_step_inf_one_cycle, // 'I'
53     kill,                          // 'k'
54     read_memory,                   // 'm'
55     write_memory,                  // 'M'
56     read_register,                 // 'p'
57     write_register,                // 'P'
58     restart,                       // 'R'
59     single_step,                   // 's'
60     single_step_with_sig,          // 'S'
61     search_mem_backwards,          // 't'
62     thread_alive_p,                // 'T'
63     vattach,                       // 'vAttach;pid'
64     vattachwait,   // 'vAttachWait:XX...' where XX is one or more hex encoded
65                    // process name ASCII bytes
66     vattachorwait, // 'vAttachOrWait:XX...' where XX is one or more hex encoded
67                    // process name ASCII bytes
68     vattachname,   // 'vAttachName:XX...' where XX is one or more hex encoded
69                    // process name ASCII bytes
70     vcont,         // 'vCont'
71     vcont_list_actions,     // 'vCont?'
72     read_data_from_memory,  // 'x'
73     write_data_to_memory,   // 'X'
74     insert_mem_bp,          // 'Z0'
75     remove_mem_bp,          // 'z0'
76     insert_hardware_bp,     // 'Z1'
77     remove_hardware_bp,     // 'z1'
78     insert_write_watch_bp,  // 'Z2'
79     remove_write_watch_bp,  // 'z2'
80     insert_read_watch_bp,   // 'Z3'
81     remove_read_watch_bp,   // 'z3'
82     insert_access_watch_bp, // 'Z4'
83     remove_access_watch_bp, // 'z4'
84 
85     query_monitor,                                 // 'qRcmd'
86     query_current_thread_id,                       // 'qC'
87     query_get_pid,                                 // 'qGetPid'
88     query_echo,                                    // 'qEcho'
89     query_thread_ids_first,                        // 'qfThreadInfo'
90     query_thread_ids_subsequent,                   // 'qsThreadInfo'
91     query_thread_extra_info,                       // 'qThreadExtraInfo'
92     query_thread_stop_info,                        // 'qThreadStopInfo'
93     query_image_offsets,                           // 'qOffsets'
94     query_symbol_lookup,                           // 'qSymbol'
95     query_launch_success,                          // 'qLaunchSuccess'
96     query_register_info,                           // 'qRegisterInfo'
97     query_shlib_notify_info_addr,                  // 'qShlibInfoAddr'
98     query_step_packet_supported,                   // 'qStepPacketSupported'
99     query_supported_features,                      // 'qSupported'
100     query_vattachorwait_supported,                 // 'qVAttachOrWaitSupported'
101     query_sync_thread_state_supported,             // 'QSyncThreadState'
102     query_host_info,                               // 'qHostInfo'
103     query_gdb_server_version,                      // 'qGDBServerVersion'
104     query_process_info,                            // 'qProcessInfo'
105     json_query_thread_extended_info,               // 'jThreadExtendedInfo'
106     json_query_get_loaded_dynamic_libraries_infos, // 'jGetLoadedDynamicLibrariesInfos'
107     json_query_threads_info,                       // 'jThreadsInfo'
108     json_query_get_shared_cache_info,              // 'jGetSharedCacheInfo'
109     pass_signals_to_inferior,                      // 'QPassSignals'
110     start_noack_mode,                              // 'QStartNoAckMode'
111     prefix_reg_packets_with_tid,        // 'QPrefixRegisterPacketsWithThreadID
112     set_logging_mode,                   // 'QSetLogging:'
113     set_max_packet_size,                // 'QSetMaxPacketSize:'
114     set_max_payload_size,               // 'QSetMaxPayloadSize:'
115     set_environment_variable,           // 'QEnvironment:'
116     set_environment_variable_hex,       // 'QEnvironmentHexEncoded:'
117     set_launch_arch,                    // 'QLaunchArch:'
118     set_disable_aslr,                   // 'QSetDisableASLR:'
119     set_stdin,                          // 'QSetSTDIN:'
120     set_stdout,                         // 'QSetSTDOUT:'
121     set_stderr,                         // 'QSetSTDERR:'
122     set_working_dir,                    // 'QSetWorkingDir:'
123     set_list_threads_in_stop_reply,     // 'QListThreadsInStopReply:'
124     sync_thread_state,                  // 'QSyncThreadState:'
125     memory_region_info,                 // 'qMemoryRegionInfo:'
126     get_profile_data,                   // 'qGetProfileData'
127     set_enable_profiling,               // 'QSetEnableAsyncProfiling'
128     enable_compression,                 // 'QEnableCompression:'
129     watchpoint_support_info,            // 'qWatchpointSupportInfo:'
130     allocate_memory,                    // '_M'
131     deallocate_memory,                  // '_m'
132     set_process_event,                  // 'QSetProcessEvent:'
133     save_register_state,                // '_g'
134     restore_register_state,             // '_G'
135     speed_test,                         // 'qSpeedTest:'
136     set_detach_on_error,                // 'QSetDetachOnError:'
137     query_transfer,                     // 'qXfer:'
138     query_supported_async_json_packets, // 'QSupportedAsyncJSONPackets'
139     configure_darwin_log,               // 'ConfigureDarwinLog:'
140     unknown_type
141   };
142 
143   typedef rnb_err_t (RNBRemote::*HandlePacketCallback)(const char *p);
144 
145   RNBRemote();
146   ~RNBRemote();
147 
148   void Initialize();
149 
150   bool InitializeRegisters(bool force = false);
151 
152   rnb_err_t HandleAsyncPacket(PacketEnum *type = NULL);
153   rnb_err_t HandleReceivedPacket(PacketEnum *type = NULL);
154 
GetContinueThread()155   nub_thread_t GetContinueThread() const { return m_continue_thread; }
156 
SetContinueThread(nub_thread_t tid)157   void SetContinueThread(nub_thread_t tid) { m_continue_thread = tid; }
158 
GetCurrentThread()159   nub_thread_t GetCurrentThread() const {
160     if (m_thread == 0 || m_thread == (nub_thread_t)-1)
161       return DNBProcessGetCurrentThread(m_ctx.ProcessID());
162     return m_thread;
163   }
164 
SetCurrentThread(nub_thread_t tid)165   void SetCurrentThread(nub_thread_t tid) {
166     DNBProcessSetCurrentThread(m_ctx.ProcessID(), tid);
167     m_thread = tid;
168   }
169 
170   static void *ThreadFunctionReadRemoteData(void *arg);
171   void StartReadRemoteDataThread();
172   void StopReadRemoteDataThread();
173 
174   void NotifyThatProcessStopped(void);
175 
176   rnb_err_t HandlePacket_A(const char *p);
177   rnb_err_t HandlePacket_H(const char *p);
178   rnb_err_t HandlePacket_qC(const char *p);
179   rnb_err_t HandlePacket_qRcmd(const char *p);
180   rnb_err_t HandlePacket_qGetPid(const char *p);
181   rnb_err_t HandlePacket_qEcho(const char *p);
182   rnb_err_t HandlePacket_qLaunchSuccess(const char *p);
183   rnb_err_t HandlePacket_qRegisterInfo(const char *p);
184   rnb_err_t HandlePacket_qShlibInfoAddr(const char *p);
185   rnb_err_t HandlePacket_qStepPacketSupported(const char *p);
186   rnb_err_t HandlePacket_qVAttachOrWaitSupported(const char *p);
187   rnb_err_t HandlePacket_qSyncThreadStateSupported(const char *p);
188   rnb_err_t HandlePacket_qThreadInfo(const char *p);
189   rnb_err_t HandlePacket_jThreadExtendedInfo(const char *p);
190   rnb_err_t HandlePacket_jGetLoadedDynamicLibrariesInfos(const char *p);
191   rnb_err_t HandlePacket_jThreadsInfo(const char *p);
192   rnb_err_t HandlePacket_jGetSharedCacheInfo(const char *p);
193   rnb_err_t HandlePacket_qThreadExtraInfo(const char *p);
194   rnb_err_t HandlePacket_qThreadStopInfo(const char *p);
195   rnb_err_t HandlePacket_qHostInfo(const char *p);
196   rnb_err_t HandlePacket_qGDBServerVersion(const char *p);
197   rnb_err_t HandlePacket_qProcessInfo(const char *p);
198   rnb_err_t HandlePacket_qSymbol(const char *p);
199   rnb_err_t HandlePacket_QStartNoAckMode(const char *p);
200   rnb_err_t HandlePacket_QThreadSuffixSupported(const char *p);
201   rnb_err_t HandlePacket_QSetLogging(const char *p);
202   rnb_err_t HandlePacket_QSetDisableASLR(const char *p);
203   rnb_err_t HandlePacket_QSetSTDIO(const char *p);
204   rnb_err_t HandlePacket_QSetWorkingDir(const char *p);
205   rnb_err_t HandlePacket_QSetMaxPayloadSize(const char *p);
206   rnb_err_t HandlePacket_QSetMaxPacketSize(const char *p);
207   rnb_err_t HandlePacket_QEnvironment(const char *p);
208   rnb_err_t HandlePacket_QEnvironmentHexEncoded(const char *p);
209   rnb_err_t HandlePacket_QLaunchArch(const char *p);
210   rnb_err_t HandlePacket_QListThreadsInStopReply(const char *p);
211   rnb_err_t HandlePacket_QSyncThreadState(const char *p);
212   rnb_err_t HandlePacket_QPrefixRegisterPacketsWithThreadID(const char *p);
213   rnb_err_t HandlePacket_QSetProcessEvent(const char *p);
214   rnb_err_t HandlePacket_last_signal(const char *p);
215   rnb_err_t HandlePacket_m(const char *p);
216   rnb_err_t HandlePacket_M(const char *p);
217   rnb_err_t HandlePacket_x(const char *p);
218   rnb_err_t HandlePacket_X(const char *p);
219   rnb_err_t HandlePacket_g(const char *p);
220   rnb_err_t HandlePacket_G(const char *p);
221   rnb_err_t HandlePacket_z(const char *p);
222   rnb_err_t HandlePacket_T(const char *p);
223   rnb_err_t HandlePacket_p(const char *p);
224   rnb_err_t HandlePacket_P(const char *p);
225   rnb_err_t HandlePacket_c(const char *p);
226   rnb_err_t HandlePacket_C(const char *p);
227   rnb_err_t HandlePacket_D(const char *p);
228   rnb_err_t HandlePacket_k(const char *p);
229   rnb_err_t HandlePacket_s(const char *p);
230   rnb_err_t HandlePacket_S(const char *p);
231   rnb_err_t HandlePacket_qSupported(const char *p);
232   rnb_err_t HandlePacket_v(const char *p);
233   rnb_err_t HandlePacket_UNIMPLEMENTED(const char *p);
234   rnb_err_t HandlePacket_ILLFORMED(const char *file, int line, const char *p,
235                                    const char *description);
236   rnb_err_t HandlePacket_AllocateMemory(const char *p);
237   rnb_err_t HandlePacket_DeallocateMemory(const char *p);
238   rnb_err_t HandlePacket_SaveRegisterState(const char *p);
239   rnb_err_t HandlePacket_RestoreRegisterState(const char *p);
240   rnb_err_t HandlePacket_MemoryRegionInfo(const char *p);
241   rnb_err_t HandlePacket_GetProfileData(const char *p);
242   rnb_err_t HandlePacket_SetEnableAsyncProfiling(const char *p);
243   rnb_err_t HandlePacket_QEnableCompression(const char *p);
244   rnb_err_t HandlePacket_WatchpointSupportInfo(const char *p);
245   rnb_err_t HandlePacket_qSpeedTest(const char *p);
246   rnb_err_t HandlePacket_qXfer(const char *p);
247   rnb_err_t HandlePacket_stop_process(const char *p);
248   rnb_err_t HandlePacket_QSetDetachOnError(const char *p);
249   rnb_err_t HandlePacket_qStructuredDataPlugins(const char *p);
250   rnb_err_t HandlePacket_QConfigureDarwinLog(const char *p);
251 
252   rnb_err_t SendStopReplyPacketForThread(nub_thread_t tid);
253   rnb_err_t SendHexEncodedBytePacket(const char *header, const void *buf,
254                                      size_t buf_len, const char *footer);
255   rnb_err_t SendSTDOUTPacket(char *buf, nub_size_t buf_size);
256   rnb_err_t SendSTDERRPacket(char *buf, nub_size_t buf_size);
257   void FlushSTDIO();
258   void SendAsyncProfileData();
259   rnb_err_t SendAsyncProfileDataPacket(char *buf, nub_size_t buf_size);
260   void SendAsyncDarwinLogData();
261   rnb_err_t SendAsyncJSONPacket(const JSONGenerator::Dictionary &dictionary);
262 
Context()263   RNBContext &Context() { return m_ctx; }
Comm()264   RNBSocket &Comm() { return m_comm; }
265 
266 private:
267   RNBRemote(const RNBRemote &) = delete;
268 
269 protected:
270   rnb_err_t GetCommData();
271   void CommDataReceived(const std::string &data);
272   struct Packet {
273     typedef std::vector<Packet> collection;
274     typedef collection::iterator iterator;
275     typedef collection::const_iterator const_iterator;
276     PacketEnum type;
277     HandlePacketCallback normal; // Function to call when inferior is halted
278     HandlePacketCallback async;  // Function to call when inferior is running
279     std::string abbrev;
280     std::string printable_name;
281 
IsPlatformPacketPacket282     bool IsPlatformPacket() const {
283       switch (type) {
284       case set_logging_mode:
285       case query_host_info:
286         return true;
287       default:
288         break;
289       }
290       return false;
291     }
PacketPacket292     Packet()
293         : type(invalid_packet), normal(NULL), async(NULL), abbrev(),
294           printable_name() {}
295 
PacketPacket296     Packet(PacketEnum in_type, HandlePacketCallback in_normal,
297            HandlePacketCallback in_async, const char *in_abbrev,
298            const char *in_printable_name)
299         : type(in_type), normal(in_normal), async(in_async), abbrev(in_abbrev),
300           printable_name(in_printable_name) {}
301   };
302 
303   struct DispatchQueueOffsets {
304     uint16_t dqo_version;
305     uint16_t dqo_label;
306     uint16_t dqo_label_size;
307     uint16_t dqo_flags;
308     uint16_t dqo_flags_size;
309     uint16_t dqo_serialnum;
310     uint16_t dqo_serialnum_size;
311     uint16_t dqo_width;
312     uint16_t dqo_width_size;
313     uint16_t dqo_running;
314     uint16_t dqo_running_size;
315     uint16_t dqo_suspend_cnt; // version 5 and later, starting with Mac OS X
316                               // 10.10/iOS 8
317     uint16_t dqo_suspend_cnt_size; // version 5 and later, starting with Mac OS
318                                    // X 10.10/iOS 8
319     uint16_t dqo_target_queue; // version 5 and later, starting with Mac OS X
320                                // 10.10/iOS 8
321     uint16_t dqo_target_queue_size; // version 5 and later, starting with Mac OS
322                                     // X 10.10/iOS 8
323     uint16_t
324         dqo_priority; // version 5 and later, starting with Mac OS X 10.10/iOS 8
325     uint16_t dqo_priority_size; // version 5 and later, starting with Mac OS X
326                                 // 10.10/iOS 8
327 
DispatchQueueOffsetsDispatchQueueOffsets328     DispatchQueueOffsets() { Clear(); }
329 
ClearDispatchQueueOffsets330     void Clear() {
331       dqo_version = UINT16_MAX;
332       dqo_label = UINT16_MAX;
333       dqo_label_size = UINT16_MAX;
334       dqo_flags = UINT16_MAX;
335       dqo_flags_size = UINT16_MAX;
336       dqo_serialnum = UINT16_MAX;
337       dqo_serialnum_size = UINT16_MAX;
338       dqo_width = UINT16_MAX;
339       dqo_width_size = UINT16_MAX;
340       dqo_running = UINT16_MAX;
341       dqo_running_size = UINT16_MAX;
342       dqo_suspend_cnt = UINT16_MAX;
343       dqo_suspend_cnt_size = UINT16_MAX;
344       dqo_target_queue = UINT16_MAX;
345       dqo_target_queue_size = UINT16_MAX;
346       dqo_priority = UINT16_MAX;
347       dqo_priority_size = UINT16_MAX;
348     }
349 
IsValidDispatchQueueOffsets350     bool IsValid() const { return dqo_version != UINT16_MAX; }
351 
352     void GetThreadQueueInfo(nub_process_t pid, nub_addr_t dispatch_qaddr,
353                             nub_addr_t &dispatch_queue_t,
354                             std::string &queue_name, uint64_t &queue_width,
355                             uint64_t &queue_serialnum) const;
356   };
357 
358   rnb_err_t GetPacket(std::string &packet_data, RNBRemote::Packet &packet_info,
359                       bool wait);
360   rnb_err_t SendPacket(const std::string &);
361   std::string CompressString(const std::string &);
362 
363   void CreatePacketTable();
364   rnb_err_t GetPacketPayload(std::string &);
365 
366   nub_thread_t ExtractThreadIDFromThreadSuffix(const char *p);
367 
368   void EnableCompressionNextSendPacket(compression_types);
369 
370   compression_types GetCompressionType();
371 
372   const DispatchQueueOffsets *GetDispatchQueueOffsets();
373 
374   JSONGenerator::ObjectSP
375   GetJSONThreadsInfo(bool threads_with_valid_stop_info_only);
376 
377   RNBContext m_ctx; // process context
378   RNBSocket m_comm; // communication port
379   std::string m_arch;
380   nub_thread_t m_continue_thread; // thread to continue; 0 for any, -1 for all
381   nub_thread_t m_thread;          // thread for other ops; 0 for any, -1 for all
382   PThreadMutex m_mutex;           // Mutex that protects
383   DispatchQueueOffsets m_dispatch_queue_offsets;
384   nub_addr_t m_dispatch_queue_offsets_addr;
385   uint32_t m_qSymbol_index;
386   uint32_t m_packets_recvd;
387   Packet::collection m_packets;
388   std::deque<std::string> m_rx_packets;
389   std::string m_rx_partial_data; // For packets that may come in more than one
390                                  // batch, anything left over can be left here
391   pthread_t m_rx_pthread;
392   uint32_t
393       m_max_payload_size; // the maximum sized payload we should send to gdb
394   bool m_extended_mode;   // are we in extended mode?
395   bool m_noack_mode;      // are we in no-ack mode?
396   bool m_thread_suffix_supported; // Set to true if the 'p', 'P', 'g', and 'G'
397                                   // packets should be prefixed with the thread
398                                   // ID and colon:
399                                   // "$pRR;thread:TTTT;" instead of "$pRR"
400   // "$PRR=VVVVVVVV;thread:TTTT;" instead of "$PRR=VVVVVVVV"
401   // "$g;thread:TTTT" instead of "$g"
402   // "$GVVVVVVVVVVVVVV;thread:TTTT;#00 instead of "$GVVVVVVVVVVVVVV"
403   bool m_list_threads_in_stop_reply;
404 
405   size_t m_compression_minsize; // only packets larger than this size will be
406                                 // compressed
407   bool m_enable_compression_next_send_packet;
408 
409   compression_types m_compression_mode;
410 };
411 
412 /* We translate the /usr/include/mach/exception_types.h exception types
413    (e.g. EXC_BAD_ACCESS) to the fake BSD signal numbers that gdb uses
414    in include/gdb/signals.h (e.g. TARGET_EXC_BAD_ACCESS).  These hard
415    coded values for TARGET_EXC_BAD_ACCESS et al must match the gdb
416    values in its include/gdb/signals.h.  */
417 
418 #define TARGET_EXC_BAD_ACCESS 0x91
419 #define TARGET_EXC_BAD_INSTRUCTION 0x92
420 #define TARGET_EXC_ARITHMETIC 0x93
421 #define TARGET_EXC_EMULATION 0x94
422 #define TARGET_EXC_SOFTWARE 0x95
423 #define TARGET_EXC_BREAKPOINT 0x96
424 
425 /* Generally speaking, you can't assume gdb can receive more than 399 bytes
426    at a time with a random gdb.  This bufsize constant is only specifying
427    how many bytes gdb can *receive* from debugserver -- it tells us nothing
428    about how many bytes gdb might try to send in a single packet.  */
429 #define DEFAULT_GDB_REMOTE_PROTOCOL_BUFSIZE 399
430 
431 #endif // LLDB_TOOLS_DEBUGSERVER_SOURCE_RNBREMOTE_H
432