blob: 207260a90b3fc0d1fc9b2701e919575e94eaad72 [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 Labathe768c4b2016-07-29 13:10:02 +000030#include "lldb/Interpreter/Args.h"
Greg Clayton0b90be12015-06-23 21:27:50 +000031#include "lldb/Symbol/Symbol.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000032#include "lldb/Target/MemoryRegionInfo.h"
Pavel Labathe768c4b2016-07-29 13:10:02 +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 Labathe768c4b2016-07-29 13:10:02 +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 Labathe768c4b2016-07-29 13:10:02 +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
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000577// Check if the target supports 'p' packet. It sends out a 'p'
578// packet and checks the response. A normal packet will tell us
579// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000580//
581// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000582bool
Sean Callananb1de1142013-09-04 23:24:15 +0000583GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000584{
585 if (m_supports_p == eLazyBoolCalculate)
586 {
587 StringExtractorGDBRemote response;
588 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000589 char packet[256];
590 if (GetThreadSuffixSupported())
591 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
592 else
593 snprintf(packet, sizeof(packet), "p0");
594
Greg Clayton3dedae12013-12-06 21:45:27 +0000595 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000596 {
597 if (response.IsNormalResponse())
598 m_supports_p = eLazyBoolYes;
599 }
600 }
601 return m_supports_p;
602}
Greg Clayton576d8832011-03-22 04:00:09 +0000603
Greg Clayton358cf1e2015-06-25 21:46:34 +0000604StructuredData::ObjectSP
605GDBRemoteCommunicationClient::GetThreadsInfo()
606{
607 // Get information on all threads at one using the "jThreadsInfo" packet
608 StructuredData::ObjectSP object_sp;
609
610 if (m_supports_jThreadsInfo)
611 {
612 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +0000613 response.SetResponseValidatorToJSON();
Greg Clayton358cf1e2015-06-25 21:46:34 +0000614 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) == PacketResult::Success)
615 {
616 if (response.IsUnsupportedResponse())
617 {
618 m_supports_jThreadsInfo = false;
619 }
620 else if (!response.Empty())
621 {
622 object_sp = StructuredData::ParseJSON (response.GetStringRef());
623 }
624 }
625 }
626 return object_sp;
627}
628
629
Jason Molendabdc4f122014-05-06 02:59:39 +0000630bool
Jason Molenda705b1802014-06-13 02:37:02 +0000631GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
632{
633 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
634 {
635 StringExtractorGDBRemote response;
636 m_supports_jThreadExtendedInfo = eLazyBoolNo;
637 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
638 {
639 if (response.IsOKResponse())
640 {
641 m_supports_jThreadExtendedInfo = eLazyBoolYes;
642 }
643 }
644 }
645 return m_supports_jThreadExtendedInfo;
646}
647
648bool
Jason Molenda20ee21b2015-07-10 23:15:22 +0000649GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported ()
650{
651 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate)
652 {
653 StringExtractorGDBRemote response;
654 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
655 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:", response, false) == PacketResult::Success)
656 {
657 if (response.IsOKResponse())
658 {
659 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
660 }
661 }
662 }
663 return m_supports_jLoadedDynamicLibrariesInfos;
664}
665
666bool
Jason Molenda37397352016-07-22 00:17:55 +0000667GDBRemoteCommunicationClient::GetSharedCacheInfoSupported ()
668{
669 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate)
670 {
671 StringExtractorGDBRemote response;
672 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
673 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) == PacketResult::Success)
674 {
675 if (response.IsOKResponse())
676 {
677 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
678 }
679 }
680 }
681 return m_supports_jGetSharedCacheInfo;
682}
683
684bool
Jason Molendabdc4f122014-05-06 02:59:39 +0000685GDBRemoteCommunicationClient::GetxPacketSupported ()
686{
687 if (m_supports_x == eLazyBoolCalculate)
688 {
689 StringExtractorGDBRemote response;
690 m_supports_x = eLazyBoolNo;
691 char packet[256];
692 snprintf (packet, sizeof (packet), "x0,0");
693 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
694 {
695 if (response.IsOKResponse())
696 m_supports_x = eLazyBoolYes;
697 }
698 }
699 return m_supports_x;
700}
701
Greg Clayton3dedae12013-12-06 21:45:27 +0000702GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000703GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
704(
705 const char *payload_prefix,
706 std::string &response_string
707)
708{
Pavel Labathe768c4b2016-07-29 13:10:02 +0000709 Lock lock(*this, false);
710 if (!lock)
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000711 {
712 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
713 if (log)
714 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
715 payload_prefix);
716 return PacketResult::ErrorNoSequenceLock;
717 }
718
719 response_string = "";
720 std::string payload_prefix_str(payload_prefix);
721 unsigned int response_size = 0x1000;
722 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
723 response_size = GetRemoteMaxPacketSize();
724 }
725
726 for (unsigned int offset = 0; true; offset += response_size)
727 {
728 StringExtractorGDBRemote this_response;
729 // Construct payload
730 char sizeDescriptor[128];
731 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
Pavel Labathe768c4b2016-07-29 13:10:02 +0000732 PacketResult result = SendPacketAndWaitForResponseNoLock(payload_prefix_str + sizeDescriptor, this_response);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000733 if (result != PacketResult::Success)
734 return result;
735
736 const std::string &this_string = this_response.GetStringRef();
737
738 // Check for m or l as first character; l seems to mean this is the last chunk
739 char first_char = *this_string.c_str();
740 if (first_char != 'm' && first_char != 'l')
741 {
742 return PacketResult::ErrorReplyInvalid;
743 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000744 // Concatenate the result so far (skipping 'm' or 'l')
745 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000746 if (first_char == 'l')
747 // We're done
748 return PacketResult::Success;
749 }
750}
751
Greg Clayton576d8832011-03-22 04:00:09 +0000752lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000753GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +0000754{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000755 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000756 return m_curr_pid;
757
758 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +0000759 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000760 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +0000761 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000762 // We really got it.
763 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +0000764 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000765 else
766 {
Todd Fialae24614f2014-05-14 00:15:32 +0000767 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
768 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
769 // The gdb remote protocol documents $qC as returning the thread id, which newer
770 // debugserver and lldb-gdbserver stubs return correctly.
771 StringExtractorGDBRemote response;
772 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000773 {
Todd Fialae24614f2014-05-14 00:15:32 +0000774 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000775 {
Todd Fialae24614f2014-05-14 00:15:32 +0000776 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000777 {
Todd Fialae24614f2014-05-14 00:15:32 +0000778 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
779 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000780 {
Todd Fialae24614f2014-05-14 00:15:32 +0000781 m_curr_pid_is_valid = eLazyBoolYes;
782 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000783 }
784 }
785 }
786 }
Jaydeep Patil1142f832015-08-13 03:46:36 +0000787
788 // If we don't get a response for $qC, check if $qfThreadID gives us a result.
789 if (m_curr_pid == LLDB_INVALID_PROCESS_ID)
790 {
791 std::vector<lldb::tid_t> thread_ids;
792 bool sequence_mutex_unavailable;
793 size_t size;
794 size = GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
795 if (size && sequence_mutex_unavailable == false)
796 {
797 m_curr_pid = thread_ids.front();
798 m_curr_pid_is_valid = eLazyBoolYes;
799 return m_curr_pid;
800 }
801 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000802 }
803
Greg Clayton576d8832011-03-22 04:00:09 +0000804 return LLDB_INVALID_PROCESS_ID;
805}
806
807bool
808GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
809{
810 error_str.clear();
811 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000812 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000813 {
814 if (response.IsOKResponse())
815 return true;
816 if (response.GetChar() == 'E')
817 {
818 // A string the describes what failed when launching...
819 error_str = response.GetStringRef().substr(1);
820 }
821 else
822 {
823 error_str.assign ("unknown error occurred launching process");
824 }
825 }
826 else
827 {
Jim Ingham98d6da52012-06-28 20:30:23 +0000828 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +0000829 }
830 return false;
831}
832
833int
Greg Claytonfbb76342013-11-20 21:07:01 +0000834GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +0000835{
Greg Claytonfbb76342013-11-20 21:07:01 +0000836 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000837 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +0000838 std::vector<const char *> argv;
839 FileSpec exe_file = launch_info.GetExecutableFile();
840 std::string exe_path;
841 const char *arg = NULL;
842 const Args &launch_args = launch_info.GetArguments();
843 if (exe_file)
Chaoren Lind3173f32015-05-29 19:52:29 +0000844 exe_path = exe_file.GetPath(false);
Greg Claytonfbb76342013-11-20 21:07:01 +0000845 else
846 {
847 arg = launch_args.GetArgumentAtIndex(0);
848 if (arg)
849 exe_path = arg;
850 }
851 if (!exe_path.empty())
852 {
853 argv.push_back(exe_path.c_str());
854 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
855 {
856 if (arg)
857 argv.push_back(arg);
858 }
859 }
860 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +0000861 {
862 StreamString packet;
863 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +0000864 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +0000865 {
Greg Claytonfbb76342013-11-20 21:07:01 +0000866 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +0000867 const int arg_len = strlen(arg);
868 if (i > 0)
869 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +0000870 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +0000871 packet.PutBytesAsRawHex8 (arg, arg_len);
872 }
873
874 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000875 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000876 {
877 if (response.IsOKResponse())
878 return 0;
879 uint8_t error = response.GetError();
880 if (error)
881 return error;
882 }
883 }
884 return -1;
885}
886
887int
888GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
889{
890 if (name_equal_value && name_equal_value[0])
891 {
892 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +0000893 bool send_hex_encoding = false;
894 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +0000895 {
Greg Clayton89600582013-10-10 17:53:50 +0000896 if (isprint(*p))
897 {
898 switch (*p)
899 {
900 case '$':
901 case '#':
Jason Molenda60bdafb2015-11-05 23:51:05 +0000902 case '*':
Tim Northover974ff612015-11-09 22:05:05 +0000903 case '}':
Greg Clayton89600582013-10-10 17:53:50 +0000904 send_hex_encoding = true;
905 break;
906 default:
907 break;
908 }
909 }
910 else
911 {
912 // We have non printable characters, lets hex encode this...
913 send_hex_encoding = true;
914 }
915 }
916
917 StringExtractorGDBRemote response;
918 if (send_hex_encoding)
919 {
920 if (m_supports_QEnvironmentHexEncoded)
921 {
922 packet.PutCString("QEnvironmentHexEncoded:");
923 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +0000924 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +0000925 {
926 if (response.IsOKResponse())
927 return 0;
928 uint8_t error = response.GetError();
929 if (error)
930 return error;
931 if (response.IsUnsupportedResponse())
932 m_supports_QEnvironmentHexEncoded = false;
933 }
934 }
935
936 }
937 else if (m_supports_QEnvironment)
938 {
939 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +0000940 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +0000941 {
942 if (response.IsOKResponse())
943 return 0;
944 uint8_t error = response.GetError();
945 if (error)
946 return error;
947 if (response.IsUnsupportedResponse())
948 m_supports_QEnvironment = false;
949 }
Greg Clayton576d8832011-03-22 04:00:09 +0000950 }
951 }
952 return -1;
953}
954
Greg Claytonc4103b32011-05-08 04:53:50 +0000955int
956GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
957{
958 if (arch && arch[0])
959 {
960 StreamString packet;
961 packet.Printf("QLaunchArch:%s", arch);
962 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000963 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +0000964 {
965 if (response.IsOKResponse())
966 return 0;
967 uint8_t error = response.GetError();
968 if (error)
969 return error;
970 }
971 }
972 return -1;
973}
974
Jason Molendaa3329782014-03-29 18:54:20 +0000975int
976GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
977{
978 if (data && *data != '\0')
979 {
980 StreamString packet;
981 packet.Printf("QSetProcessEvent:%s", data);
982 StringExtractorGDBRemote response;
983 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
984 {
985 if (response.IsOKResponse())
986 {
987 if (was_supported)
988 *was_supported = true;
989 return 0;
990 }
991 else if (response.IsUnsupportedResponse())
992 {
993 if (was_supported)
994 *was_supported = false;
995 return -1;
996 }
997 else
998 {
999 uint8_t error = response.GetError();
1000 if (was_supported)
1001 *was_supported = true;
1002 if (error)
1003 return error;
1004 }
1005 }
1006 }
1007 return -1;
1008}
1009
Greg Clayton576d8832011-03-22 04:00:09 +00001010bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001011GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1012 uint32_t &minor,
1013 uint32_t &update)
1014{
1015 if (GetHostInfo ())
1016 {
1017 if (m_os_version_major != UINT32_MAX)
1018 {
1019 major = m_os_version_major;
1020 minor = m_os_version_minor;
1021 update = m_os_version_update;
1022 return true;
1023 }
1024 }
1025 return false;
1026}
1027
1028bool
1029GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1030{
1031 if (GetHostInfo ())
1032 {
1033 if (!m_os_build.empty())
1034 {
1035 s = m_os_build;
1036 return true;
1037 }
1038 }
1039 s.clear();
1040 return false;
1041}
1042
1043
1044bool
1045GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1046{
1047 if (GetHostInfo ())
1048 {
1049 if (!m_os_kernel.empty())
1050 {
1051 s = m_os_kernel;
1052 return true;
1053 }
1054 }
1055 s.clear();
1056 return false;
1057}
1058
1059bool
1060GDBRemoteCommunicationClient::GetHostname (std::string &s)
1061{
1062 if (GetHostInfo ())
1063 {
1064 if (!m_hostname.empty())
1065 {
1066 s = m_hostname;
1067 return true;
1068 }
1069 }
1070 s.clear();
1071 return false;
1072}
1073
1074ArchSpec
1075GDBRemoteCommunicationClient::GetSystemArchitecture ()
1076{
1077 if (GetHostInfo ())
1078 return m_host_arch;
1079 return ArchSpec();
1080}
1081
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001082const lldb_private::ArchSpec &
1083GDBRemoteCommunicationClient::GetProcessArchitecture ()
1084{
1085 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1086 GetCurrentProcessInfo ();
1087 return m_process_arch;
1088}
1089
Jason Molendaa3329782014-03-29 18:54:20 +00001090bool
1091GDBRemoteCommunicationClient::GetGDBServerVersion()
1092{
1093 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1094 {
1095 m_gdb_server_name.clear();
1096 m_gdb_server_version = 0;
1097 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1098
1099 StringExtractorGDBRemote response;
1100 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1101 {
1102 if (response.IsNormalResponse())
1103 {
1104 std::string name;
1105 std::string value;
1106 bool success = false;
1107 while (response.GetNameColonValue(name, value))
1108 {
1109 if (name.compare("name") == 0)
1110 {
1111 success = true;
1112 m_gdb_server_name.swap(value);
1113 }
1114 else if (name.compare("version") == 0)
1115 {
1116 size_t dot_pos = value.find('.');
1117 if (dot_pos != std::string::npos)
1118 value[dot_pos] = '\0';
Vince Harron5275aaa2015-01-15 20:08:35 +00001119 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molendaa3329782014-03-29 18:54:20 +00001120 if (version != UINT32_MAX)
1121 {
1122 success = true;
1123 m_gdb_server_version = version;
1124 }
1125 }
1126 }
1127 if (success)
1128 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1129 }
1130 }
1131 }
1132 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1133}
1134
Jason Molenda91ffe0a2015-06-18 21:46:06 +00001135void
1136GDBRemoteCommunicationClient::MaybeEnableCompression (std::vector<std::string> supported_compressions)
1137{
1138 CompressionType avail_type = CompressionType::None;
1139 std::string avail_name;
1140
1141#if defined (HAVE_LIBCOMPRESSION)
1142 // libcompression is weak linked so test if compression_decode_buffer() is available
1143 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1144 {
1145 for (auto compression : supported_compressions)
1146 {
1147 if (compression == "lzfse")
1148 {
1149 avail_type = CompressionType::LZFSE;
1150 avail_name = compression;
1151 break;
1152 }
1153 }
1154 }
1155#endif
1156
1157#if defined (HAVE_LIBCOMPRESSION)
1158 // libcompression is weak linked so test if compression_decode_buffer() is available
1159 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1160 {
1161 for (auto compression : supported_compressions)
1162 {
1163 if (compression == "zlib-deflate")
1164 {
1165 avail_type = CompressionType::ZlibDeflate;
1166 avail_name = compression;
1167 break;
1168 }
1169 }
1170 }
1171#endif
1172
1173#if defined (HAVE_LIBZ)
1174 if (avail_type == CompressionType::None)
1175 {
1176 for (auto compression : supported_compressions)
1177 {
1178 if (compression == "zlib-deflate")
1179 {
1180 avail_type = CompressionType::ZlibDeflate;
1181 avail_name = compression;
1182 break;
1183 }
1184 }
1185 }
1186#endif
1187
1188#if defined (HAVE_LIBCOMPRESSION)
1189 // libcompression is weak linked so test if compression_decode_buffer() is available
1190 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1191 {
1192 for (auto compression : supported_compressions)
1193 {
1194 if (compression == "lz4")
1195 {
1196 avail_type = CompressionType::LZ4;
1197 avail_name = compression;
1198 break;
1199 }
1200 }
1201 }
1202#endif
1203
1204#if defined (HAVE_LIBCOMPRESSION)
1205 // libcompression is weak linked so test if compression_decode_buffer() is available
1206 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1207 {
1208 for (auto compression : supported_compressions)
1209 {
1210 if (compression == "lzma")
1211 {
1212 avail_type = CompressionType::LZMA;
1213 avail_name = compression;
1214 break;
1215 }
1216 }
1217 }
1218#endif
1219
1220 if (avail_type != CompressionType::None)
1221 {
1222 StringExtractorGDBRemote response;
1223 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1224 if (SendPacketAndWaitForResponse (packet.c_str(), response, false) != PacketResult::Success)
1225 return;
1226
1227 if (response.IsOKResponse())
1228 {
1229 m_compression_type = avail_type;
1230 }
1231 }
1232}
1233
Jason Molendaa3329782014-03-29 18:54:20 +00001234const char *
1235GDBRemoteCommunicationClient::GetGDBServerProgramName()
1236{
1237 if (GetGDBServerVersion())
1238 {
1239 if (!m_gdb_server_name.empty())
1240 return m_gdb_server_name.c_str();
1241 }
1242 return NULL;
1243}
1244
1245uint32_t
1246GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1247{
1248 if (GetGDBServerVersion())
1249 return m_gdb_server_version;
1250 return 0;
1251}
Greg Clayton1cb64962011-03-24 04:28:38 +00001252
1253bool
Ewan Crawford78baa192015-05-13 09:18:18 +00001254GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1255{
1256 StringExtractorGDBRemote response;
1257 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1258 return false;
1259
1260 if (!response.IsNormalResponse())
1261 return false;
1262
1263 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1264 tid = response.GetHexMaxU32(true, -1);
1265
1266 return true;
1267}
1268
1269bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001270GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001271{
Todd Fialaaf245d12014-06-30 21:05:18 +00001272 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1273
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001274 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001275 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001276 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001277 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001278 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001279 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001280 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001281 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001282 std::string name;
1283 std::string value;
1284 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1285 uint32_t sub = 0;
1286 std::string arch_name;
1287 std::string os_name;
1288 std::string vendor_name;
1289 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001290 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001291 uint32_t pointer_byte_size = 0;
1292 StringExtractor extractor;
1293 ByteOrder byte_order = eByteOrderInvalid;
1294 uint32_t num_keys_decoded = 0;
1295 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001296 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001297 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001298 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001299 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001300 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001301 if (cpu != LLDB_INVALID_CPUTYPE)
1302 ++num_keys_decoded;
1303 }
1304 else if (name.compare("cpusubtype") == 0)
1305 {
1306 // exception count in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001307 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001308 if (sub != 0)
1309 ++num_keys_decoded;
1310 }
1311 else if (name.compare("arch") == 0)
1312 {
1313 arch_name.swap (value);
1314 ++num_keys_decoded;
1315 }
1316 else if (name.compare("triple") == 0)
1317 {
Greg Clayton44272a42014-09-18 00:18:32 +00001318 extractor.GetStringRef ().swap (value);
1319 extractor.SetFilePos(0);
1320 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00001321 ++num_keys_decoded;
1322 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001323 else if (name.compare ("distribution_id") == 0)
1324 {
1325 extractor.GetStringRef ().swap (value);
1326 extractor.SetFilePos (0);
1327 extractor.GetHexByteString (distribution_id);
1328 ++num_keys_decoded;
1329 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001330 else if (name.compare("os_build") == 0)
1331 {
1332 extractor.GetStringRef().swap(value);
1333 extractor.SetFilePos(0);
1334 extractor.GetHexByteString (m_os_build);
1335 ++num_keys_decoded;
1336 }
1337 else if (name.compare("hostname") == 0)
1338 {
1339 extractor.GetStringRef().swap(value);
1340 extractor.SetFilePos(0);
1341 extractor.GetHexByteString (m_hostname);
1342 ++num_keys_decoded;
1343 }
1344 else if (name.compare("os_kernel") == 0)
1345 {
1346 extractor.GetStringRef().swap(value);
1347 extractor.SetFilePos(0);
1348 extractor.GetHexByteString (m_os_kernel);
1349 ++num_keys_decoded;
1350 }
1351 else if (name.compare("ostype") == 0)
1352 {
1353 os_name.swap (value);
1354 ++num_keys_decoded;
1355 }
1356 else if (name.compare("vendor") == 0)
1357 {
1358 vendor_name.swap(value);
1359 ++num_keys_decoded;
1360 }
1361 else if (name.compare("endian") == 0)
1362 {
1363 ++num_keys_decoded;
1364 if (value.compare("little") == 0)
1365 byte_order = eByteOrderLittle;
1366 else if (value.compare("big") == 0)
1367 byte_order = eByteOrderBig;
1368 else if (value.compare("pdp") == 0)
1369 byte_order = eByteOrderPDP;
1370 else
1371 --num_keys_decoded;
1372 }
1373 else if (name.compare("ptrsize") == 0)
1374 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001375 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001376 if (pointer_byte_size != 0)
1377 ++num_keys_decoded;
1378 }
Greg Clayton17499dd2016-01-28 00:16:11 +00001379 else if ((name.compare("os_version") == 0) ||
1380 (name.compare("version") == 0)) // Older debugserver binaries used the "version" key instead of "os_version"...
Greg Clayton32e0a752011-03-30 18:16:51 +00001381 {
1382 Args::StringToVersion (value.c_str(),
1383 m_os_version_major,
1384 m_os_version_minor,
1385 m_os_version_update);
1386 if (m_os_version_major != UINT32_MAX)
1387 ++num_keys_decoded;
1388 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001389 else if (name.compare("watchpoint_exceptions_received") == 0)
1390 {
1391 ++num_keys_decoded;
1392 if (strcmp(value.c_str(),"before") == 0)
1393 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1394 else if (strcmp(value.c_str(),"after") == 0)
1395 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1396 else
1397 --num_keys_decoded;
1398 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001399 else if (name.compare("default_packet_timeout") == 0)
1400 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001401 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001402 if (m_default_packet_timeout > 0)
1403 {
1404 SetPacketTimeout(m_default_packet_timeout);
1405 ++num_keys_decoded;
1406 }
1407 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001408
Greg Clayton32e0a752011-03-30 18:16:51 +00001409 }
1410
1411 if (num_keys_decoded > 0)
1412 m_qHostInfo_is_valid = eLazyBoolYes;
1413
1414 if (triple.empty())
1415 {
1416 if (arch_name.empty())
1417 {
1418 if (cpu != LLDB_INVALID_CPUTYPE)
1419 {
1420 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1421 if (pointer_byte_size)
1422 {
1423 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1424 }
1425 if (byte_order != eByteOrderInvalid)
1426 {
1427 assert (byte_order == m_host_arch.GetByteOrder());
1428 }
Greg Clayton70512312012-05-08 01:45:38 +00001429
Greg Clayton32e0a752011-03-30 18:16:51 +00001430 if (!vendor_name.empty())
1431 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1432 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001433 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001434
1435 }
1436 }
1437 else
1438 {
1439 std::string triple;
1440 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001441 if (!vendor_name.empty() || !os_name.empty())
1442 {
1443 triple += '-';
1444 if (vendor_name.empty())
1445 triple += "unknown";
1446 else
1447 triple += vendor_name;
1448 triple += '-';
1449 if (os_name.empty())
1450 triple += "unknown";
1451 else
1452 triple += os_name;
1453 }
1454 m_host_arch.SetTriple (triple.c_str());
1455
1456 llvm::Triple &host_triple = m_host_arch.GetTriple();
1457 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1458 {
1459 switch (m_host_arch.GetMachine())
1460 {
Todd Fialad8eaa172014-07-23 14:37:35 +00001461 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00001462 case llvm::Triple::arm:
1463 case llvm::Triple::thumb:
1464 host_triple.setOS(llvm::Triple::IOS);
1465 break;
1466 default:
1467 host_triple.setOS(llvm::Triple::MacOSX);
1468 break;
1469 }
1470 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001471 if (pointer_byte_size)
1472 {
1473 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1474 }
1475 if (byte_order != eByteOrderInvalid)
1476 {
1477 assert (byte_order == m_host_arch.GetByteOrder());
1478 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001479
Greg Clayton1cb64962011-03-24 04:28:38 +00001480 }
1481 }
1482 else
1483 {
Greg Clayton70512312012-05-08 01:45:38 +00001484 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001485 if (pointer_byte_size)
1486 {
1487 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1488 }
1489 if (byte_order != eByteOrderInvalid)
1490 {
1491 assert (byte_order == m_host_arch.GetByteOrder());
1492 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001493
1494 if (log)
1495 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 +00001496 }
1497 if (!distribution_id.empty ())
1498 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00001499 }
Greg Clayton576d8832011-03-22 04:00:09 +00001500 }
1501 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001502 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001503}
1504
1505int
1506GDBRemoteCommunicationClient::SendAttach
1507(
1508 lldb::pid_t pid,
1509 StringExtractorGDBRemote& response
1510)
1511{
1512 if (pid != LLDB_INVALID_PROCESS_ID)
1513 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001514 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001515 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001516 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00001517 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001518 {
1519 if (response.IsErrorResponse())
1520 return response.GetError();
1521 return 0;
1522 }
1523 }
1524 return -1;
1525}
1526
Vince Harrone0be4252015-02-06 18:32:57 +00001527int
1528GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
1529{
1530 StreamString packet;
1531 packet.PutCString("I");
1532 packet.PutBytesAsRawHex8(data, data_len);
1533 StringExtractorGDBRemote response;
1534 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1535 {
1536 return 0;
1537 }
1538 return response.GetError();
1539
1540}
1541
Greg Clayton576d8832011-03-22 04:00:09 +00001542const lldb_private::ArchSpec &
1543GDBRemoteCommunicationClient::GetHostArchitecture ()
1544{
Greg Clayton32e0a752011-03-30 18:16:51 +00001545 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001546 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001547 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001548}
1549
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001550uint32_t
1551GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1552{
1553 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1554 GetHostInfo ();
1555 return m_default_packet_timeout;
1556}
1557
Greg Clayton576d8832011-03-22 04:00:09 +00001558addr_t
1559GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1560{
Greg Clayton70b57652011-05-15 01:25:55 +00001561 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001562 {
Greg Clayton70b57652011-05-15 01:25:55 +00001563 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001564 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001565 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001566 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001567 permissions & lldb::ePermissionsReadable ? "r" : "",
1568 permissions & lldb::ePermissionsWritable ? "w" : "",
1569 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001570 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001571 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001572 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001573 {
Todd Fialaf105f582014-06-21 00:48:09 +00001574 if (response.IsUnsupportedResponse())
1575 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1576 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001577 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1578 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001579 else
1580 {
1581 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1582 }
Greg Clayton576d8832011-03-22 04:00:09 +00001583 }
1584 return LLDB_INVALID_ADDRESS;
1585}
1586
1587bool
1588GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1589{
Greg Clayton70b57652011-05-15 01:25:55 +00001590 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001591 {
Greg Clayton70b57652011-05-15 01:25:55 +00001592 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001593 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001594 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001595 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001596 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001597 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001598 {
Todd Fialaf105f582014-06-21 00:48:09 +00001599 if (response.IsUnsupportedResponse())
1600 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1601 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001602 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001603 }
1604 else
1605 {
1606 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00001607 }
Greg Clayton576d8832011-03-22 04:00:09 +00001608 }
1609 return false;
1610}
1611
Jim Inghamacff8952013-05-02 00:27:30 +00001612Error
1613GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00001614{
Jim Inghamacff8952013-05-02 00:27:30 +00001615 Error error;
1616
1617 if (keep_stopped)
1618 {
1619 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1620 {
1621 char packet[64];
1622 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001623 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00001624 StringExtractorGDBRemote response;
Jim Ingham4920a4e2015-07-15 00:59:25 +00001625 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success
1626 && response.IsOKResponse())
Jim Inghamacff8952013-05-02 00:27:30 +00001627 {
1628 m_supports_detach_stay_stopped = eLazyBoolYes;
1629 }
1630 else
1631 {
1632 m_supports_detach_stay_stopped = eLazyBoolNo;
1633 }
1634 }
1635
1636 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1637 {
1638 error.SetErrorString("Stays stopped not supported by this target.");
1639 return error;
1640 }
1641 else
1642 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00001643 StringExtractorGDBRemote response;
Jason Molenda2a667382015-07-15 00:16:09 +00001644 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 2, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00001645 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001646 error.SetErrorString ("Sending extended disconnect packet failed.");
1647 }
1648 }
1649 else
1650 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00001651 StringExtractorGDBRemote response;
1652 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00001653 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001654 error.SetErrorString ("Sending disconnect packet failed.");
1655 }
1656 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001657}
1658
Greg Clayton46fb5582011-11-18 07:03:08 +00001659Error
1660GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1661 lldb_private::MemoryRegionInfo &region_info)
1662{
1663 Error error;
1664 region_info.Clear();
1665
1666 if (m_supports_memory_region_info != eLazyBoolNo)
1667 {
1668 m_supports_memory_region_info = eLazyBoolYes;
1669 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001670 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001671 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00001672 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001673 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00001674 {
1675 std::string name;
1676 std::string value;
1677 addr_t addr_value;
1678 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00001679 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00001680 while (success && response.GetNameColonValue(name, value))
1681 {
1682 if (name.compare ("start") == 0)
1683 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001684 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00001685 if (success)
1686 region_info.GetRange().SetRangeBase(addr_value);
1687 }
1688 else if (name.compare ("size") == 0)
1689 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001690 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00001691 if (success)
1692 region_info.GetRange().SetByteSize (addr_value);
1693 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001694 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00001695 {
Jason Molendacb349ee2011-12-13 05:39:38 +00001696 saw_permissions = true;
1697 if (region_info.GetRange().Contains (addr))
1698 {
1699 if (value.find('r') != std::string::npos)
1700 region_info.SetReadable (MemoryRegionInfo::eYes);
1701 else
1702 region_info.SetReadable (MemoryRegionInfo::eNo);
1703
1704 if (value.find('w') != std::string::npos)
1705 region_info.SetWritable (MemoryRegionInfo::eYes);
1706 else
1707 region_info.SetWritable (MemoryRegionInfo::eNo);
1708
1709 if (value.find('x') != std::string::npos)
1710 region_info.SetExecutable (MemoryRegionInfo::eYes);
1711 else
1712 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00001713
1714 region_info.SetMapped(MemoryRegionInfo::eYes);
Jason Molendacb349ee2011-12-13 05:39:38 +00001715 }
1716 else
1717 {
1718 // The reported region does not contain this address -- we're looking at an unmapped page
1719 region_info.SetReadable (MemoryRegionInfo::eNo);
1720 region_info.SetWritable (MemoryRegionInfo::eNo);
1721 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00001722 region_info.SetMapped(MemoryRegionInfo::eNo);
Jason Molendacb349ee2011-12-13 05:39:38 +00001723 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001724 }
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001725 else if (name.compare ("name") == 0)
1726 {
1727 StringExtractorGDBRemote name_extractor;
1728 name_extractor.GetStringRef().swap(value);
1729 name_extractor.GetHexByteString(value);
1730 region_info.SetName(value.c_str());
1731 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001732 else if (name.compare ("error") == 0)
1733 {
1734 StringExtractorGDBRemote name_extractor;
1735 // Swap "value" over into "name_extractor"
1736 name_extractor.GetStringRef().swap(value);
1737 // Now convert the HEX bytes into a string value
1738 name_extractor.GetHexByteString (value);
1739 error.SetErrorString(value.c_str());
1740 }
1741 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001742
1743 // We got a valid address range back but no permissions -- which means this is an unmapped page
1744 if (region_info.GetRange().IsValid() && saw_permissions == false)
1745 {
1746 region_info.SetReadable (MemoryRegionInfo::eNo);
1747 region_info.SetWritable (MemoryRegionInfo::eNo);
1748 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00001749 region_info.SetMapped(MemoryRegionInfo::eNo);
Jason Molendacb349ee2011-12-13 05:39:38 +00001750 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001751 }
1752 else
1753 {
1754 m_supports_memory_region_info = eLazyBoolNo;
1755 }
1756 }
1757
1758 if (m_supports_memory_region_info == eLazyBoolNo)
1759 {
1760 error.SetErrorString("qMemoryRegionInfo is not supported");
1761 }
1762 if (error.Fail())
1763 region_info.Clear();
1764 return error;
1765
1766}
1767
Johnny Chen64637202012-05-23 21:09:52 +00001768Error
1769GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1770{
1771 Error error;
1772
1773 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1774 {
1775 num = m_num_supported_hardware_watchpoints;
1776 return error;
1777 }
1778
1779 // Set num to 0 first.
1780 num = 0;
1781 if (m_supports_watchpoint_support_info != eLazyBoolNo)
1782 {
1783 char packet[64];
1784 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001785 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00001786 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001787 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00001788 {
1789 m_supports_watchpoint_support_info = eLazyBoolYes;
1790 std::string name;
1791 std::string value;
1792 while (response.GetNameColonValue(name, value))
1793 {
1794 if (name.compare ("num") == 0)
1795 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001796 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
Johnny Chen64637202012-05-23 21:09:52 +00001797 m_num_supported_hardware_watchpoints = num;
1798 }
1799 }
1800 }
1801 else
1802 {
1803 m_supports_watchpoint_support_info = eLazyBoolNo;
1804 }
1805 }
1806
1807 if (m_supports_watchpoint_support_info == eLazyBoolNo)
1808 {
1809 error.SetErrorString("qWatchpointSupportInfo is not supported");
1810 }
1811 return error;
1812
1813}
Greg Clayton46fb5582011-11-18 07:03:08 +00001814
Enrico Granataf04a2192012-07-13 23:18:48 +00001815lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00001816GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00001817{
1818 Error error(GetWatchpointSupportInfo(num));
1819 if (error.Success())
Jaydeep Patil725666c2015-08-13 03:46:01 +00001820 error = GetWatchpointsTriggerAfterInstruction(after, arch);
Enrico Granataf04a2192012-07-13 23:18:48 +00001821 return error;
1822}
1823
1824lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00001825GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00001826{
1827 Error error;
Jaydeep Patil725666c2015-08-13 03:46:01 +00001828 llvm::Triple::ArchType atype = arch.GetMachine();
Enrico Granataf04a2192012-07-13 23:18:48 +00001829
1830 // we assume watchpoints will happen after running the relevant opcode
1831 // and we only want to override this behavior if we have explicitly
1832 // received a qHostInfo telling us otherwise
1833 if (m_qHostInfo_is_valid != eLazyBoolYes)
Jaydeep Patil725666c2015-08-13 03:46:01 +00001834 {
1835 // On targets like MIPS, watchpoint exceptions are always generated
1836 // before the instruction is executed. The connected target may not
1837 // support qHostInfo or qWatchpointSupportInfo packets.
1838 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
1839 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
1840 after = false;
1841 else
1842 after = true;
1843 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001844 else
Jaydeep Patil725666c2015-08-13 03:46:01 +00001845 {
1846 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
1847 // if it is not calculated before.
1848 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
1849 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
1850 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
1851 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1852
Enrico Granataf04a2192012-07-13 23:18:48 +00001853 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
Jaydeep Patil725666c2015-08-13 03:46:01 +00001854 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001855 return error;
1856}
1857
Greg Clayton576d8832011-03-22 04:00:09 +00001858int
Chaoren Lind3173f32015-05-29 19:52:29 +00001859GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001860{
Chaoren Lind3173f32015-05-29 19:52:29 +00001861 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001862 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001863 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001864 StreamString packet;
1865 packet.PutCString("QSetSTDIN:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001866 packet.PutCStringAsRawHex8(path.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00001867
1868 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001869 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001870 {
1871 if (response.IsOKResponse())
1872 return 0;
1873 uint8_t error = response.GetError();
1874 if (error)
1875 return error;
1876 }
1877 }
1878 return -1;
1879}
1880
1881int
Chaoren Lind3173f32015-05-29 19:52:29 +00001882GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001883{
Chaoren Lind3173f32015-05-29 19:52:29 +00001884 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001885 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001886 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001887 StreamString packet;
1888 packet.PutCString("QSetSTDOUT:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001889 packet.PutCStringAsRawHex8(path.c_str());
1890
Greg Clayton576d8832011-03-22 04:00:09 +00001891 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001892 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001893 {
1894 if (response.IsOKResponse())
1895 return 0;
1896 uint8_t error = response.GetError();
1897 if (error)
1898 return error;
1899 }
1900 }
1901 return -1;
1902}
1903
1904int
Chaoren Lind3173f32015-05-29 19:52:29 +00001905GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001906{
Chaoren Lind3173f32015-05-29 19:52:29 +00001907 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00001908 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001909 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001910 StreamString packet;
1911 packet.PutCString("QSetSTDERR:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001912 packet.PutCStringAsRawHex8(path.c_str());
1913
Greg Clayton576d8832011-03-22 04:00:09 +00001914 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001915 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001916 {
1917 if (response.IsOKResponse())
1918 return 0;
1919 uint8_t error = response.GetError();
1920 if (error)
1921 return error;
1922 }
1923 }
1924 return -1;
1925}
1926
Greg Claytonfbb76342013-11-20 21:07:01 +00001927bool
Chaoren Lind3173f32015-05-29 19:52:29 +00001928GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
Greg Claytonfbb76342013-11-20 21:07:01 +00001929{
1930 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001931 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00001932 {
1933 if (response.IsUnsupportedResponse())
1934 return false;
1935 if (response.IsErrorResponse())
1936 return false;
Chaoren Lind3173f32015-05-29 19:52:29 +00001937 std::string cwd;
1938 response.GetHexByteString(cwd);
Chaoren Lin44145d72015-05-29 19:52:37 +00001939 working_dir.SetFile(cwd, false, GetHostArchitecture());
Greg Claytonfbb76342013-11-20 21:07:01 +00001940 return !cwd.empty();
1941 }
1942 return false;
1943}
1944
Greg Clayton576d8832011-03-22 04:00:09 +00001945int
Chaoren Lind3173f32015-05-29 19:52:29 +00001946GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00001947{
Chaoren Lind3173f32015-05-29 19:52:29 +00001948 if (working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00001949 {
Chaoren Lind3173f32015-05-29 19:52:29 +00001950 std::string path{working_dir.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00001951 StreamString packet;
1952 packet.PutCString("QSetWorkingDir:");
Chaoren Lind3173f32015-05-29 19:52:29 +00001953 packet.PutCStringAsRawHex8(path.c_str());
1954
Greg Clayton576d8832011-03-22 04:00:09 +00001955 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001956 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001957 {
1958 if (response.IsOKResponse())
1959 return 0;
1960 uint8_t error = response.GetError();
1961 if (error)
1962 return error;
1963 }
1964 }
1965 return -1;
1966}
1967
1968int
1969GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1970{
Greg Clayton32e0a752011-03-30 18:16:51 +00001971 char packet[32];
1972 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00001973 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00001974 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001975 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001976 {
1977 if (response.IsOKResponse())
1978 return 0;
1979 uint8_t error = response.GetError();
1980 if (error)
1981 return error;
1982 }
1983 return -1;
1984}
Greg Clayton32e0a752011-03-30 18:16:51 +00001985
Jim Ingham106d0282014-06-25 02:32:56 +00001986int
1987GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
1988{
1989 char packet[32];
1990 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
1991 assert (packet_len < (int)sizeof(packet));
1992 StringExtractorGDBRemote response;
1993 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
1994 {
1995 if (response.IsOKResponse())
1996 return 0;
1997 uint8_t error = response.GetError();
1998 if (error)
1999 return error;
2000 }
2001 return -1;
2002}
2003
2004
Greg Clayton32e0a752011-03-30 18:16:51 +00002005bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002006GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002007{
2008 if (response.IsNormalResponse())
2009 {
2010 std::string name;
2011 std::string value;
2012 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002013
2014 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2015 uint32_t sub = 0;
2016 std::string vendor;
2017 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002018
2019 while (response.GetNameColonValue(name, value))
2020 {
2021 if (name.compare("pid") == 0)
2022 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002023 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002024 }
2025 else if (name.compare("ppid") == 0)
2026 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002027 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002028 }
2029 else if (name.compare("uid") == 0)
2030 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002031 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002032 }
2033 else if (name.compare("euid") == 0)
2034 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002035 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002036 }
2037 else if (name.compare("gid") == 0)
2038 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002039 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002040 }
2041 else if (name.compare("egid") == 0)
2042 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002043 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002044 }
2045 else if (name.compare("triple") == 0)
2046 {
Greg Clayton44272a42014-09-18 00:18:32 +00002047 StringExtractor extractor;
2048 extractor.GetStringRef().swap(value);
2049 extractor.SetFilePos(0);
2050 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002051 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002052 }
2053 else if (name.compare("name") == 0)
2054 {
2055 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002056 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002057 // control the characters in a process name
2058 extractor.GetStringRef().swap(value);
2059 extractor.SetFilePos(0);
2060 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002061 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002062 }
Jason Molenda89c37492014-01-27 22:23:20 +00002063 else if (name.compare("cputype") == 0)
2064 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002065 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002066 }
2067 else if (name.compare("cpusubtype") == 0)
2068 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002069 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002070 }
2071 else if (name.compare("vendor") == 0)
2072 {
2073 vendor = value;
2074 }
2075 else if (name.compare("ostype") == 0)
2076 {
2077 os_type = value;
2078 }
2079 }
2080
2081 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2082 {
2083 if (vendor == "apple")
2084 {
2085 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2086 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2087 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2088 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002089 }
2090
2091 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2092 return true;
2093 }
2094 return false;
2095}
2096
2097bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002098GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002099{
2100 process_info.Clear();
2101
2102 if (m_supports_qProcessInfoPID)
2103 {
2104 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002105 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002106 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002107 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002108 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002109 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002110 return DecodeProcessInfoResponse (response, process_info);
2111 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002112 else
2113 {
2114 m_supports_qProcessInfoPID = false;
2115 return false;
2116 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002117 }
2118 return false;
2119}
2120
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002121bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002122GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002123{
Todd Fiala3daa1762014-09-15 16:01:29 +00002124 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2125
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002126 if (allow_lazy)
2127 {
2128 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2129 return true;
2130 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2131 return false;
2132 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002133
2134 GetHostInfo ();
2135
2136 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002137 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002138 {
2139 if (response.IsNormalResponse())
2140 {
2141 std::string name;
2142 std::string value;
2143 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2144 uint32_t sub = 0;
2145 std::string arch_name;
2146 std::string os_name;
2147 std::string vendor_name;
2148 std::string triple;
2149 uint32_t pointer_byte_size = 0;
2150 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002151 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002152 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002153 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002154 while (response.GetNameColonValue(name, value))
2155 {
2156 if (name.compare("cputype") == 0)
2157 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002158 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002159 if (cpu != LLDB_INVALID_CPUTYPE)
2160 ++num_keys_decoded;
2161 }
2162 else if (name.compare("cpusubtype") == 0)
2163 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002164 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002165 if (sub != 0)
2166 ++num_keys_decoded;
2167 }
Todd Fialac540dd02014-08-26 18:21:02 +00002168 else if (name.compare("triple") == 0)
2169 {
Greg Clayton44272a42014-09-18 00:18:32 +00002170 StringExtractor extractor;
2171 extractor.GetStringRef().swap(value);
2172 extractor.SetFilePos(0);
2173 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002174 ++num_keys_decoded;
2175 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002176 else if (name.compare("ostype") == 0)
2177 {
2178 os_name.swap (value);
2179 ++num_keys_decoded;
2180 }
2181 else if (name.compare("vendor") == 0)
2182 {
2183 vendor_name.swap(value);
2184 ++num_keys_decoded;
2185 }
2186 else if (name.compare("endian") == 0)
2187 {
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002188 ++num_keys_decoded;
2189 if (value.compare("little") == 0)
2190 byte_order = eByteOrderLittle;
2191 else if (value.compare("big") == 0)
2192 byte_order = eByteOrderBig;
2193 else if (value.compare("pdp") == 0)
2194 byte_order = eByteOrderPDP;
2195 else
2196 --num_keys_decoded;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002197 }
2198 else if (name.compare("ptrsize") == 0)
2199 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002200 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002201 if (pointer_byte_size != 0)
2202 ++num_keys_decoded;
2203 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002204 else if (name.compare("pid") == 0)
2205 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002206 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002207 if (pid != LLDB_INVALID_PROCESS_ID)
2208 ++num_keys_decoded;
2209 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002210 }
2211 if (num_keys_decoded > 0)
2212 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002213 if (pid != LLDB_INVALID_PROCESS_ID)
2214 {
2215 m_curr_pid_is_valid = eLazyBoolYes;
2216 m_curr_pid = pid;
2217 }
Todd Fialac540dd02014-08-26 18:21:02 +00002218
2219 // Set the ArchSpec from the triple if we have it.
2220 if (!triple.empty ())
2221 {
2222 m_process_arch.SetTriple (triple.c_str ());
2223 if (pointer_byte_size)
2224 {
2225 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2226 }
2227 }
2228 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002229 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002230 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2231
2232 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2233 switch (triple.getObjectFormat()) {
2234 case llvm::Triple::MachO:
2235 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2236 break;
2237 case llvm::Triple::ELF:
2238 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2239 break;
2240 case llvm::Triple::COFF:
2241 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2242 break;
2243 case llvm::Triple::UnknownObjectFormat:
2244 if (log)
2245 log->Printf("error: failed to determine target architecture");
2246 return false;
2247 }
2248
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002249 if (pointer_byte_size)
2250 {
2251 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2252 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002253 if (byte_order != eByteOrderInvalid)
2254 {
2255 assert (byte_order == m_process_arch.GetByteOrder());
2256 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002257 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002258 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002259 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2260 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002261 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002262 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002263 }
2264 }
2265 else
2266 {
2267 m_qProcessInfo_is_valid = eLazyBoolNo;
2268 }
2269
2270 return false;
2271}
2272
2273
Greg Clayton32e0a752011-03-30 18:16:51 +00002274uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002275GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2276 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002277{
2278 process_infos.Clear();
2279
2280 if (m_supports_qfProcessInfo)
2281 {
2282 StreamString packet;
2283 packet.PutCString ("qfProcessInfo");
2284 if (!match_info.MatchAllProcesses())
2285 {
2286 packet.PutChar (':');
2287 const char *name = match_info.GetProcessInfo().GetName();
2288 bool has_name_match = false;
2289 if (name && name[0])
2290 {
2291 has_name_match = true;
2292 NameMatchType name_match_type = match_info.GetNameMatchType();
2293 switch (name_match_type)
2294 {
2295 case eNameMatchIgnore:
2296 has_name_match = false;
2297 break;
2298
2299 case eNameMatchEquals:
2300 packet.PutCString ("name_match:equals;");
2301 break;
2302
2303 case eNameMatchContains:
2304 packet.PutCString ("name_match:contains;");
2305 break;
2306
2307 case eNameMatchStartsWith:
2308 packet.PutCString ("name_match:starts_with;");
2309 break;
2310
2311 case eNameMatchEndsWith:
2312 packet.PutCString ("name_match:ends_with;");
2313 break;
2314
2315 case eNameMatchRegularExpression:
2316 packet.PutCString ("name_match:regex;");
2317 break;
2318 }
2319 if (has_name_match)
2320 {
2321 packet.PutCString ("name:");
2322 packet.PutBytesAsRawHex8(name, ::strlen(name));
2323 packet.PutChar (';');
2324 }
2325 }
2326
2327 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002328 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002329 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002330 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002331 if (match_info.GetProcessInfo().UserIDIsValid())
2332 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2333 if (match_info.GetProcessInfo().GroupIDIsValid())
2334 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002335 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2336 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2337 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2338 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2339 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2340 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2341 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2342 {
2343 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2344 const llvm::Triple &triple = match_arch.GetTriple();
2345 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00002346 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002347 packet.PutChar (';');
2348 }
2349 }
2350 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00002351 // Increase timeout as the first qfProcessInfo packet takes a long time
2352 // on Android. The value of 1min was arrived at empirically.
2353 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00002354 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002355 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002356 do
2357 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002358 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002359 if (!DecodeProcessInfoResponse (response, process_info))
2360 break;
2361 process_infos.Append(process_info);
2362 response.GetStringRef().clear();
2363 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00002364 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00002365 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002366 else
2367 {
2368 m_supports_qfProcessInfo = false;
2369 return 0;
2370 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002371 }
2372 return process_infos.GetSize();
2373
2374}
2375
2376bool
2377GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2378{
2379 if (m_supports_qUserName)
2380 {
2381 char packet[32];
2382 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002383 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002384 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002385 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002386 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002387 if (response.IsNormalResponse())
2388 {
2389 // Make sure we parsed the right number of characters. The response is
2390 // the hex encoded user name and should make up the entire packet.
2391 // If there are any non-hex ASCII bytes, the length won't match below..
2392 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2393 return true;
2394 }
2395 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002396 else
2397 {
2398 m_supports_qUserName = false;
2399 return false;
2400 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002401 }
2402 return false;
2403
2404}
2405
2406bool
2407GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2408{
2409 if (m_supports_qGroupName)
2410 {
2411 char packet[32];
2412 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002413 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002414 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002415 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002416 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002417 if (response.IsNormalResponse())
2418 {
2419 // Make sure we parsed the right number of characters. The response is
2420 // the hex encoded group name and should make up the entire packet.
2421 // If there are any non-hex ASCII bytes, the length won't match below..
2422 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2423 return true;
2424 }
2425 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002426 else
2427 {
2428 m_supports_qGroupName = false;
2429 return false;
2430 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002431 }
2432 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002433}
Greg Clayton32e0a752011-03-30 18:16:51 +00002434
Ewan Crawford78baa192015-05-13 09:18:18 +00002435bool
2436GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
2437{
2438 // Form non-stop packet request
2439 char packet[32];
2440 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2441 assert(packet_len < (int)sizeof(packet));
2442
2443 StringExtractorGDBRemote response;
2444 // Send to target
2445 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2446 if (response.IsOKResponse())
2447 return true;
2448
2449 // Failed or not supported
2450 return false;
2451
2452}
2453
Greg Claytone034a042015-05-21 20:52:06 +00002454static void
2455MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
2456{
2457 packet.Clear();
2458 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2459 uint32_t bytes_left = send_size;
2460 while (bytes_left > 0)
2461 {
2462 if (bytes_left >= 26)
2463 {
2464 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2465 bytes_left -= 26;
2466 }
2467 else
2468 {
2469 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2470 bytes_left = 0;
2471 }
2472 }
2473}
2474
2475template<typename T>
2476T calculate_standard_deviation(const std::vector<T> &v)
2477{
2478 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
2479 T mean = sum / (T)v.size();
2480 T accum = T(0);
2481 std::for_each (std::begin(v), std::end(v), [&](const T d) {
2482 T delta = d - mean;
2483 accum += delta * delta;
2484 });
2485
2486 T stdev = sqrt(accum / (v.size()-1));
2487 return stdev;
2488}
2489
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002490void
Greg Claytone034a042015-05-21 20:52:06 +00002491GDBRemoteCommunicationClient::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 +00002492{
2493 uint32_t i;
2494 TimeValue start_time, end_time;
2495 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002496 if (SendSpeedTestPacket (0, 0))
2497 {
Greg Claytone034a042015-05-21 20:52:06 +00002498 StreamString packet;
2499 if (json)
2500 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
2501 else
2502 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
2503 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00002504
Greg Claytone034a042015-05-21 20:52:06 +00002505 uint32_t result_idx = 0;
2506 uint32_t send_size;
2507 std::vector<float> packet_times;
2508
2509 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
2510 {
2511 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
2512 {
2513 MakeSpeedTestPacket (packet, send_size, recv_size);
2514
2515 packet_times.clear();
2516 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00002517 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00002518 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00002519 {
Greg Claytone034a042015-05-21 20:52:06 +00002520 TimeValue packet_start_time = TimeValue::Now();
2521 StringExtractorGDBRemote response;
2522 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2523 TimeValue packet_end_time = TimeValue::Now();
2524 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
2525 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002526 }
2527 end_time = TimeValue::Now();
2528 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00002529
2530 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2531 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
2532 float average_ms_per_packet = total_ms / num_packets;
2533 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
2534 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00002535 {
Greg Claytone034a042015-05-21 20:52:06 +00002536 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);
2537 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00002538 }
2539 else
2540 {
Greg Claytone034a042015-05-21 20:52:06 +00002541 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",
2542 send_size,
2543 recv_size,
2544 total_time_nsec / TimeValue::NanoSecPerSec,
2545 total_time_nsec % TimeValue::NanoSecPerSec,
2546 packets_per_second,
2547 average_ms_per_packet,
2548 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00002549 }
Greg Claytone034a042015-05-21 20:52:06 +00002550 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002551 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002552 }
Greg Claytone034a042015-05-21 20:52:06 +00002553
2554 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
2555
2556 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
2557 if (json)
2558 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
2559 else
2560 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
2561 strm.Flush();
2562 send_size = 0;
2563 result_idx = 0;
2564 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
2565 {
2566 MakeSpeedTestPacket (packet, send_size, recv_size);
2567
2568 // If we have a receive size, test how long it takes to receive 4MB of data
2569 if (recv_size > 0)
2570 {
2571 start_time = TimeValue::Now();
2572 uint32_t bytes_read = 0;
2573 uint32_t packet_count = 0;
2574 while (bytes_read < k_recv_amount)
2575 {
2576 StringExtractorGDBRemote response;
2577 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2578 bytes_read += recv_size;
2579 ++packet_count;
2580 }
2581 end_time = TimeValue::Now();
2582 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2583 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2584 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2585 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
2586 float average_ms_per_packet = total_ms / packet_count;
2587
2588 if (json)
2589 {
2590 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);
2591 ++result_idx;
2592 }
2593 else
2594 {
2595 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",
2596 send_size,
2597 recv_size,
2598 packet_count,
2599 k_recv_amount_mb,
2600 total_time_nsec / TimeValue::NanoSecPerSec,
2601 total_time_nsec % TimeValue::NanoSecPerSec,
2602 mb_second,
2603 packets_per_second,
2604 average_ms_per_packet);
2605 }
2606 strm.Flush();
2607 }
2608 }
2609 if (json)
2610 strm.Printf("\n ]\n }\n}\n");
2611 else
2612 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002613 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002614}
2615
2616bool
2617GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2618{
2619 StreamString packet;
2620 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2621 uint32_t bytes_left = send_size;
2622 while (bytes_left > 0)
2623 {
2624 if (bytes_left >= 26)
2625 {
2626 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2627 bytes_left -= 26;
2628 }
2629 else
2630 {
2631 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2632 bytes_left = 0;
2633 }
2634 }
2635
2636 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002637 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00002638}
Greg Clayton8b82f082011-04-12 05:54:46 +00002639
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002640bool
2641GDBRemoteCommunicationClient::LaunchGDBServer (const char *remote_accept_hostname,
2642 lldb::pid_t &pid,
2643 uint16_t &port,
2644 std::string &socket_name)
Greg Clayton8b82f082011-04-12 05:54:46 +00002645{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002646 pid = LLDB_INVALID_PROCESS_ID;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002647 port = 0;
2648 socket_name.clear();
2649
Greg Clayton8b82f082011-04-12 05:54:46 +00002650 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002651 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00002652 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002653 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00002654 if (remote_accept_hostname && remote_accept_hostname[0])
2655 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002656 else
2657 {
Zachary Turner97a14e62014-08-19 17:18:29 +00002658 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00002659 {
2660 // Make the GDB server we launch only accept connections from this host
2661 stream.Printf("host:%s;", hostname.c_str());
2662 }
2663 else
2664 {
2665 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2666 stream.Printf("host:*;");
2667 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002668 }
2669 const char *packet = stream.GetData();
2670 int packet_len = stream.GetSize();
2671
Vince Harron1b5a74e2015-01-21 22:42:49 +00002672 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00002673 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002674
Tamas Berghammer912800c2015-02-24 10:23:39 +00002675 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002676 {
2677 std::string name;
2678 std::string value;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002679 StringExtractor extractor;
Greg Clayton8b82f082011-04-12 05:54:46 +00002680 while (response.GetNameColonValue(name, value))
2681 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00002682 if (name.compare("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00002683 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002684 else if (name.compare("pid") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00002685 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002686 else if (name.compare("socket_name") == 0)
2687 {
2688 extractor.GetStringRef().swap(value);
2689 extractor.SetFilePos(0);
2690 extractor.GetHexByteString(value);
2691
2692 socket_name = value;
2693 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002694 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002695 return true;
Greg Clayton8b82f082011-04-12 05:54:46 +00002696 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00002697 return false;
Greg Clayton8b82f082011-04-12 05:54:46 +00002698}
2699
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00002700size_t
2701GDBRemoteCommunicationClient::QueryGDBServer (std::vector<std::pair<uint16_t, std::string>>& connection_urls)
2702{
2703 connection_urls.clear();
2704
2705 StringExtractorGDBRemote response;
2706 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) != PacketResult::Success)
2707 return 0;
2708
2709 StructuredData::ObjectSP data = StructuredData::ParseJSON(response.GetStringRef());
2710 if (!data)
2711 return 0;
2712
2713 StructuredData::Array* array = data->GetAsArray();
2714 if (!array)
2715 return 0;
2716
2717 for (size_t i = 0, count = array->GetSize(); i < count; ++i)
2718 {
2719 StructuredData::Dictionary* element = nullptr;
2720 if (!array->GetItemAtIndexAsDictionary(i, element))
2721 continue;
2722
2723 uint16_t port = 0;
2724 if (StructuredData::ObjectSP port_osp = element->GetValueForKey(llvm::StringRef("port")))
2725 port = port_osp->GetIntegerValue(0);
2726
2727 std::string socket_name;
2728 if (StructuredData::ObjectSP socket_name_osp = element->GetValueForKey(llvm::StringRef("socket_name")))
2729 socket_name = socket_name_osp->GetStringValue();
2730
2731 if (port != 0 || !socket_name.empty())
2732 connection_urls.emplace_back(port, socket_name);
2733 }
2734 return connection_urls.size();
2735}
2736
Greg Clayton8b82f082011-04-12 05:54:46 +00002737bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00002738GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2739{
2740 StreamString stream;
2741 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2742 const char *packet = stream.GetData();
2743 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00002744
Daniel Maleae0f8f572013-08-26 23:57:52 +00002745 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002746 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002747 {
2748 if (response.IsOKResponse())
2749 return true;
2750 }
2751 return false;
2752}
2753
2754bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002755GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002756{
2757 if (m_curr_tid == tid)
2758 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002759
Greg Clayton8b82f082011-04-12 05:54:46 +00002760 char packet[32];
2761 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002762 if (tid == UINT64_MAX)
2763 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002764 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002765 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002766 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002767 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002768 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002769 {
2770 if (response.IsOKResponse())
2771 {
2772 m_curr_tid = tid;
2773 return true;
2774 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00002775
2776 /*
2777 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hg packet.
2778 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
2779 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2780 */
2781 if (response.IsUnsupportedResponse() && IsConnected())
2782 {
2783 m_curr_tid = 1;
2784 return true;
2785 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002786 }
2787 return false;
2788}
2789
2790bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002791GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002792{
2793 if (m_curr_tid_run == tid)
2794 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002795
Greg Clayton8b82f082011-04-12 05:54:46 +00002796 char packet[32];
2797 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002798 if (tid == UINT64_MAX)
2799 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002800 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002801 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2802
Andy Gibbsa297a972013-06-19 19:04:53 +00002803 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002804 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002805 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002806 {
2807 if (response.IsOKResponse())
2808 {
2809 m_curr_tid_run = tid;
2810 return true;
2811 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00002812
2813 /*
2814 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hc packet.
2815 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
2816 * give us pid and/or tid. Assume pid=tid=1 in such cases.
2817 */
2818 if (response.IsUnsupportedResponse() && IsConnected())
2819 {
2820 m_curr_tid_run = 1;
2821 return true;
2822 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002823 }
2824 return false;
2825}
2826
2827bool
2828GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2829{
Greg Clayton3dedae12013-12-06 21:45:27 +00002830 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002831 return response.IsNormalResponse();
2832 return false;
2833}
2834
2835bool
Greg Claytonf402f782012-10-13 02:11:55 +00002836GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00002837{
2838 if (m_supports_qThreadStopInfo)
2839 {
2840 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00002841 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002842 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002843 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002844 {
Greg Claytonef8180a2013-10-15 00:14:28 +00002845 if (response.IsUnsupportedResponse())
2846 m_supports_qThreadStopInfo = false;
2847 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002848 return true;
2849 else
2850 return false;
2851 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002852 else
2853 {
2854 m_supports_qThreadStopInfo = false;
2855 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002856 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002857 return false;
2858}
2859
2860
2861uint8_t
2862GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2863{
Todd Fiala616b8272014-10-09 00:55:04 +00002864 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2865 if (log)
2866 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
2867 __FUNCTION__, insert ? "add" : "remove", addr);
2868
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002869 // Check if the stub is known not to support this breakpoint type
2870 if (!SupportsGDBStoppointPacket(type))
2871 return UINT8_MAX;
2872 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00002873 char packet[64];
2874 const int packet_len = ::snprintf (packet,
2875 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00002876 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00002877 insert ? 'Z' : 'z',
2878 type,
2879 addr,
2880 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002881 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00002882 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002883 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +00002884 // Make sure the response is either "OK", "EXX" where XX are two hex digits, or "" (unsupported)
2885 response.SetResponseValidatorToOKErrorNotSupported();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002886 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00002887 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002888 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002889 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00002890 if (response.IsOKResponse())
2891 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002892
2893 // Error while setting breakpoint, send back specific error
2894 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002895 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002896
2897 // Empty packet informs us that breakpoint is not supported
2898 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00002899 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002900 // Disable this breakpoint type since it is unsupported
2901 switch (type)
2902 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00002903 case eBreakpointSoftware: m_supports_z0 = false; break;
2904 case eBreakpointHardware: m_supports_z1 = false; break;
2905 case eWatchpointWrite: m_supports_z2 = false; break;
2906 case eWatchpointRead: m_supports_z3 = false; break;
2907 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00002908 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002909 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002910 }
2911 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002912 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00002913 return UINT8_MAX;
2914}
Greg Claytonadc00cb2011-05-20 23:38:13 +00002915
2916size_t
2917GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2918 bool &sequence_mutex_unavailable)
2919{
Greg Claytonadc00cb2011-05-20 23:38:13 +00002920 thread_ids.clear();
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002921
Pavel Labathe768c4b2016-07-29 13:10:02 +00002922 Lock lock(*this, false);
2923 if (lock)
Greg Claytonadc00cb2011-05-20 23:38:13 +00002924 {
2925 sequence_mutex_unavailable = false;
2926 StringExtractorGDBRemote response;
2927
Greg Clayton3dedae12013-12-06 21:45:27 +00002928 PacketResult packet_result;
Pavel Labathe768c4b2016-07-29 13:10:02 +00002929 for (packet_result = SendPacketAndWaitForResponseNoLock("qfThreadInfo", response);
Greg Clayton3dedae12013-12-06 21:45:27 +00002930 packet_result == PacketResult::Success && response.IsNormalResponse();
Pavel Labathe768c4b2016-07-29 13:10:02 +00002931 packet_result = SendPacketAndWaitForResponseNoLock("qsThreadInfo", response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002932 {
2933 char ch = response.GetChar();
2934 if (ch == 'l')
2935 break;
2936 if (ch == 'm')
2937 {
2938 do
2939 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00002940 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00002941
2942 if (tid != LLDB_INVALID_THREAD_ID)
2943 {
2944 thread_ids.push_back (tid);
2945 }
2946 ch = response.GetChar(); // Skip the command separator
2947 } while (ch == ','); // Make sure we got a comma separator
2948 }
2949 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00002950
2951 /*
2952 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
2953 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet could
2954 * be as simple as 'S05'. There is no packet which can give us pid and/or tid.
2955 * Assume pid=tid=1 in such cases.
2956 */
2957 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 && IsConnected())
2958 {
2959 thread_ids.push_back (1);
2960 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00002961 }
2962 else
2963 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00002964#if defined (LLDB_CONFIGURATION_DEBUG)
2965 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2966#else
Greg Clayton5160ce52013-03-27 23:08:40 +00002967 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00002968 if (log)
2969 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00002970#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00002971 sequence_mutex_unavailable = true;
2972 }
2973 return thread_ids.size();
2974}
Greg Clayton37a0a242012-04-11 00:24:49 +00002975
2976lldb::addr_t
2977GDBRemoteCommunicationClient::GetShlibInfoAddr()
2978{
Pavel Labathe768c4b2016-07-29 13:10:02 +00002979 Lock lock(*this, false);
2980 if (lock)
Greg Clayton37a0a242012-04-11 00:24:49 +00002981 {
2982 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002983 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00002984 {
2985 if (response.IsNormalResponse())
2986 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2987 }
2988 }
Pavel Labathe768c4b2016-07-29 13:10:02 +00002989 else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
2990 {
2991 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex for qShlibInfoAddr packet.",
2992 __FUNCTION__);
2993 }
Greg Clayton37a0a242012-04-11 00:24:49 +00002994 return LLDB_INVALID_ADDRESS;
2995}
2996
Daniel Maleae0f8f572013-08-26 23:57:52 +00002997lldb_private::Error
Chaoren Lind3173f32015-05-29 19:52:29 +00002998GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
2999 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3000 int *status_ptr, // Pass NULL if you don't want the process exit status
3001 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3002 std::string *command_output, // Pass NULL if you don't want the command output
3003 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
Daniel Maleae0f8f572013-08-26 23:57:52 +00003004{
3005 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003006 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003007 stream.PutBytesAsRawHex8(command, strlen(command));
3008 stream.PutChar(',');
3009 stream.PutHex32(timeout_sec);
Chaoren Lind3173f32015-05-29 19:52:29 +00003010 if (working_dir)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003011 {
Chaoren Lind3173f32015-05-29 19:52:29 +00003012 std::string path{working_dir.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003013 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003014 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003015 }
3016 const char *packet = stream.GetData();
3017 int packet_len = stream.GetSize();
3018 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003019 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003020 {
3021 if (response.GetChar() != 'F')
3022 return Error("malformed reply");
3023 if (response.GetChar() != ',')
3024 return Error("malformed reply");
3025 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3026 if (exitcode == UINT32_MAX)
3027 return Error("unable to run remote process");
3028 else if (status_ptr)
3029 *status_ptr = exitcode;
3030 if (response.GetChar() != ',')
3031 return Error("malformed reply");
3032 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3033 if (signo_ptr)
3034 *signo_ptr = signo;
3035 if (response.GetChar() != ',')
3036 return Error("malformed reply");
3037 std::string output;
3038 response.GetEscapedBinaryData(output);
3039 if (command_output)
3040 command_output->assign(output);
3041 return Error();
3042 }
3043 return Error("unable to send packet");
3044}
3045
Greg Claytonfbb76342013-11-20 21:07:01 +00003046Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003047GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3048 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003049{
Chaoren Lind3173f32015-05-29 19:52:29 +00003050 std::string path{file_spec.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003051 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003052 stream.PutCString("qPlatform_mkdir:");
3053 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003054 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003055 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003056 const char *packet = stream.GetData();
3057 int packet_len = stream.GetSize();
3058 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003059
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003060 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3061 return Error("failed to send '%s' packet", packet);
3062
3063 if (response.GetChar() != 'F')
3064 return Error("invalid response to '%s' packet", packet);
3065
3066 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003067}
3068
Greg Claytonfbb76342013-11-20 21:07:01 +00003069Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003070GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3071 uint32_t file_permissions)
Greg Claytonfbb76342013-11-20 21:07:01 +00003072{
Chaoren Lind3173f32015-05-29 19:52:29 +00003073 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003074 lldb_private::StreamString stream;
3075 stream.PutCString("qPlatform_chmod:");
3076 stream.PutHex32(file_permissions);
3077 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003078 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003079 const char *packet = stream.GetData();
3080 int packet_len = stream.GetSize();
3081 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003082
3083 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3084 return Error("failed to send '%s' packet", packet);
3085
3086 if (response.GetChar() != 'F')
3087 return Error("invalid response to '%s' packet", packet);
3088
Chaoren Lince36c4c2015-05-05 18:43:19 +00003089 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003090}
3091
Daniel Maleae0f8f572013-08-26 23:57:52 +00003092static uint64_t
3093ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3094 uint64_t fail_result,
3095 Error &error)
3096{
3097 response.SetFilePos(0);
3098 if (response.GetChar() != 'F')
3099 return fail_result;
3100 int32_t result = response.GetS32 (-2);
3101 if (result == -2)
3102 return fail_result;
3103 if (response.GetChar() == ',')
3104 {
3105 int result_errno = response.GetS32 (-2);
3106 if (result_errno != -2)
3107 error.SetError(result_errno, eErrorTypePOSIX);
3108 else
3109 error.SetError(-1, eErrorTypeGeneric);
3110 }
3111 else
3112 error.Clear();
3113 return result;
3114}
3115lldb::user_id_t
3116GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3117 uint32_t flags,
3118 mode_t mode,
3119 Error &error)
3120{
Chaoren Lind3173f32015-05-29 19:52:29 +00003121 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003122 lldb_private::StreamString stream;
3123 stream.PutCString("vFile:open:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003124 if (path.empty())
3125 return UINT64_MAX;
3126 stream.PutCStringAsRawHex8(path.c_str());
3127 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003128 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003129 stream.PutChar(',');
3130 stream.PutHex32(mode);
3131 const char* packet = stream.GetData();
3132 int packet_len = stream.GetSize();
3133 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003134 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003135 {
3136 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3137 }
3138 return UINT64_MAX;
3139}
3140
3141bool
3142GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3143 Error &error)
3144{
3145 lldb_private::StreamString stream;
3146 stream.Printf("vFile:close:%i", (int)fd);
3147 const char* packet = stream.GetData();
3148 int packet_len = stream.GetSize();
3149 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003150 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003151 {
3152 return ParseHostIOPacketResponse (response, -1, error) == 0;
3153 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003154 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003155}
3156
3157// Extension of host I/O packets to get the file size.
3158lldb::user_id_t
3159GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3160{
Chaoren Lind3173f32015-05-29 19:52:29 +00003161 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003162 lldb_private::StreamString stream;
3163 stream.PutCString("vFile:size:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003164 stream.PutCStringAsRawHex8(path.c_str());
3165 const char* packet = stream.GetData();
3166 int packet_len = stream.GetSize();
3167 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003168 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003169 {
3170 if (response.GetChar() != 'F')
3171 return UINT64_MAX;
3172 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3173 return retcode;
3174 }
3175 return UINT64_MAX;
3176}
3177
Greg Claytonfbb76342013-11-20 21:07:01 +00003178Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003179GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3180 uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003181{
Chaoren Lind3173f32015-05-29 19:52:29 +00003182 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003183 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003184 lldb_private::StreamString stream;
3185 stream.PutCString("vFile:mode:");
Chaoren Lind3173f32015-05-29 19:52:29 +00003186 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003187 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 {
3194 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003195 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003196 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003197 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003198 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003199 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003200 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003201 if (response.GetChar() == ',')
3202 {
3203 int response_errno = response.GetS32(-1);
3204 if (response_errno > 0)
3205 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3206 else
3207 error.SetErrorToGenericError();
3208 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003209 else
3210 error.SetErrorToGenericError();
3211 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003212 else
3213 {
3214 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3215 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003216 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003217 }
3218 else
3219 {
3220 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3221 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003222 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003223}
3224
3225uint64_t
3226GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3227 uint64_t offset,
3228 void *dst,
3229 uint64_t dst_len,
3230 Error &error)
3231{
3232 lldb_private::StreamString stream;
3233 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3234 const char* packet = stream.GetData();
3235 int packet_len = stream.GetSize();
3236 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003237 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003238 {
3239 if (response.GetChar() != 'F')
3240 return 0;
3241 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3242 if (retcode == UINT32_MAX)
3243 return retcode;
3244 const char next = (response.Peek() ? *response.Peek() : 0);
3245 if (next == ',')
3246 return 0;
3247 if (next == ';')
3248 {
3249 response.GetChar(); // skip the semicolon
3250 std::string buffer;
3251 if (response.GetEscapedBinaryData(buffer))
3252 {
3253 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3254 if (data_to_write > 0)
3255 memcpy(dst, &buffer[0], data_to_write);
3256 return data_to_write;
3257 }
3258 }
3259 }
3260 return 0;
3261}
3262
3263uint64_t
3264GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3265 uint64_t offset,
3266 const void* src,
3267 uint64_t src_len,
3268 Error &error)
3269{
3270 lldb_private::StreamGDBRemote stream;
3271 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3272 stream.PutEscapedBytes(src, src_len);
3273 const char* packet = stream.GetData();
3274 int packet_len = stream.GetSize();
3275 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003276 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003277 {
3278 if (response.GetChar() != 'F')
3279 {
3280 error.SetErrorStringWithFormat("write file failed");
3281 return 0;
3282 }
3283 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3284 if (bytes_written == UINT64_MAX)
3285 {
3286 error.SetErrorToGenericError();
3287 if (response.GetChar() == ',')
3288 {
3289 int response_errno = response.GetS32(-1);
3290 if (response_errno > 0)
3291 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3292 }
3293 return 0;
3294 }
3295 return bytes_written;
3296 }
3297 else
3298 {
3299 error.SetErrorString ("failed to send vFile:pwrite packet");
3300 }
3301 return 0;
3302}
3303
Greg Claytonfbb76342013-11-20 21:07:01 +00003304Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003305GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
Greg Claytonfbb76342013-11-20 21:07:01 +00003306{
Chaoren Lind3173f32015-05-29 19:52:29 +00003307 std::string src_path{src.GetPath(false)},
3308 dst_path{dst.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003309 Error error;
3310 lldb_private::StreamGDBRemote stream;
3311 stream.PutCString("vFile:symlink:");
3312 // the unix symlink() command reverses its parameters where the dst if first,
3313 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003314 stream.PutCStringAsRawHex8(dst_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003315 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003316 stream.PutCStringAsRawHex8(src_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003317 const char* packet = stream.GetData();
3318 int packet_len = stream.GetSize();
3319 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003320 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003321 {
3322 if (response.GetChar() == 'F')
3323 {
3324 uint32_t result = response.GetU32(UINT32_MAX);
3325 if (result != 0)
3326 {
3327 error.SetErrorToGenericError();
3328 if (response.GetChar() == ',')
3329 {
3330 int response_errno = response.GetS32(-1);
3331 if (response_errno > 0)
3332 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3333 }
3334 }
3335 }
3336 else
3337 {
3338 // Should have returned with 'F<result>[,<errno>]'
3339 error.SetErrorStringWithFormat("symlink failed");
3340 }
3341 }
3342 else
3343 {
3344 error.SetErrorString ("failed to send vFile:symlink packet");
3345 }
3346 return error;
3347}
3348
3349Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003350GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
Greg Claytonfbb76342013-11-20 21:07:01 +00003351{
Chaoren Lind3173f32015-05-29 19:52:29 +00003352 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003353 Error error;
3354 lldb_private::StreamGDBRemote stream;
3355 stream.PutCString("vFile:unlink:");
3356 // the unix symlink() command reverses its parameters where the dst if first,
3357 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003358 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003359 const char* packet = stream.GetData();
3360 int packet_len = stream.GetSize();
3361 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003362 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003363 {
3364 if (response.GetChar() == 'F')
3365 {
3366 uint32_t result = response.GetU32(UINT32_MAX);
3367 if (result != 0)
3368 {
3369 error.SetErrorToGenericError();
3370 if (response.GetChar() == ',')
3371 {
3372 int response_errno = response.GetS32(-1);
3373 if (response_errno > 0)
3374 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3375 }
3376 }
3377 }
3378 else
3379 {
3380 // Should have returned with 'F<result>[,<errno>]'
3381 error.SetErrorStringWithFormat("unlink failed");
3382 }
3383 }
3384 else
3385 {
3386 error.SetErrorString ("failed to send vFile:unlink packet");
3387 }
3388 return error;
3389}
3390
Daniel Maleae0f8f572013-08-26 23:57:52 +00003391// Extension of host I/O packets to get whether a file exists.
3392bool
3393GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3394{
Chaoren Lind3173f32015-05-29 19:52:29 +00003395 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003396 lldb_private::StreamString stream;
3397 stream.PutCString("vFile:exists:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003398 stream.PutCStringAsRawHex8(path.c_str());
3399 const char* packet = stream.GetData();
3400 int packet_len = stream.GetSize();
3401 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003402 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003403 {
3404 if (response.GetChar() != 'F')
3405 return false;
3406 if (response.GetChar() != ',')
3407 return false;
3408 bool retcode = (response.GetChar() != '0');
3409 return retcode;
3410 }
3411 return false;
3412}
3413
3414bool
3415GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3416 uint64_t &high,
3417 uint64_t &low)
3418{
Chaoren Lind3173f32015-05-29 19:52:29 +00003419 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003420 lldb_private::StreamString stream;
3421 stream.PutCString("vFile:MD5:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003422 stream.PutCStringAsRawHex8(path.c_str());
3423 const char* packet = stream.GetData();
3424 int packet_len = stream.GetSize();
3425 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003426 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003427 {
3428 if (response.GetChar() != 'F')
3429 return false;
3430 if (response.GetChar() != ',')
3431 return false;
3432 if (response.Peek() && *response.Peek() == 'x')
3433 return false;
3434 low = response.GetHexMaxU64(false, UINT64_MAX);
3435 high = response.GetHexMaxU64(false, UINT64_MAX);
3436 return true;
3437 }
3438 return false;
3439}
Greg Claytonf74cf862013-11-13 23:28:31 +00003440
3441bool
Jason Molendaa3329782014-03-29 18:54:20 +00003442GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3443{
3444 // Some targets have issues with g/G packets and we need to avoid using them
3445 if (m_avoid_g_packets == eLazyBoolCalculate)
3446 {
3447 if (process)
3448 {
3449 m_avoid_g_packets = eLazyBoolNo;
3450 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3451 if (arch.IsValid()
3452 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3453 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00003454 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00003455 {
3456 m_avoid_g_packets = eLazyBoolYes;
3457 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3458 if (gdb_server_version != 0)
3459 {
3460 const char *gdb_server_name = GetGDBServerProgramName();
3461 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3462 {
3463 if (gdb_server_version >= 310)
3464 m_avoid_g_packets = eLazyBoolNo;
3465 }
3466 }
3467 }
3468 }
3469 }
3470 return m_avoid_g_packets == eLazyBoolYes;
3471}
3472
3473bool
Greg Claytonf74cf862013-11-13 23:28:31 +00003474GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3475{
Pavel Labathe768c4b2016-07-29 13:10:02 +00003476 Lock lock(*this, false);
3477 if (lock)
Greg Claytonf74cf862013-11-13 23:28:31 +00003478 {
3479 const bool thread_suffix_supported = GetThreadSuffixSupported();
3480
3481 if (thread_suffix_supported || SetCurrentThread(tid))
3482 {
3483 char packet[64];
3484 int packet_len = 0;
3485 if (thread_suffix_supported)
3486 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
3487 else
3488 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3489 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003490 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003491 }
3492 }
Pavel Labathe768c4b2016-07-29 13:10:02 +00003493 else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
3494 {
3495 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex for p packet.", __FUNCTION__);
3496 }
Greg Claytonf74cf862013-11-13 23:28:31 +00003497 return false;
3498
3499}
3500
3501
3502bool
3503GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3504{
Pavel Labathe768c4b2016-07-29 13:10:02 +00003505 Lock lock(*this, false);
3506 if (lock)
Greg Claytonf74cf862013-11-13 23:28:31 +00003507 {
3508 const bool thread_suffix_supported = GetThreadSuffixSupported();
3509
3510 if (thread_suffix_supported || SetCurrentThread(tid))
3511 {
3512 char packet[64];
3513 int packet_len = 0;
3514 // Get all registers in one packet
3515 if (thread_suffix_supported)
3516 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3517 else
3518 packet_len = ::snprintf (packet, sizeof(packet), "g");
3519 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003520 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003521 }
3522 }
Pavel Labathe768c4b2016-07-29 13:10:02 +00003523 else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
3524 {
3525 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex for g packet.", __FUNCTION__);
3526 }
Greg Claytonf74cf862013-11-13 23:28:31 +00003527 return false;
3528}
3529bool
3530GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3531{
3532 save_id = 0; // Set to invalid save ID
3533 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3534 return false;
3535
3536 m_supports_QSaveRegisterState = eLazyBoolYes;
Pavel Labathe768c4b2016-07-29 13:10:02 +00003537 Lock lock(*this, false);
3538 if (lock)
Greg Claytonf74cf862013-11-13 23:28:31 +00003539 {
3540 const bool thread_suffix_supported = GetThreadSuffixSupported();
3541 if (thread_suffix_supported || SetCurrentThread(tid))
3542 {
3543 char packet[256];
3544 if (thread_suffix_supported)
3545 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3546 else
Ilia K686b1fe2015-02-27 19:43:08 +00003547 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
Greg Claytonf74cf862013-11-13 23:28:31 +00003548
3549 StringExtractorGDBRemote response;
3550
Greg Clayton3dedae12013-12-06 21:45:27 +00003551 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003552 {
3553 if (response.IsUnsupportedResponse())
3554 {
3555 // This packet isn't supported, don't try calling it again
3556 m_supports_QSaveRegisterState = eLazyBoolNo;
3557 }
3558
3559 const uint32_t response_save_id = response.GetU32(0);
3560 if (response_save_id != 0)
3561 {
3562 save_id = response_save_id;
3563 return true;
3564 }
3565 }
3566 }
3567 }
Pavel Labathe768c4b2016-07-29 13:10:02 +00003568 else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
3569 {
3570 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex for QSaveRegisterState packet.",
3571 __FUNCTION__);
3572 }
Greg Claytonf74cf862013-11-13 23:28:31 +00003573 return false;
3574}
3575
3576bool
3577GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3578{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003579 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00003580 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3581 // order to be useful
3582 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3583 return false;
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003584
Pavel Labathe768c4b2016-07-29 13:10:02 +00003585 Lock lock(*this, false);
3586 if (lock)
Greg Claytonf74cf862013-11-13 23:28:31 +00003587 {
3588 const bool thread_suffix_supported = GetThreadSuffixSupported();
3589 if (thread_suffix_supported || SetCurrentThread(tid))
3590 {
3591 char packet[256];
3592 if (thread_suffix_supported)
3593 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3594 else
3595 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3596
3597 StringExtractorGDBRemote response;
3598
Greg Clayton3dedae12013-12-06 21:45:27 +00003599 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003600 {
3601 if (response.IsOKResponse())
3602 {
3603 return true;
3604 }
3605 else if (response.IsUnsupportedResponse())
3606 {
3607 // This packet isn't supported, don't try calling this packet or
3608 // QSaveRegisterState again...
3609 m_supports_QSaveRegisterState = eLazyBoolNo;
3610 }
3611 }
3612 }
3613 }
Pavel Labathe768c4b2016-07-29 13:10:02 +00003614 else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
3615 {
3616 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex for QRestoreRegisterState packet.",
3617 __FUNCTION__);
3618 }
Greg Claytonf74cf862013-11-13 23:28:31 +00003619 return false;
3620}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003621
3622bool
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003623GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003624 const lldb_private::ArchSpec& arch_spec,
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003625 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003626{
Stephane Sezer6f455292016-01-08 00:00:17 +00003627 if (!m_supports_qModuleInfo)
3628 return false;
3629
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00003630 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003631 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003632 return false;
3633
3634 StreamString packet;
3635 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003636 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003637 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00003638 const auto& triple = arch_spec.GetTriple().getTriple();
Chaoren Lind3173f32015-05-29 19:52:29 +00003639 packet.PutCStringAsRawHex8(triple.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003640
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003641 StringExtractorGDBRemote response;
3642 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
3643 return false;
3644
Stephane Sezer6f455292016-01-08 00:00:17 +00003645 if (response.IsErrorResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003646 return false;
3647
Stephane Sezer6f455292016-01-08 00:00:17 +00003648 if (response.IsUnsupportedResponse ())
3649 {
3650 m_supports_qModuleInfo = false;
3651 return false;
3652 }
3653
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003654 std::string name;
3655 std::string value;
3656 bool success;
3657 StringExtractor extractor;
3658
3659 module_spec.Clear ();
3660 module_spec.GetFileSpec () = module_file_spec;
3661
3662 while (response.GetNameColonValue (name, value))
3663 {
3664 if (name == "uuid" || name == "md5")
3665 {
3666 extractor.GetStringRef ().swap (value);
3667 extractor.SetFilePos (0);
3668 extractor.GetHexByteString (value);
3669 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
3670 }
3671 else if (name == "triple")
3672 {
3673 extractor.GetStringRef ().swap (value);
3674 extractor.SetFilePos (0);
3675 extractor.GetHexByteString (value);
3676 module_spec.GetArchitecture().SetTriple (value.c_str ());
3677 }
3678 else if (name == "file_offset")
3679 {
3680 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
3681 if (success)
3682 module_spec.SetObjectOffset (ival);
3683 }
3684 else if (name == "file_size")
3685 {
3686 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
3687 if (success)
3688 module_spec.SetObjectSize (ival);
3689 }
3690 else if (name == "file_path")
3691 {
3692 extractor.GetStringRef ().swap (value);
3693 extractor.SetFilePos (0);
3694 extractor.GetHexByteString (value);
Chaoren Linf34f4102015-05-09 01:21:32 +00003695 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003696 }
3697 }
3698
3699 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003700}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003701
3702// query the target remote for extended information using the qXfer packet
3703//
3704// example: object='features', annex='target.xml', out=<xml output>
3705// return: 'true' on success
3706// 'false' on failure (err set)
3707bool
3708GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
3709 const lldb_private::ConstString annex,
3710 std::string & out,
3711 lldb_private::Error & err) {
3712
3713 std::stringstream output;
3714 StringExtractorGDBRemote chunk;
3715
Greg Claytond04f0ed2015-05-26 18:00:51 +00003716 uint64_t size = GetRemoteMaxPacketSize();
3717 if (size == 0)
3718 size = 0x1000;
3719 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3720 int offset = 0;
3721 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003722
3723 // loop until all data has been read
3724 while ( active ) {
3725
3726 // send query extended feature packet
3727 std::stringstream packet;
3728 packet << "qXfer:"
Ewan Crawford682e8422015-06-26 09:38:27 +00003729 << object.AsCString("") << ":read:"
3730 << annex.AsCString("") << ":"
Colin Rileyc3c95b22015-04-16 15:51:33 +00003731 << std::hex << offset << ","
3732 << std::hex << size;
3733
3734 GDBRemoteCommunication::PacketResult res =
3735 SendPacketAndWaitForResponse( packet.str().c_str(),
3736 chunk,
3737 false );
3738
3739 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
3740 err.SetErrorString( "Error sending $qXfer packet" );
3741 return false;
3742 }
3743
3744 const std::string & str = chunk.GetStringRef( );
3745 if ( str.length() == 0 ) {
3746 // should have some data in chunk
3747 err.SetErrorString( "Empty response from $qXfer packet" );
3748 return false;
3749 }
3750
3751 // check packet code
3752 switch ( str[0] ) {
3753 // last chunk
3754 case ( 'l' ):
3755 active = false;
Jason Molenda62e06812016-02-16 04:14:33 +00003756 LLVM_FALLTHROUGH;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003757
3758 // more chunks
3759 case ( 'm' ) :
3760 if ( str.length() > 1 )
3761 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00003762 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003763 break;
3764
3765 // unknown chunk
3766 default:
3767 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
3768 return false;
3769 }
3770 }
3771
3772 out = output.str( );
3773 err.Success( );
3774 return true;
3775}
Greg Clayton0b90be12015-06-23 21:27:50 +00003776
3777// Notify the target that gdb is prepared to serve symbol lookup requests.
3778// packet: "qSymbol::"
3779// reply:
3780// OK The target does not need to look up any (more) symbols.
3781// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded).
3782// LLDB may provide the value by sending another qSymbol packet
3783// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00003784//
3785// Three examples:
3786//
3787// lldb sends: qSymbol::
3788// lldb receives: OK
3789// Remote gdb stub does not need to know the addresses of any symbols, lldb does not
3790// need to ask again in this session.
3791//
3792// lldb sends: qSymbol::
3793// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3794// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
3795// lldb receives: OK
3796// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does not know
3797// the address at this time. lldb needs to send qSymbol:: again when it has more
3798// solibs loaded.
3799//
3800// lldb sends: qSymbol::
3801// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
3802// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
3803// lldb receives: OK
3804// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says that it
3805// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it does not
3806// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00003807
3808void
3809GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
3810{
Jason Molenda50018d32016-01-13 04:08:10 +00003811 // Set to true once we've resolved a symbol to an address for the remote stub.
3812 // If we get an 'OK' response after this, the remote stub doesn't need any more
3813 // symbols and we can stop asking.
3814 bool symbol_response_provided = false;
3815
Ed Maste75500e72016-07-19 15:28:02 +00003816 // Is this the initial qSymbol:: packet?
Jason Molenda50018d32016-01-13 04:08:10 +00003817 bool first_qsymbol_query = true;
3818
3819 if (m_supports_qSymbol && m_qSymbol_requests_done == false)
Greg Clayton0b90be12015-06-23 21:27:50 +00003820 {
Pavel Labathe768c4b2016-07-29 13:10:02 +00003821 Lock lock(*this, false);
3822 if (lock)
Greg Clayton0b90be12015-06-23 21:27:50 +00003823 {
3824 StreamString packet;
3825 packet.PutCString ("qSymbol::");
Greg Clayton42b01482015-08-11 22:07:46 +00003826 StringExtractorGDBRemote response;
Pavel Labathe768c4b2016-07-29 13:10:02 +00003827 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) == PacketResult::Success)
Greg Clayton0b90be12015-06-23 21:27:50 +00003828 {
Greg Clayton42b01482015-08-11 22:07:46 +00003829 if (response.IsOKResponse())
Greg Clayton0b90be12015-06-23 21:27:50 +00003830 {
Jason Molenda50018d32016-01-13 04:08:10 +00003831 if (symbol_response_provided || first_qsymbol_query)
3832 {
3833 m_qSymbol_requests_done = true;
3834 }
3835
Greg Clayton42b01482015-08-11 22:07:46 +00003836 // We are done serving symbols requests
3837 return;
3838 }
Jason Molenda50018d32016-01-13 04:08:10 +00003839 first_qsymbol_query = false;
Greg Clayton0b90be12015-06-23 21:27:50 +00003840
Greg Clayton42b01482015-08-11 22:07:46 +00003841 if (response.IsUnsupportedResponse())
3842 {
3843 // qSymbol is not supported by the current GDB server we are connected to
3844 m_supports_qSymbol = false;
3845 return;
3846 }
3847 else
3848 {
3849 llvm::StringRef response_str(response.GetStringRef());
3850 if (response_str.startswith("qSymbol:"))
Greg Clayton0b90be12015-06-23 21:27:50 +00003851 {
Greg Clayton42b01482015-08-11 22:07:46 +00003852 response.SetFilePos(strlen("qSymbol:"));
3853 std::string symbol_name;
3854 if (response.GetHexByteString(symbol_name))
Greg Clayton0b90be12015-06-23 21:27:50 +00003855 {
Greg Clayton42b01482015-08-11 22:07:46 +00003856 if (symbol_name.empty())
3857 return;
3858
3859 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
3860 lldb_private::SymbolContextList sc_list;
3861 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
Greg Clayton0b90be12015-06-23 21:27:50 +00003862 {
Greg Clayton42b01482015-08-11 22:07:46 +00003863 const size_t num_scs = sc_list.GetSize();
3864 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 +00003865 {
Greg Clayton42b01482015-08-11 22:07:46 +00003866 SymbolContext sc;
3867 if (sc_list.GetContextAtIndex(sc_idx, sc))
Greg Clayton0b90be12015-06-23 21:27:50 +00003868 {
Greg Clayton42b01482015-08-11 22:07:46 +00003869 if (sc.symbol)
Greg Clayton358cf1e2015-06-25 21:46:34 +00003870 {
Greg Clayton42b01482015-08-11 22:07:46 +00003871 switch (sc.symbol->GetType())
Greg Clayton358cf1e2015-06-25 21:46:34 +00003872 {
Greg Clayton42b01482015-08-11 22:07:46 +00003873 case eSymbolTypeInvalid:
3874 case eSymbolTypeAbsolute:
3875 case eSymbolTypeUndefined:
3876 case eSymbolTypeSourceFile:
3877 case eSymbolTypeHeaderFile:
3878 case eSymbolTypeObjectFile:
3879 case eSymbolTypeCommonBlock:
3880 case eSymbolTypeBlock:
3881 case eSymbolTypeLocal:
3882 case eSymbolTypeParam:
3883 case eSymbolTypeVariable:
3884 case eSymbolTypeVariableType:
3885 case eSymbolTypeLineEntry:
3886 case eSymbolTypeLineHeader:
3887 case eSymbolTypeScopeBegin:
3888 case eSymbolTypeScopeEnd:
3889 case eSymbolTypeAdditional:
3890 case eSymbolTypeCompiler:
3891 case eSymbolTypeInstrumentation:
3892 case eSymbolTypeTrampoline:
3893 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00003894
Greg Clayton42b01482015-08-11 22:07:46 +00003895 case eSymbolTypeCode:
3896 case eSymbolTypeResolver:
3897 case eSymbolTypeData:
3898 case eSymbolTypeRuntime:
3899 case eSymbolTypeException:
3900 case eSymbolTypeObjCClass:
3901 case eSymbolTypeObjCMetaClass:
3902 case eSymbolTypeObjCIVar:
3903 case eSymbolTypeReExported:
3904 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
3905 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00003906 }
3907 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003908 }
3909 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003910 }
Greg Clayton42b01482015-08-11 22:07:46 +00003911 // This is the normal path where our symbol lookup was successful and we want
3912 // to send a packet with the new symbol value and see if another lookup needs to be
3913 // done.
3914
3915 // Change "packet" to contain the requested symbol value and name
3916 packet.Clear();
3917 packet.PutCString("qSymbol:");
3918 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
Jason Molenda50018d32016-01-13 04:08:10 +00003919 {
Greg Clayton42b01482015-08-11 22:07:46 +00003920 packet.Printf("%" PRIx64, symbol_load_addr);
Jason Molenda50018d32016-01-13 04:08:10 +00003921 symbol_response_provided = true;
3922 }
3923 else
3924 {
3925 symbol_response_provided = false;
3926 }
Greg Clayton42b01482015-08-11 22:07:46 +00003927 packet.PutCString(":");
3928 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
3929 continue; // go back to the while loop and send "packet" and wait for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00003930 }
3931 }
3932 }
3933 }
3934 // If we make it here, the symbol request packet response wasn't valid or
3935 // our symbol lookup failed so we must abort
3936 return;
3937
3938 }
Pavel Labathe768c4b2016-07-29 13:10:02 +00003939 else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | GDBR_LOG_PACKETS))
3940 {
3941 log->Printf("GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.", __FUNCTION__);
3942 }
Greg Clayton0b90be12015-06-23 21:27:50 +00003943 }
3944}
3945
Pavel Labathe768c4b2016-07-29 13:10:02 +00003946void
3947GDBRemoteCommunicationClient::OnRunPacketSent(bool first)
3948{
3949 GDBRemoteClientBase::OnRunPacketSent(first);
3950 if (first)
3951 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
3952 m_curr_tid = LLDB_INVALID_THREAD_ID;
3953}