blob: 2690992eeed3ed6464b0f42924e97cff929a0a3c [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{
Greg Claytonfb909312013-11-23 01:58:15 +0000114 ResetDiscoverableSettings();
115
Greg Clayton1cb64962011-03-24 04:28:38 +0000116 // Start the read thread after we send the handshake ack since if we
117 // fail to send the handshake ack, there is no reason to continue...
118 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000119 {
120 // The return value from QueryNoAckModeSupported() is true if the packet
121 // was sent and _any_ response (including UNIMPLEMENTED) was received),
122 // or false if no response was received. This quickly tells us if we have
123 // a live connection to a remote GDB server...
124 if (QueryNoAckModeSupported())
125 {
126 return true;
127 }
128 else
129 {
130 if (error_ptr)
131 error_ptr->SetErrorString("failed to get reply to handshake packet");
132 }
133 }
134 else
135 {
136 if (error_ptr)
137 error_ptr->SetErrorString("failed to send the handshake ack");
138 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000139 return false;
140}
141
Greg Claytonfb909312013-11-23 01:58:15 +0000142bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000143GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000144{
145 if (m_supports_not_sending_acks == eLazyBoolCalculate)
146 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000147 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000148 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000149
150 StringExtractorGDBRemote response;
Greg Clayton576d8832011-03-22 04:00:09 +0000151 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false))
152 {
153 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000154 {
155 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000156 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000157 }
Greg Claytonfb909312013-11-23 01:58:15 +0000158 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000159 }
160 }
Greg Claytonfb909312013-11-23 01:58:15 +0000161 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000162}
163
164void
Greg Clayton44633992012-04-10 03:22:03 +0000165GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
166{
167 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
168 {
169 m_supports_threads_in_stop_reply = eLazyBoolNo;
170
171 StringExtractorGDBRemote response;
172 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false))
173 {
174 if (response.IsOKResponse())
175 m_supports_threads_in_stop_reply = eLazyBoolYes;
176 }
177 }
178}
179
Jim Inghamcd16df92012-07-20 21:37:13 +0000180bool
181GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
182{
183 if (m_attach_or_wait_reply == eLazyBoolCalculate)
184 {
185 m_attach_or_wait_reply = eLazyBoolNo;
186
187 StringExtractorGDBRemote response;
188 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false))
189 {
190 if (response.IsOKResponse())
191 m_attach_or_wait_reply = eLazyBoolYes;
192 }
193 }
194 if (m_attach_or_wait_reply == eLazyBoolYes)
195 return true;
196 else
197 return false;
198}
199
Jim Ingham279ceec2012-07-25 21:12:43 +0000200bool
201GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
202{
203 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
204 {
205 m_prepare_for_reg_writing_reply = eLazyBoolNo;
206
207 StringExtractorGDBRemote response;
208 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false))
209 {
210 if (response.IsOKResponse())
211 m_prepare_for_reg_writing_reply = eLazyBoolYes;
212 }
213 }
214 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
215 return true;
216 else
217 return false;
218}
219
Greg Clayton44633992012-04-10 03:22:03 +0000220
221void
Greg Clayton576d8832011-03-22 04:00:09 +0000222GDBRemoteCommunicationClient::ResetDiscoverableSettings()
223{
224 m_supports_not_sending_acks = eLazyBoolCalculate;
225 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton44633992012-04-10 03:22:03 +0000226 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
Greg Clayton576d8832011-03-22 04:00:09 +0000227 m_supports_vCont_c = eLazyBoolCalculate;
228 m_supports_vCont_C = eLazyBoolCalculate;
229 m_supports_vCont_s = eLazyBoolCalculate;
230 m_supports_vCont_S = eLazyBoolCalculate;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000231 m_supports_p = eLazyBoolCalculate;
Greg Claytonf74cf862013-11-13 23:28:31 +0000232 m_supports_QSaveRegisterState = eLazyBoolCalculate;
Greg Clayton32e0a752011-03-30 18:16:51 +0000233 m_qHostInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000234 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Greg Clayton70b57652011-05-15 01:25:55 +0000235 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton46fb5582011-11-18 07:03:08 +0000236 m_supports_memory_region_info = eLazyBoolCalculate;
Jim Ingham279ceec2012-07-25 21:12:43 +0000237 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
238 m_attach_or_wait_reply = eLazyBoolCalculate;
Greg Clayton2a48f522011-05-14 01:50:35 +0000239
Greg Clayton32e0a752011-03-30 18:16:51 +0000240 m_supports_qProcessInfoPID = true;
241 m_supports_qfProcessInfo = true;
242 m_supports_qUserName = true;
243 m_supports_qGroupName = true;
Greg Clayton8b82f082011-04-12 05:54:46 +0000244 m_supports_qThreadStopInfo = true;
245 m_supports_z0 = true;
246 m_supports_z1 = true;
247 m_supports_z2 = true;
248 m_supports_z3 = true;
249 m_supports_z4 = true;
Greg Clayton89600582013-10-10 17:53:50 +0000250 m_supports_QEnvironment = true;
251 m_supports_QEnvironmentHexEncoded = true;
Greg Claytond314e812011-03-23 00:09:55 +0000252 m_host_arch.Clear();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000253 m_process_arch.Clear();
Greg Clayton576d8832011-03-22 04:00:09 +0000254}
255
256
257bool
258GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
259{
260 if (m_supports_thread_suffix == eLazyBoolCalculate)
261 {
262 StringExtractorGDBRemote response;
263 m_supports_thread_suffix = eLazyBoolNo;
264 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false))
265 {
266 if (response.IsOKResponse())
267 m_supports_thread_suffix = eLazyBoolYes;
268 }
269 }
270 return m_supports_thread_suffix;
271}
272bool
273GDBRemoteCommunicationClient::GetVContSupported (char flavor)
274{
275 if (m_supports_vCont_c == eLazyBoolCalculate)
276 {
277 StringExtractorGDBRemote response;
278 m_supports_vCont_any = eLazyBoolNo;
279 m_supports_vCont_all = eLazyBoolNo;
280 m_supports_vCont_c = eLazyBoolNo;
281 m_supports_vCont_C = eLazyBoolNo;
282 m_supports_vCont_s = eLazyBoolNo;
283 m_supports_vCont_S = eLazyBoolNo;
284 if (SendPacketAndWaitForResponse("vCont?", response, false))
285 {
286 const char *response_cstr = response.GetStringRef().c_str();
287 if (::strstr (response_cstr, ";c"))
288 m_supports_vCont_c = eLazyBoolYes;
289
290 if (::strstr (response_cstr, ";C"))
291 m_supports_vCont_C = eLazyBoolYes;
292
293 if (::strstr (response_cstr, ";s"))
294 m_supports_vCont_s = eLazyBoolYes;
295
296 if (::strstr (response_cstr, ";S"))
297 m_supports_vCont_S = eLazyBoolYes;
298
299 if (m_supports_vCont_c == eLazyBoolYes &&
300 m_supports_vCont_C == eLazyBoolYes &&
301 m_supports_vCont_s == eLazyBoolYes &&
302 m_supports_vCont_S == eLazyBoolYes)
303 {
304 m_supports_vCont_all = eLazyBoolYes;
305 }
306
307 if (m_supports_vCont_c == eLazyBoolYes ||
308 m_supports_vCont_C == eLazyBoolYes ||
309 m_supports_vCont_s == eLazyBoolYes ||
310 m_supports_vCont_S == eLazyBoolYes)
311 {
312 m_supports_vCont_any = eLazyBoolYes;
313 }
314 }
315 }
316
317 switch (flavor)
318 {
319 case 'a': return m_supports_vCont_any;
320 case 'A': return m_supports_vCont_all;
321 case 'c': return m_supports_vCont_c;
322 case 'C': return m_supports_vCont_C;
323 case 's': return m_supports_vCont_s;
324 case 'S': return m_supports_vCont_S;
325 default: break;
326 }
327 return false;
328}
329
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000330// Check if the target supports 'p' packet. It sends out a 'p'
331// packet and checks the response. A normal packet will tell us
332// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000333//
334// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000335bool
Sean Callananb1de1142013-09-04 23:24:15 +0000336GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000337{
338 if (m_supports_p == eLazyBoolCalculate)
339 {
340 StringExtractorGDBRemote response;
341 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000342 char packet[256];
343 if (GetThreadSuffixSupported())
344 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
345 else
346 snprintf(packet, sizeof(packet), "p0");
347
348 if (SendPacketAndWaitForResponse(packet, response, false))
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000349 {
350 if (response.IsNormalResponse())
351 m_supports_p = eLazyBoolYes;
352 }
353 }
354 return m_supports_p;
355}
Greg Clayton576d8832011-03-22 04:00:09 +0000356
357size_t
358GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
359(
360 const char *payload,
361 StringExtractorGDBRemote &response,
362 bool send_async
363)
364{
365 return SendPacketAndWaitForResponse (payload,
366 ::strlen (payload),
367 response,
368 send_async);
369}
370
371size_t
372GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
373(
374 const char *payload,
375 size_t payload_length,
376 StringExtractorGDBRemote &response,
377 bool send_async
378)
379{
380 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000381 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton644247c2011-07-07 01:59:51 +0000382 size_t response_len = 0;
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000383 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000384 {
Greg Clayton5fe15d22011-05-20 03:15:54 +0000385 if (SendPacketNoLock (payload, payload_length))
Greg Clayton644247c2011-07-07 01:59:51 +0000386 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
387 else
388 {
389 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000390 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
Greg Clayton644247c2011-07-07 01:59:51 +0000391 }
Greg Clayton576d8832011-03-22 04:00:09 +0000392 }
393 else
394 {
395 if (send_async)
396 {
Greg Claytond3544052012-05-31 21:24:20 +0000397 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000398 {
Greg Claytond3544052012-05-31 21:24:20 +0000399 Mutex::Locker async_locker (m_async_mutex);
400 m_async_packet.assign(payload, payload_length);
401 m_async_packet_predicate.SetValue (true, eBroadcastNever);
402
403 if (log)
404 log->Printf ("async: async packet = %s", m_async_packet.c_str());
405
406 bool timed_out = false;
407 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000408 {
Greg Claytond3544052012-05-31 21:24:20 +0000409 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000410 {
Jim Inghambabfc382012-06-06 00:32:39 +0000411 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000412 TimeValue timeout_time;
413 timeout_time = TimeValue::Now();
414 timeout_time.OffsetWithSeconds (m_packet_timeout);
415
Greg Clayton576d8832011-03-22 04:00:09 +0000416 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000417 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000418
Greg Claytond3544052012-05-31 21:24:20 +0000419 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000420 {
Greg Claytond3544052012-05-31 21:24:20 +0000421 if (log)
422 log->Printf ("async: got response");
423
424 // Swap the response buffer to avoid malloc and string copy
425 response.GetStringRef().swap (m_async_response.GetStringRef());
426 response_len = response.GetStringRef().size();
427 }
428 else
429 {
430 if (log)
431 log->Printf ("async: timed out waiting for response");
432 }
433
434 // Make sure we wait until the continue packet has been sent again...
435 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
436 {
437 if (log)
438 {
439 if (timed_out)
440 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
441 else
442 log->Printf ("async: async packet sent");
443 }
444 }
445 else
446 {
447 if (log)
448 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000449 }
450 }
451 else
452 {
Greg Claytond3544052012-05-31 21:24:20 +0000453 // We had a racy condition where we went to send the interrupt
454 // yet we were able to get the lock, so the process must have
455 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000456 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000457 log->Printf ("async: got lock without sending interrupt");
458 // Send the packet normally since we got the lock
459 if (SendPacketNoLock (payload, payload_length))
460 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
461 else
462 {
463 if (log)
464 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
465 }
Greg Clayton576d8832011-03-22 04:00:09 +0000466 }
467 }
468 else
469 {
Greg Clayton644247c2011-07-07 01:59:51 +0000470 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000471 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000472 }
473 }
474 else
475 {
476 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000477 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000478 }
479 }
480 else
481 {
482 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000483 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000484 }
485 }
Greg Clayton644247c2011-07-07 01:59:51 +0000486 if (response_len == 0)
487 {
488 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000489 log->Printf("error: failed to get response for '%*s'", (int) payload_length, payload);
Greg Clayton644247c2011-07-07 01:59:51 +0000490 }
491 return response_len;
Greg Clayton576d8832011-03-22 04:00:09 +0000492}
493
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000494static const char *end_delimiter = "--end--;";
495static const int end_delimiter_len = 8;
496
497std::string
498GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
499( ProcessGDBRemote *process,
500 StringExtractorGDBRemote& profileDataExtractor
501)
502{
503 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
504 std::stringstream final_output;
505 std::string name, value;
506
507 // Going to assuming thread_used_usec comes first, else bail out.
508 while (profileDataExtractor.GetNameColonValue(name, value))
509 {
510 if (name.compare("thread_used_id") == 0)
511 {
512 StringExtractor threadIDHexExtractor(value.c_str());
513 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
514
515 bool has_used_usec = false;
516 uint32_t curr_used_usec = 0;
517 std::string usec_name, usec_value;
518 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
519 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
520 {
521 if (usec_name.compare("thread_used_usec") == 0)
522 {
523 has_used_usec = true;
524 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
525 }
526 else
527 {
528 // We didn't find what we want, it is probably
529 // an older version. Bail out.
530 profileDataExtractor.SetFilePos(input_file_pos);
531 }
532 }
533
534 if (has_used_usec)
535 {
536 uint32_t prev_used_usec = 0;
537 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
538 if (iterator != m_thread_id_to_used_usec_map.end())
539 {
540 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
541 }
542
543 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
544 // A good first time record is one that runs for at least 0.25 sec
545 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
546 bool good_subsequent_time = (prev_used_usec > 0) &&
547 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
548
549 if (good_first_time || good_subsequent_time)
550 {
551 // We try to avoid doing too many index id reservation,
552 // resulting in fast increase of index ids.
553
554 final_output << name << ":";
555 int32_t index_id = process->AssignIndexIDToThread(thread_id);
556 final_output << index_id << ";";
557
558 final_output << usec_name << ":" << usec_value << ";";
559 }
560 else
561 {
562 // Skip past 'thread_used_name'.
563 std::string local_name, local_value;
564 profileDataExtractor.GetNameColonValue(local_name, local_value);
565 }
566
567 // Store current time as previous time so that they can be compared later.
568 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
569 }
570 else
571 {
572 // Bail out and use old string.
573 final_output << name << ":" << value << ";";
574 }
575 }
576 else
577 {
578 final_output << name << ":" << value << ";";
579 }
580 }
581 final_output << end_delimiter;
582 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
583
584 return final_output.str();
585}
586
Greg Clayton576d8832011-03-22 04:00:09 +0000587StateType
588GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
589(
590 ProcessGDBRemote *process,
591 const char *payload,
592 size_t packet_length,
593 StringExtractorGDBRemote &response
594)
595{
Greg Clayton1f5181a2012-07-02 22:05:25 +0000596 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +0000597 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +0000598 if (log)
599 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
600
601 Mutex::Locker locker(m_sequence_mutex);
602 StateType state = eStateRunning;
603
604 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
605 m_public_is_running.SetValue (true, eBroadcastNever);
606 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +0000607 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +0000608 std::string continue_packet(payload, packet_length);
609
Greg Clayton3f875c52013-02-22 22:23:55 +0000610 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +0000611
Greg Clayton576d8832011-03-22 04:00:09 +0000612 while (state == eStateRunning)
613 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000614 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +0000615 {
616 if (log)
617 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +0000618 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) == 0)
Greg Claytonaf247d72011-05-19 03:54:16 +0000619 state = eStateInvalid;
Greg Clayton576d8832011-03-22 04:00:09 +0000620
Greg Claytone889ad62011-10-27 22:04:16 +0000621 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +0000622 }
623
Greg Clayton3f875c52013-02-22 22:23:55 +0000624 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000625
626 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000627 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +0000628
Greg Clayton37a0a242012-04-11 00:24:49 +0000629 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX))
Greg Clayton576d8832011-03-22 04:00:09 +0000630 {
631 if (response.Empty())
632 state = eStateInvalid;
633 else
634 {
635 const char stop_type = response.GetChar();
636 if (log)
637 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
638 switch (stop_type)
639 {
640 case 'T':
641 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +0000642 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000643 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +0000644 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000645 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
646 {
647 lldb::pid_t pid = GetCurrentProcessID ();
648 if (pid != LLDB_INVALID_PROCESS_ID)
649 process->SetID (pid);
650 }
651 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +0000652 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000653
654 // Privately notify any internal threads that we have stopped
655 // in case we wanted to interrupt our process, yet we might
656 // send a packet and continue without returning control to the
657 // user.
658 m_private_is_running.SetValue (false, eBroadcastAlways);
659
660 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
661
Jim Inghambabfc382012-06-06 00:32:39 +0000662 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
663 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +0000664 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000665 // We sent an interrupt packet to stop the inferior process
666 // for an async signal or to send an async packet while running
667 // but we might have been single stepping and received the
668 // stop packet for the step instead of for the interrupt packet.
669 // Typically when an interrupt is sent a SIGINT or SIGSTOP
670 // is used, so if we get anything else, we need to try and
671 // get another stop reply packet that may have been sent
672 // due to sending the interrupt when the target is stopped
673 // which will just re-send a copy of the last stop reply
674 // packet. If we don't do this, then the reply for our
675 // async packet will be the repeat stop reply packet and cause
676 // a lot of trouble for us!
677 if (signo != SIGINT && signo != SIGSTOP)
678 {
Greg Claytonfb72fde2012-05-15 02:50:49 +0000679 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000680
681 // We didn't get a a SIGINT or SIGSTOP, so try for a
682 // very brief time (1 ms) to get another stop reply
683 // packet to make sure it doesn't get in the way
684 StringExtractorGDBRemote extra_stop_reply_packet;
685 uint32_t timeout_usec = 1000;
686 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec))
687 {
688 switch (extra_stop_reply_packet.GetChar())
689 {
690 case 'T':
691 case 'S':
692 // We did get an extra stop reply, which means
693 // our interrupt didn't stop the target so we
694 // shouldn't continue after the async signal
695 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +0000696 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000697 break;
698 }
699 }
700 }
701 }
702
703 if (m_async_signal != -1)
704 {
705 if (log)
706 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
707
708 // Save off the async signal we are supposed to send
709 const int async_signal = m_async_signal;
710 // Clear the async signal member so we don't end up
711 // sending the signal multiple times...
712 m_async_signal = -1;
713 // Check which signal we stopped with
714 if (signo == async_signal)
715 {
716 if (log)
717 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
718
719 // We already stopped with a signal that we wanted
720 // to stop with, so we are done
721 }
722 else
723 {
724 // We stopped with a different signal that the one
725 // we wanted to stop with, so now we must resume
726 // with the signal we want
727 char signal_packet[32];
728 int signal_packet_len = 0;
729 signal_packet_len = ::snprintf (signal_packet,
730 sizeof (signal_packet),
731 "C%2.2x",
732 async_signal);
733
734 if (log)
735 log->Printf ("async: stopped with signal %s, resume with %s",
736 Host::GetSignalAsCString (signo),
737 Host::GetSignalAsCString (async_signal));
738
739 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +0000740 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000741 continue_packet.assign(signal_packet, signal_packet_len);
742 continue;
743 }
744 }
745 else if (m_async_packet_predicate.GetValue())
746 {
Greg Clayton5160ce52013-03-27 23:08:40 +0000747 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +0000748
749 // We are supposed to send an asynchronous packet while
750 // we are running.
751 m_async_response.Clear();
752 if (m_async_packet.empty())
753 {
754 if (packet_log)
755 packet_log->Printf ("async: error: empty async packet");
756
757 }
758 else
759 {
760 if (packet_log)
761 packet_log->Printf ("async: sending packet");
762
763 SendPacketAndWaitForResponse (&m_async_packet[0],
764 m_async_packet.size(),
765 m_async_response,
766 false);
767 }
768 // Let the other thread that was trying to send the async
769 // packet know that the packet has been sent and response is
770 // ready...
771 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
772
773 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +0000774 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +0000775
776 // Set the continue packet to resume if our interrupt
777 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +0000778 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000779 {
Greg Claytonf1186de2012-05-24 23:42:14 +0000780 // Reverting this for now as it is causing deadlocks
781 // in programs (<rdar://problem/11529853>). In the future
782 // we should check our thread list and "do the right thing"
783 // for new threads that show up while we stop and run async
784 // packets. Setting the packet to 'c' to continue all threads
785 // is the right thing to do 99.99% of the time because if a
786 // thread was single stepping, and we sent an interrupt, we
787 // will notice above that we didn't stop due to an interrupt
788 // but stopped due to stepping and we would _not_ continue.
789 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +0000790 continue;
791 }
792 }
793 // Stop with signal and thread info
794 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +0000795 }
Greg Clayton576d8832011-03-22 04:00:09 +0000796 break;
797
798 case 'W':
799 case 'X':
800 // process exited
801 state = eStateExited;
802 break;
803
804 case 'O':
805 // STDOUT
806 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000807 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000808 std::string inferior_stdout;
809 inferior_stdout.reserve(response.GetBytesLeft () / 2);
810 char ch;
811 while ((ch = response.GetHexU8()) != '\0')
812 inferior_stdout.append(1, ch);
813 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
814 }
815 break;
816
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000817 case 'A':
818 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
819 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000820 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000821 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
822 if (m_partial_profile_data.length() > 0)
823 {
824 m_partial_profile_data.append(input);
825 input = m_partial_profile_data;
826 m_partial_profile_data.clear();
827 }
828
829 size_t found, pos = 0, len = input.length();
830 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
831 {
832 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +0000833 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
834 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000835
836 pos = found + end_delimiter_len;
837 }
838
839 if (pos < len)
840 {
841 // Last incomplete chunk.
842 m_partial_profile_data = input.substr(pos);
843 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000844 }
845 break;
846
Greg Clayton576d8832011-03-22 04:00:09 +0000847 case 'E':
848 // ERROR
849 state = eStateInvalid;
850 break;
851
852 default:
853 if (log)
854 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
855 state = eStateInvalid;
856 break;
857 }
858 }
859 }
860 else
861 {
862 if (log)
863 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
864 state = eStateInvalid;
865 }
866 }
867 if (log)
868 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
869 response.SetFilePos(0);
870 m_private_is_running.SetValue (false, eBroadcastAlways);
871 m_public_is_running.SetValue (false, eBroadcastAlways);
872 return state;
873}
874
875bool
876GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
877{
Greg Clayton2687cd12012-03-29 01:55:41 +0000878 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +0000879 m_async_signal = signo;
880 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000881 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +0000882 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000883 return true;
884 m_async_signal = -1;
885 return false;
886}
887
Greg Clayton37a0a242012-04-11 00:24:49 +0000888// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +0000889// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
890// (the expected result), then it will send the halt packet. If it does succeed
891// then the caller that requested the interrupt will want to keep the sequence
892// locked down so that no one else can send packets while the caller has control.
893// This function usually gets called when we are running and need to stop the
894// target. It can also be used when we are running and and we need to do something
895// else (like read/write memory), so we need to interrupt the running process
896// (gdb remote protocol requires this), and do what we need to do, then resume.
897
898bool
Greg Clayton2687cd12012-03-29 01:55:41 +0000899GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +0000900(
901 Mutex::Locker& locker,
902 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +0000903 bool &timed_out
904)
905{
Greg Clayton576d8832011-03-22 04:00:09 +0000906 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +0000907 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +0000908
909 if (IsRunning())
910 {
911 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000912 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +0000913 {
914 if (log)
915 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
916 }
917 else
Greg Clayton576d8832011-03-22 04:00:09 +0000918 {
919 // Someone has the mutex locked waiting for a response or for the
920 // inferior to stop, so send the interrupt on the down low...
921 char ctrl_c = '\x03';
922 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +0000923 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +0000924 if (log)
925 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +0000926 if (bytes_written > 0)
927 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000928 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000929 if (seconds_to_wait_for_stop)
930 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000931 TimeValue timeout;
932 if (seconds_to_wait_for_stop)
933 {
934 timeout = TimeValue::Now();
935 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
936 }
Greg Clayton576d8832011-03-22 04:00:09 +0000937 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
938 {
939 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000940 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +0000941 return true;
942 }
943 else
944 {
945 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000946 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +0000947 }
948 }
949 else
950 {
951 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000952 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +0000953 return true;
954 }
955 }
956 else
957 {
958 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000959 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000960 }
961 return false;
962 }
Greg Clayton576d8832011-03-22 04:00:09 +0000963 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000964 else
965 {
966 if (log)
967 log->Printf ("SendInterrupt () - not running");
968 }
Greg Clayton576d8832011-03-22 04:00:09 +0000969 return true;
970}
971
972lldb::pid_t
973GDBRemoteCommunicationClient::GetCurrentProcessID ()
974{
975 StringExtractorGDBRemote response;
976 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false))
977 {
978 if (response.GetChar() == 'Q')
979 if (response.GetChar() == 'C')
980 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
981 }
982 return LLDB_INVALID_PROCESS_ID;
983}
984
985bool
986GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
987{
988 error_str.clear();
989 StringExtractorGDBRemote response;
990 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false))
991 {
992 if (response.IsOKResponse())
993 return true;
994 if (response.GetChar() == 'E')
995 {
996 // A string the describes what failed when launching...
997 error_str = response.GetStringRef().substr(1);
998 }
999 else
1000 {
1001 error_str.assign ("unknown error occurred launching process");
1002 }
1003 }
1004 else
1005 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001006 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001007 }
1008 return false;
1009}
1010
1011int
Greg Claytonfbb76342013-11-20 21:07:01 +00001012GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001013{
Greg Claytonfbb76342013-11-20 21:07:01 +00001014 // Since we don't get the send argv0 separate from the executable path, we need to
1015 // make sure to use the actual exectuable path found in the launch_info...
1016 std::vector<const char *> argv;
1017 FileSpec exe_file = launch_info.GetExecutableFile();
1018 std::string exe_path;
1019 const char *arg = NULL;
1020 const Args &launch_args = launch_info.GetArguments();
1021 if (exe_file)
1022 exe_path = exe_file.GetPath();
1023 else
1024 {
1025 arg = launch_args.GetArgumentAtIndex(0);
1026 if (arg)
1027 exe_path = arg;
1028 }
1029 if (!exe_path.empty())
1030 {
1031 argv.push_back(exe_path.c_str());
1032 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1033 {
1034 if (arg)
1035 argv.push_back(arg);
1036 }
1037 }
1038 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001039 {
1040 StreamString packet;
1041 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001042 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001043 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001044 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001045 const int arg_len = strlen(arg);
1046 if (i > 0)
1047 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001048 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001049 packet.PutBytesAsRawHex8 (arg, arg_len);
1050 }
1051
1052 StringExtractorGDBRemote response;
1053 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1054 {
1055 if (response.IsOKResponse())
1056 return 0;
1057 uint8_t error = response.GetError();
1058 if (error)
1059 return error;
1060 }
1061 }
1062 return -1;
1063}
1064
1065int
1066GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1067{
1068 if (name_equal_value && name_equal_value[0])
1069 {
1070 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001071 bool send_hex_encoding = false;
1072 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001073 {
Greg Clayton89600582013-10-10 17:53:50 +00001074 if (isprint(*p))
1075 {
1076 switch (*p)
1077 {
1078 case '$':
1079 case '#':
1080 send_hex_encoding = true;
1081 break;
1082 default:
1083 break;
1084 }
1085 }
1086 else
1087 {
1088 // We have non printable characters, lets hex encode this...
1089 send_hex_encoding = true;
1090 }
1091 }
1092
1093 StringExtractorGDBRemote response;
1094 if (send_hex_encoding)
1095 {
1096 if (m_supports_QEnvironmentHexEncoded)
1097 {
1098 packet.PutCString("QEnvironmentHexEncoded:");
1099 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
1100 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1101 {
1102 if (response.IsOKResponse())
1103 return 0;
1104 uint8_t error = response.GetError();
1105 if (error)
1106 return error;
1107 if (response.IsUnsupportedResponse())
1108 m_supports_QEnvironmentHexEncoded = false;
1109 }
1110 }
1111
1112 }
1113 else if (m_supports_QEnvironment)
1114 {
1115 packet.Printf("QEnvironment:%s", name_equal_value);
1116 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1117 {
1118 if (response.IsOKResponse())
1119 return 0;
1120 uint8_t error = response.GetError();
1121 if (error)
1122 return error;
1123 if (response.IsUnsupportedResponse())
1124 m_supports_QEnvironment = false;
1125 }
Greg Clayton576d8832011-03-22 04:00:09 +00001126 }
1127 }
1128 return -1;
1129}
1130
Greg Claytonc4103b32011-05-08 04:53:50 +00001131int
1132GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1133{
1134 if (arch && arch[0])
1135 {
1136 StreamString packet;
1137 packet.Printf("QLaunchArch:%s", arch);
1138 StringExtractorGDBRemote response;
1139 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1140 {
1141 if (response.IsOKResponse())
1142 return 0;
1143 uint8_t error = response.GetError();
1144 if (error)
1145 return error;
1146 }
1147 }
1148 return -1;
1149}
1150
Greg Clayton576d8832011-03-22 04:00:09 +00001151bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001152GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1153 uint32_t &minor,
1154 uint32_t &update)
1155{
1156 if (GetHostInfo ())
1157 {
1158 if (m_os_version_major != UINT32_MAX)
1159 {
1160 major = m_os_version_major;
1161 minor = m_os_version_minor;
1162 update = m_os_version_update;
1163 return true;
1164 }
1165 }
1166 return false;
1167}
1168
1169bool
1170GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1171{
1172 if (GetHostInfo ())
1173 {
1174 if (!m_os_build.empty())
1175 {
1176 s = m_os_build;
1177 return true;
1178 }
1179 }
1180 s.clear();
1181 return false;
1182}
1183
1184
1185bool
1186GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1187{
1188 if (GetHostInfo ())
1189 {
1190 if (!m_os_kernel.empty())
1191 {
1192 s = m_os_kernel;
1193 return true;
1194 }
1195 }
1196 s.clear();
1197 return false;
1198}
1199
1200bool
1201GDBRemoteCommunicationClient::GetHostname (std::string &s)
1202{
1203 if (GetHostInfo ())
1204 {
1205 if (!m_hostname.empty())
1206 {
1207 s = m_hostname;
1208 return true;
1209 }
1210 }
1211 s.clear();
1212 return false;
1213}
1214
1215ArchSpec
1216GDBRemoteCommunicationClient::GetSystemArchitecture ()
1217{
1218 if (GetHostInfo ())
1219 return m_host_arch;
1220 return ArchSpec();
1221}
1222
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001223const lldb_private::ArchSpec &
1224GDBRemoteCommunicationClient::GetProcessArchitecture ()
1225{
1226 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1227 GetCurrentProcessInfo ();
1228 return m_process_arch;
1229}
1230
Greg Clayton1cb64962011-03-24 04:28:38 +00001231
1232bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001233GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001234{
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001235 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001236 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001237 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001238 StringExtractorGDBRemote response;
1239 if (SendPacketAndWaitForResponse ("qHostInfo", response, false))
1240 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001241 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001242 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001243 std::string name;
1244 std::string value;
1245 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1246 uint32_t sub = 0;
1247 std::string arch_name;
1248 std::string os_name;
1249 std::string vendor_name;
1250 std::string triple;
1251 uint32_t pointer_byte_size = 0;
1252 StringExtractor extractor;
1253 ByteOrder byte_order = eByteOrderInvalid;
1254 uint32_t num_keys_decoded = 0;
1255 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001256 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001257 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001258 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001259 // exception type in big endian hex
1260 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1261 if (cpu != LLDB_INVALID_CPUTYPE)
1262 ++num_keys_decoded;
1263 }
1264 else if (name.compare("cpusubtype") == 0)
1265 {
1266 // exception count in big endian hex
1267 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
1268 if (sub != 0)
1269 ++num_keys_decoded;
1270 }
1271 else if (name.compare("arch") == 0)
1272 {
1273 arch_name.swap (value);
1274 ++num_keys_decoded;
1275 }
1276 else if (name.compare("triple") == 0)
1277 {
1278 // The triple comes as ASCII hex bytes since it contains '-' chars
1279 extractor.GetStringRef().swap(value);
1280 extractor.SetFilePos(0);
1281 extractor.GetHexByteString (triple);
1282 ++num_keys_decoded;
1283 }
1284 else if (name.compare("os_build") == 0)
1285 {
1286 extractor.GetStringRef().swap(value);
1287 extractor.SetFilePos(0);
1288 extractor.GetHexByteString (m_os_build);
1289 ++num_keys_decoded;
1290 }
1291 else if (name.compare("hostname") == 0)
1292 {
1293 extractor.GetStringRef().swap(value);
1294 extractor.SetFilePos(0);
1295 extractor.GetHexByteString (m_hostname);
1296 ++num_keys_decoded;
1297 }
1298 else if (name.compare("os_kernel") == 0)
1299 {
1300 extractor.GetStringRef().swap(value);
1301 extractor.SetFilePos(0);
1302 extractor.GetHexByteString (m_os_kernel);
1303 ++num_keys_decoded;
1304 }
1305 else if (name.compare("ostype") == 0)
1306 {
1307 os_name.swap (value);
1308 ++num_keys_decoded;
1309 }
1310 else if (name.compare("vendor") == 0)
1311 {
1312 vendor_name.swap(value);
1313 ++num_keys_decoded;
1314 }
1315 else if (name.compare("endian") == 0)
1316 {
1317 ++num_keys_decoded;
1318 if (value.compare("little") == 0)
1319 byte_order = eByteOrderLittle;
1320 else if (value.compare("big") == 0)
1321 byte_order = eByteOrderBig;
1322 else if (value.compare("pdp") == 0)
1323 byte_order = eByteOrderPDP;
1324 else
1325 --num_keys_decoded;
1326 }
1327 else if (name.compare("ptrsize") == 0)
1328 {
1329 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1330 if (pointer_byte_size != 0)
1331 ++num_keys_decoded;
1332 }
1333 else if (name.compare("os_version") == 0)
1334 {
1335 Args::StringToVersion (value.c_str(),
1336 m_os_version_major,
1337 m_os_version_minor,
1338 m_os_version_update);
1339 if (m_os_version_major != UINT32_MAX)
1340 ++num_keys_decoded;
1341 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001342 else if (name.compare("watchpoint_exceptions_received") == 0)
1343 {
1344 ++num_keys_decoded;
1345 if (strcmp(value.c_str(),"before") == 0)
1346 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1347 else if (strcmp(value.c_str(),"after") == 0)
1348 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1349 else
1350 --num_keys_decoded;
1351 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001352 else if (name.compare("default_packet_timeout") == 0)
1353 {
1354 m_default_packet_timeout = Args::StringToUInt32(value.c_str(), 0);
1355 if (m_default_packet_timeout > 0)
1356 {
1357 SetPacketTimeout(m_default_packet_timeout);
1358 ++num_keys_decoded;
1359 }
1360 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001361
Greg Clayton32e0a752011-03-30 18:16:51 +00001362 }
1363
1364 if (num_keys_decoded > 0)
1365 m_qHostInfo_is_valid = eLazyBoolYes;
1366
1367 if (triple.empty())
1368 {
1369 if (arch_name.empty())
1370 {
1371 if (cpu != LLDB_INVALID_CPUTYPE)
1372 {
1373 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1374 if (pointer_byte_size)
1375 {
1376 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1377 }
1378 if (byte_order != eByteOrderInvalid)
1379 {
1380 assert (byte_order == m_host_arch.GetByteOrder());
1381 }
Greg Clayton70512312012-05-08 01:45:38 +00001382
1383 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1384 {
1385 switch (m_host_arch.GetMachine())
1386 {
1387 case llvm::Triple::arm:
1388 case llvm::Triple::thumb:
1389 os_name = "ios";
1390 break;
1391 default:
1392 os_name = "macosx";
1393 break;
1394 }
1395 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001396 if (!vendor_name.empty())
1397 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1398 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001399 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001400
1401 }
1402 }
1403 else
1404 {
1405 std::string triple;
1406 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001407 if (!vendor_name.empty() || !os_name.empty())
1408 {
1409 triple += '-';
1410 if (vendor_name.empty())
1411 triple += "unknown";
1412 else
1413 triple += vendor_name;
1414 triple += '-';
1415 if (os_name.empty())
1416 triple += "unknown";
1417 else
1418 triple += os_name;
1419 }
1420 m_host_arch.SetTriple (triple.c_str());
1421
1422 llvm::Triple &host_triple = m_host_arch.GetTriple();
1423 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1424 {
1425 switch (m_host_arch.GetMachine())
1426 {
1427 case llvm::Triple::arm:
1428 case llvm::Triple::thumb:
1429 host_triple.setOS(llvm::Triple::IOS);
1430 break;
1431 default:
1432 host_triple.setOS(llvm::Triple::MacOSX);
1433 break;
1434 }
1435 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001436 if (pointer_byte_size)
1437 {
1438 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1439 }
1440 if (byte_order != eByteOrderInvalid)
1441 {
1442 assert (byte_order == m_host_arch.GetByteOrder());
1443 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001444
Greg Clayton1cb64962011-03-24 04:28:38 +00001445 }
1446 }
1447 else
1448 {
Greg Clayton70512312012-05-08 01:45:38 +00001449 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001450 if (pointer_byte_size)
1451 {
1452 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1453 }
1454 if (byte_order != eByteOrderInvalid)
1455 {
1456 assert (byte_order == m_host_arch.GetByteOrder());
1457 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001458 }
Greg Claytond314e812011-03-23 00:09:55 +00001459 }
Greg Clayton576d8832011-03-22 04:00:09 +00001460 }
1461 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001462 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001463}
1464
1465int
1466GDBRemoteCommunicationClient::SendAttach
1467(
1468 lldb::pid_t pid,
1469 StringExtractorGDBRemote& response
1470)
1471{
1472 if (pid != LLDB_INVALID_PROCESS_ID)
1473 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001474 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001475 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001476 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00001477 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton576d8832011-03-22 04:00:09 +00001478 {
1479 if (response.IsErrorResponse())
1480 return response.GetError();
1481 return 0;
1482 }
1483 }
1484 return -1;
1485}
1486
1487const lldb_private::ArchSpec &
1488GDBRemoteCommunicationClient::GetHostArchitecture ()
1489{
Greg Clayton32e0a752011-03-30 18:16:51 +00001490 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001491 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001492 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001493}
1494
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001495uint32_t
1496GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1497{
1498 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1499 GetHostInfo ();
1500 return m_default_packet_timeout;
1501}
1502
Greg Clayton576d8832011-03-22 04:00:09 +00001503addr_t
1504GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1505{
Greg Clayton70b57652011-05-15 01:25:55 +00001506 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001507 {
Greg Clayton70b57652011-05-15 01:25:55 +00001508 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001509 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001510 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001511 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001512 permissions & lldb::ePermissionsReadable ? "r" : "",
1513 permissions & lldb::ePermissionsWritable ? "w" : "",
1514 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001515 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001516 StringExtractorGDBRemote response;
1517 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1518 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001519 if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001520 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1521 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001522 else
1523 {
1524 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1525 }
Greg Clayton576d8832011-03-22 04:00:09 +00001526 }
1527 return LLDB_INVALID_ADDRESS;
1528}
1529
1530bool
1531GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1532{
Greg Clayton70b57652011-05-15 01:25:55 +00001533 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001534 {
Greg Clayton70b57652011-05-15 01:25:55 +00001535 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001536 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001537 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001538 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001539 StringExtractorGDBRemote response;
1540 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1541 {
1542 if (response.IsOKResponse())
1543 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001544 }
1545 else
1546 {
1547 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00001548 }
Greg Clayton576d8832011-03-22 04:00:09 +00001549 }
1550 return false;
1551}
1552
Jim Inghamacff8952013-05-02 00:27:30 +00001553Error
1554GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00001555{
Jim Inghamacff8952013-05-02 00:27:30 +00001556 Error error;
1557
1558 if (keep_stopped)
1559 {
1560 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1561 {
1562 char packet[64];
1563 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001564 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00001565 StringExtractorGDBRemote response;
1566 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1567 {
1568 m_supports_detach_stay_stopped = eLazyBoolYes;
1569 }
1570 else
1571 {
1572 m_supports_detach_stay_stopped = eLazyBoolNo;
1573 }
1574 }
1575
1576 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1577 {
1578 error.SetErrorString("Stays stopped not supported by this target.");
1579 return error;
1580 }
1581 else
1582 {
1583 size_t num_sent = SendPacket ("D1", 2);
1584 if (num_sent == 0)
1585 error.SetErrorString ("Sending extended disconnect packet failed.");
1586 }
1587 }
1588 else
1589 {
1590 size_t num_sent = SendPacket ("D", 1);
1591 if (num_sent == 0)
1592 error.SetErrorString ("Sending disconnect packet failed.");
1593 }
1594 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001595}
1596
Greg Clayton46fb5582011-11-18 07:03:08 +00001597Error
1598GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1599 lldb_private::MemoryRegionInfo &region_info)
1600{
1601 Error error;
1602 region_info.Clear();
1603
1604 if (m_supports_memory_region_info != eLazyBoolNo)
1605 {
1606 m_supports_memory_region_info = eLazyBoolYes;
1607 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001608 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001609 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00001610 StringExtractorGDBRemote response;
1611 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1612 {
1613 std::string name;
1614 std::string value;
1615 addr_t addr_value;
1616 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00001617 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00001618 while (success && response.GetNameColonValue(name, value))
1619 {
1620 if (name.compare ("start") == 0)
1621 {
1622 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1623 if (success)
1624 region_info.GetRange().SetRangeBase(addr_value);
1625 }
1626 else if (name.compare ("size") == 0)
1627 {
1628 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1629 if (success)
1630 region_info.GetRange().SetByteSize (addr_value);
1631 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001632 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00001633 {
Jason Molendacb349ee2011-12-13 05:39:38 +00001634 saw_permissions = true;
1635 if (region_info.GetRange().Contains (addr))
1636 {
1637 if (value.find('r') != std::string::npos)
1638 region_info.SetReadable (MemoryRegionInfo::eYes);
1639 else
1640 region_info.SetReadable (MemoryRegionInfo::eNo);
1641
1642 if (value.find('w') != std::string::npos)
1643 region_info.SetWritable (MemoryRegionInfo::eYes);
1644 else
1645 region_info.SetWritable (MemoryRegionInfo::eNo);
1646
1647 if (value.find('x') != std::string::npos)
1648 region_info.SetExecutable (MemoryRegionInfo::eYes);
1649 else
1650 region_info.SetExecutable (MemoryRegionInfo::eNo);
1651 }
1652 else
1653 {
1654 // The reported region does not contain this address -- we're looking at an unmapped page
1655 region_info.SetReadable (MemoryRegionInfo::eNo);
1656 region_info.SetWritable (MemoryRegionInfo::eNo);
1657 region_info.SetExecutable (MemoryRegionInfo::eNo);
1658 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001659 }
1660 else if (name.compare ("error") == 0)
1661 {
1662 StringExtractorGDBRemote name_extractor;
1663 // Swap "value" over into "name_extractor"
1664 name_extractor.GetStringRef().swap(value);
1665 // Now convert the HEX bytes into a string value
1666 name_extractor.GetHexByteString (value);
1667 error.SetErrorString(value.c_str());
1668 }
1669 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001670
1671 // We got a valid address range back but no permissions -- which means this is an unmapped page
1672 if (region_info.GetRange().IsValid() && saw_permissions == false)
1673 {
1674 region_info.SetReadable (MemoryRegionInfo::eNo);
1675 region_info.SetWritable (MemoryRegionInfo::eNo);
1676 region_info.SetExecutable (MemoryRegionInfo::eNo);
1677 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001678 }
1679 else
1680 {
1681 m_supports_memory_region_info = eLazyBoolNo;
1682 }
1683 }
1684
1685 if (m_supports_memory_region_info == eLazyBoolNo)
1686 {
1687 error.SetErrorString("qMemoryRegionInfo is not supported");
1688 }
1689 if (error.Fail())
1690 region_info.Clear();
1691 return error;
1692
1693}
1694
Johnny Chen64637202012-05-23 21:09:52 +00001695Error
1696GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1697{
1698 Error error;
1699
1700 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1701 {
1702 num = m_num_supported_hardware_watchpoints;
1703 return error;
1704 }
1705
1706 // Set num to 0 first.
1707 num = 0;
1708 if (m_supports_watchpoint_support_info != eLazyBoolNo)
1709 {
1710 char packet[64];
1711 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001712 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00001713 StringExtractorGDBRemote response;
1714 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1715 {
1716 m_supports_watchpoint_support_info = eLazyBoolYes;
1717 std::string name;
1718 std::string value;
1719 while (response.GetNameColonValue(name, value))
1720 {
1721 if (name.compare ("num") == 0)
1722 {
1723 num = Args::StringToUInt32(value.c_str(), 0, 0);
1724 m_num_supported_hardware_watchpoints = num;
1725 }
1726 }
1727 }
1728 else
1729 {
1730 m_supports_watchpoint_support_info = eLazyBoolNo;
1731 }
1732 }
1733
1734 if (m_supports_watchpoint_support_info == eLazyBoolNo)
1735 {
1736 error.SetErrorString("qWatchpointSupportInfo is not supported");
1737 }
1738 return error;
1739
1740}
Greg Clayton46fb5582011-11-18 07:03:08 +00001741
Enrico Granataf04a2192012-07-13 23:18:48 +00001742lldb_private::Error
1743GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
1744{
1745 Error error(GetWatchpointSupportInfo(num));
1746 if (error.Success())
1747 error = GetWatchpointsTriggerAfterInstruction(after);
1748 return error;
1749}
1750
1751lldb_private::Error
1752GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
1753{
1754 Error error;
1755
1756 // we assume watchpoints will happen after running the relevant opcode
1757 // and we only want to override this behavior if we have explicitly
1758 // received a qHostInfo telling us otherwise
1759 if (m_qHostInfo_is_valid != eLazyBoolYes)
1760 after = true;
1761 else
1762 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1763 return error;
1764}
1765
Greg Clayton576d8832011-03-22 04:00:09 +00001766int
1767GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1768{
1769 if (path && path[0])
1770 {
1771 StreamString packet;
1772 packet.PutCString("QSetSTDIN:");
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::SetSTDOUT (char const *path)
1790{
1791 if (path && path[0])
1792 {
1793 StreamString packet;
1794 packet.PutCString("QSetSTDOUT:");
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::SetSTDERR (char const *path)
1812{
1813 if (path && path[0])
1814 {
1815 StreamString packet;
1816 packet.PutCString("QSetSTDERR:");
1817 packet.PutBytesAsRawHex8(path, strlen(path));
1818
1819 StringExtractorGDBRemote response;
1820 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1821 {
1822 if (response.IsOKResponse())
1823 return 0;
1824 uint8_t error = response.GetError();
1825 if (error)
1826 return error;
1827 }
1828 }
1829 return -1;
1830}
1831
Greg Claytonfbb76342013-11-20 21:07:01 +00001832bool
1833GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd)
1834{
1835 StringExtractorGDBRemote response;
1836 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false))
1837 {
1838 if (response.IsUnsupportedResponse())
1839 return false;
1840 if (response.IsErrorResponse())
1841 return false;
1842 response.GetHexByteString (cwd);
1843 return !cwd.empty();
1844 }
1845 return false;
1846}
1847
Greg Clayton576d8832011-03-22 04:00:09 +00001848int
1849GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
1850{
1851 if (path && path[0])
1852 {
1853 StreamString packet;
1854 packet.PutCString("QSetWorkingDir:");
1855 packet.PutBytesAsRawHex8(path, strlen(path));
1856
1857 StringExtractorGDBRemote response;
1858 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1859 {
1860 if (response.IsOKResponse())
1861 return 0;
1862 uint8_t error = response.GetError();
1863 if (error)
1864 return error;
1865 }
1866 }
1867 return -1;
1868}
1869
1870int
1871GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1872{
Greg Clayton32e0a752011-03-30 18:16:51 +00001873 char packet[32];
1874 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00001875 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00001876 StringExtractorGDBRemote response;
Greg Clayton32e0a752011-03-30 18:16:51 +00001877 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton576d8832011-03-22 04:00:09 +00001878 {
1879 if (response.IsOKResponse())
1880 return 0;
1881 uint8_t error = response.GetError();
1882 if (error)
1883 return error;
1884 }
1885 return -1;
1886}
Greg Clayton32e0a752011-03-30 18:16:51 +00001887
1888bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001889GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00001890{
1891 if (response.IsNormalResponse())
1892 {
1893 std::string name;
1894 std::string value;
1895 StringExtractor extractor;
1896
1897 while (response.GetNameColonValue(name, value))
1898 {
1899 if (name.compare("pid") == 0)
1900 {
1901 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1902 }
1903 else if (name.compare("ppid") == 0)
1904 {
1905 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1906 }
1907 else if (name.compare("uid") == 0)
1908 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001909 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00001910 }
1911 else if (name.compare("euid") == 0)
1912 {
1913 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1914 }
1915 else if (name.compare("gid") == 0)
1916 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001917 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00001918 }
1919 else if (name.compare("egid") == 0)
1920 {
1921 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1922 }
1923 else if (name.compare("triple") == 0)
1924 {
1925 // The triple comes as ASCII hex bytes since it contains '-' chars
1926 extractor.GetStringRef().swap(value);
1927 extractor.SetFilePos(0);
1928 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00001929 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00001930 }
1931 else if (name.compare("name") == 0)
1932 {
1933 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00001934 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00001935 // control the characters in a process name
1936 extractor.GetStringRef().swap(value);
1937 extractor.SetFilePos(0);
1938 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00001939 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00001940 }
1941 }
1942
1943 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1944 return true;
1945 }
1946 return false;
1947}
1948
1949bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001950GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00001951{
1952 process_info.Clear();
1953
1954 if (m_supports_qProcessInfoPID)
1955 {
1956 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00001957 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001958 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00001959 StringExtractorGDBRemote response;
1960 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1961 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001962 return DecodeProcessInfoResponse (response, process_info);
1963 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001964 else
1965 {
1966 m_supports_qProcessInfoPID = false;
1967 return false;
1968 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001969 }
1970 return false;
1971}
1972
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001973bool
1974GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
1975{
1976 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1977 return true;
1978 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1979 return false;
1980
1981 GetHostInfo ();
1982
1983 StringExtractorGDBRemote response;
1984 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false))
1985 {
1986 if (response.IsNormalResponse())
1987 {
1988 std::string name;
1989 std::string value;
1990 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1991 uint32_t sub = 0;
1992 std::string arch_name;
1993 std::string os_name;
1994 std::string vendor_name;
1995 std::string triple;
1996 uint32_t pointer_byte_size = 0;
1997 StringExtractor extractor;
1998 ByteOrder byte_order = eByteOrderInvalid;
1999 uint32_t num_keys_decoded = 0;
2000 while (response.GetNameColonValue(name, value))
2001 {
2002 if (name.compare("cputype") == 0)
2003 {
2004 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2005 if (cpu != LLDB_INVALID_CPUTYPE)
2006 ++num_keys_decoded;
2007 }
2008 else if (name.compare("cpusubtype") == 0)
2009 {
2010 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2011 if (sub != 0)
2012 ++num_keys_decoded;
2013 }
2014 else if (name.compare("ostype") == 0)
2015 {
2016 os_name.swap (value);
2017 ++num_keys_decoded;
2018 }
2019 else if (name.compare("vendor") == 0)
2020 {
2021 vendor_name.swap(value);
2022 ++num_keys_decoded;
2023 }
2024 else if (name.compare("endian") == 0)
2025 {
2026 ++num_keys_decoded;
2027 if (value.compare("little") == 0)
2028 byte_order = eByteOrderLittle;
2029 else if (value.compare("big") == 0)
2030 byte_order = eByteOrderBig;
2031 else if (value.compare("pdp") == 0)
2032 byte_order = eByteOrderPDP;
2033 else
2034 --num_keys_decoded;
2035 }
2036 else if (name.compare("ptrsize") == 0)
2037 {
2038 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
2039 if (pointer_byte_size != 0)
2040 ++num_keys_decoded;
2041 }
2042 }
2043 if (num_keys_decoded > 0)
2044 m_qProcessInfo_is_valid = eLazyBoolYes;
2045 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
2046 {
2047 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2048 if (pointer_byte_size)
2049 {
2050 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2051 }
2052 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2053 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2054 return true;
2055 }
2056 }
2057 }
2058 else
2059 {
2060 m_qProcessInfo_is_valid = eLazyBoolNo;
2061 }
2062
2063 return false;
2064}
2065
2066
Greg Clayton32e0a752011-03-30 18:16:51 +00002067uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002068GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2069 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002070{
2071 process_infos.Clear();
2072
2073 if (m_supports_qfProcessInfo)
2074 {
2075 StreamString packet;
2076 packet.PutCString ("qfProcessInfo");
2077 if (!match_info.MatchAllProcesses())
2078 {
2079 packet.PutChar (':');
2080 const char *name = match_info.GetProcessInfo().GetName();
2081 bool has_name_match = false;
2082 if (name && name[0])
2083 {
2084 has_name_match = true;
2085 NameMatchType name_match_type = match_info.GetNameMatchType();
2086 switch (name_match_type)
2087 {
2088 case eNameMatchIgnore:
2089 has_name_match = false;
2090 break;
2091
2092 case eNameMatchEquals:
2093 packet.PutCString ("name_match:equals;");
2094 break;
2095
2096 case eNameMatchContains:
2097 packet.PutCString ("name_match:contains;");
2098 break;
2099
2100 case eNameMatchStartsWith:
2101 packet.PutCString ("name_match:starts_with;");
2102 break;
2103
2104 case eNameMatchEndsWith:
2105 packet.PutCString ("name_match:ends_with;");
2106 break;
2107
2108 case eNameMatchRegularExpression:
2109 packet.PutCString ("name_match:regex;");
2110 break;
2111 }
2112 if (has_name_match)
2113 {
2114 packet.PutCString ("name:");
2115 packet.PutBytesAsRawHex8(name, ::strlen(name));
2116 packet.PutChar (';');
2117 }
2118 }
2119
2120 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002121 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002122 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002123 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002124 if (match_info.GetProcessInfo().UserIDIsValid())
2125 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2126 if (match_info.GetProcessInfo().GroupIDIsValid())
2127 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002128 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2129 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2130 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2131 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2132 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2133 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2134 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2135 {
2136 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2137 const llvm::Triple &triple = match_arch.GetTriple();
2138 packet.PutCString("triple:");
2139 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
2140 packet.PutChar (';');
2141 }
2142 }
2143 StringExtractorGDBRemote response;
2144 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
2145 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002146 do
2147 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002148 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002149 if (!DecodeProcessInfoResponse (response, process_info))
2150 break;
2151 process_infos.Append(process_info);
2152 response.GetStringRef().clear();
2153 response.SetFilePos(0);
2154 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false));
2155 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002156 else
2157 {
2158 m_supports_qfProcessInfo = false;
2159 return 0;
2160 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002161 }
2162 return process_infos.GetSize();
2163
2164}
2165
2166bool
2167GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2168{
2169 if (m_supports_qUserName)
2170 {
2171 char packet[32];
2172 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002173 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002174 StringExtractorGDBRemote response;
2175 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2176 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002177 if (response.IsNormalResponse())
2178 {
2179 // Make sure we parsed the right number of characters. The response is
2180 // the hex encoded user name and should make up the entire packet.
2181 // If there are any non-hex ASCII bytes, the length won't match below..
2182 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2183 return true;
2184 }
2185 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002186 else
2187 {
2188 m_supports_qUserName = false;
2189 return false;
2190 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002191 }
2192 return false;
2193
2194}
2195
2196bool
2197GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2198{
2199 if (m_supports_qGroupName)
2200 {
2201 char packet[32];
2202 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002203 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002204 StringExtractorGDBRemote response;
2205 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2206 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002207 if (response.IsNormalResponse())
2208 {
2209 // Make sure we parsed the right number of characters. The response is
2210 // the hex encoded group name and should make up the entire packet.
2211 // If there are any non-hex ASCII bytes, the length won't match below..
2212 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2213 return true;
2214 }
2215 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002216 else
2217 {
2218 m_supports_qGroupName = false;
2219 return false;
2220 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002221 }
2222 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002223}
Greg Clayton32e0a752011-03-30 18:16:51 +00002224
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002225void
2226GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2227{
2228 uint32_t i;
2229 TimeValue start_time, end_time;
2230 uint64_t total_time_nsec;
2231 float packets_per_second;
2232 if (SendSpeedTestPacket (0, 0))
2233 {
2234 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2)
2235 {
2236 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2)
2237 {
2238 start_time = TimeValue::Now();
2239 for (i=0; i<num_packets; ++i)
2240 {
2241 SendSpeedTestPacket (send_size, recv_size);
2242 }
2243 end_time = TimeValue::Now();
2244 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002245 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Daniel Malead01b2952012-11-29 21:49:15 +00002246 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 +00002247 num_packets,
2248 send_size,
2249 recv_size,
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002250 total_time_nsec / TimeValue::NanoSecPerSec,
2251 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002252 packets_per_second);
2253 if (recv_size == 0)
2254 recv_size = 32;
2255 }
2256 if (send_size == 0)
2257 send_size = 32;
2258 }
2259 }
2260 else
2261 {
2262 start_time = TimeValue::Now();
2263 for (i=0; i<num_packets; ++i)
2264 {
2265 GetCurrentProcessID ();
2266 }
2267 end_time = TimeValue::Now();
2268 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002269 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Daniel Malead01b2952012-11-29 21:49:15 +00002270 printf ("%u 'qC' packets packets in 0x%" PRIu64 "%9.9" PRIu64 " sec for %f packets/sec.\n",
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002271 num_packets,
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002272 total_time_nsec / TimeValue::NanoSecPerSec,
2273 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002274 packets_per_second);
2275 }
2276}
2277
2278bool
2279GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2280{
2281 StreamString packet;
2282 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2283 uint32_t bytes_left = send_size;
2284 while (bytes_left > 0)
2285 {
2286 if (bytes_left >= 26)
2287 {
2288 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2289 bytes_left -= 26;
2290 }
2291 else
2292 {
2293 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2294 bytes_left = 0;
2295 }
2296 }
2297
2298 StringExtractorGDBRemote response;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002299 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) > 0;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002300 return false;
Greg Clayton32e0a752011-03-30 18:16:51 +00002301}
Greg Clayton8b82f082011-04-12 05:54:46 +00002302
2303uint16_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002304GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002305{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002306 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00002307 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002308 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00002309 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002310 std::string hostname;
2311 if (Host::GetHostname (hostname))
2312 {
2313 // Make the GDB server we launch only accept connections from this host
2314 stream.Printf("host:%s;", hostname.c_str());
2315 }
2316 else
2317 {
2318 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2319 stream.Printf("host:*;");
2320 }
2321 const char *packet = stream.GetData();
2322 int packet_len = stream.GetSize();
2323
2324 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
Greg Clayton8b82f082011-04-12 05:54:46 +00002325 {
2326 std::string name;
2327 std::string value;
2328 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002329 while (response.GetNameColonValue(name, value))
2330 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00002331 if (name.compare("port") == 0)
Greg Clayton8b82f082011-04-12 05:54:46 +00002332 port = Args::StringToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002333 else if (name.compare("pid") == 0)
2334 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00002335 }
2336 return port;
2337 }
2338 return 0;
2339}
2340
2341bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00002342GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2343{
2344 StreamString stream;
2345 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2346 const char *packet = stream.GetData();
2347 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00002348
Daniel Maleae0f8f572013-08-26 23:57:52 +00002349 StringExtractorGDBRemote response;
2350 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2351 {
2352 if (response.IsOKResponse())
2353 return true;
2354 }
2355 return false;
2356}
2357
2358bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002359GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002360{
2361 if (m_curr_tid == tid)
2362 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002363
Greg Clayton8b82f082011-04-12 05:54:46 +00002364 char packet[32];
2365 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002366 if (tid == UINT64_MAX)
2367 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002368 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002369 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002370 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002371 StringExtractorGDBRemote response;
2372 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2373 {
2374 if (response.IsOKResponse())
2375 {
2376 m_curr_tid = tid;
2377 return true;
2378 }
2379 }
2380 return false;
2381}
2382
2383bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002384GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002385{
2386 if (m_curr_tid_run == tid)
2387 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002388
Greg Clayton8b82f082011-04-12 05:54:46 +00002389 char packet[32];
2390 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002391 if (tid == UINT64_MAX)
2392 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002393 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002394 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2395
Andy Gibbsa297a972013-06-19 19:04:53 +00002396 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002397 StringExtractorGDBRemote response;
2398 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2399 {
2400 if (response.IsOKResponse())
2401 {
2402 m_curr_tid_run = tid;
2403 return true;
2404 }
2405 }
2406 return false;
2407}
2408
2409bool
2410GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2411{
2412 if (SendPacketAndWaitForResponse("?", 1, response, false))
2413 return response.IsNormalResponse();
2414 return false;
2415}
2416
2417bool
Greg Claytonf402f782012-10-13 02:11:55 +00002418GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00002419{
2420 if (m_supports_qThreadStopInfo)
2421 {
2422 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00002423 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002424 assert (packet_len < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002425 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2426 {
Greg Claytonef8180a2013-10-15 00:14:28 +00002427 if (response.IsUnsupportedResponse())
2428 m_supports_qThreadStopInfo = false;
2429 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002430 return true;
2431 else
2432 return false;
2433 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002434 else
2435 {
2436 m_supports_qThreadStopInfo = false;
2437 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002438 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002439 return false;
2440}
2441
2442
2443uint8_t
2444GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2445{
2446 switch (type)
2447 {
2448 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break;
2449 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break;
2450 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break;
2451 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break;
2452 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break;
Greg Clayton8b82f082011-04-12 05:54:46 +00002453 }
2454
2455 char packet[64];
2456 const int packet_len = ::snprintf (packet,
2457 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00002458 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00002459 insert ? 'Z' : 'z',
2460 type,
2461 addr,
2462 length);
2463
Andy Gibbsa297a972013-06-19 19:04:53 +00002464 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002465 StringExtractorGDBRemote response;
2466 if (SendPacketAndWaitForResponse(packet, packet_len, response, true))
2467 {
2468 if (response.IsOKResponse())
2469 return 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002470 else if (response.IsErrorResponse())
2471 return response.GetError();
2472 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002473 else
2474 {
2475 switch (type)
2476 {
2477 case eBreakpointSoftware: m_supports_z0 = false; break;
2478 case eBreakpointHardware: m_supports_z1 = false; break;
2479 case eWatchpointWrite: m_supports_z2 = false; break;
2480 case eWatchpointRead: m_supports_z3 = false; break;
2481 case eWatchpointReadWrite: m_supports_z4 = false; break;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002482 }
2483 }
2484
Greg Clayton8b82f082011-04-12 05:54:46 +00002485 return UINT8_MAX;
2486}
Greg Claytonadc00cb2011-05-20 23:38:13 +00002487
2488size_t
2489GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2490 bool &sequence_mutex_unavailable)
2491{
2492 Mutex::Locker locker;
2493 thread_ids.clear();
2494
Jim Ingham4ceb9282012-06-08 22:50:40 +00002495 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002496 {
2497 sequence_mutex_unavailable = false;
2498 StringExtractorGDBRemote response;
2499
Greg Clayton73bf5db2011-06-17 01:22:15 +00002500 for (SendPacketNoLock ("qfThreadInfo", strlen("qfThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
Greg Claytonadc00cb2011-05-20 23:38:13 +00002501 response.IsNormalResponse();
Greg Clayton73bf5db2011-06-17 01:22:15 +00002502 SendPacketNoLock ("qsThreadInfo", strlen("qsThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ()))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002503 {
2504 char ch = response.GetChar();
2505 if (ch == 'l')
2506 break;
2507 if (ch == 'm')
2508 {
2509 do
2510 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00002511 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00002512
2513 if (tid != LLDB_INVALID_THREAD_ID)
2514 {
2515 thread_ids.push_back (tid);
2516 }
2517 ch = response.GetChar(); // Skip the command separator
2518 } while (ch == ','); // Make sure we got a comma separator
2519 }
2520 }
2521 }
2522 else
2523 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00002524#if defined (LLDB_CONFIGURATION_DEBUG)
2525 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2526#else
Greg Clayton5160ce52013-03-27 23:08:40 +00002527 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00002528 if (log)
2529 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00002530#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00002531 sequence_mutex_unavailable = true;
2532 }
2533 return thread_ids.size();
2534}
Greg Clayton37a0a242012-04-11 00:24:49 +00002535
2536lldb::addr_t
2537GDBRemoteCommunicationClient::GetShlibInfoAddr()
2538{
2539 if (!IsRunning())
2540 {
2541 StringExtractorGDBRemote response;
2542 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
2543 {
2544 if (response.IsNormalResponse())
2545 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2546 }
2547 }
2548 return LLDB_INVALID_ADDRESS;
2549}
2550
Daniel Maleae0f8f572013-08-26 23:57:52 +00002551lldb_private::Error
2552GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL
2553 const char *working_dir, // Pass NULL to use the current working directory
2554 int *status_ptr, // Pass NULL if you don't want the process exit status
2555 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
2556 std::string *command_output, // Pass NULL if you don't want the command output
2557 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
2558{
2559 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00002560 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002561 stream.PutBytesAsRawHex8(command, strlen(command));
2562 stream.PutChar(',');
2563 stream.PutHex32(timeout_sec);
2564 if (working_dir && *working_dir)
2565 {
2566 stream.PutChar(',');
2567 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
2568 }
2569 const char *packet = stream.GetData();
2570 int packet_len = stream.GetSize();
2571 StringExtractorGDBRemote response;
2572 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2573 {
2574 if (response.GetChar() != 'F')
2575 return Error("malformed reply");
2576 if (response.GetChar() != ',')
2577 return Error("malformed reply");
2578 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2579 if (exitcode == UINT32_MAX)
2580 return Error("unable to run remote process");
2581 else if (status_ptr)
2582 *status_ptr = exitcode;
2583 if (response.GetChar() != ',')
2584 return Error("malformed reply");
2585 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2586 if (signo_ptr)
2587 *signo_ptr = signo;
2588 if (response.GetChar() != ',')
2589 return Error("malformed reply");
2590 std::string output;
2591 response.GetEscapedBinaryData(output);
2592 if (command_output)
2593 command_output->assign(output);
2594 return Error();
2595 }
2596 return Error("unable to send packet");
2597}
2598
Greg Claytonfbb76342013-11-20 21:07:01 +00002599Error
2600GDBRemoteCommunicationClient::MakeDirectory (const char *path,
2601 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002602{
2603 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00002604 stream.PutCString("qPlatform_mkdir:");
2605 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002606 stream.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00002607 stream.PutBytesAsRawHex8(path, strlen(path));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002608 const char *packet = stream.GetData();
2609 int packet_len = stream.GetSize();
2610 StringExtractorGDBRemote response;
2611 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2612 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002613 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002614 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002615 return Error();
Daniel Maleae0f8f572013-08-26 23:57:52 +00002616
2617}
2618
Greg Claytonfbb76342013-11-20 21:07:01 +00002619Error
2620GDBRemoteCommunicationClient::SetFilePermissions (const char *path,
2621 uint32_t file_permissions)
2622{
2623 lldb_private::StreamString stream;
2624 stream.PutCString("qPlatform_chmod:");
2625 stream.PutHex32(file_permissions);
2626 stream.PutChar(',');
2627 stream.PutBytesAsRawHex8(path, strlen(path));
2628 const char *packet = stream.GetData();
2629 int packet_len = stream.GetSize();
2630 StringExtractorGDBRemote response;
2631 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2632 {
2633 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
2634 }
2635 return Error();
2636
2637}
2638
Daniel Maleae0f8f572013-08-26 23:57:52 +00002639static uint64_t
2640ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
2641 uint64_t fail_result,
2642 Error &error)
2643{
2644 response.SetFilePos(0);
2645 if (response.GetChar() != 'F')
2646 return fail_result;
2647 int32_t result = response.GetS32 (-2);
2648 if (result == -2)
2649 return fail_result;
2650 if (response.GetChar() == ',')
2651 {
2652 int result_errno = response.GetS32 (-2);
2653 if (result_errno != -2)
2654 error.SetError(result_errno, eErrorTypePOSIX);
2655 else
2656 error.SetError(-1, eErrorTypeGeneric);
2657 }
2658 else
2659 error.Clear();
2660 return result;
2661}
2662lldb::user_id_t
2663GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
2664 uint32_t flags,
2665 mode_t mode,
2666 Error &error)
2667{
2668 lldb_private::StreamString stream;
2669 stream.PutCString("vFile:open:");
2670 std::string path (file_spec.GetPath());
2671 if (path.empty())
2672 return UINT64_MAX;
2673 stream.PutCStringAsRawHex8(path.c_str());
2674 stream.PutChar(',');
2675 const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags);
2676 stream.PutHex32(posix_open_flags);
2677 stream.PutChar(',');
2678 stream.PutHex32(mode);
2679 const char* packet = stream.GetData();
2680 int packet_len = stream.GetSize();
2681 StringExtractorGDBRemote response;
2682 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2683 {
2684 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
2685 }
2686 return UINT64_MAX;
2687}
2688
2689bool
2690GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
2691 Error &error)
2692{
2693 lldb_private::StreamString stream;
2694 stream.Printf("vFile:close:%i", (int)fd);
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 return ParseHostIOPacketResponse (response, -1, error) == 0;
2701 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00002702 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002703}
2704
2705// Extension of host I/O packets to get the file size.
2706lldb::user_id_t
2707GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
2708{
2709 lldb_private::StreamString stream;
2710 stream.PutCString("vFile:size:");
2711 std::string path (file_spec.GetPath());
2712 stream.PutCStringAsRawHex8(path.c_str());
2713 const char* packet = stream.GetData();
2714 int packet_len = stream.GetSize();
2715 StringExtractorGDBRemote response;
2716 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2717 {
2718 if (response.GetChar() != 'F')
2719 return UINT64_MAX;
2720 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2721 return retcode;
2722 }
2723 return UINT64_MAX;
2724}
2725
Greg Claytonfbb76342013-11-20 21:07:01 +00002726Error
2727GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002728{
Greg Claytonfbb76342013-11-20 21:07:01 +00002729 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002730 lldb_private::StreamString stream;
2731 stream.PutCString("vFile:mode:");
Greg Claytonfbb76342013-11-20 21:07:01 +00002732 stream.PutCStringAsRawHex8(path);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002733 const char* packet = stream.GetData();
2734 int packet_len = stream.GetSize();
2735 StringExtractorGDBRemote response;
2736 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2737 {
2738 if (response.GetChar() != 'F')
2739 {
2740 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002741 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002742 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002743 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002744 const uint32_t mode = response.GetS32(-1);
2745 if (mode == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002746 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002747 if (response.GetChar() == ',')
2748 {
2749 int response_errno = response.GetS32(-1);
2750 if (response_errno > 0)
2751 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2752 else
2753 error.SetErrorToGenericError();
2754 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002755 else
2756 error.SetErrorToGenericError();
2757 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002758 else
2759 {
2760 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
2761 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002762 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002763 }
2764 else
2765 {
2766 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
2767 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002768 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002769}
2770
2771uint64_t
2772GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
2773 uint64_t offset,
2774 void *dst,
2775 uint64_t dst_len,
2776 Error &error)
2777{
2778 lldb_private::StreamString stream;
2779 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
2780 const char* packet = stream.GetData();
2781 int packet_len = stream.GetSize();
2782 StringExtractorGDBRemote response;
2783 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2784 {
2785 if (response.GetChar() != 'F')
2786 return 0;
2787 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2788 if (retcode == UINT32_MAX)
2789 return retcode;
2790 const char next = (response.Peek() ? *response.Peek() : 0);
2791 if (next == ',')
2792 return 0;
2793 if (next == ';')
2794 {
2795 response.GetChar(); // skip the semicolon
2796 std::string buffer;
2797 if (response.GetEscapedBinaryData(buffer))
2798 {
2799 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
2800 if (data_to_write > 0)
2801 memcpy(dst, &buffer[0], data_to_write);
2802 return data_to_write;
2803 }
2804 }
2805 }
2806 return 0;
2807}
2808
2809uint64_t
2810GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
2811 uint64_t offset,
2812 const void* src,
2813 uint64_t src_len,
2814 Error &error)
2815{
2816 lldb_private::StreamGDBRemote stream;
2817 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2818 stream.PutEscapedBytes(src, src_len);
2819 const char* packet = stream.GetData();
2820 int packet_len = stream.GetSize();
2821 StringExtractorGDBRemote response;
2822 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2823 {
2824 if (response.GetChar() != 'F')
2825 {
2826 error.SetErrorStringWithFormat("write file failed");
2827 return 0;
2828 }
2829 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2830 if (bytes_written == UINT64_MAX)
2831 {
2832 error.SetErrorToGenericError();
2833 if (response.GetChar() == ',')
2834 {
2835 int response_errno = response.GetS32(-1);
2836 if (response_errno > 0)
2837 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2838 }
2839 return 0;
2840 }
2841 return bytes_written;
2842 }
2843 else
2844 {
2845 error.SetErrorString ("failed to send vFile:pwrite packet");
2846 }
2847 return 0;
2848}
2849
Greg Claytonfbb76342013-11-20 21:07:01 +00002850Error
2851GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst)
2852{
2853 Error error;
2854 lldb_private::StreamGDBRemote stream;
2855 stream.PutCString("vFile:symlink:");
2856 // the unix symlink() command reverses its parameters where the dst if first,
2857 // so we follow suit here
2858 stream.PutCStringAsRawHex8(dst);
2859 stream.PutChar(',');
2860 stream.PutCStringAsRawHex8(src);
2861 const char* packet = stream.GetData();
2862 int packet_len = stream.GetSize();
2863 StringExtractorGDBRemote response;
2864 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2865 {
2866 if (response.GetChar() == 'F')
2867 {
2868 uint32_t result = response.GetU32(UINT32_MAX);
2869 if (result != 0)
2870 {
2871 error.SetErrorToGenericError();
2872 if (response.GetChar() == ',')
2873 {
2874 int response_errno = response.GetS32(-1);
2875 if (response_errno > 0)
2876 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2877 }
2878 }
2879 }
2880 else
2881 {
2882 // Should have returned with 'F<result>[,<errno>]'
2883 error.SetErrorStringWithFormat("symlink failed");
2884 }
2885 }
2886 else
2887 {
2888 error.SetErrorString ("failed to send vFile:symlink packet");
2889 }
2890 return error;
2891}
2892
2893Error
2894GDBRemoteCommunicationClient::Unlink (const char *path)
2895{
2896 Error error;
2897 lldb_private::StreamGDBRemote stream;
2898 stream.PutCString("vFile:unlink:");
2899 // the unix symlink() command reverses its parameters where the dst if first,
2900 // so we follow suit here
2901 stream.PutCStringAsRawHex8(path);
2902 const char* packet = stream.GetData();
2903 int packet_len = stream.GetSize();
2904 StringExtractorGDBRemote response;
2905 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2906 {
2907 if (response.GetChar() == 'F')
2908 {
2909 uint32_t result = response.GetU32(UINT32_MAX);
2910 if (result != 0)
2911 {
2912 error.SetErrorToGenericError();
2913 if (response.GetChar() == ',')
2914 {
2915 int response_errno = response.GetS32(-1);
2916 if (response_errno > 0)
2917 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2918 }
2919 }
2920 }
2921 else
2922 {
2923 // Should have returned with 'F<result>[,<errno>]'
2924 error.SetErrorStringWithFormat("unlink failed");
2925 }
2926 }
2927 else
2928 {
2929 error.SetErrorString ("failed to send vFile:unlink packet");
2930 }
2931 return error;
2932}
2933
Daniel Maleae0f8f572013-08-26 23:57:52 +00002934// Extension of host I/O packets to get whether a file exists.
2935bool
2936GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
2937{
2938 lldb_private::StreamString stream;
2939 stream.PutCString("vFile:exists:");
2940 std::string path (file_spec.GetPath());
2941 stream.PutCStringAsRawHex8(path.c_str());
2942 const char* packet = stream.GetData();
2943 int packet_len = stream.GetSize();
2944 StringExtractorGDBRemote response;
2945 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2946 {
2947 if (response.GetChar() != 'F')
2948 return false;
2949 if (response.GetChar() != ',')
2950 return false;
2951 bool retcode = (response.GetChar() != '0');
2952 return retcode;
2953 }
2954 return false;
2955}
2956
2957bool
2958GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
2959 uint64_t &high,
2960 uint64_t &low)
2961{
2962 lldb_private::StreamString stream;
2963 stream.PutCString("vFile:MD5:");
2964 std::string path (file_spec.GetPath());
2965 stream.PutCStringAsRawHex8(path.c_str());
2966 const char* packet = stream.GetData();
2967 int packet_len = stream.GetSize();
2968 StringExtractorGDBRemote response;
2969 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2970 {
2971 if (response.GetChar() != 'F')
2972 return false;
2973 if (response.GetChar() != ',')
2974 return false;
2975 if (response.Peek() && *response.Peek() == 'x')
2976 return false;
2977 low = response.GetHexMaxU64(false, UINT64_MAX);
2978 high = response.GetHexMaxU64(false, UINT64_MAX);
2979 return true;
2980 }
2981 return false;
2982}
Greg Claytonf74cf862013-11-13 23:28:31 +00002983
2984bool
2985GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
2986{
2987 Mutex::Locker locker;
2988 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
2989 {
2990 const bool thread_suffix_supported = GetThreadSuffixSupported();
2991
2992 if (thread_suffix_supported || SetCurrentThread(tid))
2993 {
2994 char packet[64];
2995 int packet_len = 0;
2996 if (thread_suffix_supported)
2997 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
2998 else
2999 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3000 assert (packet_len < ((int)sizeof(packet) - 1));
3001 return SendPacketAndWaitForResponse(packet, response, false);
3002 }
3003 }
3004 return false;
3005
3006}
3007
3008
3009bool
3010GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3011{
3012 Mutex::Locker locker;
3013 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3014 {
3015 const bool thread_suffix_supported = GetThreadSuffixSupported();
3016
3017 if (thread_suffix_supported || SetCurrentThread(tid))
3018 {
3019 char packet[64];
3020 int packet_len = 0;
3021 // Get all registers in one packet
3022 if (thread_suffix_supported)
3023 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3024 else
3025 packet_len = ::snprintf (packet, sizeof(packet), "g");
3026 assert (packet_len < ((int)sizeof(packet) - 1));
3027 return SendPacketAndWaitForResponse(packet, response, false);
3028 }
3029 }
3030 return false;
3031}
3032bool
3033GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3034{
3035 save_id = 0; // Set to invalid save ID
3036 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3037 return false;
3038
3039 m_supports_QSaveRegisterState = eLazyBoolYes;
3040 Mutex::Locker locker;
3041 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3042 {
3043 const bool thread_suffix_supported = GetThreadSuffixSupported();
3044 if (thread_suffix_supported || SetCurrentThread(tid))
3045 {
3046 char packet[256];
3047 if (thread_suffix_supported)
3048 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3049 else
3050 ::strncpy (packet, "QSaveRegisterState", sizeof(packet));
3051
3052 StringExtractorGDBRemote response;
3053
3054 if (SendPacketAndWaitForResponse(packet, response, false))
3055 {
3056 if (response.IsUnsupportedResponse())
3057 {
3058 // This packet isn't supported, don't try calling it again
3059 m_supports_QSaveRegisterState = eLazyBoolNo;
3060 }
3061
3062 const uint32_t response_save_id = response.GetU32(0);
3063 if (response_save_id != 0)
3064 {
3065 save_id = response_save_id;
3066 return true;
3067 }
3068 }
3069 }
3070 }
3071 return false;
3072}
3073
3074bool
3075GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3076{
3077 // We use the "m_supports_QSaveRegisterState" variable here becuase the
3078 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3079 // order to be useful
3080 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3081 return false;
3082
3083 Mutex::Locker locker;
3084 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
3085 {
3086 const bool thread_suffix_supported = GetThreadSuffixSupported();
3087 if (thread_suffix_supported || SetCurrentThread(tid))
3088 {
3089 char packet[256];
3090 if (thread_suffix_supported)
3091 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3092 else
3093 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3094
3095 StringExtractorGDBRemote response;
3096
3097 if (SendPacketAndWaitForResponse(packet, response, false))
3098 {
3099 if (response.IsOKResponse())
3100 {
3101 return true;
3102 }
3103 else if (response.IsUnsupportedResponse())
3104 {
3105 // This packet isn't supported, don't try calling this packet or
3106 // QSaveRegisterState again...
3107 m_supports_QSaveRegisterState = eLazyBoolNo;
3108 }
3109 }
3110 }
3111 }
3112 return false;
3113}