blob: 0a1ec3f962cbfceee275d02c39f9026d85d1a4a8 [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
Greg Claytone034a042015-05-21 20:52:06 +000014#include <math.h>
Daniel Maleab89d0492013-08-28 16:06:16 +000015#include <sys/stat.h>
16
Greg Clayton576d8832011-03-22 04:00:09 +000017// C++ Includes
Han Ming Ong4b6459f2013-01-18 23:11:53 +000018#include <sstream>
Greg Claytone034a042015-05-21 20:52:06 +000019#include <numeric>
Han Ming Ong4b6459f2013-01-18 23:11:53 +000020
Greg Clayton576d8832011-03-22 04:00:09 +000021// Other libraries and framework includes
Saleem Abdulrasool28606952014-06-27 05:17:41 +000022#include "llvm/ADT/STLExtras.h"
Greg Clayton576d8832011-03-22 04:00:09 +000023#include "llvm/ADT/Triple.h"
24#include "lldb/Interpreter/Args.h"
Greg Clayton576d8832011-03-22 04:00:09 +000025#include "lldb/Core/Log.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000026#include "lldb/Core/ModuleSpec.h"
Greg Clayton576d8832011-03-22 04:00:09 +000027#include "lldb/Core/State.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000028#include "lldb/Core/StreamGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000029#include "lldb/Core/StreamString.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000030#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton576d8832011-03-22 04:00:09 +000031#include "lldb/Host/Endian.h"
32#include "lldb/Host/Host.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000033#include "lldb/Host/HostInfo.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000034#include "lldb/Host/StringConvert.h"
Greg Clayton576d8832011-03-22 04:00:09 +000035#include "lldb/Host/TimeValue.h"
Jason Molendaa3329782014-03-29 18:54:20 +000036#include "lldb/Target/Target.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000037#include "lldb/Target/MemoryRegionInfo.h"
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +000038#include "lldb/Target/UnixSignals.h"
Greg Clayton576d8832011-03-22 04:00:09 +000039
40// Project includes
41#include "Utility/StringExtractorGDBRemote.h"
42#include "ProcessGDBRemote.h"
43#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000044#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000045
46using namespace lldb;
47using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000048using namespace lldb_private::process_gdb_remote;
Greg Clayton576d8832011-03-22 04:00:09 +000049
50//----------------------------------------------------------------------
51// GDBRemoteCommunicationClient constructor
52//----------------------------------------------------------------------
Tamas Berghammere13c2732015-02-11 10:29:30 +000053GDBRemoteCommunicationClient::GDBRemoteCommunicationClient() :
54 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet"),
Greg Clayton576d8832011-03-22 04:00:09 +000055 m_supports_not_sending_acks (eLazyBoolCalculate),
56 m_supports_thread_suffix (eLazyBoolCalculate),
Greg Clayton44633992012-04-10 03:22:03 +000057 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
Greg Clayton576d8832011-03-22 04:00:09 +000058 m_supports_vCont_all (eLazyBoolCalculate),
59 m_supports_vCont_any (eLazyBoolCalculate),
60 m_supports_vCont_c (eLazyBoolCalculate),
61 m_supports_vCont_C (eLazyBoolCalculate),
62 m_supports_vCont_s (eLazyBoolCalculate),
63 m_supports_vCont_S (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000064 m_qHostInfo_is_valid (eLazyBoolCalculate),
Todd Fiala9f72b3a2014-05-07 19:28:21 +000065 m_curr_pid_is_valid (eLazyBoolCalculate),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000066 m_qProcessInfo_is_valid (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000067 m_qGDBServerVersion_is_valid (eLazyBoolCalculate),
Greg Clayton70b57652011-05-15 01:25:55 +000068 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
Greg Clayton46fb5582011-11-18 07:03:08 +000069 m_supports_memory_region_info (eLazyBoolCalculate),
Johnny Chen64637202012-05-23 21:09:52 +000070 m_supports_watchpoint_support_info (eLazyBoolCalculate),
Jim Inghamacff8952013-05-02 00:27:30 +000071 m_supports_detach_stay_stopped (eLazyBoolCalculate),
Enrico Granataf04a2192012-07-13 23:18:48 +000072 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
Jim Inghamcd16df92012-07-20 21:37:13 +000073 m_attach_or_wait_reply(eLazyBoolCalculate),
Jim Ingham279ceec2012-07-25 21:12:43 +000074 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
Eric Christopher2490f5c2013-08-30 17:50:57 +000075 m_supports_p (eLazyBoolCalculate),
Jason Molendabdc4f122014-05-06 02:59:39 +000076 m_supports_x (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000077 m_avoid_g_packets (eLazyBoolCalculate),
Greg Claytonf74cf862013-11-13 23:28:31 +000078 m_supports_QSaveRegisterState (eLazyBoolCalculate),
Steve Pucci03904ac2014-03-04 23:18:46 +000079 m_supports_qXfer_auxv_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000080 m_supports_qXfer_libraries_read (eLazyBoolCalculate),
81 m_supports_qXfer_libraries_svr4_read (eLazyBoolCalculate),
Greg Clayton253204e2015-04-16 23:11:06 +000082 m_supports_qXfer_features_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000083 m_supports_augmented_libraries_svr4_read (eLazyBoolCalculate),
Jason Molenda705b1802014-06-13 02:37:02 +000084 m_supports_jThreadExtendedInfo (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000085 m_supports_qProcessInfoPID (true),
86 m_supports_qfProcessInfo (true),
87 m_supports_qUserName (true),
88 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000089 m_supports_qThreadStopInfo (true),
90 m_supports_z0 (true),
91 m_supports_z1 (true),
92 m_supports_z2 (true),
93 m_supports_z3 (true),
94 m_supports_z4 (true),
Greg Clayton89600582013-10-10 17:53:50 +000095 m_supports_QEnvironment (true),
96 m_supports_QEnvironmentHexEncoded (true),
Todd Fiala9f72b3a2014-05-07 19:28:21 +000097 m_curr_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton8b82f082011-04-12 05:54:46 +000098 m_curr_tid (LLDB_INVALID_THREAD_ID),
99 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +0000100 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +0000101 m_async_mutex (Mutex::eMutexTypeRecursive),
102 m_async_packet_predicate (false),
103 m_async_packet (),
Jim Inghama6195b72013-12-18 01:24:33 +0000104 m_async_result (PacketResult::Success),
Greg Clayton576d8832011-03-22 04:00:09 +0000105 m_async_response (),
106 m_async_signal (-1),
Jim Inghamb8cd5752014-04-16 02:24:17 +0000107 m_interrupt_sent (false),
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000108 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +0000109 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000110 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +0000111 m_os_version_major (UINT32_MAX),
112 m_os_version_minor (UINT32_MAX),
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000113 m_os_version_update (UINT32_MAX),
114 m_os_build (),
115 m_os_kernel (),
116 m_hostname (),
Jason Molendaa3329782014-03-29 18:54:20 +0000117 m_gdb_server_name(),
118 m_gdb_server_version(UINT32_MAX),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000119 m_default_packet_timeout (0),
120 m_max_packet_size (0)
Greg Clayton576d8832011-03-22 04:00:09 +0000121{
Greg Clayton576d8832011-03-22 04:00:09 +0000122}
123
124//----------------------------------------------------------------------
125// Destructor
126//----------------------------------------------------------------------
127GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
128{
Greg Clayton576d8832011-03-22 04:00:09 +0000129 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000130 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000131}
132
133bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000134GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
135{
Greg Claytonfb909312013-11-23 01:58:15 +0000136 ResetDiscoverableSettings();
137
Greg Clayton1cb64962011-03-24 04:28:38 +0000138 // Start the read thread after we send the handshake ack since if we
139 // fail to send the handshake ack, there is no reason to continue...
140 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000141 {
Ed Maste48f986f2013-12-18 15:31:45 +0000142 // Wait for any responses that might have been queued up in the remote
143 // GDB server and flush them all
144 StringExtractorGDBRemote response;
145 PacketResult packet_result = PacketResult::Success;
146 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
147 while (packet_result == PacketResult::Success)
Greg Claytonb30c50c2015-05-29 00:01:55 +0000148 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, timeout_usec, false);
Ed Maste48f986f2013-12-18 15:31:45 +0000149
Greg Claytonfb909312013-11-23 01:58:15 +0000150 // The return value from QueryNoAckModeSupported() is true if the packet
151 // was sent and _any_ response (including UNIMPLEMENTED) was received),
152 // or false if no response was received. This quickly tells us if we have
153 // a live connection to a remote GDB server...
154 if (QueryNoAckModeSupported())
155 {
156 return true;
157 }
158 else
159 {
160 if (error_ptr)
161 error_ptr->SetErrorString("failed to get reply to handshake packet");
162 }
163 }
164 else
165 {
166 if (error_ptr)
167 error_ptr->SetErrorString("failed to send the handshake ack");
168 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000169 return false;
170}
171
Greg Claytonfb909312013-11-23 01:58:15 +0000172bool
Greg Claytonb30c50c2015-05-29 00:01:55 +0000173GDBRemoteCommunicationClient::GetEchoSupported ()
174{
175 if (m_supports_qEcho == eLazyBoolCalculate)
176 {
177 GetRemoteQSupported();
178 }
179 return m_supports_qEcho == eLazyBoolYes;
180}
181
182
183bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000184GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
185{
186 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
187 {
188 GetRemoteQSupported();
189 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000190 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000191}
192
193bool
194GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
195{
196 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
197 {
198 GetRemoteQSupported();
199 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000200 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000201}
202
203bool
204GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
205{
206 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
207 {
208 GetRemoteQSupported();
209 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000210 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000211}
212
Steve Pucci03904ac2014-03-04 23:18:46 +0000213bool
214GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
215{
216 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
217 {
218 GetRemoteQSupported();
219 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000220 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000221}
222
Colin Rileyc3c95b22015-04-16 15:51:33 +0000223bool
224GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported ()
225{
226 if (m_supports_qXfer_features_read == eLazyBoolCalculate)
227 {
228 GetRemoteQSupported();
229 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000230 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000231}
232
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000233uint64_t
234GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
235{
236 if (m_max_packet_size == 0)
237 {
238 GetRemoteQSupported();
239 }
240 return m_max_packet_size;
241}
242
243bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000244GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000245{
246 if (m_supports_not_sending_acks == eLazyBoolCalculate)
247 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000248 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000249 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000250
Jason Molenda36a216e2014-07-24 01:36:24 +0000251 // This is the first real packet that we'll send in a debug session and it may take a little
252 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
253
254 const uint32_t minimum_timeout = 6;
255 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000256 GDBRemoteCommunication::ScopedTimeout timeout (*this, std::max (old_timeout, minimum_timeout));
Jason Molenda36a216e2014-07-24 01:36:24 +0000257
Greg Clayton1cb64962011-03-24 04:28:38 +0000258 StringExtractorGDBRemote response;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000259 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000260 {
261 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000262 {
263 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000264 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000265 }
Greg Claytonfb909312013-11-23 01:58:15 +0000266 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000267 }
268 }
Greg Claytonfb909312013-11-23 01:58:15 +0000269 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000270}
271
272void
Greg Clayton44633992012-04-10 03:22:03 +0000273GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
274{
275 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
276 {
277 m_supports_threads_in_stop_reply = eLazyBoolNo;
278
279 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000280 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000281 {
282 if (response.IsOKResponse())
283 m_supports_threads_in_stop_reply = eLazyBoolYes;
284 }
285 }
286}
287
Jim Inghamcd16df92012-07-20 21:37:13 +0000288bool
289GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
290{
291 if (m_attach_or_wait_reply == eLazyBoolCalculate)
292 {
293 m_attach_or_wait_reply = eLazyBoolNo;
294
295 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000296 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000297 {
298 if (response.IsOKResponse())
299 m_attach_or_wait_reply = eLazyBoolYes;
300 }
301 }
302 if (m_attach_or_wait_reply == eLazyBoolYes)
303 return true;
304 else
305 return false;
306}
307
Jim Ingham279ceec2012-07-25 21:12:43 +0000308bool
309GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
310{
311 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
312 {
313 m_prepare_for_reg_writing_reply = eLazyBoolNo;
314
315 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000316 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000317 {
318 if (response.IsOKResponse())
319 m_prepare_for_reg_writing_reply = eLazyBoolYes;
320 }
321 }
322 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
323 return true;
324 else
325 return false;
326}
327
Greg Clayton44633992012-04-10 03:22:03 +0000328
329void
Greg Clayton576d8832011-03-22 04:00:09 +0000330GDBRemoteCommunicationClient::ResetDiscoverableSettings()
331{
332 m_supports_not_sending_acks = eLazyBoolCalculate;
333 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton44633992012-04-10 03:22:03 +0000334 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
Greg Clayton576d8832011-03-22 04:00:09 +0000335 m_supports_vCont_c = eLazyBoolCalculate;
336 m_supports_vCont_C = eLazyBoolCalculate;
337 m_supports_vCont_s = eLazyBoolCalculate;
338 m_supports_vCont_S = eLazyBoolCalculate;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000339 m_supports_p = eLazyBoolCalculate;
Jason Molendabdc4f122014-05-06 02:59:39 +0000340 m_supports_x = eLazyBoolCalculate;
Greg Claytonf74cf862013-11-13 23:28:31 +0000341 m_supports_QSaveRegisterState = eLazyBoolCalculate;
Greg Clayton32e0a752011-03-30 18:16:51 +0000342 m_qHostInfo_is_valid = eLazyBoolCalculate;
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000343 m_curr_pid_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000344 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000345 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
Greg Clayton70b57652011-05-15 01:25:55 +0000346 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton46fb5582011-11-18 07:03:08 +0000347 m_supports_memory_region_info = eLazyBoolCalculate;
Jim Ingham279ceec2012-07-25 21:12:43 +0000348 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
349 m_attach_or_wait_reply = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000350 m_avoid_g_packets = eLazyBoolCalculate;
Steve Pucci03904ac2014-03-04 23:18:46 +0000351 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000352 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
353 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000354 m_supports_qXfer_features_read = eLazyBoolCalculate;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000355 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
Greg Clayton2a48f522011-05-14 01:50:35 +0000356
Greg Clayton32e0a752011-03-30 18:16:51 +0000357 m_supports_qProcessInfoPID = true;
358 m_supports_qfProcessInfo = true;
359 m_supports_qUserName = true;
360 m_supports_qGroupName = true;
Greg Clayton8b82f082011-04-12 05:54:46 +0000361 m_supports_qThreadStopInfo = true;
362 m_supports_z0 = true;
363 m_supports_z1 = true;
364 m_supports_z2 = true;
365 m_supports_z3 = true;
366 m_supports_z4 = true;
Greg Clayton89600582013-10-10 17:53:50 +0000367 m_supports_QEnvironment = true;
368 m_supports_QEnvironmentHexEncoded = true;
Jason Molendaa3329782014-03-29 18:54:20 +0000369
Greg Claytond314e812011-03-23 00:09:55 +0000370 m_host_arch.Clear();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000371 m_process_arch.Clear();
Jason Molendaa3329782014-03-29 18:54:20 +0000372 m_os_version_major = UINT32_MAX;
373 m_os_version_minor = UINT32_MAX;
374 m_os_version_update = UINT32_MAX;
375 m_os_build.clear();
376 m_os_kernel.clear();
377 m_hostname.clear();
378 m_gdb_server_name.clear();
379 m_gdb_server_version = UINT32_MAX;
380 m_default_packet_timeout = 0;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000381
382 m_max_packet_size = 0;
Greg Clayton576d8832011-03-22 04:00:09 +0000383}
384
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000385void
386GDBRemoteCommunicationClient::GetRemoteQSupported ()
387{
388 // Clear out any capabilities we expect to see in the qSupported response
Steve Pucci03904ac2014-03-04 23:18:46 +0000389 m_supports_qXfer_auxv_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000390 m_supports_qXfer_libraries_read = eLazyBoolNo;
Steve Pucci03904ac2014-03-04 23:18:46 +0000391 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000392 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000393 m_supports_qXfer_features_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000394 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
395
Colin Rileyc3c95b22015-04-16 15:51:33 +0000396 // build the qSupported packet
397 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
398 StreamString packet;
399 packet.PutCString( "qSupported" );
400 for ( uint32_t i = 0; i < features.size( ); ++i )
401 {
402 packet.PutCString( i==0 ? ":" : ";");
403 packet.PutCString( features[i].c_str( ) );
404 }
405
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000406 StringExtractorGDBRemote response;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000407 if (SendPacketAndWaitForResponse(packet.GetData(),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000408 response,
409 /*send_async=*/false) == PacketResult::Success)
410 {
411 const char *response_cstr = response.GetStringRef().c_str();
Steve Pucci03904ac2014-03-04 23:18:46 +0000412 if (::strstr (response_cstr, "qXfer:auxv:read+"))
413 m_supports_qXfer_auxv_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000414 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
415 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
416 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
417 {
418 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
419 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
420 }
421 if (::strstr (response_cstr, "qXfer:libraries:read+"))
422 m_supports_qXfer_libraries_read = eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000423 if (::strstr (response_cstr, "qXfer:features:read+"))
424 m_supports_qXfer_features_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000425
Greg Claytonb30c50c2015-05-29 00:01:55 +0000426 if (::strstr (response_cstr, "qEcho"))
427 m_supports_qEcho = eLazyBoolYes;
428 else
429 m_supports_qEcho = eLazyBoolNo;
430
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000431 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
432 if (packet_size_str)
433 {
434 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
435 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
436 if (m_max_packet_size == 0)
437 {
438 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
439 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
440 if (log)
441 log->Printf ("Garbled PacketSize spec in qSupported response");
442 }
443 }
444 }
445}
Greg Clayton576d8832011-03-22 04:00:09 +0000446
447bool
448GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
449{
450 if (m_supports_thread_suffix == eLazyBoolCalculate)
451 {
452 StringExtractorGDBRemote response;
453 m_supports_thread_suffix = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000454 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000455 {
456 if (response.IsOKResponse())
457 m_supports_thread_suffix = eLazyBoolYes;
458 }
459 }
460 return m_supports_thread_suffix;
461}
462bool
463GDBRemoteCommunicationClient::GetVContSupported (char flavor)
464{
465 if (m_supports_vCont_c == eLazyBoolCalculate)
466 {
467 StringExtractorGDBRemote response;
468 m_supports_vCont_any = eLazyBoolNo;
469 m_supports_vCont_all = eLazyBoolNo;
470 m_supports_vCont_c = eLazyBoolNo;
471 m_supports_vCont_C = eLazyBoolNo;
472 m_supports_vCont_s = eLazyBoolNo;
473 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000474 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000475 {
476 const char *response_cstr = response.GetStringRef().c_str();
477 if (::strstr (response_cstr, ";c"))
478 m_supports_vCont_c = eLazyBoolYes;
479
480 if (::strstr (response_cstr, ";C"))
481 m_supports_vCont_C = eLazyBoolYes;
482
483 if (::strstr (response_cstr, ";s"))
484 m_supports_vCont_s = eLazyBoolYes;
485
486 if (::strstr (response_cstr, ";S"))
487 m_supports_vCont_S = eLazyBoolYes;
488
489 if (m_supports_vCont_c == eLazyBoolYes &&
490 m_supports_vCont_C == eLazyBoolYes &&
491 m_supports_vCont_s == eLazyBoolYes &&
492 m_supports_vCont_S == eLazyBoolYes)
493 {
494 m_supports_vCont_all = eLazyBoolYes;
495 }
496
497 if (m_supports_vCont_c == eLazyBoolYes ||
498 m_supports_vCont_C == eLazyBoolYes ||
499 m_supports_vCont_s == eLazyBoolYes ||
500 m_supports_vCont_S == eLazyBoolYes)
501 {
502 m_supports_vCont_any = eLazyBoolYes;
503 }
504 }
505 }
506
507 switch (flavor)
508 {
509 case 'a': return m_supports_vCont_any;
510 case 'A': return m_supports_vCont_all;
511 case 'c': return m_supports_vCont_c;
512 case 'C': return m_supports_vCont_C;
513 case 's': return m_supports_vCont_s;
514 case 'S': return m_supports_vCont_S;
515 default: break;
516 }
517 return false;
518}
519
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000520// Check if the target supports 'p' packet. It sends out a 'p'
521// packet and checks the response. A normal packet will tell us
522// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000523//
524// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000525bool
Sean Callananb1de1142013-09-04 23:24:15 +0000526GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000527{
528 if (m_supports_p == eLazyBoolCalculate)
529 {
530 StringExtractorGDBRemote response;
531 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000532 char packet[256];
533 if (GetThreadSuffixSupported())
534 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
535 else
536 snprintf(packet, sizeof(packet), "p0");
537
Greg Clayton3dedae12013-12-06 21:45:27 +0000538 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000539 {
540 if (response.IsNormalResponse())
541 m_supports_p = eLazyBoolYes;
542 }
543 }
544 return m_supports_p;
545}
Greg Clayton576d8832011-03-22 04:00:09 +0000546
Jason Molendabdc4f122014-05-06 02:59:39 +0000547bool
Jason Molenda705b1802014-06-13 02:37:02 +0000548GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
549{
550 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
551 {
552 StringExtractorGDBRemote response;
553 m_supports_jThreadExtendedInfo = eLazyBoolNo;
554 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
555 {
556 if (response.IsOKResponse())
557 {
558 m_supports_jThreadExtendedInfo = eLazyBoolYes;
559 }
560 }
561 }
562 return m_supports_jThreadExtendedInfo;
563}
564
565bool
Jason Molendabdc4f122014-05-06 02:59:39 +0000566GDBRemoteCommunicationClient::GetxPacketSupported ()
567{
568 if (m_supports_x == eLazyBoolCalculate)
569 {
570 StringExtractorGDBRemote response;
571 m_supports_x = eLazyBoolNo;
572 char packet[256];
573 snprintf (packet, sizeof (packet), "x0,0");
574 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
575 {
576 if (response.IsOKResponse())
577 m_supports_x = eLazyBoolYes;
578 }
579 }
580 return m_supports_x;
581}
582
Greg Clayton3dedae12013-12-06 21:45:27 +0000583GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000584GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
585(
586 const char *payload_prefix,
587 std::string &response_string
588)
589{
590 Mutex::Locker locker;
591 if (!GetSequenceMutex(locker,
592 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
593 {
594 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
595 if (log)
596 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
597 payload_prefix);
598 return PacketResult::ErrorNoSequenceLock;
599 }
600
601 response_string = "";
602 std::string payload_prefix_str(payload_prefix);
603 unsigned int response_size = 0x1000;
604 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
605 response_size = GetRemoteMaxPacketSize();
606 }
607
608 for (unsigned int offset = 0; true; offset += response_size)
609 {
610 StringExtractorGDBRemote this_response;
611 // Construct payload
612 char sizeDescriptor[128];
613 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
614 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
615 this_response,
616 /*send_async=*/false);
617 if (result != PacketResult::Success)
618 return result;
619
620 const std::string &this_string = this_response.GetStringRef();
621
622 // Check for m or l as first character; l seems to mean this is the last chunk
623 char first_char = *this_string.c_str();
624 if (first_char != 'm' && first_char != 'l')
625 {
626 return PacketResult::ErrorReplyInvalid;
627 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000628 // Concatenate the result so far (skipping 'm' or 'l')
629 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000630 if (first_char == 'l')
631 // We're done
632 return PacketResult::Success;
633 }
634}
635
636GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000637GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
638(
639 const char *payload,
640 StringExtractorGDBRemote &response,
641 bool send_async
642)
643{
644 return SendPacketAndWaitForResponse (payload,
645 ::strlen (payload),
646 response,
647 send_async);
648}
649
Greg Clayton3dedae12013-12-06 21:45:27 +0000650GDBRemoteCommunicationClient::PacketResult
651GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
652 size_t payload_length,
653 StringExtractorGDBRemote &response)
654{
655 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
656 if (packet_result == PacketResult::Success)
Greg Claytonb30c50c2015-05-29 00:01:55 +0000657 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds (), true);
Greg Clayton3dedae12013-12-06 21:45:27 +0000658 return packet_result;
659}
660
661GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000662GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
663(
664 const char *payload,
665 size_t payload_length,
666 StringExtractorGDBRemote &response,
667 bool send_async
668)
669{
Greg Clayton3dedae12013-12-06 21:45:27 +0000670 PacketResult packet_result = PacketResult::ErrorSendFailed;
Greg Clayton576d8832011-03-22 04:00:09 +0000671 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000672 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000673 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000674 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000675 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000676 }
677 else
678 {
679 if (send_async)
680 {
Greg Claytond3544052012-05-31 21:24:20 +0000681 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000682 {
Greg Claytond3544052012-05-31 21:24:20 +0000683 Mutex::Locker async_locker (m_async_mutex);
684 m_async_packet.assign(payload, payload_length);
685 m_async_packet_predicate.SetValue (true, eBroadcastNever);
686
687 if (log)
688 log->Printf ("async: async packet = %s", m_async_packet.c_str());
689
690 bool timed_out = false;
691 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000692 {
Greg Claytond3544052012-05-31 21:24:20 +0000693 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000694 {
Jim Inghambabfc382012-06-06 00:32:39 +0000695 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000696 TimeValue timeout_time;
697 timeout_time = TimeValue::Now();
698 timeout_time.OffsetWithSeconds (m_packet_timeout);
699
Greg Clayton576d8832011-03-22 04:00:09 +0000700 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000701 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000702
Greg Claytond3544052012-05-31 21:24:20 +0000703 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000704 {
Greg Claytond3544052012-05-31 21:24:20 +0000705 if (log)
706 log->Printf ("async: got response");
707
708 // Swap the response buffer to avoid malloc and string copy
709 response.GetStringRef().swap (m_async_response.GetStringRef());
Jim Inghama6195b72013-12-18 01:24:33 +0000710 packet_result = m_async_result;
Greg Claytond3544052012-05-31 21:24:20 +0000711 }
712 else
713 {
714 if (log)
715 log->Printf ("async: timed out waiting for response");
716 }
717
718 // Make sure we wait until the continue packet has been sent again...
719 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
720 {
721 if (log)
722 {
723 if (timed_out)
724 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
725 else
726 log->Printf ("async: async packet sent");
727 }
728 }
729 else
730 {
731 if (log)
732 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000733 }
734 }
735 else
736 {
Greg Claytond3544052012-05-31 21:24:20 +0000737 // We had a racy condition where we went to send the interrupt
738 // yet we were able to get the lock, so the process must have
739 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000740 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000741 log->Printf ("async: got lock without sending interrupt");
742 // Send the packet normally since we got the lock
Greg Clayton3dedae12013-12-06 21:45:27 +0000743 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000744 }
745 }
746 else
747 {
Greg Clayton644247c2011-07-07 01:59:51 +0000748 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000749 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000750 }
751 }
752 else
753 {
754 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000755 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000756 }
757 }
758 else
759 {
760 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000761 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000762 }
763 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000764 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000765}
766
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000767static const char *end_delimiter = "--end--;";
768static const int end_delimiter_len = 8;
769
770std::string
771GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
772( ProcessGDBRemote *process,
773 StringExtractorGDBRemote& profileDataExtractor
774)
775{
776 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
777 std::stringstream final_output;
778 std::string name, value;
779
780 // Going to assuming thread_used_usec comes first, else bail out.
781 while (profileDataExtractor.GetNameColonValue(name, value))
782 {
783 if (name.compare("thread_used_id") == 0)
784 {
785 StringExtractor threadIDHexExtractor(value.c_str());
786 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
787
788 bool has_used_usec = false;
789 uint32_t curr_used_usec = 0;
790 std::string usec_name, usec_value;
791 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
792 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
793 {
794 if (usec_name.compare("thread_used_usec") == 0)
795 {
796 has_used_usec = true;
797 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
798 }
799 else
800 {
801 // We didn't find what we want, it is probably
802 // an older version. Bail out.
803 profileDataExtractor.SetFilePos(input_file_pos);
804 }
805 }
806
807 if (has_used_usec)
808 {
809 uint32_t prev_used_usec = 0;
810 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
811 if (iterator != m_thread_id_to_used_usec_map.end())
812 {
813 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
814 }
815
816 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
817 // A good first time record is one that runs for at least 0.25 sec
818 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
819 bool good_subsequent_time = (prev_used_usec > 0) &&
820 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
821
822 if (good_first_time || good_subsequent_time)
823 {
824 // We try to avoid doing too many index id reservation,
825 // resulting in fast increase of index ids.
826
827 final_output << name << ":";
828 int32_t index_id = process->AssignIndexIDToThread(thread_id);
829 final_output << index_id << ";";
830
831 final_output << usec_name << ":" << usec_value << ";";
832 }
833 else
834 {
835 // Skip past 'thread_used_name'.
836 std::string local_name, local_value;
837 profileDataExtractor.GetNameColonValue(local_name, local_value);
838 }
839
840 // Store current time as previous time so that they can be compared later.
841 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
842 }
843 else
844 {
845 // Bail out and use old string.
846 final_output << name << ":" << value << ";";
847 }
848 }
849 else
850 {
851 final_output << name << ":" << value << ";";
852 }
853 }
854 final_output << end_delimiter;
855 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
856
857 return final_output.str();
858}
859
Greg Clayton576d8832011-03-22 04:00:09 +0000860StateType
861GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
862(
863 ProcessGDBRemote *process,
864 const char *payload,
865 size_t packet_length,
866 StringExtractorGDBRemote &response
867)
868{
Greg Clayton1f5181a2012-07-02 22:05:25 +0000869 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +0000870 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +0000871 if (log)
872 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
873
874 Mutex::Locker locker(m_sequence_mutex);
875 StateType state = eStateRunning;
876
877 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
878 m_public_is_running.SetValue (true, eBroadcastNever);
879 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +0000880 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +0000881 std::string continue_packet(payload, packet_length);
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +0000882
883 const auto sigstop_signo = process->GetUnixSignals().GetSignalNumberFromName("SIGSTOP");
884 const auto sigint_signo = process->GetUnixSignals().GetSignalNumberFromName("SIGINT");
885
Greg Clayton3f875c52013-02-22 22:23:55 +0000886 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +0000887
Greg Clayton576d8832011-03-22 04:00:09 +0000888 while (state == eStateRunning)
889 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000890 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +0000891 {
892 if (log)
893 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton3dedae12013-12-06 21:45:27 +0000894 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
Greg Claytonaf247d72011-05-19 03:54:16 +0000895 state = eStateInvalid;
Jim Inghamb8cd5752014-04-16 02:24:17 +0000896 else
897 m_interrupt_sent = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000898
Greg Claytone889ad62011-10-27 22:04:16 +0000899 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +0000900 }
901
Greg Clayton3f875c52013-02-22 22:23:55 +0000902 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000903
904 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000905 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +0000906
Greg Claytonb30c50c2015-05-29 00:01:55 +0000907 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000908 {
909 if (response.Empty())
910 state = eStateInvalid;
911 else
912 {
913 const char stop_type = response.GetChar();
914 if (log)
915 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
916 switch (stop_type)
917 {
918 case 'T':
919 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +0000920 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000921 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +0000922 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000923 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
924 {
925 lldb::pid_t pid = GetCurrentProcessID ();
926 if (pid != LLDB_INVALID_PROCESS_ID)
927 process->SetID (pid);
928 }
929 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +0000930 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000931
932 // Privately notify any internal threads that we have stopped
933 // in case we wanted to interrupt our process, yet we might
934 // send a packet and continue without returning control to the
935 // user.
936 m_private_is_running.SetValue (false, eBroadcastAlways);
937
938 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
939
Jim Inghambabfc382012-06-06 00:32:39 +0000940 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
941 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +0000942 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000943 // We sent an interrupt packet to stop the inferior process
944 // for an async signal or to send an async packet while running
945 // but we might have been single stepping and received the
946 // stop packet for the step instead of for the interrupt packet.
947 // Typically when an interrupt is sent a SIGINT or SIGSTOP
948 // is used, so if we get anything else, we need to try and
949 // get another stop reply packet that may have been sent
950 // due to sending the interrupt when the target is stopped
951 // which will just re-send a copy of the last stop reply
952 // packet. If we don't do this, then the reply for our
953 // async packet will be the repeat stop reply packet and cause
954 // a lot of trouble for us!
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +0000955 if (signo != sigint_signo && signo != sigstop_signo)
Greg Clayton2687cd12012-03-29 01:55:41 +0000956 {
Greg Claytonfb72fde2012-05-15 02:50:49 +0000957 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000958
959 // We didn't get a a SIGINT or SIGSTOP, so try for a
960 // very brief time (1 ms) to get another stop reply
961 // packet to make sure it doesn't get in the way
962 StringExtractorGDBRemote extra_stop_reply_packet;
963 uint32_t timeout_usec = 1000;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000964 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec, false) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +0000965 {
966 switch (extra_stop_reply_packet.GetChar())
967 {
968 case 'T':
969 case 'S':
970 // We did get an extra stop reply, which means
971 // our interrupt didn't stop the target so we
972 // shouldn't continue after the async signal
973 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +0000974 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000975 break;
976 }
977 }
978 }
979 }
980
981 if (m_async_signal != -1)
982 {
983 if (log)
984 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
985
986 // Save off the async signal we are supposed to send
987 const int async_signal = m_async_signal;
988 // Clear the async signal member so we don't end up
989 // sending the signal multiple times...
990 m_async_signal = -1;
991 // Check which signal we stopped with
992 if (signo == async_signal)
993 {
994 if (log)
995 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
996
997 // We already stopped with a signal that we wanted
998 // to stop with, so we are done
999 }
1000 else
1001 {
1002 // We stopped with a different signal that the one
1003 // we wanted to stop with, so now we must resume
1004 // with the signal we want
1005 char signal_packet[32];
1006 int signal_packet_len = 0;
1007 signal_packet_len = ::snprintf (signal_packet,
1008 sizeof (signal_packet),
1009 "C%2.2x",
1010 async_signal);
1011
1012 if (log)
1013 log->Printf ("async: stopped with signal %s, resume with %s",
1014 Host::GetSignalAsCString (signo),
1015 Host::GetSignalAsCString (async_signal));
1016
1017 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +00001018 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001019 continue_packet.assign(signal_packet, signal_packet_len);
1020 continue;
1021 }
1022 }
1023 else if (m_async_packet_predicate.GetValue())
1024 {
Greg Clayton5160ce52013-03-27 23:08:40 +00001025 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +00001026
1027 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +00001028 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +00001029 m_async_response.Clear();
1030 if (m_async_packet.empty())
1031 {
Jim Inghama6195b72013-12-18 01:24:33 +00001032 m_async_result = PacketResult::ErrorSendFailed;
1033 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001034 packet_log->Printf ("async: error: empty async packet");
1035
1036 }
1037 else
1038 {
1039 if (packet_log)
1040 packet_log->Printf ("async: sending packet");
1041
Jim Inghama6195b72013-12-18 01:24:33 +00001042 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1043 m_async_packet.size(),
1044 m_async_response,
1045 false);
Greg Clayton2687cd12012-03-29 01:55:41 +00001046 }
1047 // Let the other thread that was trying to send the async
1048 // packet know that the packet has been sent and response is
1049 // ready...
1050 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1051
1052 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +00001053 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +00001054
1055 // Set the continue packet to resume if our interrupt
1056 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +00001057 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001058 {
Greg Claytonf1186de2012-05-24 23:42:14 +00001059 // Reverting this for now as it is causing deadlocks
1060 // in programs (<rdar://problem/11529853>). In the future
1061 // we should check our thread list and "do the right thing"
1062 // for new threads that show up while we stop and run async
1063 // packets. Setting the packet to 'c' to continue all threads
1064 // is the right thing to do 99.99% of the time because if a
1065 // thread was single stepping, and we sent an interrupt, we
1066 // will notice above that we didn't stop due to an interrupt
1067 // but stopped due to stepping and we would _not_ continue.
1068 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +00001069 continue;
1070 }
1071 }
1072 // Stop with signal and thread info
1073 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +00001074 }
Greg Clayton576d8832011-03-22 04:00:09 +00001075 break;
1076
1077 case 'W':
1078 case 'X':
1079 // process exited
1080 state = eStateExited;
1081 break;
1082
1083 case 'O':
1084 // STDOUT
1085 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001086 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001087 std::string inferior_stdout;
1088 inferior_stdout.reserve(response.GetBytesLeft () / 2);
1089 char ch;
1090 while ((ch = response.GetHexU8()) != '\0')
1091 inferior_stdout.append(1, ch);
1092 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1093 }
1094 break;
1095
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001096 case 'A':
1097 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1098 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001099 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001100 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1101 if (m_partial_profile_data.length() > 0)
1102 {
1103 m_partial_profile_data.append(input);
1104 input = m_partial_profile_data;
1105 m_partial_profile_data.clear();
1106 }
1107
1108 size_t found, pos = 0, len = input.length();
1109 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1110 {
1111 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +00001112 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1113 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001114
1115 pos = found + end_delimiter_len;
1116 }
1117
1118 if (pos < len)
1119 {
1120 // Last incomplete chunk.
1121 m_partial_profile_data = input.substr(pos);
1122 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001123 }
1124 break;
1125
Greg Clayton576d8832011-03-22 04:00:09 +00001126 case 'E':
1127 // ERROR
1128 state = eStateInvalid;
1129 break;
1130
1131 default:
1132 if (log)
1133 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1134 state = eStateInvalid;
1135 break;
1136 }
1137 }
1138 }
1139 else
1140 {
1141 if (log)
1142 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
1143 state = eStateInvalid;
1144 }
1145 }
1146 if (log)
1147 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1148 response.SetFilePos(0);
1149 m_private_is_running.SetValue (false, eBroadcastAlways);
1150 m_public_is_running.SetValue (false, eBroadcastAlways);
1151 return state;
1152}
1153
1154bool
1155GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1156{
Greg Clayton2687cd12012-03-29 01:55:41 +00001157 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001158 m_async_signal = signo;
1159 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001160 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001161 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001162 return true;
1163 m_async_signal = -1;
1164 return false;
1165}
1166
Greg Clayton37a0a242012-04-11 00:24:49 +00001167// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001168// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1169// (the expected result), then it will send the halt packet. If it does succeed
1170// then the caller that requested the interrupt will want to keep the sequence
1171// locked down so that no one else can send packets while the caller has control.
1172// This function usually gets called when we are running and need to stop the
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001173// target. It can also be used when we are running and we need to do something
Greg Clayton576d8832011-03-22 04:00:09 +00001174// else (like read/write memory), so we need to interrupt the running process
1175// (gdb remote protocol requires this), and do what we need to do, then resume.
1176
1177bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001178GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001179(
1180 Mutex::Locker& locker,
1181 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001182 bool &timed_out
1183)
1184{
Greg Clayton576d8832011-03-22 04:00:09 +00001185 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001186 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001187
1188 if (IsRunning())
1189 {
1190 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001191 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001192 {
1193 if (log)
1194 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1195 }
1196 else
Greg Clayton576d8832011-03-22 04:00:09 +00001197 {
1198 // Someone has the mutex locked waiting for a response or for the
1199 // inferior to stop, so send the interrupt on the down low...
1200 char ctrl_c = '\x03';
1201 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001202 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001203 if (log)
1204 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001205 if (bytes_written > 0)
1206 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001207 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001208 if (seconds_to_wait_for_stop)
1209 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001210 TimeValue timeout;
1211 if (seconds_to_wait_for_stop)
1212 {
1213 timeout = TimeValue::Now();
1214 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1215 }
Greg Clayton576d8832011-03-22 04:00:09 +00001216 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1217 {
1218 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001219 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001220 return true;
1221 }
1222 else
1223 {
1224 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001225 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001226 }
1227 }
1228 else
1229 {
1230 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001231 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001232 return true;
1233 }
1234 }
1235 else
1236 {
1237 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001238 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001239 }
1240 return false;
1241 }
Greg Clayton576d8832011-03-22 04:00:09 +00001242 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001243 else
1244 {
1245 if (log)
1246 log->Printf ("SendInterrupt () - not running");
1247 }
Greg Clayton576d8832011-03-22 04:00:09 +00001248 return true;
1249}
1250
1251lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001252GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +00001253{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001254 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001255 return m_curr_pid;
1256
1257 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001258 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001259 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +00001260 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001261 // We really got it.
1262 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +00001263 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001264 else
1265 {
Todd Fialae24614f2014-05-14 00:15:32 +00001266 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1267 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1268 // The gdb remote protocol documents $qC as returning the thread id, which newer
1269 // debugserver and lldb-gdbserver stubs return correctly.
1270 StringExtractorGDBRemote response;
1271 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001272 {
Todd Fialae24614f2014-05-14 00:15:32 +00001273 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001274 {
Todd Fialae24614f2014-05-14 00:15:32 +00001275 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001276 {
Todd Fialae24614f2014-05-14 00:15:32 +00001277 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1278 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001279 {
Todd Fialae24614f2014-05-14 00:15:32 +00001280 m_curr_pid_is_valid = eLazyBoolYes;
1281 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001282 }
1283 }
1284 }
1285 }
1286 }
1287
Greg Clayton576d8832011-03-22 04:00:09 +00001288 return LLDB_INVALID_PROCESS_ID;
1289}
1290
1291bool
1292GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1293{
1294 error_str.clear();
1295 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001296 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001297 {
1298 if (response.IsOKResponse())
1299 return true;
1300 if (response.GetChar() == 'E')
1301 {
1302 // A string the describes what failed when launching...
1303 error_str = response.GetStringRef().substr(1);
1304 }
1305 else
1306 {
1307 error_str.assign ("unknown error occurred launching process");
1308 }
1309 }
1310 else
1311 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001312 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001313 }
1314 return false;
1315}
1316
1317int
Greg Claytonfbb76342013-11-20 21:07:01 +00001318GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001319{
Greg Claytonfbb76342013-11-20 21:07:01 +00001320 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001321 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +00001322 std::vector<const char *> argv;
1323 FileSpec exe_file = launch_info.GetExecutableFile();
1324 std::string exe_path;
1325 const char *arg = NULL;
1326 const Args &launch_args = launch_info.GetArguments();
1327 if (exe_file)
Chaoren Lind3173f32015-05-29 19:52:29 +00001328 exe_path = exe_file.GetPath(false);
Greg Claytonfbb76342013-11-20 21:07:01 +00001329 else
1330 {
1331 arg = launch_args.GetArgumentAtIndex(0);
1332 if (arg)
1333 exe_path = arg;
1334 }
1335 if (!exe_path.empty())
1336 {
1337 argv.push_back(exe_path.c_str());
1338 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1339 {
1340 if (arg)
1341 argv.push_back(arg);
1342 }
1343 }
1344 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001345 {
1346 StreamString packet;
1347 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001348 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001349 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001350 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001351 const int arg_len = strlen(arg);
1352 if (i > 0)
1353 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001354 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001355 packet.PutBytesAsRawHex8 (arg, arg_len);
1356 }
1357
1358 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001359 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001360 {
1361 if (response.IsOKResponse())
1362 return 0;
1363 uint8_t error = response.GetError();
1364 if (error)
1365 return error;
1366 }
1367 }
1368 return -1;
1369}
1370
1371int
1372GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1373{
1374 if (name_equal_value && name_equal_value[0])
1375 {
1376 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001377 bool send_hex_encoding = false;
1378 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001379 {
Greg Clayton89600582013-10-10 17:53:50 +00001380 if (isprint(*p))
1381 {
1382 switch (*p)
1383 {
1384 case '$':
1385 case '#':
1386 send_hex_encoding = true;
1387 break;
1388 default:
1389 break;
1390 }
1391 }
1392 else
1393 {
1394 // We have non printable characters, lets hex encode this...
1395 send_hex_encoding = true;
1396 }
1397 }
1398
1399 StringExtractorGDBRemote response;
1400 if (send_hex_encoding)
1401 {
1402 if (m_supports_QEnvironmentHexEncoded)
1403 {
1404 packet.PutCString("QEnvironmentHexEncoded:");
1405 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001406 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001407 {
1408 if (response.IsOKResponse())
1409 return 0;
1410 uint8_t error = response.GetError();
1411 if (error)
1412 return error;
1413 if (response.IsUnsupportedResponse())
1414 m_supports_QEnvironmentHexEncoded = false;
1415 }
1416 }
1417
1418 }
1419 else if (m_supports_QEnvironment)
1420 {
1421 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +00001422 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001423 {
1424 if (response.IsOKResponse())
1425 return 0;
1426 uint8_t error = response.GetError();
1427 if (error)
1428 return error;
1429 if (response.IsUnsupportedResponse())
1430 m_supports_QEnvironment = false;
1431 }
Greg Clayton576d8832011-03-22 04:00:09 +00001432 }
1433 }
1434 return -1;
1435}
1436
Greg Claytonc4103b32011-05-08 04:53:50 +00001437int
1438GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1439{
1440 if (arch && arch[0])
1441 {
1442 StreamString packet;
1443 packet.Printf("QLaunchArch:%s", arch);
1444 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001445 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001446 {
1447 if (response.IsOKResponse())
1448 return 0;
1449 uint8_t error = response.GetError();
1450 if (error)
1451 return error;
1452 }
1453 }
1454 return -1;
1455}
1456
Jason Molendaa3329782014-03-29 18:54:20 +00001457int
1458GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1459{
1460 if (data && *data != '\0')
1461 {
1462 StreamString packet;
1463 packet.Printf("QSetProcessEvent:%s", data);
1464 StringExtractorGDBRemote response;
1465 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1466 {
1467 if (response.IsOKResponse())
1468 {
1469 if (was_supported)
1470 *was_supported = true;
1471 return 0;
1472 }
1473 else if (response.IsUnsupportedResponse())
1474 {
1475 if (was_supported)
1476 *was_supported = false;
1477 return -1;
1478 }
1479 else
1480 {
1481 uint8_t error = response.GetError();
1482 if (was_supported)
1483 *was_supported = true;
1484 if (error)
1485 return error;
1486 }
1487 }
1488 }
1489 return -1;
1490}
1491
Greg Clayton576d8832011-03-22 04:00:09 +00001492bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001493GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1494 uint32_t &minor,
1495 uint32_t &update)
1496{
1497 if (GetHostInfo ())
1498 {
1499 if (m_os_version_major != UINT32_MAX)
1500 {
1501 major = m_os_version_major;
1502 minor = m_os_version_minor;
1503 update = m_os_version_update;
1504 return true;
1505 }
1506 }
1507 return false;
1508}
1509
1510bool
1511GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1512{
1513 if (GetHostInfo ())
1514 {
1515 if (!m_os_build.empty())
1516 {
1517 s = m_os_build;
1518 return true;
1519 }
1520 }
1521 s.clear();
1522 return false;
1523}
1524
1525
1526bool
1527GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1528{
1529 if (GetHostInfo ())
1530 {
1531 if (!m_os_kernel.empty())
1532 {
1533 s = m_os_kernel;
1534 return true;
1535 }
1536 }
1537 s.clear();
1538 return false;
1539}
1540
1541bool
1542GDBRemoteCommunicationClient::GetHostname (std::string &s)
1543{
1544 if (GetHostInfo ())
1545 {
1546 if (!m_hostname.empty())
1547 {
1548 s = m_hostname;
1549 return true;
1550 }
1551 }
1552 s.clear();
1553 return false;
1554}
1555
1556ArchSpec
1557GDBRemoteCommunicationClient::GetSystemArchitecture ()
1558{
1559 if (GetHostInfo ())
1560 return m_host_arch;
1561 return ArchSpec();
1562}
1563
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001564const lldb_private::ArchSpec &
1565GDBRemoteCommunicationClient::GetProcessArchitecture ()
1566{
1567 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1568 GetCurrentProcessInfo ();
1569 return m_process_arch;
1570}
1571
Jason Molendaa3329782014-03-29 18:54:20 +00001572bool
1573GDBRemoteCommunicationClient::GetGDBServerVersion()
1574{
1575 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1576 {
1577 m_gdb_server_name.clear();
1578 m_gdb_server_version = 0;
1579 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1580
1581 StringExtractorGDBRemote response;
1582 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1583 {
1584 if (response.IsNormalResponse())
1585 {
1586 std::string name;
1587 std::string value;
1588 bool success = false;
1589 while (response.GetNameColonValue(name, value))
1590 {
1591 if (name.compare("name") == 0)
1592 {
1593 success = true;
1594 m_gdb_server_name.swap(value);
1595 }
1596 else if (name.compare("version") == 0)
1597 {
1598 size_t dot_pos = value.find('.');
1599 if (dot_pos != std::string::npos)
1600 value[dot_pos] = '\0';
Vince Harron5275aaa2015-01-15 20:08:35 +00001601 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molendaa3329782014-03-29 18:54:20 +00001602 if (version != UINT32_MAX)
1603 {
1604 success = true;
1605 m_gdb_server_version = version;
1606 }
1607 }
1608 }
1609 if (success)
1610 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1611 }
1612 }
1613 }
1614 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1615}
1616
1617const char *
1618GDBRemoteCommunicationClient::GetGDBServerProgramName()
1619{
1620 if (GetGDBServerVersion())
1621 {
1622 if (!m_gdb_server_name.empty())
1623 return m_gdb_server_name.c_str();
1624 }
1625 return NULL;
1626}
1627
1628uint32_t
1629GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1630{
1631 if (GetGDBServerVersion())
1632 return m_gdb_server_version;
1633 return 0;
1634}
Greg Clayton1cb64962011-03-24 04:28:38 +00001635
1636bool
Ewan Crawford78baa192015-05-13 09:18:18 +00001637GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1638{
1639 StringExtractorGDBRemote response;
1640 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1641 return false;
1642
1643 if (!response.IsNormalResponse())
1644 return false;
1645
1646 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1647 tid = response.GetHexMaxU32(true, -1);
1648
1649 return true;
1650}
1651
1652bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001653GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001654{
Todd Fialaaf245d12014-06-30 21:05:18 +00001655 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1656
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001657 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001658 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001659 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001660 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001661 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001662 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001663 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001664 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001665 std::string name;
1666 std::string value;
1667 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1668 uint32_t sub = 0;
1669 std::string arch_name;
1670 std::string os_name;
1671 std::string vendor_name;
1672 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001673 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001674 uint32_t pointer_byte_size = 0;
1675 StringExtractor extractor;
1676 ByteOrder byte_order = eByteOrderInvalid;
1677 uint32_t num_keys_decoded = 0;
1678 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001679 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001680 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001681 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001682 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001683 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001684 if (cpu != LLDB_INVALID_CPUTYPE)
1685 ++num_keys_decoded;
1686 }
1687 else if (name.compare("cpusubtype") == 0)
1688 {
1689 // exception count in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001690 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001691 if (sub != 0)
1692 ++num_keys_decoded;
1693 }
1694 else if (name.compare("arch") == 0)
1695 {
1696 arch_name.swap (value);
1697 ++num_keys_decoded;
1698 }
1699 else if (name.compare("triple") == 0)
1700 {
Greg Clayton44272a42014-09-18 00:18:32 +00001701 extractor.GetStringRef ().swap (value);
1702 extractor.SetFilePos(0);
1703 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00001704 ++num_keys_decoded;
1705 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001706 else if (name.compare ("distribution_id") == 0)
1707 {
1708 extractor.GetStringRef ().swap (value);
1709 extractor.SetFilePos (0);
1710 extractor.GetHexByteString (distribution_id);
1711 ++num_keys_decoded;
1712 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001713 else if (name.compare("os_build") == 0)
1714 {
1715 extractor.GetStringRef().swap(value);
1716 extractor.SetFilePos(0);
1717 extractor.GetHexByteString (m_os_build);
1718 ++num_keys_decoded;
1719 }
1720 else if (name.compare("hostname") == 0)
1721 {
1722 extractor.GetStringRef().swap(value);
1723 extractor.SetFilePos(0);
1724 extractor.GetHexByteString (m_hostname);
1725 ++num_keys_decoded;
1726 }
1727 else if (name.compare("os_kernel") == 0)
1728 {
1729 extractor.GetStringRef().swap(value);
1730 extractor.SetFilePos(0);
1731 extractor.GetHexByteString (m_os_kernel);
1732 ++num_keys_decoded;
1733 }
1734 else if (name.compare("ostype") == 0)
1735 {
1736 os_name.swap (value);
1737 ++num_keys_decoded;
1738 }
1739 else if (name.compare("vendor") == 0)
1740 {
1741 vendor_name.swap(value);
1742 ++num_keys_decoded;
1743 }
1744 else if (name.compare("endian") == 0)
1745 {
1746 ++num_keys_decoded;
1747 if (value.compare("little") == 0)
1748 byte_order = eByteOrderLittle;
1749 else if (value.compare("big") == 0)
1750 byte_order = eByteOrderBig;
1751 else if (value.compare("pdp") == 0)
1752 byte_order = eByteOrderPDP;
1753 else
1754 --num_keys_decoded;
1755 }
1756 else if (name.compare("ptrsize") == 0)
1757 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001758 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001759 if (pointer_byte_size != 0)
1760 ++num_keys_decoded;
1761 }
1762 else if (name.compare("os_version") == 0)
1763 {
1764 Args::StringToVersion (value.c_str(),
1765 m_os_version_major,
1766 m_os_version_minor,
1767 m_os_version_update);
1768 if (m_os_version_major != UINT32_MAX)
1769 ++num_keys_decoded;
1770 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001771 else if (name.compare("watchpoint_exceptions_received") == 0)
1772 {
1773 ++num_keys_decoded;
1774 if (strcmp(value.c_str(),"before") == 0)
1775 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1776 else if (strcmp(value.c_str(),"after") == 0)
1777 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1778 else
1779 --num_keys_decoded;
1780 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001781 else if (name.compare("default_packet_timeout") == 0)
1782 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001783 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001784 if (m_default_packet_timeout > 0)
1785 {
1786 SetPacketTimeout(m_default_packet_timeout);
1787 ++num_keys_decoded;
1788 }
1789 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001790
Greg Clayton32e0a752011-03-30 18:16:51 +00001791 }
1792
1793 if (num_keys_decoded > 0)
1794 m_qHostInfo_is_valid = eLazyBoolYes;
1795
1796 if (triple.empty())
1797 {
1798 if (arch_name.empty())
1799 {
1800 if (cpu != LLDB_INVALID_CPUTYPE)
1801 {
1802 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1803 if (pointer_byte_size)
1804 {
1805 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1806 }
1807 if (byte_order != eByteOrderInvalid)
1808 {
1809 assert (byte_order == m_host_arch.GetByteOrder());
1810 }
Greg Clayton70512312012-05-08 01:45:38 +00001811
1812 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1813 {
1814 switch (m_host_arch.GetMachine())
1815 {
Todd Fialad8eaa172014-07-23 14:37:35 +00001816 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00001817 case llvm::Triple::arm:
1818 case llvm::Triple::thumb:
1819 os_name = "ios";
1820 break;
1821 default:
1822 os_name = "macosx";
1823 break;
1824 }
1825 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001826 if (!vendor_name.empty())
1827 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1828 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001829 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001830
1831 }
1832 }
1833 else
1834 {
1835 std::string triple;
1836 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001837 if (!vendor_name.empty() || !os_name.empty())
1838 {
1839 triple += '-';
1840 if (vendor_name.empty())
1841 triple += "unknown";
1842 else
1843 triple += vendor_name;
1844 triple += '-';
1845 if (os_name.empty())
1846 triple += "unknown";
1847 else
1848 triple += os_name;
1849 }
1850 m_host_arch.SetTriple (triple.c_str());
1851
1852 llvm::Triple &host_triple = m_host_arch.GetTriple();
1853 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1854 {
1855 switch (m_host_arch.GetMachine())
1856 {
Todd Fialad8eaa172014-07-23 14:37:35 +00001857 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00001858 case llvm::Triple::arm:
1859 case llvm::Triple::thumb:
1860 host_triple.setOS(llvm::Triple::IOS);
1861 break;
1862 default:
1863 host_triple.setOS(llvm::Triple::MacOSX);
1864 break;
1865 }
1866 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001867 if (pointer_byte_size)
1868 {
1869 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1870 }
1871 if (byte_order != eByteOrderInvalid)
1872 {
1873 assert (byte_order == m_host_arch.GetByteOrder());
1874 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001875
Greg Clayton1cb64962011-03-24 04:28:38 +00001876 }
1877 }
1878 else
1879 {
Greg Clayton70512312012-05-08 01:45:38 +00001880 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001881 if (pointer_byte_size)
1882 {
1883 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1884 }
1885 if (byte_order != eByteOrderInvalid)
1886 {
1887 assert (byte_order == m_host_arch.GetByteOrder());
1888 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001889
1890 if (log)
1891 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 +00001892 }
1893 if (!distribution_id.empty ())
1894 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00001895 }
Greg Clayton576d8832011-03-22 04:00:09 +00001896 }
1897 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001898 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001899}
1900
1901int
1902GDBRemoteCommunicationClient::SendAttach
1903(
1904 lldb::pid_t pid,
1905 StringExtractorGDBRemote& response
1906)
1907{
1908 if (pid != LLDB_INVALID_PROCESS_ID)
1909 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001910 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001911 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001912 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00001913 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001914 {
1915 if (response.IsErrorResponse())
1916 return response.GetError();
1917 return 0;
1918 }
1919 }
1920 return -1;
1921}
1922
Vince Harrone0be4252015-02-06 18:32:57 +00001923int
1924GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
1925{
1926 StreamString packet;
1927 packet.PutCString("I");
1928 packet.PutBytesAsRawHex8(data, data_len);
1929 StringExtractorGDBRemote response;
1930 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1931 {
1932 return 0;
1933 }
1934 return response.GetError();
1935
1936}
1937
Greg Clayton576d8832011-03-22 04:00:09 +00001938const lldb_private::ArchSpec &
1939GDBRemoteCommunicationClient::GetHostArchitecture ()
1940{
Greg Clayton32e0a752011-03-30 18:16:51 +00001941 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001942 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001943 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001944}
1945
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001946uint32_t
1947GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1948{
1949 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1950 GetHostInfo ();
1951 return m_default_packet_timeout;
1952}
1953
Greg Clayton576d8832011-03-22 04:00:09 +00001954addr_t
1955GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
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 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001962 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001963 permissions & lldb::ePermissionsReadable ? "r" : "",
1964 permissions & lldb::ePermissionsWritable ? "w" : "",
1965 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001966 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001967 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001968 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001969 {
Todd Fialaf105f582014-06-21 00:48:09 +00001970 if (response.IsUnsupportedResponse())
1971 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1972 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001973 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1974 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001975 else
1976 {
1977 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1978 }
Greg Clayton576d8832011-03-22 04:00:09 +00001979 }
1980 return LLDB_INVALID_ADDRESS;
1981}
1982
1983bool
1984GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1985{
Greg Clayton70b57652011-05-15 01:25:55 +00001986 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001987 {
Greg Clayton70b57652011-05-15 01:25:55 +00001988 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001989 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001990 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001991 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001992 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001993 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001994 {
Todd Fialaf105f582014-06-21 00:48:09 +00001995 if (response.IsUnsupportedResponse())
1996 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1997 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001998 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001999 }
2000 else
2001 {
2002 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00002003 }
Greg Clayton576d8832011-03-22 04:00:09 +00002004 }
2005 return false;
2006}
2007
Jim Inghamacff8952013-05-02 00:27:30 +00002008Error
2009GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00002010{
Jim Inghamacff8952013-05-02 00:27:30 +00002011 Error error;
2012
2013 if (keep_stopped)
2014 {
2015 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
2016 {
2017 char packet[64];
2018 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002019 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00002020 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002021 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002022 {
2023 m_supports_detach_stay_stopped = eLazyBoolYes;
2024 }
2025 else
2026 {
2027 m_supports_detach_stay_stopped = eLazyBoolNo;
2028 }
2029 }
2030
2031 if (m_supports_detach_stay_stopped == eLazyBoolNo)
2032 {
2033 error.SetErrorString("Stays stopped not supported by this target.");
2034 return error;
2035 }
2036 else
2037 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002038 StringExtractorGDBRemote response;
2039 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002040 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002041 error.SetErrorString ("Sending extended disconnect packet failed.");
2042 }
2043 }
2044 else
2045 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002046 StringExtractorGDBRemote response;
2047 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002048 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002049 error.SetErrorString ("Sending disconnect packet failed.");
2050 }
2051 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00002052}
2053
Greg Clayton46fb5582011-11-18 07:03:08 +00002054Error
2055GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2056 lldb_private::MemoryRegionInfo &region_info)
2057{
2058 Error error;
2059 region_info.Clear();
2060
2061 if (m_supports_memory_region_info != eLazyBoolNo)
2062 {
2063 m_supports_memory_region_info = eLazyBoolYes;
2064 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002065 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002066 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00002067 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002068 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00002069 {
2070 std::string name;
2071 std::string value;
2072 addr_t addr_value;
2073 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00002074 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00002075 while (success && response.GetNameColonValue(name, value))
2076 {
2077 if (name.compare ("start") == 0)
2078 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002079 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002080 if (success)
2081 region_info.GetRange().SetRangeBase(addr_value);
2082 }
2083 else if (name.compare ("size") == 0)
2084 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002085 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002086 if (success)
2087 region_info.GetRange().SetByteSize (addr_value);
2088 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002089 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00002090 {
Jason Molendacb349ee2011-12-13 05:39:38 +00002091 saw_permissions = true;
2092 if (region_info.GetRange().Contains (addr))
2093 {
2094 if (value.find('r') != std::string::npos)
2095 region_info.SetReadable (MemoryRegionInfo::eYes);
2096 else
2097 region_info.SetReadable (MemoryRegionInfo::eNo);
2098
2099 if (value.find('w') != std::string::npos)
2100 region_info.SetWritable (MemoryRegionInfo::eYes);
2101 else
2102 region_info.SetWritable (MemoryRegionInfo::eNo);
2103
2104 if (value.find('x') != std::string::npos)
2105 region_info.SetExecutable (MemoryRegionInfo::eYes);
2106 else
2107 region_info.SetExecutable (MemoryRegionInfo::eNo);
2108 }
2109 else
2110 {
2111 // The reported region does not contain this address -- we're looking at an unmapped page
2112 region_info.SetReadable (MemoryRegionInfo::eNo);
2113 region_info.SetWritable (MemoryRegionInfo::eNo);
2114 region_info.SetExecutable (MemoryRegionInfo::eNo);
2115 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002116 }
2117 else if (name.compare ("error") == 0)
2118 {
2119 StringExtractorGDBRemote name_extractor;
2120 // Swap "value" over into "name_extractor"
2121 name_extractor.GetStringRef().swap(value);
2122 // Now convert the HEX bytes into a string value
2123 name_extractor.GetHexByteString (value);
2124 error.SetErrorString(value.c_str());
2125 }
2126 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002127
2128 // We got a valid address range back but no permissions -- which means this is an unmapped page
2129 if (region_info.GetRange().IsValid() && saw_permissions == false)
2130 {
2131 region_info.SetReadable (MemoryRegionInfo::eNo);
2132 region_info.SetWritable (MemoryRegionInfo::eNo);
2133 region_info.SetExecutable (MemoryRegionInfo::eNo);
2134 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002135 }
2136 else
2137 {
2138 m_supports_memory_region_info = eLazyBoolNo;
2139 }
2140 }
2141
2142 if (m_supports_memory_region_info == eLazyBoolNo)
2143 {
2144 error.SetErrorString("qMemoryRegionInfo is not supported");
2145 }
2146 if (error.Fail())
2147 region_info.Clear();
2148 return error;
2149
2150}
2151
Johnny Chen64637202012-05-23 21:09:52 +00002152Error
2153GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2154{
2155 Error error;
2156
2157 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2158 {
2159 num = m_num_supported_hardware_watchpoints;
2160 return error;
2161 }
2162
2163 // Set num to 0 first.
2164 num = 0;
2165 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2166 {
2167 char packet[64];
2168 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002169 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00002170 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002171 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00002172 {
2173 m_supports_watchpoint_support_info = eLazyBoolYes;
2174 std::string name;
2175 std::string value;
2176 while (response.GetNameColonValue(name, value))
2177 {
2178 if (name.compare ("num") == 0)
2179 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002180 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
Johnny Chen64637202012-05-23 21:09:52 +00002181 m_num_supported_hardware_watchpoints = num;
2182 }
2183 }
2184 }
2185 else
2186 {
2187 m_supports_watchpoint_support_info = eLazyBoolNo;
2188 }
2189 }
2190
2191 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2192 {
2193 error.SetErrorString("qWatchpointSupportInfo is not supported");
2194 }
2195 return error;
2196
2197}
Greg Clayton46fb5582011-11-18 07:03:08 +00002198
Enrico Granataf04a2192012-07-13 23:18:48 +00002199lldb_private::Error
2200GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2201{
2202 Error error(GetWatchpointSupportInfo(num));
2203 if (error.Success())
2204 error = GetWatchpointsTriggerAfterInstruction(after);
2205 return error;
2206}
2207
2208lldb_private::Error
2209GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
2210{
2211 Error error;
2212
2213 // we assume watchpoints will happen after running the relevant opcode
2214 // and we only want to override this behavior if we have explicitly
2215 // received a qHostInfo telling us otherwise
2216 if (m_qHostInfo_is_valid != eLazyBoolYes)
2217 after = true;
2218 else
2219 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
2220 return error;
2221}
2222
Greg Clayton576d8832011-03-22 04:00:09 +00002223int
Chaoren Lind3173f32015-05-29 19:52:29 +00002224GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002225{
Chaoren Lind3173f32015-05-29 19:52:29 +00002226 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002227 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002228 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002229 StreamString packet;
2230 packet.PutCString("QSetSTDIN:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002231 packet.PutCStringAsRawHex8(path.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00002232
2233 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002234 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002235 {
2236 if (response.IsOKResponse())
2237 return 0;
2238 uint8_t error = response.GetError();
2239 if (error)
2240 return error;
2241 }
2242 }
2243 return -1;
2244}
2245
2246int
Chaoren Lind3173f32015-05-29 19:52:29 +00002247GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002248{
Chaoren Lind3173f32015-05-29 19:52:29 +00002249 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002250 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002251 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002252 StreamString packet;
2253 packet.PutCString("QSetSTDOUT:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002254 packet.PutCStringAsRawHex8(path.c_str());
2255
Greg Clayton576d8832011-03-22 04:00:09 +00002256 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002257 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002258 {
2259 if (response.IsOKResponse())
2260 return 0;
2261 uint8_t error = response.GetError();
2262 if (error)
2263 return error;
2264 }
2265 }
2266 return -1;
2267}
2268
2269int
Chaoren Lind3173f32015-05-29 19:52:29 +00002270GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002271{
Chaoren Lind3173f32015-05-29 19:52:29 +00002272 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002273 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002274 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002275 StreamString packet;
2276 packet.PutCString("QSetSTDERR:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002277 packet.PutCStringAsRawHex8(path.c_str());
2278
Greg Clayton576d8832011-03-22 04:00:09 +00002279 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002280 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002281 {
2282 if (response.IsOKResponse())
2283 return 0;
2284 uint8_t error = response.GetError();
2285 if (error)
2286 return error;
2287 }
2288 }
2289 return -1;
2290}
2291
Greg Claytonfbb76342013-11-20 21:07:01 +00002292bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002293GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
Greg Claytonfbb76342013-11-20 21:07:01 +00002294{
2295 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002296 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002297 {
2298 if (response.IsUnsupportedResponse())
2299 return false;
2300 if (response.IsErrorResponse())
2301 return false;
Chaoren Lind3173f32015-05-29 19:52:29 +00002302 std::string cwd;
2303 response.GetHexByteString(cwd);
2304 working_dir.SetFile(cwd, false);
Greg Claytonfbb76342013-11-20 21:07:01 +00002305 return !cwd.empty();
2306 }
2307 return false;
2308}
2309
Greg Clayton576d8832011-03-22 04:00:09 +00002310int
Chaoren Lind3173f32015-05-29 19:52:29 +00002311GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002312{
Chaoren Lind3173f32015-05-29 19:52:29 +00002313 if (working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002314 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002315 std::string path{working_dir.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002316 StreamString packet;
2317 packet.PutCString("QSetWorkingDir:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002318 packet.PutCStringAsRawHex8(path.c_str());
2319
Greg Clayton576d8832011-03-22 04:00:09 +00002320 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002321 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002322 {
2323 if (response.IsOKResponse())
2324 return 0;
2325 uint8_t error = response.GetError();
2326 if (error)
2327 return error;
2328 }
2329 }
2330 return -1;
2331}
2332
2333int
2334GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2335{
Greg Clayton32e0a752011-03-30 18:16:51 +00002336 char packet[32];
2337 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002338 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002339 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002340 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002341 {
2342 if (response.IsOKResponse())
2343 return 0;
2344 uint8_t error = response.GetError();
2345 if (error)
2346 return error;
2347 }
2348 return -1;
2349}
Greg Clayton32e0a752011-03-30 18:16:51 +00002350
Jim Ingham106d0282014-06-25 02:32:56 +00002351int
2352GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2353{
2354 char packet[32];
2355 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2356 assert (packet_len < (int)sizeof(packet));
2357 StringExtractorGDBRemote response;
2358 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2359 {
2360 if (response.IsOKResponse())
2361 return 0;
2362 uint8_t error = response.GetError();
2363 if (error)
2364 return error;
2365 }
2366 return -1;
2367}
2368
2369
Greg Clayton32e0a752011-03-30 18:16:51 +00002370bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002371GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002372{
2373 if (response.IsNormalResponse())
2374 {
2375 std::string name;
2376 std::string value;
2377 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002378
2379 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2380 uint32_t sub = 0;
2381 std::string vendor;
2382 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002383
2384 while (response.GetNameColonValue(name, value))
2385 {
2386 if (name.compare("pid") == 0)
2387 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002388 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002389 }
2390 else if (name.compare("ppid") == 0)
2391 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002392 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002393 }
2394 else if (name.compare("uid") == 0)
2395 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002396 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002397 }
2398 else if (name.compare("euid") == 0)
2399 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002400 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002401 }
2402 else if (name.compare("gid") == 0)
2403 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002404 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002405 }
2406 else if (name.compare("egid") == 0)
2407 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002408 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002409 }
2410 else if (name.compare("triple") == 0)
2411 {
Greg Clayton44272a42014-09-18 00:18:32 +00002412 StringExtractor extractor;
2413 extractor.GetStringRef().swap(value);
2414 extractor.SetFilePos(0);
2415 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002416 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002417 }
2418 else if (name.compare("name") == 0)
2419 {
2420 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002421 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002422 // control the characters in a process name
2423 extractor.GetStringRef().swap(value);
2424 extractor.SetFilePos(0);
2425 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002426 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002427 }
Jason Molenda89c37492014-01-27 22:23:20 +00002428 else if (name.compare("cputype") == 0)
2429 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002430 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002431 }
2432 else if (name.compare("cpusubtype") == 0)
2433 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002434 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002435 }
2436 else if (name.compare("vendor") == 0)
2437 {
2438 vendor = value;
2439 }
2440 else if (name.compare("ostype") == 0)
2441 {
2442 os_type = value;
2443 }
2444 }
2445
2446 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2447 {
2448 if (vendor == "apple")
2449 {
2450 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2451 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2452 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2453 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002454 }
2455
2456 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2457 return true;
2458 }
2459 return false;
2460}
2461
2462bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002463GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002464{
2465 process_info.Clear();
2466
2467 if (m_supports_qProcessInfoPID)
2468 {
2469 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002470 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002471 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002472 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002473 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002474 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002475 return DecodeProcessInfoResponse (response, process_info);
2476 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002477 else
2478 {
2479 m_supports_qProcessInfoPID = false;
2480 return false;
2481 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002482 }
2483 return false;
2484}
2485
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002486bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002487GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002488{
Todd Fiala3daa1762014-09-15 16:01:29 +00002489 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2490
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002491 if (allow_lazy)
2492 {
2493 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2494 return true;
2495 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2496 return false;
2497 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002498
2499 GetHostInfo ();
2500
2501 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002502 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002503 {
2504 if (response.IsNormalResponse())
2505 {
2506 std::string name;
2507 std::string value;
2508 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2509 uint32_t sub = 0;
2510 std::string arch_name;
2511 std::string os_name;
2512 std::string vendor_name;
2513 std::string triple;
2514 uint32_t pointer_byte_size = 0;
2515 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002516 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002517 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002518 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002519 while (response.GetNameColonValue(name, value))
2520 {
2521 if (name.compare("cputype") == 0)
2522 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002523 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002524 if (cpu != LLDB_INVALID_CPUTYPE)
2525 ++num_keys_decoded;
2526 }
2527 else if (name.compare("cpusubtype") == 0)
2528 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002529 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002530 if (sub != 0)
2531 ++num_keys_decoded;
2532 }
Todd Fialac540dd02014-08-26 18:21:02 +00002533 else if (name.compare("triple") == 0)
2534 {
Greg Clayton44272a42014-09-18 00:18:32 +00002535 StringExtractor extractor;
2536 extractor.GetStringRef().swap(value);
2537 extractor.SetFilePos(0);
2538 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002539 ++num_keys_decoded;
2540 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002541 else if (name.compare("ostype") == 0)
2542 {
2543 os_name.swap (value);
2544 ++num_keys_decoded;
2545 }
2546 else if (name.compare("vendor") == 0)
2547 {
2548 vendor_name.swap(value);
2549 ++num_keys_decoded;
2550 }
2551 else if (name.compare("endian") == 0)
2552 {
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002553 ++num_keys_decoded;
2554 if (value.compare("little") == 0)
2555 byte_order = eByteOrderLittle;
2556 else if (value.compare("big") == 0)
2557 byte_order = eByteOrderBig;
2558 else if (value.compare("pdp") == 0)
2559 byte_order = eByteOrderPDP;
2560 else
2561 --num_keys_decoded;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002562 }
2563 else if (name.compare("ptrsize") == 0)
2564 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002565 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002566 if (pointer_byte_size != 0)
2567 ++num_keys_decoded;
2568 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002569 else if (name.compare("pid") == 0)
2570 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002571 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002572 if (pid != LLDB_INVALID_PROCESS_ID)
2573 ++num_keys_decoded;
2574 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002575 }
2576 if (num_keys_decoded > 0)
2577 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002578 if (pid != LLDB_INVALID_PROCESS_ID)
2579 {
2580 m_curr_pid_is_valid = eLazyBoolYes;
2581 m_curr_pid = pid;
2582 }
Todd Fialac540dd02014-08-26 18:21:02 +00002583
2584 // Set the ArchSpec from the triple if we have it.
2585 if (!triple.empty ())
2586 {
2587 m_process_arch.SetTriple (triple.c_str ());
2588 if (pointer_byte_size)
2589 {
2590 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2591 }
2592 }
2593 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002594 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002595 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2596
2597 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2598 switch (triple.getObjectFormat()) {
2599 case llvm::Triple::MachO:
2600 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2601 break;
2602 case llvm::Triple::ELF:
2603 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2604 break;
2605 case llvm::Triple::COFF:
2606 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2607 break;
2608 case llvm::Triple::UnknownObjectFormat:
2609 if (log)
2610 log->Printf("error: failed to determine target architecture");
2611 return false;
2612 }
2613
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002614 if (pointer_byte_size)
2615 {
2616 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2617 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002618 if (byte_order != eByteOrderInvalid)
2619 {
2620 assert (byte_order == m_process_arch.GetByteOrder());
2621 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002622 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002623 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002624 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2625 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002626 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002627 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002628 }
2629 }
2630 else
2631 {
2632 m_qProcessInfo_is_valid = eLazyBoolNo;
2633 }
2634
2635 return false;
2636}
2637
2638
Greg Clayton32e0a752011-03-30 18:16:51 +00002639uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002640GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2641 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002642{
2643 process_infos.Clear();
2644
2645 if (m_supports_qfProcessInfo)
2646 {
2647 StreamString packet;
2648 packet.PutCString ("qfProcessInfo");
2649 if (!match_info.MatchAllProcesses())
2650 {
2651 packet.PutChar (':');
2652 const char *name = match_info.GetProcessInfo().GetName();
2653 bool has_name_match = false;
2654 if (name && name[0])
2655 {
2656 has_name_match = true;
2657 NameMatchType name_match_type = match_info.GetNameMatchType();
2658 switch (name_match_type)
2659 {
2660 case eNameMatchIgnore:
2661 has_name_match = false;
2662 break;
2663
2664 case eNameMatchEquals:
2665 packet.PutCString ("name_match:equals;");
2666 break;
2667
2668 case eNameMatchContains:
2669 packet.PutCString ("name_match:contains;");
2670 break;
2671
2672 case eNameMatchStartsWith:
2673 packet.PutCString ("name_match:starts_with;");
2674 break;
2675
2676 case eNameMatchEndsWith:
2677 packet.PutCString ("name_match:ends_with;");
2678 break;
2679
2680 case eNameMatchRegularExpression:
2681 packet.PutCString ("name_match:regex;");
2682 break;
2683 }
2684 if (has_name_match)
2685 {
2686 packet.PutCString ("name:");
2687 packet.PutBytesAsRawHex8(name, ::strlen(name));
2688 packet.PutChar (';');
2689 }
2690 }
2691
2692 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002693 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002694 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002695 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002696 if (match_info.GetProcessInfo().UserIDIsValid())
2697 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2698 if (match_info.GetProcessInfo().GroupIDIsValid())
2699 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002700 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2701 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2702 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2703 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2704 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2705 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2706 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2707 {
2708 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2709 const llvm::Triple &triple = match_arch.GetTriple();
2710 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00002711 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002712 packet.PutChar (';');
2713 }
2714 }
2715 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00002716 // Increase timeout as the first qfProcessInfo packet takes a long time
2717 // on Android. The value of 1min was arrived at empirically.
2718 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00002719 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002720 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002721 do
2722 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002723 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002724 if (!DecodeProcessInfoResponse (response, process_info))
2725 break;
2726 process_infos.Append(process_info);
2727 response.GetStringRef().clear();
2728 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00002729 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00002730 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002731 else
2732 {
2733 m_supports_qfProcessInfo = false;
2734 return 0;
2735 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002736 }
2737 return process_infos.GetSize();
2738
2739}
2740
2741bool
2742GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2743{
2744 if (m_supports_qUserName)
2745 {
2746 char packet[32];
2747 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002748 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002749 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002750 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002751 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002752 if (response.IsNormalResponse())
2753 {
2754 // Make sure we parsed the right number of characters. The response is
2755 // the hex encoded user name and should make up the entire packet.
2756 // If there are any non-hex ASCII bytes, the length won't match below..
2757 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2758 return true;
2759 }
2760 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002761 else
2762 {
2763 m_supports_qUserName = false;
2764 return false;
2765 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002766 }
2767 return false;
2768
2769}
2770
2771bool
2772GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2773{
2774 if (m_supports_qGroupName)
2775 {
2776 char packet[32];
2777 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002778 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002779 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002780 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002781 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002782 if (response.IsNormalResponse())
2783 {
2784 // Make sure we parsed the right number of characters. The response is
2785 // the hex encoded group name and should make up the entire packet.
2786 // If there are any non-hex ASCII bytes, the length won't match below..
2787 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2788 return true;
2789 }
2790 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002791 else
2792 {
2793 m_supports_qGroupName = false;
2794 return false;
2795 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002796 }
2797 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002798}
Greg Clayton32e0a752011-03-30 18:16:51 +00002799
Ewan Crawford78baa192015-05-13 09:18:18 +00002800bool
2801GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
2802{
2803 // Form non-stop packet request
2804 char packet[32];
2805 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2806 assert(packet_len < (int)sizeof(packet));
2807
2808 StringExtractorGDBRemote response;
2809 // Send to target
2810 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2811 if (response.IsOKResponse())
2812 return true;
2813
2814 // Failed or not supported
2815 return false;
2816
2817}
2818
Greg Claytone034a042015-05-21 20:52:06 +00002819static void
2820MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
2821{
2822 packet.Clear();
2823 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2824 uint32_t bytes_left = send_size;
2825 while (bytes_left > 0)
2826 {
2827 if (bytes_left >= 26)
2828 {
2829 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2830 bytes_left -= 26;
2831 }
2832 else
2833 {
2834 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2835 bytes_left = 0;
2836 }
2837 }
2838}
2839
2840template<typename T>
2841T calculate_standard_deviation(const std::vector<T> &v)
2842{
2843 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
2844 T mean = sum / (T)v.size();
2845 T accum = T(0);
2846 std::for_each (std::begin(v), std::end(v), [&](const T d) {
2847 T delta = d - mean;
2848 accum += delta * delta;
2849 });
2850
2851 T stdev = sqrt(accum / (v.size()-1));
2852 return stdev;
2853}
2854
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002855void
Greg Claytone034a042015-05-21 20:52:06 +00002856GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets, uint32_t max_send, uint32_t max_recv, bool json, Stream &strm)
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002857{
2858 uint32_t i;
2859 TimeValue start_time, end_time;
2860 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002861 if (SendSpeedTestPacket (0, 0))
2862 {
Greg Claytone034a042015-05-21 20:52:06 +00002863 StreamString packet;
2864 if (json)
2865 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
2866 else
2867 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
2868 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00002869
Greg Claytone034a042015-05-21 20:52:06 +00002870 uint32_t result_idx = 0;
2871 uint32_t send_size;
2872 std::vector<float> packet_times;
2873
2874 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
2875 {
2876 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
2877 {
2878 MakeSpeedTestPacket (packet, send_size, recv_size);
2879
2880 packet_times.clear();
2881 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00002882 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00002883 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00002884 {
Greg Claytone034a042015-05-21 20:52:06 +00002885 TimeValue packet_start_time = TimeValue::Now();
2886 StringExtractorGDBRemote response;
2887 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2888 TimeValue packet_end_time = TimeValue::Now();
2889 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
2890 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002891 }
2892 end_time = TimeValue::Now();
2893 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00002894
2895 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2896 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
2897 float average_ms_per_packet = total_ms / num_packets;
2898 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
2899 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00002900 {
Greg Claytone034a042015-05-21 20:52:06 +00002901 strm.Printf ("%s\n {\"send_size\" : %6" PRIu32 ", \"recv_size\" : %6" PRIu32 ", \"total_time_nsec\" : %12" PRIu64 ", \"standard_deviation_nsec\" : %9" PRIu64 " }", result_idx > 0 ? "," : "", send_size, recv_size, total_time_nsec, (uint64_t)standard_deviation);
2902 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00002903 }
2904 else
2905 {
Greg Claytone034a042015-05-21 20:52:06 +00002906 strm.Printf ("qSpeedTest(send=%-7u, recv=%-7u) in %" PRIu64 ".%9.9" PRIu64 " sec for %9.2f packets/sec (%10.6f ms per packet) with standard deviation of %10.6f ms\n",
2907 send_size,
2908 recv_size,
2909 total_time_nsec / TimeValue::NanoSecPerSec,
2910 total_time_nsec % TimeValue::NanoSecPerSec,
2911 packets_per_second,
2912 average_ms_per_packet,
2913 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00002914 }
Greg Claytone034a042015-05-21 20:52:06 +00002915 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002916 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002917 }
Greg Claytone034a042015-05-21 20:52:06 +00002918
2919 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
2920
2921 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
2922 if (json)
2923 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
2924 else
2925 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
2926 strm.Flush();
2927 send_size = 0;
2928 result_idx = 0;
2929 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
2930 {
2931 MakeSpeedTestPacket (packet, send_size, recv_size);
2932
2933 // If we have a receive size, test how long it takes to receive 4MB of data
2934 if (recv_size > 0)
2935 {
2936 start_time = TimeValue::Now();
2937 uint32_t bytes_read = 0;
2938 uint32_t packet_count = 0;
2939 while (bytes_read < k_recv_amount)
2940 {
2941 StringExtractorGDBRemote response;
2942 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2943 bytes_read += recv_size;
2944 ++packet_count;
2945 }
2946 end_time = TimeValue::Now();
2947 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2948 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2949 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2950 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
2951 float average_ms_per_packet = total_ms / packet_count;
2952
2953 if (json)
2954 {
2955 strm.Printf ("%s\n {\"send_size\" : %6" PRIu32 ", \"recv_size\" : %6" PRIu32 ", \"total_time_nsec\" : %12" PRIu64 " }", result_idx > 0 ? "," : "", send_size, recv_size, total_time_nsec);
2956 ++result_idx;
2957 }
2958 else
2959 {
2960 strm.Printf ("qSpeedTest(send=%-7u, recv=%-7u) %6u packets needed to receive %2.1fMB in %" PRIu64 ".%9.9" PRIu64 " sec for %f MB/sec for %9.2f packets/sec (%10.6f ms per packet)\n",
2961 send_size,
2962 recv_size,
2963 packet_count,
2964 k_recv_amount_mb,
2965 total_time_nsec / TimeValue::NanoSecPerSec,
2966 total_time_nsec % TimeValue::NanoSecPerSec,
2967 mb_second,
2968 packets_per_second,
2969 average_ms_per_packet);
2970 }
2971 strm.Flush();
2972 }
2973 }
2974 if (json)
2975 strm.Printf("\n ]\n }\n}\n");
2976 else
2977 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002978 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002979}
2980
2981bool
2982GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2983{
2984 StreamString packet;
2985 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2986 uint32_t bytes_left = send_size;
2987 while (bytes_left > 0)
2988 {
2989 if (bytes_left >= 26)
2990 {
2991 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2992 bytes_left -= 26;
2993 }
2994 else
2995 {
2996 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2997 bytes_left = 0;
2998 }
2999 }
3000
3001 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003002 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00003003}
Greg Clayton8b82f082011-04-12 05:54:46 +00003004
3005uint16_t
Greg Claytondbf04572013-12-04 19:40:33 +00003006GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
Greg Clayton8b82f082011-04-12 05:54:46 +00003007{
Daniel Maleae0f8f572013-08-26 23:57:52 +00003008 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00003009 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003010 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00003011 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003012 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00003013 if (remote_accept_hostname && remote_accept_hostname[0])
3014 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003015 else
3016 {
Zachary Turner97a14e62014-08-19 17:18:29 +00003017 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00003018 {
3019 // Make the GDB server we launch only accept connections from this host
3020 stream.Printf("host:%s;", hostname.c_str());
3021 }
3022 else
3023 {
3024 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
3025 stream.Printf("host:*;");
3026 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003027 }
3028 const char *packet = stream.GetData();
3029 int packet_len = stream.GetSize();
3030
Vince Harron1b5a74e2015-01-21 22:42:49 +00003031 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00003032 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
3033
3034 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003035 {
3036 std::string name;
3037 std::string value;
3038 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00003039 while (response.GetNameColonValue(name, value))
3040 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00003041 if (name.compare("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003042 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003043 else if (name.compare("pid") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003044 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00003045 }
3046 return port;
3047 }
3048 return 0;
3049}
3050
3051bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00003052GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
3053{
3054 StreamString stream;
3055 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
3056 const char *packet = stream.GetData();
3057 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00003058
Daniel Maleae0f8f572013-08-26 23:57:52 +00003059 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003060 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003061 {
3062 if (response.IsOKResponse())
3063 return true;
3064 }
3065 return false;
3066}
3067
3068bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003069GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003070{
3071 if (m_curr_tid == tid)
3072 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003073
Greg Clayton8b82f082011-04-12 05:54:46 +00003074 char packet[32];
3075 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003076 if (tid == UINT64_MAX)
3077 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003078 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003079 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003080 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003081 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003082 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003083 {
3084 if (response.IsOKResponse())
3085 {
3086 m_curr_tid = tid;
3087 return true;
3088 }
3089 }
3090 return false;
3091}
3092
3093bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003094GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003095{
3096 if (m_curr_tid_run == tid)
3097 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003098
Greg Clayton8b82f082011-04-12 05:54:46 +00003099 char packet[32];
3100 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003101 if (tid == UINT64_MAX)
3102 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003103 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003104 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3105
Andy Gibbsa297a972013-06-19 19:04:53 +00003106 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003107 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003108 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003109 {
3110 if (response.IsOKResponse())
3111 {
3112 m_curr_tid_run = tid;
3113 return true;
3114 }
3115 }
3116 return false;
3117}
3118
3119bool
3120GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3121{
Greg Clayton3dedae12013-12-06 21:45:27 +00003122 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003123 return response.IsNormalResponse();
3124 return false;
3125}
3126
3127bool
Greg Claytonf402f782012-10-13 02:11:55 +00003128GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00003129{
3130 if (m_supports_qThreadStopInfo)
3131 {
3132 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00003133 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003134 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00003135 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003136 {
Greg Claytonef8180a2013-10-15 00:14:28 +00003137 if (response.IsUnsupportedResponse())
3138 m_supports_qThreadStopInfo = false;
3139 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003140 return true;
3141 else
3142 return false;
3143 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003144 else
3145 {
3146 m_supports_qThreadStopInfo = false;
3147 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003148 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003149 return false;
3150}
3151
3152
3153uint8_t
3154GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
3155{
Todd Fiala616b8272014-10-09 00:55:04 +00003156 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3157 if (log)
3158 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3159 __FUNCTION__, insert ? "add" : "remove", addr);
3160
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003161 // Check if the stub is known not to support this breakpoint type
3162 if (!SupportsGDBStoppointPacket(type))
3163 return UINT8_MAX;
3164 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00003165 char packet[64];
3166 const int packet_len = ::snprintf (packet,
3167 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00003168 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00003169 insert ? 'Z' : 'z',
3170 type,
3171 addr,
3172 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003173 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00003174 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003175 StringExtractorGDBRemote response;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003176 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00003177 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003178 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003179 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00003180 if (response.IsOKResponse())
3181 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003182
3183 // Error while setting breakpoint, send back specific error
3184 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003185 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003186
3187 // Empty packet informs us that breakpoint is not supported
3188 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00003189 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003190 // Disable this breakpoint type since it is unsupported
3191 switch (type)
3192 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00003193 case eBreakpointSoftware: m_supports_z0 = false; break;
3194 case eBreakpointHardware: m_supports_z1 = false; break;
3195 case eWatchpointWrite: m_supports_z2 = false; break;
3196 case eWatchpointRead: m_supports_z3 = false; break;
3197 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00003198 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003199 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003200 }
3201 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003202 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00003203 return UINT8_MAX;
3204}
Greg Claytonadc00cb2011-05-20 23:38:13 +00003205
3206size_t
3207GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3208 bool &sequence_mutex_unavailable)
3209{
3210 Mutex::Locker locker;
3211 thread_ids.clear();
3212
Jim Ingham4ceb9282012-06-08 22:50:40 +00003213 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003214 {
3215 sequence_mutex_unavailable = false;
3216 StringExtractorGDBRemote response;
3217
Greg Clayton3dedae12013-12-06 21:45:27 +00003218 PacketResult packet_result;
3219 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3220 packet_result == PacketResult::Success && response.IsNormalResponse();
3221 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003222 {
3223 char ch = response.GetChar();
3224 if (ch == 'l')
3225 break;
3226 if (ch == 'm')
3227 {
3228 do
3229 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00003230 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00003231
3232 if (tid != LLDB_INVALID_THREAD_ID)
3233 {
3234 thread_ids.push_back (tid);
3235 }
3236 ch = response.GetChar(); // Skip the command separator
3237 } while (ch == ','); // Make sure we got a comma separator
3238 }
3239 }
3240 }
3241 else
3242 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00003243#if defined (LLDB_CONFIGURATION_DEBUG)
3244 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3245#else
Greg Clayton5160ce52013-03-27 23:08:40 +00003246 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00003247 if (log)
3248 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00003249#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00003250 sequence_mutex_unavailable = true;
3251 }
3252 return thread_ids.size();
3253}
Greg Clayton37a0a242012-04-11 00:24:49 +00003254
3255lldb::addr_t
3256GDBRemoteCommunicationClient::GetShlibInfoAddr()
3257{
3258 if (!IsRunning())
3259 {
3260 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003261 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00003262 {
3263 if (response.IsNormalResponse())
3264 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3265 }
3266 }
3267 return LLDB_INVALID_ADDRESS;
3268}
3269
Daniel Maleae0f8f572013-08-26 23:57:52 +00003270lldb_private::Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003271GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3272 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3273 int *status_ptr, // Pass NULL if you don't want the process exit status
3274 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3275 std::string *command_output, // Pass NULL if you don't want the command output
3276 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
Daniel Maleae0f8f572013-08-26 23:57:52 +00003277{
3278 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003279 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003280 stream.PutBytesAsRawHex8(command, strlen(command));
3281 stream.PutChar(',');
3282 stream.PutHex32(timeout_sec);
Chaoren Lind3173f32015-05-29 19:52:29 +00003283 if (working_dir)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003284 {
Chaoren Lind3173f32015-05-29 19:52:29 +00003285 std::string path{working_dir.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003286 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003287 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003288 }
3289 const char *packet = stream.GetData();
3290 int packet_len = stream.GetSize();
3291 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003292 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003293 {
3294 if (response.GetChar() != 'F')
3295 return Error("malformed reply");
3296 if (response.GetChar() != ',')
3297 return Error("malformed reply");
3298 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3299 if (exitcode == UINT32_MAX)
3300 return Error("unable to run remote process");
3301 else if (status_ptr)
3302 *status_ptr = exitcode;
3303 if (response.GetChar() != ',')
3304 return Error("malformed reply");
3305 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3306 if (signo_ptr)
3307 *signo_ptr = signo;
3308 if (response.GetChar() != ',')
3309 return Error("malformed reply");
3310 std::string output;
3311 response.GetEscapedBinaryData(output);
3312 if (command_output)
3313 command_output->assign(output);
3314 return Error();
3315 }
3316 return Error("unable to send packet");
3317}
3318
Greg Claytonfbb76342013-11-20 21:07:01 +00003319Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003320GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3321 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003322{
Chaoren Lind3173f32015-05-29 19:52:29 +00003323 std::string path{file_spec.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003324 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003325 stream.PutCString("qPlatform_mkdir:");
3326 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003327 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003328 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003329 const char *packet = stream.GetData();
3330 int packet_len = stream.GetSize();
3331 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003332
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003333 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3334 return Error("failed to send '%s' packet", packet);
3335
3336 if (response.GetChar() != 'F')
3337 return Error("invalid response to '%s' packet", packet);
3338
3339 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003340}
3341
Greg Claytonfbb76342013-11-20 21:07:01 +00003342Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003343GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3344 uint32_t file_permissions)
Greg Claytonfbb76342013-11-20 21:07:01 +00003345{
Chaoren Lind3173f32015-05-29 19:52:29 +00003346 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003347 lldb_private::StreamString stream;
3348 stream.PutCString("qPlatform_chmod:");
3349 stream.PutHex32(file_permissions);
3350 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003351 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003352 const char *packet = stream.GetData();
3353 int packet_len = stream.GetSize();
3354 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003355
3356 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3357 return Error("failed to send '%s' packet", packet);
3358
3359 if (response.GetChar() != 'F')
3360 return Error("invalid response to '%s' packet", packet);
3361
Chaoren Lince36c4c2015-05-05 18:43:19 +00003362 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003363}
3364
Daniel Maleae0f8f572013-08-26 23:57:52 +00003365static uint64_t
3366ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3367 uint64_t fail_result,
3368 Error &error)
3369{
3370 response.SetFilePos(0);
3371 if (response.GetChar() != 'F')
3372 return fail_result;
3373 int32_t result = response.GetS32 (-2);
3374 if (result == -2)
3375 return fail_result;
3376 if (response.GetChar() == ',')
3377 {
3378 int result_errno = response.GetS32 (-2);
3379 if (result_errno != -2)
3380 error.SetError(result_errno, eErrorTypePOSIX);
3381 else
3382 error.SetError(-1, eErrorTypeGeneric);
3383 }
3384 else
3385 error.Clear();
3386 return result;
3387}
3388lldb::user_id_t
3389GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3390 uint32_t flags,
3391 mode_t mode,
3392 Error &error)
3393{
Chaoren Lind3173f32015-05-29 19:52:29 +00003394 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003395 lldb_private::StreamString stream;
3396 stream.PutCString("vFile:open:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003397 if (path.empty())
3398 return UINT64_MAX;
3399 stream.PutCStringAsRawHex8(path.c_str());
3400 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003401 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003402 stream.PutChar(',');
3403 stream.PutHex32(mode);
3404 const char* packet = stream.GetData();
3405 int packet_len = stream.GetSize();
3406 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003407 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003408 {
3409 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3410 }
3411 return UINT64_MAX;
3412}
3413
3414bool
3415GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3416 Error &error)
3417{
3418 lldb_private::StreamString stream;
3419 stream.Printf("vFile:close:%i", (int)fd);
3420 const char* packet = stream.GetData();
3421 int packet_len = stream.GetSize();
3422 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003423 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003424 {
3425 return ParseHostIOPacketResponse (response, -1, error) == 0;
3426 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003427 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003428}
3429
3430// Extension of host I/O packets to get the file size.
3431lldb::user_id_t
3432GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3433{
Chaoren Lind3173f32015-05-29 19:52:29 +00003434 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003435 lldb_private::StreamString stream;
3436 stream.PutCString("vFile:size:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003437 stream.PutCStringAsRawHex8(path.c_str());
3438 const char* packet = stream.GetData();
3439 int packet_len = stream.GetSize();
3440 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003441 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003442 {
3443 if (response.GetChar() != 'F')
3444 return UINT64_MAX;
3445 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3446 return retcode;
3447 }
3448 return UINT64_MAX;
3449}
3450
Greg Claytonfbb76342013-11-20 21:07:01 +00003451Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003452GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3453 uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003454{
Chaoren Lind3173f32015-05-29 19:52:29 +00003455 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003456 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003457 lldb_private::StreamString stream;
3458 stream.PutCString("vFile:mode:");
Chaoren Lind3173f32015-05-29 19:52:29 +00003459 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003460 const char* packet = stream.GetData();
3461 int packet_len = stream.GetSize();
3462 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003463 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003464 {
3465 if (response.GetChar() != 'F')
3466 {
3467 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003468 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003469 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003470 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003471 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003472 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003473 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003474 if (response.GetChar() == ',')
3475 {
3476 int response_errno = response.GetS32(-1);
3477 if (response_errno > 0)
3478 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3479 else
3480 error.SetErrorToGenericError();
3481 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003482 else
3483 error.SetErrorToGenericError();
3484 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003485 else
3486 {
3487 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3488 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003489 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003490 }
3491 else
3492 {
3493 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3494 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003495 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003496}
3497
3498uint64_t
3499GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3500 uint64_t offset,
3501 void *dst,
3502 uint64_t dst_len,
3503 Error &error)
3504{
3505 lldb_private::StreamString stream;
3506 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3507 const char* packet = stream.GetData();
3508 int packet_len = stream.GetSize();
3509 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003510 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003511 {
3512 if (response.GetChar() != 'F')
3513 return 0;
3514 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3515 if (retcode == UINT32_MAX)
3516 return retcode;
3517 const char next = (response.Peek() ? *response.Peek() : 0);
3518 if (next == ',')
3519 return 0;
3520 if (next == ';')
3521 {
3522 response.GetChar(); // skip the semicolon
3523 std::string buffer;
3524 if (response.GetEscapedBinaryData(buffer))
3525 {
3526 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3527 if (data_to_write > 0)
3528 memcpy(dst, &buffer[0], data_to_write);
3529 return data_to_write;
3530 }
3531 }
3532 }
3533 return 0;
3534}
3535
3536uint64_t
3537GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3538 uint64_t offset,
3539 const void* src,
3540 uint64_t src_len,
3541 Error &error)
3542{
3543 lldb_private::StreamGDBRemote stream;
3544 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3545 stream.PutEscapedBytes(src, src_len);
3546 const char* packet = stream.GetData();
3547 int packet_len = stream.GetSize();
3548 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003549 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003550 {
3551 if (response.GetChar() != 'F')
3552 {
3553 error.SetErrorStringWithFormat("write file failed");
3554 return 0;
3555 }
3556 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3557 if (bytes_written == UINT64_MAX)
3558 {
3559 error.SetErrorToGenericError();
3560 if (response.GetChar() == ',')
3561 {
3562 int response_errno = response.GetS32(-1);
3563 if (response_errno > 0)
3564 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3565 }
3566 return 0;
3567 }
3568 return bytes_written;
3569 }
3570 else
3571 {
3572 error.SetErrorString ("failed to send vFile:pwrite packet");
3573 }
3574 return 0;
3575}
3576
Greg Claytonfbb76342013-11-20 21:07:01 +00003577Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003578GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
Greg Claytonfbb76342013-11-20 21:07:01 +00003579{
Chaoren Lind3173f32015-05-29 19:52:29 +00003580 std::string src_path{src.GetPath(false)},
3581 dst_path{dst.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003582 Error error;
3583 lldb_private::StreamGDBRemote stream;
3584 stream.PutCString("vFile:symlink:");
3585 // the unix symlink() command reverses its parameters where the dst if first,
3586 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003587 stream.PutCStringAsRawHex8(dst_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003588 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003589 stream.PutCStringAsRawHex8(src_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003590 const char* packet = stream.GetData();
3591 int packet_len = stream.GetSize();
3592 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003593 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003594 {
3595 if (response.GetChar() == 'F')
3596 {
3597 uint32_t result = response.GetU32(UINT32_MAX);
3598 if (result != 0)
3599 {
3600 error.SetErrorToGenericError();
3601 if (response.GetChar() == ',')
3602 {
3603 int response_errno = response.GetS32(-1);
3604 if (response_errno > 0)
3605 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3606 }
3607 }
3608 }
3609 else
3610 {
3611 // Should have returned with 'F<result>[,<errno>]'
3612 error.SetErrorStringWithFormat("symlink failed");
3613 }
3614 }
3615 else
3616 {
3617 error.SetErrorString ("failed to send vFile:symlink packet");
3618 }
3619 return error;
3620}
3621
3622Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003623GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
Greg Claytonfbb76342013-11-20 21:07:01 +00003624{
Chaoren Lind3173f32015-05-29 19:52:29 +00003625 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003626 Error error;
3627 lldb_private::StreamGDBRemote stream;
3628 stream.PutCString("vFile:unlink:");
3629 // the unix symlink() command reverses its parameters where the dst if first,
3630 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00003631 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003632 const char* packet = stream.GetData();
3633 int packet_len = stream.GetSize();
3634 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003635 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003636 {
3637 if (response.GetChar() == 'F')
3638 {
3639 uint32_t result = response.GetU32(UINT32_MAX);
3640 if (result != 0)
3641 {
3642 error.SetErrorToGenericError();
3643 if (response.GetChar() == ',')
3644 {
3645 int response_errno = response.GetS32(-1);
3646 if (response_errno > 0)
3647 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3648 }
3649 }
3650 }
3651 else
3652 {
3653 // Should have returned with 'F<result>[,<errno>]'
3654 error.SetErrorStringWithFormat("unlink failed");
3655 }
3656 }
3657 else
3658 {
3659 error.SetErrorString ("failed to send vFile:unlink packet");
3660 }
3661 return error;
3662}
3663
Daniel Maleae0f8f572013-08-26 23:57:52 +00003664// Extension of host I/O packets to get whether a file exists.
3665bool
3666GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3667{
Chaoren Lind3173f32015-05-29 19:52:29 +00003668 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003669 lldb_private::StreamString stream;
3670 stream.PutCString("vFile:exists:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003671 stream.PutCStringAsRawHex8(path.c_str());
3672 const char* packet = stream.GetData();
3673 int packet_len = stream.GetSize();
3674 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003675 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003676 {
3677 if (response.GetChar() != 'F')
3678 return false;
3679 if (response.GetChar() != ',')
3680 return false;
3681 bool retcode = (response.GetChar() != '0');
3682 return retcode;
3683 }
3684 return false;
3685}
3686
3687bool
3688GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3689 uint64_t &high,
3690 uint64_t &low)
3691{
Chaoren Lind3173f32015-05-29 19:52:29 +00003692 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003693 lldb_private::StreamString stream;
3694 stream.PutCString("vFile:MD5:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003695 stream.PutCStringAsRawHex8(path.c_str());
3696 const char* packet = stream.GetData();
3697 int packet_len = stream.GetSize();
3698 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003699 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003700 {
3701 if (response.GetChar() != 'F')
3702 return false;
3703 if (response.GetChar() != ',')
3704 return false;
3705 if (response.Peek() && *response.Peek() == 'x')
3706 return false;
3707 low = response.GetHexMaxU64(false, UINT64_MAX);
3708 high = response.GetHexMaxU64(false, UINT64_MAX);
3709 return true;
3710 }
3711 return false;
3712}
Greg Claytonf74cf862013-11-13 23:28:31 +00003713
3714bool
Jason Molendaa3329782014-03-29 18:54:20 +00003715GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3716{
3717 // Some targets have issues with g/G packets and we need to avoid using them
3718 if (m_avoid_g_packets == eLazyBoolCalculate)
3719 {
3720 if (process)
3721 {
3722 m_avoid_g_packets = eLazyBoolNo;
3723 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3724 if (arch.IsValid()
3725 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3726 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00003727 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00003728 {
3729 m_avoid_g_packets = eLazyBoolYes;
3730 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3731 if (gdb_server_version != 0)
3732 {
3733 const char *gdb_server_name = GetGDBServerProgramName();
3734 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3735 {
3736 if (gdb_server_version >= 310)
3737 m_avoid_g_packets = eLazyBoolNo;
3738 }
3739 }
3740 }
3741 }
3742 }
3743 return m_avoid_g_packets == eLazyBoolYes;
3744}
3745
3746bool
Greg Claytonf74cf862013-11-13 23:28:31 +00003747GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3748{
3749 Mutex::Locker locker;
3750 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
3751 {
3752 const bool thread_suffix_supported = GetThreadSuffixSupported();
3753
3754 if (thread_suffix_supported || SetCurrentThread(tid))
3755 {
3756 char packet[64];
3757 int packet_len = 0;
3758 if (thread_suffix_supported)
3759 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
3760 else
3761 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3762 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003763 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003764 }
3765 }
3766 return false;
3767
3768}
3769
3770
3771bool
3772GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3773{
3774 Mutex::Locker locker;
3775 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3776 {
3777 const bool thread_suffix_supported = GetThreadSuffixSupported();
3778
3779 if (thread_suffix_supported || SetCurrentThread(tid))
3780 {
3781 char packet[64];
3782 int packet_len = 0;
3783 // Get all registers in one packet
3784 if (thread_suffix_supported)
3785 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3786 else
3787 packet_len = ::snprintf (packet, sizeof(packet), "g");
3788 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003789 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003790 }
3791 }
3792 return false;
3793}
3794bool
3795GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3796{
3797 save_id = 0; // Set to invalid save ID
3798 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3799 return false;
3800
3801 m_supports_QSaveRegisterState = eLazyBoolYes;
3802 Mutex::Locker locker;
3803 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3804 {
3805 const bool thread_suffix_supported = GetThreadSuffixSupported();
3806 if (thread_suffix_supported || SetCurrentThread(tid))
3807 {
3808 char packet[256];
3809 if (thread_suffix_supported)
3810 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3811 else
Ilia K686b1fe2015-02-27 19:43:08 +00003812 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
Greg Claytonf74cf862013-11-13 23:28:31 +00003813
3814 StringExtractorGDBRemote response;
3815
Greg Clayton3dedae12013-12-06 21:45:27 +00003816 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003817 {
3818 if (response.IsUnsupportedResponse())
3819 {
3820 // This packet isn't supported, don't try calling it again
3821 m_supports_QSaveRegisterState = eLazyBoolNo;
3822 }
3823
3824 const uint32_t response_save_id = response.GetU32(0);
3825 if (response_save_id != 0)
3826 {
3827 save_id = response_save_id;
3828 return true;
3829 }
3830 }
3831 }
3832 }
3833 return false;
3834}
3835
3836bool
3837GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3838{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003839 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00003840 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3841 // order to be useful
3842 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3843 return false;
3844
3845 Mutex::Locker locker;
3846 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
3847 {
3848 const bool thread_suffix_supported = GetThreadSuffixSupported();
3849 if (thread_suffix_supported || SetCurrentThread(tid))
3850 {
3851 char packet[256];
3852 if (thread_suffix_supported)
3853 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3854 else
3855 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3856
3857 StringExtractorGDBRemote response;
3858
Greg Clayton3dedae12013-12-06 21:45:27 +00003859 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003860 {
3861 if (response.IsOKResponse())
3862 {
3863 return true;
3864 }
3865 else if (response.IsUnsupportedResponse())
3866 {
3867 // This packet isn't supported, don't try calling this packet or
3868 // QSaveRegisterState again...
3869 m_supports_QSaveRegisterState = eLazyBoolNo;
3870 }
3871 }
3872 }
3873 }
3874 return false;
3875}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003876
3877bool
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003878GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003879 const lldb_private::ArchSpec& arch_spec,
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003880 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003881{
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00003882 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003883 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003884 return false;
3885
3886 StreamString packet;
3887 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003888 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003889 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00003890 const auto& triple = arch_spec.GetTriple().getTriple();
Chaoren Lind3173f32015-05-29 19:52:29 +00003891 packet.PutCStringAsRawHex8(triple.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003892
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003893 StringExtractorGDBRemote response;
3894 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
3895 return false;
3896
Aidan Doddsdf627e72015-05-05 08:31:55 +00003897 if (response.IsErrorResponse () || response.IsUnsupportedResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003898 return false;
3899
3900 std::string name;
3901 std::string value;
3902 bool success;
3903 StringExtractor extractor;
3904
3905 module_spec.Clear ();
3906 module_spec.GetFileSpec () = module_file_spec;
3907
3908 while (response.GetNameColonValue (name, value))
3909 {
3910 if (name == "uuid" || name == "md5")
3911 {
3912 extractor.GetStringRef ().swap (value);
3913 extractor.SetFilePos (0);
3914 extractor.GetHexByteString (value);
3915 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
3916 }
3917 else if (name == "triple")
3918 {
3919 extractor.GetStringRef ().swap (value);
3920 extractor.SetFilePos (0);
3921 extractor.GetHexByteString (value);
3922 module_spec.GetArchitecture().SetTriple (value.c_str ());
3923 }
3924 else if (name == "file_offset")
3925 {
3926 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
3927 if (success)
3928 module_spec.SetObjectOffset (ival);
3929 }
3930 else if (name == "file_size")
3931 {
3932 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
3933 if (success)
3934 module_spec.SetObjectSize (ival);
3935 }
3936 else if (name == "file_path")
3937 {
3938 extractor.GetStringRef ().swap (value);
3939 extractor.SetFilePos (0);
3940 extractor.GetHexByteString (value);
Chaoren Linf34f4102015-05-09 01:21:32 +00003941 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003942 }
3943 }
3944
3945 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003946}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003947
3948// query the target remote for extended information using the qXfer packet
3949//
3950// example: object='features', annex='target.xml', out=<xml output>
3951// return: 'true' on success
3952// 'false' on failure (err set)
3953bool
3954GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
3955 const lldb_private::ConstString annex,
3956 std::string & out,
3957 lldb_private::Error & err) {
3958
3959 std::stringstream output;
3960 StringExtractorGDBRemote chunk;
3961
Greg Claytond04f0ed2015-05-26 18:00:51 +00003962 uint64_t size = GetRemoteMaxPacketSize();
3963 if (size == 0)
3964 size = 0x1000;
3965 size = size - 1; // Leave space for the 'm' or 'l' character in the response
3966 int offset = 0;
3967 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003968
3969 // loop until all data has been read
3970 while ( active ) {
3971
3972 // send query extended feature packet
3973 std::stringstream packet;
3974 packet << "qXfer:"
3975 << object.AsCString( ) << ":read:"
3976 << annex.AsCString( ) << ":"
3977 << std::hex << offset << ","
3978 << std::hex << size;
3979
3980 GDBRemoteCommunication::PacketResult res =
3981 SendPacketAndWaitForResponse( packet.str().c_str(),
3982 chunk,
3983 false );
3984
3985 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
3986 err.SetErrorString( "Error sending $qXfer packet" );
3987 return false;
3988 }
3989
3990 const std::string & str = chunk.GetStringRef( );
3991 if ( str.length() == 0 ) {
3992 // should have some data in chunk
3993 err.SetErrorString( "Empty response from $qXfer packet" );
3994 return false;
3995 }
3996
3997 // check packet code
3998 switch ( str[0] ) {
3999 // last chunk
4000 case ( 'l' ):
4001 active = false;
Aidan Doddsed9f6122015-04-29 10:08:17 +00004002 // fall through intentional
Colin Rileyc3c95b22015-04-16 15:51:33 +00004003
4004 // more chunks
4005 case ( 'm' ) :
4006 if ( str.length() > 1 )
4007 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00004008 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004009 break;
4010
4011 // unknown chunk
4012 default:
4013 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
4014 return false;
4015 }
4016 }
4017
4018 out = output.str( );
4019 err.Success( );
4020 return true;
4021}