blob: 7600c139ace74db592f5de005d9e3be2008f243e [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
10
11#include "GDBRemoteCommunicationClient.h"
12
13// C Includes
Greg Claytone034a042015-05-21 20:52:06 +000014#include <math.h>
Daniel Maleab89d0492013-08-28 16:06:16 +000015#include <sys/stat.h>
16
Greg Clayton576d8832011-03-22 04:00:09 +000017// C++ Includes
Han Ming Ong4b6459f2013-01-18 23:11:53 +000018#include <sstream>
Greg Claytone034a042015-05-21 20:52:06 +000019#include <numeric>
Han Ming Ong4b6459f2013-01-18 23:11:53 +000020
Greg Clayton576d8832011-03-22 04:00:09 +000021// Other libraries and framework includes
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"
Greg Clayton576d8832011-03-22 04:00:09 +000026#include "lldb/Core/StreamString.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000027#include "lldb/Host/HostInfo.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000028#include "lldb/Host/StringConvert.h"
Greg Clayton576d8832011-03-22 04:00:09 +000029#include "lldb/Host/TimeValue.h"
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000030#include "lldb/Interpreter/Args.h"
Greg Clayton0b90be12015-06-23 21:27:50 +000031#include "lldb/Symbol/Symbol.h"
Pavel Labath4cb69922016-07-29 15:41:52 +000032#include "lldb/Target/MemoryRegionInfo.h"
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000033#include "lldb/Target/Target.h"
Greg Clayton576d8832011-03-22 04:00:09 +000034
35// Project includes
36#include "Utility/StringExtractorGDBRemote.h"
37#include "ProcessGDBRemote.h"
38#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000039#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000040
Jason Molenda91ffe0a2015-06-18 21:46:06 +000041#if defined (HAVE_LIBCOMPRESSION)
42#include <compression.h>
43#endif
44
Greg Clayton576d8832011-03-22 04:00:09 +000045using namespace lldb;
46using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000047using namespace lldb_private::process_gdb_remote;
Greg Clayton576d8832011-03-22 04:00:09 +000048
49//----------------------------------------------------------------------
50// GDBRemoteCommunicationClient constructor
51//----------------------------------------------------------------------
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000052GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000053 : GDBRemoteClientBase("gdb-remote.client", "gdb-remote.client.rx_packet"),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000054 m_supports_not_sending_acks(eLazyBoolCalculate),
55 m_supports_thread_suffix(eLazyBoolCalculate),
56 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
57 m_supports_vCont_all(eLazyBoolCalculate),
58 m_supports_vCont_any(eLazyBoolCalculate),
59 m_supports_vCont_c(eLazyBoolCalculate),
60 m_supports_vCont_C(eLazyBoolCalculate),
61 m_supports_vCont_s(eLazyBoolCalculate),
62 m_supports_vCont_S(eLazyBoolCalculate),
63 m_qHostInfo_is_valid(eLazyBoolCalculate),
64 m_curr_pid_is_valid(eLazyBoolCalculate),
65 m_qProcessInfo_is_valid(eLazyBoolCalculate),
66 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
67 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
68 m_supports_memory_region_info(eLazyBoolCalculate),
69 m_supports_watchpoint_support_info(eLazyBoolCalculate),
70 m_supports_detach_stay_stopped(eLazyBoolCalculate),
71 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
72 m_attach_or_wait_reply(eLazyBoolCalculate),
73 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
74 m_supports_p(eLazyBoolCalculate),
75 m_supports_x(eLazyBoolCalculate),
76 m_avoid_g_packets(eLazyBoolCalculate),
77 m_supports_QSaveRegisterState(eLazyBoolCalculate),
78 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
79 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
80 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
81 m_supports_qXfer_features_read(eLazyBoolCalculate),
82 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
83 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
84 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
Pavel Labath8c1b6bd2016-08-09 12:04:46 +000085 m_supports_jGetSharedCacheInfo(eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000086 m_supports_qProcessInfoPID(true),
87 m_supports_qfProcessInfo(true),
88 m_supports_qUserName(true),
89 m_supports_qGroupName(true),
90 m_supports_qThreadStopInfo(true),
91 m_supports_z0(true),
92 m_supports_z1(true),
93 m_supports_z2(true),
94 m_supports_z3(true),
95 m_supports_z4(true),
96 m_supports_QEnvironment(true),
97 m_supports_QEnvironmentHexEncoded(true),
98 m_supports_qSymbol(true),
99 m_qSymbol_requests_done(false),
100 m_supports_qModuleInfo(true),
101 m_supports_jThreadsInfo(true),
102 m_curr_pid(LLDB_INVALID_PROCESS_ID),
103 m_curr_tid(LLDB_INVALID_THREAD_ID),
104 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
105 m_num_supported_hardware_watchpoints(0),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000106 m_host_arch(),
107 m_process_arch(),
108 m_os_version_major(UINT32_MAX),
109 m_os_version_minor(UINT32_MAX),
110 m_os_version_update(UINT32_MAX),
111 m_os_build(),
112 m_os_kernel(),
113 m_hostname(),
114 m_gdb_server_name(),
115 m_gdb_server_version(UINT32_MAX),
116 m_default_packet_timeout(0),
117 m_max_packet_size(0)
Greg Clayton576d8832011-03-22 04:00:09 +0000118{
Greg Clayton576d8832011-03-22 04:00:09 +0000119}
120
121//----------------------------------------------------------------------
122// Destructor
123//----------------------------------------------------------------------
124GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
125{
Greg Clayton576d8832011-03-22 04:00:09 +0000126 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000127 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000128}
129
130bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000131GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
132{
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000133 ResetDiscoverableSettings(false);
Greg Claytonfb909312013-11-23 01:58:15 +0000134
Greg Clayton1cb64962011-03-24 04:28:38 +0000135 // Start the read thread after we send the handshake ack since if we
136 // fail to send the handshake ack, there is no reason to continue...
137 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000138 {
Ed Maste48f986f2013-12-18 15:31:45 +0000139 // Wait for any responses that might have been queued up in the remote
140 // GDB server and flush them all
141 StringExtractorGDBRemote response;
142 PacketResult packet_result = PacketResult::Success;
143 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
144 while (packet_result == PacketResult::Success)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000145 packet_result = ReadPacket (response, timeout_usec, false);
Ed Maste48f986f2013-12-18 15:31:45 +0000146
Greg Claytonfb909312013-11-23 01:58:15 +0000147 // The return value from QueryNoAckModeSupported() is true if the packet
148 // was sent and _any_ response (including UNIMPLEMENTED) was received),
149 // or false if no response was received. This quickly tells us if we have
150 // a live connection to a remote GDB server...
151 if (QueryNoAckModeSupported())
152 {
153 return true;
154 }
155 else
156 {
157 if (error_ptr)
158 error_ptr->SetErrorString("failed to get reply to handshake packet");
159 }
160 }
161 else
162 {
163 if (error_ptr)
164 error_ptr->SetErrorString("failed to send the handshake ack");
165 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000166 return false;
167}
168
Greg Claytonfb909312013-11-23 01:58:15 +0000169bool
Greg Claytonb30c50c2015-05-29 00:01:55 +0000170GDBRemoteCommunicationClient::GetEchoSupported ()
171{
172 if (m_supports_qEcho == eLazyBoolCalculate)
173 {
174 GetRemoteQSupported();
175 }
176 return m_supports_qEcho == eLazyBoolYes;
177}
178
179
180bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000181GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
182{
183 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
184 {
185 GetRemoteQSupported();
186 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000187 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000188}
189
190bool
191GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
192{
193 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
194 {
195 GetRemoteQSupported();
196 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000197 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000198}
199
200bool
201GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
202{
203 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
204 {
205 GetRemoteQSupported();
206 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000207 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000208}
209
Steve Pucci03904ac2014-03-04 23:18:46 +0000210bool
211GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
212{
213 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
214 {
215 GetRemoteQSupported();
216 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000217 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000218}
219
Colin Rileyc3c95b22015-04-16 15:51:33 +0000220bool
221GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported ()
222{
223 if (m_supports_qXfer_features_read == eLazyBoolCalculate)
224 {
225 GetRemoteQSupported();
226 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000227 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000228}
229
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000230uint64_t
231GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
232{
233 if (m_max_packet_size == 0)
234 {
235 GetRemoteQSupported();
236 }
237 return m_max_packet_size;
238}
239
240bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000241GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000242{
243 if (m_supports_not_sending_acks == eLazyBoolCalculate)
244 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000245 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000246 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000247
Jason Molenda36a216e2014-07-24 01:36:24 +0000248 // This is the first real packet that we'll send in a debug session and it may take a little
249 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
250
251 const uint32_t minimum_timeout = 6;
252 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000253 GDBRemoteCommunication::ScopedTimeout timeout (*this, std::max (old_timeout, minimum_timeout));
Jason Molenda36a216e2014-07-24 01:36:24 +0000254
Greg Clayton1cb64962011-03-24 04:28:38 +0000255 StringExtractorGDBRemote response;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000256 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000257 {
258 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000259 {
260 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000261 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000262 }
Greg Claytonfb909312013-11-23 01:58:15 +0000263 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000264 }
265 }
Greg Claytonfb909312013-11-23 01:58:15 +0000266 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000267}
268
269void
Greg Clayton44633992012-04-10 03:22:03 +0000270GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
271{
272 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
273 {
274 m_supports_threads_in_stop_reply = eLazyBoolNo;
275
276 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000277 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000278 {
279 if (response.IsOKResponse())
280 m_supports_threads_in_stop_reply = eLazyBoolYes;
281 }
282 }
283}
284
Jim Inghamcd16df92012-07-20 21:37:13 +0000285bool
286GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
287{
288 if (m_attach_or_wait_reply == eLazyBoolCalculate)
289 {
290 m_attach_or_wait_reply = eLazyBoolNo;
291
292 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000293 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000294 {
295 if (response.IsOKResponse())
296 m_attach_or_wait_reply = eLazyBoolYes;
297 }
298 }
299 if (m_attach_or_wait_reply == eLazyBoolYes)
300 return true;
301 else
302 return false;
303}
304
Jim Ingham279ceec2012-07-25 21:12:43 +0000305bool
306GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
307{
308 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
309 {
310 m_prepare_for_reg_writing_reply = eLazyBoolNo;
311
312 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000313 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000314 {
315 if (response.IsOKResponse())
316 m_prepare_for_reg_writing_reply = eLazyBoolYes;
317 }
318 }
319 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
320 return true;
321 else
322 return false;
323}
324
Greg Clayton44633992012-04-10 03:22:03 +0000325
326void
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000327GDBRemoteCommunicationClient::ResetDiscoverableSettings (bool did_exec)
Greg Clayton576d8832011-03-22 04:00:09 +0000328{
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000329 if (did_exec == false)
330 {
331 // Hard reset everything, this is when we first connect to a GDB server
332 m_supports_not_sending_acks = eLazyBoolCalculate;
333 m_supports_thread_suffix = eLazyBoolCalculate;
334 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
335 m_supports_vCont_c = eLazyBoolCalculate;
336 m_supports_vCont_C = eLazyBoolCalculate;
337 m_supports_vCont_s = eLazyBoolCalculate;
338 m_supports_vCont_S = eLazyBoolCalculate;
339 m_supports_p = eLazyBoolCalculate;
340 m_supports_x = eLazyBoolCalculate;
341 m_supports_QSaveRegisterState = eLazyBoolCalculate;
342 m_qHostInfo_is_valid = eLazyBoolCalculate;
343 m_curr_pid_is_valid = eLazyBoolCalculate;
344 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
345 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
346 m_supports_memory_region_info = eLazyBoolCalculate;
347 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
348 m_attach_or_wait_reply = eLazyBoolCalculate;
349 m_avoid_g_packets = eLazyBoolCalculate;
350 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
351 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
352 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
353 m_supports_qXfer_features_read = eLazyBoolCalculate;
354 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
355 m_supports_qProcessInfoPID = true;
356 m_supports_qfProcessInfo = true;
357 m_supports_qUserName = true;
358 m_supports_qGroupName = true;
359 m_supports_qThreadStopInfo = true;
360 m_supports_z0 = true;
361 m_supports_z1 = true;
362 m_supports_z2 = true;
363 m_supports_z3 = true;
364 m_supports_z4 = true;
365 m_supports_QEnvironment = true;
366 m_supports_QEnvironmentHexEncoded = true;
367 m_supports_qSymbol = true;
Jason Molenda50018d32016-01-13 04:08:10 +0000368 m_qSymbol_requests_done = false;
Stephane Sezer6f455292016-01-08 00:00:17 +0000369 m_supports_qModuleInfo = true;
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000370 m_host_arch.Clear();
371 m_os_version_major = UINT32_MAX;
372 m_os_version_minor = UINT32_MAX;
373 m_os_version_update = UINT32_MAX;
374 m_os_build.clear();
375 m_os_kernel.clear();
376 m_hostname.clear();
377 m_gdb_server_name.clear();
378 m_gdb_server_version = UINT32_MAX;
379 m_default_packet_timeout = 0;
380 m_max_packet_size = 0;
381 }
382
383 // These flags should be reset when we first connect to a GDB server
384 // and when our inferior process execs
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000385 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000386 m_process_arch.Clear();
Greg Clayton576d8832011-03-22 04:00:09 +0000387}
388
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000389void
390GDBRemoteCommunicationClient::GetRemoteQSupported ()
391{
392 // Clear out any capabilities we expect to see in the qSupported response
Steve Pucci03904ac2014-03-04 23:18:46 +0000393 m_supports_qXfer_auxv_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000394 m_supports_qXfer_libraries_read = eLazyBoolNo;
Steve Pucci03904ac2014-03-04 23:18:46 +0000395 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000396 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000397 m_supports_qXfer_features_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000398 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
399
Colin Rileyc3c95b22015-04-16 15:51:33 +0000400 // build the qSupported packet
401 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
402 StreamString packet;
403 packet.PutCString( "qSupported" );
404 for ( uint32_t i = 0; i < features.size( ); ++i )
405 {
406 packet.PutCString( i==0 ? ":" : ";");
407 packet.PutCString( features[i].c_str( ) );
408 }
409
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000410 StringExtractorGDBRemote response;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000411 if (SendPacketAndWaitForResponse(packet.GetData(),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000412 response,
413 /*send_async=*/false) == PacketResult::Success)
414 {
415 const char *response_cstr = response.GetStringRef().c_str();
Steve Pucci03904ac2014-03-04 23:18:46 +0000416 if (::strstr (response_cstr, "qXfer:auxv:read+"))
417 m_supports_qXfer_auxv_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000418 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
419 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
420 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
421 {
422 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
423 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
424 }
425 if (::strstr (response_cstr, "qXfer:libraries:read+"))
426 m_supports_qXfer_libraries_read = eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000427 if (::strstr (response_cstr, "qXfer:features:read+"))
428 m_supports_qXfer_features_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000429
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000430
431 // Look for a list of compressions in the features list e.g.
432 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
433 const char *features_list = ::strstr (response_cstr, "qXfer:features:");
434 if (features_list)
435 {
436 const char *compressions = ::strstr (features_list, "SupportedCompressions=");
437 if (compressions)
438 {
439 std::vector<std::string> supported_compressions;
440 compressions += sizeof ("SupportedCompressions=") - 1;
441 const char *end_of_compressions = strchr (compressions, ';');
442 if (end_of_compressions == NULL)
443 {
444 end_of_compressions = strchr (compressions, '\0');
445 }
446 const char *current_compression = compressions;
447 while (current_compression < end_of_compressions)
448 {
449 const char *next_compression_name = strchr (current_compression, ',');
450 const char *end_of_this_word = next_compression_name;
451 if (next_compression_name == NULL || end_of_compressions < next_compression_name)
452 {
453 end_of_this_word = end_of_compressions;
454 }
455
456 if (end_of_this_word)
457 {
458 if (end_of_this_word == current_compression)
459 {
460 current_compression++;
461 }
462 else
463 {
464 std::string this_compression (current_compression, end_of_this_word - current_compression);
465 supported_compressions.push_back (this_compression);
466 current_compression = end_of_this_word + 1;
467 }
468 }
469 else
470 {
471 supported_compressions.push_back (current_compression);
472 current_compression = end_of_compressions;
473 }
474 }
475
476 if (supported_compressions.size() > 0)
477 {
478 MaybeEnableCompression (supported_compressions);
479 }
480 }
481 }
482
Greg Claytonb30c50c2015-05-29 00:01:55 +0000483 if (::strstr (response_cstr, "qEcho"))
484 m_supports_qEcho = eLazyBoolYes;
485 else
486 m_supports_qEcho = eLazyBoolNo;
487
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000488 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
489 if (packet_size_str)
490 {
491 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
492 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
493 if (m_max_packet_size == 0)
494 {
495 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
496 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
497 if (log)
498 log->Printf ("Garbled PacketSize spec in qSupported response");
499 }
500 }
501 }
502}
Greg Clayton576d8832011-03-22 04:00:09 +0000503
504bool
505GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
506{
507 if (m_supports_thread_suffix == eLazyBoolCalculate)
508 {
509 StringExtractorGDBRemote response;
510 m_supports_thread_suffix = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000511 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000512 {
513 if (response.IsOKResponse())
514 m_supports_thread_suffix = eLazyBoolYes;
515 }
516 }
517 return m_supports_thread_suffix;
518}
519bool
520GDBRemoteCommunicationClient::GetVContSupported (char flavor)
521{
522 if (m_supports_vCont_c == eLazyBoolCalculate)
523 {
524 StringExtractorGDBRemote response;
525 m_supports_vCont_any = eLazyBoolNo;
526 m_supports_vCont_all = eLazyBoolNo;
527 m_supports_vCont_c = eLazyBoolNo;
528 m_supports_vCont_C = eLazyBoolNo;
529 m_supports_vCont_s = eLazyBoolNo;
530 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000531 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000532 {
533 const char *response_cstr = response.GetStringRef().c_str();
534 if (::strstr (response_cstr, ";c"))
535 m_supports_vCont_c = eLazyBoolYes;
536
537 if (::strstr (response_cstr, ";C"))
538 m_supports_vCont_C = eLazyBoolYes;
539
540 if (::strstr (response_cstr, ";s"))
541 m_supports_vCont_s = eLazyBoolYes;
542
543 if (::strstr (response_cstr, ";S"))
544 m_supports_vCont_S = eLazyBoolYes;
545
546 if (m_supports_vCont_c == eLazyBoolYes &&
547 m_supports_vCont_C == eLazyBoolYes &&
548 m_supports_vCont_s == eLazyBoolYes &&
549 m_supports_vCont_S == eLazyBoolYes)
550 {
551 m_supports_vCont_all = eLazyBoolYes;
552 }
553
554 if (m_supports_vCont_c == eLazyBoolYes ||
555 m_supports_vCont_C == eLazyBoolYes ||
556 m_supports_vCont_s == eLazyBoolYes ||
557 m_supports_vCont_S == eLazyBoolYes)
558 {
559 m_supports_vCont_any = eLazyBoolYes;
560 }
561 }
562 }
563
564 switch (flavor)
565 {
566 case 'a': return m_supports_vCont_any;
567 case 'A': return m_supports_vCont_all;
568 case 'c': return m_supports_vCont_c;
569 case 'C': return m_supports_vCont_C;
570 case 's': return m_supports_vCont_s;
571 case 'S': return m_supports_vCont_S;
572 default: break;
573 }
574 return false;
575}
576
Pavel Labath4b6f9592016-08-18 08:30:03 +0000577GDBRemoteCommunication::PacketResult
578GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse(lldb::tid_t tid, StreamString &&payload,
579 StringExtractorGDBRemote &response,
580 bool send_async)
581{
582 Lock lock(*this, send_async);
583 if (!lock)
584 {
585 if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
586 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex for %s packet.", __FUNCTION__,
587 payload.GetString().c_str());
588 return PacketResult::ErrorNoSequenceLock;
589 }
590
591 if (GetThreadSuffixSupported())
592 payload.Printf(";thread:%4.4" PRIx64 ";", tid);
593 else
594 {
595 if (!SetCurrentThread(tid))
596 return PacketResult::ErrorSendFailed;
597 }
598
599 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response);
600}
601
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000602// Check if the target supports 'p' packet. It sends out a 'p'
603// packet and checks the response. A normal packet will tell us
604// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000605//
606// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000607bool
Sean Callananb1de1142013-09-04 23:24:15 +0000608GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000609{
610 if (m_supports_p == eLazyBoolCalculate)
611 {
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000612 m_supports_p = eLazyBoolNo;
Pavel Labath4b6f9592016-08-18 08:30:03 +0000613 StreamString payload;
614 payload.PutCString("p0");
615 StringExtractorGDBRemote response;
616 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, false) ==
617 PacketResult::Success &&
618 response.IsNormalResponse())
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000619 {
Pavel Labath4b6f9592016-08-18 08:30:03 +0000620 m_supports_p = eLazyBoolYes;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000621 }
622 }
623 return m_supports_p;
624}
Greg Clayton576d8832011-03-22 04:00:09 +0000625
Greg Clayton358cf1e2015-06-25 21:46:34 +0000626StructuredData::ObjectSP
627GDBRemoteCommunicationClient::GetThreadsInfo()
628{
629 // Get information on all threads at one using the "jThreadsInfo" packet
630 StructuredData::ObjectSP object_sp;
631
632 if (m_supports_jThreadsInfo)
633 {
634 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +0000635 response.SetResponseValidatorToJSON();
Greg Clayton358cf1e2015-06-25 21:46:34 +0000636 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) == PacketResult::Success)
637 {
638 if (response.IsUnsupportedResponse())
639 {
640 m_supports_jThreadsInfo = false;
641 }
642 else if (!response.Empty())
643 {
644 object_sp = StructuredData::ParseJSON (response.GetStringRef());
645 }
646 }
647 }
648 return object_sp;
649}
650
651
Jason Molendabdc4f122014-05-06 02:59:39 +0000652bool
Jason Molenda705b1802014-06-13 02:37:02 +0000653GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
654{
655 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
656 {
657 StringExtractorGDBRemote response;
658 m_supports_jThreadExtendedInfo = eLazyBoolNo;
659 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
660 {
661 if (response.IsOKResponse())
662 {
663 m_supports_jThreadExtendedInfo = eLazyBoolYes;
664 }
665 }
666 }
667 return m_supports_jThreadExtendedInfo;
668}
669
670bool
Jason Molenda20ee21b2015-07-10 23:15:22 +0000671GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported ()
672{
673 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate)
674 {
675 StringExtractorGDBRemote response;
676 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
677 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:", response, false) == PacketResult::Success)
678 {
679 if (response.IsOKResponse())
680 {
681 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
682 }
683 }
684 }
685 return m_supports_jLoadedDynamicLibrariesInfos;
686}
687
688bool
Jason Molenda37397352016-07-22 00:17:55 +0000689GDBRemoteCommunicationClient::GetSharedCacheInfoSupported ()
690{
691 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate)
692 {
693 StringExtractorGDBRemote response;
694 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
695 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) == PacketResult::Success)
696 {
697 if (response.IsOKResponse())
698 {
699 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
700 }
701 }
702 }
703 return m_supports_jGetSharedCacheInfo;
704}
705
706bool
Jason Molendabdc4f122014-05-06 02:59:39 +0000707GDBRemoteCommunicationClient::GetxPacketSupported ()
708{
709 if (m_supports_x == eLazyBoolCalculate)
710 {
711 StringExtractorGDBRemote response;
712 m_supports_x = eLazyBoolNo;
713 char packet[256];
714 snprintf (packet, sizeof (packet), "x0,0");
715 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
716 {
717 if (response.IsOKResponse())
718 m_supports_x = eLazyBoolYes;
719 }
720 }
721 return m_supports_x;
722}
723
Greg Clayton3dedae12013-12-06 21:45:27 +0000724GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000725GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
726(
727 const char *payload_prefix,
728 std::string &response_string
729)
730{
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000731 Lock lock(*this, false);
732 if (!lock)
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000733 {
734 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
735 if (log)
736 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
737 payload_prefix);
738 return PacketResult::ErrorNoSequenceLock;
739 }
740
741 response_string = "";
742 std::string payload_prefix_str(payload_prefix);
743 unsigned int response_size = 0x1000;
744 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
745 response_size = GetRemoteMaxPacketSize();
746 }
747
748 for (unsigned int offset = 0; true; offset += response_size)
749 {
750 StringExtractorGDBRemote this_response;
751 // Construct payload
752 char sizeDescriptor[128];
753 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +0000754 PacketResult result = SendPacketAndWaitForResponseNoLock(payload_prefix_str + sizeDescriptor, this_response);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000755 if (result != PacketResult::Success)
756 return result;
757
758 const std::string &this_string = this_response.GetStringRef();
759
760 // Check for m or l as first character; l seems to mean this is the last chunk
761 char first_char = *this_string.c_str();
762 if (first_char != 'm' && first_char != 'l')
763 {
764 return PacketResult::ErrorReplyInvalid;
765 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000766 // Concatenate the result so far (skipping 'm' or 'l')
767 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000768 if (first_char == 'l')
769 // We're done
770 return PacketResult::Success;
771 }
772}
773
Greg Clayton576d8832011-03-22 04:00:09 +0000774lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000775GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +0000776{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000777 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000778 return m_curr_pid;
779
780 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000781 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000782 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +0000783 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000784 // We really got it.
785 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +0000786 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000787 else
788 {
Todd Fialae24614f2014-05-14 00:15:32 +0000789 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
790 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
791 // The gdb remote protocol documents $qC as returning the thread id, which newer
792 // debugserver and lldb-gdbserver stubs return correctly.
793 StringExtractorGDBRemote response;
794 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000795 {
Todd Fialae24614f2014-05-14 00:15:32 +0000796 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000797 {
Todd Fialae24614f2014-05-14 00:15:32 +0000798 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000799 {
Todd Fialae24614f2014-05-14 00:15:32 +0000800 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
801 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000802 {
Todd Fialae24614f2014-05-14 00:15:32 +0000803 m_curr_pid_is_valid = eLazyBoolYes;
804 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000805 }
806 }
807 }
808 }
Jaydeep Patil1142f832015-08-13 03:46:36 +0000809
810 // If we don't get a response for $qC, check if $qfThreadID gives us a result.
811 if (m_curr_pid == LLDB_INVALID_PROCESS_ID)
812 {
813 std::vector<lldb::tid_t> thread_ids;
814 bool sequence_mutex_unavailable;
815 size_t size;
816 size = GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
817 if (size && sequence_mutex_unavailable == false)
818 {
819 m_curr_pid = thread_ids.front();
820 m_curr_pid_is_valid = eLazyBoolYes;
821 return m_curr_pid;
822 }
823 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000824 }
825
Greg Clayton576d8832011-03-22 04:00:09 +0000826 return LLDB_INVALID_PROCESS_ID;
827}
828
829bool
830GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
831{
832 error_str.clear();
833 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000834 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000835 {
836 if (response.IsOKResponse())
837 return true;
838 if (response.GetChar() == 'E')
839 {
840 // A string the describes what failed when launching...
841 error_str = response.GetStringRef().substr(1);
842 }
843 else
844 {
845 error_str.assign ("unknown error occurred launching process");
846 }
847 }
848 else
849 {
Jim Ingham98d6da52012-06-28 20:30:23 +0000850 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +0000851 }
852 return false;
853}
854
855int
Greg Claytonfbb76342013-11-20 21:07:01 +0000856GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +0000857{
Greg Claytonfbb76342013-11-20 21:07:01 +0000858 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000859 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +0000860 std::vector<const char *> argv;
861 FileSpec exe_file = launch_info.GetExecutableFile();
862 std::string exe_path;
863 const char *arg = NULL;
864 const Args &launch_args = launch_info.GetArguments();
865 if (exe_file)
Chaoren Lind3173f32015-05-29 19:52:29 +0000866 exe_path = exe_file.GetPath(false);
Greg Claytonfbb76342013-11-20 21:07:01 +0000867 else
868 {
869 arg = launch_args.GetArgumentAtIndex(0);
870 if (arg)
871 exe_path = arg;
872 }
873 if (!exe_path.empty())
874 {
875 argv.push_back(exe_path.c_str());
876 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
877 {
878 if (arg)
879 argv.push_back(arg);
880 }
881 }
882 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +0000883 {
884 StreamString packet;
885 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +0000886 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +0000887 {
Greg Claytonfbb76342013-11-20 21:07:01 +0000888 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +0000889 const int arg_len = strlen(arg);
890 if (i > 0)
891 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +0000892 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +0000893 packet.PutBytesAsRawHex8 (arg, arg_len);
894 }
895
896 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000897 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000898 {
899 if (response.IsOKResponse())
900 return 0;
901 uint8_t error = response.GetError();
902 if (error)
903 return error;
904 }
905 }
906 return -1;
907}
908
909int
910GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
911{
912 if (name_equal_value && name_equal_value[0])
913 {
914 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +0000915 bool send_hex_encoding = false;
916 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +0000917 {
Greg Clayton89600582013-10-10 17:53:50 +0000918 if (isprint(*p))
919 {
920 switch (*p)
921 {
922 case '$':
923 case '#':
Jason Molenda60bdafb2015-11-05 23:51:05 +0000924 case '*':
Tim Northover974ff612015-11-09 22:05:05 +0000925 case '}':
Greg Clayton89600582013-10-10 17:53:50 +0000926 send_hex_encoding = true;
927 break;
928 default:
929 break;
930 }
931 }
932 else
933 {
934 // We have non printable characters, lets hex encode this...
935 send_hex_encoding = true;
936 }
937 }
938
939 StringExtractorGDBRemote response;
940 if (send_hex_encoding)
941 {
942 if (m_supports_QEnvironmentHexEncoded)
943 {
944 packet.PutCString("QEnvironmentHexEncoded:");
945 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +0000946 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +0000947 {
948 if (response.IsOKResponse())
949 return 0;
950 uint8_t error = response.GetError();
951 if (error)
952 return error;
953 if (response.IsUnsupportedResponse())
954 m_supports_QEnvironmentHexEncoded = false;
955 }
956 }
957
958 }
959 else if (m_supports_QEnvironment)
960 {
961 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +0000962 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +0000963 {
964 if (response.IsOKResponse())
965 return 0;
966 uint8_t error = response.GetError();
967 if (error)
968 return error;
969 if (response.IsUnsupportedResponse())
970 m_supports_QEnvironment = false;
971 }
Greg Clayton576d8832011-03-22 04:00:09 +0000972 }
973 }
974 return -1;
975}
976
Greg Claytonc4103b32011-05-08 04:53:50 +0000977int
978GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
979{
980 if (arch && arch[0])
981 {
982 StreamString packet;
983 packet.Printf("QLaunchArch:%s", arch);
984 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000985 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +0000986 {
987 if (response.IsOKResponse())
988 return 0;
989 uint8_t error = response.GetError();
990 if (error)
991 return error;
992 }
993 }
994 return -1;
995}
996
Jason Molendaa3329782014-03-29 18:54:20 +0000997int
998GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
999{
1000 if (data && *data != '\0')
1001 {
1002 StreamString packet;
1003 packet.Printf("QSetProcessEvent:%s", data);
1004 StringExtractorGDBRemote response;
1005 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1006 {
1007 if (response.IsOKResponse())
1008 {
1009 if (was_supported)
1010 *was_supported = true;
1011 return 0;
1012 }
1013 else if (response.IsUnsupportedResponse())
1014 {
1015 if (was_supported)
1016 *was_supported = false;
1017 return -1;
1018 }
1019 else
1020 {
1021 uint8_t error = response.GetError();
1022 if (was_supported)
1023 *was_supported = true;
1024 if (error)
1025 return error;
1026 }
1027 }
1028 }
1029 return -1;
1030}
1031
Greg Clayton576d8832011-03-22 04:00:09 +00001032bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001033GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1034 uint32_t &minor,
1035 uint32_t &update)
1036{
1037 if (GetHostInfo ())
1038 {
1039 if (m_os_version_major != UINT32_MAX)
1040 {
1041 major = m_os_version_major;
1042 minor = m_os_version_minor;
1043 update = m_os_version_update;
1044 return true;
1045 }
1046 }
1047 return false;
1048}
1049
1050bool
1051GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1052{
1053 if (GetHostInfo ())
1054 {
1055 if (!m_os_build.empty())
1056 {
1057 s = m_os_build;
1058 return true;
1059 }
1060 }
1061 s.clear();
1062 return false;
1063}
1064
1065
1066bool
1067GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1068{
1069 if (GetHostInfo ())
1070 {
1071 if (!m_os_kernel.empty())
1072 {
1073 s = m_os_kernel;
1074 return true;
1075 }
1076 }
1077 s.clear();
1078 return false;
1079}
1080
1081bool
1082GDBRemoteCommunicationClient::GetHostname (std::string &s)
1083{
1084 if (GetHostInfo ())
1085 {
1086 if (!m_hostname.empty())
1087 {
1088 s = m_hostname;
1089 return true;
1090 }
1091 }
1092 s.clear();
1093 return false;
1094}
1095
1096ArchSpec
1097GDBRemoteCommunicationClient::GetSystemArchitecture ()
1098{
1099 if (GetHostInfo ())
1100 return m_host_arch;
1101 return ArchSpec();
1102}
1103
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001104const lldb_private::ArchSpec &
1105GDBRemoteCommunicationClient::GetProcessArchitecture ()
1106{
1107 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1108 GetCurrentProcessInfo ();
1109 return m_process_arch;
1110}
1111
Jason Molendaa3329782014-03-29 18:54:20 +00001112bool
1113GDBRemoteCommunicationClient::GetGDBServerVersion()
1114{
1115 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1116 {
1117 m_gdb_server_name.clear();
1118 m_gdb_server_version = 0;
1119 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1120
1121 StringExtractorGDBRemote response;
1122 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1123 {
1124 if (response.IsNormalResponse())
1125 {
1126 std::string name;
1127 std::string value;
1128 bool success = false;
1129 while (response.GetNameColonValue(name, value))
1130 {
1131 if (name.compare("name") == 0)
1132 {
1133 success = true;
1134 m_gdb_server_name.swap(value);
1135 }
1136 else if (name.compare("version") == 0)
1137 {
1138 size_t dot_pos = value.find('.');
1139 if (dot_pos != std::string::npos)
1140 value[dot_pos] = '\0';
Vince Harron5275aaa2015-01-15 20:08:35 +00001141 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molendaa3329782014-03-29 18:54:20 +00001142 if (version != UINT32_MAX)
1143 {
1144 success = true;
1145 m_gdb_server_version = version;
1146 }
1147 }
1148 }
1149 if (success)
1150 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1151 }
1152 }
1153 }
1154 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1155}
1156
Jason Molenda91ffe0a2015-06-18 21:46:06 +00001157void
1158GDBRemoteCommunicationClient::MaybeEnableCompression (std::vector<std::string> supported_compressions)
1159{
1160 CompressionType avail_type = CompressionType::None;
1161 std::string avail_name;
1162
1163#if defined (HAVE_LIBCOMPRESSION)
1164 // libcompression is weak linked so test if compression_decode_buffer() is available
1165 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1166 {
1167 for (auto compression : supported_compressions)
1168 {
1169 if (compression == "lzfse")
1170 {
1171 avail_type = CompressionType::LZFSE;
1172 avail_name = compression;
1173 break;
1174 }
1175 }
1176 }
1177#endif
1178
1179#if defined (HAVE_LIBCOMPRESSION)
1180 // libcompression is weak linked so test if compression_decode_buffer() is available
1181 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1182 {
1183 for (auto compression : supported_compressions)
1184 {
1185 if (compression == "zlib-deflate")
1186 {
1187 avail_type = CompressionType::ZlibDeflate;
1188 avail_name = compression;
1189 break;
1190 }
1191 }
1192 }
1193#endif
1194
1195#if defined (HAVE_LIBZ)
1196 if (avail_type == CompressionType::None)
1197 {
1198 for (auto compression : supported_compressions)
1199 {
1200 if (compression == "zlib-deflate")
1201 {
1202 avail_type = CompressionType::ZlibDeflate;
1203 avail_name = compression;
1204 break;
1205 }
1206 }
1207 }
1208#endif
1209
1210#if defined (HAVE_LIBCOMPRESSION)
1211 // libcompression is weak linked so test if compression_decode_buffer() is available
1212 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1213 {
1214 for (auto compression : supported_compressions)
1215 {
1216 if (compression == "lz4")
1217 {
1218 avail_type = CompressionType::LZ4;
1219 avail_name = compression;
1220 break;
1221 }
1222 }
1223 }
1224#endif
1225
1226#if defined (HAVE_LIBCOMPRESSION)
1227 // libcompression is weak linked so test if compression_decode_buffer() is available
1228 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1229 {
1230 for (auto compression : supported_compressions)
1231 {
1232 if (compression == "lzma")
1233 {
1234 avail_type = CompressionType::LZMA;
1235 avail_name = compression;
1236 break;
1237 }
1238 }
1239 }
1240#endif
1241
1242 if (avail_type != CompressionType::None)
1243 {
1244 StringExtractorGDBRemote response;
1245 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1246 if (SendPacketAndWaitForResponse (packet.c_str(), response, false) != PacketResult::Success)
1247 return;
1248
1249 if (response.IsOKResponse())
1250 {
1251 m_compression_type = avail_type;
1252 }
1253 }
1254}
1255
Jason Molendaa3329782014-03-29 18:54:20 +00001256const char *
1257GDBRemoteCommunicationClient::GetGDBServerProgramName()
1258{
1259 if (GetGDBServerVersion())
1260 {
1261 if (!m_gdb_server_name.empty())
1262 return m_gdb_server_name.c_str();
1263 }
1264 return NULL;
1265}
1266
1267uint32_t
1268GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1269{
1270 if (GetGDBServerVersion())
1271 return m_gdb_server_version;
1272 return 0;
1273}
Greg Clayton1cb64962011-03-24 04:28:38 +00001274
1275bool
Ewan Crawford78baa192015-05-13 09:18:18 +00001276GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1277{
1278 StringExtractorGDBRemote response;
1279 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1280 return false;
1281
1282 if (!response.IsNormalResponse())
1283 return false;
1284
1285 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1286 tid = response.GetHexMaxU32(true, -1);
1287
1288 return true;
1289}
1290
1291bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001292GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001293{
Todd Fialaaf245d12014-06-30 21:05:18 +00001294 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1295
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001296 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001297 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001298 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001299 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001300 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001301 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001302 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001303 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001304 std::string name;
1305 std::string value;
1306 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1307 uint32_t sub = 0;
1308 std::string arch_name;
1309 std::string os_name;
1310 std::string vendor_name;
1311 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001312 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001313 uint32_t pointer_byte_size = 0;
1314 StringExtractor extractor;
1315 ByteOrder byte_order = eByteOrderInvalid;
1316 uint32_t num_keys_decoded = 0;
1317 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001318 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001319 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001320 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001321 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001322 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001323 if (cpu != LLDB_INVALID_CPUTYPE)
1324 ++num_keys_decoded;
1325 }
1326 else if (name.compare("cpusubtype") == 0)
1327 {
1328 // exception count in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001329 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001330 if (sub != 0)
1331 ++num_keys_decoded;
1332 }
1333 else if (name.compare("arch") == 0)
1334 {
1335 arch_name.swap (value);
1336 ++num_keys_decoded;
1337 }
1338 else if (name.compare("triple") == 0)
1339 {
Greg Clayton44272a42014-09-18 00:18:32 +00001340 extractor.GetStringRef ().swap (value);
1341 extractor.SetFilePos(0);
1342 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00001343 ++num_keys_decoded;
1344 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001345 else if (name.compare ("distribution_id") == 0)
1346 {
1347 extractor.GetStringRef ().swap (value);
1348 extractor.SetFilePos (0);
1349 extractor.GetHexByteString (distribution_id);
1350 ++num_keys_decoded;
1351 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001352 else if (name.compare("os_build") == 0)
1353 {
1354 extractor.GetStringRef().swap(value);
1355 extractor.SetFilePos(0);
1356 extractor.GetHexByteString (m_os_build);
1357 ++num_keys_decoded;
1358 }
1359 else if (name.compare("hostname") == 0)
1360 {
1361 extractor.GetStringRef().swap(value);
1362 extractor.SetFilePos(0);
1363 extractor.GetHexByteString (m_hostname);
1364 ++num_keys_decoded;
1365 }
1366 else if (name.compare("os_kernel") == 0)
1367 {
1368 extractor.GetStringRef().swap(value);
1369 extractor.SetFilePos(0);
1370 extractor.GetHexByteString (m_os_kernel);
1371 ++num_keys_decoded;
1372 }
1373 else if (name.compare("ostype") == 0)
1374 {
1375 os_name.swap (value);
1376 ++num_keys_decoded;
1377 }
1378 else if (name.compare("vendor") == 0)
1379 {
1380 vendor_name.swap(value);
1381 ++num_keys_decoded;
1382 }
1383 else if (name.compare("endian") == 0)
1384 {
1385 ++num_keys_decoded;
1386 if (value.compare("little") == 0)
1387 byte_order = eByteOrderLittle;
1388 else if (value.compare("big") == 0)
1389 byte_order = eByteOrderBig;
1390 else if (value.compare("pdp") == 0)
1391 byte_order = eByteOrderPDP;
1392 else
1393 --num_keys_decoded;
1394 }
1395 else if (name.compare("ptrsize") == 0)
1396 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001397 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001398 if (pointer_byte_size != 0)
1399 ++num_keys_decoded;
1400 }
Greg Clayton17499dd2016-01-28 00:16:11 +00001401 else if ((name.compare("os_version") == 0) ||
1402 (name.compare("version") == 0)) // Older debugserver binaries used the "version" key instead of "os_version"...
Greg Clayton32e0a752011-03-30 18:16:51 +00001403 {
1404 Args::StringToVersion (value.c_str(),
1405 m_os_version_major,
1406 m_os_version_minor,
1407 m_os_version_update);
1408 if (m_os_version_major != UINT32_MAX)
1409 ++num_keys_decoded;
1410 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001411 else if (name.compare("watchpoint_exceptions_received") == 0)
1412 {
1413 ++num_keys_decoded;
1414 if (strcmp(value.c_str(),"before") == 0)
1415 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1416 else if (strcmp(value.c_str(),"after") == 0)
1417 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1418 else
1419 --num_keys_decoded;
1420 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001421 else if (name.compare("default_packet_timeout") == 0)
1422 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001423 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001424 if (m_default_packet_timeout > 0)
1425 {
1426 SetPacketTimeout(m_default_packet_timeout);
1427 ++num_keys_decoded;
1428 }
1429 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001430
Greg Clayton32e0a752011-03-30 18:16:51 +00001431 }
1432
1433 if (num_keys_decoded > 0)
1434 m_qHostInfo_is_valid = eLazyBoolYes;
1435
1436 if (triple.empty())
1437 {
1438 if (arch_name.empty())
1439 {
1440 if (cpu != LLDB_INVALID_CPUTYPE)
1441 {
1442 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1443 if (pointer_byte_size)
1444 {
1445 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1446 }
1447 if (byte_order != eByteOrderInvalid)
1448 {
1449 assert (byte_order == m_host_arch.GetByteOrder());
1450 }
Greg Clayton70512312012-05-08 01:45:38 +00001451
Greg Clayton32e0a752011-03-30 18:16:51 +00001452 if (!vendor_name.empty())
1453 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1454 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001455 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001456
1457 }
1458 }
1459 else
1460 {
1461 std::string triple;
1462 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001463 if (!vendor_name.empty() || !os_name.empty())
1464 {
1465 triple += '-';
1466 if (vendor_name.empty())
1467 triple += "unknown";
1468 else
1469 triple += vendor_name;
1470 triple += '-';
1471 if (os_name.empty())
1472 triple += "unknown";
1473 else
1474 triple += os_name;
1475 }
1476 m_host_arch.SetTriple (triple.c_str());
1477
1478 llvm::Triple &host_triple = m_host_arch.GetTriple();
1479 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1480 {
1481 switch (m_host_arch.GetMachine())
1482 {
Todd Fialad8eaa172014-07-23 14:37:35 +00001483 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00001484 case llvm::Triple::arm:
1485 case llvm::Triple::thumb:
1486 host_triple.setOS(llvm::Triple::IOS);
1487 break;
1488 default:
1489 host_triple.setOS(llvm::Triple::MacOSX);
1490 break;
1491 }
1492 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001493 if (pointer_byte_size)
1494 {
1495 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1496 }
1497 if (byte_order != eByteOrderInvalid)
1498 {
1499 assert (byte_order == m_host_arch.GetByteOrder());
1500 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001501
Greg Clayton1cb64962011-03-24 04:28:38 +00001502 }
1503 }
1504 else
1505 {
Greg Clayton70512312012-05-08 01:45:38 +00001506 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001507 if (pointer_byte_size)
1508 {
1509 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1510 }
1511 if (byte_order != eByteOrderInvalid)
1512 {
1513 assert (byte_order == m_host_arch.GetByteOrder());
1514 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001515
1516 if (log)
1517 log->Printf ("GDBRemoteCommunicationClient::%s parsed host architecture as %s, triple as %s from triple text %s", __FUNCTION__, m_host_arch.GetArchitectureName () ? m_host_arch.GetArchitectureName () : "<null-arch-name>", m_host_arch.GetTriple ().getTriple ().c_str(), triple.c_str ());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001518 }
1519 if (!distribution_id.empty ())
1520 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00001521 }
Greg Clayton576d8832011-03-22 04:00:09 +00001522 }
1523 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001524 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001525}
1526
1527int
1528GDBRemoteCommunicationClient::SendAttach
1529(
1530 lldb::pid_t pid,
1531 StringExtractorGDBRemote& response
1532)
1533{
1534 if (pid != LLDB_INVALID_PROCESS_ID)
1535 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001536 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001537 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001538 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00001539 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001540 {
1541 if (response.IsErrorResponse())
1542 return response.GetError();
1543 return 0;
1544 }
1545 }
1546 return -1;
1547}
1548
Vince Harrone0be4252015-02-06 18:32:57 +00001549int
1550GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
1551{
1552 StreamString packet;
1553 packet.PutCString("I");
1554 packet.PutBytesAsRawHex8(data, data_len);
1555 StringExtractorGDBRemote response;
1556 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1557 {
1558 return 0;
1559 }
1560 return response.GetError();
1561
1562}
1563
Greg Clayton576d8832011-03-22 04:00:09 +00001564const lldb_private::ArchSpec &
1565GDBRemoteCommunicationClient::GetHostArchitecture ()
1566{
Greg Clayton32e0a752011-03-30 18:16:51 +00001567 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001568 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001569 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001570}
1571
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001572uint32_t
1573GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1574{
1575 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1576 GetHostInfo ();
1577 return m_default_packet_timeout;
1578}
1579
Greg Clayton576d8832011-03-22 04:00:09 +00001580addr_t
1581GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1582{
Greg Clayton70b57652011-05-15 01:25:55 +00001583 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001584 {
Greg Clayton70b57652011-05-15 01:25:55 +00001585 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001586 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001587 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001588 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001589 permissions & lldb::ePermissionsReadable ? "r" : "",
1590 permissions & lldb::ePermissionsWritable ? "w" : "",
1591 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001592 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001593 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001594 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001595 {
Todd Fialaf105f582014-06-21 00:48:09 +00001596 if (response.IsUnsupportedResponse())
1597 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1598 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001599 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1600 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001601 else
1602 {
1603 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1604 }
Greg Clayton576d8832011-03-22 04:00:09 +00001605 }
1606 return LLDB_INVALID_ADDRESS;
1607}
1608
1609bool
1610GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1611{
Greg Clayton70b57652011-05-15 01:25:55 +00001612 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001613 {
Greg Clayton70b57652011-05-15 01:25:55 +00001614 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001615 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001616 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001617 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001618 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001619 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001620 {
Todd Fialaf105f582014-06-21 00:48:09 +00001621 if (response.IsUnsupportedResponse())
1622 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1623 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001624 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001625 }
1626 else
1627 {
1628 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00001629 }
Greg Clayton576d8832011-03-22 04:00:09 +00001630 }
1631 return false;
1632}
1633
Jim Inghamacff8952013-05-02 00:27:30 +00001634Error
1635GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00001636{
Jim Inghamacff8952013-05-02 00:27:30 +00001637 Error error;
1638
1639 if (keep_stopped)
1640 {
1641 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1642 {
1643 char packet[64];
1644 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001645 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00001646 StringExtractorGDBRemote response;
Jim Ingham4920a4e2015-07-15 00:59:25 +00001647 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success
1648 && response.IsOKResponse())
Jim Inghamacff8952013-05-02 00:27:30 +00001649 {
1650 m_supports_detach_stay_stopped = eLazyBoolYes;
1651 }
1652 else
1653 {
1654 m_supports_detach_stay_stopped = eLazyBoolNo;
1655 }
1656 }
1657
1658 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1659 {
1660 error.SetErrorString("Stays stopped not supported by this target.");
1661 return error;
1662 }
1663 else
1664 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00001665 StringExtractorGDBRemote response;
Jason Molenda2a667382015-07-15 00:16:09 +00001666 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 2, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00001667 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001668 error.SetErrorString ("Sending extended disconnect packet failed.");
1669 }
1670 }
1671 else
1672 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00001673 StringExtractorGDBRemote response;
1674 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00001675 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001676 error.SetErrorString ("Sending disconnect packet failed.");
1677 }
1678 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001679}
1680
Greg Clayton46fb5582011-11-18 07:03:08 +00001681Error
1682GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1683 lldb_private::MemoryRegionInfo &region_info)
1684{
1685 Error error;
1686 region_info.Clear();
1687
1688 if (m_supports_memory_region_info != eLazyBoolNo)
1689 {
1690 m_supports_memory_region_info = eLazyBoolYes;
1691 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001692 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001693 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00001694 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001695 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00001696 {
1697 std::string name;
1698 std::string value;
1699 addr_t addr_value;
1700 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00001701 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00001702 while (success && response.GetNameColonValue(name, value))
1703 {
1704 if (name.compare ("start") == 0)
1705 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001706 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00001707 if (success)
1708 region_info.GetRange().SetRangeBase(addr_value);
1709 }
1710 else if (name.compare ("size") == 0)
1711 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001712 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00001713 if (success)
1714 region_info.GetRange().SetByteSize (addr_value);
1715 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001716 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00001717 {
Jason Molendacb349ee2011-12-13 05:39:38 +00001718 saw_permissions = true;
1719 if (region_info.GetRange().Contains (addr))
1720 {
1721 if (value.find('r') != std::string::npos)
1722 region_info.SetReadable (MemoryRegionInfo::eYes);
1723 else
1724 region_info.SetReadable (MemoryRegionInfo::eNo);
1725
1726 if (value.find('w') != std::string::npos)
1727 region_info.SetWritable (MemoryRegionInfo::eYes);
1728 else
1729 region_info.SetWritable (MemoryRegionInfo::eNo);
1730
1731 if (value.find('x') != std::string::npos)
1732 region_info.SetExecutable (MemoryRegionInfo::eYes);
1733 else
1734 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00001735
1736 region_info.SetMapped(MemoryRegionInfo::eYes);
Jason Molendacb349ee2011-12-13 05:39:38 +00001737 }
1738 else
1739 {
1740 // The reported region does not contain this address -- we're looking at an unmapped page
1741 region_info.SetReadable (MemoryRegionInfo::eNo);
1742 region_info.SetWritable (MemoryRegionInfo::eNo);
1743 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00001744 region_info.SetMapped(MemoryRegionInfo::eNo);
Jason Molendacb349ee2011-12-13 05:39:38 +00001745 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001746 }
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001747 else if (name.compare ("name") == 0)
1748 {
1749 StringExtractorGDBRemote name_extractor;
1750 name_extractor.GetStringRef().swap(value);
1751 name_extractor.GetHexByteString(value);
1752 region_info.SetName(value.c_str());
1753 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001754 else if (name.compare ("error") == 0)
1755 {
1756 StringExtractorGDBRemote name_extractor;
1757 // Swap "value" over into "name_extractor"
1758 name_extractor.GetStringRef().swap(value);
1759 // Now convert the HEX bytes into a string value
1760 name_extractor.GetHexByteString (value);
1761 error.SetErrorString(value.c_str());
1762 }
1763 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001764
1765 // We got a valid address range back but no permissions -- which means this is an unmapped page
1766 if (region_info.GetRange().IsValid() && saw_permissions == false)
1767 {
1768 region_info.SetReadable (MemoryRegionInfo::eNo);
1769 region_info.SetWritable (MemoryRegionInfo::eNo);
1770 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00001771 region_info.SetMapped(MemoryRegionInfo::eNo);
Jason Molendacb349ee2011-12-13 05:39:38 +00001772 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001773 }
1774 else
1775 {
1776 m_supports_memory_region_info = eLazyBoolNo;
1777 }
1778 }
1779
1780 if (m_supports_memory_region_info == eLazyBoolNo)
1781 {
1782 error.SetErrorString("qMemoryRegionInfo is not supported");
1783 }
1784 if (error.Fail())
1785 region_info.Clear();
1786 return error;
1787
1788}
1789
Johnny Chen64637202012-05-23 21:09:52 +00001790Error
1791GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1792{
1793 Error error;
1794
1795 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1796 {
1797 num = m_num_supported_hardware_watchpoints;
1798 return error;
1799 }
1800
1801 // Set num to 0 first.
1802 num = 0;
1803 if (m_supports_watchpoint_support_info != eLazyBoolNo)
1804 {
1805 char packet[64];
1806 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001807 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00001808 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001809 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00001810 {
1811 m_supports_watchpoint_support_info = eLazyBoolYes;
1812 std::string name;
1813 std::string value;
1814 while (response.GetNameColonValue(name, value))
1815 {
1816 if (name.compare ("num") == 0)
1817 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001818 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
Johnny Chen64637202012-05-23 21:09:52 +00001819 m_num_supported_hardware_watchpoints = num;
1820 }
1821 }
1822 }
1823 else
1824 {
1825 m_supports_watchpoint_support_info = eLazyBoolNo;
1826 }
1827 }
1828
1829 if (m_supports_watchpoint_support_info == eLazyBoolNo)
1830 {
1831 error.SetErrorString("qWatchpointSupportInfo is not supported");
1832 }
1833 return error;
1834
1835}
Greg Clayton46fb5582011-11-18 07:03:08 +00001836
Enrico Granataf04a2192012-07-13 23:18:48 +00001837lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00001838GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00001839{
1840 Error error(GetWatchpointSupportInfo(num));
1841 if (error.Success())
Jaydeep Patil725666c2015-08-13 03:46:01 +00001842 error = GetWatchpointsTriggerAfterInstruction(after, arch);
Enrico Granataf04a2192012-07-13 23:18:48 +00001843 return error;
1844}
1845
1846lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00001847GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00001848{
1849 Error error;
Jaydeep Patil725666c2015-08-13 03:46:01 +00001850 llvm::Triple::ArchType atype = arch.GetMachine();
Enrico Granataf04a2192012-07-13 23:18:48 +00001851
1852 // we assume watchpoints will happen after running the relevant opcode
1853 // and we only want to override this behavior if we have explicitly
1854 // received a qHostInfo telling us otherwise
1855 if (m_qHostInfo_is_valid != eLazyBoolYes)
Jaydeep Patil725666c2015-08-13 03:46:01 +00001856 {
1857 // On targets like MIPS, watchpoint exceptions are always generated
1858 // before the instruction is executed. The connected target may not
1859 // support qHostInfo or qWatchpointSupportInfo packets.
1860 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
1861 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
1862 after = false;
1863 else
1864 after = true;
1865 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001866 else
Jaydeep Patil725666c2015-08-13 03:46:01 +00001867 {
1868 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
1869 // if it is not calculated before.
1870 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1871 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
1872 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
1873 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1874
Enrico Granataf04a2192012-07-13 23:18:48 +00001875 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
Jaydeep Patil725666c2015-08-13 03:46:01 +00001876 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001877 return error;
1878}
1879
Greg Clayton576d8832011-03-22 04:00:09 +00001880int
Chaoren Lind3173f32015-05-29 19:52:29 +00001881GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001882{
Chaoren Lind3173f32015-05-29 19:52:29 +00001883 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001884 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001885 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001886 StreamString packet;
1887 packet.PutCString("QSetSTDIN:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001888 packet.PutCStringAsRawHex8(path.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00001889
1890 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001891 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001892 {
1893 if (response.IsOKResponse())
1894 return 0;
1895 uint8_t error = response.GetError();
1896 if (error)
1897 return error;
1898 }
1899 }
1900 return -1;
1901}
1902
1903int
Chaoren Lind3173f32015-05-29 19:52:29 +00001904GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001905{
Chaoren Lind3173f32015-05-29 19:52:29 +00001906 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001907 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001908 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001909 StreamString packet;
1910 packet.PutCString("QSetSTDOUT:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001911 packet.PutCStringAsRawHex8(path.c_str());
1912
Greg Clayton576d8832011-03-22 04:00:09 +00001913 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001914 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001915 {
1916 if (response.IsOKResponse())
1917 return 0;
1918 uint8_t error = response.GetError();
1919 if (error)
1920 return error;
1921 }
1922 }
1923 return -1;
1924}
1925
1926int
Chaoren Lind3173f32015-05-29 19:52:29 +00001927GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001928{
Chaoren Lind3173f32015-05-29 19:52:29 +00001929 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001930 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001931 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001932 StreamString packet;
1933 packet.PutCString("QSetSTDERR:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001934 packet.PutCStringAsRawHex8(path.c_str());
1935
Greg Clayton576d8832011-03-22 04:00:09 +00001936 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001937 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001938 {
1939 if (response.IsOKResponse())
1940 return 0;
1941 uint8_t error = response.GetError();
1942 if (error)
1943 return error;
1944 }
1945 }
1946 return -1;
1947}
1948
Greg Claytonfbb76342013-11-20 21:07:01 +00001949bool
Chaoren Lind3173f32015-05-29 19:52:29 +00001950GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
Greg Claytonfbb76342013-11-20 21:07:01 +00001951{
1952 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001953 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00001954 {
1955 if (response.IsUnsupportedResponse())
1956 return false;
1957 if (response.IsErrorResponse())
1958 return false;
Chaoren Lind3173f32015-05-29 19:52:29 +00001959 std::string cwd;
1960 response.GetHexByteString(cwd);
Chaoren Lin44145d72015-05-29 19:52:37 +00001961 working_dir.SetFile(cwd, false, GetHostArchitecture());
Greg Claytonfbb76342013-11-20 21:07:01 +00001962 return !cwd.empty();
1963 }
1964 return false;
1965}
1966
Greg Clayton576d8832011-03-22 04:00:09 +00001967int
Chaoren Lind3173f32015-05-29 19:52:29 +00001968GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00001969{
Chaoren Lind3173f32015-05-29 19:52:29 +00001970 if (working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00001971 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001972 std::string path{working_dir.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001973 StreamString packet;
1974 packet.PutCString("QSetWorkingDir:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001975 packet.PutCStringAsRawHex8(path.c_str());
1976
Greg Clayton576d8832011-03-22 04:00:09 +00001977 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001978 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001979 {
1980 if (response.IsOKResponse())
1981 return 0;
1982 uint8_t error = response.GetError();
1983 if (error)
1984 return error;
1985 }
1986 }
1987 return -1;
1988}
1989
1990int
1991GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1992{
Greg Clayton32e0a752011-03-30 18:16:51 +00001993 char packet[32];
1994 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00001995 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00001996 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001997 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001998 {
1999 if (response.IsOKResponse())
2000 return 0;
2001 uint8_t error = response.GetError();
2002 if (error)
2003 return error;
2004 }
2005 return -1;
2006}
Greg Clayton32e0a752011-03-30 18:16:51 +00002007
Jim Ingham106d0282014-06-25 02:32:56 +00002008int
2009GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2010{
2011 char packet[32];
2012 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2013 assert (packet_len < (int)sizeof(packet));
2014 StringExtractorGDBRemote response;
2015 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2016 {
2017 if (response.IsOKResponse())
2018 return 0;
2019 uint8_t error = response.GetError();
2020 if (error)
2021 return error;
2022 }
2023 return -1;
2024}
2025
2026
Greg Clayton32e0a752011-03-30 18:16:51 +00002027bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002028GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002029{
2030 if (response.IsNormalResponse())
2031 {
2032 std::string name;
2033 std::string value;
2034 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002035
2036 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2037 uint32_t sub = 0;
2038 std::string vendor;
2039 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002040
2041 while (response.GetNameColonValue(name, value))
2042 {
2043 if (name.compare("pid") == 0)
2044 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002045 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002046 }
2047 else if (name.compare("ppid") == 0)
2048 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002049 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002050 }
2051 else if (name.compare("uid") == 0)
2052 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002053 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002054 }
2055 else if (name.compare("euid") == 0)
2056 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002057 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002058 }
2059 else if (name.compare("gid") == 0)
2060 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002061 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002062 }
2063 else if (name.compare("egid") == 0)
2064 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002065 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002066 }
2067 else if (name.compare("triple") == 0)
2068 {
Greg Clayton44272a42014-09-18 00:18:32 +00002069 StringExtractor extractor;
2070 extractor.GetStringRef().swap(value);
2071 extractor.SetFilePos(0);
2072 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002073 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002074 }
2075 else if (name.compare("name") == 0)
2076 {
2077 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002078 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002079 // control the characters in a process name
2080 extractor.GetStringRef().swap(value);
2081 extractor.SetFilePos(0);
2082 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002083 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002084 }
Jason Molenda89c37492014-01-27 22:23:20 +00002085 else if (name.compare("cputype") == 0)
2086 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002087 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002088 }
2089 else if (name.compare("cpusubtype") == 0)
2090 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002091 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002092 }
2093 else if (name.compare("vendor") == 0)
2094 {
2095 vendor = value;
2096 }
2097 else if (name.compare("ostype") == 0)
2098 {
2099 os_type = value;
2100 }
2101 }
2102
2103 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2104 {
2105 if (vendor == "apple")
2106 {
2107 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2108 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2109 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2110 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002111 }
2112
2113 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2114 return true;
2115 }
2116 return false;
2117}
2118
2119bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002120GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002121{
2122 process_info.Clear();
2123
2124 if (m_supports_qProcessInfoPID)
2125 {
2126 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002127 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002128 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002129 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002130 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002131 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002132 return DecodeProcessInfoResponse (response, process_info);
2133 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002134 else
2135 {
2136 m_supports_qProcessInfoPID = false;
2137 return false;
2138 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002139 }
2140 return false;
2141}
2142
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002143bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002144GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002145{
Todd Fiala3daa1762014-09-15 16:01:29 +00002146 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2147
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002148 if (allow_lazy)
2149 {
2150 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2151 return true;
2152 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2153 return false;
2154 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002155
2156 GetHostInfo ();
2157
2158 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002159 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002160 {
2161 if (response.IsNormalResponse())
2162 {
2163 std::string name;
2164 std::string value;
2165 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2166 uint32_t sub = 0;
2167 std::string arch_name;
2168 std::string os_name;
2169 std::string vendor_name;
2170 std::string triple;
2171 uint32_t pointer_byte_size = 0;
2172 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002173 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002174 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002175 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002176 while (response.GetNameColonValue(name, value))
2177 {
2178 if (name.compare("cputype") == 0)
2179 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002180 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002181 if (cpu != LLDB_INVALID_CPUTYPE)
2182 ++num_keys_decoded;
2183 }
2184 else if (name.compare("cpusubtype") == 0)
2185 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002186 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002187 if (sub != 0)
2188 ++num_keys_decoded;
2189 }
Todd Fialac540dd02014-08-26 18:21:02 +00002190 else if (name.compare("triple") == 0)
2191 {
Greg Clayton44272a42014-09-18 00:18:32 +00002192 StringExtractor extractor;
2193 extractor.GetStringRef().swap(value);
2194 extractor.SetFilePos(0);
2195 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002196 ++num_keys_decoded;
2197 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002198 else if (name.compare("ostype") == 0)
2199 {
2200 os_name.swap (value);
2201 ++num_keys_decoded;
2202 }
2203 else if (name.compare("vendor") == 0)
2204 {
2205 vendor_name.swap(value);
2206 ++num_keys_decoded;
2207 }
2208 else if (name.compare("endian") == 0)
2209 {
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002210 ++num_keys_decoded;
2211 if (value.compare("little") == 0)
2212 byte_order = eByteOrderLittle;
2213 else if (value.compare("big") == 0)
2214 byte_order = eByteOrderBig;
2215 else if (value.compare("pdp") == 0)
2216 byte_order = eByteOrderPDP;
2217 else
2218 --num_keys_decoded;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002219 }
2220 else if (name.compare("ptrsize") == 0)
2221 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002222 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002223 if (pointer_byte_size != 0)
2224 ++num_keys_decoded;
2225 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002226 else if (name.compare("pid") == 0)
2227 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002228 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002229 if (pid != LLDB_INVALID_PROCESS_ID)
2230 ++num_keys_decoded;
2231 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002232 }
2233 if (num_keys_decoded > 0)
2234 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002235 if (pid != LLDB_INVALID_PROCESS_ID)
2236 {
2237 m_curr_pid_is_valid = eLazyBoolYes;
2238 m_curr_pid = pid;
2239 }
Todd Fialac540dd02014-08-26 18:21:02 +00002240
2241 // Set the ArchSpec from the triple if we have it.
2242 if (!triple.empty ())
2243 {
2244 m_process_arch.SetTriple (triple.c_str ());
2245 if (pointer_byte_size)
2246 {
2247 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2248 }
2249 }
2250 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002251 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002252 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2253
2254 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2255 switch (triple.getObjectFormat()) {
2256 case llvm::Triple::MachO:
2257 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2258 break;
2259 case llvm::Triple::ELF:
2260 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2261 break;
2262 case llvm::Triple::COFF:
2263 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2264 break;
2265 case llvm::Triple::UnknownObjectFormat:
2266 if (log)
2267 log->Printf("error: failed to determine target architecture");
2268 return false;
2269 }
2270
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002271 if (pointer_byte_size)
2272 {
2273 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2274 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002275 if (byte_order != eByteOrderInvalid)
2276 {
2277 assert (byte_order == m_process_arch.GetByteOrder());
2278 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002279 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002280 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002281 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2282 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002283 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002284 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002285 }
2286 }
2287 else
2288 {
2289 m_qProcessInfo_is_valid = eLazyBoolNo;
2290 }
2291
2292 return false;
2293}
2294
2295
Greg Clayton32e0a752011-03-30 18:16:51 +00002296uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002297GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2298 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002299{
2300 process_infos.Clear();
2301
2302 if (m_supports_qfProcessInfo)
2303 {
2304 StreamString packet;
2305 packet.PutCString ("qfProcessInfo");
2306 if (!match_info.MatchAllProcesses())
2307 {
2308 packet.PutChar (':');
2309 const char *name = match_info.GetProcessInfo().GetName();
2310 bool has_name_match = false;
2311 if (name && name[0])
2312 {
2313 has_name_match = true;
2314 NameMatchType name_match_type = match_info.GetNameMatchType();
2315 switch (name_match_type)
2316 {
2317 case eNameMatchIgnore:
2318 has_name_match = false;
2319 break;
2320
2321 case eNameMatchEquals:
2322 packet.PutCString ("name_match:equals;");
2323 break;
2324
2325 case eNameMatchContains:
2326 packet.PutCString ("name_match:contains;");
2327 break;
2328
2329 case eNameMatchStartsWith:
2330 packet.PutCString ("name_match:starts_with;");
2331 break;
2332
2333 case eNameMatchEndsWith:
2334 packet.PutCString ("name_match:ends_with;");
2335 break;
2336
2337 case eNameMatchRegularExpression:
2338 packet.PutCString ("name_match:regex;");
2339 break;
2340 }
2341 if (has_name_match)
2342 {
2343 packet.PutCString ("name:");
2344 packet.PutBytesAsRawHex8(name, ::strlen(name));
2345 packet.PutChar (';');
2346 }
2347 }
2348
2349 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002350 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002351 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002352 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002353 if (match_info.GetProcessInfo().UserIDIsValid())
2354 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2355 if (match_info.GetProcessInfo().GroupIDIsValid())
2356 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002357 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2358 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2359 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2360 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2361 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2362 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2363 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2364 {
2365 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2366 const llvm::Triple &triple = match_arch.GetTriple();
2367 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00002368 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002369 packet.PutChar (';');
2370 }
2371 }
2372 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00002373 // Increase timeout as the first qfProcessInfo packet takes a long time
2374 // on Android. The value of 1min was arrived at empirically.
2375 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00002376 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002377 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002378 do
2379 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002380 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002381 if (!DecodeProcessInfoResponse (response, process_info))
2382 break;
2383 process_infos.Append(process_info);
2384 response.GetStringRef().clear();
2385 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00002386 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00002387 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002388 else
2389 {
2390 m_supports_qfProcessInfo = false;
2391 return 0;
2392 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002393 }
2394 return process_infos.GetSize();
2395
2396}
2397
2398bool
2399GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2400{
2401 if (m_supports_qUserName)
2402 {
2403 char packet[32];
2404 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002405 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002406 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002407 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002408 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002409 if (response.IsNormalResponse())
2410 {
2411 // Make sure we parsed the right number of characters. The response is
2412 // the hex encoded user name and should make up the entire packet.
2413 // If there are any non-hex ASCII bytes, the length won't match below..
2414 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2415 return true;
2416 }
2417 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002418 else
2419 {
2420 m_supports_qUserName = false;
2421 return false;
2422 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002423 }
2424 return false;
2425
2426}
2427
2428bool
2429GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2430{
2431 if (m_supports_qGroupName)
2432 {
2433 char packet[32];
2434 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002435 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002436 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002437 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002438 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002439 if (response.IsNormalResponse())
2440 {
2441 // Make sure we parsed the right number of characters. The response is
2442 // the hex encoded group name and should make up the entire packet.
2443 // If there are any non-hex ASCII bytes, the length won't match below..
2444 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2445 return true;
2446 }
2447 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002448 else
2449 {
2450 m_supports_qGroupName = false;
2451 return false;
2452 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002453 }
2454 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002455}
Greg Clayton32e0a752011-03-30 18:16:51 +00002456
Ewan Crawford78baa192015-05-13 09:18:18 +00002457bool
2458GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
2459{
2460 // Form non-stop packet request
2461 char packet[32];
2462 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2463 assert(packet_len < (int)sizeof(packet));
2464
2465 StringExtractorGDBRemote response;
2466 // Send to target
2467 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2468 if (response.IsOKResponse())
2469 return true;
2470
2471 // Failed or not supported
2472 return false;
2473
2474}
2475
Greg Claytone034a042015-05-21 20:52:06 +00002476static void
2477MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
2478{
2479 packet.Clear();
2480 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2481 uint32_t bytes_left = send_size;
2482 while (bytes_left > 0)
2483 {
2484 if (bytes_left >= 26)
2485 {
2486 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2487 bytes_left -= 26;
2488 }
2489 else
2490 {
2491 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2492 bytes_left = 0;
2493 }
2494 }
2495}
2496
2497template<typename T>
2498T calculate_standard_deviation(const std::vector<T> &v)
2499{
2500 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
2501 T mean = sum / (T)v.size();
2502 T accum = T(0);
2503 std::for_each (std::begin(v), std::end(v), [&](const T d) {
2504 T delta = d - mean;
2505 accum += delta * delta;
2506 });
2507
2508 T stdev = sqrt(accum / (v.size()-1));
2509 return stdev;
2510}
2511
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002512void
Greg Claytone034a042015-05-21 20:52:06 +00002513GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets, uint32_t max_send, uint32_t max_recv, bool json, Stream &strm)
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002514{
2515 uint32_t i;
2516 TimeValue start_time, end_time;
2517 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002518 if (SendSpeedTestPacket (0, 0))
2519 {
Greg Claytone034a042015-05-21 20:52:06 +00002520 StreamString packet;
2521 if (json)
2522 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
2523 else
2524 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
2525 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00002526
Greg Claytone034a042015-05-21 20:52:06 +00002527 uint32_t result_idx = 0;
2528 uint32_t send_size;
2529 std::vector<float> packet_times;
2530
2531 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
2532 {
2533 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
2534 {
2535 MakeSpeedTestPacket (packet, send_size, recv_size);
2536
2537 packet_times.clear();
2538 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00002539 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00002540 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00002541 {
Greg Claytone034a042015-05-21 20:52:06 +00002542 TimeValue packet_start_time = TimeValue::Now();
2543 StringExtractorGDBRemote response;
2544 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2545 TimeValue packet_end_time = TimeValue::Now();
2546 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
2547 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002548 }
2549 end_time = TimeValue::Now();
2550 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00002551
2552 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2553 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
2554 float average_ms_per_packet = total_ms / num_packets;
2555 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
2556 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00002557 {
Greg Claytone034a042015-05-21 20:52:06 +00002558 strm.Printf ("%s\n {\"send_size\" : %6" PRIu32 ", \"recv_size\" : %6" PRIu32 ", \"total_time_nsec\" : %12" PRIu64 ", \"standard_deviation_nsec\" : %9" PRIu64 " }", result_idx > 0 ? "," : "", send_size, recv_size, total_time_nsec, (uint64_t)standard_deviation);
2559 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00002560 }
2561 else
2562 {
Greg Claytone034a042015-05-21 20:52:06 +00002563 strm.Printf ("qSpeedTest(send=%-7u, recv=%-7u) in %" PRIu64 ".%9.9" PRIu64 " sec for %9.2f packets/sec (%10.6f ms per packet) with standard deviation of %10.6f ms\n",
2564 send_size,
2565 recv_size,
2566 total_time_nsec / TimeValue::NanoSecPerSec,
2567 total_time_nsec % TimeValue::NanoSecPerSec,
2568 packets_per_second,
2569 average_ms_per_packet,
2570 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00002571 }
Greg Claytone034a042015-05-21 20:52:06 +00002572 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002573 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002574 }
Greg Claytone034a042015-05-21 20:52:06 +00002575
2576 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
2577
2578 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
2579 if (json)
2580 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
2581 else
2582 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
2583 strm.Flush();
2584 send_size = 0;
2585 result_idx = 0;
2586 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
2587 {
2588 MakeSpeedTestPacket (packet, send_size, recv_size);
2589
2590 // If we have a receive size, test how long it takes to receive 4MB of data
2591 if (recv_size > 0)
2592 {
2593 start_time = TimeValue::Now();
2594 uint32_t bytes_read = 0;
2595 uint32_t packet_count = 0;
2596 while (bytes_read < k_recv_amount)
2597 {
2598 StringExtractorGDBRemote response;
2599 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2600 bytes_read += recv_size;
2601 ++packet_count;
2602 }
2603 end_time = TimeValue::Now();
2604 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2605 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2606 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2607 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
2608 float average_ms_per_packet = total_ms / packet_count;
2609
2610 if (json)
2611 {
2612 strm.Printf ("%s\n {\"send_size\" : %6" PRIu32 ", \"recv_size\" : %6" PRIu32 ", \"total_time_nsec\" : %12" PRIu64 " }", result_idx > 0 ? "," : "", send_size, recv_size, total_time_nsec);
2613 ++result_idx;
2614 }
2615 else
2616 {
2617 strm.Printf ("qSpeedTest(send=%-7u, recv=%-7u) %6u packets needed to receive %2.1fMB in %" PRIu64 ".%9.9" PRIu64 " sec for %f MB/sec for %9.2f packets/sec (%10.6f ms per packet)\n",
2618 send_size,
2619 recv_size,
2620 packet_count,
2621 k_recv_amount_mb,
2622 total_time_nsec / TimeValue::NanoSecPerSec,
2623 total_time_nsec % TimeValue::NanoSecPerSec,
2624 mb_second,
2625 packets_per_second,
2626 average_ms_per_packet);
2627 }
2628 strm.Flush();
2629 }
2630 }
2631 if (json)
2632 strm.Printf("\n ]\n }\n}\n");
2633 else
2634 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002635 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002636}
2637
2638bool
2639GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2640{
2641 StreamString packet;
2642 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2643 uint32_t bytes_left = send_size;
2644 while (bytes_left > 0)
2645 {
2646 if (bytes_left >= 26)
2647 {
2648 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2649 bytes_left -= 26;
2650 }
2651 else
2652 {
2653 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2654 bytes_left = 0;
2655 }
2656 }
2657
2658 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002659 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00002660}
Greg Clayton8b82f082011-04-12 05:54:46 +00002661
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002662bool
2663GDBRemoteCommunicationClient::LaunchGDBServer (const char *remote_accept_hostname,
2664 lldb::pid_t &pid,
2665 uint16_t &port,
2666 std::string &socket_name)
Greg Clayton8b82f082011-04-12 05:54:46 +00002667{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002668 pid = LLDB_INVALID_PROCESS_ID;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002669 port = 0;
2670 socket_name.clear();
2671
Greg Clayton8b82f082011-04-12 05:54:46 +00002672 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002673 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00002674 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002675 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00002676 if (remote_accept_hostname && remote_accept_hostname[0])
2677 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002678 else
2679 {
Zachary Turner97a14e62014-08-19 17:18:29 +00002680 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00002681 {
2682 // Make the GDB server we launch only accept connections from this host
2683 stream.Printf("host:%s;", hostname.c_str());
2684 }
2685 else
2686 {
2687 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2688 stream.Printf("host:*;");
2689 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002690 }
2691 const char *packet = stream.GetData();
2692 int packet_len = stream.GetSize();
2693
Vince Harron1b5a74e2015-01-21 22:42:49 +00002694 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00002695 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002696
Tamas Berghammer912800c2015-02-24 10:23:39 +00002697 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002698 {
2699 std::string name;
2700 std::string value;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002701 StringExtractor extractor;
Greg Clayton8b82f082011-04-12 05:54:46 +00002702 while (response.GetNameColonValue(name, value))
2703 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00002704 if (name.compare("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00002705 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002706 else if (name.compare("pid") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00002707 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002708 else if (name.compare("socket_name") == 0)
2709 {
2710 extractor.GetStringRef().swap(value);
2711 extractor.SetFilePos(0);
2712 extractor.GetHexByteString(value);
2713
2714 socket_name = value;
2715 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002716 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002717 return true;
Greg Clayton8b82f082011-04-12 05:54:46 +00002718 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002719 return false;
Greg Clayton8b82f082011-04-12 05:54:46 +00002720}
2721
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00002722size_t
2723GDBRemoteCommunicationClient::QueryGDBServer (std::vector<std::pair<uint16_t, std::string>>& connection_urls)
2724{
2725 connection_urls.clear();
2726
2727 StringExtractorGDBRemote response;
2728 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) != PacketResult::Success)
2729 return 0;
2730
2731 StructuredData::ObjectSP data = StructuredData::ParseJSON(response.GetStringRef());
2732 if (!data)
2733 return 0;
2734
2735 StructuredData::Array* array = data->GetAsArray();
2736 if (!array)
2737 return 0;
2738
2739 for (size_t i = 0, count = array->GetSize(); i < count; ++i)
2740 {
2741 StructuredData::Dictionary* element = nullptr;
2742 if (!array->GetItemAtIndexAsDictionary(i, element))
2743 continue;
2744
2745 uint16_t port = 0;
2746 if (StructuredData::ObjectSP port_osp = element->GetValueForKey(llvm::StringRef("port")))
2747 port = port_osp->GetIntegerValue(0);
2748
2749 std::string socket_name;
2750 if (StructuredData::ObjectSP socket_name_osp = element->GetValueForKey(llvm::StringRef("socket_name")))
2751 socket_name = socket_name_osp->GetStringValue();
2752
2753 if (port != 0 || !socket_name.empty())
2754 connection_urls.emplace_back(port, socket_name);
2755 }
2756 return connection_urls.size();
2757}
2758
Greg Clayton8b82f082011-04-12 05:54:46 +00002759bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00002760GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2761{
2762 StreamString stream;
2763 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2764 const char *packet = stream.GetData();
2765 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00002766
Daniel Maleae0f8f572013-08-26 23:57:52 +00002767 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002768 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002769 {
2770 if (response.IsOKResponse())
2771 return true;
2772 }
2773 return false;
2774}
2775
2776bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002777GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002778{
2779 if (m_curr_tid == tid)
2780 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002781
Greg Clayton8b82f082011-04-12 05:54:46 +00002782 char packet[32];
2783 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002784 if (tid == UINT64_MAX)
2785 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002786 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002787 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002788 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002789 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002790 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002791 {
2792 if (response.IsOKResponse())
2793 {
2794 m_curr_tid = tid;
2795 return true;
2796 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00002797
2798 /*
2799 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hg packet.
2800 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
2801 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2802 */
2803 if (response.IsUnsupportedResponse() && IsConnected())
2804 {
2805 m_curr_tid = 1;
2806 return true;
2807 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002808 }
2809 return false;
2810}
2811
2812bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002813GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002814{
2815 if (m_curr_tid_run == tid)
2816 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002817
Greg Clayton8b82f082011-04-12 05:54:46 +00002818 char packet[32];
2819 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002820 if (tid == UINT64_MAX)
2821 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002822 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002823 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2824
Andy Gibbsa297a972013-06-19 19:04:53 +00002825 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002826 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002827 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002828 {
2829 if (response.IsOKResponse())
2830 {
2831 m_curr_tid_run = tid;
2832 return true;
2833 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00002834
2835 /*
2836 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hc packet.
2837 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
2838 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2839 */
2840 if (response.IsUnsupportedResponse() && IsConnected())
2841 {
2842 m_curr_tid_run = 1;
2843 return true;
2844 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002845 }
2846 return false;
2847}
2848
2849bool
2850GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2851{
Greg Clayton3dedae12013-12-06 21:45:27 +00002852 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002853 return response.IsNormalResponse();
2854 return false;
2855}
2856
2857bool
Greg Claytonf402f782012-10-13 02:11:55 +00002858GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00002859{
2860 if (m_supports_qThreadStopInfo)
2861 {
2862 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00002863 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002864 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002865 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002866 {
Greg Claytonef8180a2013-10-15 00:14:28 +00002867 if (response.IsUnsupportedResponse())
2868 m_supports_qThreadStopInfo = false;
2869 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002870 return true;
2871 else
2872 return false;
2873 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002874 else
2875 {
2876 m_supports_qThreadStopInfo = false;
2877 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002878 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002879 return false;
2880}
2881
2882
2883uint8_t
2884GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2885{
Todd Fiala616b8272014-10-09 00:55:04 +00002886 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2887 if (log)
2888 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2889 __FUNCTION__, insert ? "add" : "remove", addr);
2890
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002891 // Check if the stub is known not to support this breakpoint type
2892 if (!SupportsGDBStoppointPacket(type))
2893 return UINT8_MAX;
2894 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00002895 char packet[64];
2896 const int packet_len = ::snprintf (packet,
2897 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00002898 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00002899 insert ? 'Z' : 'z',
2900 type,
2901 addr,
2902 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002903 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00002904 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002905 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +00002906 // Make sure the response is either "OK", "EXX" where XX are two hex digits, or "" (unsupported)
2907 response.SetResponseValidatorToOKErrorNotSupported();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002908 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00002909 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002910 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002911 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00002912 if (response.IsOKResponse())
2913 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002914
2915 // Error while setting breakpoint, send back specific error
2916 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002917 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002918
2919 // Empty packet informs us that breakpoint is not supported
2920 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00002921 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002922 // Disable this breakpoint type since it is unsupported
2923 switch (type)
2924 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00002925 case eBreakpointSoftware: m_supports_z0 = false; break;
2926 case eBreakpointHardware: m_supports_z1 = false; break;
2927 case eWatchpointWrite: m_supports_z2 = false; break;
2928 case eWatchpointRead: m_supports_z3 = false; break;
2929 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00002930 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002931 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002932 }
2933 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002934 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00002935 return UINT8_MAX;
2936}
Greg Claytonadc00cb2011-05-20 23:38:13 +00002937
2938size_t
2939GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2940 bool &sequence_mutex_unavailable)
2941{
Greg Claytonadc00cb2011-05-20 23:38:13 +00002942 thread_ids.clear();
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002943
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00002944 Lock lock(*this, false);
2945 if (lock)
Greg Claytonadc00cb2011-05-20 23:38:13 +00002946 {
2947 sequence_mutex_unavailable = false;
2948 StringExtractorGDBRemote response;
2949
Greg Clayton3dedae12013-12-06 21:45:27 +00002950 PacketResult packet_result;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00002951 for (packet_result = SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
Greg Clayton3dedae12013-12-06 21:45:27 +00002952 packet_result == PacketResult::Success && response.IsNormalResponse();
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00002953 packet_result = SendPacketAndWaitForResponseNoLock("qsThreadInfo", response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002954 {
2955 char ch = response.GetChar();
2956 if (ch == 'l')
2957 break;
2958 if (ch == 'm')
2959 {
2960 do
2961 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00002962 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00002963
2964 if (tid != LLDB_INVALID_THREAD_ID)
2965 {
2966 thread_ids.push_back (tid);
2967 }
2968 ch = response.GetChar(); // Skip the command separator
2969 } while (ch == ','); // Make sure we got a comma separator
2970 }
2971 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00002972
2973 /*
2974 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2975 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet could
2976 * be as simple as 'S05'. There is no packet which can give us pid and/or tid.
2977 * Assume pid=tid=1 in such cases.
2978 */
2979 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 && IsConnected())
2980 {
2981 thread_ids.push_back (1);
2982 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00002983 }
2984 else
2985 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00002986#if defined (LLDB_CONFIGURATION_DEBUG)
2987 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2988#else
Greg Clayton5160ce52013-03-27 23:08:40 +00002989 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00002990 if (log)
2991 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00002992#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00002993 sequence_mutex_unavailable = true;
2994 }
2995 return thread_ids.size();
2996}
Greg Clayton37a0a242012-04-11 00:24:49 +00002997
2998lldb::addr_t
2999GDBRemoteCommunicationClient::GetShlibInfoAddr()
3000{
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003001 Lock lock(*this, false);
3002 if (lock)
Greg Clayton37a0a242012-04-11 00:24:49 +00003003 {
3004 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003005 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00003006 {
3007 if (response.IsNormalResponse())
3008 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3009 }
3010 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003011 else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
3012 {
3013 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex for qShlibInfoAddr packet.",
3014 __FUNCTION__);
3015 }
Greg Clayton37a0a242012-04-11 00:24:49 +00003016 return LLDB_INVALID_ADDRESS;
3017}
3018
Daniel Maleae0f8f572013-08-26 23:57:52 +00003019lldb_private::Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003020GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3021 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3022 int *status_ptr, // Pass NULL if you don't want the process exit status
3023 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3024 std::string *command_output, // Pass NULL if you don't want the command output
3025 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
Daniel Maleae0f8f572013-08-26 23:57:52 +00003026{
3027 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003028 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003029 stream.PutBytesAsRawHex8(command, strlen(command));
3030 stream.PutChar(',');
3031 stream.PutHex32(timeout_sec);
Chaoren Lind3173f32015-05-29 19:52:29 +00003032 if (working_dir)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003033 {
Chaoren Lind3173f32015-05-29 19:52:29 +00003034 std::string path{working_dir.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003035 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003036 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003037 }
3038 const char *packet = stream.GetData();
3039 int packet_len = stream.GetSize();
3040 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003041 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003042 {
3043 if (response.GetChar() != 'F')
3044 return Error("malformed reply");
3045 if (response.GetChar() != ',')
3046 return Error("malformed reply");
3047 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3048 if (exitcode == UINT32_MAX)
3049 return Error("unable to run remote process");
3050 else if (status_ptr)
3051 *status_ptr = exitcode;
3052 if (response.GetChar() != ',')
3053 return Error("malformed reply");
3054 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3055 if (signo_ptr)
3056 *signo_ptr = signo;
3057 if (response.GetChar() != ',')
3058 return Error("malformed reply");
3059 std::string output;
3060 response.GetEscapedBinaryData(output);
3061 if (command_output)
3062 command_output->assign(output);
3063 return Error();
3064 }
3065 return Error("unable to send packet");
3066}
3067
Greg Claytonfbb76342013-11-20 21:07:01 +00003068Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003069GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3070 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003071{
Chaoren Lind3173f32015-05-29 19:52:29 +00003072 std::string path{file_spec.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003073 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003074 stream.PutCString("qPlatform_mkdir:");
3075 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003076 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003077 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003078 const char *packet = stream.GetData();
3079 int packet_len = stream.GetSize();
3080 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003081
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003082 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3083 return Error("failed to send '%s' packet", packet);
3084
3085 if (response.GetChar() != 'F')
3086 return Error("invalid response to '%s' packet", packet);
3087
3088 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003089}
3090
Greg Claytonfbb76342013-11-20 21:07:01 +00003091Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003092GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3093 uint32_t file_permissions)
Greg Claytonfbb76342013-11-20 21:07:01 +00003094{
Chaoren Lind3173f32015-05-29 19:52:29 +00003095 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003096 lldb_private::StreamString stream;
3097 stream.PutCString("qPlatform_chmod:");
3098 stream.PutHex32(file_permissions);
3099 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003100 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003101 const char *packet = stream.GetData();
3102 int packet_len = stream.GetSize();
3103 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003104
3105 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3106 return Error("failed to send '%s' packet", packet);
3107
3108 if (response.GetChar() != 'F')
3109 return Error("invalid response to '%s' packet", packet);
3110
Chaoren Lince36c4c2015-05-05 18:43:19 +00003111 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003112}
3113
Daniel Maleae0f8f572013-08-26 23:57:52 +00003114static uint64_t
3115ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3116 uint64_t fail_result,
3117 Error &error)
3118{
3119 response.SetFilePos(0);
3120 if (response.GetChar() != 'F')
3121 return fail_result;
3122 int32_t result = response.GetS32 (-2);
3123 if (result == -2)
3124 return fail_result;
3125 if (response.GetChar() == ',')
3126 {
3127 int result_errno = response.GetS32 (-2);
3128 if (result_errno != -2)
3129 error.SetError(result_errno, eErrorTypePOSIX);
3130 else
3131 error.SetError(-1, eErrorTypeGeneric);
3132 }
3133 else
3134 error.Clear();
3135 return result;
3136}
3137lldb::user_id_t
3138GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3139 uint32_t flags,
3140 mode_t mode,
3141 Error &error)
3142{
Chaoren Lind3173f32015-05-29 19:52:29 +00003143 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003144 lldb_private::StreamString stream;
3145 stream.PutCString("vFile:open:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003146 if (path.empty())
3147 return UINT64_MAX;
3148 stream.PutCStringAsRawHex8(path.c_str());
3149 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003150 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003151 stream.PutChar(',');
3152 stream.PutHex32(mode);
3153 const char* packet = stream.GetData();
3154 int packet_len = stream.GetSize();
3155 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003156 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003157 {
3158 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3159 }
3160 return UINT64_MAX;
3161}
3162
3163bool
3164GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3165 Error &error)
3166{
3167 lldb_private::StreamString stream;
3168 stream.Printf("vFile:close:%i", (int)fd);
3169 const char* packet = stream.GetData();
3170 int packet_len = stream.GetSize();
3171 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003172 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003173 {
3174 return ParseHostIOPacketResponse (response, -1, error) == 0;
3175 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003176 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003177}
3178
3179// Extension of host I/O packets to get the file size.
3180lldb::user_id_t
3181GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3182{
Chaoren Lind3173f32015-05-29 19:52:29 +00003183 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003184 lldb_private::StreamString stream;
3185 stream.PutCString("vFile:size:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003186 stream.PutCStringAsRawHex8(path.c_str());
3187 const char* packet = stream.GetData();
3188 int packet_len = stream.GetSize();
3189 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003190 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003191 {
3192 if (response.GetChar() != 'F')
3193 return UINT64_MAX;
3194 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3195 return retcode;
3196 }
3197 return UINT64_MAX;
3198}
3199
Greg Claytonfbb76342013-11-20 21:07:01 +00003200Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003201GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3202 uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003203{
Chaoren Lind3173f32015-05-29 19:52:29 +00003204 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003205 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003206 lldb_private::StreamString stream;
3207 stream.PutCString("vFile:mode:");
Chaoren Lind3173f32015-05-29 19:52:29 +00003208 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003209 const char* packet = stream.GetData();
3210 int packet_len = stream.GetSize();
3211 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003212 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003213 {
3214 if (response.GetChar() != 'F')
3215 {
3216 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003217 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003218 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003219 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003220 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003221 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003222 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003223 if (response.GetChar() == ',')
3224 {
3225 int response_errno = response.GetS32(-1);
3226 if (response_errno > 0)
3227 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3228 else
3229 error.SetErrorToGenericError();
3230 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003231 else
3232 error.SetErrorToGenericError();
3233 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003234 else
3235 {
3236 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3237 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003238 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003239 }
3240 else
3241 {
3242 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3243 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003244 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003245}
3246
3247uint64_t
3248GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3249 uint64_t offset,
3250 void *dst,
3251 uint64_t dst_len,
3252 Error &error)
3253{
3254 lldb_private::StreamString stream;
3255 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3256 const char* packet = stream.GetData();
3257 int packet_len = stream.GetSize();
3258 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003259 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003260 {
3261 if (response.GetChar() != 'F')
3262 return 0;
3263 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3264 if (retcode == UINT32_MAX)
3265 return retcode;
3266 const char next = (response.Peek() ? *response.Peek() : 0);
3267 if (next == ',')
3268 return 0;
3269 if (next == ';')
3270 {
3271 response.GetChar(); // skip the semicolon
3272 std::string buffer;
3273 if (response.GetEscapedBinaryData(buffer))
3274 {
3275 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3276 if (data_to_write > 0)
3277 memcpy(dst, &buffer[0], data_to_write);
3278 return data_to_write;
3279 }
3280 }
3281 }
3282 return 0;
3283}
3284
3285uint64_t
3286GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3287 uint64_t offset,
3288 const void* src,
3289 uint64_t src_len,
3290 Error &error)
3291{
3292 lldb_private::StreamGDBRemote stream;
3293 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3294 stream.PutEscapedBytes(src, src_len);
3295 const char* packet = stream.GetData();
3296 int packet_len = stream.GetSize();
3297 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003298 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003299 {
3300 if (response.GetChar() != 'F')
3301 {
3302 error.SetErrorStringWithFormat("write file failed");
3303 return 0;
3304 }
3305 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3306 if (bytes_written == UINT64_MAX)
3307 {
3308 error.SetErrorToGenericError();
3309 if (response.GetChar() == ',')
3310 {
3311 int response_errno = response.GetS32(-1);
3312 if (response_errno > 0)
3313 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3314 }
3315 return 0;
3316 }
3317 return bytes_written;
3318 }
3319 else
3320 {
3321 error.SetErrorString ("failed to send vFile:pwrite packet");
3322 }
3323 return 0;
3324}
3325
Greg Claytonfbb76342013-11-20 21:07:01 +00003326Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003327GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
Greg Claytonfbb76342013-11-20 21:07:01 +00003328{
Chaoren Lind3173f32015-05-29 19:52:29 +00003329 std::string src_path{src.GetPath(false)},
3330 dst_path{dst.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003331 Error error;
3332 lldb_private::StreamGDBRemote stream;
3333 stream.PutCString("vFile:symlink:");
3334 // the unix symlink() command reverses its parameters where the dst if first,
3335 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003336 stream.PutCStringAsRawHex8(dst_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003337 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003338 stream.PutCStringAsRawHex8(src_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003339 const char* packet = stream.GetData();
3340 int packet_len = stream.GetSize();
3341 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003342 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003343 {
3344 if (response.GetChar() == 'F')
3345 {
3346 uint32_t result = response.GetU32(UINT32_MAX);
3347 if (result != 0)
3348 {
3349 error.SetErrorToGenericError();
3350 if (response.GetChar() == ',')
3351 {
3352 int response_errno = response.GetS32(-1);
3353 if (response_errno > 0)
3354 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3355 }
3356 }
3357 }
3358 else
3359 {
3360 // Should have returned with 'F<result>[,<errno>]'
3361 error.SetErrorStringWithFormat("symlink failed");
3362 }
3363 }
3364 else
3365 {
3366 error.SetErrorString ("failed to send vFile:symlink packet");
3367 }
3368 return error;
3369}
3370
3371Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003372GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
Greg Claytonfbb76342013-11-20 21:07:01 +00003373{
Chaoren Lind3173f32015-05-29 19:52:29 +00003374 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003375 Error error;
3376 lldb_private::StreamGDBRemote stream;
3377 stream.PutCString("vFile:unlink:");
3378 // the unix symlink() command reverses its parameters where the dst if first,
3379 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003380 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003381 const char* packet = stream.GetData();
3382 int packet_len = stream.GetSize();
3383 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003384 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003385 {
3386 if (response.GetChar() == 'F')
3387 {
3388 uint32_t result = response.GetU32(UINT32_MAX);
3389 if (result != 0)
3390 {
3391 error.SetErrorToGenericError();
3392 if (response.GetChar() == ',')
3393 {
3394 int response_errno = response.GetS32(-1);
3395 if (response_errno > 0)
3396 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3397 }
3398 }
3399 }
3400 else
3401 {
3402 // Should have returned with 'F<result>[,<errno>]'
3403 error.SetErrorStringWithFormat("unlink failed");
3404 }
3405 }
3406 else
3407 {
3408 error.SetErrorString ("failed to send vFile:unlink packet");
3409 }
3410 return error;
3411}
3412
Daniel Maleae0f8f572013-08-26 23:57:52 +00003413// Extension of host I/O packets to get whether a file exists.
3414bool
3415GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3416{
Chaoren Lind3173f32015-05-29 19:52:29 +00003417 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003418 lldb_private::StreamString stream;
3419 stream.PutCString("vFile:exists:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003420 stream.PutCStringAsRawHex8(path.c_str());
3421 const char* packet = stream.GetData();
3422 int packet_len = stream.GetSize();
3423 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003424 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003425 {
3426 if (response.GetChar() != 'F')
3427 return false;
3428 if (response.GetChar() != ',')
3429 return false;
3430 bool retcode = (response.GetChar() != '0');
3431 return retcode;
3432 }
3433 return false;
3434}
3435
3436bool
3437GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3438 uint64_t &high,
3439 uint64_t &low)
3440{
Chaoren Lind3173f32015-05-29 19:52:29 +00003441 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003442 lldb_private::StreamString stream;
3443 stream.PutCString("vFile:MD5:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003444 stream.PutCStringAsRawHex8(path.c_str());
3445 const char* packet = stream.GetData();
3446 int packet_len = stream.GetSize();
3447 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003448 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003449 {
3450 if (response.GetChar() != 'F')
3451 return false;
3452 if (response.GetChar() != ',')
3453 return false;
3454 if (response.Peek() && *response.Peek() == 'x')
3455 return false;
3456 low = response.GetHexMaxU64(false, UINT64_MAX);
3457 high = response.GetHexMaxU64(false, UINT64_MAX);
3458 return true;
3459 }
3460 return false;
3461}
Greg Claytonf74cf862013-11-13 23:28:31 +00003462
3463bool
Jason Molendaa3329782014-03-29 18:54:20 +00003464GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3465{
3466 // Some targets have issues with g/G packets and we need to avoid using them
3467 if (m_avoid_g_packets == eLazyBoolCalculate)
3468 {
3469 if (process)
3470 {
3471 m_avoid_g_packets = eLazyBoolNo;
3472 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3473 if (arch.IsValid()
3474 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3475 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00003476 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00003477 {
3478 m_avoid_g_packets = eLazyBoolYes;
3479 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3480 if (gdb_server_version != 0)
3481 {
3482 const char *gdb_server_name = GetGDBServerProgramName();
3483 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3484 {
3485 if (gdb_server_version >= 310)
3486 m_avoid_g_packets = eLazyBoolNo;
3487 }
3488 }
3489 }
3490 }
3491 }
3492 return m_avoid_g_packets == eLazyBoolYes;
3493}
3494
3495bool
Greg Claytonf74cf862013-11-13 23:28:31 +00003496GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3497{
Pavel Labath4b6f9592016-08-18 08:30:03 +00003498 StreamString payload;
3499 payload.Printf("p%x", reg);
3500 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, false) ==
3501 PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003502}
3503
3504
3505bool
3506GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3507{
Pavel Labath4b6f9592016-08-18 08:30:03 +00003508 StreamString payload;
3509 payload.PutChar('g');
3510 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, false) ==
3511 PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003512}
Pavel Labath56d72622016-08-17 08:53:31 +00003513
3514bool
3515GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid, uint32_t reg_num, llvm::StringRef data)
3516{
Pavel Labath4b6f9592016-08-18 08:30:03 +00003517 StreamString payload;
3518 payload.Printf("P%x=", reg_num);
3519 payload.PutBytesAsRawHex8(data.data(), data.size(), endian::InlHostByteOrder(), endian::InlHostByteOrder());
Pavel Labath56d72622016-08-17 08:53:31 +00003520 StringExtractorGDBRemote response;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003521 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, false) ==
3522 PacketResult::Success;
Pavel Labath56d72622016-08-17 08:53:31 +00003523}
3524
3525bool
3526GDBRemoteCommunicationClient::WriteAllRegisters(lldb::tid_t tid, llvm::StringRef data)
3527{
Pavel Labath4b6f9592016-08-18 08:30:03 +00003528 StreamString payload;
3529 payload.PutChar('G');
3530 payload.Write(data.data(), data.size());
Pavel Labath56d72622016-08-17 08:53:31 +00003531 StringExtractorGDBRemote response;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003532 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, false) ==
3533 PacketResult::Success;
Pavel Labath56d72622016-08-17 08:53:31 +00003534}
3535
Greg Claytonf74cf862013-11-13 23:28:31 +00003536bool
3537GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3538{
3539 save_id = 0; // Set to invalid save ID
3540 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3541 return false;
3542
3543 m_supports_QSaveRegisterState = eLazyBoolYes;
Pavel Labath4b6f9592016-08-18 08:30:03 +00003544 StreamString payload;
3545 payload.PutCString("QSaveRegisterState");
3546 StringExtractorGDBRemote response;
3547 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, false) != PacketResult::Success)
3548 return false;
Greg Claytonf74cf862013-11-13 23:28:31 +00003549
Pavel Labath4b6f9592016-08-18 08:30:03 +00003550 if (response.IsUnsupportedResponse())
3551 m_supports_QSaveRegisterState = eLazyBoolNo;
3552
3553 const uint32_t response_save_id = response.GetU32(0);
3554 if (response_save_id == 0)
3555 return false;
3556
3557 save_id = response_save_id;
3558 return true;
Greg Claytonf74cf862013-11-13 23:28:31 +00003559}
3560
3561bool
3562GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3563{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003564 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00003565 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3566 // order to be useful
3567 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3568 return false;
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003569
Pavel Labath4b6f9592016-08-18 08:30:03 +00003570 StreamString payload;
3571 payload.Printf("QRestoreRegisterState:%u", save_id);
3572 StringExtractorGDBRemote response;
3573 if (SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), response, false) != PacketResult::Success)
3574 return false;
3575
3576 if (response.IsOKResponse())
3577 return true;
3578
3579 if (response.IsUnsupportedResponse())
3580 m_supports_QSaveRegisterState = eLazyBoolNo;
Greg Claytonf74cf862013-11-13 23:28:31 +00003581 return false;
3582}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003583
3584bool
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003585GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003586 const lldb_private::ArchSpec& arch_spec,
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003587 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003588{
Stephane Sezer6f455292016-01-08 00:00:17 +00003589 if (!m_supports_qModuleInfo)
3590 return false;
3591
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00003592 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003593 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003594 return false;
3595
3596 StreamString packet;
3597 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003598 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003599 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00003600 const auto& triple = arch_spec.GetTriple().getTriple();
Chaoren Lind3173f32015-05-29 19:52:29 +00003601 packet.PutCStringAsRawHex8(triple.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003602
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003603 StringExtractorGDBRemote response;
3604 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
3605 return false;
3606
Stephane Sezer6f455292016-01-08 00:00:17 +00003607 if (response.IsErrorResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003608 return false;
3609
Stephane Sezer6f455292016-01-08 00:00:17 +00003610 if (response.IsUnsupportedResponse ())
3611 {
3612 m_supports_qModuleInfo = false;
3613 return false;
3614 }
3615
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003616 std::string name;
3617 std::string value;
3618 bool success;
3619 StringExtractor extractor;
3620
3621 module_spec.Clear ();
3622 module_spec.GetFileSpec () = module_file_spec;
3623
3624 while (response.GetNameColonValue (name, value))
3625 {
3626 if (name == "uuid" || name == "md5")
3627 {
3628 extractor.GetStringRef ().swap (value);
3629 extractor.SetFilePos (0);
3630 extractor.GetHexByteString (value);
3631 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
3632 }
3633 else if (name == "triple")
3634 {
3635 extractor.GetStringRef ().swap (value);
3636 extractor.SetFilePos (0);
3637 extractor.GetHexByteString (value);
3638 module_spec.GetArchitecture().SetTriple (value.c_str ());
3639 }
3640 else if (name == "file_offset")
3641 {
3642 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
3643 if (success)
3644 module_spec.SetObjectOffset (ival);
3645 }
3646 else if (name == "file_size")
3647 {
3648 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
3649 if (success)
3650 module_spec.SetObjectSize (ival);
3651 }
3652 else if (name == "file_path")
3653 {
3654 extractor.GetStringRef ().swap (value);
3655 extractor.SetFilePos (0);
3656 extractor.GetHexByteString (value);
Chaoren Linf34f4102015-05-09 01:21:32 +00003657 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003658 }
3659 }
3660
3661 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003662}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003663
3664// query the target remote for extended information using the qXfer packet
3665//
3666// example: object='features', annex='target.xml', out=<xml output>
3667// return: 'true' on success
3668// 'false' on failure (err set)
3669bool
3670GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
3671 const lldb_private::ConstString annex,
3672 std::string & out,
3673 lldb_private::Error & err) {
3674
3675 std::stringstream output;
3676 StringExtractorGDBRemote chunk;
3677
Greg Claytond04f0ed2015-05-26 18:00:51 +00003678 uint64_t size = GetRemoteMaxPacketSize();
3679 if (size == 0)
3680 size = 0x1000;
3681 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3682 int offset = 0;
3683 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003684
3685 // loop until all data has been read
3686 while ( active ) {
3687
3688 // send query extended feature packet
3689 std::stringstream packet;
3690 packet << "qXfer:"
Ewan Crawford682e8422015-06-26 09:38:27 +00003691 << object.AsCString("") << ":read:"
3692 << annex.AsCString("") << ":"
Colin Rileyc3c95b22015-04-16 15:51:33 +00003693 << std::hex << offset << ","
3694 << std::hex << size;
3695
3696 GDBRemoteCommunication::PacketResult res =
3697 SendPacketAndWaitForResponse( packet.str().c_str(),
3698 chunk,
3699 false );
3700
3701 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
3702 err.SetErrorString( "Error sending $qXfer packet" );
3703 return false;
3704 }
3705
3706 const std::string & str = chunk.GetStringRef( );
3707 if ( str.length() == 0 ) {
3708 // should have some data in chunk
3709 err.SetErrorString( "Empty response from $qXfer packet" );
3710 return false;
3711 }
3712
3713 // check packet code
3714 switch ( str[0] ) {
3715 // last chunk
3716 case ( 'l' ):
3717 active = false;
Jason Molenda62e06812016-02-16 04:14:33 +00003718 LLVM_FALLTHROUGH;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003719
3720 // more chunks
3721 case ( 'm' ) :
3722 if ( str.length() > 1 )
3723 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00003724 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003725 break;
3726
3727 // unknown chunk
3728 default:
3729 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
3730 return false;
3731 }
3732 }
3733
3734 out = output.str( );
3735 err.Success( );
3736 return true;
3737}
Greg Clayton0b90be12015-06-23 21:27:50 +00003738
3739// Notify the target that gdb is prepared to serve symbol lookup requests.
3740// packet: "qSymbol::"
3741// reply:
3742// OK The target does not need to look up any (more) symbols.
3743// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded).
3744// LLDB may provide the value by sending another qSymbol packet
3745// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003746//
3747// Three examples:
3748//
3749// lldb sends: qSymbol::
3750// lldb receives: OK
3751// Remote gdb stub does not need to know the addresses of any symbols, lldb does not
3752// need to ask again in this session.
3753//
3754// lldb sends: qSymbol::
3755// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3756// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3757// lldb receives: OK
3758// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does not know
3759// the address at this time. lldb needs to send qSymbol:: again when it has more
3760// solibs loaded.
3761//
3762// lldb sends: qSymbol::
3763// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3764// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3765// lldb receives: OK
3766// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says that it
3767// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it does not
3768// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003769
3770void
3771GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
3772{
Jason Molenda50018d32016-01-13 04:08:10 +00003773 // Set to true once we've resolved a symbol to an address for the remote stub.
3774 // If we get an 'OK' response after this, the remote stub doesn't need any more
3775 // symbols and we can stop asking.
3776 bool symbol_response_provided = false;
3777
Ed Maste75500e72016-07-19 15:28:02 +00003778 // Is this the initial qSymbol:: packet?
Jason Molenda50018d32016-01-13 04:08:10 +00003779 bool first_qsymbol_query = true;
3780
3781 if (m_supports_qSymbol && m_qSymbol_requests_done == false)
Greg Clayton0b90be12015-06-23 21:27:50 +00003782 {
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003783 Lock lock(*this, false);
3784 if (lock)
Greg Clayton0b90be12015-06-23 21:27:50 +00003785 {
3786 StreamString packet;
3787 packet.PutCString ("qSymbol::");
Greg Clayton42b01482015-08-11 22:07:46 +00003788 StringExtractorGDBRemote response;
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003789 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) == PacketResult::Success)
Greg Clayton0b90be12015-06-23 21:27:50 +00003790 {
Greg Clayton42b01482015-08-11 22:07:46 +00003791 if (response.IsOKResponse())
Greg Clayton0b90be12015-06-23 21:27:50 +00003792 {
Jason Molenda50018d32016-01-13 04:08:10 +00003793 if (symbol_response_provided || first_qsymbol_query)
3794 {
3795 m_qSymbol_requests_done = true;
3796 }
3797
Greg Clayton42b01482015-08-11 22:07:46 +00003798 // We are done serving symbols requests
3799 return;
3800 }
Jason Molenda50018d32016-01-13 04:08:10 +00003801 first_qsymbol_query = false;
Greg Clayton0b90be12015-06-23 21:27:50 +00003802
Greg Clayton42b01482015-08-11 22:07:46 +00003803 if (response.IsUnsupportedResponse())
3804 {
3805 // qSymbol is not supported by the current GDB server we are connected to
3806 m_supports_qSymbol = false;
3807 return;
3808 }
3809 else
3810 {
3811 llvm::StringRef response_str(response.GetStringRef());
3812 if (response_str.startswith("qSymbol:"))
Greg Clayton0b90be12015-06-23 21:27:50 +00003813 {
Greg Clayton42b01482015-08-11 22:07:46 +00003814 response.SetFilePos(strlen("qSymbol:"));
3815 std::string symbol_name;
3816 if (response.GetHexByteString(symbol_name))
Greg Clayton0b90be12015-06-23 21:27:50 +00003817 {
Greg Clayton42b01482015-08-11 22:07:46 +00003818 if (symbol_name.empty())
3819 return;
3820
3821 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3822 lldb_private::SymbolContextList sc_list;
3823 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
Greg Clayton0b90be12015-06-23 21:27:50 +00003824 {
Greg Clayton42b01482015-08-11 22:07:46 +00003825 const size_t num_scs = sc_list.GetSize();
3826 for (size_t sc_idx=0; sc_idx<num_scs && symbol_load_addr == LLDB_INVALID_ADDRESS; ++sc_idx)
Greg Clayton0b90be12015-06-23 21:27:50 +00003827 {
Greg Clayton42b01482015-08-11 22:07:46 +00003828 SymbolContext sc;
3829 if (sc_list.GetContextAtIndex(sc_idx, sc))
Greg Clayton0b90be12015-06-23 21:27:50 +00003830 {
Greg Clayton42b01482015-08-11 22:07:46 +00003831 if (sc.symbol)
Greg Clayton358cf1e2015-06-25 21:46:34 +00003832 {
Greg Clayton42b01482015-08-11 22:07:46 +00003833 switch (sc.symbol->GetType())
Greg Clayton358cf1e2015-06-25 21:46:34 +00003834 {
Greg Clayton42b01482015-08-11 22:07:46 +00003835 case eSymbolTypeInvalid:
3836 case eSymbolTypeAbsolute:
3837 case eSymbolTypeUndefined:
3838 case eSymbolTypeSourceFile:
3839 case eSymbolTypeHeaderFile:
3840 case eSymbolTypeObjectFile:
3841 case eSymbolTypeCommonBlock:
3842 case eSymbolTypeBlock:
3843 case eSymbolTypeLocal:
3844 case eSymbolTypeParam:
3845 case eSymbolTypeVariable:
3846 case eSymbolTypeVariableType:
3847 case eSymbolTypeLineEntry:
3848 case eSymbolTypeLineHeader:
3849 case eSymbolTypeScopeBegin:
3850 case eSymbolTypeScopeEnd:
3851 case eSymbolTypeAdditional:
3852 case eSymbolTypeCompiler:
3853 case eSymbolTypeInstrumentation:
3854 case eSymbolTypeTrampoline:
3855 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00003856
Greg Clayton42b01482015-08-11 22:07:46 +00003857 case eSymbolTypeCode:
3858 case eSymbolTypeResolver:
3859 case eSymbolTypeData:
3860 case eSymbolTypeRuntime:
3861 case eSymbolTypeException:
3862 case eSymbolTypeObjCClass:
3863 case eSymbolTypeObjCMetaClass:
3864 case eSymbolTypeObjCIVar:
3865 case eSymbolTypeReExported:
3866 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
3867 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00003868 }
3869 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003870 }
3871 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003872 }
Greg Clayton42b01482015-08-11 22:07:46 +00003873 // This is the normal path where our symbol lookup was successful and we want
3874 // to send a packet with the new symbol value and see if another lookup needs to be
3875 // done.
3876
3877 // Change "packet" to contain the requested symbol value and name
3878 packet.Clear();
3879 packet.PutCString("qSymbol:");
3880 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
Jason Molenda50018d32016-01-13 04:08:10 +00003881 {
Greg Clayton42b01482015-08-11 22:07:46 +00003882 packet.Printf("%" PRIx64, symbol_load_addr);
Jason Molenda50018d32016-01-13 04:08:10 +00003883 symbol_response_provided = true;
3884 }
3885 else
3886 {
3887 symbol_response_provided = false;
3888 }
Greg Clayton42b01482015-08-11 22:07:46 +00003889 packet.PutCString(":");
3890 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3891 continue; // go back to the while loop and send "packet" and wait for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003892 }
3893 }
3894 }
3895 }
3896 // If we make it here, the symbol request packet response wasn't valid or
3897 // our symbol lookup failed so we must abort
3898 return;
3899
3900 }
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003901 else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
3902 {
3903 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.", __FUNCTION__);
3904 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003905 }
3906}
3907
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003908void
3909GDBRemoteCommunicationClient::OnRunPacketSent(bool first)
3910{
3911 GDBRemoteClientBase::OnRunPacketSent(first);
Pavel Labath8c1b6bd2016-08-09 12:04:46 +00003912 m_curr_tid = LLDB_INVALID_THREAD_ID;
3913}