blob: 49733a5ba752763e80551afc71fc799ce6e9f7a6 [file] [log] [blame]
Greg Clayton576d8832011-03-22 04:00:09 +00001//===-- 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
Greg Clayton576d8832011-03-22 04:00:09 +000010#include "GDBRemoteCommunicationClient.h"
11
12// C Includes
Greg Claytone034a042015-05-21 20:52:06 +000013#include <math.h>
Daniel Maleab89d0492013-08-28 16:06:16 +000014#include <sys/stat.h>
15
Greg Clayton576d8832011-03-22 04:00:09 +000016// C++ Includes
Greg Claytone034a042015-05-21 20:52:06 +000017#include <numeric>
Kate Stoneb9c1b512016-09-06 20:57:50 +000018#include <sstream>
Han Ming Ong4b6459f2013-01-18 23:11:53 +000019
Greg Clayton576d8832011-03-22 04:00:09 +000020// Other libraries and framework includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000021#include "lldb/Core/DataBufferHeap.h"
Greg Clayton576d8832011-03-22 04:00:09 +000022#include "lldb/Core/Log.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000023#include "lldb/Core/ModuleSpec.h"
Greg Clayton576d8832011-03-22 04:00:09 +000024#include "lldb/Core/State.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000025#include "lldb/Core/StreamGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000026#include "lldb/Core/StreamString.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000027#include "lldb/Host/HostInfo.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000028#include "lldb/Host/StringConvert.h"
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000029#include "lldb/Interpreter/Args.h"
Greg Clayton0b90be12015-06-23 21:27:50 +000030#include "lldb/Symbol/Symbol.h"
Pavel Labath4cb69922016-07-29 15:41:52 +000031#include "lldb/Target/MemoryRegionInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000032#include "lldb/Target/Target.h"
Todd Fiala75930012016-08-19 04:21:48 +000033#include "lldb/Target/UnixSignals.h"
Pavel Labath2f1fbae2016-09-08 10:07:04 +000034#include "lldb/Utility/JSON.h"
Todd Fiala75930012016-08-19 04:21:48 +000035#include "lldb/Utility/LLDBAssert.h"
Greg Clayton576d8832011-03-22 04:00:09 +000036
37// Project includes
Greg Clayton576d8832011-03-22 04:00:09 +000038#include "ProcessGDBRemote.h"
39#include "ProcessGDBRemoteLog.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000040#include "Utility/StringExtractorGDBRemote.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000041#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000042
Zachary Turner54695a32016-08-29 19:58:14 +000043#include "llvm/ADT/StringSwitch.h"
44
Kate Stoneb9c1b512016-09-06 20:57:50 +000045#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000046#include <compression.h>
47#endif
48
Greg Clayton576d8832011-03-22 04:00:09 +000049using namespace lldb;
50using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000051using namespace lldb_private::process_gdb_remote;
Greg Clayton576d8832011-03-22 04:00:09 +000052
53//----------------------------------------------------------------------
54// GDBRemoteCommunicationClient constructor
55//----------------------------------------------------------------------
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000056GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000057 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000058 m_supports_not_sending_acks(eLazyBoolCalculate),
59 m_supports_thread_suffix(eLazyBoolCalculate),
60 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
61 m_supports_vCont_all(eLazyBoolCalculate),
62 m_supports_vCont_any(eLazyBoolCalculate),
63 m_supports_vCont_c(eLazyBoolCalculate),
64 m_supports_vCont_C(eLazyBoolCalculate),
65 m_supports_vCont_s(eLazyBoolCalculate),
66 m_supports_vCont_S(eLazyBoolCalculate),
67 m_qHostInfo_is_valid(eLazyBoolCalculate),
68 m_curr_pid_is_valid(eLazyBoolCalculate),
69 m_qProcessInfo_is_valid(eLazyBoolCalculate),
70 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
71 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
72 m_supports_memory_region_info(eLazyBoolCalculate),
73 m_supports_watchpoint_support_info(eLazyBoolCalculate),
74 m_supports_detach_stay_stopped(eLazyBoolCalculate),
75 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
76 m_attach_or_wait_reply(eLazyBoolCalculate),
77 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000078 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000079 m_avoid_g_packets(eLazyBoolCalculate),
80 m_supports_QSaveRegisterState(eLazyBoolCalculate),
81 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
82 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
83 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
84 m_supports_qXfer_features_read(eLazyBoolCalculate),
85 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
86 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
87 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000088 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000089 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),
Pavel Labath2f1fbae2016-09-08 10:07:04 +000096 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
97 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000098 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
Kate Stoneb9c1b512016-09-06 20:57:50 +000099 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(),
100 m_os_version_major(UINT32_MAX), m_os_version_minor(UINT32_MAX),
101 m_os_version_update(UINT32_MAX), m_os_build(), m_os_kernel(),
102 m_hostname(), m_gdb_server_name(), m_gdb_server_version(UINT32_MAX),
103 m_default_packet_timeout(0), m_max_packet_size(0),
104 m_qSupported_response(), m_supported_async_json_packets_is_valid(false),
105 m_supported_async_json_packets_sp() {}
Greg Clayton576d8832011-03-22 04:00:09 +0000106
107//----------------------------------------------------------------------
108// Destructor
109//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() {
111 if (IsConnected())
112 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000113}
114
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115bool GDBRemoteCommunicationClient::HandshakeWithServer(Error *error_ptr) {
116 ResetDiscoverableSettings(false);
Greg Claytonfb909312013-11-23 01:58:15 +0000117
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118 // Start the read thread after we send the handshake ack since if we
119 // fail to 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 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
126 while (packet_result == PacketResult::Success)
127 packet_result = ReadPacket(response, timeout_usec, false);
Ed Maste48f986f2013-12-18 15:31:45 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 // The return value from QueryNoAckModeSupported() is true if the packet
130 // was sent and _any_ response (including UNIMPLEMENTED) was received),
131 // or false if no response was received. This quickly tells us if we have
132 // a live connection to a remote GDB server...
133 if (QueryNoAckModeSupported()) {
134 return true;
135 } else {
136 if (error_ptr)
137 error_ptr->SetErrorString("failed to get reply to handshake packet");
Greg Claytonfb909312013-11-23 01:58:15 +0000138 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 } else {
140 if (error_ptr)
141 error_ptr->SetErrorString("failed to send the handshake ack");
142 }
143 return false;
Greg Clayton1cb64962011-03-24 04:28:38 +0000144}
145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146bool GDBRemoteCommunicationClient::GetEchoSupported() {
147 if (m_supports_qEcho == eLazyBoolCalculate) {
148 GetRemoteQSupported();
149 }
150 return m_supports_qEcho == eLazyBoolYes;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000151}
152
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
154 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
155 GetRemoteQSupported();
156 }
157 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000158}
159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
161 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
162 GetRemoteQSupported();
163 }
164 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000165}
166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
168 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
169 GetRemoteQSupported();
170 }
171 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000172}
173
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
175 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
176 GetRemoteQSupported();
177 }
178 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000179}
180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
182 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
183 GetRemoteQSupported();
184 }
185 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000186}
187
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
189 if (m_max_packet_size == 0) {
190 GetRemoteQSupported();
191 }
192 return m_max_packet_size;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000193}
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
196 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
197 m_send_acks = true;
198 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000199
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200 // This is the first real packet that we'll send in a debug session and it
201 // may take a little
202 // longer than normal to receive a reply. Wait at least 6 seconds for a
203 // reply to this packet.
Jason Molenda36a216e2014-07-24 01:36:24 +0000204
Pavel Labath3aa04912016-10-31 17:19:42 +0000205 ScopedTimeout timeout(
206 *this, std::max(GetPacketTimeout(), std::chrono::seconds(6)));
Colin Rileyc3c95b22015-04-16 15:51:33 +0000207
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000208 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
210 PacketResult::Success) {
211 if (response.IsOKResponse()) {
212 m_send_acks = false;
213 m_supports_not_sending_acks = eLazyBoolYes;
214 }
215 return true;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000216 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217 }
218 return false;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000219}
Greg Clayton576d8832011-03-22 04:00:09 +0000220
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
222 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
223 m_supports_threads_in_stop_reply = eLazyBoolNo;
224
225 StringExtractorGDBRemote response;
226 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
227 false) == PacketResult::Success) {
228 if (response.IsOKResponse())
229 m_supports_threads_in_stop_reply = eLazyBoolYes;
Pavel Labath5c95ee42016-08-30 13:56:11 +0000230 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000231 }
Pavel Labath0faf3732016-08-25 08:34:57 +0000232}
Greg Clayton576d8832011-03-22 04:00:09 +0000233
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
235 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
236 m_attach_or_wait_reply = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +0000237
Kate Stoneb9c1b512016-09-06 20:57:50 +0000238 StringExtractorGDBRemote response;
239 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
240 false) == PacketResult::Success) {
241 if (response.IsOKResponse())
242 m_attach_or_wait_reply = eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000243 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 }
245 if (m_attach_or_wait_reply == eLazyBoolYes)
246 return true;
247 else
Greg Clayton576d8832011-03-22 04:00:09 +0000248 return false;
249}
250
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
252 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
253 m_prepare_for_reg_writing_reply = eLazyBoolNo;
254
255 StringExtractorGDBRemote response;
256 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
257 false) == PacketResult::Success) {
258 if (response.IsOKResponse())
259 m_prepare_for_reg_writing_reply = eLazyBoolYes;
260 }
261 }
262 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
263 return true;
264 else
265 return false;
266}
267
268void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
269 if (did_exec == false) {
270 // Hard reset everything, this is when we first connect to a GDB server
271 m_supports_not_sending_acks = eLazyBoolCalculate;
272 m_supports_thread_suffix = eLazyBoolCalculate;
273 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
274 m_supports_vCont_c = eLazyBoolCalculate;
275 m_supports_vCont_C = eLazyBoolCalculate;
276 m_supports_vCont_s = eLazyBoolCalculate;
277 m_supports_vCont_S = eLazyBoolCalculate;
278 m_supports_p = eLazyBoolCalculate;
279 m_supports_x = eLazyBoolCalculate;
280 m_supports_QSaveRegisterState = eLazyBoolCalculate;
281 m_qHostInfo_is_valid = eLazyBoolCalculate;
282 m_curr_pid_is_valid = eLazyBoolCalculate;
283 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
284 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
285 m_supports_memory_region_info = eLazyBoolCalculate;
286 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
287 m_attach_or_wait_reply = eLazyBoolCalculate;
288 m_avoid_g_packets = eLazyBoolCalculate;
289 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
290 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
291 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
292 m_supports_qXfer_features_read = eLazyBoolCalculate;
293 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
294 m_supports_qProcessInfoPID = true;
295 m_supports_qfProcessInfo = true;
296 m_supports_qUserName = true;
297 m_supports_qGroupName = true;
298 m_supports_qThreadStopInfo = true;
299 m_supports_z0 = true;
300 m_supports_z1 = true;
301 m_supports_z2 = true;
302 m_supports_z3 = true;
303 m_supports_z4 = true;
304 m_supports_QEnvironment = true;
305 m_supports_QEnvironmentHexEncoded = true;
306 m_supports_qSymbol = true;
307 m_qSymbol_requests_done = false;
308 m_supports_qModuleInfo = true;
309 m_host_arch.Clear();
310 m_os_version_major = UINT32_MAX;
311 m_os_version_minor = UINT32_MAX;
312 m_os_version_update = UINT32_MAX;
313 m_os_build.clear();
314 m_os_kernel.clear();
315 m_hostname.clear();
316 m_gdb_server_name.clear();
317 m_gdb_server_version = UINT32_MAX;
Pavel Labath3aa04912016-10-31 17:19:42 +0000318 m_default_packet_timeout = std::chrono::seconds(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 m_max_packet_size = 0;
320 m_qSupported_response.clear();
321 m_supported_async_json_packets_is_valid = false;
322 m_supported_async_json_packets_sp.reset();
Pavel Labath2f1fbae2016-09-08 10:07:04 +0000323 m_supports_jModulesInfo = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324 }
325
326 // These flags should be reset when we first connect to a GDB server
327 // and when our inferior process execs
328 m_qProcessInfo_is_valid = eLazyBoolCalculate;
329 m_process_arch.Clear();
330}
331
332void GDBRemoteCommunicationClient::GetRemoteQSupported() {
333 // Clear out any capabilities we expect to see in the qSupported response
334 m_supports_qXfer_auxv_read = eLazyBoolNo;
335 m_supports_qXfer_libraries_read = eLazyBoolNo;
336 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
337 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
338 m_supports_qXfer_features_read = eLazyBoolNo;
339 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
340 // not, we assume no limit
341
342 // build the qSupported packet
343 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
344 StreamString packet;
345 packet.PutCString("qSupported");
346 for (uint32_t i = 0; i < features.size(); ++i) {
347 packet.PutCString(i == 0 ? ":" : ";");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000348 packet.PutCString(features[i]);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 }
350
351 StringExtractorGDBRemote response;
352 if (SendPacketAndWaitForResponse(packet.GetData(), response,
353 /*send_async=*/false) ==
354 PacketResult::Success) {
355 const char *response_cstr = response.GetStringRef().c_str();
356
357 // Hang on to the qSupported packet, so that platforms can do custom
358 // configuration of the transport before attaching/launching the
359 // process.
360 m_qSupported_response = response_cstr;
361
362 if (::strstr(response_cstr, "qXfer:auxv:read+"))
363 m_supports_qXfer_auxv_read = eLazyBoolYes;
364 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
365 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
366 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
367 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
368 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
369 }
370 if (::strstr(response_cstr, "qXfer:libraries:read+"))
371 m_supports_qXfer_libraries_read = eLazyBoolYes;
372 if (::strstr(response_cstr, "qXfer:features:read+"))
373 m_supports_qXfer_features_read = eLazyBoolYes;
374
375 // Look for a list of compressions in the features list e.g.
376 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
377 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
378 if (features_list) {
379 const char *compressions =
380 ::strstr(features_list, "SupportedCompressions=");
381 if (compressions) {
382 std::vector<std::string> supported_compressions;
383 compressions += sizeof("SupportedCompressions=") - 1;
384 const char *end_of_compressions = strchr(compressions, ';');
385 if (end_of_compressions == NULL) {
386 end_of_compressions = strchr(compressions, '\0');
387 }
388 const char *current_compression = compressions;
389 while (current_compression < end_of_compressions) {
390 const char *next_compression_name = strchr(current_compression, ',');
391 const char *end_of_this_word = next_compression_name;
392 if (next_compression_name == NULL ||
393 end_of_compressions < next_compression_name) {
394 end_of_this_word = end_of_compressions;
395 }
396
397 if (end_of_this_word) {
398 if (end_of_this_word == current_compression) {
399 current_compression++;
400 } else {
401 std::string this_compression(
402 current_compression, end_of_this_word - current_compression);
403 supported_compressions.push_back(this_compression);
404 current_compression = end_of_this_word + 1;
405 }
406 } else {
407 supported_compressions.push_back(current_compression);
408 current_compression = end_of_compressions;
409 }
410 }
411
412 if (supported_compressions.size() > 0) {
413 MaybeEnableCompression(supported_compressions);
414 }
415 }
416 }
417
418 if (::strstr(response_cstr, "qEcho"))
419 m_supports_qEcho = eLazyBoolYes;
420 else
421 m_supports_qEcho = eLazyBoolNo;
422
423 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
424 if (packet_size_str) {
425 StringExtractorGDBRemote packet_response(packet_size_str +
426 strlen("PacketSize="));
427 m_max_packet_size =
428 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
429 if (m_max_packet_size == 0) {
430 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
431 Log *log(
432 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
433 if (log)
434 log->Printf("Garbled PacketSize spec in qSupported response");
435 }
436 }
437 }
438}
439
440bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
441 if (m_supports_thread_suffix == eLazyBoolCalculate) {
442 StringExtractorGDBRemote response;
443 m_supports_thread_suffix = eLazyBoolNo;
444 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
445 false) == PacketResult::Success) {
446 if (response.IsOKResponse())
447 m_supports_thread_suffix = eLazyBoolYes;
448 }
449 }
450 return m_supports_thread_suffix;
451}
452bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
453 if (m_supports_vCont_c == eLazyBoolCalculate) {
454 StringExtractorGDBRemote response;
455 m_supports_vCont_any = eLazyBoolNo;
456 m_supports_vCont_all = eLazyBoolNo;
457 m_supports_vCont_c = eLazyBoolNo;
458 m_supports_vCont_C = eLazyBoolNo;
459 m_supports_vCont_s = eLazyBoolNo;
460 m_supports_vCont_S = eLazyBoolNo;
461 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
462 PacketResult::Success) {
463 const char *response_cstr = response.GetStringRef().c_str();
464 if (::strstr(response_cstr, ";c"))
465 m_supports_vCont_c = eLazyBoolYes;
466
467 if (::strstr(response_cstr, ";C"))
468 m_supports_vCont_C = eLazyBoolYes;
469
470 if (::strstr(response_cstr, ";s"))
471 m_supports_vCont_s = eLazyBoolYes;
472
473 if (::strstr(response_cstr, ";S"))
474 m_supports_vCont_S = eLazyBoolYes;
475
476 if (m_supports_vCont_c == eLazyBoolYes &&
477 m_supports_vCont_C == eLazyBoolYes &&
478 m_supports_vCont_s == eLazyBoolYes &&
479 m_supports_vCont_S == eLazyBoolYes) {
480 m_supports_vCont_all = eLazyBoolYes;
481 }
482
483 if (m_supports_vCont_c == eLazyBoolYes ||
484 m_supports_vCont_C == eLazyBoolYes ||
485 m_supports_vCont_s == eLazyBoolYes ||
486 m_supports_vCont_S == eLazyBoolYes) {
487 m_supports_vCont_any = eLazyBoolYes;
488 }
489 }
490 }
491
492 switch (flavor) {
493 case 'a':
494 return m_supports_vCont_any;
495 case 'A':
496 return m_supports_vCont_all;
497 case 'c':
498 return m_supports_vCont_c;
499 case 'C':
500 return m_supports_vCont_C;
501 case 's':
502 return m_supports_vCont_s;
503 case 'S':
504 return m_supports_vCont_S;
505 default:
506 break;
507 }
508 return false;
509}
510
Pavel Labath4b6f9592016-08-18 08:30:03 +0000511GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000512GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
513 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
514 bool send_async) {
515 Lock lock(*this, send_async);
516 if (!lock) {
517 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
518 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
519 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
520 "for %s packet.",
521 __FUNCTION__, payload.GetString().c_str());
522 return PacketResult::ErrorNoSequenceLock;
523 }
Pavel Labath5c95ee42016-08-30 13:56:11 +0000524
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 if (GetThreadSuffixSupported())
526 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
527 else {
528 if (!SetCurrentThread(tid))
529 return PacketResult::ErrorSendFailed;
530 }
Pavel Labath4b6f9592016-08-18 08:30:03 +0000531
Kate Stoneb9c1b512016-09-06 20:57:50 +0000532 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
Pavel Labath4b6f9592016-08-18 08:30:03 +0000533}
534
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000535// Check if the target supports 'p' packet. It sends out a 'p'
536// packet and checks the response. A normal packet will tell us
537// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000538//
539// Takes a valid thread ID because p needs to apply to a thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
541 if (m_supports_p == eLazyBoolCalculate) {
542 m_supports_p = eLazyBoolNo;
543 StreamString payload;
544 payload.PutCString("p0");
545 StringExtractorGDBRemote response;
546 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
547 response, false) ==
548 PacketResult::Success &&
549 response.IsNormalResponse()) {
550 m_supports_p = eLazyBoolYes;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000551 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 }
553 return m_supports_p;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000554}
Greg Clayton576d8832011-03-22 04:00:09 +0000555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
557 // Get information on all threads at one using the "jThreadsInfo" packet
558 StructuredData::ObjectSP object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000559
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 if (m_supports_jThreadsInfo) {
561 StringExtractorGDBRemote response;
562 response.SetResponseValidatorToJSON();
563 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
564 PacketResult::Success) {
565 if (response.IsUnsupportedResponse()) {
566 m_supports_jThreadsInfo = false;
567 } else if (!response.Empty()) {
568 object_sp = StructuredData::ParseJSON(response.GetStringRef());
569 }
Greg Clayton358cf1e2015-06-25 21:46:34 +0000570 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 }
572 return object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000573}
574
Kate Stoneb9c1b512016-09-06 20:57:50 +0000575bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
576 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
577 StringExtractorGDBRemote response;
578 m_supports_jThreadExtendedInfo = eLazyBoolNo;
579 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
580 PacketResult::Success) {
581 if (response.IsOKResponse()) {
582 m_supports_jThreadExtendedInfo = eLazyBoolYes;
583 }
Jason Molenda705b1802014-06-13 02:37:02 +0000584 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585 }
586 return m_supports_jThreadExtendedInfo;
Jason Molenda705b1802014-06-13 02:37:02 +0000587}
588
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
590 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
591 StringExtractorGDBRemote response;
592 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
593 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
594 response,
595 false) == PacketResult::Success) {
596 if (response.IsOKResponse()) {
597 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
598 }
Jason Molenda20ee21b2015-07-10 23:15:22 +0000599 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 }
601 return m_supports_jLoadedDynamicLibrariesInfos;
Jason Molenda20ee21b2015-07-10 23:15:22 +0000602}
603
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
605 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
606 StringExtractorGDBRemote response;
607 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
608 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
609 PacketResult::Success) {
610 if (response.IsOKResponse()) {
611 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
612 }
Jason Molenda37397352016-07-22 00:17:55 +0000613 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 }
615 return m_supports_jGetSharedCacheInfo;
Jason Molenda37397352016-07-22 00:17:55 +0000616}
617
Kate Stoneb9c1b512016-09-06 20:57:50 +0000618bool GDBRemoteCommunicationClient::GetxPacketSupported() {
619 if (m_supports_x == eLazyBoolCalculate) {
620 StringExtractorGDBRemote response;
621 m_supports_x = eLazyBoolNo;
622 char packet[256];
623 snprintf(packet, sizeof(packet), "x0,0");
624 if (SendPacketAndWaitForResponse(packet, response, false) ==
625 PacketResult::Success) {
626 if (response.IsOKResponse())
627 m_supports_x = eLazyBoolYes;
Jason Molendabdc4f122014-05-06 02:59:39 +0000628 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629 }
630 return m_supports_x;
Jason Molendabdc4f122014-05-06 02:59:39 +0000631}
632
Greg Clayton3dedae12013-12-06 21:45:27 +0000633GDBRemoteCommunicationClient::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000634GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
635 const char *payload_prefix, std::string &response_string) {
636 Lock lock(*this, false);
637 if (!lock) {
638 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
639 GDBR_LOG_PACKETS));
640 if (log)
641 log->Printf("error: failed to get packet sequence mutex, not sending "
642 "packets with prefix '%s'",
643 payload_prefix);
644 return PacketResult::ErrorNoSequenceLock;
645 }
646
647 response_string = "";
648 std::string payload_prefix_str(payload_prefix);
649 unsigned int response_size = 0x1000;
650 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
651 response_size = GetRemoteMaxPacketSize();
652 }
653
654 for (unsigned int offset = 0; true; offset += response_size) {
655 StringExtractorGDBRemote this_response;
656 // Construct payload
657 char sizeDescriptor[128];
658 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
659 response_size);
660 PacketResult result = SendPacketAndWaitForResponseNoLock(
661 payload_prefix_str + sizeDescriptor, this_response);
662 if (result != PacketResult::Success)
663 return result;
664
665 const std::string &this_string = this_response.GetStringRef();
666
667 // Check for m or l as first character; l seems to mean this is the last
668 // chunk
669 char first_char = *this_string.c_str();
670 if (first_char != 'm' && first_char != 'l') {
671 return PacketResult::ErrorReplyInvalid;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000672 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 // Concatenate the result so far (skipping 'm' or 'l')
674 response_string.append(this_string, 1, std::string::npos);
675 if (first_char == 'l')
676 // We're done
677 return PacketResult::Success;
678 }
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000679}
680
Kate Stoneb9c1b512016-09-06 20:57:50 +0000681lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
682 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
683 return m_curr_pid;
Jaydeep Patil1142f832015-08-13 03:46:36 +0000684
Kate Stoneb9c1b512016-09-06 20:57:50 +0000685 // First try to retrieve the pid via the qProcessInfo request.
686 GetCurrentProcessInfo(allow_lazy);
687 if (m_curr_pid_is_valid == eLazyBoolYes) {
688 // We really got it.
689 return m_curr_pid;
690 } else {
691 // If we don't get a response for qProcessInfo, check if $qC gives us a
692 // result.
693 // $qC only returns a real process id on older debugserver and lldb-platform
694 // stubs.
695 // The gdb remote protocol documents $qC as returning the thread id, which
696 // newer
697 // debugserver and lldb-gdbserver stubs return correctly.
Greg Clayton576d8832011-03-22 04:00:09 +0000698 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000699 if (SendPacketAndWaitForResponse("qC", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000700 PacketResult::Success) {
701 if (response.GetChar() == 'Q') {
702 if (response.GetChar() == 'C') {
703 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
704 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
705 m_curr_pid_is_valid = eLazyBoolYes;
706 return m_curr_pid;
707 }
Greg Clayton576d8832011-03-22 04:00:09 +0000708 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709 }
Greg Clayton576d8832011-03-22 04:00:09 +0000710 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711
712 // If we don't get a response for $qC, check if $qfThreadID gives us a
713 // result.
714 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
715 std::vector<lldb::tid_t> thread_ids;
716 bool sequence_mutex_unavailable;
717 size_t size;
718 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
719 if (size && sequence_mutex_unavailable == false) {
720 m_curr_pid = thread_ids.front();
721 m_curr_pid_is_valid = eLazyBoolYes;
722 return m_curr_pid;
723 }
Greg Clayton576d8832011-03-22 04:00:09 +0000724 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725 }
726
727 return LLDB_INVALID_PROCESS_ID;
Greg Clayton576d8832011-03-22 04:00:09 +0000728}
729
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
731 error_str.clear();
732 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000733 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
734 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000735 if (response.IsOKResponse())
736 return true;
737 if (response.GetChar() == 'E') {
738 // A string the describes what failed when launching...
739 error_str = response.GetStringRef().substr(1);
740 } else {
741 error_str.assign("unknown error occurred launching process");
Greg Claytonfbb76342013-11-20 21:07:01 +0000742 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743 } else {
744 error_str.assign("timed out waiting for app to launch");
745 }
746 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000747}
748
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749int GDBRemoteCommunicationClient::SendArgumentsPacket(
750 const ProcessLaunchInfo &launch_info) {
751 // Since we don't get the send argv0 separate from the executable path, we
752 // need to
753 // make sure to use the actual executable path found in the launch_info...
754 std::vector<const char *> argv;
755 FileSpec exe_file = launch_info.GetExecutableFile();
756 std::string exe_path;
757 const char *arg = NULL;
758 const Args &launch_args = launch_info.GetArguments();
759 if (exe_file)
760 exe_path = exe_file.GetPath(false);
761 else {
762 arg = launch_args.GetArgumentAtIndex(0);
763 if (arg)
764 exe_path = arg;
765 }
766 if (!exe_path.empty()) {
767 argv.push_back(exe_path.c_str());
768 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL;
769 ++i) {
770 if (arg)
771 argv.push_back(arg);
Greg Clayton576d8832011-03-22 04:00:09 +0000772 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000773 }
774 if (!argv.empty()) {
Vince Harrone0be4252015-02-06 18:32:57 +0000775 StreamString packet;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 packet.PutChar('A');
777 for (size_t i = 0, n = argv.size(); i < n; ++i) {
778 arg = argv[i];
779 const int arg_len = strlen(arg);
780 if (i > 0)
781 packet.PutChar(',');
782 packet.Printf("%i,%i,", arg_len * 2, (int)i);
783 packet.PutBytesAsRawHex8(arg, arg_len);
784 }
785
Vince Harrone0be4252015-02-06 18:32:57 +0000786 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000787 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
788 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000789 if (response.IsOKResponse())
Vince Harrone0be4252015-02-06 18:32:57 +0000790 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791 uint8_t error = response.GetError();
792 if (error)
Johnny Chen64637202012-05-23 21:09:52 +0000793 return error;
794 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000795 }
796 return -1;
797}
Johnny Chen64637202012-05-23 21:09:52 +0000798
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799int GDBRemoteCommunicationClient::SendEnvironmentPacket(
800 char const *name_equal_value) {
801 if (name_equal_value && name_equal_value[0]) {
802 StreamString packet;
803 bool send_hex_encoding = false;
804 for (const char *p = name_equal_value;
805 *p != '\0' && send_hex_encoding == false; ++p) {
806 if (isprint(*p)) {
807 switch (*p) {
808 case '$':
809 case '#':
810 case '*':
811 case '}':
812 send_hex_encoding = true;
813 break;
814 default:
815 break;
Johnny Chen64637202012-05-23 21:09:52 +0000816 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000817 } else {
818 // We have non printable characters, lets hex encode this...
819 send_hex_encoding = true;
820 }
Johnny Chen64637202012-05-23 21:09:52 +0000821 }
822
Greg Claytonfbb76342013-11-20 21:07:01 +0000823 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000824 if (send_hex_encoding) {
825 if (m_supports_QEnvironmentHexEncoded) {
826 packet.PutCString("QEnvironmentHexEncoded:");
827 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000828 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
829 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830 if (response.IsOKResponse())
831 return 0;
832 uint8_t error = response.GetError();
833 if (error)
834 return error;
835 if (response.IsUnsupportedResponse())
836 m_supports_QEnvironmentHexEncoded = false;
837 }
838 }
839
840 } else if (m_supports_QEnvironment) {
841 packet.Printf("QEnvironment:%s", name_equal_value);
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000842 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
843 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000844 if (response.IsOKResponse())
845 return 0;
846 uint8_t error = response.GetError();
847 if (error)
848 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +0000849 if (response.IsUnsupportedResponse())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 m_supports_QEnvironment = false;
851 }
Greg Claytonfbb76342013-11-20 21:07:01 +0000852 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000853 }
854 return -1;
Greg Claytonfbb76342013-11-20 21:07:01 +0000855}
856
Kate Stoneb9c1b512016-09-06 20:57:50 +0000857int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
858 if (arch && arch[0]) {
859 StreamString packet;
860 packet.Printf("QLaunchArch:%s", arch);
861 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000862 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
863 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000864 if (response.IsOKResponse())
865 return 0;
866 uint8_t error = response.GetError();
867 if (error)
868 return error;
869 }
870 }
871 return -1;
872}
Chaoren Lind3173f32015-05-29 19:52:29 +0000873
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
875 char const *data, bool *was_supported) {
876 if (data && *data != '\0') {
877 StreamString packet;
878 packet.Printf("QSetProcessEvent:%s", data);
879 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000880 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
881 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882 if (response.IsOKResponse()) {
883 if (was_supported)
884 *was_supported = true;
885 return 0;
886 } else if (response.IsUnsupportedResponse()) {
887 if (was_supported)
888 *was_supported = false;
889 return -1;
890 } else {
891 uint8_t error = response.GetError();
892 if (was_supported)
893 *was_supported = true;
894 if (error)
895 return error;
896 }
897 }
898 }
899 return -1;
900}
901
902bool GDBRemoteCommunicationClient::GetOSVersion(uint32_t &major,
903 uint32_t &minor,
904 uint32_t &update) {
905 if (GetHostInfo()) {
906 if (m_os_version_major != UINT32_MAX) {
907 major = m_os_version_major;
908 minor = m_os_version_minor;
909 update = m_os_version_update;
910 return true;
911 }
912 }
913 return false;
914}
915
916bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
917 if (GetHostInfo()) {
918 if (!m_os_build.empty()) {
919 s = m_os_build;
920 return true;
921 }
922 }
923 s.clear();
924 return false;
925}
926
927bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
928 if (GetHostInfo()) {
929 if (!m_os_kernel.empty()) {
930 s = m_os_kernel;
931 return true;
932 }
933 }
934 s.clear();
935 return false;
936}
937
938bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
939 if (GetHostInfo()) {
940 if (!m_hostname.empty()) {
941 s = m_hostname;
942 return true;
943 }
944 }
945 s.clear();
946 return false;
947}
948
949ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
950 if (GetHostInfo())
951 return m_host_arch;
952 return ArchSpec();
953}
954
955const lldb_private::ArchSpec &
956GDBRemoteCommunicationClient::GetProcessArchitecture() {
957 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
958 GetCurrentProcessInfo();
959 return m_process_arch;
960}
961
962bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
963 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
964 m_gdb_server_name.clear();
965 m_gdb_server_version = 0;
966 m_qGDBServerVersion_is_valid = eLazyBoolNo;
967
968 StringExtractorGDBRemote response;
969 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
970 PacketResult::Success) {
971 if (response.IsNormalResponse()) {
972 llvm::StringRef name, value;
973 bool success = false;
974 while (response.GetNameColonValue(name, value)) {
975 if (name.equals("name")) {
976 success = true;
977 m_gdb_server_name = value;
978 } else if (name.equals("version")) {
979 llvm::StringRef major, minor;
980 std::tie(major, minor) = value.split('.');
981 if (!major.getAsInteger(0, m_gdb_server_version))
982 success = true;
983 }
Greg Clayton576d8832011-03-22 04:00:09 +0000984 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985 if (success)
986 m_qGDBServerVersion_is_valid = eLazyBoolYes;
987 }
Greg Clayton576d8832011-03-22 04:00:09 +0000988 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989 }
990 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000991}
992
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993void GDBRemoteCommunicationClient::MaybeEnableCompression(
994 std::vector<std::string> supported_compressions) {
995 CompressionType avail_type = CompressionType::None;
996 std::string avail_name;
997
998#if defined(HAVE_LIBCOMPRESSION)
999 // libcompression is weak linked so test if compression_decode_buffer() is
1000 // available
1001 if (compression_decode_buffer != NULL &&
1002 avail_type == CompressionType::None) {
1003 for (auto compression : supported_compressions) {
1004 if (compression == "lzfse") {
1005 avail_type = CompressionType::LZFSE;
1006 avail_name = compression;
1007 break;
1008 }
1009 }
1010 }
1011#endif
1012
1013#if defined(HAVE_LIBCOMPRESSION)
1014 // libcompression is weak linked so test if compression_decode_buffer() is
1015 // available
1016 if (compression_decode_buffer != NULL &&
1017 avail_type == CompressionType::None) {
1018 for (auto compression : supported_compressions) {
1019 if (compression == "zlib-deflate") {
1020 avail_type = CompressionType::ZlibDeflate;
1021 avail_name = compression;
1022 break;
1023 }
1024 }
1025 }
1026#endif
1027
1028#if defined(HAVE_LIBZ)
1029 if (avail_type == CompressionType::None) {
1030 for (auto compression : supported_compressions) {
1031 if (compression == "zlib-deflate") {
1032 avail_type = CompressionType::ZlibDeflate;
1033 avail_name = compression;
1034 break;
1035 }
1036 }
1037 }
1038#endif
1039
1040#if defined(HAVE_LIBCOMPRESSION)
1041 // libcompression is weak linked so test if compression_decode_buffer() is
1042 // available
1043 if (compression_decode_buffer != NULL &&
1044 avail_type == CompressionType::None) {
1045 for (auto compression : supported_compressions) {
1046 if (compression == "lz4") {
1047 avail_type = CompressionType::LZ4;
1048 avail_name = compression;
1049 break;
1050 }
1051 }
1052 }
1053#endif
1054
1055#if defined(HAVE_LIBCOMPRESSION)
1056 // libcompression is weak linked so test if compression_decode_buffer() is
1057 // available
1058 if (compression_decode_buffer != NULL &&
1059 avail_type == CompressionType::None) {
1060 for (auto compression : supported_compressions) {
1061 if (compression == "lzma") {
1062 avail_type = CompressionType::LZMA;
1063 avail_name = compression;
1064 break;
1065 }
1066 }
1067 }
1068#endif
1069
1070 if (avail_type != CompressionType::None) {
Greg Clayton576d8832011-03-22 04:00:09 +00001071 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001072 std::string packet = "QEnableCompression:type:" + avail_name + ";";
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001073 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074 PacketResult::Success)
1075 return;
1076
1077 if (response.IsOKResponse()) {
1078 m_compression_type = avail_type;
Greg Clayton576d8832011-03-22 04:00:09 +00001079 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 }
Greg Clayton576d8832011-03-22 04:00:09 +00001081}
Greg Clayton32e0a752011-03-30 18:16:51 +00001082
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1084 if (GetGDBServerVersion()) {
1085 if (!m_gdb_server_name.empty())
1086 return m_gdb_server_name.c_str();
1087 }
1088 return NULL;
1089}
1090
1091uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1092 if (GetGDBServerVersion())
1093 return m_gdb_server_version;
1094 return 0;
1095}
1096
1097bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1098 StringExtractorGDBRemote response;
1099 if (SendPacketAndWaitForResponse("qC", response, false) !=
1100 PacketResult::Success)
1101 return false;
1102
1103 if (!response.IsNormalResponse())
1104 return false;
1105
1106 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1107 tid = response.GetHexMaxU32(true, -1);
1108
1109 return true;
1110}
1111
1112bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1113 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1114
1115 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1116 m_qHostInfo_is_valid = eLazyBoolNo;
Jim Ingham106d0282014-06-25 02:32:56 +00001117 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1119 PacketResult::Success) {
1120 if (response.IsNormalResponse()) {
Zachary Turner54695a32016-08-29 19:58:14 +00001121 llvm::StringRef name;
1122 llvm::StringRef value;
Jason Molenda89c37492014-01-27 22:23:20 +00001123 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1124 uint32_t sub = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 std::string arch_name;
1126 std::string os_name;
1127 std::string vendor_name;
1128 std::string triple;
1129 std::string distribution_id;
1130 uint32_t pointer_byte_size = 0;
1131 ByteOrder byte_order = eByteOrderInvalid;
1132 uint32_t num_keys_decoded = 0;
1133 while (response.GetNameColonValue(name, value)) {
1134 if (name.equals("cputype")) {
1135 // exception type in big endian hex
1136 if (!value.getAsInteger(0, cpu))
1137 ++num_keys_decoded;
1138 } else if (name.equals("cpusubtype")) {
1139 // exception count in big endian hex
1140 if (!value.getAsInteger(0, sub))
1141 ++num_keys_decoded;
1142 } else if (name.equals("arch")) {
1143 arch_name = value;
1144 ++num_keys_decoded;
1145 } else if (name.equals("triple")) {
1146 StringExtractor extractor(value);
1147 extractor.GetHexByteString(triple);
1148 ++num_keys_decoded;
1149 } else if (name.equals("distribution_id")) {
1150 StringExtractor extractor(value);
1151 extractor.GetHexByteString(distribution_id);
1152 ++num_keys_decoded;
1153 } else if (name.equals("os_build")) {
1154 StringExtractor extractor(value);
1155 extractor.GetHexByteString(m_os_build);
1156 ++num_keys_decoded;
1157 } else if (name.equals("hostname")) {
1158 StringExtractor extractor(value);
1159 extractor.GetHexByteString(m_hostname);
1160 ++num_keys_decoded;
1161 } else if (name.equals("os_kernel")) {
1162 StringExtractor extractor(value);
1163 extractor.GetHexByteString(m_os_kernel);
1164 ++num_keys_decoded;
1165 } else if (name.equals("ostype")) {
1166 os_name = value;
1167 ++num_keys_decoded;
1168 } else if (name.equals("vendor")) {
1169 vendor_name = value;
1170 ++num_keys_decoded;
1171 } else if (name.equals("endian")) {
1172 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1173 .Case("little", eByteOrderLittle)
1174 .Case("big", eByteOrderBig)
1175 .Case("pdp", eByteOrderPDP)
1176 .Default(eByteOrderInvalid);
1177 if (byte_order != eByteOrderInvalid)
1178 ++num_keys_decoded;
1179 } else if (name.equals("ptrsize")) {
1180 if (!value.getAsInteger(0, pointer_byte_size))
1181 ++num_keys_decoded;
1182 } else if (name.equals("os_version") ||
1183 name.equals(
1184 "version")) // Older debugserver binaries used the
1185 // "version" key instead of
1186 // "os_version"...
1187 {
Zachary Turner6fa7681b2016-09-17 02:00:02 +00001188 Args::StringToVersion(value, m_os_version_major, m_os_version_minor,
1189 m_os_version_update);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 if (m_os_version_major != UINT32_MAX)
1191 ++num_keys_decoded;
1192 } else if (name.equals("watchpoint_exceptions_received")) {
1193 m_watchpoints_trigger_after_instruction =
1194 llvm::StringSwitch<LazyBool>(value)
1195 .Case("before", eLazyBoolNo)
1196 .Case("after", eLazyBoolYes)
1197 .Default(eLazyBoolCalculate);
1198 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1199 ++num_keys_decoded;
1200 } else if (name.equals("default_packet_timeout")) {
Pavel Labath3aa04912016-10-31 17:19:42 +00001201 uint32_t timeout_seconds;
1202 if (!value.getAsInteger(0, timeout_seconds)) {
1203 m_default_packet_timeout = std::chrono::seconds(timeout_seconds);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 SetPacketTimeout(m_default_packet_timeout);
1205 ++num_keys_decoded;
Greg Clayton32e0a752011-03-30 18:16:51 +00001206 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001207 }
Jason Molenda89c37492014-01-27 22:23:20 +00001208 }
1209
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 if (num_keys_decoded > 0)
1211 m_qHostInfo_is_valid = eLazyBoolYes;
1212
1213 if (triple.empty()) {
1214 if (arch_name.empty()) {
1215 if (cpu != LLDB_INVALID_CPUTYPE) {
1216 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1217 if (pointer_byte_size) {
1218 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1219 }
1220 if (byte_order != eByteOrderInvalid) {
1221 assert(byte_order == m_host_arch.GetByteOrder());
1222 }
1223
1224 if (!vendor_name.empty())
1225 m_host_arch.GetTriple().setVendorName(
1226 llvm::StringRef(vendor_name));
1227 if (!os_name.empty())
1228 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Jason Molenda89c37492014-01-27 22:23:20 +00001229 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230 } else {
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001231 std::string triple;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001232 triple += arch_name;
1233 if (!vendor_name.empty() || !os_name.empty()) {
1234 triple += '-';
1235 if (vendor_name.empty())
1236 triple += "unknown";
1237 else
1238 triple += vendor_name;
1239 triple += '-';
1240 if (os_name.empty())
1241 triple += "unknown";
1242 else
1243 triple += os_name;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001244 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001245 m_host_arch.SetTriple(triple.c_str());
Todd Fialac540dd02014-08-26 18:21:02 +00001246
Kate Stoneb9c1b512016-09-06 20:57:50 +00001247 llvm::Triple &host_triple = m_host_arch.GetTriple();
1248 if (host_triple.getVendor() == llvm::Triple::Apple &&
1249 host_triple.getOS() == llvm::Triple::Darwin) {
1250 switch (m_host_arch.GetMachine()) {
1251 case llvm::Triple::aarch64:
1252 case llvm::Triple::arm:
1253 case llvm::Triple::thumb:
1254 host_triple.setOS(llvm::Triple::IOS);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001255 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 default:
1257 host_triple.setOS(llvm::Triple::MacOSX);
1258 break;
1259 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001260 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261 if (pointer_byte_size) {
1262 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1263 }
1264 if (byte_order != eByteOrderInvalid) {
1265 assert(byte_order == m_host_arch.GetByteOrder());
1266 }
1267 }
1268 } else {
1269 m_host_arch.SetTriple(triple.c_str());
1270 if (pointer_byte_size) {
1271 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1272 }
1273 if (byte_order != eByteOrderInvalid) {
1274 assert(byte_order == m_host_arch.GetByteOrder());
1275 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001276
Kate Stoneb9c1b512016-09-06 20:57:50 +00001277 if (log)
1278 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1279 "architecture as %s, triple as %s from triple text %s",
1280 __FUNCTION__, m_host_arch.GetArchitectureName()
1281 ? m_host_arch.GetArchitectureName()
1282 : "<null-arch-name>",
1283 m_host_arch.GetTriple().getTriple().c_str(),
1284 triple.c_str());
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001285 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001286 if (!distribution_id.empty())
1287 m_host_arch.SetDistributionId(distribution_id.c_str());
1288 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001289 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290 }
1291 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Claytonadc00cb2011-05-20 23:38:13 +00001292}
Greg Clayton37a0a242012-04-11 00:24:49 +00001293
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294int GDBRemoteCommunicationClient::SendAttach(
1295 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1296 if (pid != LLDB_INVALID_PROCESS_ID) {
1297 char packet[64];
1298 const int packet_len =
1299 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001300 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001301 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001302 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303 PacketResult::Success) {
1304 if (response.IsErrorResponse())
1305 return response.GetError();
1306 return 0;
1307 }
1308 }
1309 return -1;
1310}
1311
1312int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1313 size_t data_len) {
1314 StreamString packet;
1315 packet.PutCString("I");
1316 packet.PutBytesAsRawHex8(data, data_len);
1317 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001318 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1319 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 return 0;
1321 }
1322 return response.GetError();
1323}
1324
1325const lldb_private::ArchSpec &
1326GDBRemoteCommunicationClient::GetHostArchitecture() {
1327 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1328 GetHostInfo();
1329 return m_host_arch;
1330}
1331
Pavel Labath3aa04912016-10-31 17:19:42 +00001332std::chrono::seconds
1333GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001334 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1335 GetHostInfo();
1336 return m_default_packet_timeout;
1337}
1338
1339addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1340 uint32_t permissions) {
1341 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1342 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1343 char packet[64];
1344 const int packet_len = ::snprintf(
1345 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1346 permissions & lldb::ePermissionsReadable ? "r" : "",
1347 permissions & lldb::ePermissionsWritable ? "w" : "",
1348 permissions & lldb::ePermissionsExecutable ? "x" : "");
1349 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001350 UNUSED_IF_ASSERT_DISABLED(packet_len);
Pavel Labath83082a02016-08-18 14:33:55 +00001351 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001352 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001353 PacketResult::Success) {
1354 if (response.IsUnsupportedResponse())
1355 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1356 else if (!response.IsErrorResponse())
1357 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1358 } else {
1359 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1360 }
1361 }
1362 return LLDB_INVALID_ADDRESS;
1363}
1364
1365bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1366 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1367 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1368 char packet[64];
1369 const int packet_len =
1370 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1371 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001372 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001373 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001374 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001375 PacketResult::Success) {
1376 if (response.IsUnsupportedResponse())
1377 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1378 else if (response.IsOKResponse())
1379 return true;
1380 } else {
1381 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1382 }
1383 }
1384 return false;
1385}
1386
1387Error GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1388 Error error;
1389
1390 if (keep_stopped) {
1391 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1392 char packet[64];
1393 const int packet_len =
1394 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1395 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001396 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001398 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001399 PacketResult::Success &&
1400 response.IsOKResponse()) {
1401 m_supports_detach_stay_stopped = eLazyBoolYes;
1402 } else {
1403 m_supports_detach_stay_stopped = eLazyBoolNo;
1404 }
1405 }
1406
1407 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1408 error.SetErrorString("Stays stopped not supported by this target.");
1409 return error;
1410 } else {
1411 StringExtractorGDBRemote response;
1412 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001413 SendPacketAndWaitForResponse("D1", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001414 if (packet_result != PacketResult::Success)
1415 error.SetErrorString("Sending extended disconnect packet failed.");
1416 }
1417 } else {
1418 StringExtractorGDBRemote response;
1419 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001420 SendPacketAndWaitForResponse("D", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421 if (packet_result != PacketResult::Success)
1422 error.SetErrorString("Sending disconnect packet failed.");
1423 }
1424 return error;
1425}
1426
1427Error GDBRemoteCommunicationClient::GetMemoryRegionInfo(
1428 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
1429 Error error;
1430 region_info.Clear();
1431
1432 if (m_supports_memory_region_info != eLazyBoolNo) {
1433 m_supports_memory_region_info = eLazyBoolYes;
1434 char packet[64];
1435 const int packet_len = ::snprintf(
1436 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1437 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001438 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001439 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001440 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441 PacketResult::Success) {
1442 llvm::StringRef name;
1443 llvm::StringRef value;
1444 addr_t addr_value = LLDB_INVALID_ADDRESS;
1445 bool success = true;
1446 bool saw_permissions = false;
1447 while (success && response.GetNameColonValue(name, value)) {
1448 if (name.equals("start")) {
1449 if (!value.getAsInteger(16, addr_value))
1450 region_info.GetRange().SetRangeBase(addr_value);
1451 } else if (name.equals("size")) {
1452 if (!value.getAsInteger(16, addr_value))
1453 region_info.GetRange().SetByteSize(addr_value);
1454 } else if (name.equals("permissions") &&
1455 region_info.GetRange().IsValid()) {
1456 saw_permissions = true;
1457 if (region_info.GetRange().Contains(addr)) {
1458 if (value.find('r') != llvm::StringRef::npos)
1459 region_info.SetReadable(MemoryRegionInfo::eYes);
1460 else
1461 region_info.SetReadable(MemoryRegionInfo::eNo);
1462
1463 if (value.find('w') != llvm::StringRef::npos)
1464 region_info.SetWritable(MemoryRegionInfo::eYes);
1465 else
1466 region_info.SetWritable(MemoryRegionInfo::eNo);
1467
1468 if (value.find('x') != llvm::StringRef::npos)
1469 region_info.SetExecutable(MemoryRegionInfo::eYes);
1470 else
1471 region_info.SetExecutable(MemoryRegionInfo::eNo);
1472
1473 region_info.SetMapped(MemoryRegionInfo::eYes);
1474 } else {
1475 // The reported region does not contain this address -- we're
1476 // looking at an unmapped page
1477 region_info.SetReadable(MemoryRegionInfo::eNo);
1478 region_info.SetWritable(MemoryRegionInfo::eNo);
1479 region_info.SetExecutable(MemoryRegionInfo::eNo);
1480 region_info.SetMapped(MemoryRegionInfo::eNo);
1481 }
1482 } else if (name.equals("name")) {
1483 StringExtractorGDBRemote name_extractor(value);
1484 std::string name;
1485 name_extractor.GetHexByteString(name);
1486 region_info.SetName(name.c_str());
1487 } else if (name.equals("error")) {
1488 StringExtractorGDBRemote error_extractor(value);
1489 std::string error_string;
1490 // Now convert the HEX bytes into a string value
1491 error_extractor.GetHexByteString(error_string);
1492 error.SetErrorString(error_string.c_str());
1493 }
1494 }
1495
1496 // We got a valid address range back but no permissions -- which means
1497 // this is an unmapped page
1498 if (region_info.GetRange().IsValid() && saw_permissions == false) {
1499 region_info.SetReadable(MemoryRegionInfo::eNo);
1500 region_info.SetWritable(MemoryRegionInfo::eNo);
1501 region_info.SetExecutable(MemoryRegionInfo::eNo);
1502 region_info.SetMapped(MemoryRegionInfo::eNo);
1503 }
1504 } else {
1505 m_supports_memory_region_info = eLazyBoolNo;
1506 }
1507 }
1508
1509 if (m_supports_memory_region_info == eLazyBoolNo) {
1510 error.SetErrorString("qMemoryRegionInfo is not supported");
1511 }
1512 if (error.Fail())
1513 region_info.Clear();
1514 return error;
1515}
1516
1517Error GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1518 Error error;
1519
1520 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1521 num = m_num_supported_hardware_watchpoints;
1522 return error;
1523 }
1524
1525 // Set num to 0 first.
1526 num = 0;
1527 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1528 char packet[64];
1529 const int packet_len =
1530 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1531 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001532 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001533 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001534 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001535 PacketResult::Success) {
1536 m_supports_watchpoint_support_info = eLazyBoolYes;
1537 llvm::StringRef name;
1538 llvm::StringRef value;
1539 while (response.GetNameColonValue(name, value)) {
1540 if (name.equals("num")) {
1541 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1542 num = m_num_supported_hardware_watchpoints;
1543 }
1544 }
1545 } else {
1546 m_supports_watchpoint_support_info = eLazyBoolNo;
1547 }
1548 }
1549
1550 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1551 error.SetErrorString("qWatchpointSupportInfo is not supported");
1552 }
1553 return error;
1554}
1555
1556lldb_private::Error GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
1557 uint32_t &num, bool &after, const ArchSpec &arch) {
1558 Error error(GetWatchpointSupportInfo(num));
1559 if (error.Success())
1560 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1561 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001562}
1563
Daniel Maleae0f8f572013-08-26 23:57:52 +00001564lldb_private::Error
Kate Stoneb9c1b512016-09-06 20:57:50 +00001565GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1566 bool &after, const ArchSpec &arch) {
1567 Error error;
1568 llvm::Triple::ArchType atype = arch.GetMachine();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001569
Kate Stoneb9c1b512016-09-06 20:57:50 +00001570 // we assume watchpoints will happen after running the relevant opcode
1571 // and we only want to override this behavior if we have explicitly
1572 // received a qHostInfo telling us otherwise
1573 if (m_qHostInfo_is_valid != eLazyBoolYes) {
1574 // On targets like MIPS, watchpoint exceptions are always generated
1575 // before the instruction is executed. The connected target may not
1576 // support qHostInfo or qWatchpointSupportInfo packets.
1577 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1578 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
1579 after = false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001580 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001581 after = true;
1582 } else {
1583 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
1584 // if it is not calculated before.
1585 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1586 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1587 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
1588 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1589
1590 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1591 }
1592 return error;
1593}
1594
1595int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1596 if (file_spec) {
1597 std::string path{file_spec.GetPath(false)};
1598 StreamString packet;
1599 packet.PutCString("QSetSTDIN:");
1600 packet.PutCStringAsRawHex8(path.c_str());
1601
1602 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001603 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1604 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001605 if (response.IsOKResponse())
1606 return 0;
1607 uint8_t error = response.GetError();
1608 if (error)
1609 return error;
1610 }
1611 }
1612 return -1;
1613}
1614
1615int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1616 if (file_spec) {
1617 std::string path{file_spec.GetPath(false)};
1618 StreamString packet;
1619 packet.PutCString("QSetSTDOUT:");
1620 packet.PutCStringAsRawHex8(path.c_str());
1621
1622 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001623 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1624 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001625 if (response.IsOKResponse())
1626 return 0;
1627 uint8_t error = response.GetError();
1628 if (error)
1629 return error;
1630 }
1631 }
1632 return -1;
1633}
1634
1635int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1636 if (file_spec) {
1637 std::string path{file_spec.GetPath(false)};
1638 StreamString packet;
1639 packet.PutCString("QSetSTDERR:");
1640 packet.PutCStringAsRawHex8(path.c_str());
1641
1642 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001643 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1644 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001645 if (response.IsOKResponse())
1646 return 0;
1647 uint8_t error = response.GetError();
1648 if (error)
1649 return error;
1650 }
1651 }
1652 return -1;
1653}
1654
1655bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1656 StringExtractorGDBRemote response;
1657 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1658 PacketResult::Success) {
1659 if (response.IsUnsupportedResponse())
1660 return false;
1661 if (response.IsErrorResponse())
1662 return false;
1663 std::string cwd;
1664 response.GetHexByteString(cwd);
1665 working_dir.SetFile(cwd, false, GetHostArchitecture());
1666 return !cwd.empty();
1667 }
1668 return false;
1669}
1670
1671int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1672 if (working_dir) {
1673 std::string path{working_dir.GetPath(false)};
1674 StreamString packet;
1675 packet.PutCString("QSetWorkingDir:");
1676 packet.PutCStringAsRawHex8(path.c_str());
1677
1678 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001679 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1680 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001681 if (response.IsOKResponse())
1682 return 0;
1683 uint8_t error = response.GetError();
1684 if (error)
1685 return error;
1686 }
1687 }
1688 return -1;
1689}
1690
1691int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1692 char packet[32];
1693 const int packet_len =
1694 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1695 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001696 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001697 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001698 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001699 PacketResult::Success) {
1700 if (response.IsOKResponse())
1701 return 0;
1702 uint8_t error = response.GetError();
1703 if (error)
1704 return error;
1705 }
1706 return -1;
1707}
1708
1709int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1710 char packet[32];
1711 const int packet_len = ::snprintf(packet, sizeof(packet),
1712 "QSetDetachOnError:%i", enable ? 1 : 0);
1713 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001714 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001715 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001716 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717 PacketResult::Success) {
1718 if (response.IsOKResponse())
1719 return 0;
1720 uint8_t error = response.GetError();
1721 if (error)
1722 return error;
1723 }
1724 return -1;
1725}
1726
1727bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1728 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1729 if (response.IsNormalResponse()) {
1730 llvm::StringRef name;
1731 llvm::StringRef value;
1732 StringExtractor extractor;
1733
1734 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1735 uint32_t sub = 0;
1736 std::string vendor;
1737 std::string os_type;
1738
1739 while (response.GetNameColonValue(name, value)) {
1740 if (name.equals("pid")) {
1741 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1742 value.getAsInteger(0, pid);
1743 process_info.SetProcessID(pid);
1744 } else if (name.equals("ppid")) {
1745 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1746 value.getAsInteger(0, pid);
1747 process_info.SetParentProcessID(pid);
1748 } else if (name.equals("uid")) {
1749 uint32_t uid = UINT32_MAX;
1750 value.getAsInteger(0, uid);
1751 process_info.SetUserID(uid);
1752 } else if (name.equals("euid")) {
1753 uint32_t uid = UINT32_MAX;
1754 value.getAsInteger(0, uid);
1755 process_info.SetEffectiveGroupID(uid);
1756 } else if (name.equals("gid")) {
1757 uint32_t gid = UINT32_MAX;
1758 value.getAsInteger(0, gid);
1759 process_info.SetGroupID(gid);
1760 } else if (name.equals("egid")) {
1761 uint32_t gid = UINT32_MAX;
1762 value.getAsInteger(0, gid);
1763 process_info.SetEffectiveGroupID(gid);
1764 } else if (name.equals("triple")) {
1765 StringExtractor extractor(value);
1766 std::string triple;
1767 extractor.GetHexByteString(triple);
1768 process_info.GetArchitecture().SetTriple(triple.c_str());
1769 } else if (name.equals("name")) {
1770 StringExtractor extractor(value);
1771 // The process name from ASCII hex bytes since we can't
1772 // control the characters in a process name
1773 std::string name;
1774 extractor.GetHexByteString(name);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001775 process_info.GetExecutableFile().SetFile(name, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001776 } else if (name.equals("cputype")) {
1777 value.getAsInteger(0, cpu);
1778 } else if (name.equals("cpusubtype")) {
1779 value.getAsInteger(0, sub);
1780 } else if (name.equals("vendor")) {
1781 vendor = value;
1782 } else if (name.equals("ostype")) {
1783 os_type = value;
1784 }
1785 }
1786
1787 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1788 if (vendor == "apple") {
1789 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1790 sub);
1791 process_info.GetArchitecture().GetTriple().setVendorName(
1792 llvm::StringRef(vendor));
1793 process_info.GetArchitecture().GetTriple().setOSName(
1794 llvm::StringRef(os_type));
1795 }
1796 }
1797
1798 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1799 return true;
1800 }
1801 return false;
1802}
1803
1804bool GDBRemoteCommunicationClient::GetProcessInfo(
1805 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1806 process_info.Clear();
1807
1808 if (m_supports_qProcessInfoPID) {
1809 char packet[32];
1810 const int packet_len =
1811 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1812 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001813 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001814 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001815 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001816 PacketResult::Success) {
1817 return DecodeProcessInfoResponse(response, process_info);
1818 } else {
1819 m_supports_qProcessInfoPID = false;
1820 return false;
1821 }
1822 }
1823 return false;
1824}
1825
1826bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1827 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1828 GDBR_LOG_PACKETS));
1829
1830 if (allow_lazy) {
1831 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1832 return true;
1833 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1834 return false;
1835 }
1836
1837 GetHostInfo();
1838
1839 StringExtractorGDBRemote response;
1840 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1841 PacketResult::Success) {
1842 if (response.IsNormalResponse()) {
1843 llvm::StringRef name;
1844 llvm::StringRef value;
1845 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1846 uint32_t sub = 0;
1847 std::string arch_name;
1848 std::string os_name;
1849 std::string vendor_name;
1850 std::string triple;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001851 std::string elf_abi;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001852 uint32_t pointer_byte_size = 0;
1853 StringExtractor extractor;
1854 ByteOrder byte_order = eByteOrderInvalid;
1855 uint32_t num_keys_decoded = 0;
1856 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1857 while (response.GetNameColonValue(name, value)) {
1858 if (name.equals("cputype")) {
1859 if (!value.getAsInteger(16, cpu))
1860 ++num_keys_decoded;
1861 } else if (name.equals("cpusubtype")) {
1862 if (!value.getAsInteger(16, sub))
1863 ++num_keys_decoded;
1864 } else if (name.equals("triple")) {
1865 StringExtractor extractor(value);
1866 extractor.GetHexByteString(triple);
1867 ++num_keys_decoded;
1868 } else if (name.equals("ostype")) {
1869 os_name = value;
1870 ++num_keys_decoded;
1871 } else if (name.equals("vendor")) {
1872 vendor_name = value;
1873 ++num_keys_decoded;
1874 } else if (name.equals("endian")) {
1875 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1876 .Case("little", eByteOrderLittle)
1877 .Case("big", eByteOrderBig)
1878 .Case("pdp", eByteOrderPDP)
1879 .Default(eByteOrderInvalid);
1880 if (byte_order != eByteOrderInvalid)
1881 ++num_keys_decoded;
1882 } else if (name.equals("ptrsize")) {
1883 if (!value.getAsInteger(16, pointer_byte_size))
1884 ++num_keys_decoded;
1885 } else if (name.equals("pid")) {
1886 if (!value.getAsInteger(16, pid))
1887 ++num_keys_decoded;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001888 } else if (name.equals("elf_abi")) {
1889 elf_abi = value;
1890 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001891 }
1892 }
1893 if (num_keys_decoded > 0)
1894 m_qProcessInfo_is_valid = eLazyBoolYes;
1895 if (pid != LLDB_INVALID_PROCESS_ID) {
1896 m_curr_pid_is_valid = eLazyBoolYes;
1897 m_curr_pid = pid;
1898 }
1899
1900 // Set the ArchSpec from the triple if we have it.
1901 if (!triple.empty()) {
1902 m_process_arch.SetTriple(triple.c_str());
Nitesh Jain8999edf2016-10-12 10:21:09 +00001903 m_process_arch.SetFlags(elf_abi);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001904 if (pointer_byte_size) {
1905 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1906 }
1907 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
1908 !vendor_name.empty()) {
1909 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
1910
1911 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
1912 switch (triple.getObjectFormat()) {
1913 case llvm::Triple::MachO:
1914 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1915 break;
1916 case llvm::Triple::ELF:
1917 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
1918 break;
1919 case llvm::Triple::COFF:
1920 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
1921 break;
1922 case llvm::Triple::UnknownObjectFormat:
1923 if (log)
1924 log->Printf("error: failed to determine target architecture");
1925 return false;
1926 }
1927
1928 if (pointer_byte_size) {
1929 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1930 }
1931 if (byte_order != eByteOrderInvalid) {
1932 assert(byte_order == m_process_arch.GetByteOrder());
1933 }
1934 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1935 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1936 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1937 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1938 }
1939 return true;
1940 }
1941 } else {
1942 m_qProcessInfo_is_valid = eLazyBoolNo;
1943 }
1944
1945 return false;
1946}
1947
1948uint32_t GDBRemoteCommunicationClient::FindProcesses(
1949 const ProcessInstanceInfoMatch &match_info,
1950 ProcessInstanceInfoList &process_infos) {
1951 process_infos.Clear();
1952
1953 if (m_supports_qfProcessInfo) {
1954 StreamString packet;
1955 packet.PutCString("qfProcessInfo");
1956 if (!match_info.MatchAllProcesses()) {
1957 packet.PutChar(':');
1958 const char *name = match_info.GetProcessInfo().GetName();
1959 bool has_name_match = false;
1960 if (name && name[0]) {
1961 has_name_match = true;
1962 NameMatchType name_match_type = match_info.GetNameMatchType();
1963 switch (name_match_type) {
1964 case eNameMatchIgnore:
1965 has_name_match = false;
1966 break;
1967
1968 case eNameMatchEquals:
1969 packet.PutCString("name_match:equals;");
1970 break;
1971
1972 case eNameMatchContains:
1973 packet.PutCString("name_match:contains;");
1974 break;
1975
1976 case eNameMatchStartsWith:
1977 packet.PutCString("name_match:starts_with;");
1978 break;
1979
1980 case eNameMatchEndsWith:
1981 packet.PutCString("name_match:ends_with;");
1982 break;
1983
1984 case eNameMatchRegularExpression:
1985 packet.PutCString("name_match:regex;");
1986 break;
1987 }
1988 if (has_name_match) {
1989 packet.PutCString("name:");
1990 packet.PutBytesAsRawHex8(name, ::strlen(name));
1991 packet.PutChar(';');
1992 }
1993 }
1994
1995 if (match_info.GetProcessInfo().ProcessIDIsValid())
1996 packet.Printf("pid:%" PRIu64 ";",
1997 match_info.GetProcessInfo().GetProcessID());
1998 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
1999 packet.Printf("parent_pid:%" PRIu64 ";",
2000 match_info.GetProcessInfo().GetParentProcessID());
2001 if (match_info.GetProcessInfo().UserIDIsValid())
2002 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2003 if (match_info.GetProcessInfo().GroupIDIsValid())
2004 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2005 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2006 packet.Printf("euid:%u;",
2007 match_info.GetProcessInfo().GetEffectiveUserID());
2008 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2009 packet.Printf("egid:%u;",
2010 match_info.GetProcessInfo().GetEffectiveGroupID());
2011 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2012 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2013 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2014 const ArchSpec &match_arch =
2015 match_info.GetProcessInfo().GetArchitecture();
2016 const llvm::Triple &triple = match_arch.GetTriple();
2017 packet.PutCString("triple:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002018 packet.PutCString(triple.getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002019 packet.PutChar(';');
2020 }
2021 }
2022 StringExtractorGDBRemote response;
2023 // Increase timeout as the first qfProcessInfo packet takes a long time
2024 // on Android. The value of 1min was arrived at empirically.
Pavel Labath3aa04912016-10-31 17:19:42 +00002025 ScopedTimeout timeout(*this, std::chrono::seconds(60));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002026 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2027 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002028 do {
2029 ProcessInstanceInfo process_info;
2030 if (!DecodeProcessInfoResponse(response, process_info))
2031 break;
2032 process_infos.Append(process_info);
2033 response.GetStringRef().clear();
2034 response.SetFilePos(0);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002035 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2036 PacketResult::Success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002037 } else {
2038 m_supports_qfProcessInfo = false;
2039 return 0;
2040 }
2041 }
2042 return process_infos.GetSize();
2043}
2044
2045bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2046 std::string &name) {
2047 if (m_supports_qUserName) {
2048 char packet[32];
2049 const int packet_len =
2050 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2051 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002052 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002053 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002054 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002055 PacketResult::Success) {
2056 if (response.IsNormalResponse()) {
2057 // Make sure we parsed the right number of characters. The response is
2058 // the hex encoded user name and should make up the entire packet.
2059 // If there are any non-hex ASCII bytes, the length won't match below..
2060 if (response.GetHexByteString(name) * 2 ==
2061 response.GetStringRef().size())
2062 return true;
2063 }
2064 } else {
2065 m_supports_qUserName = false;
2066 return false;
2067 }
2068 }
2069 return false;
2070}
2071
2072bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2073 std::string &name) {
2074 if (m_supports_qGroupName) {
2075 char packet[32];
2076 const int packet_len =
2077 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2078 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002079 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002080 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002081 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002082 PacketResult::Success) {
2083 if (response.IsNormalResponse()) {
2084 // Make sure we parsed the right number of characters. The response is
2085 // the hex encoded group name and should make up the entire packet.
2086 // If there are any non-hex ASCII bytes, the length won't match below..
2087 if (response.GetHexByteString(name) * 2 ==
2088 response.GetStringRef().size())
2089 return true;
2090 }
2091 } else {
2092 m_supports_qGroupName = false;
2093 return false;
2094 }
2095 }
2096 return false;
2097}
2098
2099bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2100 // Form non-stop packet request
2101 char packet[32];
2102 const int packet_len =
2103 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2104 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002105 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106
2107 StringExtractorGDBRemote response;
2108 // Send to target
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002109 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002110 PacketResult::Success)
2111 if (response.IsOKResponse())
2112 return true;
2113
2114 // Failed or not supported
2115 return false;
2116}
2117
2118static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2119 uint32_t recv_size) {
2120 packet.Clear();
2121 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2122 uint32_t bytes_left = send_size;
2123 while (bytes_left > 0) {
2124 if (bytes_left >= 26) {
2125 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2126 bytes_left -= 26;
2127 } else {
2128 packet.Printf("%*.*s;", bytes_left, bytes_left,
2129 "abcdefghijklmnopqrstuvwxyz");
2130 bytes_left = 0;
2131 }
2132 }
2133}
2134
Pavel Labath3aa04912016-10-31 17:19:42 +00002135std::chrono::duration<float> calculate_standard_deviation(
2136 const std::vector<std::chrono::duration<float>> &v) {
2137 using Dur = std::chrono::duration<float>;
2138 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2139 Dur mean = sum / v.size();
2140 float accum = 0;
2141 for (auto d : v) {
2142 float delta = (d - mean).count();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002143 accum += delta * delta;
Pavel Labath3aa04912016-10-31 17:19:42 +00002144 };
Kate Stoneb9c1b512016-09-06 20:57:50 +00002145
Pavel Labath3aa04912016-10-31 17:19:42 +00002146 return Dur(sqrtf(accum / (v.size() - 1)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002147}
2148
2149void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2150 uint32_t max_send,
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002151 uint32_t max_recv,
2152 uint64_t recv_amount,
2153 bool json, Stream &strm) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002154 using namespace std::chrono;
2155
Kate Stoneb9c1b512016-09-06 20:57:50 +00002156 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002157 if (SendSpeedTestPacket(0, 0)) {
2158 StreamString packet;
2159 if (json)
2160 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2161 "\"results\" : [",
2162 num_packets);
2163 else
2164 strm.Printf("Testing sending %u packets of various sizes:\n",
2165 num_packets);
2166 strm.Flush();
2167
2168 uint32_t result_idx = 0;
2169 uint32_t send_size;
Pavel Labath3aa04912016-10-31 17:19:42 +00002170 std::vector<duration<float>> packet_times;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002171
2172 for (send_size = 0; send_size <= max_send;
2173 send_size ? send_size *= 2 : send_size = 4) {
2174 for (uint32_t recv_size = 0; recv_size <= max_recv;
2175 recv_size ? recv_size *= 2 : recv_size = 4) {
2176 MakeSpeedTestPacket(packet, send_size, recv_size);
2177
2178 packet_times.clear();
2179 // Test how long it takes to send 'num_packets' packets
Pavel Labath3aa04912016-10-31 17:19:42 +00002180 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002181 for (i = 0; i < num_packets; ++i) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002182 const auto packet_start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002184 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Pavel Labath3aa04912016-10-31 17:19:42 +00002185 const auto packet_end_time = steady_clock::now();
2186 packet_times.push_back(packet_end_time - packet_start_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002187 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002188 const auto end_time = steady_clock::now();
2189 const auto total_time = end_time - start_time;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002190
2191 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002192 ((float)num_packets) / duration<float>(total_time).count();
2193 auto average_per_packet = total_time / num_packets;
2194 const duration<float> standard_deviation =
2195 calculate_standard_deviation(packet_times);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002196 if (json) {
2197 strm.Printf("%s\n {\"send_size\" : %6" PRIu32
2198 ", \"recv_size\" : %6" PRIu32
2199 ", \"total_time_nsec\" : %12" PRIu64
2200 ", \"standard_deviation_nsec\" : %9" PRIu64 " }",
2201 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath3aa04912016-10-31 17:19:42 +00002202 duration_cast<nanoseconds>(total_time).count(),
2203 duration_cast<nanoseconds>(standard_deviation).count());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002204 ++result_idx;
2205 } else {
2206 strm.Printf(
Pavel Labath3aa04912016-10-31 17:19:42 +00002207 "qSpeedTest(send=%-7u, recv=%-7u) in %.9f"
Kate Stoneb9c1b512016-09-06 20:57:50 +00002208 " sec for %9.2f packets/sec (%10.6f ms per packet) with standard "
2209 "deviation of %10.6f ms\n",
Pavel Labath3aa04912016-10-31 17:19:42 +00002210 send_size, recv_size, duration<float>(total_time).count(),
2211 packets_per_second,
2212 duration<float, std::milli>(average_per_packet).count(),
2213 duration<float, std::milli>(standard_deviation).count());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002214 }
2215 strm.Flush();
2216 }
2217 }
2218
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002219 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002220 if (json)
2221 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2222 ": %" PRIu64 ",\n \"results\" : [",
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002223 recv_amount);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002224 else
2225 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2226 "packet sizes:\n",
2227 k_recv_amount_mb);
2228 strm.Flush();
2229 send_size = 0;
2230 result_idx = 0;
2231 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2232 MakeSpeedTestPacket(packet, send_size, recv_size);
2233
2234 // If we have a receive size, test how long it takes to receive 4MB of
2235 // data
2236 if (recv_size > 0) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002237 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002238 uint32_t bytes_read = 0;
2239 uint32_t packet_count = 0;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002240 while (bytes_read < recv_amount) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002241 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002242 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002243 bytes_read += recv_size;
2244 ++packet_count;
2245 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002246 const auto end_time = steady_clock::now();
2247 const auto total_time = end_time - start_time;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002248 float mb_second = ((float)recv_amount) /
Pavel Labath3aa04912016-10-31 17:19:42 +00002249 duration<float>(total_time).count() /
Kate Stoneb9c1b512016-09-06 20:57:50 +00002250 (1024.0 * 1024.0);
2251 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002252 ((float)packet_count) / duration<float>(total_time).count();
2253 const auto average_per_packet = total_time / packet_count;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002254
2255 if (json) {
2256 strm.Printf("%s\n {\"send_size\" : %6" PRIu32
2257 ", \"recv_size\" : %6" PRIu32
2258 ", \"total_time_nsec\" : %12" PRIu64 " }",
2259 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath3aa04912016-10-31 17:19:42 +00002260 duration_cast<nanoseconds>(total_time).count());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002261 ++result_idx;
2262 } else {
2263 strm.Printf("qSpeedTest(send=%-7u, recv=%-7u) %6u packets needed to "
Pavel Labath3aa04912016-10-31 17:19:42 +00002264 "receive %2.1fMB in %.9f"
Kate Stoneb9c1b512016-09-06 20:57:50 +00002265 " sec for %f MB/sec for %9.2f packets/sec (%10.6f ms per "
2266 "packet)\n",
2267 send_size, recv_size, packet_count, k_recv_amount_mb,
Pavel Labath3aa04912016-10-31 17:19:42 +00002268 duration<float>(total_time).count(), mb_second,
2269 packets_per_second,
2270 duration<float, std::milli>(average_per_packet).count());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002271 }
2272 strm.Flush();
2273 }
2274 }
2275 if (json)
2276 strm.Printf("\n ]\n }\n}\n");
2277 else
2278 strm.EOL();
2279 }
2280}
2281
2282bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2283 uint32_t recv_size) {
2284 StreamString packet;
2285 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2286 uint32_t bytes_left = send_size;
2287 while (bytes_left > 0) {
2288 if (bytes_left >= 26) {
2289 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2290 bytes_left -= 26;
2291 } else {
2292 packet.Printf("%*.*s;", bytes_left, bytes_left,
2293 "abcdefghijklmnopqrstuvwxyz");
2294 bytes_left = 0;
2295 }
2296 }
2297
2298 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002299 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2300 PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002301}
2302
2303bool GDBRemoteCommunicationClient::LaunchGDBServer(
2304 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2305 std::string &socket_name) {
2306 pid = LLDB_INVALID_PROCESS_ID;
2307 port = 0;
2308 socket_name.clear();
2309
2310 StringExtractorGDBRemote response;
2311 StreamString stream;
2312 stream.PutCString("qLaunchGDBServer;");
2313 std::string hostname;
2314 if (remote_accept_hostname && remote_accept_hostname[0])
2315 hostname = remote_accept_hostname;
2316 else {
2317 if (HostInfo::GetHostname(hostname)) {
2318 // Make the GDB server we launch only accept connections from this host
2319 stream.Printf("host:%s;", hostname.c_str());
2320 } else {
2321 // Make the GDB server we launch accept connections from any host since we
2322 // can't figure out the hostname
2323 stream.Printf("host:*;");
2324 }
2325 }
2326 // give the process a few seconds to startup
Pavel Labath3aa04912016-10-31 17:19:42 +00002327 ScopedTimeout timeout(*this, std::chrono::seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002328
2329 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2330 PacketResult::Success) {
2331 llvm::StringRef name;
2332 llvm::StringRef value;
2333 while (response.GetNameColonValue(name, value)) {
2334 if (name.equals("port"))
2335 value.getAsInteger(0, port);
2336 else if (name.equals("pid"))
2337 value.getAsInteger(0, pid);
2338 else if (name.compare("socket_name") == 0) {
2339 StringExtractor extractor(value);
2340 extractor.GetHexByteString(socket_name);
2341 }
2342 }
2343 return true;
2344 }
2345 return false;
2346}
2347
2348size_t GDBRemoteCommunicationClient::QueryGDBServer(
2349 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2350 connection_urls.clear();
2351
2352 StringExtractorGDBRemote response;
2353 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2354 PacketResult::Success)
2355 return 0;
2356
2357 StructuredData::ObjectSP data =
2358 StructuredData::ParseJSON(response.GetStringRef());
2359 if (!data)
2360 return 0;
2361
2362 StructuredData::Array *array = data->GetAsArray();
2363 if (!array)
2364 return 0;
2365
2366 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2367 StructuredData::Dictionary *element = nullptr;
2368 if (!array->GetItemAtIndexAsDictionary(i, element))
2369 continue;
2370
2371 uint16_t port = 0;
2372 if (StructuredData::ObjectSP port_osp =
2373 element->GetValueForKey(llvm::StringRef("port")))
2374 port = port_osp->GetIntegerValue(0);
2375
2376 std::string socket_name;
2377 if (StructuredData::ObjectSP socket_name_osp =
2378 element->GetValueForKey(llvm::StringRef("socket_name")))
2379 socket_name = socket_name_osp->GetStringValue();
2380
2381 if (port != 0 || !socket_name.empty())
2382 connection_urls.emplace_back(port, socket_name);
2383 }
2384 return connection_urls.size();
2385}
2386
2387bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2388 StreamString stream;
2389 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002390
2391 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002392 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002393 PacketResult::Success) {
2394 if (response.IsOKResponse())
2395 return true;
2396 }
2397 return false;
2398}
2399
2400bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2401 if (m_curr_tid == tid)
2402 return true;
2403
2404 char packet[32];
2405 int packet_len;
2406 if (tid == UINT64_MAX)
2407 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2408 else
2409 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2410 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002411 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002412 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002413 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002414 PacketResult::Success) {
2415 if (response.IsOKResponse()) {
2416 m_curr_tid = tid;
2417 return true;
2418 }
2419
2420 /*
2421 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2422 * Hg packet.
2423 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2424 * which can
2425 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2426 */
2427 if (response.IsUnsupportedResponse() && IsConnected()) {
2428 m_curr_tid = 1;
2429 return true;
2430 }
2431 }
2432 return false;
2433}
2434
2435bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2436 if (m_curr_tid_run == tid)
2437 return true;
2438
2439 char packet[32];
2440 int packet_len;
2441 if (tid == UINT64_MAX)
2442 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2443 else
2444 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2445
2446 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002447 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002448 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002449 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002450 PacketResult::Success) {
2451 if (response.IsOKResponse()) {
2452 m_curr_tid_run = tid;
2453 return true;
2454 }
2455
2456 /*
2457 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2458 * Hc packet.
2459 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2460 * which can
2461 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2462 */
2463 if (response.IsUnsupportedResponse() && IsConnected()) {
2464 m_curr_tid_run = 1;
2465 return true;
2466 }
2467 }
2468 return false;
2469}
2470
2471bool GDBRemoteCommunicationClient::GetStopReply(
2472 StringExtractorGDBRemote &response) {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002473 if (SendPacketAndWaitForResponse("?", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002474 PacketResult::Success)
2475 return response.IsNormalResponse();
2476 return false;
2477}
2478
2479bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2480 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2481 if (m_supports_qThreadStopInfo) {
2482 char packet[256];
2483 int packet_len =
2484 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2485 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002486 UNUSED_IF_ASSERT_DISABLED(packet_len);
2487 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002488 PacketResult::Success) {
2489 if (response.IsUnsupportedResponse())
2490 m_supports_qThreadStopInfo = false;
2491 else if (response.IsNormalResponse())
2492 return true;
2493 else
2494 return false;
2495 } else {
2496 m_supports_qThreadStopInfo = false;
2497 }
2498 }
2499 return false;
2500}
2501
2502uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2503 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2504 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2505 if (log)
2506 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2507 __FUNCTION__, insert ? "add" : "remove", addr);
2508
2509 // Check if the stub is known not to support this breakpoint type
2510 if (!SupportsGDBStoppointPacket(type))
2511 return UINT8_MAX;
2512 // Construct the breakpoint packet
2513 char packet[64];
2514 const int packet_len =
2515 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2516 insert ? 'Z' : 'z', type, addr, length);
2517 // Check we haven't overwritten the end of the packet buffer
2518 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002519 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002520 StringExtractorGDBRemote response;
2521 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2522 // or "" (unsupported)
2523 response.SetResponseValidatorToOKErrorNotSupported();
2524 // Try to send the breakpoint packet, and check that it was correctly sent
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002525 if (SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002526 PacketResult::Success) {
2527 // Receive and OK packet when the breakpoint successfully placed
2528 if (response.IsOKResponse())
2529 return 0;
2530
2531 // Error while setting breakpoint, send back specific error
2532 if (response.IsErrorResponse())
2533 return response.GetError();
2534
2535 // Empty packet informs us that breakpoint is not supported
2536 if (response.IsUnsupportedResponse()) {
2537 // Disable this breakpoint type since it is unsupported
2538 switch (type) {
2539 case eBreakpointSoftware:
2540 m_supports_z0 = false;
2541 break;
2542 case eBreakpointHardware:
2543 m_supports_z1 = false;
2544 break;
2545 case eWatchpointWrite:
2546 m_supports_z2 = false;
2547 break;
2548 case eWatchpointRead:
2549 m_supports_z3 = false;
2550 break;
2551 case eWatchpointReadWrite:
2552 m_supports_z4 = false;
2553 break;
2554 case eStoppointInvalid:
2555 return UINT8_MAX;
2556 }
2557 }
2558 }
2559 // Signal generic failure
2560 return UINT8_MAX;
2561}
2562
2563size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2564 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2565 thread_ids.clear();
2566
2567 Lock lock(*this, false);
2568 if (lock) {
2569 sequence_mutex_unavailable = false;
2570 StringExtractorGDBRemote response;
2571
2572 PacketResult packet_result;
2573 for (packet_result =
2574 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2575 packet_result == PacketResult::Success && response.IsNormalResponse();
2576 packet_result =
2577 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2578 char ch = response.GetChar();
2579 if (ch == 'l')
2580 break;
2581 if (ch == 'm') {
2582 do {
2583 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2584
2585 if (tid != LLDB_INVALID_THREAD_ID) {
2586 thread_ids.push_back(tid);
2587 }
2588 ch = response.GetChar(); // Skip the command separator
2589 } while (ch == ','); // Make sure we got a comma separator
2590 }
2591 }
2592
2593 /*
2594 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2595 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2596 * could
2597 * be as simple as 'S05'. There is no packet which can give us pid and/or
2598 * tid.
2599 * Assume pid=tid=1 in such cases.
2600 */
2601 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 &&
2602 IsConnected()) {
2603 thread_ids.push_back(1);
2604 }
2605 } else {
2606#if defined(LLDB_CONFIGURATION_DEBUG)
2607// assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the
2608// sequence mutex");
2609#else
2610 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2611 GDBR_LOG_PACKETS));
2612 if (log)
2613 log->Printf("error: failed to get packet sequence mutex, not sending "
2614 "packet 'qfThreadInfo'");
2615#endif
2616 sequence_mutex_unavailable = true;
2617 }
2618 return thread_ids.size();
2619}
2620
2621lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2622 StringExtractorGDBRemote response;
2623 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2624 PacketResult::Success ||
2625 !response.IsNormalResponse())
2626 return LLDB_INVALID_ADDRESS;
2627 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2628}
2629
2630lldb_private::Error GDBRemoteCommunicationClient::RunShellCommand(
2631 const char *command, // Shouldn't be NULL
2632 const FileSpec &
2633 working_dir, // Pass empty FileSpec to use the current working directory
2634 int *status_ptr, // Pass NULL if you don't want the process exit status
2635 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2636 // process to exit
2637 std::string
2638 *command_output, // Pass NULL if you don't want the command output
2639 uint32_t
2640 timeout_sec) // Timeout in seconds to wait for shell program to finish
2641{
2642 lldb_private::StreamString stream;
2643 stream.PutCString("qPlatform_shell:");
2644 stream.PutBytesAsRawHex8(command, strlen(command));
2645 stream.PutChar(',');
2646 stream.PutHex32(timeout_sec);
2647 if (working_dir) {
2648 std::string path{working_dir.GetPath(false)};
2649 stream.PutChar(',');
2650 stream.PutCStringAsRawHex8(path.c_str());
2651 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002652 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002653 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002654 PacketResult::Success) {
2655 if (response.GetChar() != 'F')
2656 return Error("malformed reply");
2657 if (response.GetChar() != ',')
2658 return Error("malformed reply");
2659 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2660 if (exitcode == UINT32_MAX)
2661 return Error("unable to run remote process");
2662 else if (status_ptr)
2663 *status_ptr = exitcode;
2664 if (response.GetChar() != ',')
2665 return Error("malformed reply");
2666 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2667 if (signo_ptr)
2668 *signo_ptr = signo;
2669 if (response.GetChar() != ',')
2670 return Error("malformed reply");
2671 std::string output;
2672 response.GetEscapedBinaryData(output);
2673 if (command_output)
2674 command_output->assign(output);
2675 return Error();
2676 }
2677 return Error("unable to send packet");
2678}
2679
2680Error GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2681 uint32_t file_permissions) {
2682 std::string path{file_spec.GetPath(false)};
2683 lldb_private::StreamString stream;
2684 stream.PutCString("qPlatform_mkdir:");
2685 stream.PutHex32(file_permissions);
2686 stream.PutChar(',');
2687 stream.PutCStringAsRawHex8(path.c_str());
2688 const char *packet = stream.GetData();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002689 StringExtractorGDBRemote response;
2690
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002691 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002692 PacketResult::Success)
2693 return Error("failed to send '%s' packet", packet);
2694
2695 if (response.GetChar() != 'F')
2696 return Error("invalid response to '%s' packet", packet);
2697
2698 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2699}
2700
2701Error GDBRemoteCommunicationClient::SetFilePermissions(
2702 const FileSpec &file_spec, uint32_t file_permissions) {
2703 std::string path{file_spec.GetPath(false)};
2704 lldb_private::StreamString stream;
2705 stream.PutCString("qPlatform_chmod:");
2706 stream.PutHex32(file_permissions);
2707 stream.PutChar(',');
2708 stream.PutCStringAsRawHex8(path.c_str());
2709 const char *packet = stream.GetData();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002710 StringExtractorGDBRemote response;
2711
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002712 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713 PacketResult::Success)
2714 return Error("failed to send '%s' packet", packet);
2715
2716 if (response.GetChar() != 'F')
2717 return Error("invalid response to '%s' packet", packet);
2718
2719 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2720}
2721
2722static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
2723 uint64_t fail_result, Error &error) {
2724 response.SetFilePos(0);
2725 if (response.GetChar() != 'F')
2726 return fail_result;
2727 int32_t result = response.GetS32(-2);
2728 if (result == -2)
2729 return fail_result;
2730 if (response.GetChar() == ',') {
2731 int result_errno = response.GetS32(-2);
2732 if (result_errno != -2)
2733 error.SetError(result_errno, eErrorTypePOSIX);
2734 else
2735 error.SetError(-1, eErrorTypeGeneric);
2736 } else
2737 error.Clear();
2738 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002739}
2740lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002741GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2742 uint32_t flags, mode_t mode,
2743 Error &error) {
2744 std::string path(file_spec.GetPath(false));
2745 lldb_private::StreamString stream;
2746 stream.PutCString("vFile:open:");
2747 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002748 return UINT64_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002749 stream.PutCStringAsRawHex8(path.c_str());
2750 stream.PutChar(',');
2751 stream.PutHex32(flags);
2752 stream.PutChar(',');
2753 stream.PutHex32(mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002754 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002755 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002756 PacketResult::Success) {
2757 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2758 }
2759 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002760}
2761
Kate Stoneb9c1b512016-09-06 20:57:50 +00002762bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd, Error &error) {
2763 lldb_private::StreamString stream;
2764 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002765 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002766 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002767 PacketResult::Success) {
2768 return ParseHostIOPacketResponse(response, -1, error) == 0;
2769 }
2770 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002771}
2772
2773// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002774lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2775 const lldb_private::FileSpec &file_spec) {
2776 std::string path(file_spec.GetPath(false));
2777 lldb_private::StreamString stream;
2778 stream.PutCString("vFile:size:");
2779 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002780 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002781 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002782 PacketResult::Success) {
2783 if (response.GetChar() != 'F')
2784 return UINT64_MAX;
2785 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2786 return retcode;
2787 }
2788 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002789}
2790
Kate Stoneb9c1b512016-09-06 20:57:50 +00002791Error GDBRemoteCommunicationClient::GetFilePermissions(
2792 const FileSpec &file_spec, uint32_t &file_permissions) {
2793 std::string path{file_spec.GetPath(false)};
2794 Error error;
2795 lldb_private::StreamString stream;
2796 stream.PutCString("vFile:mode:");
2797 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002798 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002799 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002800 PacketResult::Success) {
2801 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002802 error.SetErrorStringWithFormat("invalid response to '%s' packet",
2803 stream.GetString().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002804 } else {
2805 const uint32_t mode = response.GetS32(-1);
2806 if (static_cast<int32_t>(mode) == -1) {
2807 if (response.GetChar() == ',') {
2808 int response_errno = response.GetS32(-1);
2809 if (response_errno > 0)
2810 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2811 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002812 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002813 } else
2814 error.SetErrorToGenericError();
2815 } else {
2816 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2817 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002818 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002819 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002820 error.SetErrorStringWithFormat("failed to send '%s' packet",
2821 stream.GetString().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002822 }
2823 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002824}
2825
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2827 uint64_t offset, void *dst,
2828 uint64_t dst_len,
2829 Error &error) {
2830 lldb_private::StreamString stream;
2831 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2832 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002833 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002834 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002835 PacketResult::Success) {
2836 if (response.GetChar() != 'F')
2837 return 0;
2838 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2839 if (retcode == UINT32_MAX)
2840 return retcode;
2841 const char next = (response.Peek() ? *response.Peek() : 0);
2842 if (next == ',')
2843 return 0;
2844 if (next == ';') {
2845 response.GetChar(); // skip the semicolon
2846 std::string buffer;
2847 if (response.GetEscapedBinaryData(buffer)) {
2848 const uint64_t data_to_write =
2849 std::min<uint64_t>(dst_len, buffer.size());
2850 if (data_to_write > 0)
2851 memcpy(dst, &buffer[0], data_to_write);
2852 return data_to_write;
2853 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002854 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 }
2856 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002857}
2858
Kate Stoneb9c1b512016-09-06 20:57:50 +00002859uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
2860 uint64_t offset,
2861 const void *src,
2862 uint64_t src_len,
2863 Error &error) {
2864 lldb_private::StreamGDBRemote stream;
2865 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2866 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002867 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002868 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002869 PacketResult::Success) {
2870 if (response.GetChar() != 'F') {
2871 error.SetErrorStringWithFormat("write file failed");
2872 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002873 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002874 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2875 if (bytes_written == UINT64_MAX) {
2876 error.SetErrorToGenericError();
2877 if (response.GetChar() == ',') {
2878 int response_errno = response.GetS32(-1);
2879 if (response_errno > 0)
2880 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2881 }
2882 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002883 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002884 return bytes_written;
2885 } else {
2886 error.SetErrorString("failed to send vFile:pwrite packet");
2887 }
2888 return 0;
2889}
2890
2891Error GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
2892 const FileSpec &dst) {
2893 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
2894 Error error;
2895 lldb_private::StreamGDBRemote stream;
2896 stream.PutCString("vFile:symlink:");
2897 // the unix symlink() command reverses its parameters where the dst if first,
2898 // so we follow suit here
2899 stream.PutCStringAsRawHex8(dst_path.c_str());
2900 stream.PutChar(',');
2901 stream.PutCStringAsRawHex8(src_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002902 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002903 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002904 PacketResult::Success) {
2905 if (response.GetChar() == 'F') {
2906 uint32_t result = response.GetU32(UINT32_MAX);
2907 if (result != 0) {
2908 error.SetErrorToGenericError();
2909 if (response.GetChar() == ',') {
2910 int response_errno = response.GetS32(-1);
2911 if (response_errno > 0)
2912 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2913 }
2914 }
2915 } else {
2916 // Should have returned with 'F<result>[,<errno>]'
2917 error.SetErrorStringWithFormat("symlink failed");
2918 }
2919 } else {
2920 error.SetErrorString("failed to send vFile:symlink packet");
2921 }
2922 return error;
2923}
2924
2925Error GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
2926 std::string path{file_spec.GetPath(false)};
2927 Error error;
2928 lldb_private::StreamGDBRemote stream;
2929 stream.PutCString("vFile:unlink:");
2930 // the unix symlink() command reverses its parameters where the dst if first,
2931 // so we follow suit here
2932 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002933 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002934 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002935 PacketResult::Success) {
2936 if (response.GetChar() == 'F') {
2937 uint32_t result = response.GetU32(UINT32_MAX);
2938 if (result != 0) {
2939 error.SetErrorToGenericError();
2940 if (response.GetChar() == ',') {
2941 int response_errno = response.GetS32(-1);
2942 if (response_errno > 0)
2943 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2944 }
2945 }
2946 } else {
2947 // Should have returned with 'F<result>[,<errno>]'
2948 error.SetErrorStringWithFormat("unlink failed");
2949 }
2950 } else {
2951 error.SetErrorString("failed to send vFile:unlink packet");
2952 }
2953 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002954}
2955
Daniel Maleae0f8f572013-08-26 23:57:52 +00002956// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002957bool GDBRemoteCommunicationClient::GetFileExists(
2958 const lldb_private::FileSpec &file_spec) {
2959 std::string path(file_spec.GetPath(false));
2960 lldb_private::StreamString stream;
2961 stream.PutCString("vFile:exists:");
2962 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002963 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002964 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002965 PacketResult::Success) {
2966 if (response.GetChar() != 'F')
2967 return false;
2968 if (response.GetChar() != ',')
2969 return false;
2970 bool retcode = (response.GetChar() != '0');
2971 return retcode;
2972 }
2973 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002974}
2975
Kate Stoneb9c1b512016-09-06 20:57:50 +00002976bool GDBRemoteCommunicationClient::CalculateMD5(
2977 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
2978 std::string path(file_spec.GetPath(false));
2979 lldb_private::StreamString stream;
2980 stream.PutCString("vFile:MD5:");
2981 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002982 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002983 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002984 PacketResult::Success) {
2985 if (response.GetChar() != 'F')
2986 return false;
2987 if (response.GetChar() != ',')
2988 return false;
2989 if (response.Peek() && *response.Peek() == 'x')
2990 return false;
2991 low = response.GetHexMaxU64(false, UINT64_MAX);
2992 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00002993 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002994 }
2995 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00002996}
2997
Kate Stoneb9c1b512016-09-06 20:57:50 +00002998bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
2999 // Some targets have issues with g/G packets and we need to avoid using them
3000 if (m_avoid_g_packets == eLazyBoolCalculate) {
3001 if (process) {
3002 m_avoid_g_packets = eLazyBoolNo;
3003 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3004 if (arch.IsValid() &&
3005 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3006 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3007 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3008 m_avoid_g_packets = eLazyBoolYes;
3009 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3010 if (gdb_server_version != 0) {
3011 const char *gdb_server_name = GetGDBServerProgramName();
3012 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3013 if (gdb_server_version >= 310)
3014 m_avoid_g_packets = eLazyBoolNo;
3015 }
3016 }
3017 }
3018 }
3019 }
3020 return m_avoid_g_packets == eLazyBoolYes;
3021}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003022
Kate Stoneb9c1b512016-09-06 20:57:50 +00003023DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3024 uint32_t reg) {
3025 StreamString payload;
3026 payload.Printf("p%x", reg);
3027 StringExtractorGDBRemote response;
3028 if (SendThreadSpecificPacketAndWaitForResponse(
3029 tid, std::move(payload), response, false) != PacketResult::Success ||
3030 !response.IsNormalResponse())
3031 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003032
Kate Stoneb9c1b512016-09-06 20:57:50 +00003033 DataBufferSP buffer_sp(
3034 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3035 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3036 return buffer_sp;
3037}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003038
Kate Stoneb9c1b512016-09-06 20:57:50 +00003039DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3040 StreamString payload;
3041 payload.PutChar('g');
3042 StringExtractorGDBRemote response;
3043 if (SendThreadSpecificPacketAndWaitForResponse(
3044 tid, std::move(payload), response, false) != PacketResult::Success ||
3045 !response.IsNormalResponse())
3046 return nullptr;
3047
3048 DataBufferSP buffer_sp(
3049 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3050 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3051 return buffer_sp;
3052}
3053
3054bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3055 uint32_t reg_num,
3056 llvm::ArrayRef<uint8_t> data) {
3057 StreamString payload;
3058 payload.Printf("P%x=", reg_num);
3059 payload.PutBytesAsRawHex8(data.data(), data.size(),
3060 endian::InlHostByteOrder(),
3061 endian::InlHostByteOrder());
3062 StringExtractorGDBRemote response;
3063 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3064 response, false) ==
3065 PacketResult::Success &&
3066 response.IsOKResponse();
3067}
3068
3069bool GDBRemoteCommunicationClient::WriteAllRegisters(
3070 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3071 StreamString payload;
3072 payload.PutChar('G');
3073 payload.PutBytesAsRawHex8(data.data(), data.size(),
3074 endian::InlHostByteOrder(),
3075 endian::InlHostByteOrder());
3076 StringExtractorGDBRemote response;
3077 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3078 response, false) ==
3079 PacketResult::Success &&
3080 response.IsOKResponse();
3081}
3082
3083bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3084 uint32_t &save_id) {
3085 save_id = 0; // Set to invalid save ID
3086 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003087 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003088
3089 m_supports_QSaveRegisterState = eLazyBoolYes;
3090 StreamString payload;
3091 payload.PutCString("QSaveRegisterState");
3092 StringExtractorGDBRemote response;
3093 if (SendThreadSpecificPacketAndWaitForResponse(
3094 tid, std::move(payload), response, false) != PacketResult::Success)
3095 return false;
3096
3097 if (response.IsUnsupportedResponse())
3098 m_supports_QSaveRegisterState = eLazyBoolNo;
3099
3100 const uint32_t response_save_id = response.GetU32(0);
3101 if (response_save_id == 0)
3102 return false;
3103
3104 save_id = response_save_id;
3105 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003106}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003107
Kate Stoneb9c1b512016-09-06 20:57:50 +00003108bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3109 uint32_t save_id) {
3110 // We use the "m_supports_QSaveRegisterState" variable here because the
3111 // QSaveRegisterState and QRestoreRegisterState packets must both be supported
3112 // in
3113 // order to be useful
3114 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3115 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003116
Kate Stoneb9c1b512016-09-06 20:57:50 +00003117 StreamString payload;
3118 payload.Printf("QRestoreRegisterState:%u", save_id);
3119 StringExtractorGDBRemote response;
3120 if (SendThreadSpecificPacketAndWaitForResponse(
3121 tid, std::move(payload), response, false) != PacketResult::Success)
3122 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003123
Kate Stoneb9c1b512016-09-06 20:57:50 +00003124 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003125 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003126
3127 if (response.IsUnsupportedResponse())
3128 m_supports_QSaveRegisterState = eLazyBoolNo;
3129 return false;
3130}
3131
3132bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3133 if (!GetSyncThreadStateSupported())
3134 return false;
3135
3136 StreamString packet;
3137 StringExtractorGDBRemote response;
3138 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3139 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3140 GDBRemoteCommunication::PacketResult::Success &&
3141 response.IsOKResponse();
3142}
3143
3144bool GDBRemoteCommunicationClient::GetModuleInfo(
3145 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3146 ModuleSpec &module_spec) {
3147 if (!m_supports_qModuleInfo)
3148 return false;
3149
3150 std::string module_path = module_file_spec.GetPath(false);
3151 if (module_path.empty())
3152 return false;
3153
3154 StreamString packet;
3155 packet.PutCString("qModuleInfo:");
3156 packet.PutCStringAsRawHex8(module_path.c_str());
3157 packet.PutCString(";");
3158 const auto &triple = arch_spec.GetTriple().getTriple();
3159 packet.PutCStringAsRawHex8(triple.c_str());
3160
3161 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003162 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3163 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003164 return false;
3165
3166 if (response.IsErrorResponse())
3167 return false;
3168
3169 if (response.IsUnsupportedResponse()) {
3170 m_supports_qModuleInfo = false;
3171 return false;
3172 }
3173
3174 llvm::StringRef name;
3175 llvm::StringRef value;
3176
3177 module_spec.Clear();
3178 module_spec.GetFileSpec() = module_file_spec;
3179
3180 while (response.GetNameColonValue(name, value)) {
3181 if (name == "uuid" || name == "md5") {
3182 StringExtractor extractor(value);
3183 std::string uuid;
3184 extractor.GetHexByteString(uuid);
3185 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
3186 } else if (name == "triple") {
3187 StringExtractor extractor(value);
3188 std::string triple;
3189 extractor.GetHexByteString(triple);
3190 module_spec.GetArchitecture().SetTriple(triple.c_str());
3191 } else if (name == "file_offset") {
3192 uint64_t ival = 0;
3193 if (!value.getAsInteger(16, ival))
3194 module_spec.SetObjectOffset(ival);
3195 } else if (name == "file_size") {
3196 uint64_t ival = 0;
3197 if (!value.getAsInteger(16, ival))
3198 module_spec.SetObjectSize(ival);
3199 } else if (name == "file_path") {
3200 StringExtractor extractor(value);
3201 std::string path;
3202 extractor.GetHexByteString(path);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003203 module_spec.GetFileSpec() = FileSpec(path, false, arch_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003204 }
3205 }
3206
3207 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003208}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003209
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003210static llvm::Optional<ModuleSpec>
3211ParseModuleSpec(StructuredData::Dictionary *dict) {
3212 ModuleSpec result;
3213 if (!dict)
3214 return llvm::None;
3215
3216 std::string string;
3217 uint64_t integer;
3218
3219 if (!dict->GetValueForKeyAsString("uuid", string))
3220 return llvm::None;
3221 result.GetUUID().SetFromCString(string.c_str(), string.size());
3222
3223 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3224 return llvm::None;
3225 result.SetObjectOffset(integer);
3226
3227 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3228 return llvm::None;
3229 result.SetObjectSize(integer);
3230
3231 if (!dict->GetValueForKeyAsString("triple", string))
3232 return llvm::None;
3233 result.GetArchitecture().SetTriple(string.c_str());
3234
3235 if (!dict->GetValueForKeyAsString("file_path", string))
3236 return llvm::None;
3237 result.GetFileSpec() = FileSpec(string, false, result.GetArchitecture());
3238
3239 return result;
3240}
3241
3242llvm::Optional<std::vector<ModuleSpec>>
3243GDBRemoteCommunicationClient::GetModulesInfo(
3244 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3245 if (!m_supports_jModulesInfo)
3246 return llvm::None;
3247
3248 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3249 for (const FileSpec &module_file_spec : module_file_specs) {
3250 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3251 module_array_sp->AppendObject(module_sp);
3252 module_sp->SetObject(
3253 "file", std::make_shared<JSONString>(module_file_spec.GetPath()));
3254 module_sp->SetObject("triple",
3255 std::make_shared<JSONString>(triple.getTriple()));
3256 }
3257 StreamString unescaped_payload;
3258 unescaped_payload.PutCString("jModulesInfo:");
3259 module_array_sp->Write(unescaped_payload);
3260 StreamGDBRemote payload;
3261 payload.PutEscapedBytes(unescaped_payload.GetData(),
3262 unescaped_payload.GetSize());
3263
3264 StringExtractorGDBRemote response;
3265 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3266 PacketResult::Success ||
3267 response.IsErrorResponse())
3268 return llvm::None;
3269
3270 if (response.IsUnsupportedResponse()) {
3271 m_supports_jModulesInfo = false;
3272 return llvm::None;
3273 }
3274
3275 StructuredData::ObjectSP response_object_sp =
3276 StructuredData::ParseJSON(response.GetStringRef());
3277 if (!response_object_sp)
3278 return llvm::None;
3279
3280 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3281 if (!response_array)
3282 return llvm::None;
3283
3284 std::vector<ModuleSpec> result;
3285 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3286 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3287 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3288 result.push_back(*module_spec);
3289 }
3290
3291 return result;
3292}
3293
Colin Rileyc3c95b22015-04-16 15:51:33 +00003294// query the target remote for extended information using the qXfer packet
3295//
3296// example: object='features', annex='target.xml', out=<xml output>
3297// return: 'true' on success
3298// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003299bool GDBRemoteCommunicationClient::ReadExtFeature(
3300 const lldb_private::ConstString object,
3301 const lldb_private::ConstString annex, std::string &out,
3302 lldb_private::Error &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003303
Kate Stoneb9c1b512016-09-06 20:57:50 +00003304 std::stringstream output;
3305 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003306
Kate Stoneb9c1b512016-09-06 20:57:50 +00003307 uint64_t size = GetRemoteMaxPacketSize();
3308 if (size == 0)
3309 size = 0x1000;
3310 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3311 int offset = 0;
3312 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003313
Kate Stoneb9c1b512016-09-06 20:57:50 +00003314 // loop until all data has been read
3315 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003316
Kate Stoneb9c1b512016-09-06 20:57:50 +00003317 // send query extended feature packet
3318 std::stringstream packet;
3319 packet << "qXfer:" << object.AsCString("")
3320 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3321 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003322
Kate Stoneb9c1b512016-09-06 20:57:50 +00003323 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003324 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003325
Kate Stoneb9c1b512016-09-06 20:57:50 +00003326 if (res != GDBRemoteCommunication::PacketResult::Success) {
3327 err.SetErrorString("Error sending $qXfer packet");
3328 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003329 }
3330
Kate Stoneb9c1b512016-09-06 20:57:50 +00003331 const std::string &str = chunk.GetStringRef();
3332 if (str.length() == 0) {
3333 // should have some data in chunk
3334 err.SetErrorString("Empty response from $qXfer packet");
3335 return false;
3336 }
3337
3338 // check packet code
3339 switch (str[0]) {
3340 // last chunk
3341 case ('l'):
3342 active = false;
3343 LLVM_FALLTHROUGH;
3344
3345 // more chunks
3346 case ('m'):
3347 if (str.length() > 1)
3348 output << &str[1];
3349 offset += size;
3350 break;
3351
3352 // unknown chunk
3353 default:
3354 err.SetErrorString("Invalid continuation code from $qXfer packet");
3355 return false;
3356 }
3357 }
3358
3359 out = output.str();
3360 err.Success();
3361 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003362}
Greg Clayton0b90be12015-06-23 21:27:50 +00003363
3364// Notify the target that gdb is prepared to serve symbol lookup requests.
3365// packet: "qSymbol::"
3366// reply:
3367// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003368// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3369// encoded).
3370// LLDB may provide the value by sending another qSymbol
3371// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003372// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003373//
3374// Three examples:
3375//
3376// lldb sends: qSymbol::
3377// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003378// Remote gdb stub does not need to know the addresses of any symbols, lldb
3379// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003380// need to ask again in this session.
3381//
3382// lldb sends: qSymbol::
3383// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3384// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3385// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003386// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3387// not know
3388// the address at this time. lldb needs to send qSymbol:: again when it has
3389// more
Jason Molenda50018d32016-01-13 04:08:10 +00003390// solibs loaded.
3391//
3392// lldb sends: qSymbol::
3393// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3394// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3395// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003396// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3397// that it
3398// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3399// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003400// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003401
Kate Stoneb9c1b512016-09-06 20:57:50 +00003402void GDBRemoteCommunicationClient::ServeSymbolLookups(
3403 lldb_private::Process *process) {
3404 // Set to true once we've resolved a symbol to an address for the remote stub.
3405 // If we get an 'OK' response after this, the remote stub doesn't need any
3406 // more
3407 // symbols and we can stop asking.
3408 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003409
Kate Stoneb9c1b512016-09-06 20:57:50 +00003410 // Is this the initial qSymbol:: packet?
3411 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003412
Kate Stoneb9c1b512016-09-06 20:57:50 +00003413 if (m_supports_qSymbol && m_qSymbol_requests_done == false) {
3414 Lock lock(*this, false);
3415 if (lock) {
3416 StreamString packet;
3417 packet.PutCString("qSymbol::");
3418 StringExtractorGDBRemote response;
3419 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3420 PacketResult::Success) {
3421 if (response.IsOKResponse()) {
3422 if (symbol_response_provided || first_qsymbol_query) {
3423 m_qSymbol_requests_done = true;
3424 }
3425
3426 // We are done serving symbols requests
3427 return;
3428 }
3429 first_qsymbol_query = false;
3430
3431 if (response.IsUnsupportedResponse()) {
3432 // qSymbol is not supported by the current GDB server we are connected
3433 // to
3434 m_supports_qSymbol = false;
3435 return;
3436 } else {
3437 llvm::StringRef response_str(response.GetStringRef());
3438 if (response_str.startswith("qSymbol:")) {
3439 response.SetFilePos(strlen("qSymbol:"));
3440 std::string symbol_name;
3441 if (response.GetHexByteString(symbol_name)) {
3442 if (symbol_name.empty())
3443 return;
3444
3445 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3446 lldb_private::SymbolContextList sc_list;
3447 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3448 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3449 const size_t num_scs = sc_list.GetSize();
3450 for (size_t sc_idx = 0;
3451 sc_idx < num_scs &&
3452 symbol_load_addr == LLDB_INVALID_ADDRESS;
3453 ++sc_idx) {
3454 SymbolContext sc;
3455 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3456 if (sc.symbol) {
3457 switch (sc.symbol->GetType()) {
3458 case eSymbolTypeInvalid:
3459 case eSymbolTypeAbsolute:
3460 case eSymbolTypeUndefined:
3461 case eSymbolTypeSourceFile:
3462 case eSymbolTypeHeaderFile:
3463 case eSymbolTypeObjectFile:
3464 case eSymbolTypeCommonBlock:
3465 case eSymbolTypeBlock:
3466 case eSymbolTypeLocal:
3467 case eSymbolTypeParam:
3468 case eSymbolTypeVariable:
3469 case eSymbolTypeVariableType:
3470 case eSymbolTypeLineEntry:
3471 case eSymbolTypeLineHeader:
3472 case eSymbolTypeScopeBegin:
3473 case eSymbolTypeScopeEnd:
3474 case eSymbolTypeAdditional:
3475 case eSymbolTypeCompiler:
3476 case eSymbolTypeInstrumentation:
3477 case eSymbolTypeTrampoline:
3478 break;
3479
3480 case eSymbolTypeCode:
3481 case eSymbolTypeResolver:
3482 case eSymbolTypeData:
3483 case eSymbolTypeRuntime:
3484 case eSymbolTypeException:
3485 case eSymbolTypeObjCClass:
3486 case eSymbolTypeObjCMetaClass:
3487 case eSymbolTypeObjCIVar:
3488 case eSymbolTypeReExported:
3489 symbol_load_addr =
3490 sc.symbol->GetLoadAddress(&process->GetTarget());
3491 break;
3492 }
Jason Molenda50018d32016-01-13 04:08:10 +00003493 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003494 }
Greg Clayton42b01482015-08-11 22:07:46 +00003495 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003496 }
3497 // This is the normal path where our symbol lookup was successful
3498 // and we want
3499 // to send a packet with the new symbol value and see if another
3500 // lookup needs to be
3501 // done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003502
Kate Stoneb9c1b512016-09-06 20:57:50 +00003503 // Change "packet" to contain the requested symbol value and name
3504 packet.Clear();
3505 packet.PutCString("qSymbol:");
3506 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3507 packet.Printf("%" PRIx64, symbol_load_addr);
3508 symbol_response_provided = true;
3509 } else {
3510 symbol_response_provided = false;
3511 }
3512 packet.PutCString(":");
3513 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3514 continue; // go back to the while loop and send "packet" and wait
3515 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003516 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003517 }
3518 }
3519 }
3520 // If we make it here, the symbol request packet response wasn't valid or
3521 // our symbol lookup failed so we must abort
3522 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003523
Kate Stoneb9c1b512016-09-06 20:57:50 +00003524 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3525 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3526 log->Printf(
3527 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3528 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003529 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003530 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003531}
3532
Kate Stoneb9c1b512016-09-06 20:57:50 +00003533StructuredData::Array *
3534GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3535 if (!m_supported_async_json_packets_is_valid) {
3536 // Query the server for the array of supported asynchronous JSON
3537 // packets.
3538 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003539
Kate Stoneb9c1b512016-09-06 20:57:50 +00003540 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003541
Kate Stoneb9c1b512016-09-06 20:57:50 +00003542 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003543 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003544 const bool send_async = false;
3545 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3546 send_async) == PacketResult::Success) {
3547 m_supported_async_json_packets_sp =
3548 StructuredData::ParseJSON(response.GetStringRef());
3549 if (m_supported_async_json_packets_sp &&
3550 !m_supported_async_json_packets_sp->GetAsArray()) {
3551 // We were returned something other than a JSON array. This
3552 // is invalid. Clear it out.
3553 if (log)
3554 log->Printf("GDBRemoteCommunicationClient::%s(): "
3555 "QSupportedAsyncJSONPackets returned invalid "
3556 "result: %s",
3557 __FUNCTION__, response.GetStringRef().c_str());
3558 m_supported_async_json_packets_sp.reset();
3559 }
3560 } else {
3561 if (log)
3562 log->Printf("GDBRemoteCommunicationClient::%s(): "
3563 "QSupportedAsyncJSONPackets unsupported",
3564 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003565 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003566
3567 if (log && m_supported_async_json_packets_sp) {
3568 StreamString stream;
3569 m_supported_async_json_packets_sp->Dump(stream);
3570 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3571 "JSON packets: %s",
3572 __FUNCTION__, stream.GetString().c_str());
Todd Fiala75930012016-08-19 04:21:48 +00003573 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003574 }
3575
3576 return m_supported_async_json_packets_sp
3577 ? m_supported_async_json_packets_sp->GetAsArray()
3578 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003579}
3580
Kate Stoneb9c1b512016-09-06 20:57:50 +00003581Error GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
3582 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
3583 Error error;
3584
3585 if (type_name.GetLength() == 0) {
3586 error.SetErrorString("invalid type_name argument");
3587 return error;
3588 }
3589
3590 // Build command: Configure{type_name}: serialized config
3591 // data.
3592 StreamGDBRemote stream;
3593 stream.PutCString("QConfigure");
3594 stream.PutCString(type_name.AsCString());
3595 stream.PutChar(':');
3596 if (config_sp) {
3597 // Gather the plain-text version of the configuration data.
3598 StreamString unescaped_stream;
3599 config_sp->Dump(unescaped_stream);
3600 unescaped_stream.Flush();
3601
3602 // Add it to the stream in escaped fashion.
3603 stream.PutEscapedBytes(unescaped_stream.GetData(),
3604 unescaped_stream.GetSize());
3605 }
3606 stream.Flush();
3607
3608 // Send the packet.
3609 const bool send_async = false;
3610 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003611 auto result =
3612 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003613 if (result == PacketResult::Success) {
3614 // We failed if the config result comes back other than OK.
3615 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3616 // Okay!
3617 error.Clear();
3618 } else {
3619 error.SetErrorStringWithFormat("configuring StructuredData feature "
3620 "%s failed with error %s",
3621 type_name.AsCString(),
3622 response.GetStringRef().c_str());
3623 }
3624 } else {
3625 // Can we get more data here on the failure?
3626 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3627 "failed when sending packet: "
3628 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00003629 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003630 }
3631 return error;
3632}
3633
3634void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
3635 GDBRemoteClientBase::OnRunPacketSent(first);
3636 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003637}