blob: 0078a14a060bd4f619b41214ea231022c1efb305 [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)
1025 // libcompression is weak linked so test if compression_decode_buffer() is
1026 // available
1027 if (compression_decode_buffer != NULL &&
1028 avail_type == CompressionType::None) {
1029 for (auto compression : supported_compressions) {
1030 if (compression == "lzfse") {
1031 avail_type = CompressionType::LZFSE;
1032 avail_name = compression;
1033 break;
1034 }
1035 }
1036 }
1037#endif
1038
1039#if defined(HAVE_LIBCOMPRESSION)
1040 // libcompression is weak linked so test if compression_decode_buffer() is
1041 // available
1042 if (compression_decode_buffer != NULL &&
1043 avail_type == CompressionType::None) {
1044 for (auto compression : supported_compressions) {
1045 if (compression == "zlib-deflate") {
1046 avail_type = CompressionType::ZlibDeflate;
1047 avail_name = compression;
1048 break;
1049 }
1050 }
1051 }
1052#endif
1053
1054#if defined(HAVE_LIBZ)
1055 if (avail_type == CompressionType::None) {
1056 for (auto compression : supported_compressions) {
1057 if (compression == "zlib-deflate") {
1058 avail_type = CompressionType::ZlibDeflate;
1059 avail_name = compression;
1060 break;
1061 }
1062 }
1063 }
1064#endif
1065
1066#if defined(HAVE_LIBCOMPRESSION)
1067 // libcompression is weak linked so test if compression_decode_buffer() is
1068 // available
1069 if (compression_decode_buffer != NULL &&
1070 avail_type == CompressionType::None) {
1071 for (auto compression : supported_compressions) {
1072 if (compression == "lz4") {
1073 avail_type = CompressionType::LZ4;
1074 avail_name = compression;
1075 break;
1076 }
1077 }
1078 }
1079#endif
1080
1081#if defined(HAVE_LIBCOMPRESSION)
1082 // libcompression is weak linked so test if compression_decode_buffer() is
1083 // available
1084 if (compression_decode_buffer != NULL &&
1085 avail_type == CompressionType::None) {
1086 for (auto compression : supported_compressions) {
1087 if (compression == "lzma") {
1088 avail_type = CompressionType::LZMA;
1089 avail_name = compression;
1090 break;
1091 }
1092 }
1093 }
1094#endif
1095
1096 if (avail_type != CompressionType::None) {
Greg Clayton576d8832011-03-22 04:00:09 +00001097 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001098 std::string packet = "QEnableCompression:type:" + avail_name + ";";
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001099 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100 PacketResult::Success)
1101 return;
1102
1103 if (response.IsOKResponse()) {
1104 m_compression_type = avail_type;
Greg Clayton576d8832011-03-22 04:00:09 +00001105 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106 }
Greg Clayton576d8832011-03-22 04:00:09 +00001107}
Greg Clayton32e0a752011-03-30 18:16:51 +00001108
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1110 if (GetGDBServerVersion()) {
1111 if (!m_gdb_server_name.empty())
1112 return m_gdb_server_name.c_str();
1113 }
1114 return NULL;
1115}
1116
1117uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1118 if (GetGDBServerVersion())
1119 return m_gdb_server_version;
1120 return 0;
1121}
1122
1123bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1124 StringExtractorGDBRemote response;
1125 if (SendPacketAndWaitForResponse("qC", response, false) !=
1126 PacketResult::Success)
1127 return false;
1128
1129 if (!response.IsNormalResponse())
1130 return false;
1131
1132 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1133 tid = response.GetHexMaxU32(true, -1);
1134
1135 return true;
1136}
1137
1138bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1139 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1140
1141 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1142 m_qHostInfo_is_valid = eLazyBoolNo;
Jim Ingham106d0282014-06-25 02:32:56 +00001143 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001144 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1145 PacketResult::Success) {
1146 if (response.IsNormalResponse()) {
Zachary Turner54695a32016-08-29 19:58:14 +00001147 llvm::StringRef name;
1148 llvm::StringRef value;
Jason Molenda89c37492014-01-27 22:23:20 +00001149 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1150 uint32_t sub = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001151 std::string arch_name;
1152 std::string os_name;
1153 std::string vendor_name;
1154 std::string triple;
1155 std::string distribution_id;
1156 uint32_t pointer_byte_size = 0;
1157 ByteOrder byte_order = eByteOrderInvalid;
1158 uint32_t num_keys_decoded = 0;
1159 while (response.GetNameColonValue(name, value)) {
1160 if (name.equals("cputype")) {
1161 // exception type in big endian hex
1162 if (!value.getAsInteger(0, cpu))
1163 ++num_keys_decoded;
1164 } else if (name.equals("cpusubtype")) {
1165 // exception count in big endian hex
1166 if (!value.getAsInteger(0, sub))
1167 ++num_keys_decoded;
1168 } else if (name.equals("arch")) {
1169 arch_name = value;
1170 ++num_keys_decoded;
1171 } else if (name.equals("triple")) {
1172 StringExtractor extractor(value);
1173 extractor.GetHexByteString(triple);
1174 ++num_keys_decoded;
1175 } else if (name.equals("distribution_id")) {
1176 StringExtractor extractor(value);
1177 extractor.GetHexByteString(distribution_id);
1178 ++num_keys_decoded;
1179 } else if (name.equals("os_build")) {
1180 StringExtractor extractor(value);
1181 extractor.GetHexByteString(m_os_build);
1182 ++num_keys_decoded;
1183 } else if (name.equals("hostname")) {
1184 StringExtractor extractor(value);
1185 extractor.GetHexByteString(m_hostname);
1186 ++num_keys_decoded;
1187 } else if (name.equals("os_kernel")) {
1188 StringExtractor extractor(value);
1189 extractor.GetHexByteString(m_os_kernel);
1190 ++num_keys_decoded;
1191 } else if (name.equals("ostype")) {
1192 os_name = value;
1193 ++num_keys_decoded;
1194 } else if (name.equals("vendor")) {
1195 vendor_name = value;
1196 ++num_keys_decoded;
1197 } else if (name.equals("endian")) {
1198 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1199 .Case("little", eByteOrderLittle)
1200 .Case("big", eByteOrderBig)
1201 .Case("pdp", eByteOrderPDP)
1202 .Default(eByteOrderInvalid);
1203 if (byte_order != eByteOrderInvalid)
1204 ++num_keys_decoded;
1205 } else if (name.equals("ptrsize")) {
1206 if (!value.getAsInteger(0, pointer_byte_size))
1207 ++num_keys_decoded;
1208 } else if (name.equals("os_version") ||
1209 name.equals(
1210 "version")) // Older debugserver binaries used the
1211 // "version" key instead of
1212 // "os_version"...
1213 {
Zachary Turner6fa7681b2016-09-17 02:00:02 +00001214 Args::StringToVersion(value, m_os_version_major, m_os_version_minor,
1215 m_os_version_update);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001216 if (m_os_version_major != UINT32_MAX)
1217 ++num_keys_decoded;
1218 } else if (name.equals("watchpoint_exceptions_received")) {
1219 m_watchpoints_trigger_after_instruction =
1220 llvm::StringSwitch<LazyBool>(value)
1221 .Case("before", eLazyBoolNo)
1222 .Case("after", eLazyBoolYes)
1223 .Default(eLazyBoolCalculate);
1224 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1225 ++num_keys_decoded;
1226 } else if (name.equals("default_packet_timeout")) {
Pavel Labath3aa04912016-10-31 17:19:42 +00001227 uint32_t timeout_seconds;
1228 if (!value.getAsInteger(0, timeout_seconds)) {
Pavel Labath1eff73c2016-11-24 10:54:49 +00001229 m_default_packet_timeout = seconds(timeout_seconds);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230 SetPacketTimeout(m_default_packet_timeout);
1231 ++num_keys_decoded;
Greg Clayton32e0a752011-03-30 18:16:51 +00001232 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233 }
Jason Molenda89c37492014-01-27 22:23:20 +00001234 }
1235
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236 if (num_keys_decoded > 0)
1237 m_qHostInfo_is_valid = eLazyBoolYes;
1238
1239 if (triple.empty()) {
1240 if (arch_name.empty()) {
1241 if (cpu != LLDB_INVALID_CPUTYPE) {
1242 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1243 if (pointer_byte_size) {
1244 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1245 }
1246 if (byte_order != eByteOrderInvalid) {
1247 assert(byte_order == m_host_arch.GetByteOrder());
1248 }
1249
1250 if (!vendor_name.empty())
1251 m_host_arch.GetTriple().setVendorName(
1252 llvm::StringRef(vendor_name));
1253 if (!os_name.empty())
1254 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Jason Molenda89c37492014-01-27 22:23:20 +00001255 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 } else {
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001257 std::string triple;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 triple += arch_name;
1259 if (!vendor_name.empty() || !os_name.empty()) {
1260 triple += '-';
1261 if (vendor_name.empty())
1262 triple += "unknown";
1263 else
1264 triple += vendor_name;
1265 triple += '-';
1266 if (os_name.empty())
1267 triple += "unknown";
1268 else
1269 triple += os_name;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001270 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001271 m_host_arch.SetTriple(triple.c_str());
Todd Fialac540dd02014-08-26 18:21:02 +00001272
Kate Stoneb9c1b512016-09-06 20:57:50 +00001273 llvm::Triple &host_triple = m_host_arch.GetTriple();
1274 if (host_triple.getVendor() == llvm::Triple::Apple &&
1275 host_triple.getOS() == llvm::Triple::Darwin) {
1276 switch (m_host_arch.GetMachine()) {
1277 case llvm::Triple::aarch64:
1278 case llvm::Triple::arm:
1279 case llvm::Triple::thumb:
1280 host_triple.setOS(llvm::Triple::IOS);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001281 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282 default:
1283 host_triple.setOS(llvm::Triple::MacOSX);
1284 break;
1285 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001286 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001287 if (pointer_byte_size) {
1288 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1289 }
1290 if (byte_order != eByteOrderInvalid) {
1291 assert(byte_order == m_host_arch.GetByteOrder());
1292 }
1293 }
1294 } else {
1295 m_host_arch.SetTriple(triple.c_str());
1296 if (pointer_byte_size) {
1297 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1298 }
1299 if (byte_order != eByteOrderInvalid) {
1300 assert(byte_order == m_host_arch.GetByteOrder());
1301 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001302
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303 if (log)
1304 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1305 "architecture as %s, triple as %s from triple text %s",
1306 __FUNCTION__, m_host_arch.GetArchitectureName()
1307 ? m_host_arch.GetArchitectureName()
1308 : "<null-arch-name>",
1309 m_host_arch.GetTriple().getTriple().c_str(),
1310 triple.c_str());
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001311 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312 if (!distribution_id.empty())
1313 m_host_arch.SetDistributionId(distribution_id.c_str());
1314 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001315 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316 }
1317 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Claytonadc00cb2011-05-20 23:38:13 +00001318}
Greg Clayton37a0a242012-04-11 00:24:49 +00001319
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320int GDBRemoteCommunicationClient::SendAttach(
1321 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1322 if (pid != LLDB_INVALID_PROCESS_ID) {
1323 char packet[64];
1324 const int packet_len =
1325 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001326 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001327 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001328 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001329 PacketResult::Success) {
1330 if (response.IsErrorResponse())
1331 return response.GetError();
1332 return 0;
1333 }
1334 }
1335 return -1;
1336}
1337
1338int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1339 size_t data_len) {
1340 StreamString packet;
1341 packet.PutCString("I");
1342 packet.PutBytesAsRawHex8(data, data_len);
1343 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001344 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1345 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001346 return 0;
1347 }
1348 return response.GetError();
1349}
1350
1351const lldb_private::ArchSpec &
1352GDBRemoteCommunicationClient::GetHostArchitecture() {
1353 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1354 GetHostInfo();
1355 return m_host_arch;
1356}
1357
Pavel Labath1eff73c2016-11-24 10:54:49 +00001358seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001359 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1360 GetHostInfo();
1361 return m_default_packet_timeout;
1362}
1363
1364addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1365 uint32_t permissions) {
1366 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1367 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1368 char packet[64];
1369 const int packet_len = ::snprintf(
1370 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1371 permissions & lldb::ePermissionsReadable ? "r" : "",
1372 permissions & lldb::ePermissionsWritable ? "w" : "",
1373 permissions & lldb::ePermissionsExecutable ? "x" : "");
1374 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001375 UNUSED_IF_ASSERT_DISABLED(packet_len);
Pavel Labath83082a02016-08-18 14:33:55 +00001376 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001377 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001378 PacketResult::Success) {
1379 if (response.IsUnsupportedResponse())
1380 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1381 else if (!response.IsErrorResponse())
1382 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1383 } else {
1384 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1385 }
1386 }
1387 return LLDB_INVALID_ADDRESS;
1388}
1389
1390bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1391 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1392 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1393 char packet[64];
1394 const int packet_len =
1395 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1396 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001397 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001398 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001399 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001400 PacketResult::Success) {
1401 if (response.IsUnsupportedResponse())
1402 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1403 else if (response.IsOKResponse())
1404 return true;
1405 } else {
1406 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1407 }
1408 }
1409 return false;
1410}
1411
Zachary Turner97206d52017-05-12 04:51:55 +00001412Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1413 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001414
1415 if (keep_stopped) {
1416 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1417 char packet[64];
1418 const int packet_len =
1419 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1420 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001421 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001422 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001423 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001424 PacketResult::Success &&
1425 response.IsOKResponse()) {
1426 m_supports_detach_stay_stopped = eLazyBoolYes;
1427 } else {
1428 m_supports_detach_stay_stopped = eLazyBoolNo;
1429 }
1430 }
1431
1432 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1433 error.SetErrorString("Stays stopped not supported by this target.");
1434 return error;
1435 } else {
1436 StringExtractorGDBRemote response;
1437 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001438 SendPacketAndWaitForResponse("D1", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001439 if (packet_result != PacketResult::Success)
1440 error.SetErrorString("Sending extended disconnect packet failed.");
1441 }
1442 } else {
1443 StringExtractorGDBRemote response;
1444 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001445 SendPacketAndWaitForResponse("D", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001446 if (packet_result != PacketResult::Success)
1447 error.SetErrorString("Sending disconnect packet failed.");
1448 }
1449 return error;
1450}
1451
Zachary Turner97206d52017-05-12 04:51:55 +00001452Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001453 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001454 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001455 region_info.Clear();
1456
1457 if (m_supports_memory_region_info != eLazyBoolNo) {
1458 m_supports_memory_region_info = eLazyBoolYes;
1459 char packet[64];
1460 const int packet_len = ::snprintf(
1461 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1462 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001463 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001464 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001465 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001466 PacketResult::Success) {
1467 llvm::StringRef name;
1468 llvm::StringRef value;
1469 addr_t addr_value = LLDB_INVALID_ADDRESS;
1470 bool success = true;
1471 bool saw_permissions = false;
1472 while (success && response.GetNameColonValue(name, value)) {
1473 if (name.equals("start")) {
1474 if (!value.getAsInteger(16, addr_value))
1475 region_info.GetRange().SetRangeBase(addr_value);
1476 } else if (name.equals("size")) {
1477 if (!value.getAsInteger(16, addr_value))
1478 region_info.GetRange().SetByteSize(addr_value);
1479 } else if (name.equals("permissions") &&
1480 region_info.GetRange().IsValid()) {
1481 saw_permissions = true;
1482 if (region_info.GetRange().Contains(addr)) {
1483 if (value.find('r') != llvm::StringRef::npos)
1484 region_info.SetReadable(MemoryRegionInfo::eYes);
1485 else
1486 region_info.SetReadable(MemoryRegionInfo::eNo);
1487
1488 if (value.find('w') != llvm::StringRef::npos)
1489 region_info.SetWritable(MemoryRegionInfo::eYes);
1490 else
1491 region_info.SetWritable(MemoryRegionInfo::eNo);
1492
1493 if (value.find('x') != llvm::StringRef::npos)
1494 region_info.SetExecutable(MemoryRegionInfo::eYes);
1495 else
1496 region_info.SetExecutable(MemoryRegionInfo::eNo);
1497
1498 region_info.SetMapped(MemoryRegionInfo::eYes);
1499 } else {
1500 // The reported region does not contain this address -- we're
1501 // looking at an unmapped page
1502 region_info.SetReadable(MemoryRegionInfo::eNo);
1503 region_info.SetWritable(MemoryRegionInfo::eNo);
1504 region_info.SetExecutable(MemoryRegionInfo::eNo);
1505 region_info.SetMapped(MemoryRegionInfo::eNo);
1506 }
1507 } else if (name.equals("name")) {
1508 StringExtractorGDBRemote name_extractor(value);
1509 std::string name;
1510 name_extractor.GetHexByteString(name);
1511 region_info.SetName(name.c_str());
1512 } else if (name.equals("error")) {
1513 StringExtractorGDBRemote error_extractor(value);
1514 std::string error_string;
1515 // Now convert the HEX bytes into a string value
1516 error_extractor.GetHexByteString(error_string);
1517 error.SetErrorString(error_string.c_str());
1518 }
1519 }
1520
Stephane Sezer48d14272017-03-31 18:00:48 +00001521 if (region_info.GetRange().IsValid()) {
1522 // We got a valid address range back but no permissions -- which means
1523 // this is an unmapped page
1524 if (!saw_permissions) {
1525 region_info.SetReadable(MemoryRegionInfo::eNo);
1526 region_info.SetWritable(MemoryRegionInfo::eNo);
1527 region_info.SetExecutable(MemoryRegionInfo::eNo);
1528 region_info.SetMapped(MemoryRegionInfo::eNo);
1529 }
1530 } else {
1531 // We got an invalid address range back
1532 error.SetErrorString("Server returned invalid range");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001533 }
1534 } else {
1535 m_supports_memory_region_info = eLazyBoolNo;
1536 }
1537 }
1538
1539 if (m_supports_memory_region_info == eLazyBoolNo) {
1540 error.SetErrorString("qMemoryRegionInfo is not supported");
1541 }
1542 if (error.Fail())
1543 region_info.Clear();
1544 return error;
1545}
1546
Zachary Turner97206d52017-05-12 04:51:55 +00001547Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1548 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001549
1550 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1551 num = m_num_supported_hardware_watchpoints;
1552 return error;
1553 }
1554
1555 // Set num to 0 first.
1556 num = 0;
1557 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1558 char packet[64];
1559 const int packet_len =
1560 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1561 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001562 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001563 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001564 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001565 PacketResult::Success) {
1566 m_supports_watchpoint_support_info = eLazyBoolYes;
1567 llvm::StringRef name;
1568 llvm::StringRef value;
1569 while (response.GetNameColonValue(name, value)) {
1570 if (name.equals("num")) {
1571 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1572 num = m_num_supported_hardware_watchpoints;
1573 }
1574 }
1575 } else {
1576 m_supports_watchpoint_support_info = eLazyBoolNo;
1577 }
1578 }
1579
1580 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1581 error.SetErrorString("qWatchpointSupportInfo is not supported");
1582 }
1583 return error;
1584}
1585
Zachary Turner97206d52017-05-12 04:51:55 +00001586lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001587 uint32_t &num, bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001588 Status error(GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001589 if (error.Success())
1590 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1591 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001592}
1593
Zachary Turner97206d52017-05-12 04:51:55 +00001594lldb_private::Status
Kate Stoneb9c1b512016-09-06 20:57:50 +00001595GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1596 bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001597 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598 llvm::Triple::ArchType atype = arch.GetMachine();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001599
Kate Stoneb9c1b512016-09-06 20:57:50 +00001600 // we assume watchpoints will happen after running the relevant opcode
1601 // and we only want to override this behavior if we have explicitly
1602 // received a qHostInfo telling us otherwise
1603 if (m_qHostInfo_is_valid != eLazyBoolYes) {
Pavel Labathc51ad482017-10-27 17:02:32 +00001604 // On targets like MIPS and ppc64le, watchpoint exceptions are always
1605 // generated before the instruction is executed. The connected target
1606 // may not support qHostInfo or qWatchpointSupportInfo packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001607 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
Pavel Labathc51ad482017-10-27 17:02:32 +00001608 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el ||
1609 atype == llvm::Triple::ppc64le)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001610 after = false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001611 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001612 after = true;
1613 } else {
Pavel Labathc51ad482017-10-27 17:02:32 +00001614 // For MIPS and ppc64le, set m_watchpoints_trigger_after_instruction to
1615 // eLazyBoolNo if it is not calculated before.
1616 if ((m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1617 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1618 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)) ||
1619 atype == llvm::Triple::ppc64le) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001620 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
Pavel Labathc51ad482017-10-27 17:02:32 +00001621 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001622
1623 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1624 }
1625 return error;
1626}
1627
1628int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1629 if (file_spec) {
1630 std::string path{file_spec.GetPath(false)};
1631 StreamString packet;
1632 packet.PutCString("QSetSTDIN:");
1633 packet.PutCStringAsRawHex8(path.c_str());
1634
1635 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001636 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1637 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001638 if (response.IsOKResponse())
1639 return 0;
1640 uint8_t error = response.GetError();
1641 if (error)
1642 return error;
1643 }
1644 }
1645 return -1;
1646}
1647
1648int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1649 if (file_spec) {
1650 std::string path{file_spec.GetPath(false)};
1651 StreamString packet;
1652 packet.PutCString("QSetSTDOUT:");
1653 packet.PutCStringAsRawHex8(path.c_str());
1654
1655 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001656 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1657 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001658 if (response.IsOKResponse())
1659 return 0;
1660 uint8_t error = response.GetError();
1661 if (error)
1662 return error;
1663 }
1664 }
1665 return -1;
1666}
1667
1668int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1669 if (file_spec) {
1670 std::string path{file_spec.GetPath(false)};
1671 StreamString packet;
1672 packet.PutCString("QSetSTDERR:");
1673 packet.PutCStringAsRawHex8(path.c_str());
1674
1675 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001676 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1677 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001678 if (response.IsOKResponse())
1679 return 0;
1680 uint8_t error = response.GetError();
1681 if (error)
1682 return error;
1683 }
1684 }
1685 return -1;
1686}
1687
1688bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1689 StringExtractorGDBRemote response;
1690 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1691 PacketResult::Success) {
1692 if (response.IsUnsupportedResponse())
1693 return false;
1694 if (response.IsErrorResponse())
1695 return false;
1696 std::string cwd;
1697 response.GetHexByteString(cwd);
Zachary Turner8c6b5462017-03-06 23:42:44 +00001698 working_dir.SetFile(cwd, false, GetHostArchitecture().GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001699 return !cwd.empty();
1700 }
1701 return false;
1702}
1703
1704int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1705 if (working_dir) {
1706 std::string path{working_dir.GetPath(false)};
1707 StreamString packet;
1708 packet.PutCString("QSetWorkingDir:");
1709 packet.PutCStringAsRawHex8(path.c_str());
1710
1711 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001712 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1713 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001714 if (response.IsOKResponse())
1715 return 0;
1716 uint8_t error = response.GetError();
1717 if (error)
1718 return error;
1719 }
1720 }
1721 return -1;
1722}
1723
1724int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1725 char packet[32];
1726 const int packet_len =
1727 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1728 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001729 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001731 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732 PacketResult::Success) {
1733 if (response.IsOKResponse())
1734 return 0;
1735 uint8_t error = response.GetError();
1736 if (error)
1737 return error;
1738 }
1739 return -1;
1740}
1741
1742int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1743 char packet[32];
1744 const int packet_len = ::snprintf(packet, sizeof(packet),
1745 "QSetDetachOnError:%i", enable ? 1 : 0);
1746 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001747 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001748 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001749 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001750 PacketResult::Success) {
1751 if (response.IsOKResponse())
1752 return 0;
1753 uint8_t error = response.GetError();
1754 if (error)
1755 return error;
1756 }
1757 return -1;
1758}
1759
1760bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1761 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1762 if (response.IsNormalResponse()) {
1763 llvm::StringRef name;
1764 llvm::StringRef value;
1765 StringExtractor extractor;
1766
1767 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1768 uint32_t sub = 0;
1769 std::string vendor;
1770 std::string os_type;
1771
1772 while (response.GetNameColonValue(name, value)) {
1773 if (name.equals("pid")) {
1774 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1775 value.getAsInteger(0, pid);
1776 process_info.SetProcessID(pid);
1777 } else if (name.equals("ppid")) {
1778 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1779 value.getAsInteger(0, pid);
1780 process_info.SetParentProcessID(pid);
1781 } else if (name.equals("uid")) {
1782 uint32_t uid = UINT32_MAX;
1783 value.getAsInteger(0, uid);
1784 process_info.SetUserID(uid);
1785 } else if (name.equals("euid")) {
1786 uint32_t uid = UINT32_MAX;
1787 value.getAsInteger(0, uid);
1788 process_info.SetEffectiveGroupID(uid);
1789 } else if (name.equals("gid")) {
1790 uint32_t gid = UINT32_MAX;
1791 value.getAsInteger(0, gid);
1792 process_info.SetGroupID(gid);
1793 } else if (name.equals("egid")) {
1794 uint32_t gid = UINT32_MAX;
1795 value.getAsInteger(0, gid);
1796 process_info.SetEffectiveGroupID(gid);
1797 } else if (name.equals("triple")) {
1798 StringExtractor extractor(value);
1799 std::string triple;
1800 extractor.GetHexByteString(triple);
1801 process_info.GetArchitecture().SetTriple(triple.c_str());
1802 } else if (name.equals("name")) {
1803 StringExtractor extractor(value);
1804 // The process name from ASCII hex bytes since we can't
1805 // control the characters in a process name
1806 std::string name;
1807 extractor.GetHexByteString(name);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001808 process_info.GetExecutableFile().SetFile(name, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001809 } else if (name.equals("cputype")) {
1810 value.getAsInteger(0, cpu);
1811 } else if (name.equals("cpusubtype")) {
1812 value.getAsInteger(0, sub);
1813 } else if (name.equals("vendor")) {
1814 vendor = value;
1815 } else if (name.equals("ostype")) {
1816 os_type = value;
1817 }
1818 }
1819
1820 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1821 if (vendor == "apple") {
1822 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1823 sub);
1824 process_info.GetArchitecture().GetTriple().setVendorName(
1825 llvm::StringRef(vendor));
1826 process_info.GetArchitecture().GetTriple().setOSName(
1827 llvm::StringRef(os_type));
1828 }
1829 }
1830
1831 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1832 return true;
1833 }
1834 return false;
1835}
1836
1837bool GDBRemoteCommunicationClient::GetProcessInfo(
1838 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1839 process_info.Clear();
1840
1841 if (m_supports_qProcessInfoPID) {
1842 char packet[32];
1843 const int packet_len =
1844 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1845 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001846 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001847 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001848 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001849 PacketResult::Success) {
1850 return DecodeProcessInfoResponse(response, process_info);
1851 } else {
1852 m_supports_qProcessInfoPID = false;
1853 return false;
1854 }
1855 }
1856 return false;
1857}
1858
1859bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1860 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1861 GDBR_LOG_PACKETS));
1862
1863 if (allow_lazy) {
1864 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1865 return true;
1866 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1867 return false;
1868 }
1869
1870 GetHostInfo();
1871
1872 StringExtractorGDBRemote response;
1873 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1874 PacketResult::Success) {
1875 if (response.IsNormalResponse()) {
1876 llvm::StringRef name;
1877 llvm::StringRef value;
1878 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1879 uint32_t sub = 0;
1880 std::string arch_name;
1881 std::string os_name;
1882 std::string vendor_name;
1883 std::string triple;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001884 std::string elf_abi;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001885 uint32_t pointer_byte_size = 0;
1886 StringExtractor extractor;
1887 ByteOrder byte_order = eByteOrderInvalid;
1888 uint32_t num_keys_decoded = 0;
1889 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1890 while (response.GetNameColonValue(name, value)) {
1891 if (name.equals("cputype")) {
1892 if (!value.getAsInteger(16, cpu))
1893 ++num_keys_decoded;
1894 } else if (name.equals("cpusubtype")) {
1895 if (!value.getAsInteger(16, sub))
1896 ++num_keys_decoded;
1897 } else if (name.equals("triple")) {
1898 StringExtractor extractor(value);
1899 extractor.GetHexByteString(triple);
1900 ++num_keys_decoded;
1901 } else if (name.equals("ostype")) {
1902 os_name = value;
1903 ++num_keys_decoded;
1904 } else if (name.equals("vendor")) {
1905 vendor_name = value;
1906 ++num_keys_decoded;
1907 } else if (name.equals("endian")) {
1908 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1909 .Case("little", eByteOrderLittle)
1910 .Case("big", eByteOrderBig)
1911 .Case("pdp", eByteOrderPDP)
1912 .Default(eByteOrderInvalid);
1913 if (byte_order != eByteOrderInvalid)
1914 ++num_keys_decoded;
1915 } else if (name.equals("ptrsize")) {
1916 if (!value.getAsInteger(16, pointer_byte_size))
1917 ++num_keys_decoded;
1918 } else if (name.equals("pid")) {
1919 if (!value.getAsInteger(16, pid))
1920 ++num_keys_decoded;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001921 } else if (name.equals("elf_abi")) {
1922 elf_abi = value;
1923 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001924 }
1925 }
1926 if (num_keys_decoded > 0)
1927 m_qProcessInfo_is_valid = eLazyBoolYes;
1928 if (pid != LLDB_INVALID_PROCESS_ID) {
1929 m_curr_pid_is_valid = eLazyBoolYes;
1930 m_curr_pid = pid;
1931 }
1932
1933 // Set the ArchSpec from the triple if we have it.
1934 if (!triple.empty()) {
1935 m_process_arch.SetTriple(triple.c_str());
Nitesh Jain8999edf2016-10-12 10:21:09 +00001936 m_process_arch.SetFlags(elf_abi);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001937 if (pointer_byte_size) {
1938 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1939 }
1940 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
1941 !vendor_name.empty()) {
1942 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
1943
1944 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
Pavel Labath4f19fce22017-02-17 13:39:50 +00001945 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001946 switch (triple.getObjectFormat()) {
1947 case llvm::Triple::MachO:
1948 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1949 break;
1950 case llvm::Triple::ELF:
1951 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
1952 break;
1953 case llvm::Triple::COFF:
1954 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
1955 break;
Pavel Labath4f19fce22017-02-17 13:39:50 +00001956 case llvm::Triple::Wasm:
1957 if (log)
1958 log->Printf("error: not supported target architecture");
1959 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001960 case llvm::Triple::UnknownObjectFormat:
1961 if (log)
1962 log->Printf("error: failed to determine target architecture");
1963 return false;
1964 }
1965
1966 if (pointer_byte_size) {
1967 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1968 }
1969 if (byte_order != eByteOrderInvalid) {
1970 assert(byte_order == m_process_arch.GetByteOrder());
1971 }
1972 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1973 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1974 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1975 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1976 }
1977 return true;
1978 }
1979 } else {
1980 m_qProcessInfo_is_valid = eLazyBoolNo;
1981 }
1982
1983 return false;
1984}
1985
1986uint32_t GDBRemoteCommunicationClient::FindProcesses(
1987 const ProcessInstanceInfoMatch &match_info,
1988 ProcessInstanceInfoList &process_infos) {
1989 process_infos.Clear();
1990
1991 if (m_supports_qfProcessInfo) {
1992 StreamString packet;
1993 packet.PutCString("qfProcessInfo");
1994 if (!match_info.MatchAllProcesses()) {
1995 packet.PutChar(':');
1996 const char *name = match_info.GetProcessInfo().GetName();
1997 bool has_name_match = false;
1998 if (name && name[0]) {
1999 has_name_match = true;
Pavel Labathc4a33952017-02-20 11:35:33 +00002000 NameMatch name_match_type = match_info.GetNameMatchType();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002001 switch (name_match_type) {
Pavel Labathc4a33952017-02-20 11:35:33 +00002002 case NameMatch::Ignore:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002003 has_name_match = false;
2004 break;
2005
Pavel Labathc4a33952017-02-20 11:35:33 +00002006 case NameMatch::Equals:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002007 packet.PutCString("name_match:equals;");
2008 break;
2009
Pavel Labathc4a33952017-02-20 11:35:33 +00002010 case NameMatch::Contains:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002011 packet.PutCString("name_match:contains;");
2012 break;
2013
Pavel Labathc4a33952017-02-20 11:35:33 +00002014 case NameMatch::StartsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002015 packet.PutCString("name_match:starts_with;");
2016 break;
2017
Pavel Labathc4a33952017-02-20 11:35:33 +00002018 case NameMatch::EndsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002019 packet.PutCString("name_match:ends_with;");
2020 break;
2021
Pavel Labathc4a33952017-02-20 11:35:33 +00002022 case NameMatch::RegularExpression:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002023 packet.PutCString("name_match:regex;");
2024 break;
2025 }
2026 if (has_name_match) {
2027 packet.PutCString("name:");
2028 packet.PutBytesAsRawHex8(name, ::strlen(name));
2029 packet.PutChar(';');
2030 }
2031 }
2032
2033 if (match_info.GetProcessInfo().ProcessIDIsValid())
2034 packet.Printf("pid:%" PRIu64 ";",
2035 match_info.GetProcessInfo().GetProcessID());
2036 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2037 packet.Printf("parent_pid:%" PRIu64 ";",
2038 match_info.GetProcessInfo().GetParentProcessID());
2039 if (match_info.GetProcessInfo().UserIDIsValid())
2040 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2041 if (match_info.GetProcessInfo().GroupIDIsValid())
2042 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2043 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2044 packet.Printf("euid:%u;",
2045 match_info.GetProcessInfo().GetEffectiveUserID());
2046 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2047 packet.Printf("egid:%u;",
2048 match_info.GetProcessInfo().GetEffectiveGroupID());
2049 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2050 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2051 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2052 const ArchSpec &match_arch =
2053 match_info.GetProcessInfo().GetArchitecture();
2054 const llvm::Triple &triple = match_arch.GetTriple();
2055 packet.PutCString("triple:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002056 packet.PutCString(triple.getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002057 packet.PutChar(';');
2058 }
2059 }
2060 StringExtractorGDBRemote response;
2061 // Increase timeout as the first qfProcessInfo packet takes a long time
2062 // on Android. The value of 1min was arrived at empirically.
Pavel Labath1eff73c2016-11-24 10:54:49 +00002063 ScopedTimeout timeout(*this, minutes(1));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002064 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2065 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002066 do {
2067 ProcessInstanceInfo process_info;
2068 if (!DecodeProcessInfoResponse(response, process_info))
2069 break;
2070 process_infos.Append(process_info);
2071 response.GetStringRef().clear();
2072 response.SetFilePos(0);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002073 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2074 PacketResult::Success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002075 } else {
2076 m_supports_qfProcessInfo = false;
2077 return 0;
2078 }
2079 }
2080 return process_infos.GetSize();
2081}
2082
2083bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2084 std::string &name) {
2085 if (m_supports_qUserName) {
2086 char packet[32];
2087 const int packet_len =
2088 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2089 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002090 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002091 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002092 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002093 PacketResult::Success) {
2094 if (response.IsNormalResponse()) {
2095 // Make sure we parsed the right number of characters. The response is
2096 // the hex encoded user name and should make up the entire packet.
2097 // If there are any non-hex ASCII bytes, the length won't match below..
2098 if (response.GetHexByteString(name) * 2 ==
2099 response.GetStringRef().size())
2100 return true;
2101 }
2102 } else {
2103 m_supports_qUserName = false;
2104 return false;
2105 }
2106 }
2107 return false;
2108}
2109
2110bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2111 std::string &name) {
2112 if (m_supports_qGroupName) {
2113 char packet[32];
2114 const int packet_len =
2115 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2116 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002117 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002118 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002119 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002120 PacketResult::Success) {
2121 if (response.IsNormalResponse()) {
2122 // Make sure we parsed the right number of characters. The response is
2123 // the hex encoded group name and should make up the entire packet.
2124 // If there are any non-hex ASCII bytes, the length won't match below..
2125 if (response.GetHexByteString(name) * 2 ==
2126 response.GetStringRef().size())
2127 return true;
2128 }
2129 } else {
2130 m_supports_qGroupName = false;
2131 return false;
2132 }
2133 }
2134 return false;
2135}
2136
2137bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2138 // Form non-stop packet request
2139 char packet[32];
2140 const int packet_len =
2141 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2142 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002143 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002144
2145 StringExtractorGDBRemote response;
2146 // Send to target
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002147 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002148 PacketResult::Success)
2149 if (response.IsOKResponse())
2150 return true;
2151
2152 // Failed or not supported
2153 return false;
2154}
2155
2156static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2157 uint32_t recv_size) {
2158 packet.Clear();
2159 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2160 uint32_t bytes_left = send_size;
2161 while (bytes_left > 0) {
2162 if (bytes_left >= 26) {
2163 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2164 bytes_left -= 26;
2165 } else {
2166 packet.Printf("%*.*s;", bytes_left, bytes_left,
2167 "abcdefghijklmnopqrstuvwxyz");
2168 bytes_left = 0;
2169 }
2170 }
2171}
2172
Pavel Labath1eff73c2016-11-24 10:54:49 +00002173duration<float>
2174calculate_standard_deviation(const std::vector<duration<float>> &v) {
2175 using Dur = duration<float>;
Pavel Labath3aa04912016-10-31 17:19:42 +00002176 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2177 Dur mean = sum / v.size();
2178 float accum = 0;
2179 for (auto d : v) {
2180 float delta = (d - mean).count();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002181 accum += delta * delta;
Pavel Labath3aa04912016-10-31 17:19:42 +00002182 };
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183
Pavel Labath3aa04912016-10-31 17:19:42 +00002184 return Dur(sqrtf(accum / (v.size() - 1)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002185}
2186
2187void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2188 uint32_t max_send,
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002189 uint32_t max_recv,
2190 uint64_t recv_amount,
2191 bool json, Stream &strm) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002192 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002193 if (SendSpeedTestPacket(0, 0)) {
2194 StreamString packet;
2195 if (json)
2196 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2197 "\"results\" : [",
2198 num_packets);
2199 else
2200 strm.Printf("Testing sending %u packets of various sizes:\n",
2201 num_packets);
2202 strm.Flush();
2203
2204 uint32_t result_idx = 0;
2205 uint32_t send_size;
Pavel Labath3aa04912016-10-31 17:19:42 +00002206 std::vector<duration<float>> packet_times;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002207
2208 for (send_size = 0; send_size <= max_send;
2209 send_size ? send_size *= 2 : send_size = 4) {
2210 for (uint32_t recv_size = 0; recv_size <= max_recv;
2211 recv_size ? recv_size *= 2 : recv_size = 4) {
2212 MakeSpeedTestPacket(packet, send_size, recv_size);
2213
2214 packet_times.clear();
2215 // Test how long it takes to send 'num_packets' packets
Pavel Labath3aa04912016-10-31 17:19:42 +00002216 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002217 for (i = 0; i < num_packets; ++i) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002218 const auto packet_start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002219 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002220 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Pavel Labath3aa04912016-10-31 17:19:42 +00002221 const auto packet_end_time = steady_clock::now();
2222 packet_times.push_back(packet_end_time - packet_start_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002223 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002224 const auto end_time = steady_clock::now();
2225 const auto total_time = end_time - start_time;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002226
2227 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002228 ((float)num_packets) / duration<float>(total_time).count();
2229 auto average_per_packet = total_time / num_packets;
2230 const duration<float> standard_deviation =
2231 calculate_standard_deviation(packet_times);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002232 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002233 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2234 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2235 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002236 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002237 total_time, standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002238 ++result_idx;
2239 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002240 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2241 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2242 "standard deviation of {5,10:ms+f6}\n",
2243 send_size, recv_size, duration<float>(total_time),
2244 packets_per_second, duration<float>(average_per_packet),
2245 standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002246 }
2247 strm.Flush();
2248 }
2249 }
2250
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002251 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002252 if (json)
2253 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2254 ": %" PRIu64 ",\n \"results\" : [",
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002255 recv_amount);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002256 else
2257 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2258 "packet sizes:\n",
2259 k_recv_amount_mb);
2260 strm.Flush();
2261 send_size = 0;
2262 result_idx = 0;
2263 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2264 MakeSpeedTestPacket(packet, send_size, recv_size);
2265
2266 // If we have a receive size, test how long it takes to receive 4MB of
2267 // data
2268 if (recv_size > 0) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002269 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002270 uint32_t bytes_read = 0;
2271 uint32_t packet_count = 0;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002272 while (bytes_read < recv_amount) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002273 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002274 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002275 bytes_read += recv_size;
2276 ++packet_count;
2277 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002278 const auto end_time = steady_clock::now();
2279 const auto total_time = end_time - start_time;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002280 float mb_second = ((float)recv_amount) /
Pavel Labath3aa04912016-10-31 17:19:42 +00002281 duration<float>(total_time).count() /
Kate Stoneb9c1b512016-09-06 20:57:50 +00002282 (1024.0 * 1024.0);
2283 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002284 ((float)packet_count) / duration<float>(total_time).count();
2285 const auto average_per_packet = total_time / packet_count;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002286
2287 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002288 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2289 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002290 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002291 total_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002292 ++result_idx;
2293 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002294 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2295 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2296 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002297 send_size, recv_size, packet_count, k_recv_amount_mb,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002298 duration<float>(total_time), mb_second,
2299 packets_per_second, duration<float>(average_per_packet));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002300 }
2301 strm.Flush();
2302 }
2303 }
2304 if (json)
2305 strm.Printf("\n ]\n }\n}\n");
2306 else
2307 strm.EOL();
2308 }
2309}
2310
2311bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2312 uint32_t recv_size) {
2313 StreamString packet;
2314 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2315 uint32_t bytes_left = send_size;
2316 while (bytes_left > 0) {
2317 if (bytes_left >= 26) {
2318 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2319 bytes_left -= 26;
2320 } else {
2321 packet.Printf("%*.*s;", bytes_left, bytes_left,
2322 "abcdefghijklmnopqrstuvwxyz");
2323 bytes_left = 0;
2324 }
2325 }
2326
2327 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002328 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2329 PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002330}
2331
2332bool GDBRemoteCommunicationClient::LaunchGDBServer(
2333 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2334 std::string &socket_name) {
2335 pid = LLDB_INVALID_PROCESS_ID;
2336 port = 0;
2337 socket_name.clear();
2338
2339 StringExtractorGDBRemote response;
2340 StreamString stream;
2341 stream.PutCString("qLaunchGDBServer;");
2342 std::string hostname;
2343 if (remote_accept_hostname && remote_accept_hostname[0])
2344 hostname = remote_accept_hostname;
2345 else {
2346 if (HostInfo::GetHostname(hostname)) {
2347 // Make the GDB server we launch only accept connections from this host
2348 stream.Printf("host:%s;", hostname.c_str());
2349 } else {
2350 // Make the GDB server we launch accept connections from any host since we
2351 // can't figure out the hostname
2352 stream.Printf("host:*;");
2353 }
2354 }
2355 // give the process a few seconds to startup
Pavel Labath1eff73c2016-11-24 10:54:49 +00002356 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002357
2358 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2359 PacketResult::Success) {
2360 llvm::StringRef name;
2361 llvm::StringRef value;
2362 while (response.GetNameColonValue(name, value)) {
2363 if (name.equals("port"))
2364 value.getAsInteger(0, port);
2365 else if (name.equals("pid"))
2366 value.getAsInteger(0, pid);
2367 else if (name.compare("socket_name") == 0) {
2368 StringExtractor extractor(value);
2369 extractor.GetHexByteString(socket_name);
2370 }
2371 }
2372 return true;
2373 }
2374 return false;
2375}
2376
2377size_t GDBRemoteCommunicationClient::QueryGDBServer(
2378 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2379 connection_urls.clear();
2380
2381 StringExtractorGDBRemote response;
2382 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2383 PacketResult::Success)
2384 return 0;
2385
2386 StructuredData::ObjectSP data =
2387 StructuredData::ParseJSON(response.GetStringRef());
2388 if (!data)
2389 return 0;
2390
2391 StructuredData::Array *array = data->GetAsArray();
2392 if (!array)
2393 return 0;
2394
2395 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2396 StructuredData::Dictionary *element = nullptr;
2397 if (!array->GetItemAtIndexAsDictionary(i, element))
2398 continue;
2399
2400 uint16_t port = 0;
2401 if (StructuredData::ObjectSP port_osp =
2402 element->GetValueForKey(llvm::StringRef("port")))
2403 port = port_osp->GetIntegerValue(0);
2404
2405 std::string socket_name;
2406 if (StructuredData::ObjectSP socket_name_osp =
2407 element->GetValueForKey(llvm::StringRef("socket_name")))
2408 socket_name = socket_name_osp->GetStringValue();
2409
2410 if (port != 0 || !socket_name.empty())
2411 connection_urls.emplace_back(port, socket_name);
2412 }
2413 return connection_urls.size();
2414}
2415
2416bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2417 StreamString stream;
2418 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002419
2420 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002421 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002422 PacketResult::Success) {
2423 if (response.IsOKResponse())
2424 return true;
2425 }
2426 return false;
2427}
2428
2429bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2430 if (m_curr_tid == tid)
2431 return true;
2432
2433 char packet[32];
2434 int packet_len;
2435 if (tid == UINT64_MAX)
2436 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2437 else
2438 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2439 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002440 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002441 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002442 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002443 PacketResult::Success) {
2444 if (response.IsOKResponse()) {
2445 m_curr_tid = tid;
2446 return true;
2447 }
2448
2449 /*
2450 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2451 * Hg packet.
2452 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2453 * which can
2454 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2455 */
2456 if (response.IsUnsupportedResponse() && IsConnected()) {
2457 m_curr_tid = 1;
2458 return true;
2459 }
2460 }
2461 return false;
2462}
2463
2464bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2465 if (m_curr_tid_run == tid)
2466 return true;
2467
2468 char packet[32];
2469 int packet_len;
2470 if (tid == UINT64_MAX)
2471 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2472 else
2473 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2474
2475 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002476 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002477 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002478 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002479 PacketResult::Success) {
2480 if (response.IsOKResponse()) {
2481 m_curr_tid_run = tid;
2482 return true;
2483 }
2484
2485 /*
2486 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2487 * Hc packet.
2488 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2489 * which can
2490 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2491 */
2492 if (response.IsUnsupportedResponse() && IsConnected()) {
2493 m_curr_tid_run = 1;
2494 return true;
2495 }
2496 }
2497 return false;
2498}
2499
2500bool GDBRemoteCommunicationClient::GetStopReply(
2501 StringExtractorGDBRemote &response) {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002502 if (SendPacketAndWaitForResponse("?", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002503 PacketResult::Success)
2504 return response.IsNormalResponse();
2505 return false;
2506}
2507
2508bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2509 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2510 if (m_supports_qThreadStopInfo) {
2511 char packet[256];
2512 int packet_len =
2513 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2514 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002515 UNUSED_IF_ASSERT_DISABLED(packet_len);
2516 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002517 PacketResult::Success) {
2518 if (response.IsUnsupportedResponse())
2519 m_supports_qThreadStopInfo = false;
2520 else if (response.IsNormalResponse())
2521 return true;
2522 else
2523 return false;
2524 } else {
2525 m_supports_qThreadStopInfo = false;
2526 }
2527 }
2528 return false;
2529}
2530
2531uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2532 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2533 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2534 if (log)
2535 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2536 __FUNCTION__, insert ? "add" : "remove", addr);
2537
2538 // Check if the stub is known not to support this breakpoint type
2539 if (!SupportsGDBStoppointPacket(type))
2540 return UINT8_MAX;
2541 // Construct the breakpoint packet
2542 char packet[64];
2543 const int packet_len =
2544 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2545 insert ? 'Z' : 'z', type, addr, length);
2546 // Check we haven't overwritten the end of the packet buffer
2547 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002548 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002549 StringExtractorGDBRemote response;
2550 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2551 // or "" (unsupported)
2552 response.SetResponseValidatorToOKErrorNotSupported();
2553 // Try to send the breakpoint packet, and check that it was correctly sent
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002554 if (SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002555 PacketResult::Success) {
2556 // Receive and OK packet when the breakpoint successfully placed
2557 if (response.IsOKResponse())
2558 return 0;
2559
Zachary Turner97206d52017-05-12 04:51:55 +00002560 // Status while setting breakpoint, send back specific error
Kate Stoneb9c1b512016-09-06 20:57:50 +00002561 if (response.IsErrorResponse())
2562 return response.GetError();
2563
2564 // Empty packet informs us that breakpoint is not supported
2565 if (response.IsUnsupportedResponse()) {
2566 // Disable this breakpoint type since it is unsupported
2567 switch (type) {
2568 case eBreakpointSoftware:
2569 m_supports_z0 = false;
2570 break;
2571 case eBreakpointHardware:
2572 m_supports_z1 = false;
2573 break;
2574 case eWatchpointWrite:
2575 m_supports_z2 = false;
2576 break;
2577 case eWatchpointRead:
2578 m_supports_z3 = false;
2579 break;
2580 case eWatchpointReadWrite:
2581 m_supports_z4 = false;
2582 break;
2583 case eStoppointInvalid:
2584 return UINT8_MAX;
2585 }
2586 }
2587 }
2588 // Signal generic failure
2589 return UINT8_MAX;
2590}
2591
2592size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2593 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2594 thread_ids.clear();
2595
2596 Lock lock(*this, false);
2597 if (lock) {
2598 sequence_mutex_unavailable = false;
2599 StringExtractorGDBRemote response;
2600
2601 PacketResult packet_result;
2602 for (packet_result =
2603 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2604 packet_result == PacketResult::Success && response.IsNormalResponse();
2605 packet_result =
2606 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2607 char ch = response.GetChar();
2608 if (ch == 'l')
2609 break;
2610 if (ch == 'm') {
2611 do {
2612 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2613
2614 if (tid != LLDB_INVALID_THREAD_ID) {
2615 thread_ids.push_back(tid);
2616 }
2617 ch = response.GetChar(); // Skip the command separator
2618 } while (ch == ','); // Make sure we got a comma separator
2619 }
2620 }
2621
2622 /*
2623 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2624 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2625 * could
2626 * be as simple as 'S05'. There is no packet which can give us pid and/or
2627 * tid.
2628 * Assume pid=tid=1 in such cases.
2629 */
Tamas Berghammer1492cb82017-09-18 10:24:48 +00002630 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2631 thread_ids.size() == 0 && IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002632 thread_ids.push_back(1);
2633 }
2634 } else {
David Blaikiea322f362017-01-06 00:38:06 +00002635#if !defined(LLDB_CONFIGURATION_DEBUG)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002636 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2637 GDBR_LOG_PACKETS));
2638 if (log)
2639 log->Printf("error: failed to get packet sequence mutex, not sending "
2640 "packet 'qfThreadInfo'");
2641#endif
2642 sequence_mutex_unavailable = true;
2643 }
2644 return thread_ids.size();
2645}
2646
2647lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2648 StringExtractorGDBRemote response;
2649 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2650 PacketResult::Success ||
2651 !response.IsNormalResponse())
2652 return LLDB_INVALID_ADDRESS;
2653 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2654}
2655
Zachary Turner97206d52017-05-12 04:51:55 +00002656lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002657 const char *command, // Shouldn't be NULL
2658 const FileSpec &
2659 working_dir, // Pass empty FileSpec to use the current working directory
2660 int *status_ptr, // Pass NULL if you don't want the process exit status
2661 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2662 // process to exit
2663 std::string
2664 *command_output, // Pass NULL if you don't want the command output
2665 uint32_t
2666 timeout_sec) // Timeout in seconds to wait for shell program to finish
2667{
2668 lldb_private::StreamString stream;
2669 stream.PutCString("qPlatform_shell:");
2670 stream.PutBytesAsRawHex8(command, strlen(command));
2671 stream.PutChar(',');
2672 stream.PutHex32(timeout_sec);
2673 if (working_dir) {
2674 std::string path{working_dir.GetPath(false)};
2675 stream.PutChar(',');
2676 stream.PutCStringAsRawHex8(path.c_str());
2677 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002678 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002679 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002680 PacketResult::Success) {
2681 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002682 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002683 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002684 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002685 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2686 if (exitcode == UINT32_MAX)
Zachary Turner97206d52017-05-12 04:51:55 +00002687 return Status("unable to run remote process");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002688 else if (status_ptr)
2689 *status_ptr = exitcode;
2690 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002691 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002692 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2693 if (signo_ptr)
2694 *signo_ptr = signo;
2695 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002696 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002697 std::string output;
2698 response.GetEscapedBinaryData(output);
2699 if (command_output)
2700 command_output->assign(output);
Zachary Turner97206d52017-05-12 04:51:55 +00002701 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002702 }
Zachary Turner97206d52017-05-12 04:51:55 +00002703 return Status("unable to send packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002704}
2705
Zachary Turner97206d52017-05-12 04:51:55 +00002706Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2707 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002708 std::string path{file_spec.GetPath(false)};
2709 lldb_private::StreamString stream;
2710 stream.PutCString("qPlatform_mkdir:");
2711 stream.PutHex32(file_permissions);
2712 stream.PutChar(',');
2713 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002714 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002715 StringExtractorGDBRemote response;
2716
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002717 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002718 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002719 return Status("failed to send '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002720
2721 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002722 return Status("invalid response to '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002723
Zachary Turner97206d52017-05-12 04:51:55 +00002724 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002725}
2726
Zachary Turner97206d52017-05-12 04:51:55 +00002727Status
2728GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2729 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002730 std::string path{file_spec.GetPath(false)};
2731 lldb_private::StreamString stream;
2732 stream.PutCString("qPlatform_chmod:");
2733 stream.PutHex32(file_permissions);
2734 stream.PutChar(',');
2735 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002736 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002737 StringExtractorGDBRemote response;
2738
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002739 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002740 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002741 return Status("failed to send '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002742
2743 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002744 return Status("invalid response to '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002745
Zachary Turner97206d52017-05-12 04:51:55 +00002746 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002747}
2748
2749static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
Zachary Turner97206d52017-05-12 04:51:55 +00002750 uint64_t fail_result, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002751 response.SetFilePos(0);
2752 if (response.GetChar() != 'F')
2753 return fail_result;
2754 int32_t result = response.GetS32(-2);
2755 if (result == -2)
2756 return fail_result;
2757 if (response.GetChar() == ',') {
2758 int result_errno = response.GetS32(-2);
2759 if (result_errno != -2)
2760 error.SetError(result_errno, eErrorTypePOSIX);
2761 else
2762 error.SetError(-1, eErrorTypeGeneric);
2763 } else
2764 error.Clear();
2765 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002766}
2767lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002768GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2769 uint32_t flags, mode_t mode,
Zachary Turner97206d52017-05-12 04:51:55 +00002770 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002771 std::string path(file_spec.GetPath(false));
2772 lldb_private::StreamString stream;
2773 stream.PutCString("vFile:open:");
2774 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002775 return UINT64_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002776 stream.PutCStringAsRawHex8(path.c_str());
2777 stream.PutChar(',');
2778 stream.PutHex32(flags);
2779 stream.PutChar(',');
2780 stream.PutHex32(mode);
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, UINT64_MAX, error);
2785 }
2786 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002787}
2788
Zachary Turner97206d52017-05-12 04:51:55 +00002789bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2790 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002791 lldb_private::StreamString stream;
2792 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002793 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002794 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795 PacketResult::Success) {
2796 return ParseHostIOPacketResponse(response, -1, error) == 0;
2797 }
2798 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002799}
2800
2801// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002802lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2803 const lldb_private::FileSpec &file_spec) {
2804 std::string path(file_spec.GetPath(false));
2805 lldb_private::StreamString stream;
2806 stream.PutCString("vFile:size:");
2807 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002808 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002809 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002810 PacketResult::Success) {
2811 if (response.GetChar() != 'F')
2812 return UINT64_MAX;
2813 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2814 return retcode;
2815 }
2816 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002817}
2818
Zachary Turner97206d52017-05-12 04:51:55 +00002819Status
2820GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2821 uint32_t &file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002822 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002823 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002824 lldb_private::StreamString stream;
2825 stream.PutCString("vFile:mode:");
2826 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002827 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002828 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002829 PacketResult::Success) {
2830 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002831 error.SetErrorStringWithFormat("invalid response to '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002832 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002833 } else {
2834 const uint32_t mode = response.GetS32(-1);
2835 if (static_cast<int32_t>(mode) == -1) {
2836 if (response.GetChar() == ',') {
2837 int response_errno = response.GetS32(-1);
2838 if (response_errno > 0)
2839 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2840 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002841 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002842 } else
2843 error.SetErrorToGenericError();
2844 } else {
2845 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2846 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002847 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002848 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002849 error.SetErrorStringWithFormat("failed to send '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002850 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002851 }
2852 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002853}
2854
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2856 uint64_t offset, void *dst,
2857 uint64_t dst_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002858 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002859 lldb_private::StreamString stream;
2860 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2861 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002862 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002863 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002864 PacketResult::Success) {
2865 if (response.GetChar() != 'F')
2866 return 0;
2867 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2868 if (retcode == UINT32_MAX)
2869 return retcode;
2870 const char next = (response.Peek() ? *response.Peek() : 0);
2871 if (next == ',')
2872 return 0;
2873 if (next == ';') {
2874 response.GetChar(); // skip the semicolon
2875 std::string buffer;
2876 if (response.GetEscapedBinaryData(buffer)) {
2877 const uint64_t data_to_write =
2878 std::min<uint64_t>(dst_len, buffer.size());
2879 if (data_to_write > 0)
2880 memcpy(dst, &buffer[0], data_to_write);
2881 return data_to_write;
2882 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002883 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002884 }
2885 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002886}
2887
Kate Stoneb9c1b512016-09-06 20:57:50 +00002888uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
2889 uint64_t offset,
2890 const void *src,
2891 uint64_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002892 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002893 lldb_private::StreamGDBRemote stream;
2894 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2895 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002896 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002897 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002898 PacketResult::Success) {
2899 if (response.GetChar() != 'F') {
2900 error.SetErrorStringWithFormat("write file failed");
2901 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002902 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002903 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2904 if (bytes_written == UINT64_MAX) {
2905 error.SetErrorToGenericError();
2906 if (response.GetChar() == ',') {
2907 int response_errno = response.GetS32(-1);
2908 if (response_errno > 0)
2909 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2910 }
2911 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002912 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002913 return bytes_written;
2914 } else {
2915 error.SetErrorString("failed to send vFile:pwrite packet");
2916 }
2917 return 0;
2918}
2919
Zachary Turner97206d52017-05-12 04:51:55 +00002920Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
2921 const FileSpec &dst) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002922 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002923 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002924 lldb_private::StreamGDBRemote stream;
2925 stream.PutCString("vFile:symlink:");
2926 // the unix symlink() command reverses its parameters where the dst if first,
2927 // so we follow suit here
2928 stream.PutCStringAsRawHex8(dst_path.c_str());
2929 stream.PutChar(',');
2930 stream.PutCStringAsRawHex8(src_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002931 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002932 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002933 PacketResult::Success) {
2934 if (response.GetChar() == 'F') {
2935 uint32_t result = response.GetU32(UINT32_MAX);
2936 if (result != 0) {
2937 error.SetErrorToGenericError();
2938 if (response.GetChar() == ',') {
2939 int response_errno = response.GetS32(-1);
2940 if (response_errno > 0)
2941 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2942 }
2943 }
2944 } else {
2945 // Should have returned with 'F<result>[,<errno>]'
2946 error.SetErrorStringWithFormat("symlink failed");
2947 }
2948 } else {
2949 error.SetErrorString("failed to send vFile:symlink packet");
2950 }
2951 return error;
2952}
2953
Zachary Turner97206d52017-05-12 04:51:55 +00002954Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002955 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002956 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002957 lldb_private::StreamGDBRemote stream;
2958 stream.PutCString("vFile:unlink:");
2959 // the unix symlink() command reverses its parameters where the dst if first,
2960 // so we follow suit here
2961 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002962 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002963 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002964 PacketResult::Success) {
2965 if (response.GetChar() == 'F') {
2966 uint32_t result = response.GetU32(UINT32_MAX);
2967 if (result != 0) {
2968 error.SetErrorToGenericError();
2969 if (response.GetChar() == ',') {
2970 int response_errno = response.GetS32(-1);
2971 if (response_errno > 0)
2972 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2973 }
2974 }
2975 } else {
2976 // Should have returned with 'F<result>[,<errno>]'
2977 error.SetErrorStringWithFormat("unlink failed");
2978 }
2979 } else {
2980 error.SetErrorString("failed to send vFile:unlink packet");
2981 }
2982 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002983}
2984
Daniel Maleae0f8f572013-08-26 23:57:52 +00002985// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002986bool GDBRemoteCommunicationClient::GetFileExists(
2987 const lldb_private::FileSpec &file_spec) {
2988 std::string path(file_spec.GetPath(false));
2989 lldb_private::StreamString stream;
2990 stream.PutCString("vFile:exists:");
2991 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002993 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002994 PacketResult::Success) {
2995 if (response.GetChar() != 'F')
2996 return false;
2997 if (response.GetChar() != ',')
2998 return false;
2999 bool retcode = (response.GetChar() != '0');
3000 return retcode;
3001 }
3002 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003003}
3004
Kate Stoneb9c1b512016-09-06 20:57:50 +00003005bool GDBRemoteCommunicationClient::CalculateMD5(
3006 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3007 std::string path(file_spec.GetPath(false));
3008 lldb_private::StreamString stream;
3009 stream.PutCString("vFile:MD5:");
3010 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003011 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003012 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003013 PacketResult::Success) {
3014 if (response.GetChar() != 'F')
3015 return false;
3016 if (response.GetChar() != ',')
3017 return false;
3018 if (response.Peek() && *response.Peek() == 'x')
3019 return false;
3020 low = response.GetHexMaxU64(false, UINT64_MAX);
3021 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00003022 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003023 }
3024 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003025}
3026
Kate Stoneb9c1b512016-09-06 20:57:50 +00003027bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3028 // Some targets have issues with g/G packets and we need to avoid using them
3029 if (m_avoid_g_packets == eLazyBoolCalculate) {
3030 if (process) {
3031 m_avoid_g_packets = eLazyBoolNo;
3032 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3033 if (arch.IsValid() &&
3034 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3035 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3036 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3037 m_avoid_g_packets = eLazyBoolYes;
3038 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3039 if (gdb_server_version != 0) {
3040 const char *gdb_server_name = GetGDBServerProgramName();
3041 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3042 if (gdb_server_version >= 310)
3043 m_avoid_g_packets = eLazyBoolNo;
3044 }
3045 }
3046 }
3047 }
3048 }
3049 return m_avoid_g_packets == eLazyBoolYes;
3050}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003051
Kate Stoneb9c1b512016-09-06 20:57:50 +00003052DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3053 uint32_t reg) {
3054 StreamString payload;
3055 payload.Printf("p%x", reg);
3056 StringExtractorGDBRemote response;
3057 if (SendThreadSpecificPacketAndWaitForResponse(
3058 tid, std::move(payload), response, false) != PacketResult::Success ||
3059 !response.IsNormalResponse())
3060 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003061
Kate Stoneb9c1b512016-09-06 20:57:50 +00003062 DataBufferSP buffer_sp(
3063 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3064 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3065 return buffer_sp;
3066}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003067
Kate Stoneb9c1b512016-09-06 20:57:50 +00003068DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3069 StreamString payload;
3070 payload.PutChar('g');
3071 StringExtractorGDBRemote response;
3072 if (SendThreadSpecificPacketAndWaitForResponse(
3073 tid, std::move(payload), response, false) != PacketResult::Success ||
3074 !response.IsNormalResponse())
3075 return nullptr;
3076
3077 DataBufferSP buffer_sp(
3078 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3079 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3080 return buffer_sp;
3081}
3082
3083bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3084 uint32_t reg_num,
3085 llvm::ArrayRef<uint8_t> data) {
3086 StreamString payload;
3087 payload.Printf("P%x=", reg_num);
3088 payload.PutBytesAsRawHex8(data.data(), data.size(),
3089 endian::InlHostByteOrder(),
3090 endian::InlHostByteOrder());
3091 StringExtractorGDBRemote response;
3092 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3093 response, false) ==
3094 PacketResult::Success &&
3095 response.IsOKResponse();
3096}
3097
3098bool GDBRemoteCommunicationClient::WriteAllRegisters(
3099 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3100 StreamString payload;
3101 payload.PutChar('G');
3102 payload.PutBytesAsRawHex8(data.data(), data.size(),
3103 endian::InlHostByteOrder(),
3104 endian::InlHostByteOrder());
3105 StringExtractorGDBRemote response;
3106 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3107 response, false) ==
3108 PacketResult::Success &&
3109 response.IsOKResponse();
3110}
3111
3112bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3113 uint32_t &save_id) {
3114 save_id = 0; // Set to invalid save ID
3115 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003116 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003117
3118 m_supports_QSaveRegisterState = eLazyBoolYes;
3119 StreamString payload;
3120 payload.PutCString("QSaveRegisterState");
3121 StringExtractorGDBRemote response;
3122 if (SendThreadSpecificPacketAndWaitForResponse(
3123 tid, std::move(payload), response, false) != PacketResult::Success)
3124 return false;
3125
3126 if (response.IsUnsupportedResponse())
3127 m_supports_QSaveRegisterState = eLazyBoolNo;
3128
3129 const uint32_t response_save_id = response.GetU32(0);
3130 if (response_save_id == 0)
3131 return false;
3132
3133 save_id = response_save_id;
3134 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003135}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003136
Kate Stoneb9c1b512016-09-06 20:57:50 +00003137bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3138 uint32_t save_id) {
3139 // We use the "m_supports_QSaveRegisterState" variable here because the
3140 // QSaveRegisterState and QRestoreRegisterState packets must both be supported
3141 // in
3142 // order to be useful
3143 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3144 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003145
Kate Stoneb9c1b512016-09-06 20:57:50 +00003146 StreamString payload;
3147 payload.Printf("QRestoreRegisterState:%u", save_id);
3148 StringExtractorGDBRemote response;
3149 if (SendThreadSpecificPacketAndWaitForResponse(
3150 tid, std::move(payload), response, false) != PacketResult::Success)
3151 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003152
Kate Stoneb9c1b512016-09-06 20:57:50 +00003153 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003154 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003155
3156 if (response.IsUnsupportedResponse())
3157 m_supports_QSaveRegisterState = eLazyBoolNo;
3158 return false;
3159}
3160
3161bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3162 if (!GetSyncThreadStateSupported())
3163 return false;
3164
3165 StreamString packet;
3166 StringExtractorGDBRemote response;
3167 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3168 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3169 GDBRemoteCommunication::PacketResult::Success &&
3170 response.IsOKResponse();
3171}
3172
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003173lldb::user_id_t
3174GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3175 Status &error) {
3176 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3177 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3178
3179 StreamGDBRemote escaped_packet;
3180 escaped_packet.PutCString("jTraceStart:");
3181
3182 StructuredData::Dictionary json_packet;
3183 json_packet.AddIntegerItem("type", options.getType());
3184 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3185 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3186
3187 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3188 json_packet.AddIntegerItem("threadid", options.getThreadID());
3189
3190 StructuredData::DictionarySP custom_params = options.getTraceParams();
3191 if (custom_params)
3192 json_packet.AddItem("params", custom_params);
3193
3194 StreamString json_string;
3195 json_packet.Dump(json_string, false);
3196 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3197
3198 StringExtractorGDBRemote response;
3199 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3200 true) ==
3201 GDBRemoteCommunication::PacketResult::Success) {
3202 if (!response.IsNormalResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003203 error = response.GetStatus();
3204 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003205 } else {
3206 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3207 }
3208 } else {
3209 LLDB_LOG(log, "failed to send packet");
3210 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3211 escaped_packet.GetData());
3212 }
3213 return ret_uid;
3214}
3215
3216Status
3217GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3218 lldb::tid_t thread_id) {
3219 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3220 StringExtractorGDBRemote response;
3221 Status error;
3222
3223 StructuredData::Dictionary json_packet;
3224 StreamGDBRemote escaped_packet;
3225 StreamString json_string;
3226 escaped_packet.PutCString("jTraceStop:");
3227
3228 json_packet.AddIntegerItem("traceid", uid);
3229
3230 if (thread_id != LLDB_INVALID_THREAD_ID)
3231 json_packet.AddIntegerItem("threadid", thread_id);
3232
3233 json_packet.Dump(json_string, false);
3234
3235 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3236
3237 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3238 true) ==
3239 GDBRemoteCommunication::PacketResult::Success) {
3240 if (!response.IsOKResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003241 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003242 LLDB_LOG(log, "stop tracing failed");
3243 }
3244 } else {
3245 LLDB_LOG(log, "failed to send packet");
3246 error.SetErrorStringWithFormat(
3247 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3248 response.GetError());
3249 }
3250 return error;
3251}
3252
3253Status GDBRemoteCommunicationClient::SendGetDataPacket(
3254 lldb::user_id_t uid, lldb::tid_t thread_id,
3255 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003256
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003257 StreamGDBRemote escaped_packet;
3258 escaped_packet.PutCString("jTraceBufferRead:");
3259 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3260}
3261
3262Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3263 lldb::user_id_t uid, lldb::tid_t thread_id,
3264 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003265
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003266 StreamGDBRemote escaped_packet;
3267 escaped_packet.PutCString("jTraceMetaRead:");
3268 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3269}
3270
3271Status
3272GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3273 TraceOptions &options) {
3274 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3275 StringExtractorGDBRemote response;
3276 Status error;
3277
3278 StreamString json_string;
3279 StreamGDBRemote escaped_packet;
3280 escaped_packet.PutCString("jTraceConfigRead:");
3281
3282 StructuredData::Dictionary json_packet;
3283 json_packet.AddIntegerItem("traceid", uid);
3284
3285 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3286 json_packet.AddIntegerItem("threadid", options.getThreadID());
3287
3288 json_packet.Dump(json_string, false);
3289 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3290
3291 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3292 true) ==
3293 GDBRemoteCommunication::PacketResult::Success) {
3294 if (response.IsNormalResponse()) {
3295 uint64_t type = std::numeric_limits<uint64_t>::max();
3296 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3297 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3298
3299 auto json_object = StructuredData::ParseJSON(response.Peek());
3300
3301 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003302 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003303 error.SetErrorString("Invalid Configuration obtained");
3304 return error;
3305 }
3306
3307 auto json_dict = json_object->GetAsDictionary();
3308
3309 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3310 metabuffersize);
3311 options.setMetaDataBufferSize(metabuffersize);
3312
3313 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3314 options.setTraceBufferSize(buffersize);
3315
3316 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3317 options.setType(static_cast<lldb::TraceType>(type));
3318
3319 StructuredData::ObjectSP custom_params_sp =
3320 json_dict->GetValueForKey("params");
3321 if (custom_params_sp) {
3322 if (custom_params_sp->GetType() !=
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003323 lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003324 error.SetErrorString("Invalid Configuration obtained");
3325 return error;
3326 } else
3327 options.setTraceParams(
3328 static_pointer_cast<StructuredData::Dictionary>(
3329 custom_params_sp));
3330 }
3331 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003332 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003333 }
3334 } else {
3335 LLDB_LOG(log, "failed to send packet");
3336 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3337 escaped_packet.GetData());
3338 }
3339 return error;
3340}
3341
3342Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3343 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3344 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3345 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3346 Status error;
3347
3348 StructuredData::Dictionary json_packet;
3349
3350 json_packet.AddIntegerItem("traceid", uid);
3351 json_packet.AddIntegerItem("offset", offset);
3352 json_packet.AddIntegerItem("buffersize", buffer.size());
3353
3354 if (thread_id != LLDB_INVALID_THREAD_ID)
3355 json_packet.AddIntegerItem("threadid", thread_id);
3356
3357 StreamString json_string;
3358 json_packet.Dump(json_string, false);
3359
3360 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3361 StringExtractorGDBRemote response;
3362 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3363 GDBRemoteCommunication::PacketResult::Success) {
3364 if (response.IsNormalResponse()) {
3365 size_t filled_size = response.GetHexBytesAvail(buffer);
3366 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3367 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003368 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003369 buffer = buffer.slice(buffer.size());
3370 }
3371 } else {
3372 LLDB_LOG(log, "failed to send packet");
3373 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3374 packet.GetData());
3375 buffer = buffer.slice(buffer.size());
3376 }
3377 return error;
3378}
3379
Kate Stoneb9c1b512016-09-06 20:57:50 +00003380bool GDBRemoteCommunicationClient::GetModuleInfo(
3381 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3382 ModuleSpec &module_spec) {
3383 if (!m_supports_qModuleInfo)
3384 return false;
3385
3386 std::string module_path = module_file_spec.GetPath(false);
3387 if (module_path.empty())
3388 return false;
3389
3390 StreamString packet;
3391 packet.PutCString("qModuleInfo:");
3392 packet.PutCStringAsRawHex8(module_path.c_str());
3393 packet.PutCString(";");
3394 const auto &triple = arch_spec.GetTriple().getTriple();
3395 packet.PutCStringAsRawHex8(triple.c_str());
3396
3397 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003398 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3399 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003400 return false;
3401
3402 if (response.IsErrorResponse())
3403 return false;
3404
3405 if (response.IsUnsupportedResponse()) {
3406 m_supports_qModuleInfo = false;
3407 return false;
3408 }
3409
3410 llvm::StringRef name;
3411 llvm::StringRef value;
3412
3413 module_spec.Clear();
3414 module_spec.GetFileSpec() = module_file_spec;
3415
3416 while (response.GetNameColonValue(name, value)) {
3417 if (name == "uuid" || name == "md5") {
3418 StringExtractor extractor(value);
3419 std::string uuid;
3420 extractor.GetHexByteString(uuid);
3421 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
3422 } else if (name == "triple") {
3423 StringExtractor extractor(value);
3424 std::string triple;
3425 extractor.GetHexByteString(triple);
3426 module_spec.GetArchitecture().SetTriple(triple.c_str());
3427 } else if (name == "file_offset") {
3428 uint64_t ival = 0;
3429 if (!value.getAsInteger(16, ival))
3430 module_spec.SetObjectOffset(ival);
3431 } else if (name == "file_size") {
3432 uint64_t ival = 0;
3433 if (!value.getAsInteger(16, ival))
3434 module_spec.SetObjectSize(ival);
3435 } else if (name == "file_path") {
3436 StringExtractor extractor(value);
3437 std::string path;
3438 extractor.GetHexByteString(path);
Zachary Turner8c6b5462017-03-06 23:42:44 +00003439 module_spec.GetFileSpec() = FileSpec(path, false, arch_spec.GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003440 }
3441 }
3442
3443 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003444}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003445
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003446static llvm::Optional<ModuleSpec>
3447ParseModuleSpec(StructuredData::Dictionary *dict) {
3448 ModuleSpec result;
3449 if (!dict)
3450 return llvm::None;
3451
Zachary Turner28333212017-05-12 05:49:54 +00003452 llvm::StringRef string;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003453 uint64_t integer;
3454
3455 if (!dict->GetValueForKeyAsString("uuid", string))
3456 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003457 result.GetUUID().SetFromStringRef(string, string.size());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003458
3459 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3460 return llvm::None;
3461 result.SetObjectOffset(integer);
3462
3463 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3464 return llvm::None;
3465 result.SetObjectSize(integer);
3466
3467 if (!dict->GetValueForKeyAsString("triple", string))
3468 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003469 result.GetArchitecture().SetTriple(string);
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003470
3471 if (!dict->GetValueForKeyAsString("file_path", string))
3472 return llvm::None;
Zachary Turner8c6b5462017-03-06 23:42:44 +00003473 result.GetFileSpec() =
3474 FileSpec(string, false, result.GetArchitecture().GetTriple());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003475
3476 return result;
3477}
3478
3479llvm::Optional<std::vector<ModuleSpec>>
3480GDBRemoteCommunicationClient::GetModulesInfo(
3481 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3482 if (!m_supports_jModulesInfo)
3483 return llvm::None;
3484
3485 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3486 for (const FileSpec &module_file_spec : module_file_specs) {
3487 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3488 module_array_sp->AppendObject(module_sp);
3489 module_sp->SetObject(
Pavel Labath763f1c42017-01-05 13:18:46 +00003490 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003491 module_sp->SetObject("triple",
3492 std::make_shared<JSONString>(triple.getTriple()));
3493 }
3494 StreamString unescaped_payload;
3495 unescaped_payload.PutCString("jModulesInfo:");
3496 module_array_sp->Write(unescaped_payload);
3497 StreamGDBRemote payload;
Zachary Turnerc1564272016-11-16 21:15:24 +00003498 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003499 unescaped_payload.GetSize());
3500
Greg Clayton70a9f512017-04-14 17:10:04 +00003501 // Increase the timeout for jModulesInfo since this packet can take longer.
3502 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3503
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003504 StringExtractorGDBRemote response;
3505 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3506 PacketResult::Success ||
3507 response.IsErrorResponse())
3508 return llvm::None;
3509
3510 if (response.IsUnsupportedResponse()) {
3511 m_supports_jModulesInfo = false;
3512 return llvm::None;
3513 }
3514
3515 StructuredData::ObjectSP response_object_sp =
3516 StructuredData::ParseJSON(response.GetStringRef());
3517 if (!response_object_sp)
3518 return llvm::None;
3519
3520 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3521 if (!response_array)
3522 return llvm::None;
3523
3524 std::vector<ModuleSpec> result;
3525 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3526 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3527 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3528 result.push_back(*module_spec);
3529 }
3530
3531 return result;
3532}
3533
Colin Rileyc3c95b22015-04-16 15:51:33 +00003534// query the target remote for extended information using the qXfer packet
3535//
3536// example: object='features', annex='target.xml', out=<xml output>
3537// return: 'true' on success
3538// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003539bool GDBRemoteCommunicationClient::ReadExtFeature(
3540 const lldb_private::ConstString object,
3541 const lldb_private::ConstString annex, std::string &out,
Zachary Turner97206d52017-05-12 04:51:55 +00003542 lldb_private::Status &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003543
Kate Stoneb9c1b512016-09-06 20:57:50 +00003544 std::stringstream output;
3545 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003546
Kate Stoneb9c1b512016-09-06 20:57:50 +00003547 uint64_t size = GetRemoteMaxPacketSize();
3548 if (size == 0)
3549 size = 0x1000;
3550 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3551 int offset = 0;
3552 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003553
Kate Stoneb9c1b512016-09-06 20:57:50 +00003554 // loop until all data has been read
3555 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003556
Kate Stoneb9c1b512016-09-06 20:57:50 +00003557 // send query extended feature packet
3558 std::stringstream packet;
3559 packet << "qXfer:" << object.AsCString("")
3560 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3561 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003562
Kate Stoneb9c1b512016-09-06 20:57:50 +00003563 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003564 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003565
Kate Stoneb9c1b512016-09-06 20:57:50 +00003566 if (res != GDBRemoteCommunication::PacketResult::Success) {
3567 err.SetErrorString("Error sending $qXfer packet");
3568 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003569 }
3570
Kate Stoneb9c1b512016-09-06 20:57:50 +00003571 const std::string &str = chunk.GetStringRef();
3572 if (str.length() == 0) {
3573 // should have some data in chunk
3574 err.SetErrorString("Empty response from $qXfer packet");
3575 return false;
3576 }
3577
3578 // check packet code
3579 switch (str[0]) {
3580 // last chunk
3581 case ('l'):
3582 active = false;
3583 LLVM_FALLTHROUGH;
3584
3585 // more chunks
3586 case ('m'):
3587 if (str.length() > 1)
3588 output << &str[1];
3589 offset += size;
3590 break;
3591
3592 // unknown chunk
3593 default:
3594 err.SetErrorString("Invalid continuation code from $qXfer packet");
3595 return false;
3596 }
3597 }
3598
3599 out = output.str();
3600 err.Success();
3601 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003602}
Greg Clayton0b90be12015-06-23 21:27:50 +00003603
3604// Notify the target that gdb is prepared to serve symbol lookup requests.
3605// packet: "qSymbol::"
3606// reply:
3607// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003608// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3609// encoded).
3610// LLDB may provide the value by sending another qSymbol
3611// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003612// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003613//
3614// Three examples:
3615//
3616// lldb sends: qSymbol::
3617// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003618// Remote gdb stub does not need to know the addresses of any symbols, lldb
3619// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003620// need to ask again in this session.
3621//
3622// lldb sends: qSymbol::
3623// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3624// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3625// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003626// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3627// not know
3628// the address at this time. lldb needs to send qSymbol:: again when it has
3629// more
Jason Molenda50018d32016-01-13 04:08:10 +00003630// solibs loaded.
3631//
3632// lldb sends: qSymbol::
3633// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3634// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3635// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003636// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3637// that it
3638// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3639// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003640// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003641
Kate Stoneb9c1b512016-09-06 20:57:50 +00003642void GDBRemoteCommunicationClient::ServeSymbolLookups(
3643 lldb_private::Process *process) {
3644 // Set to true once we've resolved a symbol to an address for the remote stub.
3645 // If we get an 'OK' response after this, the remote stub doesn't need any
3646 // more
3647 // symbols and we can stop asking.
3648 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003649
Kate Stoneb9c1b512016-09-06 20:57:50 +00003650 // Is this the initial qSymbol:: packet?
3651 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003652
Kate Stoneb9c1b512016-09-06 20:57:50 +00003653 if (m_supports_qSymbol && m_qSymbol_requests_done == false) {
3654 Lock lock(*this, false);
3655 if (lock) {
3656 StreamString packet;
3657 packet.PutCString("qSymbol::");
3658 StringExtractorGDBRemote response;
3659 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3660 PacketResult::Success) {
3661 if (response.IsOKResponse()) {
3662 if (symbol_response_provided || first_qsymbol_query) {
3663 m_qSymbol_requests_done = true;
3664 }
3665
3666 // We are done serving symbols requests
3667 return;
3668 }
3669 first_qsymbol_query = false;
3670
3671 if (response.IsUnsupportedResponse()) {
3672 // qSymbol is not supported by the current GDB server we are connected
3673 // to
3674 m_supports_qSymbol = false;
3675 return;
3676 } else {
3677 llvm::StringRef response_str(response.GetStringRef());
3678 if (response_str.startswith("qSymbol:")) {
3679 response.SetFilePos(strlen("qSymbol:"));
3680 std::string symbol_name;
3681 if (response.GetHexByteString(symbol_name)) {
3682 if (symbol_name.empty())
3683 return;
3684
3685 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3686 lldb_private::SymbolContextList sc_list;
3687 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3688 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3689 const size_t num_scs = sc_list.GetSize();
3690 for (size_t sc_idx = 0;
3691 sc_idx < num_scs &&
3692 symbol_load_addr == LLDB_INVALID_ADDRESS;
3693 ++sc_idx) {
3694 SymbolContext sc;
3695 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3696 if (sc.symbol) {
3697 switch (sc.symbol->GetType()) {
3698 case eSymbolTypeInvalid:
3699 case eSymbolTypeAbsolute:
3700 case eSymbolTypeUndefined:
3701 case eSymbolTypeSourceFile:
3702 case eSymbolTypeHeaderFile:
3703 case eSymbolTypeObjectFile:
3704 case eSymbolTypeCommonBlock:
3705 case eSymbolTypeBlock:
3706 case eSymbolTypeLocal:
3707 case eSymbolTypeParam:
3708 case eSymbolTypeVariable:
3709 case eSymbolTypeVariableType:
3710 case eSymbolTypeLineEntry:
3711 case eSymbolTypeLineHeader:
3712 case eSymbolTypeScopeBegin:
3713 case eSymbolTypeScopeEnd:
3714 case eSymbolTypeAdditional:
3715 case eSymbolTypeCompiler:
3716 case eSymbolTypeInstrumentation:
3717 case eSymbolTypeTrampoline:
3718 break;
3719
3720 case eSymbolTypeCode:
3721 case eSymbolTypeResolver:
3722 case eSymbolTypeData:
3723 case eSymbolTypeRuntime:
3724 case eSymbolTypeException:
3725 case eSymbolTypeObjCClass:
3726 case eSymbolTypeObjCMetaClass:
3727 case eSymbolTypeObjCIVar:
3728 case eSymbolTypeReExported:
3729 symbol_load_addr =
3730 sc.symbol->GetLoadAddress(&process->GetTarget());
3731 break;
3732 }
Jason Molenda50018d32016-01-13 04:08:10 +00003733 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003734 }
Greg Clayton42b01482015-08-11 22:07:46 +00003735 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003736 }
3737 // This is the normal path where our symbol lookup was successful
3738 // and we want
3739 // to send a packet with the new symbol value and see if another
3740 // lookup needs to be
3741 // done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003742
Kate Stoneb9c1b512016-09-06 20:57:50 +00003743 // Change "packet" to contain the requested symbol value and name
3744 packet.Clear();
3745 packet.PutCString("qSymbol:");
3746 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3747 packet.Printf("%" PRIx64, symbol_load_addr);
3748 symbol_response_provided = true;
3749 } else {
3750 symbol_response_provided = false;
3751 }
3752 packet.PutCString(":");
3753 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3754 continue; // go back to the while loop and send "packet" and wait
3755 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003756 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003757 }
3758 }
3759 }
3760 // If we make it here, the symbol request packet response wasn't valid or
3761 // our symbol lookup failed so we must abort
3762 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003763
Kate Stoneb9c1b512016-09-06 20:57:50 +00003764 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3765 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3766 log->Printf(
3767 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3768 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003769 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003770 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003771}
3772
Kate Stoneb9c1b512016-09-06 20:57:50 +00003773StructuredData::Array *
3774GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3775 if (!m_supported_async_json_packets_is_valid) {
3776 // Query the server for the array of supported asynchronous JSON
3777 // packets.
3778 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003779
Kate Stoneb9c1b512016-09-06 20:57:50 +00003780 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003781
Kate Stoneb9c1b512016-09-06 20:57:50 +00003782 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003783 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003784 const bool send_async = false;
3785 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3786 send_async) == PacketResult::Success) {
3787 m_supported_async_json_packets_sp =
3788 StructuredData::ParseJSON(response.GetStringRef());
3789 if (m_supported_async_json_packets_sp &&
3790 !m_supported_async_json_packets_sp->GetAsArray()) {
3791 // We were returned something other than a JSON array. This
3792 // is invalid. Clear it out.
3793 if (log)
3794 log->Printf("GDBRemoteCommunicationClient::%s(): "
3795 "QSupportedAsyncJSONPackets returned invalid "
3796 "result: %s",
3797 __FUNCTION__, response.GetStringRef().c_str());
3798 m_supported_async_json_packets_sp.reset();
3799 }
3800 } else {
3801 if (log)
3802 log->Printf("GDBRemoteCommunicationClient::%s(): "
3803 "QSupportedAsyncJSONPackets unsupported",
3804 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003805 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003806
3807 if (log && m_supported_async_json_packets_sp) {
3808 StreamString stream;
3809 m_supported_async_json_packets_sp->Dump(stream);
3810 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3811 "JSON packets: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00003812 __FUNCTION__, stream.GetData());
Todd Fiala75930012016-08-19 04:21:48 +00003813 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003814 }
3815
3816 return m_supported_async_json_packets_sp
3817 ? m_supported_async_json_packets_sp->GetAsArray()
3818 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003819}
3820
Zachary Turner97206d52017-05-12 04:51:55 +00003821Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003822 llvm::ArrayRef<int32_t> signals) {
3823 // Format packet:
3824 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3825 auto range = llvm::make_range(signals.begin(), signals.end());
3826 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3827
3828 StringExtractorGDBRemote response;
3829 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3830
3831 if (send_status != GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00003832 return Status("Sending QPassSignals packet failed");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003833
3834 if (response.IsOKResponse()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003835 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003836 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00003837 return Status("Unknown error happened during sending QPassSignals packet.");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003838 }
3839}
3840
Zachary Turner97206d52017-05-12 04:51:55 +00003841Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003842 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00003843 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003844
3845 if (type_name.GetLength() == 0) {
3846 error.SetErrorString("invalid type_name argument");
3847 return error;
3848 }
3849
3850 // Build command: Configure{type_name}: serialized config
3851 // data.
3852 StreamGDBRemote stream;
3853 stream.PutCString("QConfigure");
3854 stream.PutCString(type_name.AsCString());
3855 stream.PutChar(':');
3856 if (config_sp) {
3857 // Gather the plain-text version of the configuration data.
3858 StreamString unescaped_stream;
3859 config_sp->Dump(unescaped_stream);
3860 unescaped_stream.Flush();
3861
3862 // Add it to the stream in escaped fashion.
Zachary Turnerc1564272016-11-16 21:15:24 +00003863 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003864 unescaped_stream.GetSize());
3865 }
3866 stream.Flush();
3867
3868 // Send the packet.
3869 const bool send_async = false;
3870 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003871 auto result =
3872 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003873 if (result == PacketResult::Success) {
3874 // We failed if the config result comes back other than OK.
3875 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3876 // Okay!
3877 error.Clear();
3878 } else {
3879 error.SetErrorStringWithFormat("configuring StructuredData feature "
3880 "%s failed with error %s",
3881 type_name.AsCString(),
3882 response.GetStringRef().c_str());
3883 }
3884 } else {
3885 // Can we get more data here on the failure?
3886 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3887 "failed when sending packet: "
3888 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00003889 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003890 }
3891 return error;
3892}
3893
3894void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
3895 GDBRemoteClientBase::OnRunPacketSent(first);
3896 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003897}