blob: a2659443900f553fe4f46bf15b8d85e55431d684 [file] [log] [blame]
Greg Clayton576d8832011-03-22 04:00:09 +00001//===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Greg Clayton576d8832011-03-22 04:00:09 +000010#include "GDBRemoteCommunicationClient.h"
11
12// C Includes
Greg Claytone034a042015-05-21 20:52:06 +000013#include <math.h>
Daniel Maleab89d0492013-08-28 16:06:16 +000014#include <sys/stat.h>
15
Greg Clayton576d8832011-03-22 04:00:09 +000016// C++ Includes
Greg Claytone034a042015-05-21 20:52:06 +000017#include <numeric>
Kate Stoneb9c1b512016-09-06 20:57:50 +000018#include <sstream>
Han Ming Ong4b6459f2013-01-18 23:11:53 +000019
Greg Clayton576d8832011-03-22 04:00:09 +000020// Other libraries and framework includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000021#include "lldb/Core/DataBufferHeap.h"
Greg Clayton576d8832011-03-22 04:00:09 +000022#include "lldb/Core/Log.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000023#include "lldb/Core/ModuleSpec.h"
Greg Clayton576d8832011-03-22 04:00:09 +000024#include "lldb/Core/State.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000025#include "lldb/Core/StreamGDBRemote.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000026#include "lldb/Host/HostInfo.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000027#include "lldb/Host/StringConvert.h"
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000028#include "lldb/Interpreter/Args.h"
Greg Clayton0b90be12015-06-23 21:27:50 +000029#include "lldb/Symbol/Symbol.h"
Pavel Labath4cb69922016-07-29 15:41:52 +000030#include "lldb/Target/MemoryRegionInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000031#include "lldb/Target/Target.h"
Todd Fiala75930012016-08-19 04:21:48 +000032#include "lldb/Target/UnixSignals.h"
Pavel Labath2f1fbae2016-09-08 10:07:04 +000033#include "lldb/Utility/JSON.h"
Todd Fiala75930012016-08-19 04:21:48 +000034#include "lldb/Utility/LLDBAssert.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000035#include "lldb/Utility/StreamString.h"
Greg Clayton576d8832011-03-22 04:00:09 +000036
37// Project includes
Greg Clayton576d8832011-03-22 04:00:09 +000038#include "ProcessGDBRemote.h"
39#include "ProcessGDBRemoteLog.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000040#include "Utility/StringExtractorGDBRemote.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000041#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000042
Zachary Turner54695a32016-08-29 19:58:14 +000043#include "llvm/ADT/StringSwitch.h"
44
Kate Stoneb9c1b512016-09-06 20:57:50 +000045#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000046#include <compression.h>
47#endif
48
Greg Clayton576d8832011-03-22 04:00:09 +000049using namespace lldb;
50using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000051using namespace lldb_private::process_gdb_remote;
Pavel Labath1eff73c2016-11-24 10:54:49 +000052using namespace std::chrono;
Greg Clayton576d8832011-03-22 04:00:09 +000053
54//----------------------------------------------------------------------
55// GDBRemoteCommunicationClient constructor
56//----------------------------------------------------------------------
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000057GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000058 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000059 m_supports_not_sending_acks(eLazyBoolCalculate),
60 m_supports_thread_suffix(eLazyBoolCalculate),
61 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
62 m_supports_vCont_all(eLazyBoolCalculate),
63 m_supports_vCont_any(eLazyBoolCalculate),
64 m_supports_vCont_c(eLazyBoolCalculate),
65 m_supports_vCont_C(eLazyBoolCalculate),
66 m_supports_vCont_s(eLazyBoolCalculate),
67 m_supports_vCont_S(eLazyBoolCalculate),
68 m_qHostInfo_is_valid(eLazyBoolCalculate),
69 m_curr_pid_is_valid(eLazyBoolCalculate),
70 m_qProcessInfo_is_valid(eLazyBoolCalculate),
71 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
72 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
73 m_supports_memory_region_info(eLazyBoolCalculate),
74 m_supports_watchpoint_support_info(eLazyBoolCalculate),
75 m_supports_detach_stay_stopped(eLazyBoolCalculate),
76 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
77 m_attach_or_wait_reply(eLazyBoolCalculate),
78 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
Kate Stoneb9c1b512016-09-06 20:57:50 +000079 m_supports_p(eLazyBoolCalculate), m_supports_x(eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000080 m_avoid_g_packets(eLazyBoolCalculate),
81 m_supports_QSaveRegisterState(eLazyBoolCalculate),
82 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
83 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
84 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
85 m_supports_qXfer_features_read(eLazyBoolCalculate),
86 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
87 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
88 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000089 m_supports_jGetSharedCacheInfo(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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116bool GDBRemoteCommunicationClient::HandshakeWithServer(Error *error_ptr) {
117 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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() {
154 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) {
155 GetRemoteQSupported();
156 }
157 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000158}
159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() {
161 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) {
162 GetRemoteQSupported();
163 }
164 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000165}
166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() {
168 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) {
169 GetRemoteQSupported();
170 }
171 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000172}
173
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() {
175 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) {
176 GetRemoteQSupported();
177 }
178 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000179}
180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() {
182 if (m_supports_qXfer_features_read == eLazyBoolCalculate) {
183 GetRemoteQSupported();
184 }
185 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000186}
187
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() {
189 if (m_max_packet_size == 0) {
190 GetRemoteQSupported();
191 }
192 return m_max_packet_size;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000193}
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() {
196 if (m_supports_not_sending_acks == eLazyBoolCalculate) {
197 m_send_acks = true;
198 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000199
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200 // This is the first real packet that we'll send in a debug session and it
201 // may take a little
202 // longer than normal to receive a reply. Wait at least 6 seconds for a
203 // reply to this packet.
Jason Molenda36a216e2014-07-24 01:36:24 +0000204
Pavel Labath1eff73c2016-11-24 10:54:49 +0000205 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6)));
Colin Rileyc3c95b22015-04-16 15:51:33 +0000206
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000207 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) ==
209 PacketResult::Success) {
210 if (response.IsOKResponse()) {
211 m_send_acks = false;
212 m_supports_not_sending_acks = eLazyBoolYes;
213 }
214 return true;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000215 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216 }
217 return false;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000218}
Greg Clayton576d8832011-03-22 04:00:09 +0000219
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() {
221 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) {
222 m_supports_threads_in_stop_reply = eLazyBoolNo;
223
224 StringExtractorGDBRemote response;
225 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response,
226 false) == PacketResult::Success) {
227 if (response.IsOKResponse())
228 m_supports_threads_in_stop_reply = eLazyBoolYes;
Pavel Labath5c95ee42016-08-30 13:56:11 +0000229 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 }
Pavel Labath0faf3732016-08-25 08:34:57 +0000231}
Greg Clayton576d8832011-03-22 04:00:09 +0000232
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() {
234 if (m_attach_or_wait_reply == eLazyBoolCalculate) {
235 m_attach_or_wait_reply = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +0000236
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 StringExtractorGDBRemote response;
238 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response,
239 false) == PacketResult::Success) {
240 if (response.IsOKResponse())
241 m_attach_or_wait_reply = eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000242 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243 }
244 if (m_attach_or_wait_reply == eLazyBoolYes)
245 return true;
246 else
Greg Clayton576d8832011-03-22 04:00:09 +0000247 return false;
248}
249
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() {
251 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) {
252 m_prepare_for_reg_writing_reply = eLazyBoolNo;
253
254 StringExtractorGDBRemote response;
255 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response,
256 false) == PacketResult::Success) {
257 if (response.IsOKResponse())
258 m_prepare_for_reg_writing_reply = eLazyBoolYes;
259 }
260 }
261 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
262 return true;
263 else
264 return false;
265}
266
267void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) {
268 if (did_exec == false) {
269 // Hard reset everything, this is when we first connect to a GDB server
270 m_supports_not_sending_acks = eLazyBoolCalculate;
271 m_supports_thread_suffix = eLazyBoolCalculate;
272 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
273 m_supports_vCont_c = eLazyBoolCalculate;
274 m_supports_vCont_C = eLazyBoolCalculate;
275 m_supports_vCont_s = eLazyBoolCalculate;
276 m_supports_vCont_S = eLazyBoolCalculate;
277 m_supports_p = eLazyBoolCalculate;
278 m_supports_x = eLazyBoolCalculate;
279 m_supports_QSaveRegisterState = eLazyBoolCalculate;
280 m_qHostInfo_is_valid = eLazyBoolCalculate;
281 m_curr_pid_is_valid = eLazyBoolCalculate;
282 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
283 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
284 m_supports_memory_region_info = eLazyBoolCalculate;
285 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
286 m_attach_or_wait_reply = eLazyBoolCalculate;
287 m_avoid_g_packets = eLazyBoolCalculate;
288 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
289 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
290 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
291 m_supports_qXfer_features_read = eLazyBoolCalculate;
292 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
293 m_supports_qProcessInfoPID = true;
294 m_supports_qfProcessInfo = true;
295 m_supports_qUserName = true;
296 m_supports_qGroupName = true;
297 m_supports_qThreadStopInfo = true;
298 m_supports_z0 = true;
299 m_supports_z1 = true;
300 m_supports_z2 = true;
301 m_supports_z3 = true;
302 m_supports_z4 = true;
303 m_supports_QEnvironment = true;
304 m_supports_QEnvironmentHexEncoded = true;
305 m_supports_qSymbol = true;
306 m_qSymbol_requests_done = false;
307 m_supports_qModuleInfo = true;
308 m_host_arch.Clear();
309 m_os_version_major = UINT32_MAX;
310 m_os_version_minor = UINT32_MAX;
311 m_os_version_update = UINT32_MAX;
312 m_os_build.clear();
313 m_os_kernel.clear();
314 m_hostname.clear();
315 m_gdb_server_name.clear();
316 m_gdb_server_version = UINT32_MAX;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000317 m_default_packet_timeout = seconds(0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000318 m_max_packet_size = 0;
319 m_qSupported_response.clear();
320 m_supported_async_json_packets_is_valid = false;
321 m_supported_async_json_packets_sp.reset();
Pavel Labath2f1fbae2016-09-08 10:07:04 +0000322 m_supports_jModulesInfo = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 }
324
325 // These flags should be reset when we first connect to a GDB server
326 // and when our inferior process execs
327 m_qProcessInfo_is_valid = eLazyBoolCalculate;
328 m_process_arch.Clear();
329}
330
331void GDBRemoteCommunicationClient::GetRemoteQSupported() {
332 // Clear out any capabilities we expect to see in the qSupported response
333 m_supports_qXfer_auxv_read = eLazyBoolNo;
334 m_supports_qXfer_libraries_read = eLazyBoolNo;
335 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
336 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
337 m_supports_qXfer_features_read = eLazyBoolNo;
338 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if
339 // not, we assume no limit
340
341 // build the qSupported packet
342 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
343 StreamString packet;
344 packet.PutCString("qSupported");
345 for (uint32_t i = 0; i < features.size(); ++i) {
346 packet.PutCString(i == 0 ? ":" : ";");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000347 packet.PutCString(features[i]);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348 }
349
350 StringExtractorGDBRemote response;
Zachary Turnerc1564272016-11-16 21:15:24 +0000351 if (SendPacketAndWaitForResponse(packet.GetString(), response,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 /*send_async=*/false) ==
353 PacketResult::Success) {
354 const char *response_cstr = response.GetStringRef().c_str();
355
356 // Hang on to the qSupported packet, so that platforms can do custom
357 // configuration of the transport before attaching/launching the
358 // process.
359 m_qSupported_response = response_cstr;
360
361 if (::strstr(response_cstr, "qXfer:auxv:read+"))
362 m_supports_qXfer_auxv_read = eLazyBoolYes;
363 if (::strstr(response_cstr, "qXfer:libraries-svr4:read+"))
364 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
365 if (::strstr(response_cstr, "augmented-libraries-svr4-read")) {
366 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
367 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
368 }
369 if (::strstr(response_cstr, "qXfer:libraries:read+"))
370 m_supports_qXfer_libraries_read = eLazyBoolYes;
371 if (::strstr(response_cstr, "qXfer:features:read+"))
372 m_supports_qXfer_features_read = eLazyBoolYes;
373
374 // Look for a list of compressions in the features list e.g.
375 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
376 const char *features_list = ::strstr(response_cstr, "qXfer:features:");
377 if (features_list) {
378 const char *compressions =
379 ::strstr(features_list, "SupportedCompressions=");
380 if (compressions) {
381 std::vector<std::string> supported_compressions;
382 compressions += sizeof("SupportedCompressions=") - 1;
383 const char *end_of_compressions = strchr(compressions, ';');
384 if (end_of_compressions == NULL) {
385 end_of_compressions = strchr(compressions, '\0');
386 }
387 const char *current_compression = compressions;
388 while (current_compression < end_of_compressions) {
389 const char *next_compression_name = strchr(current_compression, ',');
390 const char *end_of_this_word = next_compression_name;
391 if (next_compression_name == NULL ||
392 end_of_compressions < next_compression_name) {
393 end_of_this_word = end_of_compressions;
394 }
395
396 if (end_of_this_word) {
397 if (end_of_this_word == current_compression) {
398 current_compression++;
399 } else {
400 std::string this_compression(
401 current_compression, end_of_this_word - current_compression);
402 supported_compressions.push_back(this_compression);
403 current_compression = end_of_this_word + 1;
404 }
405 } else {
406 supported_compressions.push_back(current_compression);
407 current_compression = end_of_compressions;
408 }
409 }
410
411 if (supported_compressions.size() > 0) {
412 MaybeEnableCompression(supported_compressions);
413 }
414 }
415 }
416
417 if (::strstr(response_cstr, "qEcho"))
418 m_supports_qEcho = eLazyBoolYes;
419 else
420 m_supports_qEcho = eLazyBoolNo;
421
422 const char *packet_size_str = ::strstr(response_cstr, "PacketSize=");
423 if (packet_size_str) {
424 StringExtractorGDBRemote packet_response(packet_size_str +
425 strlen("PacketSize="));
426 m_max_packet_size =
427 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
428 if (m_max_packet_size == 0) {
429 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
430 Log *log(
431 ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
432 if (log)
433 log->Printf("Garbled PacketSize spec in qSupported response");
434 }
435 }
436 }
437}
438
439bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() {
440 if (m_supports_thread_suffix == eLazyBoolCalculate) {
441 StringExtractorGDBRemote response;
442 m_supports_thread_suffix = eLazyBoolNo;
443 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response,
444 false) == PacketResult::Success) {
445 if (response.IsOKResponse())
446 m_supports_thread_suffix = eLazyBoolYes;
447 }
448 }
449 return m_supports_thread_suffix;
450}
451bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) {
452 if (m_supports_vCont_c == eLazyBoolCalculate) {
453 StringExtractorGDBRemote response;
454 m_supports_vCont_any = eLazyBoolNo;
455 m_supports_vCont_all = eLazyBoolNo;
456 m_supports_vCont_c = eLazyBoolNo;
457 m_supports_vCont_C = eLazyBoolNo;
458 m_supports_vCont_s = eLazyBoolNo;
459 m_supports_vCont_S = eLazyBoolNo;
460 if (SendPacketAndWaitForResponse("vCont?", response, false) ==
461 PacketResult::Success) {
462 const char *response_cstr = response.GetStringRef().c_str();
463 if (::strstr(response_cstr, ";c"))
464 m_supports_vCont_c = eLazyBoolYes;
465
466 if (::strstr(response_cstr, ";C"))
467 m_supports_vCont_C = eLazyBoolYes;
468
469 if (::strstr(response_cstr, ";s"))
470 m_supports_vCont_s = eLazyBoolYes;
471
472 if (::strstr(response_cstr, ";S"))
473 m_supports_vCont_S = eLazyBoolYes;
474
475 if (m_supports_vCont_c == eLazyBoolYes &&
476 m_supports_vCont_C == eLazyBoolYes &&
477 m_supports_vCont_s == eLazyBoolYes &&
478 m_supports_vCont_S == eLazyBoolYes) {
479 m_supports_vCont_all = eLazyBoolYes;
480 }
481
482 if (m_supports_vCont_c == eLazyBoolYes ||
483 m_supports_vCont_C == eLazyBoolYes ||
484 m_supports_vCont_s == eLazyBoolYes ||
485 m_supports_vCont_S == eLazyBoolYes) {
486 m_supports_vCont_any = eLazyBoolYes;
487 }
488 }
489 }
490
491 switch (flavor) {
492 case 'a':
493 return m_supports_vCont_any;
494 case 'A':
495 return m_supports_vCont_all;
496 case 'c':
497 return m_supports_vCont_c;
498 case 'C':
499 return m_supports_vCont_C;
500 case 's':
501 return m_supports_vCont_s;
502 case 'S':
503 return m_supports_vCont_S;
504 default:
505 break;
506 }
507 return false;
508}
509
Pavel Labath4b6f9592016-08-18 08:30:03 +0000510GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000511GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(
512 lldb::tid_t tid, StreamString &&payload, StringExtractorGDBRemote &response,
513 bool send_async) {
514 Lock lock(*this, send_async);
515 if (!lock) {
516 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
517 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
518 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex "
519 "for %s packet.",
Zachary Turnerc1564272016-11-16 21:15:24 +0000520 __FUNCTION__, payload.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 return PacketResult::ErrorNoSequenceLock;
522 }
Pavel Labath5c95ee42016-08-30 13:56:11 +0000523
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524 if (GetThreadSuffixSupported())
525 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
526 else {
527 if (!SetCurrentThread(tid))
528 return PacketResult::ErrorSendFailed;
529 }
Pavel Labath4b6f9592016-08-18 08:30:03 +0000530
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
Pavel Labath4b6f9592016-08-18 08:30:03 +0000532}
533
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000534// Check if the target supports 'p' packet. It sends out a 'p'
535// packet and checks the response. A normal packet will tell us
536// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000537//
538// Takes a valid thread ID because p needs to apply to a thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) {
540 if (m_supports_p == eLazyBoolCalculate) {
541 m_supports_p = eLazyBoolNo;
542 StreamString payload;
543 payload.PutCString("p0");
544 StringExtractorGDBRemote response;
545 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
546 response, false) ==
547 PacketResult::Success &&
548 response.IsNormalResponse()) {
549 m_supports_p = eLazyBoolYes;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000550 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 }
552 return m_supports_p;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000553}
Greg Clayton576d8832011-03-22 04:00:09 +0000554
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() {
556 // Get information on all threads at one using the "jThreadsInfo" packet
557 StructuredData::ObjectSP object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000558
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 if (m_supports_jThreadsInfo) {
560 StringExtractorGDBRemote response;
561 response.SetResponseValidatorToJSON();
562 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) ==
563 PacketResult::Success) {
564 if (response.IsUnsupportedResponse()) {
565 m_supports_jThreadsInfo = false;
566 } else if (!response.Empty()) {
567 object_sp = StructuredData::ParseJSON(response.GetStringRef());
568 }
Greg Clayton358cf1e2015-06-25 21:46:34 +0000569 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 }
571 return object_sp;
Greg Clayton358cf1e2015-06-25 21:46:34 +0000572}
573
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() {
575 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) {
576 StringExtractorGDBRemote response;
577 m_supports_jThreadExtendedInfo = eLazyBoolNo;
578 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) ==
579 PacketResult::Success) {
580 if (response.IsOKResponse()) {
581 m_supports_jThreadExtendedInfo = eLazyBoolYes;
582 }
Jason Molenda705b1802014-06-13 02:37:02 +0000583 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584 }
585 return m_supports_jThreadExtendedInfo;
Jason Molenda705b1802014-06-13 02:37:02 +0000586}
587
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() {
589 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) {
590 StringExtractorGDBRemote response;
591 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
592 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:",
593 response,
594 false) == PacketResult::Success) {
595 if (response.IsOKResponse()) {
596 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
597 }
Jason Molenda20ee21b2015-07-10 23:15:22 +0000598 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599 }
600 return m_supports_jLoadedDynamicLibrariesInfos;
Jason Molenda20ee21b2015-07-10 23:15:22 +0000601}
602
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() {
604 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) {
605 StringExtractorGDBRemote response;
606 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
607 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) ==
608 PacketResult::Success) {
609 if (response.IsOKResponse()) {
610 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
611 }
Jason Molenda37397352016-07-22 00:17:55 +0000612 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 }
614 return m_supports_jGetSharedCacheInfo;
Jason Molenda37397352016-07-22 00:17:55 +0000615}
616
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617bool GDBRemoteCommunicationClient::GetxPacketSupported() {
618 if (m_supports_x == eLazyBoolCalculate) {
619 StringExtractorGDBRemote response;
620 m_supports_x = eLazyBoolNo;
621 char packet[256];
622 snprintf(packet, sizeof(packet), "x0,0");
623 if (SendPacketAndWaitForResponse(packet, response, false) ==
624 PacketResult::Success) {
625 if (response.IsOKResponse())
626 m_supports_x = eLazyBoolYes;
Jason Molendabdc4f122014-05-06 02:59:39 +0000627 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628 }
629 return m_supports_x;
Jason Molendabdc4f122014-05-06 02:59:39 +0000630}
631
Greg Clayton3dedae12013-12-06 21:45:27 +0000632GDBRemoteCommunicationClient::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses(
634 const char *payload_prefix, std::string &response_string) {
635 Lock lock(*this, false);
636 if (!lock) {
637 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
638 GDBR_LOG_PACKETS));
639 if (log)
640 log->Printf("error: failed to get packet sequence mutex, not sending "
641 "packets with prefix '%s'",
642 payload_prefix);
643 return PacketResult::ErrorNoSequenceLock;
644 }
645
646 response_string = "";
647 std::string payload_prefix_str(payload_prefix);
648 unsigned int response_size = 0x1000;
649 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
650 response_size = GetRemoteMaxPacketSize();
651 }
652
653 for (unsigned int offset = 0; true; offset += response_size) {
654 StringExtractorGDBRemote this_response;
655 // Construct payload
656 char sizeDescriptor[128];
657 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset,
658 response_size);
659 PacketResult result = SendPacketAndWaitForResponseNoLock(
660 payload_prefix_str + sizeDescriptor, this_response);
661 if (result != PacketResult::Success)
662 return result;
663
664 const std::string &this_string = this_response.GetStringRef();
665
666 // Check for m or l as first character; l seems to mean this is the last
667 // chunk
668 char first_char = *this_string.c_str();
669 if (first_char != 'm' && first_char != 'l') {
670 return PacketResult::ErrorReplyInvalid;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000671 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672 // Concatenate the result so far (skipping 'm' or 'l')
673 response_string.append(this_string, 1, std::string::npos);
674 if (first_char == 'l')
675 // We're done
676 return PacketResult::Success;
677 }
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000678}
679
Kate Stoneb9c1b512016-09-06 20:57:50 +0000680lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) {
681 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
682 return m_curr_pid;
Jaydeep Patil1142f832015-08-13 03:46:36 +0000683
Kate Stoneb9c1b512016-09-06 20:57:50 +0000684 // First try to retrieve the pid via the qProcessInfo request.
685 GetCurrentProcessInfo(allow_lazy);
686 if (m_curr_pid_is_valid == eLazyBoolYes) {
687 // We really got it.
688 return m_curr_pid;
689 } else {
690 // If we don't get a response for qProcessInfo, check if $qC gives us a
691 // result.
692 // $qC only returns a real process id on older debugserver and lldb-platform
693 // stubs.
694 // The gdb remote protocol documents $qC as returning the thread id, which
695 // newer
696 // debugserver and lldb-gdbserver stubs return correctly.
Greg Clayton576d8832011-03-22 04:00:09 +0000697 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000698 if (SendPacketAndWaitForResponse("qC", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 PacketResult::Success) {
700 if (response.GetChar() == 'Q') {
701 if (response.GetChar() == 'C') {
702 m_curr_pid = response.GetHexMaxU32(false, LLDB_INVALID_PROCESS_ID);
703 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) {
704 m_curr_pid_is_valid = eLazyBoolYes;
705 return m_curr_pid;
706 }
Greg Clayton576d8832011-03-22 04:00:09 +0000707 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708 }
Greg Clayton576d8832011-03-22 04:00:09 +0000709 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710
711 // If we don't get a response for $qC, check if $qfThreadID gives us a
712 // result.
713 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) {
714 std::vector<lldb::tid_t> thread_ids;
715 bool sequence_mutex_unavailable;
716 size_t size;
717 size = GetCurrentThreadIDs(thread_ids, sequence_mutex_unavailable);
718 if (size && sequence_mutex_unavailable == false) {
719 m_curr_pid = thread_ids.front();
720 m_curr_pid_is_valid = eLazyBoolYes;
721 return m_curr_pid;
722 }
Greg Clayton576d8832011-03-22 04:00:09 +0000723 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724 }
725
726 return LLDB_INVALID_PROCESS_ID;
Greg Clayton576d8832011-03-22 04:00:09 +0000727}
728
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729bool GDBRemoteCommunicationClient::GetLaunchSuccess(std::string &error_str) {
730 error_str.clear();
731 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000732 if (SendPacketAndWaitForResponse("qLaunchSuccess", response, false) ==
733 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734 if (response.IsOKResponse())
735 return true;
736 if (response.GetChar() == 'E') {
737 // A string the describes what failed when launching...
738 error_str = response.GetStringRef().substr(1);
739 } else {
740 error_str.assign("unknown error occurred launching process");
Greg Claytonfbb76342013-11-20 21:07:01 +0000741 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000742 } else {
743 error_str.assign("timed out waiting for app to launch");
744 }
745 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000746}
747
Kate Stoneb9c1b512016-09-06 20:57:50 +0000748int GDBRemoteCommunicationClient::SendArgumentsPacket(
749 const ProcessLaunchInfo &launch_info) {
750 // Since we don't get the send argv0 separate from the executable path, we
751 // need to
752 // make sure to use the actual executable path found in the launch_info...
753 std::vector<const char *> argv;
754 FileSpec exe_file = launch_info.GetExecutableFile();
755 std::string exe_path;
756 const char *arg = NULL;
757 const Args &launch_args = launch_info.GetArguments();
758 if (exe_file)
759 exe_path = exe_file.GetPath(false);
760 else {
761 arg = launch_args.GetArgumentAtIndex(0);
762 if (arg)
763 exe_path = arg;
764 }
765 if (!exe_path.empty()) {
766 argv.push_back(exe_path.c_str());
767 for (uint32_t i = 1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL;
768 ++i) {
769 if (arg)
770 argv.push_back(arg);
Greg Clayton576d8832011-03-22 04:00:09 +0000771 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 }
773 if (!argv.empty()) {
Vince Harrone0be4252015-02-06 18:32:57 +0000774 StreamString packet;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 packet.PutChar('A');
776 for (size_t i = 0, n = argv.size(); i < n; ++i) {
777 arg = argv[i];
778 const int arg_len = strlen(arg);
779 if (i > 0)
780 packet.PutChar(',');
781 packet.Printf("%i,%i,", arg_len * 2, (int)i);
782 packet.PutBytesAsRawHex8(arg, arg_len);
783 }
784
Vince Harrone0be4252015-02-06 18:32:57 +0000785 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000786 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
787 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788 if (response.IsOKResponse())
Vince Harrone0be4252015-02-06 18:32:57 +0000789 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000790 uint8_t error = response.GetError();
791 if (error)
Johnny Chen64637202012-05-23 21:09:52 +0000792 return error;
793 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 }
795 return -1;
796}
Johnny Chen64637202012-05-23 21:09:52 +0000797
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798int GDBRemoteCommunicationClient::SendEnvironmentPacket(
799 char const *name_equal_value) {
800 if (name_equal_value && name_equal_value[0]) {
801 StreamString packet;
802 bool send_hex_encoding = false;
803 for (const char *p = name_equal_value;
804 *p != '\0' && send_hex_encoding == false; ++p) {
805 if (isprint(*p)) {
806 switch (*p) {
807 case '$':
808 case '#':
809 case '*':
810 case '}':
811 send_hex_encoding = true;
812 break;
813 default:
814 break;
Johnny Chen64637202012-05-23 21:09:52 +0000815 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 } else {
817 // We have non printable characters, lets hex encode this...
818 send_hex_encoding = true;
819 }
Johnny Chen64637202012-05-23 21:09:52 +0000820 }
821
Greg Claytonfbb76342013-11-20 21:07:01 +0000822 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 if (send_hex_encoding) {
824 if (m_supports_QEnvironmentHexEncoded) {
825 packet.PutCString("QEnvironmentHexEncoded:");
826 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value));
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000827 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
828 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000829 if (response.IsOKResponse())
830 return 0;
831 uint8_t error = response.GetError();
832 if (error)
833 return error;
834 if (response.IsUnsupportedResponse())
835 m_supports_QEnvironmentHexEncoded = false;
836 }
837 }
838
839 } else if (m_supports_QEnvironment) {
840 packet.Printf("QEnvironment:%s", name_equal_value);
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000841 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
842 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843 if (response.IsOKResponse())
844 return 0;
845 uint8_t error = response.GetError();
846 if (error)
847 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +0000848 if (response.IsUnsupportedResponse())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849 m_supports_QEnvironment = false;
850 }
Greg Claytonfbb76342013-11-20 21:07:01 +0000851 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852 }
853 return -1;
Greg Claytonfbb76342013-11-20 21:07:01 +0000854}
855
Kate Stoneb9c1b512016-09-06 20:57:50 +0000856int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) {
857 if (arch && arch[0]) {
858 StreamString packet;
859 packet.Printf("QLaunchArch:%s", arch);
860 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000861 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
862 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000863 if (response.IsOKResponse())
864 return 0;
865 uint8_t error = response.GetError();
866 if (error)
867 return error;
868 }
869 }
870 return -1;
871}
Chaoren Lind3173f32015-05-29 19:52:29 +0000872
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873int GDBRemoteCommunicationClient::SendLaunchEventDataPacket(
874 char const *data, bool *was_supported) {
875 if (data && *data != '\0') {
876 StreamString packet;
877 packet.Printf("QSetProcessEvent:%s", data);
878 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +0000879 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
880 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 if (response.IsOKResponse()) {
882 if (was_supported)
883 *was_supported = true;
884 return 0;
885 } else if (response.IsUnsupportedResponse()) {
886 if (was_supported)
887 *was_supported = false;
888 return -1;
889 } else {
890 uint8_t error = response.GetError();
891 if (was_supported)
892 *was_supported = true;
893 if (error)
894 return error;
895 }
896 }
897 }
898 return -1;
899}
900
901bool GDBRemoteCommunicationClient::GetOSVersion(uint32_t &major,
902 uint32_t &minor,
903 uint32_t &update) {
904 if (GetHostInfo()) {
905 if (m_os_version_major != UINT32_MAX) {
906 major = m_os_version_major;
907 minor = m_os_version_minor;
908 update = m_os_version_update;
909 return true;
910 }
911 }
912 return false;
913}
914
915bool GDBRemoteCommunicationClient::GetOSBuildString(std::string &s) {
916 if (GetHostInfo()) {
917 if (!m_os_build.empty()) {
918 s = m_os_build;
919 return true;
920 }
921 }
922 s.clear();
923 return false;
924}
925
926bool GDBRemoteCommunicationClient::GetOSKernelDescription(std::string &s) {
927 if (GetHostInfo()) {
928 if (!m_os_kernel.empty()) {
929 s = m_os_kernel;
930 return true;
931 }
932 }
933 s.clear();
934 return false;
935}
936
937bool GDBRemoteCommunicationClient::GetHostname(std::string &s) {
938 if (GetHostInfo()) {
939 if (!m_hostname.empty()) {
940 s = m_hostname;
941 return true;
942 }
943 }
944 s.clear();
945 return false;
946}
947
948ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() {
949 if (GetHostInfo())
950 return m_host_arch;
951 return ArchSpec();
952}
953
954const lldb_private::ArchSpec &
955GDBRemoteCommunicationClient::GetProcessArchitecture() {
956 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
957 GetCurrentProcessInfo();
958 return m_process_arch;
959}
960
961bool GDBRemoteCommunicationClient::GetGDBServerVersion() {
962 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) {
963 m_gdb_server_name.clear();
964 m_gdb_server_version = 0;
965 m_qGDBServerVersion_is_valid = eLazyBoolNo;
966
967 StringExtractorGDBRemote response;
968 if (SendPacketAndWaitForResponse("qGDBServerVersion", response, false) ==
969 PacketResult::Success) {
970 if (response.IsNormalResponse()) {
971 llvm::StringRef name, value;
972 bool success = false;
973 while (response.GetNameColonValue(name, value)) {
974 if (name.equals("name")) {
975 success = true;
976 m_gdb_server_name = value;
977 } else if (name.equals("version")) {
978 llvm::StringRef major, minor;
979 std::tie(major, minor) = value.split('.');
980 if (!major.getAsInteger(0, m_gdb_server_version))
981 success = true;
982 }
Greg Clayton576d8832011-03-22 04:00:09 +0000983 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 if (success)
985 m_qGDBServerVersion_is_valid = eLazyBoolYes;
986 }
Greg Clayton576d8832011-03-22 04:00:09 +0000987 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000988 }
989 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +0000990}
991
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992void GDBRemoteCommunicationClient::MaybeEnableCompression(
993 std::vector<std::string> supported_compressions) {
994 CompressionType avail_type = CompressionType::None;
995 std::string avail_name;
996
997#if defined(HAVE_LIBCOMPRESSION)
998 // libcompression is weak linked so test if compression_decode_buffer() is
999 // available
1000 if (compression_decode_buffer != NULL &&
1001 avail_type == CompressionType::None) {
1002 for (auto compression : supported_compressions) {
1003 if (compression == "lzfse") {
1004 avail_type = CompressionType::LZFSE;
1005 avail_name = compression;
1006 break;
1007 }
1008 }
1009 }
1010#endif
1011
1012#if defined(HAVE_LIBCOMPRESSION)
1013 // libcompression is weak linked so test if compression_decode_buffer() is
1014 // available
1015 if (compression_decode_buffer != NULL &&
1016 avail_type == CompressionType::None) {
1017 for (auto compression : supported_compressions) {
1018 if (compression == "zlib-deflate") {
1019 avail_type = CompressionType::ZlibDeflate;
1020 avail_name = compression;
1021 break;
1022 }
1023 }
1024 }
1025#endif
1026
1027#if defined(HAVE_LIBZ)
1028 if (avail_type == CompressionType::None) {
1029 for (auto compression : supported_compressions) {
1030 if (compression == "zlib-deflate") {
1031 avail_type = CompressionType::ZlibDeflate;
1032 avail_name = compression;
1033 break;
1034 }
1035 }
1036 }
1037#endif
1038
1039#if defined(HAVE_LIBCOMPRESSION)
1040 // libcompression is weak linked so test if compression_decode_buffer() is
1041 // available
1042 if (compression_decode_buffer != NULL &&
1043 avail_type == CompressionType::None) {
1044 for (auto compression : supported_compressions) {
1045 if (compression == "lz4") {
1046 avail_type = CompressionType::LZ4;
1047 avail_name = compression;
1048 break;
1049 }
1050 }
1051 }
1052#endif
1053
1054#if defined(HAVE_LIBCOMPRESSION)
1055 // libcompression is weak linked so test if compression_decode_buffer() is
1056 // available
1057 if (compression_decode_buffer != NULL &&
1058 avail_type == CompressionType::None) {
1059 for (auto compression : supported_compressions) {
1060 if (compression == "lzma") {
1061 avail_type = CompressionType::LZMA;
1062 avail_name = compression;
1063 break;
1064 }
1065 }
1066 }
1067#endif
1068
1069 if (avail_type != CompressionType::None) {
Greg Clayton576d8832011-03-22 04:00:09 +00001070 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001071 std::string packet = "QEnableCompression:type:" + avail_name + ";";
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001072 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073 PacketResult::Success)
1074 return;
1075
1076 if (response.IsOKResponse()) {
1077 m_compression_type = avail_type;
Greg Clayton576d8832011-03-22 04:00:09 +00001078 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079 }
Greg Clayton576d8832011-03-22 04:00:09 +00001080}
Greg Clayton32e0a752011-03-30 18:16:51 +00001081
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() {
1083 if (GetGDBServerVersion()) {
1084 if (!m_gdb_server_name.empty())
1085 return m_gdb_server_name.c_str();
1086 }
1087 return NULL;
1088}
1089
1090uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() {
1091 if (GetGDBServerVersion())
1092 return m_gdb_server_version;
1093 return 0;
1094}
1095
1096bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) {
1097 StringExtractorGDBRemote response;
1098 if (SendPacketAndWaitForResponse("qC", response, false) !=
1099 PacketResult::Success)
1100 return false;
1101
1102 if (!response.IsNormalResponse())
1103 return false;
1104
1105 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1106 tid = response.GetHexMaxU32(true, -1);
1107
1108 return true;
1109}
1110
1111bool GDBRemoteCommunicationClient::GetHostInfo(bool force) {
1112 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS));
1113
1114 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) {
1115 m_qHostInfo_is_valid = eLazyBoolNo;
Jim Ingham106d0282014-06-25 02:32:56 +00001116 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117 if (SendPacketAndWaitForResponse("qHostInfo", response, false) ==
1118 PacketResult::Success) {
1119 if (response.IsNormalResponse()) {
Zachary Turner54695a32016-08-29 19:58:14 +00001120 llvm::StringRef name;
1121 llvm::StringRef value;
Jason Molenda89c37492014-01-27 22:23:20 +00001122 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1123 uint32_t sub = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124 std::string arch_name;
1125 std::string os_name;
1126 std::string vendor_name;
1127 std::string triple;
1128 std::string distribution_id;
1129 uint32_t pointer_byte_size = 0;
1130 ByteOrder byte_order = eByteOrderInvalid;
1131 uint32_t num_keys_decoded = 0;
1132 while (response.GetNameColonValue(name, value)) {
1133 if (name.equals("cputype")) {
1134 // exception type in big endian hex
1135 if (!value.getAsInteger(0, cpu))
1136 ++num_keys_decoded;
1137 } else if (name.equals("cpusubtype")) {
1138 // exception count in big endian hex
1139 if (!value.getAsInteger(0, sub))
1140 ++num_keys_decoded;
1141 } else if (name.equals("arch")) {
1142 arch_name = value;
1143 ++num_keys_decoded;
1144 } else if (name.equals("triple")) {
1145 StringExtractor extractor(value);
1146 extractor.GetHexByteString(triple);
1147 ++num_keys_decoded;
1148 } else if (name.equals("distribution_id")) {
1149 StringExtractor extractor(value);
1150 extractor.GetHexByteString(distribution_id);
1151 ++num_keys_decoded;
1152 } else if (name.equals("os_build")) {
1153 StringExtractor extractor(value);
1154 extractor.GetHexByteString(m_os_build);
1155 ++num_keys_decoded;
1156 } else if (name.equals("hostname")) {
1157 StringExtractor extractor(value);
1158 extractor.GetHexByteString(m_hostname);
1159 ++num_keys_decoded;
1160 } else if (name.equals("os_kernel")) {
1161 StringExtractor extractor(value);
1162 extractor.GetHexByteString(m_os_kernel);
1163 ++num_keys_decoded;
1164 } else if (name.equals("ostype")) {
1165 os_name = value;
1166 ++num_keys_decoded;
1167 } else if (name.equals("vendor")) {
1168 vendor_name = value;
1169 ++num_keys_decoded;
1170 } else if (name.equals("endian")) {
1171 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1172 .Case("little", eByteOrderLittle)
1173 .Case("big", eByteOrderBig)
1174 .Case("pdp", eByteOrderPDP)
1175 .Default(eByteOrderInvalid);
1176 if (byte_order != eByteOrderInvalid)
1177 ++num_keys_decoded;
1178 } else if (name.equals("ptrsize")) {
1179 if (!value.getAsInteger(0, pointer_byte_size))
1180 ++num_keys_decoded;
1181 } else if (name.equals("os_version") ||
1182 name.equals(
1183 "version")) // Older debugserver binaries used the
1184 // "version" key instead of
1185 // "os_version"...
1186 {
Zachary Turner6fa7681b2016-09-17 02:00:02 +00001187 Args::StringToVersion(value, m_os_version_major, m_os_version_minor,
1188 m_os_version_update);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001189 if (m_os_version_major != UINT32_MAX)
1190 ++num_keys_decoded;
1191 } else if (name.equals("watchpoint_exceptions_received")) {
1192 m_watchpoints_trigger_after_instruction =
1193 llvm::StringSwitch<LazyBool>(value)
1194 .Case("before", eLazyBoolNo)
1195 .Case("after", eLazyBoolYes)
1196 .Default(eLazyBoolCalculate);
1197 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate)
1198 ++num_keys_decoded;
1199 } else if (name.equals("default_packet_timeout")) {
Pavel Labath3aa04912016-10-31 17:19:42 +00001200 uint32_t timeout_seconds;
1201 if (!value.getAsInteger(0, timeout_seconds)) {
Pavel Labath1eff73c2016-11-24 10:54:49 +00001202 m_default_packet_timeout = seconds(timeout_seconds);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001203 SetPacketTimeout(m_default_packet_timeout);
1204 ++num_keys_decoded;
Greg Clayton32e0a752011-03-30 18:16:51 +00001205 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206 }
Jason Molenda89c37492014-01-27 22:23:20 +00001207 }
1208
Kate Stoneb9c1b512016-09-06 20:57:50 +00001209 if (num_keys_decoded > 0)
1210 m_qHostInfo_is_valid = eLazyBoolYes;
1211
1212 if (triple.empty()) {
1213 if (arch_name.empty()) {
1214 if (cpu != LLDB_INVALID_CPUTYPE) {
1215 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1216 if (pointer_byte_size) {
1217 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1218 }
1219 if (byte_order != eByteOrderInvalid) {
1220 assert(byte_order == m_host_arch.GetByteOrder());
1221 }
1222
1223 if (!vendor_name.empty())
1224 m_host_arch.GetTriple().setVendorName(
1225 llvm::StringRef(vendor_name));
1226 if (!os_name.empty())
1227 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
Jason Molenda89c37492014-01-27 22:23:20 +00001228 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 } else {
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001230 std::string triple;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001231 triple += arch_name;
1232 if (!vendor_name.empty() || !os_name.empty()) {
1233 triple += '-';
1234 if (vendor_name.empty())
1235 triple += "unknown";
1236 else
1237 triple += vendor_name;
1238 triple += '-';
1239 if (os_name.empty())
1240 triple += "unknown";
1241 else
1242 triple += os_name;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001243 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001244 m_host_arch.SetTriple(triple.c_str());
Todd Fialac540dd02014-08-26 18:21:02 +00001245
Kate Stoneb9c1b512016-09-06 20:57:50 +00001246 llvm::Triple &host_triple = m_host_arch.GetTriple();
1247 if (host_triple.getVendor() == llvm::Triple::Apple &&
1248 host_triple.getOS() == llvm::Triple::Darwin) {
1249 switch (m_host_arch.GetMachine()) {
1250 case llvm::Triple::aarch64:
1251 case llvm::Triple::arm:
1252 case llvm::Triple::thumb:
1253 host_triple.setOS(llvm::Triple::IOS);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001254 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 default:
1256 host_triple.setOS(llvm::Triple::MacOSX);
1257 break;
1258 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001259 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001260 if (pointer_byte_size) {
1261 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1262 }
1263 if (byte_order != eByteOrderInvalid) {
1264 assert(byte_order == m_host_arch.GetByteOrder());
1265 }
1266 }
1267 } else {
1268 m_host_arch.SetTriple(triple.c_str());
1269 if (pointer_byte_size) {
1270 assert(pointer_byte_size == m_host_arch.GetAddressByteSize());
1271 }
1272 if (byte_order != eByteOrderInvalid) {
1273 assert(byte_order == m_host_arch.GetByteOrder());
1274 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001275
Kate Stoneb9c1b512016-09-06 20:57:50 +00001276 if (log)
1277 log->Printf("GDBRemoteCommunicationClient::%s parsed host "
1278 "architecture as %s, triple as %s from triple text %s",
1279 __FUNCTION__, m_host_arch.GetArchitectureName()
1280 ? m_host_arch.GetArchitectureName()
1281 : "<null-arch-name>",
1282 m_host_arch.GetTriple().getTriple().c_str(),
1283 triple.c_str());
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00001284 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001285 if (!distribution_id.empty())
1286 m_host_arch.SetDistributionId(distribution_id.c_str());
1287 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00001288 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001289 }
1290 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Claytonadc00cb2011-05-20 23:38:13 +00001291}
Greg Clayton37a0a242012-04-11 00:24:49 +00001292
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293int GDBRemoteCommunicationClient::SendAttach(
1294 lldb::pid_t pid, StringExtractorGDBRemote &response) {
1295 if (pid != LLDB_INVALID_PROCESS_ID) {
1296 char packet[64];
1297 const int packet_len =
1298 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001299 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001301 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001302 PacketResult::Success) {
1303 if (response.IsErrorResponse())
1304 return response.GetError();
1305 return 0;
1306 }
1307 }
1308 return -1;
1309}
1310
1311int GDBRemoteCommunicationClient::SendStdinNotification(const char *data,
1312 size_t data_len) {
1313 StreamString packet;
1314 packet.PutCString("I");
1315 packet.PutBytesAsRawHex8(data, data_len);
1316 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001317 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1318 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001319 return 0;
1320 }
1321 return response.GetError();
1322}
1323
1324const lldb_private::ArchSpec &
1325GDBRemoteCommunicationClient::GetHostArchitecture() {
1326 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1327 GetHostInfo();
1328 return m_host_arch;
1329}
1330
Pavel Labath1eff73c2016-11-24 10:54:49 +00001331seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001332 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1333 GetHostInfo();
1334 return m_default_packet_timeout;
1335}
1336
1337addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size,
1338 uint32_t permissions) {
1339 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1340 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1341 char packet[64];
1342 const int packet_len = ::snprintf(
1343 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size,
1344 permissions & lldb::ePermissionsReadable ? "r" : "",
1345 permissions & lldb::ePermissionsWritable ? "w" : "",
1346 permissions & lldb::ePermissionsExecutable ? "x" : "");
1347 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001348 UNUSED_IF_ASSERT_DISABLED(packet_len);
Pavel Labath83082a02016-08-18 14:33:55 +00001349 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001350 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001351 PacketResult::Success) {
1352 if (response.IsUnsupportedResponse())
1353 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1354 else if (!response.IsErrorResponse())
1355 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1356 } else {
1357 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1358 }
1359 }
1360 return LLDB_INVALID_ADDRESS;
1361}
1362
1363bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) {
1364 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) {
1365 m_supports_alloc_dealloc_memory = eLazyBoolYes;
1366 char packet[64];
1367 const int packet_len =
1368 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
1369 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001370 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001372 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001373 PacketResult::Success) {
1374 if (response.IsUnsupportedResponse())
1375 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1376 else if (response.IsOKResponse())
1377 return true;
1378 } else {
1379 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1380 }
1381 }
1382 return false;
1383}
1384
1385Error GDBRemoteCommunicationClient::Detach(bool keep_stopped) {
1386 Error error;
1387
1388 if (keep_stopped) {
1389 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) {
1390 char packet[64];
1391 const int packet_len =
1392 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
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 response.IsOKResponse()) {
1399 m_supports_detach_stay_stopped = eLazyBoolYes;
1400 } else {
1401 m_supports_detach_stay_stopped = eLazyBoolNo;
1402 }
1403 }
1404
1405 if (m_supports_detach_stay_stopped == eLazyBoolNo) {
1406 error.SetErrorString("Stays stopped not supported by this target.");
1407 return error;
1408 } else {
1409 StringExtractorGDBRemote response;
1410 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001411 SendPacketAndWaitForResponse("D1", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001412 if (packet_result != PacketResult::Success)
1413 error.SetErrorString("Sending extended disconnect packet failed.");
1414 }
1415 } else {
1416 StringExtractorGDBRemote response;
1417 PacketResult packet_result =
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001418 SendPacketAndWaitForResponse("D", response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001419 if (packet_result != PacketResult::Success)
1420 error.SetErrorString("Sending disconnect packet failed.");
1421 }
1422 return error;
1423}
1424
1425Error GDBRemoteCommunicationClient::GetMemoryRegionInfo(
1426 lldb::addr_t addr, lldb_private::MemoryRegionInfo &region_info) {
1427 Error error;
1428 region_info.Clear();
1429
1430 if (m_supports_memory_region_info != eLazyBoolNo) {
1431 m_supports_memory_region_info = eLazyBoolYes;
1432 char packet[64];
1433 const int packet_len = ::snprintf(
1434 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
1435 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001436 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001438 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001439 PacketResult::Success) {
1440 llvm::StringRef name;
1441 llvm::StringRef value;
1442 addr_t addr_value = LLDB_INVALID_ADDRESS;
1443 bool success = true;
1444 bool saw_permissions = false;
1445 while (success && response.GetNameColonValue(name, value)) {
1446 if (name.equals("start")) {
1447 if (!value.getAsInteger(16, addr_value))
1448 region_info.GetRange().SetRangeBase(addr_value);
1449 } else if (name.equals("size")) {
1450 if (!value.getAsInteger(16, addr_value))
1451 region_info.GetRange().SetByteSize(addr_value);
1452 } else if (name.equals("permissions") &&
1453 region_info.GetRange().IsValid()) {
1454 saw_permissions = true;
1455 if (region_info.GetRange().Contains(addr)) {
1456 if (value.find('r') != llvm::StringRef::npos)
1457 region_info.SetReadable(MemoryRegionInfo::eYes);
1458 else
1459 region_info.SetReadable(MemoryRegionInfo::eNo);
1460
1461 if (value.find('w') != llvm::StringRef::npos)
1462 region_info.SetWritable(MemoryRegionInfo::eYes);
1463 else
1464 region_info.SetWritable(MemoryRegionInfo::eNo);
1465
1466 if (value.find('x') != llvm::StringRef::npos)
1467 region_info.SetExecutable(MemoryRegionInfo::eYes);
1468 else
1469 region_info.SetExecutable(MemoryRegionInfo::eNo);
1470
1471 region_info.SetMapped(MemoryRegionInfo::eYes);
1472 } else {
1473 // The reported region does not contain this address -- we're
1474 // looking at an unmapped page
1475 region_info.SetReadable(MemoryRegionInfo::eNo);
1476 region_info.SetWritable(MemoryRegionInfo::eNo);
1477 region_info.SetExecutable(MemoryRegionInfo::eNo);
1478 region_info.SetMapped(MemoryRegionInfo::eNo);
1479 }
1480 } else if (name.equals("name")) {
1481 StringExtractorGDBRemote name_extractor(value);
1482 std::string name;
1483 name_extractor.GetHexByteString(name);
1484 region_info.SetName(name.c_str());
1485 } else if (name.equals("error")) {
1486 StringExtractorGDBRemote error_extractor(value);
1487 std::string error_string;
1488 // Now convert the HEX bytes into a string value
1489 error_extractor.GetHexByteString(error_string);
1490 error.SetErrorString(error_string.c_str());
1491 }
1492 }
1493
1494 // We got a valid address range back but no permissions -- which means
1495 // this is an unmapped page
1496 if (region_info.GetRange().IsValid() && saw_permissions == false) {
1497 region_info.SetReadable(MemoryRegionInfo::eNo);
1498 region_info.SetWritable(MemoryRegionInfo::eNo);
1499 region_info.SetExecutable(MemoryRegionInfo::eNo);
1500 region_info.SetMapped(MemoryRegionInfo::eNo);
1501 }
1502 } else {
1503 m_supports_memory_region_info = eLazyBoolNo;
1504 }
1505 }
1506
1507 if (m_supports_memory_region_info == eLazyBoolNo) {
1508 error.SetErrorString("qMemoryRegionInfo is not supported");
1509 }
1510 if (error.Fail())
1511 region_info.Clear();
1512 return error;
1513}
1514
1515Error GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) {
1516 Error error;
1517
1518 if (m_supports_watchpoint_support_info == eLazyBoolYes) {
1519 num = m_num_supported_hardware_watchpoints;
1520 return error;
1521 }
1522
1523 // Set num to 0 first.
1524 num = 0;
1525 if (m_supports_watchpoint_support_info != eLazyBoolNo) {
1526 char packet[64];
1527 const int packet_len =
1528 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
1529 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001530 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001531 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001532 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001533 PacketResult::Success) {
1534 m_supports_watchpoint_support_info = eLazyBoolYes;
1535 llvm::StringRef name;
1536 llvm::StringRef value;
1537 while (response.GetNameColonValue(name, value)) {
1538 if (name.equals("num")) {
1539 value.getAsInteger(0, m_num_supported_hardware_watchpoints);
1540 num = m_num_supported_hardware_watchpoints;
1541 }
1542 }
1543 } else {
1544 m_supports_watchpoint_support_info = eLazyBoolNo;
1545 }
1546 }
1547
1548 if (m_supports_watchpoint_support_info == eLazyBoolNo) {
1549 error.SetErrorString("qWatchpointSupportInfo is not supported");
1550 }
1551 return error;
1552}
1553
1554lldb_private::Error GDBRemoteCommunicationClient::GetWatchpointSupportInfo(
1555 uint32_t &num, bool &after, const ArchSpec &arch) {
1556 Error error(GetWatchpointSupportInfo(num));
1557 if (error.Success())
1558 error = GetWatchpointsTriggerAfterInstruction(after, arch);
1559 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001560}
1561
Daniel Maleae0f8f572013-08-26 23:57:52 +00001562lldb_private::Error
Kate Stoneb9c1b512016-09-06 20:57:50 +00001563GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction(
1564 bool &after, const ArchSpec &arch) {
1565 Error error;
1566 llvm::Triple::ArchType atype = arch.GetMachine();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001567
Kate Stoneb9c1b512016-09-06 20:57:50 +00001568 // we assume watchpoints will happen after running the relevant opcode
1569 // and we only want to override this behavior if we have explicitly
1570 // received a qHostInfo telling us otherwise
1571 if (m_qHostInfo_is_valid != eLazyBoolYes) {
1572 // On targets like MIPS, watchpoint exceptions are always generated
1573 // before the instruction is executed. The connected target may not
1574 // support qHostInfo or qWatchpointSupportInfo packets.
1575 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1576 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
1577 after = false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001578 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001579 after = true;
1580 } else {
1581 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
1582 // if it is not calculated before.
1583 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1584 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel ||
1585 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
1586 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1587
1588 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1589 }
1590 return error;
1591}
1592
1593int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) {
1594 if (file_spec) {
1595 std::string path{file_spec.GetPath(false)};
1596 StreamString packet;
1597 packet.PutCString("QSetSTDIN:");
1598 packet.PutCStringAsRawHex8(path.c_str());
1599
1600 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001601 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1602 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001603 if (response.IsOKResponse())
1604 return 0;
1605 uint8_t error = response.GetError();
1606 if (error)
1607 return error;
1608 }
1609 }
1610 return -1;
1611}
1612
1613int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) {
1614 if (file_spec) {
1615 std::string path{file_spec.GetPath(false)};
1616 StreamString packet;
1617 packet.PutCString("QSetSTDOUT:");
1618 packet.PutCStringAsRawHex8(path.c_str());
1619
1620 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001621 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1622 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001623 if (response.IsOKResponse())
1624 return 0;
1625 uint8_t error = response.GetError();
1626 if (error)
1627 return error;
1628 }
1629 }
1630 return -1;
1631}
1632
1633int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) {
1634 if (file_spec) {
1635 std::string path{file_spec.GetPath(false)};
1636 StreamString packet;
1637 packet.PutCString("QSetSTDERR:");
1638 packet.PutCStringAsRawHex8(path.c_str());
1639
1640 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001641 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1642 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001643 if (response.IsOKResponse())
1644 return 0;
1645 uint8_t error = response.GetError();
1646 if (error)
1647 return error;
1648 }
1649 }
1650 return -1;
1651}
1652
1653bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) {
1654 StringExtractorGDBRemote response;
1655 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) ==
1656 PacketResult::Success) {
1657 if (response.IsUnsupportedResponse())
1658 return false;
1659 if (response.IsErrorResponse())
1660 return false;
1661 std::string cwd;
1662 response.GetHexByteString(cwd);
1663 working_dir.SetFile(cwd, false, GetHostArchitecture());
1664 return !cwd.empty();
1665 }
1666 return false;
1667}
1668
1669int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) {
1670 if (working_dir) {
1671 std::string path{working_dir.GetPath(false)};
1672 StreamString packet;
1673 packet.PutCString("QSetWorkingDir:");
1674 packet.PutCStringAsRawHex8(path.c_str());
1675
1676 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001677 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
1678 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001679 if (response.IsOKResponse())
1680 return 0;
1681 uint8_t error = response.GetError();
1682 if (error)
1683 return error;
1684 }
1685 }
1686 return -1;
1687}
1688
1689int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) {
1690 char packet[32];
1691 const int packet_len =
1692 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0);
1693 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001694 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001695 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001696 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001697 PacketResult::Success) {
1698 if (response.IsOKResponse())
1699 return 0;
1700 uint8_t error = response.GetError();
1701 if (error)
1702 return error;
1703 }
1704 return -1;
1705}
1706
1707int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) {
1708 char packet[32];
1709 const int packet_len = ::snprintf(packet, sizeof(packet),
1710 "QSetDetachOnError:%i", enable ? 1 : 0);
1711 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001712 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001713 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001714 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001715 PacketResult::Success) {
1716 if (response.IsOKResponse())
1717 return 0;
1718 uint8_t error = response.GetError();
1719 if (error)
1720 return error;
1721 }
1722 return -1;
1723}
1724
1725bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse(
1726 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) {
1727 if (response.IsNormalResponse()) {
1728 llvm::StringRef name;
1729 llvm::StringRef value;
1730 StringExtractor extractor;
1731
1732 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1733 uint32_t sub = 0;
1734 std::string vendor;
1735 std::string os_type;
1736
1737 while (response.GetNameColonValue(name, value)) {
1738 if (name.equals("pid")) {
1739 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1740 value.getAsInteger(0, pid);
1741 process_info.SetProcessID(pid);
1742 } else if (name.equals("ppid")) {
1743 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1744 value.getAsInteger(0, pid);
1745 process_info.SetParentProcessID(pid);
1746 } else if (name.equals("uid")) {
1747 uint32_t uid = UINT32_MAX;
1748 value.getAsInteger(0, uid);
1749 process_info.SetUserID(uid);
1750 } else if (name.equals("euid")) {
1751 uint32_t uid = UINT32_MAX;
1752 value.getAsInteger(0, uid);
1753 process_info.SetEffectiveGroupID(uid);
1754 } else if (name.equals("gid")) {
1755 uint32_t gid = UINT32_MAX;
1756 value.getAsInteger(0, gid);
1757 process_info.SetGroupID(gid);
1758 } else if (name.equals("egid")) {
1759 uint32_t gid = UINT32_MAX;
1760 value.getAsInteger(0, gid);
1761 process_info.SetEffectiveGroupID(gid);
1762 } else if (name.equals("triple")) {
1763 StringExtractor extractor(value);
1764 std::string triple;
1765 extractor.GetHexByteString(triple);
1766 process_info.GetArchitecture().SetTriple(triple.c_str());
1767 } else if (name.equals("name")) {
1768 StringExtractor extractor(value);
1769 // The process name from ASCII hex bytes since we can't
1770 // control the characters in a process name
1771 std::string name;
1772 extractor.GetHexByteString(name);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00001773 process_info.GetExecutableFile().SetFile(name, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001774 } else if (name.equals("cputype")) {
1775 value.getAsInteger(0, cpu);
1776 } else if (name.equals("cpusubtype")) {
1777 value.getAsInteger(0, sub);
1778 } else if (name.equals("vendor")) {
1779 vendor = value;
1780 } else if (name.equals("ostype")) {
1781 os_type = value;
1782 }
1783 }
1784
1785 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) {
1786 if (vendor == "apple") {
1787 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu,
1788 sub);
1789 process_info.GetArchitecture().GetTriple().setVendorName(
1790 llvm::StringRef(vendor));
1791 process_info.GetArchitecture().GetTriple().setOSName(
1792 llvm::StringRef(os_type));
1793 }
1794 }
1795
1796 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1797 return true;
1798 }
1799 return false;
1800}
1801
1802bool GDBRemoteCommunicationClient::GetProcessInfo(
1803 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
1804 process_info.Clear();
1805
1806 if (m_supports_qProcessInfoPID) {
1807 char packet[32];
1808 const int packet_len =
1809 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid);
1810 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001811 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001812 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00001813 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00001814 PacketResult::Success) {
1815 return DecodeProcessInfoResponse(response, process_info);
1816 } else {
1817 m_supports_qProcessInfoPID = false;
1818 return false;
1819 }
1820 }
1821 return false;
1822}
1823
1824bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) {
1825 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
1826 GDBR_LOG_PACKETS));
1827
1828 if (allow_lazy) {
1829 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1830 return true;
1831 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1832 return false;
1833 }
1834
1835 GetHostInfo();
1836
1837 StringExtractorGDBRemote response;
1838 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) ==
1839 PacketResult::Success) {
1840 if (response.IsNormalResponse()) {
1841 llvm::StringRef name;
1842 llvm::StringRef value;
1843 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1844 uint32_t sub = 0;
1845 std::string arch_name;
1846 std::string os_name;
1847 std::string vendor_name;
1848 std::string triple;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001849 std::string elf_abi;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850 uint32_t pointer_byte_size = 0;
1851 StringExtractor extractor;
1852 ByteOrder byte_order = eByteOrderInvalid;
1853 uint32_t num_keys_decoded = 0;
1854 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1855 while (response.GetNameColonValue(name, value)) {
1856 if (name.equals("cputype")) {
1857 if (!value.getAsInteger(16, cpu))
1858 ++num_keys_decoded;
1859 } else if (name.equals("cpusubtype")) {
1860 if (!value.getAsInteger(16, sub))
1861 ++num_keys_decoded;
1862 } else if (name.equals("triple")) {
1863 StringExtractor extractor(value);
1864 extractor.GetHexByteString(triple);
1865 ++num_keys_decoded;
1866 } else if (name.equals("ostype")) {
1867 os_name = value;
1868 ++num_keys_decoded;
1869 } else if (name.equals("vendor")) {
1870 vendor_name = value;
1871 ++num_keys_decoded;
1872 } else if (name.equals("endian")) {
1873 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value)
1874 .Case("little", eByteOrderLittle)
1875 .Case("big", eByteOrderBig)
1876 .Case("pdp", eByteOrderPDP)
1877 .Default(eByteOrderInvalid);
1878 if (byte_order != eByteOrderInvalid)
1879 ++num_keys_decoded;
1880 } else if (name.equals("ptrsize")) {
1881 if (!value.getAsInteger(16, pointer_byte_size))
1882 ++num_keys_decoded;
1883 } else if (name.equals("pid")) {
1884 if (!value.getAsInteger(16, pid))
1885 ++num_keys_decoded;
Nitesh Jain8999edf2016-10-12 10:21:09 +00001886 } else if (name.equals("elf_abi")) {
1887 elf_abi = value;
1888 ++num_keys_decoded;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001889 }
1890 }
1891 if (num_keys_decoded > 0)
1892 m_qProcessInfo_is_valid = eLazyBoolYes;
1893 if (pid != LLDB_INVALID_PROCESS_ID) {
1894 m_curr_pid_is_valid = eLazyBoolYes;
1895 m_curr_pid = pid;
1896 }
1897
1898 // Set the ArchSpec from the triple if we have it.
1899 if (!triple.empty()) {
1900 m_process_arch.SetTriple(triple.c_str());
Nitesh Jain8999edf2016-10-12 10:21:09 +00001901 m_process_arch.SetFlags(elf_abi);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001902 if (pointer_byte_size) {
1903 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1904 }
1905 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() &&
1906 !vendor_name.empty()) {
1907 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
1908
1909 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
1910 switch (triple.getObjectFormat()) {
1911 case llvm::Triple::MachO:
1912 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub);
1913 break;
1914 case llvm::Triple::ELF:
1915 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub);
1916 break;
1917 case llvm::Triple::COFF:
1918 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub);
1919 break;
1920 case llvm::Triple::UnknownObjectFormat:
1921 if (log)
1922 log->Printf("error: failed to determine target architecture");
1923 return false;
1924 }
1925
1926 if (pointer_byte_size) {
1927 assert(pointer_byte_size == m_process_arch.GetAddressByteSize());
1928 }
1929 if (byte_order != eByteOrderInvalid) {
1930 assert(byte_order == m_process_arch.GetByteOrder());
1931 }
1932 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1933 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1934 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name));
1935 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name));
1936 }
1937 return true;
1938 }
1939 } else {
1940 m_qProcessInfo_is_valid = eLazyBoolNo;
1941 }
1942
1943 return false;
1944}
1945
1946uint32_t GDBRemoteCommunicationClient::FindProcesses(
1947 const ProcessInstanceInfoMatch &match_info,
1948 ProcessInstanceInfoList &process_infos) {
1949 process_infos.Clear();
1950
1951 if (m_supports_qfProcessInfo) {
1952 StreamString packet;
1953 packet.PutCString("qfProcessInfo");
1954 if (!match_info.MatchAllProcesses()) {
1955 packet.PutChar(':');
1956 const char *name = match_info.GetProcessInfo().GetName();
1957 bool has_name_match = false;
1958 if (name && name[0]) {
1959 has_name_match = true;
1960 NameMatchType name_match_type = match_info.GetNameMatchType();
1961 switch (name_match_type) {
1962 case eNameMatchIgnore:
1963 has_name_match = false;
1964 break;
1965
1966 case eNameMatchEquals:
1967 packet.PutCString("name_match:equals;");
1968 break;
1969
1970 case eNameMatchContains:
1971 packet.PutCString("name_match:contains;");
1972 break;
1973
1974 case eNameMatchStartsWith:
1975 packet.PutCString("name_match:starts_with;");
1976 break;
1977
1978 case eNameMatchEndsWith:
1979 packet.PutCString("name_match:ends_with;");
1980 break;
1981
1982 case eNameMatchRegularExpression:
1983 packet.PutCString("name_match:regex;");
1984 break;
1985 }
1986 if (has_name_match) {
1987 packet.PutCString("name:");
1988 packet.PutBytesAsRawHex8(name, ::strlen(name));
1989 packet.PutChar(';');
1990 }
1991 }
1992
1993 if (match_info.GetProcessInfo().ProcessIDIsValid())
1994 packet.Printf("pid:%" PRIu64 ";",
1995 match_info.GetProcessInfo().GetProcessID());
1996 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
1997 packet.Printf("parent_pid:%" PRIu64 ";",
1998 match_info.GetProcessInfo().GetParentProcessID());
1999 if (match_info.GetProcessInfo().UserIDIsValid())
2000 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID());
2001 if (match_info.GetProcessInfo().GroupIDIsValid())
2002 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID());
2003 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2004 packet.Printf("euid:%u;",
2005 match_info.GetProcessInfo().GetEffectiveUserID());
2006 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2007 packet.Printf("egid:%u;",
2008 match_info.GetProcessInfo().GetEffectiveGroupID());
2009 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2010 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0);
2011 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) {
2012 const ArchSpec &match_arch =
2013 match_info.GetProcessInfo().GetArchitecture();
2014 const llvm::Triple &triple = match_arch.GetTriple();
2015 packet.PutCString("triple:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002016 packet.PutCString(triple.getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002017 packet.PutChar(';');
2018 }
2019 }
2020 StringExtractorGDBRemote response;
2021 // Increase timeout as the first qfProcessInfo packet takes a long time
2022 // on Android. The value of 1min was arrived at empirically.
Pavel Labath1eff73c2016-11-24 10:54:49 +00002023 ScopedTimeout timeout(*this, minutes(1));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002024 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2025 PacketResult::Success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002026 do {
2027 ProcessInstanceInfo process_info;
2028 if (!DecodeProcessInfoResponse(response, process_info))
2029 break;
2030 process_infos.Append(process_info);
2031 response.GetStringRef().clear();
2032 response.SetFilePos(0);
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002033 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) ==
2034 PacketResult::Success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002035 } else {
2036 m_supports_qfProcessInfo = false;
2037 return 0;
2038 }
2039 }
2040 return process_infos.GetSize();
2041}
2042
2043bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid,
2044 std::string &name) {
2045 if (m_supports_qUserName) {
2046 char packet[32];
2047 const int packet_len =
2048 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid);
2049 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002050 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002051 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002052 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002053 PacketResult::Success) {
2054 if (response.IsNormalResponse()) {
2055 // Make sure we parsed the right number of characters. The response is
2056 // the hex encoded user name and should make up the entire packet.
2057 // If there are any non-hex ASCII bytes, the length won't match below..
2058 if (response.GetHexByteString(name) * 2 ==
2059 response.GetStringRef().size())
2060 return true;
2061 }
2062 } else {
2063 m_supports_qUserName = false;
2064 return false;
2065 }
2066 }
2067 return false;
2068}
2069
2070bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid,
2071 std::string &name) {
2072 if (m_supports_qGroupName) {
2073 char packet[32];
2074 const int packet_len =
2075 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid);
2076 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002077 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002078 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002079 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002080 PacketResult::Success) {
2081 if (response.IsNormalResponse()) {
2082 // Make sure we parsed the right number of characters. The response is
2083 // the hex encoded group name and should make up the entire packet.
2084 // If there are any non-hex ASCII bytes, the length won't match below..
2085 if (response.GetHexByteString(name) * 2 ==
2086 response.GetStringRef().size())
2087 return true;
2088 }
2089 } else {
2090 m_supports_qGroupName = false;
2091 return false;
2092 }
2093 }
2094 return false;
2095}
2096
2097bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) {
2098 // Form non-stop packet request
2099 char packet[32];
2100 const int packet_len =
2101 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2102 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002103 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002104
2105 StringExtractorGDBRemote response;
2106 // Send to target
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002107 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002108 PacketResult::Success)
2109 if (response.IsOKResponse())
2110 return true;
2111
2112 // Failed or not supported
2113 return false;
2114}
2115
2116static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size,
2117 uint32_t recv_size) {
2118 packet.Clear();
2119 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2120 uint32_t bytes_left = send_size;
2121 while (bytes_left > 0) {
2122 if (bytes_left >= 26) {
2123 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2124 bytes_left -= 26;
2125 } else {
2126 packet.Printf("%*.*s;", bytes_left, bytes_left,
2127 "abcdefghijklmnopqrstuvwxyz");
2128 bytes_left = 0;
2129 }
2130 }
2131}
2132
Pavel Labath1eff73c2016-11-24 10:54:49 +00002133duration<float>
2134calculate_standard_deviation(const std::vector<duration<float>> &v) {
2135 using Dur = duration<float>;
Pavel Labath3aa04912016-10-31 17:19:42 +00002136 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur());
2137 Dur mean = sum / v.size();
2138 float accum = 0;
2139 for (auto d : v) {
2140 float delta = (d - mean).count();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002141 accum += delta * delta;
Pavel Labath3aa04912016-10-31 17:19:42 +00002142 };
Kate Stoneb9c1b512016-09-06 20:57:50 +00002143
Pavel Labath3aa04912016-10-31 17:19:42 +00002144 return Dur(sqrtf(accum / (v.size() - 1)));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002145}
2146
2147void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets,
2148 uint32_t max_send,
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002149 uint32_t max_recv,
2150 uint64_t recv_amount,
2151 bool json, Stream &strm) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002152 uint32_t i;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002153 if (SendSpeedTestPacket(0, 0)) {
2154 StreamString packet;
2155 if (json)
2156 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n "
2157 "\"results\" : [",
2158 num_packets);
2159 else
2160 strm.Printf("Testing sending %u packets of various sizes:\n",
2161 num_packets);
2162 strm.Flush();
2163
2164 uint32_t result_idx = 0;
2165 uint32_t send_size;
Pavel Labath3aa04912016-10-31 17:19:42 +00002166 std::vector<duration<float>> packet_times;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002167
2168 for (send_size = 0; send_size <= max_send;
2169 send_size ? send_size *= 2 : send_size = 4) {
2170 for (uint32_t recv_size = 0; recv_size <= max_recv;
2171 recv_size ? recv_size *= 2 : recv_size = 4) {
2172 MakeSpeedTestPacket(packet, send_size, recv_size);
2173
2174 packet_times.clear();
2175 // Test how long it takes to send 'num_packets' packets
Pavel Labath3aa04912016-10-31 17:19:42 +00002176 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002177 for (i = 0; i < num_packets; ++i) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002178 const auto packet_start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002179 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002180 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Pavel Labath3aa04912016-10-31 17:19:42 +00002181 const auto packet_end_time = steady_clock::now();
2182 packet_times.push_back(packet_end_time - packet_start_time);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002184 const auto end_time = steady_clock::now();
2185 const auto total_time = end_time - start_time;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002186
2187 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002188 ((float)num_packets) / duration<float>(total_time).count();
2189 auto average_per_packet = total_time / num_packets;
2190 const duration<float> standard_deviation =
2191 calculate_standard_deviation(packet_times);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002192 if (json) {
2193 strm.Printf("%s\n {\"send_size\" : %6" PRIu32
2194 ", \"recv_size\" : %6" PRIu32
2195 ", \"total_time_nsec\" : %12" PRIu64
2196 ", \"standard_deviation_nsec\" : %9" PRIu64 " }",
2197 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath3aa04912016-10-31 17:19:42 +00002198 duration_cast<nanoseconds>(total_time).count(),
2199 duration_cast<nanoseconds>(standard_deviation).count());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002200 ++result_idx;
2201 } else {
2202 strm.Printf(
Pavel Labath3aa04912016-10-31 17:19:42 +00002203 "qSpeedTest(send=%-7u, recv=%-7u) in %.9f"
Kate Stoneb9c1b512016-09-06 20:57:50 +00002204 " sec for %9.2f packets/sec (%10.6f ms per packet) with standard "
2205 "deviation of %10.6f ms\n",
Pavel Labath3aa04912016-10-31 17:19:42 +00002206 send_size, recv_size, duration<float>(total_time).count(),
2207 packets_per_second,
2208 duration<float, std::milli>(average_per_packet).count(),
2209 duration<float, std::milli>(standard_deviation).count());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002210 }
2211 strm.Flush();
2212 }
2213 }
2214
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002215 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002216 if (json)
2217 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" "
2218 ": %" PRIu64 ",\n \"results\" : [",
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002219 recv_amount);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002220 else
2221 strm.Printf("Testing receiving %2.1fMB of data using varying receive "
2222 "packet sizes:\n",
2223 k_recv_amount_mb);
2224 strm.Flush();
2225 send_size = 0;
2226 result_idx = 0;
2227 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) {
2228 MakeSpeedTestPacket(packet, send_size, recv_size);
2229
2230 // If we have a receive size, test how long it takes to receive 4MB of
2231 // data
2232 if (recv_size > 0) {
Pavel Labath3aa04912016-10-31 17:19:42 +00002233 const auto start_time = steady_clock::now();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234 uint32_t bytes_read = 0;
2235 uint32_t packet_count = 0;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002236 while (bytes_read < recv_amount) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002237 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002238 SendPacketAndWaitForResponse(packet.GetString(), response, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002239 bytes_read += recv_size;
2240 ++packet_count;
2241 }
Pavel Labath3aa04912016-10-31 17:19:42 +00002242 const auto end_time = steady_clock::now();
2243 const auto total_time = end_time - start_time;
Pavel Labath2fd9a1e2016-11-04 11:49:06 +00002244 float mb_second = ((float)recv_amount) /
Pavel Labath3aa04912016-10-31 17:19:42 +00002245 duration<float>(total_time).count() /
Kate Stoneb9c1b512016-09-06 20:57:50 +00002246 (1024.0 * 1024.0);
2247 float packets_per_second =
Pavel Labath3aa04912016-10-31 17:19:42 +00002248 ((float)packet_count) / duration<float>(total_time).count();
2249 const auto average_per_packet = total_time / packet_count;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002250
2251 if (json) {
2252 strm.Printf("%s\n {\"send_size\" : %6" PRIu32
2253 ", \"recv_size\" : %6" PRIu32
2254 ", \"total_time_nsec\" : %12" PRIu64 " }",
2255 result_idx > 0 ? "," : "", send_size, recv_size,
Pavel Labath3aa04912016-10-31 17:19:42 +00002256 duration_cast<nanoseconds>(total_time).count());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257 ++result_idx;
2258 } else {
2259 strm.Printf("qSpeedTest(send=%-7u, recv=%-7u) %6u packets needed to "
Pavel Labath3aa04912016-10-31 17:19:42 +00002260 "receive %2.1fMB in %.9f"
Kate Stoneb9c1b512016-09-06 20:57:50 +00002261 " sec for %f MB/sec for %9.2f packets/sec (%10.6f ms per "
2262 "packet)\n",
2263 send_size, recv_size, packet_count, k_recv_amount_mb,
Pavel Labath3aa04912016-10-31 17:19:42 +00002264 duration<float>(total_time).count(), mb_second,
2265 packets_per_second,
2266 duration<float, std::milli>(average_per_packet).count());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002267 }
2268 strm.Flush();
2269 }
2270 }
2271 if (json)
2272 strm.Printf("\n ]\n }\n}\n");
2273 else
2274 strm.EOL();
2275 }
2276}
2277
2278bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size,
2279 uint32_t recv_size) {
2280 StreamString packet;
2281 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size);
2282 uint32_t bytes_left = send_size;
2283 while (bytes_left > 0) {
2284 if (bytes_left >= 26) {
2285 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2286 bytes_left -= 26;
2287 } else {
2288 packet.Printf("%*.*s;", bytes_left, bytes_left,
2289 "abcdefghijklmnopqrstuvwxyz");
2290 bytes_left = 0;
2291 }
2292 }
2293
2294 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002295 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
2296 PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002297}
2298
2299bool GDBRemoteCommunicationClient::LaunchGDBServer(
2300 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port,
2301 std::string &socket_name) {
2302 pid = LLDB_INVALID_PROCESS_ID;
2303 port = 0;
2304 socket_name.clear();
2305
2306 StringExtractorGDBRemote response;
2307 StreamString stream;
2308 stream.PutCString("qLaunchGDBServer;");
2309 std::string hostname;
2310 if (remote_accept_hostname && remote_accept_hostname[0])
2311 hostname = remote_accept_hostname;
2312 else {
2313 if (HostInfo::GetHostname(hostname)) {
2314 // Make the GDB server we launch only accept connections from this host
2315 stream.Printf("host:%s;", hostname.c_str());
2316 } else {
2317 // Make the GDB server we launch accept connections from any host since we
2318 // can't figure out the hostname
2319 stream.Printf("host:*;");
2320 }
2321 }
2322 // give the process a few seconds to startup
Pavel Labath1eff73c2016-11-24 10:54:49 +00002323 ScopedTimeout timeout(*this, seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002324
2325 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
2326 PacketResult::Success) {
2327 llvm::StringRef name;
2328 llvm::StringRef value;
2329 while (response.GetNameColonValue(name, value)) {
2330 if (name.equals("port"))
2331 value.getAsInteger(0, port);
2332 else if (name.equals("pid"))
2333 value.getAsInteger(0, pid);
2334 else if (name.compare("socket_name") == 0) {
2335 StringExtractor extractor(value);
2336 extractor.GetHexByteString(socket_name);
2337 }
2338 }
2339 return true;
2340 }
2341 return false;
2342}
2343
2344size_t GDBRemoteCommunicationClient::QueryGDBServer(
2345 std::vector<std::pair<uint16_t, std::string>> &connection_urls) {
2346 connection_urls.clear();
2347
2348 StringExtractorGDBRemote response;
2349 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) !=
2350 PacketResult::Success)
2351 return 0;
2352
2353 StructuredData::ObjectSP data =
2354 StructuredData::ParseJSON(response.GetStringRef());
2355 if (!data)
2356 return 0;
2357
2358 StructuredData::Array *array = data->GetAsArray();
2359 if (!array)
2360 return 0;
2361
2362 for (size_t i = 0, count = array->GetSize(); i < count; ++i) {
2363 StructuredData::Dictionary *element = nullptr;
2364 if (!array->GetItemAtIndexAsDictionary(i, element))
2365 continue;
2366
2367 uint16_t port = 0;
2368 if (StructuredData::ObjectSP port_osp =
2369 element->GetValueForKey(llvm::StringRef("port")))
2370 port = port_osp->GetIntegerValue(0);
2371
2372 std::string socket_name;
2373 if (StructuredData::ObjectSP socket_name_osp =
2374 element->GetValueForKey(llvm::StringRef("socket_name")))
2375 socket_name = socket_name_osp->GetStringValue();
2376
2377 if (port != 0 || !socket_name.empty())
2378 connection_urls.emplace_back(port, socket_name);
2379 }
2380 return connection_urls.size();
2381}
2382
2383bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) {
2384 StreamString stream;
2385 stream.Printf("qKillSpawnedProcess:%" PRId64, pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002386
2387 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002388 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002389 PacketResult::Success) {
2390 if (response.IsOKResponse())
2391 return true;
2392 }
2393 return false;
2394}
2395
2396bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) {
2397 if (m_curr_tid == tid)
2398 return true;
2399
2400 char packet[32];
2401 int packet_len;
2402 if (tid == UINT64_MAX)
2403 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1");
2404 else
2405 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid);
2406 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002407 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002408 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002409 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410 PacketResult::Success) {
2411 if (response.IsOKResponse()) {
2412 m_curr_tid = tid;
2413 return true;
2414 }
2415
2416 /*
2417 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2418 * Hg packet.
2419 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2420 * which can
2421 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2422 */
2423 if (response.IsUnsupportedResponse() && IsConnected()) {
2424 m_curr_tid = 1;
2425 return true;
2426 }
2427 }
2428 return false;
2429}
2430
2431bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) {
2432 if (m_curr_tid_run == tid)
2433 return true;
2434
2435 char packet[32];
2436 int packet_len;
2437 if (tid == UINT64_MAX)
2438 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1");
2439 else
2440 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid);
2441
2442 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002443 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002444 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002445 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002446 PacketResult::Success) {
2447 if (response.IsOKResponse()) {
2448 m_curr_tid_run = tid;
2449 return true;
2450 }
2451
2452 /*
2453 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2454 * Hc packet.
2455 * The reply from '?' packet could be as simple as 'S05'. There is no packet
2456 * which can
2457 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2458 */
2459 if (response.IsUnsupportedResponse() && IsConnected()) {
2460 m_curr_tid_run = 1;
2461 return true;
2462 }
2463 }
2464 return false;
2465}
2466
2467bool GDBRemoteCommunicationClient::GetStopReply(
2468 StringExtractorGDBRemote &response) {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002469 if (SendPacketAndWaitForResponse("?", response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002470 PacketResult::Success)
2471 return response.IsNormalResponse();
2472 return false;
2473}
2474
2475bool GDBRemoteCommunicationClient::GetThreadStopInfo(
2476 lldb::tid_t tid, StringExtractorGDBRemote &response) {
2477 if (m_supports_qThreadStopInfo) {
2478 char packet[256];
2479 int packet_len =
2480 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
2481 assert(packet_len < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002482 UNUSED_IF_ASSERT_DISABLED(packet_len);
2483 if (SendPacketAndWaitForResponse(packet, response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002484 PacketResult::Success) {
2485 if (response.IsUnsupportedResponse())
2486 m_supports_qThreadStopInfo = false;
2487 else if (response.IsNormalResponse())
2488 return true;
2489 else
2490 return false;
2491 } else {
2492 m_supports_qThreadStopInfo = false;
2493 }
2494 }
2495 return false;
2496}
2497
2498uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket(
2499 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) {
2500 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2501 if (log)
2502 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2503 __FUNCTION__, insert ? "add" : "remove", addr);
2504
2505 // Check if the stub is known not to support this breakpoint type
2506 if (!SupportsGDBStoppointPacket(type))
2507 return UINT8_MAX;
2508 // Construct the breakpoint packet
2509 char packet[64];
2510 const int packet_len =
2511 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x",
2512 insert ? 'Z' : 'z', type, addr, length);
2513 // Check we haven't overwritten the end of the packet buffer
2514 assert(packet_len + 1 < (int)sizeof(packet));
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002515 UNUSED_IF_ASSERT_DISABLED(packet_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002516 StringExtractorGDBRemote response;
2517 // Make sure the response is either "OK", "EXX" where XX are two hex digits,
2518 // or "" (unsupported)
2519 response.SetResponseValidatorToOKErrorNotSupported();
2520 // Try to send the breakpoint packet, and check that it was correctly sent
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002521 if (SendPacketAndWaitForResponse(packet, response, true) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002522 PacketResult::Success) {
2523 // Receive and OK packet when the breakpoint successfully placed
2524 if (response.IsOKResponse())
2525 return 0;
2526
2527 // Error while setting breakpoint, send back specific error
2528 if (response.IsErrorResponse())
2529 return response.GetError();
2530
2531 // Empty packet informs us that breakpoint is not supported
2532 if (response.IsUnsupportedResponse()) {
2533 // Disable this breakpoint type since it is unsupported
2534 switch (type) {
2535 case eBreakpointSoftware:
2536 m_supports_z0 = false;
2537 break;
2538 case eBreakpointHardware:
2539 m_supports_z1 = false;
2540 break;
2541 case eWatchpointWrite:
2542 m_supports_z2 = false;
2543 break;
2544 case eWatchpointRead:
2545 m_supports_z3 = false;
2546 break;
2547 case eWatchpointReadWrite:
2548 m_supports_z4 = false;
2549 break;
2550 case eStoppointInvalid:
2551 return UINT8_MAX;
2552 }
2553 }
2554 }
2555 // Signal generic failure
2556 return UINT8_MAX;
2557}
2558
2559size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs(
2560 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) {
2561 thread_ids.clear();
2562
2563 Lock lock(*this, false);
2564 if (lock) {
2565 sequence_mutex_unavailable = false;
2566 StringExtractorGDBRemote response;
2567
2568 PacketResult packet_result;
2569 for (packet_result =
2570 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
2571 packet_result == PacketResult::Success && response.IsNormalResponse();
2572 packet_result =
2573 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) {
2574 char ch = response.GetChar();
2575 if (ch == 'l')
2576 break;
2577 if (ch == 'm') {
2578 do {
2579 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
2580
2581 if (tid != LLDB_INVALID_THREAD_ID) {
2582 thread_ids.push_back(tid);
2583 }
2584 ch = response.GetChar(); // Skip the command separator
2585 } while (ch == ','); // Make sure we got a comma separator
2586 }
2587 }
2588
2589 /*
2590 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2591 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet
2592 * could
2593 * be as simple as 'S05'. There is no packet which can give us pid and/or
2594 * tid.
2595 * Assume pid=tid=1 in such cases.
2596 */
2597 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 &&
2598 IsConnected()) {
2599 thread_ids.push_back(1);
2600 }
2601 } else {
David Blaikiea322f362017-01-06 00:38:06 +00002602#if !defined(LLDB_CONFIGURATION_DEBUG)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002603 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS |
2604 GDBR_LOG_PACKETS));
2605 if (log)
2606 log->Printf("error: failed to get packet sequence mutex, not sending "
2607 "packet 'qfThreadInfo'");
2608#endif
2609 sequence_mutex_unavailable = true;
2610 }
2611 return thread_ids.size();
2612}
2613
2614lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() {
2615 StringExtractorGDBRemote response;
2616 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) !=
2617 PacketResult::Success ||
2618 !response.IsNormalResponse())
2619 return LLDB_INVALID_ADDRESS;
2620 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2621}
2622
2623lldb_private::Error GDBRemoteCommunicationClient::RunShellCommand(
2624 const char *command, // Shouldn't be NULL
2625 const FileSpec &
2626 working_dir, // Pass empty FileSpec to use the current working directory
2627 int *status_ptr, // Pass NULL if you don't want the process exit status
2628 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
2629 // process to exit
2630 std::string
2631 *command_output, // Pass NULL if you don't want the command output
2632 uint32_t
2633 timeout_sec) // Timeout in seconds to wait for shell program to finish
2634{
2635 lldb_private::StreamString stream;
2636 stream.PutCString("qPlatform_shell:");
2637 stream.PutBytesAsRawHex8(command, strlen(command));
2638 stream.PutChar(',');
2639 stream.PutHex32(timeout_sec);
2640 if (working_dir) {
2641 std::string path{working_dir.GetPath(false)};
2642 stream.PutChar(',');
2643 stream.PutCStringAsRawHex8(path.c_str());
2644 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002645 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002646 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002647 PacketResult::Success) {
2648 if (response.GetChar() != 'F')
2649 return Error("malformed reply");
2650 if (response.GetChar() != ',')
2651 return Error("malformed reply");
2652 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2653 if (exitcode == UINT32_MAX)
2654 return Error("unable to run remote process");
2655 else if (status_ptr)
2656 *status_ptr = exitcode;
2657 if (response.GetChar() != ',')
2658 return Error("malformed reply");
2659 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2660 if (signo_ptr)
2661 *signo_ptr = signo;
2662 if (response.GetChar() != ',')
2663 return Error("malformed reply");
2664 std::string output;
2665 response.GetEscapedBinaryData(output);
2666 if (command_output)
2667 command_output->assign(output);
Mehdi Aminic1edf562016-11-11 04:29:25 +00002668 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002669 }
2670 return Error("unable to send packet");
2671}
2672
2673Error GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
2674 uint32_t file_permissions) {
2675 std::string path{file_spec.GetPath(false)};
2676 lldb_private::StreamString stream;
2677 stream.PutCString("qPlatform_mkdir:");
2678 stream.PutHex32(file_permissions);
2679 stream.PutChar(',');
2680 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002681 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002682 StringExtractorGDBRemote response;
2683
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002684 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002685 PacketResult::Success)
Zachary Turnerc1564272016-11-16 21:15:24 +00002686 return Error("failed to send '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002687
2688 if (response.GetChar() != 'F')
Zachary Turnerc1564272016-11-16 21:15:24 +00002689 return Error("invalid response to '%s' packet", packet.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002690
2691 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2692}
2693
2694Error GDBRemoteCommunicationClient::SetFilePermissions(
2695 const FileSpec &file_spec, uint32_t file_permissions) {
2696 std::string path{file_spec.GetPath(false)};
2697 lldb_private::StreamString stream;
2698 stream.PutCString("qPlatform_chmod:");
2699 stream.PutHex32(file_permissions);
2700 stream.PutChar(',');
2701 stream.PutCStringAsRawHex8(path.c_str());
Zachary Turnerc1564272016-11-16 21:15:24 +00002702 llvm::StringRef packet = stream.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002703 StringExtractorGDBRemote response;
2704
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002705 if (SendPacketAndWaitForResponse(packet, response, false) !=
Kate Stoneb9c1b512016-09-06 20:57:50 +00002706 PacketResult::Success)
Zachary Turnerc1564272016-11-16 21:15:24 +00002707 return Error("failed to send '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002708
2709 if (response.GetChar() != 'F')
Zachary Turnerc1564272016-11-16 21:15:24 +00002710 return Error("invalid response to '%s' packet", stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002711
2712 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
2713}
2714
2715static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response,
2716 uint64_t fail_result, Error &error) {
2717 response.SetFilePos(0);
2718 if (response.GetChar() != 'F')
2719 return fail_result;
2720 int32_t result = response.GetS32(-2);
2721 if (result == -2)
2722 return fail_result;
2723 if (response.GetChar() == ',') {
2724 int result_errno = response.GetS32(-2);
2725 if (result_errno != -2)
2726 error.SetError(result_errno, eErrorTypePOSIX);
2727 else
2728 error.SetError(-1, eErrorTypeGeneric);
2729 } else
2730 error.Clear();
2731 return result;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002732}
2733lldb::user_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00002734GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec,
2735 uint32_t flags, mode_t mode,
2736 Error &error) {
2737 std::string path(file_spec.GetPath(false));
2738 lldb_private::StreamString stream;
2739 stream.PutCString("vFile:open:");
2740 if (path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002741 return UINT64_MAX;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002742 stream.PutCStringAsRawHex8(path.c_str());
2743 stream.PutChar(',');
2744 stream.PutHex32(flags);
2745 stream.PutChar(',');
2746 stream.PutHex32(mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002747 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002748 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002749 PacketResult::Success) {
2750 return ParseHostIOPacketResponse(response, UINT64_MAX, error);
2751 }
2752 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002753}
2754
Kate Stoneb9c1b512016-09-06 20:57:50 +00002755bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd, Error &error) {
2756 lldb_private::StreamString stream;
2757 stream.Printf("vFile:close:%i", (int)fd);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002758 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002759 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002760 PacketResult::Success) {
2761 return ParseHostIOPacketResponse(response, -1, error) == 0;
2762 }
2763 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002764}
2765
2766// Extension of host I/O packets to get the file size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002767lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize(
2768 const lldb_private::FileSpec &file_spec) {
2769 std::string path(file_spec.GetPath(false));
2770 lldb_private::StreamString stream;
2771 stream.PutCString("vFile:size:");
2772 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002773 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002774 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002775 PacketResult::Success) {
2776 if (response.GetChar() != 'F')
2777 return UINT64_MAX;
2778 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2779 return retcode;
2780 }
2781 return UINT64_MAX;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002782}
2783
Kate Stoneb9c1b512016-09-06 20:57:50 +00002784Error GDBRemoteCommunicationClient::GetFilePermissions(
2785 const FileSpec &file_spec, uint32_t &file_permissions) {
2786 std::string path{file_spec.GetPath(false)};
2787 Error error;
2788 lldb_private::StreamString stream;
2789 stream.PutCString("vFile:mode:");
2790 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002791 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002792 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002793 PacketResult::Success) {
2794 if (response.GetChar() != 'F') {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002795 error.SetErrorStringWithFormat("invalid response to '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002796 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002797 } else {
2798 const uint32_t mode = response.GetS32(-1);
2799 if (static_cast<int32_t>(mode) == -1) {
2800 if (response.GetChar() == ',') {
2801 int response_errno = response.GetS32(-1);
2802 if (response_errno > 0)
2803 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2804 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002805 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002806 } else
2807 error.SetErrorToGenericError();
2808 } else {
2809 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2810 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002811 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002812 } else {
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002813 error.SetErrorStringWithFormat("failed to send '%s' packet",
Zachary Turnerc1564272016-11-16 21:15:24 +00002814 stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002815 }
2816 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002817}
2818
Kate Stoneb9c1b512016-09-06 20:57:50 +00002819uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd,
2820 uint64_t offset, void *dst,
2821 uint64_t dst_len,
2822 Error &error) {
2823 lldb_private::StreamString stream;
2824 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len,
2825 offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002827 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002828 PacketResult::Success) {
2829 if (response.GetChar() != 'F')
2830 return 0;
2831 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2832 if (retcode == UINT32_MAX)
2833 return retcode;
2834 const char next = (response.Peek() ? *response.Peek() : 0);
2835 if (next == ',')
2836 return 0;
2837 if (next == ';') {
2838 response.GetChar(); // skip the semicolon
2839 std::string buffer;
2840 if (response.GetEscapedBinaryData(buffer)) {
2841 const uint64_t data_to_write =
2842 std::min<uint64_t>(dst_len, buffer.size());
2843 if (data_to_write > 0)
2844 memcpy(dst, &buffer[0], data_to_write);
2845 return data_to_write;
2846 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002847 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002848 }
2849 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002850}
2851
Kate Stoneb9c1b512016-09-06 20:57:50 +00002852uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd,
2853 uint64_t offset,
2854 const void *src,
2855 uint64_t src_len,
2856 Error &error) {
2857 lldb_private::StreamGDBRemote stream;
2858 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2859 stream.PutEscapedBytes(src, src_len);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002860 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002861 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002862 PacketResult::Success) {
2863 if (response.GetChar() != 'F') {
2864 error.SetErrorStringWithFormat("write file failed");
2865 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002866 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002867 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2868 if (bytes_written == UINT64_MAX) {
2869 error.SetErrorToGenericError();
2870 if (response.GetChar() == ',') {
2871 int response_errno = response.GetS32(-1);
2872 if (response_errno > 0)
2873 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2874 }
2875 return 0;
Greg Claytonfbb76342013-11-20 21:07:01 +00002876 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002877 return bytes_written;
2878 } else {
2879 error.SetErrorString("failed to send vFile:pwrite packet");
2880 }
2881 return 0;
2882}
2883
2884Error GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src,
2885 const FileSpec &dst) {
2886 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)};
2887 Error error;
2888 lldb_private::StreamGDBRemote stream;
2889 stream.PutCString("vFile:symlink:");
2890 // the unix symlink() command reverses its parameters where the dst if first,
2891 // so we follow suit here
2892 stream.PutCStringAsRawHex8(dst_path.c_str());
2893 stream.PutChar(',');
2894 stream.PutCStringAsRawHex8(src_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002895 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002896 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002897 PacketResult::Success) {
2898 if (response.GetChar() == 'F') {
2899 uint32_t result = response.GetU32(UINT32_MAX);
2900 if (result != 0) {
2901 error.SetErrorToGenericError();
2902 if (response.GetChar() == ',') {
2903 int response_errno = response.GetS32(-1);
2904 if (response_errno > 0)
2905 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2906 }
2907 }
2908 } else {
2909 // Should have returned with 'F<result>[,<errno>]'
2910 error.SetErrorStringWithFormat("symlink failed");
2911 }
2912 } else {
2913 error.SetErrorString("failed to send vFile:symlink packet");
2914 }
2915 return error;
2916}
2917
2918Error GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) {
2919 std::string path{file_spec.GetPath(false)};
2920 Error error;
2921 lldb_private::StreamGDBRemote stream;
2922 stream.PutCString("vFile:unlink:");
2923 // the unix symlink() command reverses its parameters where the dst if first,
2924 // so we follow suit here
2925 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002926 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002927 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002928 PacketResult::Success) {
2929 if (response.GetChar() == 'F') {
2930 uint32_t result = response.GetU32(UINT32_MAX);
2931 if (result != 0) {
2932 error.SetErrorToGenericError();
2933 if (response.GetChar() == ',') {
2934 int response_errno = response.GetS32(-1);
2935 if (response_errno > 0)
2936 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2937 }
2938 }
2939 } else {
2940 // Should have returned with 'F<result>[,<errno>]'
2941 error.SetErrorStringWithFormat("unlink failed");
2942 }
2943 } else {
2944 error.SetErrorString("failed to send vFile:unlink packet");
2945 }
2946 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002947}
2948
Daniel Maleae0f8f572013-08-26 23:57:52 +00002949// Extension of host I/O packets to get whether a file exists.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002950bool GDBRemoteCommunicationClient::GetFileExists(
2951 const lldb_private::FileSpec &file_spec) {
2952 std::string path(file_spec.GetPath(false));
2953 lldb_private::StreamString stream;
2954 stream.PutCString("vFile:exists:");
2955 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002956 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002957 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002958 PacketResult::Success) {
2959 if (response.GetChar() != 'F')
2960 return false;
2961 if (response.GetChar() != ',')
2962 return false;
2963 bool retcode = (response.GetChar() != '0');
2964 return retcode;
2965 }
2966 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002967}
2968
Kate Stoneb9c1b512016-09-06 20:57:50 +00002969bool GDBRemoteCommunicationClient::CalculateMD5(
2970 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) {
2971 std::string path(file_spec.GetPath(false));
2972 lldb_private::StreamString stream;
2973 stream.PutCString("vFile:MD5:");
2974 stream.PutCStringAsRawHex8(path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00002976 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) ==
Kate Stoneb9c1b512016-09-06 20:57:50 +00002977 PacketResult::Success) {
2978 if (response.GetChar() != 'F')
2979 return false;
2980 if (response.GetChar() != ',')
2981 return false;
2982 if (response.Peek() && *response.Peek() == 'x')
2983 return false;
2984 low = response.GetHexMaxU64(false, UINT64_MAX);
2985 high = response.GetHexMaxU64(false, UINT64_MAX);
Pavel Labath4b6f9592016-08-18 08:30:03 +00002986 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002987 }
2988 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00002989}
2990
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) {
2992 // Some targets have issues with g/G packets and we need to avoid using them
2993 if (m_avoid_g_packets == eLazyBoolCalculate) {
2994 if (process) {
2995 m_avoid_g_packets = eLazyBoolNo;
2996 const ArchSpec &arch = process->GetTarget().GetArchitecture();
2997 if (arch.IsValid() &&
2998 arch.GetTriple().getVendor() == llvm::Triple::Apple &&
2999 arch.GetTriple().getOS() == llvm::Triple::IOS &&
3000 arch.GetTriple().getArch() == llvm::Triple::aarch64) {
3001 m_avoid_g_packets = eLazyBoolYes;
3002 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3003 if (gdb_server_version != 0) {
3004 const char *gdb_server_name = GetGDBServerProgramName();
3005 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) {
3006 if (gdb_server_version >= 310)
3007 m_avoid_g_packets = eLazyBoolNo;
3008 }
3009 }
3010 }
3011 }
3012 }
3013 return m_avoid_g_packets == eLazyBoolYes;
3014}
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003015
Kate Stoneb9c1b512016-09-06 20:57:50 +00003016DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid,
3017 uint32_t reg) {
3018 StreamString payload;
3019 payload.Printf("p%x", reg);
3020 StringExtractorGDBRemote response;
3021 if (SendThreadSpecificPacketAndWaitForResponse(
3022 tid, std::move(payload), response, false) != PacketResult::Success ||
3023 !response.IsNormalResponse())
3024 return nullptr;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003025
Kate Stoneb9c1b512016-09-06 20:57:50 +00003026 DataBufferSP buffer_sp(
3027 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3028 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3029 return buffer_sp;
3030}
Pavel Labath4b6f9592016-08-18 08:30:03 +00003031
Kate Stoneb9c1b512016-09-06 20:57:50 +00003032DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) {
3033 StreamString payload;
3034 payload.PutChar('g');
3035 StringExtractorGDBRemote response;
3036 if (SendThreadSpecificPacketAndWaitForResponse(
3037 tid, std::move(payload), response, false) != PacketResult::Success ||
3038 !response.IsNormalResponse())
3039 return nullptr;
3040
3041 DataBufferSP buffer_sp(
3042 new DataBufferHeap(response.GetStringRef().size() / 2, 0));
3043 response.GetHexBytes(buffer_sp->GetData(), '\xcc');
3044 return buffer_sp;
3045}
3046
3047bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid,
3048 uint32_t reg_num,
3049 llvm::ArrayRef<uint8_t> data) {
3050 StreamString payload;
3051 payload.Printf("P%x=", reg_num);
3052 payload.PutBytesAsRawHex8(data.data(), data.size(),
3053 endian::InlHostByteOrder(),
3054 endian::InlHostByteOrder());
3055 StringExtractorGDBRemote response;
3056 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3057 response, false) ==
3058 PacketResult::Success &&
3059 response.IsOKResponse();
3060}
3061
3062bool GDBRemoteCommunicationClient::WriteAllRegisters(
3063 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) {
3064 StreamString payload;
3065 payload.PutChar('G');
3066 payload.PutBytesAsRawHex8(data.data(), data.size(),
3067 endian::InlHostByteOrder(),
3068 endian::InlHostByteOrder());
3069 StringExtractorGDBRemote response;
3070 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload),
3071 response, false) ==
3072 PacketResult::Success &&
3073 response.IsOKResponse();
3074}
3075
3076bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid,
3077 uint32_t &save_id) {
3078 save_id = 0; // Set to invalid save ID
3079 if (m_supports_QSaveRegisterState == eLazyBoolNo)
Greg Claytonf74cf862013-11-13 23:28:31 +00003080 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003081
3082 m_supports_QSaveRegisterState = eLazyBoolYes;
3083 StreamString payload;
3084 payload.PutCString("QSaveRegisterState");
3085 StringExtractorGDBRemote response;
3086 if (SendThreadSpecificPacketAndWaitForResponse(
3087 tid, std::move(payload), response, false) != PacketResult::Success)
3088 return false;
3089
3090 if (response.IsUnsupportedResponse())
3091 m_supports_QSaveRegisterState = eLazyBoolNo;
3092
3093 const uint32_t response_save_id = response.GetU32(0);
3094 if (response_save_id == 0)
3095 return false;
3096
3097 save_id = response_save_id;
3098 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003099}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003100
Kate Stoneb9c1b512016-09-06 20:57:50 +00003101bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid,
3102 uint32_t save_id) {
3103 // We use the "m_supports_QSaveRegisterState" variable here because the
3104 // QSaveRegisterState and QRestoreRegisterState packets must both be supported
3105 // in
3106 // order to be useful
3107 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3108 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003109
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110 StreamString payload;
3111 payload.Printf("QRestoreRegisterState:%u", save_id);
3112 StringExtractorGDBRemote response;
3113 if (SendThreadSpecificPacketAndWaitForResponse(
3114 tid, std::move(payload), response, false) != PacketResult::Success)
3115 return false;
Pavel Labath27402d22016-08-18 12:32:41 +00003116
Kate Stoneb9c1b512016-09-06 20:57:50 +00003117 if (response.IsOKResponse())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003118 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003119
3120 if (response.IsUnsupportedResponse())
3121 m_supports_QSaveRegisterState = eLazyBoolNo;
3122 return false;
3123}
3124
3125bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) {
3126 if (!GetSyncThreadStateSupported())
3127 return false;
3128
3129 StreamString packet;
3130 StringExtractorGDBRemote response;
3131 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid);
3132 return SendPacketAndWaitForResponse(packet.GetString(), response, false) ==
3133 GDBRemoteCommunication::PacketResult::Success &&
3134 response.IsOKResponse();
3135}
3136
3137bool GDBRemoteCommunicationClient::GetModuleInfo(
3138 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec,
3139 ModuleSpec &module_spec) {
3140 if (!m_supports_qModuleInfo)
3141 return false;
3142
3143 std::string module_path = module_file_spec.GetPath(false);
3144 if (module_path.empty())
3145 return false;
3146
3147 StreamString packet;
3148 packet.PutCString("qModuleInfo:");
3149 packet.PutCStringAsRawHex8(module_path.c_str());
3150 packet.PutCString(";");
3151 const auto &triple = arch_spec.GetTriple().getTriple();
3152 packet.PutCStringAsRawHex8(triple.c_str());
3153
3154 StringExtractorGDBRemote response;
Pavel Labath0f8f0d32016-09-23 09:11:49 +00003155 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) !=
3156 PacketResult::Success)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003157 return false;
3158
3159 if (response.IsErrorResponse())
3160 return false;
3161
3162 if (response.IsUnsupportedResponse()) {
3163 m_supports_qModuleInfo = false;
3164 return false;
3165 }
3166
3167 llvm::StringRef name;
3168 llvm::StringRef value;
3169
3170 module_spec.Clear();
3171 module_spec.GetFileSpec() = module_file_spec;
3172
3173 while (response.GetNameColonValue(name, value)) {
3174 if (name == "uuid" || name == "md5") {
3175 StringExtractor extractor(value);
3176 std::string uuid;
3177 extractor.GetHexByteString(uuid);
3178 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2);
3179 } else if (name == "triple") {
3180 StringExtractor extractor(value);
3181 std::string triple;
3182 extractor.GetHexByteString(triple);
3183 module_spec.GetArchitecture().SetTriple(triple.c_str());
3184 } else if (name == "file_offset") {
3185 uint64_t ival = 0;
3186 if (!value.getAsInteger(16, ival))
3187 module_spec.SetObjectOffset(ival);
3188 } else if (name == "file_size") {
3189 uint64_t ival = 0;
3190 if (!value.getAsInteger(16, ival))
3191 module_spec.SetObjectSize(ival);
3192 } else if (name == "file_path") {
3193 StringExtractor extractor(value);
3194 std::string path;
3195 extractor.GetHexByteString(path);
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003196 module_spec.GetFileSpec() = FileSpec(path, false, arch_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003197 }
3198 }
3199
3200 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003201}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003202
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003203static llvm::Optional<ModuleSpec>
3204ParseModuleSpec(StructuredData::Dictionary *dict) {
3205 ModuleSpec result;
3206 if (!dict)
3207 return llvm::None;
3208
3209 std::string string;
3210 uint64_t integer;
3211
3212 if (!dict->GetValueForKeyAsString("uuid", string))
3213 return llvm::None;
3214 result.GetUUID().SetFromCString(string.c_str(), string.size());
3215
3216 if (!dict->GetValueForKeyAsInteger("file_offset", integer))
3217 return llvm::None;
3218 result.SetObjectOffset(integer);
3219
3220 if (!dict->GetValueForKeyAsInteger("file_size", integer))
3221 return llvm::None;
3222 result.SetObjectSize(integer);
3223
3224 if (!dict->GetValueForKeyAsString("triple", string))
3225 return llvm::None;
3226 result.GetArchitecture().SetTriple(string.c_str());
3227
3228 if (!dict->GetValueForKeyAsString("file_path", string))
3229 return llvm::None;
3230 result.GetFileSpec() = FileSpec(string, false, result.GetArchitecture());
3231
3232 return result;
3233}
3234
3235llvm::Optional<std::vector<ModuleSpec>>
3236GDBRemoteCommunicationClient::GetModulesInfo(
3237 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3238 if (!m_supports_jModulesInfo)
3239 return llvm::None;
3240
3241 JSONArray::SP module_array_sp = std::make_shared<JSONArray>();
3242 for (const FileSpec &module_file_spec : module_file_specs) {
3243 JSONObject::SP module_sp = std::make_shared<JSONObject>();
3244 module_array_sp->AppendObject(module_sp);
3245 module_sp->SetObject(
Pavel Labath763f1c42017-01-05 13:18:46 +00003246 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false)));
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003247 module_sp->SetObject("triple",
3248 std::make_shared<JSONString>(triple.getTriple()));
3249 }
3250 StreamString unescaped_payload;
3251 unescaped_payload.PutCString("jModulesInfo:");
3252 module_array_sp->Write(unescaped_payload);
3253 StreamGDBRemote payload;
Zachary Turnerc1564272016-11-16 21:15:24 +00003254 payload.PutEscapedBytes(unescaped_payload.GetString().data(),
Pavel Labath2f1fbae2016-09-08 10:07:04 +00003255 unescaped_payload.GetSize());
3256
3257 StringExtractorGDBRemote response;
3258 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) !=
3259 PacketResult::Success ||
3260 response.IsErrorResponse())
3261 return llvm::None;
3262
3263 if (response.IsUnsupportedResponse()) {
3264 m_supports_jModulesInfo = false;
3265 return llvm::None;
3266 }
3267
3268 StructuredData::ObjectSP response_object_sp =
3269 StructuredData::ParseJSON(response.GetStringRef());
3270 if (!response_object_sp)
3271 return llvm::None;
3272
3273 StructuredData::Array *response_array = response_object_sp->GetAsArray();
3274 if (!response_array)
3275 return llvm::None;
3276
3277 std::vector<ModuleSpec> result;
3278 for (size_t i = 0; i < response_array->GetSize(); ++i) {
3279 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec(
3280 response_array->GetItemAtIndex(i)->GetAsDictionary()))
3281 result.push_back(*module_spec);
3282 }
3283
3284 return result;
3285}
3286
Colin Rileyc3c95b22015-04-16 15:51:33 +00003287// query the target remote for extended information using the qXfer packet
3288//
3289// example: object='features', annex='target.xml', out=<xml output>
3290// return: 'true' on success
3291// 'false' on failure (err set)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003292bool GDBRemoteCommunicationClient::ReadExtFeature(
3293 const lldb_private::ConstString object,
3294 const lldb_private::ConstString annex, std::string &out,
3295 lldb_private::Error &err) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003296
Kate Stoneb9c1b512016-09-06 20:57:50 +00003297 std::stringstream output;
3298 StringExtractorGDBRemote chunk;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003299
Kate Stoneb9c1b512016-09-06 20:57:50 +00003300 uint64_t size = GetRemoteMaxPacketSize();
3301 if (size == 0)
3302 size = 0x1000;
3303 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3304 int offset = 0;
3305 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003306
Kate Stoneb9c1b512016-09-06 20:57:50 +00003307 // loop until all data has been read
3308 while (active) {
Colin Rileyc3c95b22015-04-16 15:51:33 +00003309
Kate Stoneb9c1b512016-09-06 20:57:50 +00003310 // send query extended feature packet
3311 std::stringstream packet;
3312 packet << "qXfer:" << object.AsCString("")
3313 << ":read:" << annex.AsCString("") << ":" << std::hex << offset
3314 << "," << std::hex << size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003315
Kate Stoneb9c1b512016-09-06 20:57:50 +00003316 GDBRemoteCommunication::PacketResult res =
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003317 SendPacketAndWaitForResponse(packet.str(), chunk, false);
Colin Rileyc3c95b22015-04-16 15:51:33 +00003318
Kate Stoneb9c1b512016-09-06 20:57:50 +00003319 if (res != GDBRemoteCommunication::PacketResult::Success) {
3320 err.SetErrorString("Error sending $qXfer packet");
3321 return false;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003322 }
3323
Kate Stoneb9c1b512016-09-06 20:57:50 +00003324 const std::string &str = chunk.GetStringRef();
3325 if (str.length() == 0) {
3326 // should have some data in chunk
3327 err.SetErrorString("Empty response from $qXfer packet");
3328 return false;
3329 }
3330
3331 // check packet code
3332 switch (str[0]) {
3333 // last chunk
3334 case ('l'):
3335 active = false;
3336 LLVM_FALLTHROUGH;
3337
3338 // more chunks
3339 case ('m'):
3340 if (str.length() > 1)
3341 output << &str[1];
3342 offset += size;
3343 break;
3344
3345 // unknown chunk
3346 default:
3347 err.SetErrorString("Invalid continuation code from $qXfer packet");
3348 return false;
3349 }
3350 }
3351
3352 out = output.str();
3353 err.Success();
3354 return true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003355}
Greg Clayton0b90be12015-06-23 21:27:50 +00003356
3357// Notify the target that gdb is prepared to serve symbol lookup requests.
3358// packet: "qSymbol::"
3359// reply:
3360// OK The target does not need to look up any (more) symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003361// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex
3362// encoded).
3363// LLDB may provide the value by sending another qSymbol
3364// packet
Greg Clayton0b90be12015-06-23 21:27:50 +00003365// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003366//
3367// Three examples:
3368//
3369// lldb sends: qSymbol::
3370// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003371// Remote gdb stub does not need to know the addresses of any symbols, lldb
3372// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003373// need to ask again in this session.
3374//
3375// lldb sends: qSymbol::
3376// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3377// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3378// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003379// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does
3380// not know
3381// the address at this time. lldb needs to send qSymbol:: again when it has
3382// more
Jason Molenda50018d32016-01-13 04:08:10 +00003383// solibs loaded.
3384//
3385// lldb sends: qSymbol::
3386// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3387// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3388// lldb receives: OK
Kate Stoneb9c1b512016-09-06 20:57:50 +00003389// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says
3390// that it
3391// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it
3392// does not
Jason Molenda50018d32016-01-13 04:08:10 +00003393// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003394
Kate Stoneb9c1b512016-09-06 20:57:50 +00003395void GDBRemoteCommunicationClient::ServeSymbolLookups(
3396 lldb_private::Process *process) {
3397 // Set to true once we've resolved a symbol to an address for the remote stub.
3398 // If we get an 'OK' response after this, the remote stub doesn't need any
3399 // more
3400 // symbols and we can stop asking.
3401 bool symbol_response_provided = false;
Jason Molenda50018d32016-01-13 04:08:10 +00003402
Kate Stoneb9c1b512016-09-06 20:57:50 +00003403 // Is this the initial qSymbol:: packet?
3404 bool first_qsymbol_query = true;
Jason Molenda50018d32016-01-13 04:08:10 +00003405
Kate Stoneb9c1b512016-09-06 20:57:50 +00003406 if (m_supports_qSymbol && m_qSymbol_requests_done == false) {
3407 Lock lock(*this, false);
3408 if (lock) {
3409 StreamString packet;
3410 packet.PutCString("qSymbol::");
3411 StringExtractorGDBRemote response;
3412 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) ==
3413 PacketResult::Success) {
3414 if (response.IsOKResponse()) {
3415 if (symbol_response_provided || first_qsymbol_query) {
3416 m_qSymbol_requests_done = true;
3417 }
3418
3419 // We are done serving symbols requests
3420 return;
3421 }
3422 first_qsymbol_query = false;
3423
3424 if (response.IsUnsupportedResponse()) {
3425 // qSymbol is not supported by the current GDB server we are connected
3426 // to
3427 m_supports_qSymbol = false;
3428 return;
3429 } else {
3430 llvm::StringRef response_str(response.GetStringRef());
3431 if (response_str.startswith("qSymbol:")) {
3432 response.SetFilePos(strlen("qSymbol:"));
3433 std::string symbol_name;
3434 if (response.GetHexByteString(symbol_name)) {
3435 if (symbol_name.empty())
3436 return;
3437
3438 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3439 lldb_private::SymbolContextList sc_list;
3440 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(
3441 ConstString(symbol_name), eSymbolTypeAny, sc_list)) {
3442 const size_t num_scs = sc_list.GetSize();
3443 for (size_t sc_idx = 0;
3444 sc_idx < num_scs &&
3445 symbol_load_addr == LLDB_INVALID_ADDRESS;
3446 ++sc_idx) {
3447 SymbolContext sc;
3448 if (sc_list.GetContextAtIndex(sc_idx, sc)) {
3449 if (sc.symbol) {
3450 switch (sc.symbol->GetType()) {
3451 case eSymbolTypeInvalid:
3452 case eSymbolTypeAbsolute:
3453 case eSymbolTypeUndefined:
3454 case eSymbolTypeSourceFile:
3455 case eSymbolTypeHeaderFile:
3456 case eSymbolTypeObjectFile:
3457 case eSymbolTypeCommonBlock:
3458 case eSymbolTypeBlock:
3459 case eSymbolTypeLocal:
3460 case eSymbolTypeParam:
3461 case eSymbolTypeVariable:
3462 case eSymbolTypeVariableType:
3463 case eSymbolTypeLineEntry:
3464 case eSymbolTypeLineHeader:
3465 case eSymbolTypeScopeBegin:
3466 case eSymbolTypeScopeEnd:
3467 case eSymbolTypeAdditional:
3468 case eSymbolTypeCompiler:
3469 case eSymbolTypeInstrumentation:
3470 case eSymbolTypeTrampoline:
3471 break;
3472
3473 case eSymbolTypeCode:
3474 case eSymbolTypeResolver:
3475 case eSymbolTypeData:
3476 case eSymbolTypeRuntime:
3477 case eSymbolTypeException:
3478 case eSymbolTypeObjCClass:
3479 case eSymbolTypeObjCMetaClass:
3480 case eSymbolTypeObjCIVar:
3481 case eSymbolTypeReExported:
3482 symbol_load_addr =
3483 sc.symbol->GetLoadAddress(&process->GetTarget());
3484 break;
3485 }
Jason Molenda50018d32016-01-13 04:08:10 +00003486 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003487 }
Greg Clayton42b01482015-08-11 22:07:46 +00003488 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003489 }
3490 // This is the normal path where our symbol lookup was successful
3491 // and we want
3492 // to send a packet with the new symbol value and see if another
3493 // lookup needs to be
3494 // done.
Greg Clayton0b90be12015-06-23 21:27:50 +00003495
Kate Stoneb9c1b512016-09-06 20:57:50 +00003496 // Change "packet" to contain the requested symbol value and name
3497 packet.Clear();
3498 packet.PutCString("qSymbol:");
3499 if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
3500 packet.Printf("%" PRIx64, symbol_load_addr);
3501 symbol_response_provided = true;
3502 } else {
3503 symbol_response_provided = false;
3504 }
3505 packet.PutCString(":");
3506 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3507 continue; // go back to the while loop and send "packet" and wait
3508 // for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003509 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003510 }
3511 }
3512 }
3513 // If we make it here, the symbol request packet response wasn't valid or
3514 // our symbol lookup failed so we must abort
3515 return;
Greg Clayton0b90be12015-06-23 21:27:50 +00003516
Kate Stoneb9c1b512016-09-06 20:57:50 +00003517 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(
3518 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) {
3519 log->Printf(
3520 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.",
3521 __FUNCTION__);
Greg Clayton0b90be12015-06-23 21:27:50 +00003522 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003523 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003524}
3525
Kate Stoneb9c1b512016-09-06 20:57:50 +00003526StructuredData::Array *
3527GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() {
3528 if (!m_supported_async_json_packets_is_valid) {
3529 // Query the server for the array of supported asynchronous JSON
3530 // packets.
3531 m_supported_async_json_packets_is_valid = true;
Todd Fiala75930012016-08-19 04:21:48 +00003532
Kate Stoneb9c1b512016-09-06 20:57:50 +00003533 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Todd Fiala75930012016-08-19 04:21:48 +00003534
Kate Stoneb9c1b512016-09-06 20:57:50 +00003535 // Poll it now.
Todd Fiala75930012016-08-19 04:21:48 +00003536 StringExtractorGDBRemote response;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003537 const bool send_async = false;
3538 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response,
3539 send_async) == PacketResult::Success) {
3540 m_supported_async_json_packets_sp =
3541 StructuredData::ParseJSON(response.GetStringRef());
3542 if (m_supported_async_json_packets_sp &&
3543 !m_supported_async_json_packets_sp->GetAsArray()) {
3544 // We were returned something other than a JSON array. This
3545 // is invalid. Clear it out.
3546 if (log)
3547 log->Printf("GDBRemoteCommunicationClient::%s(): "
3548 "QSupportedAsyncJSONPackets returned invalid "
3549 "result: %s",
3550 __FUNCTION__, response.GetStringRef().c_str());
3551 m_supported_async_json_packets_sp.reset();
3552 }
3553 } else {
3554 if (log)
3555 log->Printf("GDBRemoteCommunicationClient::%s(): "
3556 "QSupportedAsyncJSONPackets unsupported",
3557 __FUNCTION__);
Todd Fiala75930012016-08-19 04:21:48 +00003558 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003559
3560 if (log && m_supported_async_json_packets_sp) {
3561 StreamString stream;
3562 m_supported_async_json_packets_sp->Dump(stream);
3563 log->Printf("GDBRemoteCommunicationClient::%s(): supported async "
3564 "JSON packets: %s",
Zachary Turnerc1564272016-11-16 21:15:24 +00003565 __FUNCTION__, stream.GetData());
Todd Fiala75930012016-08-19 04:21:48 +00003566 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003567 }
3568
3569 return m_supported_async_json_packets_sp
3570 ? m_supported_async_json_packets_sp->GetAsArray()
3571 : nullptr;
Todd Fiala75930012016-08-19 04:21:48 +00003572}
3573
Kate Stoneb9c1b512016-09-06 20:57:50 +00003574Error GDBRemoteCommunicationClient::ConfigureRemoteStructuredData(
3575 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
3576 Error error;
3577
3578 if (type_name.GetLength() == 0) {
3579 error.SetErrorString("invalid type_name argument");
3580 return error;
3581 }
3582
3583 // Build command: Configure{type_name}: serialized config
3584 // data.
3585 StreamGDBRemote stream;
3586 stream.PutCString("QConfigure");
3587 stream.PutCString(type_name.AsCString());
3588 stream.PutChar(':');
3589 if (config_sp) {
3590 // Gather the plain-text version of the configuration data.
3591 StreamString unescaped_stream;
3592 config_sp->Dump(unescaped_stream);
3593 unescaped_stream.Flush();
3594
3595 // Add it to the stream in escaped fashion.
Zachary Turnerc1564272016-11-16 21:15:24 +00003596 stream.PutEscapedBytes(unescaped_stream.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003597 unescaped_stream.GetSize());
3598 }
3599 stream.Flush();
3600
3601 // Send the packet.
3602 const bool send_async = false;
3603 StringExtractorGDBRemote response;
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00003604 auto result =
3605 SendPacketAndWaitForResponse(stream.GetString(), response, send_async);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003606 if (result == PacketResult::Success) {
3607 // We failed if the config result comes back other than OK.
3608 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) {
3609 // Okay!
3610 error.Clear();
3611 } else {
3612 error.SetErrorStringWithFormat("configuring StructuredData feature "
3613 "%s failed with error %s",
3614 type_name.AsCString(),
3615 response.GetStringRef().c_str());
3616 }
3617 } else {
3618 // Can we get more data here on the failure?
3619 error.SetErrorStringWithFormat("configuring StructuredData feature %s "
3620 "failed when sending packet: "
3621 "PacketResult=%d",
Ilia K4f730dc2016-09-12 05:25:33 +00003622 type_name.AsCString(), (int)result);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003623 }
3624 return error;
3625}
3626
3627void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) {
3628 GDBRemoteClientBase::OnRunPacketSent(first);
3629 m_curr_tid = LLDB_INVALID_THREAD_ID;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003630}