blob: 536df20dfb32bc746fd053df7a76068c2cb8ec8b [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
Saleem Abdulrasool28606952014-06-27 05:17:41 +000020#include "llvm/ADT/STLExtras.h"
Greg Clayton576d8832011-03-22 04:00:09 +000021#include "llvm/ADT/Triple.h"
22#include "lldb/Interpreter/Args.h"
Greg Clayton576d8832011-03-22 04:00:09 +000023#include "lldb/Core/Log.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000024#include "lldb/Core/ModuleSpec.h"
Greg Clayton576d8832011-03-22 04:00:09 +000025#include "lldb/Core/State.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000026#include "lldb/Core/StreamGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000027#include "lldb/Core/StreamString.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000028#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton576d8832011-03-22 04:00:09 +000029#include "lldb/Host/Endian.h"
30#include "lldb/Host/Host.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000031#include "lldb/Host/HostInfo.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000032#include "lldb/Host/StringConvert.h"
Greg Clayton576d8832011-03-22 04:00:09 +000033#include "lldb/Host/TimeValue.h"
Jason Molendaa3329782014-03-29 18:54:20 +000034#include "lldb/Target/Target.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000035#include "lldb/Target/MemoryRegionInfo.h"
Greg Clayton576d8832011-03-22 04:00:09 +000036
37// Project includes
38#include "Utility/StringExtractorGDBRemote.h"
39#include "ProcessGDBRemote.h"
40#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000041#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000042
43using namespace lldb;
44using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000045using namespace lldb_private::process_gdb_remote;
Greg Clayton576d8832011-03-22 04:00:09 +000046
Todd Fiala0a70a842014-05-28 16:43:26 +000047#if defined(LLDB_DISABLE_POSIX) && !defined(SIGSTOP)
Virgile Bellob2f1fb22013-08-23 12:44:05 +000048#define SIGSTOP 17
49#endif
50
Greg Clayton576d8832011-03-22 04:00:09 +000051//----------------------------------------------------------------------
52// GDBRemoteCommunicationClient constructor
53//----------------------------------------------------------------------
Tamas Berghammere13c2732015-02-11 10:29:30 +000054GDBRemoteCommunicationClient::GDBRemoteCommunicationClient() :
55 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet"),
Greg Clayton576d8832011-03-22 04:00:09 +000056 m_supports_not_sending_acks (eLazyBoolCalculate),
57 m_supports_thread_suffix (eLazyBoolCalculate),
Greg Clayton44633992012-04-10 03:22:03 +000058 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
Greg Clayton576d8832011-03-22 04:00:09 +000059 m_supports_vCont_all (eLazyBoolCalculate),
60 m_supports_vCont_any (eLazyBoolCalculate),
61 m_supports_vCont_c (eLazyBoolCalculate),
62 m_supports_vCont_C (eLazyBoolCalculate),
63 m_supports_vCont_s (eLazyBoolCalculate),
64 m_supports_vCont_S (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000065 m_qHostInfo_is_valid (eLazyBoolCalculate),
Todd Fiala9f72b3a2014-05-07 19:28:21 +000066 m_curr_pid_is_valid (eLazyBoolCalculate),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000067 m_qProcessInfo_is_valid (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000068 m_qGDBServerVersion_is_valid (eLazyBoolCalculate),
Greg Clayton70b57652011-05-15 01:25:55 +000069 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
Greg Clayton46fb5582011-11-18 07:03:08 +000070 m_supports_memory_region_info (eLazyBoolCalculate),
Johnny Chen64637202012-05-23 21:09:52 +000071 m_supports_watchpoint_support_info (eLazyBoolCalculate),
Jim Inghamacff8952013-05-02 00:27:30 +000072 m_supports_detach_stay_stopped (eLazyBoolCalculate),
Enrico Granataf04a2192012-07-13 23:18:48 +000073 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
Jim Inghamcd16df92012-07-20 21:37:13 +000074 m_attach_or_wait_reply(eLazyBoolCalculate),
Jim Ingham279ceec2012-07-25 21:12:43 +000075 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
Eric Christopher2490f5c2013-08-30 17:50:57 +000076 m_supports_p (eLazyBoolCalculate),
Jason Molendabdc4f122014-05-06 02:59:39 +000077 m_supports_x (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000078 m_avoid_g_packets (eLazyBoolCalculate),
Greg Claytonf74cf862013-11-13 23:28:31 +000079 m_supports_QSaveRegisterState (eLazyBoolCalculate),
Steve Pucci03904ac2014-03-04 23:18:46 +000080 m_supports_qXfer_auxv_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000081 m_supports_qXfer_libraries_read (eLazyBoolCalculate),
82 m_supports_qXfer_libraries_svr4_read (eLazyBoolCalculate),
Greg Clayton253204e2015-04-16 23:11:06 +000083 m_supports_qXfer_features_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000084 m_supports_augmented_libraries_svr4_read (eLazyBoolCalculate),
Jason Molenda705b1802014-06-13 02:37:02 +000085 m_supports_jThreadExtendedInfo (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000086 m_supports_qProcessInfoPID (true),
87 m_supports_qfProcessInfo (true),
88 m_supports_qUserName (true),
89 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000090 m_supports_qThreadStopInfo (true),
91 m_supports_z0 (true),
92 m_supports_z1 (true),
93 m_supports_z2 (true),
94 m_supports_z3 (true),
95 m_supports_z4 (true),
Greg Clayton89600582013-10-10 17:53:50 +000096 m_supports_QEnvironment (true),
97 m_supports_QEnvironmentHexEncoded (true),
Todd Fiala9f72b3a2014-05-07 19:28:21 +000098 m_curr_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton8b82f082011-04-12 05:54:46 +000099 m_curr_tid (LLDB_INVALID_THREAD_ID),
100 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +0000101 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +0000102 m_async_mutex (Mutex::eMutexTypeRecursive),
103 m_async_packet_predicate (false),
104 m_async_packet (),
Jim Inghama6195b72013-12-18 01:24:33 +0000105 m_async_result (PacketResult::Success),
Greg Clayton576d8832011-03-22 04:00:09 +0000106 m_async_response (),
107 m_async_signal (-1),
Jim Inghamb8cd5752014-04-16 02:24:17 +0000108 m_interrupt_sent (false),
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000109 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +0000110 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000111 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +0000112 m_os_version_major (UINT32_MAX),
113 m_os_version_minor (UINT32_MAX),
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000114 m_os_version_update (UINT32_MAX),
115 m_os_build (),
116 m_os_kernel (),
117 m_hostname (),
Jason Molendaa3329782014-03-29 18:54:20 +0000118 m_gdb_server_name(),
119 m_gdb_server_version(UINT32_MAX),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000120 m_default_packet_timeout (0),
121 m_max_packet_size (0)
Greg Clayton576d8832011-03-22 04:00:09 +0000122{
Greg Clayton576d8832011-03-22 04:00:09 +0000123}
124
125//----------------------------------------------------------------------
126// Destructor
127//----------------------------------------------------------------------
128GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
129{
Greg Clayton576d8832011-03-22 04:00:09 +0000130 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000131 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000132}
133
134bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000135GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
136{
Greg Claytonfb909312013-11-23 01:58:15 +0000137 ResetDiscoverableSettings();
138
Greg Clayton1cb64962011-03-24 04:28:38 +0000139 // Start the read thread after we send the handshake ack since if we
140 // fail to send the handshake ack, there is no reason to continue...
141 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000142 {
Ed Maste48f986f2013-12-18 15:31:45 +0000143 // Wait for any responses that might have been queued up in the remote
144 // GDB server and flush them all
145 StringExtractorGDBRemote response;
146 PacketResult packet_result = PacketResult::Success;
147 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
148 while (packet_result == PacketResult::Success)
149 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, timeout_usec);
150
Greg Claytonfb909312013-11-23 01:58:15 +0000151 // The return value from QueryNoAckModeSupported() is true if the packet
152 // was sent and _any_ response (including UNIMPLEMENTED) was received),
153 // or false if no response was received. This quickly tells us if we have
154 // a live connection to a remote GDB server...
155 if (QueryNoAckModeSupported())
156 {
Greg Clayton700e5082014-02-21 19:11:28 +0000157#if 0
158 // Set above line to "#if 1" to test packet speed if remote GDB server
159 // supports the qSpeedTest packet...
160 TestPacketSpeed(10000);
161#endif
Greg Claytonfb909312013-11-23 01:58:15 +0000162 return true;
163 }
164 else
165 {
166 if (error_ptr)
167 error_ptr->SetErrorString("failed to get reply to handshake packet");
168 }
169 }
170 else
171 {
172 if (error_ptr)
173 error_ptr->SetErrorString("failed to send the handshake ack");
174 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000175 return false;
176}
177
Greg Claytonfb909312013-11-23 01:58:15 +0000178bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000179GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
180{
181 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
182 {
183 GetRemoteQSupported();
184 }
185 return (m_supports_augmented_libraries_svr4_read == eLazyBoolYes);
186}
187
188bool
189GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
190{
191 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
192 {
193 GetRemoteQSupported();
194 }
195 return (m_supports_qXfer_libraries_svr4_read == eLazyBoolYes);
196}
197
198bool
199GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
200{
201 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
202 {
203 GetRemoteQSupported();
204 }
205 return (m_supports_qXfer_libraries_read == eLazyBoolYes);
206}
207
Steve Pucci03904ac2014-03-04 23:18:46 +0000208bool
209GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
210{
211 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
212 {
213 GetRemoteQSupported();
214 }
215 return (m_supports_qXfer_auxv_read == eLazyBoolYes);
216}
217
Colin Rileyc3c95b22015-04-16 15:51:33 +0000218bool
219GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported ()
220{
221 if (m_supports_qXfer_features_read == eLazyBoolCalculate)
222 {
223 GetRemoteQSupported();
224 }
225 return (m_supports_qXfer_features_read == eLazyBoolYes);
226}
227
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000228uint64_t
229GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
230{
231 if (m_max_packet_size == 0)
232 {
233 GetRemoteQSupported();
234 }
235 return m_max_packet_size;
236}
237
238bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000239GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000240{
241 if (m_supports_not_sending_acks == eLazyBoolCalculate)
242 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000243 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000244 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000245
Jason Molenda36a216e2014-07-24 01:36:24 +0000246 // This is the first real packet that we'll send in a debug session and it may take a little
247 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
248
249 const uint32_t minimum_timeout = 6;
250 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000251 GDBRemoteCommunication::ScopedTimeout timeout (*this, std::max (old_timeout, minimum_timeout));
Jason Molenda36a216e2014-07-24 01:36:24 +0000252
Greg Clayton1cb64962011-03-24 04:28:38 +0000253 StringExtractorGDBRemote response;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000254 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000255 {
256 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000257 {
258 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000259 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000260 }
Greg Claytonfb909312013-11-23 01:58:15 +0000261 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000262 }
263 }
Greg Claytonfb909312013-11-23 01:58:15 +0000264 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000265}
266
267void
Greg Clayton44633992012-04-10 03:22:03 +0000268GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
269{
270 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
271 {
272 m_supports_threads_in_stop_reply = eLazyBoolNo;
273
274 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000275 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000276 {
277 if (response.IsOKResponse())
278 m_supports_threads_in_stop_reply = eLazyBoolYes;
279 }
280 }
281}
282
Jim Inghamcd16df92012-07-20 21:37:13 +0000283bool
284GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
285{
286 if (m_attach_or_wait_reply == eLazyBoolCalculate)
287 {
288 m_attach_or_wait_reply = eLazyBoolNo;
289
290 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000291 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000292 {
293 if (response.IsOKResponse())
294 m_attach_or_wait_reply = eLazyBoolYes;
295 }
296 }
297 if (m_attach_or_wait_reply == eLazyBoolYes)
298 return true;
299 else
300 return false;
301}
302
Jim Ingham279ceec2012-07-25 21:12:43 +0000303bool
304GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
305{
306 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
307 {
308 m_prepare_for_reg_writing_reply = eLazyBoolNo;
309
310 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000311 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000312 {
313 if (response.IsOKResponse())
314 m_prepare_for_reg_writing_reply = eLazyBoolYes;
315 }
316 }
317 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
318 return true;
319 else
320 return false;
321}
322
Greg Clayton44633992012-04-10 03:22:03 +0000323
324void
Greg Clayton576d8832011-03-22 04:00:09 +0000325GDBRemoteCommunicationClient::ResetDiscoverableSettings()
326{
327 m_supports_not_sending_acks = eLazyBoolCalculate;
328 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton44633992012-04-10 03:22:03 +0000329 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
Greg Clayton576d8832011-03-22 04:00:09 +0000330 m_supports_vCont_c = eLazyBoolCalculate;
331 m_supports_vCont_C = eLazyBoolCalculate;
332 m_supports_vCont_s = eLazyBoolCalculate;
333 m_supports_vCont_S = eLazyBoolCalculate;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000334 m_supports_p = eLazyBoolCalculate;
Jason Molendabdc4f122014-05-06 02:59:39 +0000335 m_supports_x = eLazyBoolCalculate;
Greg Claytonf74cf862013-11-13 23:28:31 +0000336 m_supports_QSaveRegisterState = eLazyBoolCalculate;
Greg Clayton32e0a752011-03-30 18:16:51 +0000337 m_qHostInfo_is_valid = eLazyBoolCalculate;
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000338 m_curr_pid_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000339 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000340 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
Greg Clayton70b57652011-05-15 01:25:55 +0000341 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton46fb5582011-11-18 07:03:08 +0000342 m_supports_memory_region_info = eLazyBoolCalculate;
Jim Ingham279ceec2012-07-25 21:12:43 +0000343 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
344 m_attach_or_wait_reply = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000345 m_avoid_g_packets = eLazyBoolCalculate;
Steve Pucci03904ac2014-03-04 23:18:46 +0000346 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000347 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
348 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000349 m_supports_qXfer_features_read = eLazyBoolCalculate;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000350 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
Greg Clayton2a48f522011-05-14 01:50:35 +0000351
Greg Clayton32e0a752011-03-30 18:16:51 +0000352 m_supports_qProcessInfoPID = true;
353 m_supports_qfProcessInfo = true;
354 m_supports_qUserName = true;
355 m_supports_qGroupName = true;
Greg Clayton8b82f082011-04-12 05:54:46 +0000356 m_supports_qThreadStopInfo = true;
357 m_supports_z0 = true;
358 m_supports_z1 = true;
359 m_supports_z2 = true;
360 m_supports_z3 = true;
361 m_supports_z4 = true;
Greg Clayton89600582013-10-10 17:53:50 +0000362 m_supports_QEnvironment = true;
363 m_supports_QEnvironmentHexEncoded = true;
Jason Molendaa3329782014-03-29 18:54:20 +0000364
Greg Claytond314e812011-03-23 00:09:55 +0000365 m_host_arch.Clear();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000366 m_process_arch.Clear();
Jason Molendaa3329782014-03-29 18:54:20 +0000367 m_os_version_major = UINT32_MAX;
368 m_os_version_minor = UINT32_MAX;
369 m_os_version_update = UINT32_MAX;
370 m_os_build.clear();
371 m_os_kernel.clear();
372 m_hostname.clear();
373 m_gdb_server_name.clear();
374 m_gdb_server_version = UINT32_MAX;
375 m_default_packet_timeout = 0;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000376
377 m_max_packet_size = 0;
Greg Clayton576d8832011-03-22 04:00:09 +0000378}
379
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000380void
381GDBRemoteCommunicationClient::GetRemoteQSupported ()
382{
383 // Clear out any capabilities we expect to see in the qSupported response
Steve Pucci03904ac2014-03-04 23:18:46 +0000384 m_supports_qXfer_auxv_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000385 m_supports_qXfer_libraries_read = eLazyBoolNo;
Steve Pucci03904ac2014-03-04 23:18:46 +0000386 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000387 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000388 m_supports_qXfer_features_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000389 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
390
Colin Rileyc3c95b22015-04-16 15:51:33 +0000391 // build the qSupported packet
392 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
393 StreamString packet;
394 packet.PutCString( "qSupported" );
395 for ( uint32_t i = 0; i < features.size( ); ++i )
396 {
397 packet.PutCString( i==0 ? ":" : ";");
398 packet.PutCString( features[i].c_str( ) );
399 }
400
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000401 StringExtractorGDBRemote response;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000402 if (SendPacketAndWaitForResponse(packet.GetData(),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000403 response,
404 /*send_async=*/false) == PacketResult::Success)
405 {
406 const char *response_cstr = response.GetStringRef().c_str();
Steve Pucci03904ac2014-03-04 23:18:46 +0000407 if (::strstr (response_cstr, "qXfer:auxv:read+"))
408 m_supports_qXfer_auxv_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000409 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
410 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
411 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
412 {
413 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
414 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
415 }
416 if (::strstr (response_cstr, "qXfer:libraries:read+"))
417 m_supports_qXfer_libraries_read = eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000418 if (::strstr (response_cstr, "qXfer:features:read+"))
419 m_supports_qXfer_features_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000420
421 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
422 if (packet_size_str)
423 {
424 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
425 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
426 if (m_max_packet_size == 0)
427 {
428 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
429 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
430 if (log)
431 log->Printf ("Garbled PacketSize spec in qSupported response");
432 }
433 }
434 }
435}
Greg Clayton576d8832011-03-22 04:00:09 +0000436
437bool
438GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
439{
440 if (m_supports_thread_suffix == eLazyBoolCalculate)
441 {
442 StringExtractorGDBRemote response;
443 m_supports_thread_suffix = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000444 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000445 {
446 if (response.IsOKResponse())
447 m_supports_thread_suffix = eLazyBoolYes;
448 }
449 }
450 return m_supports_thread_suffix;
451}
452bool
453GDBRemoteCommunicationClient::GetVContSupported (char flavor)
454{
455 if (m_supports_vCont_c == eLazyBoolCalculate)
456 {
457 StringExtractorGDBRemote response;
458 m_supports_vCont_any = eLazyBoolNo;
459 m_supports_vCont_all = eLazyBoolNo;
460 m_supports_vCont_c = eLazyBoolNo;
461 m_supports_vCont_C = eLazyBoolNo;
462 m_supports_vCont_s = eLazyBoolNo;
463 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000464 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000465 {
466 const char *response_cstr = response.GetStringRef().c_str();
467 if (::strstr (response_cstr, ";c"))
468 m_supports_vCont_c = eLazyBoolYes;
469
470 if (::strstr (response_cstr, ";C"))
471 m_supports_vCont_C = eLazyBoolYes;
472
473 if (::strstr (response_cstr, ";s"))
474 m_supports_vCont_s = eLazyBoolYes;
475
476 if (::strstr (response_cstr, ";S"))
477 m_supports_vCont_S = eLazyBoolYes;
478
479 if (m_supports_vCont_c == eLazyBoolYes &&
480 m_supports_vCont_C == eLazyBoolYes &&
481 m_supports_vCont_s == eLazyBoolYes &&
482 m_supports_vCont_S == eLazyBoolYes)
483 {
484 m_supports_vCont_all = eLazyBoolYes;
485 }
486
487 if (m_supports_vCont_c == eLazyBoolYes ||
488 m_supports_vCont_C == eLazyBoolYes ||
489 m_supports_vCont_s == eLazyBoolYes ||
490 m_supports_vCont_S == eLazyBoolYes)
491 {
492 m_supports_vCont_any = eLazyBoolYes;
493 }
494 }
495 }
496
497 switch (flavor)
498 {
499 case 'a': return m_supports_vCont_any;
500 case 'A': return m_supports_vCont_all;
501 case 'c': return m_supports_vCont_c;
502 case 'C': return m_supports_vCont_C;
503 case 's': return m_supports_vCont_s;
504 case 'S': return m_supports_vCont_S;
505 default: break;
506 }
507 return false;
508}
509
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000510// Check if the target supports 'p' packet. It sends out a 'p'
511// packet and checks the response. A normal packet will tell us
512// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000513//
514// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000515bool
Sean Callananb1de1142013-09-04 23:24:15 +0000516GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000517{
518 if (m_supports_p == eLazyBoolCalculate)
519 {
520 StringExtractorGDBRemote response;
521 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000522 char packet[256];
523 if (GetThreadSuffixSupported())
524 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
525 else
526 snprintf(packet, sizeof(packet), "p0");
527
Greg Clayton3dedae12013-12-06 21:45:27 +0000528 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000529 {
530 if (response.IsNormalResponse())
531 m_supports_p = eLazyBoolYes;
532 }
533 }
534 return m_supports_p;
535}
Greg Clayton576d8832011-03-22 04:00:09 +0000536
Jason Molendabdc4f122014-05-06 02:59:39 +0000537bool
Jason Molenda705b1802014-06-13 02:37:02 +0000538GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
539{
540 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
541 {
542 StringExtractorGDBRemote response;
543 m_supports_jThreadExtendedInfo = eLazyBoolNo;
544 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
545 {
546 if (response.IsOKResponse())
547 {
548 m_supports_jThreadExtendedInfo = eLazyBoolYes;
549 }
550 }
551 }
552 return m_supports_jThreadExtendedInfo;
553}
554
555bool
Jason Molendabdc4f122014-05-06 02:59:39 +0000556GDBRemoteCommunicationClient::GetxPacketSupported ()
557{
558 if (m_supports_x == eLazyBoolCalculate)
559 {
560 StringExtractorGDBRemote response;
561 m_supports_x = eLazyBoolNo;
562 char packet[256];
563 snprintf (packet, sizeof (packet), "x0,0");
564 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
565 {
566 if (response.IsOKResponse())
567 m_supports_x = eLazyBoolYes;
568 }
569 }
570 return m_supports_x;
571}
572
Greg Clayton3dedae12013-12-06 21:45:27 +0000573GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000574GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
575(
576 const char *payload_prefix,
577 std::string &response_string
578)
579{
580 Mutex::Locker locker;
581 if (!GetSequenceMutex(locker,
582 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
583 {
584 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
585 if (log)
586 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
587 payload_prefix);
588 return PacketResult::ErrorNoSequenceLock;
589 }
590
591 response_string = "";
592 std::string payload_prefix_str(payload_prefix);
593 unsigned int response_size = 0x1000;
594 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
595 response_size = GetRemoteMaxPacketSize();
596 }
597
598 for (unsigned int offset = 0; true; offset += response_size)
599 {
600 StringExtractorGDBRemote this_response;
601 // Construct payload
602 char sizeDescriptor[128];
603 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
604 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
605 this_response,
606 /*send_async=*/false);
607 if (result != PacketResult::Success)
608 return result;
609
610 const std::string &this_string = this_response.GetStringRef();
611
612 // Check for m or l as first character; l seems to mean this is the last chunk
613 char first_char = *this_string.c_str();
614 if (first_char != 'm' && first_char != 'l')
615 {
616 return PacketResult::ErrorReplyInvalid;
617 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000618 // Concatenate the result so far (skipping 'm' or 'l')
619 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000620 if (first_char == 'l')
621 // We're done
622 return PacketResult::Success;
623 }
624}
625
626GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000627GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
628(
629 const char *payload,
630 StringExtractorGDBRemote &response,
631 bool send_async
632)
633{
634 return SendPacketAndWaitForResponse (payload,
635 ::strlen (payload),
636 response,
637 send_async);
638}
639
Greg Clayton3dedae12013-12-06 21:45:27 +0000640GDBRemoteCommunicationClient::PacketResult
641GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
642 size_t payload_length,
643 StringExtractorGDBRemote &response)
644{
645 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
646 if (packet_result == PacketResult::Success)
647 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
648 return packet_result;
649}
650
651GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000652GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
653(
654 const char *payload,
655 size_t payload_length,
656 StringExtractorGDBRemote &response,
657 bool send_async
658)
659{
Greg Clayton3dedae12013-12-06 21:45:27 +0000660 PacketResult packet_result = PacketResult::ErrorSendFailed;
Greg Clayton576d8832011-03-22 04:00:09 +0000661 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000662 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000663 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000664 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000665 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000666 }
667 else
668 {
669 if (send_async)
670 {
Greg Claytond3544052012-05-31 21:24:20 +0000671 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000672 {
Greg Claytond3544052012-05-31 21:24:20 +0000673 Mutex::Locker async_locker (m_async_mutex);
674 m_async_packet.assign(payload, payload_length);
675 m_async_packet_predicate.SetValue (true, eBroadcastNever);
676
677 if (log)
678 log->Printf ("async: async packet = %s", m_async_packet.c_str());
679
680 bool timed_out = false;
681 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000682 {
Greg Claytond3544052012-05-31 21:24:20 +0000683 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000684 {
Jim Inghambabfc382012-06-06 00:32:39 +0000685 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000686 TimeValue timeout_time;
687 timeout_time = TimeValue::Now();
688 timeout_time.OffsetWithSeconds (m_packet_timeout);
689
Greg Clayton576d8832011-03-22 04:00:09 +0000690 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000691 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000692
Greg Claytond3544052012-05-31 21:24:20 +0000693 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000694 {
Greg Claytond3544052012-05-31 21:24:20 +0000695 if (log)
696 log->Printf ("async: got response");
697
698 // Swap the response buffer to avoid malloc and string copy
699 response.GetStringRef().swap (m_async_response.GetStringRef());
Jim Inghama6195b72013-12-18 01:24:33 +0000700 packet_result = m_async_result;
Greg Claytond3544052012-05-31 21:24:20 +0000701 }
702 else
703 {
704 if (log)
705 log->Printf ("async: timed out waiting for response");
706 }
707
708 // Make sure we wait until the continue packet has been sent again...
709 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
710 {
711 if (log)
712 {
713 if (timed_out)
714 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
715 else
716 log->Printf ("async: async packet sent");
717 }
718 }
719 else
720 {
721 if (log)
722 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000723 }
724 }
725 else
726 {
Greg Claytond3544052012-05-31 21:24:20 +0000727 // We had a racy condition where we went to send the interrupt
728 // yet we were able to get the lock, so the process must have
729 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000730 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000731 log->Printf ("async: got lock without sending interrupt");
732 // Send the packet normally since we got the lock
Greg Clayton3dedae12013-12-06 21:45:27 +0000733 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000734 }
735 }
736 else
737 {
Greg Clayton644247c2011-07-07 01:59:51 +0000738 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000739 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000740 }
741 }
742 else
743 {
744 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000745 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000746 }
747 }
748 else
749 {
750 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000751 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000752 }
753 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000754 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000755}
756
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000757static const char *end_delimiter = "--end--;";
758static const int end_delimiter_len = 8;
759
760std::string
761GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
762( ProcessGDBRemote *process,
763 StringExtractorGDBRemote& profileDataExtractor
764)
765{
766 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
767 std::stringstream final_output;
768 std::string name, value;
769
770 // Going to assuming thread_used_usec comes first, else bail out.
771 while (profileDataExtractor.GetNameColonValue(name, value))
772 {
773 if (name.compare("thread_used_id") == 0)
774 {
775 StringExtractor threadIDHexExtractor(value.c_str());
776 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
777
778 bool has_used_usec = false;
779 uint32_t curr_used_usec = 0;
780 std::string usec_name, usec_value;
781 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
782 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
783 {
784 if (usec_name.compare("thread_used_usec") == 0)
785 {
786 has_used_usec = true;
787 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
788 }
789 else
790 {
791 // We didn't find what we want, it is probably
792 // an older version. Bail out.
793 profileDataExtractor.SetFilePos(input_file_pos);
794 }
795 }
796
797 if (has_used_usec)
798 {
799 uint32_t prev_used_usec = 0;
800 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
801 if (iterator != m_thread_id_to_used_usec_map.end())
802 {
803 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
804 }
805
806 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
807 // A good first time record is one that runs for at least 0.25 sec
808 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
809 bool good_subsequent_time = (prev_used_usec > 0) &&
810 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
811
812 if (good_first_time || good_subsequent_time)
813 {
814 // We try to avoid doing too many index id reservation,
815 // resulting in fast increase of index ids.
816
817 final_output << name << ":";
818 int32_t index_id = process->AssignIndexIDToThread(thread_id);
819 final_output << index_id << ";";
820
821 final_output << usec_name << ":" << usec_value << ";";
822 }
823 else
824 {
825 // Skip past 'thread_used_name'.
826 std::string local_name, local_value;
827 profileDataExtractor.GetNameColonValue(local_name, local_value);
828 }
829
830 // Store current time as previous time so that they can be compared later.
831 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
832 }
833 else
834 {
835 // Bail out and use old string.
836 final_output << name << ":" << value << ";";
837 }
838 }
839 else
840 {
841 final_output << name << ":" << value << ";";
842 }
843 }
844 final_output << end_delimiter;
845 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
846
847 return final_output.str();
848}
849
Greg Clayton576d8832011-03-22 04:00:09 +0000850StateType
851GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
852(
853 ProcessGDBRemote *process,
854 const char *payload,
855 size_t packet_length,
856 StringExtractorGDBRemote &response
857)
858{
Greg Clayton1f5181a2012-07-02 22:05:25 +0000859 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +0000860 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +0000861 if (log)
862 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
863
864 Mutex::Locker locker(m_sequence_mutex);
865 StateType state = eStateRunning;
866
867 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
868 m_public_is_running.SetValue (true, eBroadcastNever);
869 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +0000870 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +0000871 std::string continue_packet(payload, packet_length);
872
Greg Clayton3f875c52013-02-22 22:23:55 +0000873 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +0000874
Greg Clayton576d8832011-03-22 04:00:09 +0000875 while (state == eStateRunning)
876 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000877 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +0000878 {
879 if (log)
880 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton3dedae12013-12-06 21:45:27 +0000881 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
Greg Claytonaf247d72011-05-19 03:54:16 +0000882 state = eStateInvalid;
Jim Inghamb8cd5752014-04-16 02:24:17 +0000883 else
884 m_interrupt_sent = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000885
Greg Claytone889ad62011-10-27 22:04:16 +0000886 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +0000887 }
888
Greg Clayton3f875c52013-02-22 22:23:55 +0000889 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000890
891 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000892 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +0000893
Greg Clayton3dedae12013-12-06 21:45:27 +0000894 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000895 {
896 if (response.Empty())
897 state = eStateInvalid;
898 else
899 {
900 const char stop_type = response.GetChar();
901 if (log)
902 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
903 switch (stop_type)
904 {
905 case 'T':
906 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +0000907 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000908 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +0000909 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000910 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
911 {
912 lldb::pid_t pid = GetCurrentProcessID ();
913 if (pid != LLDB_INVALID_PROCESS_ID)
914 process->SetID (pid);
915 }
916 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +0000917 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000918
919 // Privately notify any internal threads that we have stopped
920 // in case we wanted to interrupt our process, yet we might
921 // send a packet and continue without returning control to the
922 // user.
923 m_private_is_running.SetValue (false, eBroadcastAlways);
924
925 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
926
Jim Inghambabfc382012-06-06 00:32:39 +0000927 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
928 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +0000929 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000930 // We sent an interrupt packet to stop the inferior process
931 // for an async signal or to send an async packet while running
932 // but we might have been single stepping and received the
933 // stop packet for the step instead of for the interrupt packet.
934 // Typically when an interrupt is sent a SIGINT or SIGSTOP
935 // is used, so if we get anything else, we need to try and
936 // get another stop reply packet that may have been sent
937 // due to sending the interrupt when the target is stopped
938 // which will just re-send a copy of the last stop reply
939 // packet. If we don't do this, then the reply for our
940 // async packet will be the repeat stop reply packet and cause
941 // a lot of trouble for us!
942 if (signo != SIGINT && signo != SIGSTOP)
943 {
Greg Claytonfb72fde2012-05-15 02:50:49 +0000944 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000945
946 // We didn't get a a SIGINT or SIGSTOP, so try for a
947 // very brief time (1 ms) to get another stop reply
948 // packet to make sure it doesn't get in the way
949 StringExtractorGDBRemote extra_stop_reply_packet;
950 uint32_t timeout_usec = 1000;
Greg Clayton3dedae12013-12-06 21:45:27 +0000951 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +0000952 {
953 switch (extra_stop_reply_packet.GetChar())
954 {
955 case 'T':
956 case 'S':
957 // We did get an extra stop reply, which means
958 // our interrupt didn't stop the target so we
959 // shouldn't continue after the async signal
960 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +0000961 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000962 break;
963 }
964 }
965 }
966 }
967
968 if (m_async_signal != -1)
969 {
970 if (log)
971 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
972
973 // Save off the async signal we are supposed to send
974 const int async_signal = m_async_signal;
975 // Clear the async signal member so we don't end up
976 // sending the signal multiple times...
977 m_async_signal = -1;
978 // Check which signal we stopped with
979 if (signo == async_signal)
980 {
981 if (log)
982 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
983
984 // We already stopped with a signal that we wanted
985 // to stop with, so we are done
986 }
987 else
988 {
989 // We stopped with a different signal that the one
990 // we wanted to stop with, so now we must resume
991 // with the signal we want
992 char signal_packet[32];
993 int signal_packet_len = 0;
994 signal_packet_len = ::snprintf (signal_packet,
995 sizeof (signal_packet),
996 "C%2.2x",
997 async_signal);
998
999 if (log)
1000 log->Printf ("async: stopped with signal %s, resume with %s",
1001 Host::GetSignalAsCString (signo),
1002 Host::GetSignalAsCString (async_signal));
1003
1004 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +00001005 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001006 continue_packet.assign(signal_packet, signal_packet_len);
1007 continue;
1008 }
1009 }
1010 else if (m_async_packet_predicate.GetValue())
1011 {
Greg Clayton5160ce52013-03-27 23:08:40 +00001012 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +00001013
1014 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +00001015 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +00001016 m_async_response.Clear();
1017 if (m_async_packet.empty())
1018 {
Jim Inghama6195b72013-12-18 01:24:33 +00001019 m_async_result = PacketResult::ErrorSendFailed;
1020 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001021 packet_log->Printf ("async: error: empty async packet");
1022
1023 }
1024 else
1025 {
1026 if (packet_log)
1027 packet_log->Printf ("async: sending packet");
1028
Jim Inghama6195b72013-12-18 01:24:33 +00001029 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1030 m_async_packet.size(),
1031 m_async_response,
1032 false);
Greg Clayton2687cd12012-03-29 01:55:41 +00001033 }
1034 // Let the other thread that was trying to send the async
1035 // packet know that the packet has been sent and response is
1036 // ready...
1037 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1038
1039 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +00001040 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +00001041
1042 // Set the continue packet to resume if our interrupt
1043 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +00001044 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001045 {
Greg Claytonf1186de2012-05-24 23:42:14 +00001046 // Reverting this for now as it is causing deadlocks
1047 // in programs (<rdar://problem/11529853>). In the future
1048 // we should check our thread list and "do the right thing"
1049 // for new threads that show up while we stop and run async
1050 // packets. Setting the packet to 'c' to continue all threads
1051 // is the right thing to do 99.99% of the time because if a
1052 // thread was single stepping, and we sent an interrupt, we
1053 // will notice above that we didn't stop due to an interrupt
1054 // but stopped due to stepping and we would _not_ continue.
1055 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +00001056 continue;
1057 }
1058 }
1059 // Stop with signal and thread info
1060 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +00001061 }
Greg Clayton576d8832011-03-22 04:00:09 +00001062 break;
1063
1064 case 'W':
1065 case 'X':
1066 // process exited
1067 state = eStateExited;
1068 break;
1069
1070 case 'O':
1071 // STDOUT
1072 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001073 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001074 std::string inferior_stdout;
1075 inferior_stdout.reserve(response.GetBytesLeft () / 2);
1076 char ch;
1077 while ((ch = response.GetHexU8()) != '\0')
1078 inferior_stdout.append(1, ch);
1079 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1080 }
1081 break;
1082
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001083 case 'A':
1084 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1085 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001086 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001087 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1088 if (m_partial_profile_data.length() > 0)
1089 {
1090 m_partial_profile_data.append(input);
1091 input = m_partial_profile_data;
1092 m_partial_profile_data.clear();
1093 }
1094
1095 size_t found, pos = 0, len = input.length();
1096 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1097 {
1098 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +00001099 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1100 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001101
1102 pos = found + end_delimiter_len;
1103 }
1104
1105 if (pos < len)
1106 {
1107 // Last incomplete chunk.
1108 m_partial_profile_data = input.substr(pos);
1109 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001110 }
1111 break;
1112
Greg Clayton576d8832011-03-22 04:00:09 +00001113 case 'E':
1114 // ERROR
1115 state = eStateInvalid;
1116 break;
1117
1118 default:
1119 if (log)
1120 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1121 state = eStateInvalid;
1122 break;
1123 }
1124 }
1125 }
1126 else
1127 {
1128 if (log)
1129 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
1130 state = eStateInvalid;
1131 }
1132 }
1133 if (log)
1134 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1135 response.SetFilePos(0);
1136 m_private_is_running.SetValue (false, eBroadcastAlways);
1137 m_public_is_running.SetValue (false, eBroadcastAlways);
1138 return state;
1139}
1140
1141bool
1142GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1143{
Greg Clayton2687cd12012-03-29 01:55:41 +00001144 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001145 m_async_signal = signo;
1146 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001147 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001148 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001149 return true;
1150 m_async_signal = -1;
1151 return false;
1152}
1153
Greg Clayton37a0a242012-04-11 00:24:49 +00001154// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001155// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1156// (the expected result), then it will send the halt packet. If it does succeed
1157// then the caller that requested the interrupt will want to keep the sequence
1158// locked down so that no one else can send packets while the caller has control.
1159// This function usually gets called when we are running and need to stop the
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001160// target. It can also be used when we are running and we need to do something
Greg Clayton576d8832011-03-22 04:00:09 +00001161// else (like read/write memory), so we need to interrupt the running process
1162// (gdb remote protocol requires this), and do what we need to do, then resume.
1163
1164bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001165GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001166(
1167 Mutex::Locker& locker,
1168 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001169 bool &timed_out
1170)
1171{
Greg Clayton576d8832011-03-22 04:00:09 +00001172 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001173 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001174
1175 if (IsRunning())
1176 {
1177 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001178 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001179 {
1180 if (log)
1181 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1182 }
1183 else
Greg Clayton576d8832011-03-22 04:00:09 +00001184 {
1185 // Someone has the mutex locked waiting for a response or for the
1186 // inferior to stop, so send the interrupt on the down low...
1187 char ctrl_c = '\x03';
1188 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001189 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001190 if (log)
1191 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001192 if (bytes_written > 0)
1193 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001194 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001195 if (seconds_to_wait_for_stop)
1196 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001197 TimeValue timeout;
1198 if (seconds_to_wait_for_stop)
1199 {
1200 timeout = TimeValue::Now();
1201 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1202 }
Greg Clayton576d8832011-03-22 04:00:09 +00001203 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1204 {
1205 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001206 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001207 return true;
1208 }
1209 else
1210 {
1211 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001212 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001213 }
1214 }
1215 else
1216 {
1217 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001218 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001219 return true;
1220 }
1221 }
1222 else
1223 {
1224 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001225 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001226 }
1227 return false;
1228 }
Greg Clayton576d8832011-03-22 04:00:09 +00001229 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001230 else
1231 {
1232 if (log)
1233 log->Printf ("SendInterrupt () - not running");
1234 }
Greg Clayton576d8832011-03-22 04:00:09 +00001235 return true;
1236}
1237
1238lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001239GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +00001240{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001241 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001242 return m_curr_pid;
1243
1244 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001245 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001246 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +00001247 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001248 // We really got it.
1249 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +00001250 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001251 else
1252 {
Todd Fialae24614f2014-05-14 00:15:32 +00001253 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1254 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1255 // The gdb remote protocol documents $qC as returning the thread id, which newer
1256 // debugserver and lldb-gdbserver stubs return correctly.
1257 StringExtractorGDBRemote response;
1258 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001259 {
Todd Fialae24614f2014-05-14 00:15:32 +00001260 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001261 {
Todd Fialae24614f2014-05-14 00:15:32 +00001262 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001263 {
Todd Fialae24614f2014-05-14 00:15:32 +00001264 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1265 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001266 {
Todd Fialae24614f2014-05-14 00:15:32 +00001267 m_curr_pid_is_valid = eLazyBoolYes;
1268 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001269 }
1270 }
1271 }
1272 }
1273 }
1274
Greg Clayton576d8832011-03-22 04:00:09 +00001275 return LLDB_INVALID_PROCESS_ID;
1276}
1277
1278bool
1279GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1280{
1281 error_str.clear();
1282 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001283 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001284 {
1285 if (response.IsOKResponse())
1286 return true;
1287 if (response.GetChar() == 'E')
1288 {
1289 // A string the describes what failed when launching...
1290 error_str = response.GetStringRef().substr(1);
1291 }
1292 else
1293 {
1294 error_str.assign ("unknown error occurred launching process");
1295 }
1296 }
1297 else
1298 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001299 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001300 }
1301 return false;
1302}
1303
1304int
Greg Claytonfbb76342013-11-20 21:07:01 +00001305GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001306{
Greg Claytonfbb76342013-11-20 21:07:01 +00001307 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001308 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +00001309 std::vector<const char *> argv;
1310 FileSpec exe_file = launch_info.GetExecutableFile();
1311 std::string exe_path;
1312 const char *arg = NULL;
1313 const Args &launch_args = launch_info.GetArguments();
1314 if (exe_file)
1315 exe_path = exe_file.GetPath();
1316 else
1317 {
1318 arg = launch_args.GetArgumentAtIndex(0);
1319 if (arg)
1320 exe_path = arg;
1321 }
1322 if (!exe_path.empty())
1323 {
1324 argv.push_back(exe_path.c_str());
1325 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1326 {
1327 if (arg)
1328 argv.push_back(arg);
1329 }
1330 }
1331 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001332 {
1333 StreamString packet;
1334 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001335 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001336 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001337 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001338 const int arg_len = strlen(arg);
1339 if (i > 0)
1340 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001341 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001342 packet.PutBytesAsRawHex8 (arg, arg_len);
1343 }
1344
1345 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001346 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001347 {
1348 if (response.IsOKResponse())
1349 return 0;
1350 uint8_t error = response.GetError();
1351 if (error)
1352 return error;
1353 }
1354 }
1355 return -1;
1356}
1357
1358int
1359GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1360{
1361 if (name_equal_value && name_equal_value[0])
1362 {
1363 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001364 bool send_hex_encoding = false;
1365 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001366 {
Greg Clayton89600582013-10-10 17:53:50 +00001367 if (isprint(*p))
1368 {
1369 switch (*p)
1370 {
1371 case '$':
1372 case '#':
1373 send_hex_encoding = true;
1374 break;
1375 default:
1376 break;
1377 }
1378 }
1379 else
1380 {
1381 // We have non printable characters, lets hex encode this...
1382 send_hex_encoding = true;
1383 }
1384 }
1385
1386 StringExtractorGDBRemote response;
1387 if (send_hex_encoding)
1388 {
1389 if (m_supports_QEnvironmentHexEncoded)
1390 {
1391 packet.PutCString("QEnvironmentHexEncoded:");
1392 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001393 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001394 {
1395 if (response.IsOKResponse())
1396 return 0;
1397 uint8_t error = response.GetError();
1398 if (error)
1399 return error;
1400 if (response.IsUnsupportedResponse())
1401 m_supports_QEnvironmentHexEncoded = false;
1402 }
1403 }
1404
1405 }
1406 else if (m_supports_QEnvironment)
1407 {
1408 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +00001409 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001410 {
1411 if (response.IsOKResponse())
1412 return 0;
1413 uint8_t error = response.GetError();
1414 if (error)
1415 return error;
1416 if (response.IsUnsupportedResponse())
1417 m_supports_QEnvironment = false;
1418 }
Greg Clayton576d8832011-03-22 04:00:09 +00001419 }
1420 }
1421 return -1;
1422}
1423
Greg Claytonc4103b32011-05-08 04:53:50 +00001424int
1425GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1426{
1427 if (arch && arch[0])
1428 {
1429 StreamString packet;
1430 packet.Printf("QLaunchArch:%s", arch);
1431 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001432 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001433 {
1434 if (response.IsOKResponse())
1435 return 0;
1436 uint8_t error = response.GetError();
1437 if (error)
1438 return error;
1439 }
1440 }
1441 return -1;
1442}
1443
Jason Molendaa3329782014-03-29 18:54:20 +00001444int
1445GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1446{
1447 if (data && *data != '\0')
1448 {
1449 StreamString packet;
1450 packet.Printf("QSetProcessEvent:%s", data);
1451 StringExtractorGDBRemote response;
1452 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1453 {
1454 if (response.IsOKResponse())
1455 {
1456 if (was_supported)
1457 *was_supported = true;
1458 return 0;
1459 }
1460 else if (response.IsUnsupportedResponse())
1461 {
1462 if (was_supported)
1463 *was_supported = false;
1464 return -1;
1465 }
1466 else
1467 {
1468 uint8_t error = response.GetError();
1469 if (was_supported)
1470 *was_supported = true;
1471 if (error)
1472 return error;
1473 }
1474 }
1475 }
1476 return -1;
1477}
1478
Greg Clayton576d8832011-03-22 04:00:09 +00001479bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001480GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1481 uint32_t &minor,
1482 uint32_t &update)
1483{
1484 if (GetHostInfo ())
1485 {
1486 if (m_os_version_major != UINT32_MAX)
1487 {
1488 major = m_os_version_major;
1489 minor = m_os_version_minor;
1490 update = m_os_version_update;
1491 return true;
1492 }
1493 }
1494 return false;
1495}
1496
1497bool
1498GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1499{
1500 if (GetHostInfo ())
1501 {
1502 if (!m_os_build.empty())
1503 {
1504 s = m_os_build;
1505 return true;
1506 }
1507 }
1508 s.clear();
1509 return false;
1510}
1511
1512
1513bool
1514GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1515{
1516 if (GetHostInfo ())
1517 {
1518 if (!m_os_kernel.empty())
1519 {
1520 s = m_os_kernel;
1521 return true;
1522 }
1523 }
1524 s.clear();
1525 return false;
1526}
1527
1528bool
1529GDBRemoteCommunicationClient::GetHostname (std::string &s)
1530{
1531 if (GetHostInfo ())
1532 {
1533 if (!m_hostname.empty())
1534 {
1535 s = m_hostname;
1536 return true;
1537 }
1538 }
1539 s.clear();
1540 return false;
1541}
1542
1543ArchSpec
1544GDBRemoteCommunicationClient::GetSystemArchitecture ()
1545{
1546 if (GetHostInfo ())
1547 return m_host_arch;
1548 return ArchSpec();
1549}
1550
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001551const lldb_private::ArchSpec &
1552GDBRemoteCommunicationClient::GetProcessArchitecture ()
1553{
1554 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1555 GetCurrentProcessInfo ();
1556 return m_process_arch;
1557}
1558
Jason Molendaa3329782014-03-29 18:54:20 +00001559bool
1560GDBRemoteCommunicationClient::GetGDBServerVersion()
1561{
1562 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1563 {
1564 m_gdb_server_name.clear();
1565 m_gdb_server_version = 0;
1566 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1567
1568 StringExtractorGDBRemote response;
1569 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1570 {
1571 if (response.IsNormalResponse())
1572 {
1573 std::string name;
1574 std::string value;
1575 bool success = false;
1576 while (response.GetNameColonValue(name, value))
1577 {
1578 if (name.compare("name") == 0)
1579 {
1580 success = true;
1581 m_gdb_server_name.swap(value);
1582 }
1583 else if (name.compare("version") == 0)
1584 {
1585 size_t dot_pos = value.find('.');
1586 if (dot_pos != std::string::npos)
1587 value[dot_pos] = '\0';
Vince Harron5275aaa2015-01-15 20:08:35 +00001588 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molendaa3329782014-03-29 18:54:20 +00001589 if (version != UINT32_MAX)
1590 {
1591 success = true;
1592 m_gdb_server_version = version;
1593 }
1594 }
1595 }
1596 if (success)
1597 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1598 }
1599 }
1600 }
1601 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1602}
1603
1604const char *
1605GDBRemoteCommunicationClient::GetGDBServerProgramName()
1606{
1607 if (GetGDBServerVersion())
1608 {
1609 if (!m_gdb_server_name.empty())
1610 return m_gdb_server_name.c_str();
1611 }
1612 return NULL;
1613}
1614
1615uint32_t
1616GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1617{
1618 if (GetGDBServerVersion())
1619 return m_gdb_server_version;
1620 return 0;
1621}
Greg Clayton1cb64962011-03-24 04:28:38 +00001622
1623bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001624GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001625{
Todd Fialaaf245d12014-06-30 21:05:18 +00001626 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1627
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001628 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001629 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001630 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001631 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001632 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001633 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001634 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001635 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001636 std::string name;
1637 std::string value;
1638 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1639 uint32_t sub = 0;
1640 std::string arch_name;
1641 std::string os_name;
1642 std::string vendor_name;
1643 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001644 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001645 uint32_t pointer_byte_size = 0;
1646 StringExtractor extractor;
1647 ByteOrder byte_order = eByteOrderInvalid;
1648 uint32_t num_keys_decoded = 0;
1649 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001650 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001651 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001652 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001653 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001654 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001655 if (cpu != LLDB_INVALID_CPUTYPE)
1656 ++num_keys_decoded;
1657 }
1658 else if (name.compare("cpusubtype") == 0)
1659 {
1660 // exception count in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001661 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001662 if (sub != 0)
1663 ++num_keys_decoded;
1664 }
1665 else if (name.compare("arch") == 0)
1666 {
1667 arch_name.swap (value);
1668 ++num_keys_decoded;
1669 }
1670 else if (name.compare("triple") == 0)
1671 {
Greg Clayton44272a42014-09-18 00:18:32 +00001672 extractor.GetStringRef ().swap (value);
1673 extractor.SetFilePos(0);
1674 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00001675 ++num_keys_decoded;
1676 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001677 else if (name.compare ("distribution_id") == 0)
1678 {
1679 extractor.GetStringRef ().swap (value);
1680 extractor.SetFilePos (0);
1681 extractor.GetHexByteString (distribution_id);
1682 ++num_keys_decoded;
1683 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001684 else if (name.compare("os_build") == 0)
1685 {
1686 extractor.GetStringRef().swap(value);
1687 extractor.SetFilePos(0);
1688 extractor.GetHexByteString (m_os_build);
1689 ++num_keys_decoded;
1690 }
1691 else if (name.compare("hostname") == 0)
1692 {
1693 extractor.GetStringRef().swap(value);
1694 extractor.SetFilePos(0);
1695 extractor.GetHexByteString (m_hostname);
1696 ++num_keys_decoded;
1697 }
1698 else if (name.compare("os_kernel") == 0)
1699 {
1700 extractor.GetStringRef().swap(value);
1701 extractor.SetFilePos(0);
1702 extractor.GetHexByteString (m_os_kernel);
1703 ++num_keys_decoded;
1704 }
1705 else if (name.compare("ostype") == 0)
1706 {
1707 os_name.swap (value);
1708 ++num_keys_decoded;
1709 }
1710 else if (name.compare("vendor") == 0)
1711 {
1712 vendor_name.swap(value);
1713 ++num_keys_decoded;
1714 }
1715 else if (name.compare("endian") == 0)
1716 {
1717 ++num_keys_decoded;
1718 if (value.compare("little") == 0)
1719 byte_order = eByteOrderLittle;
1720 else if (value.compare("big") == 0)
1721 byte_order = eByteOrderBig;
1722 else if (value.compare("pdp") == 0)
1723 byte_order = eByteOrderPDP;
1724 else
1725 --num_keys_decoded;
1726 }
1727 else if (name.compare("ptrsize") == 0)
1728 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001729 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001730 if (pointer_byte_size != 0)
1731 ++num_keys_decoded;
1732 }
1733 else if (name.compare("os_version") == 0)
1734 {
1735 Args::StringToVersion (value.c_str(),
1736 m_os_version_major,
1737 m_os_version_minor,
1738 m_os_version_update);
1739 if (m_os_version_major != UINT32_MAX)
1740 ++num_keys_decoded;
1741 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001742 else if (name.compare("watchpoint_exceptions_received") == 0)
1743 {
1744 ++num_keys_decoded;
1745 if (strcmp(value.c_str(),"before") == 0)
1746 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1747 else if (strcmp(value.c_str(),"after") == 0)
1748 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1749 else
1750 --num_keys_decoded;
1751 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001752 else if (name.compare("default_packet_timeout") == 0)
1753 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001754 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001755 if (m_default_packet_timeout > 0)
1756 {
1757 SetPacketTimeout(m_default_packet_timeout);
1758 ++num_keys_decoded;
1759 }
1760 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001761
Greg Clayton32e0a752011-03-30 18:16:51 +00001762 }
1763
1764 if (num_keys_decoded > 0)
1765 m_qHostInfo_is_valid = eLazyBoolYes;
1766
1767 if (triple.empty())
1768 {
1769 if (arch_name.empty())
1770 {
1771 if (cpu != LLDB_INVALID_CPUTYPE)
1772 {
1773 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1774 if (pointer_byte_size)
1775 {
1776 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1777 }
1778 if (byte_order != eByteOrderInvalid)
1779 {
1780 assert (byte_order == m_host_arch.GetByteOrder());
1781 }
Greg Clayton70512312012-05-08 01:45:38 +00001782
1783 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1784 {
1785 switch (m_host_arch.GetMachine())
1786 {
Todd Fialad8eaa172014-07-23 14:37:35 +00001787 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00001788 case llvm::Triple::arm:
1789 case llvm::Triple::thumb:
1790 os_name = "ios";
1791 break;
1792 default:
1793 os_name = "macosx";
1794 break;
1795 }
1796 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001797 if (!vendor_name.empty())
1798 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1799 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001800 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001801
1802 }
1803 }
1804 else
1805 {
1806 std::string triple;
1807 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001808 if (!vendor_name.empty() || !os_name.empty())
1809 {
1810 triple += '-';
1811 if (vendor_name.empty())
1812 triple += "unknown";
1813 else
1814 triple += vendor_name;
1815 triple += '-';
1816 if (os_name.empty())
1817 triple += "unknown";
1818 else
1819 triple += os_name;
1820 }
1821 m_host_arch.SetTriple (triple.c_str());
1822
1823 llvm::Triple &host_triple = m_host_arch.GetTriple();
1824 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1825 {
1826 switch (m_host_arch.GetMachine())
1827 {
Todd Fialad8eaa172014-07-23 14:37:35 +00001828 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00001829 case llvm::Triple::arm:
1830 case llvm::Triple::thumb:
1831 host_triple.setOS(llvm::Triple::IOS);
1832 break;
1833 default:
1834 host_triple.setOS(llvm::Triple::MacOSX);
1835 break;
1836 }
1837 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001838 if (pointer_byte_size)
1839 {
1840 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1841 }
1842 if (byte_order != eByteOrderInvalid)
1843 {
1844 assert (byte_order == m_host_arch.GetByteOrder());
1845 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001846
Greg Clayton1cb64962011-03-24 04:28:38 +00001847 }
1848 }
1849 else
1850 {
Greg Clayton70512312012-05-08 01:45:38 +00001851 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001852 if (pointer_byte_size)
1853 {
1854 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1855 }
1856 if (byte_order != eByteOrderInvalid)
1857 {
1858 assert (byte_order == m_host_arch.GetByteOrder());
1859 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001860
1861 if (log)
1862 log->Printf ("GDBRemoteCommunicationClient::%s parsed host architecture as %s, triple as %s from triple text %s", __FUNCTION__, m_host_arch.GetArchitectureName () ? m_host_arch.GetArchitectureName () : "<null-arch-name>", m_host_arch.GetTriple ().getTriple ().c_str(), triple.c_str ());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001863 }
1864 if (!distribution_id.empty ())
1865 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00001866 }
Greg Clayton576d8832011-03-22 04:00:09 +00001867 }
1868 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001869 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001870}
1871
1872int
1873GDBRemoteCommunicationClient::SendAttach
1874(
1875 lldb::pid_t pid,
1876 StringExtractorGDBRemote& response
1877)
1878{
1879 if (pid != LLDB_INVALID_PROCESS_ID)
1880 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001881 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001882 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001883 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00001884 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001885 {
1886 if (response.IsErrorResponse())
1887 return response.GetError();
1888 return 0;
1889 }
1890 }
1891 return -1;
1892}
1893
Vince Harrone0be4252015-02-06 18:32:57 +00001894int
1895GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
1896{
1897 StreamString packet;
1898 packet.PutCString("I");
1899 packet.PutBytesAsRawHex8(data, data_len);
1900 StringExtractorGDBRemote response;
1901 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1902 {
1903 return 0;
1904 }
1905 return response.GetError();
1906
1907}
1908
Greg Clayton576d8832011-03-22 04:00:09 +00001909const lldb_private::ArchSpec &
1910GDBRemoteCommunicationClient::GetHostArchitecture ()
1911{
Greg Clayton32e0a752011-03-30 18:16:51 +00001912 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001913 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001914 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001915}
1916
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001917uint32_t
1918GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1919{
1920 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1921 GetHostInfo ();
1922 return m_default_packet_timeout;
1923}
1924
Greg Clayton576d8832011-03-22 04:00:09 +00001925addr_t
1926GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1927{
Greg Clayton70b57652011-05-15 01:25:55 +00001928 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001929 {
Greg Clayton70b57652011-05-15 01:25:55 +00001930 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001931 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001932 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001933 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001934 permissions & lldb::ePermissionsReadable ? "r" : "",
1935 permissions & lldb::ePermissionsWritable ? "w" : "",
1936 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001937 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001938 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001939 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001940 {
Todd Fialaf105f582014-06-21 00:48:09 +00001941 if (response.IsUnsupportedResponse())
1942 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1943 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001944 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1945 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001946 else
1947 {
1948 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1949 }
Greg Clayton576d8832011-03-22 04:00:09 +00001950 }
1951 return LLDB_INVALID_ADDRESS;
1952}
1953
1954bool
1955GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1956{
Greg Clayton70b57652011-05-15 01:25:55 +00001957 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001958 {
Greg Clayton70b57652011-05-15 01:25:55 +00001959 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001960 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001961 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001962 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001963 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001964 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001965 {
Todd Fialaf105f582014-06-21 00:48:09 +00001966 if (response.IsUnsupportedResponse())
1967 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1968 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001969 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001970 }
1971 else
1972 {
1973 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00001974 }
Greg Clayton576d8832011-03-22 04:00:09 +00001975 }
1976 return false;
1977}
1978
Jim Inghamacff8952013-05-02 00:27:30 +00001979Error
1980GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00001981{
Jim Inghamacff8952013-05-02 00:27:30 +00001982 Error error;
1983
1984 if (keep_stopped)
1985 {
1986 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1987 {
1988 char packet[64];
1989 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001990 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00001991 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001992 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00001993 {
1994 m_supports_detach_stay_stopped = eLazyBoolYes;
1995 }
1996 else
1997 {
1998 m_supports_detach_stay_stopped = eLazyBoolNo;
1999 }
2000 }
2001
2002 if (m_supports_detach_stay_stopped == eLazyBoolNo)
2003 {
2004 error.SetErrorString("Stays stopped not supported by this target.");
2005 return error;
2006 }
2007 else
2008 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002009 StringExtractorGDBRemote response;
2010 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002011 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002012 error.SetErrorString ("Sending extended disconnect packet failed.");
2013 }
2014 }
2015 else
2016 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002017 StringExtractorGDBRemote response;
2018 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002019 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002020 error.SetErrorString ("Sending disconnect packet failed.");
2021 }
2022 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00002023}
2024
Greg Clayton46fb5582011-11-18 07:03:08 +00002025Error
2026GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2027 lldb_private::MemoryRegionInfo &region_info)
2028{
2029 Error error;
2030 region_info.Clear();
2031
2032 if (m_supports_memory_region_info != eLazyBoolNo)
2033 {
2034 m_supports_memory_region_info = eLazyBoolYes;
2035 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002036 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002037 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00002038 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002039 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00002040 {
2041 std::string name;
2042 std::string value;
2043 addr_t addr_value;
2044 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00002045 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00002046 while (success && response.GetNameColonValue(name, value))
2047 {
2048 if (name.compare ("start") == 0)
2049 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002050 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002051 if (success)
2052 region_info.GetRange().SetRangeBase(addr_value);
2053 }
2054 else if (name.compare ("size") == 0)
2055 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002056 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002057 if (success)
2058 region_info.GetRange().SetByteSize (addr_value);
2059 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002060 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00002061 {
Jason Molendacb349ee2011-12-13 05:39:38 +00002062 saw_permissions = true;
2063 if (region_info.GetRange().Contains (addr))
2064 {
2065 if (value.find('r') != std::string::npos)
2066 region_info.SetReadable (MemoryRegionInfo::eYes);
2067 else
2068 region_info.SetReadable (MemoryRegionInfo::eNo);
2069
2070 if (value.find('w') != std::string::npos)
2071 region_info.SetWritable (MemoryRegionInfo::eYes);
2072 else
2073 region_info.SetWritable (MemoryRegionInfo::eNo);
2074
2075 if (value.find('x') != std::string::npos)
2076 region_info.SetExecutable (MemoryRegionInfo::eYes);
2077 else
2078 region_info.SetExecutable (MemoryRegionInfo::eNo);
2079 }
2080 else
2081 {
2082 // The reported region does not contain this address -- we're looking at an unmapped page
2083 region_info.SetReadable (MemoryRegionInfo::eNo);
2084 region_info.SetWritable (MemoryRegionInfo::eNo);
2085 region_info.SetExecutable (MemoryRegionInfo::eNo);
2086 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002087 }
2088 else if (name.compare ("error") == 0)
2089 {
2090 StringExtractorGDBRemote name_extractor;
2091 // Swap "value" over into "name_extractor"
2092 name_extractor.GetStringRef().swap(value);
2093 // Now convert the HEX bytes into a string value
2094 name_extractor.GetHexByteString (value);
2095 error.SetErrorString(value.c_str());
2096 }
2097 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002098
2099 // We got a valid address range back but no permissions -- which means this is an unmapped page
2100 if (region_info.GetRange().IsValid() && saw_permissions == false)
2101 {
2102 region_info.SetReadable (MemoryRegionInfo::eNo);
2103 region_info.SetWritable (MemoryRegionInfo::eNo);
2104 region_info.SetExecutable (MemoryRegionInfo::eNo);
2105 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002106 }
2107 else
2108 {
2109 m_supports_memory_region_info = eLazyBoolNo;
2110 }
2111 }
2112
2113 if (m_supports_memory_region_info == eLazyBoolNo)
2114 {
2115 error.SetErrorString("qMemoryRegionInfo is not supported");
2116 }
2117 if (error.Fail())
2118 region_info.Clear();
2119 return error;
2120
2121}
2122
Johnny Chen64637202012-05-23 21:09:52 +00002123Error
2124GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2125{
2126 Error error;
2127
2128 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2129 {
2130 num = m_num_supported_hardware_watchpoints;
2131 return error;
2132 }
2133
2134 // Set num to 0 first.
2135 num = 0;
2136 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2137 {
2138 char packet[64];
2139 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002140 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00002141 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002142 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00002143 {
2144 m_supports_watchpoint_support_info = eLazyBoolYes;
2145 std::string name;
2146 std::string value;
2147 while (response.GetNameColonValue(name, value))
2148 {
2149 if (name.compare ("num") == 0)
2150 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002151 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
Johnny Chen64637202012-05-23 21:09:52 +00002152 m_num_supported_hardware_watchpoints = num;
2153 }
2154 }
2155 }
2156 else
2157 {
2158 m_supports_watchpoint_support_info = eLazyBoolNo;
2159 }
2160 }
2161
2162 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2163 {
2164 error.SetErrorString("qWatchpointSupportInfo is not supported");
2165 }
2166 return error;
2167
2168}
Greg Clayton46fb5582011-11-18 07:03:08 +00002169
Enrico Granataf04a2192012-07-13 23:18:48 +00002170lldb_private::Error
2171GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2172{
2173 Error error(GetWatchpointSupportInfo(num));
2174 if (error.Success())
2175 error = GetWatchpointsTriggerAfterInstruction(after);
2176 return error;
2177}
2178
2179lldb_private::Error
2180GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
2181{
2182 Error error;
2183
2184 // we assume watchpoints will happen after running the relevant opcode
2185 // and we only want to override this behavior if we have explicitly
2186 // received a qHostInfo telling us otherwise
2187 if (m_qHostInfo_is_valid != eLazyBoolYes)
2188 after = true;
2189 else
2190 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
2191 return error;
2192}
2193
Greg Clayton576d8832011-03-22 04:00:09 +00002194int
2195GDBRemoteCommunicationClient::SetSTDIN (char const *path)
2196{
2197 if (path && path[0])
2198 {
2199 StreamString packet;
2200 packet.PutCString("QSetSTDIN:");
2201 packet.PutBytesAsRawHex8(path, strlen(path));
2202
2203 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002204 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002205 {
2206 if (response.IsOKResponse())
2207 return 0;
2208 uint8_t error = response.GetError();
2209 if (error)
2210 return error;
2211 }
2212 }
2213 return -1;
2214}
2215
2216int
2217GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
2218{
2219 if (path && path[0])
2220 {
2221 StreamString packet;
2222 packet.PutCString("QSetSTDOUT:");
2223 packet.PutBytesAsRawHex8(path, strlen(path));
2224
2225 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002226 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002227 {
2228 if (response.IsOKResponse())
2229 return 0;
2230 uint8_t error = response.GetError();
2231 if (error)
2232 return error;
2233 }
2234 }
2235 return -1;
2236}
2237
2238int
2239GDBRemoteCommunicationClient::SetSTDERR (char const *path)
2240{
2241 if (path && path[0])
2242 {
2243 StreamString packet;
2244 packet.PutCString("QSetSTDERR:");
2245 packet.PutBytesAsRawHex8(path, strlen(path));
2246
2247 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002248 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002249 {
2250 if (response.IsOKResponse())
2251 return 0;
2252 uint8_t error = response.GetError();
2253 if (error)
2254 return error;
2255 }
2256 }
2257 return -1;
2258}
2259
Greg Claytonfbb76342013-11-20 21:07:01 +00002260bool
2261GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd)
2262{
2263 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002264 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002265 {
2266 if (response.IsUnsupportedResponse())
2267 return false;
2268 if (response.IsErrorResponse())
2269 return false;
2270 response.GetHexByteString (cwd);
2271 return !cwd.empty();
2272 }
2273 return false;
2274}
2275
Greg Clayton576d8832011-03-22 04:00:09 +00002276int
2277GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
2278{
2279 if (path && path[0])
2280 {
2281 StreamString packet;
2282 packet.PutCString("QSetWorkingDir:");
2283 packet.PutBytesAsRawHex8(path, strlen(path));
2284
2285 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002286 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002287 {
2288 if (response.IsOKResponse())
2289 return 0;
2290 uint8_t error = response.GetError();
2291 if (error)
2292 return error;
2293 }
2294 }
2295 return -1;
2296}
2297
2298int
2299GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2300{
Greg Clayton32e0a752011-03-30 18:16:51 +00002301 char packet[32];
2302 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002303 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002304 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002305 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002306 {
2307 if (response.IsOKResponse())
2308 return 0;
2309 uint8_t error = response.GetError();
2310 if (error)
2311 return error;
2312 }
2313 return -1;
2314}
Greg Clayton32e0a752011-03-30 18:16:51 +00002315
Jim Ingham106d0282014-06-25 02:32:56 +00002316int
2317GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2318{
2319 char packet[32];
2320 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2321 assert (packet_len < (int)sizeof(packet));
2322 StringExtractorGDBRemote response;
2323 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2324 {
2325 if (response.IsOKResponse())
2326 return 0;
2327 uint8_t error = response.GetError();
2328 if (error)
2329 return error;
2330 }
2331 return -1;
2332}
2333
2334
Greg Clayton32e0a752011-03-30 18:16:51 +00002335bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002336GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002337{
2338 if (response.IsNormalResponse())
2339 {
2340 std::string name;
2341 std::string value;
2342 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002343
2344 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2345 uint32_t sub = 0;
2346 std::string vendor;
2347 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002348
2349 while (response.GetNameColonValue(name, value))
2350 {
2351 if (name.compare("pid") == 0)
2352 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002353 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002354 }
2355 else if (name.compare("ppid") == 0)
2356 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002357 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002358 }
2359 else if (name.compare("uid") == 0)
2360 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002361 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002362 }
2363 else if (name.compare("euid") == 0)
2364 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002365 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002366 }
2367 else if (name.compare("gid") == 0)
2368 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002369 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002370 }
2371 else if (name.compare("egid") == 0)
2372 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002373 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002374 }
2375 else if (name.compare("triple") == 0)
2376 {
Greg Clayton44272a42014-09-18 00:18:32 +00002377 StringExtractor extractor;
2378 extractor.GetStringRef().swap(value);
2379 extractor.SetFilePos(0);
2380 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002381 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002382 }
2383 else if (name.compare("name") == 0)
2384 {
2385 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002386 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002387 // control the characters in a process name
2388 extractor.GetStringRef().swap(value);
2389 extractor.SetFilePos(0);
2390 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002391 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002392 }
Jason Molenda89c37492014-01-27 22:23:20 +00002393 else if (name.compare("cputype") == 0)
2394 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002395 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002396 }
2397 else if (name.compare("cpusubtype") == 0)
2398 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002399 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002400 }
2401 else if (name.compare("vendor") == 0)
2402 {
2403 vendor = value;
2404 }
2405 else if (name.compare("ostype") == 0)
2406 {
2407 os_type = value;
2408 }
2409 }
2410
2411 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2412 {
2413 if (vendor == "apple")
2414 {
2415 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2416 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2417 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2418 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002419 }
2420
2421 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2422 return true;
2423 }
2424 return false;
2425}
2426
2427bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002428GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002429{
2430 process_info.Clear();
2431
2432 if (m_supports_qProcessInfoPID)
2433 {
2434 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002435 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002436 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002437 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002438 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002439 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002440 return DecodeProcessInfoResponse (response, process_info);
2441 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002442 else
2443 {
2444 m_supports_qProcessInfoPID = false;
2445 return false;
2446 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002447 }
2448 return false;
2449}
2450
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002451bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002452GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002453{
Todd Fiala3daa1762014-09-15 16:01:29 +00002454 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2455
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002456 if (allow_lazy)
2457 {
2458 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2459 return true;
2460 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2461 return false;
2462 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002463
2464 GetHostInfo ();
2465
2466 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002467 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002468 {
2469 if (response.IsNormalResponse())
2470 {
2471 std::string name;
2472 std::string value;
2473 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2474 uint32_t sub = 0;
2475 std::string arch_name;
2476 std::string os_name;
2477 std::string vendor_name;
2478 std::string triple;
2479 uint32_t pointer_byte_size = 0;
2480 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002481 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002482 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002483 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002484 while (response.GetNameColonValue(name, value))
2485 {
2486 if (name.compare("cputype") == 0)
2487 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002488 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002489 if (cpu != LLDB_INVALID_CPUTYPE)
2490 ++num_keys_decoded;
2491 }
2492 else if (name.compare("cpusubtype") == 0)
2493 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002494 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002495 if (sub != 0)
2496 ++num_keys_decoded;
2497 }
Todd Fialac540dd02014-08-26 18:21:02 +00002498 else if (name.compare("triple") == 0)
2499 {
Greg Clayton44272a42014-09-18 00:18:32 +00002500 StringExtractor extractor;
2501 extractor.GetStringRef().swap(value);
2502 extractor.SetFilePos(0);
2503 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002504 ++num_keys_decoded;
2505 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002506 else if (name.compare("ostype") == 0)
2507 {
2508 os_name.swap (value);
2509 ++num_keys_decoded;
2510 }
2511 else if (name.compare("vendor") == 0)
2512 {
2513 vendor_name.swap(value);
2514 ++num_keys_decoded;
2515 }
2516 else if (name.compare("endian") == 0)
2517 {
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002518 ++num_keys_decoded;
2519 if (value.compare("little") == 0)
2520 byte_order = eByteOrderLittle;
2521 else if (value.compare("big") == 0)
2522 byte_order = eByteOrderBig;
2523 else if (value.compare("pdp") == 0)
2524 byte_order = eByteOrderPDP;
2525 else
2526 --num_keys_decoded;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002527 }
2528 else if (name.compare("ptrsize") == 0)
2529 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002530 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002531 if (pointer_byte_size != 0)
2532 ++num_keys_decoded;
2533 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002534 else if (name.compare("pid") == 0)
2535 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002536 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002537 if (pid != LLDB_INVALID_PROCESS_ID)
2538 ++num_keys_decoded;
2539 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002540 }
2541 if (num_keys_decoded > 0)
2542 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002543 if (pid != LLDB_INVALID_PROCESS_ID)
2544 {
2545 m_curr_pid_is_valid = eLazyBoolYes;
2546 m_curr_pid = pid;
2547 }
Todd Fialac540dd02014-08-26 18:21:02 +00002548
2549 // Set the ArchSpec from the triple if we have it.
2550 if (!triple.empty ())
2551 {
2552 m_process_arch.SetTriple (triple.c_str ());
2553 if (pointer_byte_size)
2554 {
2555 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2556 }
2557 }
2558 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002559 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002560 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2561
2562 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2563 switch (triple.getObjectFormat()) {
2564 case llvm::Triple::MachO:
2565 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2566 break;
2567 case llvm::Triple::ELF:
2568 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2569 break;
2570 case llvm::Triple::COFF:
2571 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2572 break;
2573 case llvm::Triple::UnknownObjectFormat:
2574 if (log)
2575 log->Printf("error: failed to determine target architecture");
2576 return false;
2577 }
2578
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002579 if (pointer_byte_size)
2580 {
2581 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2582 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002583 if (byte_order != eByteOrderInvalid)
2584 {
2585 assert (byte_order == m_process_arch.GetByteOrder());
2586 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002587 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002588 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002589 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2590 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002591 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002592 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002593 }
2594 }
2595 else
2596 {
2597 m_qProcessInfo_is_valid = eLazyBoolNo;
2598 }
2599
2600 return false;
2601}
2602
2603
Greg Clayton32e0a752011-03-30 18:16:51 +00002604uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002605GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2606 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002607{
2608 process_infos.Clear();
2609
2610 if (m_supports_qfProcessInfo)
2611 {
2612 StreamString packet;
2613 packet.PutCString ("qfProcessInfo");
2614 if (!match_info.MatchAllProcesses())
2615 {
2616 packet.PutChar (':');
2617 const char *name = match_info.GetProcessInfo().GetName();
2618 bool has_name_match = false;
2619 if (name && name[0])
2620 {
2621 has_name_match = true;
2622 NameMatchType name_match_type = match_info.GetNameMatchType();
2623 switch (name_match_type)
2624 {
2625 case eNameMatchIgnore:
2626 has_name_match = false;
2627 break;
2628
2629 case eNameMatchEquals:
2630 packet.PutCString ("name_match:equals;");
2631 break;
2632
2633 case eNameMatchContains:
2634 packet.PutCString ("name_match:contains;");
2635 break;
2636
2637 case eNameMatchStartsWith:
2638 packet.PutCString ("name_match:starts_with;");
2639 break;
2640
2641 case eNameMatchEndsWith:
2642 packet.PutCString ("name_match:ends_with;");
2643 break;
2644
2645 case eNameMatchRegularExpression:
2646 packet.PutCString ("name_match:regex;");
2647 break;
2648 }
2649 if (has_name_match)
2650 {
2651 packet.PutCString ("name:");
2652 packet.PutBytesAsRawHex8(name, ::strlen(name));
2653 packet.PutChar (';');
2654 }
2655 }
2656
2657 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002658 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002659 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002660 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002661 if (match_info.GetProcessInfo().UserIDIsValid())
2662 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2663 if (match_info.GetProcessInfo().GroupIDIsValid())
2664 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002665 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2666 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2667 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2668 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2669 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2670 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2671 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2672 {
2673 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2674 const llvm::Triple &triple = match_arch.GetTriple();
2675 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00002676 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002677 packet.PutChar (';');
2678 }
2679 }
2680 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002681 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002682 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002683 do
2684 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002685 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002686 if (!DecodeProcessInfoResponse (response, process_info))
2687 break;
2688 process_infos.Append(process_info);
2689 response.GetStringRef().clear();
2690 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00002691 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00002692 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002693 else
2694 {
2695 m_supports_qfProcessInfo = false;
2696 return 0;
2697 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002698 }
2699 return process_infos.GetSize();
2700
2701}
2702
2703bool
2704GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2705{
2706 if (m_supports_qUserName)
2707 {
2708 char packet[32];
2709 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002710 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002711 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002712 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002713 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002714 if (response.IsNormalResponse())
2715 {
2716 // Make sure we parsed the right number of characters. The response is
2717 // the hex encoded user name and should make up the entire packet.
2718 // If there are any non-hex ASCII bytes, the length won't match below..
2719 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2720 return true;
2721 }
2722 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002723 else
2724 {
2725 m_supports_qUserName = false;
2726 return false;
2727 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002728 }
2729 return false;
2730
2731}
2732
2733bool
2734GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2735{
2736 if (m_supports_qGroupName)
2737 {
2738 char packet[32];
2739 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002740 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002741 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002742 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002743 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002744 if (response.IsNormalResponse())
2745 {
2746 // Make sure we parsed the right number of characters. The response is
2747 // the hex encoded group name and should make up the entire packet.
2748 // If there are any non-hex ASCII bytes, the length won't match below..
2749 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2750 return true;
2751 }
2752 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002753 else
2754 {
2755 m_supports_qGroupName = false;
2756 return false;
2757 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002758 }
2759 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002760}
Greg Clayton32e0a752011-03-30 18:16:51 +00002761
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002762void
2763GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2764{
2765 uint32_t i;
2766 TimeValue start_time, end_time;
2767 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002768 if (SendSpeedTestPacket (0, 0))
2769 {
Greg Clayton700e5082014-02-21 19:11:28 +00002770 static uint32_t g_send_sizes[] = { 0, 64, 128, 512, 1024 };
2771 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 };
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002772 const size_t k_num_send_sizes = llvm::array_lengthof(g_send_sizes);
2773 const size_t k_num_recv_sizes = llvm::array_lengthof(g_recv_sizes);
Greg Clayton700e5082014-02-21 19:11:28 +00002774 const uint64_t k_recv_amount = 4*1024*1024; // Receive 4MB
2775 for (uint32_t send_idx = 0; send_idx < k_num_send_sizes; ++send_idx)
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002776 {
Greg Clayton700e5082014-02-21 19:11:28 +00002777 const uint32_t send_size = g_send_sizes[send_idx];
2778 for (uint32_t recv_idx = 0; recv_idx < k_num_recv_sizes; ++recv_idx)
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002779 {
Greg Clayton700e5082014-02-21 19:11:28 +00002780 const uint32_t recv_size = g_recv_sizes[recv_idx];
2781 StreamString packet;
2782 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2783 uint32_t bytes_left = send_size;
2784 while (bytes_left > 0)
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002785 {
Greg Clayton700e5082014-02-21 19:11:28 +00002786 if (bytes_left >= 26)
2787 {
2788 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2789 bytes_left -= 26;
2790 }
2791 else
2792 {
2793 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2794 bytes_left = 0;
2795 }
2796 }
2797
2798 start_time = TimeValue::Now();
2799 if (recv_size == 0)
2800 {
2801 for (i=0; i<num_packets; ++i)
2802 {
2803 StringExtractorGDBRemote response;
2804 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2805 }
2806 }
2807 else
2808 {
2809 uint32_t bytes_read = 0;
2810 while (bytes_read < k_recv_amount)
2811 {
2812 StringExtractorGDBRemote response;
2813 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2814 bytes_read += recv_size;
2815 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002816 }
2817 end_time = TimeValue::Now();
2818 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002819 if (recv_size == 0)
Greg Clayton700e5082014-02-21 19:11:28 +00002820 {
2821 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2822 printf ("%u qSpeedTest(send=%-7u, recv=%-7u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
2823 num_packets,
2824 send_size,
2825 recv_size,
2826 total_time_nsec / TimeValue::NanoSecPerSec,
2827 total_time_nsec % TimeValue::NanoSecPerSec,
2828 packets_per_second);
2829 }
2830 else
2831 {
2832 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2833 printf ("%u qSpeedTest(send=%-7u, recv=%-7u) sent 4MB in %" PRIu64 ".%9.9" PRIu64 " sec for %f MB/sec.\n",
2834 num_packets,
2835 send_size,
2836 recv_size,
2837 total_time_nsec / TimeValue::NanoSecPerSec,
2838 total_time_nsec % TimeValue::NanoSecPerSec,
2839 mb_second);
2840 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002841 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002842 }
2843 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002844}
2845
2846bool
2847GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2848{
2849 StreamString packet;
2850 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2851 uint32_t bytes_left = send_size;
2852 while (bytes_left > 0)
2853 {
2854 if (bytes_left >= 26)
2855 {
2856 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2857 bytes_left -= 26;
2858 }
2859 else
2860 {
2861 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2862 bytes_left = 0;
2863 }
2864 }
2865
2866 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002867 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00002868}
Greg Clayton8b82f082011-04-12 05:54:46 +00002869
2870uint16_t
Greg Claytondbf04572013-12-04 19:40:33 +00002871GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
Greg Clayton8b82f082011-04-12 05:54:46 +00002872{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002873 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00002874 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002875 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00002876 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002877 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00002878 if (remote_accept_hostname && remote_accept_hostname[0])
2879 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002880 else
2881 {
Zachary Turner97a14e62014-08-19 17:18:29 +00002882 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00002883 {
2884 // Make the GDB server we launch only accept connections from this host
2885 stream.Printf("host:%s;", hostname.c_str());
2886 }
2887 else
2888 {
2889 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2890 stream.Printf("host:*;");
2891 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002892 }
2893 const char *packet = stream.GetData();
2894 int packet_len = stream.GetSize();
2895
Vince Harron1b5a74e2015-01-21 22:42:49 +00002896 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00002897 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
2898
2899 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002900 {
2901 std::string name;
2902 std::string value;
2903 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002904 while (response.GetNameColonValue(name, value))
2905 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00002906 if (name.compare("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00002907 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002908 else if (name.compare("pid") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00002909 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00002910 }
2911 return port;
2912 }
2913 return 0;
2914}
2915
2916bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00002917GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2918{
2919 StreamString stream;
2920 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2921 const char *packet = stream.GetData();
2922 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00002923
Daniel Maleae0f8f572013-08-26 23:57:52 +00002924 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002925 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002926 {
2927 if (response.IsOKResponse())
2928 return true;
2929 }
2930 return false;
2931}
2932
2933bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002934GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002935{
2936 if (m_curr_tid == tid)
2937 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002938
Greg Clayton8b82f082011-04-12 05:54:46 +00002939 char packet[32];
2940 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002941 if (tid == UINT64_MAX)
2942 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002943 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002944 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002945 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002946 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002947 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002948 {
2949 if (response.IsOKResponse())
2950 {
2951 m_curr_tid = tid;
2952 return true;
2953 }
2954 }
2955 return false;
2956}
2957
2958bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002959GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002960{
2961 if (m_curr_tid_run == tid)
2962 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002963
Greg Clayton8b82f082011-04-12 05:54:46 +00002964 char packet[32];
2965 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002966 if (tid == UINT64_MAX)
2967 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002968 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002969 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2970
Andy Gibbsa297a972013-06-19 19:04:53 +00002971 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002972 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002973 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002974 {
2975 if (response.IsOKResponse())
2976 {
2977 m_curr_tid_run = tid;
2978 return true;
2979 }
2980 }
2981 return false;
2982}
2983
2984bool
2985GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2986{
Greg Clayton3dedae12013-12-06 21:45:27 +00002987 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00002988 return response.IsNormalResponse();
2989 return false;
2990}
2991
2992bool
Greg Claytonf402f782012-10-13 02:11:55 +00002993GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00002994{
2995 if (m_supports_qThreadStopInfo)
2996 {
2997 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00002998 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002999 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00003000 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003001 {
Greg Claytonef8180a2013-10-15 00:14:28 +00003002 if (response.IsUnsupportedResponse())
3003 m_supports_qThreadStopInfo = false;
3004 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003005 return true;
3006 else
3007 return false;
3008 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003009 else
3010 {
3011 m_supports_qThreadStopInfo = false;
3012 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003013 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003014 return false;
3015}
3016
3017
3018uint8_t
3019GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
3020{
Todd Fiala616b8272014-10-09 00:55:04 +00003021 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3022 if (log)
3023 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3024 __FUNCTION__, insert ? "add" : "remove", addr);
3025
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003026 // Check if the stub is known not to support this breakpoint type
3027 if (!SupportsGDBStoppointPacket(type))
3028 return UINT8_MAX;
3029 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00003030 char packet[64];
3031 const int packet_len = ::snprintf (packet,
3032 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00003033 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00003034 insert ? 'Z' : 'z',
3035 type,
3036 addr,
3037 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003038 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00003039 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003040 StringExtractorGDBRemote response;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003041 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00003042 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003043 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003044 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00003045 if (response.IsOKResponse())
3046 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003047
3048 // Error while setting breakpoint, send back specific error
3049 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003050 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003051
3052 // Empty packet informs us that breakpoint is not supported
3053 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00003054 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003055 // Disable this breakpoint type since it is unsupported
3056 switch (type)
3057 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00003058 case eBreakpointSoftware: m_supports_z0 = false; break;
3059 case eBreakpointHardware: m_supports_z1 = false; break;
3060 case eWatchpointWrite: m_supports_z2 = false; break;
3061 case eWatchpointRead: m_supports_z3 = false; break;
3062 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00003063 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003064 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003065 }
3066 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003067 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00003068 return UINT8_MAX;
3069}
Greg Claytonadc00cb2011-05-20 23:38:13 +00003070
3071size_t
3072GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3073 bool &sequence_mutex_unavailable)
3074{
3075 Mutex::Locker locker;
3076 thread_ids.clear();
3077
Jim Ingham4ceb9282012-06-08 22:50:40 +00003078 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003079 {
3080 sequence_mutex_unavailable = false;
3081 StringExtractorGDBRemote response;
3082
Greg Clayton3dedae12013-12-06 21:45:27 +00003083 PacketResult packet_result;
3084 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3085 packet_result == PacketResult::Success && response.IsNormalResponse();
3086 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003087 {
3088 char ch = response.GetChar();
3089 if (ch == 'l')
3090 break;
3091 if (ch == 'm')
3092 {
3093 do
3094 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00003095 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00003096
3097 if (tid != LLDB_INVALID_THREAD_ID)
3098 {
3099 thread_ids.push_back (tid);
3100 }
3101 ch = response.GetChar(); // Skip the command separator
3102 } while (ch == ','); // Make sure we got a comma separator
3103 }
3104 }
3105 }
3106 else
3107 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00003108#if defined (LLDB_CONFIGURATION_DEBUG)
3109 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3110#else
Greg Clayton5160ce52013-03-27 23:08:40 +00003111 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00003112 if (log)
3113 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00003114#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00003115 sequence_mutex_unavailable = true;
3116 }
3117 return thread_ids.size();
3118}
Greg Clayton37a0a242012-04-11 00:24:49 +00003119
3120lldb::addr_t
3121GDBRemoteCommunicationClient::GetShlibInfoAddr()
3122{
3123 if (!IsRunning())
3124 {
3125 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003126 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00003127 {
3128 if (response.IsNormalResponse())
3129 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3130 }
3131 }
3132 return LLDB_INVALID_ADDRESS;
3133}
3134
Daniel Maleae0f8f572013-08-26 23:57:52 +00003135lldb_private::Error
3136GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL
3137 const char *working_dir, // Pass NULL to use the current working directory
3138 int *status_ptr, // Pass NULL if you don't want the process exit status
3139 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3140 std::string *command_output, // Pass NULL if you don't want the command output
3141 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
3142{
3143 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003144 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003145 stream.PutBytesAsRawHex8(command, strlen(command));
3146 stream.PutChar(',');
3147 stream.PutHex32(timeout_sec);
3148 if (working_dir && *working_dir)
3149 {
3150 stream.PutChar(',');
3151 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
3152 }
3153 const char *packet = stream.GetData();
3154 int packet_len = stream.GetSize();
3155 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003156 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003157 {
3158 if (response.GetChar() != 'F')
3159 return Error("malformed reply");
3160 if (response.GetChar() != ',')
3161 return Error("malformed reply");
3162 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3163 if (exitcode == UINT32_MAX)
3164 return Error("unable to run remote process");
3165 else if (status_ptr)
3166 *status_ptr = exitcode;
3167 if (response.GetChar() != ',')
3168 return Error("malformed reply");
3169 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3170 if (signo_ptr)
3171 *signo_ptr = signo;
3172 if (response.GetChar() != ',')
3173 return Error("malformed reply");
3174 std::string output;
3175 response.GetEscapedBinaryData(output);
3176 if (command_output)
3177 command_output->assign(output);
3178 return Error();
3179 }
3180 return Error("unable to send packet");
3181}
3182
Greg Claytonfbb76342013-11-20 21:07:01 +00003183Error
3184GDBRemoteCommunicationClient::MakeDirectory (const char *path,
3185 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003186{
3187 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003188 stream.PutCString("qPlatform_mkdir:");
3189 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003190 stream.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00003191 stream.PutBytesAsRawHex8(path, strlen(path));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003192 const char *packet = stream.GetData();
3193 int packet_len = stream.GetSize();
3194 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003195
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003196 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3197 return Error("failed to send '%s' packet", packet);
3198
3199 if (response.GetChar() != 'F')
3200 return Error("invalid response to '%s' packet", packet);
3201
3202 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003203}
3204
Greg Claytonfbb76342013-11-20 21:07:01 +00003205Error
3206GDBRemoteCommunicationClient::SetFilePermissions (const char *path,
3207 uint32_t file_permissions)
3208{
3209 lldb_private::StreamString stream;
3210 stream.PutCString("qPlatform_chmod:");
3211 stream.PutHex32(file_permissions);
3212 stream.PutChar(',');
3213 stream.PutBytesAsRawHex8(path, strlen(path));
3214 const char *packet = stream.GetData();
3215 int packet_len = stream.GetSize();
3216 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003217
3218 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3219 return Error("failed to send '%s' packet", packet);
3220
3221 if (response.GetChar() != 'F')
3222 return Error("invalid response to '%s' packet", packet);
3223
3224 return Error(response.GetU32(false, UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003225}
3226
Daniel Maleae0f8f572013-08-26 23:57:52 +00003227static uint64_t
3228ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3229 uint64_t fail_result,
3230 Error &error)
3231{
3232 response.SetFilePos(0);
3233 if (response.GetChar() != 'F')
3234 return fail_result;
3235 int32_t result = response.GetS32 (-2);
3236 if (result == -2)
3237 return fail_result;
3238 if (response.GetChar() == ',')
3239 {
3240 int result_errno = response.GetS32 (-2);
3241 if (result_errno != -2)
3242 error.SetError(result_errno, eErrorTypePOSIX);
3243 else
3244 error.SetError(-1, eErrorTypeGeneric);
3245 }
3246 else
3247 error.Clear();
3248 return result;
3249}
3250lldb::user_id_t
3251GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3252 uint32_t flags,
3253 mode_t mode,
3254 Error &error)
3255{
3256 lldb_private::StreamString stream;
3257 stream.PutCString("vFile:open:");
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00003258 std::string path (file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003259 if (path.empty())
3260 return UINT64_MAX;
3261 stream.PutCStringAsRawHex8(path.c_str());
3262 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003263 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003264 stream.PutChar(',');
3265 stream.PutHex32(mode);
3266 const char* packet = stream.GetData();
3267 int packet_len = stream.GetSize();
3268 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003269 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003270 {
3271 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3272 }
3273 return UINT64_MAX;
3274}
3275
3276bool
3277GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3278 Error &error)
3279{
3280 lldb_private::StreamString stream;
3281 stream.Printf("vFile:close:%i", (int)fd);
3282 const char* packet = stream.GetData();
3283 int packet_len = stream.GetSize();
3284 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003285 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003286 {
3287 return ParseHostIOPacketResponse (response, -1, error) == 0;
3288 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003289 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003290}
3291
3292// Extension of host I/O packets to get the file size.
3293lldb::user_id_t
3294GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3295{
3296 lldb_private::StreamString stream;
3297 stream.PutCString("vFile:size:");
3298 std::string path (file_spec.GetPath());
3299 stream.PutCStringAsRawHex8(path.c_str());
3300 const char* packet = stream.GetData();
3301 int packet_len = stream.GetSize();
3302 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003303 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003304 {
3305 if (response.GetChar() != 'F')
3306 return UINT64_MAX;
3307 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3308 return retcode;
3309 }
3310 return UINT64_MAX;
3311}
3312
Greg Claytonfbb76342013-11-20 21:07:01 +00003313Error
3314GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003315{
Greg Claytonfbb76342013-11-20 21:07:01 +00003316 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003317 lldb_private::StreamString stream;
3318 stream.PutCString("vFile:mode:");
Greg Claytonfbb76342013-11-20 21:07:01 +00003319 stream.PutCStringAsRawHex8(path);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003320 const char* packet = stream.GetData();
3321 int packet_len = stream.GetSize();
3322 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003323 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003324 {
3325 if (response.GetChar() != 'F')
3326 {
3327 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003328 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003329 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003330 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003331 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003332 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003333 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003334 if (response.GetChar() == ',')
3335 {
3336 int response_errno = response.GetS32(-1);
3337 if (response_errno > 0)
3338 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3339 else
3340 error.SetErrorToGenericError();
3341 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003342 else
3343 error.SetErrorToGenericError();
3344 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003345 else
3346 {
3347 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3348 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003349 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003350 }
3351 else
3352 {
3353 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3354 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003355 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003356}
3357
3358uint64_t
3359GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3360 uint64_t offset,
3361 void *dst,
3362 uint64_t dst_len,
3363 Error &error)
3364{
3365 lldb_private::StreamString stream;
3366 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3367 const char* packet = stream.GetData();
3368 int packet_len = stream.GetSize();
3369 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003370 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003371 {
3372 if (response.GetChar() != 'F')
3373 return 0;
3374 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3375 if (retcode == UINT32_MAX)
3376 return retcode;
3377 const char next = (response.Peek() ? *response.Peek() : 0);
3378 if (next == ',')
3379 return 0;
3380 if (next == ';')
3381 {
3382 response.GetChar(); // skip the semicolon
3383 std::string buffer;
3384 if (response.GetEscapedBinaryData(buffer))
3385 {
3386 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3387 if (data_to_write > 0)
3388 memcpy(dst, &buffer[0], data_to_write);
3389 return data_to_write;
3390 }
3391 }
3392 }
3393 return 0;
3394}
3395
3396uint64_t
3397GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3398 uint64_t offset,
3399 const void* src,
3400 uint64_t src_len,
3401 Error &error)
3402{
3403 lldb_private::StreamGDBRemote stream;
3404 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3405 stream.PutEscapedBytes(src, src_len);
3406 const char* packet = stream.GetData();
3407 int packet_len = stream.GetSize();
3408 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003409 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003410 {
3411 if (response.GetChar() != 'F')
3412 {
3413 error.SetErrorStringWithFormat("write file failed");
3414 return 0;
3415 }
3416 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3417 if (bytes_written == UINT64_MAX)
3418 {
3419 error.SetErrorToGenericError();
3420 if (response.GetChar() == ',')
3421 {
3422 int response_errno = response.GetS32(-1);
3423 if (response_errno > 0)
3424 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3425 }
3426 return 0;
3427 }
3428 return bytes_written;
3429 }
3430 else
3431 {
3432 error.SetErrorString ("failed to send vFile:pwrite packet");
3433 }
3434 return 0;
3435}
3436
Greg Claytonfbb76342013-11-20 21:07:01 +00003437Error
3438GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst)
3439{
3440 Error error;
3441 lldb_private::StreamGDBRemote stream;
3442 stream.PutCString("vFile:symlink:");
3443 // the unix symlink() command reverses its parameters where the dst if first,
3444 // so we follow suit here
3445 stream.PutCStringAsRawHex8(dst);
3446 stream.PutChar(',');
3447 stream.PutCStringAsRawHex8(src);
3448 const char* packet = stream.GetData();
3449 int packet_len = stream.GetSize();
3450 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003451 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003452 {
3453 if (response.GetChar() == 'F')
3454 {
3455 uint32_t result = response.GetU32(UINT32_MAX);
3456 if (result != 0)
3457 {
3458 error.SetErrorToGenericError();
3459 if (response.GetChar() == ',')
3460 {
3461 int response_errno = response.GetS32(-1);
3462 if (response_errno > 0)
3463 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3464 }
3465 }
3466 }
3467 else
3468 {
3469 // Should have returned with 'F<result>[,<errno>]'
3470 error.SetErrorStringWithFormat("symlink failed");
3471 }
3472 }
3473 else
3474 {
3475 error.SetErrorString ("failed to send vFile:symlink packet");
3476 }
3477 return error;
3478}
3479
3480Error
3481GDBRemoteCommunicationClient::Unlink (const char *path)
3482{
3483 Error error;
3484 lldb_private::StreamGDBRemote stream;
3485 stream.PutCString("vFile:unlink:");
3486 // the unix symlink() command reverses its parameters where the dst if first,
3487 // so we follow suit here
3488 stream.PutCStringAsRawHex8(path);
3489 const char* packet = stream.GetData();
3490 int packet_len = stream.GetSize();
3491 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003492 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003493 {
3494 if (response.GetChar() == 'F')
3495 {
3496 uint32_t result = response.GetU32(UINT32_MAX);
3497 if (result != 0)
3498 {
3499 error.SetErrorToGenericError();
3500 if (response.GetChar() == ',')
3501 {
3502 int response_errno = response.GetS32(-1);
3503 if (response_errno > 0)
3504 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3505 }
3506 }
3507 }
3508 else
3509 {
3510 // Should have returned with 'F<result>[,<errno>]'
3511 error.SetErrorStringWithFormat("unlink failed");
3512 }
3513 }
3514 else
3515 {
3516 error.SetErrorString ("failed to send vFile:unlink packet");
3517 }
3518 return error;
3519}
3520
Daniel Maleae0f8f572013-08-26 23:57:52 +00003521// Extension of host I/O packets to get whether a file exists.
3522bool
3523GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3524{
3525 lldb_private::StreamString stream;
3526 stream.PutCString("vFile:exists:");
3527 std::string path (file_spec.GetPath());
3528 stream.PutCStringAsRawHex8(path.c_str());
3529 const char* packet = stream.GetData();
3530 int packet_len = stream.GetSize();
3531 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003532 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003533 {
3534 if (response.GetChar() != 'F')
3535 return false;
3536 if (response.GetChar() != ',')
3537 return false;
3538 bool retcode = (response.GetChar() != '0');
3539 return retcode;
3540 }
3541 return false;
3542}
3543
3544bool
3545GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3546 uint64_t &high,
3547 uint64_t &low)
3548{
3549 lldb_private::StreamString stream;
3550 stream.PutCString("vFile:MD5:");
3551 std::string path (file_spec.GetPath());
3552 stream.PutCStringAsRawHex8(path.c_str());
3553 const char* packet = stream.GetData();
3554 int packet_len = stream.GetSize();
3555 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003556 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003557 {
3558 if (response.GetChar() != 'F')
3559 return false;
3560 if (response.GetChar() != ',')
3561 return false;
3562 if (response.Peek() && *response.Peek() == 'x')
3563 return false;
3564 low = response.GetHexMaxU64(false, UINT64_MAX);
3565 high = response.GetHexMaxU64(false, UINT64_MAX);
3566 return true;
3567 }
3568 return false;
3569}
Greg Claytonf74cf862013-11-13 23:28:31 +00003570
3571bool
Jason Molendaa3329782014-03-29 18:54:20 +00003572GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3573{
3574 // Some targets have issues with g/G packets and we need to avoid using them
3575 if (m_avoid_g_packets == eLazyBoolCalculate)
3576 {
3577 if (process)
3578 {
3579 m_avoid_g_packets = eLazyBoolNo;
3580 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3581 if (arch.IsValid()
3582 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3583 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00003584 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00003585 {
3586 m_avoid_g_packets = eLazyBoolYes;
3587 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3588 if (gdb_server_version != 0)
3589 {
3590 const char *gdb_server_name = GetGDBServerProgramName();
3591 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3592 {
3593 if (gdb_server_version >= 310)
3594 m_avoid_g_packets = eLazyBoolNo;
3595 }
3596 }
3597 }
3598 }
3599 }
3600 return m_avoid_g_packets == eLazyBoolYes;
3601}
3602
3603bool
Greg Claytonf74cf862013-11-13 23:28:31 +00003604GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3605{
3606 Mutex::Locker locker;
3607 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
3608 {
3609 const bool thread_suffix_supported = GetThreadSuffixSupported();
3610
3611 if (thread_suffix_supported || SetCurrentThread(tid))
3612 {
3613 char packet[64];
3614 int packet_len = 0;
3615 if (thread_suffix_supported)
3616 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
3617 else
3618 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3619 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003620 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003621 }
3622 }
3623 return false;
3624
3625}
3626
3627
3628bool
3629GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3630{
3631 Mutex::Locker locker;
3632 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3633 {
3634 const bool thread_suffix_supported = GetThreadSuffixSupported();
3635
3636 if (thread_suffix_supported || SetCurrentThread(tid))
3637 {
3638 char packet[64];
3639 int packet_len = 0;
3640 // Get all registers in one packet
3641 if (thread_suffix_supported)
3642 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3643 else
3644 packet_len = ::snprintf (packet, sizeof(packet), "g");
3645 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003646 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003647 }
3648 }
3649 return false;
3650}
3651bool
3652GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3653{
3654 save_id = 0; // Set to invalid save ID
3655 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3656 return false;
3657
3658 m_supports_QSaveRegisterState = eLazyBoolYes;
3659 Mutex::Locker locker;
3660 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3661 {
3662 const bool thread_suffix_supported = GetThreadSuffixSupported();
3663 if (thread_suffix_supported || SetCurrentThread(tid))
3664 {
3665 char packet[256];
3666 if (thread_suffix_supported)
3667 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3668 else
Ilia K686b1fe2015-02-27 19:43:08 +00003669 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
Greg Claytonf74cf862013-11-13 23:28:31 +00003670
3671 StringExtractorGDBRemote response;
3672
Greg Clayton3dedae12013-12-06 21:45:27 +00003673 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003674 {
3675 if (response.IsUnsupportedResponse())
3676 {
3677 // This packet isn't supported, don't try calling it again
3678 m_supports_QSaveRegisterState = eLazyBoolNo;
3679 }
3680
3681 const uint32_t response_save_id = response.GetU32(0);
3682 if (response_save_id != 0)
3683 {
3684 save_id = response_save_id;
3685 return true;
3686 }
3687 }
3688 }
3689 }
3690 return false;
3691}
3692
3693bool
3694GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3695{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003696 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00003697 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3698 // order to be useful
3699 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3700 return false;
3701
3702 Mutex::Locker locker;
3703 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
3704 {
3705 const bool thread_suffix_supported = GetThreadSuffixSupported();
3706 if (thread_suffix_supported || SetCurrentThread(tid))
3707 {
3708 char packet[256];
3709 if (thread_suffix_supported)
3710 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3711 else
3712 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3713
3714 StringExtractorGDBRemote response;
3715
Greg Clayton3dedae12013-12-06 21:45:27 +00003716 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003717 {
3718 if (response.IsOKResponse())
3719 {
3720 return true;
3721 }
3722 else if (response.IsUnsupportedResponse())
3723 {
3724 // This packet isn't supported, don't try calling this packet or
3725 // QSaveRegisterState again...
3726 m_supports_QSaveRegisterState = eLazyBoolNo;
3727 }
3728 }
3729 }
3730 }
3731 return false;
3732}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003733
3734bool
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003735GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003736 const lldb_private::ArchSpec& arch_spec,
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003737 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003738{
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00003739 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003740 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003741 return false;
3742
3743 StreamString packet;
3744 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003745 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003746 packet.PutCString(";");
3747 const auto& tripple = arch_spec.GetTriple().getTriple();
3748 packet.PutBytesAsRawHex8(tripple.c_str(), tripple.size());
3749
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003750 StringExtractorGDBRemote response;
3751 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
3752 return false;
3753
Aidan Doddsdf627e72015-05-05 08:31:55 +00003754 if (response.IsErrorResponse () || response.IsUnsupportedResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003755 return false;
3756
3757 std::string name;
3758 std::string value;
3759 bool success;
3760 StringExtractor extractor;
3761
3762 module_spec.Clear ();
3763 module_spec.GetFileSpec () = module_file_spec;
3764
3765 while (response.GetNameColonValue (name, value))
3766 {
3767 if (name == "uuid" || name == "md5")
3768 {
3769 extractor.GetStringRef ().swap (value);
3770 extractor.SetFilePos (0);
3771 extractor.GetHexByteString (value);
3772 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
3773 }
3774 else if (name == "triple")
3775 {
3776 extractor.GetStringRef ().swap (value);
3777 extractor.SetFilePos (0);
3778 extractor.GetHexByteString (value);
3779 module_spec.GetArchitecture().SetTriple (value.c_str ());
3780 }
3781 else if (name == "file_offset")
3782 {
3783 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
3784 if (success)
3785 module_spec.SetObjectOffset (ival);
3786 }
3787 else if (name == "file_size")
3788 {
3789 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
3790 if (success)
3791 module_spec.SetObjectSize (ival);
3792 }
3793 else if (name == "file_path")
3794 {
3795 extractor.GetStringRef ().swap (value);
3796 extractor.SetFilePos (0);
3797 extractor.GetHexByteString (value);
3798 module_spec.GetFileSpec () = FileSpec (value.c_str(), false);
3799 }
3800 }
3801
3802 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003803}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003804
3805// query the target remote for extended information using the qXfer packet
3806//
3807// example: object='features', annex='target.xml', out=<xml output>
3808// return: 'true' on success
3809// 'false' on failure (err set)
3810bool
3811GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
3812 const lldb_private::ConstString annex,
3813 std::string & out,
3814 lldb_private::Error & err) {
3815
3816 std::stringstream output;
3817 StringExtractorGDBRemote chunk;
3818
3819 const int size = 0xfff;
3820 int offset = 0;
3821 bool active = true;
3822
3823 // loop until all data has been read
3824 while ( active ) {
3825
3826 // send query extended feature packet
3827 std::stringstream packet;
3828 packet << "qXfer:"
3829 << object.AsCString( ) << ":read:"
3830 << annex.AsCString( ) << ":"
3831 << std::hex << offset << ","
3832 << std::hex << size;
3833
3834 GDBRemoteCommunication::PacketResult res =
3835 SendPacketAndWaitForResponse( packet.str().c_str(),
3836 chunk,
3837 false );
3838
3839 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
3840 err.SetErrorString( "Error sending $qXfer packet" );
3841 return false;
3842 }
3843
3844 const std::string & str = chunk.GetStringRef( );
3845 if ( str.length() == 0 ) {
3846 // should have some data in chunk
3847 err.SetErrorString( "Empty response from $qXfer packet" );
3848 return false;
3849 }
3850
3851 // check packet code
3852 switch ( str[0] ) {
3853 // last chunk
3854 case ( 'l' ):
3855 active = false;
Aidan Doddsed9f6122015-04-29 10:08:17 +00003856 // fall through intentional
Colin Rileyc3c95b22015-04-16 15:51:33 +00003857
3858 // more chunks
3859 case ( 'm' ) :
3860 if ( str.length() > 1 )
3861 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00003862 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003863 break;
3864
3865 // unknown chunk
3866 default:
3867 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
3868 return false;
3869 }
3870 }
3871
3872 out = output.str( );
3873 err.Success( );
3874 return true;
3875}