blob: aa60ec1b4a27737f38cf180766526517e639d5c2 [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),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000069 m_supports_qXfer_libraries_read (eLazyBoolCalculate),
70 m_supports_qXfer_libraries_svr4_read (eLazyBoolCalculate),
71 m_supports_augmented_libraries_svr4_read (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000072 m_supports_qProcessInfoPID (true),
73 m_supports_qfProcessInfo (true),
74 m_supports_qUserName (true),
75 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000076 m_supports_qThreadStopInfo (true),
77 m_supports_z0 (true),
78 m_supports_z1 (true),
79 m_supports_z2 (true),
80 m_supports_z3 (true),
81 m_supports_z4 (true),
Greg Clayton89600582013-10-10 17:53:50 +000082 m_supports_QEnvironment (true),
83 m_supports_QEnvironmentHexEncoded (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000084 m_curr_tid (LLDB_INVALID_THREAD_ID),
85 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +000086 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +000087 m_async_mutex (Mutex::eMutexTypeRecursive),
88 m_async_packet_predicate (false),
89 m_async_packet (),
Jim Inghama6195b72013-12-18 01:24:33 +000090 m_async_result (PacketResult::Success),
Greg Clayton576d8832011-03-22 04:00:09 +000091 m_async_response (),
92 m_async_signal (-1),
Han Ming Ong4b6459f2013-01-18 23:11:53 +000093 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +000094 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000095 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +000096 m_os_version_major (UINT32_MAX),
97 m_os_version_minor (UINT32_MAX),
Greg Clayton9ac6d2d2013-10-25 18:13:17 +000098 m_os_version_update (UINT32_MAX),
99 m_os_build (),
100 m_os_kernel (),
101 m_hostname (),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000102 m_default_packet_timeout (0),
103 m_max_packet_size (0)
Greg Clayton576d8832011-03-22 04:00:09 +0000104{
Greg Clayton576d8832011-03-22 04:00:09 +0000105}
106
107//----------------------------------------------------------------------
108// Destructor
109//----------------------------------------------------------------------
110GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
111{
Greg Clayton576d8832011-03-22 04:00:09 +0000112 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000113 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000114}
115
116bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000117GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
118{
Greg Claytonfb909312013-11-23 01:58:15 +0000119 ResetDiscoverableSettings();
120
Greg Clayton1cb64962011-03-24 04:28:38 +0000121 // Start the read thread after we send the handshake ack since if we
122 // fail to send the handshake ack, there is no reason to continue...
123 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000124 {
Ed Maste48f986f2013-12-18 15:31:45 +0000125 // Wait for any responses that might have been queued up in the remote
126 // GDB server and flush them all
127 StringExtractorGDBRemote response;
128 PacketResult packet_result = PacketResult::Success;
129 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
130 while (packet_result == PacketResult::Success)
131 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, timeout_usec);
132
Greg Claytonfb909312013-11-23 01:58:15 +0000133 // The return value from QueryNoAckModeSupported() is true if the packet
134 // was sent and _any_ response (including UNIMPLEMENTED) was received),
135 // or false if no response was received. This quickly tells us if we have
136 // a live connection to a remote GDB server...
137 if (QueryNoAckModeSupported())
138 {
139 return true;
140 }
141 else
142 {
143 if (error_ptr)
144 error_ptr->SetErrorString("failed to get reply to handshake packet");
145 }
146 }
147 else
148 {
149 if (error_ptr)
150 error_ptr->SetErrorString("failed to send the handshake ack");
151 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000152 return false;
153}
154
Greg Claytonfb909312013-11-23 01:58:15 +0000155bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000156GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
157{
158 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
159 {
160 GetRemoteQSupported();
161 }
162 return (m_supports_augmented_libraries_svr4_read == eLazyBoolYes);
163}
164
165bool
166GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
167{
168 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
169 {
170 GetRemoteQSupported();
171 }
172 return (m_supports_qXfer_libraries_svr4_read == eLazyBoolYes);
173}
174
175bool
176GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
177{
178 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
179 {
180 GetRemoteQSupported();
181 }
182 return (m_supports_qXfer_libraries_read == eLazyBoolYes);
183}
184
185uint64_t
186GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
187{
188 if (m_max_packet_size == 0)
189 {
190 GetRemoteQSupported();
191 }
192 return m_max_packet_size;
193}
194
195bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000196GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000197{
198 if (m_supports_not_sending_acks == eLazyBoolCalculate)
199 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000200 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000201 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000202
203 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000204 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000205 {
206 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000207 {
208 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000209 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000210 }
Greg Claytonfb909312013-11-23 01:58:15 +0000211 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000212 }
213 }
Greg Claytonfb909312013-11-23 01:58:15 +0000214 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000215}
216
217void
Greg Clayton44633992012-04-10 03:22:03 +0000218GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
219{
220 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
221 {
222 m_supports_threads_in_stop_reply = eLazyBoolNo;
223
224 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000225 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000226 {
227 if (response.IsOKResponse())
228 m_supports_threads_in_stop_reply = eLazyBoolYes;
229 }
230 }
231}
232
Jim Inghamcd16df92012-07-20 21:37:13 +0000233bool
234GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
235{
236 if (m_attach_or_wait_reply == eLazyBoolCalculate)
237 {
238 m_attach_or_wait_reply = eLazyBoolNo;
239
240 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000241 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000242 {
243 if (response.IsOKResponse())
244 m_attach_or_wait_reply = eLazyBoolYes;
245 }
246 }
247 if (m_attach_or_wait_reply == eLazyBoolYes)
248 return true;
249 else
250 return false;
251}
252
Jim Ingham279ceec2012-07-25 21:12:43 +0000253bool
254GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
255{
256 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
257 {
258 m_prepare_for_reg_writing_reply = eLazyBoolNo;
259
260 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000261 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000262 {
263 if (response.IsOKResponse())
264 m_prepare_for_reg_writing_reply = eLazyBoolYes;
265 }
266 }
267 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
268 return true;
269 else
270 return false;
271}
272
Greg Clayton44633992012-04-10 03:22:03 +0000273
274void
Greg Clayton576d8832011-03-22 04:00:09 +0000275GDBRemoteCommunicationClient::ResetDiscoverableSettings()
276{
277 m_supports_not_sending_acks = eLazyBoolCalculate;
278 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton44633992012-04-10 03:22:03 +0000279 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
Greg Clayton576d8832011-03-22 04:00:09 +0000280 m_supports_vCont_c = eLazyBoolCalculate;
281 m_supports_vCont_C = eLazyBoolCalculate;
282 m_supports_vCont_s = eLazyBoolCalculate;
283 m_supports_vCont_S = eLazyBoolCalculate;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000284 m_supports_p = eLazyBoolCalculate;
Greg Claytonf74cf862013-11-13 23:28:31 +0000285 m_supports_QSaveRegisterState = eLazyBoolCalculate;
Greg Clayton32e0a752011-03-30 18:16:51 +0000286 m_qHostInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000287 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Greg Clayton70b57652011-05-15 01:25:55 +0000288 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton46fb5582011-11-18 07:03:08 +0000289 m_supports_memory_region_info = eLazyBoolCalculate;
Jim Ingham279ceec2012-07-25 21:12:43 +0000290 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
291 m_attach_or_wait_reply = eLazyBoolCalculate;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000292 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
293 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
294 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
Greg Clayton2a48f522011-05-14 01:50:35 +0000295
Greg Clayton32e0a752011-03-30 18:16:51 +0000296 m_supports_qProcessInfoPID = true;
297 m_supports_qfProcessInfo = true;
298 m_supports_qUserName = true;
299 m_supports_qGroupName = true;
Greg Clayton8b82f082011-04-12 05:54:46 +0000300 m_supports_qThreadStopInfo = true;
301 m_supports_z0 = true;
302 m_supports_z1 = true;
303 m_supports_z2 = true;
304 m_supports_z3 = true;
305 m_supports_z4 = true;
Greg Clayton89600582013-10-10 17:53:50 +0000306 m_supports_QEnvironment = true;
307 m_supports_QEnvironmentHexEncoded = true;
Greg Claytond314e812011-03-23 00:09:55 +0000308 m_host_arch.Clear();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000309 m_process_arch.Clear();
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000310
311 m_max_packet_size = 0;
Greg Clayton576d8832011-03-22 04:00:09 +0000312}
313
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000314void
315GDBRemoteCommunicationClient::GetRemoteQSupported ()
316{
317 // Clear out any capabilities we expect to see in the qSupported response
318 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
319 m_supports_qXfer_libraries_read = eLazyBoolNo;
320 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
321 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
322
323 StringExtractorGDBRemote response;
324 if (SendPacketAndWaitForResponse("qSupported",
325 response,
326 /*send_async=*/false) == PacketResult::Success)
327 {
328 const char *response_cstr = response.GetStringRef().c_str();
329 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
330 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
331 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
332 {
333 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
334 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
335 }
336 if (::strstr (response_cstr, "qXfer:libraries:read+"))
337 m_supports_qXfer_libraries_read = eLazyBoolYes;
338
339 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
340 if (packet_size_str)
341 {
342 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
343 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
344 if (m_max_packet_size == 0)
345 {
346 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
347 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
348 if (log)
349 log->Printf ("Garbled PacketSize spec in qSupported response");
350 }
351 }
352 }
353}
Greg Clayton576d8832011-03-22 04:00:09 +0000354
355bool
356GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
357{
358 if (m_supports_thread_suffix == eLazyBoolCalculate)
359 {
360 StringExtractorGDBRemote response;
361 m_supports_thread_suffix = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000362 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000363 {
364 if (response.IsOKResponse())
365 m_supports_thread_suffix = eLazyBoolYes;
366 }
367 }
368 return m_supports_thread_suffix;
369}
370bool
371GDBRemoteCommunicationClient::GetVContSupported (char flavor)
372{
373 if (m_supports_vCont_c == eLazyBoolCalculate)
374 {
375 StringExtractorGDBRemote response;
376 m_supports_vCont_any = eLazyBoolNo;
377 m_supports_vCont_all = eLazyBoolNo;
378 m_supports_vCont_c = eLazyBoolNo;
379 m_supports_vCont_C = eLazyBoolNo;
380 m_supports_vCont_s = eLazyBoolNo;
381 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000382 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000383 {
384 const char *response_cstr = response.GetStringRef().c_str();
385 if (::strstr (response_cstr, ";c"))
386 m_supports_vCont_c = eLazyBoolYes;
387
388 if (::strstr (response_cstr, ";C"))
389 m_supports_vCont_C = eLazyBoolYes;
390
391 if (::strstr (response_cstr, ";s"))
392 m_supports_vCont_s = eLazyBoolYes;
393
394 if (::strstr (response_cstr, ";S"))
395 m_supports_vCont_S = eLazyBoolYes;
396
397 if (m_supports_vCont_c == eLazyBoolYes &&
398 m_supports_vCont_C == eLazyBoolYes &&
399 m_supports_vCont_s == eLazyBoolYes &&
400 m_supports_vCont_S == eLazyBoolYes)
401 {
402 m_supports_vCont_all = eLazyBoolYes;
403 }
404
405 if (m_supports_vCont_c == eLazyBoolYes ||
406 m_supports_vCont_C == eLazyBoolYes ||
407 m_supports_vCont_s == eLazyBoolYes ||
408 m_supports_vCont_S == eLazyBoolYes)
409 {
410 m_supports_vCont_any = eLazyBoolYes;
411 }
412 }
413 }
414
415 switch (flavor)
416 {
417 case 'a': return m_supports_vCont_any;
418 case 'A': return m_supports_vCont_all;
419 case 'c': return m_supports_vCont_c;
420 case 'C': return m_supports_vCont_C;
421 case 's': return m_supports_vCont_s;
422 case 'S': return m_supports_vCont_S;
423 default: break;
424 }
425 return false;
426}
427
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000428// Check if the target supports 'p' packet. It sends out a 'p'
429// packet and checks the response. A normal packet will tell us
430// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000431//
432// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000433bool
Sean Callananb1de1142013-09-04 23:24:15 +0000434GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000435{
436 if (m_supports_p == eLazyBoolCalculate)
437 {
438 StringExtractorGDBRemote response;
439 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000440 char packet[256];
441 if (GetThreadSuffixSupported())
442 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
443 else
444 snprintf(packet, sizeof(packet), "p0");
445
Greg Clayton3dedae12013-12-06 21:45:27 +0000446 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000447 {
448 if (response.IsNormalResponse())
449 m_supports_p = eLazyBoolYes;
450 }
451 }
452 return m_supports_p;
453}
Greg Clayton576d8832011-03-22 04:00:09 +0000454
Greg Clayton3dedae12013-12-06 21:45:27 +0000455GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000456GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
457(
458 const char *payload_prefix,
459 std::string &response_string
460)
461{
462 Mutex::Locker locker;
463 if (!GetSequenceMutex(locker,
464 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
465 {
466 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
467 if (log)
468 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
469 payload_prefix);
470 return PacketResult::ErrorNoSequenceLock;
471 }
472
473 response_string = "";
474 std::string payload_prefix_str(payload_prefix);
475 unsigned int response_size = 0x1000;
476 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
477 response_size = GetRemoteMaxPacketSize();
478 }
479
480 for (unsigned int offset = 0; true; offset += response_size)
481 {
482 StringExtractorGDBRemote this_response;
483 // Construct payload
484 char sizeDescriptor[128];
485 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
486 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
487 this_response,
488 /*send_async=*/false);
489 if (result != PacketResult::Success)
490 return result;
491
492 const std::string &this_string = this_response.GetStringRef();
493
494 // Check for m or l as first character; l seems to mean this is the last chunk
495 char first_char = *this_string.c_str();
496 if (first_char != 'm' && first_char != 'l')
497 {
498 return PacketResult::ErrorReplyInvalid;
499 }
500 // Skip past m or l
501 const char *s = this_string.c_str() + 1;
502
503 // Concatenate the result so far
504 response_string += s;
505 if (first_char == 'l')
506 // We're done
507 return PacketResult::Success;
508 }
509}
510
511GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000512GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
513(
514 const char *payload,
515 StringExtractorGDBRemote &response,
516 bool send_async
517)
518{
519 return SendPacketAndWaitForResponse (payload,
520 ::strlen (payload),
521 response,
522 send_async);
523}
524
Greg Clayton3dedae12013-12-06 21:45:27 +0000525GDBRemoteCommunicationClient::PacketResult
526GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
527 size_t payload_length,
528 StringExtractorGDBRemote &response)
529{
530 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
531 if (packet_result == PacketResult::Success)
532 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
533 return packet_result;
534}
535
536GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000537GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
538(
539 const char *payload,
540 size_t payload_length,
541 StringExtractorGDBRemote &response,
542 bool send_async
543)
544{
Greg Clayton3dedae12013-12-06 21:45:27 +0000545 PacketResult packet_result = PacketResult::ErrorSendFailed;
Greg Clayton576d8832011-03-22 04:00:09 +0000546 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000547 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton644247c2011-07-07 01:59:51 +0000548 size_t response_len = 0;
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000549 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000550 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000551 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000552 }
553 else
554 {
555 if (send_async)
556 {
Greg Claytond3544052012-05-31 21:24:20 +0000557 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000558 {
Greg Claytond3544052012-05-31 21:24:20 +0000559 Mutex::Locker async_locker (m_async_mutex);
560 m_async_packet.assign(payload, payload_length);
561 m_async_packet_predicate.SetValue (true, eBroadcastNever);
562
563 if (log)
564 log->Printf ("async: async packet = %s", m_async_packet.c_str());
565
566 bool timed_out = false;
567 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000568 {
Greg Claytond3544052012-05-31 21:24:20 +0000569 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000570 {
Jim Inghambabfc382012-06-06 00:32:39 +0000571 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000572 TimeValue timeout_time;
573 timeout_time = TimeValue::Now();
574 timeout_time.OffsetWithSeconds (m_packet_timeout);
575
Greg Clayton576d8832011-03-22 04:00:09 +0000576 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000577 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000578
Greg Claytond3544052012-05-31 21:24:20 +0000579 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000580 {
Greg Claytond3544052012-05-31 21:24:20 +0000581 if (log)
582 log->Printf ("async: got response");
583
584 // Swap the response buffer to avoid malloc and string copy
585 response.GetStringRef().swap (m_async_response.GetStringRef());
586 response_len = response.GetStringRef().size();
Jim Inghama6195b72013-12-18 01:24:33 +0000587 packet_result = m_async_result;
Greg Claytond3544052012-05-31 21:24:20 +0000588 }
589 else
590 {
591 if (log)
592 log->Printf ("async: timed out waiting for response");
593 }
594
595 // Make sure we wait until the continue packet has been sent again...
596 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
597 {
598 if (log)
599 {
600 if (timed_out)
601 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
602 else
603 log->Printf ("async: async packet sent");
604 }
605 }
606 else
607 {
608 if (log)
609 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000610 }
611 }
612 else
613 {
Greg Claytond3544052012-05-31 21:24:20 +0000614 // We had a racy condition where we went to send the interrupt
615 // yet we were able to get the lock, so the process must have
616 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000617 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000618 log->Printf ("async: got lock without sending interrupt");
619 // Send the packet normally since we got the lock
Greg Clayton3dedae12013-12-06 21:45:27 +0000620 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000621 }
622 }
623 else
624 {
Greg Clayton644247c2011-07-07 01:59:51 +0000625 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000626 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000627 }
628 }
629 else
630 {
631 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000632 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000633 }
634 }
635 else
636 {
637 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000638 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000639 }
640 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000641 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000642}
643
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000644static const char *end_delimiter = "--end--;";
645static const int end_delimiter_len = 8;
646
647std::string
648GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
649( ProcessGDBRemote *process,
650 StringExtractorGDBRemote& profileDataExtractor
651)
652{
653 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
654 std::stringstream final_output;
655 std::string name, value;
656
657 // Going to assuming thread_used_usec comes first, else bail out.
658 while (profileDataExtractor.GetNameColonValue(name, value))
659 {
660 if (name.compare("thread_used_id") == 0)
661 {
662 StringExtractor threadIDHexExtractor(value.c_str());
663 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
664
665 bool has_used_usec = false;
666 uint32_t curr_used_usec = 0;
667 std::string usec_name, usec_value;
668 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
669 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
670 {
671 if (usec_name.compare("thread_used_usec") == 0)
672 {
673 has_used_usec = true;
674 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
675 }
676 else
677 {
678 // We didn't find what we want, it is probably
679 // an older version. Bail out.
680 profileDataExtractor.SetFilePos(input_file_pos);
681 }
682 }
683
684 if (has_used_usec)
685 {
686 uint32_t prev_used_usec = 0;
687 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
688 if (iterator != m_thread_id_to_used_usec_map.end())
689 {
690 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
691 }
692
693 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
694 // A good first time record is one that runs for at least 0.25 sec
695 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
696 bool good_subsequent_time = (prev_used_usec > 0) &&
697 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
698
699 if (good_first_time || good_subsequent_time)
700 {
701 // We try to avoid doing too many index id reservation,
702 // resulting in fast increase of index ids.
703
704 final_output << name << ":";
705 int32_t index_id = process->AssignIndexIDToThread(thread_id);
706 final_output << index_id << ";";
707
708 final_output << usec_name << ":" << usec_value << ";";
709 }
710 else
711 {
712 // Skip past 'thread_used_name'.
713 std::string local_name, local_value;
714 profileDataExtractor.GetNameColonValue(local_name, local_value);
715 }
716
717 // Store current time as previous time so that they can be compared later.
718 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
719 }
720 else
721 {
722 // Bail out and use old string.
723 final_output << name << ":" << value << ";";
724 }
725 }
726 else
727 {
728 final_output << name << ":" << value << ";";
729 }
730 }
731 final_output << end_delimiter;
732 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
733
734 return final_output.str();
735}
736
Greg Clayton576d8832011-03-22 04:00:09 +0000737StateType
738GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
739(
740 ProcessGDBRemote *process,
741 const char *payload,
742 size_t packet_length,
743 StringExtractorGDBRemote &response
744)
745{
Greg Clayton1f5181a2012-07-02 22:05:25 +0000746 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +0000747 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +0000748 if (log)
749 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
750
751 Mutex::Locker locker(m_sequence_mutex);
752 StateType state = eStateRunning;
753
754 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
755 m_public_is_running.SetValue (true, eBroadcastNever);
756 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +0000757 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +0000758 std::string continue_packet(payload, packet_length);
759
Greg Clayton3f875c52013-02-22 22:23:55 +0000760 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +0000761
Greg Clayton576d8832011-03-22 04:00:09 +0000762 while (state == eStateRunning)
763 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000764 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +0000765 {
766 if (log)
767 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton3dedae12013-12-06 21:45:27 +0000768 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
Greg Claytonaf247d72011-05-19 03:54:16 +0000769 state = eStateInvalid;
Greg Clayton576d8832011-03-22 04:00:09 +0000770
Greg Claytone889ad62011-10-27 22:04:16 +0000771 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +0000772 }
773
Greg Clayton3f875c52013-02-22 22:23:55 +0000774 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000775
776 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000777 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +0000778
Greg Clayton3dedae12013-12-06 21:45:27 +0000779 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000780 {
781 if (response.Empty())
782 state = eStateInvalid;
783 else
784 {
785 const char stop_type = response.GetChar();
786 if (log)
787 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
788 switch (stop_type)
789 {
790 case 'T':
791 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +0000792 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000793 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +0000794 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000795 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
796 {
797 lldb::pid_t pid = GetCurrentProcessID ();
798 if (pid != LLDB_INVALID_PROCESS_ID)
799 process->SetID (pid);
800 }
801 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +0000802 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000803
804 // Privately notify any internal threads that we have stopped
805 // in case we wanted to interrupt our process, yet we might
806 // send a packet and continue without returning control to the
807 // user.
808 m_private_is_running.SetValue (false, eBroadcastAlways);
809
810 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
811
Jim Inghambabfc382012-06-06 00:32:39 +0000812 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
813 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +0000814 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000815 // We sent an interrupt packet to stop the inferior process
816 // for an async signal or to send an async packet while running
817 // but we might have been single stepping and received the
818 // stop packet for the step instead of for the interrupt packet.
819 // Typically when an interrupt is sent a SIGINT or SIGSTOP
820 // is used, so if we get anything else, we need to try and
821 // get another stop reply packet that may have been sent
822 // due to sending the interrupt when the target is stopped
823 // which will just re-send a copy of the last stop reply
824 // packet. If we don't do this, then the reply for our
825 // async packet will be the repeat stop reply packet and cause
826 // a lot of trouble for us!
827 if (signo != SIGINT && signo != SIGSTOP)
828 {
Greg Claytonfb72fde2012-05-15 02:50:49 +0000829 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000830
831 // We didn't get a a SIGINT or SIGSTOP, so try for a
832 // very brief time (1 ms) to get another stop reply
833 // packet to make sure it doesn't get in the way
834 StringExtractorGDBRemote extra_stop_reply_packet;
835 uint32_t timeout_usec = 1000;
Greg Clayton3dedae12013-12-06 21:45:27 +0000836 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +0000837 {
838 switch (extra_stop_reply_packet.GetChar())
839 {
840 case 'T':
841 case 'S':
842 // We did get an extra stop reply, which means
843 // our interrupt didn't stop the target so we
844 // shouldn't continue after the async signal
845 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +0000846 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000847 break;
848 }
849 }
850 }
851 }
852
853 if (m_async_signal != -1)
854 {
855 if (log)
856 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
857
858 // Save off the async signal we are supposed to send
859 const int async_signal = m_async_signal;
860 // Clear the async signal member so we don't end up
861 // sending the signal multiple times...
862 m_async_signal = -1;
863 // Check which signal we stopped with
864 if (signo == async_signal)
865 {
866 if (log)
867 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
868
869 // We already stopped with a signal that we wanted
870 // to stop with, so we are done
871 }
872 else
873 {
874 // We stopped with a different signal that the one
875 // we wanted to stop with, so now we must resume
876 // with the signal we want
877 char signal_packet[32];
878 int signal_packet_len = 0;
879 signal_packet_len = ::snprintf (signal_packet,
880 sizeof (signal_packet),
881 "C%2.2x",
882 async_signal);
883
884 if (log)
885 log->Printf ("async: stopped with signal %s, resume with %s",
886 Host::GetSignalAsCString (signo),
887 Host::GetSignalAsCString (async_signal));
888
889 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +0000890 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000891 continue_packet.assign(signal_packet, signal_packet_len);
892 continue;
893 }
894 }
895 else if (m_async_packet_predicate.GetValue())
896 {
Greg Clayton5160ce52013-03-27 23:08:40 +0000897 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +0000898
899 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +0000900 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +0000901 m_async_response.Clear();
902 if (m_async_packet.empty())
903 {
Jim Inghama6195b72013-12-18 01:24:33 +0000904 m_async_result = PacketResult::ErrorSendFailed;
905 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000906 packet_log->Printf ("async: error: empty async packet");
907
908 }
909 else
910 {
911 if (packet_log)
912 packet_log->Printf ("async: sending packet");
913
Jim Inghama6195b72013-12-18 01:24:33 +0000914 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
915 m_async_packet.size(),
916 m_async_response,
917 false);
Greg Clayton2687cd12012-03-29 01:55:41 +0000918 }
919 // Let the other thread that was trying to send the async
920 // packet know that the packet has been sent and response is
921 // ready...
922 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
923
924 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +0000925 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +0000926
927 // Set the continue packet to resume if our interrupt
928 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +0000929 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000930 {
Greg Claytonf1186de2012-05-24 23:42:14 +0000931 // Reverting this for now as it is causing deadlocks
932 // in programs (<rdar://problem/11529853>). In the future
933 // we should check our thread list and "do the right thing"
934 // for new threads that show up while we stop and run async
935 // packets. Setting the packet to 'c' to continue all threads
936 // is the right thing to do 99.99% of the time because if a
937 // thread was single stepping, and we sent an interrupt, we
938 // will notice above that we didn't stop due to an interrupt
939 // but stopped due to stepping and we would _not_ continue.
940 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +0000941 continue;
942 }
943 }
944 // Stop with signal and thread info
945 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +0000946 }
Greg Clayton576d8832011-03-22 04:00:09 +0000947 break;
948
949 case 'W':
950 case 'X':
951 // process exited
952 state = eStateExited;
953 break;
954
955 case 'O':
956 // STDOUT
957 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000958 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000959 std::string inferior_stdout;
960 inferior_stdout.reserve(response.GetBytesLeft () / 2);
961 char ch;
962 while ((ch = response.GetHexU8()) != '\0')
963 inferior_stdout.append(1, ch);
964 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
965 }
966 break;
967
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000968 case 'A':
969 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
970 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000971 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000972 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
973 if (m_partial_profile_data.length() > 0)
974 {
975 m_partial_profile_data.append(input);
976 input = m_partial_profile_data;
977 m_partial_profile_data.clear();
978 }
979
980 size_t found, pos = 0, len = input.length();
981 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
982 {
983 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +0000984 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
985 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000986
987 pos = found + end_delimiter_len;
988 }
989
990 if (pos < len)
991 {
992 // Last incomplete chunk.
993 m_partial_profile_data = input.substr(pos);
994 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000995 }
996 break;
997
Greg Clayton576d8832011-03-22 04:00:09 +0000998 case 'E':
999 // ERROR
1000 state = eStateInvalid;
1001 break;
1002
1003 default:
1004 if (log)
1005 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1006 state = eStateInvalid;
1007 break;
1008 }
1009 }
1010 }
1011 else
1012 {
1013 if (log)
1014 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
1015 state = eStateInvalid;
1016 }
1017 }
1018 if (log)
1019 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1020 response.SetFilePos(0);
1021 m_private_is_running.SetValue (false, eBroadcastAlways);
1022 m_public_is_running.SetValue (false, eBroadcastAlways);
1023 return state;
1024}
1025
1026bool
1027GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1028{
Greg Clayton2687cd12012-03-29 01:55:41 +00001029 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001030 m_async_signal = signo;
1031 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001032 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001033 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001034 return true;
1035 m_async_signal = -1;
1036 return false;
1037}
1038
Greg Clayton37a0a242012-04-11 00:24:49 +00001039// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001040// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1041// (the expected result), then it will send the halt packet. If it does succeed
1042// then the caller that requested the interrupt will want to keep the sequence
1043// locked down so that no one else can send packets while the caller has control.
1044// This function usually gets called when we are running and need to stop the
1045// target. It can also be used when we are running and and we need to do something
1046// else (like read/write memory), so we need to interrupt the running process
1047// (gdb remote protocol requires this), and do what we need to do, then resume.
1048
1049bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001050GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001051(
1052 Mutex::Locker& locker,
1053 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001054 bool &timed_out
1055)
1056{
Greg Clayton576d8832011-03-22 04:00:09 +00001057 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001058 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001059
1060 if (IsRunning())
1061 {
1062 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001063 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001064 {
1065 if (log)
1066 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1067 }
1068 else
Greg Clayton576d8832011-03-22 04:00:09 +00001069 {
1070 // Someone has the mutex locked waiting for a response or for the
1071 // inferior to stop, so send the interrupt on the down low...
1072 char ctrl_c = '\x03';
1073 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001074 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001075 if (log)
1076 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001077 if (bytes_written > 0)
1078 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001079 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001080 if (seconds_to_wait_for_stop)
1081 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001082 TimeValue timeout;
1083 if (seconds_to_wait_for_stop)
1084 {
1085 timeout = TimeValue::Now();
1086 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1087 }
Greg Clayton576d8832011-03-22 04:00:09 +00001088 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1089 {
1090 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001091 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001092 return true;
1093 }
1094 else
1095 {
1096 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001097 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001098 }
1099 }
1100 else
1101 {
1102 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001103 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001104 return true;
1105 }
1106 }
1107 else
1108 {
1109 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001110 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001111 }
1112 return false;
1113 }
Greg Clayton576d8832011-03-22 04:00:09 +00001114 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001115 else
1116 {
1117 if (log)
1118 log->Printf ("SendInterrupt () - not running");
1119 }
Greg Clayton576d8832011-03-22 04:00:09 +00001120 return true;
1121}
1122
1123lldb::pid_t
1124GDBRemoteCommunicationClient::GetCurrentProcessID ()
1125{
1126 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001127 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001128 {
1129 if (response.GetChar() == 'Q')
1130 if (response.GetChar() == 'C')
1131 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1132 }
1133 return LLDB_INVALID_PROCESS_ID;
1134}
1135
1136bool
1137GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1138{
1139 error_str.clear();
1140 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001141 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001142 {
1143 if (response.IsOKResponse())
1144 return true;
1145 if (response.GetChar() == 'E')
1146 {
1147 // A string the describes what failed when launching...
1148 error_str = response.GetStringRef().substr(1);
1149 }
1150 else
1151 {
1152 error_str.assign ("unknown error occurred launching process");
1153 }
1154 }
1155 else
1156 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001157 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001158 }
1159 return false;
1160}
1161
1162int
Greg Claytonfbb76342013-11-20 21:07:01 +00001163GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001164{
Greg Claytonfbb76342013-11-20 21:07:01 +00001165 // Since we don't get the send argv0 separate from the executable path, we need to
1166 // make sure to use the actual exectuable path found in the launch_info...
1167 std::vector<const char *> argv;
1168 FileSpec exe_file = launch_info.GetExecutableFile();
1169 std::string exe_path;
1170 const char *arg = NULL;
1171 const Args &launch_args = launch_info.GetArguments();
1172 if (exe_file)
1173 exe_path = exe_file.GetPath();
1174 else
1175 {
1176 arg = launch_args.GetArgumentAtIndex(0);
1177 if (arg)
1178 exe_path = arg;
1179 }
1180 if (!exe_path.empty())
1181 {
1182 argv.push_back(exe_path.c_str());
1183 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1184 {
1185 if (arg)
1186 argv.push_back(arg);
1187 }
1188 }
1189 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001190 {
1191 StreamString packet;
1192 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001193 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001194 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001195 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001196 const int arg_len = strlen(arg);
1197 if (i > 0)
1198 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001199 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001200 packet.PutBytesAsRawHex8 (arg, arg_len);
1201 }
1202
1203 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001204 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001205 {
1206 if (response.IsOKResponse())
1207 return 0;
1208 uint8_t error = response.GetError();
1209 if (error)
1210 return error;
1211 }
1212 }
1213 return -1;
1214}
1215
1216int
1217GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1218{
1219 if (name_equal_value && name_equal_value[0])
1220 {
1221 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001222 bool send_hex_encoding = false;
1223 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001224 {
Greg Clayton89600582013-10-10 17:53:50 +00001225 if (isprint(*p))
1226 {
1227 switch (*p)
1228 {
1229 case '$':
1230 case '#':
1231 send_hex_encoding = true;
1232 break;
1233 default:
1234 break;
1235 }
1236 }
1237 else
1238 {
1239 // We have non printable characters, lets hex encode this...
1240 send_hex_encoding = true;
1241 }
1242 }
1243
1244 StringExtractorGDBRemote response;
1245 if (send_hex_encoding)
1246 {
1247 if (m_supports_QEnvironmentHexEncoded)
1248 {
1249 packet.PutCString("QEnvironmentHexEncoded:");
1250 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001251 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001252 {
1253 if (response.IsOKResponse())
1254 return 0;
1255 uint8_t error = response.GetError();
1256 if (error)
1257 return error;
1258 if (response.IsUnsupportedResponse())
1259 m_supports_QEnvironmentHexEncoded = false;
1260 }
1261 }
1262
1263 }
1264 else if (m_supports_QEnvironment)
1265 {
1266 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +00001267 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001268 {
1269 if (response.IsOKResponse())
1270 return 0;
1271 uint8_t error = response.GetError();
1272 if (error)
1273 return error;
1274 if (response.IsUnsupportedResponse())
1275 m_supports_QEnvironment = false;
1276 }
Greg Clayton576d8832011-03-22 04:00:09 +00001277 }
1278 }
1279 return -1;
1280}
1281
Greg Claytonc4103b32011-05-08 04:53:50 +00001282int
1283GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1284{
1285 if (arch && arch[0])
1286 {
1287 StreamString packet;
1288 packet.Printf("QLaunchArch:%s", arch);
1289 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001290 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001291 {
1292 if (response.IsOKResponse())
1293 return 0;
1294 uint8_t error = response.GetError();
1295 if (error)
1296 return error;
1297 }
1298 }
1299 return -1;
1300}
1301
Greg Clayton576d8832011-03-22 04:00:09 +00001302bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001303GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1304 uint32_t &minor,
1305 uint32_t &update)
1306{
1307 if (GetHostInfo ())
1308 {
1309 if (m_os_version_major != UINT32_MAX)
1310 {
1311 major = m_os_version_major;
1312 minor = m_os_version_minor;
1313 update = m_os_version_update;
1314 return true;
1315 }
1316 }
1317 return false;
1318}
1319
1320bool
1321GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1322{
1323 if (GetHostInfo ())
1324 {
1325 if (!m_os_build.empty())
1326 {
1327 s = m_os_build;
1328 return true;
1329 }
1330 }
1331 s.clear();
1332 return false;
1333}
1334
1335
1336bool
1337GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1338{
1339 if (GetHostInfo ())
1340 {
1341 if (!m_os_kernel.empty())
1342 {
1343 s = m_os_kernel;
1344 return true;
1345 }
1346 }
1347 s.clear();
1348 return false;
1349}
1350
1351bool
1352GDBRemoteCommunicationClient::GetHostname (std::string &s)
1353{
1354 if (GetHostInfo ())
1355 {
1356 if (!m_hostname.empty())
1357 {
1358 s = m_hostname;
1359 return true;
1360 }
1361 }
1362 s.clear();
1363 return false;
1364}
1365
1366ArchSpec
1367GDBRemoteCommunicationClient::GetSystemArchitecture ()
1368{
1369 if (GetHostInfo ())
1370 return m_host_arch;
1371 return ArchSpec();
1372}
1373
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001374const lldb_private::ArchSpec &
1375GDBRemoteCommunicationClient::GetProcessArchitecture ()
1376{
1377 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1378 GetCurrentProcessInfo ();
1379 return m_process_arch;
1380}
1381
Greg Clayton1cb64962011-03-24 04:28:38 +00001382
1383bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001384GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001385{
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001386 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001387 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001388 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001389 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001390 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001391 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001392 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001393 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001394 std::string name;
1395 std::string value;
1396 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1397 uint32_t sub = 0;
1398 std::string arch_name;
1399 std::string os_name;
1400 std::string vendor_name;
1401 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001402 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001403 uint32_t pointer_byte_size = 0;
1404 StringExtractor extractor;
1405 ByteOrder byte_order = eByteOrderInvalid;
1406 uint32_t num_keys_decoded = 0;
1407 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001408 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001409 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001410 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001411 // exception type in big endian hex
1412 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1413 if (cpu != LLDB_INVALID_CPUTYPE)
1414 ++num_keys_decoded;
1415 }
1416 else if (name.compare("cpusubtype") == 0)
1417 {
1418 // exception count in big endian hex
1419 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
1420 if (sub != 0)
1421 ++num_keys_decoded;
1422 }
1423 else if (name.compare("arch") == 0)
1424 {
1425 arch_name.swap (value);
1426 ++num_keys_decoded;
1427 }
1428 else if (name.compare("triple") == 0)
1429 {
1430 // The triple comes as ASCII hex bytes since it contains '-' chars
1431 extractor.GetStringRef().swap(value);
1432 extractor.SetFilePos(0);
1433 extractor.GetHexByteString (triple);
1434 ++num_keys_decoded;
1435 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001436 else if (name.compare ("distribution_id") == 0)
1437 {
1438 extractor.GetStringRef ().swap (value);
1439 extractor.SetFilePos (0);
1440 extractor.GetHexByteString (distribution_id);
1441 ++num_keys_decoded;
1442 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001443 else if (name.compare("os_build") == 0)
1444 {
1445 extractor.GetStringRef().swap(value);
1446 extractor.SetFilePos(0);
1447 extractor.GetHexByteString (m_os_build);
1448 ++num_keys_decoded;
1449 }
1450 else if (name.compare("hostname") == 0)
1451 {
1452 extractor.GetStringRef().swap(value);
1453 extractor.SetFilePos(0);
1454 extractor.GetHexByteString (m_hostname);
1455 ++num_keys_decoded;
1456 }
1457 else if (name.compare("os_kernel") == 0)
1458 {
1459 extractor.GetStringRef().swap(value);
1460 extractor.SetFilePos(0);
1461 extractor.GetHexByteString (m_os_kernel);
1462 ++num_keys_decoded;
1463 }
1464 else if (name.compare("ostype") == 0)
1465 {
1466 os_name.swap (value);
1467 ++num_keys_decoded;
1468 }
1469 else if (name.compare("vendor") == 0)
1470 {
1471 vendor_name.swap(value);
1472 ++num_keys_decoded;
1473 }
1474 else if (name.compare("endian") == 0)
1475 {
1476 ++num_keys_decoded;
1477 if (value.compare("little") == 0)
1478 byte_order = eByteOrderLittle;
1479 else if (value.compare("big") == 0)
1480 byte_order = eByteOrderBig;
1481 else if (value.compare("pdp") == 0)
1482 byte_order = eByteOrderPDP;
1483 else
1484 --num_keys_decoded;
1485 }
1486 else if (name.compare("ptrsize") == 0)
1487 {
1488 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1489 if (pointer_byte_size != 0)
1490 ++num_keys_decoded;
1491 }
1492 else if (name.compare("os_version") == 0)
1493 {
1494 Args::StringToVersion (value.c_str(),
1495 m_os_version_major,
1496 m_os_version_minor,
1497 m_os_version_update);
1498 if (m_os_version_major != UINT32_MAX)
1499 ++num_keys_decoded;
1500 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001501 else if (name.compare("watchpoint_exceptions_received") == 0)
1502 {
1503 ++num_keys_decoded;
1504 if (strcmp(value.c_str(),"before") == 0)
1505 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1506 else if (strcmp(value.c_str(),"after") == 0)
1507 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1508 else
1509 --num_keys_decoded;
1510 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001511 else if (name.compare("default_packet_timeout") == 0)
1512 {
1513 m_default_packet_timeout = Args::StringToUInt32(value.c_str(), 0);
1514 if (m_default_packet_timeout > 0)
1515 {
1516 SetPacketTimeout(m_default_packet_timeout);
1517 ++num_keys_decoded;
1518 }
1519 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001520
Greg Clayton32e0a752011-03-30 18:16:51 +00001521 }
1522
1523 if (num_keys_decoded > 0)
1524 m_qHostInfo_is_valid = eLazyBoolYes;
1525
1526 if (triple.empty())
1527 {
1528 if (arch_name.empty())
1529 {
1530 if (cpu != LLDB_INVALID_CPUTYPE)
1531 {
1532 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1533 if (pointer_byte_size)
1534 {
1535 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1536 }
1537 if (byte_order != eByteOrderInvalid)
1538 {
1539 assert (byte_order == m_host_arch.GetByteOrder());
1540 }
Greg Clayton70512312012-05-08 01:45:38 +00001541
1542 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1543 {
1544 switch (m_host_arch.GetMachine())
1545 {
1546 case llvm::Triple::arm:
1547 case llvm::Triple::thumb:
1548 os_name = "ios";
1549 break;
1550 default:
1551 os_name = "macosx";
1552 break;
1553 }
1554 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001555 if (!vendor_name.empty())
1556 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1557 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001558 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001559
1560 }
1561 }
1562 else
1563 {
1564 std::string triple;
1565 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001566 if (!vendor_name.empty() || !os_name.empty())
1567 {
1568 triple += '-';
1569 if (vendor_name.empty())
1570 triple += "unknown";
1571 else
1572 triple += vendor_name;
1573 triple += '-';
1574 if (os_name.empty())
1575 triple += "unknown";
1576 else
1577 triple += os_name;
1578 }
1579 m_host_arch.SetTriple (triple.c_str());
1580
1581 llvm::Triple &host_triple = m_host_arch.GetTriple();
1582 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1583 {
1584 switch (m_host_arch.GetMachine())
1585 {
1586 case llvm::Triple::arm:
1587 case llvm::Triple::thumb:
1588 host_triple.setOS(llvm::Triple::IOS);
1589 break;
1590 default:
1591 host_triple.setOS(llvm::Triple::MacOSX);
1592 break;
1593 }
1594 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001595 if (pointer_byte_size)
1596 {
1597 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1598 }
1599 if (byte_order != eByteOrderInvalid)
1600 {
1601 assert (byte_order == m_host_arch.GetByteOrder());
1602 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001603
Greg Clayton1cb64962011-03-24 04:28:38 +00001604 }
1605 }
1606 else
1607 {
Greg Clayton70512312012-05-08 01:45:38 +00001608 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001609 if (pointer_byte_size)
1610 {
1611 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1612 }
1613 if (byte_order != eByteOrderInvalid)
1614 {
1615 assert (byte_order == m_host_arch.GetByteOrder());
1616 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001617 }
1618 if (!distribution_id.empty ())
1619 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00001620 }
Greg Clayton576d8832011-03-22 04:00:09 +00001621 }
1622 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001623 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001624}
1625
1626int
1627GDBRemoteCommunicationClient::SendAttach
1628(
1629 lldb::pid_t pid,
1630 StringExtractorGDBRemote& response
1631)
1632{
1633 if (pid != LLDB_INVALID_PROCESS_ID)
1634 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001635 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001636 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001637 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00001638 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001639 {
1640 if (response.IsErrorResponse())
1641 return response.GetError();
1642 return 0;
1643 }
1644 }
1645 return -1;
1646}
1647
1648const lldb_private::ArchSpec &
1649GDBRemoteCommunicationClient::GetHostArchitecture ()
1650{
Greg Clayton32e0a752011-03-30 18:16:51 +00001651 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001652 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001653 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001654}
1655
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001656uint32_t
1657GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1658{
1659 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1660 GetHostInfo ();
1661 return m_default_packet_timeout;
1662}
1663
Greg Clayton576d8832011-03-22 04:00:09 +00001664addr_t
1665GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1666{
Greg Clayton70b57652011-05-15 01:25:55 +00001667 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001668 {
Greg Clayton70b57652011-05-15 01:25:55 +00001669 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001670 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001671 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001672 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001673 permissions & lldb::ePermissionsReadable ? "r" : "",
1674 permissions & lldb::ePermissionsWritable ? "w" : "",
1675 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001676 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001677 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001678 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001679 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001680 if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001681 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1682 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001683 else
1684 {
1685 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1686 }
Greg Clayton576d8832011-03-22 04:00:09 +00001687 }
1688 return LLDB_INVALID_ADDRESS;
1689}
1690
1691bool
1692GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1693{
Greg Clayton70b57652011-05-15 01:25:55 +00001694 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001695 {
Greg Clayton70b57652011-05-15 01:25:55 +00001696 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001697 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001698 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001699 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001700 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001701 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001702 {
1703 if (response.IsOKResponse())
1704 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001705 }
1706 else
1707 {
1708 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00001709 }
Greg Clayton576d8832011-03-22 04:00:09 +00001710 }
1711 return false;
1712}
1713
Jim Inghamacff8952013-05-02 00:27:30 +00001714Error
1715GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00001716{
Jim Inghamacff8952013-05-02 00:27:30 +00001717 Error error;
1718
1719 if (keep_stopped)
1720 {
1721 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1722 {
1723 char packet[64];
1724 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001725 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00001726 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001727 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001728 {
1729 m_supports_detach_stay_stopped = eLazyBoolYes;
1730 }
1731 else
1732 {
1733 m_supports_detach_stay_stopped = eLazyBoolNo;
1734 }
1735 }
1736
1737 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1738 {
1739 error.SetErrorString("Stays stopped not supported by this target.");
1740 return error;
1741 }
1742 else
1743 {
Greg Clayton3dedae12013-12-06 21:45:27 +00001744 PacketResult packet_result = SendPacket ("D1", 2);
1745 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001746 error.SetErrorString ("Sending extended disconnect packet failed.");
1747 }
1748 }
1749 else
1750 {
Greg Clayton3dedae12013-12-06 21:45:27 +00001751 PacketResult packet_result = SendPacket ("D", 1);
1752 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001753 error.SetErrorString ("Sending disconnect packet failed.");
1754 }
1755 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001756}
1757
Greg Clayton46fb5582011-11-18 07:03:08 +00001758Error
1759GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1760 lldb_private::MemoryRegionInfo &region_info)
1761{
1762 Error error;
1763 region_info.Clear();
1764
1765 if (m_supports_memory_region_info != eLazyBoolNo)
1766 {
1767 m_supports_memory_region_info = eLazyBoolYes;
1768 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001769 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001770 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00001771 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001772 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00001773 {
1774 std::string name;
1775 std::string value;
1776 addr_t addr_value;
1777 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00001778 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00001779 while (success && response.GetNameColonValue(name, value))
1780 {
1781 if (name.compare ("start") == 0)
1782 {
1783 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1784 if (success)
1785 region_info.GetRange().SetRangeBase(addr_value);
1786 }
1787 else if (name.compare ("size") == 0)
1788 {
1789 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1790 if (success)
1791 region_info.GetRange().SetByteSize (addr_value);
1792 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001793 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00001794 {
Jason Molendacb349ee2011-12-13 05:39:38 +00001795 saw_permissions = true;
1796 if (region_info.GetRange().Contains (addr))
1797 {
1798 if (value.find('r') != std::string::npos)
1799 region_info.SetReadable (MemoryRegionInfo::eYes);
1800 else
1801 region_info.SetReadable (MemoryRegionInfo::eNo);
1802
1803 if (value.find('w') != std::string::npos)
1804 region_info.SetWritable (MemoryRegionInfo::eYes);
1805 else
1806 region_info.SetWritable (MemoryRegionInfo::eNo);
1807
1808 if (value.find('x') != std::string::npos)
1809 region_info.SetExecutable (MemoryRegionInfo::eYes);
1810 else
1811 region_info.SetExecutable (MemoryRegionInfo::eNo);
1812 }
1813 else
1814 {
1815 // The reported region does not contain this address -- we're looking at an unmapped page
1816 region_info.SetReadable (MemoryRegionInfo::eNo);
1817 region_info.SetWritable (MemoryRegionInfo::eNo);
1818 region_info.SetExecutable (MemoryRegionInfo::eNo);
1819 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001820 }
1821 else if (name.compare ("error") == 0)
1822 {
1823 StringExtractorGDBRemote name_extractor;
1824 // Swap "value" over into "name_extractor"
1825 name_extractor.GetStringRef().swap(value);
1826 // Now convert the HEX bytes into a string value
1827 name_extractor.GetHexByteString (value);
1828 error.SetErrorString(value.c_str());
1829 }
1830 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001831
1832 // We got a valid address range back but no permissions -- which means this is an unmapped page
1833 if (region_info.GetRange().IsValid() && saw_permissions == false)
1834 {
1835 region_info.SetReadable (MemoryRegionInfo::eNo);
1836 region_info.SetWritable (MemoryRegionInfo::eNo);
1837 region_info.SetExecutable (MemoryRegionInfo::eNo);
1838 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001839 }
1840 else
1841 {
1842 m_supports_memory_region_info = eLazyBoolNo;
1843 }
1844 }
1845
1846 if (m_supports_memory_region_info == eLazyBoolNo)
1847 {
1848 error.SetErrorString("qMemoryRegionInfo is not supported");
1849 }
1850 if (error.Fail())
1851 region_info.Clear();
1852 return error;
1853
1854}
1855
Johnny Chen64637202012-05-23 21:09:52 +00001856Error
1857GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1858{
1859 Error error;
1860
1861 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1862 {
1863 num = m_num_supported_hardware_watchpoints;
1864 return error;
1865 }
1866
1867 // Set num to 0 first.
1868 num = 0;
1869 if (m_supports_watchpoint_support_info != eLazyBoolNo)
1870 {
1871 char packet[64];
1872 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001873 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00001874 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001875 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00001876 {
1877 m_supports_watchpoint_support_info = eLazyBoolYes;
1878 std::string name;
1879 std::string value;
1880 while (response.GetNameColonValue(name, value))
1881 {
1882 if (name.compare ("num") == 0)
1883 {
1884 num = Args::StringToUInt32(value.c_str(), 0, 0);
1885 m_num_supported_hardware_watchpoints = num;
1886 }
1887 }
1888 }
1889 else
1890 {
1891 m_supports_watchpoint_support_info = eLazyBoolNo;
1892 }
1893 }
1894
1895 if (m_supports_watchpoint_support_info == eLazyBoolNo)
1896 {
1897 error.SetErrorString("qWatchpointSupportInfo is not supported");
1898 }
1899 return error;
1900
1901}
Greg Clayton46fb5582011-11-18 07:03:08 +00001902
Enrico Granataf04a2192012-07-13 23:18:48 +00001903lldb_private::Error
1904GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
1905{
1906 Error error(GetWatchpointSupportInfo(num));
1907 if (error.Success())
1908 error = GetWatchpointsTriggerAfterInstruction(after);
1909 return error;
1910}
1911
1912lldb_private::Error
1913GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
1914{
1915 Error error;
1916
1917 // we assume watchpoints will happen after running the relevant opcode
1918 // and we only want to override this behavior if we have explicitly
1919 // received a qHostInfo telling us otherwise
1920 if (m_qHostInfo_is_valid != eLazyBoolYes)
1921 after = true;
1922 else
1923 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1924 return error;
1925}
1926
Greg Clayton576d8832011-03-22 04:00:09 +00001927int
1928GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1929{
1930 if (path && path[0])
1931 {
1932 StreamString packet;
1933 packet.PutCString("QSetSTDIN:");
1934 packet.PutBytesAsRawHex8(path, strlen(path));
1935
1936 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001937 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001938 {
1939 if (response.IsOKResponse())
1940 return 0;
1941 uint8_t error = response.GetError();
1942 if (error)
1943 return error;
1944 }
1945 }
1946 return -1;
1947}
1948
1949int
1950GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1951{
1952 if (path && path[0])
1953 {
1954 StreamString packet;
1955 packet.PutCString("QSetSTDOUT:");
1956 packet.PutBytesAsRawHex8(path, strlen(path));
1957
1958 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001959 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001960 {
1961 if (response.IsOKResponse())
1962 return 0;
1963 uint8_t error = response.GetError();
1964 if (error)
1965 return error;
1966 }
1967 }
1968 return -1;
1969}
1970
1971int
1972GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1973{
1974 if (path && path[0])
1975 {
1976 StreamString packet;
1977 packet.PutCString("QSetSTDERR:");
1978 packet.PutBytesAsRawHex8(path, strlen(path));
1979
1980 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001981 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001982 {
1983 if (response.IsOKResponse())
1984 return 0;
1985 uint8_t error = response.GetError();
1986 if (error)
1987 return error;
1988 }
1989 }
1990 return -1;
1991}
1992
Greg Claytonfbb76342013-11-20 21:07:01 +00001993bool
1994GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd)
1995{
1996 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001997 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00001998 {
1999 if (response.IsUnsupportedResponse())
2000 return false;
2001 if (response.IsErrorResponse())
2002 return false;
2003 response.GetHexByteString (cwd);
2004 return !cwd.empty();
2005 }
2006 return false;
2007}
2008
Greg Clayton576d8832011-03-22 04:00:09 +00002009int
2010GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
2011{
2012 if (path && path[0])
2013 {
2014 StreamString packet;
2015 packet.PutCString("QSetWorkingDir:");
2016 packet.PutBytesAsRawHex8(path, strlen(path));
2017
2018 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002019 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002020 {
2021 if (response.IsOKResponse())
2022 return 0;
2023 uint8_t error = response.GetError();
2024 if (error)
2025 return error;
2026 }
2027 }
2028 return -1;
2029}
2030
2031int
2032GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2033{
Greg Clayton32e0a752011-03-30 18:16:51 +00002034 char packet[32];
2035 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002036 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002037 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002038 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002039 {
2040 if (response.IsOKResponse())
2041 return 0;
2042 uint8_t error = response.GetError();
2043 if (error)
2044 return error;
2045 }
2046 return -1;
2047}
Greg Clayton32e0a752011-03-30 18:16:51 +00002048
2049bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002050GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002051{
2052 if (response.IsNormalResponse())
2053 {
2054 std::string name;
2055 std::string value;
2056 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002057
2058 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2059 uint32_t sub = 0;
2060 std::string vendor;
2061 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002062
2063 while (response.GetNameColonValue(name, value))
2064 {
2065 if (name.compare("pid") == 0)
2066 {
2067 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2068 }
2069 else if (name.compare("ppid") == 0)
2070 {
2071 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2072 }
2073 else if (name.compare("uid") == 0)
2074 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002075 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002076 }
2077 else if (name.compare("euid") == 0)
2078 {
2079 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2080 }
2081 else if (name.compare("gid") == 0)
2082 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002083 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002084 }
2085 else if (name.compare("egid") == 0)
2086 {
2087 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2088 }
2089 else if (name.compare("triple") == 0)
2090 {
2091 // The triple comes as ASCII hex bytes since it contains '-' chars
2092 extractor.GetStringRef().swap(value);
2093 extractor.SetFilePos(0);
2094 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002095 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002096 }
2097 else if (name.compare("name") == 0)
2098 {
2099 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002100 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002101 // control the characters in a process name
2102 extractor.GetStringRef().swap(value);
2103 extractor.SetFilePos(0);
2104 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002105 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002106 }
Jason Molenda89c37492014-01-27 22:23:20 +00002107 else if (name.compare("cputype") == 0)
2108 {
2109 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2110 }
2111 else if (name.compare("cpusubtype") == 0)
2112 {
2113 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2114 }
2115 else if (name.compare("vendor") == 0)
2116 {
2117 vendor = value;
2118 }
2119 else if (name.compare("ostype") == 0)
2120 {
2121 os_type = value;
2122 }
2123 }
2124
2125 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2126 {
2127 if (vendor == "apple")
2128 {
2129 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2130 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2131 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2132 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002133 }
2134
2135 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2136 return true;
2137 }
2138 return false;
2139}
2140
2141bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002142GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002143{
2144 process_info.Clear();
2145
2146 if (m_supports_qProcessInfoPID)
2147 {
2148 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002149 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002150 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002151 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002152 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002153 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002154 return DecodeProcessInfoResponse (response, process_info);
2155 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002156 else
2157 {
2158 m_supports_qProcessInfoPID = false;
2159 return false;
2160 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002161 }
2162 return false;
2163}
2164
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002165bool
2166GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
2167{
2168 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2169 return true;
2170 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2171 return false;
2172
2173 GetHostInfo ();
2174
2175 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002176 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002177 {
2178 if (response.IsNormalResponse())
2179 {
2180 std::string name;
2181 std::string value;
2182 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2183 uint32_t sub = 0;
2184 std::string arch_name;
2185 std::string os_name;
2186 std::string vendor_name;
2187 std::string triple;
2188 uint32_t pointer_byte_size = 0;
2189 StringExtractor extractor;
2190 ByteOrder byte_order = eByteOrderInvalid;
2191 uint32_t num_keys_decoded = 0;
2192 while (response.GetNameColonValue(name, value))
2193 {
2194 if (name.compare("cputype") == 0)
2195 {
2196 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2197 if (cpu != LLDB_INVALID_CPUTYPE)
2198 ++num_keys_decoded;
2199 }
2200 else if (name.compare("cpusubtype") == 0)
2201 {
2202 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2203 if (sub != 0)
2204 ++num_keys_decoded;
2205 }
2206 else if (name.compare("ostype") == 0)
2207 {
2208 os_name.swap (value);
2209 ++num_keys_decoded;
2210 }
2211 else if (name.compare("vendor") == 0)
2212 {
2213 vendor_name.swap(value);
2214 ++num_keys_decoded;
2215 }
2216 else if (name.compare("endian") == 0)
2217 {
2218 ++num_keys_decoded;
2219 if (value.compare("little") == 0)
2220 byte_order = eByteOrderLittle;
2221 else if (value.compare("big") == 0)
2222 byte_order = eByteOrderBig;
2223 else if (value.compare("pdp") == 0)
2224 byte_order = eByteOrderPDP;
2225 else
2226 --num_keys_decoded;
2227 }
2228 else if (name.compare("ptrsize") == 0)
2229 {
2230 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
2231 if (pointer_byte_size != 0)
2232 ++num_keys_decoded;
2233 }
2234 }
2235 if (num_keys_decoded > 0)
2236 m_qProcessInfo_is_valid = eLazyBoolYes;
2237 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
2238 {
2239 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2240 if (pointer_byte_size)
2241 {
2242 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2243 }
2244 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2245 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2246 return true;
2247 }
2248 }
2249 }
2250 else
2251 {
2252 m_qProcessInfo_is_valid = eLazyBoolNo;
2253 }
2254
2255 return false;
2256}
2257
2258
Greg Clayton32e0a752011-03-30 18:16:51 +00002259uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002260GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2261 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002262{
2263 process_infos.Clear();
2264
2265 if (m_supports_qfProcessInfo)
2266 {
2267 StreamString packet;
2268 packet.PutCString ("qfProcessInfo");
2269 if (!match_info.MatchAllProcesses())
2270 {
2271 packet.PutChar (':');
2272 const char *name = match_info.GetProcessInfo().GetName();
2273 bool has_name_match = false;
2274 if (name && name[0])
2275 {
2276 has_name_match = true;
2277 NameMatchType name_match_type = match_info.GetNameMatchType();
2278 switch (name_match_type)
2279 {
2280 case eNameMatchIgnore:
2281 has_name_match = false;
2282 break;
2283
2284 case eNameMatchEquals:
2285 packet.PutCString ("name_match:equals;");
2286 break;
2287
2288 case eNameMatchContains:
2289 packet.PutCString ("name_match:contains;");
2290 break;
2291
2292 case eNameMatchStartsWith:
2293 packet.PutCString ("name_match:starts_with;");
2294 break;
2295
2296 case eNameMatchEndsWith:
2297 packet.PutCString ("name_match:ends_with;");
2298 break;
2299
2300 case eNameMatchRegularExpression:
2301 packet.PutCString ("name_match:regex;");
2302 break;
2303 }
2304 if (has_name_match)
2305 {
2306 packet.PutCString ("name:");
2307 packet.PutBytesAsRawHex8(name, ::strlen(name));
2308 packet.PutChar (';');
2309 }
2310 }
2311
2312 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002313 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002314 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002315 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002316 if (match_info.GetProcessInfo().UserIDIsValid())
2317 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2318 if (match_info.GetProcessInfo().GroupIDIsValid())
2319 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002320 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2321 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2322 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2323 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2324 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2325 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2326 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2327 {
2328 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2329 const llvm::Triple &triple = match_arch.GetTriple();
2330 packet.PutCString("triple:");
2331 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
2332 packet.PutChar (';');
2333 }
2334 }
2335 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002336 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002337 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002338 do
2339 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002340 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002341 if (!DecodeProcessInfoResponse (response, process_info))
2342 break;
2343 process_infos.Append(process_info);
2344 response.GetStringRef().clear();
2345 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00002346 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00002347 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002348 else
2349 {
2350 m_supports_qfProcessInfo = false;
2351 return 0;
2352 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002353 }
2354 return process_infos.GetSize();
2355
2356}
2357
2358bool
2359GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2360{
2361 if (m_supports_qUserName)
2362 {
2363 char packet[32];
2364 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002365 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002366 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002367 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002368 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002369 if (response.IsNormalResponse())
2370 {
2371 // Make sure we parsed the right number of characters. The response is
2372 // the hex encoded user name and should make up the entire packet.
2373 // If there are any non-hex ASCII bytes, the length won't match below..
2374 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2375 return true;
2376 }
2377 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002378 else
2379 {
2380 m_supports_qUserName = false;
2381 return false;
2382 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002383 }
2384 return false;
2385
2386}
2387
2388bool
2389GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2390{
2391 if (m_supports_qGroupName)
2392 {
2393 char packet[32];
2394 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002395 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002396 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002397 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002398 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002399 if (response.IsNormalResponse())
2400 {
2401 // Make sure we parsed the right number of characters. The response is
2402 // the hex encoded group name and should make up the entire packet.
2403 // If there are any non-hex ASCII bytes, the length won't match below..
2404 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2405 return true;
2406 }
2407 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002408 else
2409 {
2410 m_supports_qGroupName = false;
2411 return false;
2412 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002413 }
2414 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002415}
Greg Clayton32e0a752011-03-30 18:16:51 +00002416
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002417void
2418GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2419{
2420 uint32_t i;
2421 TimeValue start_time, end_time;
2422 uint64_t total_time_nsec;
2423 float packets_per_second;
2424 if (SendSpeedTestPacket (0, 0))
2425 {
2426 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2)
2427 {
2428 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2)
2429 {
2430 start_time = TimeValue::Now();
2431 for (i=0; i<num_packets; ++i)
2432 {
2433 SendSpeedTestPacket (send_size, recv_size);
2434 }
2435 end_time = TimeValue::Now();
2436 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002437 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Daniel Malead01b2952012-11-29 21:49:15 +00002438 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 +00002439 num_packets,
2440 send_size,
2441 recv_size,
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002442 total_time_nsec / TimeValue::NanoSecPerSec,
2443 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002444 packets_per_second);
2445 if (recv_size == 0)
2446 recv_size = 32;
2447 }
2448 if (send_size == 0)
2449 send_size = 32;
2450 }
2451 }
2452 else
2453 {
2454 start_time = TimeValue::Now();
2455 for (i=0; i<num_packets; ++i)
2456 {
2457 GetCurrentProcessID ();
2458 }
2459 end_time = TimeValue::Now();
2460 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002461 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Daniel Malead01b2952012-11-29 21:49:15 +00002462 printf ("%u 'qC' packets packets in 0x%" PRIu64 "%9.9" PRIu64 " sec for %f packets/sec.\n",
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002463 num_packets,
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002464 total_time_nsec / TimeValue::NanoSecPerSec,
2465 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002466 packets_per_second);
2467 }
2468}
2469
2470bool
2471GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2472{
2473 StreamString packet;
2474 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2475 uint32_t bytes_left = send_size;
2476 while (bytes_left > 0)
2477 {
2478 if (bytes_left >= 26)
2479 {
2480 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2481 bytes_left -= 26;
2482 }
2483 else
2484 {
2485 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2486 bytes_left = 0;
2487 }
2488 }
2489
2490 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002491 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00002492}
Greg Clayton8b82f082011-04-12 05:54:46 +00002493
2494uint16_t
Greg Claytondbf04572013-12-04 19:40:33 +00002495GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
Greg Clayton8b82f082011-04-12 05:54:46 +00002496{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002497 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00002498 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002499 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00002500 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002501 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00002502 if (remote_accept_hostname && remote_accept_hostname[0])
2503 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002504 else
2505 {
Greg Claytondbf04572013-12-04 19:40:33 +00002506 if (Host::GetHostname (hostname))
2507 {
2508 // Make the GDB server we launch only accept connections from this host
2509 stream.Printf("host:%s;", hostname.c_str());
2510 }
2511 else
2512 {
2513 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2514 stream.Printf("host:*;");
2515 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002516 }
2517 const char *packet = stream.GetData();
2518 int packet_len = stream.GetSize();
2519
Greg Clayton3dedae12013-12-06 21:45:27 +00002520 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002521 {
2522 std::string name;
2523 std::string value;
2524 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002525 while (response.GetNameColonValue(name, value))
2526 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00002527 if (name.compare("port") == 0)
Greg Clayton8b82f082011-04-12 05:54:46 +00002528 port = Args::StringToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002529 else if (name.compare("pid") == 0)
2530 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00002531 }
2532 return port;
2533 }
2534 return 0;
2535}
2536
2537bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00002538GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2539{
2540 StreamString stream;
2541 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2542 const char *packet = stream.GetData();
2543 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00002544
Daniel Maleae0f8f572013-08-26 23:57:52 +00002545 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002546 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002547 {
2548 if (response.IsOKResponse())
2549 return true;
2550 }
2551 return false;
2552}
2553
2554bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002555GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002556{
2557 if (m_curr_tid == tid)
2558 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002559
Greg Clayton8b82f082011-04-12 05:54:46 +00002560 char packet[32];
2561 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002562 if (tid == UINT64_MAX)
2563 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002564 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002565 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002566 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002567 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002568 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002569 {
2570 if (response.IsOKResponse())
2571 {
2572 m_curr_tid = tid;
2573 return true;
2574 }
2575 }
2576 return false;
2577}
2578
2579bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002580GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002581{
2582 if (m_curr_tid_run == tid)
2583 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002584
Greg Clayton8b82f082011-04-12 05:54:46 +00002585 char packet[32];
2586 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002587 if (tid == UINT64_MAX)
2588 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002589 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002590 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2591
Andy Gibbsa297a972013-06-19 19:04:53 +00002592 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002593 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002594 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002595 {
2596 if (response.IsOKResponse())
2597 {
2598 m_curr_tid_run = tid;
2599 return true;
2600 }
2601 }
2602 return false;
2603}
2604
2605bool
2606GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2607{
Greg Clayton3dedae12013-12-06 21:45:27 +00002608 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002609 return response.IsNormalResponse();
2610 return false;
2611}
2612
2613bool
Greg Claytonf402f782012-10-13 02:11:55 +00002614GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00002615{
2616 if (m_supports_qThreadStopInfo)
2617 {
2618 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00002619 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002620 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002621 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002622 {
Greg Claytonef8180a2013-10-15 00:14:28 +00002623 if (response.IsUnsupportedResponse())
2624 m_supports_qThreadStopInfo = false;
2625 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002626 return true;
2627 else
2628 return false;
2629 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002630 else
2631 {
2632 m_supports_qThreadStopInfo = false;
2633 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002634 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002635 return false;
2636}
2637
2638
2639uint8_t
2640GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2641{
2642 switch (type)
2643 {
2644 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break;
2645 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break;
2646 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break;
2647 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break;
2648 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break;
Greg Clayton8b82f082011-04-12 05:54:46 +00002649 }
2650
2651 char packet[64];
2652 const int packet_len = ::snprintf (packet,
2653 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00002654 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00002655 insert ? 'Z' : 'z',
2656 type,
2657 addr,
2658 length);
2659
Andy Gibbsa297a972013-06-19 19:04:53 +00002660 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002661 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002662 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002663 {
2664 if (response.IsOKResponse())
2665 return 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002666 else if (response.IsErrorResponse())
2667 return response.GetError();
2668 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002669 else
2670 {
2671 switch (type)
2672 {
2673 case eBreakpointSoftware: m_supports_z0 = false; break;
2674 case eBreakpointHardware: m_supports_z1 = false; break;
2675 case eWatchpointWrite: m_supports_z2 = false; break;
2676 case eWatchpointRead: m_supports_z3 = false; break;
2677 case eWatchpointReadWrite: m_supports_z4 = false; break;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002678 }
2679 }
2680
Greg Clayton8b82f082011-04-12 05:54:46 +00002681 return UINT8_MAX;
2682}
Greg Claytonadc00cb2011-05-20 23:38:13 +00002683
2684size_t
2685GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2686 bool &sequence_mutex_unavailable)
2687{
2688 Mutex::Locker locker;
2689 thread_ids.clear();
2690
Jim Ingham4ceb9282012-06-08 22:50:40 +00002691 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002692 {
2693 sequence_mutex_unavailable = false;
2694 StringExtractorGDBRemote response;
2695
Greg Clayton3dedae12013-12-06 21:45:27 +00002696 PacketResult packet_result;
2697 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
2698 packet_result == PacketResult::Success && response.IsNormalResponse();
2699 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002700 {
2701 char ch = response.GetChar();
2702 if (ch == 'l')
2703 break;
2704 if (ch == 'm')
2705 {
2706 do
2707 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00002708 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00002709
2710 if (tid != LLDB_INVALID_THREAD_ID)
2711 {
2712 thread_ids.push_back (tid);
2713 }
2714 ch = response.GetChar(); // Skip the command separator
2715 } while (ch == ','); // Make sure we got a comma separator
2716 }
2717 }
2718 }
2719 else
2720 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00002721#if defined (LLDB_CONFIGURATION_DEBUG)
2722 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2723#else
Greg Clayton5160ce52013-03-27 23:08:40 +00002724 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00002725 if (log)
2726 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00002727#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00002728 sequence_mutex_unavailable = true;
2729 }
2730 return thread_ids.size();
2731}
Greg Clayton37a0a242012-04-11 00:24:49 +00002732
2733lldb::addr_t
2734GDBRemoteCommunicationClient::GetShlibInfoAddr()
2735{
2736 if (!IsRunning())
2737 {
2738 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002739 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00002740 {
2741 if (response.IsNormalResponse())
2742 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2743 }
2744 }
2745 return LLDB_INVALID_ADDRESS;
2746}
2747
Daniel Maleae0f8f572013-08-26 23:57:52 +00002748lldb_private::Error
2749GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL
2750 const char *working_dir, // Pass NULL to use the current working directory
2751 int *status_ptr, // Pass NULL if you don't want the process exit status
2752 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
2753 std::string *command_output, // Pass NULL if you don't want the command output
2754 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
2755{
2756 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00002757 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002758 stream.PutBytesAsRawHex8(command, strlen(command));
2759 stream.PutChar(',');
2760 stream.PutHex32(timeout_sec);
2761 if (working_dir && *working_dir)
2762 {
2763 stream.PutChar(',');
2764 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
2765 }
2766 const char *packet = stream.GetData();
2767 int packet_len = stream.GetSize();
2768 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002769 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002770 {
2771 if (response.GetChar() != 'F')
2772 return Error("malformed reply");
2773 if (response.GetChar() != ',')
2774 return Error("malformed reply");
2775 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2776 if (exitcode == UINT32_MAX)
2777 return Error("unable to run remote process");
2778 else if (status_ptr)
2779 *status_ptr = exitcode;
2780 if (response.GetChar() != ',')
2781 return Error("malformed reply");
2782 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2783 if (signo_ptr)
2784 *signo_ptr = signo;
2785 if (response.GetChar() != ',')
2786 return Error("malformed reply");
2787 std::string output;
2788 response.GetEscapedBinaryData(output);
2789 if (command_output)
2790 command_output->assign(output);
2791 return Error();
2792 }
2793 return Error("unable to send packet");
2794}
2795
Greg Claytonfbb76342013-11-20 21:07:01 +00002796Error
2797GDBRemoteCommunicationClient::MakeDirectory (const char *path,
2798 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002799{
2800 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00002801 stream.PutCString("qPlatform_mkdir:");
2802 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002803 stream.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00002804 stream.PutBytesAsRawHex8(path, strlen(path));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002805 const char *packet = stream.GetData();
2806 int packet_len = stream.GetSize();
2807 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002808 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002809 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002810 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002811 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002812 return Error();
Daniel Maleae0f8f572013-08-26 23:57:52 +00002813
2814}
2815
Greg Claytonfbb76342013-11-20 21:07:01 +00002816Error
2817GDBRemoteCommunicationClient::SetFilePermissions (const char *path,
2818 uint32_t file_permissions)
2819{
2820 lldb_private::StreamString stream;
2821 stream.PutCString("qPlatform_chmod:");
2822 stream.PutHex32(file_permissions);
2823 stream.PutChar(',');
2824 stream.PutBytesAsRawHex8(path, strlen(path));
2825 const char *packet = stream.GetData();
2826 int packet_len = stream.GetSize();
2827 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002828 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002829 {
2830 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
2831 }
2832 return Error();
2833
2834}
2835
Daniel Maleae0f8f572013-08-26 23:57:52 +00002836static uint64_t
2837ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
2838 uint64_t fail_result,
2839 Error &error)
2840{
2841 response.SetFilePos(0);
2842 if (response.GetChar() != 'F')
2843 return fail_result;
2844 int32_t result = response.GetS32 (-2);
2845 if (result == -2)
2846 return fail_result;
2847 if (response.GetChar() == ',')
2848 {
2849 int result_errno = response.GetS32 (-2);
2850 if (result_errno != -2)
2851 error.SetError(result_errno, eErrorTypePOSIX);
2852 else
2853 error.SetError(-1, eErrorTypeGeneric);
2854 }
2855 else
2856 error.Clear();
2857 return result;
2858}
2859lldb::user_id_t
2860GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
2861 uint32_t flags,
2862 mode_t mode,
2863 Error &error)
2864{
2865 lldb_private::StreamString stream;
2866 stream.PutCString("vFile:open:");
2867 std::string path (file_spec.GetPath());
2868 if (path.empty())
2869 return UINT64_MAX;
2870 stream.PutCStringAsRawHex8(path.c_str());
2871 stream.PutChar(',');
2872 const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags);
2873 stream.PutHex32(posix_open_flags);
2874 stream.PutChar(',');
2875 stream.PutHex32(mode);
2876 const char* packet = stream.GetData();
2877 int packet_len = stream.GetSize();
2878 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002879 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002880 {
2881 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
2882 }
2883 return UINT64_MAX;
2884}
2885
2886bool
2887GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
2888 Error &error)
2889{
2890 lldb_private::StreamString stream;
2891 stream.Printf("vFile:close:%i", (int)fd);
2892 const char* packet = stream.GetData();
2893 int packet_len = stream.GetSize();
2894 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002895 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002896 {
2897 return ParseHostIOPacketResponse (response, -1, error) == 0;
2898 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00002899 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002900}
2901
2902// Extension of host I/O packets to get the file size.
2903lldb::user_id_t
2904GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
2905{
2906 lldb_private::StreamString stream;
2907 stream.PutCString("vFile:size:");
2908 std::string path (file_spec.GetPath());
2909 stream.PutCStringAsRawHex8(path.c_str());
2910 const char* packet = stream.GetData();
2911 int packet_len = stream.GetSize();
2912 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002913 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002914 {
2915 if (response.GetChar() != 'F')
2916 return UINT64_MAX;
2917 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2918 return retcode;
2919 }
2920 return UINT64_MAX;
2921}
2922
Greg Claytonfbb76342013-11-20 21:07:01 +00002923Error
2924GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002925{
Greg Claytonfbb76342013-11-20 21:07:01 +00002926 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002927 lldb_private::StreamString stream;
2928 stream.PutCString("vFile:mode:");
Greg Claytonfbb76342013-11-20 21:07:01 +00002929 stream.PutCStringAsRawHex8(path);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002930 const char* packet = stream.GetData();
2931 int packet_len = stream.GetSize();
2932 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002933 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002934 {
2935 if (response.GetChar() != 'F')
2936 {
2937 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002938 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002939 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002940 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002941 const uint32_t mode = response.GetS32(-1);
2942 if (mode == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002943 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002944 if (response.GetChar() == ',')
2945 {
2946 int response_errno = response.GetS32(-1);
2947 if (response_errno > 0)
2948 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2949 else
2950 error.SetErrorToGenericError();
2951 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002952 else
2953 error.SetErrorToGenericError();
2954 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002955 else
2956 {
2957 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
2958 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002959 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002960 }
2961 else
2962 {
2963 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
2964 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002965 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002966}
2967
2968uint64_t
2969GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
2970 uint64_t offset,
2971 void *dst,
2972 uint64_t dst_len,
2973 Error &error)
2974{
2975 lldb_private::StreamString stream;
2976 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
2977 const char* packet = stream.GetData();
2978 int packet_len = stream.GetSize();
2979 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002980 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002981 {
2982 if (response.GetChar() != 'F')
2983 return 0;
2984 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2985 if (retcode == UINT32_MAX)
2986 return retcode;
2987 const char next = (response.Peek() ? *response.Peek() : 0);
2988 if (next == ',')
2989 return 0;
2990 if (next == ';')
2991 {
2992 response.GetChar(); // skip the semicolon
2993 std::string buffer;
2994 if (response.GetEscapedBinaryData(buffer))
2995 {
2996 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
2997 if (data_to_write > 0)
2998 memcpy(dst, &buffer[0], data_to_write);
2999 return data_to_write;
3000 }
3001 }
3002 }
3003 return 0;
3004}
3005
3006uint64_t
3007GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3008 uint64_t offset,
3009 const void* src,
3010 uint64_t src_len,
3011 Error &error)
3012{
3013 lldb_private::StreamGDBRemote stream;
3014 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3015 stream.PutEscapedBytes(src, src_len);
3016 const char* packet = stream.GetData();
3017 int packet_len = stream.GetSize();
3018 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003019 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003020 {
3021 if (response.GetChar() != 'F')
3022 {
3023 error.SetErrorStringWithFormat("write file failed");
3024 return 0;
3025 }
3026 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3027 if (bytes_written == UINT64_MAX)
3028 {
3029 error.SetErrorToGenericError();
3030 if (response.GetChar() == ',')
3031 {
3032 int response_errno = response.GetS32(-1);
3033 if (response_errno > 0)
3034 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3035 }
3036 return 0;
3037 }
3038 return bytes_written;
3039 }
3040 else
3041 {
3042 error.SetErrorString ("failed to send vFile:pwrite packet");
3043 }
3044 return 0;
3045}
3046
Greg Claytonfbb76342013-11-20 21:07:01 +00003047Error
3048GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst)
3049{
3050 Error error;
3051 lldb_private::StreamGDBRemote stream;
3052 stream.PutCString("vFile:symlink:");
3053 // the unix symlink() command reverses its parameters where the dst if first,
3054 // so we follow suit here
3055 stream.PutCStringAsRawHex8(dst);
3056 stream.PutChar(',');
3057 stream.PutCStringAsRawHex8(src);
3058 const char* packet = stream.GetData();
3059 int packet_len = stream.GetSize();
3060 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003061 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003062 {
3063 if (response.GetChar() == 'F')
3064 {
3065 uint32_t result = response.GetU32(UINT32_MAX);
3066 if (result != 0)
3067 {
3068 error.SetErrorToGenericError();
3069 if (response.GetChar() == ',')
3070 {
3071 int response_errno = response.GetS32(-1);
3072 if (response_errno > 0)
3073 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3074 }
3075 }
3076 }
3077 else
3078 {
3079 // Should have returned with 'F<result>[,<errno>]'
3080 error.SetErrorStringWithFormat("symlink failed");
3081 }
3082 }
3083 else
3084 {
3085 error.SetErrorString ("failed to send vFile:symlink packet");
3086 }
3087 return error;
3088}
3089
3090Error
3091GDBRemoteCommunicationClient::Unlink (const char *path)
3092{
3093 Error error;
3094 lldb_private::StreamGDBRemote stream;
3095 stream.PutCString("vFile:unlink:");
3096 // the unix symlink() command reverses its parameters where the dst if first,
3097 // so we follow suit here
3098 stream.PutCStringAsRawHex8(path);
3099 const char* packet = stream.GetData();
3100 int packet_len = stream.GetSize();
3101 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003102 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003103 {
3104 if (response.GetChar() == 'F')
3105 {
3106 uint32_t result = response.GetU32(UINT32_MAX);
3107 if (result != 0)
3108 {
3109 error.SetErrorToGenericError();
3110 if (response.GetChar() == ',')
3111 {
3112 int response_errno = response.GetS32(-1);
3113 if (response_errno > 0)
3114 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3115 }
3116 }
3117 }
3118 else
3119 {
3120 // Should have returned with 'F<result>[,<errno>]'
3121 error.SetErrorStringWithFormat("unlink failed");
3122 }
3123 }
3124 else
3125 {
3126 error.SetErrorString ("failed to send vFile:unlink packet");
3127 }
3128 return error;
3129}
3130
Daniel Maleae0f8f572013-08-26 23:57:52 +00003131// Extension of host I/O packets to get whether a file exists.
3132bool
3133GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3134{
3135 lldb_private::StreamString stream;
3136 stream.PutCString("vFile:exists:");
3137 std::string path (file_spec.GetPath());
3138 stream.PutCStringAsRawHex8(path.c_str());
3139 const char* packet = stream.GetData();
3140 int packet_len = stream.GetSize();
3141 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003142 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003143 {
3144 if (response.GetChar() != 'F')
3145 return false;
3146 if (response.GetChar() != ',')
3147 return false;
3148 bool retcode = (response.GetChar() != '0');
3149 return retcode;
3150 }
3151 return false;
3152}
3153
3154bool
3155GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3156 uint64_t &high,
3157 uint64_t &low)
3158{
3159 lldb_private::StreamString stream;
3160 stream.PutCString("vFile:MD5:");
3161 std::string path (file_spec.GetPath());
3162 stream.PutCStringAsRawHex8(path.c_str());
3163 const char* packet = stream.GetData();
3164 int packet_len = stream.GetSize();
3165 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003166 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003167 {
3168 if (response.GetChar() != 'F')
3169 return false;
3170 if (response.GetChar() != ',')
3171 return false;
3172 if (response.Peek() && *response.Peek() == 'x')
3173 return false;
3174 low = response.GetHexMaxU64(false, UINT64_MAX);
3175 high = response.GetHexMaxU64(false, UINT64_MAX);
3176 return true;
3177 }
3178 return false;
3179}
Greg Claytonf74cf862013-11-13 23:28:31 +00003180
3181bool
3182GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3183{
3184 Mutex::Locker locker;
3185 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
3186 {
3187 const bool thread_suffix_supported = GetThreadSuffixSupported();
3188
3189 if (thread_suffix_supported || SetCurrentThread(tid))
3190 {
3191 char packet[64];
3192 int packet_len = 0;
3193 if (thread_suffix_supported)
3194 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
3195 else
3196 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3197 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003198 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003199 }
3200 }
3201 return false;
3202
3203}
3204
3205
3206bool
3207GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3208{
3209 Mutex::Locker locker;
3210 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3211 {
3212 const bool thread_suffix_supported = GetThreadSuffixSupported();
3213
3214 if (thread_suffix_supported || SetCurrentThread(tid))
3215 {
3216 char packet[64];
3217 int packet_len = 0;
3218 // Get all registers in one packet
3219 if (thread_suffix_supported)
3220 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3221 else
3222 packet_len = ::snprintf (packet, sizeof(packet), "g");
3223 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003224 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003225 }
3226 }
3227 return false;
3228}
3229bool
3230GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3231{
3232 save_id = 0; // Set to invalid save ID
3233 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3234 return false;
3235
3236 m_supports_QSaveRegisterState = eLazyBoolYes;
3237 Mutex::Locker locker;
3238 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3239 {
3240 const bool thread_suffix_supported = GetThreadSuffixSupported();
3241 if (thread_suffix_supported || SetCurrentThread(tid))
3242 {
3243 char packet[256];
3244 if (thread_suffix_supported)
3245 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3246 else
3247 ::strncpy (packet, "QSaveRegisterState", sizeof(packet));
3248
3249 StringExtractorGDBRemote response;
3250
Greg Clayton3dedae12013-12-06 21:45:27 +00003251 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003252 {
3253 if (response.IsUnsupportedResponse())
3254 {
3255 // This packet isn't supported, don't try calling it again
3256 m_supports_QSaveRegisterState = eLazyBoolNo;
3257 }
3258
3259 const uint32_t response_save_id = response.GetU32(0);
3260 if (response_save_id != 0)
3261 {
3262 save_id = response_save_id;
3263 return true;
3264 }
3265 }
3266 }
3267 }
3268 return false;
3269}
3270
3271bool
3272GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3273{
3274 // We use the "m_supports_QSaveRegisterState" variable here becuase the
3275 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3276 // order to be useful
3277 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3278 return false;
3279
3280 Mutex::Locker locker;
3281 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
3282 {
3283 const bool thread_suffix_supported = GetThreadSuffixSupported();
3284 if (thread_suffix_supported || SetCurrentThread(tid))
3285 {
3286 char packet[256];
3287 if (thread_suffix_supported)
3288 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3289 else
3290 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3291
3292 StringExtractorGDBRemote response;
3293
Greg Clayton3dedae12013-12-06 21:45:27 +00003294 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003295 {
3296 if (response.IsOKResponse())
3297 {
3298 return true;
3299 }
3300 else if (response.IsUnsupportedResponse())
3301 {
3302 // This packet isn't supported, don't try calling this packet or
3303 // QSaveRegisterState again...
3304 m_supports_QSaveRegisterState = eLazyBoolNo;
3305 }
3306 }
3307 }
3308 }
3309 return false;
3310}