blob: cdc51ec8a2d14cc92f70040cb96ce674581d985d [file] [log] [blame]
Greg Clayton576d8832011-03-22 04:00:09 +00001//===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10
11#include "GDBRemoteCommunicationClient.h"
12
13// C Includes
Daniel Maleab89d0492013-08-28 16:06:16 +000014#include <sys/stat.h>
15
Greg Clayton576d8832011-03-22 04:00:09 +000016// C++ Includes
Han Ming Ong4b6459f2013-01-18 23:11:53 +000017#include <sstream>
18
Greg Clayton576d8832011-03-22 04:00:09 +000019// Other libraries and framework includes
20#include "llvm/ADT/Triple.h"
21#include "lldb/Interpreter/Args.h"
22#include "lldb/Core/ConnectionFileDescriptor.h"
23#include "lldb/Core/Log.h"
24#include "lldb/Core/State.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000025#include "lldb/Core/StreamGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000026#include "lldb/Core/StreamString.h"
27#include "lldb/Host/Endian.h"
28#include "lldb/Host/Host.h"
29#include "lldb/Host/TimeValue.h"
Jason Molendaa3329782014-03-29 18:54:20 +000030#include "lldb/Target/Target.h"
Greg Clayton576d8832011-03-22 04:00:09 +000031
32// Project includes
33#include "Utility/StringExtractorGDBRemote.h"
34#include "ProcessGDBRemote.h"
35#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000036#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000037
38using namespace lldb;
39using namespace lldb_private;
40
Virgile Bellob2f1fb22013-08-23 12:44:05 +000041#ifdef LLDB_DISABLE_POSIX
42#define SIGSTOP 17
43#endif
44
Greg Clayton576d8832011-03-22 04:00:09 +000045//----------------------------------------------------------------------
46// GDBRemoteCommunicationClient constructor
47//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +000048GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) :
49 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform),
Greg Clayton576d8832011-03-22 04:00:09 +000050 m_supports_not_sending_acks (eLazyBoolCalculate),
51 m_supports_thread_suffix (eLazyBoolCalculate),
Greg Clayton44633992012-04-10 03:22:03 +000052 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
Greg Clayton576d8832011-03-22 04:00:09 +000053 m_supports_vCont_all (eLazyBoolCalculate),
54 m_supports_vCont_any (eLazyBoolCalculate),
55 m_supports_vCont_c (eLazyBoolCalculate),
56 m_supports_vCont_C (eLazyBoolCalculate),
57 m_supports_vCont_s (eLazyBoolCalculate),
58 m_supports_vCont_S (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000059 m_qHostInfo_is_valid (eLazyBoolCalculate),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000060 m_qProcessInfo_is_valid (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000061 m_qGDBServerVersion_is_valid (eLazyBoolCalculate),
Greg Clayton70b57652011-05-15 01:25:55 +000062 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
Greg Clayton46fb5582011-11-18 07:03:08 +000063 m_supports_memory_region_info (eLazyBoolCalculate),
Johnny Chen64637202012-05-23 21:09:52 +000064 m_supports_watchpoint_support_info (eLazyBoolCalculate),
Jim Inghamacff8952013-05-02 00:27:30 +000065 m_supports_detach_stay_stopped (eLazyBoolCalculate),
Enrico Granataf04a2192012-07-13 23:18:48 +000066 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
Jim Inghamcd16df92012-07-20 21:37:13 +000067 m_attach_or_wait_reply(eLazyBoolCalculate),
Jim Ingham279ceec2012-07-25 21:12:43 +000068 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
Eric Christopher2490f5c2013-08-30 17:50:57 +000069 m_supports_p (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000070 m_avoid_g_packets (eLazyBoolCalculate),
Greg Claytonf74cf862013-11-13 23:28:31 +000071 m_supports_QSaveRegisterState (eLazyBoolCalculate),
Steve Pucci03904ac2014-03-04 23:18:46 +000072 m_supports_qXfer_auxv_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000073 m_supports_qXfer_libraries_read (eLazyBoolCalculate),
74 m_supports_qXfer_libraries_svr4_read (eLazyBoolCalculate),
75 m_supports_augmented_libraries_svr4_read (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000076 m_supports_qProcessInfoPID (true),
77 m_supports_qfProcessInfo (true),
78 m_supports_qUserName (true),
79 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000080 m_supports_qThreadStopInfo (true),
81 m_supports_z0 (true),
82 m_supports_z1 (true),
83 m_supports_z2 (true),
84 m_supports_z3 (true),
85 m_supports_z4 (true),
Greg Clayton89600582013-10-10 17:53:50 +000086 m_supports_QEnvironment (true),
87 m_supports_QEnvironmentHexEncoded (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000088 m_curr_tid (LLDB_INVALID_THREAD_ID),
89 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +000090 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +000091 m_async_mutex (Mutex::eMutexTypeRecursive),
92 m_async_packet_predicate (false),
93 m_async_packet (),
Jim Inghama6195b72013-12-18 01:24:33 +000094 m_async_result (PacketResult::Success),
Greg Clayton576d8832011-03-22 04:00:09 +000095 m_async_response (),
96 m_async_signal (-1),
Jim Inghamb8cd5752014-04-16 02:24:17 +000097 m_interrupt_sent (false),
Han Ming Ong4b6459f2013-01-18 23:11:53 +000098 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +000099 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000100 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +0000101 m_os_version_major (UINT32_MAX),
102 m_os_version_minor (UINT32_MAX),
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000103 m_os_version_update (UINT32_MAX),
104 m_os_build (),
105 m_os_kernel (),
106 m_hostname (),
Jason Molendaa3329782014-03-29 18:54:20 +0000107 m_gdb_server_name(),
108 m_gdb_server_version(UINT32_MAX),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000109 m_default_packet_timeout (0),
110 m_max_packet_size (0)
Greg Clayton576d8832011-03-22 04:00:09 +0000111{
Greg Clayton576d8832011-03-22 04:00:09 +0000112}
113
114//----------------------------------------------------------------------
115// Destructor
116//----------------------------------------------------------------------
117GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
118{
Greg Clayton576d8832011-03-22 04:00:09 +0000119 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000120 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000121}
122
123bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000124GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
125{
Greg Claytonfb909312013-11-23 01:58:15 +0000126 ResetDiscoverableSettings();
127
Greg Clayton1cb64962011-03-24 04:28:38 +0000128 // Start the read thread after we send the handshake ack since if we
129 // fail to send the handshake ack, there is no reason to continue...
130 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000131 {
Ed Maste48f986f2013-12-18 15:31:45 +0000132 // Wait for any responses that might have been queued up in the remote
133 // GDB server and flush them all
134 StringExtractorGDBRemote response;
135 PacketResult packet_result = PacketResult::Success;
136 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
137 while (packet_result == PacketResult::Success)
138 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, timeout_usec);
139
Greg Claytonfb909312013-11-23 01:58:15 +0000140 // The return value from QueryNoAckModeSupported() is true if the packet
141 // was sent and _any_ response (including UNIMPLEMENTED) was received),
142 // or false if no response was received. This quickly tells us if we have
143 // a live connection to a remote GDB server...
144 if (QueryNoAckModeSupported())
145 {
Greg Clayton700e5082014-02-21 19:11:28 +0000146#if 0
147 // Set above line to "#if 1" to test packet speed if remote GDB server
148 // supports the qSpeedTest packet...
149 TestPacketSpeed(10000);
150#endif
Greg Claytonfb909312013-11-23 01:58:15 +0000151 return true;
152 }
153 else
154 {
155 if (error_ptr)
156 error_ptr->SetErrorString("failed to get reply to handshake packet");
157 }
158 }
159 else
160 {
161 if (error_ptr)
162 error_ptr->SetErrorString("failed to send the handshake ack");
163 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000164 return false;
165}
166
Greg Claytonfb909312013-11-23 01:58:15 +0000167bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000168GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
169{
170 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
171 {
172 GetRemoteQSupported();
173 }
174 return (m_supports_augmented_libraries_svr4_read == eLazyBoolYes);
175}
176
177bool
178GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
179{
180 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
181 {
182 GetRemoteQSupported();
183 }
184 return (m_supports_qXfer_libraries_svr4_read == eLazyBoolYes);
185}
186
187bool
188GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
189{
190 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
191 {
192 GetRemoteQSupported();
193 }
194 return (m_supports_qXfer_libraries_read == eLazyBoolYes);
195}
196
Steve Pucci03904ac2014-03-04 23:18:46 +0000197bool
198GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
199{
200 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
201 {
202 GetRemoteQSupported();
203 }
204 return (m_supports_qXfer_auxv_read == eLazyBoolYes);
205}
206
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000207uint64_t
208GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
209{
210 if (m_max_packet_size == 0)
211 {
212 GetRemoteQSupported();
213 }
214 return m_max_packet_size;
215}
216
217bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000218GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000219{
220 if (m_supports_not_sending_acks == eLazyBoolCalculate)
221 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000222 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000223 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000224
225 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000226 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000227 {
228 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000229 {
230 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000231 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000232 }
Greg Claytonfb909312013-11-23 01:58:15 +0000233 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000234 }
235 }
Greg Claytonfb909312013-11-23 01:58:15 +0000236 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000237}
238
239void
Greg Clayton44633992012-04-10 03:22:03 +0000240GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
241{
242 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
243 {
244 m_supports_threads_in_stop_reply = eLazyBoolNo;
245
246 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000247 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000248 {
249 if (response.IsOKResponse())
250 m_supports_threads_in_stop_reply = eLazyBoolYes;
251 }
252 }
253}
254
Jim Inghamcd16df92012-07-20 21:37:13 +0000255bool
256GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
257{
258 if (m_attach_or_wait_reply == eLazyBoolCalculate)
259 {
260 m_attach_or_wait_reply = eLazyBoolNo;
261
262 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000263 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000264 {
265 if (response.IsOKResponse())
266 m_attach_or_wait_reply = eLazyBoolYes;
267 }
268 }
269 if (m_attach_or_wait_reply == eLazyBoolYes)
270 return true;
271 else
272 return false;
273}
274
Jim Ingham279ceec2012-07-25 21:12:43 +0000275bool
276GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
277{
278 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
279 {
280 m_prepare_for_reg_writing_reply = eLazyBoolNo;
281
282 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000283 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000284 {
285 if (response.IsOKResponse())
286 m_prepare_for_reg_writing_reply = eLazyBoolYes;
287 }
288 }
289 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
290 return true;
291 else
292 return false;
293}
294
Greg Clayton44633992012-04-10 03:22:03 +0000295
296void
Greg Clayton576d8832011-03-22 04:00:09 +0000297GDBRemoteCommunicationClient::ResetDiscoverableSettings()
298{
299 m_supports_not_sending_acks = eLazyBoolCalculate;
300 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton44633992012-04-10 03:22:03 +0000301 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
Greg Clayton576d8832011-03-22 04:00:09 +0000302 m_supports_vCont_c = eLazyBoolCalculate;
303 m_supports_vCont_C = eLazyBoolCalculate;
304 m_supports_vCont_s = eLazyBoolCalculate;
305 m_supports_vCont_S = eLazyBoolCalculate;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000306 m_supports_p = eLazyBoolCalculate;
Greg Claytonf74cf862013-11-13 23:28:31 +0000307 m_supports_QSaveRegisterState = eLazyBoolCalculate;
Greg Clayton32e0a752011-03-30 18:16:51 +0000308 m_qHostInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000309 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000310 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
Greg Clayton70b57652011-05-15 01:25:55 +0000311 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton46fb5582011-11-18 07:03:08 +0000312 m_supports_memory_region_info = eLazyBoolCalculate;
Jim Ingham279ceec2012-07-25 21:12:43 +0000313 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
314 m_attach_or_wait_reply = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000315 m_avoid_g_packets = eLazyBoolCalculate;
Steve Pucci03904ac2014-03-04 23:18:46 +0000316 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000317 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
318 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
319 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
Greg Clayton2a48f522011-05-14 01:50:35 +0000320
Greg Clayton32e0a752011-03-30 18:16:51 +0000321 m_supports_qProcessInfoPID = true;
322 m_supports_qfProcessInfo = true;
323 m_supports_qUserName = true;
324 m_supports_qGroupName = true;
Greg Clayton8b82f082011-04-12 05:54:46 +0000325 m_supports_qThreadStopInfo = true;
326 m_supports_z0 = true;
327 m_supports_z1 = true;
328 m_supports_z2 = true;
329 m_supports_z3 = true;
330 m_supports_z4 = true;
Greg Clayton89600582013-10-10 17:53:50 +0000331 m_supports_QEnvironment = true;
332 m_supports_QEnvironmentHexEncoded = true;
Jason Molendaa3329782014-03-29 18:54:20 +0000333
Greg Claytond314e812011-03-23 00:09:55 +0000334 m_host_arch.Clear();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000335 m_process_arch.Clear();
Jason Molendaa3329782014-03-29 18:54:20 +0000336 m_os_version_major = UINT32_MAX;
337 m_os_version_minor = UINT32_MAX;
338 m_os_version_update = UINT32_MAX;
339 m_os_build.clear();
340 m_os_kernel.clear();
341 m_hostname.clear();
342 m_gdb_server_name.clear();
343 m_gdb_server_version = UINT32_MAX;
344 m_default_packet_timeout = 0;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000345
346 m_max_packet_size = 0;
Greg Clayton576d8832011-03-22 04:00:09 +0000347}
348
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000349void
350GDBRemoteCommunicationClient::GetRemoteQSupported ()
351{
352 // Clear out any capabilities we expect to see in the qSupported response
Steve Pucci03904ac2014-03-04 23:18:46 +0000353 m_supports_qXfer_auxv_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000354 m_supports_qXfer_libraries_read = eLazyBoolNo;
Steve Pucci03904ac2014-03-04 23:18:46 +0000355 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000356 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
357 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
358
359 StringExtractorGDBRemote response;
360 if (SendPacketAndWaitForResponse("qSupported",
361 response,
362 /*send_async=*/false) == PacketResult::Success)
363 {
364 const char *response_cstr = response.GetStringRef().c_str();
Steve Pucci03904ac2014-03-04 23:18:46 +0000365 if (::strstr (response_cstr, "qXfer:auxv:read+"))
366 m_supports_qXfer_auxv_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000367 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
368 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
369 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
370 {
371 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
372 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
373 }
374 if (::strstr (response_cstr, "qXfer:libraries:read+"))
375 m_supports_qXfer_libraries_read = eLazyBoolYes;
376
377 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
378 if (packet_size_str)
379 {
380 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
381 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
382 if (m_max_packet_size == 0)
383 {
384 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
385 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
386 if (log)
387 log->Printf ("Garbled PacketSize spec in qSupported response");
388 }
389 }
390 }
391}
Greg Clayton576d8832011-03-22 04:00:09 +0000392
393bool
394GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
395{
396 if (m_supports_thread_suffix == eLazyBoolCalculate)
397 {
398 StringExtractorGDBRemote response;
399 m_supports_thread_suffix = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000400 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000401 {
402 if (response.IsOKResponse())
403 m_supports_thread_suffix = eLazyBoolYes;
404 }
405 }
406 return m_supports_thread_suffix;
407}
408bool
409GDBRemoteCommunicationClient::GetVContSupported (char flavor)
410{
411 if (m_supports_vCont_c == eLazyBoolCalculate)
412 {
413 StringExtractorGDBRemote response;
414 m_supports_vCont_any = eLazyBoolNo;
415 m_supports_vCont_all = eLazyBoolNo;
416 m_supports_vCont_c = eLazyBoolNo;
417 m_supports_vCont_C = eLazyBoolNo;
418 m_supports_vCont_s = eLazyBoolNo;
419 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000420 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000421 {
422 const char *response_cstr = response.GetStringRef().c_str();
423 if (::strstr (response_cstr, ";c"))
424 m_supports_vCont_c = eLazyBoolYes;
425
426 if (::strstr (response_cstr, ";C"))
427 m_supports_vCont_C = eLazyBoolYes;
428
429 if (::strstr (response_cstr, ";s"))
430 m_supports_vCont_s = eLazyBoolYes;
431
432 if (::strstr (response_cstr, ";S"))
433 m_supports_vCont_S = eLazyBoolYes;
434
435 if (m_supports_vCont_c == eLazyBoolYes &&
436 m_supports_vCont_C == eLazyBoolYes &&
437 m_supports_vCont_s == eLazyBoolYes &&
438 m_supports_vCont_S == eLazyBoolYes)
439 {
440 m_supports_vCont_all = eLazyBoolYes;
441 }
442
443 if (m_supports_vCont_c == eLazyBoolYes ||
444 m_supports_vCont_C == eLazyBoolYes ||
445 m_supports_vCont_s == eLazyBoolYes ||
446 m_supports_vCont_S == eLazyBoolYes)
447 {
448 m_supports_vCont_any = eLazyBoolYes;
449 }
450 }
451 }
452
453 switch (flavor)
454 {
455 case 'a': return m_supports_vCont_any;
456 case 'A': return m_supports_vCont_all;
457 case 'c': return m_supports_vCont_c;
458 case 'C': return m_supports_vCont_C;
459 case 's': return m_supports_vCont_s;
460 case 'S': return m_supports_vCont_S;
461 default: break;
462 }
463 return false;
464}
465
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000466// Check if the target supports 'p' packet. It sends out a 'p'
467// packet and checks the response. A normal packet will tell us
468// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000469//
470// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000471bool
Sean Callananb1de1142013-09-04 23:24:15 +0000472GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000473{
474 if (m_supports_p == eLazyBoolCalculate)
475 {
476 StringExtractorGDBRemote response;
477 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000478 char packet[256];
479 if (GetThreadSuffixSupported())
480 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
481 else
482 snprintf(packet, sizeof(packet), "p0");
483
Greg Clayton3dedae12013-12-06 21:45:27 +0000484 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000485 {
486 if (response.IsNormalResponse())
487 m_supports_p = eLazyBoolYes;
488 }
489 }
490 return m_supports_p;
491}
Greg Clayton576d8832011-03-22 04:00:09 +0000492
Greg Clayton3dedae12013-12-06 21:45:27 +0000493GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000494GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
495(
496 const char *payload_prefix,
497 std::string &response_string
498)
499{
500 Mutex::Locker locker;
501 if (!GetSequenceMutex(locker,
502 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
503 {
504 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
505 if (log)
506 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
507 payload_prefix);
508 return PacketResult::ErrorNoSequenceLock;
509 }
510
511 response_string = "";
512 std::string payload_prefix_str(payload_prefix);
513 unsigned int response_size = 0x1000;
514 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
515 response_size = GetRemoteMaxPacketSize();
516 }
517
518 for (unsigned int offset = 0; true; offset += response_size)
519 {
520 StringExtractorGDBRemote this_response;
521 // Construct payload
522 char sizeDescriptor[128];
523 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
524 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
525 this_response,
526 /*send_async=*/false);
527 if (result != PacketResult::Success)
528 return result;
529
530 const std::string &this_string = this_response.GetStringRef();
531
532 // Check for m or l as first character; l seems to mean this is the last chunk
533 char first_char = *this_string.c_str();
534 if (first_char != 'm' && first_char != 'l')
535 {
536 return PacketResult::ErrorReplyInvalid;
537 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000538 // Concatenate the result so far (skipping 'm' or 'l')
539 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000540 if (first_char == 'l')
541 // We're done
542 return PacketResult::Success;
543 }
544}
545
546GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000547GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
548(
549 const char *payload,
550 StringExtractorGDBRemote &response,
551 bool send_async
552)
553{
554 return SendPacketAndWaitForResponse (payload,
555 ::strlen (payload),
556 response,
557 send_async);
558}
559
Greg Clayton3dedae12013-12-06 21:45:27 +0000560GDBRemoteCommunicationClient::PacketResult
561GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
562 size_t payload_length,
563 StringExtractorGDBRemote &response)
564{
565 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
566 if (packet_result == PacketResult::Success)
567 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
568 return packet_result;
569}
570
571GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000572GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
573(
574 const char *payload,
575 size_t payload_length,
576 StringExtractorGDBRemote &response,
577 bool send_async
578)
579{
Greg Clayton3dedae12013-12-06 21:45:27 +0000580 PacketResult packet_result = PacketResult::ErrorSendFailed;
Greg Clayton576d8832011-03-22 04:00:09 +0000581 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000582 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000583 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000584 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000585 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000586 }
587 else
588 {
589 if (send_async)
590 {
Greg Claytond3544052012-05-31 21:24:20 +0000591 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000592 {
Greg Claytond3544052012-05-31 21:24:20 +0000593 Mutex::Locker async_locker (m_async_mutex);
594 m_async_packet.assign(payload, payload_length);
595 m_async_packet_predicate.SetValue (true, eBroadcastNever);
596
597 if (log)
598 log->Printf ("async: async packet = %s", m_async_packet.c_str());
599
600 bool timed_out = false;
601 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000602 {
Greg Claytond3544052012-05-31 21:24:20 +0000603 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000604 {
Jim Inghambabfc382012-06-06 00:32:39 +0000605 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000606 TimeValue timeout_time;
607 timeout_time = TimeValue::Now();
608 timeout_time.OffsetWithSeconds (m_packet_timeout);
609
Greg Clayton576d8832011-03-22 04:00:09 +0000610 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000611 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000612
Greg Claytond3544052012-05-31 21:24:20 +0000613 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000614 {
Greg Claytond3544052012-05-31 21:24:20 +0000615 if (log)
616 log->Printf ("async: got response");
617
618 // Swap the response buffer to avoid malloc and string copy
619 response.GetStringRef().swap (m_async_response.GetStringRef());
Jim Inghama6195b72013-12-18 01:24:33 +0000620 packet_result = m_async_result;
Greg Claytond3544052012-05-31 21:24:20 +0000621 }
622 else
623 {
624 if (log)
625 log->Printf ("async: timed out waiting for response");
626 }
627
628 // Make sure we wait until the continue packet has been sent again...
629 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
630 {
631 if (log)
632 {
633 if (timed_out)
634 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
635 else
636 log->Printf ("async: async packet sent");
637 }
638 }
639 else
640 {
641 if (log)
642 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000643 }
644 }
645 else
646 {
Greg Claytond3544052012-05-31 21:24:20 +0000647 // We had a racy condition where we went to send the interrupt
648 // yet we were able to get the lock, so the process must have
649 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000650 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000651 log->Printf ("async: got lock without sending interrupt");
652 // Send the packet normally since we got the lock
Greg Clayton3dedae12013-12-06 21:45:27 +0000653 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000654 }
655 }
656 else
657 {
Greg Clayton644247c2011-07-07 01:59:51 +0000658 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000659 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000660 }
661 }
662 else
663 {
664 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000665 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000666 }
667 }
668 else
669 {
670 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000671 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000672 }
673 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000674 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000675}
676
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000677static const char *end_delimiter = "--end--;";
678static const int end_delimiter_len = 8;
679
680std::string
681GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
682( ProcessGDBRemote *process,
683 StringExtractorGDBRemote& profileDataExtractor
684)
685{
686 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
687 std::stringstream final_output;
688 std::string name, value;
689
690 // Going to assuming thread_used_usec comes first, else bail out.
691 while (profileDataExtractor.GetNameColonValue(name, value))
692 {
693 if (name.compare("thread_used_id") == 0)
694 {
695 StringExtractor threadIDHexExtractor(value.c_str());
696 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
697
698 bool has_used_usec = false;
699 uint32_t curr_used_usec = 0;
700 std::string usec_name, usec_value;
701 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
702 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
703 {
704 if (usec_name.compare("thread_used_usec") == 0)
705 {
706 has_used_usec = true;
707 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
708 }
709 else
710 {
711 // We didn't find what we want, it is probably
712 // an older version. Bail out.
713 profileDataExtractor.SetFilePos(input_file_pos);
714 }
715 }
716
717 if (has_used_usec)
718 {
719 uint32_t prev_used_usec = 0;
720 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
721 if (iterator != m_thread_id_to_used_usec_map.end())
722 {
723 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
724 }
725
726 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
727 // A good first time record is one that runs for at least 0.25 sec
728 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
729 bool good_subsequent_time = (prev_used_usec > 0) &&
730 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
731
732 if (good_first_time || good_subsequent_time)
733 {
734 // We try to avoid doing too many index id reservation,
735 // resulting in fast increase of index ids.
736
737 final_output << name << ":";
738 int32_t index_id = process->AssignIndexIDToThread(thread_id);
739 final_output << index_id << ";";
740
741 final_output << usec_name << ":" << usec_value << ";";
742 }
743 else
744 {
745 // Skip past 'thread_used_name'.
746 std::string local_name, local_value;
747 profileDataExtractor.GetNameColonValue(local_name, local_value);
748 }
749
750 // Store current time as previous time so that they can be compared later.
751 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
752 }
753 else
754 {
755 // Bail out and use old string.
756 final_output << name << ":" << value << ";";
757 }
758 }
759 else
760 {
761 final_output << name << ":" << value << ";";
762 }
763 }
764 final_output << end_delimiter;
765 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
766
767 return final_output.str();
768}
769
Greg Clayton576d8832011-03-22 04:00:09 +0000770StateType
771GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
772(
773 ProcessGDBRemote *process,
774 const char *payload,
775 size_t packet_length,
776 StringExtractorGDBRemote &response
777)
778{
Greg Clayton1f5181a2012-07-02 22:05:25 +0000779 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +0000780 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +0000781 if (log)
782 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
783
784 Mutex::Locker locker(m_sequence_mutex);
785 StateType state = eStateRunning;
786
787 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
788 m_public_is_running.SetValue (true, eBroadcastNever);
789 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +0000790 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +0000791 std::string continue_packet(payload, packet_length);
792
Greg Clayton3f875c52013-02-22 22:23:55 +0000793 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +0000794
Greg Clayton576d8832011-03-22 04:00:09 +0000795 while (state == eStateRunning)
796 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000797 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +0000798 {
799 if (log)
800 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton3dedae12013-12-06 21:45:27 +0000801 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
Greg Claytonaf247d72011-05-19 03:54:16 +0000802 state = eStateInvalid;
Jim Inghamb8cd5752014-04-16 02:24:17 +0000803 else
804 m_interrupt_sent = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000805
Greg Claytone889ad62011-10-27 22:04:16 +0000806 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +0000807 }
808
Greg Clayton3f875c52013-02-22 22:23:55 +0000809 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000810
811 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000812 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +0000813
Greg Clayton3dedae12013-12-06 21:45:27 +0000814 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000815 {
816 if (response.Empty())
817 state = eStateInvalid;
818 else
819 {
820 const char stop_type = response.GetChar();
821 if (log)
822 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
823 switch (stop_type)
824 {
825 case 'T':
826 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +0000827 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000828 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +0000829 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000830 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
831 {
832 lldb::pid_t pid = GetCurrentProcessID ();
833 if (pid != LLDB_INVALID_PROCESS_ID)
834 process->SetID (pid);
835 }
836 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +0000837 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000838
839 // Privately notify any internal threads that we have stopped
840 // in case we wanted to interrupt our process, yet we might
841 // send a packet and continue without returning control to the
842 // user.
843 m_private_is_running.SetValue (false, eBroadcastAlways);
844
845 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
846
Jim Inghambabfc382012-06-06 00:32:39 +0000847 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
848 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +0000849 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000850 // We sent an interrupt packet to stop the inferior process
851 // for an async signal or to send an async packet while running
852 // but we might have been single stepping and received the
853 // stop packet for the step instead of for the interrupt packet.
854 // Typically when an interrupt is sent a SIGINT or SIGSTOP
855 // is used, so if we get anything else, we need to try and
856 // get another stop reply packet that may have been sent
857 // due to sending the interrupt when the target is stopped
858 // which will just re-send a copy of the last stop reply
859 // packet. If we don't do this, then the reply for our
860 // async packet will be the repeat stop reply packet and cause
861 // a lot of trouble for us!
862 if (signo != SIGINT && signo != SIGSTOP)
863 {
Greg Claytonfb72fde2012-05-15 02:50:49 +0000864 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000865
866 // We didn't get a a SIGINT or SIGSTOP, so try for a
867 // very brief time (1 ms) to get another stop reply
868 // packet to make sure it doesn't get in the way
869 StringExtractorGDBRemote extra_stop_reply_packet;
870 uint32_t timeout_usec = 1000;
Greg Clayton3dedae12013-12-06 21:45:27 +0000871 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +0000872 {
873 switch (extra_stop_reply_packet.GetChar())
874 {
875 case 'T':
876 case 'S':
877 // We did get an extra stop reply, which means
878 // our interrupt didn't stop the target so we
879 // shouldn't continue after the async signal
880 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +0000881 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000882 break;
883 }
884 }
885 }
886 }
887
888 if (m_async_signal != -1)
889 {
890 if (log)
891 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
892
893 // Save off the async signal we are supposed to send
894 const int async_signal = m_async_signal;
895 // Clear the async signal member so we don't end up
896 // sending the signal multiple times...
897 m_async_signal = -1;
898 // Check which signal we stopped with
899 if (signo == async_signal)
900 {
901 if (log)
902 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
903
904 // We already stopped with a signal that we wanted
905 // to stop with, so we are done
906 }
907 else
908 {
909 // We stopped with a different signal that the one
910 // we wanted to stop with, so now we must resume
911 // with the signal we want
912 char signal_packet[32];
913 int signal_packet_len = 0;
914 signal_packet_len = ::snprintf (signal_packet,
915 sizeof (signal_packet),
916 "C%2.2x",
917 async_signal);
918
919 if (log)
920 log->Printf ("async: stopped with signal %s, resume with %s",
921 Host::GetSignalAsCString (signo),
922 Host::GetSignalAsCString (async_signal));
923
924 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +0000925 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000926 continue_packet.assign(signal_packet, signal_packet_len);
927 continue;
928 }
929 }
930 else if (m_async_packet_predicate.GetValue())
931 {
Greg Clayton5160ce52013-03-27 23:08:40 +0000932 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +0000933
934 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +0000935 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +0000936 m_async_response.Clear();
937 if (m_async_packet.empty())
938 {
Jim Inghama6195b72013-12-18 01:24:33 +0000939 m_async_result = PacketResult::ErrorSendFailed;
940 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000941 packet_log->Printf ("async: error: empty async packet");
942
943 }
944 else
945 {
946 if (packet_log)
947 packet_log->Printf ("async: sending packet");
948
Jim Inghama6195b72013-12-18 01:24:33 +0000949 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
950 m_async_packet.size(),
951 m_async_response,
952 false);
Greg Clayton2687cd12012-03-29 01:55:41 +0000953 }
954 // Let the other thread that was trying to send the async
955 // packet know that the packet has been sent and response is
956 // ready...
957 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
958
959 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +0000960 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +0000961
962 // Set the continue packet to resume if our interrupt
963 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +0000964 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000965 {
Greg Claytonf1186de2012-05-24 23:42:14 +0000966 // Reverting this for now as it is causing deadlocks
967 // in programs (<rdar://problem/11529853>). In the future
968 // we should check our thread list and "do the right thing"
969 // for new threads that show up while we stop and run async
970 // packets. Setting the packet to 'c' to continue all threads
971 // is the right thing to do 99.99% of the time because if a
972 // thread was single stepping, and we sent an interrupt, we
973 // will notice above that we didn't stop due to an interrupt
974 // but stopped due to stepping and we would _not_ continue.
975 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +0000976 continue;
977 }
978 }
979 // Stop with signal and thread info
980 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +0000981 }
Greg Clayton576d8832011-03-22 04:00:09 +0000982 break;
983
984 case 'W':
985 case 'X':
986 // process exited
987 state = eStateExited;
988 break;
989
990 case 'O':
991 // STDOUT
992 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000993 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000994 std::string inferior_stdout;
995 inferior_stdout.reserve(response.GetBytesLeft () / 2);
996 char ch;
997 while ((ch = response.GetHexU8()) != '\0')
998 inferior_stdout.append(1, ch);
999 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1000 }
1001 break;
1002
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001003 case 'A':
1004 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1005 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001006 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001007 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1008 if (m_partial_profile_data.length() > 0)
1009 {
1010 m_partial_profile_data.append(input);
1011 input = m_partial_profile_data;
1012 m_partial_profile_data.clear();
1013 }
1014
1015 size_t found, pos = 0, len = input.length();
1016 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1017 {
1018 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +00001019 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1020 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001021
1022 pos = found + end_delimiter_len;
1023 }
1024
1025 if (pos < len)
1026 {
1027 // Last incomplete chunk.
1028 m_partial_profile_data = input.substr(pos);
1029 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001030 }
1031 break;
1032
Greg Clayton576d8832011-03-22 04:00:09 +00001033 case 'E':
1034 // ERROR
1035 state = eStateInvalid;
1036 break;
1037
1038 default:
1039 if (log)
1040 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1041 state = eStateInvalid;
1042 break;
1043 }
1044 }
1045 }
1046 else
1047 {
1048 if (log)
1049 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
1050 state = eStateInvalid;
1051 }
1052 }
1053 if (log)
1054 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1055 response.SetFilePos(0);
1056 m_private_is_running.SetValue (false, eBroadcastAlways);
1057 m_public_is_running.SetValue (false, eBroadcastAlways);
1058 return state;
1059}
1060
1061bool
1062GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1063{
Greg Clayton2687cd12012-03-29 01:55:41 +00001064 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001065 m_async_signal = signo;
1066 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001067 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001068 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001069 return true;
1070 m_async_signal = -1;
1071 return false;
1072}
1073
Greg Clayton37a0a242012-04-11 00:24:49 +00001074// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001075// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1076// (the expected result), then it will send the halt packet. If it does succeed
1077// then the caller that requested the interrupt will want to keep the sequence
1078// locked down so that no one else can send packets while the caller has control.
1079// This function usually gets called when we are running and need to stop the
1080// target. It can also be used when we are running and and we need to do something
1081// else (like read/write memory), so we need to interrupt the running process
1082// (gdb remote protocol requires this), and do what we need to do, then resume.
1083
1084bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001085GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001086(
1087 Mutex::Locker& locker,
1088 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001089 bool &timed_out
1090)
1091{
Greg Clayton576d8832011-03-22 04:00:09 +00001092 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001093 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001094
1095 if (IsRunning())
1096 {
1097 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001098 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001099 {
1100 if (log)
1101 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1102 }
1103 else
Greg Clayton576d8832011-03-22 04:00:09 +00001104 {
1105 // Someone has the mutex locked waiting for a response or for the
1106 // inferior to stop, so send the interrupt on the down low...
1107 char ctrl_c = '\x03';
1108 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001109 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001110 if (log)
1111 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001112 if (bytes_written > 0)
1113 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001114 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001115 if (seconds_to_wait_for_stop)
1116 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001117 TimeValue timeout;
1118 if (seconds_to_wait_for_stop)
1119 {
1120 timeout = TimeValue::Now();
1121 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1122 }
Greg Clayton576d8832011-03-22 04:00:09 +00001123 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1124 {
1125 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001126 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001127 return true;
1128 }
1129 else
1130 {
1131 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001132 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001133 }
1134 }
1135 else
1136 {
1137 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001138 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001139 return true;
1140 }
1141 }
1142 else
1143 {
1144 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001145 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001146 }
1147 return false;
1148 }
Greg Clayton576d8832011-03-22 04:00:09 +00001149 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001150 else
1151 {
1152 if (log)
1153 log->Printf ("SendInterrupt () - not running");
1154 }
Greg Clayton576d8832011-03-22 04:00:09 +00001155 return true;
1156}
1157
1158lldb::pid_t
1159GDBRemoteCommunicationClient::GetCurrentProcessID ()
1160{
1161 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001162 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001163 {
1164 if (response.GetChar() == 'Q')
1165 if (response.GetChar() == 'C')
1166 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1167 }
1168 return LLDB_INVALID_PROCESS_ID;
1169}
1170
1171bool
1172GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1173{
1174 error_str.clear();
1175 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001176 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001177 {
1178 if (response.IsOKResponse())
1179 return true;
1180 if (response.GetChar() == 'E')
1181 {
1182 // A string the describes what failed when launching...
1183 error_str = response.GetStringRef().substr(1);
1184 }
1185 else
1186 {
1187 error_str.assign ("unknown error occurred launching process");
1188 }
1189 }
1190 else
1191 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001192 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001193 }
1194 return false;
1195}
1196
1197int
Greg Claytonfbb76342013-11-20 21:07:01 +00001198GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001199{
Greg Claytonfbb76342013-11-20 21:07:01 +00001200 // Since we don't get the send argv0 separate from the executable path, we need to
1201 // make sure to use the actual exectuable path found in the launch_info...
1202 std::vector<const char *> argv;
1203 FileSpec exe_file = launch_info.GetExecutableFile();
1204 std::string exe_path;
1205 const char *arg = NULL;
1206 const Args &launch_args = launch_info.GetArguments();
1207 if (exe_file)
1208 exe_path = exe_file.GetPath();
1209 else
1210 {
1211 arg = launch_args.GetArgumentAtIndex(0);
1212 if (arg)
1213 exe_path = arg;
1214 }
1215 if (!exe_path.empty())
1216 {
1217 argv.push_back(exe_path.c_str());
1218 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1219 {
1220 if (arg)
1221 argv.push_back(arg);
1222 }
1223 }
1224 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001225 {
1226 StreamString packet;
1227 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001228 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001229 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001230 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001231 const int arg_len = strlen(arg);
1232 if (i > 0)
1233 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001234 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001235 packet.PutBytesAsRawHex8 (arg, arg_len);
1236 }
1237
1238 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001239 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001240 {
1241 if (response.IsOKResponse())
1242 return 0;
1243 uint8_t error = response.GetError();
1244 if (error)
1245 return error;
1246 }
1247 }
1248 return -1;
1249}
1250
1251int
1252GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1253{
1254 if (name_equal_value && name_equal_value[0])
1255 {
1256 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001257 bool send_hex_encoding = false;
1258 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001259 {
Greg Clayton89600582013-10-10 17:53:50 +00001260 if (isprint(*p))
1261 {
1262 switch (*p)
1263 {
1264 case '$':
1265 case '#':
1266 send_hex_encoding = true;
1267 break;
1268 default:
1269 break;
1270 }
1271 }
1272 else
1273 {
1274 // We have non printable characters, lets hex encode this...
1275 send_hex_encoding = true;
1276 }
1277 }
1278
1279 StringExtractorGDBRemote response;
1280 if (send_hex_encoding)
1281 {
1282 if (m_supports_QEnvironmentHexEncoded)
1283 {
1284 packet.PutCString("QEnvironmentHexEncoded:");
1285 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001286 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001287 {
1288 if (response.IsOKResponse())
1289 return 0;
1290 uint8_t error = response.GetError();
1291 if (error)
1292 return error;
1293 if (response.IsUnsupportedResponse())
1294 m_supports_QEnvironmentHexEncoded = false;
1295 }
1296 }
1297
1298 }
1299 else if (m_supports_QEnvironment)
1300 {
1301 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +00001302 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001303 {
1304 if (response.IsOKResponse())
1305 return 0;
1306 uint8_t error = response.GetError();
1307 if (error)
1308 return error;
1309 if (response.IsUnsupportedResponse())
1310 m_supports_QEnvironment = false;
1311 }
Greg Clayton576d8832011-03-22 04:00:09 +00001312 }
1313 }
1314 return -1;
1315}
1316
Greg Claytonc4103b32011-05-08 04:53:50 +00001317int
1318GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1319{
1320 if (arch && arch[0])
1321 {
1322 StreamString packet;
1323 packet.Printf("QLaunchArch:%s", arch);
1324 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001325 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001326 {
1327 if (response.IsOKResponse())
1328 return 0;
1329 uint8_t error = response.GetError();
1330 if (error)
1331 return error;
1332 }
1333 }
1334 return -1;
1335}
1336
Jason Molendaa3329782014-03-29 18:54:20 +00001337int
1338GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1339{
1340 if (data && *data != '\0')
1341 {
1342 StreamString packet;
1343 packet.Printf("QSetProcessEvent:%s", data);
1344 StringExtractorGDBRemote response;
1345 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1346 {
1347 if (response.IsOKResponse())
1348 {
1349 if (was_supported)
1350 *was_supported = true;
1351 return 0;
1352 }
1353 else if (response.IsUnsupportedResponse())
1354 {
1355 if (was_supported)
1356 *was_supported = false;
1357 return -1;
1358 }
1359 else
1360 {
1361 uint8_t error = response.GetError();
1362 if (was_supported)
1363 *was_supported = true;
1364 if (error)
1365 return error;
1366 }
1367 }
1368 }
1369 return -1;
1370}
1371
Greg Clayton576d8832011-03-22 04:00:09 +00001372bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001373GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1374 uint32_t &minor,
1375 uint32_t &update)
1376{
1377 if (GetHostInfo ())
1378 {
1379 if (m_os_version_major != UINT32_MAX)
1380 {
1381 major = m_os_version_major;
1382 minor = m_os_version_minor;
1383 update = m_os_version_update;
1384 return true;
1385 }
1386 }
1387 return false;
1388}
1389
1390bool
1391GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1392{
1393 if (GetHostInfo ())
1394 {
1395 if (!m_os_build.empty())
1396 {
1397 s = m_os_build;
1398 return true;
1399 }
1400 }
1401 s.clear();
1402 return false;
1403}
1404
1405
1406bool
1407GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1408{
1409 if (GetHostInfo ())
1410 {
1411 if (!m_os_kernel.empty())
1412 {
1413 s = m_os_kernel;
1414 return true;
1415 }
1416 }
1417 s.clear();
1418 return false;
1419}
1420
1421bool
1422GDBRemoteCommunicationClient::GetHostname (std::string &s)
1423{
1424 if (GetHostInfo ())
1425 {
1426 if (!m_hostname.empty())
1427 {
1428 s = m_hostname;
1429 return true;
1430 }
1431 }
1432 s.clear();
1433 return false;
1434}
1435
1436ArchSpec
1437GDBRemoteCommunicationClient::GetSystemArchitecture ()
1438{
1439 if (GetHostInfo ())
1440 return m_host_arch;
1441 return ArchSpec();
1442}
1443
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001444const lldb_private::ArchSpec &
1445GDBRemoteCommunicationClient::GetProcessArchitecture ()
1446{
1447 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1448 GetCurrentProcessInfo ();
1449 return m_process_arch;
1450}
1451
Jason Molendaa3329782014-03-29 18:54:20 +00001452bool
1453GDBRemoteCommunicationClient::GetGDBServerVersion()
1454{
1455 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1456 {
1457 m_gdb_server_name.clear();
1458 m_gdb_server_version = 0;
1459 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1460
1461 StringExtractorGDBRemote response;
1462 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1463 {
1464 if (response.IsNormalResponse())
1465 {
1466 std::string name;
1467 std::string value;
1468 bool success = false;
1469 while (response.GetNameColonValue(name, value))
1470 {
1471 if (name.compare("name") == 0)
1472 {
1473 success = true;
1474 m_gdb_server_name.swap(value);
1475 }
1476 else if (name.compare("version") == 0)
1477 {
1478 size_t dot_pos = value.find('.');
1479 if (dot_pos != std::string::npos)
1480 value[dot_pos] = '\0';
1481 const uint32_t version = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
1482 if (version != UINT32_MAX)
1483 {
1484 success = true;
1485 m_gdb_server_version = version;
1486 }
1487 }
1488 }
1489 if (success)
1490 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1491 }
1492 }
1493 }
1494 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1495}
1496
1497const char *
1498GDBRemoteCommunicationClient::GetGDBServerProgramName()
1499{
1500 if (GetGDBServerVersion())
1501 {
1502 if (!m_gdb_server_name.empty())
1503 return m_gdb_server_name.c_str();
1504 }
1505 return NULL;
1506}
1507
1508uint32_t
1509GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1510{
1511 if (GetGDBServerVersion())
1512 return m_gdb_server_version;
1513 return 0;
1514}
Greg Clayton1cb64962011-03-24 04:28:38 +00001515
1516bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001517GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001518{
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001519 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001520 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001521 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001522 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001523 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001524 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001525 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001526 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001527 std::string name;
1528 std::string value;
1529 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1530 uint32_t sub = 0;
1531 std::string arch_name;
1532 std::string os_name;
1533 std::string vendor_name;
1534 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001535 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001536 uint32_t pointer_byte_size = 0;
1537 StringExtractor extractor;
1538 ByteOrder byte_order = eByteOrderInvalid;
1539 uint32_t num_keys_decoded = 0;
1540 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001541 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001542 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001543 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001544 // exception type in big endian hex
1545 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1546 if (cpu != LLDB_INVALID_CPUTYPE)
1547 ++num_keys_decoded;
1548 }
1549 else if (name.compare("cpusubtype") == 0)
1550 {
1551 // exception count in big endian hex
1552 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
1553 if (sub != 0)
1554 ++num_keys_decoded;
1555 }
1556 else if (name.compare("arch") == 0)
1557 {
1558 arch_name.swap (value);
1559 ++num_keys_decoded;
1560 }
1561 else if (name.compare("triple") == 0)
1562 {
1563 // The triple comes as ASCII hex bytes since it contains '-' chars
1564 extractor.GetStringRef().swap(value);
1565 extractor.SetFilePos(0);
1566 extractor.GetHexByteString (triple);
1567 ++num_keys_decoded;
1568 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001569 else if (name.compare ("distribution_id") == 0)
1570 {
1571 extractor.GetStringRef ().swap (value);
1572 extractor.SetFilePos (0);
1573 extractor.GetHexByteString (distribution_id);
1574 ++num_keys_decoded;
1575 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001576 else if (name.compare("os_build") == 0)
1577 {
1578 extractor.GetStringRef().swap(value);
1579 extractor.SetFilePos(0);
1580 extractor.GetHexByteString (m_os_build);
1581 ++num_keys_decoded;
1582 }
1583 else if (name.compare("hostname") == 0)
1584 {
1585 extractor.GetStringRef().swap(value);
1586 extractor.SetFilePos(0);
1587 extractor.GetHexByteString (m_hostname);
1588 ++num_keys_decoded;
1589 }
1590 else if (name.compare("os_kernel") == 0)
1591 {
1592 extractor.GetStringRef().swap(value);
1593 extractor.SetFilePos(0);
1594 extractor.GetHexByteString (m_os_kernel);
1595 ++num_keys_decoded;
1596 }
1597 else if (name.compare("ostype") == 0)
1598 {
1599 os_name.swap (value);
1600 ++num_keys_decoded;
1601 }
1602 else if (name.compare("vendor") == 0)
1603 {
1604 vendor_name.swap(value);
1605 ++num_keys_decoded;
1606 }
1607 else if (name.compare("endian") == 0)
1608 {
1609 ++num_keys_decoded;
1610 if (value.compare("little") == 0)
1611 byte_order = eByteOrderLittle;
1612 else if (value.compare("big") == 0)
1613 byte_order = eByteOrderBig;
1614 else if (value.compare("pdp") == 0)
1615 byte_order = eByteOrderPDP;
1616 else
1617 --num_keys_decoded;
1618 }
1619 else if (name.compare("ptrsize") == 0)
1620 {
1621 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1622 if (pointer_byte_size != 0)
1623 ++num_keys_decoded;
1624 }
1625 else if (name.compare("os_version") == 0)
1626 {
1627 Args::StringToVersion (value.c_str(),
1628 m_os_version_major,
1629 m_os_version_minor,
1630 m_os_version_update);
1631 if (m_os_version_major != UINT32_MAX)
1632 ++num_keys_decoded;
1633 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001634 else if (name.compare("watchpoint_exceptions_received") == 0)
1635 {
1636 ++num_keys_decoded;
1637 if (strcmp(value.c_str(),"before") == 0)
1638 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1639 else if (strcmp(value.c_str(),"after") == 0)
1640 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1641 else
1642 --num_keys_decoded;
1643 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001644 else if (name.compare("default_packet_timeout") == 0)
1645 {
1646 m_default_packet_timeout = Args::StringToUInt32(value.c_str(), 0);
1647 if (m_default_packet_timeout > 0)
1648 {
1649 SetPacketTimeout(m_default_packet_timeout);
1650 ++num_keys_decoded;
1651 }
1652 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001653
Greg Clayton32e0a752011-03-30 18:16:51 +00001654 }
1655
1656 if (num_keys_decoded > 0)
1657 m_qHostInfo_is_valid = eLazyBoolYes;
1658
1659 if (triple.empty())
1660 {
1661 if (arch_name.empty())
1662 {
1663 if (cpu != LLDB_INVALID_CPUTYPE)
1664 {
1665 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1666 if (pointer_byte_size)
1667 {
1668 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1669 }
1670 if (byte_order != eByteOrderInvalid)
1671 {
1672 assert (byte_order == m_host_arch.GetByteOrder());
1673 }
Greg Clayton70512312012-05-08 01:45:38 +00001674
1675 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1676 {
1677 switch (m_host_arch.GetMachine())
1678 {
Jason Molendaa3329782014-03-29 18:54:20 +00001679 case llvm::Triple::arm64:
Greg Clayton70512312012-05-08 01:45:38 +00001680 case llvm::Triple::arm:
1681 case llvm::Triple::thumb:
1682 os_name = "ios";
1683 break;
1684 default:
1685 os_name = "macosx";
1686 break;
1687 }
1688 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001689 if (!vendor_name.empty())
1690 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1691 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001692 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001693
1694 }
1695 }
1696 else
1697 {
1698 std::string triple;
1699 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001700 if (!vendor_name.empty() || !os_name.empty())
1701 {
1702 triple += '-';
1703 if (vendor_name.empty())
1704 triple += "unknown";
1705 else
1706 triple += vendor_name;
1707 triple += '-';
1708 if (os_name.empty())
1709 triple += "unknown";
1710 else
1711 triple += os_name;
1712 }
1713 m_host_arch.SetTriple (triple.c_str());
1714
1715 llvm::Triple &host_triple = m_host_arch.GetTriple();
1716 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1717 {
1718 switch (m_host_arch.GetMachine())
1719 {
Jason Molendaa3329782014-03-29 18:54:20 +00001720 case llvm::Triple::arm64:
Greg Clayton70512312012-05-08 01:45:38 +00001721 case llvm::Triple::arm:
1722 case llvm::Triple::thumb:
1723 host_triple.setOS(llvm::Triple::IOS);
1724 break;
1725 default:
1726 host_triple.setOS(llvm::Triple::MacOSX);
1727 break;
1728 }
1729 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001730 if (pointer_byte_size)
1731 {
1732 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1733 }
1734 if (byte_order != eByteOrderInvalid)
1735 {
1736 assert (byte_order == m_host_arch.GetByteOrder());
1737 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001738
Greg Clayton1cb64962011-03-24 04:28:38 +00001739 }
1740 }
1741 else
1742 {
Greg Clayton70512312012-05-08 01:45:38 +00001743 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001744 if (pointer_byte_size)
1745 {
1746 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1747 }
1748 if (byte_order != eByteOrderInvalid)
1749 {
1750 assert (byte_order == m_host_arch.GetByteOrder());
1751 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001752 }
1753 if (!distribution_id.empty ())
1754 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00001755 }
Greg Clayton576d8832011-03-22 04:00:09 +00001756 }
1757 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001758 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001759}
1760
1761int
1762GDBRemoteCommunicationClient::SendAttach
1763(
1764 lldb::pid_t pid,
1765 StringExtractorGDBRemote& response
1766)
1767{
1768 if (pid != LLDB_INVALID_PROCESS_ID)
1769 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001770 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001771 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001772 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00001773 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001774 {
1775 if (response.IsErrorResponse())
1776 return response.GetError();
1777 return 0;
1778 }
1779 }
1780 return -1;
1781}
1782
1783const lldb_private::ArchSpec &
1784GDBRemoteCommunicationClient::GetHostArchitecture ()
1785{
Greg Clayton32e0a752011-03-30 18:16:51 +00001786 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001787 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001788 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001789}
1790
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001791uint32_t
1792GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1793{
1794 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1795 GetHostInfo ();
1796 return m_default_packet_timeout;
1797}
1798
Greg Clayton576d8832011-03-22 04:00:09 +00001799addr_t
1800GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1801{
Greg Clayton70b57652011-05-15 01:25:55 +00001802 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001803 {
Greg Clayton70b57652011-05-15 01:25:55 +00001804 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001805 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001806 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001807 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001808 permissions & lldb::ePermissionsReadable ? "r" : "",
1809 permissions & lldb::ePermissionsWritable ? "w" : "",
1810 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001811 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001812 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001813 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001814 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001815 if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001816 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1817 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001818 else
1819 {
1820 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1821 }
Greg Clayton576d8832011-03-22 04:00:09 +00001822 }
1823 return LLDB_INVALID_ADDRESS;
1824}
1825
1826bool
1827GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1828{
Greg Clayton70b57652011-05-15 01:25:55 +00001829 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001830 {
Greg Clayton70b57652011-05-15 01:25:55 +00001831 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001832 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001833 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001834 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001835 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001836 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001837 {
1838 if (response.IsOKResponse())
1839 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001840 }
1841 else
1842 {
1843 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00001844 }
Greg Clayton576d8832011-03-22 04:00:09 +00001845 }
1846 return false;
1847}
1848
Jim Inghamacff8952013-05-02 00:27:30 +00001849Error
1850GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00001851{
Jim Inghamacff8952013-05-02 00:27:30 +00001852 Error error;
1853
1854 if (keep_stopped)
1855 {
1856 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1857 {
1858 char packet[64];
1859 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001860 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00001861 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001862 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001863 {
1864 m_supports_detach_stay_stopped = eLazyBoolYes;
1865 }
1866 else
1867 {
1868 m_supports_detach_stay_stopped = eLazyBoolNo;
1869 }
1870 }
1871
1872 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1873 {
1874 error.SetErrorString("Stays stopped not supported by this target.");
1875 return error;
1876 }
1877 else
1878 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00001879 StringExtractorGDBRemote response;
1880 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00001881 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001882 error.SetErrorString ("Sending extended disconnect packet failed.");
1883 }
1884 }
1885 else
1886 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00001887 StringExtractorGDBRemote response;
1888 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00001889 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001890 error.SetErrorString ("Sending disconnect packet failed.");
1891 }
1892 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001893}
1894
Greg Clayton46fb5582011-11-18 07:03:08 +00001895Error
1896GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1897 lldb_private::MemoryRegionInfo &region_info)
1898{
1899 Error error;
1900 region_info.Clear();
1901
1902 if (m_supports_memory_region_info != eLazyBoolNo)
1903 {
1904 m_supports_memory_region_info = eLazyBoolYes;
1905 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001906 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001907 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00001908 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001909 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00001910 {
1911 std::string name;
1912 std::string value;
1913 addr_t addr_value;
1914 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00001915 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00001916 while (success && response.GetNameColonValue(name, value))
1917 {
1918 if (name.compare ("start") == 0)
1919 {
1920 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1921 if (success)
1922 region_info.GetRange().SetRangeBase(addr_value);
1923 }
1924 else if (name.compare ("size") == 0)
1925 {
1926 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1927 if (success)
1928 region_info.GetRange().SetByteSize (addr_value);
1929 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001930 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00001931 {
Jason Molendacb349ee2011-12-13 05:39:38 +00001932 saw_permissions = true;
1933 if (region_info.GetRange().Contains (addr))
1934 {
1935 if (value.find('r') != std::string::npos)
1936 region_info.SetReadable (MemoryRegionInfo::eYes);
1937 else
1938 region_info.SetReadable (MemoryRegionInfo::eNo);
1939
1940 if (value.find('w') != std::string::npos)
1941 region_info.SetWritable (MemoryRegionInfo::eYes);
1942 else
1943 region_info.SetWritable (MemoryRegionInfo::eNo);
1944
1945 if (value.find('x') != std::string::npos)
1946 region_info.SetExecutable (MemoryRegionInfo::eYes);
1947 else
1948 region_info.SetExecutable (MemoryRegionInfo::eNo);
1949 }
1950 else
1951 {
1952 // The reported region does not contain this address -- we're looking at an unmapped page
1953 region_info.SetReadable (MemoryRegionInfo::eNo);
1954 region_info.SetWritable (MemoryRegionInfo::eNo);
1955 region_info.SetExecutable (MemoryRegionInfo::eNo);
1956 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001957 }
1958 else if (name.compare ("error") == 0)
1959 {
1960 StringExtractorGDBRemote name_extractor;
1961 // Swap "value" over into "name_extractor"
1962 name_extractor.GetStringRef().swap(value);
1963 // Now convert the HEX bytes into a string value
1964 name_extractor.GetHexByteString (value);
1965 error.SetErrorString(value.c_str());
1966 }
1967 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001968
1969 // We got a valid address range back but no permissions -- which means this is an unmapped page
1970 if (region_info.GetRange().IsValid() && saw_permissions == false)
1971 {
1972 region_info.SetReadable (MemoryRegionInfo::eNo);
1973 region_info.SetWritable (MemoryRegionInfo::eNo);
1974 region_info.SetExecutable (MemoryRegionInfo::eNo);
1975 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001976 }
1977 else
1978 {
1979 m_supports_memory_region_info = eLazyBoolNo;
1980 }
1981 }
1982
1983 if (m_supports_memory_region_info == eLazyBoolNo)
1984 {
1985 error.SetErrorString("qMemoryRegionInfo is not supported");
1986 }
1987 if (error.Fail())
1988 region_info.Clear();
1989 return error;
1990
1991}
1992
Johnny Chen64637202012-05-23 21:09:52 +00001993Error
1994GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1995{
1996 Error error;
1997
1998 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1999 {
2000 num = m_num_supported_hardware_watchpoints;
2001 return error;
2002 }
2003
2004 // Set num to 0 first.
2005 num = 0;
2006 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2007 {
2008 char packet[64];
2009 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002010 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00002011 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002012 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00002013 {
2014 m_supports_watchpoint_support_info = eLazyBoolYes;
2015 std::string name;
2016 std::string value;
2017 while (response.GetNameColonValue(name, value))
2018 {
2019 if (name.compare ("num") == 0)
2020 {
2021 num = Args::StringToUInt32(value.c_str(), 0, 0);
2022 m_num_supported_hardware_watchpoints = num;
2023 }
2024 }
2025 }
2026 else
2027 {
2028 m_supports_watchpoint_support_info = eLazyBoolNo;
2029 }
2030 }
2031
2032 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2033 {
2034 error.SetErrorString("qWatchpointSupportInfo is not supported");
2035 }
2036 return error;
2037
2038}
Greg Clayton46fb5582011-11-18 07:03:08 +00002039
Enrico Granataf04a2192012-07-13 23:18:48 +00002040lldb_private::Error
2041GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2042{
2043 Error error(GetWatchpointSupportInfo(num));
2044 if (error.Success())
2045 error = GetWatchpointsTriggerAfterInstruction(after);
2046 return error;
2047}
2048
2049lldb_private::Error
2050GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
2051{
2052 Error error;
2053
2054 // we assume watchpoints will happen after running the relevant opcode
2055 // and we only want to override this behavior if we have explicitly
2056 // received a qHostInfo telling us otherwise
2057 if (m_qHostInfo_is_valid != eLazyBoolYes)
2058 after = true;
2059 else
2060 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
2061 return error;
2062}
2063
Greg Clayton576d8832011-03-22 04:00:09 +00002064int
2065GDBRemoteCommunicationClient::SetSTDIN (char const *path)
2066{
2067 if (path && path[0])
2068 {
2069 StreamString packet;
2070 packet.PutCString("QSetSTDIN:");
2071 packet.PutBytesAsRawHex8(path, strlen(path));
2072
2073 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002074 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002075 {
2076 if (response.IsOKResponse())
2077 return 0;
2078 uint8_t error = response.GetError();
2079 if (error)
2080 return error;
2081 }
2082 }
2083 return -1;
2084}
2085
2086int
2087GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
2088{
2089 if (path && path[0])
2090 {
2091 StreamString packet;
2092 packet.PutCString("QSetSTDOUT:");
2093 packet.PutBytesAsRawHex8(path, strlen(path));
2094
2095 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002096 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002097 {
2098 if (response.IsOKResponse())
2099 return 0;
2100 uint8_t error = response.GetError();
2101 if (error)
2102 return error;
2103 }
2104 }
2105 return -1;
2106}
2107
2108int
2109GDBRemoteCommunicationClient::SetSTDERR (char const *path)
2110{
2111 if (path && path[0])
2112 {
2113 StreamString packet;
2114 packet.PutCString("QSetSTDERR:");
2115 packet.PutBytesAsRawHex8(path, strlen(path));
2116
2117 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002118 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002119 {
2120 if (response.IsOKResponse())
2121 return 0;
2122 uint8_t error = response.GetError();
2123 if (error)
2124 return error;
2125 }
2126 }
2127 return -1;
2128}
2129
Greg Claytonfbb76342013-11-20 21:07:01 +00002130bool
2131GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd)
2132{
2133 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002134 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002135 {
2136 if (response.IsUnsupportedResponse())
2137 return false;
2138 if (response.IsErrorResponse())
2139 return false;
2140 response.GetHexByteString (cwd);
2141 return !cwd.empty();
2142 }
2143 return false;
2144}
2145
Greg Clayton576d8832011-03-22 04:00:09 +00002146int
2147GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
2148{
2149 if (path && path[0])
2150 {
2151 StreamString packet;
2152 packet.PutCString("QSetWorkingDir:");
2153 packet.PutBytesAsRawHex8(path, strlen(path));
2154
2155 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002156 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002157 {
2158 if (response.IsOKResponse())
2159 return 0;
2160 uint8_t error = response.GetError();
2161 if (error)
2162 return error;
2163 }
2164 }
2165 return -1;
2166}
2167
2168int
2169GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2170{
Greg Clayton32e0a752011-03-30 18:16:51 +00002171 char packet[32];
2172 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002173 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002174 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002175 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002176 {
2177 if (response.IsOKResponse())
2178 return 0;
2179 uint8_t error = response.GetError();
2180 if (error)
2181 return error;
2182 }
2183 return -1;
2184}
Greg Clayton32e0a752011-03-30 18:16:51 +00002185
2186bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002187GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002188{
2189 if (response.IsNormalResponse())
2190 {
2191 std::string name;
2192 std::string value;
2193 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002194
2195 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2196 uint32_t sub = 0;
2197 std::string vendor;
2198 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002199
2200 while (response.GetNameColonValue(name, value))
2201 {
2202 if (name.compare("pid") == 0)
2203 {
2204 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2205 }
2206 else if (name.compare("ppid") == 0)
2207 {
2208 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
2209 }
2210 else if (name.compare("uid") == 0)
2211 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002212 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002213 }
2214 else if (name.compare("euid") == 0)
2215 {
2216 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2217 }
2218 else if (name.compare("gid") == 0)
2219 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002220 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002221 }
2222 else if (name.compare("egid") == 0)
2223 {
2224 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
2225 }
2226 else if (name.compare("triple") == 0)
2227 {
2228 // The triple comes as ASCII hex bytes since it contains '-' chars
2229 extractor.GetStringRef().swap(value);
2230 extractor.SetFilePos(0);
2231 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002232 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002233 }
2234 else if (name.compare("name") == 0)
2235 {
2236 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002237 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002238 // control the characters in a process name
2239 extractor.GetStringRef().swap(value);
2240 extractor.SetFilePos(0);
2241 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002242 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002243 }
Jason Molenda89c37492014-01-27 22:23:20 +00002244 else if (name.compare("cputype") == 0)
2245 {
2246 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2247 }
2248 else if (name.compare("cpusubtype") == 0)
2249 {
2250 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2251 }
2252 else if (name.compare("vendor") == 0)
2253 {
2254 vendor = value;
2255 }
2256 else if (name.compare("ostype") == 0)
2257 {
2258 os_type = value;
2259 }
2260 }
2261
2262 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2263 {
2264 if (vendor == "apple")
2265 {
2266 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2267 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2268 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2269 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002270 }
2271
2272 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2273 return true;
2274 }
2275 return false;
2276}
2277
2278bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002279GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002280{
2281 process_info.Clear();
2282
2283 if (m_supports_qProcessInfoPID)
2284 {
2285 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002286 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002287 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002288 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002289 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002290 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002291 return DecodeProcessInfoResponse (response, process_info);
2292 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002293 else
2294 {
2295 m_supports_qProcessInfoPID = false;
2296 return false;
2297 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002298 }
2299 return false;
2300}
2301
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002302bool
2303GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
2304{
2305 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2306 return true;
2307 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2308 return false;
2309
2310 GetHostInfo ();
2311
2312 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002313 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002314 {
2315 if (response.IsNormalResponse())
2316 {
2317 std::string name;
2318 std::string value;
2319 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2320 uint32_t sub = 0;
2321 std::string arch_name;
2322 std::string os_name;
2323 std::string vendor_name;
2324 std::string triple;
2325 uint32_t pointer_byte_size = 0;
2326 StringExtractor extractor;
2327 ByteOrder byte_order = eByteOrderInvalid;
2328 uint32_t num_keys_decoded = 0;
2329 while (response.GetNameColonValue(name, value))
2330 {
2331 if (name.compare("cputype") == 0)
2332 {
2333 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
2334 if (cpu != LLDB_INVALID_CPUTYPE)
2335 ++num_keys_decoded;
2336 }
2337 else if (name.compare("cpusubtype") == 0)
2338 {
2339 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
2340 if (sub != 0)
2341 ++num_keys_decoded;
2342 }
2343 else if (name.compare("ostype") == 0)
2344 {
2345 os_name.swap (value);
2346 ++num_keys_decoded;
2347 }
2348 else if (name.compare("vendor") == 0)
2349 {
2350 vendor_name.swap(value);
2351 ++num_keys_decoded;
2352 }
2353 else if (name.compare("endian") == 0)
2354 {
2355 ++num_keys_decoded;
2356 if (value.compare("little") == 0)
2357 byte_order = eByteOrderLittle;
2358 else if (value.compare("big") == 0)
2359 byte_order = eByteOrderBig;
2360 else if (value.compare("pdp") == 0)
2361 byte_order = eByteOrderPDP;
2362 else
2363 --num_keys_decoded;
2364 }
2365 else if (name.compare("ptrsize") == 0)
2366 {
2367 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
2368 if (pointer_byte_size != 0)
2369 ++num_keys_decoded;
2370 }
2371 }
2372 if (num_keys_decoded > 0)
2373 m_qProcessInfo_is_valid = eLazyBoolYes;
2374 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
2375 {
2376 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2377 if (pointer_byte_size)
2378 {
2379 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2380 }
2381 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2382 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
2383 return true;
2384 }
2385 }
2386 }
2387 else
2388 {
2389 m_qProcessInfo_is_valid = eLazyBoolNo;
2390 }
2391
2392 return false;
2393}
2394
2395
Greg Clayton32e0a752011-03-30 18:16:51 +00002396uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002397GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2398 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002399{
2400 process_infos.Clear();
2401
2402 if (m_supports_qfProcessInfo)
2403 {
2404 StreamString packet;
2405 packet.PutCString ("qfProcessInfo");
2406 if (!match_info.MatchAllProcesses())
2407 {
2408 packet.PutChar (':');
2409 const char *name = match_info.GetProcessInfo().GetName();
2410 bool has_name_match = false;
2411 if (name && name[0])
2412 {
2413 has_name_match = true;
2414 NameMatchType name_match_type = match_info.GetNameMatchType();
2415 switch (name_match_type)
2416 {
2417 case eNameMatchIgnore:
2418 has_name_match = false;
2419 break;
2420
2421 case eNameMatchEquals:
2422 packet.PutCString ("name_match:equals;");
2423 break;
2424
2425 case eNameMatchContains:
2426 packet.PutCString ("name_match:contains;");
2427 break;
2428
2429 case eNameMatchStartsWith:
2430 packet.PutCString ("name_match:starts_with;");
2431 break;
2432
2433 case eNameMatchEndsWith:
2434 packet.PutCString ("name_match:ends_with;");
2435 break;
2436
2437 case eNameMatchRegularExpression:
2438 packet.PutCString ("name_match:regex;");
2439 break;
2440 }
2441 if (has_name_match)
2442 {
2443 packet.PutCString ("name:");
2444 packet.PutBytesAsRawHex8(name, ::strlen(name));
2445 packet.PutChar (';');
2446 }
2447 }
2448
2449 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002450 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002451 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002452 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002453 if (match_info.GetProcessInfo().UserIDIsValid())
2454 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2455 if (match_info.GetProcessInfo().GroupIDIsValid())
2456 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002457 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2458 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2459 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2460 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2461 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2462 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2463 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2464 {
2465 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2466 const llvm::Triple &triple = match_arch.GetTriple();
2467 packet.PutCString("triple:");
2468 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
2469 packet.PutChar (';');
2470 }
2471 }
2472 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002473 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002474 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002475 do
2476 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002477 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002478 if (!DecodeProcessInfoResponse (response, process_info))
2479 break;
2480 process_infos.Append(process_info);
2481 response.GetStringRef().clear();
2482 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00002483 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00002484 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002485 else
2486 {
2487 m_supports_qfProcessInfo = false;
2488 return 0;
2489 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002490 }
2491 return process_infos.GetSize();
2492
2493}
2494
2495bool
2496GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2497{
2498 if (m_supports_qUserName)
2499 {
2500 char packet[32];
2501 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002502 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002503 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002504 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002505 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002506 if (response.IsNormalResponse())
2507 {
2508 // Make sure we parsed the right number of characters. The response is
2509 // the hex encoded user name and should make up the entire packet.
2510 // If there are any non-hex ASCII bytes, the length won't match below..
2511 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2512 return true;
2513 }
2514 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002515 else
2516 {
2517 m_supports_qUserName = false;
2518 return false;
2519 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002520 }
2521 return false;
2522
2523}
2524
2525bool
2526GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2527{
2528 if (m_supports_qGroupName)
2529 {
2530 char packet[32];
2531 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002532 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002533 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002534 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002535 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002536 if (response.IsNormalResponse())
2537 {
2538 // Make sure we parsed the right number of characters. The response is
2539 // the hex encoded group name and should make up the entire packet.
2540 // If there are any non-hex ASCII bytes, the length won't match below..
2541 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2542 return true;
2543 }
2544 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002545 else
2546 {
2547 m_supports_qGroupName = false;
2548 return false;
2549 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002550 }
2551 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002552}
Greg Clayton32e0a752011-03-30 18:16:51 +00002553
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002554void
2555GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2556{
2557 uint32_t i;
2558 TimeValue start_time, end_time;
2559 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002560 if (SendSpeedTestPacket (0, 0))
2561 {
Greg Clayton700e5082014-02-21 19:11:28 +00002562 static uint32_t g_send_sizes[] = { 0, 64, 128, 512, 1024 };
2563 static uint32_t g_recv_sizes[] = { 0, 64, 128, 512, 1024 }; //, 4*1024, 8*1024, 16*1024, 32*1024, 48*1024, 64*1024, 96*1024, 128*1024 };
2564 const size_t k_num_send_sizes = sizeof(g_send_sizes)/sizeof(uint32_t);
2565 const size_t k_num_recv_sizes = sizeof(g_recv_sizes)/sizeof(uint32_t);
2566 const uint64_t k_recv_amount = 4*1024*1024; // Receive 4MB
2567 for (uint32_t send_idx = 0; send_idx < k_num_send_sizes; ++send_idx)
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002568 {
Greg Clayton700e5082014-02-21 19:11:28 +00002569 const uint32_t send_size = g_send_sizes[send_idx];
2570 for (uint32_t recv_idx = 0; recv_idx < k_num_recv_sizes; ++recv_idx)
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002571 {
Greg Clayton700e5082014-02-21 19:11:28 +00002572 const uint32_t recv_size = g_recv_sizes[recv_idx];
2573 StreamString packet;
2574 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2575 uint32_t bytes_left = send_size;
2576 while (bytes_left > 0)
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002577 {
Greg Clayton700e5082014-02-21 19:11:28 +00002578 if (bytes_left >= 26)
2579 {
2580 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2581 bytes_left -= 26;
2582 }
2583 else
2584 {
2585 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2586 bytes_left = 0;
2587 }
2588 }
2589
2590 start_time = TimeValue::Now();
2591 if (recv_size == 0)
2592 {
2593 for (i=0; i<num_packets; ++i)
2594 {
2595 StringExtractorGDBRemote response;
2596 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2597 }
2598 }
2599 else
2600 {
2601 uint32_t bytes_read = 0;
2602 while (bytes_read < k_recv_amount)
2603 {
2604 StringExtractorGDBRemote response;
2605 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2606 bytes_read += recv_size;
2607 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002608 }
2609 end_time = TimeValue::Now();
2610 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002611 if (recv_size == 0)
Greg Clayton700e5082014-02-21 19:11:28 +00002612 {
2613 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2614 printf ("%u qSpeedTest(send=%-7u, recv=%-7u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
2615 num_packets,
2616 send_size,
2617 recv_size,
2618 total_time_nsec / TimeValue::NanoSecPerSec,
2619 total_time_nsec % TimeValue::NanoSecPerSec,
2620 packets_per_second);
2621 }
2622 else
2623 {
2624 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2625 printf ("%u qSpeedTest(send=%-7u, recv=%-7u) sent 4MB in %" PRIu64 ".%9.9" PRIu64 " sec for %f MB/sec.\n",
2626 num_packets,
2627 send_size,
2628 recv_size,
2629 total_time_nsec / TimeValue::NanoSecPerSec,
2630 total_time_nsec % TimeValue::NanoSecPerSec,
2631 mb_second);
2632 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002633 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002634 }
2635 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002636}
2637
2638bool
2639GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2640{
2641 StreamString packet;
2642 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2643 uint32_t bytes_left = send_size;
2644 while (bytes_left > 0)
2645 {
2646 if (bytes_left >= 26)
2647 {
2648 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2649 bytes_left -= 26;
2650 }
2651 else
2652 {
2653 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2654 bytes_left = 0;
2655 }
2656 }
2657
2658 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002659 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00002660}
Greg Clayton8b82f082011-04-12 05:54:46 +00002661
2662uint16_t
Greg Claytondbf04572013-12-04 19:40:33 +00002663GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
Greg Clayton8b82f082011-04-12 05:54:46 +00002664{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002665 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00002666 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002667 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00002668 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002669 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00002670 if (remote_accept_hostname && remote_accept_hostname[0])
2671 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002672 else
2673 {
Greg Claytondbf04572013-12-04 19:40:33 +00002674 if (Host::GetHostname (hostname))
2675 {
2676 // Make the GDB server we launch only accept connections from this host
2677 stream.Printf("host:%s;", hostname.c_str());
2678 }
2679 else
2680 {
2681 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2682 stream.Printf("host:*;");
2683 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002684 }
2685 const char *packet = stream.GetData();
2686 int packet_len = stream.GetSize();
2687
Greg Clayton3dedae12013-12-06 21:45:27 +00002688 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002689 {
2690 std::string name;
2691 std::string value;
2692 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002693 while (response.GetNameColonValue(name, value))
2694 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00002695 if (name.compare("port") == 0)
Greg Clayton8b82f082011-04-12 05:54:46 +00002696 port = Args::StringToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002697 else if (name.compare("pid") == 0)
2698 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00002699 }
2700 return port;
2701 }
2702 return 0;
2703}
2704
2705bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00002706GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2707{
2708 StreamString stream;
2709 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2710 const char *packet = stream.GetData();
2711 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00002712
Daniel Maleae0f8f572013-08-26 23:57:52 +00002713 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002714 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002715 {
2716 if (response.IsOKResponse())
2717 return true;
2718 }
2719 return false;
2720}
2721
2722bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002723GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002724{
2725 if (m_curr_tid == tid)
2726 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002727
Greg Clayton8b82f082011-04-12 05:54:46 +00002728 char packet[32];
2729 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002730 if (tid == UINT64_MAX)
2731 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002732 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002733 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002734 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002735 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002736 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002737 {
2738 if (response.IsOKResponse())
2739 {
2740 m_curr_tid = tid;
2741 return true;
2742 }
2743 }
2744 return false;
2745}
2746
2747bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002748GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002749{
2750 if (m_curr_tid_run == tid)
2751 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002752
Greg Clayton8b82f082011-04-12 05:54:46 +00002753 char packet[32];
2754 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002755 if (tid == UINT64_MAX)
2756 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002757 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002758 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2759
Andy Gibbsa297a972013-06-19 19:04:53 +00002760 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002761 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002762 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002763 {
2764 if (response.IsOKResponse())
2765 {
2766 m_curr_tid_run = tid;
2767 return true;
2768 }
2769 }
2770 return false;
2771}
2772
2773bool
2774GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2775{
Greg Clayton3dedae12013-12-06 21:45:27 +00002776 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002777 return response.IsNormalResponse();
2778 return false;
2779}
2780
2781bool
Greg Claytonf402f782012-10-13 02:11:55 +00002782GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00002783{
2784 if (m_supports_qThreadStopInfo)
2785 {
2786 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00002787 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002788 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002789 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002790 {
Greg Claytonef8180a2013-10-15 00:14:28 +00002791 if (response.IsUnsupportedResponse())
2792 m_supports_qThreadStopInfo = false;
2793 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002794 return true;
2795 else
2796 return false;
2797 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002798 else
2799 {
2800 m_supports_qThreadStopInfo = false;
2801 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002802 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002803 return false;
2804}
2805
2806
2807uint8_t
2808GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2809{
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002810 // Check if the stub is known not to support this breakpoint type
2811 if (!SupportsGDBStoppointPacket(type))
2812 return UINT8_MAX;
2813 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00002814 char packet[64];
2815 const int packet_len = ::snprintf (packet,
2816 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00002817 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00002818 insert ? 'Z' : 'z',
2819 type,
2820 addr,
2821 length);
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002822 // Check we havent overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00002823 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002824 StringExtractorGDBRemote response;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002825 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00002826 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002827 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002828 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00002829 if (response.IsOKResponse())
2830 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002831
2832 // Error while setting breakpoint, send back specific error
2833 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002834 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002835
2836 // Empty packet informs us that breakpoint is not supported
2837 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00002838 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002839 // Disable this breakpoint type since it is unsupported
2840 switch (type)
2841 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00002842 case eBreakpointSoftware: m_supports_z0 = false; break;
2843 case eBreakpointHardware: m_supports_z1 = false; break;
2844 case eWatchpointWrite: m_supports_z2 = false; break;
2845 case eWatchpointRead: m_supports_z3 = false; break;
2846 case eWatchpointReadWrite: m_supports_z4 = false; break;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002847 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002848 }
2849 }
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00002850 // Signal generic faliure
Greg Clayton8b82f082011-04-12 05:54:46 +00002851 return UINT8_MAX;
2852}
Greg Claytonadc00cb2011-05-20 23:38:13 +00002853
2854size_t
2855GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2856 bool &sequence_mutex_unavailable)
2857{
2858 Mutex::Locker locker;
2859 thread_ids.clear();
2860
Jim Ingham4ceb9282012-06-08 22:50:40 +00002861 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002862 {
2863 sequence_mutex_unavailable = false;
2864 StringExtractorGDBRemote response;
2865
Greg Clayton3dedae12013-12-06 21:45:27 +00002866 PacketResult packet_result;
2867 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
2868 packet_result == PacketResult::Success && response.IsNormalResponse();
2869 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002870 {
2871 char ch = response.GetChar();
2872 if (ch == 'l')
2873 break;
2874 if (ch == 'm')
2875 {
2876 do
2877 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00002878 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00002879
2880 if (tid != LLDB_INVALID_THREAD_ID)
2881 {
2882 thread_ids.push_back (tid);
2883 }
2884 ch = response.GetChar(); // Skip the command separator
2885 } while (ch == ','); // Make sure we got a comma separator
2886 }
2887 }
2888 }
2889 else
2890 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00002891#if defined (LLDB_CONFIGURATION_DEBUG)
2892 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2893#else
Greg Clayton5160ce52013-03-27 23:08:40 +00002894 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00002895 if (log)
2896 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00002897#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00002898 sequence_mutex_unavailable = true;
2899 }
2900 return thread_ids.size();
2901}
Greg Clayton37a0a242012-04-11 00:24:49 +00002902
2903lldb::addr_t
2904GDBRemoteCommunicationClient::GetShlibInfoAddr()
2905{
2906 if (!IsRunning())
2907 {
2908 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002909 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00002910 {
2911 if (response.IsNormalResponse())
2912 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2913 }
2914 }
2915 return LLDB_INVALID_ADDRESS;
2916}
2917
Daniel Maleae0f8f572013-08-26 23:57:52 +00002918lldb_private::Error
2919GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL
2920 const char *working_dir, // Pass NULL to use the current working directory
2921 int *status_ptr, // Pass NULL if you don't want the process exit status
2922 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
2923 std::string *command_output, // Pass NULL if you don't want the command output
2924 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
2925{
2926 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00002927 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002928 stream.PutBytesAsRawHex8(command, strlen(command));
2929 stream.PutChar(',');
2930 stream.PutHex32(timeout_sec);
2931 if (working_dir && *working_dir)
2932 {
2933 stream.PutChar(',');
2934 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
2935 }
2936 const char *packet = stream.GetData();
2937 int packet_len = stream.GetSize();
2938 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002939 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002940 {
2941 if (response.GetChar() != 'F')
2942 return Error("malformed reply");
2943 if (response.GetChar() != ',')
2944 return Error("malformed reply");
2945 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2946 if (exitcode == UINT32_MAX)
2947 return Error("unable to run remote process");
2948 else if (status_ptr)
2949 *status_ptr = exitcode;
2950 if (response.GetChar() != ',')
2951 return Error("malformed reply");
2952 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2953 if (signo_ptr)
2954 *signo_ptr = signo;
2955 if (response.GetChar() != ',')
2956 return Error("malformed reply");
2957 std::string output;
2958 response.GetEscapedBinaryData(output);
2959 if (command_output)
2960 command_output->assign(output);
2961 return Error();
2962 }
2963 return Error("unable to send packet");
2964}
2965
Greg Claytonfbb76342013-11-20 21:07:01 +00002966Error
2967GDBRemoteCommunicationClient::MakeDirectory (const char *path,
2968 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002969{
2970 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00002971 stream.PutCString("qPlatform_mkdir:");
2972 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002973 stream.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00002974 stream.PutBytesAsRawHex8(path, strlen(path));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002975 const char *packet = stream.GetData();
2976 int packet_len = stream.GetSize();
2977 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002978 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002979 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002980 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002981 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002982 return Error();
Daniel Maleae0f8f572013-08-26 23:57:52 +00002983
2984}
2985
Greg Claytonfbb76342013-11-20 21:07:01 +00002986Error
2987GDBRemoteCommunicationClient::SetFilePermissions (const char *path,
2988 uint32_t file_permissions)
2989{
2990 lldb_private::StreamString stream;
2991 stream.PutCString("qPlatform_chmod:");
2992 stream.PutHex32(file_permissions);
2993 stream.PutChar(',');
2994 stream.PutBytesAsRawHex8(path, strlen(path));
2995 const char *packet = stream.GetData();
2996 int packet_len = stream.GetSize();
2997 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002998 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002999 {
3000 return Error(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX);
3001 }
3002 return Error();
3003
3004}
3005
Daniel Maleae0f8f572013-08-26 23:57:52 +00003006static uint64_t
3007ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3008 uint64_t fail_result,
3009 Error &error)
3010{
3011 response.SetFilePos(0);
3012 if (response.GetChar() != 'F')
3013 return fail_result;
3014 int32_t result = response.GetS32 (-2);
3015 if (result == -2)
3016 return fail_result;
3017 if (response.GetChar() == ',')
3018 {
3019 int result_errno = response.GetS32 (-2);
3020 if (result_errno != -2)
3021 error.SetError(result_errno, eErrorTypePOSIX);
3022 else
3023 error.SetError(-1, eErrorTypeGeneric);
3024 }
3025 else
3026 error.Clear();
3027 return result;
3028}
3029lldb::user_id_t
3030GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3031 uint32_t flags,
3032 mode_t mode,
3033 Error &error)
3034{
3035 lldb_private::StreamString stream;
3036 stream.PutCString("vFile:open:");
3037 std::string path (file_spec.GetPath());
3038 if (path.empty())
3039 return UINT64_MAX;
3040 stream.PutCStringAsRawHex8(path.c_str());
3041 stream.PutChar(',');
3042 const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags);
3043 stream.PutHex32(posix_open_flags);
3044 stream.PutChar(',');
3045 stream.PutHex32(mode);
3046 const char* packet = stream.GetData();
3047 int packet_len = stream.GetSize();
3048 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003049 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003050 {
3051 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3052 }
3053 return UINT64_MAX;
3054}
3055
3056bool
3057GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3058 Error &error)
3059{
3060 lldb_private::StreamString stream;
3061 stream.Printf("vFile:close:%i", (int)fd);
3062 const char* packet = stream.GetData();
3063 int packet_len = stream.GetSize();
3064 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003065 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003066 {
3067 return ParseHostIOPacketResponse (response, -1, error) == 0;
3068 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003069 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003070}
3071
3072// Extension of host I/O packets to get the file size.
3073lldb::user_id_t
3074GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3075{
3076 lldb_private::StreamString stream;
3077 stream.PutCString("vFile:size:");
3078 std::string path (file_spec.GetPath());
3079 stream.PutCStringAsRawHex8(path.c_str());
3080 const char* packet = stream.GetData();
3081 int packet_len = stream.GetSize();
3082 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003083 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003084 {
3085 if (response.GetChar() != 'F')
3086 return UINT64_MAX;
3087 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3088 return retcode;
3089 }
3090 return UINT64_MAX;
3091}
3092
Greg Claytonfbb76342013-11-20 21:07:01 +00003093Error
3094GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003095{
Greg Claytonfbb76342013-11-20 21:07:01 +00003096 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003097 lldb_private::StreamString stream;
3098 stream.PutCString("vFile:mode:");
Greg Claytonfbb76342013-11-20 21:07:01 +00003099 stream.PutCStringAsRawHex8(path);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003100 const char* packet = stream.GetData();
3101 int packet_len = stream.GetSize();
3102 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003103 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003104 {
3105 if (response.GetChar() != 'F')
3106 {
3107 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003108 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003109 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003110 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003111 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003112 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003113 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003114 if (response.GetChar() == ',')
3115 {
3116 int response_errno = response.GetS32(-1);
3117 if (response_errno > 0)
3118 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3119 else
3120 error.SetErrorToGenericError();
3121 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003122 else
3123 error.SetErrorToGenericError();
3124 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003125 else
3126 {
3127 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3128 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003129 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003130 }
3131 else
3132 {
3133 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3134 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003135 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003136}
3137
3138uint64_t
3139GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3140 uint64_t offset,
3141 void *dst,
3142 uint64_t dst_len,
3143 Error &error)
3144{
3145 lldb_private::StreamString stream;
3146 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3147 const char* packet = stream.GetData();
3148 int packet_len = stream.GetSize();
3149 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003150 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003151 {
3152 if (response.GetChar() != 'F')
3153 return 0;
3154 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3155 if (retcode == UINT32_MAX)
3156 return retcode;
3157 const char next = (response.Peek() ? *response.Peek() : 0);
3158 if (next == ',')
3159 return 0;
3160 if (next == ';')
3161 {
3162 response.GetChar(); // skip the semicolon
3163 std::string buffer;
3164 if (response.GetEscapedBinaryData(buffer))
3165 {
3166 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3167 if (data_to_write > 0)
3168 memcpy(dst, &buffer[0], data_to_write);
3169 return data_to_write;
3170 }
3171 }
3172 }
3173 return 0;
3174}
3175
3176uint64_t
3177GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3178 uint64_t offset,
3179 const void* src,
3180 uint64_t src_len,
3181 Error &error)
3182{
3183 lldb_private::StreamGDBRemote stream;
3184 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3185 stream.PutEscapedBytes(src, src_len);
3186 const char* packet = stream.GetData();
3187 int packet_len = stream.GetSize();
3188 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003189 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003190 {
3191 if (response.GetChar() != 'F')
3192 {
3193 error.SetErrorStringWithFormat("write file failed");
3194 return 0;
3195 }
3196 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3197 if (bytes_written == UINT64_MAX)
3198 {
3199 error.SetErrorToGenericError();
3200 if (response.GetChar() == ',')
3201 {
3202 int response_errno = response.GetS32(-1);
3203 if (response_errno > 0)
3204 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3205 }
3206 return 0;
3207 }
3208 return bytes_written;
3209 }
3210 else
3211 {
3212 error.SetErrorString ("failed to send vFile:pwrite packet");
3213 }
3214 return 0;
3215}
3216
Greg Claytonfbb76342013-11-20 21:07:01 +00003217Error
3218GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst)
3219{
3220 Error error;
3221 lldb_private::StreamGDBRemote stream;
3222 stream.PutCString("vFile:symlink:");
3223 // the unix symlink() command reverses its parameters where the dst if first,
3224 // so we follow suit here
3225 stream.PutCStringAsRawHex8(dst);
3226 stream.PutChar(',');
3227 stream.PutCStringAsRawHex8(src);
3228 const char* packet = stream.GetData();
3229 int packet_len = stream.GetSize();
3230 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003231 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003232 {
3233 if (response.GetChar() == 'F')
3234 {
3235 uint32_t result = response.GetU32(UINT32_MAX);
3236 if (result != 0)
3237 {
3238 error.SetErrorToGenericError();
3239 if (response.GetChar() == ',')
3240 {
3241 int response_errno = response.GetS32(-1);
3242 if (response_errno > 0)
3243 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3244 }
3245 }
3246 }
3247 else
3248 {
3249 // Should have returned with 'F<result>[,<errno>]'
3250 error.SetErrorStringWithFormat("symlink failed");
3251 }
3252 }
3253 else
3254 {
3255 error.SetErrorString ("failed to send vFile:symlink packet");
3256 }
3257 return error;
3258}
3259
3260Error
3261GDBRemoteCommunicationClient::Unlink (const char *path)
3262{
3263 Error error;
3264 lldb_private::StreamGDBRemote stream;
3265 stream.PutCString("vFile:unlink:");
3266 // the unix symlink() command reverses its parameters where the dst if first,
3267 // so we follow suit here
3268 stream.PutCStringAsRawHex8(path);
3269 const char* packet = stream.GetData();
3270 int packet_len = stream.GetSize();
3271 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003272 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003273 {
3274 if (response.GetChar() == 'F')
3275 {
3276 uint32_t result = response.GetU32(UINT32_MAX);
3277 if (result != 0)
3278 {
3279 error.SetErrorToGenericError();
3280 if (response.GetChar() == ',')
3281 {
3282 int response_errno = response.GetS32(-1);
3283 if (response_errno > 0)
3284 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3285 }
3286 }
3287 }
3288 else
3289 {
3290 // Should have returned with 'F<result>[,<errno>]'
3291 error.SetErrorStringWithFormat("unlink failed");
3292 }
3293 }
3294 else
3295 {
3296 error.SetErrorString ("failed to send vFile:unlink packet");
3297 }
3298 return error;
3299}
3300
Daniel Maleae0f8f572013-08-26 23:57:52 +00003301// Extension of host I/O packets to get whether a file exists.
3302bool
3303GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3304{
3305 lldb_private::StreamString stream;
3306 stream.PutCString("vFile:exists:");
3307 std::string path (file_spec.GetPath());
3308 stream.PutCStringAsRawHex8(path.c_str());
3309 const char* packet = stream.GetData();
3310 int packet_len = stream.GetSize();
3311 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003312 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003313 {
3314 if (response.GetChar() != 'F')
3315 return false;
3316 if (response.GetChar() != ',')
3317 return false;
3318 bool retcode = (response.GetChar() != '0');
3319 return retcode;
3320 }
3321 return false;
3322}
3323
3324bool
3325GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3326 uint64_t &high,
3327 uint64_t &low)
3328{
3329 lldb_private::StreamString stream;
3330 stream.PutCString("vFile:MD5:");
3331 std::string path (file_spec.GetPath());
3332 stream.PutCStringAsRawHex8(path.c_str());
3333 const char* packet = stream.GetData();
3334 int packet_len = stream.GetSize();
3335 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003336 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003337 {
3338 if (response.GetChar() != 'F')
3339 return false;
3340 if (response.GetChar() != ',')
3341 return false;
3342 if (response.Peek() && *response.Peek() == 'x')
3343 return false;
3344 low = response.GetHexMaxU64(false, UINT64_MAX);
3345 high = response.GetHexMaxU64(false, UINT64_MAX);
3346 return true;
3347 }
3348 return false;
3349}
Greg Claytonf74cf862013-11-13 23:28:31 +00003350
3351bool
Jason Molendaa3329782014-03-29 18:54:20 +00003352GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3353{
3354 // Some targets have issues with g/G packets and we need to avoid using them
3355 if (m_avoid_g_packets == eLazyBoolCalculate)
3356 {
3357 if (process)
3358 {
3359 m_avoid_g_packets = eLazyBoolNo;
3360 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3361 if (arch.IsValid()
3362 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3363 && arch.GetTriple().getOS() == llvm::Triple::IOS
3364 && arch.GetTriple().getArch() == llvm::Triple::arm64)
3365 {
3366 m_avoid_g_packets = eLazyBoolYes;
3367 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3368 if (gdb_server_version != 0)
3369 {
3370 const char *gdb_server_name = GetGDBServerProgramName();
3371 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3372 {
3373 if (gdb_server_version >= 310)
3374 m_avoid_g_packets = eLazyBoolNo;
3375 }
3376 }
3377 }
3378 }
3379 }
3380 return m_avoid_g_packets == eLazyBoolYes;
3381}
3382
3383bool
Greg Claytonf74cf862013-11-13 23:28:31 +00003384GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3385{
3386 Mutex::Locker locker;
3387 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
3388 {
3389 const bool thread_suffix_supported = GetThreadSuffixSupported();
3390
3391 if (thread_suffix_supported || SetCurrentThread(tid))
3392 {
3393 char packet[64];
3394 int packet_len = 0;
3395 if (thread_suffix_supported)
3396 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
3397 else
3398 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3399 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003400 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003401 }
3402 }
3403 return false;
3404
3405}
3406
3407
3408bool
3409GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3410{
3411 Mutex::Locker locker;
3412 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3413 {
3414 const bool thread_suffix_supported = GetThreadSuffixSupported();
3415
3416 if (thread_suffix_supported || SetCurrentThread(tid))
3417 {
3418 char packet[64];
3419 int packet_len = 0;
3420 // Get all registers in one packet
3421 if (thread_suffix_supported)
3422 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3423 else
3424 packet_len = ::snprintf (packet, sizeof(packet), "g");
3425 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003426 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003427 }
3428 }
3429 return false;
3430}
3431bool
3432GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3433{
3434 save_id = 0; // Set to invalid save ID
3435 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3436 return false;
3437
3438 m_supports_QSaveRegisterState = eLazyBoolYes;
3439 Mutex::Locker locker;
3440 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3441 {
3442 const bool thread_suffix_supported = GetThreadSuffixSupported();
3443 if (thread_suffix_supported || SetCurrentThread(tid))
3444 {
3445 char packet[256];
3446 if (thread_suffix_supported)
3447 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3448 else
3449 ::strncpy (packet, "QSaveRegisterState", sizeof(packet));
3450
3451 StringExtractorGDBRemote response;
3452
Greg Clayton3dedae12013-12-06 21:45:27 +00003453 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003454 {
3455 if (response.IsUnsupportedResponse())
3456 {
3457 // This packet isn't supported, don't try calling it again
3458 m_supports_QSaveRegisterState = eLazyBoolNo;
3459 }
3460
3461 const uint32_t response_save_id = response.GetU32(0);
3462 if (response_save_id != 0)
3463 {
3464 save_id = response_save_id;
3465 return true;
3466 }
3467 }
3468 }
3469 }
3470 return false;
3471}
3472
3473bool
3474GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3475{
3476 // We use the "m_supports_QSaveRegisterState" variable here becuase the
3477 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3478 // order to be useful
3479 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3480 return false;
3481
3482 Mutex::Locker locker;
3483 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
3484 {
3485 const bool thread_suffix_supported = GetThreadSuffixSupported();
3486 if (thread_suffix_supported || SetCurrentThread(tid))
3487 {
3488 char packet[256];
3489 if (thread_suffix_supported)
3490 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3491 else
3492 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3493
3494 StringExtractorGDBRemote response;
3495
Greg Clayton3dedae12013-12-06 21:45:27 +00003496 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003497 {
3498 if (response.IsOKResponse())
3499 {
3500 return true;
3501 }
3502 else if (response.IsUnsupportedResponse())
3503 {
3504 // This packet isn't supported, don't try calling this packet or
3505 // QSaveRegisterState again...
3506 m_supports_QSaveRegisterState = eLazyBoolNo;
3507 }
3508 }
3509 }
3510 }
3511 return false;
3512}