1 //===-- GDBRemoteCommunicationClient.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 "GDBRemoteCommunicationClient.h"
11
12 #include <math.h>
13 #include <sys/stat.h>
14
15 #include <numeric>
16 #include <sstream>
17
18 #include "lldb/Core/ModuleSpec.h"
19 #include "lldb/Host/HostInfo.h"
20 #include "lldb/Host/XML.h"
21 #include "lldb/Symbol/Symbol.h"
22 #include "lldb/Target/MemoryRegionInfo.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/UnixSignals.h"
25 #include "lldb/Utility/Args.h"
26 #include "lldb/Utility/DataBufferHeap.h"
27 #include "lldb/Utility/JSON.h"
28 #include "lldb/Utility/LLDBAssert.h"
29 #include "lldb/Utility/Log.h"
30 #include "lldb/Utility/State.h"
31 #include "lldb/Utility/StreamString.h"
32
33 #include "ProcessGDBRemote.h"
34 #include "ProcessGDBRemoteLog.h"
35 #include "lldb/Host/Config.h"
36 #include "lldb/Utility/StringExtractorGDBRemote.h"
37
38 #include "llvm/ADT/StringSwitch.h"
39
40 #if defined(__APPLE__)
41 #define HAVE_LIBCOMPRESSION
42 #include <compression.h>
43 #endif
44
45 using namespace lldb;
46 using namespace lldb_private;
47 using namespace lldb_private::process_gdb_remote;
48 using namespace std::chrono;
49
50 //----------------------------------------------------------------------
51 // GDBRemoteCommunicationClient constructor
52 //----------------------------------------------------------------------
GDBRemoteCommunicationClient()53 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
54 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
55 m_supports_not_sending_acks(eLazyBoolCalculate),
56 m_supports_thread_suffix(eLazyBoolCalculate),
57 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
58 m_supports_vCont_all(eLazyBoolCalculate),
59 m_supports_vCont_any(eLazyBoolCalculate),
60 m_supports_vCont_c(eLazyBoolCalculate),
61 m_supports_vCont_C(eLazyBoolCalculate),
62 m_supports_vCont_s(eLazyBoolCalculate),
63 m_supports_vCont_S(eLazyBoolCalculate),
64 m_qHostInfo_is_valid(eLazyBoolCalculate),
65 m_curr_pid_is_valid(eLazyBoolCalculate),
66 m_qProcessInfo_is_valid(eLazyBoolCalculate),
67 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
68 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
69 m_supports_memory_region_info(eLazyBoolCalculate),
70 m_supports_watchpoint_support_info(eLazyBoolCalculate),
71 m_supports_detach_stay_stopped(eLazyBoolCalculate),
72 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
73 m_attach_or_wait_reply(eLazyBoolCalculate),
74 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
75 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate),
76 m_avoid_g_packets(eLazyBoolCalculate),
77 m_supports_QSaveRegisterState(eLazyBoolCalculate),
78 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
79 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
80 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
81 m_supports_qXfer_features_read(eLazyBoolCalculate),
82 m_supports_qXfer_memory_map_read(eLazyBoolCalculate),
83 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
84 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
85 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
86 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
87 m_supports_QPassSignals(eLazyBoolCalculate),
88 m_supports_error_string_reply(eLazyBoolCalculate),
89 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true),
90 m_supports_qUserName(true), m_supports_qGroupName(true),
91 m_supports_qThreadStopInfo(true), m_supports_z0(true),
92 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true),
93 m_supports_z4(true), m_supports_QEnvironment(true),
94 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true),
95 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true),
96 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
97 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID),
98 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
99 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(),
100 m_os_build(), m_os_kernel(), m_hostname(), m_gdb_server_name(),
101 m_gdb_server_version(UINT32_MAX), m_default_packet_timeout(0),
102 m_max_packet_size(0), m_qSupported_response(),
103 m_supported_async_json_packets_is_valid(false),
104 m_supported_async_json_packets_sp(), m_qXfer_memory_map(),
105 m_qXfer_memory_map_loaded(false) {}
106
107 //----------------------------------------------------------------------
108 // Destructor
109 //----------------------------------------------------------------------
~GDBRemoteCommunicationClient()110 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() {
111 if (IsConnected())
112 Disconnect();
113 }
114
HandshakeWithServer(Status * error_ptr)115 bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) {
116 ResetDiscoverableSettings(false);
117
118 // Start the read thread after we send the handshake ack since if we fail to
119 // send the handshake ack, there is no reason to continue...
120 if (SendAck()) {
121 // Wait for any responses that might have been queued up in the remote
122 // GDB server and flush them all
123 StringExtractorGDBRemote response;
124 PacketResult packet_result = PacketResult::Success;
125 while (packet_result == PacketResult::Success)
126 packet_result = ReadPacket(response, milliseconds(10), false);
127
128 // The return value from QueryNoAckModeSupported() is true if the packet
129 // was sent and _any_ response (including UNIMPLEMENTED) was received), or
130 // false if no response was received. This quickly tells us if we have a
131 // live connection to a remote GDB server...
132 if (QueryNoAckModeSupported()) {
133 return true;
134 } else {
135 if (error_ptr)
136 error_ptr->SetErrorString("failed to get reply to handshake packet");
137 }
138 } else {
139 if (error_ptr)
140 error_ptr->SetErrorString("failed to send the handshake ack");
141 }
142 return false;
143 }
144
GetEchoSupported()145 bool GDBRemoteCommunicationClient::GetEchoSupported() {
146 if (m_supports_qEcho == eLazyBoolCalculate) {
147 GetRemoteQSupported();
148 }
149 return m_supports_qEcho == eLazyBoolYes;
150 }
151
GetQPassSignalsSupported()152 bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() {
153 if (m_supports_QPassSignals == eLazyBoolCalculate) {
154 GetRemoteQSupported();
155 }
156 return m_supports_QPassSignals == eLazyBoolYes;
157 }
158
GetAugmentedLibrariesSVR4ReadSupported()159 bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
160 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
161 GetRemoteQSupported();
162 }
163 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
164 }
165
GetQXferLibrariesSVR4ReadSupported()166 bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
167 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
168 GetRemoteQSupported();
169 }
170 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
171 }
172
GetQXferLibrariesReadSupported()173 bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
174 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
175 GetRemoteQSupported();
176 }
177 return m_supports_qXfer_libraries_read == eLazyBoolYes;
178 }
179
GetQXferAuxvReadSupported()180 bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
181 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
182 GetRemoteQSupported();
183 }
184 return m_supports_qXfer_auxv_read == eLazyBoolYes;
185 }
186
GetQXferFeaturesReadSupported()187 bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
188 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
189 GetRemoteQSupported();
190 }
191 return m_supports_qXfer_features_read == eLazyBoolYes;
192 }
193
GetQXferMemoryMapReadSupported()194 bool GDBRemoteCommunicationClient::GetQXferMemoryMapReadSupported() {
195 if (m_supports_qXfer_memory_map_read == eLazyBoolCalculate) {
196 GetRemoteQSupported();
197 }
198 return m_supports_qXfer_memory_map_read == eLazyBoolYes;
199 }
200
GetRemoteMaxPacketSize()201 uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
202 if (m_max_packet_size == 0) {
203 GetRemoteQSupported();
204 }
205 return m_max_packet_size;
206 }
207
QueryNoAckModeSupported()208 bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
209 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
210 m_send_acks = true;
211 m_supports_not_sending_acks = eLazyBoolNo;
212
213 // This is the first real packet that we'll send in a debug session and it
214 // may take a little longer than normal to receive a reply. Wait at least
215 // 6 seconds for a reply to this packet.
216
217 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
218
219 StringExtractorGDBRemote response;
220 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
221 PacketResult::Success) {
222 if (response.IsOKResponse()) {
223 m_send_acks = false;
224 m_supports_not_sending_acks = eLazyBoolYes;
225 }
226 return true;
227 }
228 }
229 return false;
230 }
231
GetListThreadsInStopReplySupported()232 void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
233 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
234 m_supports_threads_in_stop_reply = eLazyBoolNo;
235
236 StringExtractorGDBRemote response;
237 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
238 false) == PacketResult::Success) {
239 if (response.IsOKResponse())
240 m_supports_threads_in_stop_reply = eLazyBoolYes;
241 }
242 }
243 }
244
GetVAttachOrWaitSupported()245 bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
246 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
247 m_attach_or_wait_reply = eLazyBoolNo;
248
249 StringExtractorGDBRemote response;
250 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
251 false) == PacketResult::Success) {
252 if (response.IsOKResponse())
253 m_attach_or_wait_reply = eLazyBoolYes;
254 }
255 }
256 return m_attach_or_wait_reply == eLazyBoolYes;
257 }
258
GetSyncThreadStateSupported()259 bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
260 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
261 m_prepare_for_reg_writing_reply = eLazyBoolNo;
262
263 StringExtractorGDBRemote response;
264 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
265 false) == PacketResult::Success) {
266 if (response.IsOKResponse())
267 m_prepare_for_reg_writing_reply = eLazyBoolYes;
268 }
269 }
270 return m_prepare_for_reg_writing_reply == eLazyBoolYes;
271 }
272
ResetDiscoverableSettings(bool did_exec)273 void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
274 if (!did_exec) {
275 // Hard reset everything, this is when we first connect to a GDB server
276 m_supports_not_sending_acks = eLazyBoolCalculate;
277 m_supports_thread_suffix = eLazyBoolCalculate;
278 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
279 m_supports_vCont_c = eLazyBoolCalculate;
280 m_supports_vCont_C = eLazyBoolCalculate;
281 m_supports_vCont_s = eLazyBoolCalculate;
282 m_supports_vCont_S = eLazyBoolCalculate;
283 m_supports_p = eLazyBoolCalculate;
284 m_supports_x = eLazyBoolCalculate;
285 m_supports_QSaveRegisterState = eLazyBoolCalculate;
286 m_qHostInfo_is_valid = eLazyBoolCalculate;
287 m_curr_pid_is_valid = eLazyBoolCalculate;
288 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
289 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
290 m_supports_memory_region_info = eLazyBoolCalculate;
291 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
292 m_attach_or_wait_reply = eLazyBoolCalculate;
293 m_avoid_g_packets = eLazyBoolCalculate;
294 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
295 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
296 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
297 m_supports_qXfer_features_read = eLazyBoolCalculate;
298 m_supports_qXfer_memory_map_read = eLazyBoolCalculate;
299 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
300 m_supports_qProcessInfoPID = true;
301 m_supports_qfProcessInfo = true;
302 m_supports_qUserName = true;
303 m_supports_qGroupName = true;
304 m_supports_qThreadStopInfo = true;
305 m_supports_z0 = true;
306 m_supports_z1 = true;
307 m_supports_z2 = true;
308 m_supports_z3 = true;
309 m_supports_z4 = true;
310 m_supports_QEnvironment = true;
311 m_supports_QEnvironmentHexEncoded = true;
312 m_supports_qSymbol = true;
313 m_qSymbol_requests_done = false;
314 m_supports_qModuleInfo = true;
315 m_host_arch.Clear();
316 m_os_version = llvm::VersionTuple();
317 m_os_build.clear();
318 m_os_kernel.clear();
319 m_hostname.clear();
320 m_gdb_server_name.clear();
321 m_gdb_server_version = UINT32_MAX;
322 m_default_packet_timeout = seconds(0);
323 m_max_packet_size = 0;
324 m_qSupported_response.clear();
325 m_supported_async_json_packets_is_valid = false;
326 m_supported_async_json_packets_sp.reset();
327 m_supports_jModulesInfo = true;
328 }
329
330 // These flags should be reset when we first connect to a GDB server and when
331 // our inferior process execs
332 m_qProcessInfo_is_valid = eLazyBoolCalculate;
333 m_process_arch.Clear();
334 }
335
GetRemoteQSupported()336 void GDBRemoteCommunicationClient::GetRemoteQSupported() {
337 // Clear out any capabilities we expect to see in the qSupported response
338 m_supports_qXfer_auxv_read = eLazyBoolNo;
339 m_supports_qXfer_libraries_read = eLazyBoolNo;
340 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
341 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
342 m_supports_qXfer_features_read = eLazyBoolNo;
343 m_supports_qXfer_memory_map_read = eLazyBoolNo;
344 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
345 // not, we assume no limit
346
347 // build the qSupported packet
348 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
349 StreamString packet;
350 packet.PutCString("qSupported");
351 for (uint32_t i = 0; i < features.size(); ++i) {
352 packet.PutCString(i == 0 ? ":" : ";");
353 packet.PutCString(features[i]);
354 }
355
356 StringExtractorGDBRemote response;
357 if (SendPacketAndWaitForResponse(packet.GetString(), response,
358 /*send_async=*/false) ==
359 PacketResult::Success) {
360 const char *response_cstr = response.GetStringRef().c_str();
361
362 // Hang on to the qSupported packet, so that platforms can do custom
363 // configuration of the transport before attaching/launching the process.
364 m_qSupported_response = response_cstr;
365
366 if (::strstr(response_cstr, "qXfer:auxv:read+"))
367 m_supports_qXfer_auxv_read = eLazyBoolYes;
368 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
369 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
370 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
371 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
372 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
373 }
374 if (::strstr(response_cstr, "qXfer:libraries:read+"))
375 m_supports_qXfer_libraries_read = eLazyBoolYes;
376 if (::strstr(response_cstr, "qXfer:features:read+"))
377 m_supports_qXfer_features_read = eLazyBoolYes;
378 if (::strstr(response_cstr, "qXfer:memory-map:read+"))
379 m_supports_qXfer_memory_map_read = eLazyBoolYes;
380
381 // Look for a list of compressions in the features list e.g.
382 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-
383 // deflate,lzma
384 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
385 if (features_list) {
386 const char *compressions =
387 ::strstr(features_list, "SupportedCompressions=");
388 if (compressions) {
389 std::vector<std::string> supported_compressions;
390 compressions += sizeof("SupportedCompressions=") - 1;
391 const char *end_of_compressions = strchr(compressions, ';');
392 if (end_of_compressions == NULL) {
393 end_of_compressions = strchr(compressions, '\0');
394 }
395 const char *current_compression = compressions;
396 while (current_compression < end_of_compressions) {
397 const char *next_compression_name = strchr(current_compression, ',');
398 const char *end_of_this_word = next_compression_name;
399 if (next_compression_name == NULL ||
400 end_of_compressions < next_compression_name) {
401 end_of_this_word = end_of_compressions;
402 }
403
404 if (end_of_this_word) {
405 if (end_of_this_word == current_compression) {
406 current_compression++;
407 } else {
408 std::string this_compression(
409 current_compression, end_of_this_word - current_compression);
410 supported_compressions.push_back(this_compression);
411 current_compression = end_of_this_word + 1;
412 }
413 } else {
414 supported_compressions.push_back(current_compression);
415 current_compression = end_of_compressions;
416 }
417 }
418
419 if (supported_compressions.size() > 0) {
420 MaybeEnableCompression(supported_compressions);
421 }
422 }
423 }
424
425 if (::strstr(response_cstr, "qEcho"))
426 m_supports_qEcho = eLazyBoolYes;
427 else
428 m_supports_qEcho = eLazyBoolNo;
429
430 if (::strstr(response_cstr, "QPassSignals+"))
431 m_supports_QPassSignals = eLazyBoolYes;
432 else
433 m_supports_QPassSignals = eLazyBoolNo;
434
435 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
436 if (packet_size_str) {
437 StringExtractorGDBRemote packet_response(packet_size_str +
438 strlen("PacketSize="));
439 m_max_packet_size =
440 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
441 if (m_max_packet_size == 0) {
442 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
443 Log *log(
444 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
445 if (log)
446 log->Printf("Garbled PacketSize spec in qSupported response");
447 }
448 }
449 }
450 }
451
GetThreadSuffixSupported()452 bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
453 if (m_supports_thread_suffix == eLazyBoolCalculate) {
454 StringExtractorGDBRemote response;
455 m_supports_thread_suffix = eLazyBoolNo;
456 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
457 false) == PacketResult::Success) {
458 if (response.IsOKResponse())
459 m_supports_thread_suffix = eLazyBoolYes;
460 }
461 }
462 return m_supports_thread_suffix;
463 }
GetVContSupported(char flavor)464 bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
465 if (m_supports_vCont_c == eLazyBoolCalculate) {
466 StringExtractorGDBRemote response;
467 m_supports_vCont_any = eLazyBoolNo;
468 m_supports_vCont_all = eLazyBoolNo;
469 m_supports_vCont_c = eLazyBoolNo;
470 m_supports_vCont_C = eLazyBoolNo;
471 m_supports_vCont_s = eLazyBoolNo;
472 m_supports_vCont_S = eLazyBoolNo;
473 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
474 PacketResult::Success) {
475 const char *response_cstr = response.GetStringRef().c_str();
476 if (::strstr(response_cstr, ";c"))
477 m_supports_vCont_c = eLazyBoolYes;
478
479 if (::strstr(response_cstr, ";C"))
480 m_supports_vCont_C = eLazyBoolYes;
481
482 if (::strstr(response_cstr, ";s"))
483 m_supports_vCont_s = eLazyBoolYes;
484
485 if (::strstr(response_cstr, ";S"))
486 m_supports_vCont_S = eLazyBoolYes;
487
488 if (m_supports_vCont_c == eLazyBoolYes &&
489 m_supports_vCont_C == eLazyBoolYes &&
490 m_supports_vCont_s == eLazyBoolYes &&
491 m_supports_vCont_S == eLazyBoolYes) {
492 m_supports_vCont_all = eLazyBoolYes;
493 }
494
495 if (m_supports_vCont_c == eLazyBoolYes ||
496 m_supports_vCont_C == eLazyBoolYes ||
497 m_supports_vCont_s == eLazyBoolYes ||
498 m_supports_vCont_S == eLazyBoolYes) {
499 m_supports_vCont_any = eLazyBoolYes;
500 }
501 }
502 }
503
504 switch (flavor) {
505 case 'a':
506 return m_supports_vCont_any;
507 case 'A':
508 return m_supports_vCont_all;
509 case 'c':
510 return m_supports_vCont_c;
511 case 'C':
512 return m_supports_vCont_C;
513 case 's':
514 return m_supports_vCont_s;
515 case 'S':
516 return m_supports_vCont_S;
517 default:
518 break;
519 }
520 return false;
521 }
522
523 GDBRemoteCommunication::PacketResult
SendThreadSpecificPacketAndWaitForResponse(lldb::tid_t tid,StreamString && payload,StringExtractorGDBRemote & response,bool send_async)524 GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
525 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
526 bool send_async) {
527 Lock lock(*this, send_async);
528 if (!lock) {
529 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
530 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
531 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
532 "for %s packet.",
533 __FUNCTION__, payload.GetData());
534 return PacketResult::ErrorNoSequenceLock;
535 }
536
537 if (GetThreadSuffixSupported())
538 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
539 else {
540 if (!SetCurrentThread(tid))
541 return PacketResult::ErrorSendFailed;
542 }
543
544 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
545 }
546
547 // Check if the target supports 'p' packet. It sends out a 'p' packet and
548 // checks the response. A normal packet will tell us that support is available.
549 //
550 // Takes a valid thread ID because p needs to apply to a thread.
GetpPacketSupported(lldb::tid_t tid)551 bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
552 if (m_supports_p == eLazyBoolCalculate) {
553 m_supports_p = eLazyBoolNo;
554 StreamString payload;
555 payload.PutCString("p0");
556 StringExtractorGDBRemote response;
557 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
558 response, false) ==
559 PacketResult::Success &&
560 response.IsNormalResponse()) {
561 m_supports_p = eLazyBoolYes;
562 }
563 }
564 return m_supports_p;
565 }
566
GetThreadsInfo()567 StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
568 // Get information on all threads at one using the "jThreadsInfo" packet
569 StructuredData::ObjectSP object_sp;
570
571 if (m_supports_jThreadsInfo) {
572 StringExtractorGDBRemote response;
573 response.SetResponseValidatorToJSON();
574 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
575 PacketResult::Success) {
576 if (response.IsUnsupportedResponse()) {
577 m_supports_jThreadsInfo = false;
578 } else if (!response.Empty()) {
579 object_sp = StructuredData::ParseJSON(response.GetStringRef());
580 }
581 }
582 }
583 return object_sp;
584 }
585
GetThreadExtendedInfoSupported()586 bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
587 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
588 StringExtractorGDBRemote response;
589 m_supports_jThreadExtendedInfo = eLazyBoolNo;
590 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
591 PacketResult::Success) {
592 if (response.IsOKResponse()) {
593 m_supports_jThreadExtendedInfo = eLazyBoolYes;
594 }
595 }
596 }
597 return m_supports_jThreadExtendedInfo;
598 }
599
EnableErrorStringInPacket()600 void GDBRemoteCommunicationClient::EnableErrorStringInPacket() {
601 if (m_supports_error_string_reply == eLazyBoolCalculate) {
602 StringExtractorGDBRemote response;
603 // We try to enable error strings in remote packets but if we fail, we just
604 // work in the older way.
605 m_supports_error_string_reply = eLazyBoolNo;
606 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response, false) ==
607 PacketResult::Success) {
608 if (response.IsOKResponse()) {
609 m_supports_error_string_reply = eLazyBoolYes;
610 }
611 }
612 }
613 }
614
GetLoadedDynamicLibrariesInfosSupported()615 bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
616 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
617 StringExtractorGDBRemote response;
618 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
619 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
620 response,
621 false) == PacketResult::Success) {
622 if (response.IsOKResponse()) {
623 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
624 }
625 }
626 }
627 return m_supports_jLoadedDynamicLibrariesInfos;
628 }
629
GetSharedCacheInfoSupported()630 bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
631 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
632 StringExtractorGDBRemote response;
633 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
634 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
635 PacketResult::Success) {
636 if (response.IsOKResponse()) {
637 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
638 }
639 }
640 }
641 return m_supports_jGetSharedCacheInfo;
642 }
643
GetxPacketSupported()644 bool GDBRemoteCommunicationClient::GetxPacketSupported() {
645 if (m_supports_x == eLazyBoolCalculate) {
646 StringExtractorGDBRemote response;
647 m_supports_x = eLazyBoolNo;
648 char packet[256];
649 snprintf(packet, sizeof(packet), "x0,0");
650 if (SendPacketAndWaitForResponse(packet, response, false) ==
651 PacketResult::Success) {
652 if (response.IsOKResponse())
653 m_supports_x = eLazyBoolYes;
654 }
655 }
656 return m_supports_x;
657 }
658
659 GDBRemoteCommunicationClient::PacketResult
SendPacketsAndConcatenateResponses(const char * payload_prefix,std::string & response_string)660 GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
661 const char *payload_prefix, std::string &response_string) {
662 Lock lock(*this, false);
663 if (!lock) {
664 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
665 GDBR_LOG_PACKETS));
666 if (log)
667 log->Printf("error: failed to get packet sequence mutex, not sending "
668 "packets with prefix '%s'",
669 payload_prefix);
670 return PacketResult::ErrorNoSequenceLock;
671 }
672
673 response_string = "";
674 std::string payload_prefix_str(payload_prefix);
675 unsigned int response_size = 0x1000;
676 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
677 response_size = GetRemoteMaxPacketSize();
678 }
679
680 for (unsigned int offset = 0; true; offset += response_size) {
681 StringExtractorGDBRemote this_response;
682 // Construct payload
683 char sizeDescriptor[128];
684 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
685 response_size);
686 PacketResult result = SendPacketAndWaitForResponseNoLock(
687 payload_prefix_str + sizeDescriptor, this_response);
688 if (result != PacketResult::Success)
689 return result;
690
691 const std::string &this_string = this_response.GetStringRef();
692
693 // Check for m or l as first character; l seems to mean this is the last
694 // chunk
695 char first_char = *this_string.c_str();
696 if (first_char != 'm' && first_char != 'l') {
697 return PacketResult::ErrorReplyInvalid;
698 }
699 // Concatenate the result so far (skipping 'm' or 'l')
700 response_string.append(this_string, 1, std::string::npos);
701 if (first_char == 'l')
702 // We're done
703 return PacketResult::Success;
704 }
705 }
706
GetCurrentProcessID(bool allow_lazy)707 lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
708 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
709 return m_curr_pid;
710
711 // First try to retrieve the pid via the qProcessInfo request.
712 GetCurrentProcessInfo(allow_lazy);
713 if (m_curr_pid_is_valid == eLazyBoolYes) {
714 // We really got it.
715 return m_curr_pid;
716 } else {
717 // If we don't get a response for qProcessInfo, check if $qC gives us a
718 // result. $qC only returns a real process id on older debugserver and
719 // lldb-platform stubs. The gdb remote protocol documents $qC as returning
720 // the thread id, which newer debugserver and lldb-gdbserver stubs return
721 // correctly.
722 StringExtractorGDBRemote response;
723 if (SendPacketAndWaitForResponse("qC", response, false) ==
724 PacketResult::Success) {
725 if (response.GetChar() == 'Q') {
726 if (response.GetChar() == 'C') {
727 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
728 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
729 m_curr_pid_is_valid = eLazyBoolYes;
730 return m_curr_pid;
731 }
732 }
733 }
734 }
735
736 // If we don't get a response for $qC, check if $qfThreadID gives us a
737 // result.
738 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
739 std::vector<lldb::tid_t> thread_ids;
740 bool sequence_mutex_unavailable;
741 size_t size;
742 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
743 if (size && !sequence_mutex_unavailable) {
744 m_curr_pid = thread_ids.front();
745 m_curr_pid_is_valid = eLazyBoolYes;
746 return m_curr_pid;
747 }
748 }
749 }
750
751 return LLDB_INVALID_PROCESS_ID;
752 }
753
GetLaunchSuccess(std::string & error_str)754 bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
755 error_str.clear();
756 StringExtractorGDBRemote response;
757 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
758 PacketResult::Success) {
759 if (response.IsOKResponse())
760 return true;
761 if (response.GetChar() == 'E') {
762 // A string the describes what failed when launching...
763 error_str = response.GetStringRef().substr(1);
764 } else {
765 error_str.assign("unknown error occurred launching process");
766 }
767 } else {
768 error_str.assign("timed out waiting for app to launch");
769 }
770 return false;
771 }
772
SendArgumentsPacket(const ProcessLaunchInfo & launch_info)773 int GDBRemoteCommunicationClient::SendArgumentsPacket(
774 const ProcessLaunchInfo &launch_info) {
775 // Since we don't get the send argv0 separate from the executable path, we
776 // need to make sure to use the actual executable path found in the
777 // launch_info...
778 std::vector<const char *> argv;
779 FileSpec exe_file = launch_info.GetExecutableFile();
780 std::string exe_path;
781 const char *arg = NULL;
782 const Args &launch_args = launch_info.GetArguments();
783 if (exe_file)
784 exe_path = exe_file.GetPath(false);
785 else {
786 arg = launch_args.GetArgumentAtIndex(0);
787 if (arg)
788 exe_path = arg;
789 }
790 if (!exe_path.empty()) {
791 argv.push_back(exe_path.c_str());
792 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL;
793 ++i) {
794 if (arg)
795 argv.push_back(arg);
796 }
797 }
798 if (!argv.empty()) {
799 StreamString packet;
800 packet.PutChar('A');
801 for (size_t i = 0, n = argv.size(); i < n; ++i) {
802 arg = argv[i];
803 const int arg_len = strlen(arg);
804 if (i > 0)
805 packet.PutChar(',');
806 packet.Printf("%i,%i,", arg_len * 2, (int)i);
807 packet.PutBytesAsRawHex8(arg, arg_len);
808 }
809
810 StringExtractorGDBRemote response;
811 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
812 PacketResult::Success) {
813 if (response.IsOKResponse())
814 return 0;
815 uint8_t error = response.GetError();
816 if (error)
817 return error;
818 }
819 }
820 return -1;
821 }
822
SendEnvironment(const Environment & env)823 int GDBRemoteCommunicationClient::SendEnvironment(const Environment &env) {
824 for (const auto &KV : env) {
825 int r = SendEnvironmentPacket(Environment::compose(KV).c_str());
826 if (r != 0)
827 return r;
828 }
829 return 0;
830 }
831
SendEnvironmentPacket(char const * name_equal_value)832 int GDBRemoteCommunicationClient::SendEnvironmentPacket(
833 char const *name_equal_value) {
834 if (name_equal_value && name_equal_value[0]) {
835 StreamString packet;
836 bool send_hex_encoding = false;
837 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding;
838 ++p) {
839 if (isprint(*p)) {
840 switch (*p) {
841 case '$':
842 case '#':
843 case '*':
844 case '}':
845 send_hex_encoding = true;
846 break;
847 default:
848 break;
849 }
850 } else {
851 // We have non printable characters, lets hex encode this...
852 send_hex_encoding = true;
853 }
854 }
855
856 StringExtractorGDBRemote response;
857 if (send_hex_encoding) {
858 if (m_supports_QEnvironmentHexEncoded) {
859 packet.PutCString("QEnvironmentHexEncoded:");
860 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
861 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
862 PacketResult::Success) {
863 if (response.IsOKResponse())
864 return 0;
865 uint8_t error = response.GetError();
866 if (error)
867 return error;
868 if (response.IsUnsupportedResponse())
869 m_supports_QEnvironmentHexEncoded = false;
870 }
871 }
872
873 } else if (m_supports_QEnvironment) {
874 packet.Printf("QEnvironment:%s", name_equal_value);
875 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
876 PacketResult::Success) {
877 if (response.IsOKResponse())
878 return 0;
879 uint8_t error = response.GetError();
880 if (error)
881 return error;
882 if (response.IsUnsupportedResponse())
883 m_supports_QEnvironment = false;
884 }
885 }
886 }
887 return -1;
888 }
889
SendLaunchArchPacket(char const * arch)890 int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
891 if (arch && arch[0]) {
892 StreamString packet;
893 packet.Printf("QLaunchArch:%s", arch);
894 StringExtractorGDBRemote response;
895 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
896 PacketResult::Success) {
897 if (response.IsOKResponse())
898 return 0;
899 uint8_t error = response.GetError();
900 if (error)
901 return error;
902 }
903 }
904 return -1;
905 }
906
SendLaunchEventDataPacket(char const * data,bool * was_supported)907 int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
908 char const *data, bool *was_supported) {
909 if (data && *data != '\0') {
910 StreamString packet;
911 packet.Printf("QSetProcessEvent:%s", data);
912 StringExtractorGDBRemote response;
913 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
914 PacketResult::Success) {
915 if (response.IsOKResponse()) {
916 if (was_supported)
917 *was_supported = true;
918 return 0;
919 } else if (response.IsUnsupportedResponse()) {
920 if (was_supported)
921 *was_supported = false;
922 return -1;
923 } else {
924 uint8_t error = response.GetError();
925 if (was_supported)
926 *was_supported = true;
927 if (error)
928 return error;
929 }
930 }
931 }
932 return -1;
933 }
934
GetOSVersion()935 llvm::VersionTuple GDBRemoteCommunicationClient::GetOSVersion() {
936 GetHostInfo();
937 return m_os_version;
938 }
939
GetOSBuildString(std::string & s)940 bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
941 if (GetHostInfo()) {
942 if (!m_os_build.empty()) {
943 s = m_os_build;
944 return true;
945 }
946 }
947 s.clear();
948 return false;
949 }
950
GetOSKernelDescription(std::string & s)951 bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
952 if (GetHostInfo()) {
953 if (!m_os_kernel.empty()) {
954 s = m_os_kernel;
955 return true;
956 }
957 }
958 s.clear();
959 return false;
960 }
961
GetHostname(std::string & s)962 bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
963 if (GetHostInfo()) {
964 if (!m_hostname.empty()) {
965 s = m_hostname;
966 return true;
967 }
968 }
969 s.clear();
970 return false;
971 }
972
GetSystemArchitecture()973 ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
974 if (GetHostInfo())
975 return m_host_arch;
976 return ArchSpec();
977 }
978
979 const lldb_private::ArchSpec &
GetProcessArchitecture()980 GDBRemoteCommunicationClient::GetProcessArchitecture() {
981 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
982 GetCurrentProcessInfo();
983 return m_process_arch;
984 }
985
GetGDBServerVersion()986 bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
987 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
988 m_gdb_server_name.clear();
989 m_gdb_server_version = 0;
990 m_qGDBServerVersion_is_valid = eLazyBoolNo;
991
992 StringExtractorGDBRemote response;
993 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
994 PacketResult::Success) {
995 if (response.IsNormalResponse()) {
996 llvm::StringRef name, value;
997 bool success = false;
998 while (response.GetNameColonValue(name, value)) {
999 if (name.equals("name")) {
1000 success = true;
1001 m_gdb_server_name = value;
1002 } else if (name.equals("version")) {
1003 llvm::StringRef major, minor;
1004 std::tie(major, minor) = value.split('.');
1005 if (!major.getAsInteger(0, m_gdb_server_version))
1006 success = true;
1007 }
1008 }
1009 if (success)
1010 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1011 }
1012 }
1013 }
1014 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1015 }
1016
MaybeEnableCompression(std::vector<std::string> supported_compressions)1017 void GDBRemoteCommunicationClient::MaybeEnableCompression(
1018 std::vector<std::string> supported_compressions) {
1019 CompressionType avail_type = CompressionType::None;
1020 std::string avail_name;
1021
1022 #if defined(HAVE_LIBCOMPRESSION)
1023 if (avail_type == CompressionType::None) {
1024 for (auto compression : supported_compressions) {
1025 if (compression == "lzfse") {
1026 avail_type = CompressionType::LZFSE;
1027 avail_name = compression;
1028 break;
1029 }
1030 }
1031 }
1032 #endif
1033
1034 #if defined(HAVE_LIBCOMPRESSION)
1035 if (avail_type == CompressionType::None) {
1036 for (auto compression : supported_compressions) {
1037 if (compression == "zlib-deflate") {
1038 avail_type = CompressionType::ZlibDeflate;
1039 avail_name = compression;
1040 break;
1041 }
1042 }
1043 }
1044 #endif
1045
1046 #if defined(HAVE_LIBZ)
1047 if (avail_type == CompressionType::None) {
1048 for (auto compression : supported_compressions) {
1049 if (compression == "zlib-deflate") {
1050 avail_type = CompressionType::ZlibDeflate;
1051 avail_name = compression;
1052 break;
1053 }
1054 }
1055 }
1056 #endif
1057
1058 #if defined(HAVE_LIBCOMPRESSION)
1059 if (avail_type == CompressionType::None) {
1060 for (auto compression : supported_compressions) {
1061 if (compression == "lz4") {
1062 avail_type = CompressionType::LZ4;
1063 avail_name = compression;
1064 break;
1065 }
1066 }
1067 }
1068 #endif
1069
1070 #if defined(HAVE_LIBCOMPRESSION)
1071 if (avail_type == CompressionType::None) {
1072 for (auto compression : supported_compressions) {
1073 if (compression == "lzma") {
1074 avail_type = CompressionType::LZMA;
1075 avail_name = compression;
1076 break;
1077 }
1078 }
1079 }
1080 #endif
1081
1082 if (avail_type != CompressionType::None) {
1083 StringExtractorGDBRemote response;
1084 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1085 if (SendPacketAndWaitForResponse(packet, response, false) !=
1086 PacketResult::Success)
1087 return;
1088
1089 if (response.IsOKResponse()) {
1090 m_compression_type = avail_type;
1091 }
1092 }
1093 }
1094
GetGDBServerProgramName()1095 const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1096 if (GetGDBServerVersion()) {
1097 if (!m_gdb_server_name.empty())
1098 return m_gdb_server_name.c_str();
1099 }
1100 return NULL;
1101 }
1102
GetGDBServerProgramVersion()1103 uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1104 if (GetGDBServerVersion())
1105 return m_gdb_server_version;
1106 return 0;
1107 }
1108
GetDefaultThreadId(lldb::tid_t & tid)1109 bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1110 StringExtractorGDBRemote response;
1111 if (SendPacketAndWaitForResponse("qC", response, false) !=
1112 PacketResult::Success)
1113 return false;
1114
1115 if (!response.IsNormalResponse())
1116 return false;
1117
1118 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1119 tid = response.GetHexMaxU32(true, -1);
1120
1121 return true;
1122 }
1123
GetHostInfo(bool force)1124 bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1125 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1126
1127 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1128 // host info computation can require DNS traffic and shelling out to external processes.
1129 // Increase the timeout to account for that.
1130 ScopedTimeout timeout(*this, seconds(10));
1131 m_qHostInfo_is_valid = eLazyBoolNo;
1132 StringExtractorGDBRemote response;
1133 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1134 PacketResult::Success) {
1135 if (response.IsNormalResponse()) {
1136 llvm::StringRef name;
1137 llvm::StringRef value;
1138 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1139 uint32_t sub = 0;
1140 std::string arch_name;
1141 std::string os_name;
1142 std::string vendor_name;
1143 std::string triple;
1144 std::string distribution_id;
1145 uint32_t pointer_byte_size = 0;
1146 ByteOrder byte_order = eByteOrderInvalid;
1147 uint32_t num_keys_decoded = 0;
1148 while (response.GetNameColonValue(name, value)) {
1149 if (name.equals("cputype")) {
1150 // exception type in big endian hex
1151 if (!value.getAsInteger(0, cpu))
1152 ++num_keys_decoded;
1153 } else if (name.equals("cpusubtype")) {
1154 // exception count in big endian hex
1155 if (!value.getAsInteger(0, sub))
1156 ++num_keys_decoded;
1157 } else if (name.equals("arch")) {
1158 arch_name = value;
1159 ++num_keys_decoded;
1160 } else if (name.equals("triple")) {
1161 StringExtractor extractor(value);
1162 extractor.GetHexByteString(triple);
1163 ++num_keys_decoded;
1164 } else if (name.equals("distribution_id")) {
1165 StringExtractor extractor(value);
1166 extractor.GetHexByteString(distribution_id);
1167 ++num_keys_decoded;
1168 } else if (name.equals("os_build")) {
1169 StringExtractor extractor(value);
1170 extractor.GetHexByteString(m_os_build);
1171 ++num_keys_decoded;
1172 } else if (name.equals("hostname")) {
1173 StringExtractor extractor(value);
1174 extractor.GetHexByteString(m_hostname);
1175 ++num_keys_decoded;
1176 } else if (name.equals("os_kernel")) {
1177 StringExtractor extractor(value);
1178 extractor.GetHexByteString(m_os_kernel);
1179 ++num_keys_decoded;
1180 } else if (name.equals("ostype")) {
1181 os_name = value;
1182 ++num_keys_decoded;
1183 } else if (name.equals("vendor")) {
1184 vendor_name = value;
1185 ++num_keys_decoded;
1186 } else if (name.equals("endian")) {
1187 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1188 .Case("little", eByteOrderLittle)
1189 .Case("big", eByteOrderBig)
1190 .Case("pdp", eByteOrderPDP)
1191 .Default(eByteOrderInvalid);
1192 if (byte_order != eByteOrderInvalid)
1193 ++num_keys_decoded;
1194 } else if (name.equals("ptrsize")) {
1195 if (!value.getAsInteger(0, pointer_byte_size))
1196 ++num_keys_decoded;
1197 } else if (name.equals("os_version") ||
1198 name.equals(
1199 "version")) // Older debugserver binaries used the
1200 // "version" key instead of
1201 // "os_version"...
1202 {
1203 if (!m_os_version.tryParse(value))
1204 ++num_keys_decoded;
1205 } else if (name.equals("watchpoint_exceptions_received")) {
1206 m_watchpoints_trigger_after_instruction =
1207 llvm::StringSwitch<LazyBool>(value)
1208 .Case("before", eLazyBoolNo)
1209 .Case("after", eLazyBoolYes)
1210 .Default(eLazyBoolCalculate);
1211 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1212 ++num_keys_decoded;
1213 } else if (name.equals("default_packet_timeout")) {
1214 uint32_t timeout_seconds;
1215 if (!value.getAsInteger(0, timeout_seconds)) {
1216 m_default_packet_timeout = seconds(timeout_seconds);
1217 SetPacketTimeout(m_default_packet_timeout);
1218 ++num_keys_decoded;
1219 }
1220 }
1221 }
1222
1223 if (num_keys_decoded > 0)
1224 m_qHostInfo_is_valid = eLazyBoolYes;
1225
1226 if (triple.empty()) {
1227 if (arch_name.empty()) {
1228 if (cpu != LLDB_INVALID_CPUTYPE) {
1229 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1230 if (pointer_byte_size) {
1231 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1232 }
1233 if (byte_order != eByteOrderInvalid) {
1234 assert(byte_order == m_host_arch.GetByteOrder());
1235 }
1236
1237 if (!vendor_name.empty())
1238 m_host_arch.GetTriple().setVendorName(
1239 llvm::StringRef(vendor_name));
1240 if (!os_name.empty())
1241 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1242 }
1243 } else {
1244 std::string triple;
1245 triple += arch_name;
1246 if (!vendor_name.empty() || !os_name.empty()) {
1247 triple += '-';
1248 if (vendor_name.empty())
1249 triple += "unknown";
1250 else
1251 triple += vendor_name;
1252 triple += '-';
1253 if (os_name.empty())
1254 triple += "unknown";
1255 else
1256 triple += os_name;
1257 }
1258 m_host_arch.SetTriple(triple.c_str());
1259
1260 llvm::Triple &host_triple = m_host_arch.GetTriple();
1261 if (host_triple.getVendor() == llvm::Triple::Apple &&
1262 host_triple.getOS() == llvm::Triple::Darwin) {
1263 switch (m_host_arch.GetMachine()) {
1264 case llvm::Triple::aarch64:
1265 case llvm::Triple::arm:
1266 case llvm::Triple::thumb:
1267 host_triple.setOS(llvm::Triple::IOS);
1268 break;
1269 default:
1270 host_triple.setOS(llvm::Triple::MacOSX);
1271 break;
1272 }
1273 }
1274 if (pointer_byte_size) {
1275 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1276 }
1277 if (byte_order != eByteOrderInvalid) {
1278 assert(byte_order == m_host_arch.GetByteOrder());
1279 }
1280 }
1281 } else {
1282 m_host_arch.SetTriple(triple.c_str());
1283 if (pointer_byte_size) {
1284 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1285 }
1286 if (byte_order != eByteOrderInvalid) {
1287 assert(byte_order == m_host_arch.GetByteOrder());
1288 }
1289
1290 if (log)
1291 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1292 "architecture as %s, triple as %s from triple text %s",
1293 __FUNCTION__, m_host_arch.GetArchitectureName()
1294 ? m_host_arch.GetArchitectureName()
1295 : "<null-arch-name>",
1296 m_host_arch.GetTriple().getTriple().c_str(),
1297 triple.c_str());
1298 }
1299 if (!distribution_id.empty())
1300 m_host_arch.SetDistributionId(distribution_id.c_str());
1301 }
1302 }
1303 }
1304 return m_qHostInfo_is_valid == eLazyBoolYes;
1305 }
1306
SendAttach(lldb::pid_t pid,StringExtractorGDBRemote & response)1307 int GDBRemoteCommunicationClient::SendAttach(
1308 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1309 if (pid != LLDB_INVALID_PROCESS_ID) {
1310 char packet[64];
1311 const int packet_len =
1312 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
1313 UNUSED_IF_ASSERT_DISABLED(packet_len);
1314 assert(packet_len < (int)sizeof(packet));
1315 if (SendPacketAndWaitForResponse(packet, response, false) ==
1316 PacketResult::Success) {
1317 if (response.IsErrorResponse())
1318 return response.GetError();
1319 return 0;
1320 }
1321 }
1322 return -1;
1323 }
1324
SendStdinNotification(const char * data,size_t data_len)1325 int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1326 size_t data_len) {
1327 StreamString packet;
1328 packet.PutCString("I");
1329 packet.PutBytesAsRawHex8(data, data_len);
1330 StringExtractorGDBRemote response;
1331 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1332 PacketResult::Success) {
1333 return 0;
1334 }
1335 return response.GetError();
1336 }
1337
1338 const lldb_private::ArchSpec &
GetHostArchitecture()1339 GDBRemoteCommunicationClient::GetHostArchitecture() {
1340 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1341 GetHostInfo();
1342 return m_host_arch;
1343 }
1344
GetHostDefaultPacketTimeout()1345 seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
1346 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1347 GetHostInfo();
1348 return m_default_packet_timeout;
1349 }
1350
AllocateMemory(size_t size,uint32_t permissions)1351 addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1352 uint32_t permissions) {
1353 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1354 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1355 char packet[64];
1356 const int packet_len = ::snprintf(
1357 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1358 permissions & lldb::ePermissionsReadable ? "r" : "",
1359 permissions & lldb::ePermissionsWritable ? "w" : "",
1360 permissions & lldb::ePermissionsExecutable ? "x" : "");
1361 assert(packet_len < (int)sizeof(packet));
1362 UNUSED_IF_ASSERT_DISABLED(packet_len);
1363 StringExtractorGDBRemote response;
1364 if (SendPacketAndWaitForResponse(packet, response, false) ==
1365 PacketResult::Success) {
1366 if (response.IsUnsupportedResponse())
1367 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1368 else if (!response.IsErrorResponse())
1369 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1370 } else {
1371 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1372 }
1373 }
1374 return LLDB_INVALID_ADDRESS;
1375 }
1376
DeallocateMemory(addr_t addr)1377 bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1378 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1379 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1380 char packet[64];
1381 const int packet_len =
1382 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1383 assert(packet_len < (int)sizeof(packet));
1384 UNUSED_IF_ASSERT_DISABLED(packet_len);
1385 StringExtractorGDBRemote response;
1386 if (SendPacketAndWaitForResponse(packet, response, false) ==
1387 PacketResult::Success) {
1388 if (response.IsUnsupportedResponse())
1389 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1390 else if (response.IsOKResponse())
1391 return true;
1392 } else {
1393 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1394 }
1395 }
1396 return false;
1397 }
1398
Detach(bool keep_stopped)1399 Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1400 Status error;
1401
1402 if (keep_stopped) {
1403 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1404 char packet[64];
1405 const int packet_len =
1406 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1407 assert(packet_len < (int)sizeof(packet));
1408 UNUSED_IF_ASSERT_DISABLED(packet_len);
1409 StringExtractorGDBRemote response;
1410 if (SendPacketAndWaitForResponse(packet, response, false) ==
1411 PacketResult::Success &&
1412 response.IsOKResponse()) {
1413 m_supports_detach_stay_stopped = eLazyBoolYes;
1414 } else {
1415 m_supports_detach_stay_stopped = eLazyBoolNo;
1416 }
1417 }
1418
1419 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1420 error.SetErrorString("Stays stopped not supported by this target.");
1421 return error;
1422 } else {
1423 StringExtractorGDBRemote response;
1424 PacketResult packet_result =
1425 SendPacketAndWaitForResponse("D1", response, false);
1426 if (packet_result != PacketResult::Success)
1427 error.SetErrorString("Sending extended disconnect packet failed.");
1428 }
1429 } else {
1430 StringExtractorGDBRemote response;
1431 PacketResult packet_result =
1432 SendPacketAndWaitForResponse("D", response, false);
1433 if (packet_result != PacketResult::Success)
1434 error.SetErrorString("Sending disconnect packet failed.");
1435 }
1436 return error;
1437 }
1438
GetMemoryRegionInfo(lldb::addr_t addr,lldb_private::MemoryRegionInfo & region_info)1439 Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
1440 lldb::addr_t addr, lldb_private::MemoryRegionInfo ®ion_info) {
1441 Status error;
1442 region_info.Clear();
1443
1444 if (m_supports_memory_region_info != eLazyBoolNo) {
1445 m_supports_memory_region_info = eLazyBoolYes;
1446 char packet[64];
1447 const int packet_len = ::snprintf(
1448 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1449 assert(packet_len < (int)sizeof(packet));
1450 UNUSED_IF_ASSERT_DISABLED(packet_len);
1451 StringExtractorGDBRemote response;
1452 if (SendPacketAndWaitForResponse(packet, response, false) ==
1453 PacketResult::Success &&
1454 response.GetResponseType() == StringExtractorGDBRemote::eResponse) {
1455 llvm::StringRef name;
1456 llvm::StringRef value;
1457 addr_t addr_value = LLDB_INVALID_ADDRESS;
1458 bool success = true;
1459 bool saw_permissions = false;
1460 while (success && response.GetNameColonValue(name, value)) {
1461 if (name.equals("start")) {
1462 if (!value.getAsInteger(16, addr_value))
1463 region_info.GetRange().SetRangeBase(addr_value);
1464 } else if (name.equals("size")) {
1465 if (!value.getAsInteger(16, addr_value))
1466 region_info.GetRange().SetByteSize(addr_value);
1467 } else if (name.equals("permissions") &&
1468 region_info.GetRange().IsValid()) {
1469 saw_permissions = true;
1470 if (region_info.GetRange().Contains(addr)) {
1471 if (value.find('r') != llvm::StringRef::npos)
1472 region_info.SetReadable(MemoryRegionInfo::eYes);
1473 else
1474 region_info.SetReadable(MemoryRegionInfo::eNo);
1475
1476 if (value.find('w') != llvm::StringRef::npos)
1477 region_info.SetWritable(MemoryRegionInfo::eYes);
1478 else
1479 region_info.SetWritable(MemoryRegionInfo::eNo);
1480
1481 if (value.find('x') != llvm::StringRef::npos)
1482 region_info.SetExecutable(MemoryRegionInfo::eYes);
1483 else
1484 region_info.SetExecutable(MemoryRegionInfo::eNo);
1485
1486 region_info.SetMapped(MemoryRegionInfo::eYes);
1487 } else {
1488 // The reported region does not contain this address -- we're
1489 // looking at an unmapped page
1490 region_info.SetReadable(MemoryRegionInfo::eNo);
1491 region_info.SetWritable(MemoryRegionInfo::eNo);
1492 region_info.SetExecutable(MemoryRegionInfo::eNo);
1493 region_info.SetMapped(MemoryRegionInfo::eNo);
1494 }
1495 } else if (name.equals("name")) {
1496 StringExtractorGDBRemote name_extractor(value);
1497 std::string name;
1498 name_extractor.GetHexByteString(name);
1499 region_info.SetName(name.c_str());
1500 } else if (name.equals("error")) {
1501 StringExtractorGDBRemote error_extractor(value);
1502 std::string error_string;
1503 // Now convert the HEX bytes into a string value
1504 error_extractor.GetHexByteString(error_string);
1505 error.SetErrorString(error_string.c_str());
1506 }
1507 }
1508
1509 if (region_info.GetRange().IsValid()) {
1510 // We got a valid address range back but no permissions -- which means
1511 // this is an unmapped page
1512 if (!saw_permissions) {
1513 region_info.SetReadable(MemoryRegionInfo::eNo);
1514 region_info.SetWritable(MemoryRegionInfo::eNo);
1515 region_info.SetExecutable(MemoryRegionInfo::eNo);
1516 region_info.SetMapped(MemoryRegionInfo::eNo);
1517 }
1518 } else {
1519 // We got an invalid address range back
1520 error.SetErrorString("Server returned invalid range");
1521 }
1522 } else {
1523 m_supports_memory_region_info = eLazyBoolNo;
1524 }
1525 }
1526
1527 if (m_supports_memory_region_info == eLazyBoolNo) {
1528 error.SetErrorString("qMemoryRegionInfo is not supported");
1529 }
1530
1531 // Try qXfer:memory-map:read to get region information not included in
1532 // qMemoryRegionInfo
1533 MemoryRegionInfo qXfer_region_info;
1534 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info);
1535
1536 if (error.Fail()) {
1537 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use
1538 // the qXfer result as a fallback
1539 if (qXfer_error.Success()) {
1540 region_info = qXfer_region_info;
1541 error.Clear();
1542 } else {
1543 region_info.Clear();
1544 }
1545 } else if (qXfer_error.Success()) {
1546 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if
1547 // both regions are the same range, update the result to include the flash-
1548 // memory information that is specific to the qXfer result.
1549 if (region_info.GetRange() == qXfer_region_info.GetRange()) {
1550 region_info.SetFlash(qXfer_region_info.GetFlash());
1551 region_info.SetBlocksize(qXfer_region_info.GetBlocksize());
1552 }
1553 }
1554 return error;
1555 }
1556
GetQXferMemoryMapRegionInfo(lldb::addr_t addr,MemoryRegionInfo & region)1557 Status GDBRemoteCommunicationClient::GetQXferMemoryMapRegionInfo(
1558 lldb::addr_t addr, MemoryRegionInfo ®ion) {
1559 Status error = LoadQXferMemoryMap();
1560 if (!error.Success())
1561 return error;
1562 for (const auto &map_region : m_qXfer_memory_map) {
1563 if (map_region.GetRange().Contains(addr)) {
1564 region = map_region;
1565 return error;
1566 }
1567 }
1568 error.SetErrorString("Region not found");
1569 return error;
1570 }
1571
LoadQXferMemoryMap()1572 Status GDBRemoteCommunicationClient::LoadQXferMemoryMap() {
1573
1574 Status error;
1575
1576 if (m_qXfer_memory_map_loaded)
1577 // Already loaded, return success
1578 return error;
1579
1580 if (!XMLDocument::XMLEnabled()) {
1581 error.SetErrorString("XML is not supported");
1582 return error;
1583 }
1584
1585 if (!GetQXferMemoryMapReadSupported()) {
1586 error.SetErrorString("Memory map is not supported");
1587 return error;
1588 }
1589
1590 std::string xml;
1591 lldb_private::Status lldberr;
1592 if (!ReadExtFeature(ConstString("memory-map"), ConstString(""), xml,
1593 lldberr)) {
1594 error.SetErrorString("Failed to read memory map");
1595 return error;
1596 }
1597
1598 XMLDocument xml_document;
1599
1600 if (!xml_document.ParseMemory(xml.c_str(), xml.size())) {
1601 error.SetErrorString("Failed to parse memory map xml");
1602 return error;
1603 }
1604
1605 XMLNode map_node = xml_document.GetRootElement("memory-map");
1606 if (!map_node) {
1607 error.SetErrorString("Invalid root node in memory map xml");
1608 return error;
1609 }
1610
1611 m_qXfer_memory_map.clear();
1612
1613 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool {
1614 if (!memory_node.IsElement())
1615 return true;
1616 if (memory_node.GetName() != "memory")
1617 return true;
1618 auto type = memory_node.GetAttributeValue("type", "");
1619 uint64_t start;
1620 uint64_t length;
1621 if (!memory_node.GetAttributeValueAsUnsigned("start", start))
1622 return true;
1623 if (!memory_node.GetAttributeValueAsUnsigned("length", length))
1624 return true;
1625 MemoryRegionInfo region;
1626 region.GetRange().SetRangeBase(start);
1627 region.GetRange().SetByteSize(length);
1628 if (type == "rom") {
1629 region.SetReadable(MemoryRegionInfo::eYes);
1630 this->m_qXfer_memory_map.push_back(region);
1631 } else if (type == "ram") {
1632 region.SetReadable(MemoryRegionInfo::eYes);
1633 region.SetWritable(MemoryRegionInfo::eYes);
1634 this->m_qXfer_memory_map.push_back(region);
1635 } else if (type == "flash") {
1636 region.SetFlash(MemoryRegionInfo::eYes);
1637 memory_node.ForEachChildElement(
1638 [®ion](const XMLNode &prop_node) -> bool {
1639 if (!prop_node.IsElement())
1640 return true;
1641 if (prop_node.GetName() != "property")
1642 return true;
1643 auto propname = prop_node.GetAttributeValue("name", "");
1644 if (propname == "blocksize") {
1645 uint64_t blocksize;
1646 if (prop_node.GetElementTextAsUnsigned(blocksize))
1647 region.SetBlocksize(blocksize);
1648 }
1649 return true;
1650 });
1651 this->m_qXfer_memory_map.push_back(region);
1652 }
1653 return true;
1654 });
1655
1656 m_qXfer_memory_map_loaded = true;
1657
1658 return error;
1659 }
1660
GetWatchpointSupportInfo(uint32_t & num)1661 Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1662 Status error;
1663
1664 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1665 num = m_num_supported_hardware_watchpoints;
1666 return error;
1667 }
1668
1669 // Set num to 0 first.
1670 num = 0;
1671 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1672 char packet[64];
1673 const int packet_len =
1674 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1675 assert(packet_len < (int)sizeof(packet));
1676 UNUSED_IF_ASSERT_DISABLED(packet_len);
1677 StringExtractorGDBRemote response;
1678 if (SendPacketAndWaitForResponse(packet, response, false) ==
1679 PacketResult::Success) {
1680 m_supports_watchpoint_support_info = eLazyBoolYes;
1681 llvm::StringRef name;
1682 llvm::StringRef value;
1683 bool found_num_field = false;
1684 while (response.GetNameColonValue(name, value)) {
1685 if (name.equals("num")) {
1686 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1687 num = m_num_supported_hardware_watchpoints;
1688 found_num_field = true;
1689 }
1690 }
1691 if (!found_num_field) {
1692 m_supports_watchpoint_support_info = eLazyBoolNo;
1693 }
1694 } else {
1695 m_supports_watchpoint_support_info = eLazyBoolNo;
1696 }
1697 }
1698
1699 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1700 error.SetErrorString("qWatchpointSupportInfo is not supported");
1701 }
1702 return error;
1703 }
1704
GetWatchpointSupportInfo(uint32_t & num,bool & after,const ArchSpec & arch)1705 lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
1706 uint32_t &num, bool &after, const ArchSpec &arch) {
1707 Status error(GetWatchpointSupportInfo(num));
1708 if (error.Success())
1709 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1710 return error;
1711 }
1712
1713 lldb_private::Status
GetWatchpointsTriggerAfterInstruction(bool & after,const ArchSpec & arch)1714 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1715 bool &after, const ArchSpec &arch) {
1716 Status error;
1717 llvm::Triple::ArchType atype = arch.GetMachine();
1718
1719 // we assume watchpoints will happen after running the relevant opcode and we
1720 // only want to override this behavior if we have explicitly received a
1721 // qHostInfo telling us otherwise
1722 if (m_qHostInfo_is_valid != eLazyBoolYes) {
1723 // On targets like MIPS and ppc64le, watchpoint exceptions are always
1724 // generated before the instruction is executed. The connected target may
1725 // not support qHostInfo or qWatchpointSupportInfo packets.
1726 after =
1727 !(atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1728 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el ||
1729 atype == llvm::Triple::ppc64le);
1730 } else {
1731 // For MIPS and ppc64le, set m_watchpoints_trigger_after_instruction to
1732 // eLazyBoolNo if it is not calculated before.
1733 if ((m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1734 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1735 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)) ||
1736 atype == llvm::Triple::ppc64le) {
1737 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1738 }
1739
1740 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1741 }
1742 return error;
1743 }
1744
SetSTDIN(const FileSpec & file_spec)1745 int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1746 if (file_spec) {
1747 std::string path{file_spec.GetPath(false)};
1748 StreamString packet;
1749 packet.PutCString("QSetSTDIN:");
1750 packet.PutCStringAsRawHex8(path.c_str());
1751
1752 StringExtractorGDBRemote response;
1753 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1754 PacketResult::Success) {
1755 if (response.IsOKResponse())
1756 return 0;
1757 uint8_t error = response.GetError();
1758 if (error)
1759 return error;
1760 }
1761 }
1762 return -1;
1763 }
1764
SetSTDOUT(const FileSpec & file_spec)1765 int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1766 if (file_spec) {
1767 std::string path{file_spec.GetPath(false)};
1768 StreamString packet;
1769 packet.PutCString("QSetSTDOUT:");
1770 packet.PutCStringAsRawHex8(path.c_str());
1771
1772 StringExtractorGDBRemote response;
1773 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1774 PacketResult::Success) {
1775 if (response.IsOKResponse())
1776 return 0;
1777 uint8_t error = response.GetError();
1778 if (error)
1779 return error;
1780 }
1781 }
1782 return -1;
1783 }
1784
SetSTDERR(const FileSpec & file_spec)1785 int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1786 if (file_spec) {
1787 std::string path{file_spec.GetPath(false)};
1788 StreamString packet;
1789 packet.PutCString("QSetSTDERR:");
1790 packet.PutCStringAsRawHex8(path.c_str());
1791
1792 StringExtractorGDBRemote response;
1793 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1794 PacketResult::Success) {
1795 if (response.IsOKResponse())
1796 return 0;
1797 uint8_t error = response.GetError();
1798 if (error)
1799 return error;
1800 }
1801 }
1802 return -1;
1803 }
1804
GetWorkingDir(FileSpec & working_dir)1805 bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1806 StringExtractorGDBRemote response;
1807 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1808 PacketResult::Success) {
1809 if (response.IsUnsupportedResponse())
1810 return false;
1811 if (response.IsErrorResponse())
1812 return false;
1813 std::string cwd;
1814 response.GetHexByteString(cwd);
1815 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple());
1816 return !cwd.empty();
1817 }
1818 return false;
1819 }
1820
SetWorkingDir(const FileSpec & working_dir)1821 int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1822 if (working_dir) {
1823 std::string path{working_dir.GetPath(false)};
1824 StreamString packet;
1825 packet.PutCString("QSetWorkingDir:");
1826 packet.PutCStringAsRawHex8(path.c_str());
1827
1828 StringExtractorGDBRemote response;
1829 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1830 PacketResult::Success) {
1831 if (response.IsOKResponse())
1832 return 0;
1833 uint8_t error = response.GetError();
1834 if (error)
1835 return error;
1836 }
1837 }
1838 return -1;
1839 }
1840
SetDisableASLR(bool enable)1841 int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1842 char packet[32];
1843 const int packet_len =
1844 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1845 assert(packet_len < (int)sizeof(packet));
1846 UNUSED_IF_ASSERT_DISABLED(packet_len);
1847 StringExtractorGDBRemote response;
1848 if (SendPacketAndWaitForResponse(packet, response, false) ==
1849 PacketResult::Success) {
1850 if (response.IsOKResponse())
1851 return 0;
1852 uint8_t error = response.GetError();
1853 if (error)
1854 return error;
1855 }
1856 return -1;
1857 }
1858
SetDetachOnError(bool enable)1859 int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1860 char packet[32];
1861 const int packet_len = ::snprintf(packet, sizeof(packet),
1862 "QSetDetachOnError:%i", enable ? 1 : 0);
1863 assert(packet_len < (int)sizeof(packet));
1864 UNUSED_IF_ASSERT_DISABLED(packet_len);
1865 StringExtractorGDBRemote response;
1866 if (SendPacketAndWaitForResponse(packet, response, false) ==
1867 PacketResult::Success) {
1868 if (response.IsOKResponse())
1869 return 0;
1870 uint8_t error = response.GetError();
1871 if (error)
1872 return error;
1873 }
1874 return -1;
1875 }
1876
DecodeProcessInfoResponse(StringExtractorGDBRemote & response,ProcessInstanceInfo & process_info)1877 bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1878 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1879 if (response.IsNormalResponse()) {
1880 llvm::StringRef name;
1881 llvm::StringRef value;
1882 StringExtractor extractor;
1883
1884 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1885 uint32_t sub = 0;
1886 std::string vendor;
1887 std::string os_type;
1888
1889 while (response.GetNameColonValue(name, value)) {
1890 if (name.equals("pid")) {
1891 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1892 value.getAsInteger(0, pid);
1893 process_info.SetProcessID(pid);
1894 } else if (name.equals("ppid")) {
1895 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1896 value.getAsInteger(0, pid);
1897 process_info.SetParentProcessID(pid);
1898 } else if (name.equals("uid")) {
1899 uint32_t uid = UINT32_MAX;
1900 value.getAsInteger(0, uid);
1901 process_info.SetUserID(uid);
1902 } else if (name.equals("euid")) {
1903 uint32_t uid = UINT32_MAX;
1904 value.getAsInteger(0, uid);
1905 process_info.SetEffectiveGroupID(uid);
1906 } else if (name.equals("gid")) {
1907 uint32_t gid = UINT32_MAX;
1908 value.getAsInteger(0, gid);
1909 process_info.SetGroupID(gid);
1910 } else if (name.equals("egid")) {
1911 uint32_t gid = UINT32_MAX;
1912 value.getAsInteger(0, gid);
1913 process_info.SetEffectiveGroupID(gid);
1914 } else if (name.equals("triple")) {
1915 StringExtractor extractor(value);
1916 std::string triple;
1917 extractor.GetHexByteString(triple);
1918 process_info.GetArchitecture().SetTriple(triple.c_str());
1919 } else if (name.equals("name")) {
1920 StringExtractor extractor(value);
1921 // The process name from ASCII hex bytes since we can't control the
1922 // characters in a process name
1923 std::string name;
1924 extractor.GetHexByteString(name);
1925 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
1926 } else if (name.equals("cputype")) {
1927 value.getAsInteger(0, cpu);
1928 } else if (name.equals("cpusubtype")) {
1929 value.getAsInteger(0, sub);
1930 } else if (name.equals("vendor")) {
1931 vendor = value;
1932 } else if (name.equals("ostype")) {
1933 os_type = value;
1934 }
1935 }
1936
1937 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1938 if (vendor == "apple") {
1939 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1940 sub);
1941 process_info.GetArchitecture().GetTriple().setVendorName(
1942 llvm::StringRef(vendor));
1943 process_info.GetArchitecture().GetTriple().setOSName(
1944 llvm::StringRef(os_type));
1945 }
1946 }
1947
1948 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1949 return true;
1950 }
1951 return false;
1952 }
1953
GetProcessInfo(lldb::pid_t pid,ProcessInstanceInfo & process_info)1954 bool GDBRemoteCommunicationClient::GetProcessInfo(
1955 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1956 process_info.Clear();
1957
1958 if (m_supports_qProcessInfoPID) {
1959 char packet[32];
1960 const int packet_len =
1961 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1962 assert(packet_len < (int)sizeof(packet));
1963 UNUSED_IF_ASSERT_DISABLED(packet_len);
1964 StringExtractorGDBRemote response;
1965 if (SendPacketAndWaitForResponse(packet, response, false) ==
1966 PacketResult::Success) {
1967 return DecodeProcessInfoResponse(response, process_info);
1968 } else {
1969 m_supports_qProcessInfoPID = false;
1970 return false;
1971 }
1972 }
1973 return false;
1974 }
1975
GetCurrentProcessInfo(bool allow_lazy)1976 bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1977 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1978 GDBR_LOG_PACKETS));
1979
1980 if (allow_lazy) {
1981 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1982 return true;
1983 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1984 return false;
1985 }
1986
1987 GetHostInfo();
1988
1989 StringExtractorGDBRemote response;
1990 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1991 PacketResult::Success) {
1992 if (response.IsNormalResponse()) {
1993 llvm::StringRef name;
1994 llvm::StringRef value;
1995 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1996 uint32_t sub = 0;
1997 std::string arch_name;
1998 std::string os_name;
1999 std::string vendor_name;
2000 std::string triple;
2001 std::string elf_abi;
2002 uint32_t pointer_byte_size = 0;
2003 StringExtractor extractor;
2004 ByteOrder byte_order = eByteOrderInvalid;
2005 uint32_t num_keys_decoded = 0;
2006 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2007 while (response.GetNameColonValue(name, value)) {
2008 if (name.equals("cputype")) {
2009 if (!value.getAsInteger(16, cpu))
2010 ++num_keys_decoded;
2011 } else if (name.equals("cpusubtype")) {
2012 if (!value.getAsInteger(16, sub))
2013 ++num_keys_decoded;
2014 } else if (name.equals("triple")) {
2015 StringExtractor extractor(value);
2016 extractor.GetHexByteString(triple);
2017 ++num_keys_decoded;
2018 } else if (name.equals("ostype")) {
2019 os_name = value;
2020 ++num_keys_decoded;
2021 } else if (name.equals("vendor")) {
2022 vendor_name = value;
2023 ++num_keys_decoded;
2024 } else if (name.equals("endian")) {
2025 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
2026 .Case("little", eByteOrderLittle)
2027 .Case("big", eByteOrderBig)
2028 .Case("pdp", eByteOrderPDP)
2029 .Default(eByteOrderInvalid);
2030 if (byte_order != eByteOrderInvalid)
2031 ++num_keys_decoded;
2032 } else if (name.equals("ptrsize")) {
2033 if (!value.getAsInteger(16, pointer_byte_size))
2034 ++num_keys_decoded;
2035 } else if (name.equals("pid")) {
2036 if (!value.getAsInteger(16, pid))
2037 ++num_keys_decoded;
2038 } else if (name.equals("elf_abi")) {
2039 elf_abi = value;
2040 ++num_keys_decoded;
2041 }
2042 }
2043 if (num_keys_decoded > 0)
2044 m_qProcessInfo_is_valid = eLazyBoolYes;
2045 if (pid != LLDB_INVALID_PROCESS_ID) {
2046 m_curr_pid_is_valid = eLazyBoolYes;
2047 m_curr_pid = pid;
2048 }
2049
2050 // Set the ArchSpec from the triple if we have it.
2051 if (!triple.empty()) {
2052 m_process_arch.SetTriple(triple.c_str());
2053 m_process_arch.SetFlags(elf_abi);
2054 if (pointer_byte_size) {
2055 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2056 }
2057 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
2058 !vendor_name.empty()) {
2059 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2060
2061 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2062 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
2063 switch (triple.getObjectFormat()) {
2064 case llvm::Triple::MachO:
2065 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
2066 break;
2067 case llvm::Triple::ELF:
2068 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
2069 break;
2070 case llvm::Triple::COFF:
2071 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
2072 break;
2073 case llvm::Triple::Wasm:
2074 if (log)
2075 log->Printf("error: not supported target architecture");
2076 return false;
2077 case llvm::Triple::UnknownObjectFormat:
2078 if (log)
2079 log->Printf("error: failed to determine target architecture");
2080 return false;
2081 }
2082
2083 if (pointer_byte_size) {
2084 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
2085 }
2086 if (byte_order != eByteOrderInvalid) {
2087 assert(byte_order == m_process_arch.GetByteOrder());
2088 }
2089 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2090 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2091 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
2092 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
2093 }
2094 return true;
2095 }
2096 } else {
2097 m_qProcessInfo_is_valid = eLazyBoolNo;
2098 }
2099
2100 return false;
2101 }
2102
FindProcesses(const ProcessInstanceInfoMatch & match_info,ProcessInstanceInfoList & process_infos)2103 uint32_t GDBRemoteCommunicationClient::FindProcesses(
2104 const ProcessInstanceInfoMatch &match_info,
2105 ProcessInstanceInfoList &process_infos) {
2106 process_infos.Clear();
2107
2108 if (m_supports_qfProcessInfo) {
2109 StreamString packet;
2110 packet.PutCString("qfProcessInfo");
2111 if (!match_info.MatchAllProcesses()) {
2112 packet.PutChar(':');
2113 const char *name = match_info.GetProcessInfo().GetName();
2114 bool has_name_match = false;
2115 if (name && name[0]) {
2116 has_name_match = true;
2117 NameMatch name_match_type = match_info.GetNameMatchType();
2118 switch (name_match_type) {
2119 case NameMatch::Ignore:
2120 has_name_match = false;
2121 break;
2122
2123 case NameMatch::Equals:
2124 packet.PutCString("name_match:equals;");
2125 break;
2126
2127 case NameMatch::Contains:
2128 packet.PutCString("name_match:contains;");
2129 break;
2130
2131 case NameMatch::StartsWith:
2132 packet.PutCString("name_match:starts_with;");
2133 break;
2134
2135 case NameMatch::EndsWith:
2136 packet.PutCString("name_match:ends_with;");
2137 break;
2138
2139 case NameMatch::RegularExpression:
2140 packet.PutCString("name_match:regex;");
2141 break;
2142 }
2143 if (has_name_match) {
2144 packet.PutCString("name:");
2145 packet.PutBytesAsRawHex8(name, ::strlen(name));
2146 packet.PutChar(';');
2147 }
2148 }
2149
2150 if (match_info.GetProcessInfo().ProcessIDIsValid())
2151 packet.Printf("pid:%" PRIu64 ";",
2152 match_info.GetProcessInfo().GetProcessID());
2153 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2154 packet.Printf("parent_pid:%" PRIu64 ";",
2155 match_info.GetProcessInfo().GetParentProcessID());
2156 if (match_info.GetProcessInfo().UserIDIsValid())
2157 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2158 if (match_info.GetProcessInfo().GroupIDIsValid())
2159 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2160 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2161 packet.Printf("euid:%u;",
2162 match_info.GetProcessInfo().GetEffectiveUserID());
2163 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2164 packet.Printf("egid:%u;",
2165 match_info.GetProcessInfo().GetEffectiveGroupID());
2166 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2167 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2168 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2169 const ArchSpec &match_arch =
2170 match_info.GetProcessInfo().GetArchitecture();
2171 const llvm::Triple &triple = match_arch.GetTriple();
2172 packet.PutCString("triple:");
2173 packet.PutCString(triple.getTriple());
2174 packet.PutChar(';');
2175 }
2176 }
2177 StringExtractorGDBRemote response;
2178 // Increase timeout as the first qfProcessInfo packet takes a long time on
2179 // Android. The value of 1min was arrived at empirically.
2180 ScopedTimeout timeout(*this, minutes(1));
2181 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2182 PacketResult::Success) {
2183 do {
2184 ProcessInstanceInfo process_info;
2185 if (!DecodeProcessInfoResponse(response, process_info))
2186 break;
2187 process_infos.Append(process_info);
2188 response.GetStringRef().clear();
2189 response.SetFilePos(0);
2190 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2191 PacketResult::Success);
2192 } else {
2193 m_supports_qfProcessInfo = false;
2194 return 0;
2195 }
2196 }
2197 return process_infos.GetSize();
2198 }
2199
GetUserName(uint32_t uid,std::string & name)2200 bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2201 std::string &name) {
2202 if (m_supports_qUserName) {
2203 char packet[32];
2204 const int packet_len =
2205 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2206 assert(packet_len < (int)sizeof(packet));
2207 UNUSED_IF_ASSERT_DISABLED(packet_len);
2208 StringExtractorGDBRemote response;
2209 if (SendPacketAndWaitForResponse(packet, response, false) ==
2210 PacketResult::Success) {
2211 if (response.IsNormalResponse()) {
2212 // Make sure we parsed the right number of characters. The response is
2213 // the hex encoded user name and should make up the entire packet. If
2214 // there are any non-hex ASCII bytes, the length won't match below..
2215 if (response.GetHexByteString(name) * 2 ==
2216 response.GetStringRef().size())
2217 return true;
2218 }
2219 } else {
2220 m_supports_qUserName = false;
2221 return false;
2222 }
2223 }
2224 return false;
2225 }
2226
GetGroupName(uint32_t gid,std::string & name)2227 bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2228 std::string &name) {
2229 if (m_supports_qGroupName) {
2230 char packet[32];
2231 const int packet_len =
2232 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2233 assert(packet_len < (int)sizeof(packet));
2234 UNUSED_IF_ASSERT_DISABLED(packet_len);
2235 StringExtractorGDBRemote response;
2236 if (SendPacketAndWaitForResponse(packet, response, false) ==
2237 PacketResult::Success) {
2238 if (response.IsNormalResponse()) {
2239 // Make sure we parsed the right number of characters. The response is
2240 // the hex encoded group name and should make up the entire packet. If
2241 // there are any non-hex ASCII bytes, the length won't match below..
2242 if (response.GetHexByteString(name) * 2 ==
2243 response.GetStringRef().size())
2244 return true;
2245 }
2246 } else {
2247 m_supports_qGroupName = false;
2248 return false;
2249 }
2250 }
2251 return false;
2252 }
2253
SetNonStopMode(const bool enable)2254 bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2255 // Form non-stop packet request
2256 char packet[32];
2257 const int packet_len =
2258 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2259 assert(packet_len < (int)sizeof(packet));
2260 UNUSED_IF_ASSERT_DISABLED(packet_len);
2261
2262 StringExtractorGDBRemote response;
2263 // Send to target
2264 if (SendPacketAndWaitForResponse(packet, response, false) ==
2265 PacketResult::Success)
2266 if (response.IsOKResponse())
2267 return true;
2268
2269 // Failed or not supported
2270 return false;
2271 }
2272
MakeSpeedTestPacket(StreamString & packet,uint32_t send_size,uint32_t recv_size)2273 static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2274 uint32_t recv_size) {
2275 packet.Clear();
2276 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2277 uint32_t bytes_left = send_size;
2278 while (bytes_left > 0) {
2279 if (bytes_left >= 26) {
2280 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2281 bytes_left -= 26;
2282 } else {
2283 packet.Printf("%*.*s;", bytes_left, bytes_left,
2284 "abcdefghijklmnopqrstuvwxyz");
2285 bytes_left = 0;
2286 }
2287 }
2288 }
2289
2290 duration<float>
calculate_standard_deviation(const std::vector<duration<float>> & v)2291 calculate_standard_deviation(const std::vector<duration<float>> &v) {
2292 using Dur = duration<float>;
2293 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2294 Dur mean = sum / v.size();
2295 float accum = 0;
2296 for (auto d : v) {
2297 float delta = (d - mean).count();
2298 accum += delta * delta;
2299 };
2300
2301 return Dur(sqrtf(accum / (v.size() - 1)));
2302 }
2303
TestPacketSpeed(const uint32_t num_packets,uint32_t max_send,uint32_t max_recv,uint64_t recv_amount,bool json,Stream & strm)2304 void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2305 uint32_t max_send,
2306 uint32_t max_recv,
2307 uint64_t recv_amount,
2308 bool json, Stream &strm) {
2309 uint32_t i;
2310 if (SendSpeedTestPacket(0, 0)) {
2311 StreamString packet;
2312 if (json)
2313 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2314 "\"results\" : [",
2315 num_packets);
2316 else
2317 strm.Printf("Testing sending %u packets of various sizes:\n",
2318 num_packets);
2319 strm.Flush();
2320
2321 uint32_t result_idx = 0;
2322 uint32_t send_size;
2323 std::vector<duration<float>> packet_times;
2324
2325 for (send_size = 0; send_size <= max_send;
2326 send_size ? send_size *= 2 : send_size = 4) {
2327 for (uint32_t recv_size = 0; recv_size <= max_recv;
2328 recv_size ? recv_size *= 2 : recv_size = 4) {
2329 MakeSpeedTestPacket(packet, send_size, recv_size);
2330
2331 packet_times.clear();
2332 // Test how long it takes to send 'num_packets' packets
2333 const auto start_time = steady_clock::now();
2334 for (i = 0; i < num_packets; ++i) {
2335 const auto packet_start_time = steady_clock::now();
2336 StringExtractorGDBRemote response;
2337 SendPacketAndWaitForResponse(packet.GetString(), response, false);
2338 const auto packet_end_time = steady_clock::now();
2339 packet_times.push_back(packet_end_time - packet_start_time);
2340 }
2341 const auto end_time = steady_clock::now();
2342 const auto total_time = end_time - start_time;
2343
2344 float packets_per_second =
2345 ((float)num_packets) / duration<float>(total_time).count();
2346 auto average_per_packet = total_time / num_packets;
2347 const duration<float> standard_deviation =
2348 calculate_standard_deviation(packet_times);
2349 if (json) {
2350 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2351 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2352 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
2353 result_idx > 0 ? "," : "", send_size, recv_size,
2354 total_time, standard_deviation);
2355 ++result_idx;
2356 } else {
2357 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2358 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2359 "standard deviation of {5,10:ms+f6}\n",
2360 send_size, recv_size, duration<float>(total_time),
2361 packets_per_second, duration<float>(average_per_packet),
2362 standard_deviation);
2363 }
2364 strm.Flush();
2365 }
2366 }
2367
2368 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
2369 if (json)
2370 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2371 ": %" PRIu64 ",\n \"results\" : [",
2372 recv_amount);
2373 else
2374 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2375 "packet sizes:\n",
2376 k_recv_amount_mb);
2377 strm.Flush();
2378 send_size = 0;
2379 result_idx = 0;
2380 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2381 MakeSpeedTestPacket(packet, send_size, recv_size);
2382
2383 // If we have a receive size, test how long it takes to receive 4MB of
2384 // data
2385 if (recv_size > 0) {
2386 const auto start_time = steady_clock::now();
2387 uint32_t bytes_read = 0;
2388 uint32_t packet_count = 0;
2389 while (bytes_read < recv_amount) {
2390 StringExtractorGDBRemote response;
2391 SendPacketAndWaitForResponse(packet.GetString(), response, false);
2392 bytes_read += recv_size;
2393 ++packet_count;
2394 }
2395 const auto end_time = steady_clock::now();
2396 const auto total_time = end_time - start_time;
2397 float mb_second = ((float)recv_amount) /
2398 duration<float>(total_time).count() /
2399 (1024.0 * 1024.0);
2400 float packets_per_second =
2401 ((float)packet_count) / duration<float>(total_time).count();
2402 const auto average_per_packet = total_time / packet_count;
2403
2404 if (json) {
2405 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2406 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
2407 result_idx > 0 ? "," : "", send_size, recv_size,
2408 total_time);
2409 ++result_idx;
2410 } else {
2411 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2412 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2413 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
2414 send_size, recv_size, packet_count, k_recv_amount_mb,
2415 duration<float>(total_time), mb_second,
2416 packets_per_second, duration<float>(average_per_packet));
2417 }
2418 strm.Flush();
2419 }
2420 }
2421 if (json)
2422 strm.Printf("\n ]\n }\n}\n");
2423 else
2424 strm.EOL();
2425 }
2426 }
2427
SendSpeedTestPacket(uint32_t send_size,uint32_t recv_size)2428 bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2429 uint32_t recv_size) {
2430 StreamString packet;
2431 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2432 uint32_t bytes_left = send_size;
2433 while (bytes_left > 0) {
2434 if (bytes_left >= 26) {
2435 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2436 bytes_left -= 26;
2437 } else {
2438 packet.Printf("%*.*s;", bytes_left, bytes_left,
2439 "abcdefghijklmnopqrstuvwxyz");
2440 bytes_left = 0;
2441 }
2442 }
2443
2444 StringExtractorGDBRemote response;
2445 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2446 PacketResult::Success;
2447 }
2448
LaunchGDBServer(const char * remote_accept_hostname,lldb::pid_t & pid,uint16_t & port,std::string & socket_name)2449 bool GDBRemoteCommunicationClient::LaunchGDBServer(
2450 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2451 std::string &socket_name) {
2452 pid = LLDB_INVALID_PROCESS_ID;
2453 port = 0;
2454 socket_name.clear();
2455
2456 StringExtractorGDBRemote response;
2457 StreamString stream;
2458 stream.PutCString("qLaunchGDBServer;");
2459 std::string hostname;
2460 if (remote_accept_hostname && remote_accept_hostname[0])
2461 hostname = remote_accept_hostname;
2462 else {
2463 if (HostInfo::GetHostname(hostname)) {
2464 // Make the GDB server we launch only accept connections from this host
2465 stream.Printf("host:%s;", hostname.c_str());
2466 } else {
2467 // Make the GDB server we launch accept connections from any host since
2468 // we can't figure out the hostname
2469 stream.Printf("host:*;");
2470 }
2471 }
2472 // give the process a few seconds to startup
2473 ScopedTimeout timeout(*this, seconds(10));
2474
2475 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2476 PacketResult::Success) {
2477 llvm::StringRef name;
2478 llvm::StringRef value;
2479 while (response.GetNameColonValue(name, value)) {
2480 if (name.equals("port"))
2481 value.getAsInteger(0, port);
2482 else if (name.equals("pid"))
2483 value.getAsInteger(0, pid);
2484 else if (name.compare("socket_name") == 0) {
2485 StringExtractor extractor(value);
2486 extractor.GetHexByteString(socket_name);
2487 }
2488 }
2489 return true;
2490 }
2491 return false;
2492 }
2493
QueryGDBServer(std::vector<std::pair<uint16_t,std::string>> & connection_urls)2494 size_t GDBRemoteCommunicationClient::QueryGDBServer(
2495 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2496 connection_urls.clear();
2497
2498 StringExtractorGDBRemote response;
2499 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2500 PacketResult::Success)
2501 return 0;
2502
2503 StructuredData::ObjectSP data =
2504 StructuredData::ParseJSON(response.GetStringRef());
2505 if (!data)
2506 return 0;
2507
2508 StructuredData::Array *array = data->GetAsArray();
2509 if (!array)
2510 return 0;
2511
2512 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2513 StructuredData::Dictionary *element = nullptr;
2514 if (!array->GetItemAtIndexAsDictionary(i, element))
2515 continue;
2516
2517 uint16_t port = 0;
2518 if (StructuredData::ObjectSP port_osp =
2519 element->GetValueForKey(llvm::StringRef("port")))
2520 port = port_osp->GetIntegerValue(0);
2521
2522 std::string socket_name;
2523 if (StructuredData::ObjectSP socket_name_osp =
2524 element->GetValueForKey(llvm::StringRef("socket_name")))
2525 socket_name = socket_name_osp->GetStringValue();
2526
2527 if (port != 0 || !socket_name.empty())
2528 connection_urls.emplace_back(port, socket_name);
2529 }
2530 return connection_urls.size();
2531 }
2532
KillSpawnedProcess(lldb::pid_t pid)2533 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2534 StreamString stream;
2535 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
2536
2537 StringExtractorGDBRemote response;
2538 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2539 PacketResult::Success) {
2540 if (response.IsOKResponse())
2541 return true;
2542 }
2543 return false;
2544 }
2545
SetCurrentThread(uint64_t tid)2546 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2547 if (m_curr_tid == tid)
2548 return true;
2549
2550 char packet[32];
2551 int packet_len;
2552 if (tid == UINT64_MAX)
2553 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2554 else
2555 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2556 assert(packet_len + 1 < (int)sizeof(packet));
2557 UNUSED_IF_ASSERT_DISABLED(packet_len);
2558 StringExtractorGDBRemote response;
2559 if (SendPacketAndWaitForResponse(packet, response, false) ==
2560 PacketResult::Success) {
2561 if (response.IsOKResponse()) {
2562 m_curr_tid = tid;
2563 return true;
2564 }
2565
2566 /*
2567 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2568 * Hg packet.
2569 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2570 * which can
2571 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2572 */
2573 if (response.IsUnsupportedResponse() && IsConnected()) {
2574 m_curr_tid = 1;
2575 return true;
2576 }
2577 }
2578 return false;
2579 }
2580
SetCurrentThreadForRun(uint64_t tid)2581 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2582 if (m_curr_tid_run == tid)
2583 return true;
2584
2585 char packet[32];
2586 int packet_len;
2587 if (tid == UINT64_MAX)
2588 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2589 else
2590 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2591
2592 assert(packet_len + 1 < (int)sizeof(packet));
2593 UNUSED_IF_ASSERT_DISABLED(packet_len);
2594 StringExtractorGDBRemote response;
2595 if (SendPacketAndWaitForResponse(packet, response, false) ==
2596 PacketResult::Success) {
2597 if (response.IsOKResponse()) {
2598 m_curr_tid_run = tid;
2599 return true;
2600 }
2601
2602 /*
2603 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2604 * Hc packet.
2605 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2606 * which can
2607 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2608 */
2609 if (response.IsUnsupportedResponse() && IsConnected()) {
2610 m_curr_tid_run = 1;
2611 return true;
2612 }
2613 }
2614 return false;
2615 }
2616
GetStopReply(StringExtractorGDBRemote & response)2617 bool GDBRemoteCommunicationClient::GetStopReply(
2618 StringExtractorGDBRemote &response) {
2619 if (SendPacketAndWaitForResponse("?", response, false) ==
2620 PacketResult::Success)
2621 return response.IsNormalResponse();
2622 return false;
2623 }
2624
GetThreadStopInfo(lldb::tid_t tid,StringExtractorGDBRemote & response)2625 bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2626 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2627 if (m_supports_qThreadStopInfo) {
2628 char packet[256];
2629 int packet_len =
2630 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2631 assert(packet_len < (int)sizeof(packet));
2632 UNUSED_IF_ASSERT_DISABLED(packet_len);
2633 if (SendPacketAndWaitForResponse(packet, response, false) ==
2634 PacketResult::Success) {
2635 if (response.IsUnsupportedResponse())
2636 m_supports_qThreadStopInfo = false;
2637 else if (response.IsNormalResponse())
2638 return true;
2639 else
2640 return false;
2641 } else {
2642 m_supports_qThreadStopInfo = false;
2643 }
2644 }
2645 return false;
2646 }
2647
SendGDBStoppointTypePacket(GDBStoppointType type,bool insert,addr_t addr,uint32_t length)2648 uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2649 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2650 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2651 if (log)
2652 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2653 __FUNCTION__, insert ? "add" : "remove", addr);
2654
2655 // Check if the stub is known not to support this breakpoint type
2656 if (!SupportsGDBStoppointPacket(type))
2657 return UINT8_MAX;
2658 // Construct the breakpoint packet
2659 char packet[64];
2660 const int packet_len =
2661 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2662 insert ? 'Z' : 'z', type, addr, length);
2663 // Check we haven't overwritten the end of the packet buffer
2664 assert(packet_len + 1 < (int)sizeof(packet));
2665 UNUSED_IF_ASSERT_DISABLED(packet_len);
2666 StringExtractorGDBRemote response;
2667 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2668 // or "" (unsupported)
2669 response.SetResponseValidatorToOKErrorNotSupported();
2670 // Try to send the breakpoint packet, and check that it was correctly sent
2671 if (SendPacketAndWaitForResponse(packet, response, true) ==
2672 PacketResult::Success) {
2673 // Receive and OK packet when the breakpoint successfully placed
2674 if (response.IsOKResponse())
2675 return 0;
2676
2677 // Status while setting breakpoint, send back specific error
2678 if (response.IsErrorResponse())
2679 return response.GetError();
2680
2681 // Empty packet informs us that breakpoint is not supported
2682 if (response.IsUnsupportedResponse()) {
2683 // Disable this breakpoint type since it is unsupported
2684 switch (type) {
2685 case eBreakpointSoftware:
2686 m_supports_z0 = false;
2687 break;
2688 case eBreakpointHardware:
2689 m_supports_z1 = false;
2690 break;
2691 case eWatchpointWrite:
2692 m_supports_z2 = false;
2693 break;
2694 case eWatchpointRead:
2695 m_supports_z3 = false;
2696 break;
2697 case eWatchpointReadWrite:
2698 m_supports_z4 = false;
2699 break;
2700 case eStoppointInvalid:
2701 return UINT8_MAX;
2702 }
2703 }
2704 }
2705 // Signal generic failure
2706 return UINT8_MAX;
2707 }
2708
GetCurrentThreadIDs(std::vector<lldb::tid_t> & thread_ids,bool & sequence_mutex_unavailable)2709 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2710 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2711 thread_ids.clear();
2712
2713 Lock lock(*this, false);
2714 if (lock) {
2715 sequence_mutex_unavailable = false;
2716 StringExtractorGDBRemote response;
2717
2718 PacketResult packet_result;
2719 for (packet_result =
2720 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2721 packet_result == PacketResult::Success && response.IsNormalResponse();
2722 packet_result =
2723 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2724 char ch = response.GetChar();
2725 if (ch == 'l')
2726 break;
2727 if (ch == 'm') {
2728 do {
2729 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2730
2731 if (tid != LLDB_INVALID_THREAD_ID) {
2732 thread_ids.push_back(tid);
2733 }
2734 ch = response.GetChar(); // Skip the command separator
2735 } while (ch == ','); // Make sure we got a comma separator
2736 }
2737 }
2738
2739 /*
2740 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2741 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2742 * could
2743 * be as simple as 'S05'. There is no packet which can give us pid and/or
2744 * tid.
2745 * Assume pid=tid=1 in such cases.
2746 */
2747 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2748 thread_ids.size() == 0 && IsConnected()) {
2749 thread_ids.push_back(1);
2750 }
2751 } else {
2752 #if !defined(LLDB_CONFIGURATION_DEBUG)
2753 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2754 GDBR_LOG_PACKETS));
2755 if (log)
2756 log->Printf("error: failed to get packet sequence mutex, not sending "
2757 "packet 'qfThreadInfo'");
2758 #endif
2759 sequence_mutex_unavailable = true;
2760 }
2761 return thread_ids.size();
2762 }
2763
GetShlibInfoAddr()2764 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2765 StringExtractorGDBRemote response;
2766 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2767 PacketResult::Success ||
2768 !response.IsNormalResponse())
2769 return LLDB_INVALID_ADDRESS;
2770 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2771 }
2772
RunShellCommand(const char * command,const FileSpec & working_dir,int * status_ptr,int * signo_ptr,std::string * command_output,const Timeout<std::micro> & timeout)2773 lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
2774 const char *command, // Shouldn't be NULL
2775 const FileSpec &
2776 working_dir, // Pass empty FileSpec to use the current working directory
2777 int *status_ptr, // Pass NULL if you don't want the process exit status
2778 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2779 // process to exit
2780 std::string
2781 *command_output, // Pass NULL if you don't want the command output
2782 const Timeout<std::micro> &timeout) {
2783 lldb_private::StreamString stream;
2784 stream.PutCString("qPlatform_shell:");
2785 stream.PutBytesAsRawHex8(command, strlen(command));
2786 stream.PutChar(',');
2787 uint32_t timeout_sec = UINT32_MAX;
2788 if (timeout) {
2789 // TODO: Use chrono version of std::ceil once c++17 is available.
2790 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count());
2791 }
2792 stream.PutHex32(timeout_sec);
2793 if (working_dir) {
2794 std::string path{working_dir.GetPath(false)};
2795 stream.PutChar(',');
2796 stream.PutCStringAsRawHex8(path.c_str());
2797 }
2798 StringExtractorGDBRemote response;
2799 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2800 PacketResult::Success) {
2801 if (response.GetChar() != 'F')
2802 return Status("malformed reply");
2803 if (response.GetChar() != ',')
2804 return Status("malformed reply");
2805 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2806 if (exitcode == UINT32_MAX)
2807 return Status("unable to run remote process");
2808 else if (status_ptr)
2809 *status_ptr = exitcode;
2810 if (response.GetChar() != ',')
2811 return Status("malformed reply");
2812 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2813 if (signo_ptr)
2814 *signo_ptr = signo;
2815 if (response.GetChar() != ',')
2816 return Status("malformed reply");
2817 std::string output;
2818 response.GetEscapedBinaryData(output);
2819 if (command_output)
2820 command_output->assign(output);
2821 return Status();
2822 }
2823 return Status("unable to send packet");
2824 }
2825
MakeDirectory(const FileSpec & file_spec,uint32_t file_permissions)2826 Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2827 uint32_t file_permissions) {
2828 std::string path{file_spec.GetPath(false)};
2829 lldb_private::StreamString stream;
2830 stream.PutCString("qPlatform_mkdir:");
2831 stream.PutHex32(file_permissions);
2832 stream.PutChar(',');
2833 stream.PutCStringAsRawHex8(path.c_str());
2834 llvm::StringRef packet = stream.GetString();
2835 StringExtractorGDBRemote response;
2836
2837 if (SendPacketAndWaitForResponse(packet, response, false) !=
2838 PacketResult::Success)
2839 return Status("failed to send '%s' packet", packet.str().c_str());
2840
2841 if (response.GetChar() != 'F')
2842 return Status("invalid response to '%s' packet", packet.str().c_str());
2843
2844 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2845 }
2846
2847 Status
SetFilePermissions(const FileSpec & file_spec,uint32_t file_permissions)2848 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2849 uint32_t file_permissions) {
2850 std::string path{file_spec.GetPath(false)};
2851 lldb_private::StreamString stream;
2852 stream.PutCString("qPlatform_chmod:");
2853 stream.PutHex32(file_permissions);
2854 stream.PutChar(',');
2855 stream.PutCStringAsRawHex8(path.c_str());
2856 llvm::StringRef packet = stream.GetString();
2857 StringExtractorGDBRemote response;
2858
2859 if (SendPacketAndWaitForResponse(packet, response, false) !=
2860 PacketResult::Success)
2861 return Status("failed to send '%s' packet", stream.GetData());
2862
2863 if (response.GetChar() != 'F')
2864 return Status("invalid response to '%s' packet", stream.GetData());
2865
2866 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2867 }
2868
ParseHostIOPacketResponse(StringExtractorGDBRemote & response,uint64_t fail_result,Status & error)2869 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
2870 uint64_t fail_result, Status &error) {
2871 response.SetFilePos(0);
2872 if (response.GetChar() != 'F')
2873 return fail_result;
2874 int32_t result = response.GetS32(-2);
2875 if (result == -2)
2876 return fail_result;
2877 if (response.GetChar() == ',') {
2878 int result_errno = response.GetS32(-2);
2879 if (result_errno != -2)
2880 error.SetError(result_errno, eErrorTypePOSIX);
2881 else
2882 error.SetError(-1, eErrorTypeGeneric);
2883 } else
2884 error.Clear();
2885 return result;
2886 }
2887 lldb::user_id_t
OpenFile(const lldb_private::FileSpec & file_spec,uint32_t flags,mode_t mode,Status & error)2888 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2889 uint32_t flags, mode_t mode,
2890 Status &error) {
2891 std::string path(file_spec.GetPath(false));
2892 lldb_private::StreamString stream;
2893 stream.PutCString("vFile:open:");
2894 if (path.empty())
2895 return UINT64_MAX;
2896 stream.PutCStringAsRawHex8(path.c_str());
2897 stream.PutChar(',');
2898 stream.PutHex32(flags);
2899 stream.PutChar(',');
2900 stream.PutHex32(mode);
2901 StringExtractorGDBRemote response;
2902 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2903 PacketResult::Success) {
2904 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2905 }
2906 return UINT64_MAX;
2907 }
2908
CloseFile(lldb::user_id_t fd,Status & error)2909 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2910 Status &error) {
2911 lldb_private::StreamString stream;
2912 stream.Printf("vFile:close:%i", (int)fd);
2913 StringExtractorGDBRemote response;
2914 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2915 PacketResult::Success) {
2916 return ParseHostIOPacketResponse(response, -1, error) == 0;
2917 }
2918 return false;
2919 }
2920
2921 // Extension of host I/O packets to get the file size.
GetFileSize(const lldb_private::FileSpec & file_spec)2922 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2923 const lldb_private::FileSpec &file_spec) {
2924 std::string path(file_spec.GetPath(false));
2925 lldb_private::StreamString stream;
2926 stream.PutCString("vFile:size:");
2927 stream.PutCStringAsRawHex8(path.c_str());
2928 StringExtractorGDBRemote response;
2929 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2930 PacketResult::Success) {
2931 if (response.GetChar() != 'F')
2932 return UINT64_MAX;
2933 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2934 return retcode;
2935 }
2936 return UINT64_MAX;
2937 }
2938
2939 Status
GetFilePermissions(const FileSpec & file_spec,uint32_t & file_permissions)2940 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2941 uint32_t &file_permissions) {
2942 std::string path{file_spec.GetPath(false)};
2943 Status error;
2944 lldb_private::StreamString stream;
2945 stream.PutCString("vFile:mode:");
2946 stream.PutCStringAsRawHex8(path.c_str());
2947 StringExtractorGDBRemote response;
2948 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2949 PacketResult::Success) {
2950 if (response.GetChar() != 'F') {
2951 error.SetErrorStringWithFormat("invalid response to '%s' packet",
2952 stream.GetData());
2953 } else {
2954 const uint32_t mode = response.GetS32(-1);
2955 if (static_cast<int32_t>(mode) == -1) {
2956 if (response.GetChar() == ',') {
2957 int response_errno = response.GetS32(-1);
2958 if (response_errno > 0)
2959 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2960 else
2961 error.SetErrorToGenericError();
2962 } else
2963 error.SetErrorToGenericError();
2964 } else {
2965 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2966 }
2967 }
2968 } else {
2969 error.SetErrorStringWithFormat("failed to send '%s' packet",
2970 stream.GetData());
2971 }
2972 return error;
2973 }
2974
ReadFile(lldb::user_id_t fd,uint64_t offset,void * dst,uint64_t dst_len,Status & error)2975 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2976 uint64_t offset, void *dst,
2977 uint64_t dst_len,
2978 Status &error) {
2979 lldb_private::StreamString stream;
2980 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2981 offset);
2982 StringExtractorGDBRemote response;
2983 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2984 PacketResult::Success) {
2985 if (response.GetChar() != 'F')
2986 return 0;
2987 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2988 if (retcode == UINT32_MAX)
2989 return retcode;
2990 const char next = (response.Peek() ? *response.Peek() : 0);
2991 if (next == ',')
2992 return 0;
2993 if (next == ';') {
2994 response.GetChar(); // skip the semicolon
2995 std::string buffer;
2996 if (response.GetEscapedBinaryData(buffer)) {
2997 const uint64_t data_to_write =
2998 std::min<uint64_t>(dst_len, buffer.size());
2999 if (data_to_write > 0)
3000 memcpy(dst, &buffer[0], data_to_write);
3001 return data_to_write;
3002 }
3003 }
3004 }
3005 return 0;
3006 }
3007
WriteFile(lldb::user_id_t fd,uint64_t offset,const void * src,uint64_t src_len,Status & error)3008 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
3009 uint64_t offset,
3010 const void *src,
3011 uint64_t src_len,
3012 Status &error) {
3013 lldb_private::StreamGDBRemote stream;
3014 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3015 stream.PutEscapedBytes(src, src_len);
3016 StringExtractorGDBRemote response;
3017 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3018 PacketResult::Success) {
3019 if (response.GetChar() != 'F') {
3020 error.SetErrorStringWithFormat("write file failed");
3021 return 0;
3022 }
3023 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3024 if (bytes_written == UINT64_MAX) {
3025 error.SetErrorToGenericError();
3026 if (response.GetChar() == ',') {
3027 int response_errno = response.GetS32(-1);
3028 if (response_errno > 0)
3029 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3030 }
3031 return 0;
3032 }
3033 return bytes_written;
3034 } else {
3035 error.SetErrorString("failed to send vFile:pwrite packet");
3036 }
3037 return 0;
3038 }
3039
CreateSymlink(const FileSpec & src,const FileSpec & dst)3040 Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
3041 const FileSpec &dst) {
3042 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
3043 Status error;
3044 lldb_private::StreamGDBRemote stream;
3045 stream.PutCString("vFile:symlink:");
3046 // the unix symlink() command reverses its parameters where the dst if first,
3047 // so we follow suit here
3048 stream.PutCStringAsRawHex8(dst_path.c_str());
3049 stream.PutChar(',');
3050 stream.PutCStringAsRawHex8(src_path.c_str());
3051 StringExtractorGDBRemote response;
3052 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3053 PacketResult::Success) {
3054 if (response.GetChar() == 'F') {
3055 uint32_t result = response.GetU32(UINT32_MAX);
3056 if (result != 0) {
3057 error.SetErrorToGenericError();
3058 if (response.GetChar() == ',') {
3059 int response_errno = response.GetS32(-1);
3060 if (response_errno > 0)
3061 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3062 }
3063 }
3064 } else {
3065 // Should have returned with 'F<result>[,<errno>]'
3066 error.SetErrorStringWithFormat("symlink failed");
3067 }
3068 } else {
3069 error.SetErrorString("failed to send vFile:symlink packet");
3070 }
3071 return error;
3072 }
3073
Unlink(const FileSpec & file_spec)3074 Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
3075 std::string path{file_spec.GetPath(false)};
3076 Status error;
3077 lldb_private::StreamGDBRemote stream;
3078 stream.PutCString("vFile:unlink:");
3079 // the unix symlink() command reverses its parameters where the dst if first,
3080 // so we follow suit here
3081 stream.PutCStringAsRawHex8(path.c_str());
3082 StringExtractorGDBRemote response;
3083 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3084 PacketResult::Success) {
3085 if (response.GetChar() == 'F') {
3086 uint32_t result = response.GetU32(UINT32_MAX);
3087 if (result != 0) {
3088 error.SetErrorToGenericError();
3089 if (response.GetChar() == ',') {
3090 int response_errno = response.GetS32(-1);
3091 if (response_errno > 0)
3092 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3093 }
3094 }
3095 } else {
3096 // Should have returned with 'F<result>[,<errno>]'
3097 error.SetErrorStringWithFormat("unlink failed");
3098 }
3099 } else {
3100 error.SetErrorString("failed to send vFile:unlink packet");
3101 }
3102 return error;
3103 }
3104
3105 // Extension of host I/O packets to get whether a file exists.
GetFileExists(const lldb_private::FileSpec & file_spec)3106 bool GDBRemoteCommunicationClient::GetFileExists(
3107 const lldb_private::FileSpec &file_spec) {
3108 std::string path(file_spec.GetPath(false));
3109 lldb_private::StreamString stream;
3110 stream.PutCString("vFile:exists:");
3111 stream.PutCStringAsRawHex8(path.c_str());
3112 StringExtractorGDBRemote response;
3113 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3114 PacketResult::Success) {
3115 if (response.GetChar() != 'F')
3116 return false;
3117 if (response.GetChar() != ',')
3118 return false;
3119 bool retcode = (response.GetChar() != '0');
3120 return retcode;
3121 }
3122 return false;
3123 }
3124
CalculateMD5(const lldb_private::FileSpec & file_spec,uint64_t & high,uint64_t & low)3125 bool GDBRemoteCommunicationClient::CalculateMD5(
3126 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3127 std::string path(file_spec.GetPath(false));
3128 lldb_private::StreamString stream;
3129 stream.PutCString("vFile:MD5:");
3130 stream.PutCStringAsRawHex8(path.c_str());
3131 StringExtractorGDBRemote response;
3132 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
3133 PacketResult::Success) {
3134 if (response.GetChar() != 'F')
3135 return false;
3136 if (response.GetChar() != ',')
3137 return false;
3138 if (response.Peek() && *response.Peek() == 'x')
3139 return false;
3140 low = response.GetHexMaxU64(false, UINT64_MAX);
3141 high = response.GetHexMaxU64(false, UINT64_MAX);
3142 return true;
3143 }
3144 return false;
3145 }
3146
AvoidGPackets(ProcessGDBRemote * process)3147 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3148 // Some targets have issues with g/G packets and we need to avoid using them
3149 if (m_avoid_g_packets == eLazyBoolCalculate) {
3150 if (process) {
3151 m_avoid_g_packets = eLazyBoolNo;
3152 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3153 if (arch.IsValid() &&
3154 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3155 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3156 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3157 m_avoid_g_packets = eLazyBoolYes;
3158 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3159 if (gdb_server_version != 0) {
3160 const char *gdb_server_name = GetGDBServerProgramName();
3161 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3162 if (gdb_server_version >= 310)
3163 m_avoid_g_packets = eLazyBoolNo;
3164 }
3165 }
3166 }
3167 }
3168 }
3169 return m_avoid_g_packets == eLazyBoolYes;
3170 }
3171
ReadRegister(lldb::tid_t tid,uint32_t reg)3172 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3173 uint32_t reg) {
3174 StreamString payload;
3175 payload.Printf("p%x", reg);
3176 StringExtractorGDBRemote response;
3177 if (SendThreadSpecificPacketAndWaitForResponse(
3178 tid, std::move(payload), response, false) != PacketResult::Success ||
3179 !response.IsNormalResponse())
3180 return nullptr;
3181
3182 DataBufferSP buffer_sp(
3183 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3184 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3185 return buffer_sp;
3186 }
3187
ReadAllRegisters(lldb::tid_t tid)3188 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3189 StreamString payload;
3190 payload.PutChar('g');
3191 StringExtractorGDBRemote response;
3192 if (SendThreadSpecificPacketAndWaitForResponse(
3193 tid, std::move(payload), response, false) != PacketResult::Success ||
3194 !response.IsNormalResponse())
3195 return nullptr;
3196
3197 DataBufferSP buffer_sp(
3198 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3199 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3200 return buffer_sp;
3201 }
3202
WriteRegister(lldb::tid_t tid,uint32_t reg_num,llvm::ArrayRef<uint8_t> data)3203 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3204 uint32_t reg_num,
3205 llvm::ArrayRef<uint8_t> data) {
3206 StreamString payload;
3207 payload.Printf("P%x=", reg_num);
3208 payload.PutBytesAsRawHex8(data.data(), data.size(),
3209 endian::InlHostByteOrder(),
3210 endian::InlHostByteOrder());
3211 StringExtractorGDBRemote response;
3212 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3213 response, false) ==
3214 PacketResult::Success &&
3215 response.IsOKResponse();
3216 }
3217
WriteAllRegisters(lldb::tid_t tid,llvm::ArrayRef<uint8_t> data)3218 bool GDBRemoteCommunicationClient::WriteAllRegisters(
3219 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3220 StreamString payload;
3221 payload.PutChar('G');
3222 payload.PutBytesAsRawHex8(data.data(), data.size(),
3223 endian::InlHostByteOrder(),
3224 endian::InlHostByteOrder());
3225 StringExtractorGDBRemote response;
3226 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3227 response, false) ==
3228 PacketResult::Success &&
3229 response.IsOKResponse();
3230 }
3231
SaveRegisterState(lldb::tid_t tid,uint32_t & save_id)3232 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3233 uint32_t &save_id) {
3234 save_id = 0; // Set to invalid save ID
3235 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3236 return false;
3237
3238 m_supports_QSaveRegisterState = eLazyBoolYes;
3239 StreamString payload;
3240 payload.PutCString("QSaveRegisterState");
3241 StringExtractorGDBRemote response;
3242 if (SendThreadSpecificPacketAndWaitForResponse(
3243 tid, std::move(payload), response, false) != PacketResult::Success)
3244 return false;
3245
3246 if (response.IsUnsupportedResponse())
3247 m_supports_QSaveRegisterState = eLazyBoolNo;
3248
3249 const uint32_t response_save_id = response.GetU32(0);
3250 if (response_save_id == 0)
3251 return false;
3252
3253 save_id = response_save_id;
3254 return true;
3255 }
3256
RestoreRegisterState(lldb::tid_t tid,uint32_t save_id)3257 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3258 uint32_t save_id) {
3259 // We use the "m_supports_QSaveRegisterState" variable here because the
3260 // QSaveRegisterState and QRestoreRegisterState packets must both be
3261 // supported in order to be useful
3262 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3263 return false;
3264
3265 StreamString payload;
3266 payload.Printf("QRestoreRegisterState:%u", save_id);
3267 StringExtractorGDBRemote response;
3268 if (SendThreadSpecificPacketAndWaitForResponse(
3269 tid, std::move(payload), response, false) != PacketResult::Success)
3270 return false;
3271
3272 if (response.IsOKResponse())
3273 return true;
3274
3275 if (response.IsUnsupportedResponse())
3276 m_supports_QSaveRegisterState = eLazyBoolNo;
3277 return false;
3278 }
3279
SyncThreadState(lldb::tid_t tid)3280 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3281 if (!GetSyncThreadStateSupported())
3282 return false;
3283
3284 StreamString packet;
3285 StringExtractorGDBRemote response;
3286 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3287 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3288 GDBRemoteCommunication::PacketResult::Success &&
3289 response.IsOKResponse();
3290 }
3291
3292 lldb::user_id_t
SendStartTracePacket(const TraceOptions & options,Status & error)3293 GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3294 Status &error) {
3295 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3296 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3297
3298 StreamGDBRemote escaped_packet;
3299 escaped_packet.PutCString("jTraceStart:");
3300
3301 StructuredData::Dictionary json_packet;
3302 json_packet.AddIntegerItem("type", options.getType());
3303 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3304 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3305
3306 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3307 json_packet.AddIntegerItem("threadid", options.getThreadID());
3308
3309 StructuredData::DictionarySP custom_params = options.getTraceParams();
3310 if (custom_params)
3311 json_packet.AddItem("params", custom_params);
3312
3313 StreamString json_string;
3314 json_packet.Dump(json_string, false);
3315 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3316
3317 StringExtractorGDBRemote response;
3318 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3319 true) ==
3320 GDBRemoteCommunication::PacketResult::Success) {
3321 if (!response.IsNormalResponse()) {
3322 error = response.GetStatus();
3323 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
3324 } else {
3325 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3326 }
3327 } else {
3328 LLDB_LOG(log, "failed to send packet");
3329 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3330 escaped_packet.GetData());
3331 }
3332 return ret_uid;
3333 }
3334
3335 Status
SendStopTracePacket(lldb::user_id_t uid,lldb::tid_t thread_id)3336 GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3337 lldb::tid_t thread_id) {
3338 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3339 StringExtractorGDBRemote response;
3340 Status error;
3341
3342 StructuredData::Dictionary json_packet;
3343 StreamGDBRemote escaped_packet;
3344 StreamString json_string;
3345 escaped_packet.PutCString("jTraceStop:");
3346
3347 json_packet.AddIntegerItem("traceid", uid);
3348
3349 if (thread_id != LLDB_INVALID_THREAD_ID)
3350 json_packet.AddIntegerItem("threadid", thread_id);
3351
3352 json_packet.Dump(json_string, false);
3353
3354 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3355
3356 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3357 true) ==
3358 GDBRemoteCommunication::PacketResult::Success) {
3359 if (!response.IsOKResponse()) {
3360 error = response.GetStatus();
3361 LLDB_LOG(log, "stop tracing failed");
3362 }
3363 } else {
3364 LLDB_LOG(log, "failed to send packet");
3365 error.SetErrorStringWithFormat(
3366 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3367 response.GetError());
3368 }
3369 return error;
3370 }
3371
SendGetDataPacket(lldb::user_id_t uid,lldb::tid_t thread_id,llvm::MutableArrayRef<uint8_t> & buffer,size_t offset)3372 Status GDBRemoteCommunicationClient::SendGetDataPacket(
3373 lldb::user_id_t uid, lldb::tid_t thread_id,
3374 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3375
3376 StreamGDBRemote escaped_packet;
3377 escaped_packet.PutCString("jTraceBufferRead:");
3378 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3379 }
3380
SendGetMetaDataPacket(lldb::user_id_t uid,lldb::tid_t thread_id,llvm::MutableArrayRef<uint8_t> & buffer,size_t offset)3381 Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3382 lldb::user_id_t uid, lldb::tid_t thread_id,
3383 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3384
3385 StreamGDBRemote escaped_packet;
3386 escaped_packet.PutCString("jTraceMetaRead:");
3387 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3388 }
3389
3390 Status
SendGetTraceConfigPacket(lldb::user_id_t uid,TraceOptions & options)3391 GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3392 TraceOptions &options) {
3393 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3394 StringExtractorGDBRemote response;
3395 Status error;
3396
3397 StreamString json_string;
3398 StreamGDBRemote escaped_packet;
3399 escaped_packet.PutCString("jTraceConfigRead:");
3400
3401 StructuredData::Dictionary json_packet;
3402 json_packet.AddIntegerItem("traceid", uid);
3403
3404 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3405 json_packet.AddIntegerItem("threadid", options.getThreadID());
3406
3407 json_packet.Dump(json_string, false);
3408 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3409
3410 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3411 true) ==
3412 GDBRemoteCommunication::PacketResult::Success) {
3413 if (response.IsNormalResponse()) {
3414 uint64_t type = std::numeric_limits<uint64_t>::max();
3415 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3416 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3417
3418 auto json_object = StructuredData::ParseJSON(response.Peek());
3419
3420 if (!json_object ||
3421 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
3422 error.SetErrorString("Invalid Configuration obtained");
3423 return error;
3424 }
3425
3426 auto json_dict = json_object->GetAsDictionary();
3427
3428 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3429 metabuffersize);
3430 options.setMetaDataBufferSize(metabuffersize);
3431
3432 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3433 options.setTraceBufferSize(buffersize);
3434
3435 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3436 options.setType(static_cast<lldb::TraceType>(type));
3437
3438 StructuredData::ObjectSP custom_params_sp =
3439 json_dict->GetValueForKey("params");
3440 if (custom_params_sp) {
3441 if (custom_params_sp->GetType() !=
3442 lldb::eStructuredDataTypeDictionary) {
3443 error.SetErrorString("Invalid Configuration obtained");
3444 return error;
3445 } else
3446 options.setTraceParams(
3447 static_pointer_cast<StructuredData::Dictionary>(
3448 custom_params_sp));
3449 }
3450 } else {
3451 error = response.GetStatus();
3452 }
3453 } else {
3454 LLDB_LOG(log, "failed to send packet");
3455 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3456 escaped_packet.GetData());
3457 }
3458 return error;
3459 }
3460
SendGetTraceDataPacket(StreamGDBRemote & packet,lldb::user_id_t uid,lldb::tid_t thread_id,llvm::MutableArrayRef<uint8_t> & buffer,size_t offset)3461 Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3462 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3463 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3464 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3465 Status error;
3466
3467 StructuredData::Dictionary json_packet;
3468
3469 json_packet.AddIntegerItem("traceid", uid);
3470 json_packet.AddIntegerItem("offset", offset);
3471 json_packet.AddIntegerItem("buffersize", buffer.size());
3472
3473 if (thread_id != LLDB_INVALID_THREAD_ID)
3474 json_packet.AddIntegerItem("threadid", thread_id);
3475
3476 StreamString json_string;
3477 json_packet.Dump(json_string, false);
3478
3479 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3480 StringExtractorGDBRemote response;
3481 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3482 GDBRemoteCommunication::PacketResult::Success) {
3483 if (response.IsNormalResponse()) {
3484 size_t filled_size = response.GetHexBytesAvail(buffer);
3485 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3486 } else {
3487 error = response.GetStatus();
3488 buffer = buffer.slice(buffer.size());
3489 }
3490 } else {
3491 LLDB_LOG(log, "failed to send packet");
3492 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3493 packet.GetData());
3494 buffer = buffer.slice(buffer.size());
3495 }
3496 return error;
3497 }
3498
GetModuleInfo(const FileSpec & module_file_spec,const lldb_private::ArchSpec & arch_spec,ModuleSpec & module_spec)3499 bool GDBRemoteCommunicationClient::GetModuleInfo(
3500 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3501 ModuleSpec &module_spec) {
3502 if (!m_supports_qModuleInfo)
3503 return false;
3504
3505 std::string module_path = module_file_spec.GetPath(false);
3506 if (module_path.empty())
3507 return false;
3508
3509 StreamString packet;
3510 packet.PutCString("qModuleInfo:");
3511 packet.PutCStringAsRawHex8(module_path.c_str());
3512 packet.PutCString(";");
3513 const auto &triple = arch_spec.GetTriple().getTriple();
3514 packet.PutCStringAsRawHex8(triple.c_str());
3515
3516 StringExtractorGDBRemote response;
3517 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3518 PacketResult::Success)
3519 return false;
3520
3521 if (response.IsErrorResponse())
3522 return false;
3523
3524 if (response.IsUnsupportedResponse()) {
3525 m_supports_qModuleInfo = false;
3526 return false;
3527 }
3528
3529 llvm::StringRef name;
3530 llvm::StringRef value;
3531
3532 module_spec.Clear();
3533 module_spec.GetFileSpec() = module_file_spec;
3534
3535 while (response.GetNameColonValue(name, value)) {
3536 if (name == "uuid" || name == "md5") {
3537 StringExtractor extractor(value);
3538 std::string uuid;
3539 extractor.GetHexByteString(uuid);
3540 module_spec.GetUUID().SetFromStringRef(uuid, uuid.size() / 2);
3541 } else if (name == "triple") {
3542 StringExtractor extractor(value);
3543 std::string triple;
3544 extractor.GetHexByteString(triple);
3545 module_spec.GetArchitecture().SetTriple(triple.c_str());
3546 } else if (name == "file_offset") {
3547 uint64_t ival = 0;
3548 if (!value.getAsInteger(16, ival))
3549 module_spec.SetObjectOffset(ival);
3550 } else if (name == "file_size") {
3551 uint64_t ival = 0;
3552 if (!value.getAsInteger(16, ival))
3553 module_spec.SetObjectSize(ival);
3554 } else if (name == "file_path") {
3555 StringExtractor extractor(value);
3556 std::string path;
3557 extractor.GetHexByteString(path);
3558 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple());
3559 }
3560 }
3561
3562 return true;
3563 }
3564
3565 static llvm::Optional<ModuleSpec>
ParseModuleSpec(StructuredData::Dictionary * dict)3566 ParseModuleSpec(StructuredData::Dictionary *dict) {
3567 ModuleSpec result;
3568 if (!dict)
3569 return llvm::None;
3570
3571 llvm::StringRef string;
3572 uint64_t integer;
3573
3574 if (!dict->GetValueForKeyAsString("uuid", string))
3575 return llvm::None;
3576 if (result.GetUUID().SetFromStringRef(string, string.size() / 2) !=
3577 string.size())
3578 return llvm::None;
3579
3580 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3581 return llvm::None;
3582 result.SetObjectOffset(integer);
3583
3584 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3585 return llvm::None;
3586 result.SetObjectSize(integer);
3587
3588 if (!dict->GetValueForKeyAsString("triple", string))
3589 return llvm::None;
3590 result.GetArchitecture().SetTriple(string);
3591
3592 if (!dict->GetValueForKeyAsString("file_path", string))
3593 return llvm::None;
3594 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple());
3595
3596 return result;
3597 }
3598
3599 llvm::Optional<std::vector<ModuleSpec>>
GetModulesInfo(llvm::ArrayRef<FileSpec> module_file_specs,const llvm::Triple & triple)3600 GDBRemoteCommunicationClient::GetModulesInfo(
3601 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3602 if (!m_supports_jModulesInfo)
3603 return llvm::None;
3604
3605 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3606 for (const FileSpec &module_file_spec : module_file_specs) {
3607 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3608 module_array_sp->AppendObject(module_sp);
3609 module_sp->SetObject(
3610 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
3611 module_sp->SetObject("triple",
3612 std::make_shared<JSONString>(triple.getTriple()));
3613 }
3614 StreamString unescaped_payload;
3615 unescaped_payload.PutCString("jModulesInfo:");
3616 module_array_sp->Write(unescaped_payload);
3617 StreamGDBRemote payload;
3618 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
3619 unescaped_payload.GetSize());
3620
3621 // Increase the timeout for jModulesInfo since this packet can take longer.
3622 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3623
3624 StringExtractorGDBRemote response;
3625 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3626 PacketResult::Success ||
3627 response.IsErrorResponse())
3628 return llvm::None;
3629
3630 if (response.IsUnsupportedResponse()) {
3631 m_supports_jModulesInfo = false;
3632 return llvm::None;
3633 }
3634
3635 StructuredData::ObjectSP response_object_sp =
3636 StructuredData::ParseJSON(response.GetStringRef());
3637 if (!response_object_sp)
3638 return llvm::None;
3639
3640 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3641 if (!response_array)
3642 return llvm::None;
3643
3644 std::vector<ModuleSpec> result;
3645 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3646 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3647 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3648 result.push_back(*module_spec);
3649 }
3650
3651 return result;
3652 }
3653
3654 // query the target remote for extended information using the qXfer packet
3655 //
3656 // example: object='features', annex='target.xml', out=<xml output> return:
3657 // 'true' on success
3658 // 'false' on failure (err set)
ReadExtFeature(const lldb_private::ConstString object,const lldb_private::ConstString annex,std::string & out,lldb_private::Status & err)3659 bool GDBRemoteCommunicationClient::ReadExtFeature(
3660 const lldb_private::ConstString object,
3661 const lldb_private::ConstString annex, std::string &out,
3662 lldb_private::Status &err) {
3663
3664 std::stringstream output;
3665 StringExtractorGDBRemote chunk;
3666
3667 uint64_t size = GetRemoteMaxPacketSize();
3668 if (size == 0)
3669 size = 0x1000;
3670 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3671 int offset = 0;
3672 bool active = true;
3673
3674 // loop until all data has been read
3675 while (active) {
3676
3677 // send query extended feature packet
3678 std::stringstream packet;
3679 packet << "qXfer:" << object.AsCString("")
3680 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3681 << "," << std::hex << size;
3682
3683 GDBRemoteCommunication::PacketResult res =
3684 SendPacketAndWaitForResponse(packet.str(), chunk, false);
3685
3686 if (res != GDBRemoteCommunication::PacketResult::Success) {
3687 err.SetErrorString("Error sending $qXfer packet");
3688 return false;
3689 }
3690
3691 const std::string &str = chunk.GetStringRef();
3692 if (str.length() == 0) {
3693 // should have some data in chunk
3694 err.SetErrorString("Empty response from $qXfer packet");
3695 return false;
3696 }
3697
3698 // check packet code
3699 switch (str[0]) {
3700 // last chunk
3701 case ('l'):
3702 active = false;
3703 LLVM_FALLTHROUGH;
3704
3705 // more chunks
3706 case ('m'):
3707 if (str.length() > 1)
3708 output << &str[1];
3709 offset += size;
3710 break;
3711
3712 // unknown chunk
3713 default:
3714 err.SetErrorString("Invalid continuation code from $qXfer packet");
3715 return false;
3716 }
3717 }
3718
3719 out = output.str();
3720 err.Success();
3721 return true;
3722 }
3723
3724 // Notify the target that gdb is prepared to serve symbol lookup requests.
3725 // packet: "qSymbol::"
3726 // reply:
3727 // OK The target does not need to look up any (more) symbols.
3728 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3729 // encoded).
3730 // LLDB may provide the value by sending another qSymbol
3731 // packet
3732 // in the form of"qSymbol:<sym_value>:<sym_name>".
3733 //
3734 // Three examples:
3735 //
3736 // lldb sends: qSymbol::
3737 // lldb receives: OK
3738 // Remote gdb stub does not need to know the addresses of any symbols, lldb
3739 // does not
3740 // need to ask again in this session.
3741 //
3742 // lldb sends: qSymbol::
3743 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3744 // lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3745 // lldb receives: OK
3746 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3747 // not know
3748 // the address at this time. lldb needs to send qSymbol:: again when it has
3749 // more
3750 // solibs loaded.
3751 //
3752 // lldb sends: qSymbol::
3753 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3754 // lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3755 // lldb receives: OK
3756 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3757 // that it
3758 // is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3759 // does not
3760 // need any more symbols. lldb does not need to ask again in this session.
3761
ServeSymbolLookups(lldb_private::Process * process)3762 void GDBRemoteCommunicationClient::ServeSymbolLookups(
3763 lldb_private::Process *process) {
3764 // Set to true once we've resolved a symbol to an address for the remote
3765 // stub. If we get an 'OK' response after this, the remote stub doesn't need
3766 // any more symbols and we can stop asking.
3767 bool symbol_response_provided = false;
3768
3769 // Is this the initial qSymbol:: packet?
3770 bool first_qsymbol_query = true;
3771
3772 if (m_supports_qSymbol && !m_qSymbol_requests_done) {
3773 Lock lock(*this, false);
3774 if (lock) {
3775 StreamString packet;
3776 packet.PutCString("qSymbol::");
3777 StringExtractorGDBRemote response;
3778 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3779 PacketResult::Success) {
3780 if (response.IsOKResponse()) {
3781 if (symbol_response_provided || first_qsymbol_query) {
3782 m_qSymbol_requests_done = true;
3783 }
3784
3785 // We are done serving symbols requests
3786 return;
3787 }
3788 first_qsymbol_query = false;
3789
3790 if (response.IsUnsupportedResponse()) {
3791 // qSymbol is not supported by the current GDB server we are
3792 // connected to
3793 m_supports_qSymbol = false;
3794 return;
3795 } else {
3796 llvm::StringRef response_str(response.GetStringRef());
3797 if (response_str.startswith("qSymbol:")) {
3798 response.SetFilePos(strlen("qSymbol:"));
3799 std::string symbol_name;
3800 if (response.GetHexByteString(symbol_name)) {
3801 if (symbol_name.empty())
3802 return;
3803
3804 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3805 lldb_private::SymbolContextList sc_list;
3806 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3807 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3808 const size_t num_scs = sc_list.GetSize();
3809 for (size_t sc_idx = 0;
3810 sc_idx < num_scs &&
3811 symbol_load_addr == LLDB_INVALID_ADDRESS;
3812 ++sc_idx) {
3813 SymbolContext sc;
3814 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3815 if (sc.symbol) {
3816 switch (sc.symbol->GetType()) {
3817 case eSymbolTypeInvalid:
3818 case eSymbolTypeAbsolute:
3819 case eSymbolTypeUndefined:
3820 case eSymbolTypeSourceFile:
3821 case eSymbolTypeHeaderFile:
3822 case eSymbolTypeObjectFile:
3823 case eSymbolTypeCommonBlock:
3824 case eSymbolTypeBlock:
3825 case eSymbolTypeLocal:
3826 case eSymbolTypeParam:
3827 case eSymbolTypeVariable:
3828 case eSymbolTypeVariableType:
3829 case eSymbolTypeLineEntry:
3830 case eSymbolTypeLineHeader:
3831 case eSymbolTypeScopeBegin:
3832 case eSymbolTypeScopeEnd:
3833 case eSymbolTypeAdditional:
3834 case eSymbolTypeCompiler:
3835 case eSymbolTypeInstrumentation:
3836 case eSymbolTypeTrampoline:
3837 break;
3838
3839 case eSymbolTypeCode:
3840 case eSymbolTypeResolver:
3841 case eSymbolTypeData:
3842 case eSymbolTypeRuntime:
3843 case eSymbolTypeException:
3844 case eSymbolTypeObjCClass:
3845 case eSymbolTypeObjCMetaClass:
3846 case eSymbolTypeObjCIVar:
3847 case eSymbolTypeReExported:
3848 symbol_load_addr =
3849 sc.symbol->GetLoadAddress(&process->GetTarget());
3850 break;
3851 }
3852 }
3853 }
3854 }
3855 }
3856 // This is the normal path where our symbol lookup was successful
3857 // and we want to send a packet with the new symbol value and see
3858 // if another lookup needs to be done.
3859
3860 // Change "packet" to contain the requested symbol value and name
3861 packet.Clear();
3862 packet.PutCString("qSymbol:");
3863 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3864 packet.Printf("%" PRIx64, symbol_load_addr);
3865 symbol_response_provided = true;
3866 } else {
3867 symbol_response_provided = false;
3868 }
3869 packet.PutCString(":");
3870 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3871 continue; // go back to the while loop and send "packet" and wait
3872 // for another response
3873 }
3874 }
3875 }
3876 }
3877 // If we make it here, the symbol request packet response wasn't valid or
3878 // our symbol lookup failed so we must abort
3879 return;
3880
3881 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3882 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3883 log->Printf(
3884 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3885 __FUNCTION__);
3886 }
3887 }
3888 }
3889
3890 StructuredData::Array *
GetSupportedStructuredDataPlugins()3891 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3892 if (!m_supported_async_json_packets_is_valid) {
3893 // Query the server for the array of supported asynchronous JSON packets.
3894 m_supported_async_json_packets_is_valid = true;
3895
3896 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3897
3898 // Poll it now.
3899 StringExtractorGDBRemote response;
3900 const bool send_async = false;
3901 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3902 send_async) == PacketResult::Success) {
3903 m_supported_async_json_packets_sp =
3904 StructuredData::ParseJSON(response.GetStringRef());
3905 if (m_supported_async_json_packets_sp &&
3906 !m_supported_async_json_packets_sp->GetAsArray()) {
3907 // We were returned something other than a JSON array. This is
3908 // invalid. Clear it out.
3909 if (log)
3910 log->Printf("GDBRemoteCommunicationClient::%s(): "
3911 "QSupportedAsyncJSONPackets returned invalid "
3912 "result: %s",
3913 __FUNCTION__, response.GetStringRef().c_str());
3914 m_supported_async_json_packets_sp.reset();
3915 }
3916 } else {
3917 if (log)
3918 log->Printf("GDBRemoteCommunicationClient::%s(): "
3919 "QSupportedAsyncJSONPackets unsupported",
3920 __FUNCTION__);
3921 }
3922
3923 if (log && m_supported_async_json_packets_sp) {
3924 StreamString stream;
3925 m_supported_async_json_packets_sp->Dump(stream);
3926 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3927 "JSON packets: %s",
3928 __FUNCTION__, stream.GetData());
3929 }
3930 }
3931
3932 return m_supported_async_json_packets_sp
3933 ? m_supported_async_json_packets_sp->GetAsArray()
3934 : nullptr;
3935 }
3936
SendSignalsToIgnore(llvm::ArrayRef<int32_t> signals)3937 Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
3938 llvm::ArrayRef<int32_t> signals) {
3939 // Format packet:
3940 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3941 auto range = llvm::make_range(signals.begin(), signals.end());
3942 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3943
3944 StringExtractorGDBRemote response;
3945 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3946
3947 if (send_status != GDBRemoteCommunication::PacketResult::Success)
3948 return Status("Sending QPassSignals packet failed");
3949
3950 if (response.IsOKResponse()) {
3951 return Status();
3952 } else {
3953 return Status("Unknown error happened during sending QPassSignals packet.");
3954 }
3955 }
3956
ConfigureRemoteStructuredData(const ConstString & type_name,const StructuredData::ObjectSP & config_sp)3957 Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
3958 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
3959 Status error;
3960
3961 if (type_name.GetLength() == 0) {
3962 error.SetErrorString("invalid type_name argument");
3963 return error;
3964 }
3965
3966 // Build command: Configure{type_name}: serialized config data.
3967 StreamGDBRemote stream;
3968 stream.PutCString("QConfigure");
3969 stream.PutCString(type_name.AsCString());
3970 stream.PutChar(':');
3971 if (config_sp) {
3972 // Gather the plain-text version of the configuration data.
3973 StreamString unescaped_stream;
3974 config_sp->Dump(unescaped_stream);
3975 unescaped_stream.Flush();
3976
3977 // Add it to the stream in escaped fashion.
3978 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
3979 unescaped_stream.GetSize());
3980 }
3981 stream.Flush();
3982
3983 // Send the packet.
3984 const bool send_async = false;
3985 StringExtractorGDBRemote response;
3986 auto result =
3987 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
3988 if (result == PacketResult::Success) {
3989 // We failed if the config result comes back other than OK.
3990 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3991 // Okay!
3992 error.Clear();
3993 } else {
3994 error.SetErrorStringWithFormat("configuring StructuredData feature "
3995 "%s failed with error %s",
3996 type_name.AsCString(),
3997 response.GetStringRef().c_str());
3998 }
3999 } else {
4000 // Can we get more data here on the failure?
4001 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
4002 "failed when sending packet: "
4003 "PacketResult=%d",
4004 type_name.AsCString(), (int)result);
4005 }
4006 return error;
4007 }
4008
OnRunPacketSent(bool first)4009 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
4010 GDBRemoteClientBase::OnRunPacketSent(first);
4011 m_curr_tid = LLDB_INVALID_THREAD_ID;
4012 }
4013