blob: 33aed7a43c4a18a8d8ab76d5a463f2c25e54c2cf [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
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000021#include "lldb/Core/ModuleSpec.h"
Greg Clayton576d8832011-03-22 04:00:09 +000022#include "lldb/Core/State.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000023#include "lldb/Host/HostInfo.h"
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000024#include "lldb/Interpreter/Args.h"
Greg Clayton0b90be12015-06-23 21:27:50 +000025#include "lldb/Symbol/Symbol.h"
Pavel Labath4cb69922016-07-29 15:41:52 +000026#include "lldb/Target/MemoryRegionInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000027#include "lldb/Target/Target.h"
Todd Fiala75930012016-08-19 04:21:48 +000028#include "lldb/Target/UnixSignals.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000029#include "lldb/Utility/DataBufferHeap.h"
Pavel Labath2f1fbae2016-09-08 10:07:04 +000030#include "lldb/Utility/JSON.h"
Todd Fiala75930012016-08-19 04:21:48 +000031#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000032#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000033#include "lldb/Utility/StreamString.h"
Greg Clayton576d8832011-03-22 04:00:09 +000034
35// Project includes
Greg Clayton576d8832011-03-22 04:00:09 +000036#include "ProcessGDBRemote.h"
37#include "ProcessGDBRemoteLog.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000038#include "Utility/StringExtractorGDBRemote.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000039#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000040
Zachary Turner54695a32016-08-29 19:58:14 +000041#include "llvm/ADT/StringSwitch.h"
42
Kate Stoneb9c1b512016-09-06 20:57:50 +000043#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000044#include <compression.h>
45#endif
46
Greg Clayton576d8832011-03-22 04:00:09 +000047using namespace lldb;
48using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000049using namespace lldb_private::process_gdb_remote;
Pavel Labath1eff73c2016-11-24 10:54:49 +000050using namespace std::chrono;
Greg Clayton576d8832011-03-22 04:00:09 +000051
52//----------------------------------------------------------------------
53// GDBRemoteCommunicationClient constructor
54//----------------------------------------------------------------------
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000055GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000056 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000057 m_supports_not_sending_acks(eLazyBoolCalculate),
58 m_supports_thread_suffix(eLazyBoolCalculate),
59 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
60 m_supports_vCont_all(eLazyBoolCalculate),
61 m_supports_vCont_any(eLazyBoolCalculate),
62 m_supports_vCont_c(eLazyBoolCalculate),
63 m_supports_vCont_C(eLazyBoolCalculate),
64 m_supports_vCont_s(eLazyBoolCalculate),
65 m_supports_vCont_S(eLazyBoolCalculate),
66 m_qHostInfo_is_valid(eLazyBoolCalculate),
67 m_curr_pid_is_valid(eLazyBoolCalculate),
68 m_qProcessInfo_is_valid(eLazyBoolCalculate),
69 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
70 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
71 m_supports_memory_region_info(eLazyBoolCalculate),
72 m_supports_watchpoint_support_info(eLazyBoolCalculate),
73 m_supports_detach_stay_stopped(eLazyBoolCalculate),
74 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
75 m_attach_or_wait_reply(eLazyBoolCalculate),
76 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000077 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000078 m_avoid_g_packets(eLazyBoolCalculate),
79 m_supports_QSaveRegisterState(eLazyBoolCalculate),
80 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
81 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
82 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
83 m_supports_qXfer_features_read(eLazyBoolCalculate),
84 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
85 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
86 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000087 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
Eugene Zemtsov7993cc52017-03-07 21:34:40 +000088 m_supports_QPassSignals(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
Zachary Turner97206d52017-05-12 04:51:55 +0000115bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 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;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125 while (packet_result == PacketResult::Success)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000126 packet_result = ReadPacket(response, milliseconds(10), false);
Ed Maste48f986f2013-12-18 15:31:45 +0000127
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128 // The return value from QueryNoAckModeSupported() is true if the packet
129 // was sent and _any_ response (including UNIMPLEMENTED) was received),
130 // or false if no response was received. This quickly tells us if we have
131 // a live connection to a remote GDB server...
132 if (QueryNoAckModeSupported()) {
133 return true;
134 } else {
135 if (error_ptr)
136 error_ptr->SetErrorString("failed to get reply to handshake packet");
Greg Claytonfb909312013-11-23 01:58:15 +0000137 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138 } else {
139 if (error_ptr)
140 error_ptr->SetErrorString("failed to send the handshake ack");
141 }
142 return false;
Greg Clayton1cb64962011-03-24 04:28:38 +0000143}
144
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145bool GDBRemoteCommunicationClient::GetEchoSupported() {
146 if (m_supports_qEcho == eLazyBoolCalculate) {
147 GetRemoteQSupported();
148 }
149 return m_supports_qEcho == eLazyBoolYes;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000150}
151
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000152bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() {
153 if (m_supports_QPassSignals == eLazyBoolCalculate) {
154 GetRemoteQSupported();
155 }
156 return m_supports_QPassSignals == eLazyBoolYes;
157}
158
Kate Stoneb9c1b512016-09-06 20:57:50 +0000159bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
160 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
161 GetRemoteQSupported();
162 }
163 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000164}
165
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
167 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
168 GetRemoteQSupported();
169 }
170 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000171}
172
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
174 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
175 GetRemoteQSupported();
176 }
177 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000178}
179
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
181 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
182 GetRemoteQSupported();
183 }
184 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000185}
186
Kate Stoneb9c1b512016-09-06 20:57:50 +0000187bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
188 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
189 GetRemoteQSupported();
190 }
191 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000192}
193
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
195 if (m_max_packet_size == 0) {
196 GetRemoteQSupported();
197 }
198 return m_max_packet_size;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000199}
200
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
202 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
203 m_send_acks = true;
204 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000205
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206 // This is the first real packet that we'll send in a debug session and it
207 // may take a little
208 // longer than normal to receive a reply. Wait at least 6 seconds for a
209 // reply to this packet.
Jason Molenda36a216e2014-07-24 01:36:24 +0000210
Pavel Labath1eff73c2016-11-24 10:54:49 +0000211 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
Colin Rileyc3c95b22015-04-16 15:51:33 +0000212
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000213 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
215 PacketResult::Success) {
216 if (response.IsOKResponse()) {
217 m_send_acks = false;
218 m_supports_not_sending_acks = eLazyBoolYes;
219 }
220 return true;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000221 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000222 }
223 return false;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000224}
Greg Clayton576d8832011-03-22 04:00:09 +0000225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
227 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
228 m_supports_threads_in_stop_reply = eLazyBoolNo;
229
230 StringExtractorGDBRemote response;
231 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
232 false) == PacketResult::Success) {
233 if (response.IsOKResponse())
234 m_supports_threads_in_stop_reply = eLazyBoolYes;
Pavel Labath5c95ee42016-08-30 13:56:11 +0000235 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236 }
Pavel Labath0faf3732016-08-25 08:34:57 +0000237}
Greg Clayton576d8832011-03-22 04:00:09 +0000238
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
240 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
241 m_attach_or_wait_reply = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +0000242
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243 StringExtractorGDBRemote response;
244 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
245 false) == PacketResult::Success) {
246 if (response.IsOKResponse())
247 m_attach_or_wait_reply = eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000248 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 }
250 if (m_attach_or_wait_reply == eLazyBoolYes)
251 return true;
252 else
Greg Clayton576d8832011-03-22 04:00:09 +0000253 return false;
254}
255
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
257 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
258 m_prepare_for_reg_writing_reply = eLazyBoolNo;
259
260 StringExtractorGDBRemote response;
261 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
262 false) == PacketResult::Success) {
263 if (response.IsOKResponse())
264 m_prepare_for_reg_writing_reply = eLazyBoolYes;
265 }
266 }
267 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
268 return true;
269 else
270 return false;
271}
272
273void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
274 if (did_exec == false) {
275 // Hard reset everything, this is when we first connect to a GDB server
276 m_supports_not_sending_acks = eLazyBoolCalculate;
277 m_supports_thread_suffix = eLazyBoolCalculate;
278 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
279 m_supports_vCont_c = eLazyBoolCalculate;
280 m_supports_vCont_C = eLazyBoolCalculate;
281 m_supports_vCont_s = eLazyBoolCalculate;
282 m_supports_vCont_S = eLazyBoolCalculate;
283 m_supports_p = eLazyBoolCalculate;
284 m_supports_x = eLazyBoolCalculate;
285 m_supports_QSaveRegisterState = eLazyBoolCalculate;
286 m_qHostInfo_is_valid = eLazyBoolCalculate;
287 m_curr_pid_is_valid = eLazyBoolCalculate;
288 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
289 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
290 m_supports_memory_region_info = eLazyBoolCalculate;
291 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
292 m_attach_or_wait_reply = eLazyBoolCalculate;
293 m_avoid_g_packets = eLazyBoolCalculate;
294 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
295 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
296 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
297 m_supports_qXfer_features_read = eLazyBoolCalculate;
298 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
299 m_supports_qProcessInfoPID = true;
300 m_supports_qfProcessInfo = true;
301 m_supports_qUserName = true;
302 m_supports_qGroupName = true;
303 m_supports_qThreadStopInfo = true;
304 m_supports_z0 = true;
305 m_supports_z1 = true;
306 m_supports_z2 = true;
307 m_supports_z3 = true;
308 m_supports_z4 = true;
309 m_supports_QEnvironment = true;
310 m_supports_QEnvironmentHexEncoded = true;
311 m_supports_qSymbol = true;
312 m_qSymbol_requests_done = false;
313 m_supports_qModuleInfo = true;
314 m_host_arch.Clear();
315 m_os_version_major = UINT32_MAX;
316 m_os_version_minor = UINT32_MAX;
317 m_os_version_update = UINT32_MAX;
318 m_os_build.clear();
319 m_os_kernel.clear();
320 m_hostname.clear();
321 m_gdb_server_name.clear();
322 m_gdb_server_version = UINT32_MAX;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000323 m_default_packet_timeout = seconds(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324 m_max_packet_size = 0;
325 m_qSupported_response.clear();
326 m_supported_async_json_packets_is_valid = false;
327 m_supported_async_json_packets_sp.reset();
Pavel Labath2f1fbae2016-09-08 10:07:04 +0000328 m_supports_jModulesInfo = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329 }
330
331 // These flags should be reset when we first connect to a GDB server
332 // and when our inferior process execs
333 m_qProcessInfo_is_valid = eLazyBoolCalculate;
334 m_process_arch.Clear();
335}
336
337void GDBRemoteCommunicationClient::GetRemoteQSupported() {
338 // Clear out any capabilities we expect to see in the qSupported response
339 m_supports_qXfer_auxv_read = eLazyBoolNo;
340 m_supports_qXfer_libraries_read = eLazyBoolNo;
341 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
342 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
343 m_supports_qXfer_features_read = eLazyBoolNo;
344 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
345 // not, we assume no limit
346
347 // build the qSupported packet
348 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
349 StreamString packet;
350 packet.PutCString("qSupported");
351 for (uint32_t i = 0; i < features.size(); ++i) {
352 packet.PutCString(i == 0 ? ":" : ";");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000353 packet.PutCString(features[i]);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 }
355
356 StringExtractorGDBRemote response;
Zachary Turnerc1564272016-11-16 21:15:24 +0000357 if (SendPacketAndWaitForResponse(packet.GetString(), response,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 /*send_async=*/false) ==
359 PacketResult::Success) {
360 const char *response_cstr = response.GetStringRef().c_str();
361
362 // Hang on to the qSupported packet, so that platforms can do custom
363 // configuration of the transport before attaching/launching the
364 // process.
365 m_qSupported_response = response_cstr;
366
367 if (::strstr(response_cstr, "qXfer:auxv:read+"))
368 m_supports_qXfer_auxv_read = eLazyBoolYes;
369 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
370 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
371 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
372 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
373 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
374 }
375 if (::strstr(response_cstr, "qXfer:libraries:read+"))
376 m_supports_qXfer_libraries_read = eLazyBoolYes;
377 if (::strstr(response_cstr, "qXfer:features:read+"))
378 m_supports_qXfer_features_read = eLazyBoolYes;
379
380 // Look for a list of compressions in the features list e.g.
381 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
382 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
383 if (features_list) {
384 const char *compressions =
385 ::strstr(features_list, "SupportedCompressions=");
386 if (compressions) {
387 std::vector<std::string> supported_compressions;
388 compressions += sizeof("SupportedCompressions=") - 1;
389 const char *end_of_compressions = strchr(compressions, ';');
390 if (end_of_compressions == NULL) {
391 end_of_compressions = strchr(compressions, '\0');
392 }
393 const char *current_compression = compressions;
394 while (current_compression < end_of_compressions) {
395 const char *next_compression_name = strchr(current_compression, ',');
396 const char *end_of_this_word = next_compression_name;
397 if (next_compression_name == NULL ||
398 end_of_compressions < next_compression_name) {
399 end_of_this_word = end_of_compressions;
400 }
401
402 if (end_of_this_word) {
403 if (end_of_this_word == current_compression) {
404 current_compression++;
405 } else {
406 std::string this_compression(
407 current_compression, end_of_this_word - current_compression);
408 supported_compressions.push_back(this_compression);
409 current_compression = end_of_this_word + 1;
410 }
411 } else {
412 supported_compressions.push_back(current_compression);
413 current_compression = end_of_compressions;
414 }
415 }
416
417 if (supported_compressions.size() > 0) {
418 MaybeEnableCompression(supported_compressions);
419 }
420 }
421 }
422
423 if (::strstr(response_cstr, "qEcho"))
424 m_supports_qEcho = eLazyBoolYes;
425 else
426 m_supports_qEcho = eLazyBoolNo;
427
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000428 if (::strstr(response_cstr, "QPassSignals+"))
429 m_supports_QPassSignals = eLazyBoolYes;
430 else
431 m_supports_QPassSignals = eLazyBoolNo;
432
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
434 if (packet_size_str) {
435 StringExtractorGDBRemote packet_response(packet_size_str +
436 strlen("PacketSize="));
437 m_max_packet_size =
438 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
439 if (m_max_packet_size == 0) {
440 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
441 Log *log(
442 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
443 if (log)
444 log->Printf("Garbled PacketSize spec in qSupported response");
445 }
446 }
447 }
448}
449
450bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
451 if (m_supports_thread_suffix == eLazyBoolCalculate) {
452 StringExtractorGDBRemote response;
453 m_supports_thread_suffix = eLazyBoolNo;
454 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
455 false) == PacketResult::Success) {
456 if (response.IsOKResponse())
457 m_supports_thread_suffix = eLazyBoolYes;
458 }
459 }
460 return m_supports_thread_suffix;
461}
462bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
463 if (m_supports_vCont_c == eLazyBoolCalculate) {
464 StringExtractorGDBRemote response;
465 m_supports_vCont_any = eLazyBoolNo;
466 m_supports_vCont_all = eLazyBoolNo;
467 m_supports_vCont_c = eLazyBoolNo;
468 m_supports_vCont_C = eLazyBoolNo;
469 m_supports_vCont_s = eLazyBoolNo;
470 m_supports_vCont_S = eLazyBoolNo;
471 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
472 PacketResult::Success) {
473 const char *response_cstr = response.GetStringRef().c_str();
474 if (::strstr(response_cstr, ";c"))
475 m_supports_vCont_c = eLazyBoolYes;
476
477 if (::strstr(response_cstr, ";C"))
478 m_supports_vCont_C = eLazyBoolYes;
479
480 if (::strstr(response_cstr, ";s"))
481 m_supports_vCont_s = eLazyBoolYes;
482
483 if (::strstr(response_cstr, ";S"))
484 m_supports_vCont_S = eLazyBoolYes;
485
486 if (m_supports_vCont_c == eLazyBoolYes &&
487 m_supports_vCont_C == eLazyBoolYes &&
488 m_supports_vCont_s == eLazyBoolYes &&
489 m_supports_vCont_S == eLazyBoolYes) {
490 m_supports_vCont_all = eLazyBoolYes;
491 }
492
493 if (m_supports_vCont_c == eLazyBoolYes ||
494 m_supports_vCont_C == eLazyBoolYes ||
495 m_supports_vCont_s == eLazyBoolYes ||
496 m_supports_vCont_S == eLazyBoolYes) {
497 m_supports_vCont_any = eLazyBoolYes;
498 }
499 }
500 }
501
502 switch (flavor) {
503 case 'a':
504 return m_supports_vCont_any;
505 case 'A':
506 return m_supports_vCont_all;
507 case 'c':
508 return m_supports_vCont_c;
509 case 'C':
510 return m_supports_vCont_C;
511 case 's':
512 return m_supports_vCont_s;
513 case 'S':
514 return m_supports_vCont_S;
515 default:
516 break;
517 }
518 return false;
519}
520
Pavel Labath4b6f9592016-08-18 08:30:03 +0000521GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
523 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
524 bool send_async) {
525 Lock lock(*this, send_async);
526 if (!lock) {
527 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
528 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
529 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
530 "for %s packet.",
Zachary Turnerc1564272016-11-16 21:15:24 +0000531 __FUNCTION__, payload.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000532 return PacketResult::ErrorNoSequenceLock;
533 }
Pavel Labath5c95ee42016-08-30 13:56:11 +0000534
Kate Stoneb9c1b512016-09-06 20:57:50 +0000535 if (GetThreadSuffixSupported())
536 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
537 else {
538 if (!SetCurrentThread(tid))
539 return PacketResult::ErrorSendFailed;
540 }
Pavel Labath4b6f9592016-08-18 08:30:03 +0000541
Kate Stoneb9c1b512016-09-06 20:57:50 +0000542 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
Pavel Labath4b6f9592016-08-18 08:30:03 +0000543}
544
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000545// Check if the target supports 'p' packet. It sends out a 'p'
546// packet and checks the response. A normal packet will tell us
547// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000548//
549// Takes a valid thread ID because p needs to apply to a thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
551 if (m_supports_p == eLazyBoolCalculate) {
552 m_supports_p = eLazyBoolNo;
553 StreamString payload;
554 payload.PutCString("p0");
555 StringExtractorGDBRemote response;
556 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
557 response, false) ==
558 PacketResult::Success &&
559 response.IsNormalResponse()) {
560 m_supports_p = eLazyBoolYes;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000561 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 }
563 return m_supports_p;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000564}
Greg Clayton576d8832011-03-22 04:00:09 +0000565
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
567 // Get information on all threads at one using the "jThreadsInfo" packet
568 StructuredData::ObjectSP object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000569
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 if (m_supports_jThreadsInfo) {
571 StringExtractorGDBRemote response;
572 response.SetResponseValidatorToJSON();
573 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
574 PacketResult::Success) {
575 if (response.IsUnsupportedResponse()) {
576 m_supports_jThreadsInfo = false;
577 } else if (!response.Empty()) {
578 object_sp = StructuredData::ParseJSON(response.GetStringRef());
579 }
Greg Clayton358cf1e2015-06-25 21:46:34 +0000580 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581 }
582 return object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000583}
584
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
586 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
587 StringExtractorGDBRemote response;
588 m_supports_jThreadExtendedInfo = eLazyBoolNo;
589 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
590 PacketResult::Success) {
591 if (response.IsOKResponse()) {
592 m_supports_jThreadExtendedInfo = eLazyBoolYes;
593 }
Jason Molenda705b1802014-06-13 02:37:02 +0000594 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595 }
596 return m_supports_jThreadExtendedInfo;
Jason Molenda705b1802014-06-13 02:37:02 +0000597}
598
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
600 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
601 StringExtractorGDBRemote response;
602 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
603 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
604 response,
605 false) == PacketResult::Success) {
606 if (response.IsOKResponse()) {
607 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
608 }
Jason Molenda20ee21b2015-07-10 23:15:22 +0000609 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000610 }
611 return m_supports_jLoadedDynamicLibrariesInfos;
Jason Molenda20ee21b2015-07-10 23:15:22 +0000612}
613
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
615 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
616 StringExtractorGDBRemote response;
617 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
618 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
619 PacketResult::Success) {
620 if (response.IsOKResponse()) {
621 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
622 }
Jason Molenda37397352016-07-22 00:17:55 +0000623 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624 }
625 return m_supports_jGetSharedCacheInfo;
Jason Molenda37397352016-07-22 00:17:55 +0000626}
627
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628bool GDBRemoteCommunicationClient::GetxPacketSupported() {
629 if (m_supports_x == eLazyBoolCalculate) {
630 StringExtractorGDBRemote response;
631 m_supports_x = eLazyBoolNo;
632 char packet[256];
633 snprintf(packet, sizeof(packet), "x0,0");
634 if (SendPacketAndWaitForResponse(packet, response, false) ==
635 PacketResult::Success) {
636 if (response.IsOKResponse())
637 m_supports_x = eLazyBoolYes;
Jason Molendabdc4f122014-05-06 02:59:39 +0000638 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639 }
640 return m_supports_x;
Jason Molendabdc4f122014-05-06 02:59:39 +0000641}
642
Greg Clayton3dedae12013-12-06 21:45:27 +0000643GDBRemoteCommunicationClient::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
645 const char *payload_prefix, std::string &response_string) {
646 Lock lock(*this, false);
647 if (!lock) {
648 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
649 GDBR_LOG_PACKETS));
650 if (log)
651 log->Printf("error: failed to get packet sequence mutex, not sending "
652 "packets with prefix '%s'",
653 payload_prefix);
654 return PacketResult::ErrorNoSequenceLock;
655 }
656
657 response_string = "";
658 std::string payload_prefix_str(payload_prefix);
659 unsigned int response_size = 0x1000;
660 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
661 response_size = GetRemoteMaxPacketSize();
662 }
663
664 for (unsigned int offset = 0; true; offset += response_size) {
665 StringExtractorGDBRemote this_response;
666 // Construct payload
667 char sizeDescriptor[128];
668 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
669 response_size);
670 PacketResult result = SendPacketAndWaitForResponseNoLock(
671 payload_prefix_str + sizeDescriptor, this_response);
672 if (result != PacketResult::Success)
673 return result;
674
675 const std::string &this_string = this_response.GetStringRef();
676
677 // Check for m or l as first character; l seems to mean this is the last
678 // chunk
679 char first_char = *this_string.c_str();
680 if (first_char != 'm' && first_char != 'l') {
681 return PacketResult::ErrorReplyInvalid;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000682 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000683 // Concatenate the result so far (skipping 'm' or 'l')
684 response_string.append(this_string, 1, std::string::npos);
685 if (first_char == 'l')
686 // We're done
687 return PacketResult::Success;
688 }
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000689}
690
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
692 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
693 return m_curr_pid;
Jaydeep Patil1142f832015-08-13 03:46:36 +0000694
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 // First try to retrieve the pid via the qProcessInfo request.
696 GetCurrentProcessInfo(allow_lazy);
697 if (m_curr_pid_is_valid == eLazyBoolYes) {
698 // We really got it.
699 return m_curr_pid;
700 } else {
701 // If we don't get a response for qProcessInfo, check if $qC gives us a
702 // result.
703 // $qC only returns a real process id on older debugserver and lldb-platform
704 // stubs.
705 // The gdb remote protocol documents $qC as returning the thread id, which
706 // newer
707 // debugserver and lldb-gdbserver stubs return correctly.
Greg Clayton576d8832011-03-22 04:00:09 +0000708 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000709 if (SendPacketAndWaitForResponse("qC", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710 PacketResult::Success) {
711 if (response.GetChar() == 'Q') {
712 if (response.GetChar() == 'C') {
713 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
714 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
715 m_curr_pid_is_valid = eLazyBoolYes;
716 return m_curr_pid;
717 }
Greg Clayton576d8832011-03-22 04:00:09 +0000718 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719 }
Greg Clayton576d8832011-03-22 04:00:09 +0000720 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721
722 // If we don't get a response for $qC, check if $qfThreadID gives us a
723 // result.
724 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
725 std::vector<lldb::tid_t> thread_ids;
726 bool sequence_mutex_unavailable;
727 size_t size;
728 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
729 if (size && sequence_mutex_unavailable == false) {
730 m_curr_pid = thread_ids.front();
731 m_curr_pid_is_valid = eLazyBoolYes;
732 return m_curr_pid;
733 }
Greg Clayton576d8832011-03-22 04:00:09 +0000734 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000735 }
736
737 return LLDB_INVALID_PROCESS_ID;
Greg Clayton576d8832011-03-22 04:00:09 +0000738}
739
Kate Stoneb9c1b512016-09-06 20:57:50 +0000740bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
741 error_str.clear();
742 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000743 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
744 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000745 if (response.IsOKResponse())
746 return true;
747 if (response.GetChar() == 'E') {
748 // A string the describes what failed when launching...
749 error_str = response.GetStringRef().substr(1);
750 } else {
751 error_str.assign("unknown error occurred launching process");
Greg Claytonfbb76342013-11-20 21:07:01 +0000752 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 } else {
754 error_str.assign("timed out waiting for app to launch");
755 }
756 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000757}
758
Kate Stoneb9c1b512016-09-06 20:57:50 +0000759int GDBRemoteCommunicationClient::SendArgumentsPacket(
760 const ProcessLaunchInfo &launch_info) {
761 // Since we don't get the send argv0 separate from the executable path, we
762 // need to
763 // make sure to use the actual executable path found in the launch_info...
764 std::vector<const char *> argv;
765 FileSpec exe_file = launch_info.GetExecutableFile();
766 std::string exe_path;
767 const char *arg = NULL;
768 const Args &launch_args = launch_info.GetArguments();
769 if (exe_file)
770 exe_path = exe_file.GetPath(false);
771 else {
772 arg = launch_args.GetArgumentAtIndex(0);
773 if (arg)
774 exe_path = arg;
775 }
776 if (!exe_path.empty()) {
777 argv.push_back(exe_path.c_str());
778 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL;
779 ++i) {
780 if (arg)
781 argv.push_back(arg);
Greg Clayton576d8832011-03-22 04:00:09 +0000782 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 }
784 if (!argv.empty()) {
Vince Harrone0be4252015-02-06 18:32:57 +0000785 StreamString packet;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786 packet.PutChar('A');
787 for (size_t i = 0, n = argv.size(); i < n; ++i) {
788 arg = argv[i];
789 const int arg_len = strlen(arg);
790 if (i > 0)
791 packet.PutChar(',');
792 packet.Printf("%i,%i,", arg_len * 2, (int)i);
793 packet.PutBytesAsRawHex8(arg, arg_len);
794 }
795
Vince Harrone0be4252015-02-06 18:32:57 +0000796 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000797 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
798 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 if (response.IsOKResponse())
Vince Harrone0be4252015-02-06 18:32:57 +0000800 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801 uint8_t error = response.GetError();
802 if (error)
Johnny Chen64637202012-05-23 21:09:52 +0000803 return error;
804 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000805 }
806 return -1;
807}
Johnny Chen64637202012-05-23 21:09:52 +0000808
Kate Stoneb9c1b512016-09-06 20:57:50 +0000809int GDBRemoteCommunicationClient::SendEnvironmentPacket(
810 char const *name_equal_value) {
811 if (name_equal_value && name_equal_value[0]) {
812 StreamString packet;
813 bool send_hex_encoding = false;
814 for (const char *p = name_equal_value;
815 *p != '\0' && send_hex_encoding == false; ++p) {
816 if (isprint(*p)) {
817 switch (*p) {
818 case '$':
819 case '#':
820 case '*':
821 case '}':
822 send_hex_encoding = true;
823 break;
824 default:
825 break;
Johnny Chen64637202012-05-23 21:09:52 +0000826 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 } else {
828 // We have non printable characters, lets hex encode this...
829 send_hex_encoding = true;
830 }
Johnny Chen64637202012-05-23 21:09:52 +0000831 }
832
Greg Claytonfbb76342013-11-20 21:07:01 +0000833 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 if (send_hex_encoding) {
835 if (m_supports_QEnvironmentHexEncoded) {
836 packet.PutCString("QEnvironmentHexEncoded:");
837 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000838 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
839 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000840 if (response.IsOKResponse())
841 return 0;
842 uint8_t error = response.GetError();
843 if (error)
844 return error;
845 if (response.IsUnsupportedResponse())
846 m_supports_QEnvironmentHexEncoded = false;
847 }
848 }
849
850 } else if (m_supports_QEnvironment) {
851 packet.Printf("QEnvironment:%s", name_equal_value);
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000852 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
853 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854 if (response.IsOKResponse())
855 return 0;
856 uint8_t error = response.GetError();
857 if (error)
858 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +0000859 if (response.IsUnsupportedResponse())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860 m_supports_QEnvironment = false;
861 }
Greg Claytonfbb76342013-11-20 21:07:01 +0000862 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000863 }
864 return -1;
Greg Claytonfbb76342013-11-20 21:07:01 +0000865}
866
Kate Stoneb9c1b512016-09-06 20:57:50 +0000867int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
868 if (arch && arch[0]) {
869 StreamString packet;
870 packet.Printf("QLaunchArch:%s", arch);
871 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000872 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
873 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874 if (response.IsOKResponse())
875 return 0;
876 uint8_t error = response.GetError();
877 if (error)
878 return error;
879 }
880 }
881 return -1;
882}
Chaoren Lind3173f32015-05-29 19:52:29 +0000883
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
885 char const *data, bool *was_supported) {
886 if (data && *data != '\0') {
887 StreamString packet;
888 packet.Printf("QSetProcessEvent:%s", data);
889 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000890 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
891 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892 if (response.IsOKResponse()) {
893 if (was_supported)
894 *was_supported = true;
895 return 0;
896 } else if (response.IsUnsupportedResponse()) {
897 if (was_supported)
898 *was_supported = false;
899 return -1;
900 } else {
901 uint8_t error = response.GetError();
902 if (was_supported)
903 *was_supported = true;
904 if (error)
905 return error;
906 }
907 }
908 }
909 return -1;
910}
911
912bool GDBRemoteCommunicationClient::GetOSVersion(uint32_t &major,
913 uint32_t &minor,
914 uint32_t &update) {
915 if (GetHostInfo()) {
916 if (m_os_version_major != UINT32_MAX) {
917 major = m_os_version_major;
918 minor = m_os_version_minor;
919 update = m_os_version_update;
920 return true;
921 }
922 }
923 return false;
924}
925
926bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
927 if (GetHostInfo()) {
928 if (!m_os_build.empty()) {
929 s = m_os_build;
930 return true;
931 }
932 }
933 s.clear();
934 return false;
935}
936
937bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
938 if (GetHostInfo()) {
939 if (!m_os_kernel.empty()) {
940 s = m_os_kernel;
941 return true;
942 }
943 }
944 s.clear();
945 return false;
946}
947
948bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
949 if (GetHostInfo()) {
950 if (!m_hostname.empty()) {
951 s = m_hostname;
952 return true;
953 }
954 }
955 s.clear();
956 return false;
957}
958
959ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
960 if (GetHostInfo())
961 return m_host_arch;
962 return ArchSpec();
963}
964
965const lldb_private::ArchSpec &
966GDBRemoteCommunicationClient::GetProcessArchitecture() {
967 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
968 GetCurrentProcessInfo();
969 return m_process_arch;
970}
971
972bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
973 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
974 m_gdb_server_name.clear();
975 m_gdb_server_version = 0;
976 m_qGDBServerVersion_is_valid = eLazyBoolNo;
977
978 StringExtractorGDBRemote response;
979 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
980 PacketResult::Success) {
981 if (response.IsNormalResponse()) {
982 llvm::StringRef name, value;
983 bool success = false;
984 while (response.GetNameColonValue(name, value)) {
985 if (name.equals("name")) {
986 success = true;
987 m_gdb_server_name = value;
988 } else if (name.equals("version")) {
989 llvm::StringRef major, minor;
990 std::tie(major, minor) = value.split('.');
991 if (!major.getAsInteger(0, m_gdb_server_version))
992 success = true;
993 }
Greg Clayton576d8832011-03-22 04:00:09 +0000994 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995 if (success)
996 m_qGDBServerVersion_is_valid = eLazyBoolYes;
997 }
Greg Clayton576d8832011-03-22 04:00:09 +0000998 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 }
1000 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001001}
1002
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003void GDBRemoteCommunicationClient::MaybeEnableCompression(
1004 std::vector<std::string> supported_compressions) {
1005 CompressionType avail_type = CompressionType::None;
1006 std::string avail_name;
1007
1008#if defined(HAVE_LIBCOMPRESSION)
1009 // libcompression is weak linked so test if compression_decode_buffer() is
1010 // available
1011 if (compression_decode_buffer != NULL &&
1012 avail_type == CompressionType::None) {
1013 for (auto compression : supported_compressions) {
1014 if (compression == "lzfse") {
1015 avail_type = CompressionType::LZFSE;
1016 avail_name = compression;
1017 break;
1018 }
1019 }
1020 }
1021#endif
1022
1023#if defined(HAVE_LIBCOMPRESSION)
1024 // libcompression is weak linked so test if compression_decode_buffer() is
1025 // available
1026 if (compression_decode_buffer != NULL &&
1027 avail_type == CompressionType::None) {
1028 for (auto compression : supported_compressions) {
1029 if (compression == "zlib-deflate") {
1030 avail_type = CompressionType::ZlibDeflate;
1031 avail_name = compression;
1032 break;
1033 }
1034 }
1035 }
1036#endif
1037
1038#if defined(HAVE_LIBZ)
1039 if (avail_type == CompressionType::None) {
1040 for (auto compression : supported_compressions) {
1041 if (compression == "zlib-deflate") {
1042 avail_type = CompressionType::ZlibDeflate;
1043 avail_name = compression;
1044 break;
1045 }
1046 }
1047 }
1048#endif
1049
1050#if defined(HAVE_LIBCOMPRESSION)
1051 // libcompression is weak linked so test if compression_decode_buffer() is
1052 // available
1053 if (compression_decode_buffer != NULL &&
1054 avail_type == CompressionType::None) {
1055 for (auto compression : supported_compressions) {
1056 if (compression == "lz4") {
1057 avail_type = CompressionType::LZ4;
1058 avail_name = compression;
1059 break;
1060 }
1061 }
1062 }
1063#endif
1064
1065#if defined(HAVE_LIBCOMPRESSION)
1066 // libcompression is weak linked so test if compression_decode_buffer() is
1067 // available
1068 if (compression_decode_buffer != NULL &&
1069 avail_type == CompressionType::None) {
1070 for (auto compression : supported_compressions) {
1071 if (compression == "lzma") {
1072 avail_type = CompressionType::LZMA;
1073 avail_name = compression;
1074 break;
1075 }
1076 }
1077 }
1078#endif
1079
1080 if (avail_type != CompressionType::None) {
Greg Clayton576d8832011-03-22 04:00:09 +00001081 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082 std::string packet = "QEnableCompression:type:" + avail_name + ";";
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001083 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 PacketResult::Success)
1085 return;
1086
1087 if (response.IsOKResponse()) {
1088 m_compression_type = avail_type;
Greg Clayton576d8832011-03-22 04:00:09 +00001089 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001090 }
Greg Clayton576d8832011-03-22 04:00:09 +00001091}
Greg Clayton32e0a752011-03-30 18:16:51 +00001092
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1094 if (GetGDBServerVersion()) {
1095 if (!m_gdb_server_name.empty())
1096 return m_gdb_server_name.c_str();
1097 }
1098 return NULL;
1099}
1100
1101uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1102 if (GetGDBServerVersion())
1103 return m_gdb_server_version;
1104 return 0;
1105}
1106
1107bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1108 StringExtractorGDBRemote response;
1109 if (SendPacketAndWaitForResponse("qC", response, false) !=
1110 PacketResult::Success)
1111 return false;
1112
1113 if (!response.IsNormalResponse())
1114 return false;
1115
1116 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1117 tid = response.GetHexMaxU32(true, -1);
1118
1119 return true;
1120}
1121
1122bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1123 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1124
1125 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1126 m_qHostInfo_is_valid = eLazyBoolNo;
Jim Ingham106d0282014-06-25 02:32:56 +00001127 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1129 PacketResult::Success) {
1130 if (response.IsNormalResponse()) {
Zachary Turner54695a32016-08-29 19:58:14 +00001131 llvm::StringRef name;
1132 llvm::StringRef value;
Jason Molenda89c37492014-01-27 22:23:20 +00001133 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1134 uint32_t sub = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001135 std::string arch_name;
1136 std::string os_name;
1137 std::string vendor_name;
1138 std::string triple;
1139 std::string distribution_id;
1140 uint32_t pointer_byte_size = 0;
1141 ByteOrder byte_order = eByteOrderInvalid;
1142 uint32_t num_keys_decoded = 0;
1143 while (response.GetNameColonValue(name, value)) {
1144 if (name.equals("cputype")) {
1145 // exception type in big endian hex
1146 if (!value.getAsInteger(0, cpu))
1147 ++num_keys_decoded;
1148 } else if (name.equals("cpusubtype")) {
1149 // exception count in big endian hex
1150 if (!value.getAsInteger(0, sub))
1151 ++num_keys_decoded;
1152 } else if (name.equals("arch")) {
1153 arch_name = value;
1154 ++num_keys_decoded;
1155 } else if (name.equals("triple")) {
1156 StringExtractor extractor(value);
1157 extractor.GetHexByteString(triple);
1158 ++num_keys_decoded;
1159 } else if (name.equals("distribution_id")) {
1160 StringExtractor extractor(value);
1161 extractor.GetHexByteString(distribution_id);
1162 ++num_keys_decoded;
1163 } else if (name.equals("os_build")) {
1164 StringExtractor extractor(value);
1165 extractor.GetHexByteString(m_os_build);
1166 ++num_keys_decoded;
1167 } else if (name.equals("hostname")) {
1168 StringExtractor extractor(value);
1169 extractor.GetHexByteString(m_hostname);
1170 ++num_keys_decoded;
1171 } else if (name.equals("os_kernel")) {
1172 StringExtractor extractor(value);
1173 extractor.GetHexByteString(m_os_kernel);
1174 ++num_keys_decoded;
1175 } else if (name.equals("ostype")) {
1176 os_name = value;
1177 ++num_keys_decoded;
1178 } else if (name.equals("vendor")) {
1179 vendor_name = value;
1180 ++num_keys_decoded;
1181 } else if (name.equals("endian")) {
1182 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1183 .Case("little", eByteOrderLittle)
1184 .Case("big", eByteOrderBig)
1185 .Case("pdp", eByteOrderPDP)
1186 .Default(eByteOrderInvalid);
1187 if (byte_order != eByteOrderInvalid)
1188 ++num_keys_decoded;
1189 } else if (name.equals("ptrsize")) {
1190 if (!value.getAsInteger(0, pointer_byte_size))
1191 ++num_keys_decoded;
1192 } else if (name.equals("os_version") ||
1193 name.equals(
1194 "version")) // Older debugserver binaries used the
1195 // "version" key instead of
1196 // "os_version"...
1197 {
Zachary Turner6fa7681b2016-09-17 02:00:02 +00001198 Args::StringToVersion(value, m_os_version_major, m_os_version_minor,
1199 m_os_version_update);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001200 if (m_os_version_major != UINT32_MAX)
1201 ++num_keys_decoded;
1202 } else if (name.equals("watchpoint_exceptions_received")) {
1203 m_watchpoints_trigger_after_instruction =
1204 llvm::StringSwitch<LazyBool>(value)
1205 .Case("before", eLazyBoolNo)
1206 .Case("after", eLazyBoolYes)
1207 .Default(eLazyBoolCalculate);
1208 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1209 ++num_keys_decoded;
1210 } else if (name.equals("default_packet_timeout")) {
Pavel Labath3aa04912016-10-31 17:19:42 +00001211 uint32_t timeout_seconds;
1212 if (!value.getAsInteger(0, timeout_seconds)) {
Pavel Labath1eff73c2016-11-24 10:54:49 +00001213 m_default_packet_timeout = seconds(timeout_seconds);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214 SetPacketTimeout(m_default_packet_timeout);
1215 ++num_keys_decoded;
Greg Clayton32e0a752011-03-30 18:16:51 +00001216 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 }
Jason Molenda89c37492014-01-27 22:23:20 +00001218 }
1219
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 if (num_keys_decoded > 0)
1221 m_qHostInfo_is_valid = eLazyBoolYes;
1222
1223 if (triple.empty()) {
1224 if (arch_name.empty()) {
1225 if (cpu != LLDB_INVALID_CPUTYPE) {
1226 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1227 if (pointer_byte_size) {
1228 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1229 }
1230 if (byte_order != eByteOrderInvalid) {
1231 assert(byte_order == m_host_arch.GetByteOrder());
1232 }
1233
1234 if (!vendor_name.empty())
1235 m_host_arch.GetTriple().setVendorName(
1236 llvm::StringRef(vendor_name));
1237 if (!os_name.empty())
1238 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Jason Molenda89c37492014-01-27 22:23:20 +00001239 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001240 } else {
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001241 std::string triple;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001242 triple += arch_name;
1243 if (!vendor_name.empty() || !os_name.empty()) {
1244 triple += '-';
1245 if (vendor_name.empty())
1246 triple += "unknown";
1247 else
1248 triple += vendor_name;
1249 triple += '-';
1250 if (os_name.empty())
1251 triple += "unknown";
1252 else
1253 triple += os_name;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001254 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 m_host_arch.SetTriple(triple.c_str());
Todd Fialac540dd02014-08-26 18:21:02 +00001256
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257 llvm::Triple &host_triple = m_host_arch.GetTriple();
1258 if (host_triple.getVendor() == llvm::Triple::Apple &&
1259 host_triple.getOS() == llvm::Triple::Darwin) {
1260 switch (m_host_arch.GetMachine()) {
1261 case llvm::Triple::aarch64:
1262 case llvm::Triple::arm:
1263 case llvm::Triple::thumb:
1264 host_triple.setOS(llvm::Triple::IOS);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001265 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 default:
1267 host_triple.setOS(llvm::Triple::MacOSX);
1268 break;
1269 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001270 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001271 if (pointer_byte_size) {
1272 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1273 }
1274 if (byte_order != eByteOrderInvalid) {
1275 assert(byte_order == m_host_arch.GetByteOrder());
1276 }
1277 }
1278 } else {
1279 m_host_arch.SetTriple(triple.c_str());
1280 if (pointer_byte_size) {
1281 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1282 }
1283 if (byte_order != eByteOrderInvalid) {
1284 assert(byte_order == m_host_arch.GetByteOrder());
1285 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001286
Kate Stoneb9c1b512016-09-06 20:57:50 +00001287 if (log)
1288 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1289 "architecture as %s, triple as %s from triple text %s",
1290 __FUNCTION__, m_host_arch.GetArchitectureName()
1291 ? m_host_arch.GetArchitectureName()
1292 : "<null-arch-name>",
1293 m_host_arch.GetTriple().getTriple().c_str(),
1294 triple.c_str());
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001295 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296 if (!distribution_id.empty())
1297 m_host_arch.SetDistributionId(distribution_id.c_str());
1298 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001299 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 }
1301 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Claytonadc00cb2011-05-20 23:38:13 +00001302}
Greg Clayton37a0a242012-04-11 00:24:49 +00001303
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304int GDBRemoteCommunicationClient::SendAttach(
1305 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1306 if (pid != LLDB_INVALID_PROCESS_ID) {
1307 char packet[64];
1308 const int packet_len =
1309 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001310 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001311 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001312 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001313 PacketResult::Success) {
1314 if (response.IsErrorResponse())
1315 return response.GetError();
1316 return 0;
1317 }
1318 }
1319 return -1;
1320}
1321
1322int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1323 size_t data_len) {
1324 StreamString packet;
1325 packet.PutCString("I");
1326 packet.PutBytesAsRawHex8(data, data_len);
1327 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001328 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1329 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330 return 0;
1331 }
1332 return response.GetError();
1333}
1334
1335const lldb_private::ArchSpec &
1336GDBRemoteCommunicationClient::GetHostArchitecture() {
1337 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1338 GetHostInfo();
1339 return m_host_arch;
1340}
1341
Pavel Labath1eff73c2016-11-24 10:54:49 +00001342seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001343 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1344 GetHostInfo();
1345 return m_default_packet_timeout;
1346}
1347
1348addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1349 uint32_t permissions) {
1350 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1351 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1352 char packet[64];
1353 const int packet_len = ::snprintf(
1354 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1355 permissions & lldb::ePermissionsReadable ? "r" : "",
1356 permissions & lldb::ePermissionsWritable ? "w" : "",
1357 permissions & lldb::ePermissionsExecutable ? "x" : "");
1358 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001359 UNUSED_IF_ASSERT_DISABLED(packet_len);
Pavel Labath83082a02016-08-18 14:33:55 +00001360 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001361 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362 PacketResult::Success) {
1363 if (response.IsUnsupportedResponse())
1364 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1365 else if (!response.IsErrorResponse())
1366 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1367 } else {
1368 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1369 }
1370 }
1371 return LLDB_INVALID_ADDRESS;
1372}
1373
1374bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1375 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1376 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1377 char packet[64];
1378 const int packet_len =
1379 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1380 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001381 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001383 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001384 PacketResult::Success) {
1385 if (response.IsUnsupportedResponse())
1386 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1387 else if (response.IsOKResponse())
1388 return true;
1389 } else {
1390 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1391 }
1392 }
1393 return false;
1394}
1395
Zachary Turner97206d52017-05-12 04:51:55 +00001396Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1397 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001398
1399 if (keep_stopped) {
1400 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1401 char packet[64];
1402 const int packet_len =
1403 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1404 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001405 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001407 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001408 PacketResult::Success &&
1409 response.IsOKResponse()) {
1410 m_supports_detach_stay_stopped = eLazyBoolYes;
1411 } else {
1412 m_supports_detach_stay_stopped = eLazyBoolNo;
1413 }
1414 }
1415
1416 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1417 error.SetErrorString("Stays stopped not supported by this target.");
1418 return error;
1419 } else {
1420 StringExtractorGDBRemote response;
1421 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001422 SendPacketAndWaitForResponse("D1", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001423 if (packet_result != PacketResult::Success)
1424 error.SetErrorString("Sending extended disconnect packet failed.");
1425 }
1426 } else {
1427 StringExtractorGDBRemote response;
1428 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001429 SendPacketAndWaitForResponse("D", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001430 if (packet_result != PacketResult::Success)
1431 error.SetErrorString("Sending disconnect packet failed.");
1432 }
1433 return error;
1434}
1435
Zachary Turner97206d52017-05-12 04:51:55 +00001436Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001438 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001439 region_info.Clear();
1440
1441 if (m_supports_memory_region_info != eLazyBoolNo) {
1442 m_supports_memory_region_info = eLazyBoolYes;
1443 char packet[64];
1444 const int packet_len = ::snprintf(
1445 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1446 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001447 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001448 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001449 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001450 PacketResult::Success) {
1451 llvm::StringRef name;
1452 llvm::StringRef value;
1453 addr_t addr_value = LLDB_INVALID_ADDRESS;
1454 bool success = true;
1455 bool saw_permissions = false;
1456 while (success && response.GetNameColonValue(name, value)) {
1457 if (name.equals("start")) {
1458 if (!value.getAsInteger(16, addr_value))
1459 region_info.GetRange().SetRangeBase(addr_value);
1460 } else if (name.equals("size")) {
1461 if (!value.getAsInteger(16, addr_value))
1462 region_info.GetRange().SetByteSize(addr_value);
1463 } else if (name.equals("permissions") &&
1464 region_info.GetRange().IsValid()) {
1465 saw_permissions = true;
1466 if (region_info.GetRange().Contains(addr)) {
1467 if (value.find('r') != llvm::StringRef::npos)
1468 region_info.SetReadable(MemoryRegionInfo::eYes);
1469 else
1470 region_info.SetReadable(MemoryRegionInfo::eNo);
1471
1472 if (value.find('w') != llvm::StringRef::npos)
1473 region_info.SetWritable(MemoryRegionInfo::eYes);
1474 else
1475 region_info.SetWritable(MemoryRegionInfo::eNo);
1476
1477 if (value.find('x') != llvm::StringRef::npos)
1478 region_info.SetExecutable(MemoryRegionInfo::eYes);
1479 else
1480 region_info.SetExecutable(MemoryRegionInfo::eNo);
1481
1482 region_info.SetMapped(MemoryRegionInfo::eYes);
1483 } else {
1484 // The reported region does not contain this address -- we're
1485 // looking at an unmapped page
1486 region_info.SetReadable(MemoryRegionInfo::eNo);
1487 region_info.SetWritable(MemoryRegionInfo::eNo);
1488 region_info.SetExecutable(MemoryRegionInfo::eNo);
1489 region_info.SetMapped(MemoryRegionInfo::eNo);
1490 }
1491 } else if (name.equals("name")) {
1492 StringExtractorGDBRemote name_extractor(value);
1493 std::string name;
1494 name_extractor.GetHexByteString(name);
1495 region_info.SetName(name.c_str());
1496 } else if (name.equals("error")) {
1497 StringExtractorGDBRemote error_extractor(value);
1498 std::string error_string;
1499 // Now convert the HEX bytes into a string value
1500 error_extractor.GetHexByteString(error_string);
1501 error.SetErrorString(error_string.c_str());
1502 }
1503 }
1504
Stephane Sezer48d14272017-03-31 18:00:48 +00001505 if (region_info.GetRange().IsValid()) {
1506 // We got a valid address range back but no permissions -- which means
1507 // this is an unmapped page
1508 if (!saw_permissions) {
1509 region_info.SetReadable(MemoryRegionInfo::eNo);
1510 region_info.SetWritable(MemoryRegionInfo::eNo);
1511 region_info.SetExecutable(MemoryRegionInfo::eNo);
1512 region_info.SetMapped(MemoryRegionInfo::eNo);
1513 }
1514 } else {
1515 // We got an invalid address range back
1516 error.SetErrorString("Server returned invalid range");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001517 }
1518 } else {
1519 m_supports_memory_region_info = eLazyBoolNo;
1520 }
1521 }
1522
1523 if (m_supports_memory_region_info == eLazyBoolNo) {
1524 error.SetErrorString("qMemoryRegionInfo is not supported");
1525 }
1526 if (error.Fail())
1527 region_info.Clear();
1528 return error;
1529}
1530
Zachary Turner97206d52017-05-12 04:51:55 +00001531Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1532 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001533
1534 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1535 num = m_num_supported_hardware_watchpoints;
1536 return error;
1537 }
1538
1539 // Set num to 0 first.
1540 num = 0;
1541 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1542 char packet[64];
1543 const int packet_len =
1544 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1545 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001546 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001547 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001548 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001549 PacketResult::Success) {
1550 m_supports_watchpoint_support_info = eLazyBoolYes;
1551 llvm::StringRef name;
1552 llvm::StringRef value;
1553 while (response.GetNameColonValue(name, value)) {
1554 if (name.equals("num")) {
1555 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1556 num = m_num_supported_hardware_watchpoints;
1557 }
1558 }
1559 } else {
1560 m_supports_watchpoint_support_info = eLazyBoolNo;
1561 }
1562 }
1563
1564 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1565 error.SetErrorString("qWatchpointSupportInfo is not supported");
1566 }
1567 return error;
1568}
1569
Zachary Turner97206d52017-05-12 04:51:55 +00001570lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001571 uint32_t &num, bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001572 Status error(GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001573 if (error.Success())
1574 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1575 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001576}
1577
Zachary Turner97206d52017-05-12 04:51:55 +00001578lldb_private::Status
Kate Stoneb9c1b512016-09-06 20:57:50 +00001579GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1580 bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001581 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001582 llvm::Triple::ArchType atype = arch.GetMachine();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001583
Kate Stoneb9c1b512016-09-06 20:57:50 +00001584 // we assume watchpoints will happen after running the relevant opcode
1585 // and we only want to override this behavior if we have explicitly
1586 // received a qHostInfo telling us otherwise
1587 if (m_qHostInfo_is_valid != eLazyBoolYes) {
1588 // On targets like MIPS, watchpoint exceptions are always generated
1589 // before the instruction is executed. The connected target may not
1590 // support qHostInfo or qWatchpointSupportInfo packets.
1591 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1592 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
1593 after = false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001594 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001595 after = true;
1596 } else {
1597 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
1598 // if it is not calculated before.
1599 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1600 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1601 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
1602 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1603
1604 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1605 }
1606 return error;
1607}
1608
1609int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1610 if (file_spec) {
1611 std::string path{file_spec.GetPath(false)};
1612 StreamString packet;
1613 packet.PutCString("QSetSTDIN:");
1614 packet.PutCStringAsRawHex8(path.c_str());
1615
1616 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001617 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1618 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001619 if (response.IsOKResponse())
1620 return 0;
1621 uint8_t error = response.GetError();
1622 if (error)
1623 return error;
1624 }
1625 }
1626 return -1;
1627}
1628
1629int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1630 if (file_spec) {
1631 std::string path{file_spec.GetPath(false)};
1632 StreamString packet;
1633 packet.PutCString("QSetSTDOUT:");
1634 packet.PutCStringAsRawHex8(path.c_str());
1635
1636 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001637 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1638 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001639 if (response.IsOKResponse())
1640 return 0;
1641 uint8_t error = response.GetError();
1642 if (error)
1643 return error;
1644 }
1645 }
1646 return -1;
1647}
1648
1649int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1650 if (file_spec) {
1651 std::string path{file_spec.GetPath(false)};
1652 StreamString packet;
1653 packet.PutCString("QSetSTDERR:");
1654 packet.PutCStringAsRawHex8(path.c_str());
1655
1656 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001657 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1658 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001659 if (response.IsOKResponse())
1660 return 0;
1661 uint8_t error = response.GetError();
1662 if (error)
1663 return error;
1664 }
1665 }
1666 return -1;
1667}
1668
1669bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1670 StringExtractorGDBRemote response;
1671 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1672 PacketResult::Success) {
1673 if (response.IsUnsupportedResponse())
1674 return false;
1675 if (response.IsErrorResponse())
1676 return false;
1677 std::string cwd;
1678 response.GetHexByteString(cwd);
Zachary Turner8c6b5462017-03-06 23:42:44 +00001679 working_dir.SetFile(cwd, false, GetHostArchitecture().GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001680 return !cwd.empty();
1681 }
1682 return false;
1683}
1684
1685int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1686 if (working_dir) {
1687 std::string path{working_dir.GetPath(false)};
1688 StreamString packet;
1689 packet.PutCString("QSetWorkingDir:");
1690 packet.PutCStringAsRawHex8(path.c_str());
1691
1692 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001693 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1694 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001695 if (response.IsOKResponse())
1696 return 0;
1697 uint8_t error = response.GetError();
1698 if (error)
1699 return error;
1700 }
1701 }
1702 return -1;
1703}
1704
1705int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1706 char packet[32];
1707 const int packet_len =
1708 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1709 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001710 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001711 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001712 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001713 PacketResult::Success) {
1714 if (response.IsOKResponse())
1715 return 0;
1716 uint8_t error = response.GetError();
1717 if (error)
1718 return error;
1719 }
1720 return -1;
1721}
1722
1723int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1724 char packet[32];
1725 const int packet_len = ::snprintf(packet, sizeof(packet),
1726 "QSetDetachOnError:%i", enable ? 1 : 0);
1727 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001728 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001729 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001730 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001731 PacketResult::Success) {
1732 if (response.IsOKResponse())
1733 return 0;
1734 uint8_t error = response.GetError();
1735 if (error)
1736 return error;
1737 }
1738 return -1;
1739}
1740
1741bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1742 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1743 if (response.IsNormalResponse()) {
1744 llvm::StringRef name;
1745 llvm::StringRef value;
1746 StringExtractor extractor;
1747
1748 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1749 uint32_t sub = 0;
1750 std::string vendor;
1751 std::string os_type;
1752
1753 while (response.GetNameColonValue(name, value)) {
1754 if (name.equals("pid")) {
1755 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1756 value.getAsInteger(0, pid);
1757 process_info.SetProcessID(pid);
1758 } else if (name.equals("ppid")) {
1759 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1760 value.getAsInteger(0, pid);
1761 process_info.SetParentProcessID(pid);
1762 } else if (name.equals("uid")) {
1763 uint32_t uid = UINT32_MAX;
1764 value.getAsInteger(0, uid);
1765 process_info.SetUserID(uid);
1766 } else if (name.equals("euid")) {
1767 uint32_t uid = UINT32_MAX;
1768 value.getAsInteger(0, uid);
1769 process_info.SetEffectiveGroupID(uid);
1770 } else if (name.equals("gid")) {
1771 uint32_t gid = UINT32_MAX;
1772 value.getAsInteger(0, gid);
1773 process_info.SetGroupID(gid);
1774 } else if (name.equals("egid")) {
1775 uint32_t gid = UINT32_MAX;
1776 value.getAsInteger(0, gid);
1777 process_info.SetEffectiveGroupID(gid);
1778 } else if (name.equals("triple")) {
1779 StringExtractor extractor(value);
1780 std::string triple;
1781 extractor.GetHexByteString(triple);
1782 process_info.GetArchitecture().SetTriple(triple.c_str());
1783 } else if (name.equals("name")) {
1784 StringExtractor extractor(value);
1785 // The process name from ASCII hex bytes since we can't
1786 // control the characters in a process name
1787 std::string name;
1788 extractor.GetHexByteString(name);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001789 process_info.GetExecutableFile().SetFile(name, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001790 } else if (name.equals("cputype")) {
1791 value.getAsInteger(0, cpu);
1792 } else if (name.equals("cpusubtype")) {
1793 value.getAsInteger(0, sub);
1794 } else if (name.equals("vendor")) {
1795 vendor = value;
1796 } else if (name.equals("ostype")) {
1797 os_type = value;
1798 }
1799 }
1800
1801 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1802 if (vendor == "apple") {
1803 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1804 sub);
1805 process_info.GetArchitecture().GetTriple().setVendorName(
1806 llvm::StringRef(vendor));
1807 process_info.GetArchitecture().GetTriple().setOSName(
1808 llvm::StringRef(os_type));
1809 }
1810 }
1811
1812 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1813 return true;
1814 }
1815 return false;
1816}
1817
1818bool GDBRemoteCommunicationClient::GetProcessInfo(
1819 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1820 process_info.Clear();
1821
1822 if (m_supports_qProcessInfoPID) {
1823 char packet[32];
1824 const int packet_len =
1825 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1826 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001827 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001828 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001829 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001830 PacketResult::Success) {
1831 return DecodeProcessInfoResponse(response, process_info);
1832 } else {
1833 m_supports_qProcessInfoPID = false;
1834 return false;
1835 }
1836 }
1837 return false;
1838}
1839
1840bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1841 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1842 GDBR_LOG_PACKETS));
1843
1844 if (allow_lazy) {
1845 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1846 return true;
1847 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1848 return false;
1849 }
1850
1851 GetHostInfo();
1852
1853 StringExtractorGDBRemote response;
1854 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1855 PacketResult::Success) {
1856 if (response.IsNormalResponse()) {
1857 llvm::StringRef name;
1858 llvm::StringRef value;
1859 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1860 uint32_t sub = 0;
1861 std::string arch_name;
1862 std::string os_name;
1863 std::string vendor_name;
1864 std::string triple;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001865 std::string elf_abi;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001866 uint32_t pointer_byte_size = 0;
1867 StringExtractor extractor;
1868 ByteOrder byte_order = eByteOrderInvalid;
1869 uint32_t num_keys_decoded = 0;
1870 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1871 while (response.GetNameColonValue(name, value)) {
1872 if (name.equals("cputype")) {
1873 if (!value.getAsInteger(16, cpu))
1874 ++num_keys_decoded;
1875 } else if (name.equals("cpusubtype")) {
1876 if (!value.getAsInteger(16, sub))
1877 ++num_keys_decoded;
1878 } else if (name.equals("triple")) {
1879 StringExtractor extractor(value);
1880 extractor.GetHexByteString(triple);
1881 ++num_keys_decoded;
1882 } else if (name.equals("ostype")) {
1883 os_name = value;
1884 ++num_keys_decoded;
1885 } else if (name.equals("vendor")) {
1886 vendor_name = value;
1887 ++num_keys_decoded;
1888 } else if (name.equals("endian")) {
1889 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1890 .Case("little", eByteOrderLittle)
1891 .Case("big", eByteOrderBig)
1892 .Case("pdp", eByteOrderPDP)
1893 .Default(eByteOrderInvalid);
1894 if (byte_order != eByteOrderInvalid)
1895 ++num_keys_decoded;
1896 } else if (name.equals("ptrsize")) {
1897 if (!value.getAsInteger(16, pointer_byte_size))
1898 ++num_keys_decoded;
1899 } else if (name.equals("pid")) {
1900 if (!value.getAsInteger(16, pid))
1901 ++num_keys_decoded;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001902 } else if (name.equals("elf_abi")) {
1903 elf_abi = value;
1904 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001905 }
1906 }
1907 if (num_keys_decoded > 0)
1908 m_qProcessInfo_is_valid = eLazyBoolYes;
1909 if (pid != LLDB_INVALID_PROCESS_ID) {
1910 m_curr_pid_is_valid = eLazyBoolYes;
1911 m_curr_pid = pid;
1912 }
1913
1914 // Set the ArchSpec from the triple if we have it.
1915 if (!triple.empty()) {
1916 m_process_arch.SetTriple(triple.c_str());
Nitesh Jain8999edf2016-10-12 10:21:09 +00001917 m_process_arch.SetFlags(elf_abi);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001918 if (pointer_byte_size) {
1919 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1920 }
1921 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
1922 !vendor_name.empty()) {
1923 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
1924
1925 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
Pavel Labath4f19fce22017-02-17 13:39:50 +00001926 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001927 switch (triple.getObjectFormat()) {
1928 case llvm::Triple::MachO:
1929 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1930 break;
1931 case llvm::Triple::ELF:
1932 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
1933 break;
1934 case llvm::Triple::COFF:
1935 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
1936 break;
Pavel Labath4f19fce22017-02-17 13:39:50 +00001937 case llvm::Triple::Wasm:
1938 if (log)
1939 log->Printf("error: not supported target architecture");
1940 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001941 case llvm::Triple::UnknownObjectFormat:
1942 if (log)
1943 log->Printf("error: failed to determine target architecture");
1944 return false;
1945 }
1946
1947 if (pointer_byte_size) {
1948 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1949 }
1950 if (byte_order != eByteOrderInvalid) {
1951 assert(byte_order == m_process_arch.GetByteOrder());
1952 }
1953 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1954 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1955 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1956 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1957 }
1958 return true;
1959 }
1960 } else {
1961 m_qProcessInfo_is_valid = eLazyBoolNo;
1962 }
1963
1964 return false;
1965}
1966
1967uint32_t GDBRemoteCommunicationClient::FindProcesses(
1968 const ProcessInstanceInfoMatch &match_info,
1969 ProcessInstanceInfoList &process_infos) {
1970 process_infos.Clear();
1971
1972 if (m_supports_qfProcessInfo) {
1973 StreamString packet;
1974 packet.PutCString("qfProcessInfo");
1975 if (!match_info.MatchAllProcesses()) {
1976 packet.PutChar(':');
1977 const char *name = match_info.GetProcessInfo().GetName();
1978 bool has_name_match = false;
1979 if (name && name[0]) {
1980 has_name_match = true;
Pavel Labathc4a33952017-02-20 11:35:33 +00001981 NameMatch name_match_type = match_info.GetNameMatchType();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001982 switch (name_match_type) {
Pavel Labathc4a33952017-02-20 11:35:33 +00001983 case NameMatch::Ignore:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001984 has_name_match = false;
1985 break;
1986
Pavel Labathc4a33952017-02-20 11:35:33 +00001987 case NameMatch::Equals:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001988 packet.PutCString("name_match:equals;");
1989 break;
1990
Pavel Labathc4a33952017-02-20 11:35:33 +00001991 case NameMatch::Contains:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001992 packet.PutCString("name_match:contains;");
1993 break;
1994
Pavel Labathc4a33952017-02-20 11:35:33 +00001995 case NameMatch::StartsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001996 packet.PutCString("name_match:starts_with;");
1997 break;
1998
Pavel Labathc4a33952017-02-20 11:35:33 +00001999 case NameMatch::EndsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002000 packet.PutCString("name_match:ends_with;");
2001 break;
2002
Pavel Labathc4a33952017-02-20 11:35:33 +00002003 case NameMatch::RegularExpression:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002004 packet.PutCString("name_match:regex;");
2005 break;
2006 }
2007 if (has_name_match) {
2008 packet.PutCString("name:");
2009 packet.PutBytesAsRawHex8(name, ::strlen(name));
2010 packet.PutChar(';');
2011 }
2012 }
2013
2014 if (match_info.GetProcessInfo().ProcessIDIsValid())
2015 packet.Printf("pid:%" PRIu64 ";",
2016 match_info.GetProcessInfo().GetProcessID());
2017 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2018 packet.Printf("parent_pid:%" PRIu64 ";",
2019 match_info.GetProcessInfo().GetParentProcessID());
2020 if (match_info.GetProcessInfo().UserIDIsValid())
2021 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2022 if (match_info.GetProcessInfo().GroupIDIsValid())
2023 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2024 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2025 packet.Printf("euid:%u;",
2026 match_info.GetProcessInfo().GetEffectiveUserID());
2027 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2028 packet.Printf("egid:%u;",
2029 match_info.GetProcessInfo().GetEffectiveGroupID());
2030 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2031 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2032 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2033 const ArchSpec &match_arch =
2034 match_info.GetProcessInfo().GetArchitecture();
2035 const llvm::Triple &triple = match_arch.GetTriple();
2036 packet.PutCString("triple:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002037 packet.PutCString(triple.getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002038 packet.PutChar(';');
2039 }
2040 }
2041 StringExtractorGDBRemote response;
2042 // Increase timeout as the first qfProcessInfo packet takes a long time
2043 // on Android. The value of 1min was arrived at empirically.
Pavel Labath1eff73c2016-11-24 10:54:49 +00002044 ScopedTimeout timeout(*this, minutes(1));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002045 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2046 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002047 do {
2048 ProcessInstanceInfo process_info;
2049 if (!DecodeProcessInfoResponse(response, process_info))
2050 break;
2051 process_infos.Append(process_info);
2052 response.GetStringRef().clear();
2053 response.SetFilePos(0);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002054 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2055 PacketResult::Success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002056 } else {
2057 m_supports_qfProcessInfo = false;
2058 return 0;
2059 }
2060 }
2061 return process_infos.GetSize();
2062}
2063
2064bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2065 std::string &name) {
2066 if (m_supports_qUserName) {
2067 char packet[32];
2068 const int packet_len =
2069 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2070 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002071 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002072 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002073 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002074 PacketResult::Success) {
2075 if (response.IsNormalResponse()) {
2076 // Make sure we parsed the right number of characters. The response is
2077 // the hex encoded user name and should make up the entire packet.
2078 // If there are any non-hex ASCII bytes, the length won't match below..
2079 if (response.GetHexByteString(name) * 2 ==
2080 response.GetStringRef().size())
2081 return true;
2082 }
2083 } else {
2084 m_supports_qUserName = false;
2085 return false;
2086 }
2087 }
2088 return false;
2089}
2090
2091bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2092 std::string &name) {
2093 if (m_supports_qGroupName) {
2094 char packet[32];
2095 const int packet_len =
2096 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2097 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002098 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002099 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002100 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002101 PacketResult::Success) {
2102 if (response.IsNormalResponse()) {
2103 // Make sure we parsed the right number of characters. The response is
2104 // the hex encoded group name and should make up the entire packet.
2105 // If there are any non-hex ASCII bytes, the length won't match below..
2106 if (response.GetHexByteString(name) * 2 ==
2107 response.GetStringRef().size())
2108 return true;
2109 }
2110 } else {
2111 m_supports_qGroupName = false;
2112 return false;
2113 }
2114 }
2115 return false;
2116}
2117
2118bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2119 // Form non-stop packet request
2120 char packet[32];
2121 const int packet_len =
2122 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2123 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002124 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002125
2126 StringExtractorGDBRemote response;
2127 // Send to target
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002128 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002129 PacketResult::Success)
2130 if (response.IsOKResponse())
2131 return true;
2132
2133 // Failed or not supported
2134 return false;
2135}
2136
2137static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2138 uint32_t recv_size) {
2139 packet.Clear();
2140 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2141 uint32_t bytes_left = send_size;
2142 while (bytes_left > 0) {
2143 if (bytes_left >= 26) {
2144 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2145 bytes_left -= 26;
2146 } else {
2147 packet.Printf("%*.*s;", bytes_left, bytes_left,
2148 "abcdefghijklmnopqrstuvwxyz");
2149 bytes_left = 0;
2150 }
2151 }
2152}
2153
Pavel Labath1eff73c2016-11-24 10:54:49 +00002154duration<float>
2155calculate_standard_deviation(const std::vector<duration<float>> &v) {
2156 using Dur = duration<float>;
Pavel Labath3aa04912016-10-31 17:19:42 +00002157 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2158 Dur mean = sum / v.size();
2159 float accum = 0;
2160 for (auto d : v) {
2161 float delta = (d - mean).count();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002162 accum += delta * delta;
Pavel Labath3aa04912016-10-31 17:19:42 +00002163 };
Kate Stoneb9c1b512016-09-06 20:57:50 +00002164
Pavel Labath3aa04912016-10-31 17:19:42 +00002165 return Dur(sqrtf(accum / (v.size() - 1)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002166}
2167
2168void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2169 uint32_t max_send,
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002170 uint32_t max_recv,
2171 uint64_t recv_amount,
2172 bool json, Stream &strm) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002173 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002174 if (SendSpeedTestPacket(0, 0)) {
2175 StreamString packet;
2176 if (json)
2177 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2178 "\"results\" : [",
2179 num_packets);
2180 else
2181 strm.Printf("Testing sending %u packets of various sizes:\n",
2182 num_packets);
2183 strm.Flush();
2184
2185 uint32_t result_idx = 0;
2186 uint32_t send_size;
Pavel Labath3aa04912016-10-31 17:19:42 +00002187 std::vector<duration<float>> packet_times;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002188
2189 for (send_size = 0; send_size <= max_send;
2190 send_size ? send_size *= 2 : send_size = 4) {
2191 for (uint32_t recv_size = 0; recv_size <= max_recv;
2192 recv_size ? recv_size *= 2 : recv_size = 4) {
2193 MakeSpeedTestPacket(packet, send_size, recv_size);
2194
2195 packet_times.clear();
2196 // Test how long it takes to send 'num_packets' packets
Pavel Labath3aa04912016-10-31 17:19:42 +00002197 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002198 for (i = 0; i < num_packets; ++i) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002199 const auto packet_start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002200 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002201 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Pavel Labath3aa04912016-10-31 17:19:42 +00002202 const auto packet_end_time = steady_clock::now();
2203 packet_times.push_back(packet_end_time - packet_start_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002204 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002205 const auto end_time = steady_clock::now();
2206 const auto total_time = end_time - start_time;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002207
2208 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002209 ((float)num_packets) / duration<float>(total_time).count();
2210 auto average_per_packet = total_time / num_packets;
2211 const duration<float> standard_deviation =
2212 calculate_standard_deviation(packet_times);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002213 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002214 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2215 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2216 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002217 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002218 total_time, standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002219 ++result_idx;
2220 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002221 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2222 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2223 "standard deviation of {5,10:ms+f6}\n",
2224 send_size, recv_size, duration<float>(total_time),
2225 packets_per_second, duration<float>(average_per_packet),
2226 standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002227 }
2228 strm.Flush();
2229 }
2230 }
2231
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002232 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002233 if (json)
2234 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2235 ": %" PRIu64 ",\n \"results\" : [",
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002236 recv_amount);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002237 else
2238 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2239 "packet sizes:\n",
2240 k_recv_amount_mb);
2241 strm.Flush();
2242 send_size = 0;
2243 result_idx = 0;
2244 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2245 MakeSpeedTestPacket(packet, send_size, recv_size);
2246
2247 // If we have a receive size, test how long it takes to receive 4MB of
2248 // data
2249 if (recv_size > 0) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002250 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002251 uint32_t bytes_read = 0;
2252 uint32_t packet_count = 0;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002253 while (bytes_read < recv_amount) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002254 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002255 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002256 bytes_read += recv_size;
2257 ++packet_count;
2258 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002259 const auto end_time = steady_clock::now();
2260 const auto total_time = end_time - start_time;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002261 float mb_second = ((float)recv_amount) /
Pavel Labath3aa04912016-10-31 17:19:42 +00002262 duration<float>(total_time).count() /
Kate Stoneb9c1b512016-09-06 20:57:50 +00002263 (1024.0 * 1024.0);
2264 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002265 ((float)packet_count) / duration<float>(total_time).count();
2266 const auto average_per_packet = total_time / packet_count;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002267
2268 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002269 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2270 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002271 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002272 total_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002273 ++result_idx;
2274 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002275 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2276 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2277 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002278 send_size, recv_size, packet_count, k_recv_amount_mb,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002279 duration<float>(total_time), mb_second,
2280 packets_per_second, duration<float>(average_per_packet));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002281 }
2282 strm.Flush();
2283 }
2284 }
2285 if (json)
2286 strm.Printf("\n ]\n }\n}\n");
2287 else
2288 strm.EOL();
2289 }
2290}
2291
2292bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2293 uint32_t recv_size) {
2294 StreamString packet;
2295 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2296 uint32_t bytes_left = send_size;
2297 while (bytes_left > 0) {
2298 if (bytes_left >= 26) {
2299 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2300 bytes_left -= 26;
2301 } else {
2302 packet.Printf("%*.*s;", bytes_left, bytes_left,
2303 "abcdefghijklmnopqrstuvwxyz");
2304 bytes_left = 0;
2305 }
2306 }
2307
2308 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002309 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2310 PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002311}
2312
2313bool GDBRemoteCommunicationClient::LaunchGDBServer(
2314 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2315 std::string &socket_name) {
2316 pid = LLDB_INVALID_PROCESS_ID;
2317 port = 0;
2318 socket_name.clear();
2319
2320 StringExtractorGDBRemote response;
2321 StreamString stream;
2322 stream.PutCString("qLaunchGDBServer;");
2323 std::string hostname;
2324 if (remote_accept_hostname && remote_accept_hostname[0])
2325 hostname = remote_accept_hostname;
2326 else {
2327 if (HostInfo::GetHostname(hostname)) {
2328 // Make the GDB server we launch only accept connections from this host
2329 stream.Printf("host:%s;", hostname.c_str());
2330 } else {
2331 // Make the GDB server we launch accept connections from any host since we
2332 // can't figure out the hostname
2333 stream.Printf("host:*;");
2334 }
2335 }
2336 // give the process a few seconds to startup
Pavel Labath1eff73c2016-11-24 10:54:49 +00002337 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002338
2339 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2340 PacketResult::Success) {
2341 llvm::StringRef name;
2342 llvm::StringRef value;
2343 while (response.GetNameColonValue(name, value)) {
2344 if (name.equals("port"))
2345 value.getAsInteger(0, port);
2346 else if (name.equals("pid"))
2347 value.getAsInteger(0, pid);
2348 else if (name.compare("socket_name") == 0) {
2349 StringExtractor extractor(value);
2350 extractor.GetHexByteString(socket_name);
2351 }
2352 }
2353 return true;
2354 }
2355 return false;
2356}
2357
2358size_t GDBRemoteCommunicationClient::QueryGDBServer(
2359 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2360 connection_urls.clear();
2361
2362 StringExtractorGDBRemote response;
2363 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2364 PacketResult::Success)
2365 return 0;
2366
2367 StructuredData::ObjectSP data =
2368 StructuredData::ParseJSON(response.GetStringRef());
2369 if (!data)
2370 return 0;
2371
2372 StructuredData::Array *array = data->GetAsArray();
2373 if (!array)
2374 return 0;
2375
2376 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2377 StructuredData::Dictionary *element = nullptr;
2378 if (!array->GetItemAtIndexAsDictionary(i, element))
2379 continue;
2380
2381 uint16_t port = 0;
2382 if (StructuredData::ObjectSP port_osp =
2383 element->GetValueForKey(llvm::StringRef("port")))
2384 port = port_osp->GetIntegerValue(0);
2385
2386 std::string socket_name;
2387 if (StructuredData::ObjectSP socket_name_osp =
2388 element->GetValueForKey(llvm::StringRef("socket_name")))
2389 socket_name = socket_name_osp->GetStringValue();
2390
2391 if (port != 0 || !socket_name.empty())
2392 connection_urls.emplace_back(port, socket_name);
2393 }
2394 return connection_urls.size();
2395}
2396
2397bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2398 StreamString stream;
2399 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002400
2401 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002402 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002403 PacketResult::Success) {
2404 if (response.IsOKResponse())
2405 return true;
2406 }
2407 return false;
2408}
2409
2410bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2411 if (m_curr_tid == tid)
2412 return true;
2413
2414 char packet[32];
2415 int packet_len;
2416 if (tid == UINT64_MAX)
2417 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2418 else
2419 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2420 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002421 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002422 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002423 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002424 PacketResult::Success) {
2425 if (response.IsOKResponse()) {
2426 m_curr_tid = tid;
2427 return true;
2428 }
2429
2430 /*
2431 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2432 * Hg packet.
2433 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2434 * which can
2435 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2436 */
2437 if (response.IsUnsupportedResponse() && IsConnected()) {
2438 m_curr_tid = 1;
2439 return true;
2440 }
2441 }
2442 return false;
2443}
2444
2445bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2446 if (m_curr_tid_run == tid)
2447 return true;
2448
2449 char packet[32];
2450 int packet_len;
2451 if (tid == UINT64_MAX)
2452 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2453 else
2454 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2455
2456 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002457 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002458 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002459 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002460 PacketResult::Success) {
2461 if (response.IsOKResponse()) {
2462 m_curr_tid_run = tid;
2463 return true;
2464 }
2465
2466 /*
2467 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2468 * Hc packet.
2469 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2470 * which can
2471 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2472 */
2473 if (response.IsUnsupportedResponse() && IsConnected()) {
2474 m_curr_tid_run = 1;
2475 return true;
2476 }
2477 }
2478 return false;
2479}
2480
2481bool GDBRemoteCommunicationClient::GetStopReply(
2482 StringExtractorGDBRemote &response) {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002483 if (SendPacketAndWaitForResponse("?", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002484 PacketResult::Success)
2485 return response.IsNormalResponse();
2486 return false;
2487}
2488
2489bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2490 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2491 if (m_supports_qThreadStopInfo) {
2492 char packet[256];
2493 int packet_len =
2494 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2495 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002496 UNUSED_IF_ASSERT_DISABLED(packet_len);
2497 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002498 PacketResult::Success) {
2499 if (response.IsUnsupportedResponse())
2500 m_supports_qThreadStopInfo = false;
2501 else if (response.IsNormalResponse())
2502 return true;
2503 else
2504 return false;
2505 } else {
2506 m_supports_qThreadStopInfo = false;
2507 }
2508 }
2509 return false;
2510}
2511
2512uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2513 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2514 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2515 if (log)
2516 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2517 __FUNCTION__, insert ? "add" : "remove", addr);
2518
2519 // Check if the stub is known not to support this breakpoint type
2520 if (!SupportsGDBStoppointPacket(type))
2521 return UINT8_MAX;
2522 // Construct the breakpoint packet
2523 char packet[64];
2524 const int packet_len =
2525 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2526 insert ? 'Z' : 'z', type, addr, length);
2527 // Check we haven't overwritten the end of the packet buffer
2528 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002529 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002530 StringExtractorGDBRemote response;
2531 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2532 // or "" (unsupported)
2533 response.SetResponseValidatorToOKErrorNotSupported();
2534 // Try to send the breakpoint packet, and check that it was correctly sent
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002535 if (SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002536 PacketResult::Success) {
2537 // Receive and OK packet when the breakpoint successfully placed
2538 if (response.IsOKResponse())
2539 return 0;
2540
Zachary Turner97206d52017-05-12 04:51:55 +00002541 // Status while setting breakpoint, send back specific error
Kate Stoneb9c1b512016-09-06 20:57:50 +00002542 if (response.IsErrorResponse())
2543 return response.GetError();
2544
2545 // Empty packet informs us that breakpoint is not supported
2546 if (response.IsUnsupportedResponse()) {
2547 // Disable this breakpoint type since it is unsupported
2548 switch (type) {
2549 case eBreakpointSoftware:
2550 m_supports_z0 = false;
2551 break;
2552 case eBreakpointHardware:
2553 m_supports_z1 = false;
2554 break;
2555 case eWatchpointWrite:
2556 m_supports_z2 = false;
2557 break;
2558 case eWatchpointRead:
2559 m_supports_z3 = false;
2560 break;
2561 case eWatchpointReadWrite:
2562 m_supports_z4 = false;
2563 break;
2564 case eStoppointInvalid:
2565 return UINT8_MAX;
2566 }
2567 }
2568 }
2569 // Signal generic failure
2570 return UINT8_MAX;
2571}
2572
2573size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2574 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2575 thread_ids.clear();
2576
2577 Lock lock(*this, false);
2578 if (lock) {
2579 sequence_mutex_unavailable = false;
2580 StringExtractorGDBRemote response;
2581
2582 PacketResult packet_result;
2583 for (packet_result =
2584 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2585 packet_result == PacketResult::Success && response.IsNormalResponse();
2586 packet_result =
2587 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2588 char ch = response.GetChar();
2589 if (ch == 'l')
2590 break;
2591 if (ch == 'm') {
2592 do {
2593 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2594
2595 if (tid != LLDB_INVALID_THREAD_ID) {
2596 thread_ids.push_back(tid);
2597 }
2598 ch = response.GetChar(); // Skip the command separator
2599 } while (ch == ','); // Make sure we got a comma separator
2600 }
2601 }
2602
2603 /*
2604 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2605 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2606 * could
2607 * be as simple as 'S05'. There is no packet which can give us pid and/or
2608 * tid.
2609 * Assume pid=tid=1 in such cases.
2610 */
2611 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 &&
2612 IsConnected()) {
2613 thread_ids.push_back(1);
2614 }
2615 } else {
David Blaikiea322f362017-01-06 00:38:06 +00002616#if !defined(LLDB_CONFIGURATION_DEBUG)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002617 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2618 GDBR_LOG_PACKETS));
2619 if (log)
2620 log->Printf("error: failed to get packet sequence mutex, not sending "
2621 "packet 'qfThreadInfo'");
2622#endif
2623 sequence_mutex_unavailable = true;
2624 }
2625 return thread_ids.size();
2626}
2627
2628lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2629 StringExtractorGDBRemote response;
2630 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2631 PacketResult::Success ||
2632 !response.IsNormalResponse())
2633 return LLDB_INVALID_ADDRESS;
2634 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2635}
2636
Zachary Turner97206d52017-05-12 04:51:55 +00002637lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002638 const char *command, // Shouldn't be NULL
2639 const FileSpec &
2640 working_dir, // Pass empty FileSpec to use the current working directory
2641 int *status_ptr, // Pass NULL if you don't want the process exit status
2642 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2643 // process to exit
2644 std::string
2645 *command_output, // Pass NULL if you don't want the command output
2646 uint32_t
2647 timeout_sec) // Timeout in seconds to wait for shell program to finish
2648{
2649 lldb_private::StreamString stream;
2650 stream.PutCString("qPlatform_shell:");
2651 stream.PutBytesAsRawHex8(command, strlen(command));
2652 stream.PutChar(',');
2653 stream.PutHex32(timeout_sec);
2654 if (working_dir) {
2655 std::string path{working_dir.GetPath(false)};
2656 stream.PutChar(',');
2657 stream.PutCStringAsRawHex8(path.c_str());
2658 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002659 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002660 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002661 PacketResult::Success) {
2662 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002663 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002664 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002665 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002666 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2667 if (exitcode == UINT32_MAX)
Zachary Turner97206d52017-05-12 04:51:55 +00002668 return Status("unable to run remote process");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002669 else if (status_ptr)
2670 *status_ptr = exitcode;
2671 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002672 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002673 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2674 if (signo_ptr)
2675 *signo_ptr = signo;
2676 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002677 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002678 std::string output;
2679 response.GetEscapedBinaryData(output);
2680 if (command_output)
2681 command_output->assign(output);
Zachary Turner97206d52017-05-12 04:51:55 +00002682 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002683 }
Zachary Turner97206d52017-05-12 04:51:55 +00002684 return Status("unable to send packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002685}
2686
Zachary Turner97206d52017-05-12 04:51:55 +00002687Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2688 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002689 std::string path{file_spec.GetPath(false)};
2690 lldb_private::StreamString stream;
2691 stream.PutCString("qPlatform_mkdir:");
2692 stream.PutHex32(file_permissions);
2693 stream.PutChar(',');
2694 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002695 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002696 StringExtractorGDBRemote response;
2697
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002698 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002699 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002700 return Status("failed to send '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002701
2702 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002703 return Status("invalid response to '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002704
Zachary Turner97206d52017-05-12 04:51:55 +00002705 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002706}
2707
Zachary Turner97206d52017-05-12 04:51:55 +00002708Status
2709GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2710 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002711 std::string path{file_spec.GetPath(false)};
2712 lldb_private::StreamString stream;
2713 stream.PutCString("qPlatform_chmod:");
2714 stream.PutHex32(file_permissions);
2715 stream.PutChar(',');
2716 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002717 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002718 StringExtractorGDBRemote response;
2719
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002720 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002721 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002722 return Status("failed to send '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002723
2724 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002725 return Status("invalid response to '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002726
Zachary Turner97206d52017-05-12 04:51:55 +00002727 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002728}
2729
2730static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
Zachary Turner97206d52017-05-12 04:51:55 +00002731 uint64_t fail_result, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002732 response.SetFilePos(0);
2733 if (response.GetChar() != 'F')
2734 return fail_result;
2735 int32_t result = response.GetS32(-2);
2736 if (result == -2)
2737 return fail_result;
2738 if (response.GetChar() == ',') {
2739 int result_errno = response.GetS32(-2);
2740 if (result_errno != -2)
2741 error.SetError(result_errno, eErrorTypePOSIX);
2742 else
2743 error.SetError(-1, eErrorTypeGeneric);
2744 } else
2745 error.Clear();
2746 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002747}
2748lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002749GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2750 uint32_t flags, mode_t mode,
Zachary Turner97206d52017-05-12 04:51:55 +00002751 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002752 std::string path(file_spec.GetPath(false));
2753 lldb_private::StreamString stream;
2754 stream.PutCString("vFile:open:");
2755 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002756 return UINT64_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002757 stream.PutCStringAsRawHex8(path.c_str());
2758 stream.PutChar(',');
2759 stream.PutHex32(flags);
2760 stream.PutChar(',');
2761 stream.PutHex32(mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002762 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002763 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002764 PacketResult::Success) {
2765 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2766 }
2767 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002768}
2769
Zachary Turner97206d52017-05-12 04:51:55 +00002770bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2771 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002772 lldb_private::StreamString stream;
2773 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002774 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002775 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002776 PacketResult::Success) {
2777 return ParseHostIOPacketResponse(response, -1, error) == 0;
2778 }
2779 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002780}
2781
2782// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2784 const lldb_private::FileSpec &file_spec) {
2785 std::string path(file_spec.GetPath(false));
2786 lldb_private::StreamString stream;
2787 stream.PutCString("vFile:size:");
2788 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002789 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002790 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002791 PacketResult::Success) {
2792 if (response.GetChar() != 'F')
2793 return UINT64_MAX;
2794 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2795 return retcode;
2796 }
2797 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002798}
2799
Zachary Turner97206d52017-05-12 04:51:55 +00002800Status
2801GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2802 uint32_t &file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002803 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002804 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002805 lldb_private::StreamString stream;
2806 stream.PutCString("vFile:mode:");
2807 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002808 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002809 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002810 PacketResult::Success) {
2811 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002812 error.SetErrorStringWithFormat("invalid response to '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002813 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002814 } else {
2815 const uint32_t mode = response.GetS32(-1);
2816 if (static_cast<int32_t>(mode) == -1) {
2817 if (response.GetChar() == ',') {
2818 int response_errno = response.GetS32(-1);
2819 if (response_errno > 0)
2820 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2821 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002822 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002823 } else
2824 error.SetErrorToGenericError();
2825 } else {
2826 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2827 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002828 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002829 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002830 error.SetErrorStringWithFormat("failed to send '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002831 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002832 }
2833 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002834}
2835
Kate Stoneb9c1b512016-09-06 20:57:50 +00002836uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2837 uint64_t offset, void *dst,
2838 uint64_t dst_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002839 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002840 lldb_private::StreamString stream;
2841 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2842 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002843 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002844 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002845 PacketResult::Success) {
2846 if (response.GetChar() != 'F')
2847 return 0;
2848 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2849 if (retcode == UINT32_MAX)
2850 return retcode;
2851 const char next = (response.Peek() ? *response.Peek() : 0);
2852 if (next == ',')
2853 return 0;
2854 if (next == ';') {
2855 response.GetChar(); // skip the semicolon
2856 std::string buffer;
2857 if (response.GetEscapedBinaryData(buffer)) {
2858 const uint64_t data_to_write =
2859 std::min<uint64_t>(dst_len, buffer.size());
2860 if (data_to_write > 0)
2861 memcpy(dst, &buffer[0], data_to_write);
2862 return data_to_write;
2863 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002864 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002865 }
2866 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002867}
2868
Kate Stoneb9c1b512016-09-06 20:57:50 +00002869uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
2870 uint64_t offset,
2871 const void *src,
2872 uint64_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002873 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002874 lldb_private::StreamGDBRemote stream;
2875 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2876 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002877 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002878 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002879 PacketResult::Success) {
2880 if (response.GetChar() != 'F') {
2881 error.SetErrorStringWithFormat("write file failed");
2882 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002883 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002884 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2885 if (bytes_written == UINT64_MAX) {
2886 error.SetErrorToGenericError();
2887 if (response.GetChar() == ',') {
2888 int response_errno = response.GetS32(-1);
2889 if (response_errno > 0)
2890 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2891 }
2892 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002893 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002894 return bytes_written;
2895 } else {
2896 error.SetErrorString("failed to send vFile:pwrite packet");
2897 }
2898 return 0;
2899}
2900
Zachary Turner97206d52017-05-12 04:51:55 +00002901Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
2902 const FileSpec &dst) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002903 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002904 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002905 lldb_private::StreamGDBRemote stream;
2906 stream.PutCString("vFile:symlink:");
2907 // the unix symlink() command reverses its parameters where the dst if first,
2908 // so we follow suit here
2909 stream.PutCStringAsRawHex8(dst_path.c_str());
2910 stream.PutChar(',');
2911 stream.PutCStringAsRawHex8(src_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002912 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002913 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002914 PacketResult::Success) {
2915 if (response.GetChar() == 'F') {
2916 uint32_t result = response.GetU32(UINT32_MAX);
2917 if (result != 0) {
2918 error.SetErrorToGenericError();
2919 if (response.GetChar() == ',') {
2920 int response_errno = response.GetS32(-1);
2921 if (response_errno > 0)
2922 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2923 }
2924 }
2925 } else {
2926 // Should have returned with 'F<result>[,<errno>]'
2927 error.SetErrorStringWithFormat("symlink failed");
2928 }
2929 } else {
2930 error.SetErrorString("failed to send vFile:symlink packet");
2931 }
2932 return error;
2933}
2934
Zachary Turner97206d52017-05-12 04:51:55 +00002935Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002936 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002937 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002938 lldb_private::StreamGDBRemote stream;
2939 stream.PutCString("vFile:unlink:");
2940 // the unix symlink() command reverses its parameters where the dst if first,
2941 // so we follow suit here
2942 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002943 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002944 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002945 PacketResult::Success) {
2946 if (response.GetChar() == 'F') {
2947 uint32_t result = response.GetU32(UINT32_MAX);
2948 if (result != 0) {
2949 error.SetErrorToGenericError();
2950 if (response.GetChar() == ',') {
2951 int response_errno = response.GetS32(-1);
2952 if (response_errno > 0)
2953 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2954 }
2955 }
2956 } else {
2957 // Should have returned with 'F<result>[,<errno>]'
2958 error.SetErrorStringWithFormat("unlink failed");
2959 }
2960 } else {
2961 error.SetErrorString("failed to send vFile:unlink packet");
2962 }
2963 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002964}
2965
Daniel Maleae0f8f572013-08-26 23:57:52 +00002966// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002967bool GDBRemoteCommunicationClient::GetFileExists(
2968 const lldb_private::FileSpec &file_spec) {
2969 std::string path(file_spec.GetPath(false));
2970 lldb_private::StreamString stream;
2971 stream.PutCString("vFile:exists:");
2972 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002973 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002974 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975 PacketResult::Success) {
2976 if (response.GetChar() != 'F')
2977 return false;
2978 if (response.GetChar() != ',')
2979 return false;
2980 bool retcode = (response.GetChar() != '0');
2981 return retcode;
2982 }
2983 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002984}
2985
Kate Stoneb9c1b512016-09-06 20:57:50 +00002986bool GDBRemoteCommunicationClient::CalculateMD5(
2987 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
2988 std::string path(file_spec.GetPath(false));
2989 lldb_private::StreamString stream;
2990 stream.PutCString("vFile:MD5:");
2991 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002993 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002994 PacketResult::Success) {
2995 if (response.GetChar() != 'F')
2996 return false;
2997 if (response.GetChar() != ',')
2998 return false;
2999 if (response.Peek() && *response.Peek() == 'x')
3000 return false;
3001 low = response.GetHexMaxU64(false, UINT64_MAX);
3002 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00003003 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003004 }
3005 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003006}
3007
Kate Stoneb9c1b512016-09-06 20:57:50 +00003008bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3009 // Some targets have issues with g/G packets and we need to avoid using them
3010 if (m_avoid_g_packets == eLazyBoolCalculate) {
3011 if (process) {
3012 m_avoid_g_packets = eLazyBoolNo;
3013 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3014 if (arch.IsValid() &&
3015 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3016 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3017 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3018 m_avoid_g_packets = eLazyBoolYes;
3019 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3020 if (gdb_server_version != 0) {
3021 const char *gdb_server_name = GetGDBServerProgramName();
3022 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3023 if (gdb_server_version >= 310)
3024 m_avoid_g_packets = eLazyBoolNo;
3025 }
3026 }
3027 }
3028 }
3029 }
3030 return m_avoid_g_packets == eLazyBoolYes;
3031}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003032
Kate Stoneb9c1b512016-09-06 20:57:50 +00003033DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3034 uint32_t reg) {
3035 StreamString payload;
3036 payload.Printf("p%x", reg);
3037 StringExtractorGDBRemote response;
3038 if (SendThreadSpecificPacketAndWaitForResponse(
3039 tid, std::move(payload), response, false) != PacketResult::Success ||
3040 !response.IsNormalResponse())
3041 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003042
Kate Stoneb9c1b512016-09-06 20:57:50 +00003043 DataBufferSP buffer_sp(
3044 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3045 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3046 return buffer_sp;
3047}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003048
Kate Stoneb9c1b512016-09-06 20:57:50 +00003049DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3050 StreamString payload;
3051 payload.PutChar('g');
3052 StringExtractorGDBRemote response;
3053 if (SendThreadSpecificPacketAndWaitForResponse(
3054 tid, std::move(payload), response, false) != PacketResult::Success ||
3055 !response.IsNormalResponse())
3056 return nullptr;
3057
3058 DataBufferSP buffer_sp(
3059 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3060 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3061 return buffer_sp;
3062}
3063
3064bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3065 uint32_t reg_num,
3066 llvm::ArrayRef<uint8_t> data) {
3067 StreamString payload;
3068 payload.Printf("P%x=", reg_num);
3069 payload.PutBytesAsRawHex8(data.data(), data.size(),
3070 endian::InlHostByteOrder(),
3071 endian::InlHostByteOrder());
3072 StringExtractorGDBRemote response;
3073 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3074 response, false) ==
3075 PacketResult::Success &&
3076 response.IsOKResponse();
3077}
3078
3079bool GDBRemoteCommunicationClient::WriteAllRegisters(
3080 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3081 StreamString payload;
3082 payload.PutChar('G');
3083 payload.PutBytesAsRawHex8(data.data(), data.size(),
3084 endian::InlHostByteOrder(),
3085 endian::InlHostByteOrder());
3086 StringExtractorGDBRemote response;
3087 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3088 response, false) ==
3089 PacketResult::Success &&
3090 response.IsOKResponse();
3091}
3092
3093bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3094 uint32_t &save_id) {
3095 save_id = 0; // Set to invalid save ID
3096 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003097 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003098
3099 m_supports_QSaveRegisterState = eLazyBoolYes;
3100 StreamString payload;
3101 payload.PutCString("QSaveRegisterState");
3102 StringExtractorGDBRemote response;
3103 if (SendThreadSpecificPacketAndWaitForResponse(
3104 tid, std::move(payload), response, false) != PacketResult::Success)
3105 return false;
3106
3107 if (response.IsUnsupportedResponse())
3108 m_supports_QSaveRegisterState = eLazyBoolNo;
3109
3110 const uint32_t response_save_id = response.GetU32(0);
3111 if (response_save_id == 0)
3112 return false;
3113
3114 save_id = response_save_id;
3115 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003116}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003117
Kate Stoneb9c1b512016-09-06 20:57:50 +00003118bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3119 uint32_t save_id) {
3120 // We use the "m_supports_QSaveRegisterState" variable here because the
3121 // QSaveRegisterState and QRestoreRegisterState packets must both be supported
3122 // in
3123 // order to be useful
3124 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3125 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003126
Kate Stoneb9c1b512016-09-06 20:57:50 +00003127 StreamString payload;
3128 payload.Printf("QRestoreRegisterState:%u", save_id);
3129 StringExtractorGDBRemote response;
3130 if (SendThreadSpecificPacketAndWaitForResponse(
3131 tid, std::move(payload), response, false) != PacketResult::Success)
3132 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003133
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003135 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003136
3137 if (response.IsUnsupportedResponse())
3138 m_supports_QSaveRegisterState = eLazyBoolNo;
3139 return false;
3140}
3141
3142bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3143 if (!GetSyncThreadStateSupported())
3144 return false;
3145
3146 StreamString packet;
3147 StringExtractorGDBRemote response;
3148 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3149 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3150 GDBRemoteCommunication::PacketResult::Success &&
3151 response.IsOKResponse();
3152}
3153
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003154lldb::user_id_t
3155GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3156 Status &error) {
3157 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3158 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3159
3160 StreamGDBRemote escaped_packet;
3161 escaped_packet.PutCString("jTraceStart:");
3162
3163 StructuredData::Dictionary json_packet;
3164 json_packet.AddIntegerItem("type", options.getType());
3165 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3166 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3167
3168 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3169 json_packet.AddIntegerItem("threadid", options.getThreadID());
3170
3171 StructuredData::DictionarySP custom_params = options.getTraceParams();
3172 if (custom_params)
3173 json_packet.AddItem("params", custom_params);
3174
3175 StreamString json_string;
3176 json_packet.Dump(json_string, false);
3177 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3178
3179 StringExtractorGDBRemote response;
3180 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3181 true) ==
3182 GDBRemoteCommunication::PacketResult::Success) {
3183 if (!response.IsNormalResponse()) {
3184 error.SetError(response.GetError(), eErrorTypeGeneric);
3185 LLDB_LOG(log, "Target does not support Tracing");
3186 } else {
3187 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3188 }
3189 } else {
3190 LLDB_LOG(log, "failed to send packet");
3191 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3192 escaped_packet.GetData());
3193 }
3194 return ret_uid;
3195}
3196
3197Status
3198GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3199 lldb::tid_t thread_id) {
3200 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3201 StringExtractorGDBRemote response;
3202 Status error;
3203
3204 StructuredData::Dictionary json_packet;
3205 StreamGDBRemote escaped_packet;
3206 StreamString json_string;
3207 escaped_packet.PutCString("jTraceStop:");
3208
3209 json_packet.AddIntegerItem("traceid", uid);
3210
3211 if (thread_id != LLDB_INVALID_THREAD_ID)
3212 json_packet.AddIntegerItem("threadid", thread_id);
3213
3214 json_packet.Dump(json_string, false);
3215
3216 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3217
3218 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3219 true) ==
3220 GDBRemoteCommunication::PacketResult::Success) {
3221 if (!response.IsOKResponse()) {
3222 error.SetError(response.GetError(), eErrorTypeGeneric);
3223 LLDB_LOG(log, "stop tracing failed");
3224 }
3225 } else {
3226 LLDB_LOG(log, "failed to send packet");
3227 error.SetErrorStringWithFormat(
3228 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3229 response.GetError());
3230 }
3231 return error;
3232}
3233
3234Status GDBRemoteCommunicationClient::SendGetDataPacket(
3235 lldb::user_id_t uid, lldb::tid_t thread_id,
3236 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3237 StreamGDBRemote escaped_packet;
3238 escaped_packet.PutCString("jTraceBufferRead:");
3239 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3240}
3241
3242Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3243 lldb::user_id_t uid, lldb::tid_t thread_id,
3244 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3245 StreamGDBRemote escaped_packet;
3246 escaped_packet.PutCString("jTraceMetaRead:");
3247 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3248}
3249
3250Status
3251GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3252 TraceOptions &options) {
3253 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3254 StringExtractorGDBRemote response;
3255 Status error;
3256
3257 StreamString json_string;
3258 StreamGDBRemote escaped_packet;
3259 escaped_packet.PutCString("jTraceConfigRead:");
3260
3261 StructuredData::Dictionary json_packet;
3262 json_packet.AddIntegerItem("traceid", uid);
3263
3264 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3265 json_packet.AddIntegerItem("threadid", options.getThreadID());
3266
3267 json_packet.Dump(json_string, false);
3268 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3269
3270 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3271 true) ==
3272 GDBRemoteCommunication::PacketResult::Success) {
3273 if (response.IsNormalResponse()) {
3274 uint64_t type = std::numeric_limits<uint64_t>::max();
3275 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3276 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3277
3278 auto json_object = StructuredData::ParseJSON(response.Peek());
3279
3280 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003281 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003282 error.SetErrorString("Invalid Configuration obtained");
3283 return error;
3284 }
3285
3286 auto json_dict = json_object->GetAsDictionary();
3287
3288 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3289 metabuffersize);
3290 options.setMetaDataBufferSize(metabuffersize);
3291
3292 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3293 options.setTraceBufferSize(buffersize);
3294
3295 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3296 options.setType(static_cast<lldb::TraceType>(type));
3297
3298 StructuredData::ObjectSP custom_params_sp =
3299 json_dict->GetValueForKey("params");
3300 if (custom_params_sp) {
3301 if (custom_params_sp->GetType() !=
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003302 lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003303 error.SetErrorString("Invalid Configuration obtained");
3304 return error;
3305 } else
3306 options.setTraceParams(
3307 static_pointer_cast<StructuredData::Dictionary>(
3308 custom_params_sp));
3309 }
3310 } else {
3311 error.SetError(response.GetError(), eErrorTypeGeneric);
3312 }
3313 } else {
3314 LLDB_LOG(log, "failed to send packet");
3315 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3316 escaped_packet.GetData());
3317 }
3318 return error;
3319}
3320
3321Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3322 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3323 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3324 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3325 Status error;
3326
3327 StructuredData::Dictionary json_packet;
3328
3329 json_packet.AddIntegerItem("traceid", uid);
3330 json_packet.AddIntegerItem("offset", offset);
3331 json_packet.AddIntegerItem("buffersize", buffer.size());
3332
3333 if (thread_id != LLDB_INVALID_THREAD_ID)
3334 json_packet.AddIntegerItem("threadid", thread_id);
3335
3336 StreamString json_string;
3337 json_packet.Dump(json_string, false);
3338
3339 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3340 StringExtractorGDBRemote response;
3341 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3342 GDBRemoteCommunication::PacketResult::Success) {
3343 if (response.IsNormalResponse()) {
3344 size_t filled_size = response.GetHexBytesAvail(buffer);
3345 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3346 } else {
3347 error.SetError(response.GetError(), eErrorTypeGeneric);
3348 buffer = buffer.slice(buffer.size());
3349 }
3350 } else {
3351 LLDB_LOG(log, "failed to send packet");
3352 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3353 packet.GetData());
3354 buffer = buffer.slice(buffer.size());
3355 }
3356 return error;
3357}
3358
Kate Stoneb9c1b512016-09-06 20:57:50 +00003359bool GDBRemoteCommunicationClient::GetModuleInfo(
3360 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3361 ModuleSpec &module_spec) {
3362 if (!m_supports_qModuleInfo)
3363 return false;
3364
3365 std::string module_path = module_file_spec.GetPath(false);
3366 if (module_path.empty())
3367 return false;
3368
3369 StreamString packet;
3370 packet.PutCString("qModuleInfo:");
3371 packet.PutCStringAsRawHex8(module_path.c_str());
3372 packet.PutCString(";");
3373 const auto &triple = arch_spec.GetTriple().getTriple();
3374 packet.PutCStringAsRawHex8(triple.c_str());
3375
3376 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003377 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3378 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003379 return false;
3380
3381 if (response.IsErrorResponse())
3382 return false;
3383
3384 if (response.IsUnsupportedResponse()) {
3385 m_supports_qModuleInfo = false;
3386 return false;
3387 }
3388
3389 llvm::StringRef name;
3390 llvm::StringRef value;
3391
3392 module_spec.Clear();
3393 module_spec.GetFileSpec() = module_file_spec;
3394
3395 while (response.GetNameColonValue(name, value)) {
3396 if (name == "uuid" || name == "md5") {
3397 StringExtractor extractor(value);
3398 std::string uuid;
3399 extractor.GetHexByteString(uuid);
3400 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
3401 } else if (name == "triple") {
3402 StringExtractor extractor(value);
3403 std::string triple;
3404 extractor.GetHexByteString(triple);
3405 module_spec.GetArchitecture().SetTriple(triple.c_str());
3406 } else if (name == "file_offset") {
3407 uint64_t ival = 0;
3408 if (!value.getAsInteger(16, ival))
3409 module_spec.SetObjectOffset(ival);
3410 } else if (name == "file_size") {
3411 uint64_t ival = 0;
3412 if (!value.getAsInteger(16, ival))
3413 module_spec.SetObjectSize(ival);
3414 } else if (name == "file_path") {
3415 StringExtractor extractor(value);
3416 std::string path;
3417 extractor.GetHexByteString(path);
Zachary Turner8c6b5462017-03-06 23:42:44 +00003418 module_spec.GetFileSpec() = FileSpec(path, false, arch_spec.GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003419 }
3420 }
3421
3422 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003423}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003424
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003425static llvm::Optional<ModuleSpec>
3426ParseModuleSpec(StructuredData::Dictionary *dict) {
3427 ModuleSpec result;
3428 if (!dict)
3429 return llvm::None;
3430
Zachary Turner28333212017-05-12 05:49:54 +00003431 llvm::StringRef string;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003432 uint64_t integer;
3433
3434 if (!dict->GetValueForKeyAsString("uuid", string))
3435 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003436 result.GetUUID().SetFromStringRef(string, string.size());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003437
3438 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3439 return llvm::None;
3440 result.SetObjectOffset(integer);
3441
3442 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3443 return llvm::None;
3444 result.SetObjectSize(integer);
3445
3446 if (!dict->GetValueForKeyAsString("triple", string))
3447 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003448 result.GetArchitecture().SetTriple(string);
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003449
3450 if (!dict->GetValueForKeyAsString("file_path", string))
3451 return llvm::None;
Zachary Turner8c6b5462017-03-06 23:42:44 +00003452 result.GetFileSpec() =
3453 FileSpec(string, false, result.GetArchitecture().GetTriple());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003454
3455 return result;
3456}
3457
3458llvm::Optional<std::vector<ModuleSpec>>
3459GDBRemoteCommunicationClient::GetModulesInfo(
3460 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3461 if (!m_supports_jModulesInfo)
3462 return llvm::None;
3463
3464 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3465 for (const FileSpec &module_file_spec : module_file_specs) {
3466 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3467 module_array_sp->AppendObject(module_sp);
3468 module_sp->SetObject(
Pavel Labath763f1c42017-01-05 13:18:46 +00003469 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003470 module_sp->SetObject("triple",
3471 std::make_shared<JSONString>(triple.getTriple()));
3472 }
3473 StreamString unescaped_payload;
3474 unescaped_payload.PutCString("jModulesInfo:");
3475 module_array_sp->Write(unescaped_payload);
3476 StreamGDBRemote payload;
Zachary Turnerc1564272016-11-16 21:15:24 +00003477 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003478 unescaped_payload.GetSize());
3479
Greg Clayton70a9f512017-04-14 17:10:04 +00003480 // Increase the timeout for jModulesInfo since this packet can take longer.
3481 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3482
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003483 StringExtractorGDBRemote response;
3484 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3485 PacketResult::Success ||
3486 response.IsErrorResponse())
3487 return llvm::None;
3488
3489 if (response.IsUnsupportedResponse()) {
3490 m_supports_jModulesInfo = false;
3491 return llvm::None;
3492 }
3493
3494 StructuredData::ObjectSP response_object_sp =
3495 StructuredData::ParseJSON(response.GetStringRef());
3496 if (!response_object_sp)
3497 return llvm::None;
3498
3499 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3500 if (!response_array)
3501 return llvm::None;
3502
3503 std::vector<ModuleSpec> result;
3504 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3505 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3506 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3507 result.push_back(*module_spec);
3508 }
3509
3510 return result;
3511}
3512
Colin Rileyc3c95b22015-04-16 15:51:33 +00003513// query the target remote for extended information using the qXfer packet
3514//
3515// example: object='features', annex='target.xml', out=<xml output>
3516// return: 'true' on success
3517// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003518bool GDBRemoteCommunicationClient::ReadExtFeature(
3519 const lldb_private::ConstString object,
3520 const lldb_private::ConstString annex, std::string &out,
Zachary Turner97206d52017-05-12 04:51:55 +00003521 lldb_private::Status &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003522
Kate Stoneb9c1b512016-09-06 20:57:50 +00003523 std::stringstream output;
3524 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003525
Kate Stoneb9c1b512016-09-06 20:57:50 +00003526 uint64_t size = GetRemoteMaxPacketSize();
3527 if (size == 0)
3528 size = 0x1000;
3529 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3530 int offset = 0;
3531 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003532
Kate Stoneb9c1b512016-09-06 20:57:50 +00003533 // loop until all data has been read
3534 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003535
Kate Stoneb9c1b512016-09-06 20:57:50 +00003536 // send query extended feature packet
3537 std::stringstream packet;
3538 packet << "qXfer:" << object.AsCString("")
3539 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3540 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003541
Kate Stoneb9c1b512016-09-06 20:57:50 +00003542 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003543 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003544
Kate Stoneb9c1b512016-09-06 20:57:50 +00003545 if (res != GDBRemoteCommunication::PacketResult::Success) {
3546 err.SetErrorString("Error sending $qXfer packet");
3547 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003548 }
3549
Kate Stoneb9c1b512016-09-06 20:57:50 +00003550 const std::string &str = chunk.GetStringRef();
3551 if (str.length() == 0) {
3552 // should have some data in chunk
3553 err.SetErrorString("Empty response from $qXfer packet");
3554 return false;
3555 }
3556
3557 // check packet code
3558 switch (str[0]) {
3559 // last chunk
3560 case ('l'):
3561 active = false;
3562 LLVM_FALLTHROUGH;
3563
3564 // more chunks
3565 case ('m'):
3566 if (str.length() > 1)
3567 output << &str[1];
3568 offset += size;
3569 break;
3570
3571 // unknown chunk
3572 default:
3573 err.SetErrorString("Invalid continuation code from $qXfer packet");
3574 return false;
3575 }
3576 }
3577
3578 out = output.str();
3579 err.Success();
3580 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003581}
Greg Clayton0b90be12015-06-23 21:27:50 +00003582
3583// Notify the target that gdb is prepared to serve symbol lookup requests.
3584// packet: "qSymbol::"
3585// reply:
3586// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003587// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3588// encoded).
3589// LLDB may provide the value by sending another qSymbol
3590// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003591// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003592//
3593// Three examples:
3594//
3595// lldb sends: qSymbol::
3596// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003597// Remote gdb stub does not need to know the addresses of any symbols, lldb
3598// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003599// need to ask again in this session.
3600//
3601// lldb sends: qSymbol::
3602// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3603// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3604// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003605// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3606// not know
3607// the address at this time. lldb needs to send qSymbol:: again when it has
3608// more
Jason Molenda50018d32016-01-13 04:08:10 +00003609// solibs loaded.
3610//
3611// lldb sends: qSymbol::
3612// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3613// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3614// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003615// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3616// that it
3617// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3618// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003619// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003620
Kate Stoneb9c1b512016-09-06 20:57:50 +00003621void GDBRemoteCommunicationClient::ServeSymbolLookups(
3622 lldb_private::Process *process) {
3623 // Set to true once we've resolved a symbol to an address for the remote stub.
3624 // If we get an 'OK' response after this, the remote stub doesn't need any
3625 // more
3626 // symbols and we can stop asking.
3627 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003628
Kate Stoneb9c1b512016-09-06 20:57:50 +00003629 // Is this the initial qSymbol:: packet?
3630 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003631
Kate Stoneb9c1b512016-09-06 20:57:50 +00003632 if (m_supports_qSymbol && m_qSymbol_requests_done == false) {
3633 Lock lock(*this, false);
3634 if (lock) {
3635 StreamString packet;
3636 packet.PutCString("qSymbol::");
3637 StringExtractorGDBRemote response;
3638 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3639 PacketResult::Success) {
3640 if (response.IsOKResponse()) {
3641 if (symbol_response_provided || first_qsymbol_query) {
3642 m_qSymbol_requests_done = true;
3643 }
3644
3645 // We are done serving symbols requests
3646 return;
3647 }
3648 first_qsymbol_query = false;
3649
3650 if (response.IsUnsupportedResponse()) {
3651 // qSymbol is not supported by the current GDB server we are connected
3652 // to
3653 m_supports_qSymbol = false;
3654 return;
3655 } else {
3656 llvm::StringRef response_str(response.GetStringRef());
3657 if (response_str.startswith("qSymbol:")) {
3658 response.SetFilePos(strlen("qSymbol:"));
3659 std::string symbol_name;
3660 if (response.GetHexByteString(symbol_name)) {
3661 if (symbol_name.empty())
3662 return;
3663
3664 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3665 lldb_private::SymbolContextList sc_list;
3666 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3667 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3668 const size_t num_scs = sc_list.GetSize();
3669 for (size_t sc_idx = 0;
3670 sc_idx < num_scs &&
3671 symbol_load_addr == LLDB_INVALID_ADDRESS;
3672 ++sc_idx) {
3673 SymbolContext sc;
3674 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3675 if (sc.symbol) {
3676 switch (sc.symbol->GetType()) {
3677 case eSymbolTypeInvalid:
3678 case eSymbolTypeAbsolute:
3679 case eSymbolTypeUndefined:
3680 case eSymbolTypeSourceFile:
3681 case eSymbolTypeHeaderFile:
3682 case eSymbolTypeObjectFile:
3683 case eSymbolTypeCommonBlock:
3684 case eSymbolTypeBlock:
3685 case eSymbolTypeLocal:
3686 case eSymbolTypeParam:
3687 case eSymbolTypeVariable:
3688 case eSymbolTypeVariableType:
3689 case eSymbolTypeLineEntry:
3690 case eSymbolTypeLineHeader:
3691 case eSymbolTypeScopeBegin:
3692 case eSymbolTypeScopeEnd:
3693 case eSymbolTypeAdditional:
3694 case eSymbolTypeCompiler:
3695 case eSymbolTypeInstrumentation:
3696 case eSymbolTypeTrampoline:
3697 break;
3698
3699 case eSymbolTypeCode:
3700 case eSymbolTypeResolver:
3701 case eSymbolTypeData:
3702 case eSymbolTypeRuntime:
3703 case eSymbolTypeException:
3704 case eSymbolTypeObjCClass:
3705 case eSymbolTypeObjCMetaClass:
3706 case eSymbolTypeObjCIVar:
3707 case eSymbolTypeReExported:
3708 symbol_load_addr =
3709 sc.symbol->GetLoadAddress(&process->GetTarget());
3710 break;
3711 }
Jason Molenda50018d32016-01-13 04:08:10 +00003712 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003713 }
Greg Clayton42b01482015-08-11 22:07:46 +00003714 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003715 }
3716 // This is the normal path where our symbol lookup was successful
3717 // and we want
3718 // to send a packet with the new symbol value and see if another
3719 // lookup needs to be
3720 // done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003721
Kate Stoneb9c1b512016-09-06 20:57:50 +00003722 // Change "packet" to contain the requested symbol value and name
3723 packet.Clear();
3724 packet.PutCString("qSymbol:");
3725 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3726 packet.Printf("%" PRIx64, symbol_load_addr);
3727 symbol_response_provided = true;
3728 } else {
3729 symbol_response_provided = false;
3730 }
3731 packet.PutCString(":");
3732 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3733 continue; // go back to the while loop and send "packet" and wait
3734 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003735 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003736 }
3737 }
3738 }
3739 // If we make it here, the symbol request packet response wasn't valid or
3740 // our symbol lookup failed so we must abort
3741 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003742
Kate Stoneb9c1b512016-09-06 20:57:50 +00003743 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3744 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3745 log->Printf(
3746 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3747 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003748 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003749 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003750}
3751
Kate Stoneb9c1b512016-09-06 20:57:50 +00003752StructuredData::Array *
3753GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3754 if (!m_supported_async_json_packets_is_valid) {
3755 // Query the server for the array of supported asynchronous JSON
3756 // packets.
3757 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003758
Kate Stoneb9c1b512016-09-06 20:57:50 +00003759 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003760
Kate Stoneb9c1b512016-09-06 20:57:50 +00003761 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003762 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003763 const bool send_async = false;
3764 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3765 send_async) == PacketResult::Success) {
3766 m_supported_async_json_packets_sp =
3767 StructuredData::ParseJSON(response.GetStringRef());
3768 if (m_supported_async_json_packets_sp &&
3769 !m_supported_async_json_packets_sp->GetAsArray()) {
3770 // We were returned something other than a JSON array. This
3771 // is invalid. Clear it out.
3772 if (log)
3773 log->Printf("GDBRemoteCommunicationClient::%s(): "
3774 "QSupportedAsyncJSONPackets returned invalid "
3775 "result: %s",
3776 __FUNCTION__, response.GetStringRef().c_str());
3777 m_supported_async_json_packets_sp.reset();
3778 }
3779 } else {
3780 if (log)
3781 log->Printf("GDBRemoteCommunicationClient::%s(): "
3782 "QSupportedAsyncJSONPackets unsupported",
3783 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003784 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003785
3786 if (log && m_supported_async_json_packets_sp) {
3787 StreamString stream;
3788 m_supported_async_json_packets_sp->Dump(stream);
3789 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3790 "JSON packets: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00003791 __FUNCTION__, stream.GetData());
Todd Fiala75930012016-08-19 04:21:48 +00003792 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003793 }
3794
3795 return m_supported_async_json_packets_sp
3796 ? m_supported_async_json_packets_sp->GetAsArray()
3797 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003798}
3799
Zachary Turner97206d52017-05-12 04:51:55 +00003800Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003801 llvm::ArrayRef<int32_t> signals) {
3802 // Format packet:
3803 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3804 auto range = llvm::make_range(signals.begin(), signals.end());
3805 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3806
3807 StringExtractorGDBRemote response;
3808 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3809
3810 if (send_status != GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00003811 return Status("Sending QPassSignals packet failed");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003812
3813 if (response.IsOKResponse()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003814 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003815 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00003816 return Status("Unknown error happened during sending QPassSignals packet.");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003817 }
3818}
3819
Zachary Turner97206d52017-05-12 04:51:55 +00003820Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003821 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00003822 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003823
3824 if (type_name.GetLength() == 0) {
3825 error.SetErrorString("invalid type_name argument");
3826 return error;
3827 }
3828
3829 // Build command: Configure{type_name}: serialized config
3830 // data.
3831 StreamGDBRemote stream;
3832 stream.PutCString("QConfigure");
3833 stream.PutCString(type_name.AsCString());
3834 stream.PutChar(':');
3835 if (config_sp) {
3836 // Gather the plain-text version of the configuration data.
3837 StreamString unescaped_stream;
3838 config_sp->Dump(unescaped_stream);
3839 unescaped_stream.Flush();
3840
3841 // Add it to the stream in escaped fashion.
Zachary Turnerc1564272016-11-16 21:15:24 +00003842 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003843 unescaped_stream.GetSize());
3844 }
3845 stream.Flush();
3846
3847 // Send the packet.
3848 const bool send_async = false;
3849 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003850 auto result =
3851 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003852 if (result == PacketResult::Success) {
3853 // We failed if the config result comes back other than OK.
3854 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3855 // Okay!
3856 error.Clear();
3857 } else {
3858 error.SetErrorStringWithFormat("configuring StructuredData feature "
3859 "%s failed with error %s",
3860 type_name.AsCString(),
3861 response.GetStringRef().c_str());
3862 }
3863 } else {
3864 // Can we get more data here on the failure?
3865 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3866 "failed when sending packet: "
3867 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00003868 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003869 }
3870 return error;
3871}
3872
3873void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
3874 GDBRemoteClientBase::OnRunPacketSent(first);
3875 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003876}