blob: e79f5d0c467efce5a2cd06f510dd8cb9ce6bf532 [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),
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +000089 m_supports_error_string_reply(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000090 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true),
91 m_supports_qUserName(true), m_supports_qGroupName(true),
92 m_supports_qThreadStopInfo(true), m_supports_z0(true),
93 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true),
94 m_supports_z4(true), m_supports_QEnvironment(true),
95 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true),
96 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true),
Pavel Labath2f1fbae2016-09-08 10:07:04 +000097 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true),
98 m_curr_pid(LLDB_INVALID_PROCESS_ID), m_curr_tid(LLDB_INVALID_THREAD_ID),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000099 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100 m_num_supported_hardware_watchpoints(0), m_host_arch(), m_process_arch(),
101 m_os_version_major(UINT32_MAX), m_os_version_minor(UINT32_MAX),
102 m_os_version_update(UINT32_MAX), m_os_build(), m_os_kernel(),
103 m_hostname(), m_gdb_server_name(), m_gdb_server_version(UINT32_MAX),
104 m_default_packet_timeout(0), m_max_packet_size(0),
105 m_qSupported_response(), m_supported_async_json_packets_is_valid(false),
106 m_supported_async_json_packets_sp() {}
Greg Clayton576d8832011-03-22 04:00:09 +0000107
108//----------------------------------------------------------------------
109// Destructor
110//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() {
112 if (IsConnected())
113 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000114}
115
Zachary Turner97206d52017-05-12 04:51:55 +0000116bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 ResetDiscoverableSettings(false);
Greg Claytonfb909312013-11-23 01:58:15 +0000118
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 // Start the read thread after we send the handshake ack since if we
120 // fail to send the handshake ack, there is no reason to continue...
121 if (SendAck()) {
122 // Wait for any responses that might have been queued up in the remote
123 // GDB server and flush them all
124 StringExtractorGDBRemote response;
125 PacketResult packet_result = PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126 while (packet_result == PacketResult::Success)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000127 packet_result = ReadPacket(response, milliseconds(10), false);
Ed Maste48f986f2013-12-18 15:31:45 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 // The return value from QueryNoAckModeSupported() is true if the packet
130 // was sent and _any_ response (including UNIMPLEMENTED) was received),
131 // or false if no response was received. This quickly tells us if we have
132 // a live connection to a remote GDB server...
133 if (QueryNoAckModeSupported()) {
134 return true;
135 } else {
136 if (error_ptr)
137 error_ptr->SetErrorString("failed to get reply to handshake packet");
Greg Claytonfb909312013-11-23 01:58:15 +0000138 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 } else {
140 if (error_ptr)
141 error_ptr->SetErrorString("failed to send the handshake ack");
142 }
143 return false;
Greg Clayton1cb64962011-03-24 04:28:38 +0000144}
145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146bool GDBRemoteCommunicationClient::GetEchoSupported() {
147 if (m_supports_qEcho == eLazyBoolCalculate) {
148 GetRemoteQSupported();
149 }
150 return m_supports_qEcho == eLazyBoolYes;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000151}
152
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000153bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() {
154 if (m_supports_QPassSignals == eLazyBoolCalculate) {
155 GetRemoteQSupported();
156 }
157 return m_supports_QPassSignals == eLazyBoolYes;
158}
159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
161 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
162 GetRemoteQSupported();
163 }
164 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000165}
166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
168 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
169 GetRemoteQSupported();
170 }
171 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000172}
173
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
175 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
176 GetRemoteQSupported();
177 }
178 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000179}
180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
182 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
183 GetRemoteQSupported();
184 }
185 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000186}
187
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
189 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
190 GetRemoteQSupported();
191 }
192 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000193}
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
196 if (m_max_packet_size == 0) {
197 GetRemoteQSupported();
198 }
199 return m_max_packet_size;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000200}
201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
203 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
204 m_send_acks = true;
205 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000206
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207 // This is the first real packet that we'll send in a debug session and it
208 // may take a little
209 // longer than normal to receive a reply. Wait at least 6 seconds for a
210 // reply to this packet.
Jason Molenda36a216e2014-07-24 01:36:24 +0000211
Pavel Labath1eff73c2016-11-24 10:54:49 +0000212 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
Colin Rileyc3c95b22015-04-16 15:51:33 +0000213
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000214 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
216 PacketResult::Success) {
217 if (response.IsOKResponse()) {
218 m_send_acks = false;
219 m_supports_not_sending_acks = eLazyBoolYes;
220 }
221 return true;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000222 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 }
224 return false;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000225}
Greg Clayton576d8832011-03-22 04:00:09 +0000226
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
228 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
229 m_supports_threads_in_stop_reply = eLazyBoolNo;
230
231 StringExtractorGDBRemote response;
232 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
233 false) == PacketResult::Success) {
234 if (response.IsOKResponse())
235 m_supports_threads_in_stop_reply = eLazyBoolYes;
Pavel Labath5c95ee42016-08-30 13:56:11 +0000236 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 }
Pavel Labath0faf3732016-08-25 08:34:57 +0000238}
Greg Clayton576d8832011-03-22 04:00:09 +0000239
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
241 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
242 m_attach_or_wait_reply = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +0000243
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 StringExtractorGDBRemote response;
245 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
246 false) == PacketResult::Success) {
247 if (response.IsOKResponse())
248 m_attach_or_wait_reply = eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000249 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250 }
251 if (m_attach_or_wait_reply == eLazyBoolYes)
252 return true;
253 else
Greg Clayton576d8832011-03-22 04:00:09 +0000254 return false;
255}
256
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
258 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
259 m_prepare_for_reg_writing_reply = eLazyBoolNo;
260
261 StringExtractorGDBRemote response;
262 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
263 false) == PacketResult::Success) {
264 if (response.IsOKResponse())
265 m_prepare_for_reg_writing_reply = eLazyBoolYes;
266 }
267 }
268 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
269 return true;
270 else
271 return false;
272}
273
274void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
275 if (did_exec == false) {
276 // Hard reset everything, this is when we first connect to a GDB server
277 m_supports_not_sending_acks = eLazyBoolCalculate;
278 m_supports_thread_suffix = eLazyBoolCalculate;
279 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
280 m_supports_vCont_c = eLazyBoolCalculate;
281 m_supports_vCont_C = eLazyBoolCalculate;
282 m_supports_vCont_s = eLazyBoolCalculate;
283 m_supports_vCont_S = eLazyBoolCalculate;
284 m_supports_p = eLazyBoolCalculate;
285 m_supports_x = eLazyBoolCalculate;
286 m_supports_QSaveRegisterState = eLazyBoolCalculate;
287 m_qHostInfo_is_valid = eLazyBoolCalculate;
288 m_curr_pid_is_valid = eLazyBoolCalculate;
289 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
290 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
291 m_supports_memory_region_info = eLazyBoolCalculate;
292 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
293 m_attach_or_wait_reply = eLazyBoolCalculate;
294 m_avoid_g_packets = eLazyBoolCalculate;
295 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
296 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
297 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
298 m_supports_qXfer_features_read = eLazyBoolCalculate;
299 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
300 m_supports_qProcessInfoPID = true;
301 m_supports_qfProcessInfo = true;
302 m_supports_qUserName = true;
303 m_supports_qGroupName = true;
304 m_supports_qThreadStopInfo = true;
305 m_supports_z0 = true;
306 m_supports_z1 = true;
307 m_supports_z2 = true;
308 m_supports_z3 = true;
309 m_supports_z4 = true;
310 m_supports_QEnvironment = true;
311 m_supports_QEnvironmentHexEncoded = true;
312 m_supports_qSymbol = true;
313 m_qSymbol_requests_done = false;
314 m_supports_qModuleInfo = true;
315 m_host_arch.Clear();
316 m_os_version_major = UINT32_MAX;
317 m_os_version_minor = UINT32_MAX;
318 m_os_version_update = UINT32_MAX;
319 m_os_build.clear();
320 m_os_kernel.clear();
321 m_hostname.clear();
322 m_gdb_server_name.clear();
323 m_gdb_server_version = UINT32_MAX;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000324 m_default_packet_timeout = seconds(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 m_max_packet_size = 0;
326 m_qSupported_response.clear();
327 m_supported_async_json_packets_is_valid = false;
328 m_supported_async_json_packets_sp.reset();
Pavel Labath2f1fbae2016-09-08 10:07:04 +0000329 m_supports_jModulesInfo = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330 }
331
332 // These flags should be reset when we first connect to a GDB server
333 // and when our inferior process execs
334 m_qProcessInfo_is_valid = eLazyBoolCalculate;
335 m_process_arch.Clear();
336}
337
338void GDBRemoteCommunicationClient::GetRemoteQSupported() {
339 // Clear out any capabilities we expect to see in the qSupported response
340 m_supports_qXfer_auxv_read = eLazyBoolNo;
341 m_supports_qXfer_libraries_read = eLazyBoolNo;
342 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
343 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
344 m_supports_qXfer_features_read = eLazyBoolNo;
345 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
346 // not, we assume no limit
347
348 // build the qSupported packet
349 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
350 StreamString packet;
351 packet.PutCString("qSupported");
352 for (uint32_t i = 0; i < features.size(); ++i) {
353 packet.PutCString(i == 0 ? ":" : ";");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000354 packet.PutCString(features[i]);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 }
356
357 StringExtractorGDBRemote response;
Zachary Turnerc1564272016-11-16 21:15:24 +0000358 if (SendPacketAndWaitForResponse(packet.GetString(), response,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 /*send_async=*/false) ==
360 PacketResult::Success) {
361 const char *response_cstr = response.GetStringRef().c_str();
362
363 // Hang on to the qSupported packet, so that platforms can do custom
364 // configuration of the transport before attaching/launching the
365 // process.
366 m_qSupported_response = response_cstr;
367
368 if (::strstr(response_cstr, "qXfer:auxv:read+"))
369 m_supports_qXfer_auxv_read = eLazyBoolYes;
370 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
371 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
372 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
373 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
374 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
375 }
376 if (::strstr(response_cstr, "qXfer:libraries:read+"))
377 m_supports_qXfer_libraries_read = eLazyBoolYes;
378 if (::strstr(response_cstr, "qXfer:features:read+"))
379 m_supports_qXfer_features_read = eLazyBoolYes;
380
381 // Look for a list of compressions in the features list e.g.
382 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
383 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
384 if (features_list) {
385 const char *compressions =
386 ::strstr(features_list, "SupportedCompressions=");
387 if (compressions) {
388 std::vector<std::string> supported_compressions;
389 compressions += sizeof("SupportedCompressions=") - 1;
390 const char *end_of_compressions = strchr(compressions, ';');
391 if (end_of_compressions == NULL) {
392 end_of_compressions = strchr(compressions, '\0');
393 }
394 const char *current_compression = compressions;
395 while (current_compression < end_of_compressions) {
396 const char *next_compression_name = strchr(current_compression, ',');
397 const char *end_of_this_word = next_compression_name;
398 if (next_compression_name == NULL ||
399 end_of_compressions < next_compression_name) {
400 end_of_this_word = end_of_compressions;
401 }
402
403 if (end_of_this_word) {
404 if (end_of_this_word == current_compression) {
405 current_compression++;
406 } else {
407 std::string this_compression(
408 current_compression, end_of_this_word - current_compression);
409 supported_compressions.push_back(this_compression);
410 current_compression = end_of_this_word + 1;
411 }
412 } else {
413 supported_compressions.push_back(current_compression);
414 current_compression = end_of_compressions;
415 }
416 }
417
418 if (supported_compressions.size() > 0) {
419 MaybeEnableCompression(supported_compressions);
420 }
421 }
422 }
423
424 if (::strstr(response_cstr, "qEcho"))
425 m_supports_qEcho = eLazyBoolYes;
426 else
427 m_supports_qEcho = eLazyBoolNo;
428
Eugene Zemtsov7993cc52017-03-07 21:34:40 +0000429 if (::strstr(response_cstr, "QPassSignals+"))
430 m_supports_QPassSignals = eLazyBoolYes;
431 else
432 m_supports_QPassSignals = eLazyBoolNo;
433
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
435 if (packet_size_str) {
436 StringExtractorGDBRemote packet_response(packet_size_str +
437 strlen("PacketSize="));
438 m_max_packet_size =
439 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
440 if (m_max_packet_size == 0) {
441 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
442 Log *log(
443 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
444 if (log)
445 log->Printf("Garbled PacketSize spec in qSupported response");
446 }
447 }
448 }
449}
450
451bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
452 if (m_supports_thread_suffix == eLazyBoolCalculate) {
453 StringExtractorGDBRemote response;
454 m_supports_thread_suffix = eLazyBoolNo;
455 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
456 false) == PacketResult::Success) {
457 if (response.IsOKResponse())
458 m_supports_thread_suffix = eLazyBoolYes;
459 }
460 }
461 return m_supports_thread_suffix;
462}
463bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
464 if (m_supports_vCont_c == eLazyBoolCalculate) {
465 StringExtractorGDBRemote response;
466 m_supports_vCont_any = eLazyBoolNo;
467 m_supports_vCont_all = eLazyBoolNo;
468 m_supports_vCont_c = eLazyBoolNo;
469 m_supports_vCont_C = eLazyBoolNo;
470 m_supports_vCont_s = eLazyBoolNo;
471 m_supports_vCont_S = eLazyBoolNo;
472 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
473 PacketResult::Success) {
474 const char *response_cstr = response.GetStringRef().c_str();
475 if (::strstr(response_cstr, ";c"))
476 m_supports_vCont_c = eLazyBoolYes;
477
478 if (::strstr(response_cstr, ";C"))
479 m_supports_vCont_C = eLazyBoolYes;
480
481 if (::strstr(response_cstr, ";s"))
482 m_supports_vCont_s = eLazyBoolYes;
483
484 if (::strstr(response_cstr, ";S"))
485 m_supports_vCont_S = eLazyBoolYes;
486
487 if (m_supports_vCont_c == eLazyBoolYes &&
488 m_supports_vCont_C == eLazyBoolYes &&
489 m_supports_vCont_s == eLazyBoolYes &&
490 m_supports_vCont_S == eLazyBoolYes) {
491 m_supports_vCont_all = eLazyBoolYes;
492 }
493
494 if (m_supports_vCont_c == eLazyBoolYes ||
495 m_supports_vCont_C == eLazyBoolYes ||
496 m_supports_vCont_s == eLazyBoolYes ||
497 m_supports_vCont_S == eLazyBoolYes) {
498 m_supports_vCont_any = eLazyBoolYes;
499 }
500 }
501 }
502
503 switch (flavor) {
504 case 'a':
505 return m_supports_vCont_any;
506 case 'A':
507 return m_supports_vCont_all;
508 case 'c':
509 return m_supports_vCont_c;
510 case 'C':
511 return m_supports_vCont_C;
512 case 's':
513 return m_supports_vCont_s;
514 case 'S':
515 return m_supports_vCont_S;
516 default:
517 break;
518 }
519 return false;
520}
521
Pavel Labath4b6f9592016-08-18 08:30:03 +0000522GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
524 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
525 bool send_async) {
526 Lock lock(*this, send_async);
527 if (!lock) {
528 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
529 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
530 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
531 "for %s packet.",
Zachary Turnerc1564272016-11-16 21:15:24 +0000532 __FUNCTION__, payload.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533 return PacketResult::ErrorNoSequenceLock;
534 }
Pavel Labath5c95ee42016-08-30 13:56:11 +0000535
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536 if (GetThreadSuffixSupported())
537 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
538 else {
539 if (!SetCurrentThread(tid))
540 return PacketResult::ErrorSendFailed;
541 }
Pavel Labath4b6f9592016-08-18 08:30:03 +0000542
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
Pavel Labath4b6f9592016-08-18 08:30:03 +0000544}
545
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000546// Check if the target supports 'p' packet. It sends out a 'p'
547// packet and checks the response. A normal packet will tell us
548// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000549//
550// Takes a valid thread ID because p needs to apply to a thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
552 if (m_supports_p == eLazyBoolCalculate) {
553 m_supports_p = eLazyBoolNo;
554 StreamString payload;
555 payload.PutCString("p0");
556 StringExtractorGDBRemote response;
557 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
558 response, false) ==
559 PacketResult::Success &&
560 response.IsNormalResponse()) {
561 m_supports_p = eLazyBoolYes;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000562 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 }
564 return m_supports_p;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000565}
Greg Clayton576d8832011-03-22 04:00:09 +0000566
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
568 // Get information on all threads at one using the "jThreadsInfo" packet
569 StructuredData::ObjectSP object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000570
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 if (m_supports_jThreadsInfo) {
572 StringExtractorGDBRemote response;
573 response.SetResponseValidatorToJSON();
574 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
575 PacketResult::Success) {
576 if (response.IsUnsupportedResponse()) {
577 m_supports_jThreadsInfo = false;
578 } else if (!response.Empty()) {
579 object_sp = StructuredData::ParseJSON(response.GetStringRef());
580 }
Greg Clayton358cf1e2015-06-25 21:46:34 +0000581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 }
583 return object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000584}
585
Kate Stoneb9c1b512016-09-06 20:57:50 +0000586bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
587 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
588 StringExtractorGDBRemote response;
589 m_supports_jThreadExtendedInfo = eLazyBoolNo;
590 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
591 PacketResult::Success) {
592 if (response.IsOKResponse()) {
593 m_supports_jThreadExtendedInfo = eLazyBoolYes;
594 }
Jason Molenda705b1802014-06-13 02:37:02 +0000595 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596 }
597 return m_supports_jThreadExtendedInfo;
Jason Molenda705b1802014-06-13 02:37:02 +0000598}
599
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +0000600void GDBRemoteCommunicationClient::EnableErrorStringInPacket() {
601 if (m_supports_error_string_reply == eLazyBoolCalculate) {
602 StringExtractorGDBRemote response;
603 // We try to enable error strings in remote packets
604 // but if we fail, we just work in the older way.
605 m_supports_error_string_reply = eLazyBoolNo;
606 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response, false) ==
607 PacketResult::Success) {
608 if (response.IsOKResponse()) {
609 m_supports_error_string_reply = eLazyBoolYes;
610 }
611 }
612 }
613}
614
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
616 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
617 StringExtractorGDBRemote response;
618 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
619 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
620 response,
621 false) == PacketResult::Success) {
622 if (response.IsOKResponse()) {
623 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
624 }
Jason Molenda20ee21b2015-07-10 23:15:22 +0000625 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000626 }
627 return m_supports_jLoadedDynamicLibrariesInfos;
Jason Molenda20ee21b2015-07-10 23:15:22 +0000628}
629
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
631 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
632 StringExtractorGDBRemote response;
633 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
634 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
635 PacketResult::Success) {
636 if (response.IsOKResponse()) {
637 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
638 }
Jason Molenda37397352016-07-22 00:17:55 +0000639 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000640 }
641 return m_supports_jGetSharedCacheInfo;
Jason Molenda37397352016-07-22 00:17:55 +0000642}
643
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644bool GDBRemoteCommunicationClient::GetxPacketSupported() {
645 if (m_supports_x == eLazyBoolCalculate) {
646 StringExtractorGDBRemote response;
647 m_supports_x = eLazyBoolNo;
648 char packet[256];
649 snprintf(packet, sizeof(packet), "x0,0");
650 if (SendPacketAndWaitForResponse(packet, response, false) ==
651 PacketResult::Success) {
652 if (response.IsOKResponse())
653 m_supports_x = eLazyBoolYes;
Jason Molendabdc4f122014-05-06 02:59:39 +0000654 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000655 }
656 return m_supports_x;
Jason Molendabdc4f122014-05-06 02:59:39 +0000657}
658
Greg Clayton3dedae12013-12-06 21:45:27 +0000659GDBRemoteCommunicationClient::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000660GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
661 const char *payload_prefix, std::string &response_string) {
662 Lock lock(*this, false);
663 if (!lock) {
664 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
665 GDBR_LOG_PACKETS));
666 if (log)
667 log->Printf("error: failed to get packet sequence mutex, not sending "
668 "packets with prefix '%s'",
669 payload_prefix);
670 return PacketResult::ErrorNoSequenceLock;
671 }
672
673 response_string = "";
674 std::string payload_prefix_str(payload_prefix);
675 unsigned int response_size = 0x1000;
676 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
677 response_size = GetRemoteMaxPacketSize();
678 }
679
680 for (unsigned int offset = 0; true; offset += response_size) {
681 StringExtractorGDBRemote this_response;
682 // Construct payload
683 char sizeDescriptor[128];
684 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
685 response_size);
686 PacketResult result = SendPacketAndWaitForResponseNoLock(
687 payload_prefix_str + sizeDescriptor, this_response);
688 if (result != PacketResult::Success)
689 return result;
690
691 const std::string &this_string = this_response.GetStringRef();
692
693 // Check for m or l as first character; l seems to mean this is the last
694 // chunk
695 char first_char = *this_string.c_str();
696 if (first_char != 'm' && first_char != 'l') {
697 return PacketResult::ErrorReplyInvalid;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000698 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 // Concatenate the result so far (skipping 'm' or 'l')
700 response_string.append(this_string, 1, std::string::npos);
701 if (first_char == 'l')
702 // We're done
703 return PacketResult::Success;
704 }
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000705}
706
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
708 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
709 return m_curr_pid;
Jaydeep Patil1142f832015-08-13 03:46:36 +0000710
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 // First try to retrieve the pid via the qProcessInfo request.
712 GetCurrentProcessInfo(allow_lazy);
713 if (m_curr_pid_is_valid == eLazyBoolYes) {
714 // We really got it.
715 return m_curr_pid;
716 } else {
717 // If we don't get a response for qProcessInfo, check if $qC gives us a
718 // result.
719 // $qC only returns a real process id on older debugserver and lldb-platform
720 // stubs.
721 // The gdb remote protocol documents $qC as returning the thread id, which
722 // newer
723 // debugserver and lldb-gdbserver stubs return correctly.
Greg Clayton576d8832011-03-22 04:00:09 +0000724 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000725 if (SendPacketAndWaitForResponse("qC", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000726 PacketResult::Success) {
727 if (response.GetChar() == 'Q') {
728 if (response.GetChar() == 'C') {
729 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
730 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
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 }
Greg Clayton576d8832011-03-22 04:00:09 +0000736 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737
738 // If we don't get a response for $qC, check if $qfThreadID gives us a
739 // result.
740 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
741 std::vector<lldb::tid_t> thread_ids;
742 bool sequence_mutex_unavailable;
743 size_t size;
744 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
745 if (size && sequence_mutex_unavailable == false) {
746 m_curr_pid = thread_ids.front();
747 m_curr_pid_is_valid = eLazyBoolYes;
748 return m_curr_pid;
749 }
Greg Clayton576d8832011-03-22 04:00:09 +0000750 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751 }
752
753 return LLDB_INVALID_PROCESS_ID;
Greg Clayton576d8832011-03-22 04:00:09 +0000754}
755
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
757 error_str.clear();
758 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000759 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
760 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000761 if (response.IsOKResponse())
762 return true;
763 if (response.GetChar() == 'E') {
764 // A string the describes what failed when launching...
765 error_str = response.GetStringRef().substr(1);
766 } else {
767 error_str.assign("unknown error occurred launching process");
Greg Claytonfbb76342013-11-20 21:07:01 +0000768 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000769 } else {
770 error_str.assign("timed out waiting for app to launch");
771 }
772 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000773}
774
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775int GDBRemoteCommunicationClient::SendArgumentsPacket(
776 const ProcessLaunchInfo &launch_info) {
777 // Since we don't get the send argv0 separate from the executable path, we
778 // need to
779 // make sure to use the actual executable path found in the launch_info...
780 std::vector<const char *> argv;
781 FileSpec exe_file = launch_info.GetExecutableFile();
782 std::string exe_path;
783 const char *arg = NULL;
784 const Args &launch_args = launch_info.GetArguments();
785 if (exe_file)
786 exe_path = exe_file.GetPath(false);
787 else {
788 arg = launch_args.GetArgumentAtIndex(0);
789 if (arg)
790 exe_path = arg;
791 }
792 if (!exe_path.empty()) {
793 argv.push_back(exe_path.c_str());
794 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL;
795 ++i) {
796 if (arg)
797 argv.push_back(arg);
Greg Clayton576d8832011-03-22 04:00:09 +0000798 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 }
800 if (!argv.empty()) {
Vince Harrone0be4252015-02-06 18:32:57 +0000801 StreamString packet;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 packet.PutChar('A');
803 for (size_t i = 0, n = argv.size(); i < n; ++i) {
804 arg = argv[i];
805 const int arg_len = strlen(arg);
806 if (i > 0)
807 packet.PutChar(',');
808 packet.Printf("%i,%i,", arg_len * 2, (int)i);
809 packet.PutBytesAsRawHex8(arg, arg_len);
810 }
811
Vince Harrone0be4252015-02-06 18:32:57 +0000812 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000813 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
814 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000815 if (response.IsOKResponse())
Vince Harrone0be4252015-02-06 18:32:57 +0000816 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000817 uint8_t error = response.GetError();
818 if (error)
Johnny Chen64637202012-05-23 21:09:52 +0000819 return error;
820 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821 }
822 return -1;
823}
Johnny Chen64637202012-05-23 21:09:52 +0000824
Kate Stoneb9c1b512016-09-06 20:57:50 +0000825int GDBRemoteCommunicationClient::SendEnvironmentPacket(
826 char const *name_equal_value) {
827 if (name_equal_value && name_equal_value[0]) {
828 StreamString packet;
829 bool send_hex_encoding = false;
830 for (const char *p = name_equal_value;
831 *p != '\0' && send_hex_encoding == false; ++p) {
832 if (isprint(*p)) {
833 switch (*p) {
834 case '$':
835 case '#':
836 case '*':
837 case '}':
838 send_hex_encoding = true;
839 break;
840 default:
841 break;
Johnny Chen64637202012-05-23 21:09:52 +0000842 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843 } else {
844 // We have non printable characters, lets hex encode this...
845 send_hex_encoding = true;
846 }
Johnny Chen64637202012-05-23 21:09:52 +0000847 }
848
Greg Claytonfbb76342013-11-20 21:07:01 +0000849 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 if (send_hex_encoding) {
851 if (m_supports_QEnvironmentHexEncoded) {
852 packet.PutCString("QEnvironmentHexEncoded:");
853 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000854 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
855 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000856 if (response.IsOKResponse())
857 return 0;
858 uint8_t error = response.GetError();
859 if (error)
860 return error;
861 if (response.IsUnsupportedResponse())
862 m_supports_QEnvironmentHexEncoded = false;
863 }
864 }
865
866 } else if (m_supports_QEnvironment) {
867 packet.Printf("QEnvironment:%s", name_equal_value);
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000868 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
869 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870 if (response.IsOKResponse())
871 return 0;
872 uint8_t error = response.GetError();
873 if (error)
874 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +0000875 if (response.IsUnsupportedResponse())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000876 m_supports_QEnvironment = false;
877 }
Greg Claytonfbb76342013-11-20 21:07:01 +0000878 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879 }
880 return -1;
Greg Claytonfbb76342013-11-20 21:07:01 +0000881}
882
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
884 if (arch && arch[0]) {
885 StreamString packet;
886 packet.Printf("QLaunchArch:%s", arch);
887 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000888 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
889 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000890 if (response.IsOKResponse())
891 return 0;
892 uint8_t error = response.GetError();
893 if (error)
894 return error;
895 }
896 }
897 return -1;
898}
Chaoren Lind3173f32015-05-29 19:52:29 +0000899
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
901 char const *data, bool *was_supported) {
902 if (data && *data != '\0') {
903 StreamString packet;
904 packet.Printf("QSetProcessEvent:%s", data);
905 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000906 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
907 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 if (response.IsOKResponse()) {
909 if (was_supported)
910 *was_supported = true;
911 return 0;
912 } else if (response.IsUnsupportedResponse()) {
913 if (was_supported)
914 *was_supported = false;
915 return -1;
916 } else {
917 uint8_t error = response.GetError();
918 if (was_supported)
919 *was_supported = true;
920 if (error)
921 return error;
922 }
923 }
924 }
925 return -1;
926}
927
928bool GDBRemoteCommunicationClient::GetOSVersion(uint32_t &major,
929 uint32_t &minor,
930 uint32_t &update) {
931 if (GetHostInfo()) {
932 if (m_os_version_major != UINT32_MAX) {
933 major = m_os_version_major;
934 minor = m_os_version_minor;
935 update = m_os_version_update;
936 return true;
937 }
938 }
939 return false;
940}
941
942bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
943 if (GetHostInfo()) {
944 if (!m_os_build.empty()) {
945 s = m_os_build;
946 return true;
947 }
948 }
949 s.clear();
950 return false;
951}
952
953bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
954 if (GetHostInfo()) {
955 if (!m_os_kernel.empty()) {
956 s = m_os_kernel;
957 return true;
958 }
959 }
960 s.clear();
961 return false;
962}
963
964bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
965 if (GetHostInfo()) {
966 if (!m_hostname.empty()) {
967 s = m_hostname;
968 return true;
969 }
970 }
971 s.clear();
972 return false;
973}
974
975ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
976 if (GetHostInfo())
977 return m_host_arch;
978 return ArchSpec();
979}
980
981const lldb_private::ArchSpec &
982GDBRemoteCommunicationClient::GetProcessArchitecture() {
983 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
984 GetCurrentProcessInfo();
985 return m_process_arch;
986}
987
988bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
989 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
990 m_gdb_server_name.clear();
991 m_gdb_server_version = 0;
992 m_qGDBServerVersion_is_valid = eLazyBoolNo;
993
994 StringExtractorGDBRemote response;
995 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
996 PacketResult::Success) {
997 if (response.IsNormalResponse()) {
998 llvm::StringRef name, value;
999 bool success = false;
1000 while (response.GetNameColonValue(name, value)) {
1001 if (name.equals("name")) {
1002 success = true;
1003 m_gdb_server_name = value;
1004 } else if (name.equals("version")) {
1005 llvm::StringRef major, minor;
1006 std::tie(major, minor) = value.split('.');
1007 if (!major.getAsInteger(0, m_gdb_server_version))
1008 success = true;
1009 }
Greg Clayton576d8832011-03-22 04:00:09 +00001010 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 if (success)
1012 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1013 }
Greg Clayton576d8832011-03-22 04:00:09 +00001014 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 }
1016 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001017}
1018
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019void GDBRemoteCommunicationClient::MaybeEnableCompression(
1020 std::vector<std::string> supported_compressions) {
1021 CompressionType avail_type = CompressionType::None;
1022 std::string avail_name;
1023
1024#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001025 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026 for (auto compression : supported_compressions) {
1027 if (compression == "lzfse") {
1028 avail_type = CompressionType::LZFSE;
1029 avail_name = compression;
1030 break;
1031 }
1032 }
1033 }
1034#endif
1035
1036#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001037 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001038 for (auto compression : supported_compressions) {
1039 if (compression == "zlib-deflate") {
1040 avail_type = CompressionType::ZlibDeflate;
1041 avail_name = compression;
1042 break;
1043 }
1044 }
1045 }
1046#endif
1047
1048#if defined(HAVE_LIBZ)
1049 if (avail_type == CompressionType::None) {
1050 for (auto compression : supported_compressions) {
1051 if (compression == "zlib-deflate") {
1052 avail_type = CompressionType::ZlibDeflate;
1053 avail_name = compression;
1054 break;
1055 }
1056 }
1057 }
1058#endif
1059
1060#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001061 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062 for (auto compression : supported_compressions) {
1063 if (compression == "lz4") {
1064 avail_type = CompressionType::LZ4;
1065 avail_name = compression;
1066 break;
1067 }
1068 }
1069 }
1070#endif
1071
1072#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001073 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074 for (auto compression : supported_compressions) {
1075 if (compression == "lzma") {
1076 avail_type = CompressionType::LZMA;
1077 avail_name = compression;
1078 break;
1079 }
1080 }
1081 }
1082#endif
1083
1084 if (avail_type != CompressionType::None) {
Greg Clayton576d8832011-03-22 04:00:09 +00001085 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086 std::string packet = "QEnableCompression:type:" + avail_name + ";";
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001087 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088 PacketResult::Success)
1089 return;
1090
1091 if (response.IsOKResponse()) {
1092 m_compression_type = avail_type;
Greg Clayton576d8832011-03-22 04:00:09 +00001093 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001094 }
Greg Clayton576d8832011-03-22 04:00:09 +00001095}
Greg Clayton32e0a752011-03-30 18:16:51 +00001096
Kate Stoneb9c1b512016-09-06 20:57:50 +00001097const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1098 if (GetGDBServerVersion()) {
1099 if (!m_gdb_server_name.empty())
1100 return m_gdb_server_name.c_str();
1101 }
1102 return NULL;
1103}
1104
1105uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1106 if (GetGDBServerVersion())
1107 return m_gdb_server_version;
1108 return 0;
1109}
1110
1111bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1112 StringExtractorGDBRemote response;
1113 if (SendPacketAndWaitForResponse("qC", response, false) !=
1114 PacketResult::Success)
1115 return false;
1116
1117 if (!response.IsNormalResponse())
1118 return false;
1119
1120 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1121 tid = response.GetHexMaxU32(true, -1);
1122
1123 return true;
1124}
1125
1126bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1127 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1128
1129 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1130 m_qHostInfo_is_valid = eLazyBoolNo;
Jim Ingham106d0282014-06-25 02:32:56 +00001131 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001132 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1133 PacketResult::Success) {
1134 if (response.IsNormalResponse()) {
Zachary Turner54695a32016-08-29 19:58:14 +00001135 llvm::StringRef name;
1136 llvm::StringRef value;
Jason Molenda89c37492014-01-27 22:23:20 +00001137 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1138 uint32_t sub = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139 std::string arch_name;
1140 std::string os_name;
1141 std::string vendor_name;
1142 std::string triple;
1143 std::string distribution_id;
1144 uint32_t pointer_byte_size = 0;
1145 ByteOrder byte_order = eByteOrderInvalid;
1146 uint32_t num_keys_decoded = 0;
1147 while (response.GetNameColonValue(name, value)) {
1148 if (name.equals("cputype")) {
1149 // exception type in big endian hex
1150 if (!value.getAsInteger(0, cpu))
1151 ++num_keys_decoded;
1152 } else if (name.equals("cpusubtype")) {
1153 // exception count in big endian hex
1154 if (!value.getAsInteger(0, sub))
1155 ++num_keys_decoded;
1156 } else if (name.equals("arch")) {
1157 arch_name = value;
1158 ++num_keys_decoded;
1159 } else if (name.equals("triple")) {
1160 StringExtractor extractor(value);
1161 extractor.GetHexByteString(triple);
1162 ++num_keys_decoded;
1163 } else if (name.equals("distribution_id")) {
1164 StringExtractor extractor(value);
1165 extractor.GetHexByteString(distribution_id);
1166 ++num_keys_decoded;
1167 } else if (name.equals("os_build")) {
1168 StringExtractor extractor(value);
1169 extractor.GetHexByteString(m_os_build);
1170 ++num_keys_decoded;
1171 } else if (name.equals("hostname")) {
1172 StringExtractor extractor(value);
1173 extractor.GetHexByteString(m_hostname);
1174 ++num_keys_decoded;
1175 } else if (name.equals("os_kernel")) {
1176 StringExtractor extractor(value);
1177 extractor.GetHexByteString(m_os_kernel);
1178 ++num_keys_decoded;
1179 } else if (name.equals("ostype")) {
1180 os_name = value;
1181 ++num_keys_decoded;
1182 } else if (name.equals("vendor")) {
1183 vendor_name = value;
1184 ++num_keys_decoded;
1185 } else if (name.equals("endian")) {
1186 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1187 .Case("little", eByteOrderLittle)
1188 .Case("big", eByteOrderBig)
1189 .Case("pdp", eByteOrderPDP)
1190 .Default(eByteOrderInvalid);
1191 if (byte_order != eByteOrderInvalid)
1192 ++num_keys_decoded;
1193 } else if (name.equals("ptrsize")) {
1194 if (!value.getAsInteger(0, pointer_byte_size))
1195 ++num_keys_decoded;
1196 } else if (name.equals("os_version") ||
1197 name.equals(
1198 "version")) // Older debugserver binaries used the
1199 // "version" key instead of
1200 // "os_version"...
1201 {
Zachary Turner6fa7681b2016-09-17 02:00:02 +00001202 Args::StringToVersion(value, m_os_version_major, m_os_version_minor,
1203 m_os_version_update);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 if (m_os_version_major != UINT32_MAX)
1205 ++num_keys_decoded;
1206 } else if (name.equals("watchpoint_exceptions_received")) {
1207 m_watchpoints_trigger_after_instruction =
1208 llvm::StringSwitch<LazyBool>(value)
1209 .Case("before", eLazyBoolNo)
1210 .Case("after", eLazyBoolYes)
1211 .Default(eLazyBoolCalculate);
1212 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1213 ++num_keys_decoded;
1214 } else if (name.equals("default_packet_timeout")) {
Pavel Labath3aa04912016-10-31 17:19:42 +00001215 uint32_t timeout_seconds;
1216 if (!value.getAsInteger(0, timeout_seconds)) {
Pavel Labath1eff73c2016-11-24 10:54:49 +00001217 m_default_packet_timeout = seconds(timeout_seconds);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218 SetPacketTimeout(m_default_packet_timeout);
1219 ++num_keys_decoded;
Greg Clayton32e0a752011-03-30 18:16:51 +00001220 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001221 }
Jason Molenda89c37492014-01-27 22:23:20 +00001222 }
1223
Kate Stoneb9c1b512016-09-06 20:57:50 +00001224 if (num_keys_decoded > 0)
1225 m_qHostInfo_is_valid = eLazyBoolYes;
1226
1227 if (triple.empty()) {
1228 if (arch_name.empty()) {
1229 if (cpu != LLDB_INVALID_CPUTYPE) {
1230 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1231 if (pointer_byte_size) {
1232 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1233 }
1234 if (byte_order != eByteOrderInvalid) {
1235 assert(byte_order == m_host_arch.GetByteOrder());
1236 }
1237
1238 if (!vendor_name.empty())
1239 m_host_arch.GetTriple().setVendorName(
1240 llvm::StringRef(vendor_name));
1241 if (!os_name.empty())
1242 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Jason Molenda89c37492014-01-27 22:23:20 +00001243 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001244 } else {
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001245 std::string triple;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001246 triple += arch_name;
1247 if (!vendor_name.empty() || !os_name.empty()) {
1248 triple += '-';
1249 if (vendor_name.empty())
1250 triple += "unknown";
1251 else
1252 triple += vendor_name;
1253 triple += '-';
1254 if (os_name.empty())
1255 triple += "unknown";
1256 else
1257 triple += os_name;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001258 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001259 m_host_arch.SetTriple(triple.c_str());
Todd Fialac540dd02014-08-26 18:21:02 +00001260
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261 llvm::Triple &host_triple = m_host_arch.GetTriple();
1262 if (host_triple.getVendor() == llvm::Triple::Apple &&
1263 host_triple.getOS() == llvm::Triple::Darwin) {
1264 switch (m_host_arch.GetMachine()) {
1265 case llvm::Triple::aarch64:
1266 case llvm::Triple::arm:
1267 case llvm::Triple::thumb:
1268 host_triple.setOS(llvm::Triple::IOS);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001269 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 default:
1271 host_triple.setOS(llvm::Triple::MacOSX);
1272 break;
1273 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001274 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001275 if (pointer_byte_size) {
1276 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1277 }
1278 if (byte_order != eByteOrderInvalid) {
1279 assert(byte_order == m_host_arch.GetByteOrder());
1280 }
1281 }
1282 } else {
1283 m_host_arch.SetTriple(triple.c_str());
1284 if (pointer_byte_size) {
1285 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1286 }
1287 if (byte_order != eByteOrderInvalid) {
1288 assert(byte_order == m_host_arch.GetByteOrder());
1289 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001290
Kate Stoneb9c1b512016-09-06 20:57:50 +00001291 if (log)
1292 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1293 "architecture as %s, triple as %s from triple text %s",
1294 __FUNCTION__, m_host_arch.GetArchitectureName()
1295 ? m_host_arch.GetArchitectureName()
1296 : "<null-arch-name>",
1297 m_host_arch.GetTriple().getTriple().c_str(),
1298 triple.c_str());
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001299 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 if (!distribution_id.empty())
1301 m_host_arch.SetDistributionId(distribution_id.c_str());
1302 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001303 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304 }
1305 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Claytonadc00cb2011-05-20 23:38:13 +00001306}
Greg Clayton37a0a242012-04-11 00:24:49 +00001307
Kate Stoneb9c1b512016-09-06 20:57:50 +00001308int GDBRemoteCommunicationClient::SendAttach(
1309 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1310 if (pid != LLDB_INVALID_PROCESS_ID) {
1311 char packet[64];
1312 const int packet_len =
1313 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001314 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001315 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001316 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 PacketResult::Success) {
1318 if (response.IsErrorResponse())
1319 return response.GetError();
1320 return 0;
1321 }
1322 }
1323 return -1;
1324}
1325
1326int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1327 size_t data_len) {
1328 StreamString packet;
1329 packet.PutCString("I");
1330 packet.PutBytesAsRawHex8(data, data_len);
1331 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001332 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1333 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001334 return 0;
1335 }
1336 return response.GetError();
1337}
1338
1339const lldb_private::ArchSpec &
1340GDBRemoteCommunicationClient::GetHostArchitecture() {
1341 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1342 GetHostInfo();
1343 return m_host_arch;
1344}
1345
Pavel Labath1eff73c2016-11-24 10:54:49 +00001346seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001347 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1348 GetHostInfo();
1349 return m_default_packet_timeout;
1350}
1351
1352addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1353 uint32_t permissions) {
1354 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1355 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1356 char packet[64];
1357 const int packet_len = ::snprintf(
1358 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1359 permissions & lldb::ePermissionsReadable ? "r" : "",
1360 permissions & lldb::ePermissionsWritable ? "w" : "",
1361 permissions & lldb::ePermissionsExecutable ? "x" : "");
1362 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001363 UNUSED_IF_ASSERT_DISABLED(packet_len);
Pavel Labath83082a02016-08-18 14:33:55 +00001364 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001365 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001366 PacketResult::Success) {
1367 if (response.IsUnsupportedResponse())
1368 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1369 else if (!response.IsErrorResponse())
1370 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1371 } else {
1372 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1373 }
1374 }
1375 return LLDB_INVALID_ADDRESS;
1376}
1377
1378bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1379 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1380 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1381 char packet[64];
1382 const int packet_len =
1383 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1384 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001385 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001386 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001387 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001388 PacketResult::Success) {
1389 if (response.IsUnsupportedResponse())
1390 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1391 else if (response.IsOKResponse())
1392 return true;
1393 } else {
1394 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1395 }
1396 }
1397 return false;
1398}
1399
Zachary Turner97206d52017-05-12 04:51:55 +00001400Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1401 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001402
1403 if (keep_stopped) {
1404 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1405 char packet[64];
1406 const int packet_len =
1407 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1408 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001409 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001410 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001411 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001412 PacketResult::Success &&
1413 response.IsOKResponse()) {
1414 m_supports_detach_stay_stopped = eLazyBoolYes;
1415 } else {
1416 m_supports_detach_stay_stopped = eLazyBoolNo;
1417 }
1418 }
1419
1420 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1421 error.SetErrorString("Stays stopped not supported by this target.");
1422 return error;
1423 } else {
1424 StringExtractorGDBRemote response;
1425 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001426 SendPacketAndWaitForResponse("D1", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001427 if (packet_result != PacketResult::Success)
1428 error.SetErrorString("Sending extended disconnect packet failed.");
1429 }
1430 } else {
1431 StringExtractorGDBRemote response;
1432 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001433 SendPacketAndWaitForResponse("D", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001434 if (packet_result != PacketResult::Success)
1435 error.SetErrorString("Sending disconnect packet failed.");
1436 }
1437 return error;
1438}
1439
Zachary Turner97206d52017-05-12 04:51:55 +00001440Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001442 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 region_info.Clear();
1444
1445 if (m_supports_memory_region_info != eLazyBoolNo) {
1446 m_supports_memory_region_info = eLazyBoolYes;
1447 char packet[64];
1448 const int packet_len = ::snprintf(
1449 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1450 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001451 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001452 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001453 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454 PacketResult::Success) {
1455 llvm::StringRef name;
1456 llvm::StringRef value;
1457 addr_t addr_value = LLDB_INVALID_ADDRESS;
1458 bool success = true;
1459 bool saw_permissions = false;
1460 while (success && response.GetNameColonValue(name, value)) {
1461 if (name.equals("start")) {
1462 if (!value.getAsInteger(16, addr_value))
1463 region_info.GetRange().SetRangeBase(addr_value);
1464 } else if (name.equals("size")) {
1465 if (!value.getAsInteger(16, addr_value))
1466 region_info.GetRange().SetByteSize(addr_value);
1467 } else if (name.equals("permissions") &&
1468 region_info.GetRange().IsValid()) {
1469 saw_permissions = true;
1470 if (region_info.GetRange().Contains(addr)) {
1471 if (value.find('r') != llvm::StringRef::npos)
1472 region_info.SetReadable(MemoryRegionInfo::eYes);
1473 else
1474 region_info.SetReadable(MemoryRegionInfo::eNo);
1475
1476 if (value.find('w') != llvm::StringRef::npos)
1477 region_info.SetWritable(MemoryRegionInfo::eYes);
1478 else
1479 region_info.SetWritable(MemoryRegionInfo::eNo);
1480
1481 if (value.find('x') != llvm::StringRef::npos)
1482 region_info.SetExecutable(MemoryRegionInfo::eYes);
1483 else
1484 region_info.SetExecutable(MemoryRegionInfo::eNo);
1485
1486 region_info.SetMapped(MemoryRegionInfo::eYes);
1487 } else {
1488 // The reported region does not contain this address -- we're
1489 // looking at an unmapped page
1490 region_info.SetReadable(MemoryRegionInfo::eNo);
1491 region_info.SetWritable(MemoryRegionInfo::eNo);
1492 region_info.SetExecutable(MemoryRegionInfo::eNo);
1493 region_info.SetMapped(MemoryRegionInfo::eNo);
1494 }
1495 } else if (name.equals("name")) {
1496 StringExtractorGDBRemote name_extractor(value);
1497 std::string name;
1498 name_extractor.GetHexByteString(name);
1499 region_info.SetName(name.c_str());
1500 } else if (name.equals("error")) {
1501 StringExtractorGDBRemote error_extractor(value);
1502 std::string error_string;
1503 // Now convert the HEX bytes into a string value
1504 error_extractor.GetHexByteString(error_string);
1505 error.SetErrorString(error_string.c_str());
1506 }
1507 }
1508
Stephane Sezer48d14272017-03-31 18:00:48 +00001509 if (region_info.GetRange().IsValid()) {
1510 // We got a valid address range back but no permissions -- which means
1511 // this is an unmapped page
1512 if (!saw_permissions) {
1513 region_info.SetReadable(MemoryRegionInfo::eNo);
1514 region_info.SetWritable(MemoryRegionInfo::eNo);
1515 region_info.SetExecutable(MemoryRegionInfo::eNo);
1516 region_info.SetMapped(MemoryRegionInfo::eNo);
1517 }
1518 } else {
1519 // We got an invalid address range back
1520 error.SetErrorString("Server returned invalid range");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001521 }
1522 } else {
1523 m_supports_memory_region_info = eLazyBoolNo;
1524 }
1525 }
1526
1527 if (m_supports_memory_region_info == eLazyBoolNo) {
1528 error.SetErrorString("qMemoryRegionInfo is not supported");
1529 }
1530 if (error.Fail())
1531 region_info.Clear();
1532 return error;
1533}
1534
Zachary Turner97206d52017-05-12 04:51:55 +00001535Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1536 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001537
1538 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1539 num = m_num_supported_hardware_watchpoints;
1540 return error;
1541 }
1542
1543 // Set num to 0 first.
1544 num = 0;
1545 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1546 char packet[64];
1547 const int packet_len =
1548 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1549 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001550 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001551 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001552 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001553 PacketResult::Success) {
1554 m_supports_watchpoint_support_info = eLazyBoolYes;
1555 llvm::StringRef name;
1556 llvm::StringRef value;
1557 while (response.GetNameColonValue(name, value)) {
1558 if (name.equals("num")) {
1559 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1560 num = m_num_supported_hardware_watchpoints;
1561 }
1562 }
1563 } else {
1564 m_supports_watchpoint_support_info = eLazyBoolNo;
1565 }
1566 }
1567
1568 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1569 error.SetErrorString("qWatchpointSupportInfo is not supported");
1570 }
1571 return error;
1572}
1573
Zachary Turner97206d52017-05-12 04:51:55 +00001574lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001575 uint32_t &num, bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001576 Status error(GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001577 if (error.Success())
1578 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1579 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001580}
1581
Zachary Turner97206d52017-05-12 04:51:55 +00001582lldb_private::Status
Kate Stoneb9c1b512016-09-06 20:57:50 +00001583GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1584 bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001585 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001586 llvm::Triple::ArchType atype = arch.GetMachine();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001587
Kate Stoneb9c1b512016-09-06 20:57:50 +00001588 // we assume watchpoints will happen after running the relevant opcode
1589 // and we only want to override this behavior if we have explicitly
1590 // received a qHostInfo telling us otherwise
1591 if (m_qHostInfo_is_valid != eLazyBoolYes) {
Pavel Labathc51ad482017-10-27 17:02:32 +00001592 // On targets like MIPS and ppc64le, watchpoint exceptions are always
1593 // generated before the instruction is executed. The connected target
1594 // may not support qHostInfo or qWatchpointSupportInfo packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001595 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
Pavel Labathc51ad482017-10-27 17:02:32 +00001596 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el ||
1597 atype == llvm::Triple::ppc64le)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598 after = false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001599 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001600 after = true;
1601 } else {
Pavel Labathc51ad482017-10-27 17:02:32 +00001602 // For MIPS and ppc64le, set m_watchpoints_trigger_after_instruction to
1603 // eLazyBoolNo if it is not calculated before.
1604 if ((m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1605 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1606 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)) ||
1607 atype == llvm::Triple::ppc64le) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001608 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
Pavel Labathc51ad482017-10-27 17:02:32 +00001609 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001610
1611 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1612 }
1613 return error;
1614}
1615
1616int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1617 if (file_spec) {
1618 std::string path{file_spec.GetPath(false)};
1619 StreamString packet;
1620 packet.PutCString("QSetSTDIN:");
1621 packet.PutCStringAsRawHex8(path.c_str());
1622
1623 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001624 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1625 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001626 if (response.IsOKResponse())
1627 return 0;
1628 uint8_t error = response.GetError();
1629 if (error)
1630 return error;
1631 }
1632 }
1633 return -1;
1634}
1635
1636int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1637 if (file_spec) {
1638 std::string path{file_spec.GetPath(false)};
1639 StreamString packet;
1640 packet.PutCString("QSetSTDOUT:");
1641 packet.PutCStringAsRawHex8(path.c_str());
1642
1643 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001644 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1645 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001646 if (response.IsOKResponse())
1647 return 0;
1648 uint8_t error = response.GetError();
1649 if (error)
1650 return error;
1651 }
1652 }
1653 return -1;
1654}
1655
1656int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1657 if (file_spec) {
1658 std::string path{file_spec.GetPath(false)};
1659 StreamString packet;
1660 packet.PutCString("QSetSTDERR:");
1661 packet.PutCStringAsRawHex8(path.c_str());
1662
1663 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001664 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1665 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001666 if (response.IsOKResponse())
1667 return 0;
1668 uint8_t error = response.GetError();
1669 if (error)
1670 return error;
1671 }
1672 }
1673 return -1;
1674}
1675
1676bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1677 StringExtractorGDBRemote response;
1678 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1679 PacketResult::Success) {
1680 if (response.IsUnsupportedResponse())
1681 return false;
1682 if (response.IsErrorResponse())
1683 return false;
1684 std::string cwd;
1685 response.GetHexByteString(cwd);
Zachary Turner8c6b5462017-03-06 23:42:44 +00001686 working_dir.SetFile(cwd, false, GetHostArchitecture().GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001687 return !cwd.empty();
1688 }
1689 return false;
1690}
1691
1692int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1693 if (working_dir) {
1694 std::string path{working_dir.GetPath(false)};
1695 StreamString packet;
1696 packet.PutCString("QSetWorkingDir:");
1697 packet.PutCStringAsRawHex8(path.c_str());
1698
1699 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001700 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1701 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001702 if (response.IsOKResponse())
1703 return 0;
1704 uint8_t error = response.GetError();
1705 if (error)
1706 return error;
1707 }
1708 }
1709 return -1;
1710}
1711
1712int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1713 char packet[32];
1714 const int packet_len =
1715 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1716 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001717 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001718 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001719 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001720 PacketResult::Success) {
1721 if (response.IsOKResponse())
1722 return 0;
1723 uint8_t error = response.GetError();
1724 if (error)
1725 return error;
1726 }
1727 return -1;
1728}
1729
1730int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1731 char packet[32];
1732 const int packet_len = ::snprintf(packet, sizeof(packet),
1733 "QSetDetachOnError:%i", enable ? 1 : 0);
1734 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001735 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001736 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001737 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001738 PacketResult::Success) {
1739 if (response.IsOKResponse())
1740 return 0;
1741 uint8_t error = response.GetError();
1742 if (error)
1743 return error;
1744 }
1745 return -1;
1746}
1747
1748bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1749 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1750 if (response.IsNormalResponse()) {
1751 llvm::StringRef name;
1752 llvm::StringRef value;
1753 StringExtractor extractor;
1754
1755 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1756 uint32_t sub = 0;
1757 std::string vendor;
1758 std::string os_type;
1759
1760 while (response.GetNameColonValue(name, value)) {
1761 if (name.equals("pid")) {
1762 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1763 value.getAsInteger(0, pid);
1764 process_info.SetProcessID(pid);
1765 } else if (name.equals("ppid")) {
1766 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1767 value.getAsInteger(0, pid);
1768 process_info.SetParentProcessID(pid);
1769 } else if (name.equals("uid")) {
1770 uint32_t uid = UINT32_MAX;
1771 value.getAsInteger(0, uid);
1772 process_info.SetUserID(uid);
1773 } else if (name.equals("euid")) {
1774 uint32_t uid = UINT32_MAX;
1775 value.getAsInteger(0, uid);
1776 process_info.SetEffectiveGroupID(uid);
1777 } else if (name.equals("gid")) {
1778 uint32_t gid = UINT32_MAX;
1779 value.getAsInteger(0, gid);
1780 process_info.SetGroupID(gid);
1781 } else if (name.equals("egid")) {
1782 uint32_t gid = UINT32_MAX;
1783 value.getAsInteger(0, gid);
1784 process_info.SetEffectiveGroupID(gid);
1785 } else if (name.equals("triple")) {
1786 StringExtractor extractor(value);
1787 std::string triple;
1788 extractor.GetHexByteString(triple);
1789 process_info.GetArchitecture().SetTriple(triple.c_str());
1790 } else if (name.equals("name")) {
1791 StringExtractor extractor(value);
1792 // The process name from ASCII hex bytes since we can't
1793 // control the characters in a process name
1794 std::string name;
1795 extractor.GetHexByteString(name);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001796 process_info.GetExecutableFile().SetFile(name, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001797 } else if (name.equals("cputype")) {
1798 value.getAsInteger(0, cpu);
1799 } else if (name.equals("cpusubtype")) {
1800 value.getAsInteger(0, sub);
1801 } else if (name.equals("vendor")) {
1802 vendor = value;
1803 } else if (name.equals("ostype")) {
1804 os_type = value;
1805 }
1806 }
1807
1808 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1809 if (vendor == "apple") {
1810 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1811 sub);
1812 process_info.GetArchitecture().GetTriple().setVendorName(
1813 llvm::StringRef(vendor));
1814 process_info.GetArchitecture().GetTriple().setOSName(
1815 llvm::StringRef(os_type));
1816 }
1817 }
1818
1819 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1820 return true;
1821 }
1822 return false;
1823}
1824
1825bool GDBRemoteCommunicationClient::GetProcessInfo(
1826 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1827 process_info.Clear();
1828
1829 if (m_supports_qProcessInfoPID) {
1830 char packet[32];
1831 const int packet_len =
1832 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1833 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001834 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001835 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001836 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001837 PacketResult::Success) {
1838 return DecodeProcessInfoResponse(response, process_info);
1839 } else {
1840 m_supports_qProcessInfoPID = false;
1841 return false;
1842 }
1843 }
1844 return false;
1845}
1846
1847bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1848 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1849 GDBR_LOG_PACKETS));
1850
1851 if (allow_lazy) {
1852 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1853 return true;
1854 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1855 return false;
1856 }
1857
1858 GetHostInfo();
1859
1860 StringExtractorGDBRemote response;
1861 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1862 PacketResult::Success) {
1863 if (response.IsNormalResponse()) {
1864 llvm::StringRef name;
1865 llvm::StringRef value;
1866 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1867 uint32_t sub = 0;
1868 std::string arch_name;
1869 std::string os_name;
1870 std::string vendor_name;
1871 std::string triple;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001872 std::string elf_abi;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001873 uint32_t pointer_byte_size = 0;
1874 StringExtractor extractor;
1875 ByteOrder byte_order = eByteOrderInvalid;
1876 uint32_t num_keys_decoded = 0;
1877 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1878 while (response.GetNameColonValue(name, value)) {
1879 if (name.equals("cputype")) {
1880 if (!value.getAsInteger(16, cpu))
1881 ++num_keys_decoded;
1882 } else if (name.equals("cpusubtype")) {
1883 if (!value.getAsInteger(16, sub))
1884 ++num_keys_decoded;
1885 } else if (name.equals("triple")) {
1886 StringExtractor extractor(value);
1887 extractor.GetHexByteString(triple);
1888 ++num_keys_decoded;
1889 } else if (name.equals("ostype")) {
1890 os_name = value;
1891 ++num_keys_decoded;
1892 } else if (name.equals("vendor")) {
1893 vendor_name = value;
1894 ++num_keys_decoded;
1895 } else if (name.equals("endian")) {
1896 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1897 .Case("little", eByteOrderLittle)
1898 .Case("big", eByteOrderBig)
1899 .Case("pdp", eByteOrderPDP)
1900 .Default(eByteOrderInvalid);
1901 if (byte_order != eByteOrderInvalid)
1902 ++num_keys_decoded;
1903 } else if (name.equals("ptrsize")) {
1904 if (!value.getAsInteger(16, pointer_byte_size))
1905 ++num_keys_decoded;
1906 } else if (name.equals("pid")) {
1907 if (!value.getAsInteger(16, pid))
1908 ++num_keys_decoded;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001909 } else if (name.equals("elf_abi")) {
1910 elf_abi = value;
1911 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001912 }
1913 }
1914 if (num_keys_decoded > 0)
1915 m_qProcessInfo_is_valid = eLazyBoolYes;
1916 if (pid != LLDB_INVALID_PROCESS_ID) {
1917 m_curr_pid_is_valid = eLazyBoolYes;
1918 m_curr_pid = pid;
1919 }
1920
1921 // Set the ArchSpec from the triple if we have it.
1922 if (!triple.empty()) {
1923 m_process_arch.SetTriple(triple.c_str());
Nitesh Jain8999edf2016-10-12 10:21:09 +00001924 m_process_arch.SetFlags(elf_abi);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001925 if (pointer_byte_size) {
1926 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1927 }
1928 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
1929 !vendor_name.empty()) {
1930 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
1931
1932 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
Pavel Labath4f19fce22017-02-17 13:39:50 +00001933 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001934 switch (triple.getObjectFormat()) {
1935 case llvm::Triple::MachO:
1936 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1937 break;
1938 case llvm::Triple::ELF:
1939 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
1940 break;
1941 case llvm::Triple::COFF:
1942 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
1943 break;
Pavel Labath4f19fce22017-02-17 13:39:50 +00001944 case llvm::Triple::Wasm:
1945 if (log)
1946 log->Printf("error: not supported target architecture");
1947 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001948 case llvm::Triple::UnknownObjectFormat:
1949 if (log)
1950 log->Printf("error: failed to determine target architecture");
1951 return false;
1952 }
1953
1954 if (pointer_byte_size) {
1955 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1956 }
1957 if (byte_order != eByteOrderInvalid) {
1958 assert(byte_order == m_process_arch.GetByteOrder());
1959 }
1960 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1961 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1962 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1963 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1964 }
1965 return true;
1966 }
1967 } else {
1968 m_qProcessInfo_is_valid = eLazyBoolNo;
1969 }
1970
1971 return false;
1972}
1973
1974uint32_t GDBRemoteCommunicationClient::FindProcesses(
1975 const ProcessInstanceInfoMatch &match_info,
1976 ProcessInstanceInfoList &process_infos) {
1977 process_infos.Clear();
1978
1979 if (m_supports_qfProcessInfo) {
1980 StreamString packet;
1981 packet.PutCString("qfProcessInfo");
1982 if (!match_info.MatchAllProcesses()) {
1983 packet.PutChar(':');
1984 const char *name = match_info.GetProcessInfo().GetName();
1985 bool has_name_match = false;
1986 if (name && name[0]) {
1987 has_name_match = true;
Pavel Labathc4a33952017-02-20 11:35:33 +00001988 NameMatch name_match_type = match_info.GetNameMatchType();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001989 switch (name_match_type) {
Pavel Labathc4a33952017-02-20 11:35:33 +00001990 case NameMatch::Ignore:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001991 has_name_match = false;
1992 break;
1993
Pavel Labathc4a33952017-02-20 11:35:33 +00001994 case NameMatch::Equals:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001995 packet.PutCString("name_match:equals;");
1996 break;
1997
Pavel Labathc4a33952017-02-20 11:35:33 +00001998 case NameMatch::Contains:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001999 packet.PutCString("name_match:contains;");
2000 break;
2001
Pavel Labathc4a33952017-02-20 11:35:33 +00002002 case NameMatch::StartsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002003 packet.PutCString("name_match:starts_with;");
2004 break;
2005
Pavel Labathc4a33952017-02-20 11:35:33 +00002006 case NameMatch::EndsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002007 packet.PutCString("name_match:ends_with;");
2008 break;
2009
Pavel Labathc4a33952017-02-20 11:35:33 +00002010 case NameMatch::RegularExpression:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002011 packet.PutCString("name_match:regex;");
2012 break;
2013 }
2014 if (has_name_match) {
2015 packet.PutCString("name:");
2016 packet.PutBytesAsRawHex8(name, ::strlen(name));
2017 packet.PutChar(';');
2018 }
2019 }
2020
2021 if (match_info.GetProcessInfo().ProcessIDIsValid())
2022 packet.Printf("pid:%" PRIu64 ";",
2023 match_info.GetProcessInfo().GetProcessID());
2024 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2025 packet.Printf("parent_pid:%" PRIu64 ";",
2026 match_info.GetProcessInfo().GetParentProcessID());
2027 if (match_info.GetProcessInfo().UserIDIsValid())
2028 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2029 if (match_info.GetProcessInfo().GroupIDIsValid())
2030 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2031 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2032 packet.Printf("euid:%u;",
2033 match_info.GetProcessInfo().GetEffectiveUserID());
2034 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2035 packet.Printf("egid:%u;",
2036 match_info.GetProcessInfo().GetEffectiveGroupID());
2037 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2038 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2039 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2040 const ArchSpec &match_arch =
2041 match_info.GetProcessInfo().GetArchitecture();
2042 const llvm::Triple &triple = match_arch.GetTriple();
2043 packet.PutCString("triple:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002044 packet.PutCString(triple.getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002045 packet.PutChar(';');
2046 }
2047 }
2048 StringExtractorGDBRemote response;
2049 // Increase timeout as the first qfProcessInfo packet takes a long time
2050 // on Android. The value of 1min was arrived at empirically.
Pavel Labath1eff73c2016-11-24 10:54:49 +00002051 ScopedTimeout timeout(*this, minutes(1));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002052 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2053 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002054 do {
2055 ProcessInstanceInfo process_info;
2056 if (!DecodeProcessInfoResponse(response, process_info))
2057 break;
2058 process_infos.Append(process_info);
2059 response.GetStringRef().clear();
2060 response.SetFilePos(0);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002061 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2062 PacketResult::Success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002063 } else {
2064 m_supports_qfProcessInfo = false;
2065 return 0;
2066 }
2067 }
2068 return process_infos.GetSize();
2069}
2070
2071bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2072 std::string &name) {
2073 if (m_supports_qUserName) {
2074 char packet[32];
2075 const int packet_len =
2076 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2077 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002078 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002079 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002080 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002081 PacketResult::Success) {
2082 if (response.IsNormalResponse()) {
2083 // Make sure we parsed the right number of characters. The response is
2084 // the hex encoded user name and should make up the entire packet.
2085 // If there are any non-hex ASCII bytes, the length won't match below..
2086 if (response.GetHexByteString(name) * 2 ==
2087 response.GetStringRef().size())
2088 return true;
2089 }
2090 } else {
2091 m_supports_qUserName = false;
2092 return false;
2093 }
2094 }
2095 return false;
2096}
2097
2098bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2099 std::string &name) {
2100 if (m_supports_qGroupName) {
2101 char packet[32];
2102 const int packet_len =
2103 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2104 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002105 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002107 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002108 PacketResult::Success) {
2109 if (response.IsNormalResponse()) {
2110 // Make sure we parsed the right number of characters. The response is
2111 // the hex encoded group name and should make up the entire packet.
2112 // If there are any non-hex ASCII bytes, the length won't match below..
2113 if (response.GetHexByteString(name) * 2 ==
2114 response.GetStringRef().size())
2115 return true;
2116 }
2117 } else {
2118 m_supports_qGroupName = false;
2119 return false;
2120 }
2121 }
2122 return false;
2123}
2124
2125bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2126 // Form non-stop packet request
2127 char packet[32];
2128 const int packet_len =
2129 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2130 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002131 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002132
2133 StringExtractorGDBRemote response;
2134 // Send to target
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002135 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002136 PacketResult::Success)
2137 if (response.IsOKResponse())
2138 return true;
2139
2140 // Failed or not supported
2141 return false;
2142}
2143
2144static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2145 uint32_t recv_size) {
2146 packet.Clear();
2147 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2148 uint32_t bytes_left = send_size;
2149 while (bytes_left > 0) {
2150 if (bytes_left >= 26) {
2151 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2152 bytes_left -= 26;
2153 } else {
2154 packet.Printf("%*.*s;", bytes_left, bytes_left,
2155 "abcdefghijklmnopqrstuvwxyz");
2156 bytes_left = 0;
2157 }
2158 }
2159}
2160
Pavel Labath1eff73c2016-11-24 10:54:49 +00002161duration<float>
2162calculate_standard_deviation(const std::vector<duration<float>> &v) {
2163 using Dur = duration<float>;
Pavel Labath3aa04912016-10-31 17:19:42 +00002164 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2165 Dur mean = sum / v.size();
2166 float accum = 0;
2167 for (auto d : v) {
2168 float delta = (d - mean).count();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002169 accum += delta * delta;
Pavel Labath3aa04912016-10-31 17:19:42 +00002170 };
Kate Stoneb9c1b512016-09-06 20:57:50 +00002171
Pavel Labath3aa04912016-10-31 17:19:42 +00002172 return Dur(sqrtf(accum / (v.size() - 1)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002173}
2174
2175void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2176 uint32_t max_send,
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002177 uint32_t max_recv,
2178 uint64_t recv_amount,
2179 bool json, Stream &strm) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002180 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002181 if (SendSpeedTestPacket(0, 0)) {
2182 StreamString packet;
2183 if (json)
2184 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2185 "\"results\" : [",
2186 num_packets);
2187 else
2188 strm.Printf("Testing sending %u packets of various sizes:\n",
2189 num_packets);
2190 strm.Flush();
2191
2192 uint32_t result_idx = 0;
2193 uint32_t send_size;
Pavel Labath3aa04912016-10-31 17:19:42 +00002194 std::vector<duration<float>> packet_times;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002195
2196 for (send_size = 0; send_size <= max_send;
2197 send_size ? send_size *= 2 : send_size = 4) {
2198 for (uint32_t recv_size = 0; recv_size <= max_recv;
2199 recv_size ? recv_size *= 2 : recv_size = 4) {
2200 MakeSpeedTestPacket(packet, send_size, recv_size);
2201
2202 packet_times.clear();
2203 // Test how long it takes to send 'num_packets' packets
Pavel Labath3aa04912016-10-31 17:19:42 +00002204 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002205 for (i = 0; i < num_packets; ++i) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002206 const auto packet_start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002207 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002208 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Pavel Labath3aa04912016-10-31 17:19:42 +00002209 const auto packet_end_time = steady_clock::now();
2210 packet_times.push_back(packet_end_time - packet_start_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002211 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002212 const auto end_time = steady_clock::now();
2213 const auto total_time = end_time - start_time;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002214
2215 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002216 ((float)num_packets) / duration<float>(total_time).count();
2217 auto average_per_packet = total_time / num_packets;
2218 const duration<float> standard_deviation =
2219 calculate_standard_deviation(packet_times);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002220 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002221 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2222 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2223 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002224 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002225 total_time, standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002226 ++result_idx;
2227 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002228 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2229 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2230 "standard deviation of {5,10:ms+f6}\n",
2231 send_size, recv_size, duration<float>(total_time),
2232 packets_per_second, duration<float>(average_per_packet),
2233 standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234 }
2235 strm.Flush();
2236 }
2237 }
2238
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002239 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002240 if (json)
2241 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2242 ": %" PRIu64 ",\n \"results\" : [",
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002243 recv_amount);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002244 else
2245 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2246 "packet sizes:\n",
2247 k_recv_amount_mb);
2248 strm.Flush();
2249 send_size = 0;
2250 result_idx = 0;
2251 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2252 MakeSpeedTestPacket(packet, send_size, recv_size);
2253
2254 // If we have a receive size, test how long it takes to receive 4MB of
2255 // data
2256 if (recv_size > 0) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002257 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002258 uint32_t bytes_read = 0;
2259 uint32_t packet_count = 0;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002260 while (bytes_read < recv_amount) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002261 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002262 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002263 bytes_read += recv_size;
2264 ++packet_count;
2265 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002266 const auto end_time = steady_clock::now();
2267 const auto total_time = end_time - start_time;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002268 float mb_second = ((float)recv_amount) /
Pavel Labath3aa04912016-10-31 17:19:42 +00002269 duration<float>(total_time).count() /
Kate Stoneb9c1b512016-09-06 20:57:50 +00002270 (1024.0 * 1024.0);
2271 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002272 ((float)packet_count) / duration<float>(total_time).count();
2273 const auto average_per_packet = total_time / packet_count;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002274
2275 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002276 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2277 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002278 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002279 total_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002280 ++result_idx;
2281 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002282 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2283 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2284 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002285 send_size, recv_size, packet_count, k_recv_amount_mb,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002286 duration<float>(total_time), mb_second,
2287 packets_per_second, duration<float>(average_per_packet));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002288 }
2289 strm.Flush();
2290 }
2291 }
2292 if (json)
2293 strm.Printf("\n ]\n }\n}\n");
2294 else
2295 strm.EOL();
2296 }
2297}
2298
2299bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2300 uint32_t recv_size) {
2301 StreamString packet;
2302 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2303 uint32_t bytes_left = send_size;
2304 while (bytes_left > 0) {
2305 if (bytes_left >= 26) {
2306 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2307 bytes_left -= 26;
2308 } else {
2309 packet.Printf("%*.*s;", bytes_left, bytes_left,
2310 "abcdefghijklmnopqrstuvwxyz");
2311 bytes_left = 0;
2312 }
2313 }
2314
2315 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002316 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2317 PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002318}
2319
2320bool GDBRemoteCommunicationClient::LaunchGDBServer(
2321 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2322 std::string &socket_name) {
2323 pid = LLDB_INVALID_PROCESS_ID;
2324 port = 0;
2325 socket_name.clear();
2326
2327 StringExtractorGDBRemote response;
2328 StreamString stream;
2329 stream.PutCString("qLaunchGDBServer;");
2330 std::string hostname;
2331 if (remote_accept_hostname && remote_accept_hostname[0])
2332 hostname = remote_accept_hostname;
2333 else {
2334 if (HostInfo::GetHostname(hostname)) {
2335 // Make the GDB server we launch only accept connections from this host
2336 stream.Printf("host:%s;", hostname.c_str());
2337 } else {
2338 // Make the GDB server we launch accept connections from any host since we
2339 // can't figure out the hostname
2340 stream.Printf("host:*;");
2341 }
2342 }
2343 // give the process a few seconds to startup
Pavel Labath1eff73c2016-11-24 10:54:49 +00002344 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002345
2346 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2347 PacketResult::Success) {
2348 llvm::StringRef name;
2349 llvm::StringRef value;
2350 while (response.GetNameColonValue(name, value)) {
2351 if (name.equals("port"))
2352 value.getAsInteger(0, port);
2353 else if (name.equals("pid"))
2354 value.getAsInteger(0, pid);
2355 else if (name.compare("socket_name") == 0) {
2356 StringExtractor extractor(value);
2357 extractor.GetHexByteString(socket_name);
2358 }
2359 }
2360 return true;
2361 }
2362 return false;
2363}
2364
2365size_t GDBRemoteCommunicationClient::QueryGDBServer(
2366 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2367 connection_urls.clear();
2368
2369 StringExtractorGDBRemote response;
2370 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2371 PacketResult::Success)
2372 return 0;
2373
2374 StructuredData::ObjectSP data =
2375 StructuredData::ParseJSON(response.GetStringRef());
2376 if (!data)
2377 return 0;
2378
2379 StructuredData::Array *array = data->GetAsArray();
2380 if (!array)
2381 return 0;
2382
2383 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2384 StructuredData::Dictionary *element = nullptr;
2385 if (!array->GetItemAtIndexAsDictionary(i, element))
2386 continue;
2387
2388 uint16_t port = 0;
2389 if (StructuredData::ObjectSP port_osp =
2390 element->GetValueForKey(llvm::StringRef("port")))
2391 port = port_osp->GetIntegerValue(0);
2392
2393 std::string socket_name;
2394 if (StructuredData::ObjectSP socket_name_osp =
2395 element->GetValueForKey(llvm::StringRef("socket_name")))
2396 socket_name = socket_name_osp->GetStringValue();
2397
2398 if (port != 0 || !socket_name.empty())
2399 connection_urls.emplace_back(port, socket_name);
2400 }
2401 return connection_urls.size();
2402}
2403
2404bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2405 StreamString stream;
2406 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002407
2408 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002409 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410 PacketResult::Success) {
2411 if (response.IsOKResponse())
2412 return true;
2413 }
2414 return false;
2415}
2416
2417bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2418 if (m_curr_tid == tid)
2419 return true;
2420
2421 char packet[32];
2422 int packet_len;
2423 if (tid == UINT64_MAX)
2424 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2425 else
2426 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2427 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002428 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002429 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002430 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002431 PacketResult::Success) {
2432 if (response.IsOKResponse()) {
2433 m_curr_tid = tid;
2434 return true;
2435 }
2436
2437 /*
2438 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2439 * Hg packet.
2440 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2441 * which can
2442 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2443 */
2444 if (response.IsUnsupportedResponse() && IsConnected()) {
2445 m_curr_tid = 1;
2446 return true;
2447 }
2448 }
2449 return false;
2450}
2451
2452bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2453 if (m_curr_tid_run == tid)
2454 return true;
2455
2456 char packet[32];
2457 int packet_len;
2458 if (tid == UINT64_MAX)
2459 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2460 else
2461 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2462
2463 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002464 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002465 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002466 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002467 PacketResult::Success) {
2468 if (response.IsOKResponse()) {
2469 m_curr_tid_run = tid;
2470 return true;
2471 }
2472
2473 /*
2474 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2475 * Hc packet.
2476 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2477 * which can
2478 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2479 */
2480 if (response.IsUnsupportedResponse() && IsConnected()) {
2481 m_curr_tid_run = 1;
2482 return true;
2483 }
2484 }
2485 return false;
2486}
2487
2488bool GDBRemoteCommunicationClient::GetStopReply(
2489 StringExtractorGDBRemote &response) {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002490 if (SendPacketAndWaitForResponse("?", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002491 PacketResult::Success)
2492 return response.IsNormalResponse();
2493 return false;
2494}
2495
2496bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2497 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2498 if (m_supports_qThreadStopInfo) {
2499 char packet[256];
2500 int packet_len =
2501 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2502 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002503 UNUSED_IF_ASSERT_DISABLED(packet_len);
2504 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002505 PacketResult::Success) {
2506 if (response.IsUnsupportedResponse())
2507 m_supports_qThreadStopInfo = false;
2508 else if (response.IsNormalResponse())
2509 return true;
2510 else
2511 return false;
2512 } else {
2513 m_supports_qThreadStopInfo = false;
2514 }
2515 }
2516 return false;
2517}
2518
2519uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2520 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2521 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2522 if (log)
2523 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2524 __FUNCTION__, insert ? "add" : "remove", addr);
2525
2526 // Check if the stub is known not to support this breakpoint type
2527 if (!SupportsGDBStoppointPacket(type))
2528 return UINT8_MAX;
2529 // Construct the breakpoint packet
2530 char packet[64];
2531 const int packet_len =
2532 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2533 insert ? 'Z' : 'z', type, addr, length);
2534 // Check we haven't overwritten the end of the packet buffer
2535 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002536 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002537 StringExtractorGDBRemote response;
2538 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2539 // or "" (unsupported)
2540 response.SetResponseValidatorToOKErrorNotSupported();
2541 // Try to send the breakpoint packet, and check that it was correctly sent
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002542 if (SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002543 PacketResult::Success) {
2544 // Receive and OK packet when the breakpoint successfully placed
2545 if (response.IsOKResponse())
2546 return 0;
2547
Zachary Turner97206d52017-05-12 04:51:55 +00002548 // Status while setting breakpoint, send back specific error
Kate Stoneb9c1b512016-09-06 20:57:50 +00002549 if (response.IsErrorResponse())
2550 return response.GetError();
2551
2552 // Empty packet informs us that breakpoint is not supported
2553 if (response.IsUnsupportedResponse()) {
2554 // Disable this breakpoint type since it is unsupported
2555 switch (type) {
2556 case eBreakpointSoftware:
2557 m_supports_z0 = false;
2558 break;
2559 case eBreakpointHardware:
2560 m_supports_z1 = false;
2561 break;
2562 case eWatchpointWrite:
2563 m_supports_z2 = false;
2564 break;
2565 case eWatchpointRead:
2566 m_supports_z3 = false;
2567 break;
2568 case eWatchpointReadWrite:
2569 m_supports_z4 = false;
2570 break;
2571 case eStoppointInvalid:
2572 return UINT8_MAX;
2573 }
2574 }
2575 }
2576 // Signal generic failure
2577 return UINT8_MAX;
2578}
2579
2580size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2581 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2582 thread_ids.clear();
2583
2584 Lock lock(*this, false);
2585 if (lock) {
2586 sequence_mutex_unavailable = false;
2587 StringExtractorGDBRemote response;
2588
2589 PacketResult packet_result;
2590 for (packet_result =
2591 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2592 packet_result == PacketResult::Success && response.IsNormalResponse();
2593 packet_result =
2594 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2595 char ch = response.GetChar();
2596 if (ch == 'l')
2597 break;
2598 if (ch == 'm') {
2599 do {
2600 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2601
2602 if (tid != LLDB_INVALID_THREAD_ID) {
2603 thread_ids.push_back(tid);
2604 }
2605 ch = response.GetChar(); // Skip the command separator
2606 } while (ch == ','); // Make sure we got a comma separator
2607 }
2608 }
2609
2610 /*
2611 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2612 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2613 * could
2614 * be as simple as 'S05'. There is no packet which can give us pid and/or
2615 * tid.
2616 * Assume pid=tid=1 in such cases.
2617 */
Tamas Berghammer1492cb82017-09-18 10:24:48 +00002618 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2619 thread_ids.size() == 0 && IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002620 thread_ids.push_back(1);
2621 }
2622 } else {
David Blaikiea322f362017-01-06 00:38:06 +00002623#if !defined(LLDB_CONFIGURATION_DEBUG)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002624 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2625 GDBR_LOG_PACKETS));
2626 if (log)
2627 log->Printf("error: failed to get packet sequence mutex, not sending "
2628 "packet 'qfThreadInfo'");
2629#endif
2630 sequence_mutex_unavailable = true;
2631 }
2632 return thread_ids.size();
2633}
2634
2635lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2636 StringExtractorGDBRemote response;
2637 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2638 PacketResult::Success ||
2639 !response.IsNormalResponse())
2640 return LLDB_INVALID_ADDRESS;
2641 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2642}
2643
Zachary Turner97206d52017-05-12 04:51:55 +00002644lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002645 const char *command, // Shouldn't be NULL
2646 const FileSpec &
2647 working_dir, // Pass empty FileSpec to use the current working directory
2648 int *status_ptr, // Pass NULL if you don't want the process exit status
2649 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2650 // process to exit
2651 std::string
2652 *command_output, // Pass NULL if you don't want the command output
2653 uint32_t
2654 timeout_sec) // Timeout in seconds to wait for shell program to finish
2655{
2656 lldb_private::StreamString stream;
2657 stream.PutCString("qPlatform_shell:");
2658 stream.PutBytesAsRawHex8(command, strlen(command));
2659 stream.PutChar(',');
2660 stream.PutHex32(timeout_sec);
2661 if (working_dir) {
2662 std::string path{working_dir.GetPath(false)};
2663 stream.PutChar(',');
2664 stream.PutCStringAsRawHex8(path.c_str());
2665 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002666 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002667 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002668 PacketResult::Success) {
2669 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002670 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002671 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 exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2674 if (exitcode == UINT32_MAX)
Zachary Turner97206d52017-05-12 04:51:55 +00002675 return Status("unable to run remote process");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002676 else if (status_ptr)
2677 *status_ptr = exitcode;
2678 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002679 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002680 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2681 if (signo_ptr)
2682 *signo_ptr = signo;
2683 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002684 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002685 std::string output;
2686 response.GetEscapedBinaryData(output);
2687 if (command_output)
2688 command_output->assign(output);
Zachary Turner97206d52017-05-12 04:51:55 +00002689 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002690 }
Zachary Turner97206d52017-05-12 04:51:55 +00002691 return Status("unable to send packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002692}
2693
Zachary Turner97206d52017-05-12 04:51:55 +00002694Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2695 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002696 std::string path{file_spec.GetPath(false)};
2697 lldb_private::StreamString stream;
2698 stream.PutCString("qPlatform_mkdir:");
2699 stream.PutHex32(file_permissions);
2700 stream.PutChar(',');
2701 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002702 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002703 StringExtractorGDBRemote response;
2704
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002705 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002706 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002707 return Status("failed to send '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002708
2709 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002710 return Status("invalid response to '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002711
Zachary Turner97206d52017-05-12 04:51:55 +00002712 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713}
2714
Zachary Turner97206d52017-05-12 04:51:55 +00002715Status
2716GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2717 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002718 std::string path{file_spec.GetPath(false)};
2719 lldb_private::StreamString stream;
2720 stream.PutCString("qPlatform_chmod:");
2721 stream.PutHex32(file_permissions);
2722 stream.PutChar(',');
2723 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002724 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002725 StringExtractorGDBRemote response;
2726
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002727 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002728 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002729 return Status("failed to send '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002730
2731 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002732 return Status("invalid response to '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002733
Zachary Turner97206d52017-05-12 04:51:55 +00002734 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002735}
2736
2737static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
Zachary Turner97206d52017-05-12 04:51:55 +00002738 uint64_t fail_result, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002739 response.SetFilePos(0);
2740 if (response.GetChar() != 'F')
2741 return fail_result;
2742 int32_t result = response.GetS32(-2);
2743 if (result == -2)
2744 return fail_result;
2745 if (response.GetChar() == ',') {
2746 int result_errno = response.GetS32(-2);
2747 if (result_errno != -2)
2748 error.SetError(result_errno, eErrorTypePOSIX);
2749 else
2750 error.SetError(-1, eErrorTypeGeneric);
2751 } else
2752 error.Clear();
2753 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002754}
2755lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002756GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2757 uint32_t flags, mode_t mode,
Zachary Turner97206d52017-05-12 04:51:55 +00002758 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002759 std::string path(file_spec.GetPath(false));
2760 lldb_private::StreamString stream;
2761 stream.PutCString("vFile:open:");
2762 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002763 return UINT64_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002764 stream.PutCStringAsRawHex8(path.c_str());
2765 stream.PutChar(',');
2766 stream.PutHex32(flags);
2767 stream.PutChar(',');
2768 stream.PutHex32(mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002769 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002770 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002771 PacketResult::Success) {
2772 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2773 }
2774 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002775}
2776
Zachary Turner97206d52017-05-12 04:51:55 +00002777bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2778 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002779 lldb_private::StreamString stream;
2780 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002781 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002782 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002783 PacketResult::Success) {
2784 return ParseHostIOPacketResponse(response, -1, error) == 0;
2785 }
2786 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002787}
2788
2789// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2791 const lldb_private::FileSpec &file_spec) {
2792 std::string path(file_spec.GetPath(false));
2793 lldb_private::StreamString stream;
2794 stream.PutCString("vFile:size:");
2795 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002796 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002797 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002798 PacketResult::Success) {
2799 if (response.GetChar() != 'F')
2800 return UINT64_MAX;
2801 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2802 return retcode;
2803 }
2804 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002805}
2806
Zachary Turner97206d52017-05-12 04:51:55 +00002807Status
2808GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2809 uint32_t &file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002810 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002811 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002812 lldb_private::StreamString stream;
2813 stream.PutCString("vFile:mode:");
2814 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002815 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002816 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002817 PacketResult::Success) {
2818 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002819 error.SetErrorStringWithFormat("invalid response to '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002820 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 } else {
2822 const uint32_t mode = response.GetS32(-1);
2823 if (static_cast<int32_t>(mode) == -1) {
2824 if (response.GetChar() == ',') {
2825 int response_errno = response.GetS32(-1);
2826 if (response_errno > 0)
2827 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2828 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002829 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830 } else
2831 error.SetErrorToGenericError();
2832 } else {
2833 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2834 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002835 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002836 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002837 error.SetErrorStringWithFormat("failed to send '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002838 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002839 }
2840 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002841}
2842
Kate Stoneb9c1b512016-09-06 20:57:50 +00002843uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2844 uint64_t offset, void *dst,
2845 uint64_t dst_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002846 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002847 lldb_private::StreamString stream;
2848 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2849 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002850 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002851 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002852 PacketResult::Success) {
2853 if (response.GetChar() != 'F')
2854 return 0;
2855 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2856 if (retcode == UINT32_MAX)
2857 return retcode;
2858 const char next = (response.Peek() ? *response.Peek() : 0);
2859 if (next == ',')
2860 return 0;
2861 if (next == ';') {
2862 response.GetChar(); // skip the semicolon
2863 std::string buffer;
2864 if (response.GetEscapedBinaryData(buffer)) {
2865 const uint64_t data_to_write =
2866 std::min<uint64_t>(dst_len, buffer.size());
2867 if (data_to_write > 0)
2868 memcpy(dst, &buffer[0], data_to_write);
2869 return data_to_write;
2870 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002871 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002872 }
2873 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002874}
2875
Kate Stoneb9c1b512016-09-06 20:57:50 +00002876uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
2877 uint64_t offset,
2878 const void *src,
2879 uint64_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002880 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002881 lldb_private::StreamGDBRemote stream;
2882 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2883 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002884 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002885 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002886 PacketResult::Success) {
2887 if (response.GetChar() != 'F') {
2888 error.SetErrorStringWithFormat("write file failed");
2889 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002890 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002891 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2892 if (bytes_written == UINT64_MAX) {
2893 error.SetErrorToGenericError();
2894 if (response.GetChar() == ',') {
2895 int response_errno = response.GetS32(-1);
2896 if (response_errno > 0)
2897 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2898 }
2899 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002900 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901 return bytes_written;
2902 } else {
2903 error.SetErrorString("failed to send vFile:pwrite packet");
2904 }
2905 return 0;
2906}
2907
Zachary Turner97206d52017-05-12 04:51:55 +00002908Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
2909 const FileSpec &dst) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002910 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002911 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002912 lldb_private::StreamGDBRemote stream;
2913 stream.PutCString("vFile:symlink:");
2914 // the unix symlink() command reverses its parameters where the dst if first,
2915 // so we follow suit here
2916 stream.PutCStringAsRawHex8(dst_path.c_str());
2917 stream.PutChar(',');
2918 stream.PutCStringAsRawHex8(src_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002919 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002920 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002921 PacketResult::Success) {
2922 if (response.GetChar() == 'F') {
2923 uint32_t result = response.GetU32(UINT32_MAX);
2924 if (result != 0) {
2925 error.SetErrorToGenericError();
2926 if (response.GetChar() == ',') {
2927 int response_errno = response.GetS32(-1);
2928 if (response_errno > 0)
2929 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2930 }
2931 }
2932 } else {
2933 // Should have returned with 'F<result>[,<errno>]'
2934 error.SetErrorStringWithFormat("symlink failed");
2935 }
2936 } else {
2937 error.SetErrorString("failed to send vFile:symlink packet");
2938 }
2939 return error;
2940}
2941
Zachary Turner97206d52017-05-12 04:51:55 +00002942Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002943 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002944 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002945 lldb_private::StreamGDBRemote stream;
2946 stream.PutCString("vFile:unlink:");
2947 // the unix symlink() command reverses its parameters where the dst if first,
2948 // so we follow suit here
2949 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002950 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002951 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002952 PacketResult::Success) {
2953 if (response.GetChar() == 'F') {
2954 uint32_t result = response.GetU32(UINT32_MAX);
2955 if (result != 0) {
2956 error.SetErrorToGenericError();
2957 if (response.GetChar() == ',') {
2958 int response_errno = response.GetS32(-1);
2959 if (response_errno > 0)
2960 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2961 }
2962 }
2963 } else {
2964 // Should have returned with 'F<result>[,<errno>]'
2965 error.SetErrorStringWithFormat("unlink failed");
2966 }
2967 } else {
2968 error.SetErrorString("failed to send vFile:unlink packet");
2969 }
2970 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002971}
2972
Daniel Maleae0f8f572013-08-26 23:57:52 +00002973// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002974bool GDBRemoteCommunicationClient::GetFileExists(
2975 const lldb_private::FileSpec &file_spec) {
2976 std::string path(file_spec.GetPath(false));
2977 lldb_private::StreamString stream;
2978 stream.PutCString("vFile:exists:");
2979 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002980 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002981 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002982 PacketResult::Success) {
2983 if (response.GetChar() != 'F')
2984 return false;
2985 if (response.GetChar() != ',')
2986 return false;
2987 bool retcode = (response.GetChar() != '0');
2988 return retcode;
2989 }
2990 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002991}
2992
Kate Stoneb9c1b512016-09-06 20:57:50 +00002993bool GDBRemoteCommunicationClient::CalculateMD5(
2994 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
2995 std::string path(file_spec.GetPath(false));
2996 lldb_private::StreamString stream;
2997 stream.PutCString("vFile:MD5:");
2998 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002999 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003000 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003001 PacketResult::Success) {
3002 if (response.GetChar() != 'F')
3003 return false;
3004 if (response.GetChar() != ',')
3005 return false;
3006 if (response.Peek() && *response.Peek() == 'x')
3007 return false;
3008 low = response.GetHexMaxU64(false, UINT64_MAX);
3009 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00003010 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003011 }
3012 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003013}
3014
Kate Stoneb9c1b512016-09-06 20:57:50 +00003015bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3016 // Some targets have issues with g/G packets and we need to avoid using them
3017 if (m_avoid_g_packets == eLazyBoolCalculate) {
3018 if (process) {
3019 m_avoid_g_packets = eLazyBoolNo;
3020 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3021 if (arch.IsValid() &&
3022 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3023 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3024 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3025 m_avoid_g_packets = eLazyBoolYes;
3026 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3027 if (gdb_server_version != 0) {
3028 const char *gdb_server_name = GetGDBServerProgramName();
3029 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3030 if (gdb_server_version >= 310)
3031 m_avoid_g_packets = eLazyBoolNo;
3032 }
3033 }
3034 }
3035 }
3036 }
3037 return m_avoid_g_packets == eLazyBoolYes;
3038}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003039
Kate Stoneb9c1b512016-09-06 20:57:50 +00003040DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3041 uint32_t reg) {
3042 StreamString payload;
3043 payload.Printf("p%x", reg);
3044 StringExtractorGDBRemote response;
3045 if (SendThreadSpecificPacketAndWaitForResponse(
3046 tid, std::move(payload), response, false) != PacketResult::Success ||
3047 !response.IsNormalResponse())
3048 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003049
Kate Stoneb9c1b512016-09-06 20:57:50 +00003050 DataBufferSP buffer_sp(
3051 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3052 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3053 return buffer_sp;
3054}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003055
Kate Stoneb9c1b512016-09-06 20:57:50 +00003056DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3057 StreamString payload;
3058 payload.PutChar('g');
3059 StringExtractorGDBRemote response;
3060 if (SendThreadSpecificPacketAndWaitForResponse(
3061 tid, std::move(payload), response, false) != PacketResult::Success ||
3062 !response.IsNormalResponse())
3063 return nullptr;
3064
3065 DataBufferSP buffer_sp(
3066 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3067 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3068 return buffer_sp;
3069}
3070
3071bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3072 uint32_t reg_num,
3073 llvm::ArrayRef<uint8_t> data) {
3074 StreamString payload;
3075 payload.Printf("P%x=", reg_num);
3076 payload.PutBytesAsRawHex8(data.data(), data.size(),
3077 endian::InlHostByteOrder(),
3078 endian::InlHostByteOrder());
3079 StringExtractorGDBRemote response;
3080 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3081 response, false) ==
3082 PacketResult::Success &&
3083 response.IsOKResponse();
3084}
3085
3086bool GDBRemoteCommunicationClient::WriteAllRegisters(
3087 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3088 StreamString payload;
3089 payload.PutChar('G');
3090 payload.PutBytesAsRawHex8(data.data(), data.size(),
3091 endian::InlHostByteOrder(),
3092 endian::InlHostByteOrder());
3093 StringExtractorGDBRemote response;
3094 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3095 response, false) ==
3096 PacketResult::Success &&
3097 response.IsOKResponse();
3098}
3099
3100bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3101 uint32_t &save_id) {
3102 save_id = 0; // Set to invalid save ID
3103 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003104 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003105
3106 m_supports_QSaveRegisterState = eLazyBoolYes;
3107 StreamString payload;
3108 payload.PutCString("QSaveRegisterState");
3109 StringExtractorGDBRemote response;
3110 if (SendThreadSpecificPacketAndWaitForResponse(
3111 tid, std::move(payload), response, false) != PacketResult::Success)
3112 return false;
3113
3114 if (response.IsUnsupportedResponse())
3115 m_supports_QSaveRegisterState = eLazyBoolNo;
3116
3117 const uint32_t response_save_id = response.GetU32(0);
3118 if (response_save_id == 0)
3119 return false;
3120
3121 save_id = response_save_id;
3122 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003123}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003124
Kate Stoneb9c1b512016-09-06 20:57:50 +00003125bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3126 uint32_t save_id) {
3127 // We use the "m_supports_QSaveRegisterState" variable here because the
3128 // QSaveRegisterState and QRestoreRegisterState packets must both be supported
3129 // in
3130 // order to be useful
3131 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3132 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003133
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134 StreamString payload;
3135 payload.Printf("QRestoreRegisterState:%u", save_id);
3136 StringExtractorGDBRemote response;
3137 if (SendThreadSpecificPacketAndWaitForResponse(
3138 tid, std::move(payload), response, false) != PacketResult::Success)
3139 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003140
Kate Stoneb9c1b512016-09-06 20:57:50 +00003141 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003142 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003143
3144 if (response.IsUnsupportedResponse())
3145 m_supports_QSaveRegisterState = eLazyBoolNo;
3146 return false;
3147}
3148
3149bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3150 if (!GetSyncThreadStateSupported())
3151 return false;
3152
3153 StreamString packet;
3154 StringExtractorGDBRemote response;
3155 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3156 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3157 GDBRemoteCommunication::PacketResult::Success &&
3158 response.IsOKResponse();
3159}
3160
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003161lldb::user_id_t
3162GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3163 Status &error) {
3164 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3165 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3166
3167 StreamGDBRemote escaped_packet;
3168 escaped_packet.PutCString("jTraceStart:");
3169
3170 StructuredData::Dictionary json_packet;
3171 json_packet.AddIntegerItem("type", options.getType());
3172 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3173 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3174
3175 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3176 json_packet.AddIntegerItem("threadid", options.getThreadID());
3177
3178 StructuredData::DictionarySP custom_params = options.getTraceParams();
3179 if (custom_params)
3180 json_packet.AddItem("params", custom_params);
3181
3182 StreamString json_string;
3183 json_packet.Dump(json_string, false);
3184 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3185
3186 StringExtractorGDBRemote response;
3187 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3188 true) ==
3189 GDBRemoteCommunication::PacketResult::Success) {
3190 if (!response.IsNormalResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003191 error = response.GetStatus();
3192 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003193 } else {
3194 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3195 }
3196 } else {
3197 LLDB_LOG(log, "failed to send packet");
3198 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3199 escaped_packet.GetData());
3200 }
3201 return ret_uid;
3202}
3203
3204Status
3205GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3206 lldb::tid_t thread_id) {
3207 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3208 StringExtractorGDBRemote response;
3209 Status error;
3210
3211 StructuredData::Dictionary json_packet;
3212 StreamGDBRemote escaped_packet;
3213 StreamString json_string;
3214 escaped_packet.PutCString("jTraceStop:");
3215
3216 json_packet.AddIntegerItem("traceid", uid);
3217
3218 if (thread_id != LLDB_INVALID_THREAD_ID)
3219 json_packet.AddIntegerItem("threadid", thread_id);
3220
3221 json_packet.Dump(json_string, false);
3222
3223 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3224
3225 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3226 true) ==
3227 GDBRemoteCommunication::PacketResult::Success) {
3228 if (!response.IsOKResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003229 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003230 LLDB_LOG(log, "stop tracing failed");
3231 }
3232 } else {
3233 LLDB_LOG(log, "failed to send packet");
3234 error.SetErrorStringWithFormat(
3235 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3236 response.GetError());
3237 }
3238 return error;
3239}
3240
3241Status GDBRemoteCommunicationClient::SendGetDataPacket(
3242 lldb::user_id_t uid, lldb::tid_t thread_id,
3243 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003244
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003245 StreamGDBRemote escaped_packet;
3246 escaped_packet.PutCString("jTraceBufferRead:");
3247 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3248}
3249
3250Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3251 lldb::user_id_t uid, lldb::tid_t thread_id,
3252 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003253
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003254 StreamGDBRemote escaped_packet;
3255 escaped_packet.PutCString("jTraceMetaRead:");
3256 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3257}
3258
3259Status
3260GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3261 TraceOptions &options) {
3262 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3263 StringExtractorGDBRemote response;
3264 Status error;
3265
3266 StreamString json_string;
3267 StreamGDBRemote escaped_packet;
3268 escaped_packet.PutCString("jTraceConfigRead:");
3269
3270 StructuredData::Dictionary json_packet;
3271 json_packet.AddIntegerItem("traceid", uid);
3272
3273 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3274 json_packet.AddIntegerItem("threadid", options.getThreadID());
3275
3276 json_packet.Dump(json_string, false);
3277 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3278
3279 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3280 true) ==
3281 GDBRemoteCommunication::PacketResult::Success) {
3282 if (response.IsNormalResponse()) {
3283 uint64_t type = std::numeric_limits<uint64_t>::max();
3284 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3285 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3286
3287 auto json_object = StructuredData::ParseJSON(response.Peek());
3288
3289 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003290 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003291 error.SetErrorString("Invalid Configuration obtained");
3292 return error;
3293 }
3294
3295 auto json_dict = json_object->GetAsDictionary();
3296
3297 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3298 metabuffersize);
3299 options.setMetaDataBufferSize(metabuffersize);
3300
3301 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3302 options.setTraceBufferSize(buffersize);
3303
3304 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3305 options.setType(static_cast<lldb::TraceType>(type));
3306
3307 StructuredData::ObjectSP custom_params_sp =
3308 json_dict->GetValueForKey("params");
3309 if (custom_params_sp) {
3310 if (custom_params_sp->GetType() !=
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003311 lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003312 error.SetErrorString("Invalid Configuration obtained");
3313 return error;
3314 } else
3315 options.setTraceParams(
3316 static_pointer_cast<StructuredData::Dictionary>(
3317 custom_params_sp));
3318 }
3319 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003320 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003321 }
3322 } else {
3323 LLDB_LOG(log, "failed to send packet");
3324 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3325 escaped_packet.GetData());
3326 }
3327 return error;
3328}
3329
3330Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3331 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3332 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3333 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3334 Status error;
3335
3336 StructuredData::Dictionary json_packet;
3337
3338 json_packet.AddIntegerItem("traceid", uid);
3339 json_packet.AddIntegerItem("offset", offset);
3340 json_packet.AddIntegerItem("buffersize", buffer.size());
3341
3342 if (thread_id != LLDB_INVALID_THREAD_ID)
3343 json_packet.AddIntegerItem("threadid", thread_id);
3344
3345 StreamString json_string;
3346 json_packet.Dump(json_string, false);
3347
3348 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3349 StringExtractorGDBRemote response;
3350 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3351 GDBRemoteCommunication::PacketResult::Success) {
3352 if (response.IsNormalResponse()) {
3353 size_t filled_size = response.GetHexBytesAvail(buffer);
3354 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3355 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003356 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003357 buffer = buffer.slice(buffer.size());
3358 }
3359 } else {
3360 LLDB_LOG(log, "failed to send packet");
3361 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3362 packet.GetData());
3363 buffer = buffer.slice(buffer.size());
3364 }
3365 return error;
3366}
3367
Kate Stoneb9c1b512016-09-06 20:57:50 +00003368bool GDBRemoteCommunicationClient::GetModuleInfo(
3369 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3370 ModuleSpec &module_spec) {
3371 if (!m_supports_qModuleInfo)
3372 return false;
3373
3374 std::string module_path = module_file_spec.GetPath(false);
3375 if (module_path.empty())
3376 return false;
3377
3378 StreamString packet;
3379 packet.PutCString("qModuleInfo:");
3380 packet.PutCStringAsRawHex8(module_path.c_str());
3381 packet.PutCString(";");
3382 const auto &triple = arch_spec.GetTriple().getTriple();
3383 packet.PutCStringAsRawHex8(triple.c_str());
3384
3385 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003386 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3387 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003388 return false;
3389
3390 if (response.IsErrorResponse())
3391 return false;
3392
3393 if (response.IsUnsupportedResponse()) {
3394 m_supports_qModuleInfo = false;
3395 return false;
3396 }
3397
3398 llvm::StringRef name;
3399 llvm::StringRef value;
3400
3401 module_spec.Clear();
3402 module_spec.GetFileSpec() = module_file_spec;
3403
3404 while (response.GetNameColonValue(name, value)) {
3405 if (name == "uuid" || name == "md5") {
3406 StringExtractor extractor(value);
3407 std::string uuid;
3408 extractor.GetHexByteString(uuid);
3409 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
3410 } else if (name == "triple") {
3411 StringExtractor extractor(value);
3412 std::string triple;
3413 extractor.GetHexByteString(triple);
3414 module_spec.GetArchitecture().SetTriple(triple.c_str());
3415 } else if (name == "file_offset") {
3416 uint64_t ival = 0;
3417 if (!value.getAsInteger(16, ival))
3418 module_spec.SetObjectOffset(ival);
3419 } else if (name == "file_size") {
3420 uint64_t ival = 0;
3421 if (!value.getAsInteger(16, ival))
3422 module_spec.SetObjectSize(ival);
3423 } else if (name == "file_path") {
3424 StringExtractor extractor(value);
3425 std::string path;
3426 extractor.GetHexByteString(path);
Zachary Turner8c6b5462017-03-06 23:42:44 +00003427 module_spec.GetFileSpec() = FileSpec(path, false, arch_spec.GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003428 }
3429 }
3430
3431 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003432}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003433
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003434static llvm::Optional<ModuleSpec>
3435ParseModuleSpec(StructuredData::Dictionary *dict) {
3436 ModuleSpec result;
3437 if (!dict)
3438 return llvm::None;
3439
Zachary Turner28333212017-05-12 05:49:54 +00003440 llvm::StringRef string;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003441 uint64_t integer;
3442
3443 if (!dict->GetValueForKeyAsString("uuid", string))
3444 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003445 result.GetUUID().SetFromStringRef(string, string.size());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003446
3447 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3448 return llvm::None;
3449 result.SetObjectOffset(integer);
3450
3451 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3452 return llvm::None;
3453 result.SetObjectSize(integer);
3454
3455 if (!dict->GetValueForKeyAsString("triple", string))
3456 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003457 result.GetArchitecture().SetTriple(string);
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003458
3459 if (!dict->GetValueForKeyAsString("file_path", string))
3460 return llvm::None;
Zachary Turner8c6b5462017-03-06 23:42:44 +00003461 result.GetFileSpec() =
3462 FileSpec(string, false, result.GetArchitecture().GetTriple());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003463
3464 return result;
3465}
3466
3467llvm::Optional<std::vector<ModuleSpec>>
3468GDBRemoteCommunicationClient::GetModulesInfo(
3469 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3470 if (!m_supports_jModulesInfo)
3471 return llvm::None;
3472
3473 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3474 for (const FileSpec &module_file_spec : module_file_specs) {
3475 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3476 module_array_sp->AppendObject(module_sp);
3477 module_sp->SetObject(
Pavel Labath763f1c42017-01-05 13:18:46 +00003478 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003479 module_sp->SetObject("triple",
3480 std::make_shared<JSONString>(triple.getTriple()));
3481 }
3482 StreamString unescaped_payload;
3483 unescaped_payload.PutCString("jModulesInfo:");
3484 module_array_sp->Write(unescaped_payload);
3485 StreamGDBRemote payload;
Zachary Turnerc1564272016-11-16 21:15:24 +00003486 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003487 unescaped_payload.GetSize());
3488
Greg Clayton70a9f512017-04-14 17:10:04 +00003489 // Increase the timeout for jModulesInfo since this packet can take longer.
3490 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3491
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003492 StringExtractorGDBRemote response;
3493 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3494 PacketResult::Success ||
3495 response.IsErrorResponse())
3496 return llvm::None;
3497
3498 if (response.IsUnsupportedResponse()) {
3499 m_supports_jModulesInfo = false;
3500 return llvm::None;
3501 }
3502
3503 StructuredData::ObjectSP response_object_sp =
3504 StructuredData::ParseJSON(response.GetStringRef());
3505 if (!response_object_sp)
3506 return llvm::None;
3507
3508 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3509 if (!response_array)
3510 return llvm::None;
3511
3512 std::vector<ModuleSpec> result;
3513 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3514 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3515 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3516 result.push_back(*module_spec);
3517 }
3518
3519 return result;
3520}
3521
Colin Rileyc3c95b22015-04-16 15:51:33 +00003522// query the target remote for extended information using the qXfer packet
3523//
3524// example: object='features', annex='target.xml', out=<xml output>
3525// return: 'true' on success
3526// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003527bool GDBRemoteCommunicationClient::ReadExtFeature(
3528 const lldb_private::ConstString object,
3529 const lldb_private::ConstString annex, std::string &out,
Zachary Turner97206d52017-05-12 04:51:55 +00003530 lldb_private::Status &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003531
Kate Stoneb9c1b512016-09-06 20:57:50 +00003532 std::stringstream output;
3533 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003534
Kate Stoneb9c1b512016-09-06 20:57:50 +00003535 uint64_t size = GetRemoteMaxPacketSize();
3536 if (size == 0)
3537 size = 0x1000;
3538 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3539 int offset = 0;
3540 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003541
Kate Stoneb9c1b512016-09-06 20:57:50 +00003542 // loop until all data has been read
3543 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003544
Kate Stoneb9c1b512016-09-06 20:57:50 +00003545 // send query extended feature packet
3546 std::stringstream packet;
3547 packet << "qXfer:" << object.AsCString("")
3548 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3549 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003550
Kate Stoneb9c1b512016-09-06 20:57:50 +00003551 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003552 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003553
Kate Stoneb9c1b512016-09-06 20:57:50 +00003554 if (res != GDBRemoteCommunication::PacketResult::Success) {
3555 err.SetErrorString("Error sending $qXfer packet");
3556 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003557 }
3558
Kate Stoneb9c1b512016-09-06 20:57:50 +00003559 const std::string &str = chunk.GetStringRef();
3560 if (str.length() == 0) {
3561 // should have some data in chunk
3562 err.SetErrorString("Empty response from $qXfer packet");
3563 return false;
3564 }
3565
3566 // check packet code
3567 switch (str[0]) {
3568 // last chunk
3569 case ('l'):
3570 active = false;
3571 LLVM_FALLTHROUGH;
3572
3573 // more chunks
3574 case ('m'):
3575 if (str.length() > 1)
3576 output << &str[1];
3577 offset += size;
3578 break;
3579
3580 // unknown chunk
3581 default:
3582 err.SetErrorString("Invalid continuation code from $qXfer packet");
3583 return false;
3584 }
3585 }
3586
3587 out = output.str();
3588 err.Success();
3589 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003590}
Greg Clayton0b90be12015-06-23 21:27:50 +00003591
3592// Notify the target that gdb is prepared to serve symbol lookup requests.
3593// packet: "qSymbol::"
3594// reply:
3595// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003596// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3597// encoded).
3598// LLDB may provide the value by sending another qSymbol
3599// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003600// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003601//
3602// Three examples:
3603//
3604// lldb sends: qSymbol::
3605// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003606// Remote gdb stub does not need to know the addresses of any symbols, lldb
3607// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003608// need to ask again in this session.
3609//
3610// lldb sends: qSymbol::
3611// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3612// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3613// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003614// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3615// not know
3616// the address at this time. lldb needs to send qSymbol:: again when it has
3617// more
Jason Molenda50018d32016-01-13 04:08:10 +00003618// solibs loaded.
3619//
3620// lldb sends: qSymbol::
3621// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3622// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3623// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003624// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3625// that it
3626// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3627// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003628// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003629
Kate Stoneb9c1b512016-09-06 20:57:50 +00003630void GDBRemoteCommunicationClient::ServeSymbolLookups(
3631 lldb_private::Process *process) {
3632 // Set to true once we've resolved a symbol to an address for the remote stub.
3633 // If we get an 'OK' response after this, the remote stub doesn't need any
3634 // more
3635 // symbols and we can stop asking.
3636 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003637
Kate Stoneb9c1b512016-09-06 20:57:50 +00003638 // Is this the initial qSymbol:: packet?
3639 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003640
Kate Stoneb9c1b512016-09-06 20:57:50 +00003641 if (m_supports_qSymbol && m_qSymbol_requests_done == false) {
3642 Lock lock(*this, false);
3643 if (lock) {
3644 StreamString packet;
3645 packet.PutCString("qSymbol::");
3646 StringExtractorGDBRemote response;
3647 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3648 PacketResult::Success) {
3649 if (response.IsOKResponse()) {
3650 if (symbol_response_provided || first_qsymbol_query) {
3651 m_qSymbol_requests_done = true;
3652 }
3653
3654 // We are done serving symbols requests
3655 return;
3656 }
3657 first_qsymbol_query = false;
3658
3659 if (response.IsUnsupportedResponse()) {
3660 // qSymbol is not supported by the current GDB server we are connected
3661 // to
3662 m_supports_qSymbol = false;
3663 return;
3664 } else {
3665 llvm::StringRef response_str(response.GetStringRef());
3666 if (response_str.startswith("qSymbol:")) {
3667 response.SetFilePos(strlen("qSymbol:"));
3668 std::string symbol_name;
3669 if (response.GetHexByteString(symbol_name)) {
3670 if (symbol_name.empty())
3671 return;
3672
3673 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3674 lldb_private::SymbolContextList sc_list;
3675 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3676 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3677 const size_t num_scs = sc_list.GetSize();
3678 for (size_t sc_idx = 0;
3679 sc_idx < num_scs &&
3680 symbol_load_addr == LLDB_INVALID_ADDRESS;
3681 ++sc_idx) {
3682 SymbolContext sc;
3683 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3684 if (sc.symbol) {
3685 switch (sc.symbol->GetType()) {
3686 case eSymbolTypeInvalid:
3687 case eSymbolTypeAbsolute:
3688 case eSymbolTypeUndefined:
3689 case eSymbolTypeSourceFile:
3690 case eSymbolTypeHeaderFile:
3691 case eSymbolTypeObjectFile:
3692 case eSymbolTypeCommonBlock:
3693 case eSymbolTypeBlock:
3694 case eSymbolTypeLocal:
3695 case eSymbolTypeParam:
3696 case eSymbolTypeVariable:
3697 case eSymbolTypeVariableType:
3698 case eSymbolTypeLineEntry:
3699 case eSymbolTypeLineHeader:
3700 case eSymbolTypeScopeBegin:
3701 case eSymbolTypeScopeEnd:
3702 case eSymbolTypeAdditional:
3703 case eSymbolTypeCompiler:
3704 case eSymbolTypeInstrumentation:
3705 case eSymbolTypeTrampoline:
3706 break;
3707
3708 case eSymbolTypeCode:
3709 case eSymbolTypeResolver:
3710 case eSymbolTypeData:
3711 case eSymbolTypeRuntime:
3712 case eSymbolTypeException:
3713 case eSymbolTypeObjCClass:
3714 case eSymbolTypeObjCMetaClass:
3715 case eSymbolTypeObjCIVar:
3716 case eSymbolTypeReExported:
3717 symbol_load_addr =
3718 sc.symbol->GetLoadAddress(&process->GetTarget());
3719 break;
3720 }
Jason Molenda50018d32016-01-13 04:08:10 +00003721 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003722 }
Greg Clayton42b01482015-08-11 22:07:46 +00003723 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003724 }
3725 // This is the normal path where our symbol lookup was successful
3726 // and we want
3727 // to send a packet with the new symbol value and see if another
3728 // lookup needs to be
3729 // done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003730
Kate Stoneb9c1b512016-09-06 20:57:50 +00003731 // Change "packet" to contain the requested symbol value and name
3732 packet.Clear();
3733 packet.PutCString("qSymbol:");
3734 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3735 packet.Printf("%" PRIx64, symbol_load_addr);
3736 symbol_response_provided = true;
3737 } else {
3738 symbol_response_provided = false;
3739 }
3740 packet.PutCString(":");
3741 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3742 continue; // go back to the while loop and send "packet" and wait
3743 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003744 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003745 }
3746 }
3747 }
3748 // If we make it here, the symbol request packet response wasn't valid or
3749 // our symbol lookup failed so we must abort
3750 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003751
Kate Stoneb9c1b512016-09-06 20:57:50 +00003752 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3753 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3754 log->Printf(
3755 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3756 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003757 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003758 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003759}
3760
Kate Stoneb9c1b512016-09-06 20:57:50 +00003761StructuredData::Array *
3762GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3763 if (!m_supported_async_json_packets_is_valid) {
3764 // Query the server for the array of supported asynchronous JSON
3765 // packets.
3766 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003767
Kate Stoneb9c1b512016-09-06 20:57:50 +00003768 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003769
Kate Stoneb9c1b512016-09-06 20:57:50 +00003770 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003771 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003772 const bool send_async = false;
3773 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3774 send_async) == PacketResult::Success) {
3775 m_supported_async_json_packets_sp =
3776 StructuredData::ParseJSON(response.GetStringRef());
3777 if (m_supported_async_json_packets_sp &&
3778 !m_supported_async_json_packets_sp->GetAsArray()) {
3779 // We were returned something other than a JSON array. This
3780 // is invalid. Clear it out.
3781 if (log)
3782 log->Printf("GDBRemoteCommunicationClient::%s(): "
3783 "QSupportedAsyncJSONPackets returned invalid "
3784 "result: %s",
3785 __FUNCTION__, response.GetStringRef().c_str());
3786 m_supported_async_json_packets_sp.reset();
3787 }
3788 } else {
3789 if (log)
3790 log->Printf("GDBRemoteCommunicationClient::%s(): "
3791 "QSupportedAsyncJSONPackets unsupported",
3792 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003793 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003794
3795 if (log && m_supported_async_json_packets_sp) {
3796 StreamString stream;
3797 m_supported_async_json_packets_sp->Dump(stream);
3798 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3799 "JSON packets: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00003800 __FUNCTION__, stream.GetData());
Todd Fiala75930012016-08-19 04:21:48 +00003801 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003802 }
3803
3804 return m_supported_async_json_packets_sp
3805 ? m_supported_async_json_packets_sp->GetAsArray()
3806 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003807}
3808
Zachary Turner97206d52017-05-12 04:51:55 +00003809Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003810 llvm::ArrayRef<int32_t> signals) {
3811 // Format packet:
3812 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3813 auto range = llvm::make_range(signals.begin(), signals.end());
3814 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3815
3816 StringExtractorGDBRemote response;
3817 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3818
3819 if (send_status != GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00003820 return Status("Sending QPassSignals packet failed");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003821
3822 if (response.IsOKResponse()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003823 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003824 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00003825 return Status("Unknown error happened during sending QPassSignals packet.");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003826 }
3827}
3828
Zachary Turner97206d52017-05-12 04:51:55 +00003829Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003830 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00003831 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003832
3833 if (type_name.GetLength() == 0) {
3834 error.SetErrorString("invalid type_name argument");
3835 return error;
3836 }
3837
3838 // Build command: Configure{type_name}: serialized config
3839 // data.
3840 StreamGDBRemote stream;
3841 stream.PutCString("QConfigure");
3842 stream.PutCString(type_name.AsCString());
3843 stream.PutChar(':');
3844 if (config_sp) {
3845 // Gather the plain-text version of the configuration data.
3846 StreamString unescaped_stream;
3847 config_sp->Dump(unescaped_stream);
3848 unescaped_stream.Flush();
3849
3850 // Add it to the stream in escaped fashion.
Zachary Turnerc1564272016-11-16 21:15:24 +00003851 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003852 unescaped_stream.GetSize());
3853 }
3854 stream.Flush();
3855
3856 // Send the packet.
3857 const bool send_async = false;
3858 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003859 auto result =
3860 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003861 if (result == PacketResult::Success) {
3862 // We failed if the config result comes back other than OK.
3863 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3864 // Okay!
3865 error.Clear();
3866 } else {
3867 error.SetErrorStringWithFormat("configuring StructuredData feature "
3868 "%s failed with error %s",
3869 type_name.AsCString(),
3870 response.GetStringRef().c_str());
3871 }
3872 } else {
3873 // Can we get more data here on the failure?
3874 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3875 "failed when sending packet: "
3876 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00003877 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003878 }
3879 return error;
3880}
3881
3882void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
3883 GDBRemoteClientBase::OnRunPacketSent(first);
3884 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003885}