blob: b0785a687f5dc18ab220ef458da4ee143cffbffa [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
Pavel Labath62930e52018-01-10 11:57:31 +0000825int GDBRemoteCommunicationClient::SendEnvironment(const Environment &env) {
826 for (const auto &KV : env) {
827 int r = SendEnvironmentPacket(Environment::compose(KV).c_str());
828 if (r != 0)
829 return r;
830 }
831 return 0;
832}
833
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834int GDBRemoteCommunicationClient::SendEnvironmentPacket(
835 char const *name_equal_value) {
836 if (name_equal_value && name_equal_value[0]) {
837 StreamString packet;
838 bool send_hex_encoding = false;
839 for (const char *p = name_equal_value;
840 *p != '\0' && send_hex_encoding == false; ++p) {
841 if (isprint(*p)) {
842 switch (*p) {
843 case '$':
844 case '#':
845 case '*':
846 case '}':
847 send_hex_encoding = true;
848 break;
849 default:
850 break;
Johnny Chen64637202012-05-23 21:09:52 +0000851 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852 } else {
853 // We have non printable characters, lets hex encode this...
854 send_hex_encoding = true;
855 }
Johnny Chen64637202012-05-23 21:09:52 +0000856 }
857
Greg Claytonfbb76342013-11-20 21:07:01 +0000858 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859 if (send_hex_encoding) {
860 if (m_supports_QEnvironmentHexEncoded) {
861 packet.PutCString("QEnvironmentHexEncoded:");
862 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000863 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
864 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 if (response.IsOKResponse())
866 return 0;
867 uint8_t error = response.GetError();
868 if (error)
869 return error;
870 if (response.IsUnsupportedResponse())
871 m_supports_QEnvironmentHexEncoded = false;
872 }
873 }
874
875 } else if (m_supports_QEnvironment) {
876 packet.Printf("QEnvironment:%s", name_equal_value);
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000877 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
878 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879 if (response.IsOKResponse())
880 return 0;
881 uint8_t error = response.GetError();
882 if (error)
883 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +0000884 if (response.IsUnsupportedResponse())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885 m_supports_QEnvironment = false;
886 }
Greg Claytonfbb76342013-11-20 21:07:01 +0000887 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 }
889 return -1;
Greg Claytonfbb76342013-11-20 21:07:01 +0000890}
891
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
893 if (arch && arch[0]) {
894 StreamString packet;
895 packet.Printf("QLaunchArch:%s", arch);
896 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000897 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
898 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000899 if (response.IsOKResponse())
900 return 0;
901 uint8_t error = response.GetError();
902 if (error)
903 return error;
904 }
905 }
906 return -1;
907}
Chaoren Lind3173f32015-05-29 19:52:29 +0000908
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
910 char const *data, bool *was_supported) {
911 if (data && *data != '\0') {
912 StreamString packet;
913 packet.Printf("QSetProcessEvent:%s", data);
914 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000915 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
916 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917 if (response.IsOKResponse()) {
918 if (was_supported)
919 *was_supported = true;
920 return 0;
921 } else if (response.IsUnsupportedResponse()) {
922 if (was_supported)
923 *was_supported = false;
924 return -1;
925 } else {
926 uint8_t error = response.GetError();
927 if (was_supported)
928 *was_supported = true;
929 if (error)
930 return error;
931 }
932 }
933 }
934 return -1;
935}
936
937bool GDBRemoteCommunicationClient::GetOSVersion(uint32_t &major,
938 uint32_t &minor,
939 uint32_t &update) {
940 if (GetHostInfo()) {
941 if (m_os_version_major != UINT32_MAX) {
942 major = m_os_version_major;
943 minor = m_os_version_minor;
944 update = m_os_version_update;
945 return true;
946 }
947 }
948 return false;
949}
950
951bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
952 if (GetHostInfo()) {
953 if (!m_os_build.empty()) {
954 s = m_os_build;
955 return true;
956 }
957 }
958 s.clear();
959 return false;
960}
961
962bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
963 if (GetHostInfo()) {
964 if (!m_os_kernel.empty()) {
965 s = m_os_kernel;
966 return true;
967 }
968 }
969 s.clear();
970 return false;
971}
972
973bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
974 if (GetHostInfo()) {
975 if (!m_hostname.empty()) {
976 s = m_hostname;
977 return true;
978 }
979 }
980 s.clear();
981 return false;
982}
983
984ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
985 if (GetHostInfo())
986 return m_host_arch;
987 return ArchSpec();
988}
989
990const lldb_private::ArchSpec &
991GDBRemoteCommunicationClient::GetProcessArchitecture() {
992 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
993 GetCurrentProcessInfo();
994 return m_process_arch;
995}
996
997bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
998 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
999 m_gdb_server_name.clear();
1000 m_gdb_server_version = 0;
1001 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1002
1003 StringExtractorGDBRemote response;
1004 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
1005 PacketResult::Success) {
1006 if (response.IsNormalResponse()) {
1007 llvm::StringRef name, value;
1008 bool success = false;
1009 while (response.GetNameColonValue(name, value)) {
1010 if (name.equals("name")) {
1011 success = true;
1012 m_gdb_server_name = value;
1013 } else if (name.equals("version")) {
1014 llvm::StringRef major, minor;
1015 std::tie(major, minor) = value.split('.');
1016 if (!major.getAsInteger(0, m_gdb_server_version))
1017 success = true;
1018 }
Greg Clayton576d8832011-03-22 04:00:09 +00001019 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 if (success)
1021 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1022 }
Greg Clayton576d8832011-03-22 04:00:09 +00001023 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001024 }
1025 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001026}
1027
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028void GDBRemoteCommunicationClient::MaybeEnableCompression(
1029 std::vector<std::string> supported_compressions) {
1030 CompressionType avail_type = CompressionType::None;
1031 std::string avail_name;
1032
1033#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001034 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035 for (auto compression : supported_compressions) {
1036 if (compression == "lzfse") {
1037 avail_type = CompressionType::LZFSE;
1038 avail_name = compression;
1039 break;
1040 }
1041 }
1042 }
1043#endif
1044
1045#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001046 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001047 for (auto compression : supported_compressions) {
1048 if (compression == "zlib-deflate") {
1049 avail_type = CompressionType::ZlibDeflate;
1050 avail_name = compression;
1051 break;
1052 }
1053 }
1054 }
1055#endif
1056
1057#if defined(HAVE_LIBZ)
1058 if (avail_type == CompressionType::None) {
1059 for (auto compression : supported_compressions) {
1060 if (compression == "zlib-deflate") {
1061 avail_type = CompressionType::ZlibDeflate;
1062 avail_name = compression;
1063 break;
1064 }
1065 }
1066 }
1067#endif
1068
1069#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +00001070 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001071 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)
Vedant Kumar606908a2017-12-06 19:21:10 +00001082 if (avail_type == CompressionType::None) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083 for (auto compression : supported_compressions) {
1084 if (compression == "lzma") {
1085 avail_type = CompressionType::LZMA;
1086 avail_name = compression;
1087 break;
1088 }
1089 }
1090 }
1091#endif
1092
1093 if (avail_type != CompressionType::None) {
Greg Clayton576d8832011-03-22 04:00:09 +00001094 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001095 std::string packet = "QEnableCompression:type:" + avail_name + ";";
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001096 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00001097 PacketResult::Success)
1098 return;
1099
1100 if (response.IsOKResponse()) {
1101 m_compression_type = avail_type;
Greg Clayton576d8832011-03-22 04:00:09 +00001102 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103 }
Greg Clayton576d8832011-03-22 04:00:09 +00001104}
Greg Clayton32e0a752011-03-30 18:16:51 +00001105
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1107 if (GetGDBServerVersion()) {
1108 if (!m_gdb_server_name.empty())
1109 return m_gdb_server_name.c_str();
1110 }
1111 return NULL;
1112}
1113
1114uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1115 if (GetGDBServerVersion())
1116 return m_gdb_server_version;
1117 return 0;
1118}
1119
1120bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1121 StringExtractorGDBRemote response;
1122 if (SendPacketAndWaitForResponse("qC", response, false) !=
1123 PacketResult::Success)
1124 return false;
1125
1126 if (!response.IsNormalResponse())
1127 return false;
1128
1129 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1130 tid = response.GetHexMaxU32(true, -1);
1131
1132 return true;
1133}
1134
1135bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1136 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1137
1138 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1139 m_qHostInfo_is_valid = eLazyBoolNo;
Jim Ingham106d0282014-06-25 02:32:56 +00001140 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001141 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1142 PacketResult::Success) {
1143 if (response.IsNormalResponse()) {
Zachary Turner54695a32016-08-29 19:58:14 +00001144 llvm::StringRef name;
1145 llvm::StringRef value;
Jason Molenda89c37492014-01-27 22:23:20 +00001146 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1147 uint32_t sub = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001148 std::string arch_name;
1149 std::string os_name;
1150 std::string vendor_name;
1151 std::string triple;
1152 std::string distribution_id;
1153 uint32_t pointer_byte_size = 0;
1154 ByteOrder byte_order = eByteOrderInvalid;
1155 uint32_t num_keys_decoded = 0;
1156 while (response.GetNameColonValue(name, value)) {
1157 if (name.equals("cputype")) {
1158 // exception type in big endian hex
1159 if (!value.getAsInteger(0, cpu))
1160 ++num_keys_decoded;
1161 } else if (name.equals("cpusubtype")) {
1162 // exception count in big endian hex
1163 if (!value.getAsInteger(0, sub))
1164 ++num_keys_decoded;
1165 } else if (name.equals("arch")) {
1166 arch_name = value;
1167 ++num_keys_decoded;
1168 } else if (name.equals("triple")) {
1169 StringExtractor extractor(value);
1170 extractor.GetHexByteString(triple);
1171 ++num_keys_decoded;
1172 } else if (name.equals("distribution_id")) {
1173 StringExtractor extractor(value);
1174 extractor.GetHexByteString(distribution_id);
1175 ++num_keys_decoded;
1176 } else if (name.equals("os_build")) {
1177 StringExtractor extractor(value);
1178 extractor.GetHexByteString(m_os_build);
1179 ++num_keys_decoded;
1180 } else if (name.equals("hostname")) {
1181 StringExtractor extractor(value);
1182 extractor.GetHexByteString(m_hostname);
1183 ++num_keys_decoded;
1184 } else if (name.equals("os_kernel")) {
1185 StringExtractor extractor(value);
1186 extractor.GetHexByteString(m_os_kernel);
1187 ++num_keys_decoded;
1188 } else if (name.equals("ostype")) {
1189 os_name = value;
1190 ++num_keys_decoded;
1191 } else if (name.equals("vendor")) {
1192 vendor_name = value;
1193 ++num_keys_decoded;
1194 } else if (name.equals("endian")) {
1195 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1196 .Case("little", eByteOrderLittle)
1197 .Case("big", eByteOrderBig)
1198 .Case("pdp", eByteOrderPDP)
1199 .Default(eByteOrderInvalid);
1200 if (byte_order != eByteOrderInvalid)
1201 ++num_keys_decoded;
1202 } else if (name.equals("ptrsize")) {
1203 if (!value.getAsInteger(0, pointer_byte_size))
1204 ++num_keys_decoded;
1205 } else if (name.equals("os_version") ||
1206 name.equals(
1207 "version")) // Older debugserver binaries used the
1208 // "version" key instead of
1209 // "os_version"...
1210 {
Zachary Turner6fa7681b2016-09-17 02:00:02 +00001211 Args::StringToVersion(value, m_os_version_major, m_os_version_minor,
1212 m_os_version_update);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213 if (m_os_version_major != UINT32_MAX)
1214 ++num_keys_decoded;
1215 } else if (name.equals("watchpoint_exceptions_received")) {
1216 m_watchpoints_trigger_after_instruction =
1217 llvm::StringSwitch<LazyBool>(value)
1218 .Case("before", eLazyBoolNo)
1219 .Case("after", eLazyBoolYes)
1220 .Default(eLazyBoolCalculate);
1221 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1222 ++num_keys_decoded;
1223 } else if (name.equals("default_packet_timeout")) {
Pavel Labath3aa04912016-10-31 17:19:42 +00001224 uint32_t timeout_seconds;
1225 if (!value.getAsInteger(0, timeout_seconds)) {
Pavel Labath1eff73c2016-11-24 10:54:49 +00001226 m_default_packet_timeout = seconds(timeout_seconds);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001227 SetPacketTimeout(m_default_packet_timeout);
1228 ++num_keys_decoded;
Greg Clayton32e0a752011-03-30 18:16:51 +00001229 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230 }
Jason Molenda89c37492014-01-27 22:23:20 +00001231 }
1232
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233 if (num_keys_decoded > 0)
1234 m_qHostInfo_is_valid = eLazyBoolYes;
1235
1236 if (triple.empty()) {
1237 if (arch_name.empty()) {
1238 if (cpu != LLDB_INVALID_CPUTYPE) {
1239 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1240 if (pointer_byte_size) {
1241 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1242 }
1243 if (byte_order != eByteOrderInvalid) {
1244 assert(byte_order == m_host_arch.GetByteOrder());
1245 }
1246
1247 if (!vendor_name.empty())
1248 m_host_arch.GetTriple().setVendorName(
1249 llvm::StringRef(vendor_name));
1250 if (!os_name.empty())
1251 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Jason Molenda89c37492014-01-27 22:23:20 +00001252 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001253 } else {
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001254 std::string triple;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 triple += arch_name;
1256 if (!vendor_name.empty() || !os_name.empty()) {
1257 triple += '-';
1258 if (vendor_name.empty())
1259 triple += "unknown";
1260 else
1261 triple += vendor_name;
1262 triple += '-';
1263 if (os_name.empty())
1264 triple += "unknown";
1265 else
1266 triple += os_name;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001267 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001268 m_host_arch.SetTriple(triple.c_str());
Todd Fialac540dd02014-08-26 18:21:02 +00001269
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 llvm::Triple &host_triple = m_host_arch.GetTriple();
1271 if (host_triple.getVendor() == llvm::Triple::Apple &&
1272 host_triple.getOS() == llvm::Triple::Darwin) {
1273 switch (m_host_arch.GetMachine()) {
1274 case llvm::Triple::aarch64:
1275 case llvm::Triple::arm:
1276 case llvm::Triple::thumb:
1277 host_triple.setOS(llvm::Triple::IOS);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001278 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001279 default:
1280 host_triple.setOS(llvm::Triple::MacOSX);
1281 break;
1282 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001283 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284 if (pointer_byte_size) {
1285 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1286 }
1287 if (byte_order != eByteOrderInvalid) {
1288 assert(byte_order == m_host_arch.GetByteOrder());
1289 }
1290 }
1291 } else {
1292 m_host_arch.SetTriple(triple.c_str());
1293 if (pointer_byte_size) {
1294 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1295 }
1296 if (byte_order != eByteOrderInvalid) {
1297 assert(byte_order == m_host_arch.GetByteOrder());
1298 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001299
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 if (log)
1301 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1302 "architecture as %s, triple as %s from triple text %s",
1303 __FUNCTION__, m_host_arch.GetArchitectureName()
1304 ? m_host_arch.GetArchitectureName()
1305 : "<null-arch-name>",
1306 m_host_arch.GetTriple().getTriple().c_str(),
1307 triple.c_str());
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001308 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001309 if (!distribution_id.empty())
1310 m_host_arch.SetDistributionId(distribution_id.c_str());
1311 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001312 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001313 }
1314 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Claytonadc00cb2011-05-20 23:38:13 +00001315}
Greg Clayton37a0a242012-04-11 00:24:49 +00001316
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317int GDBRemoteCommunicationClient::SendAttach(
1318 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1319 if (pid != LLDB_INVALID_PROCESS_ID) {
1320 char packet[64];
1321 const int packet_len =
1322 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001323 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001325 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001326 PacketResult::Success) {
1327 if (response.IsErrorResponse())
1328 return response.GetError();
1329 return 0;
1330 }
1331 }
1332 return -1;
1333}
1334
1335int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1336 size_t data_len) {
1337 StreamString packet;
1338 packet.PutCString("I");
1339 packet.PutBytesAsRawHex8(data, data_len);
1340 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001341 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1342 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001343 return 0;
1344 }
1345 return response.GetError();
1346}
1347
1348const lldb_private::ArchSpec &
1349GDBRemoteCommunicationClient::GetHostArchitecture() {
1350 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1351 GetHostInfo();
1352 return m_host_arch;
1353}
1354
Pavel Labath1eff73c2016-11-24 10:54:49 +00001355seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001356 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1357 GetHostInfo();
1358 return m_default_packet_timeout;
1359}
1360
1361addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1362 uint32_t permissions) {
1363 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1364 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1365 char packet[64];
1366 const int packet_len = ::snprintf(
1367 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1368 permissions & lldb::ePermissionsReadable ? "r" : "",
1369 permissions & lldb::ePermissionsWritable ? "w" : "",
1370 permissions & lldb::ePermissionsExecutable ? "x" : "");
1371 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001372 UNUSED_IF_ASSERT_DISABLED(packet_len);
Pavel Labath83082a02016-08-18 14:33:55 +00001373 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001374 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001375 PacketResult::Success) {
1376 if (response.IsUnsupportedResponse())
1377 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1378 else if (!response.IsErrorResponse())
1379 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1380 } else {
1381 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1382 }
1383 }
1384 return LLDB_INVALID_ADDRESS;
1385}
1386
1387bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1388 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1389 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1390 char packet[64];
1391 const int packet_len =
1392 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1393 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001394 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001396 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397 PacketResult::Success) {
1398 if (response.IsUnsupportedResponse())
1399 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1400 else if (response.IsOKResponse())
1401 return true;
1402 } else {
1403 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1404 }
1405 }
1406 return false;
1407}
1408
Zachary Turner97206d52017-05-12 04:51:55 +00001409Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1410 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001411
1412 if (keep_stopped) {
1413 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1414 char packet[64];
1415 const int packet_len =
1416 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
1417 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001418 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001419 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001420 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421 PacketResult::Success &&
1422 response.IsOKResponse()) {
1423 m_supports_detach_stay_stopped = eLazyBoolYes;
1424 } else {
1425 m_supports_detach_stay_stopped = eLazyBoolNo;
1426 }
1427 }
1428
1429 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1430 error.SetErrorString("Stays stopped not supported by this target.");
1431 return error;
1432 } else {
1433 StringExtractorGDBRemote response;
1434 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001435 SendPacketAndWaitForResponse("D1", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001436 if (packet_result != PacketResult::Success)
1437 error.SetErrorString("Sending extended disconnect packet failed.");
1438 }
1439 } else {
1440 StringExtractorGDBRemote response;
1441 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001442 SendPacketAndWaitForResponse("D", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 if (packet_result != PacketResult::Success)
1444 error.SetErrorString("Sending disconnect packet failed.");
1445 }
1446 return error;
1447}
1448
Zachary Turner97206d52017-05-12 04:51:55 +00001449Status GDBRemoteCommunicationClient::GetMemoryRegionInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001450 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
Zachary Turner97206d52017-05-12 04:51:55 +00001451 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001452 region_info.Clear();
1453
1454 if (m_supports_memory_region_info != eLazyBoolNo) {
1455 m_supports_memory_region_info = eLazyBoolYes;
1456 char packet[64];
1457 const int packet_len = ::snprintf(
1458 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1459 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001460 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001461 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001462 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001463 PacketResult::Success) {
1464 llvm::StringRef name;
1465 llvm::StringRef value;
1466 addr_t addr_value = LLDB_INVALID_ADDRESS;
1467 bool success = true;
1468 bool saw_permissions = false;
1469 while (success && response.GetNameColonValue(name, value)) {
1470 if (name.equals("start")) {
1471 if (!value.getAsInteger(16, addr_value))
1472 region_info.GetRange().SetRangeBase(addr_value);
1473 } else if (name.equals("size")) {
1474 if (!value.getAsInteger(16, addr_value))
1475 region_info.GetRange().SetByteSize(addr_value);
1476 } else if (name.equals("permissions") &&
1477 region_info.GetRange().IsValid()) {
1478 saw_permissions = true;
1479 if (region_info.GetRange().Contains(addr)) {
1480 if (value.find('r') != llvm::StringRef::npos)
1481 region_info.SetReadable(MemoryRegionInfo::eYes);
1482 else
1483 region_info.SetReadable(MemoryRegionInfo::eNo);
1484
1485 if (value.find('w') != llvm::StringRef::npos)
1486 region_info.SetWritable(MemoryRegionInfo::eYes);
1487 else
1488 region_info.SetWritable(MemoryRegionInfo::eNo);
1489
1490 if (value.find('x') != llvm::StringRef::npos)
1491 region_info.SetExecutable(MemoryRegionInfo::eYes);
1492 else
1493 region_info.SetExecutable(MemoryRegionInfo::eNo);
1494
1495 region_info.SetMapped(MemoryRegionInfo::eYes);
1496 } else {
1497 // The reported region does not contain this address -- we're
1498 // looking at an unmapped page
1499 region_info.SetReadable(MemoryRegionInfo::eNo);
1500 region_info.SetWritable(MemoryRegionInfo::eNo);
1501 region_info.SetExecutable(MemoryRegionInfo::eNo);
1502 region_info.SetMapped(MemoryRegionInfo::eNo);
1503 }
1504 } else if (name.equals("name")) {
1505 StringExtractorGDBRemote name_extractor(value);
1506 std::string name;
1507 name_extractor.GetHexByteString(name);
1508 region_info.SetName(name.c_str());
1509 } else if (name.equals("error")) {
1510 StringExtractorGDBRemote error_extractor(value);
1511 std::string error_string;
1512 // Now convert the HEX bytes into a string value
1513 error_extractor.GetHexByteString(error_string);
1514 error.SetErrorString(error_string.c_str());
1515 }
1516 }
1517
Stephane Sezer48d14272017-03-31 18:00:48 +00001518 if (region_info.GetRange().IsValid()) {
1519 // We got a valid address range back but no permissions -- which means
1520 // this is an unmapped page
1521 if (!saw_permissions) {
1522 region_info.SetReadable(MemoryRegionInfo::eNo);
1523 region_info.SetWritable(MemoryRegionInfo::eNo);
1524 region_info.SetExecutable(MemoryRegionInfo::eNo);
1525 region_info.SetMapped(MemoryRegionInfo::eNo);
1526 }
1527 } else {
1528 // We got an invalid address range back
1529 error.SetErrorString("Server returned invalid range");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001530 }
1531 } else {
1532 m_supports_memory_region_info = eLazyBoolNo;
1533 }
1534 }
1535
1536 if (m_supports_memory_region_info == eLazyBoolNo) {
1537 error.SetErrorString("qMemoryRegionInfo is not supported");
1538 }
1539 if (error.Fail())
1540 region_info.Clear();
1541 return error;
1542}
1543
Zachary Turner97206d52017-05-12 04:51:55 +00001544Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1545 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001546
1547 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1548 num = m_num_supported_hardware_watchpoints;
1549 return error;
1550 }
1551
1552 // Set num to 0 first.
1553 num = 0;
1554 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1555 char packet[64];
1556 const int packet_len =
1557 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1558 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001559 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001560 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001561 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001562 PacketResult::Success) {
1563 m_supports_watchpoint_support_info = eLazyBoolYes;
1564 llvm::StringRef name;
1565 llvm::StringRef value;
1566 while (response.GetNameColonValue(name, value)) {
1567 if (name.equals("num")) {
1568 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1569 num = m_num_supported_hardware_watchpoints;
1570 }
1571 }
1572 } else {
1573 m_supports_watchpoint_support_info = eLazyBoolNo;
1574 }
1575 }
1576
1577 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1578 error.SetErrorString("qWatchpointSupportInfo is not supported");
1579 }
1580 return error;
1581}
1582
Zachary Turner97206d52017-05-12 04:51:55 +00001583lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001584 uint32_t &num, bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001585 Status error(GetWatchpointSupportInfo(num));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001586 if (error.Success())
1587 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1588 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001589}
1590
Zachary Turner97206d52017-05-12 04:51:55 +00001591lldb_private::Status
Kate Stoneb9c1b512016-09-06 20:57:50 +00001592GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1593 bool &after, const ArchSpec &arch) {
Zachary Turner97206d52017-05-12 04:51:55 +00001594 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001595 llvm::Triple::ArchType atype = arch.GetMachine();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001596
Kate Stoneb9c1b512016-09-06 20:57:50 +00001597 // we assume watchpoints will happen after running the relevant opcode
1598 // and we only want to override this behavior if we have explicitly
1599 // received a qHostInfo telling us otherwise
1600 if (m_qHostInfo_is_valid != eLazyBoolYes) {
Pavel Labathc51ad482017-10-27 17:02:32 +00001601 // On targets like MIPS and ppc64le, watchpoint exceptions are always
1602 // generated before the instruction is executed. The connected target
1603 // may not support qHostInfo or qWatchpointSupportInfo packets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001604 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
Pavel Labathc51ad482017-10-27 17:02:32 +00001605 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el ||
1606 atype == llvm::Triple::ppc64le)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001607 after = false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001608 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001609 after = true;
1610 } else {
Pavel Labathc51ad482017-10-27 17:02:32 +00001611 // For MIPS and ppc64le, set m_watchpoints_trigger_after_instruction to
1612 // eLazyBoolNo if it is not calculated before.
1613 if ((m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1614 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1615 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)) ||
1616 atype == llvm::Triple::ppc64le) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001617 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
Pavel Labathc51ad482017-10-27 17:02:32 +00001618 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001619
1620 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1621 }
1622 return error;
1623}
1624
1625int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1626 if (file_spec) {
1627 std::string path{file_spec.GetPath(false)};
1628 StreamString packet;
1629 packet.PutCString("QSetSTDIN:");
1630 packet.PutCStringAsRawHex8(path.c_str());
1631
1632 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001633 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1634 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001635 if (response.IsOKResponse())
1636 return 0;
1637 uint8_t error = response.GetError();
1638 if (error)
1639 return error;
1640 }
1641 }
1642 return -1;
1643}
1644
1645int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1646 if (file_spec) {
1647 std::string path{file_spec.GetPath(false)};
1648 StreamString packet;
1649 packet.PutCString("QSetSTDOUT:");
1650 packet.PutCStringAsRawHex8(path.c_str());
1651
1652 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001653 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1654 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001655 if (response.IsOKResponse())
1656 return 0;
1657 uint8_t error = response.GetError();
1658 if (error)
1659 return error;
1660 }
1661 }
1662 return -1;
1663}
1664
1665int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1666 if (file_spec) {
1667 std::string path{file_spec.GetPath(false)};
1668 StreamString packet;
1669 packet.PutCString("QSetSTDERR:");
1670 packet.PutCStringAsRawHex8(path.c_str());
1671
1672 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001673 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1674 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001675 if (response.IsOKResponse())
1676 return 0;
1677 uint8_t error = response.GetError();
1678 if (error)
1679 return error;
1680 }
1681 }
1682 return -1;
1683}
1684
1685bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1686 StringExtractorGDBRemote response;
1687 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1688 PacketResult::Success) {
1689 if (response.IsUnsupportedResponse())
1690 return false;
1691 if (response.IsErrorResponse())
1692 return false;
1693 std::string cwd;
1694 response.GetHexByteString(cwd);
Zachary Turner8c6b5462017-03-06 23:42:44 +00001695 working_dir.SetFile(cwd, false, GetHostArchitecture().GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001696 return !cwd.empty();
1697 }
1698 return false;
1699}
1700
1701int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1702 if (working_dir) {
1703 std::string path{working_dir.GetPath(false)};
1704 StreamString packet;
1705 packet.PutCString("QSetWorkingDir:");
1706 packet.PutCStringAsRawHex8(path.c_str());
1707
1708 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001709 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1710 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001711 if (response.IsOKResponse())
1712 return 0;
1713 uint8_t error = response.GetError();
1714 if (error)
1715 return error;
1716 }
1717 }
1718 return -1;
1719}
1720
1721int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1722 char packet[32];
1723 const int packet_len =
1724 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1725 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001726 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001727 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001728 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001729 PacketResult::Success) {
1730 if (response.IsOKResponse())
1731 return 0;
1732 uint8_t error = response.GetError();
1733 if (error)
1734 return error;
1735 }
1736 return -1;
1737}
1738
1739int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1740 char packet[32];
1741 const int packet_len = ::snprintf(packet, sizeof(packet),
1742 "QSetDetachOnError:%i", enable ? 1 : 0);
1743 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001744 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001745 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001746 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001747 PacketResult::Success) {
1748 if (response.IsOKResponse())
1749 return 0;
1750 uint8_t error = response.GetError();
1751 if (error)
1752 return error;
1753 }
1754 return -1;
1755}
1756
1757bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1758 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1759 if (response.IsNormalResponse()) {
1760 llvm::StringRef name;
1761 llvm::StringRef value;
1762 StringExtractor extractor;
1763
1764 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1765 uint32_t sub = 0;
1766 std::string vendor;
1767 std::string os_type;
1768
1769 while (response.GetNameColonValue(name, value)) {
1770 if (name.equals("pid")) {
1771 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1772 value.getAsInteger(0, pid);
1773 process_info.SetProcessID(pid);
1774 } else if (name.equals("ppid")) {
1775 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1776 value.getAsInteger(0, pid);
1777 process_info.SetParentProcessID(pid);
1778 } else if (name.equals("uid")) {
1779 uint32_t uid = UINT32_MAX;
1780 value.getAsInteger(0, uid);
1781 process_info.SetUserID(uid);
1782 } else if (name.equals("euid")) {
1783 uint32_t uid = UINT32_MAX;
1784 value.getAsInteger(0, uid);
1785 process_info.SetEffectiveGroupID(uid);
1786 } else if (name.equals("gid")) {
1787 uint32_t gid = UINT32_MAX;
1788 value.getAsInteger(0, gid);
1789 process_info.SetGroupID(gid);
1790 } else if (name.equals("egid")) {
1791 uint32_t gid = UINT32_MAX;
1792 value.getAsInteger(0, gid);
1793 process_info.SetEffectiveGroupID(gid);
1794 } else if (name.equals("triple")) {
1795 StringExtractor extractor(value);
1796 std::string triple;
1797 extractor.GetHexByteString(triple);
1798 process_info.GetArchitecture().SetTriple(triple.c_str());
1799 } else if (name.equals("name")) {
1800 StringExtractor extractor(value);
1801 // The process name from ASCII hex bytes since we can't
1802 // control the characters in a process name
1803 std::string name;
1804 extractor.GetHexByteString(name);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001805 process_info.GetExecutableFile().SetFile(name, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001806 } else if (name.equals("cputype")) {
1807 value.getAsInteger(0, cpu);
1808 } else if (name.equals("cpusubtype")) {
1809 value.getAsInteger(0, sub);
1810 } else if (name.equals("vendor")) {
1811 vendor = value;
1812 } else if (name.equals("ostype")) {
1813 os_type = value;
1814 }
1815 }
1816
1817 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1818 if (vendor == "apple") {
1819 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1820 sub);
1821 process_info.GetArchitecture().GetTriple().setVendorName(
1822 llvm::StringRef(vendor));
1823 process_info.GetArchitecture().GetTriple().setOSName(
1824 llvm::StringRef(os_type));
1825 }
1826 }
1827
1828 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1829 return true;
1830 }
1831 return false;
1832}
1833
1834bool GDBRemoteCommunicationClient::GetProcessInfo(
1835 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1836 process_info.Clear();
1837
1838 if (m_supports_qProcessInfoPID) {
1839 char packet[32];
1840 const int packet_len =
1841 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1842 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001843 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001844 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001845 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001846 PacketResult::Success) {
1847 return DecodeProcessInfoResponse(response, process_info);
1848 } else {
1849 m_supports_qProcessInfoPID = false;
1850 return false;
1851 }
1852 }
1853 return false;
1854}
1855
1856bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1857 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1858 GDBR_LOG_PACKETS));
1859
1860 if (allow_lazy) {
1861 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1862 return true;
1863 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1864 return false;
1865 }
1866
1867 GetHostInfo();
1868
1869 StringExtractorGDBRemote response;
1870 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1871 PacketResult::Success) {
1872 if (response.IsNormalResponse()) {
1873 llvm::StringRef name;
1874 llvm::StringRef value;
1875 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1876 uint32_t sub = 0;
1877 std::string arch_name;
1878 std::string os_name;
1879 std::string vendor_name;
1880 std::string triple;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001881 std::string elf_abi;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001882 uint32_t pointer_byte_size = 0;
1883 StringExtractor extractor;
1884 ByteOrder byte_order = eByteOrderInvalid;
1885 uint32_t num_keys_decoded = 0;
1886 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1887 while (response.GetNameColonValue(name, value)) {
1888 if (name.equals("cputype")) {
1889 if (!value.getAsInteger(16, cpu))
1890 ++num_keys_decoded;
1891 } else if (name.equals("cpusubtype")) {
1892 if (!value.getAsInteger(16, sub))
1893 ++num_keys_decoded;
1894 } else if (name.equals("triple")) {
1895 StringExtractor extractor(value);
1896 extractor.GetHexByteString(triple);
1897 ++num_keys_decoded;
1898 } else if (name.equals("ostype")) {
1899 os_name = value;
1900 ++num_keys_decoded;
1901 } else if (name.equals("vendor")) {
1902 vendor_name = value;
1903 ++num_keys_decoded;
1904 } else if (name.equals("endian")) {
1905 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1906 .Case("little", eByteOrderLittle)
1907 .Case("big", eByteOrderBig)
1908 .Case("pdp", eByteOrderPDP)
1909 .Default(eByteOrderInvalid);
1910 if (byte_order != eByteOrderInvalid)
1911 ++num_keys_decoded;
1912 } else if (name.equals("ptrsize")) {
1913 if (!value.getAsInteger(16, pointer_byte_size))
1914 ++num_keys_decoded;
1915 } else if (name.equals("pid")) {
1916 if (!value.getAsInteger(16, pid))
1917 ++num_keys_decoded;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001918 } else if (name.equals("elf_abi")) {
1919 elf_abi = value;
1920 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001921 }
1922 }
1923 if (num_keys_decoded > 0)
1924 m_qProcessInfo_is_valid = eLazyBoolYes;
1925 if (pid != LLDB_INVALID_PROCESS_ID) {
1926 m_curr_pid_is_valid = eLazyBoolYes;
1927 m_curr_pid = pid;
1928 }
1929
1930 // Set the ArchSpec from the triple if we have it.
1931 if (!triple.empty()) {
1932 m_process_arch.SetTriple(triple.c_str());
Nitesh Jain8999edf2016-10-12 10:21:09 +00001933 m_process_arch.SetFlags(elf_abi);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001934 if (pointer_byte_size) {
1935 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1936 }
1937 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
1938 !vendor_name.empty()) {
1939 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
1940
1941 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
Pavel Labath4f19fce22017-02-17 13:39:50 +00001942 assert(triple.getObjectFormat() != llvm::Triple::Wasm);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001943 switch (triple.getObjectFormat()) {
1944 case llvm::Triple::MachO:
1945 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1946 break;
1947 case llvm::Triple::ELF:
1948 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
1949 break;
1950 case llvm::Triple::COFF:
1951 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
1952 break;
Pavel Labath4f19fce22017-02-17 13:39:50 +00001953 case llvm::Triple::Wasm:
1954 if (log)
1955 log->Printf("error: not supported target architecture");
1956 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001957 case llvm::Triple::UnknownObjectFormat:
1958 if (log)
1959 log->Printf("error: failed to determine target architecture");
1960 return false;
1961 }
1962
1963 if (pointer_byte_size) {
1964 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1965 }
1966 if (byte_order != eByteOrderInvalid) {
1967 assert(byte_order == m_process_arch.GetByteOrder());
1968 }
1969 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1970 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1971 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1972 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1973 }
1974 return true;
1975 }
1976 } else {
1977 m_qProcessInfo_is_valid = eLazyBoolNo;
1978 }
1979
1980 return false;
1981}
1982
1983uint32_t GDBRemoteCommunicationClient::FindProcesses(
1984 const ProcessInstanceInfoMatch &match_info,
1985 ProcessInstanceInfoList &process_infos) {
1986 process_infos.Clear();
1987
1988 if (m_supports_qfProcessInfo) {
1989 StreamString packet;
1990 packet.PutCString("qfProcessInfo");
1991 if (!match_info.MatchAllProcesses()) {
1992 packet.PutChar(':');
1993 const char *name = match_info.GetProcessInfo().GetName();
1994 bool has_name_match = false;
1995 if (name && name[0]) {
1996 has_name_match = true;
Pavel Labathc4a33952017-02-20 11:35:33 +00001997 NameMatch name_match_type = match_info.GetNameMatchType();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001998 switch (name_match_type) {
Pavel Labathc4a33952017-02-20 11:35:33 +00001999 case NameMatch::Ignore:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002000 has_name_match = false;
2001 break;
2002
Pavel Labathc4a33952017-02-20 11:35:33 +00002003 case NameMatch::Equals:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002004 packet.PutCString("name_match:equals;");
2005 break;
2006
Pavel Labathc4a33952017-02-20 11:35:33 +00002007 case NameMatch::Contains:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002008 packet.PutCString("name_match:contains;");
2009 break;
2010
Pavel Labathc4a33952017-02-20 11:35:33 +00002011 case NameMatch::StartsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002012 packet.PutCString("name_match:starts_with;");
2013 break;
2014
Pavel Labathc4a33952017-02-20 11:35:33 +00002015 case NameMatch::EndsWith:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002016 packet.PutCString("name_match:ends_with;");
2017 break;
2018
Pavel Labathc4a33952017-02-20 11:35:33 +00002019 case NameMatch::RegularExpression:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002020 packet.PutCString("name_match:regex;");
2021 break;
2022 }
2023 if (has_name_match) {
2024 packet.PutCString("name:");
2025 packet.PutBytesAsRawHex8(name, ::strlen(name));
2026 packet.PutChar(';');
2027 }
2028 }
2029
2030 if (match_info.GetProcessInfo().ProcessIDIsValid())
2031 packet.Printf("pid:%" PRIu64 ";",
2032 match_info.GetProcessInfo().GetProcessID());
2033 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
2034 packet.Printf("parent_pid:%" PRIu64 ";",
2035 match_info.GetProcessInfo().GetParentProcessID());
2036 if (match_info.GetProcessInfo().UserIDIsValid())
2037 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2038 if (match_info.GetProcessInfo().GroupIDIsValid())
2039 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2040 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2041 packet.Printf("euid:%u;",
2042 match_info.GetProcessInfo().GetEffectiveUserID());
2043 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2044 packet.Printf("egid:%u;",
2045 match_info.GetProcessInfo().GetEffectiveGroupID());
2046 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2047 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2048 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2049 const ArchSpec &match_arch =
2050 match_info.GetProcessInfo().GetArchitecture();
2051 const llvm::Triple &triple = match_arch.GetTriple();
2052 packet.PutCString("triple:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002053 packet.PutCString(triple.getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002054 packet.PutChar(';');
2055 }
2056 }
2057 StringExtractorGDBRemote response;
2058 // Increase timeout as the first qfProcessInfo packet takes a long time
2059 // on Android. The value of 1min was arrived at empirically.
Pavel Labath1eff73c2016-11-24 10:54:49 +00002060 ScopedTimeout timeout(*this, minutes(1));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002061 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2062 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002063 do {
2064 ProcessInstanceInfo process_info;
2065 if (!DecodeProcessInfoResponse(response, process_info))
2066 break;
2067 process_infos.Append(process_info);
2068 response.GetStringRef().clear();
2069 response.SetFilePos(0);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002070 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2071 PacketResult::Success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002072 } else {
2073 m_supports_qfProcessInfo = false;
2074 return 0;
2075 }
2076 }
2077 return process_infos.GetSize();
2078}
2079
2080bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2081 std::string &name) {
2082 if (m_supports_qUserName) {
2083 char packet[32];
2084 const int packet_len =
2085 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2086 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002087 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002088 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002089 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002090 PacketResult::Success) {
2091 if (response.IsNormalResponse()) {
2092 // Make sure we parsed the right number of characters. The response is
2093 // the hex encoded user name and should make up the entire packet.
2094 // If there are any non-hex ASCII bytes, the length won't match below..
2095 if (response.GetHexByteString(name) * 2 ==
2096 response.GetStringRef().size())
2097 return true;
2098 }
2099 } else {
2100 m_supports_qUserName = false;
2101 return false;
2102 }
2103 }
2104 return false;
2105}
2106
2107bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2108 std::string &name) {
2109 if (m_supports_qGroupName) {
2110 char packet[32];
2111 const int packet_len =
2112 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2113 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002114 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002115 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002116 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002117 PacketResult::Success) {
2118 if (response.IsNormalResponse()) {
2119 // Make sure we parsed the right number of characters. The response is
2120 // the hex encoded group name and should make up the entire packet.
2121 // If there are any non-hex ASCII bytes, the length won't match below..
2122 if (response.GetHexByteString(name) * 2 ==
2123 response.GetStringRef().size())
2124 return true;
2125 }
2126 } else {
2127 m_supports_qGroupName = false;
2128 return false;
2129 }
2130 }
2131 return false;
2132}
2133
2134bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2135 // Form non-stop packet request
2136 char packet[32];
2137 const int packet_len =
2138 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2139 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002140 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002141
2142 StringExtractorGDBRemote response;
2143 // Send to target
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002144 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002145 PacketResult::Success)
2146 if (response.IsOKResponse())
2147 return true;
2148
2149 // Failed or not supported
2150 return false;
2151}
2152
2153static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2154 uint32_t recv_size) {
2155 packet.Clear();
2156 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2157 uint32_t bytes_left = send_size;
2158 while (bytes_left > 0) {
2159 if (bytes_left >= 26) {
2160 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2161 bytes_left -= 26;
2162 } else {
2163 packet.Printf("%*.*s;", bytes_left, bytes_left,
2164 "abcdefghijklmnopqrstuvwxyz");
2165 bytes_left = 0;
2166 }
2167 }
2168}
2169
Pavel Labath1eff73c2016-11-24 10:54:49 +00002170duration<float>
2171calculate_standard_deviation(const std::vector<duration<float>> &v) {
2172 using Dur = duration<float>;
Pavel Labath3aa04912016-10-31 17:19:42 +00002173 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2174 Dur mean = sum / v.size();
2175 float accum = 0;
2176 for (auto d : v) {
2177 float delta = (d - mean).count();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002178 accum += delta * delta;
Pavel Labath3aa04912016-10-31 17:19:42 +00002179 };
Kate Stoneb9c1b512016-09-06 20:57:50 +00002180
Pavel Labath3aa04912016-10-31 17:19:42 +00002181 return Dur(sqrtf(accum / (v.size() - 1)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002182}
2183
2184void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2185 uint32_t max_send,
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002186 uint32_t max_recv,
2187 uint64_t recv_amount,
2188 bool json, Stream &strm) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002190 if (SendSpeedTestPacket(0, 0)) {
2191 StreamString packet;
2192 if (json)
2193 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2194 "\"results\" : [",
2195 num_packets);
2196 else
2197 strm.Printf("Testing sending %u packets of various sizes:\n",
2198 num_packets);
2199 strm.Flush();
2200
2201 uint32_t result_idx = 0;
2202 uint32_t send_size;
Pavel Labath3aa04912016-10-31 17:19:42 +00002203 std::vector<duration<float>> packet_times;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002204
2205 for (send_size = 0; send_size <= max_send;
2206 send_size ? send_size *= 2 : send_size = 4) {
2207 for (uint32_t recv_size = 0; recv_size <= max_recv;
2208 recv_size ? recv_size *= 2 : recv_size = 4) {
2209 MakeSpeedTestPacket(packet, send_size, recv_size);
2210
2211 packet_times.clear();
2212 // Test how long it takes to send 'num_packets' packets
Pavel Labath3aa04912016-10-31 17:19:42 +00002213 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002214 for (i = 0; i < num_packets; ++i) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002215 const auto packet_start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002216 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002217 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Pavel Labath3aa04912016-10-31 17:19:42 +00002218 const auto packet_end_time = steady_clock::now();
2219 packet_times.push_back(packet_end_time - packet_start_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002220 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002221 const auto end_time = steady_clock::now();
2222 const auto total_time = end_time - start_time;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002223
2224 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002225 ((float)num_packets) / duration<float>(total_time).count();
2226 auto average_per_packet = total_time / num_packets;
2227 const duration<float> standard_deviation =
2228 calculate_standard_deviation(packet_times);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002229 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002230 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2231 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, "
2232 "\"standard_deviation_nsec\" : {4,9:ns-f0}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002233 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002234 total_time, standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 ++result_idx;
2236 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002237 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for "
2238 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with "
2239 "standard deviation of {5,10:ms+f6}\n",
2240 send_size, recv_size, duration<float>(total_time),
2241 packets_per_second, duration<float>(average_per_packet),
2242 standard_deviation);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002243 }
2244 strm.Flush();
2245 }
2246 }
2247
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002248 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002249 if (json)
2250 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2251 ": %" PRIu64 ",\n \"results\" : [",
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002252 recv_amount);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002253 else
2254 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2255 "packet sizes:\n",
2256 k_recv_amount_mb);
2257 strm.Flush();
2258 send_size = 0;
2259 result_idx = 0;
2260 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2261 MakeSpeedTestPacket(packet, send_size, recv_size);
2262
2263 // If we have a receive size, test how long it takes to receive 4MB of
2264 // data
2265 if (recv_size > 0) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002266 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002267 uint32_t bytes_read = 0;
2268 uint32_t packet_count = 0;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002269 while (bytes_read < recv_amount) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002270 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002271 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002272 bytes_read += recv_size;
2273 ++packet_count;
2274 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002275 const auto end_time = steady_clock::now();
2276 const auto total_time = end_time - start_time;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002277 float mb_second = ((float)recv_amount) /
Pavel Labath3aa04912016-10-31 17:19:42 +00002278 duration<float>(total_time).count() /
Kate Stoneb9c1b512016-09-06 20:57:50 +00002279 (1024.0 * 1024.0);
2280 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002281 ((float)packet_count) / duration<float>(total_time).count();
2282 const auto average_per_packet = total_time / packet_count;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002283
2284 if (json) {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002285 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : "
2286 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002287 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002288 total_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002289 ++result_idx;
2290 } else {
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002291 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed "
2292 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for "
2293 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n",
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294 send_size, recv_size, packet_count, k_recv_amount_mb,
Pavel Labath2f7cfaf2017-02-10 11:49:40 +00002295 duration<float>(total_time), mb_second,
2296 packets_per_second, duration<float>(average_per_packet));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002297 }
2298 strm.Flush();
2299 }
2300 }
2301 if (json)
2302 strm.Printf("\n ]\n }\n}\n");
2303 else
2304 strm.EOL();
2305 }
2306}
2307
2308bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2309 uint32_t recv_size) {
2310 StreamString packet;
2311 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2312 uint32_t bytes_left = send_size;
2313 while (bytes_left > 0) {
2314 if (bytes_left >= 26) {
2315 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2316 bytes_left -= 26;
2317 } else {
2318 packet.Printf("%*.*s;", bytes_left, bytes_left,
2319 "abcdefghijklmnopqrstuvwxyz");
2320 bytes_left = 0;
2321 }
2322 }
2323
2324 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002325 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2326 PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002327}
2328
2329bool GDBRemoteCommunicationClient::LaunchGDBServer(
2330 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2331 std::string &socket_name) {
2332 pid = LLDB_INVALID_PROCESS_ID;
2333 port = 0;
2334 socket_name.clear();
2335
2336 StringExtractorGDBRemote response;
2337 StreamString stream;
2338 stream.PutCString("qLaunchGDBServer;");
2339 std::string hostname;
2340 if (remote_accept_hostname && remote_accept_hostname[0])
2341 hostname = remote_accept_hostname;
2342 else {
2343 if (HostInfo::GetHostname(hostname)) {
2344 // Make the GDB server we launch only accept connections from this host
2345 stream.Printf("host:%s;", hostname.c_str());
2346 } else {
2347 // Make the GDB server we launch accept connections from any host since we
2348 // can't figure out the hostname
2349 stream.Printf("host:*;");
2350 }
2351 }
2352 // give the process a few seconds to startup
Pavel Labath1eff73c2016-11-24 10:54:49 +00002353 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002354
2355 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2356 PacketResult::Success) {
2357 llvm::StringRef name;
2358 llvm::StringRef value;
2359 while (response.GetNameColonValue(name, value)) {
2360 if (name.equals("port"))
2361 value.getAsInteger(0, port);
2362 else if (name.equals("pid"))
2363 value.getAsInteger(0, pid);
2364 else if (name.compare("socket_name") == 0) {
2365 StringExtractor extractor(value);
2366 extractor.GetHexByteString(socket_name);
2367 }
2368 }
2369 return true;
2370 }
2371 return false;
2372}
2373
2374size_t GDBRemoteCommunicationClient::QueryGDBServer(
2375 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2376 connection_urls.clear();
2377
2378 StringExtractorGDBRemote response;
2379 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2380 PacketResult::Success)
2381 return 0;
2382
2383 StructuredData::ObjectSP data =
2384 StructuredData::ParseJSON(response.GetStringRef());
2385 if (!data)
2386 return 0;
2387
2388 StructuredData::Array *array = data->GetAsArray();
2389 if (!array)
2390 return 0;
2391
2392 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2393 StructuredData::Dictionary *element = nullptr;
2394 if (!array->GetItemAtIndexAsDictionary(i, element))
2395 continue;
2396
2397 uint16_t port = 0;
2398 if (StructuredData::ObjectSP port_osp =
2399 element->GetValueForKey(llvm::StringRef("port")))
2400 port = port_osp->GetIntegerValue(0);
2401
2402 std::string socket_name;
2403 if (StructuredData::ObjectSP socket_name_osp =
2404 element->GetValueForKey(llvm::StringRef("socket_name")))
2405 socket_name = socket_name_osp->GetStringValue();
2406
2407 if (port != 0 || !socket_name.empty())
2408 connection_urls.emplace_back(port, socket_name);
2409 }
2410 return connection_urls.size();
2411}
2412
2413bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2414 StreamString stream;
2415 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002416
2417 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002418 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002419 PacketResult::Success) {
2420 if (response.IsOKResponse())
2421 return true;
2422 }
2423 return false;
2424}
2425
2426bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2427 if (m_curr_tid == tid)
2428 return true;
2429
2430 char packet[32];
2431 int packet_len;
2432 if (tid == UINT64_MAX)
2433 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2434 else
2435 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2436 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002437 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002438 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002439 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002440 PacketResult::Success) {
2441 if (response.IsOKResponse()) {
2442 m_curr_tid = tid;
2443 return true;
2444 }
2445
2446 /*
2447 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2448 * Hg packet.
2449 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2450 * which can
2451 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2452 */
2453 if (response.IsUnsupportedResponse() && IsConnected()) {
2454 m_curr_tid = 1;
2455 return true;
2456 }
2457 }
2458 return false;
2459}
2460
2461bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2462 if (m_curr_tid_run == tid)
2463 return true;
2464
2465 char packet[32];
2466 int packet_len;
2467 if (tid == UINT64_MAX)
2468 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2469 else
2470 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2471
2472 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002473 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002474 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002475 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002476 PacketResult::Success) {
2477 if (response.IsOKResponse()) {
2478 m_curr_tid_run = tid;
2479 return true;
2480 }
2481
2482 /*
2483 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2484 * Hc packet.
2485 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2486 * which can
2487 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2488 */
2489 if (response.IsUnsupportedResponse() && IsConnected()) {
2490 m_curr_tid_run = 1;
2491 return true;
2492 }
2493 }
2494 return false;
2495}
2496
2497bool GDBRemoteCommunicationClient::GetStopReply(
2498 StringExtractorGDBRemote &response) {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002499 if (SendPacketAndWaitForResponse("?", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002500 PacketResult::Success)
2501 return response.IsNormalResponse();
2502 return false;
2503}
2504
2505bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2506 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2507 if (m_supports_qThreadStopInfo) {
2508 char packet[256];
2509 int packet_len =
2510 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2511 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002512 UNUSED_IF_ASSERT_DISABLED(packet_len);
2513 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514 PacketResult::Success) {
2515 if (response.IsUnsupportedResponse())
2516 m_supports_qThreadStopInfo = false;
2517 else if (response.IsNormalResponse())
2518 return true;
2519 else
2520 return false;
2521 } else {
2522 m_supports_qThreadStopInfo = false;
2523 }
2524 }
2525 return false;
2526}
2527
2528uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2529 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2530 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2531 if (log)
2532 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2533 __FUNCTION__, insert ? "add" : "remove", addr);
2534
2535 // Check if the stub is known not to support this breakpoint type
2536 if (!SupportsGDBStoppointPacket(type))
2537 return UINT8_MAX;
2538 // Construct the breakpoint packet
2539 char packet[64];
2540 const int packet_len =
2541 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2542 insert ? 'Z' : 'z', type, addr, length);
2543 // Check we haven't overwritten the end of the packet buffer
2544 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002545 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002546 StringExtractorGDBRemote response;
2547 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2548 // or "" (unsupported)
2549 response.SetResponseValidatorToOKErrorNotSupported();
2550 // Try to send the breakpoint packet, and check that it was correctly sent
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002551 if (SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002552 PacketResult::Success) {
2553 // Receive and OK packet when the breakpoint successfully placed
2554 if (response.IsOKResponse())
2555 return 0;
2556
Zachary Turner97206d52017-05-12 04:51:55 +00002557 // Status while setting breakpoint, send back specific error
Kate Stoneb9c1b512016-09-06 20:57:50 +00002558 if (response.IsErrorResponse())
2559 return response.GetError();
2560
2561 // Empty packet informs us that breakpoint is not supported
2562 if (response.IsUnsupportedResponse()) {
2563 // Disable this breakpoint type since it is unsupported
2564 switch (type) {
2565 case eBreakpointSoftware:
2566 m_supports_z0 = false;
2567 break;
2568 case eBreakpointHardware:
2569 m_supports_z1 = false;
2570 break;
2571 case eWatchpointWrite:
2572 m_supports_z2 = false;
2573 break;
2574 case eWatchpointRead:
2575 m_supports_z3 = false;
2576 break;
2577 case eWatchpointReadWrite:
2578 m_supports_z4 = false;
2579 break;
2580 case eStoppointInvalid:
2581 return UINT8_MAX;
2582 }
2583 }
2584 }
2585 // Signal generic failure
2586 return UINT8_MAX;
2587}
2588
2589size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2590 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2591 thread_ids.clear();
2592
2593 Lock lock(*this, false);
2594 if (lock) {
2595 sequence_mutex_unavailable = false;
2596 StringExtractorGDBRemote response;
2597
2598 PacketResult packet_result;
2599 for (packet_result =
2600 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2601 packet_result == PacketResult::Success && response.IsNormalResponse();
2602 packet_result =
2603 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2604 char ch = response.GetChar();
2605 if (ch == 'l')
2606 break;
2607 if (ch == 'm') {
2608 do {
2609 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2610
2611 if (tid != LLDB_INVALID_THREAD_ID) {
2612 thread_ids.push_back(tid);
2613 }
2614 ch = response.GetChar(); // Skip the command separator
2615 } while (ch == ','); // Make sure we got a comma separator
2616 }
2617 }
2618
2619 /*
2620 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2621 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2622 * could
2623 * be as simple as 'S05'. There is no packet which can give us pid and/or
2624 * tid.
2625 * Assume pid=tid=1 in such cases.
2626 */
Tamas Berghammer1492cb82017-09-18 10:24:48 +00002627 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) &&
2628 thread_ids.size() == 0 && IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002629 thread_ids.push_back(1);
2630 }
2631 } else {
David Blaikiea322f362017-01-06 00:38:06 +00002632#if !defined(LLDB_CONFIGURATION_DEBUG)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002633 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2634 GDBR_LOG_PACKETS));
2635 if (log)
2636 log->Printf("error: failed to get packet sequence mutex, not sending "
2637 "packet 'qfThreadInfo'");
2638#endif
2639 sequence_mutex_unavailable = true;
2640 }
2641 return thread_ids.size();
2642}
2643
2644lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2645 StringExtractorGDBRemote response;
2646 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2647 PacketResult::Success ||
2648 !response.IsNormalResponse())
2649 return LLDB_INVALID_ADDRESS;
2650 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2651}
2652
Zachary Turner97206d52017-05-12 04:51:55 +00002653lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002654 const char *command, // Shouldn't be NULL
2655 const FileSpec &
2656 working_dir, // Pass empty FileSpec to use the current working directory
2657 int *status_ptr, // Pass NULL if you don't want the process exit status
2658 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2659 // process to exit
2660 std::string
2661 *command_output, // Pass NULL if you don't want the command output
2662 uint32_t
2663 timeout_sec) // Timeout in seconds to wait for shell program to finish
2664{
2665 lldb_private::StreamString stream;
2666 stream.PutCString("qPlatform_shell:");
2667 stream.PutBytesAsRawHex8(command, strlen(command));
2668 stream.PutChar(',');
2669 stream.PutHex32(timeout_sec);
2670 if (working_dir) {
2671 std::string path{working_dir.GetPath(false)};
2672 stream.PutChar(',');
2673 stream.PutCStringAsRawHex8(path.c_str());
2674 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002675 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002676 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002677 PacketResult::Success) {
2678 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002679 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002680 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002681 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002682 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2683 if (exitcode == UINT32_MAX)
Zachary Turner97206d52017-05-12 04:51:55 +00002684 return Status("unable to run remote process");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002685 else if (status_ptr)
2686 *status_ptr = exitcode;
2687 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002688 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002689 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2690 if (signo_ptr)
2691 *signo_ptr = signo;
2692 if (response.GetChar() != ',')
Zachary Turner97206d52017-05-12 04:51:55 +00002693 return Status("malformed reply");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002694 std::string output;
2695 response.GetEscapedBinaryData(output);
2696 if (command_output)
2697 command_output->assign(output);
Zachary Turner97206d52017-05-12 04:51:55 +00002698 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002699 }
Zachary Turner97206d52017-05-12 04:51:55 +00002700 return Status("unable to send packet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002701}
2702
Zachary Turner97206d52017-05-12 04:51:55 +00002703Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2704 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002705 std::string path{file_spec.GetPath(false)};
2706 lldb_private::StreamString stream;
2707 stream.PutCString("qPlatform_mkdir:");
2708 stream.PutHex32(file_permissions);
2709 stream.PutChar(',');
2710 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002711 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002712 StringExtractorGDBRemote response;
2713
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002714 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002715 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002716 return Status("failed to send '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002717
2718 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002719 return Status("invalid response to '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002720
Zachary Turner97206d52017-05-12 04:51:55 +00002721 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002722}
2723
Zachary Turner97206d52017-05-12 04:51:55 +00002724Status
2725GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
2726 uint32_t file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002727 std::string path{file_spec.GetPath(false)};
2728 lldb_private::StreamString stream;
2729 stream.PutCString("qPlatform_chmod:");
2730 stream.PutHex32(file_permissions);
2731 stream.PutChar(',');
2732 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002733 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002734 StringExtractorGDBRemote response;
2735
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002736 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002737 PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00002738 return Status("failed to send '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002739
2740 if (response.GetChar() != 'F')
Zachary Turner97206d52017-05-12 04:51:55 +00002741 return Status("invalid response to '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002742
Zachary Turner97206d52017-05-12 04:51:55 +00002743 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002744}
2745
2746static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
Zachary Turner97206d52017-05-12 04:51:55 +00002747 uint64_t fail_result, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002748 response.SetFilePos(0);
2749 if (response.GetChar() != 'F')
2750 return fail_result;
2751 int32_t result = response.GetS32(-2);
2752 if (result == -2)
2753 return fail_result;
2754 if (response.GetChar() == ',') {
2755 int result_errno = response.GetS32(-2);
2756 if (result_errno != -2)
2757 error.SetError(result_errno, eErrorTypePOSIX);
2758 else
2759 error.SetError(-1, eErrorTypeGeneric);
2760 } else
2761 error.Clear();
2762 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002763}
2764lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002765GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2766 uint32_t flags, mode_t mode,
Zachary Turner97206d52017-05-12 04:51:55 +00002767 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002768 std::string path(file_spec.GetPath(false));
2769 lldb_private::StreamString stream;
2770 stream.PutCString("vFile:open:");
2771 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002772 return UINT64_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002773 stream.PutCStringAsRawHex8(path.c_str());
2774 stream.PutChar(',');
2775 stream.PutHex32(flags);
2776 stream.PutChar(',');
2777 stream.PutHex32(mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002778 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002779 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002780 PacketResult::Success) {
2781 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2782 }
2783 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002784}
2785
Zachary Turner97206d52017-05-12 04:51:55 +00002786bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd,
2787 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002788 lldb_private::StreamString stream;
2789 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002791 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002792 PacketResult::Success) {
2793 return ParseHostIOPacketResponse(response, -1, error) == 0;
2794 }
2795 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002796}
2797
2798// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002799lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2800 const lldb_private::FileSpec &file_spec) {
2801 std::string path(file_spec.GetPath(false));
2802 lldb_private::StreamString stream;
2803 stream.PutCString("vFile:size:");
2804 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002805 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002806 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002807 PacketResult::Success) {
2808 if (response.GetChar() != 'F')
2809 return UINT64_MAX;
2810 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2811 return retcode;
2812 }
2813 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002814}
2815
Zachary Turner97206d52017-05-12 04:51:55 +00002816Status
2817GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
2818 uint32_t &file_permissions) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002819 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002820 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 lldb_private::StreamString stream;
2822 stream.PutCString("vFile:mode:");
2823 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002824 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002825 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 PacketResult::Success) {
2827 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002828 error.SetErrorStringWithFormat("invalid response to '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002829 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830 } else {
2831 const uint32_t mode = response.GetS32(-1);
2832 if (static_cast<int32_t>(mode) == -1) {
2833 if (response.GetChar() == ',') {
2834 int response_errno = response.GetS32(-1);
2835 if (response_errno > 0)
2836 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2837 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002838 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002839 } else
2840 error.SetErrorToGenericError();
2841 } else {
2842 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2843 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002844 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002845 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002846 error.SetErrorStringWithFormat("failed to send '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002847 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002848 }
2849 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002850}
2851
Kate Stoneb9c1b512016-09-06 20:57:50 +00002852uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2853 uint64_t offset, void *dst,
2854 uint64_t dst_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002855 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002856 lldb_private::StreamString stream;
2857 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2858 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002859 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002860 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002861 PacketResult::Success) {
2862 if (response.GetChar() != 'F')
2863 return 0;
2864 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2865 if (retcode == UINT32_MAX)
2866 return retcode;
2867 const char next = (response.Peek() ? *response.Peek() : 0);
2868 if (next == ',')
2869 return 0;
2870 if (next == ';') {
2871 response.GetChar(); // skip the semicolon
2872 std::string buffer;
2873 if (response.GetEscapedBinaryData(buffer)) {
2874 const uint64_t data_to_write =
2875 std::min<uint64_t>(dst_len, buffer.size());
2876 if (data_to_write > 0)
2877 memcpy(dst, &buffer[0], data_to_write);
2878 return data_to_write;
2879 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002880 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002881 }
2882 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002883}
2884
Kate Stoneb9c1b512016-09-06 20:57:50 +00002885uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
2886 uint64_t offset,
2887 const void *src,
2888 uint64_t src_len,
Zachary Turner97206d52017-05-12 04:51:55 +00002889 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002890 lldb_private::StreamGDBRemote stream;
2891 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2892 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002893 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002894 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002895 PacketResult::Success) {
2896 if (response.GetChar() != 'F') {
2897 error.SetErrorStringWithFormat("write file failed");
2898 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002899 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002900 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2901 if (bytes_written == UINT64_MAX) {
2902 error.SetErrorToGenericError();
2903 if (response.GetChar() == ',') {
2904 int response_errno = response.GetS32(-1);
2905 if (response_errno > 0)
2906 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2907 }
2908 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002909 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002910 return bytes_written;
2911 } else {
2912 error.SetErrorString("failed to send vFile:pwrite packet");
2913 }
2914 return 0;
2915}
2916
Zachary Turner97206d52017-05-12 04:51:55 +00002917Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
2918 const FileSpec &dst) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002919 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002920 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002921 lldb_private::StreamGDBRemote stream;
2922 stream.PutCString("vFile:symlink:");
2923 // the unix symlink() command reverses its parameters where the dst if first,
2924 // so we follow suit here
2925 stream.PutCStringAsRawHex8(dst_path.c_str());
2926 stream.PutChar(',');
2927 stream.PutCStringAsRawHex8(src_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002928 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002929 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002930 PacketResult::Success) {
2931 if (response.GetChar() == 'F') {
2932 uint32_t result = response.GetU32(UINT32_MAX);
2933 if (result != 0) {
2934 error.SetErrorToGenericError();
2935 if (response.GetChar() == ',') {
2936 int response_errno = response.GetS32(-1);
2937 if (response_errno > 0)
2938 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2939 }
2940 }
2941 } else {
2942 // Should have returned with 'F<result>[,<errno>]'
2943 error.SetErrorStringWithFormat("symlink failed");
2944 }
2945 } else {
2946 error.SetErrorString("failed to send vFile:symlink packet");
2947 }
2948 return error;
2949}
2950
Zachary Turner97206d52017-05-12 04:51:55 +00002951Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002952 std::string path{file_spec.GetPath(false)};
Zachary Turner97206d52017-05-12 04:51:55 +00002953 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002954 lldb_private::StreamGDBRemote stream;
2955 stream.PutCString("vFile:unlink:");
2956 // the unix symlink() command reverses its parameters where the dst if first,
2957 // so we follow suit here
2958 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002959 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002960 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002961 PacketResult::Success) {
2962 if (response.GetChar() == 'F') {
2963 uint32_t result = response.GetU32(UINT32_MAX);
2964 if (result != 0) {
2965 error.SetErrorToGenericError();
2966 if (response.GetChar() == ',') {
2967 int response_errno = response.GetS32(-1);
2968 if (response_errno > 0)
2969 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2970 }
2971 }
2972 } else {
2973 // Should have returned with 'F<result>[,<errno>]'
2974 error.SetErrorStringWithFormat("unlink failed");
2975 }
2976 } else {
2977 error.SetErrorString("failed to send vFile:unlink packet");
2978 }
2979 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002980}
2981
Daniel Maleae0f8f572013-08-26 23:57:52 +00002982// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002983bool GDBRemoteCommunicationClient::GetFileExists(
2984 const lldb_private::FileSpec &file_spec) {
2985 std::string path(file_spec.GetPath(false));
2986 lldb_private::StreamString stream;
2987 stream.PutCString("vFile:exists:");
2988 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002989 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002990 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991 PacketResult::Success) {
2992 if (response.GetChar() != 'F')
2993 return false;
2994 if (response.GetChar() != ',')
2995 return false;
2996 bool retcode = (response.GetChar() != '0');
2997 return retcode;
2998 }
2999 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003000}
3001
Kate Stoneb9c1b512016-09-06 20:57:50 +00003002bool GDBRemoteCommunicationClient::CalculateMD5(
3003 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
3004 std::string path(file_spec.GetPath(false));
3005 lldb_private::StreamString stream;
3006 stream.PutCString("vFile:MD5:");
3007 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003008 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003009 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00003010 PacketResult::Success) {
3011 if (response.GetChar() != 'F')
3012 return false;
3013 if (response.GetChar() != ',')
3014 return false;
3015 if (response.Peek() && *response.Peek() == 'x')
3016 return false;
3017 low = response.GetHexMaxU64(false, UINT64_MAX);
3018 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00003019 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003020 }
3021 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003022}
3023
Kate Stoneb9c1b512016-09-06 20:57:50 +00003024bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
3025 // Some targets have issues with g/G packets and we need to avoid using them
3026 if (m_avoid_g_packets == eLazyBoolCalculate) {
3027 if (process) {
3028 m_avoid_g_packets = eLazyBoolNo;
3029 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3030 if (arch.IsValid() &&
3031 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
3032 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3033 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3034 m_avoid_g_packets = eLazyBoolYes;
3035 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3036 if (gdb_server_version != 0) {
3037 const char *gdb_server_name = GetGDBServerProgramName();
3038 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3039 if (gdb_server_version >= 310)
3040 m_avoid_g_packets = eLazyBoolNo;
3041 }
3042 }
3043 }
3044 }
3045 }
3046 return m_avoid_g_packets == eLazyBoolYes;
3047}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003048
Kate Stoneb9c1b512016-09-06 20:57:50 +00003049DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3050 uint32_t reg) {
3051 StreamString payload;
3052 payload.Printf("p%x", reg);
3053 StringExtractorGDBRemote response;
3054 if (SendThreadSpecificPacketAndWaitForResponse(
3055 tid, std::move(payload), response, false) != PacketResult::Success ||
3056 !response.IsNormalResponse())
3057 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003058
Kate Stoneb9c1b512016-09-06 20:57:50 +00003059 DataBufferSP buffer_sp(
3060 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3061 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3062 return buffer_sp;
3063}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003064
Kate Stoneb9c1b512016-09-06 20:57:50 +00003065DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3066 StreamString payload;
3067 payload.PutChar('g');
3068 StringExtractorGDBRemote response;
3069 if (SendThreadSpecificPacketAndWaitForResponse(
3070 tid, std::move(payload), response, false) != PacketResult::Success ||
3071 !response.IsNormalResponse())
3072 return nullptr;
3073
3074 DataBufferSP buffer_sp(
3075 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3076 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3077 return buffer_sp;
3078}
3079
3080bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3081 uint32_t reg_num,
3082 llvm::ArrayRef<uint8_t> data) {
3083 StreamString payload;
3084 payload.Printf("P%x=", reg_num);
3085 payload.PutBytesAsRawHex8(data.data(), data.size(),
3086 endian::InlHostByteOrder(),
3087 endian::InlHostByteOrder());
3088 StringExtractorGDBRemote response;
3089 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3090 response, false) ==
3091 PacketResult::Success &&
3092 response.IsOKResponse();
3093}
3094
3095bool GDBRemoteCommunicationClient::WriteAllRegisters(
3096 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3097 StreamString payload;
3098 payload.PutChar('G');
3099 payload.PutBytesAsRawHex8(data.data(), data.size(),
3100 endian::InlHostByteOrder(),
3101 endian::InlHostByteOrder());
3102 StringExtractorGDBRemote response;
3103 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3104 response, false) ==
3105 PacketResult::Success &&
3106 response.IsOKResponse();
3107}
3108
3109bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3110 uint32_t &save_id) {
3111 save_id = 0; // Set to invalid save ID
3112 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003113 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003114
3115 m_supports_QSaveRegisterState = eLazyBoolYes;
3116 StreamString payload;
3117 payload.PutCString("QSaveRegisterState");
3118 StringExtractorGDBRemote response;
3119 if (SendThreadSpecificPacketAndWaitForResponse(
3120 tid, std::move(payload), response, false) != PacketResult::Success)
3121 return false;
3122
3123 if (response.IsUnsupportedResponse())
3124 m_supports_QSaveRegisterState = eLazyBoolNo;
3125
3126 const uint32_t response_save_id = response.GetU32(0);
3127 if (response_save_id == 0)
3128 return false;
3129
3130 save_id = response_save_id;
3131 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003132}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003133
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3135 uint32_t save_id) {
3136 // We use the "m_supports_QSaveRegisterState" variable here because the
3137 // QSaveRegisterState and QRestoreRegisterState packets must both be supported
3138 // in
3139 // order to be useful
3140 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3141 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003142
Kate Stoneb9c1b512016-09-06 20:57:50 +00003143 StreamString payload;
3144 payload.Printf("QRestoreRegisterState:%u", save_id);
3145 StringExtractorGDBRemote response;
3146 if (SendThreadSpecificPacketAndWaitForResponse(
3147 tid, std::move(payload), response, false) != PacketResult::Success)
3148 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003149
Kate Stoneb9c1b512016-09-06 20:57:50 +00003150 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003151 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003152
3153 if (response.IsUnsupportedResponse())
3154 m_supports_QSaveRegisterState = eLazyBoolNo;
3155 return false;
3156}
3157
3158bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3159 if (!GetSyncThreadStateSupported())
3160 return false;
3161
3162 StreamString packet;
3163 StringExtractorGDBRemote response;
3164 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3165 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3166 GDBRemoteCommunication::PacketResult::Success &&
3167 response.IsOKResponse();
3168}
3169
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003170lldb::user_id_t
3171GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options,
3172 Status &error) {
3173 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3174 lldb::user_id_t ret_uid = LLDB_INVALID_UID;
3175
3176 StreamGDBRemote escaped_packet;
3177 escaped_packet.PutCString("jTraceStart:");
3178
3179 StructuredData::Dictionary json_packet;
3180 json_packet.AddIntegerItem("type", options.getType());
3181 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
3182 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
3183
3184 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3185 json_packet.AddIntegerItem("threadid", options.getThreadID());
3186
3187 StructuredData::DictionarySP custom_params = options.getTraceParams();
3188 if (custom_params)
3189 json_packet.AddItem("params", custom_params);
3190
3191 StreamString json_string;
3192 json_packet.Dump(json_string, false);
3193 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3194
3195 StringExtractorGDBRemote response;
3196 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3197 true) ==
3198 GDBRemoteCommunication::PacketResult::Success) {
3199 if (!response.IsNormalResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003200 error = response.GetStatus();
3201 LLDB_LOG(log, "Target does not support Tracing , error {0}", error);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003202 } else {
3203 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID);
3204 }
3205 } else {
3206 LLDB_LOG(log, "failed to send packet");
3207 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3208 escaped_packet.GetData());
3209 }
3210 return ret_uid;
3211}
3212
3213Status
3214GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid,
3215 lldb::tid_t thread_id) {
3216 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3217 StringExtractorGDBRemote response;
3218 Status error;
3219
3220 StructuredData::Dictionary json_packet;
3221 StreamGDBRemote escaped_packet;
3222 StreamString json_string;
3223 escaped_packet.PutCString("jTraceStop:");
3224
3225 json_packet.AddIntegerItem("traceid", uid);
3226
3227 if (thread_id != LLDB_INVALID_THREAD_ID)
3228 json_packet.AddIntegerItem("threadid", thread_id);
3229
3230 json_packet.Dump(json_string, false);
3231
3232 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3233
3234 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3235 true) ==
3236 GDBRemoteCommunication::PacketResult::Success) {
3237 if (!response.IsOKResponse()) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003238 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003239 LLDB_LOG(log, "stop tracing failed");
3240 }
3241 } else {
3242 LLDB_LOG(log, "failed to send packet");
3243 error.SetErrorStringWithFormat(
3244 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(),
3245 response.GetError());
3246 }
3247 return error;
3248}
3249
3250Status GDBRemoteCommunicationClient::SendGetDataPacket(
3251 lldb::user_id_t uid, lldb::tid_t thread_id,
3252 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003253
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003254 StreamGDBRemote escaped_packet;
3255 escaped_packet.PutCString("jTraceBufferRead:");
3256 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3257}
3258
3259Status GDBRemoteCommunicationClient::SendGetMetaDataPacket(
3260 lldb::user_id_t uid, lldb::tid_t thread_id,
3261 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003262
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003263 StreamGDBRemote escaped_packet;
3264 escaped_packet.PutCString("jTraceMetaRead:");
3265 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset);
3266}
3267
3268Status
3269GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid,
3270 TraceOptions &options) {
3271 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3272 StringExtractorGDBRemote response;
3273 Status error;
3274
3275 StreamString json_string;
3276 StreamGDBRemote escaped_packet;
3277 escaped_packet.PutCString("jTraceConfigRead:");
3278
3279 StructuredData::Dictionary json_packet;
3280 json_packet.AddIntegerItem("traceid", uid);
3281
3282 if (options.getThreadID() != LLDB_INVALID_THREAD_ID)
3283 json_packet.AddIntegerItem("threadid", options.getThreadID());
3284
3285 json_packet.Dump(json_string, false);
3286 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3287
3288 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response,
3289 true) ==
3290 GDBRemoteCommunication::PacketResult::Success) {
3291 if (response.IsNormalResponse()) {
3292 uint64_t type = std::numeric_limits<uint64_t>::max();
3293 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
3294 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
3295
3296 auto json_object = StructuredData::ParseJSON(response.Peek());
3297
3298 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003299 json_object->GetType() != lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003300 error.SetErrorString("Invalid Configuration obtained");
3301 return error;
3302 }
3303
3304 auto json_dict = json_object->GetAsDictionary();
3305
3306 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize",
3307 metabuffersize);
3308 options.setMetaDataBufferSize(metabuffersize);
3309
3310 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize);
3311 options.setTraceBufferSize(buffersize);
3312
3313 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type);
3314 options.setType(static_cast<lldb::TraceType>(type));
3315
3316 StructuredData::ObjectSP custom_params_sp =
3317 json_dict->GetValueForKey("params");
3318 if (custom_params_sp) {
3319 if (custom_params_sp->GetType() !=
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00003320 lldb::eStructuredDataTypeDictionary) {
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003321 error.SetErrorString("Invalid Configuration obtained");
3322 return error;
3323 } else
3324 options.setTraceParams(
3325 static_pointer_cast<StructuredData::Dictionary>(
3326 custom_params_sp));
3327 }
3328 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003329 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003330 }
3331 } else {
3332 LLDB_LOG(log, "failed to send packet");
3333 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3334 escaped_packet.GetData());
3335 }
3336 return error;
3337}
3338
3339Status GDBRemoteCommunicationClient::SendGetTraceDataPacket(
3340 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id,
3341 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) {
3342 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3343 Status error;
3344
3345 StructuredData::Dictionary json_packet;
3346
3347 json_packet.AddIntegerItem("traceid", uid);
3348 json_packet.AddIntegerItem("offset", offset);
3349 json_packet.AddIntegerItem("buffersize", buffer.size());
3350
3351 if (thread_id != LLDB_INVALID_THREAD_ID)
3352 json_packet.AddIntegerItem("threadid", thread_id);
3353
3354 StreamString json_string;
3355 json_packet.Dump(json_string, false);
3356
3357 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize());
3358 StringExtractorGDBRemote response;
3359 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) ==
3360 GDBRemoteCommunication::PacketResult::Success) {
3361 if (response.IsNormalResponse()) {
3362 size_t filled_size = response.GetHexBytesAvail(buffer);
3363 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size);
3364 } else {
Ravitheja Addepallydab1d5f2017-07-12 11:15:34 +00003365 error = response.GetStatus();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00003366 buffer = buffer.slice(buffer.size());
3367 }
3368 } else {
3369 LLDB_LOG(log, "failed to send packet");
3370 error.SetErrorStringWithFormat("failed to send packet: '%s'",
3371 packet.GetData());
3372 buffer = buffer.slice(buffer.size());
3373 }
3374 return error;
3375}
3376
Kate Stoneb9c1b512016-09-06 20:57:50 +00003377bool GDBRemoteCommunicationClient::GetModuleInfo(
3378 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3379 ModuleSpec &module_spec) {
3380 if (!m_supports_qModuleInfo)
3381 return false;
3382
3383 std::string module_path = module_file_spec.GetPath(false);
3384 if (module_path.empty())
3385 return false;
3386
3387 StreamString packet;
3388 packet.PutCString("qModuleInfo:");
3389 packet.PutCStringAsRawHex8(module_path.c_str());
3390 packet.PutCString(";");
3391 const auto &triple = arch_spec.GetTriple().getTriple();
3392 packet.PutCStringAsRawHex8(triple.c_str());
3393
3394 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003395 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3396 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003397 return false;
3398
3399 if (response.IsErrorResponse())
3400 return false;
3401
3402 if (response.IsUnsupportedResponse()) {
3403 m_supports_qModuleInfo = false;
3404 return false;
3405 }
3406
3407 llvm::StringRef name;
3408 llvm::StringRef value;
3409
3410 module_spec.Clear();
3411 module_spec.GetFileSpec() = module_file_spec;
3412
3413 while (response.GetNameColonValue(name, value)) {
3414 if (name == "uuid" || name == "md5") {
3415 StringExtractor extractor(value);
3416 std::string uuid;
3417 extractor.GetHexByteString(uuid);
3418 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
3419 } else if (name == "triple") {
3420 StringExtractor extractor(value);
3421 std::string triple;
3422 extractor.GetHexByteString(triple);
3423 module_spec.GetArchitecture().SetTriple(triple.c_str());
3424 } else if (name == "file_offset") {
3425 uint64_t ival = 0;
3426 if (!value.getAsInteger(16, ival))
3427 module_spec.SetObjectOffset(ival);
3428 } else if (name == "file_size") {
3429 uint64_t ival = 0;
3430 if (!value.getAsInteger(16, ival))
3431 module_spec.SetObjectSize(ival);
3432 } else if (name == "file_path") {
3433 StringExtractor extractor(value);
3434 std::string path;
3435 extractor.GetHexByteString(path);
Zachary Turner8c6b5462017-03-06 23:42:44 +00003436 module_spec.GetFileSpec() = FileSpec(path, false, arch_spec.GetTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003437 }
3438 }
3439
3440 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003441}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003442
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003443static llvm::Optional<ModuleSpec>
3444ParseModuleSpec(StructuredData::Dictionary *dict) {
3445 ModuleSpec result;
3446 if (!dict)
3447 return llvm::None;
3448
Zachary Turner28333212017-05-12 05:49:54 +00003449 llvm::StringRef string;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003450 uint64_t integer;
3451
3452 if (!dict->GetValueForKeyAsString("uuid", string))
3453 return llvm::None;
Pavel Labath8c92c892017-12-18 14:31:44 +00003454 if (result.GetUUID().SetFromStringRef(string, string.size() / 2) !=
3455 string.size())
3456 return llvm::None;
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003457
3458 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3459 return llvm::None;
3460 result.SetObjectOffset(integer);
3461
3462 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3463 return llvm::None;
3464 result.SetObjectSize(integer);
3465
3466 if (!dict->GetValueForKeyAsString("triple", string))
3467 return llvm::None;
Zachary Turner28333212017-05-12 05:49:54 +00003468 result.GetArchitecture().SetTriple(string);
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003469
3470 if (!dict->GetValueForKeyAsString("file_path", string))
3471 return llvm::None;
Zachary Turner8c6b5462017-03-06 23:42:44 +00003472 result.GetFileSpec() =
3473 FileSpec(string, false, result.GetArchitecture().GetTriple());
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003474
3475 return result;
3476}
3477
3478llvm::Optional<std::vector<ModuleSpec>>
3479GDBRemoteCommunicationClient::GetModulesInfo(
3480 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3481 if (!m_supports_jModulesInfo)
3482 return llvm::None;
3483
3484 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3485 for (const FileSpec &module_file_spec : module_file_specs) {
3486 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3487 module_array_sp->AppendObject(module_sp);
3488 module_sp->SetObject(
Pavel Labath763f1c42017-01-05 13:18:46 +00003489 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003490 module_sp->SetObject("triple",
3491 std::make_shared<JSONString>(triple.getTriple()));
3492 }
3493 StreamString unescaped_payload;
3494 unescaped_payload.PutCString("jModulesInfo:");
3495 module_array_sp->Write(unescaped_payload);
3496 StreamGDBRemote payload;
Zachary Turnerc1564272016-11-16 21:15:24 +00003497 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003498 unescaped_payload.GetSize());
3499
Greg Clayton70a9f512017-04-14 17:10:04 +00003500 // Increase the timeout for jModulesInfo since this packet can take longer.
3501 ScopedTimeout timeout(*this, std::chrono::seconds(10));
3502
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003503 StringExtractorGDBRemote response;
3504 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3505 PacketResult::Success ||
3506 response.IsErrorResponse())
3507 return llvm::None;
3508
3509 if (response.IsUnsupportedResponse()) {
3510 m_supports_jModulesInfo = false;
3511 return llvm::None;
3512 }
3513
3514 StructuredData::ObjectSP response_object_sp =
3515 StructuredData::ParseJSON(response.GetStringRef());
3516 if (!response_object_sp)
3517 return llvm::None;
3518
3519 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3520 if (!response_array)
3521 return llvm::None;
3522
3523 std::vector<ModuleSpec> result;
3524 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3525 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3526 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3527 result.push_back(*module_spec);
3528 }
3529
3530 return result;
3531}
3532
Colin Rileyc3c95b22015-04-16 15:51:33 +00003533// query the target remote for extended information using the qXfer packet
3534//
3535// example: object='features', annex='target.xml', out=<xml output>
3536// return: 'true' on success
3537// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003538bool GDBRemoteCommunicationClient::ReadExtFeature(
3539 const lldb_private::ConstString object,
3540 const lldb_private::ConstString annex, std::string &out,
Zachary Turner97206d52017-05-12 04:51:55 +00003541 lldb_private::Status &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003542
Kate Stoneb9c1b512016-09-06 20:57:50 +00003543 std::stringstream output;
3544 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003545
Kate Stoneb9c1b512016-09-06 20:57:50 +00003546 uint64_t size = GetRemoteMaxPacketSize();
3547 if (size == 0)
3548 size = 0x1000;
3549 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3550 int offset = 0;
3551 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003552
Kate Stoneb9c1b512016-09-06 20:57:50 +00003553 // loop until all data has been read
3554 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003555
Kate Stoneb9c1b512016-09-06 20:57:50 +00003556 // send query extended feature packet
3557 std::stringstream packet;
3558 packet << "qXfer:" << object.AsCString("")
3559 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3560 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003561
Kate Stoneb9c1b512016-09-06 20:57:50 +00003562 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003563 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003564
Kate Stoneb9c1b512016-09-06 20:57:50 +00003565 if (res != GDBRemoteCommunication::PacketResult::Success) {
3566 err.SetErrorString("Error sending $qXfer packet");
3567 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003568 }
3569
Kate Stoneb9c1b512016-09-06 20:57:50 +00003570 const std::string &str = chunk.GetStringRef();
3571 if (str.length() == 0) {
3572 // should have some data in chunk
3573 err.SetErrorString("Empty response from $qXfer packet");
3574 return false;
3575 }
3576
3577 // check packet code
3578 switch (str[0]) {
3579 // last chunk
3580 case ('l'):
3581 active = false;
3582 LLVM_FALLTHROUGH;
3583
3584 // more chunks
3585 case ('m'):
3586 if (str.length() > 1)
3587 output << &str[1];
3588 offset += size;
3589 break;
3590
3591 // unknown chunk
3592 default:
3593 err.SetErrorString("Invalid continuation code from $qXfer packet");
3594 return false;
3595 }
3596 }
3597
3598 out = output.str();
3599 err.Success();
3600 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003601}
Greg Clayton0b90be12015-06-23 21:27:50 +00003602
3603// Notify the target that gdb is prepared to serve symbol lookup requests.
3604// packet: "qSymbol::"
3605// reply:
3606// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003607// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3608// encoded).
3609// LLDB may provide the value by sending another qSymbol
3610// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003611// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003612//
3613// Three examples:
3614//
3615// lldb sends: qSymbol::
3616// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003617// Remote gdb stub does not need to know the addresses of any symbols, lldb
3618// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003619// need to ask again in this session.
3620//
3621// lldb sends: qSymbol::
3622// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3623// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3624// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003625// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3626// not know
3627// the address at this time. lldb needs to send qSymbol:: again when it has
3628// more
Jason Molenda50018d32016-01-13 04:08:10 +00003629// solibs loaded.
3630//
3631// lldb sends: qSymbol::
3632// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3633// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3634// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003635// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3636// that it
3637// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3638// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003639// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003640
Kate Stoneb9c1b512016-09-06 20:57:50 +00003641void GDBRemoteCommunicationClient::ServeSymbolLookups(
3642 lldb_private::Process *process) {
3643 // Set to true once we've resolved a symbol to an address for the remote stub.
3644 // If we get an 'OK' response after this, the remote stub doesn't need any
3645 // more
3646 // symbols and we can stop asking.
3647 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003648
Kate Stoneb9c1b512016-09-06 20:57:50 +00003649 // Is this the initial qSymbol:: packet?
3650 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003651
Kate Stoneb9c1b512016-09-06 20:57:50 +00003652 if (m_supports_qSymbol && m_qSymbol_requests_done == false) {
3653 Lock lock(*this, false);
3654 if (lock) {
3655 StreamString packet;
3656 packet.PutCString("qSymbol::");
3657 StringExtractorGDBRemote response;
3658 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3659 PacketResult::Success) {
3660 if (response.IsOKResponse()) {
3661 if (symbol_response_provided || first_qsymbol_query) {
3662 m_qSymbol_requests_done = true;
3663 }
3664
3665 // We are done serving symbols requests
3666 return;
3667 }
3668 first_qsymbol_query = false;
3669
3670 if (response.IsUnsupportedResponse()) {
3671 // qSymbol is not supported by the current GDB server we are connected
3672 // to
3673 m_supports_qSymbol = false;
3674 return;
3675 } else {
3676 llvm::StringRef response_str(response.GetStringRef());
3677 if (response_str.startswith("qSymbol:")) {
3678 response.SetFilePos(strlen("qSymbol:"));
3679 std::string symbol_name;
3680 if (response.GetHexByteString(symbol_name)) {
3681 if (symbol_name.empty())
3682 return;
3683
3684 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3685 lldb_private::SymbolContextList sc_list;
3686 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3687 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3688 const size_t num_scs = sc_list.GetSize();
3689 for (size_t sc_idx = 0;
3690 sc_idx < num_scs &&
3691 symbol_load_addr == LLDB_INVALID_ADDRESS;
3692 ++sc_idx) {
3693 SymbolContext sc;
3694 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3695 if (sc.symbol) {
3696 switch (sc.symbol->GetType()) {
3697 case eSymbolTypeInvalid:
3698 case eSymbolTypeAbsolute:
3699 case eSymbolTypeUndefined:
3700 case eSymbolTypeSourceFile:
3701 case eSymbolTypeHeaderFile:
3702 case eSymbolTypeObjectFile:
3703 case eSymbolTypeCommonBlock:
3704 case eSymbolTypeBlock:
3705 case eSymbolTypeLocal:
3706 case eSymbolTypeParam:
3707 case eSymbolTypeVariable:
3708 case eSymbolTypeVariableType:
3709 case eSymbolTypeLineEntry:
3710 case eSymbolTypeLineHeader:
3711 case eSymbolTypeScopeBegin:
3712 case eSymbolTypeScopeEnd:
3713 case eSymbolTypeAdditional:
3714 case eSymbolTypeCompiler:
3715 case eSymbolTypeInstrumentation:
3716 case eSymbolTypeTrampoline:
3717 break;
3718
3719 case eSymbolTypeCode:
3720 case eSymbolTypeResolver:
3721 case eSymbolTypeData:
3722 case eSymbolTypeRuntime:
3723 case eSymbolTypeException:
3724 case eSymbolTypeObjCClass:
3725 case eSymbolTypeObjCMetaClass:
3726 case eSymbolTypeObjCIVar:
3727 case eSymbolTypeReExported:
3728 symbol_load_addr =
3729 sc.symbol->GetLoadAddress(&process->GetTarget());
3730 break;
3731 }
Jason Molenda50018d32016-01-13 04:08:10 +00003732 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003733 }
Greg Clayton42b01482015-08-11 22:07:46 +00003734 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003735 }
3736 // This is the normal path where our symbol lookup was successful
3737 // and we want
3738 // to send a packet with the new symbol value and see if another
3739 // lookup needs to be
3740 // done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003741
Kate Stoneb9c1b512016-09-06 20:57:50 +00003742 // Change "packet" to contain the requested symbol value and name
3743 packet.Clear();
3744 packet.PutCString("qSymbol:");
3745 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3746 packet.Printf("%" PRIx64, symbol_load_addr);
3747 symbol_response_provided = true;
3748 } else {
3749 symbol_response_provided = false;
3750 }
3751 packet.PutCString(":");
3752 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3753 continue; // go back to the while loop and send "packet" and wait
3754 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003755 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003756 }
3757 }
3758 }
3759 // If we make it here, the symbol request packet response wasn't valid or
3760 // our symbol lookup failed so we must abort
3761 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003762
Kate Stoneb9c1b512016-09-06 20:57:50 +00003763 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3764 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3765 log->Printf(
3766 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3767 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003768 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003769 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003770}
3771
Kate Stoneb9c1b512016-09-06 20:57:50 +00003772StructuredData::Array *
3773GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3774 if (!m_supported_async_json_packets_is_valid) {
3775 // Query the server for the array of supported asynchronous JSON
3776 // packets.
3777 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003778
Kate Stoneb9c1b512016-09-06 20:57:50 +00003779 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003780
Kate Stoneb9c1b512016-09-06 20:57:50 +00003781 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003782 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003783 const bool send_async = false;
3784 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3785 send_async) == PacketResult::Success) {
3786 m_supported_async_json_packets_sp =
3787 StructuredData::ParseJSON(response.GetStringRef());
3788 if (m_supported_async_json_packets_sp &&
3789 !m_supported_async_json_packets_sp->GetAsArray()) {
3790 // We were returned something other than a JSON array. This
3791 // is invalid. Clear it out.
3792 if (log)
3793 log->Printf("GDBRemoteCommunicationClient::%s(): "
3794 "QSupportedAsyncJSONPackets returned invalid "
3795 "result: %s",
3796 __FUNCTION__, response.GetStringRef().c_str());
3797 m_supported_async_json_packets_sp.reset();
3798 }
3799 } else {
3800 if (log)
3801 log->Printf("GDBRemoteCommunicationClient::%s(): "
3802 "QSupportedAsyncJSONPackets unsupported",
3803 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003804 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003805
3806 if (log && m_supported_async_json_packets_sp) {
3807 StreamString stream;
3808 m_supported_async_json_packets_sp->Dump(stream);
3809 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3810 "JSON packets: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00003811 __FUNCTION__, stream.GetData());
Todd Fiala75930012016-08-19 04:21:48 +00003812 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003813 }
3814
3815 return m_supported_async_json_packets_sp
3816 ? m_supported_async_json_packets_sp->GetAsArray()
3817 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003818}
3819
Zachary Turner97206d52017-05-12 04:51:55 +00003820Status GDBRemoteCommunicationClient::SendSignalsToIgnore(
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003821 llvm::ArrayRef<int32_t> signals) {
3822 // Format packet:
3823 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN>
3824 auto range = llvm::make_range(signals.begin(), signals.end());
3825 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str();
3826
3827 StringExtractorGDBRemote response;
3828 auto send_status = SendPacketAndWaitForResponse(packet, response, false);
3829
3830 if (send_status != GDBRemoteCommunication::PacketResult::Success)
Zachary Turner97206d52017-05-12 04:51:55 +00003831 return Status("Sending QPassSignals packet failed");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003832
3833 if (response.IsOKResponse()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003834 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003835 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00003836 return Status("Unknown error happened during sending QPassSignals packet.");
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003837 }
3838}
3839
Zachary Turner97206d52017-05-12 04:51:55 +00003840Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
Kate Stoneb9c1b512016-09-06 20:57:50 +00003841 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00003842 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003843
3844 if (type_name.GetLength() == 0) {
3845 error.SetErrorString("invalid type_name argument");
3846 return error;
3847 }
3848
3849 // Build command: Configure{type_name}: serialized config
3850 // data.
3851 StreamGDBRemote stream;
3852 stream.PutCString("QConfigure");
3853 stream.PutCString(type_name.AsCString());
3854 stream.PutChar(':');
3855 if (config_sp) {
3856 // Gather the plain-text version of the configuration data.
3857 StreamString unescaped_stream;
3858 config_sp->Dump(unescaped_stream);
3859 unescaped_stream.Flush();
3860
3861 // Add it to the stream in escaped fashion.
Zachary Turnerc1564272016-11-16 21:15:24 +00003862 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003863 unescaped_stream.GetSize());
3864 }
3865 stream.Flush();
3866
3867 // Send the packet.
3868 const bool send_async = false;
3869 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003870 auto result =
3871 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003872 if (result == PacketResult::Success) {
3873 // We failed if the config result comes back other than OK.
3874 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3875 // Okay!
3876 error.Clear();
3877 } else {
3878 error.SetErrorStringWithFormat("configuring StructuredData feature "
3879 "%s failed with error %s",
3880 type_name.AsCString(),
3881 response.GetStringRef().c_str());
3882 }
3883 } else {
3884 // Can we get more data here on the failure?
3885 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3886 "failed when sending packet: "
3887 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00003888 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003889 }
3890 return error;
3891}
3892
3893void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
3894 GDBRemoteClientBase::OnRunPacketSent(first);
3895 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003896}