blob: da2299a408c27f8b7ef0e77ee0b96d9e80f11738 [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"
30
31// Project includes
32#include "Utility/StringExtractorGDBRemote.h"
33#include "ProcessGDBRemote.h"
34#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000035#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000036
37using namespace lldb;
38using namespace lldb_private;
39
Virgile Bellob2f1fb22013-08-23 12:44:05 +000040#ifdef LLDB_DISABLE_POSIX
41#define SIGSTOP 17
42#endif
43
Greg Clayton576d8832011-03-22 04:00:09 +000044//----------------------------------------------------------------------
45// GDBRemoteCommunicationClient constructor
46//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +000047GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) :
48 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform),
Greg Clayton576d8832011-03-22 04:00:09 +000049 m_supports_not_sending_acks (eLazyBoolCalculate),
50 m_supports_thread_suffix (eLazyBoolCalculate),
Greg Clayton44633992012-04-10 03:22:03 +000051 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
Greg Clayton576d8832011-03-22 04:00:09 +000052 m_supports_vCont_all (eLazyBoolCalculate),
53 m_supports_vCont_any (eLazyBoolCalculate),
54 m_supports_vCont_c (eLazyBoolCalculate),
55 m_supports_vCont_C (eLazyBoolCalculate),
56 m_supports_vCont_s (eLazyBoolCalculate),
57 m_supports_vCont_S (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000058 m_qHostInfo_is_valid (eLazyBoolCalculate),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000059 m_qProcessInfo_is_valid (eLazyBoolCalculate),
Greg Clayton70b57652011-05-15 01:25:55 +000060 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
Greg Clayton46fb5582011-11-18 07:03:08 +000061 m_supports_memory_region_info (eLazyBoolCalculate),
Johnny Chen64637202012-05-23 21:09:52 +000062 m_supports_watchpoint_support_info (eLazyBoolCalculate),
Jim Inghamacff8952013-05-02 00:27:30 +000063 m_supports_detach_stay_stopped (eLazyBoolCalculate),
Enrico Granataf04a2192012-07-13 23:18:48 +000064 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
Jim Inghamcd16df92012-07-20 21:37:13 +000065 m_attach_or_wait_reply(eLazyBoolCalculate),
Jim Ingham279ceec2012-07-25 21:12:43 +000066 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
Eric Christopher2490f5c2013-08-30 17:50:57 +000067 m_supports_p (eLazyBoolCalculate),
Greg Claytonf74cf862013-11-13 23:28:31 +000068 m_supports_QSaveRegisterState (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000069 m_supports_qProcessInfoPID (true),
70 m_supports_qfProcessInfo (true),
71 m_supports_qUserName (true),
72 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000073 m_supports_qThreadStopInfo (true),
74 m_supports_z0 (true),
75 m_supports_z1 (true),
76 m_supports_z2 (true),
77 m_supports_z3 (true),
78 m_supports_z4 (true),
Greg Clayton89600582013-10-10 17:53:50 +000079 m_supports_QEnvironment (true),
80 m_supports_QEnvironmentHexEncoded (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000081 m_curr_tid (LLDB_INVALID_THREAD_ID),
82 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +000083 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +000084 m_async_mutex (Mutex::eMutexTypeRecursive),
85 m_async_packet_predicate (false),
86 m_async_packet (),
87 m_async_response (),
88 m_async_signal (-1),
Han Ming Ong4b6459f2013-01-18 23:11:53 +000089 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +000090 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000091 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +000092 m_os_version_major (UINT32_MAX),
93 m_os_version_minor (UINT32_MAX),
Greg Clayton9ac6d2d2013-10-25 18:13:17 +000094 m_os_version_update (UINT32_MAX),
95 m_os_build (),
96 m_os_kernel (),
97 m_hostname (),
98 m_default_packet_timeout (0)
Greg Clayton576d8832011-03-22 04:00:09 +000099{
Greg Clayton576d8832011-03-22 04:00:09 +0000100}
101
102//----------------------------------------------------------------------
103// Destructor
104//----------------------------------------------------------------------
105GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
106{
Greg Clayton576d8832011-03-22 04:00:09 +0000107 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000108 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000109}
110
111bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000112GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
113{
114 // Start the read thread after we send the handshake ack since if we
115 // fail to send the handshake ack, there is no reason to continue...
116 if (SendAck())
Greg Clayton73bf5db2011-06-17 01:22:15 +0000117 return true;
Greg Clayton1cb64962011-03-24 04:28:38 +0000118
119 if (error_ptr)
120 error_ptr->SetErrorString("failed to send the handshake ack");
121 return false;
122}
123
124void
125GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000126{
127 if (m_supports_not_sending_acks == eLazyBoolCalculate)
128 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000129 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000130 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000131
132 StringExtractorGDBRemote response;
Greg Clayton576d8832011-03-22 04:00:09 +0000133 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false))
134 {
135 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000136 {
137 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000138 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000139 }
Greg Clayton576d8832011-03-22 04:00:09 +0000140 }
141 }
Greg Clayton576d8832011-03-22 04:00:09 +0000142}
143
144void
Greg Clayton44633992012-04-10 03:22:03 +0000145GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
146{
147 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
148 {
149 m_supports_threads_in_stop_reply = eLazyBoolNo;
150
151 StringExtractorGDBRemote response;
152 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false))
153 {
154 if (response.IsOKResponse())
155 m_supports_threads_in_stop_reply = eLazyBoolYes;
156 }
157 }
158}
159
Jim Inghamcd16df92012-07-20 21:37:13 +0000160bool
161GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
162{
163 if (m_attach_or_wait_reply == eLazyBoolCalculate)
164 {
165 m_attach_or_wait_reply = eLazyBoolNo;
166
167 StringExtractorGDBRemote response;
168 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false))
169 {
170 if (response.IsOKResponse())
171 m_attach_or_wait_reply = eLazyBoolYes;
172 }
173 }
174 if (m_attach_or_wait_reply == eLazyBoolYes)
175 return true;
176 else
177 return false;
178}
179
Jim Ingham279ceec2012-07-25 21:12:43 +0000180bool
181GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
182{
183 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
184 {
185 m_prepare_for_reg_writing_reply = eLazyBoolNo;
186
187 StringExtractorGDBRemote response;
188 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false))
189 {
190 if (response.IsOKResponse())
191 m_prepare_for_reg_writing_reply = eLazyBoolYes;
192 }
193 }
194 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
195 return true;
196 else
197 return false;
198}
199
Greg Clayton44633992012-04-10 03:22:03 +0000200
201void
Greg Clayton576d8832011-03-22 04:00:09 +0000202GDBRemoteCommunicationClient::ResetDiscoverableSettings()
203{
204 m_supports_not_sending_acks = eLazyBoolCalculate;
205 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton44633992012-04-10 03:22:03 +0000206 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
Greg Clayton576d8832011-03-22 04:00:09 +0000207 m_supports_vCont_c = eLazyBoolCalculate;
208 m_supports_vCont_C = eLazyBoolCalculate;
209 m_supports_vCont_s = eLazyBoolCalculate;
210 m_supports_vCont_S = eLazyBoolCalculate;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000211 m_supports_p = eLazyBoolCalculate;
Greg Claytonf74cf862013-11-13 23:28:31 +0000212 m_supports_QSaveRegisterState = eLazyBoolCalculate;
Greg Clayton32e0a752011-03-30 18:16:51 +0000213 m_qHostInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000214 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Greg Clayton70b57652011-05-15 01:25:55 +0000215 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton46fb5582011-11-18 07:03:08 +0000216 m_supports_memory_region_info = eLazyBoolCalculate;
Jim Ingham279ceec2012-07-25 21:12:43 +0000217 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
218 m_attach_or_wait_reply = eLazyBoolCalculate;
Greg Clayton2a48f522011-05-14 01:50:35 +0000219
Greg Clayton32e0a752011-03-30 18:16:51 +0000220 m_supports_qProcessInfoPID = true;
221 m_supports_qfProcessInfo = true;
222 m_supports_qUserName = true;
223 m_supports_qGroupName = true;
Greg Clayton8b82f082011-04-12 05:54:46 +0000224 m_supports_qThreadStopInfo = true;
225 m_supports_z0 = true;
226 m_supports_z1 = true;
227 m_supports_z2 = true;
228 m_supports_z3 = true;
229 m_supports_z4 = true;
Greg Clayton89600582013-10-10 17:53:50 +0000230 m_supports_QEnvironment = true;
231 m_supports_QEnvironmentHexEncoded = true;
Greg Claytond314e812011-03-23 00:09:55 +0000232 m_host_arch.Clear();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000233 m_process_arch.Clear();
Greg Clayton576d8832011-03-22 04:00:09 +0000234}
235
236
237bool
238GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
239{
240 if (m_supports_thread_suffix == eLazyBoolCalculate)
241 {
242 StringExtractorGDBRemote response;
243 m_supports_thread_suffix = eLazyBoolNo;
244 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false))
245 {
246 if (response.IsOKResponse())
247 m_supports_thread_suffix = eLazyBoolYes;
248 }
249 }
250 return m_supports_thread_suffix;
251}
252bool
253GDBRemoteCommunicationClient::GetVContSupported (char flavor)
254{
255 if (m_supports_vCont_c == eLazyBoolCalculate)
256 {
257 StringExtractorGDBRemote response;
258 m_supports_vCont_any = eLazyBoolNo;
259 m_supports_vCont_all = eLazyBoolNo;
260 m_supports_vCont_c = eLazyBoolNo;
261 m_supports_vCont_C = eLazyBoolNo;
262 m_supports_vCont_s = eLazyBoolNo;
263 m_supports_vCont_S = eLazyBoolNo;
264 if (SendPacketAndWaitForResponse("vCont?", response, false))
265 {
266 const char *response_cstr = response.GetStringRef().c_str();
267 if (::strstr (response_cstr, ";c"))
268 m_supports_vCont_c = eLazyBoolYes;
269
270 if (::strstr (response_cstr, ";C"))
271 m_supports_vCont_C = eLazyBoolYes;
272
273 if (::strstr (response_cstr, ";s"))
274 m_supports_vCont_s = eLazyBoolYes;
275
276 if (::strstr (response_cstr, ";S"))
277 m_supports_vCont_S = eLazyBoolYes;
278
279 if (m_supports_vCont_c == eLazyBoolYes &&
280 m_supports_vCont_C == eLazyBoolYes &&
281 m_supports_vCont_s == eLazyBoolYes &&
282 m_supports_vCont_S == eLazyBoolYes)
283 {
284 m_supports_vCont_all = eLazyBoolYes;
285 }
286
287 if (m_supports_vCont_c == eLazyBoolYes ||
288 m_supports_vCont_C == eLazyBoolYes ||
289 m_supports_vCont_s == eLazyBoolYes ||
290 m_supports_vCont_S == eLazyBoolYes)
291 {
292 m_supports_vCont_any = eLazyBoolYes;
293 }
294 }
295 }
296
297 switch (flavor)
298 {
299 case 'a': return m_supports_vCont_any;
300 case 'A': return m_supports_vCont_all;
301 case 'c': return m_supports_vCont_c;
302 case 'C': return m_supports_vCont_C;
303 case 's': return m_supports_vCont_s;
304 case 'S': return m_supports_vCont_S;
305 default: break;
306 }
307 return false;
308}
309
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000310// Check if the target supports 'p' packet. It sends out a 'p'
311// packet and checks the response. A normal packet will tell us
312// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000313//
314// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000315bool
Sean Callananb1de1142013-09-04 23:24:15 +0000316GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000317{
318 if (m_supports_p == eLazyBoolCalculate)
319 {
320 StringExtractorGDBRemote response;
321 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000322 char packet[256];
323 if (GetThreadSuffixSupported())
324 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
325 else
326 snprintf(packet, sizeof(packet), "p0");
327
328 if (SendPacketAndWaitForResponse(packet, response, false))
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000329 {
330 if (response.IsNormalResponse())
331 m_supports_p = eLazyBoolYes;
332 }
333 }
334 return m_supports_p;
335}
Greg Clayton576d8832011-03-22 04:00:09 +0000336
337size_t
338GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
339(
340 const char *payload,
341 StringExtractorGDBRemote &response,
342 bool send_async
343)
344{
345 return SendPacketAndWaitForResponse (payload,
346 ::strlen (payload),
347 response,
348 send_async);
349}
350
351size_t
352GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
353(
354 const char *payload,
355 size_t payload_length,
356 StringExtractorGDBRemote &response,
357 bool send_async
358)
359{
360 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000361 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton644247c2011-07-07 01:59:51 +0000362 size_t response_len = 0;
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000363 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000364 {
Greg Clayton5fe15d22011-05-20 03:15:54 +0000365 if (SendPacketNoLock (payload, payload_length))
Greg Clayton644247c2011-07-07 01:59:51 +0000366 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
367 else
368 {
369 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000370 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
Greg Clayton644247c2011-07-07 01:59:51 +0000371 }
Greg Clayton576d8832011-03-22 04:00:09 +0000372 }
373 else
374 {
375 if (send_async)
376 {
Greg Claytond3544052012-05-31 21:24:20 +0000377 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000378 {
Greg Claytond3544052012-05-31 21:24:20 +0000379 Mutex::Locker async_locker (m_async_mutex);
380 m_async_packet.assign(payload, payload_length);
381 m_async_packet_predicate.SetValue (true, eBroadcastNever);
382
383 if (log)
384 log->Printf ("async: async packet = %s", m_async_packet.c_str());
385
386 bool timed_out = false;
387 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000388 {
Greg Claytond3544052012-05-31 21:24:20 +0000389 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000390 {
Jim Inghambabfc382012-06-06 00:32:39 +0000391 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000392 TimeValue timeout_time;
393 timeout_time = TimeValue::Now();
394 timeout_time.OffsetWithSeconds (m_packet_timeout);
395
Greg Clayton576d8832011-03-22 04:00:09 +0000396 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000397 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000398
Greg Claytond3544052012-05-31 21:24:20 +0000399 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000400 {
Greg Claytond3544052012-05-31 21:24:20 +0000401 if (log)
402 log->Printf ("async: got response");
403
404 // Swap the response buffer to avoid malloc and string copy
405 response.GetStringRef().swap (m_async_response.GetStringRef());
406 response_len = response.GetStringRef().size();
407 }
408 else
409 {
410 if (log)
411 log->Printf ("async: timed out waiting for response");
412 }
413
414 // Make sure we wait until the continue packet has been sent again...
415 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
416 {
417 if (log)
418 {
419 if (timed_out)
420 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
421 else
422 log->Printf ("async: async packet sent");
423 }
424 }
425 else
426 {
427 if (log)
428 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000429 }
430 }
431 else
432 {
Greg Claytond3544052012-05-31 21:24:20 +0000433 // We had a racy condition where we went to send the interrupt
434 // yet we were able to get the lock, so the process must have
435 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000436 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000437 log->Printf ("async: got lock without sending interrupt");
438 // Send the packet normally since we got the lock
439 if (SendPacketNoLock (payload, payload_length))
440 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
441 else
442 {
443 if (log)
444 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
445 }
Greg Clayton576d8832011-03-22 04:00:09 +0000446 }
447 }
448 else
449 {
Greg Clayton644247c2011-07-07 01:59:51 +0000450 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000451 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000452 }
453 }
454 else
455 {
456 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000457 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000458 }
459 }
460 else
461 {
462 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000463 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000464 }
465 }
Greg Clayton644247c2011-07-07 01:59:51 +0000466 if (response_len == 0)
467 {
468 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000469 log->Printf("error: failed to get response for '%*s'", (int) payload_length, payload);
Greg Clayton644247c2011-07-07 01:59:51 +0000470 }
471 return response_len;
Greg Clayton576d8832011-03-22 04:00:09 +0000472}
473
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000474static const char *end_delimiter = "--end--;";
475static const int end_delimiter_len = 8;
476
477std::string
478GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
479( ProcessGDBRemote *process,
480 StringExtractorGDBRemote& profileDataExtractor
481)
482{
483 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
484 std::stringstream final_output;
485 std::string name, value;
486
487 // Going to assuming thread_used_usec comes first, else bail out.
488 while (profileDataExtractor.GetNameColonValue(name, value))
489 {
490 if (name.compare("thread_used_id") == 0)
491 {
492 StringExtractor threadIDHexExtractor(value.c_str());
493 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
494
495 bool has_used_usec = false;
496 uint32_t curr_used_usec = 0;
497 std::string usec_name, usec_value;
498 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
499 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
500 {
501 if (usec_name.compare("thread_used_usec") == 0)
502 {
503 has_used_usec = true;
504 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
505 }
506 else
507 {
508 // We didn't find what we want, it is probably
509 // an older version. Bail out.
510 profileDataExtractor.SetFilePos(input_file_pos);
511 }
512 }
513
514 if (has_used_usec)
515 {
516 uint32_t prev_used_usec = 0;
517 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
518 if (iterator != m_thread_id_to_used_usec_map.end())
519 {
520 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
521 }
522
523 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
524 // A good first time record is one that runs for at least 0.25 sec
525 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
526 bool good_subsequent_time = (prev_used_usec > 0) &&
527 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
528
529 if (good_first_time || good_subsequent_time)
530 {
531 // We try to avoid doing too many index id reservation,
532 // resulting in fast increase of index ids.
533
534 final_output << name << ":";
535 int32_t index_id = process->AssignIndexIDToThread(thread_id);
536 final_output << index_id << ";";
537
538 final_output << usec_name << ":" << usec_value << ";";
539 }
540 else
541 {
542 // Skip past 'thread_used_name'.
543 std::string local_name, local_value;
544 profileDataExtractor.GetNameColonValue(local_name, local_value);
545 }
546
547 // Store current time as previous time so that they can be compared later.
548 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
549 }
550 else
551 {
552 // Bail out and use old string.
553 final_output << name << ":" << value << ";";
554 }
555 }
556 else
557 {
558 final_output << name << ":" << value << ";";
559 }
560 }
561 final_output << end_delimiter;
562 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
563
564 return final_output.str();
565}
566
Greg Clayton576d8832011-03-22 04:00:09 +0000567StateType
568GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
569(
570 ProcessGDBRemote *process,
571 const char *payload,
572 size_t packet_length,
573 StringExtractorGDBRemote &response
574)
575{
Greg Clayton1f5181a2012-07-02 22:05:25 +0000576 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +0000577 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +0000578 if (log)
579 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
580
581 Mutex::Locker locker(m_sequence_mutex);
582 StateType state = eStateRunning;
583
584 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
585 m_public_is_running.SetValue (true, eBroadcastNever);
586 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +0000587 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +0000588 std::string continue_packet(payload, packet_length);
589
Greg Clayton3f875c52013-02-22 22:23:55 +0000590 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +0000591
Greg Clayton576d8832011-03-22 04:00:09 +0000592 while (state == eStateRunning)
593 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000594 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +0000595 {
596 if (log)
597 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +0000598 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) == 0)
Greg Claytonaf247d72011-05-19 03:54:16 +0000599 state = eStateInvalid;
Greg Clayton576d8832011-03-22 04:00:09 +0000600
Greg Claytone889ad62011-10-27 22:04:16 +0000601 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +0000602 }
603
Greg Clayton3f875c52013-02-22 22:23:55 +0000604 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000605
606 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000607 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +0000608
Greg Clayton37a0a242012-04-11 00:24:49 +0000609 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX))
Greg Clayton576d8832011-03-22 04:00:09 +0000610 {
611 if (response.Empty())
612 state = eStateInvalid;
613 else
614 {
615 const char stop_type = response.GetChar();
616 if (log)
617 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
618 switch (stop_type)
619 {
620 case 'T':
621 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +0000622 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000623 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +0000624 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000625 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
626 {
627 lldb::pid_t pid = GetCurrentProcessID ();
628 if (pid != LLDB_INVALID_PROCESS_ID)
629 process->SetID (pid);
630 }
631 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +0000632 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000633
634 // Privately notify any internal threads that we have stopped
635 // in case we wanted to interrupt our process, yet we might
636 // send a packet and continue without returning control to the
637 // user.
638 m_private_is_running.SetValue (false, eBroadcastAlways);
639
640 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
641
Jim Inghambabfc382012-06-06 00:32:39 +0000642 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
643 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +0000644 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000645 // We sent an interrupt packet to stop the inferior process
646 // for an async signal or to send an async packet while running
647 // but we might have been single stepping and received the
648 // stop packet for the step instead of for the interrupt packet.
649 // Typically when an interrupt is sent a SIGINT or SIGSTOP
650 // is used, so if we get anything else, we need to try and
651 // get another stop reply packet that may have been sent
652 // due to sending the interrupt when the target is stopped
653 // which will just re-send a copy of the last stop reply
654 // packet. If we don't do this, then the reply for our
655 // async packet will be the repeat stop reply packet and cause
656 // a lot of trouble for us!
657 if (signo != SIGINT && signo != SIGSTOP)
658 {
Greg Claytonfb72fde2012-05-15 02:50:49 +0000659 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000660
661 // We didn't get a a SIGINT or SIGSTOP, so try for a
662 // very brief time (1 ms) to get another stop reply
663 // packet to make sure it doesn't get in the way
664 StringExtractorGDBRemote extra_stop_reply_packet;
665 uint32_t timeout_usec = 1000;
666 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec))
667 {
668 switch (extra_stop_reply_packet.GetChar())
669 {
670 case 'T':
671 case 'S':
672 // We did get an extra stop reply, which means
673 // our interrupt didn't stop the target so we
674 // shouldn't continue after the async signal
675 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +0000676 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000677 break;
678 }
679 }
680 }
681 }
682
683 if (m_async_signal != -1)
684 {
685 if (log)
686 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
687
688 // Save off the async signal we are supposed to send
689 const int async_signal = m_async_signal;
690 // Clear the async signal member so we don't end up
691 // sending the signal multiple times...
692 m_async_signal = -1;
693 // Check which signal we stopped with
694 if (signo == async_signal)
695 {
696 if (log)
697 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
698
699 // We already stopped with a signal that we wanted
700 // to stop with, so we are done
701 }
702 else
703 {
704 // We stopped with a different signal that the one
705 // we wanted to stop with, so now we must resume
706 // with the signal we want
707 char signal_packet[32];
708 int signal_packet_len = 0;
709 signal_packet_len = ::snprintf (signal_packet,
710 sizeof (signal_packet),
711 "C%2.2x",
712 async_signal);
713
714 if (log)
715 log->Printf ("async: stopped with signal %s, resume with %s",
716 Host::GetSignalAsCString (signo),
717 Host::GetSignalAsCString (async_signal));
718
719 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +0000720 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000721 continue_packet.assign(signal_packet, signal_packet_len);
722 continue;
723 }
724 }
725 else if (m_async_packet_predicate.GetValue())
726 {
Greg Clayton5160ce52013-03-27 23:08:40 +0000727 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +0000728
729 // We are supposed to send an asynchronous packet while
730 // we are running.
731 m_async_response.Clear();
732 if (m_async_packet.empty())
733 {
734 if (packet_log)
735 packet_log->Printf ("async: error: empty async packet");
736
737 }
738 else
739 {
740 if (packet_log)
741 packet_log->Printf ("async: sending packet");
742
743 SendPacketAndWaitForResponse (&m_async_packet[0],
744 m_async_packet.size(),
745 m_async_response,
746 false);
747 }
748 // Let the other thread that was trying to send the async
749 // packet know that the packet has been sent and response is
750 // ready...
751 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
752
753 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +0000754 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +0000755
756 // Set the continue packet to resume if our interrupt
757 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +0000758 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000759 {
Greg Claytonf1186de2012-05-24 23:42:14 +0000760 // Reverting this for now as it is causing deadlocks
761 // in programs (<rdar://problem/11529853>). In the future
762 // we should check our thread list and "do the right thing"
763 // for new threads that show up while we stop and run async
764 // packets. Setting the packet to 'c' to continue all threads
765 // is the right thing to do 99.99% of the time because if a
766 // thread was single stepping, and we sent an interrupt, we
767 // will notice above that we didn't stop due to an interrupt
768 // but stopped due to stepping and we would _not_ continue.
769 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +0000770 continue;
771 }
772 }
773 // Stop with signal and thread info
774 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +0000775 }
Greg Clayton576d8832011-03-22 04:00:09 +0000776 break;
777
778 case 'W':
779 case 'X':
780 // process exited
781 state = eStateExited;
782 break;
783
784 case 'O':
785 // STDOUT
786 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000787 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000788 std::string inferior_stdout;
789 inferior_stdout.reserve(response.GetBytesLeft () / 2);
790 char ch;
791 while ((ch = response.GetHexU8()) != '\0')
792 inferior_stdout.append(1, ch);
793 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
794 }
795 break;
796
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000797 case 'A':
798 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
799 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000800 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000801 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
802 if (m_partial_profile_data.length() > 0)
803 {
804 m_partial_profile_data.append(input);
805 input = m_partial_profile_data;
806 m_partial_profile_data.clear();
807 }
808
809 size_t found, pos = 0, len = input.length();
810 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
811 {
812 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +0000813 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
814 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000815
816 pos = found + end_delimiter_len;
817 }
818
819 if (pos < len)
820 {
821 // Last incomplete chunk.
822 m_partial_profile_data = input.substr(pos);
823 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000824 }
825 break;
826
Greg Clayton576d8832011-03-22 04:00:09 +0000827 case 'E':
828 // ERROR
829 state = eStateInvalid;
830 break;
831
832 default:
833 if (log)
834 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
835 state = eStateInvalid;
836 break;
837 }
838 }
839 }
840 else
841 {
842 if (log)
843 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
844 state = eStateInvalid;
845 }
846 }
847 if (log)
848 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
849 response.SetFilePos(0);
850 m_private_is_running.SetValue (false, eBroadcastAlways);
851 m_public_is_running.SetValue (false, eBroadcastAlways);
852 return state;
853}
854
855bool
856GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
857{
Greg Clayton2687cd12012-03-29 01:55:41 +0000858 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +0000859 m_async_signal = signo;
860 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000861 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +0000862 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000863 return true;
864 m_async_signal = -1;
865 return false;
866}
867
Greg Clayton37a0a242012-04-11 00:24:49 +0000868// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +0000869// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
870// (the expected result), then it will send the halt packet. If it does succeed
871// then the caller that requested the interrupt will want to keep the sequence
872// locked down so that no one else can send packets while the caller has control.
873// This function usually gets called when we are running and need to stop the
874// target. It can also be used when we are running and and we need to do something
875// else (like read/write memory), so we need to interrupt the running process
876// (gdb remote protocol requires this), and do what we need to do, then resume.
877
878bool
Greg Clayton2687cd12012-03-29 01:55:41 +0000879GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +0000880(
881 Mutex::Locker& locker,
882 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +0000883 bool &timed_out
884)
885{
Greg Clayton576d8832011-03-22 04:00:09 +0000886 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +0000887 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +0000888
889 if (IsRunning())
890 {
891 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000892 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +0000893 {
894 if (log)
895 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
896 }
897 else
Greg Clayton576d8832011-03-22 04:00:09 +0000898 {
899 // Someone has the mutex locked waiting for a response or for the
900 // inferior to stop, so send the interrupt on the down low...
901 char ctrl_c = '\x03';
902 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +0000903 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +0000904 if (log)
905 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +0000906 if (bytes_written > 0)
907 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000908 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000909 if (seconds_to_wait_for_stop)
910 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000911 TimeValue timeout;
912 if (seconds_to_wait_for_stop)
913 {
914 timeout = TimeValue::Now();
915 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
916 }
Greg Clayton576d8832011-03-22 04:00:09 +0000917 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
918 {
919 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000920 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +0000921 return true;
922 }
923 else
924 {
925 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000926 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +0000927 }
928 }
929 else
930 {
931 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000932 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +0000933 return true;
934 }
935 }
936 else
937 {
938 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000939 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000940 }
941 return false;
942 }
Greg Clayton576d8832011-03-22 04:00:09 +0000943 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000944 else
945 {
946 if (log)
947 log->Printf ("SendInterrupt () - not running");
948 }
Greg Clayton576d8832011-03-22 04:00:09 +0000949 return true;
950}
951
952lldb::pid_t
953GDBRemoteCommunicationClient::GetCurrentProcessID ()
954{
955 StringExtractorGDBRemote response;
956 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false))
957 {
958 if (response.GetChar() == 'Q')
959 if (response.GetChar() == 'C')
960 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
961 }
962 return LLDB_INVALID_PROCESS_ID;
963}
964
965bool
966GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
967{
968 error_str.clear();
969 StringExtractorGDBRemote response;
970 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false))
971 {
972 if (response.IsOKResponse())
973 return true;
974 if (response.GetChar() == 'E')
975 {
976 // A string the describes what failed when launching...
977 error_str = response.GetStringRef().substr(1);
978 }
979 else
980 {
981 error_str.assign ("unknown error occurred launching process");
982 }
983 }
984 else
985 {
Jim Ingham98d6da52012-06-28 20:30:23 +0000986 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +0000987 }
988 return false;
989}
990
991int
992GDBRemoteCommunicationClient::SendArgumentsPacket (char const *argv[])
993{
994 if (argv && argv[0])
995 {
996 StreamString packet;
997 packet.PutChar('A');
998 const char *arg;
999 for (uint32_t i = 0; (arg = argv[i]) != NULL; ++i)
1000 {
1001 const int arg_len = strlen(arg);
1002 if (i > 0)
1003 packet.PutChar(',');
1004 packet.Printf("%i,%i,", arg_len * 2, i);
1005 packet.PutBytesAsRawHex8 (arg, arg_len);
1006 }
1007
1008 StringExtractorGDBRemote response;
1009 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1010 {
1011 if (response.IsOKResponse())
1012 return 0;
1013 uint8_t error = response.GetError();
1014 if (error)
1015 return error;
1016 }
1017 }
1018 return -1;
1019}
1020
1021int
1022GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1023{
1024 if (name_equal_value && name_equal_value[0])
1025 {
1026 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001027 bool send_hex_encoding = false;
1028 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001029 {
Greg Clayton89600582013-10-10 17:53:50 +00001030 if (isprint(*p))
1031 {
1032 switch (*p)
1033 {
1034 case '$':
1035 case '#':
1036 send_hex_encoding = true;
1037 break;
1038 default:
1039 break;
1040 }
1041 }
1042 else
1043 {
1044 // We have non printable characters, lets hex encode this...
1045 send_hex_encoding = true;
1046 }
1047 }
1048
1049 StringExtractorGDBRemote response;
1050 if (send_hex_encoding)
1051 {
1052 if (m_supports_QEnvironmentHexEncoded)
1053 {
1054 packet.PutCString("QEnvironmentHexEncoded:");
1055 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
1056 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1057 {
1058 if (response.IsOKResponse())
1059 return 0;
1060 uint8_t error = response.GetError();
1061 if (error)
1062 return error;
1063 if (response.IsUnsupportedResponse())
1064 m_supports_QEnvironmentHexEncoded = false;
1065 }
1066 }
1067
1068 }
1069 else if (m_supports_QEnvironment)
1070 {
1071 packet.Printf("QEnvironment:%s", name_equal_value);
1072 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1073 {
1074 if (response.IsOKResponse())
1075 return 0;
1076 uint8_t error = response.GetError();
1077 if (error)
1078 return error;
1079 if (response.IsUnsupportedResponse())
1080 m_supports_QEnvironment = false;
1081 }
Greg Clayton576d8832011-03-22 04:00:09 +00001082 }
1083 }
1084 return -1;
1085}
1086
Greg Claytonc4103b32011-05-08 04:53:50 +00001087int
1088GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1089{
1090 if (arch && arch[0])
1091 {
1092 StreamString packet;
1093 packet.Printf("QLaunchArch:%s", arch);
1094 StringExtractorGDBRemote response;
1095 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1096 {
1097 if (response.IsOKResponse())
1098 return 0;
1099 uint8_t error = response.GetError();
1100 if (error)
1101 return error;
1102 }
1103 }
1104 return -1;
1105}
1106
Greg Clayton576d8832011-03-22 04:00:09 +00001107bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001108GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1109 uint32_t &minor,
1110 uint32_t &update)
1111{
1112 if (GetHostInfo ())
1113 {
1114 if (m_os_version_major != UINT32_MAX)
1115 {
1116 major = m_os_version_major;
1117 minor = m_os_version_minor;
1118 update = m_os_version_update;
1119 return true;
1120 }
1121 }
1122 return false;
1123}
1124
1125bool
1126GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1127{
1128 if (GetHostInfo ())
1129 {
1130 if (!m_os_build.empty())
1131 {
1132 s = m_os_build;
1133 return true;
1134 }
1135 }
1136 s.clear();
1137 return false;
1138}
1139
1140
1141bool
1142GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1143{
1144 if (GetHostInfo ())
1145 {
1146 if (!m_os_kernel.empty())
1147 {
1148 s = m_os_kernel;
1149 return true;
1150 }
1151 }
1152 s.clear();
1153 return false;
1154}
1155
1156bool
1157GDBRemoteCommunicationClient::GetHostname (std::string &s)
1158{
1159 if (GetHostInfo ())
1160 {
1161 if (!m_hostname.empty())
1162 {
1163 s = m_hostname;
1164 return true;
1165 }
1166 }
1167 s.clear();
1168 return false;
1169}
1170
1171ArchSpec
1172GDBRemoteCommunicationClient::GetSystemArchitecture ()
1173{
1174 if (GetHostInfo ())
1175 return m_host_arch;
1176 return ArchSpec();
1177}
1178
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001179const lldb_private::ArchSpec &
1180GDBRemoteCommunicationClient::GetProcessArchitecture ()
1181{
1182 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1183 GetCurrentProcessInfo ();
1184 return m_process_arch;
1185}
1186
Greg Clayton1cb64962011-03-24 04:28:38 +00001187
1188bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001189GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001190{
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001191 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001192 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001193 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001194 StringExtractorGDBRemote response;
1195 if (SendPacketAndWaitForResponse ("qHostInfo", response, false))
1196 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001197 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001198 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001199 std::string name;
1200 std::string value;
1201 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1202 uint32_t sub = 0;
1203 std::string arch_name;
1204 std::string os_name;
1205 std::string vendor_name;
1206 std::string triple;
1207 uint32_t pointer_byte_size = 0;
1208 StringExtractor extractor;
1209 ByteOrder byte_order = eByteOrderInvalid;
1210 uint32_t num_keys_decoded = 0;
1211 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001212 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001213 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001214 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001215 // exception type in big endian hex
1216 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1217 if (cpu != LLDB_INVALID_CPUTYPE)
1218 ++num_keys_decoded;
1219 }
1220 else if (name.compare("cpusubtype") == 0)
1221 {
1222 // exception count in big endian hex
1223 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
1224 if (sub != 0)
1225 ++num_keys_decoded;
1226 }
1227 else if (name.compare("arch") == 0)
1228 {
1229 arch_name.swap (value);
1230 ++num_keys_decoded;
1231 }
1232 else if (name.compare("triple") == 0)
1233 {
1234 // The triple comes as ASCII hex bytes since it contains '-' chars
1235 extractor.GetStringRef().swap(value);
1236 extractor.SetFilePos(0);
1237 extractor.GetHexByteString (triple);
1238 ++num_keys_decoded;
1239 }
1240 else if (name.compare("os_build") == 0)
1241 {
1242 extractor.GetStringRef().swap(value);
1243 extractor.SetFilePos(0);
1244 extractor.GetHexByteString (m_os_build);
1245 ++num_keys_decoded;
1246 }
1247 else if (name.compare("hostname") == 0)
1248 {
1249 extractor.GetStringRef().swap(value);
1250 extractor.SetFilePos(0);
1251 extractor.GetHexByteString (m_hostname);
1252 ++num_keys_decoded;
1253 }
1254 else if (name.compare("os_kernel") == 0)
1255 {
1256 extractor.GetStringRef().swap(value);
1257 extractor.SetFilePos(0);
1258 extractor.GetHexByteString (m_os_kernel);
1259 ++num_keys_decoded;
1260 }
1261 else if (name.compare("ostype") == 0)
1262 {
1263 os_name.swap (value);
1264 ++num_keys_decoded;
1265 }
1266 else if (name.compare("vendor") == 0)
1267 {
1268 vendor_name.swap(value);
1269 ++num_keys_decoded;
1270 }
1271 else if (name.compare("endian") == 0)
1272 {
1273 ++num_keys_decoded;
1274 if (value.compare("little") == 0)
1275 byte_order = eByteOrderLittle;
1276 else if (value.compare("big") == 0)
1277 byte_order = eByteOrderBig;
1278 else if (value.compare("pdp") == 0)
1279 byte_order = eByteOrderPDP;
1280 else
1281 --num_keys_decoded;
1282 }
1283 else if (name.compare("ptrsize") == 0)
1284 {
1285 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1286 if (pointer_byte_size != 0)
1287 ++num_keys_decoded;
1288 }
1289 else if (name.compare("os_version") == 0)
1290 {
1291 Args::StringToVersion (value.c_str(),
1292 m_os_version_major,
1293 m_os_version_minor,
1294 m_os_version_update);
1295 if (m_os_version_major != UINT32_MAX)
1296 ++num_keys_decoded;
1297 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001298 else if (name.compare("watchpoint_exceptions_received") == 0)
1299 {
1300 ++num_keys_decoded;
1301 if (strcmp(value.c_str(),"before") == 0)
1302 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1303 else if (strcmp(value.c_str(),"after") == 0)
1304 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1305 else
1306 --num_keys_decoded;
1307 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001308 else if (name.compare("default_packet_timeout") == 0)
1309 {
1310 m_default_packet_timeout = Args::StringToUInt32(value.c_str(), 0);
1311 if (m_default_packet_timeout > 0)
1312 {
1313 SetPacketTimeout(m_default_packet_timeout);
1314 ++num_keys_decoded;
1315 }
1316 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001317
Greg Clayton32e0a752011-03-30 18:16:51 +00001318 }
1319
1320 if (num_keys_decoded > 0)
1321 m_qHostInfo_is_valid = eLazyBoolYes;
1322
1323 if (triple.empty())
1324 {
1325 if (arch_name.empty())
1326 {
1327 if (cpu != LLDB_INVALID_CPUTYPE)
1328 {
1329 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1330 if (pointer_byte_size)
1331 {
1332 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1333 }
1334 if (byte_order != eByteOrderInvalid)
1335 {
1336 assert (byte_order == m_host_arch.GetByteOrder());
1337 }
Greg Clayton70512312012-05-08 01:45:38 +00001338
1339 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1340 {
1341 switch (m_host_arch.GetMachine())
1342 {
1343 case llvm::Triple::arm:
1344 case llvm::Triple::thumb:
1345 os_name = "ios";
1346 break;
1347 default:
1348 os_name = "macosx";
1349 break;
1350 }
1351 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001352 if (!vendor_name.empty())
1353 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1354 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001355 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001356
1357 }
1358 }
1359 else
1360 {
1361 std::string triple;
1362 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001363 if (!vendor_name.empty() || !os_name.empty())
1364 {
1365 triple += '-';
1366 if (vendor_name.empty())
1367 triple += "unknown";
1368 else
1369 triple += vendor_name;
1370 triple += '-';
1371 if (os_name.empty())
1372 triple += "unknown";
1373 else
1374 triple += os_name;
1375 }
1376 m_host_arch.SetTriple (triple.c_str());
1377
1378 llvm::Triple &host_triple = m_host_arch.GetTriple();
1379 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1380 {
1381 switch (m_host_arch.GetMachine())
1382 {
1383 case llvm::Triple::arm:
1384 case llvm::Triple::thumb:
1385 host_triple.setOS(llvm::Triple::IOS);
1386 break;
1387 default:
1388 host_triple.setOS(llvm::Triple::MacOSX);
1389 break;
1390 }
1391 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001392 if (pointer_byte_size)
1393 {
1394 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1395 }
1396 if (byte_order != eByteOrderInvalid)
1397 {
1398 assert (byte_order == m_host_arch.GetByteOrder());
1399 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001400
Greg Clayton1cb64962011-03-24 04:28:38 +00001401 }
1402 }
1403 else
1404 {
Greg Clayton70512312012-05-08 01:45:38 +00001405 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001406 if (pointer_byte_size)
1407 {
1408 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1409 }
1410 if (byte_order != eByteOrderInvalid)
1411 {
1412 assert (byte_order == m_host_arch.GetByteOrder());
1413 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001414 }
Greg Claytond314e812011-03-23 00:09:55 +00001415 }
Greg Clayton576d8832011-03-22 04:00:09 +00001416 }
1417 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001418 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001419}
1420
1421int
1422GDBRemoteCommunicationClient::SendAttach
1423(
1424 lldb::pid_t pid,
1425 StringExtractorGDBRemote& response
1426)
1427{
1428 if (pid != LLDB_INVALID_PROCESS_ID)
1429 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001430 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001431 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001432 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00001433 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton576d8832011-03-22 04:00:09 +00001434 {
1435 if (response.IsErrorResponse())
1436 return response.GetError();
1437 return 0;
1438 }
1439 }
1440 return -1;
1441}
1442
1443const lldb_private::ArchSpec &
1444GDBRemoteCommunicationClient::GetHostArchitecture ()
1445{
Greg Clayton32e0a752011-03-30 18:16:51 +00001446 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001447 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001448 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001449}
1450
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001451uint32_t
1452GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1453{
1454 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1455 GetHostInfo ();
1456 return m_default_packet_timeout;
1457}
1458
Greg Clayton576d8832011-03-22 04:00:09 +00001459addr_t
1460GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1461{
Greg Clayton70b57652011-05-15 01:25:55 +00001462 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001463 {
Greg Clayton70b57652011-05-15 01:25:55 +00001464 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001465 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001466 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001467 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001468 permissions & lldb::ePermissionsReadable ? "r" : "",
1469 permissions & lldb::ePermissionsWritable ? "w" : "",
1470 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001471 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001472 StringExtractorGDBRemote response;
1473 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1474 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001475 if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001476 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1477 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001478 else
1479 {
1480 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1481 }
Greg Clayton576d8832011-03-22 04:00:09 +00001482 }
1483 return LLDB_INVALID_ADDRESS;
1484}
1485
1486bool
1487GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1488{
Greg Clayton70b57652011-05-15 01:25:55 +00001489 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001490 {
Greg Clayton70b57652011-05-15 01:25:55 +00001491 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001492 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001493 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001494 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001495 StringExtractorGDBRemote response;
1496 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1497 {
1498 if (response.IsOKResponse())
1499 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001500 }
1501 else
1502 {
1503 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00001504 }
Greg Clayton576d8832011-03-22 04:00:09 +00001505 }
1506 return false;
1507}
1508
Jim Inghamacff8952013-05-02 00:27:30 +00001509Error
1510GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00001511{
Jim Inghamacff8952013-05-02 00:27:30 +00001512 Error error;
1513
1514 if (keep_stopped)
1515 {
1516 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1517 {
1518 char packet[64];
1519 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001520 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00001521 StringExtractorGDBRemote response;
1522 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1523 {
1524 m_supports_detach_stay_stopped = eLazyBoolYes;
1525 }
1526 else
1527 {
1528 m_supports_detach_stay_stopped = eLazyBoolNo;
1529 }
1530 }
1531
1532 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1533 {
1534 error.SetErrorString("Stays stopped not supported by this target.");
1535 return error;
1536 }
1537 else
1538 {
1539 size_t num_sent = SendPacket ("D1", 2);
1540 if (num_sent == 0)
1541 error.SetErrorString ("Sending extended disconnect packet failed.");
1542 }
1543 }
1544 else
1545 {
1546 size_t num_sent = SendPacket ("D", 1);
1547 if (num_sent == 0)
1548 error.SetErrorString ("Sending disconnect packet failed.");
1549 }
1550 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001551}
1552
Greg Clayton46fb5582011-11-18 07:03:08 +00001553Error
1554GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1555 lldb_private::MemoryRegionInfo &region_info)
1556{
1557 Error error;
1558 region_info.Clear();
1559
1560 if (m_supports_memory_region_info != eLazyBoolNo)
1561 {
1562 m_supports_memory_region_info = eLazyBoolYes;
1563 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001564 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001565 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00001566 StringExtractorGDBRemote response;
1567 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1568 {
1569 std::string name;
1570 std::string value;
1571 addr_t addr_value;
1572 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00001573 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00001574 while (success && response.GetNameColonValue(name, value))
1575 {
1576 if (name.compare ("start") == 0)
1577 {
1578 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1579 if (success)
1580 region_info.GetRange().SetRangeBase(addr_value);
1581 }
1582 else if (name.compare ("size") == 0)
1583 {
1584 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1585 if (success)
1586 region_info.GetRange().SetByteSize (addr_value);
1587 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001588 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00001589 {
Jason Molendacb349ee2011-12-13 05:39:38 +00001590 saw_permissions = true;
1591 if (region_info.GetRange().Contains (addr))
1592 {
1593 if (value.find('r') != std::string::npos)
1594 region_info.SetReadable (MemoryRegionInfo::eYes);
1595 else
1596 region_info.SetReadable (MemoryRegionInfo::eNo);
1597
1598 if (value.find('w') != std::string::npos)
1599 region_info.SetWritable (MemoryRegionInfo::eYes);
1600 else
1601 region_info.SetWritable (MemoryRegionInfo::eNo);
1602
1603 if (value.find('x') != std::string::npos)
1604 region_info.SetExecutable (MemoryRegionInfo::eYes);
1605 else
1606 region_info.SetExecutable (MemoryRegionInfo::eNo);
1607 }
1608 else
1609 {
1610 // The reported region does not contain this address -- we're looking at an unmapped page
1611 region_info.SetReadable (MemoryRegionInfo::eNo);
1612 region_info.SetWritable (MemoryRegionInfo::eNo);
1613 region_info.SetExecutable (MemoryRegionInfo::eNo);
1614 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001615 }
1616 else if (name.compare ("error") == 0)
1617 {
1618 StringExtractorGDBRemote name_extractor;
1619 // Swap "value" over into "name_extractor"
1620 name_extractor.GetStringRef().swap(value);
1621 // Now convert the HEX bytes into a string value
1622 name_extractor.GetHexByteString (value);
1623 error.SetErrorString(value.c_str());
1624 }
1625 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001626
1627 // We got a valid address range back but no permissions -- which means this is an unmapped page
1628 if (region_info.GetRange().IsValid() && saw_permissions == false)
1629 {
1630 region_info.SetReadable (MemoryRegionInfo::eNo);
1631 region_info.SetWritable (MemoryRegionInfo::eNo);
1632 region_info.SetExecutable (MemoryRegionInfo::eNo);
1633 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001634 }
1635 else
1636 {
1637 m_supports_memory_region_info = eLazyBoolNo;
1638 }
1639 }
1640
1641 if (m_supports_memory_region_info == eLazyBoolNo)
1642 {
1643 error.SetErrorString("qMemoryRegionInfo is not supported");
1644 }
1645 if (error.Fail())
1646 region_info.Clear();
1647 return error;
1648
1649}
1650
Johnny Chen64637202012-05-23 21:09:52 +00001651Error
1652GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1653{
1654 Error error;
1655
1656 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1657 {
1658 num = m_num_supported_hardware_watchpoints;
1659 return error;
1660 }
1661
1662 // Set num to 0 first.
1663 num = 0;
1664 if (m_supports_watchpoint_support_info != eLazyBoolNo)
1665 {
1666 char packet[64];
1667 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001668 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00001669 StringExtractorGDBRemote response;
1670 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1671 {
1672 m_supports_watchpoint_support_info = eLazyBoolYes;
1673 std::string name;
1674 std::string value;
1675 while (response.GetNameColonValue(name, value))
1676 {
1677 if (name.compare ("num") == 0)
1678 {
1679 num = Args::StringToUInt32(value.c_str(), 0, 0);
1680 m_num_supported_hardware_watchpoints = num;
1681 }
1682 }
1683 }
1684 else
1685 {
1686 m_supports_watchpoint_support_info = eLazyBoolNo;
1687 }
1688 }
1689
1690 if (m_supports_watchpoint_support_info == eLazyBoolNo)
1691 {
1692 error.SetErrorString("qWatchpointSupportInfo is not supported");
1693 }
1694 return error;
1695
1696}
Greg Clayton46fb5582011-11-18 07:03:08 +00001697
Enrico Granataf04a2192012-07-13 23:18:48 +00001698lldb_private::Error
1699GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
1700{
1701 Error error(GetWatchpointSupportInfo(num));
1702 if (error.Success())
1703 error = GetWatchpointsTriggerAfterInstruction(after);
1704 return error;
1705}
1706
1707lldb_private::Error
1708GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
1709{
1710 Error error;
1711
1712 // we assume watchpoints will happen after running the relevant opcode
1713 // and we only want to override this behavior if we have explicitly
1714 // received a qHostInfo telling us otherwise
1715 if (m_qHostInfo_is_valid != eLazyBoolYes)
1716 after = true;
1717 else
1718 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1719 return error;
1720}
1721
Greg Clayton576d8832011-03-22 04:00:09 +00001722int
1723GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1724{
1725 if (path && path[0])
1726 {
1727 StreamString packet;
1728 packet.PutCString("QSetSTDIN:");
1729 packet.PutBytesAsRawHex8(path, strlen(path));
1730
1731 StringExtractorGDBRemote response;
1732 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1733 {
1734 if (response.IsOKResponse())
1735 return 0;
1736 uint8_t error = response.GetError();
1737 if (error)
1738 return error;
1739 }
1740 }
1741 return -1;
1742}
1743
1744int
1745GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1746{
1747 if (path && path[0])
1748 {
1749 StreamString packet;
1750 packet.PutCString("QSetSTDOUT:");
1751 packet.PutBytesAsRawHex8(path, strlen(path));
1752
1753 StringExtractorGDBRemote response;
1754 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1755 {
1756 if (response.IsOKResponse())
1757 return 0;
1758 uint8_t error = response.GetError();
1759 if (error)
1760 return error;
1761 }
1762 }
1763 return -1;
1764}
1765
1766int
1767GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1768{
1769 if (path && path[0])
1770 {
1771 StreamString packet;
1772 packet.PutCString("QSetSTDERR:");
1773 packet.PutBytesAsRawHex8(path, strlen(path));
1774
1775 StringExtractorGDBRemote response;
1776 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1777 {
1778 if (response.IsOKResponse())
1779 return 0;
1780 uint8_t error = response.GetError();
1781 if (error)
1782 return error;
1783 }
1784 }
1785 return -1;
1786}
1787
1788int
1789GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
1790{
1791 if (path && path[0])
1792 {
1793 StreamString packet;
1794 packet.PutCString("QSetWorkingDir:");
1795 packet.PutBytesAsRawHex8(path, strlen(path));
1796
1797 StringExtractorGDBRemote response;
1798 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1799 {
1800 if (response.IsOKResponse())
1801 return 0;
1802 uint8_t error = response.GetError();
1803 if (error)
1804 return error;
1805 }
1806 }
1807 return -1;
1808}
1809
1810int
1811GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1812{
Greg Clayton32e0a752011-03-30 18:16:51 +00001813 char packet[32];
1814 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00001815 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00001816 StringExtractorGDBRemote response;
Greg Clayton32e0a752011-03-30 18:16:51 +00001817 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton576d8832011-03-22 04:00:09 +00001818 {
1819 if (response.IsOKResponse())
1820 return 0;
1821 uint8_t error = response.GetError();
1822 if (error)
1823 return error;
1824 }
1825 return -1;
1826}
Greg Clayton32e0a752011-03-30 18:16:51 +00001827
1828bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001829GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00001830{
1831 if (response.IsNormalResponse())
1832 {
1833 std::string name;
1834 std::string value;
1835 StringExtractor extractor;
1836
1837 while (response.GetNameColonValue(name, value))
1838 {
1839 if (name.compare("pid") == 0)
1840 {
1841 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1842 }
1843 else if (name.compare("ppid") == 0)
1844 {
1845 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1846 }
1847 else if (name.compare("uid") == 0)
1848 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001849 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00001850 }
1851 else if (name.compare("euid") == 0)
1852 {
1853 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1854 }
1855 else if (name.compare("gid") == 0)
1856 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001857 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00001858 }
1859 else if (name.compare("egid") == 0)
1860 {
1861 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1862 }
1863 else if (name.compare("triple") == 0)
1864 {
1865 // The triple comes as ASCII hex bytes since it contains '-' chars
1866 extractor.GetStringRef().swap(value);
1867 extractor.SetFilePos(0);
1868 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00001869 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00001870 }
1871 else if (name.compare("name") == 0)
1872 {
1873 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00001874 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00001875 // control the characters in a process name
1876 extractor.GetStringRef().swap(value);
1877 extractor.SetFilePos(0);
1878 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00001879 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00001880 }
1881 }
1882
1883 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1884 return true;
1885 }
1886 return false;
1887}
1888
1889bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001890GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00001891{
1892 process_info.Clear();
1893
1894 if (m_supports_qProcessInfoPID)
1895 {
1896 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00001897 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001898 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00001899 StringExtractorGDBRemote response;
1900 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1901 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001902 return DecodeProcessInfoResponse (response, process_info);
1903 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001904 else
1905 {
1906 m_supports_qProcessInfoPID = false;
1907 return false;
1908 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001909 }
1910 return false;
1911}
1912
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001913bool
1914GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
1915{
1916 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1917 return true;
1918 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1919 return false;
1920
1921 GetHostInfo ();
1922
1923 StringExtractorGDBRemote response;
1924 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false))
1925 {
1926 if (response.IsNormalResponse())
1927 {
1928 std::string name;
1929 std::string value;
1930 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1931 uint32_t sub = 0;
1932 std::string arch_name;
1933 std::string os_name;
1934 std::string vendor_name;
1935 std::string triple;
1936 uint32_t pointer_byte_size = 0;
1937 StringExtractor extractor;
1938 ByteOrder byte_order = eByteOrderInvalid;
1939 uint32_t num_keys_decoded = 0;
1940 while (response.GetNameColonValue(name, value))
1941 {
1942 if (name.compare("cputype") == 0)
1943 {
1944 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
1945 if (cpu != LLDB_INVALID_CPUTYPE)
1946 ++num_keys_decoded;
1947 }
1948 else if (name.compare("cpusubtype") == 0)
1949 {
1950 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
1951 if (sub != 0)
1952 ++num_keys_decoded;
1953 }
1954 else if (name.compare("ostype") == 0)
1955 {
1956 os_name.swap (value);
1957 ++num_keys_decoded;
1958 }
1959 else if (name.compare("vendor") == 0)
1960 {
1961 vendor_name.swap(value);
1962 ++num_keys_decoded;
1963 }
1964 else if (name.compare("endian") == 0)
1965 {
1966 ++num_keys_decoded;
1967 if (value.compare("little") == 0)
1968 byte_order = eByteOrderLittle;
1969 else if (value.compare("big") == 0)
1970 byte_order = eByteOrderBig;
1971 else if (value.compare("pdp") == 0)
1972 byte_order = eByteOrderPDP;
1973 else
1974 --num_keys_decoded;
1975 }
1976 else if (name.compare("ptrsize") == 0)
1977 {
1978 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
1979 if (pointer_byte_size != 0)
1980 ++num_keys_decoded;
1981 }
1982 }
1983 if (num_keys_decoded > 0)
1984 m_qProcessInfo_is_valid = eLazyBoolYes;
1985 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
1986 {
1987 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1988 if (pointer_byte_size)
1989 {
1990 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
1991 }
1992 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1993 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1994 return true;
1995 }
1996 }
1997 }
1998 else
1999 {
2000 m_qProcessInfo_is_valid = eLazyBoolNo;
2001 }
2002
2003 return false;
2004}
2005
2006
Greg Clayton32e0a752011-03-30 18:16:51 +00002007uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002008GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2009 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002010{
2011 process_infos.Clear();
2012
2013 if (m_supports_qfProcessInfo)
2014 {
2015 StreamString packet;
2016 packet.PutCString ("qfProcessInfo");
2017 if (!match_info.MatchAllProcesses())
2018 {
2019 packet.PutChar (':');
2020 const char *name = match_info.GetProcessInfo().GetName();
2021 bool has_name_match = false;
2022 if (name && name[0])
2023 {
2024 has_name_match = true;
2025 NameMatchType name_match_type = match_info.GetNameMatchType();
2026 switch (name_match_type)
2027 {
2028 case eNameMatchIgnore:
2029 has_name_match = false;
2030 break;
2031
2032 case eNameMatchEquals:
2033 packet.PutCString ("name_match:equals;");
2034 break;
2035
2036 case eNameMatchContains:
2037 packet.PutCString ("name_match:contains;");
2038 break;
2039
2040 case eNameMatchStartsWith:
2041 packet.PutCString ("name_match:starts_with;");
2042 break;
2043
2044 case eNameMatchEndsWith:
2045 packet.PutCString ("name_match:ends_with;");
2046 break;
2047
2048 case eNameMatchRegularExpression:
2049 packet.PutCString ("name_match:regex;");
2050 break;
2051 }
2052 if (has_name_match)
2053 {
2054 packet.PutCString ("name:");
2055 packet.PutBytesAsRawHex8(name, ::strlen(name));
2056 packet.PutChar (';');
2057 }
2058 }
2059
2060 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002061 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002062 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002063 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002064 if (match_info.GetProcessInfo().UserIDIsValid())
2065 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2066 if (match_info.GetProcessInfo().GroupIDIsValid())
2067 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002068 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2069 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2070 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2071 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2072 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2073 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2074 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2075 {
2076 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2077 const llvm::Triple &triple = match_arch.GetTriple();
2078 packet.PutCString("triple:");
2079 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
2080 packet.PutChar (';');
2081 }
2082 }
2083 StringExtractorGDBRemote response;
2084 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
2085 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002086 do
2087 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002088 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002089 if (!DecodeProcessInfoResponse (response, process_info))
2090 break;
2091 process_infos.Append(process_info);
2092 response.GetStringRef().clear();
2093 response.SetFilePos(0);
2094 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false));
2095 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002096 else
2097 {
2098 m_supports_qfProcessInfo = false;
2099 return 0;
2100 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002101 }
2102 return process_infos.GetSize();
2103
2104}
2105
2106bool
2107GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2108{
2109 if (m_supports_qUserName)
2110 {
2111 char packet[32];
2112 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002113 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002114 StringExtractorGDBRemote response;
2115 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2116 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002117 if (response.IsNormalResponse())
2118 {
2119 // Make sure we parsed the right number of characters. The response is
2120 // the hex encoded user name and should make up the entire packet.
2121 // If there are any non-hex ASCII bytes, the length won't match below..
2122 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2123 return true;
2124 }
2125 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002126 else
2127 {
2128 m_supports_qUserName = false;
2129 return false;
2130 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002131 }
2132 return false;
2133
2134}
2135
2136bool
2137GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2138{
2139 if (m_supports_qGroupName)
2140 {
2141 char packet[32];
2142 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002143 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002144 StringExtractorGDBRemote response;
2145 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2146 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002147 if (response.IsNormalResponse())
2148 {
2149 // Make sure we parsed the right number of characters. The response is
2150 // the hex encoded group name and should make up the entire packet.
2151 // If there are any non-hex ASCII bytes, the length won't match below..
2152 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2153 return true;
2154 }
2155 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002156 else
2157 {
2158 m_supports_qGroupName = false;
2159 return false;
2160 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002161 }
2162 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002163}
Greg Clayton32e0a752011-03-30 18:16:51 +00002164
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002165void
2166GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2167{
2168 uint32_t i;
2169 TimeValue start_time, end_time;
2170 uint64_t total_time_nsec;
2171 float packets_per_second;
2172 if (SendSpeedTestPacket (0, 0))
2173 {
2174 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2)
2175 {
2176 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2)
2177 {
2178 start_time = TimeValue::Now();
2179 for (i=0; i<num_packets; ++i)
2180 {
2181 SendSpeedTestPacket (send_size, recv_size);
2182 }
2183 end_time = TimeValue::Now();
2184 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002185 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Daniel Malead01b2952012-11-29 21:49:15 +00002186 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002187 num_packets,
2188 send_size,
2189 recv_size,
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002190 total_time_nsec / TimeValue::NanoSecPerSec,
2191 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002192 packets_per_second);
2193 if (recv_size == 0)
2194 recv_size = 32;
2195 }
2196 if (send_size == 0)
2197 send_size = 32;
2198 }
2199 }
2200 else
2201 {
2202 start_time = TimeValue::Now();
2203 for (i=0; i<num_packets; ++i)
2204 {
2205 GetCurrentProcessID ();
2206 }
2207 end_time = TimeValue::Now();
2208 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002209 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Daniel Malead01b2952012-11-29 21:49:15 +00002210 printf ("%u 'qC' packets packets in 0x%" PRIu64 "%9.9" PRIu64 " sec for %f packets/sec.\n",
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002211 num_packets,
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002212 total_time_nsec / TimeValue::NanoSecPerSec,
2213 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002214 packets_per_second);
2215 }
2216}
2217
2218bool
2219GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2220{
2221 StreamString packet;
2222 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2223 uint32_t bytes_left = send_size;
2224 while (bytes_left > 0)
2225 {
2226 if (bytes_left >= 26)
2227 {
2228 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2229 bytes_left -= 26;
2230 }
2231 else
2232 {
2233 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2234 bytes_left = 0;
2235 }
2236 }
2237
2238 StringExtractorGDBRemote response;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002239 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) > 0;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002240 return false;
Greg Clayton32e0a752011-03-30 18:16:51 +00002241}
Greg Clayton8b82f082011-04-12 05:54:46 +00002242
2243uint16_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002244GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002245{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002246 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00002247 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002248 StreamString stream;
2249 stream.PutCString("qLaunchGDBServer:port:0;");
2250 std::string hostname;
2251 if (Host::GetHostname (hostname))
2252 {
2253 // Make the GDB server we launch only accept connections from this host
2254 stream.Printf("host:%s;", hostname.c_str());
2255 }
2256 else
2257 {
2258 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2259 stream.Printf("host:*;");
2260 }
2261 const char *packet = stream.GetData();
2262 int packet_len = stream.GetSize();
2263
2264 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
Greg Clayton8b82f082011-04-12 05:54:46 +00002265 {
2266 std::string name;
2267 std::string value;
2268 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002269 while (response.GetNameColonValue(name, value))
2270 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00002271 if (name.compare("port") == 0)
Greg Clayton8b82f082011-04-12 05:54:46 +00002272 port = Args::StringToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002273 else if (name.compare("pid") == 0)
2274 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00002275 }
2276 return port;
2277 }
2278 return 0;
2279}
2280
2281bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00002282GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2283{
2284 StreamString stream;
2285 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2286 const char *packet = stream.GetData();
2287 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00002288
Daniel Maleae0f8f572013-08-26 23:57:52 +00002289 StringExtractorGDBRemote response;
2290 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2291 {
2292 if (response.IsOKResponse())
2293 return true;
2294 }
2295 return false;
2296}
2297
2298bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002299GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002300{
2301 if (m_curr_tid == tid)
2302 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002303
Greg Clayton8b82f082011-04-12 05:54:46 +00002304 char packet[32];
2305 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002306 if (tid == UINT64_MAX)
2307 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002308 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002309 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002310 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002311 StringExtractorGDBRemote response;
2312 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2313 {
2314 if (response.IsOKResponse())
2315 {
2316 m_curr_tid = tid;
2317 return true;
2318 }
2319 }
2320 return false;
2321}
2322
2323bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002324GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002325{
2326 if (m_curr_tid_run == tid)
2327 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002328
Greg Clayton8b82f082011-04-12 05:54:46 +00002329 char packet[32];
2330 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002331 if (tid == UINT64_MAX)
2332 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002333 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002334 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2335
Andy Gibbsa297a972013-06-19 19:04:53 +00002336 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002337 StringExtractorGDBRemote response;
2338 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2339 {
2340 if (response.IsOKResponse())
2341 {
2342 m_curr_tid_run = tid;
2343 return true;
2344 }
2345 }
2346 return false;
2347}
2348
2349bool
2350GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2351{
2352 if (SendPacketAndWaitForResponse("?", 1, response, false))
2353 return response.IsNormalResponse();
2354 return false;
2355}
2356
2357bool
Greg Claytonf402f782012-10-13 02:11:55 +00002358GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00002359{
2360 if (m_supports_qThreadStopInfo)
2361 {
2362 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00002363 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002364 assert (packet_len < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002365 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2366 {
Greg Claytonef8180a2013-10-15 00:14:28 +00002367 if (response.IsUnsupportedResponse())
2368 m_supports_qThreadStopInfo = false;
2369 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002370 return true;
2371 else
2372 return false;
2373 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002374 else
2375 {
2376 m_supports_qThreadStopInfo = false;
2377 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002378 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002379 return false;
2380}
2381
2382
2383uint8_t
2384GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2385{
2386 switch (type)
2387 {
2388 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break;
2389 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break;
2390 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break;
2391 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break;
2392 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break;
Greg Clayton8b82f082011-04-12 05:54:46 +00002393 }
2394
2395 char packet[64];
2396 const int packet_len = ::snprintf (packet,
2397 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00002398 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00002399 insert ? 'Z' : 'z',
2400 type,
2401 addr,
2402 length);
2403
Andy Gibbsa297a972013-06-19 19:04:53 +00002404 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002405 StringExtractorGDBRemote response;
2406 if (SendPacketAndWaitForResponse(packet, packet_len, response, true))
2407 {
2408 if (response.IsOKResponse())
2409 return 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002410 else if (response.IsErrorResponse())
2411 return response.GetError();
2412 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002413 else
2414 {
2415 switch (type)
2416 {
2417 case eBreakpointSoftware: m_supports_z0 = false; break;
2418 case eBreakpointHardware: m_supports_z1 = false; break;
2419 case eWatchpointWrite: m_supports_z2 = false; break;
2420 case eWatchpointRead: m_supports_z3 = false; break;
2421 case eWatchpointReadWrite: m_supports_z4 = false; break;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002422 }
2423 }
2424
Greg Clayton8b82f082011-04-12 05:54:46 +00002425 return UINT8_MAX;
2426}
Greg Claytonadc00cb2011-05-20 23:38:13 +00002427
2428size_t
2429GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2430 bool &sequence_mutex_unavailable)
2431{
2432 Mutex::Locker locker;
2433 thread_ids.clear();
2434
Jim Ingham4ceb9282012-06-08 22:50:40 +00002435 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002436 {
2437 sequence_mutex_unavailable = false;
2438 StringExtractorGDBRemote response;
2439
Greg Clayton73bf5db2011-06-17 01:22:15 +00002440 for (SendPacketNoLock ("qfThreadInfo", strlen("qfThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
Greg Claytonadc00cb2011-05-20 23:38:13 +00002441 response.IsNormalResponse();
Greg Clayton73bf5db2011-06-17 01:22:15 +00002442 SendPacketNoLock ("qsThreadInfo", strlen("qsThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ()))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002443 {
2444 char ch = response.GetChar();
2445 if (ch == 'l')
2446 break;
2447 if (ch == 'm')
2448 {
2449 do
2450 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00002451 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00002452
2453 if (tid != LLDB_INVALID_THREAD_ID)
2454 {
2455 thread_ids.push_back (tid);
2456 }
2457 ch = response.GetChar(); // Skip the command separator
2458 } while (ch == ','); // Make sure we got a comma separator
2459 }
2460 }
2461 }
2462 else
2463 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00002464#if defined (LLDB_CONFIGURATION_DEBUG)
2465 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2466#else
Greg Clayton5160ce52013-03-27 23:08:40 +00002467 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00002468 if (log)
2469 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00002470#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00002471 sequence_mutex_unavailable = true;
2472 }
2473 return thread_ids.size();
2474}
Greg Clayton37a0a242012-04-11 00:24:49 +00002475
2476lldb::addr_t
2477GDBRemoteCommunicationClient::GetShlibInfoAddr()
2478{
2479 if (!IsRunning())
2480 {
2481 StringExtractorGDBRemote response;
2482 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
2483 {
2484 if (response.IsNormalResponse())
2485 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2486 }
2487 }
2488 return LLDB_INVALID_ADDRESS;
2489}
2490
Daniel Maleae0f8f572013-08-26 23:57:52 +00002491lldb_private::Error
2492GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL
2493 const char *working_dir, // Pass NULL to use the current working directory
2494 int *status_ptr, // Pass NULL if you don't want the process exit status
2495 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
2496 std::string *command_output, // Pass NULL if you don't want the command output
2497 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
2498{
2499 lldb_private::StreamString stream;
2500 stream.PutCString("qPlatform_RunCommand:");
2501 stream.PutBytesAsRawHex8(command, strlen(command));
2502 stream.PutChar(',');
2503 stream.PutHex32(timeout_sec);
2504 if (working_dir && *working_dir)
2505 {
2506 stream.PutChar(',');
2507 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
2508 }
2509 const char *packet = stream.GetData();
2510 int packet_len = stream.GetSize();
2511 StringExtractorGDBRemote response;
2512 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2513 {
2514 if (response.GetChar() != 'F')
2515 return Error("malformed reply");
2516 if (response.GetChar() != ',')
2517 return Error("malformed reply");
2518 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2519 if (exitcode == UINT32_MAX)
2520 return Error("unable to run remote process");
2521 else if (status_ptr)
2522 *status_ptr = exitcode;
2523 if (response.GetChar() != ',')
2524 return Error("malformed reply");
2525 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2526 if (signo_ptr)
2527 *signo_ptr = signo;
2528 if (response.GetChar() != ',')
2529 return Error("malformed reply");
2530 std::string output;
2531 response.GetEscapedBinaryData(output);
2532 if (command_output)
2533 command_output->assign(output);
2534 return Error();
2535 }
2536 return Error("unable to send packet");
2537}
2538
2539uint32_t
2540GDBRemoteCommunicationClient::MakeDirectory (const std::string &path,
2541 mode_t mode)
2542{
2543 lldb_private::StreamString stream;
2544 stream.PutCString("qPlatform_IO_MkDir:");
2545 stream.PutHex32(mode);
2546 stream.PutChar(',');
2547 stream.PutBytesAsRawHex8(path.c_str(), path.size());
2548 const char *packet = stream.GetData();
2549 int packet_len = stream.GetSize();
2550 StringExtractorGDBRemote response;
2551 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2552 {
2553 return response.GetHexMaxU32(false, UINT32_MAX);
2554 }
2555 return UINT32_MAX;
2556
2557}
2558
2559static uint64_t
2560ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
2561 uint64_t fail_result,
2562 Error &error)
2563{
2564 response.SetFilePos(0);
2565 if (response.GetChar() != 'F')
2566 return fail_result;
2567 int32_t result = response.GetS32 (-2);
2568 if (result == -2)
2569 return fail_result;
2570 if (response.GetChar() == ',')
2571 {
2572 int result_errno = response.GetS32 (-2);
2573 if (result_errno != -2)
2574 error.SetError(result_errno, eErrorTypePOSIX);
2575 else
2576 error.SetError(-1, eErrorTypeGeneric);
2577 }
2578 else
2579 error.Clear();
2580 return result;
2581}
2582lldb::user_id_t
2583GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
2584 uint32_t flags,
2585 mode_t mode,
2586 Error &error)
2587{
2588 lldb_private::StreamString stream;
2589 stream.PutCString("vFile:open:");
2590 std::string path (file_spec.GetPath());
2591 if (path.empty())
2592 return UINT64_MAX;
2593 stream.PutCStringAsRawHex8(path.c_str());
2594 stream.PutChar(',');
2595 const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags);
2596 stream.PutHex32(posix_open_flags);
2597 stream.PutChar(',');
2598 stream.PutHex32(mode);
2599 const char* packet = stream.GetData();
2600 int packet_len = stream.GetSize();
2601 StringExtractorGDBRemote response;
2602 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2603 {
2604 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
2605 }
2606 return UINT64_MAX;
2607}
2608
2609bool
2610GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
2611 Error &error)
2612{
2613 lldb_private::StreamString stream;
2614 stream.Printf("vFile:close:%i", (int)fd);
2615 const char* packet = stream.GetData();
2616 int packet_len = stream.GetSize();
2617 StringExtractorGDBRemote response;
2618 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2619 {
2620 return ParseHostIOPacketResponse (response, -1, error) == 0;
2621 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00002622 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002623}
2624
2625// Extension of host I/O packets to get the file size.
2626lldb::user_id_t
2627GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
2628{
2629 lldb_private::StreamString stream;
2630 stream.PutCString("vFile:size:");
2631 std::string path (file_spec.GetPath());
2632 stream.PutCStringAsRawHex8(path.c_str());
2633 const char* packet = stream.GetData();
2634 int packet_len = stream.GetSize();
2635 StringExtractorGDBRemote response;
2636 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2637 {
2638 if (response.GetChar() != 'F')
2639 return UINT64_MAX;
2640 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2641 return retcode;
2642 }
2643 return UINT64_MAX;
2644}
2645
2646uint32_t
2647GDBRemoteCommunicationClient::GetFilePermissions(const lldb_private::FileSpec& file_spec, Error &error)
2648{
2649 lldb_private::StreamString stream;
2650 stream.PutCString("vFile:mode:");
2651 std::string path (file_spec.GetPath());
2652 stream.PutCStringAsRawHex8(path.c_str());
2653 const char* packet = stream.GetData();
2654 int packet_len = stream.GetSize();
2655 StringExtractorGDBRemote response;
2656 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2657 {
2658 if (response.GetChar() != 'F')
2659 {
2660 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
2661 return 0;
2662 }
2663 const uint32_t mode = response.GetS32(-1);
2664 if (mode == -1)
2665 {
2666 if (response.GetChar() == ',')
2667 {
2668 int response_errno = response.GetS32(-1);
2669 if (response_errno > 0)
2670 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2671 else
2672 error.SetErrorToGenericError();
2673 }
2674 }
2675 else
2676 error.Clear();
2677 return mode & (S_IRWXU|S_IRWXG|S_IRWXO);
2678 }
2679 else
2680 {
2681 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
2682 }
2683 return 0;
2684}
2685
2686uint64_t
2687GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
2688 uint64_t offset,
2689 void *dst,
2690 uint64_t dst_len,
2691 Error &error)
2692{
2693 lldb_private::StreamString stream;
2694 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
2695 const char* packet = stream.GetData();
2696 int packet_len = stream.GetSize();
2697 StringExtractorGDBRemote response;
2698 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2699 {
2700 if (response.GetChar() != 'F')
2701 return 0;
2702 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2703 if (retcode == UINT32_MAX)
2704 return retcode;
2705 const char next = (response.Peek() ? *response.Peek() : 0);
2706 if (next == ',')
2707 return 0;
2708 if (next == ';')
2709 {
2710 response.GetChar(); // skip the semicolon
2711 std::string buffer;
2712 if (response.GetEscapedBinaryData(buffer))
2713 {
2714 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
2715 if (data_to_write > 0)
2716 memcpy(dst, &buffer[0], data_to_write);
2717 return data_to_write;
2718 }
2719 }
2720 }
2721 return 0;
2722}
2723
2724uint64_t
2725GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
2726 uint64_t offset,
2727 const void* src,
2728 uint64_t src_len,
2729 Error &error)
2730{
2731 lldb_private::StreamGDBRemote stream;
2732 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2733 stream.PutEscapedBytes(src, src_len);
2734 const char* packet = stream.GetData();
2735 int packet_len = stream.GetSize();
2736 StringExtractorGDBRemote response;
2737 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2738 {
2739 if (response.GetChar() != 'F')
2740 {
2741 error.SetErrorStringWithFormat("write file failed");
2742 return 0;
2743 }
2744 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2745 if (bytes_written == UINT64_MAX)
2746 {
2747 error.SetErrorToGenericError();
2748 if (response.GetChar() == ',')
2749 {
2750 int response_errno = response.GetS32(-1);
2751 if (response_errno > 0)
2752 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2753 }
2754 return 0;
2755 }
2756 return bytes_written;
2757 }
2758 else
2759 {
2760 error.SetErrorString ("failed to send vFile:pwrite packet");
2761 }
2762 return 0;
2763}
2764
2765// Extension of host I/O packets to get whether a file exists.
2766bool
2767GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
2768{
2769 lldb_private::StreamString stream;
2770 stream.PutCString("vFile:exists:");
2771 std::string path (file_spec.GetPath());
2772 stream.PutCStringAsRawHex8(path.c_str());
2773 const char* packet = stream.GetData();
2774 int packet_len = stream.GetSize();
2775 StringExtractorGDBRemote response;
2776 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2777 {
2778 if (response.GetChar() != 'F')
2779 return false;
2780 if (response.GetChar() != ',')
2781 return false;
2782 bool retcode = (response.GetChar() != '0');
2783 return retcode;
2784 }
2785 return false;
2786}
2787
2788bool
2789GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
2790 uint64_t &high,
2791 uint64_t &low)
2792{
2793 lldb_private::StreamString stream;
2794 stream.PutCString("vFile:MD5:");
2795 std::string path (file_spec.GetPath());
2796 stream.PutCStringAsRawHex8(path.c_str());
2797 const char* packet = stream.GetData();
2798 int packet_len = stream.GetSize();
2799 StringExtractorGDBRemote response;
2800 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2801 {
2802 if (response.GetChar() != 'F')
2803 return false;
2804 if (response.GetChar() != ',')
2805 return false;
2806 if (response.Peek() && *response.Peek() == 'x')
2807 return false;
2808 low = response.GetHexMaxU64(false, UINT64_MAX);
2809 high = response.GetHexMaxU64(false, UINT64_MAX);
2810 return true;
2811 }
2812 return false;
2813}
Greg Claytonf74cf862013-11-13 23:28:31 +00002814
2815bool
2816GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
2817{
2818 Mutex::Locker locker;
2819 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
2820 {
2821 const bool thread_suffix_supported = GetThreadSuffixSupported();
2822
2823 if (thread_suffix_supported || SetCurrentThread(tid))
2824 {
2825 char packet[64];
2826 int packet_len = 0;
2827 if (thread_suffix_supported)
2828 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
2829 else
2830 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
2831 assert (packet_len < ((int)sizeof(packet) - 1));
2832 return SendPacketAndWaitForResponse(packet, response, false);
2833 }
2834 }
2835 return false;
2836
2837}
2838
2839
2840bool
2841GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
2842{
2843 Mutex::Locker locker;
2844 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
2845 {
2846 const bool thread_suffix_supported = GetThreadSuffixSupported();
2847
2848 if (thread_suffix_supported || SetCurrentThread(tid))
2849 {
2850 char packet[64];
2851 int packet_len = 0;
2852 // Get all registers in one packet
2853 if (thread_suffix_supported)
2854 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
2855 else
2856 packet_len = ::snprintf (packet, sizeof(packet), "g");
2857 assert (packet_len < ((int)sizeof(packet) - 1));
2858 return SendPacketAndWaitForResponse(packet, response, false);
2859 }
2860 }
2861 return false;
2862}
2863bool
2864GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
2865{
2866 save_id = 0; // Set to invalid save ID
2867 if (m_supports_QSaveRegisterState == eLazyBoolNo)
2868 return false;
2869
2870 m_supports_QSaveRegisterState = eLazyBoolYes;
2871 Mutex::Locker locker;
2872 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
2873 {
2874 const bool thread_suffix_supported = GetThreadSuffixSupported();
2875 if (thread_suffix_supported || SetCurrentThread(tid))
2876 {
2877 char packet[256];
2878 if (thread_suffix_supported)
2879 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
2880 else
2881 ::strncpy (packet, "QSaveRegisterState", sizeof(packet));
2882
2883 StringExtractorGDBRemote response;
2884
2885 if (SendPacketAndWaitForResponse(packet, response, false))
2886 {
2887 if (response.IsUnsupportedResponse())
2888 {
2889 // This packet isn't supported, don't try calling it again
2890 m_supports_QSaveRegisterState = eLazyBoolNo;
2891 }
2892
2893 const uint32_t response_save_id = response.GetU32(0);
2894 if (response_save_id != 0)
2895 {
2896 save_id = response_save_id;
2897 return true;
2898 }
2899 }
2900 }
2901 }
2902 return false;
2903}
2904
2905bool
2906GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
2907{
2908 // We use the "m_supports_QSaveRegisterState" variable here becuase the
2909 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
2910 // order to be useful
2911 if (m_supports_QSaveRegisterState == eLazyBoolNo)
2912 return false;
2913
2914 Mutex::Locker locker;
2915 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
2916 {
2917 const bool thread_suffix_supported = GetThreadSuffixSupported();
2918 if (thread_suffix_supported || SetCurrentThread(tid))
2919 {
2920 char packet[256];
2921 if (thread_suffix_supported)
2922 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
2923 else
2924 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
2925
2926 StringExtractorGDBRemote response;
2927
2928 if (SendPacketAndWaitForResponse(packet, response, false))
2929 {
2930 if (response.IsOKResponse())
2931 {
2932 return true;
2933 }
2934 else if (response.IsUnsupportedResponse())
2935 {
2936 // This packet isn't supported, don't try calling this packet or
2937 // QSaveRegisterState again...
2938 m_supports_QSaveRegisterState = eLazyBoolNo;
2939 }
2940 }
2941 }
2942 }
2943 return false;
2944}