blob: f436799a86a1f2cffdbce8ff76988492856b320b [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
Daniel Maleab89d0492013-08-28 16:06:16 +000014#include <sys/stat.h>
15
Greg Clayton576d8832011-03-22 04:00:09 +000016// C++ Includes
Han Ming Ong4b6459f2013-01-18 23:11:53 +000017#include <sstream>
18
Greg Clayton576d8832011-03-22 04:00:09 +000019// Other libraries and framework includes
20#include "llvm/ADT/Triple.h"
21#include "lldb/Interpreter/Args.h"
22#include "lldb/Core/ConnectionFileDescriptor.h"
23#include "lldb/Core/Log.h"
24#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"
27#include "lldb/Host/Endian.h"
28#include "lldb/Host/Host.h"
29#include "lldb/Host/TimeValue.h"
Jason Molendaa3329782014-03-29 18:54:20 +000030#include "lldb/Target/Target.h"
Greg Clayton576d8832011-03-22 04:00:09 +000031
32// Project includes
33#include "Utility/StringExtractorGDBRemote.h"
34#include "ProcessGDBRemote.h"
35#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000036#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000037
38using namespace lldb;
39using namespace lldb_private;
40
Virgile Bellob2f1fb22013-08-23 12:44:05 +000041#ifdef LLDB_DISABLE_POSIX
42#define SIGSTOP 17
43#endif
44
Greg Clayton576d8832011-03-22 04:00:09 +000045//----------------------------------------------------------------------
46// GDBRemoteCommunicationClient constructor
47//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +000048GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) :
49 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform),
Greg Clayton576d8832011-03-22 04:00:09 +000050 m_supports_not_sending_acks (eLazyBoolCalculate),
51 m_supports_thread_suffix (eLazyBoolCalculate),
Greg Clayton44633992012-04-10 03:22:03 +000052 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
Greg Clayton576d8832011-03-22 04:00:09 +000053 m_supports_vCont_all (eLazyBoolCalculate),
54 m_supports_vCont_any (eLazyBoolCalculate),
55 m_supports_vCont_c (eLazyBoolCalculate),
56 m_supports_vCont_C (eLazyBoolCalculate),
57 m_supports_vCont_s (eLazyBoolCalculate),
58 m_supports_vCont_S (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000059 m_qHostInfo_is_valid (eLazyBoolCalculate),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000060 m_qProcessInfo_is_valid (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000061 m_qGDBServerVersion_is_valid (eLazyBoolCalculate),
Greg Clayton70b57652011-05-15 01:25:55 +000062 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
Greg Clayton46fb5582011-11-18 07:03:08 +000063 m_supports_memory_region_info (eLazyBoolCalculate),
Johnny Chen64637202012-05-23 21:09:52 +000064 m_supports_watchpoint_support_info (eLazyBoolCalculate),
Jim Inghamacff8952013-05-02 00:27:30 +000065 m_supports_detach_stay_stopped (eLazyBoolCalculate),
Enrico Granataf04a2192012-07-13 23:18:48 +000066 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
Jim Inghamcd16df92012-07-20 21:37:13 +000067 m_attach_or_wait_reply(eLazyBoolCalculate),
Jim Ingham279ceec2012-07-25 21:12:43 +000068 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
Eric Christopher2490f5c2013-08-30 17:50:57 +000069 m_supports_p (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000070 m_avoid_g_packets (eLazyBoolCalculate),
Greg Claytonf74cf862013-11-13 23:28:31 +000071 m_supports_QSaveRegisterState (eLazyBoolCalculate),
Steve Pucci03904ac2014-03-04 23:18:46 +000072 m_supports_qXfer_auxv_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000073 m_supports_qXfer_libraries_read (eLazyBoolCalculate),
74 m_supports_qXfer_libraries_svr4_read (eLazyBoolCalculate),
75 m_supports_augmented_libraries_svr4_read (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000076 m_supports_qProcessInfoPID (true),
77 m_supports_qfProcessInfo (true),
78 m_supports_qUserName (true),
79 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000080 m_supports_qThreadStopInfo (true),
81 m_supports_z0 (true),
82 m_supports_z1 (true),
83 m_supports_z2 (true),
84 m_supports_z3 (true),
85 m_supports_z4 (true),
Greg Clayton89600582013-10-10 17:53:50 +000086 m_supports_QEnvironment (true),
87 m_supports_QEnvironmentHexEncoded (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000088 m_curr_tid (LLDB_INVALID_THREAD_ID),
89 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +000090 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +000091 m_async_mutex (Mutex::eMutexTypeRecursive),
92 m_async_packet_predicate (false),
93 m_async_packet (),
Jim Inghama6195b72013-12-18 01:24:33 +000094 m_async_result (PacketResult::Success),
Greg Clayton576d8832011-03-22 04:00:09 +000095 m_async_response (),
96 m_async_signal (-1),
Han Ming Ong4b6459f2013-01-18 23:11:53 +000097 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +000098 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000099 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +0000100 m_os_version_major (UINT32_MAX),
101 m_os_version_minor (UINT32_MAX),
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000102 m_os_version_update (UINT32_MAX),
103 m_os_build (),
104 m_os_kernel (),
105 m_hostname (),
Jason Molendaa3329782014-03-29 18:54:20 +0000106 m_gdb_server_name(),
107 m_gdb_server_version(UINT32_MAX),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000108 m_default_packet_timeout (0),
109 m_max_packet_size (0)
Greg Clayton576d8832011-03-22 04:00:09 +0000110{
Greg Clayton576d8832011-03-22 04:00:09 +0000111}
112
113//----------------------------------------------------------------------
114// Destructor
115//----------------------------------------------------------------------
116GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
117{
Greg Clayton576d8832011-03-22 04:00:09 +0000118 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000119 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000120}
121
122bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000123GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
124{
Greg Claytonfb909312013-11-23 01:58:15 +0000125 ResetDiscoverableSettings();
126
Greg Clayton1cb64962011-03-24 04:28:38 +0000127 // Start the read thread after we send the handshake ack since if we
128 // fail to send the handshake ack, there is no reason to continue...
129 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000130 {
Ed Maste48f986f2013-12-18 15:31:45 +0000131 // Wait for any responses that might have been queued up in the remote
132 // GDB server and flush them all
133 StringExtractorGDBRemote response;
134 PacketResult packet_result = PacketResult::Success;
135 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
136 while (packet_result == PacketResult::Success)
137 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, timeout_usec);
138
Greg Claytonfb909312013-11-23 01:58:15 +0000139 // The return value from QueryNoAckModeSupported() is true if the packet
140 // was sent and _any_ response (including UNIMPLEMENTED) was received),
141 // or false if no response was received. This quickly tells us if we have
142 // a live connection to a remote GDB server...
143 if (QueryNoAckModeSupported())
144 {
Greg Clayton700e5082014-02-21 19:11:28 +0000145#if 0
146 // Set above line to "#if 1" to test packet speed if remote GDB server
147 // supports the qSpeedTest packet...
148 TestPacketSpeed(10000);
149#endif
Greg Claytonfb909312013-11-23 01:58:15 +0000150 return true;
151 }
152 else
153 {
154 if (error_ptr)
155 error_ptr->SetErrorString("failed to get reply to handshake packet");
156 }
157 }
158 else
159 {
160 if (error_ptr)
161 error_ptr->SetErrorString("failed to send the handshake ack");
162 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000163 return false;
164}
165
Greg Claytonfb909312013-11-23 01:58:15 +0000166bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000167GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
168{
169 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
170 {
171 GetRemoteQSupported();
172 }
173 return (m_supports_augmented_libraries_svr4_read == eLazyBoolYes);
174}
175
176bool
177GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
178{
179 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
180 {
181 GetRemoteQSupported();
182 }
183 return (m_supports_qXfer_libraries_svr4_read == eLazyBoolYes);
184}
185
186bool
187GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
188{
189 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
190 {
191 GetRemoteQSupported();
192 }
193 return (m_supports_qXfer_libraries_read == eLazyBoolYes);
194}
195
Steve Pucci03904ac2014-03-04 23:18:46 +0000196bool
197GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
198{
199 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
200 {
201 GetRemoteQSupported();
202 }
203 return (m_supports_qXfer_auxv_read == eLazyBoolYes);
204}
205
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000206uint64_t
207GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
208{
209 if (m_max_packet_size == 0)
210 {
211 GetRemoteQSupported();
212 }
213 return m_max_packet_size;
214}
215
216bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000217GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000218{
219 if (m_supports_not_sending_acks == eLazyBoolCalculate)
220 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000221 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000222 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000223
224 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000225 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000226 {
227 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000228 {
229 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000230 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000231 }
Greg Claytonfb909312013-11-23 01:58:15 +0000232 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000233 }
234 }
Greg Claytonfb909312013-11-23 01:58:15 +0000235 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000236}
237
238void
Greg Clayton44633992012-04-10 03:22:03 +0000239GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
240{
241 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
242 {
243 m_supports_threads_in_stop_reply = eLazyBoolNo;
244
245 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000246 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000247 {
248 if (response.IsOKResponse())
249 m_supports_threads_in_stop_reply = eLazyBoolYes;
250 }
251 }
252}
253
Jim Inghamcd16df92012-07-20 21:37:13 +0000254bool
255GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
256{
257 if (m_attach_or_wait_reply == eLazyBoolCalculate)
258 {
259 m_attach_or_wait_reply = eLazyBoolNo;
260
261 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000262 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000263 {
264 if (response.IsOKResponse())
265 m_attach_or_wait_reply = eLazyBoolYes;
266 }
267 }
268 if (m_attach_or_wait_reply == eLazyBoolYes)
269 return true;
270 else
271 return false;
272}
273
Jim Ingham279ceec2012-07-25 21:12:43 +0000274bool
275GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
276{
277 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
278 {
279 m_prepare_for_reg_writing_reply = eLazyBoolNo;
280
281 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000282 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000283 {
284 if (response.IsOKResponse())
285 m_prepare_for_reg_writing_reply = eLazyBoolYes;
286 }
287 }
288 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
289 return true;
290 else
291 return false;
292}
293
Greg Clayton44633992012-04-10 03:22:03 +0000294
295void
Greg Clayton576d8832011-03-22 04:00:09 +0000296GDBRemoteCommunicationClient::ResetDiscoverableSettings()
297{
298 m_supports_not_sending_acks = eLazyBoolCalculate;
299 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton44633992012-04-10 03:22:03 +0000300 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
Greg Clayton576d8832011-03-22 04:00:09 +0000301 m_supports_vCont_c = eLazyBoolCalculate;
302 m_supports_vCont_C = eLazyBoolCalculate;
303 m_supports_vCont_s = eLazyBoolCalculate;
304 m_supports_vCont_S = eLazyBoolCalculate;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000305 m_supports_p = eLazyBoolCalculate;
Greg Claytonf74cf862013-11-13 23:28:31 +0000306 m_supports_QSaveRegisterState = eLazyBoolCalculate;
Greg Clayton32e0a752011-03-30 18:16:51 +0000307 m_qHostInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000308 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000309 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
Greg Clayton70b57652011-05-15 01:25:55 +0000310 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton46fb5582011-11-18 07:03:08 +0000311 m_supports_memory_region_info = eLazyBoolCalculate;
Jim Ingham279ceec2012-07-25 21:12:43 +0000312 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
313 m_attach_or_wait_reply = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000314 m_avoid_g_packets = eLazyBoolCalculate;
Steve Pucci03904ac2014-03-04 23:18:46 +0000315 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000316 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
317 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
318 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
Greg Clayton2a48f522011-05-14 01:50:35 +0000319
Greg Clayton32e0a752011-03-30 18:16:51 +0000320 m_supports_qProcessInfoPID = true;
321 m_supports_qfProcessInfo = true;
322 m_supports_qUserName = true;
323 m_supports_qGroupName = true;
Greg Clayton8b82f082011-04-12 05:54:46 +0000324 m_supports_qThreadStopInfo = true;
325 m_supports_z0 = true;
326 m_supports_z1 = true;
327 m_supports_z2 = true;
328 m_supports_z3 = true;
329 m_supports_z4 = true;
Greg Clayton89600582013-10-10 17:53:50 +0000330 m_supports_QEnvironment = true;
331 m_supports_QEnvironmentHexEncoded = true;
Jason Molendaa3329782014-03-29 18:54:20 +0000332
Greg Claytond314e812011-03-23 00:09:55 +0000333 m_host_arch.Clear();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000334 m_process_arch.Clear();
Jason Molendaa3329782014-03-29 18:54:20 +0000335 m_os_version_major = UINT32_MAX;
336 m_os_version_minor = UINT32_MAX;
337 m_os_version_update = UINT32_MAX;
338 m_os_build.clear();
339 m_os_kernel.clear();
340 m_hostname.clear();
341 m_gdb_server_name.clear();
342 m_gdb_server_version = UINT32_MAX;
343 m_default_packet_timeout = 0;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000344
345 m_max_packet_size = 0;
Greg Clayton576d8832011-03-22 04:00:09 +0000346}
347
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000348void
349GDBRemoteCommunicationClient::GetRemoteQSupported ()
350{
351 // Clear out any capabilities we expect to see in the qSupported response
Steve Pucci03904ac2014-03-04 23:18:46 +0000352 m_supports_qXfer_auxv_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000353 m_supports_qXfer_libraries_read = eLazyBoolNo;
Steve Pucci03904ac2014-03-04 23:18:46 +0000354 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000355 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
356 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
357
358 StringExtractorGDBRemote response;
359 if (SendPacketAndWaitForResponse("qSupported",
360 response,
361 /*send_async=*/false) == PacketResult::Success)
362 {
363 const char *response_cstr = response.GetStringRef().c_str();
Steve Pucci03904ac2014-03-04 23:18:46 +0000364 if (::strstr (response_cstr, "qXfer:auxv:read+"))
365 m_supports_qXfer_auxv_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000366 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
367 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
368 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
369 {
370 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
371 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
372 }
373 if (::strstr (response_cstr, "qXfer:libraries:read+"))
374 m_supports_qXfer_libraries_read = eLazyBoolYes;
375
376 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
377 if (packet_size_str)
378 {
379 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
380 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
381 if (m_max_packet_size == 0)
382 {
383 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
384 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
385 if (log)
386 log->Printf ("Garbled PacketSize spec in qSupported response");
387 }
388 }
389 }
390}
Greg Clayton576d8832011-03-22 04:00:09 +0000391
392bool
393GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
394{
395 if (m_supports_thread_suffix == eLazyBoolCalculate)
396 {
397 StringExtractorGDBRemote response;
398 m_supports_thread_suffix = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000399 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000400 {
401 if (response.IsOKResponse())
402 m_supports_thread_suffix = eLazyBoolYes;
403 }
404 }
405 return m_supports_thread_suffix;
406}
407bool
408GDBRemoteCommunicationClient::GetVContSupported (char flavor)
409{
410 if (m_supports_vCont_c == eLazyBoolCalculate)
411 {
412 StringExtractorGDBRemote response;
413 m_supports_vCont_any = eLazyBoolNo;
414 m_supports_vCont_all = eLazyBoolNo;
415 m_supports_vCont_c = eLazyBoolNo;
416 m_supports_vCont_C = eLazyBoolNo;
417 m_supports_vCont_s = eLazyBoolNo;
418 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000419 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000420 {
421 const char *response_cstr = response.GetStringRef().c_str();
422 if (::strstr (response_cstr, ";c"))
423 m_supports_vCont_c = eLazyBoolYes;
424
425 if (::strstr (response_cstr, ";C"))
426 m_supports_vCont_C = eLazyBoolYes;
427
428 if (::strstr (response_cstr, ";s"))
429 m_supports_vCont_s = eLazyBoolYes;
430
431 if (::strstr (response_cstr, ";S"))
432 m_supports_vCont_S = eLazyBoolYes;
433
434 if (m_supports_vCont_c == eLazyBoolYes &&
435 m_supports_vCont_C == eLazyBoolYes &&
436 m_supports_vCont_s == eLazyBoolYes &&
437 m_supports_vCont_S == eLazyBoolYes)
438 {
439 m_supports_vCont_all = eLazyBoolYes;
440 }
441
442 if (m_supports_vCont_c == eLazyBoolYes ||
443 m_supports_vCont_C == eLazyBoolYes ||
444 m_supports_vCont_s == eLazyBoolYes ||
445 m_supports_vCont_S == eLazyBoolYes)
446 {
447 m_supports_vCont_any = eLazyBoolYes;
448 }
449 }
450 }
451
452 switch (flavor)
453 {
454 case 'a': return m_supports_vCont_any;
455 case 'A': return m_supports_vCont_all;
456 case 'c': return m_supports_vCont_c;
457 case 'C': return m_supports_vCont_C;
458 case 's': return m_supports_vCont_s;
459 case 'S': return m_supports_vCont_S;
460 default: break;
461 }
462 return false;
463}
464
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000465// Check if the target supports 'p' packet. It sends out a 'p'
466// packet and checks the response. A normal packet will tell us
467// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000468//
469// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000470bool
Sean Callananb1de1142013-09-04 23:24:15 +0000471GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000472{
473 if (m_supports_p == eLazyBoolCalculate)
474 {
475 StringExtractorGDBRemote response;
476 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000477 char packet[256];
478 if (GetThreadSuffixSupported())
479 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
480 else
481 snprintf(packet, sizeof(packet), "p0");
482
Greg Clayton3dedae12013-12-06 21:45:27 +0000483 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000484 {
485 if (response.IsNormalResponse())
486 m_supports_p = eLazyBoolYes;
487 }
488 }
489 return m_supports_p;
490}
Greg Clayton576d8832011-03-22 04:00:09 +0000491
Greg Clayton3dedae12013-12-06 21:45:27 +0000492GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000493GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
494(
495 const char *payload_prefix,
496 std::string &response_string
497)
498{
499 Mutex::Locker locker;
500 if (!GetSequenceMutex(locker,
501 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
502 {
503 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
504 if (log)
505 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
506 payload_prefix);
507 return PacketResult::ErrorNoSequenceLock;
508 }
509
510 response_string = "";
511 std::string payload_prefix_str(payload_prefix);
512 unsigned int response_size = 0x1000;
513 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
514 response_size = GetRemoteMaxPacketSize();
515 }
516
517 for (unsigned int offset = 0; true; offset += response_size)
518 {
519 StringExtractorGDBRemote this_response;
520 // Construct payload
521 char sizeDescriptor[128];
522 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
523 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
524 this_response,
525 /*send_async=*/false);
526 if (result != PacketResult::Success)
527 return result;
528
529 const std::string &this_string = this_response.GetStringRef();
530
531 // Check for m or l as first character; l seems to mean this is the last chunk
532 char first_char = *this_string.c_str();
533 if (first_char != 'm' && first_char != 'l')
534 {
535 return PacketResult::ErrorReplyInvalid;
536 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000537 // Concatenate the result so far (skipping 'm' or 'l')
538 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000539 if (first_char == 'l')
540 // We're done
541 return PacketResult::Success;
542 }
543}
544
545GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000546GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
547(
548 const char *payload,
549 StringExtractorGDBRemote &response,
550 bool send_async
551)
552{
553 return SendPacketAndWaitForResponse (payload,
554 ::strlen (payload),
555 response,
556 send_async);
557}
558
Greg Clayton3dedae12013-12-06 21:45:27 +0000559GDBRemoteCommunicationClient::PacketResult
560GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
561 size_t payload_length,
562 StringExtractorGDBRemote &response)
563{
564 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
565 if (packet_result == PacketResult::Success)
566 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
567 return packet_result;
568}
569
570GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000571GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
572(
573 const char *payload,
574 size_t payload_length,
575 StringExtractorGDBRemote &response,
576 bool send_async
577)
578{
Greg Clayton3dedae12013-12-06 21:45:27 +0000579 PacketResult packet_result = PacketResult::ErrorSendFailed;
Greg Clayton576d8832011-03-22 04:00:09 +0000580 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000581 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000582 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000583 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000584 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000585 }
586 else
587 {
588 if (send_async)
589 {
Greg Claytond3544052012-05-31 21:24:20 +0000590 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000591 {
Greg Claytond3544052012-05-31 21:24:20 +0000592 Mutex::Locker async_locker (m_async_mutex);
593 m_async_packet.assign(payload, payload_length);
594 m_async_packet_predicate.SetValue (true, eBroadcastNever);
595
596 if (log)
597 log->Printf ("async: async packet = %s", m_async_packet.c_str());
598
599 bool timed_out = false;
600 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000601 {
Greg Claytond3544052012-05-31 21:24:20 +0000602 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000603 {
Jim Inghambabfc382012-06-06 00:32:39 +0000604 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000605 TimeValue timeout_time;
606 timeout_time = TimeValue::Now();
607 timeout_time.OffsetWithSeconds (m_packet_timeout);
608
Greg Clayton576d8832011-03-22 04:00:09 +0000609 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000610 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000611
Greg Claytond3544052012-05-31 21:24:20 +0000612 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000613 {
Greg Claytond3544052012-05-31 21:24:20 +0000614 if (log)
615 log->Printf ("async: got response");
616
617 // Swap the response buffer to avoid malloc and string copy
618 response.GetStringRef().swap (m_async_response.GetStringRef());
Jim Inghama6195b72013-12-18 01:24:33 +0000619 packet_result = m_async_result;
Greg Claytond3544052012-05-31 21:24:20 +0000620 }
621 else
622 {
623 if (log)
624 log->Printf ("async: timed out waiting for response");
625 }
626
627 // Make sure we wait until the continue packet has been sent again...
628 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
629 {
630 if (log)
631 {
632 if (timed_out)
633 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
634 else
635 log->Printf ("async: async packet sent");
636 }
637 }
638 else
639 {
640 if (log)
641 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000642 }
643 }
644 else
645 {
Greg Claytond3544052012-05-31 21:24:20 +0000646 // We had a racy condition where we went to send the interrupt
647 // yet we were able to get the lock, so the process must have
648 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000649 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000650 log->Printf ("async: got lock without sending interrupt");
651 // Send the packet normally since we got the lock
Greg Clayton3dedae12013-12-06 21:45:27 +0000652 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000653 }
654 }
655 else
656 {
Greg Clayton644247c2011-07-07 01:59:51 +0000657 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000658 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000659 }
660 }
661 else
662 {
663 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000664 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000665 }
666 }
667 else
668 {
669 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000670 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000671 }
672 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000673 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000674}
675
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000676static const char *end_delimiter = "--end--;";
677static const int end_delimiter_len = 8;
678
679std::string
680GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
681( ProcessGDBRemote *process,
682 StringExtractorGDBRemote& profileDataExtractor
683)
684{
685 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
686 std::stringstream final_output;
687 std::string name, value;
688
689 // Going to assuming thread_used_usec comes first, else bail out.
690 while (profileDataExtractor.GetNameColonValue(name, value))
691 {
692 if (name.compare("thread_used_id") == 0)
693 {
694 StringExtractor threadIDHexExtractor(value.c_str());
695 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
696
697 bool has_used_usec = false;
698 uint32_t curr_used_usec = 0;
699 std::string usec_name, usec_value;
700 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
701 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
702 {
703 if (usec_name.compare("thread_used_usec") == 0)
704 {
705 has_used_usec = true;
706 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
707 }
708 else
709 {
710 // We didn't find what we want, it is probably
711 // an older version. Bail out.
712 profileDataExtractor.SetFilePos(input_file_pos);
713 }
714 }
715
716 if (has_used_usec)
717 {
718 uint32_t prev_used_usec = 0;
719 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
720 if (iterator != m_thread_id_to_used_usec_map.end())
721 {
722 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
723 }
724
725 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
726 // A good first time record is one that runs for at least 0.25 sec
727 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
728 bool good_subsequent_time = (prev_used_usec > 0) &&
729 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
730
731 if (good_first_time || good_subsequent_time)
732 {
733 // We try to avoid doing too many index id reservation,
734 // resulting in fast increase of index ids.
735
736 final_output << name << ":";
737 int32_t index_id = process->AssignIndexIDToThread(thread_id);
738 final_output << index_id << ";";
739
740 final_output << usec_name << ":" << usec_value << ";";
741 }
742 else
743 {
744 // Skip past 'thread_used_name'.
745 std::string local_name, local_value;
746 profileDataExtractor.GetNameColonValue(local_name, local_value);
747 }
748
749 // Store current time as previous time so that they can be compared later.
750 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
751 }
752 else
753 {
754 // Bail out and use old string.
755 final_output << name << ":" << value << ";";
756 }
757 }
758 else
759 {
760 final_output << name << ":" << value << ";";
761 }
762 }
763 final_output << end_delimiter;
764 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
765
766 return final_output.str();
767}
768
Greg Clayton576d8832011-03-22 04:00:09 +0000769StateType
770GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
771(
772 ProcessGDBRemote *process,
773 const char *payload,
774 size_t packet_length,
775 StringExtractorGDBRemote &response
776)
777{
Greg Clayton1f5181a2012-07-02 22:05:25 +0000778 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +0000779 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +0000780 if (log)
781 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
782
783 Mutex::Locker locker(m_sequence_mutex);
784 StateType state = eStateRunning;
785
786 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
787 m_public_is_running.SetValue (true, eBroadcastNever);
788 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +0000789 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +0000790 std::string continue_packet(payload, packet_length);
791
Greg Clayton3f875c52013-02-22 22:23:55 +0000792 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +0000793
Greg Clayton576d8832011-03-22 04:00:09 +0000794 while (state == eStateRunning)
795 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000796 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +0000797 {
798 if (log)
799 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton3dedae12013-12-06 21:45:27 +0000800 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
Greg Claytonaf247d72011-05-19 03:54:16 +0000801 state = eStateInvalid;
Greg Clayton576d8832011-03-22 04:00:09 +0000802
Greg Claytone889ad62011-10-27 22:04:16 +0000803 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +0000804 }
805
Greg Clayton3f875c52013-02-22 22:23:55 +0000806 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000807
808 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000809 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +0000810
Greg Clayton3dedae12013-12-06 21:45:27 +0000811 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000812 {
813 if (response.Empty())
814 state = eStateInvalid;
815 else
816 {
817 const char stop_type = response.GetChar();
818 if (log)
819 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
820 switch (stop_type)
821 {
822 case 'T':
823 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +0000824 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000825 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +0000826 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000827 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
828 {
829 lldb::pid_t pid = GetCurrentProcessID ();
830 if (pid != LLDB_INVALID_PROCESS_ID)
831 process->SetID (pid);
832 }
833 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +0000834 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000835
836 // Privately notify any internal threads that we have stopped
837 // in case we wanted to interrupt our process, yet we might
838 // send a packet and continue without returning control to the
839 // user.
840 m_private_is_running.SetValue (false, eBroadcastAlways);
841
842 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
843
Jim Inghambabfc382012-06-06 00:32:39 +0000844 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
845 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +0000846 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000847 // We sent an interrupt packet to stop the inferior process
848 // for an async signal or to send an async packet while running
849 // but we might have been single stepping and received the
850 // stop packet for the step instead of for the interrupt packet.
851 // Typically when an interrupt is sent a SIGINT or SIGSTOP
852 // is used, so if we get anything else, we need to try and
853 // get another stop reply packet that may have been sent
854 // due to sending the interrupt when the target is stopped
855 // which will just re-send a copy of the last stop reply
856 // packet. If we don't do this, then the reply for our
857 // async packet will be the repeat stop reply packet and cause
858 // a lot of trouble for us!
859 if (signo != SIGINT && signo != SIGSTOP)
860 {
Greg Claytonfb72fde2012-05-15 02:50:49 +0000861 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000862
863 // We didn't get a a SIGINT or SIGSTOP, so try for a
864 // very brief time (1 ms) to get another stop reply
865 // packet to make sure it doesn't get in the way
866 StringExtractorGDBRemote extra_stop_reply_packet;
867 uint32_t timeout_usec = 1000;
Greg Clayton3dedae12013-12-06 21:45:27 +0000868 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +0000869 {
870 switch (extra_stop_reply_packet.GetChar())
871 {
872 case 'T':
873 case 'S':
874 // We did get an extra stop reply, which means
875 // our interrupt didn't stop the target so we
876 // shouldn't continue after the async signal
877 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +0000878 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000879 break;
880 }
881 }
882 }
883 }
884
885 if (m_async_signal != -1)
886 {
887 if (log)
888 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
889
890 // Save off the async signal we are supposed to send
891 const int async_signal = m_async_signal;
892 // Clear the async signal member so we don't end up
893 // sending the signal multiple times...
894 m_async_signal = -1;
895 // Check which signal we stopped with
896 if (signo == async_signal)
897 {
898 if (log)
899 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
900
901 // We already stopped with a signal that we wanted
902 // to stop with, so we are done
903 }
904 else
905 {
906 // We stopped with a different signal that the one
907 // we wanted to stop with, so now we must resume
908 // with the signal we want
909 char signal_packet[32];
910 int signal_packet_len = 0;
911 signal_packet_len = ::snprintf (signal_packet,
912 sizeof (signal_packet),
913 "C%2.2x",
914 async_signal);
915
916 if (log)
917 log->Printf ("async: stopped with signal %s, resume with %s",
918 Host::GetSignalAsCString (signo),
919 Host::GetSignalAsCString (async_signal));
920
921 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +0000922 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000923 continue_packet.assign(signal_packet, signal_packet_len);
924 continue;
925 }
926 }
927 else if (m_async_packet_predicate.GetValue())
928 {
Greg Clayton5160ce52013-03-27 23:08:40 +0000929 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +0000930
931 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +0000932 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +0000933 m_async_response.Clear();
934 if (m_async_packet.empty())
935 {
Jim Inghama6195b72013-12-18 01:24:33 +0000936 m_async_result = PacketResult::ErrorSendFailed;
937 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000938 packet_log->Printf ("async: error: empty async packet");
939
940 }
941 else
942 {
943 if (packet_log)
944 packet_log->Printf ("async: sending packet");
945
Jim Inghama6195b72013-12-18 01:24:33 +0000946 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
947 m_async_packet.size(),
948 m_async_response,
949 false);
Greg Clayton2687cd12012-03-29 01:55:41 +0000950 }
951 // Let the other thread that was trying to send the async
952 // packet know that the packet has been sent and response is
953 // ready...
954 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
955
956 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +0000957 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +0000958
959 // Set the continue packet to resume if our interrupt
960 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +0000961 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000962 {
Greg Claytonf1186de2012-05-24 23:42:14 +0000963 // Reverting this for now as it is causing deadlocks
964 // in programs (<rdar://problem/11529853>). In the future
965 // we should check our thread list and "do the right thing"
966 // for new threads that show up while we stop and run async
967 // packets. Setting the packet to 'c' to continue all threads
968 // is the right thing to do 99.99% of the time because if a
969 // thread was single stepping, and we sent an interrupt, we
970 // will notice above that we didn't stop due to an interrupt
971 // but stopped due to stepping and we would _not_ continue.
972 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +0000973 continue;
974 }
975 }
976 // Stop with signal and thread info
977 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +0000978 }
Greg Clayton576d8832011-03-22 04:00:09 +0000979 break;
980
981 case 'W':
982 case 'X':
983 // process exited
984 state = eStateExited;
985 break;
986
987 case 'O':
988 // STDOUT
989 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000990 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000991 std::string inferior_stdout;
992 inferior_stdout.reserve(response.GetBytesLeft () / 2);
993 char ch;
994 while ((ch = response.GetHexU8()) != '\0')
995 inferior_stdout.append(1, ch);
996 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
997 }
998 break;
999
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001000 case 'A':
1001 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1002 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001003 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001004 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1005 if (m_partial_profile_data.length() > 0)
1006 {
1007 m_partial_profile_data.append(input);
1008 input = m_partial_profile_data;
1009 m_partial_profile_data.clear();
1010 }
1011
1012 size_t found, pos = 0, len = input.length();
1013 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1014 {
1015 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +00001016 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1017 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001018
1019 pos = found + end_delimiter_len;
1020 }
1021
1022 if (pos < len)
1023 {
1024 // Last incomplete chunk.
1025 m_partial_profile_data = input.substr(pos);
1026 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001027 }
1028 break;
1029
Greg Clayton576d8832011-03-22 04:00:09 +00001030 case 'E':
1031 // ERROR
1032 state = eStateInvalid;
1033 break;
1034
1035 default:
1036 if (log)
1037 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1038 state = eStateInvalid;
1039 break;
1040 }
1041 }
1042 }
1043 else
1044 {
1045 if (log)
1046 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
1047 state = eStateInvalid;
1048 }
1049 }
1050 if (log)
1051 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1052 response.SetFilePos(0);
1053 m_private_is_running.SetValue (false, eBroadcastAlways);
1054 m_public_is_running.SetValue (false, eBroadcastAlways);
1055 return state;
1056}
1057
1058bool
1059GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1060{
Greg Clayton2687cd12012-03-29 01:55:41 +00001061 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001062 m_async_signal = signo;
1063 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001064 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001065 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001066 return true;
1067 m_async_signal = -1;
1068 return false;
1069}
1070
Greg Clayton37a0a242012-04-11 00:24:49 +00001071// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001072// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1073// (the expected result), then it will send the halt packet. If it does succeed
1074// then the caller that requested the interrupt will want to keep the sequence
1075// locked down so that no one else can send packets while the caller has control.
1076// This function usually gets called when we are running and need to stop the
1077// target. It can also be used when we are running and and we need to do something
1078// else (like read/write memory), so we need to interrupt the running process
1079// (gdb remote protocol requires this), and do what we need to do, then resume.
1080
1081bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001082GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001083(
1084 Mutex::Locker& locker,
1085 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001086 bool &timed_out
1087)
1088{
Greg Clayton576d8832011-03-22 04:00:09 +00001089 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001090 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001091
1092 if (IsRunning())
1093 {
1094 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001095 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001096 {
1097 if (log)
1098 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1099 }
1100 else
Greg Clayton576d8832011-03-22 04:00:09 +00001101 {
1102 // Someone has the mutex locked waiting for a response or for the
1103 // inferior to stop, so send the interrupt on the down low...
1104 char ctrl_c = '\x03';
1105 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001106 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001107 if (log)
1108 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001109 if (bytes_written > 0)
1110 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001111 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001112 if (seconds_to_wait_for_stop)
1113 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001114 TimeValue timeout;
1115 if (seconds_to_wait_for_stop)
1116 {
1117 timeout = TimeValue::Now();
1118 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1119 }
Greg Clayton576d8832011-03-22 04:00:09 +00001120 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1121 {
1122 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001123 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001124 return true;
1125 }
1126 else
1127 {
1128 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001129 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001130 }
1131 }
1132 else
1133 {
1134 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001135 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001136 return true;
1137 }
1138 }
1139 else
1140 {
1141 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001142 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001143 }
1144 return false;
1145 }
Greg Clayton576d8832011-03-22 04:00:09 +00001146 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001147 else
1148 {
1149 if (log)
1150 log->Printf ("SendInterrupt () - not running");
1151 }
Greg Clayton576d8832011-03-22 04:00:09 +00001152 return true;
1153}
1154
1155lldb::pid_t
1156GDBRemoteCommunicationClient::GetCurrentProcessID ()
1157{
1158 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001159 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001160 {
1161 if (response.GetChar() == 'Q')
1162 if (response.GetChar() == 'C')
1163 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1164 }
1165 return LLDB_INVALID_PROCESS_ID;
1166}
1167
1168bool
1169GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1170{
1171 error_str.clear();
1172 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001173 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001174 {
1175 if (response.IsOKResponse())
1176 return true;
1177 if (response.GetChar() == 'E')
1178 {
1179 // A string the describes what failed when launching...
1180 error_str = response.GetStringRef().substr(1);
1181 }
1182 else
1183 {
1184 error_str.assign ("unknown error occurred launching process");
1185 }
1186 }
1187 else
1188 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001189 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001190 }
1191 return false;
1192}
1193
1194int
Greg Claytonfbb76342013-11-20 21:07:01 +00001195GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001196{
Greg Claytonfbb76342013-11-20 21:07:01 +00001197 // Since we don't get the send argv0 separate from the executable path, we need to
1198 // make sure to use the actual exectuable path found in the launch_info...
1199 std::vector<const char *> argv;
1200 FileSpec exe_file = launch_info.GetExecutableFile();
1201 std::string exe_path;
1202 const char *arg = NULL;
1203 const Args &launch_args = launch_info.GetArguments();
1204 if (exe_file)
1205 exe_path = exe_file.GetPath();
1206 else
1207 {
1208 arg = launch_args.GetArgumentAtIndex(0);
1209 if (arg)
1210 exe_path = arg;
1211 }
1212 if (!exe_path.empty())
1213 {
1214 argv.push_back(exe_path.c_str());
1215 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1216 {
1217 if (arg)
1218 argv.push_back(arg);
1219 }
1220 }
1221 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001222 {
1223 StreamString packet;
1224 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001225 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001226 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001227 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001228 const int arg_len = strlen(arg);
1229 if (i > 0)
1230 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001231 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001232 packet.PutBytesAsRawHex8 (arg, arg_len);
1233 }
1234
1235 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001236 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001237 {
1238 if (response.IsOKResponse())
1239 return 0;
1240 uint8_t error = response.GetError();
1241 if (error)
1242 return error;
1243 }
1244 }
1245 return -1;
1246}
1247
1248int
1249GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1250{
1251 if (name_equal_value && name_equal_value[0])
1252 {
1253 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001254 bool send_hex_encoding = false;
1255 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001256 {
Greg Clayton89600582013-10-10 17:53:50 +00001257 if (isprint(*p))
1258 {
1259 switch (*p)
1260 {
1261 case '$':
1262 case '#':
1263 send_hex_encoding = true;
1264 break;
1265 default:
1266 break;
1267 }
1268 }
1269 else
1270 {
1271 // We have non printable characters, lets hex encode this...
1272 send_hex_encoding = true;
1273 }
1274 }
1275
1276 StringExtractorGDBRemote response;
1277 if (send_hex_encoding)
1278 {
1279 if (m_supports_QEnvironmentHexEncoded)
1280 {
1281 packet.PutCString("QEnvironmentHexEncoded:");
1282 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001283 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001284 {
1285 if (response.IsOKResponse())
1286 return 0;
1287 uint8_t error = response.GetError();
1288 if (error)
1289 return error;
1290 if (response.IsUnsupportedResponse())
1291 m_supports_QEnvironmentHexEncoded = false;
1292 }
1293 }
1294
1295 }
1296 else if (m_supports_QEnvironment)
1297 {
1298 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +00001299 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001300 {
1301 if (response.IsOKResponse())
1302 return 0;
1303 uint8_t error = response.GetError();
1304 if (error)
1305 return error;
1306 if (response.IsUnsupportedResponse())
1307 m_supports_QEnvironment = false;
1308 }
Greg Clayton576d8832011-03-22 04:00:09 +00001309 }
1310 }
1311 return -1;
1312}
1313
Greg Claytonc4103b32011-05-08 04:53:50 +00001314int
1315GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1316{
1317 if (arch && arch[0])
1318 {
1319 StreamString packet;
1320 packet.Printf("QLaunchArch:%s", arch);
1321 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001322 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001323 {
1324 if (response.IsOKResponse())
1325 return 0;
1326 uint8_t error = response.GetError();
1327 if (error)
1328 return error;
1329 }
1330 }
1331 return -1;
1332}
1333
Jason Molendaa3329782014-03-29 18:54:20 +00001334int
1335GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1336{
1337 if (data && *data != '\0')
1338 {
1339 StreamString packet;
1340 packet.Printf("QSetProcessEvent:%s", data);
1341 StringExtractorGDBRemote response;
1342 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1343 {
1344 if (response.IsOKResponse())
1345 {
1346 if (was_supported)
1347 *was_supported = true;
1348 return 0;
1349 }
1350 else if (response.IsUnsupportedResponse())
1351 {
1352 if (was_supported)
1353 *was_supported = false;
1354 return -1;
1355 }
1356 else
1357 {
1358 uint8_t error = response.GetError();
1359 if (was_supported)
1360 *was_supported = true;
1361 if (error)
1362 return error;
1363 }
1364 }
1365 }
1366 return -1;
1367}
1368
Greg Clayton576d8832011-03-22 04:00:09 +00001369bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001370GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1371 uint32_t &minor,
1372 uint32_t &update)
1373{
1374 if (GetHostInfo ())
1375 {
1376 if (m_os_version_major != UINT32_MAX)
1377 {
1378 major = m_os_version_major;
1379 minor = m_os_version_minor;
1380 update = m_os_version_update;
1381 return true;
1382 }
1383 }
1384 return false;
1385}
1386
1387bool
1388GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1389{
1390 if (GetHostInfo ())
1391 {
1392 if (!m_os_build.empty())
1393 {
1394 s = m_os_build;
1395 return true;
1396 }
1397 }
1398 s.clear();
1399 return false;
1400}
1401
1402
1403bool
1404GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1405{
1406 if (GetHostInfo ())
1407 {
1408 if (!m_os_kernel.empty())
1409 {
1410 s = m_os_kernel;
1411 return true;
1412 }
1413 }
1414 s.clear();
1415 return false;
1416}
1417
1418bool
1419GDBRemoteCommunicationClient::GetHostname (std::string &s)
1420{
1421 if (GetHostInfo ())
1422 {
1423 if (!m_hostname.empty())
1424 {
1425 s = m_hostname;
1426 return true;
1427 }
1428 }
1429 s.clear();
1430 return false;
1431}
1432
1433ArchSpec
1434GDBRemoteCommunicationClient::GetSystemArchitecture ()
1435{
1436 if (GetHostInfo ())
1437 return m_host_arch;
1438 return ArchSpec();
1439}
1440
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001441const lldb_private::ArchSpec &
1442GDBRemoteCommunicationClient::GetProcessArchitecture ()
1443{
1444 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1445 GetCurrentProcessInfo ();
1446 return m_process_arch;
1447}
1448
Jason Molendaa3329782014-03-29 18:54:20 +00001449bool
1450GDBRemoteCommunicationClient::GetGDBServerVersion()
1451{
1452 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1453 {
1454 m_gdb_server_name.clear();
1455 m_gdb_server_version = 0;
1456 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1457
1458 StringExtractorGDBRemote response;
1459 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1460 {
1461 if (response.IsNormalResponse())
1462 {
1463 std::string name;
1464 std::string value;
1465 bool success = false;
1466 while (response.GetNameColonValue(name, value))
1467 {
1468 if (name.compare("name") == 0)
1469 {
1470 success = true;
1471 m_gdb_server_name.swap(value);
1472 }
1473 else if (name.compare("version") == 0)
1474 {
1475 size_t dot_pos = value.find('.');
1476 if (dot_pos != std::string::npos)
1477 value[dot_pos] = '\0';
1478 const uint32_t version = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
1479 if (version != UINT32_MAX)
1480 {
1481 success = true;
1482 m_gdb_server_version = version;
1483 }
1484 }
1485 }
1486 if (success)
1487 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1488 }
1489 }
1490 }
1491 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1492}
1493
1494const char *
1495GDBRemoteCommunicationClient::GetGDBServerProgramName()
1496{
1497 if (GetGDBServerVersion())
1498 {
1499 if (!m_gdb_server_name.empty())
1500 return m_gdb_server_name.c_str();
1501 }
1502 return NULL;
1503}
1504
1505uint32_t
1506GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1507{
1508 if (GetGDBServerVersion())
1509 return m_gdb_server_version;
1510 return 0;
1511}
Greg Clayton1cb64962011-03-24 04:28:38 +00001512
1513bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001514GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001515{
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001516 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001517 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001518 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001519 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001520 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001521 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001522 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001523 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001524 std::string name;
1525 std::string value;
1526 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1527 uint32_t sub = 0;
1528 std::string arch_name;
1529 std::string os_name;
1530 std::string vendor_name;
1531 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001532 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001533 uint32_t pointer_byte_size = 0;
1534 StringExtractor extractor;
1535 ByteOrder byte_order = eByteOrderInvalid;
1536 uint32_t num_keys_decoded = 0;
1537 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001538 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001539 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001540 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001541 // exception type in big endian hex
1542 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1543 if (cpu != LLDB_INVALID_CPUTYPE)
1544 ++num_keys_decoded;
1545 }
1546 else if (name.compare("cpusubtype") == 0)
1547 {
1548 // exception count in big endian hex
1549 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
1550 if (sub != 0)
1551 ++num_keys_decoded;
1552 }
1553 else if (name.compare("arch") == 0)
1554 {
1555 arch_name.swap (value);
1556 ++num_keys_decoded;
1557 }
1558 else if (name.compare("triple") == 0)
1559 {
1560 // The triple comes as ASCII hex bytes since it contains '-' chars
1561 extractor.GetStringRef().swap(value);
1562 extractor.SetFilePos(0);
1563 extractor.GetHexByteString (triple);
1564 ++num_keys_decoded;
1565 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001566 else if (name.compare ("distribution_id") == 0)
1567 {
1568 extractor.GetStringRef ().swap (value);
1569 extractor.SetFilePos (0);
1570 extractor.GetHexByteString (distribution_id);
1571 ++num_keys_decoded;
1572 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001573 else if (name.compare("os_build") == 0)
1574 {
1575 extractor.GetStringRef().swap(value);
1576 extractor.SetFilePos(0);
1577 extractor.GetHexByteString (m_os_build);
1578 ++num_keys_decoded;
1579 }
1580 else if (name.compare("hostname") == 0)
1581 {
1582 extractor.GetStringRef().swap(value);
1583 extractor.SetFilePos(0);
1584 extractor.GetHexByteString (m_hostname);
1585 ++num_keys_decoded;
1586 }
1587 else if (name.compare("os_kernel") == 0)
1588 {
1589 extractor.GetStringRef().swap(value);
1590 extractor.SetFilePos(0);
1591 extractor.GetHexByteString (m_os_kernel);
1592 ++num_keys_decoded;
1593 }
1594 else if (name.compare("ostype") == 0)
1595 {
1596 os_name.swap (value);
1597 ++num_keys_decoded;
1598 }
1599 else if (name.compare("vendor") == 0)
1600 {
1601 vendor_name.swap(value);
1602 ++num_keys_decoded;
1603 }
1604 else if (name.compare("endian") == 0)
1605 {
1606 ++num_keys_decoded;
1607 if (value.compare("little") == 0)
1608 byte_order = eByteOrderLittle;
1609 else if (value.compare("big") == 0)
1610 byte_order = eByteOrderBig;
1611 else if (value.compare("pdp") == 0)
1612 byte_order = eByteOrderPDP;
1613 else
1614 --num_keys_decoded;
1615 }
1616 else if (name.compare("ptrsize") == 0)
1617 {
1618 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1619 if (pointer_byte_size != 0)
1620 ++num_keys_decoded;
1621 }
1622 else if (name.compare("os_version") == 0)
1623 {
1624 Args::StringToVersion (value.c_str(),
1625 m_os_version_major,
1626 m_os_version_minor,
1627 m_os_version_update);
1628 if (m_os_version_major != UINT32_MAX)
1629 ++num_keys_decoded;
1630 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001631 else if (name.compare("watchpoint_exceptions_received") == 0)
1632 {
1633 ++num_keys_decoded;
1634 if (strcmp(value.c_str(),"before") == 0)
1635 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1636 else if (strcmp(value.c_str(),"after") == 0)
1637 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1638 else
1639 --num_keys_decoded;
1640 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001641 else if (name.compare("default_packet_timeout") == 0)
1642 {
1643 m_default_packet_timeout = Args::StringToUInt32(value.c_str(), 0);
1644 if (m_default_packet_timeout > 0)
1645 {
1646 SetPacketTimeout(m_default_packet_timeout);
1647 ++num_keys_decoded;
1648 }
1649 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001650
Greg Clayton32e0a752011-03-30 18:16:51 +00001651 }
1652
1653 if (num_keys_decoded > 0)
1654 m_qHostInfo_is_valid = eLazyBoolYes;
1655
1656 if (triple.empty())
1657 {
1658 if (arch_name.empty())
1659 {
1660 if (cpu != LLDB_INVALID_CPUTYPE)
1661 {
1662 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1663 if (pointer_byte_size)
1664 {
1665 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1666 }
1667 if (byte_order != eByteOrderInvalid)
1668 {
1669 assert (byte_order == m_host_arch.GetByteOrder());
1670 }
Greg Clayton70512312012-05-08 01:45:38 +00001671
1672 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1673 {
1674 switch (m_host_arch.GetMachine())
1675 {
Jason Molendaa3329782014-03-29 18:54:20 +00001676 case llvm::Triple::arm64:
Greg Clayton70512312012-05-08 01:45:38 +00001677 case llvm::Triple::arm:
1678 case llvm::Triple::thumb:
1679 os_name = "ios";
1680 break;
1681 default:
1682 os_name = "macosx";
1683 break;
1684 }
1685 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001686 if (!vendor_name.empty())
1687 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1688 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001689 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001690
1691 }
1692 }
1693 else
1694 {
1695 std::string triple;
1696 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001697 if (!vendor_name.empty() || !os_name.empty())
1698 {
1699 triple += '-';
1700 if (vendor_name.empty())
1701 triple += "unknown";
1702 else
1703 triple += vendor_name;
1704 triple += '-';
1705 if (os_name.empty())
1706 triple += "unknown";
1707 else
1708 triple += os_name;
1709 }
1710 m_host_arch.SetTriple (triple.c_str());
1711
1712 llvm::Triple &host_triple = m_host_arch.GetTriple();
1713 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1714 {
1715 switch (m_host_arch.GetMachine())
1716 {
Jason Molendaa3329782014-03-29 18:54:20 +00001717 case llvm::Triple::arm64:
Greg Clayton70512312012-05-08 01:45:38 +00001718 case llvm::Triple::arm:
1719 case llvm::Triple::thumb:
1720 host_triple.setOS(llvm::Triple::IOS);
1721 break;
1722 default:
1723 host_triple.setOS(llvm::Triple::MacOSX);
1724 break;
1725 }
1726 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001727 if (pointer_byte_size)
1728 {
1729 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1730 }
1731 if (byte_order != eByteOrderInvalid)
1732 {
1733 assert (byte_order == m_host_arch.GetByteOrder());
1734 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001735
Greg Clayton1cb64962011-03-24 04:28:38 +00001736 }
1737 }
1738 else
1739 {
Greg Clayton70512312012-05-08 01:45:38 +00001740 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001741 if (pointer_byte_size)
1742 {
1743 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1744 }
1745 if (byte_order != eByteOrderInvalid)
1746 {
1747 assert (byte_order == m_host_arch.GetByteOrder());
1748 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001749 }
1750 if (!distribution_id.empty ())
1751 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00001752 }
Greg Clayton576d8832011-03-22 04:00:09 +00001753 }
1754 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001755 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001756}
1757
1758int
1759GDBRemoteCommunicationClient::SendAttach
1760(
1761 lldb::pid_t pid,
1762 StringExtractorGDBRemote& response
1763)
1764{
1765 if (pid != LLDB_INVALID_PROCESS_ID)
1766 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001767 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001768 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001769 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00001770 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001771 {
1772 if (response.IsErrorResponse())
1773 return response.GetError();
1774 return 0;
1775 }
1776 }
1777 return -1;
1778}
1779
1780const lldb_private::ArchSpec &
1781GDBRemoteCommunicationClient::GetHostArchitecture ()
1782{
Greg Clayton32e0a752011-03-30 18:16:51 +00001783 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001784 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001785 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001786}
1787
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001788uint32_t
1789GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1790{
1791 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1792 GetHostInfo ();
1793 return m_default_packet_timeout;
1794}
1795
Greg Clayton576d8832011-03-22 04:00:09 +00001796addr_t
1797GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1798{
Greg Clayton70b57652011-05-15 01:25:55 +00001799 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001800 {
Greg Clayton70b57652011-05-15 01:25:55 +00001801 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001802 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001803 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001804 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001805 permissions & lldb::ePermissionsReadable ? "r" : "",
1806 permissions & lldb::ePermissionsWritable ? "w" : "",
1807 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001808 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001809 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001810 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001811 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001812 if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001813 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1814 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001815 else
1816 {
1817 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1818 }
Greg Clayton576d8832011-03-22 04:00:09 +00001819 }
1820 return LLDB_INVALID_ADDRESS;
1821}
1822
1823bool
1824GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1825{
Greg Clayton70b57652011-05-15 01:25:55 +00001826 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001827 {
Greg Clayton70b57652011-05-15 01:25:55 +00001828 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001829 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001830 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001831 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001832 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001833 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001834 {
1835 if (response.IsOKResponse())
1836 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001837 }
1838 else
1839 {
1840 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00001841 }
Greg Clayton576d8832011-03-22 04:00:09 +00001842 }
1843 return false;
1844}
1845
Jim Inghamacff8952013-05-02 00:27:30 +00001846Error
1847GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00001848{
Jim Inghamacff8952013-05-02 00:27:30 +00001849 Error error;
1850
1851 if (keep_stopped)
1852 {
1853 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1854 {
1855 char packet[64];
1856 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001857 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00001858 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001859 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001860 {
1861 m_supports_detach_stay_stopped = eLazyBoolYes;
1862 }
1863 else
1864 {
1865 m_supports_detach_stay_stopped = eLazyBoolNo;
1866 }
1867 }
1868
1869 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1870 {
1871 error.SetErrorString("Stays stopped not supported by this target.");
1872 return error;
1873 }
1874 else
1875 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00001876 StringExtractorGDBRemote response;
1877 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00001878 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001879 error.SetErrorString ("Sending extended disconnect packet failed.");
1880 }
1881 }
1882 else
1883 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00001884 StringExtractorGDBRemote response;
1885 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00001886 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001887 error.SetErrorString ("Sending disconnect packet failed.");
1888 }
1889 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001890}
1891
Greg Clayton46fb5582011-11-18 07:03:08 +00001892Error
1893GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1894 lldb_private::MemoryRegionInfo &region_info)
1895{
1896 Error error;
1897 region_info.Clear();
1898
1899 if (m_supports_memory_region_info != eLazyBoolNo)
1900 {
1901 m_supports_memory_region_info = eLazyBoolYes;
1902 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001903 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001904 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00001905 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001906 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00001907 {
1908 std::string name;
1909 std::string value;
1910 addr_t addr_value;
1911 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00001912 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00001913 while (success && response.GetNameColonValue(name, value))
1914 {
1915 if (name.compare ("start") == 0)
1916 {
1917 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1918 if (success)
1919 region_info.GetRange().SetRangeBase(addr_value);
1920 }
1921 else if (name.compare ("size") == 0)
1922 {
1923 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1924 if (success)
1925 region_info.GetRange().SetByteSize (addr_value);
1926 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001927 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00001928 {
Jason Molendacb349ee2011-12-13 05:39:38 +00001929 saw_permissions = true;
1930 if (region_info.GetRange().Contains (addr))
1931 {
1932 if (value.find('r') != std::string::npos)
1933 region_info.SetReadable (MemoryRegionInfo::eYes);
1934 else
1935 region_info.SetReadable (MemoryRegionInfo::eNo);
1936
1937 if (value.find('w') != std::string::npos)
1938 region_info.SetWritable (MemoryRegionInfo::eYes);
1939 else
1940 region_info.SetWritable (MemoryRegionInfo::eNo);
1941
1942 if (value.find('x') != std::string::npos)
1943 region_info.SetExecutable (MemoryRegionInfo::eYes);
1944 else
1945 region_info.SetExecutable (MemoryRegionInfo::eNo);
1946 }
1947 else
1948 {
1949 // The reported region does not contain this address -- we're looking at an unmapped page
1950 region_info.SetReadable (MemoryRegionInfo::eNo);
1951 region_info.SetWritable (MemoryRegionInfo::eNo);
1952 region_info.SetExecutable (MemoryRegionInfo::eNo);
1953 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001954 }
1955 else if (name.compare ("error") == 0)
1956 {
1957 StringExtractorGDBRemote name_extractor;
1958 // Swap "value" over into "name_extractor"
1959 name_extractor.GetStringRef().swap(value);
1960 // Now convert the HEX bytes into a string value
1961 name_extractor.GetHexByteString (value);
1962 error.SetErrorString(value.c_str());
1963 }
1964 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001965
1966 // We got a valid address range back but no permissions -- which means this is an unmapped page
1967 if (region_info.GetRange().IsValid() && saw_permissions == false)
1968 {
1969 region_info.SetReadable (MemoryRegionInfo::eNo);
1970 region_info.SetWritable (MemoryRegionInfo::eNo);
1971 region_info.SetExecutable (MemoryRegionInfo::eNo);
1972 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001973 }
1974 else
1975 {
1976 m_supports_memory_region_info = eLazyBoolNo;
1977 }
1978 }
1979
1980 if (m_supports_memory_region_info == eLazyBoolNo)
1981 {
1982 error.SetErrorString("qMemoryRegionInfo is not supported");
1983 }
1984 if (error.Fail())
1985 region_info.Clear();
1986 return error;
1987
1988}
1989
Johnny Chen64637202012-05-23 21:09:52 +00001990Error
1991GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1992{
1993 Error error;
1994
1995 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1996 {
1997 num = m_num_supported_hardware_watchpoints;
1998 return error;
1999 }
2000
2001 // Set num to 0 first.
2002 num = 0;
2003 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2004 {
2005 char packet[64];
2006 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002007 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00002008 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002009 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00002010 {
2011 m_supports_watchpoint_support_info = eLazyBoolYes;
2012 std::string name;
2013 std::string value;
2014 while (response.GetNameColonValue(name, value))
2015 {
2016 if (name.compare ("num") == 0)
2017 {
2018 num = Args::StringToUInt32(value.c_str(), 0, 0);
2019 m_num_supported_hardware_watchpoints = num;
2020 }
2021 }
2022 }
2023 else
2024 {
2025 m_supports_watchpoint_support_info = eLazyBoolNo;
2026 }
2027 }
2028
2029 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2030 {
2031 error.SetErrorString("qWatchpointSupportInfo is not supported");
2032 }
2033 return error;
2034
2035}
Greg Clayton46fb5582011-11-18 07:03:08 +00002036
Enrico Granataf04a2192012-07-13 23:18:48 +00002037lldb_private::Error
2038GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2039{
2040 Error error(GetWatchpointSupportInfo(num));
2041 if (error.Success())
2042 error = GetWatchpointsTriggerAfterInstruction(after);
2043 return error;
2044}
2045
2046lldb_private::Error
2047GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
2048{
2049 Error error;
2050
2051 // we assume watchpoints will happen after running the relevant opcode
2052 // and we only want to override this behavior if we have explicitly
2053 // received a qHostInfo telling us otherwise
2054 if (m_qHostInfo_is_valid != eLazyBoolYes)
2055 after = true;
2056 else
2057 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
2058 return error;
2059}
2060
Greg Clayton576d8832011-03-22 04:00:09 +00002061int
2062GDBRemoteCommunicationClient::SetSTDIN (char const *path)
2063{
2064 if (path && path[0])
2065 {
2066 StreamString packet;
2067 packet.PutCString("QSetSTDIN:");
2068 packet.PutBytesAsRawHex8(path, strlen(path));
2069
2070 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002071 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002072 {
2073 if (response.IsOKResponse())
2074 return 0;
2075 uint8_t error = response.GetError();
2076 if (error)
2077 return error;
2078 }
2079 }
2080 return -1;
2081}
2082
2083int
2084GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
2085{
2086 if (path && path[0])
2087 {
2088 StreamString packet;
2089 packet.PutCString("QSetSTDOUT:");
2090 packet.PutBytesAsRawHex8(path, strlen(path));
2091
2092 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002093 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002094 {
2095 if (response.IsOKResponse())
2096 return 0;
2097 uint8_t error = response.GetError();
2098 if (error)
2099 return error;
2100 }
2101 }
2102 return -1;
2103}
2104
2105int
2106GDBRemoteCommunicationClient::SetSTDERR (char const *path)
2107{
2108 if (path && path[0])
2109 {
2110 StreamString packet;
2111 packet.PutCString("QSetSTDERR:");
2112 packet.PutBytesAsRawHex8(path, strlen(path));
2113
2114 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002115 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002116 {
2117 if (response.IsOKResponse())
2118 return 0;
2119 uint8_t error = response.GetError();
2120 if (error)
2121 return error;
2122 }
2123 }
2124 return -1;
2125}
2126
Greg Claytonfbb76342013-11-20 21:07:01 +00002127bool
2128GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd)
2129{
2130 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002131 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002132 {
2133 if (response.IsUnsupportedResponse())
2134 return false;
2135 if (response.IsErrorResponse())
2136 return false;
2137 response.GetHexByteString (cwd);
2138 return !cwd.empty();
2139 }
2140 return false;
2141}
2142
Greg Clayton576d8832011-03-22 04:00:09 +00002143int
2144GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
2145{
2146 if (path && path[0])
2147 {
2148 StreamString packet;
2149 packet.PutCString("QSetWorkingDir:");
2150 packet.PutBytesAsRawHex8(path, strlen(path));
2151
2152 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002153 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002154 {
2155 if (response.IsOKResponse())
2156 return 0;
2157 uint8_t error = response.GetError();
2158 if (error)
2159 return error;
2160 }
2161 }
2162 return -1;
2163}
2164
2165int
2166GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2167{
Greg Clayton32e0a752011-03-30 18:16:51 +00002168 char packet[32];
2169 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002170 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002171 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002172 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002173 {
2174 if (response.IsOKResponse())
2175 return 0;
2176 uint8_t error = response.GetError();
2177 if (error)
2178 return error;
2179 }
2180 return -1;
2181}
Greg Clayton32e0a752011-03-30 18:16:51 +00002182
2183bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002184GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002185{
2186 if (response.IsNormalResponse())
2187 {
2188 std::string name;
2189 std::string value;
2190 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002191
2192 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2193 uint32_t sub = 0;
2194 std::string vendor;
2195 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002196
2197 while (response.GetNameColonValue(name, value))
2198 {
2199 if (name.compare("pid") == 0)
2200 {
2201 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2202 }
2203 else if (name.compare("ppid") == 0)
2204 {
2205 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2206 }
2207 else if (name.compare("uid") == 0)
2208 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002209 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002210 }
2211 else if (name.compare("euid") == 0)
2212 {
2213 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2214 }
2215 else if (name.compare("gid") == 0)
2216 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002217 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002218 }
2219 else if (name.compare("egid") == 0)
2220 {
2221 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2222 }
2223 else if (name.compare("triple") == 0)
2224 {
2225 // The triple comes as ASCII hex bytes since it contains '-' chars
2226 extractor.GetStringRef().swap(value);
2227 extractor.SetFilePos(0);
2228 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002229 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002230 }
2231 else if (name.compare("name") == 0)
2232 {
2233 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002234 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002235 // control the characters in a process name
2236 extractor.GetStringRef().swap(value);
2237 extractor.SetFilePos(0);
2238 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002239 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002240 }
Jason Molenda89c37492014-01-27 22:23:20 +00002241 else if (name.compare("cputype") == 0)
2242 {
2243 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2244 }
2245 else if (name.compare("cpusubtype") == 0)
2246 {
2247 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2248 }
2249 else if (name.compare("vendor") == 0)
2250 {
2251 vendor = value;
2252 }
2253 else if (name.compare("ostype") == 0)
2254 {
2255 os_type = value;
2256 }
2257 }
2258
2259 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2260 {
2261 if (vendor == "apple")
2262 {
2263 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2264 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2265 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2266 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002267 }
2268
2269 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2270 return true;
2271 }
2272 return false;
2273}
2274
2275bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002276GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002277{
2278 process_info.Clear();
2279
2280 if (m_supports_qProcessInfoPID)
2281 {
2282 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002283 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002284 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002285 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002286 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002287 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002288 return DecodeProcessInfoResponse (response, process_info);
2289 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002290 else
2291 {
2292 m_supports_qProcessInfoPID = false;
2293 return false;
2294 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002295 }
2296 return false;
2297}
2298
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002299bool
2300GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
2301{
2302 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2303 return true;
2304 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2305 return false;
2306
2307 GetHostInfo ();
2308
2309 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002310 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002311 {
2312 if (response.IsNormalResponse())
2313 {
2314 std::string name;
2315 std::string value;
2316 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2317 uint32_t sub = 0;
2318 std::string arch_name;
2319 std::string os_name;
2320 std::string vendor_name;
2321 std::string triple;
2322 uint32_t pointer_byte_size = 0;
2323 StringExtractor extractor;
2324 ByteOrder byte_order = eByteOrderInvalid;
2325 uint32_t num_keys_decoded = 0;
2326 while (response.GetNameColonValue(name, value))
2327 {
2328 if (name.compare("cputype") == 0)
2329 {
2330 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2331 if (cpu != LLDB_INVALID_CPUTYPE)
2332 ++num_keys_decoded;
2333 }
2334 else if (name.compare("cpusubtype") == 0)
2335 {
2336 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2337 if (sub != 0)
2338 ++num_keys_decoded;
2339 }
2340 else if (name.compare("ostype") == 0)
2341 {
2342 os_name.swap (value);
2343 ++num_keys_decoded;
2344 }
2345 else if (name.compare("vendor") == 0)
2346 {
2347 vendor_name.swap(value);
2348 ++num_keys_decoded;
2349 }
2350 else if (name.compare("endian") == 0)
2351 {
2352 ++num_keys_decoded;
2353 if (value.compare("little") == 0)
2354 byte_order = eByteOrderLittle;
2355 else if (value.compare("big") == 0)
2356 byte_order = eByteOrderBig;
2357 else if (value.compare("pdp") == 0)
2358 byte_order = eByteOrderPDP;
2359 else
2360 --num_keys_decoded;
2361 }
2362 else if (name.compare("ptrsize") == 0)
2363 {
2364 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
2365 if (pointer_byte_size != 0)
2366 ++num_keys_decoded;
2367 }
2368 }
2369 if (num_keys_decoded > 0)
2370 m_qProcessInfo_is_valid = eLazyBoolYes;
2371 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
2372 {
2373 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2374 if (pointer_byte_size)
2375 {
2376 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2377 }
2378 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2379 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2380 return true;
2381 }
2382 }
2383 }
2384 else
2385 {
2386 m_qProcessInfo_is_valid = eLazyBoolNo;
2387 }
2388
2389 return false;
2390}
2391
2392
Greg Clayton32e0a752011-03-30 18:16:51 +00002393uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002394GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2395 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002396{
2397 process_infos.Clear();
2398
2399 if (m_supports_qfProcessInfo)
2400 {
2401 StreamString packet;
2402 packet.PutCString ("qfProcessInfo");
2403 if (!match_info.MatchAllProcesses())
2404 {
2405 packet.PutChar (':');
2406 const char *name = match_info.GetProcessInfo().GetName();
2407 bool has_name_match = false;
2408 if (name && name[0])
2409 {
2410 has_name_match = true;
2411 NameMatchType name_match_type = match_info.GetNameMatchType();
2412 switch (name_match_type)
2413 {
2414 case eNameMatchIgnore:
2415 has_name_match = false;
2416 break;
2417
2418 case eNameMatchEquals:
2419 packet.PutCString ("name_match:equals;");
2420 break;
2421
2422 case eNameMatchContains:
2423 packet.PutCString ("name_match:contains;");
2424 break;
2425
2426 case eNameMatchStartsWith:
2427 packet.PutCString ("name_match:starts_with;");
2428 break;
2429
2430 case eNameMatchEndsWith:
2431 packet.PutCString ("name_match:ends_with;");
2432 break;
2433
2434 case eNameMatchRegularExpression:
2435 packet.PutCString ("name_match:regex;");
2436 break;
2437 }
2438 if (has_name_match)
2439 {
2440 packet.PutCString ("name:");
2441 packet.PutBytesAsRawHex8(name, ::strlen(name));
2442 packet.PutChar (';');
2443 }
2444 }
2445
2446 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002447 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002448 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002449 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002450 if (match_info.GetProcessInfo().UserIDIsValid())
2451 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2452 if (match_info.GetProcessInfo().GroupIDIsValid())
2453 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002454 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2455 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2456 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2457 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2458 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2459 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2460 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2461 {
2462 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2463 const llvm::Triple &triple = match_arch.GetTriple();
2464 packet.PutCString("triple:");
2465 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
2466 packet.PutChar (';');
2467 }
2468 }
2469 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002470 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002471 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002472 do
2473 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002474 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002475 if (!DecodeProcessInfoResponse (response, process_info))
2476 break;
2477 process_infos.Append(process_info);
2478 response.GetStringRef().clear();
2479 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00002480 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00002481 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002482 else
2483 {
2484 m_supports_qfProcessInfo = false;
2485 return 0;
2486 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002487 }
2488 return process_infos.GetSize();
2489
2490}
2491
2492bool
2493GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2494{
2495 if (m_supports_qUserName)
2496 {
2497 char packet[32];
2498 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002499 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002500 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002501 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002502 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002503 if (response.IsNormalResponse())
2504 {
2505 // Make sure we parsed the right number of characters. The response is
2506 // the hex encoded user name and should make up the entire packet.
2507 // If there are any non-hex ASCII bytes, the length won't match below..
2508 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2509 return true;
2510 }
2511 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002512 else
2513 {
2514 m_supports_qUserName = false;
2515 return false;
2516 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002517 }
2518 return false;
2519
2520}
2521
2522bool
2523GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2524{
2525 if (m_supports_qGroupName)
2526 {
2527 char packet[32];
2528 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002529 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002530 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002531 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002532 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002533 if (response.IsNormalResponse())
2534 {
2535 // Make sure we parsed the right number of characters. The response is
2536 // the hex encoded group name and should make up the entire packet.
2537 // If there are any non-hex ASCII bytes, the length won't match below..
2538 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2539 return true;
2540 }
2541 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002542 else
2543 {
2544 m_supports_qGroupName = false;
2545 return false;
2546 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002547 }
2548 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002549}
Greg Clayton32e0a752011-03-30 18:16:51 +00002550
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002551void
2552GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2553{
2554 uint32_t i;
2555 TimeValue start_time, end_time;
2556 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002557 if (SendSpeedTestPacket (0, 0))
2558 {
Greg Clayton700e5082014-02-21 19:11:28 +00002559 static uint32_t g_send_sizes[] = { 0, 64, 128, 512, 1024 };
2560 static uint32_t g_recv_sizes[] = { 0, 64, 128, 512, 1024 }; //, 4*1024, 8*1024, 16*1024, 32*1024, 48*1024, 64*1024, 96*1024, 128*1024 };
2561 const size_t k_num_send_sizes = sizeof(g_send_sizes)/sizeof(uint32_t);
2562 const size_t k_num_recv_sizes = sizeof(g_recv_sizes)/sizeof(uint32_t);
2563 const uint64_t k_recv_amount = 4*1024*1024; // Receive 4MB
2564 for (uint32_t send_idx = 0; send_idx < k_num_send_sizes; ++send_idx)
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002565 {
Greg Clayton700e5082014-02-21 19:11:28 +00002566 const uint32_t send_size = g_send_sizes[send_idx];
2567 for (uint32_t recv_idx = 0; recv_idx < k_num_recv_sizes; ++recv_idx)
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002568 {
Greg Clayton700e5082014-02-21 19:11:28 +00002569 const uint32_t recv_size = g_recv_sizes[recv_idx];
2570 StreamString packet;
2571 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2572 uint32_t bytes_left = send_size;
2573 while (bytes_left > 0)
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002574 {
Greg Clayton700e5082014-02-21 19:11:28 +00002575 if (bytes_left >= 26)
2576 {
2577 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2578 bytes_left -= 26;
2579 }
2580 else
2581 {
2582 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2583 bytes_left = 0;
2584 }
2585 }
2586
2587 start_time = TimeValue::Now();
2588 if (recv_size == 0)
2589 {
2590 for (i=0; i<num_packets; ++i)
2591 {
2592 StringExtractorGDBRemote response;
2593 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2594 }
2595 }
2596 else
2597 {
2598 uint32_t bytes_read = 0;
2599 while (bytes_read < k_recv_amount)
2600 {
2601 StringExtractorGDBRemote response;
2602 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2603 bytes_read += recv_size;
2604 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002605 }
2606 end_time = TimeValue::Now();
2607 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002608 if (recv_size == 0)
Greg Clayton700e5082014-02-21 19:11:28 +00002609 {
2610 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2611 printf ("%u qSpeedTest(send=%-7u, recv=%-7u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
2612 num_packets,
2613 send_size,
2614 recv_size,
2615 total_time_nsec / TimeValue::NanoSecPerSec,
2616 total_time_nsec % TimeValue::NanoSecPerSec,
2617 packets_per_second);
2618 }
2619 else
2620 {
2621 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2622 printf ("%u qSpeedTest(send=%-7u, recv=%-7u) sent 4MB in %" PRIu64 ".%9.9" PRIu64 " sec for %f MB/sec.\n",
2623 num_packets,
2624 send_size,
2625 recv_size,
2626 total_time_nsec / TimeValue::NanoSecPerSec,
2627 total_time_nsec % TimeValue::NanoSecPerSec,
2628 mb_second);
2629 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002630 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002631 }
2632 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002633}
2634
2635bool
2636GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2637{
2638 StreamString packet;
2639 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2640 uint32_t bytes_left = send_size;
2641 while (bytes_left > 0)
2642 {
2643 if (bytes_left >= 26)
2644 {
2645 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2646 bytes_left -= 26;
2647 }
2648 else
2649 {
2650 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2651 bytes_left = 0;
2652 }
2653 }
2654
2655 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002656 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00002657}
Greg Clayton8b82f082011-04-12 05:54:46 +00002658
2659uint16_t
Greg Claytondbf04572013-12-04 19:40:33 +00002660GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
Greg Clayton8b82f082011-04-12 05:54:46 +00002661{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002662 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00002663 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002664 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00002665 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002666 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00002667 if (remote_accept_hostname && remote_accept_hostname[0])
2668 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002669 else
2670 {
Greg Claytondbf04572013-12-04 19:40:33 +00002671 if (Host::GetHostname (hostname))
2672 {
2673 // Make the GDB server we launch only accept connections from this host
2674 stream.Printf("host:%s;", hostname.c_str());
2675 }
2676 else
2677 {
2678 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2679 stream.Printf("host:*;");
2680 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002681 }
2682 const char *packet = stream.GetData();
2683 int packet_len = stream.GetSize();
2684
Greg Clayton3dedae12013-12-06 21:45:27 +00002685 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002686 {
2687 std::string name;
2688 std::string value;
2689 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002690 while (response.GetNameColonValue(name, value))
2691 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00002692 if (name.compare("port") == 0)
Greg Clayton8b82f082011-04-12 05:54:46 +00002693 port = Args::StringToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002694 else if (name.compare("pid") == 0)
2695 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00002696 }
2697 return port;
2698 }
2699 return 0;
2700}
2701
2702bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00002703GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2704{
2705 StreamString stream;
2706 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2707 const char *packet = stream.GetData();
2708 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00002709
Daniel Maleae0f8f572013-08-26 23:57:52 +00002710 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002711 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002712 {
2713 if (response.IsOKResponse())
2714 return true;
2715 }
2716 return false;
2717}
2718
2719bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002720GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002721{
2722 if (m_curr_tid == tid)
2723 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002724
Greg Clayton8b82f082011-04-12 05:54:46 +00002725 char packet[32];
2726 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002727 if (tid == UINT64_MAX)
2728 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002729 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002730 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002731 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002732 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002733 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002734 {
2735 if (response.IsOKResponse())
2736 {
2737 m_curr_tid = tid;
2738 return true;
2739 }
2740 }
2741 return false;
2742}
2743
2744bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002745GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002746{
2747 if (m_curr_tid_run == tid)
2748 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002749
Greg Clayton8b82f082011-04-12 05:54:46 +00002750 char packet[32];
2751 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002752 if (tid == UINT64_MAX)
2753 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002754 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002755 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2756
Andy Gibbsa297a972013-06-19 19:04:53 +00002757 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002758 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002759 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002760 {
2761 if (response.IsOKResponse())
2762 {
2763 m_curr_tid_run = tid;
2764 return true;
2765 }
2766 }
2767 return false;
2768}
2769
2770bool
2771GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2772{
Greg Clayton3dedae12013-12-06 21:45:27 +00002773 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002774 return response.IsNormalResponse();
2775 return false;
2776}
2777
2778bool
Greg Claytonf402f782012-10-13 02:11:55 +00002779GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00002780{
2781 if (m_supports_qThreadStopInfo)
2782 {
2783 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00002784 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002785 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002786 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002787 {
Greg Claytonef8180a2013-10-15 00:14:28 +00002788 if (response.IsUnsupportedResponse())
2789 m_supports_qThreadStopInfo = false;
2790 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002791 return true;
2792 else
2793 return false;
2794 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002795 else
2796 {
2797 m_supports_qThreadStopInfo = false;
2798 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002799 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002800 return false;
2801}
2802
2803
2804uint8_t
2805GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2806{
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002807 // Check if the stub is known not to support this breakpoint type
2808 if (!SupportsGDBStoppointPacket(type))
2809 return UINT8_MAX;
2810 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00002811 char packet[64];
2812 const int packet_len = ::snprintf (packet,
2813 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00002814 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00002815 insert ? 'Z' : 'z',
2816 type,
2817 addr,
2818 length);
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002819 // Check we havent overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00002820 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002821 StringExtractorGDBRemote response;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002822 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00002823 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002824 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002825 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00002826 if (response.IsOKResponse())
2827 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002828
2829 // Error while setting breakpoint, send back specific error
2830 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002831 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002832
2833 // Empty packet informs us that breakpoint is not supported
2834 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00002835 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002836 // Disable this breakpoint type since it is unsupported
2837 switch (type)
2838 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00002839 case eBreakpointSoftware: m_supports_z0 = false; break;
2840 case eBreakpointHardware: m_supports_z1 = false; break;
2841 case eWatchpointWrite: m_supports_z2 = false; break;
2842 case eWatchpointRead: m_supports_z3 = false; break;
2843 case eWatchpointReadWrite: m_supports_z4 = false; break;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002844 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002845 }
2846 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002847 // Signal generic faliure
Greg Clayton8b82f082011-04-12 05:54:46 +00002848 return UINT8_MAX;
2849}
Greg Claytonadc00cb2011-05-20 23:38:13 +00002850
2851size_t
2852GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2853 bool &sequence_mutex_unavailable)
2854{
2855 Mutex::Locker locker;
2856 thread_ids.clear();
2857
Jim Ingham4ceb9282012-06-08 22:50:40 +00002858 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002859 {
2860 sequence_mutex_unavailable = false;
2861 StringExtractorGDBRemote response;
2862
Greg Clayton3dedae12013-12-06 21:45:27 +00002863 PacketResult packet_result;
2864 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
2865 packet_result == PacketResult::Success && response.IsNormalResponse();
2866 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002867 {
2868 char ch = response.GetChar();
2869 if (ch == 'l')
2870 break;
2871 if (ch == 'm')
2872 {
2873 do
2874 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00002875 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00002876
2877 if (tid != LLDB_INVALID_THREAD_ID)
2878 {
2879 thread_ids.push_back (tid);
2880 }
2881 ch = response.GetChar(); // Skip the command separator
2882 } while (ch == ','); // Make sure we got a comma separator
2883 }
2884 }
2885 }
2886 else
2887 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00002888#if defined (LLDB_CONFIGURATION_DEBUG)
2889 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2890#else
Greg Clayton5160ce52013-03-27 23:08:40 +00002891 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00002892 if (log)
2893 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00002894#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00002895 sequence_mutex_unavailable = true;
2896 }
2897 return thread_ids.size();
2898}
Greg Clayton37a0a242012-04-11 00:24:49 +00002899
2900lldb::addr_t
2901GDBRemoteCommunicationClient::GetShlibInfoAddr()
2902{
2903 if (!IsRunning())
2904 {
2905 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002906 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00002907 {
2908 if (response.IsNormalResponse())
2909 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2910 }
2911 }
2912 return LLDB_INVALID_ADDRESS;
2913}
2914
Daniel Maleae0f8f572013-08-26 23:57:52 +00002915lldb_private::Error
2916GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL
2917 const char *working_dir, // Pass NULL to use the current working directory
2918 int *status_ptr, // Pass NULL if you don't want the process exit status
2919 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
2920 std::string *command_output, // Pass NULL if you don't want the command output
2921 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
2922{
2923 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00002924 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002925 stream.PutBytesAsRawHex8(command, strlen(command));
2926 stream.PutChar(',');
2927 stream.PutHex32(timeout_sec);
2928 if (working_dir && *working_dir)
2929 {
2930 stream.PutChar(',');
2931 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
2932 }
2933 const char *packet = stream.GetData();
2934 int packet_len = stream.GetSize();
2935 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002936 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002937 {
2938 if (response.GetChar() != 'F')
2939 return Error("malformed reply");
2940 if (response.GetChar() != ',')
2941 return Error("malformed reply");
2942 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2943 if (exitcode == UINT32_MAX)
2944 return Error("unable to run remote process");
2945 else if (status_ptr)
2946 *status_ptr = exitcode;
2947 if (response.GetChar() != ',')
2948 return Error("malformed reply");
2949 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2950 if (signo_ptr)
2951 *signo_ptr = signo;
2952 if (response.GetChar() != ',')
2953 return Error("malformed reply");
2954 std::string output;
2955 response.GetEscapedBinaryData(output);
2956 if (command_output)
2957 command_output->assign(output);
2958 return Error();
2959 }
2960 return Error("unable to send packet");
2961}
2962
Greg Claytonfbb76342013-11-20 21:07:01 +00002963Error
2964GDBRemoteCommunicationClient::MakeDirectory (const char *path,
2965 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002966{
2967 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00002968 stream.PutCString("qPlatform_mkdir:");
2969 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002970 stream.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00002971 stream.PutBytesAsRawHex8(path, strlen(path));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002972 const char *packet = stream.GetData();
2973 int packet_len = stream.GetSize();
2974 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002975 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002976 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002977 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002978 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002979 return Error();
Daniel Maleae0f8f572013-08-26 23:57:52 +00002980
2981}
2982
Greg Claytonfbb76342013-11-20 21:07:01 +00002983Error
2984GDBRemoteCommunicationClient::SetFilePermissions (const char *path,
2985 uint32_t file_permissions)
2986{
2987 lldb_private::StreamString stream;
2988 stream.PutCString("qPlatform_chmod:");
2989 stream.PutHex32(file_permissions);
2990 stream.PutChar(',');
2991 stream.PutBytesAsRawHex8(path, strlen(path));
2992 const char *packet = stream.GetData();
2993 int packet_len = stream.GetSize();
2994 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002995 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002996 {
2997 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
2998 }
2999 return Error();
3000
3001}
3002
Daniel Maleae0f8f572013-08-26 23:57:52 +00003003static uint64_t
3004ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3005 uint64_t fail_result,
3006 Error &error)
3007{
3008 response.SetFilePos(0);
3009 if (response.GetChar() != 'F')
3010 return fail_result;
3011 int32_t result = response.GetS32 (-2);
3012 if (result == -2)
3013 return fail_result;
3014 if (response.GetChar() == ',')
3015 {
3016 int result_errno = response.GetS32 (-2);
3017 if (result_errno != -2)
3018 error.SetError(result_errno, eErrorTypePOSIX);
3019 else
3020 error.SetError(-1, eErrorTypeGeneric);
3021 }
3022 else
3023 error.Clear();
3024 return result;
3025}
3026lldb::user_id_t
3027GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3028 uint32_t flags,
3029 mode_t mode,
3030 Error &error)
3031{
3032 lldb_private::StreamString stream;
3033 stream.PutCString("vFile:open:");
3034 std::string path (file_spec.GetPath());
3035 if (path.empty())
3036 return UINT64_MAX;
3037 stream.PutCStringAsRawHex8(path.c_str());
3038 stream.PutChar(',');
3039 const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags);
3040 stream.PutHex32(posix_open_flags);
3041 stream.PutChar(',');
3042 stream.PutHex32(mode);
3043 const char* packet = stream.GetData();
3044 int packet_len = stream.GetSize();
3045 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003046 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003047 {
3048 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3049 }
3050 return UINT64_MAX;
3051}
3052
3053bool
3054GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3055 Error &error)
3056{
3057 lldb_private::StreamString stream;
3058 stream.Printf("vFile:close:%i", (int)fd);
3059 const char* packet = stream.GetData();
3060 int packet_len = stream.GetSize();
3061 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003062 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003063 {
3064 return ParseHostIOPacketResponse (response, -1, error) == 0;
3065 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003066 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003067}
3068
3069// Extension of host I/O packets to get the file size.
3070lldb::user_id_t
3071GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3072{
3073 lldb_private::StreamString stream;
3074 stream.PutCString("vFile:size:");
3075 std::string path (file_spec.GetPath());
3076 stream.PutCStringAsRawHex8(path.c_str());
3077 const char* packet = stream.GetData();
3078 int packet_len = stream.GetSize();
3079 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003080 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003081 {
3082 if (response.GetChar() != 'F')
3083 return UINT64_MAX;
3084 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3085 return retcode;
3086 }
3087 return UINT64_MAX;
3088}
3089
Greg Claytonfbb76342013-11-20 21:07:01 +00003090Error
3091GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003092{
Greg Claytonfbb76342013-11-20 21:07:01 +00003093 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003094 lldb_private::StreamString stream;
3095 stream.PutCString("vFile:mode:");
Greg Claytonfbb76342013-11-20 21:07:01 +00003096 stream.PutCStringAsRawHex8(path);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003097 const char* packet = stream.GetData();
3098 int packet_len = stream.GetSize();
3099 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003100 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003101 {
3102 if (response.GetChar() != 'F')
3103 {
3104 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003105 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003106 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003107 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003108 const uint32_t mode = response.GetS32(-1);
3109 if (mode == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003110 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003111 if (response.GetChar() == ',')
3112 {
3113 int response_errno = response.GetS32(-1);
3114 if (response_errno > 0)
3115 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3116 else
3117 error.SetErrorToGenericError();
3118 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003119 else
3120 error.SetErrorToGenericError();
3121 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003122 else
3123 {
3124 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3125 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003126 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003127 }
3128 else
3129 {
3130 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3131 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003132 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003133}
3134
3135uint64_t
3136GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3137 uint64_t offset,
3138 void *dst,
3139 uint64_t dst_len,
3140 Error &error)
3141{
3142 lldb_private::StreamString stream;
3143 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3144 const char* packet = stream.GetData();
3145 int packet_len = stream.GetSize();
3146 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003147 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003148 {
3149 if (response.GetChar() != 'F')
3150 return 0;
3151 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3152 if (retcode == UINT32_MAX)
3153 return retcode;
3154 const char next = (response.Peek() ? *response.Peek() : 0);
3155 if (next == ',')
3156 return 0;
3157 if (next == ';')
3158 {
3159 response.GetChar(); // skip the semicolon
3160 std::string buffer;
3161 if (response.GetEscapedBinaryData(buffer))
3162 {
3163 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3164 if (data_to_write > 0)
3165 memcpy(dst, &buffer[0], data_to_write);
3166 return data_to_write;
3167 }
3168 }
3169 }
3170 return 0;
3171}
3172
3173uint64_t
3174GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3175 uint64_t offset,
3176 const void* src,
3177 uint64_t src_len,
3178 Error &error)
3179{
3180 lldb_private::StreamGDBRemote stream;
3181 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3182 stream.PutEscapedBytes(src, src_len);
3183 const char* packet = stream.GetData();
3184 int packet_len = stream.GetSize();
3185 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003186 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003187 {
3188 if (response.GetChar() != 'F')
3189 {
3190 error.SetErrorStringWithFormat("write file failed");
3191 return 0;
3192 }
3193 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3194 if (bytes_written == UINT64_MAX)
3195 {
3196 error.SetErrorToGenericError();
3197 if (response.GetChar() == ',')
3198 {
3199 int response_errno = response.GetS32(-1);
3200 if (response_errno > 0)
3201 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3202 }
3203 return 0;
3204 }
3205 return bytes_written;
3206 }
3207 else
3208 {
3209 error.SetErrorString ("failed to send vFile:pwrite packet");
3210 }
3211 return 0;
3212}
3213
Greg Claytonfbb76342013-11-20 21:07:01 +00003214Error
3215GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst)
3216{
3217 Error error;
3218 lldb_private::StreamGDBRemote stream;
3219 stream.PutCString("vFile:symlink:");
3220 // the unix symlink() command reverses its parameters where the dst if first,
3221 // so we follow suit here
3222 stream.PutCStringAsRawHex8(dst);
3223 stream.PutChar(',');
3224 stream.PutCStringAsRawHex8(src);
3225 const char* packet = stream.GetData();
3226 int packet_len = stream.GetSize();
3227 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003228 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003229 {
3230 if (response.GetChar() == 'F')
3231 {
3232 uint32_t result = response.GetU32(UINT32_MAX);
3233 if (result != 0)
3234 {
3235 error.SetErrorToGenericError();
3236 if (response.GetChar() == ',')
3237 {
3238 int response_errno = response.GetS32(-1);
3239 if (response_errno > 0)
3240 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3241 }
3242 }
3243 }
3244 else
3245 {
3246 // Should have returned with 'F<result>[,<errno>]'
3247 error.SetErrorStringWithFormat("symlink failed");
3248 }
3249 }
3250 else
3251 {
3252 error.SetErrorString ("failed to send vFile:symlink packet");
3253 }
3254 return error;
3255}
3256
3257Error
3258GDBRemoteCommunicationClient::Unlink (const char *path)
3259{
3260 Error error;
3261 lldb_private::StreamGDBRemote stream;
3262 stream.PutCString("vFile:unlink:");
3263 // the unix symlink() command reverses its parameters where the dst if first,
3264 // so we follow suit here
3265 stream.PutCStringAsRawHex8(path);
3266 const char* packet = stream.GetData();
3267 int packet_len = stream.GetSize();
3268 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003269 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003270 {
3271 if (response.GetChar() == 'F')
3272 {
3273 uint32_t result = response.GetU32(UINT32_MAX);
3274 if (result != 0)
3275 {
3276 error.SetErrorToGenericError();
3277 if (response.GetChar() == ',')
3278 {
3279 int response_errno = response.GetS32(-1);
3280 if (response_errno > 0)
3281 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3282 }
3283 }
3284 }
3285 else
3286 {
3287 // Should have returned with 'F<result>[,<errno>]'
3288 error.SetErrorStringWithFormat("unlink failed");
3289 }
3290 }
3291 else
3292 {
3293 error.SetErrorString ("failed to send vFile:unlink packet");
3294 }
3295 return error;
3296}
3297
Daniel Maleae0f8f572013-08-26 23:57:52 +00003298// Extension of host I/O packets to get whether a file exists.
3299bool
3300GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3301{
3302 lldb_private::StreamString stream;
3303 stream.PutCString("vFile:exists:");
3304 std::string path (file_spec.GetPath());
3305 stream.PutCStringAsRawHex8(path.c_str());
3306 const char* packet = stream.GetData();
3307 int packet_len = stream.GetSize();
3308 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003309 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003310 {
3311 if (response.GetChar() != 'F')
3312 return false;
3313 if (response.GetChar() != ',')
3314 return false;
3315 bool retcode = (response.GetChar() != '0');
3316 return retcode;
3317 }
3318 return false;
3319}
3320
3321bool
3322GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3323 uint64_t &high,
3324 uint64_t &low)
3325{
3326 lldb_private::StreamString stream;
3327 stream.PutCString("vFile:MD5:");
3328 std::string path (file_spec.GetPath());
3329 stream.PutCStringAsRawHex8(path.c_str());
3330 const char* packet = stream.GetData();
3331 int packet_len = stream.GetSize();
3332 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003333 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003334 {
3335 if (response.GetChar() != 'F')
3336 return false;
3337 if (response.GetChar() != ',')
3338 return false;
3339 if (response.Peek() && *response.Peek() == 'x')
3340 return false;
3341 low = response.GetHexMaxU64(false, UINT64_MAX);
3342 high = response.GetHexMaxU64(false, UINT64_MAX);
3343 return true;
3344 }
3345 return false;
3346}
Greg Claytonf74cf862013-11-13 23:28:31 +00003347
3348bool
Jason Molendaa3329782014-03-29 18:54:20 +00003349GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3350{
3351 // Some targets have issues with g/G packets and we need to avoid using them
3352 if (m_avoid_g_packets == eLazyBoolCalculate)
3353 {
3354 if (process)
3355 {
3356 m_avoid_g_packets = eLazyBoolNo;
3357 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3358 if (arch.IsValid()
3359 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3360 && arch.GetTriple().getOS() == llvm::Triple::IOS
3361 && arch.GetTriple().getArch() == llvm::Triple::arm64)
3362 {
3363 m_avoid_g_packets = eLazyBoolYes;
3364 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3365 if (gdb_server_version != 0)
3366 {
3367 const char *gdb_server_name = GetGDBServerProgramName();
3368 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3369 {
3370 if (gdb_server_version >= 310)
3371 m_avoid_g_packets = eLazyBoolNo;
3372 }
3373 }
3374 }
3375 }
3376 }
3377 return m_avoid_g_packets == eLazyBoolYes;
3378}
3379
3380bool
Greg Claytonf74cf862013-11-13 23:28:31 +00003381GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3382{
3383 Mutex::Locker locker;
3384 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
3385 {
3386 const bool thread_suffix_supported = GetThreadSuffixSupported();
3387
3388 if (thread_suffix_supported || SetCurrentThread(tid))
3389 {
3390 char packet[64];
3391 int packet_len = 0;
3392 if (thread_suffix_supported)
3393 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
3394 else
3395 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3396 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003397 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003398 }
3399 }
3400 return false;
3401
3402}
3403
3404
3405bool
3406GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3407{
3408 Mutex::Locker locker;
3409 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3410 {
3411 const bool thread_suffix_supported = GetThreadSuffixSupported();
3412
3413 if (thread_suffix_supported || SetCurrentThread(tid))
3414 {
3415 char packet[64];
3416 int packet_len = 0;
3417 // Get all registers in one packet
3418 if (thread_suffix_supported)
3419 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3420 else
3421 packet_len = ::snprintf (packet, sizeof(packet), "g");
3422 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003423 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003424 }
3425 }
3426 return false;
3427}
3428bool
3429GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3430{
3431 save_id = 0; // Set to invalid save ID
3432 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3433 return false;
3434
3435 m_supports_QSaveRegisterState = eLazyBoolYes;
3436 Mutex::Locker locker;
3437 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3438 {
3439 const bool thread_suffix_supported = GetThreadSuffixSupported();
3440 if (thread_suffix_supported || SetCurrentThread(tid))
3441 {
3442 char packet[256];
3443 if (thread_suffix_supported)
3444 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3445 else
3446 ::strncpy (packet, "QSaveRegisterState", sizeof(packet));
3447
3448 StringExtractorGDBRemote response;
3449
Greg Clayton3dedae12013-12-06 21:45:27 +00003450 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003451 {
3452 if (response.IsUnsupportedResponse())
3453 {
3454 // This packet isn't supported, don't try calling it again
3455 m_supports_QSaveRegisterState = eLazyBoolNo;
3456 }
3457
3458 const uint32_t response_save_id = response.GetU32(0);
3459 if (response_save_id != 0)
3460 {
3461 save_id = response_save_id;
3462 return true;
3463 }
3464 }
3465 }
3466 }
3467 return false;
3468}
3469
3470bool
3471GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3472{
3473 // We use the "m_supports_QSaveRegisterState" variable here becuase the
3474 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3475 // order to be useful
3476 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3477 return false;
3478
3479 Mutex::Locker locker;
3480 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
3481 {
3482 const bool thread_suffix_supported = GetThreadSuffixSupported();
3483 if (thread_suffix_supported || SetCurrentThread(tid))
3484 {
3485 char packet[256];
3486 if (thread_suffix_supported)
3487 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3488 else
3489 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3490
3491 StringExtractorGDBRemote response;
3492
Greg Clayton3dedae12013-12-06 21:45:27 +00003493 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003494 {
3495 if (response.IsOKResponse())
3496 {
3497 return true;
3498 }
3499 else if (response.IsUnsupportedResponse())
3500 {
3501 // This packet isn't supported, don't try calling this packet or
3502 // QSaveRegisterState again...
3503 m_supports_QSaveRegisterState = eLazyBoolNo;
3504 }
3505 }
3506 }
3507 }
3508 return false;
3509}