blob: a05059f061a5c2b3f00a1688724aab2fba30636c [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"
Greg Clayton576d8832011-03-22 04:00:09 +000038
39// Project includes
40#include "Utility/StringExtractorGDBRemote.h"
41#include "ProcessGDBRemote.h"
42#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000043#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000044
45using namespace lldb;
46using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000047using namespace lldb_private::process_gdb_remote;
Greg Clayton576d8832011-03-22 04:00:09 +000048
Todd Fiala0a70a842014-05-28 16:43:26 +000049#if defined(LLDB_DISABLE_POSIX) && !defined(SIGSTOP)
Virgile Bellob2f1fb22013-08-23 12:44:05 +000050#define SIGSTOP 17
51#endif
52
Greg Clayton576d8832011-03-22 04:00:09 +000053//----------------------------------------------------------------------
54// GDBRemoteCommunicationClient constructor
55//----------------------------------------------------------------------
Tamas Berghammere13c2732015-02-11 10:29:30 +000056GDBRemoteCommunicationClient::GDBRemoteCommunicationClient() :
57 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet"),
Greg Clayton576d8832011-03-22 04:00:09 +000058 m_supports_not_sending_acks (eLazyBoolCalculate),
59 m_supports_thread_suffix (eLazyBoolCalculate),
Greg Clayton44633992012-04-10 03:22:03 +000060 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
Greg Clayton576d8832011-03-22 04:00:09 +000061 m_supports_vCont_all (eLazyBoolCalculate),
62 m_supports_vCont_any (eLazyBoolCalculate),
63 m_supports_vCont_c (eLazyBoolCalculate),
64 m_supports_vCont_C (eLazyBoolCalculate),
65 m_supports_vCont_s (eLazyBoolCalculate),
66 m_supports_vCont_S (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000067 m_qHostInfo_is_valid (eLazyBoolCalculate),
Todd Fiala9f72b3a2014-05-07 19:28:21 +000068 m_curr_pid_is_valid (eLazyBoolCalculate),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000069 m_qProcessInfo_is_valid (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000070 m_qGDBServerVersion_is_valid (eLazyBoolCalculate),
Greg Clayton70b57652011-05-15 01:25:55 +000071 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
Greg Clayton46fb5582011-11-18 07:03:08 +000072 m_supports_memory_region_info (eLazyBoolCalculate),
Johnny Chen64637202012-05-23 21:09:52 +000073 m_supports_watchpoint_support_info (eLazyBoolCalculate),
Jim Inghamacff8952013-05-02 00:27:30 +000074 m_supports_detach_stay_stopped (eLazyBoolCalculate),
Enrico Granataf04a2192012-07-13 23:18:48 +000075 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
Jim Inghamcd16df92012-07-20 21:37:13 +000076 m_attach_or_wait_reply(eLazyBoolCalculate),
Jim Ingham279ceec2012-07-25 21:12:43 +000077 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
Eric Christopher2490f5c2013-08-30 17:50:57 +000078 m_supports_p (eLazyBoolCalculate),
Jason Molendabdc4f122014-05-06 02:59:39 +000079 m_supports_x (eLazyBoolCalculate),
Jason Molendaa3329782014-03-29 18:54:20 +000080 m_avoid_g_packets (eLazyBoolCalculate),
Greg Claytonf74cf862013-11-13 23:28:31 +000081 m_supports_QSaveRegisterState (eLazyBoolCalculate),
Steve Pucci03904ac2014-03-04 23:18:46 +000082 m_supports_qXfer_auxv_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000083 m_supports_qXfer_libraries_read (eLazyBoolCalculate),
84 m_supports_qXfer_libraries_svr4_read (eLazyBoolCalculate),
Greg Clayton253204e2015-04-16 23:11:06 +000085 m_supports_qXfer_features_read (eLazyBoolCalculate),
Steve Pucci5ae54ae2014-01-25 05:46:51 +000086 m_supports_augmented_libraries_svr4_read (eLazyBoolCalculate),
Jason Molenda705b1802014-06-13 02:37:02 +000087 m_supports_jThreadExtendedInfo (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000088 m_supports_qProcessInfoPID (true),
89 m_supports_qfProcessInfo (true),
90 m_supports_qUserName (true),
91 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000092 m_supports_qThreadStopInfo (true),
93 m_supports_z0 (true),
94 m_supports_z1 (true),
95 m_supports_z2 (true),
96 m_supports_z3 (true),
97 m_supports_z4 (true),
Greg Clayton89600582013-10-10 17:53:50 +000098 m_supports_QEnvironment (true),
99 m_supports_QEnvironmentHexEncoded (true),
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000100 m_curr_pid (LLDB_INVALID_PROCESS_ID),
Greg Clayton8b82f082011-04-12 05:54:46 +0000101 m_curr_tid (LLDB_INVALID_THREAD_ID),
102 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +0000103 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +0000104 m_async_mutex (Mutex::eMutexTypeRecursive),
105 m_async_packet_predicate (false),
106 m_async_packet (),
Jim Inghama6195b72013-12-18 01:24:33 +0000107 m_async_result (PacketResult::Success),
Greg Clayton576d8832011-03-22 04:00:09 +0000108 m_async_response (),
109 m_async_signal (-1),
Jim Inghamb8cd5752014-04-16 02:24:17 +0000110 m_interrupt_sent (false),
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000111 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +0000112 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000113 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +0000114 m_os_version_major (UINT32_MAX),
115 m_os_version_minor (UINT32_MAX),
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000116 m_os_version_update (UINT32_MAX),
117 m_os_build (),
118 m_os_kernel (),
119 m_hostname (),
Jason Molendaa3329782014-03-29 18:54:20 +0000120 m_gdb_server_name(),
121 m_gdb_server_version(UINT32_MAX),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000122 m_default_packet_timeout (0),
123 m_max_packet_size (0)
Greg Clayton576d8832011-03-22 04:00:09 +0000124{
Greg Clayton576d8832011-03-22 04:00:09 +0000125}
126
127//----------------------------------------------------------------------
128// Destructor
129//----------------------------------------------------------------------
130GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
131{
Greg Clayton576d8832011-03-22 04:00:09 +0000132 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000133 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000134}
135
136bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000137GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
138{
Greg Claytonfb909312013-11-23 01:58:15 +0000139 ResetDiscoverableSettings();
140
Greg Clayton1cb64962011-03-24 04:28:38 +0000141 // Start the read thread after we send the handshake ack since if we
142 // fail to send the handshake ack, there is no reason to continue...
143 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000144 {
Ed Maste48f986f2013-12-18 15:31:45 +0000145 // Wait for any responses that might have been queued up in the remote
146 // GDB server and flush them all
147 StringExtractorGDBRemote response;
148 PacketResult packet_result = PacketResult::Success;
149 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
150 while (packet_result == PacketResult::Success)
151 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, timeout_usec);
152
Greg Claytonfb909312013-11-23 01:58:15 +0000153 // The return value from QueryNoAckModeSupported() is true if the packet
154 // was sent and _any_ response (including UNIMPLEMENTED) was received),
155 // or false if no response was received. This quickly tells us if we have
156 // a live connection to a remote GDB server...
157 if (QueryNoAckModeSupported())
158 {
159 return true;
160 }
161 else
162 {
163 if (error_ptr)
164 error_ptr->SetErrorString("failed to get reply to handshake packet");
165 }
166 }
167 else
168 {
169 if (error_ptr)
170 error_ptr->SetErrorString("failed to send the handshake ack");
171 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000172 return false;
173}
174
Greg Claytonfb909312013-11-23 01:58:15 +0000175bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000176GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
177{
178 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
179 {
180 GetRemoteQSupported();
181 }
182 return (m_supports_augmented_libraries_svr4_read == eLazyBoolYes);
183}
184
185bool
186GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
187{
188 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
189 {
190 GetRemoteQSupported();
191 }
192 return (m_supports_qXfer_libraries_svr4_read == eLazyBoolYes);
193}
194
195bool
196GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
197{
198 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
199 {
200 GetRemoteQSupported();
201 }
202 return (m_supports_qXfer_libraries_read == eLazyBoolYes);
203}
204
Steve Pucci03904ac2014-03-04 23:18:46 +0000205bool
206GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
207{
208 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
209 {
210 GetRemoteQSupported();
211 }
212 return (m_supports_qXfer_auxv_read == eLazyBoolYes);
213}
214
Colin Rileyc3c95b22015-04-16 15:51:33 +0000215bool
216GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported ()
217{
218 if (m_supports_qXfer_features_read == eLazyBoolCalculate)
219 {
220 GetRemoteQSupported();
221 }
222 return (m_supports_qXfer_features_read == eLazyBoolYes);
223}
224
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000225uint64_t
226GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
227{
228 if (m_max_packet_size == 0)
229 {
230 GetRemoteQSupported();
231 }
232 return m_max_packet_size;
233}
234
235bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000236GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000237{
238 if (m_supports_not_sending_acks == eLazyBoolCalculate)
239 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000240 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000241 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000242
Jason Molenda36a216e2014-07-24 01:36:24 +0000243 // This is the first real packet that we'll send in a debug session and it may take a little
244 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
245
246 const uint32_t minimum_timeout = 6;
247 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000248 GDBRemoteCommunication::ScopedTimeout timeout (*this, std::max (old_timeout, minimum_timeout));
Jason Molenda36a216e2014-07-24 01:36:24 +0000249
Greg Clayton1cb64962011-03-24 04:28:38 +0000250 StringExtractorGDBRemote response;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000251 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000252 {
253 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000254 {
255 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000256 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000257 }
Greg Claytonfb909312013-11-23 01:58:15 +0000258 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000259 }
260 }
Greg Claytonfb909312013-11-23 01:58:15 +0000261 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000262}
263
264void
Greg Clayton44633992012-04-10 03:22:03 +0000265GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
266{
267 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
268 {
269 m_supports_threads_in_stop_reply = eLazyBoolNo;
270
271 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000272 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000273 {
274 if (response.IsOKResponse())
275 m_supports_threads_in_stop_reply = eLazyBoolYes;
276 }
277 }
278}
279
Jim Inghamcd16df92012-07-20 21:37:13 +0000280bool
281GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
282{
283 if (m_attach_or_wait_reply == eLazyBoolCalculate)
284 {
285 m_attach_or_wait_reply = eLazyBoolNo;
286
287 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000288 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000289 {
290 if (response.IsOKResponse())
291 m_attach_or_wait_reply = eLazyBoolYes;
292 }
293 }
294 if (m_attach_or_wait_reply == eLazyBoolYes)
295 return true;
296 else
297 return false;
298}
299
Jim Ingham279ceec2012-07-25 21:12:43 +0000300bool
301GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
302{
303 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
304 {
305 m_prepare_for_reg_writing_reply = eLazyBoolNo;
306
307 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000308 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000309 {
310 if (response.IsOKResponse())
311 m_prepare_for_reg_writing_reply = eLazyBoolYes;
312 }
313 }
314 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
315 return true;
316 else
317 return false;
318}
319
Greg Clayton44633992012-04-10 03:22:03 +0000320
321void
Greg Clayton576d8832011-03-22 04:00:09 +0000322GDBRemoteCommunicationClient::ResetDiscoverableSettings()
323{
324 m_supports_not_sending_acks = eLazyBoolCalculate;
325 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton44633992012-04-10 03:22:03 +0000326 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
Greg Clayton576d8832011-03-22 04:00:09 +0000327 m_supports_vCont_c = eLazyBoolCalculate;
328 m_supports_vCont_C = eLazyBoolCalculate;
329 m_supports_vCont_s = eLazyBoolCalculate;
330 m_supports_vCont_S = eLazyBoolCalculate;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000331 m_supports_p = eLazyBoolCalculate;
Jason Molendabdc4f122014-05-06 02:59:39 +0000332 m_supports_x = eLazyBoolCalculate;
Greg Claytonf74cf862013-11-13 23:28:31 +0000333 m_supports_QSaveRegisterState = eLazyBoolCalculate;
Greg Clayton32e0a752011-03-30 18:16:51 +0000334 m_qHostInfo_is_valid = eLazyBoolCalculate;
Todd Fiala9f72b3a2014-05-07 19:28:21 +0000335 m_curr_pid_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000336 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000337 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
Greg Clayton70b57652011-05-15 01:25:55 +0000338 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton46fb5582011-11-18 07:03:08 +0000339 m_supports_memory_region_info = eLazyBoolCalculate;
Jim Ingham279ceec2012-07-25 21:12:43 +0000340 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
341 m_attach_or_wait_reply = eLazyBoolCalculate;
Jason Molendaa3329782014-03-29 18:54:20 +0000342 m_avoid_g_packets = eLazyBoolCalculate;
Steve Pucci03904ac2014-03-04 23:18:46 +0000343 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000344 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
345 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000346 m_supports_qXfer_features_read = eLazyBoolCalculate;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000347 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
Greg Clayton2a48f522011-05-14 01:50:35 +0000348
Greg Clayton32e0a752011-03-30 18:16:51 +0000349 m_supports_qProcessInfoPID = true;
350 m_supports_qfProcessInfo = true;
351 m_supports_qUserName = true;
352 m_supports_qGroupName = true;
Greg Clayton8b82f082011-04-12 05:54:46 +0000353 m_supports_qThreadStopInfo = true;
354 m_supports_z0 = true;
355 m_supports_z1 = true;
356 m_supports_z2 = true;
357 m_supports_z3 = true;
358 m_supports_z4 = true;
Greg Clayton89600582013-10-10 17:53:50 +0000359 m_supports_QEnvironment = true;
360 m_supports_QEnvironmentHexEncoded = true;
Jason Molendaa3329782014-03-29 18:54:20 +0000361
Greg Claytond314e812011-03-23 00:09:55 +0000362 m_host_arch.Clear();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000363 m_process_arch.Clear();
Jason Molendaa3329782014-03-29 18:54:20 +0000364 m_os_version_major = UINT32_MAX;
365 m_os_version_minor = UINT32_MAX;
366 m_os_version_update = UINT32_MAX;
367 m_os_build.clear();
368 m_os_kernel.clear();
369 m_hostname.clear();
370 m_gdb_server_name.clear();
371 m_gdb_server_version = UINT32_MAX;
372 m_default_packet_timeout = 0;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000373
374 m_max_packet_size = 0;
Greg Clayton576d8832011-03-22 04:00:09 +0000375}
376
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000377void
378GDBRemoteCommunicationClient::GetRemoteQSupported ()
379{
380 // Clear out any capabilities we expect to see in the qSupported response
Steve Pucci03904ac2014-03-04 23:18:46 +0000381 m_supports_qXfer_auxv_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000382 m_supports_qXfer_libraries_read = eLazyBoolNo;
Steve Pucci03904ac2014-03-04 23:18:46 +0000383 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000384 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000385 m_supports_qXfer_features_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000386 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
387
Colin Rileyc3c95b22015-04-16 15:51:33 +0000388 // build the qSupported packet
389 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
390 StreamString packet;
391 packet.PutCString( "qSupported" );
392 for ( uint32_t i = 0; i < features.size( ); ++i )
393 {
394 packet.PutCString( i==0 ? ":" : ";");
395 packet.PutCString( features[i].c_str( ) );
396 }
397
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000398 StringExtractorGDBRemote response;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000399 if (SendPacketAndWaitForResponse(packet.GetData(),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000400 response,
401 /*send_async=*/false) == PacketResult::Success)
402 {
403 const char *response_cstr = response.GetStringRef().c_str();
Steve Pucci03904ac2014-03-04 23:18:46 +0000404 if (::strstr (response_cstr, "qXfer:auxv:read+"))
405 m_supports_qXfer_auxv_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000406 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
407 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
408 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
409 {
410 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
411 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
412 }
413 if (::strstr (response_cstr, "qXfer:libraries:read+"))
414 m_supports_qXfer_libraries_read = eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000415 if (::strstr (response_cstr, "qXfer:features:read+"))
416 m_supports_qXfer_features_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000417
418 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
419 if (packet_size_str)
420 {
421 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
422 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
423 if (m_max_packet_size == 0)
424 {
425 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
426 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
427 if (log)
428 log->Printf ("Garbled PacketSize spec in qSupported response");
429 }
430 }
431 }
432}
Greg Clayton576d8832011-03-22 04:00:09 +0000433
434bool
435GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
436{
437 if (m_supports_thread_suffix == eLazyBoolCalculate)
438 {
439 StringExtractorGDBRemote response;
440 m_supports_thread_suffix = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000441 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000442 {
443 if (response.IsOKResponse())
444 m_supports_thread_suffix = eLazyBoolYes;
445 }
446 }
447 return m_supports_thread_suffix;
448}
449bool
450GDBRemoteCommunicationClient::GetVContSupported (char flavor)
451{
452 if (m_supports_vCont_c == eLazyBoolCalculate)
453 {
454 StringExtractorGDBRemote response;
455 m_supports_vCont_any = eLazyBoolNo;
456 m_supports_vCont_all = eLazyBoolNo;
457 m_supports_vCont_c = eLazyBoolNo;
458 m_supports_vCont_C = eLazyBoolNo;
459 m_supports_vCont_s = eLazyBoolNo;
460 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000461 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000462 {
463 const char *response_cstr = response.GetStringRef().c_str();
464 if (::strstr (response_cstr, ";c"))
465 m_supports_vCont_c = eLazyBoolYes;
466
467 if (::strstr (response_cstr, ";C"))
468 m_supports_vCont_C = eLazyBoolYes;
469
470 if (::strstr (response_cstr, ";s"))
471 m_supports_vCont_s = eLazyBoolYes;
472
473 if (::strstr (response_cstr, ";S"))
474 m_supports_vCont_S = eLazyBoolYes;
475
476 if (m_supports_vCont_c == eLazyBoolYes &&
477 m_supports_vCont_C == eLazyBoolYes &&
478 m_supports_vCont_s == eLazyBoolYes &&
479 m_supports_vCont_S == eLazyBoolYes)
480 {
481 m_supports_vCont_all = eLazyBoolYes;
482 }
483
484 if (m_supports_vCont_c == eLazyBoolYes ||
485 m_supports_vCont_C == eLazyBoolYes ||
486 m_supports_vCont_s == eLazyBoolYes ||
487 m_supports_vCont_S == eLazyBoolYes)
488 {
489 m_supports_vCont_any = eLazyBoolYes;
490 }
491 }
492 }
493
494 switch (flavor)
495 {
496 case 'a': return m_supports_vCont_any;
497 case 'A': return m_supports_vCont_all;
498 case 'c': return m_supports_vCont_c;
499 case 'C': return m_supports_vCont_C;
500 case 's': return m_supports_vCont_s;
501 case 'S': return m_supports_vCont_S;
502 default: break;
503 }
504 return false;
505}
506
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000507// Check if the target supports 'p' packet. It sends out a 'p'
508// packet and checks the response. A normal packet will tell us
509// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000510//
511// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000512bool
Sean Callananb1de1142013-09-04 23:24:15 +0000513GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000514{
515 if (m_supports_p == eLazyBoolCalculate)
516 {
517 StringExtractorGDBRemote response;
518 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000519 char packet[256];
520 if (GetThreadSuffixSupported())
521 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
522 else
523 snprintf(packet, sizeof(packet), "p0");
524
Greg Clayton3dedae12013-12-06 21:45:27 +0000525 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000526 {
527 if (response.IsNormalResponse())
528 m_supports_p = eLazyBoolYes;
529 }
530 }
531 return m_supports_p;
532}
Greg Clayton576d8832011-03-22 04:00:09 +0000533
Jason Molendabdc4f122014-05-06 02:59:39 +0000534bool
Jason Molenda705b1802014-06-13 02:37:02 +0000535GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
536{
537 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
538 {
539 StringExtractorGDBRemote response;
540 m_supports_jThreadExtendedInfo = eLazyBoolNo;
541 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
542 {
543 if (response.IsOKResponse())
544 {
545 m_supports_jThreadExtendedInfo = eLazyBoolYes;
546 }
547 }
548 }
549 return m_supports_jThreadExtendedInfo;
550}
551
552bool
Jason Molendabdc4f122014-05-06 02:59:39 +0000553GDBRemoteCommunicationClient::GetxPacketSupported ()
554{
555 if (m_supports_x == eLazyBoolCalculate)
556 {
557 StringExtractorGDBRemote response;
558 m_supports_x = eLazyBoolNo;
559 char packet[256];
560 snprintf (packet, sizeof (packet), "x0,0");
561 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
562 {
563 if (response.IsOKResponse())
564 m_supports_x = eLazyBoolYes;
565 }
566 }
567 return m_supports_x;
568}
569
Greg Clayton3dedae12013-12-06 21:45:27 +0000570GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000571GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
572(
573 const char *payload_prefix,
574 std::string &response_string
575)
576{
577 Mutex::Locker locker;
578 if (!GetSequenceMutex(locker,
579 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
580 {
581 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
582 if (log)
583 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
584 payload_prefix);
585 return PacketResult::ErrorNoSequenceLock;
586 }
587
588 response_string = "";
589 std::string payload_prefix_str(payload_prefix);
590 unsigned int response_size = 0x1000;
591 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
592 response_size = GetRemoteMaxPacketSize();
593 }
594
595 for (unsigned int offset = 0; true; offset += response_size)
596 {
597 StringExtractorGDBRemote this_response;
598 // Construct payload
599 char sizeDescriptor[128];
600 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
601 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
602 this_response,
603 /*send_async=*/false);
604 if (result != PacketResult::Success)
605 return result;
606
607 const std::string &this_string = this_response.GetStringRef();
608
609 // Check for m or l as first character; l seems to mean this is the last chunk
610 char first_char = *this_string.c_str();
611 if (first_char != 'm' && first_char != 'l')
612 {
613 return PacketResult::ErrorReplyInvalid;
614 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000615 // Concatenate the result so far (skipping 'm' or 'l')
616 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000617 if (first_char == 'l')
618 // We're done
619 return PacketResult::Success;
620 }
621}
622
623GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000624GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
625(
626 const char *payload,
627 StringExtractorGDBRemote &response,
628 bool send_async
629)
630{
631 return SendPacketAndWaitForResponse (payload,
632 ::strlen (payload),
633 response,
634 send_async);
635}
636
Greg Clayton3dedae12013-12-06 21:45:27 +0000637GDBRemoteCommunicationClient::PacketResult
638GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
639 size_t payload_length,
640 StringExtractorGDBRemote &response)
641{
642 PacketResult packet_result = SendPacketNoLock (payload, payload_length);
643 if (packet_result == PacketResult::Success)
644 packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
645 return packet_result;
646}
647
648GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000649GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
650(
651 const char *payload,
652 size_t payload_length,
653 StringExtractorGDBRemote &response,
654 bool send_async
655)
656{
Greg Clayton3dedae12013-12-06 21:45:27 +0000657 PacketResult packet_result = PacketResult::ErrorSendFailed;
Greg Clayton576d8832011-03-22 04:00:09 +0000658 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000659 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000660 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000661 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000662 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000663 }
664 else
665 {
666 if (send_async)
667 {
Greg Claytond3544052012-05-31 21:24:20 +0000668 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000669 {
Greg Claytond3544052012-05-31 21:24:20 +0000670 Mutex::Locker async_locker (m_async_mutex);
671 m_async_packet.assign(payload, payload_length);
672 m_async_packet_predicate.SetValue (true, eBroadcastNever);
673
674 if (log)
675 log->Printf ("async: async packet = %s", m_async_packet.c_str());
676
677 bool timed_out = false;
678 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000679 {
Greg Claytond3544052012-05-31 21:24:20 +0000680 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000681 {
Jim Inghambabfc382012-06-06 00:32:39 +0000682 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000683 TimeValue timeout_time;
684 timeout_time = TimeValue::Now();
685 timeout_time.OffsetWithSeconds (m_packet_timeout);
686
Greg Clayton576d8832011-03-22 04:00:09 +0000687 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000688 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000689
Greg Claytond3544052012-05-31 21:24:20 +0000690 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000691 {
Greg Claytond3544052012-05-31 21:24:20 +0000692 if (log)
693 log->Printf ("async: got response");
694
695 // Swap the response buffer to avoid malloc and string copy
696 response.GetStringRef().swap (m_async_response.GetStringRef());
Jim Inghama6195b72013-12-18 01:24:33 +0000697 packet_result = m_async_result;
Greg Claytond3544052012-05-31 21:24:20 +0000698 }
699 else
700 {
701 if (log)
702 log->Printf ("async: timed out waiting for response");
703 }
704
705 // Make sure we wait until the continue packet has been sent again...
706 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
707 {
708 if (log)
709 {
710 if (timed_out)
711 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
712 else
713 log->Printf ("async: async packet sent");
714 }
715 }
716 else
717 {
718 if (log)
719 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000720 }
721 }
722 else
723 {
Greg Claytond3544052012-05-31 21:24:20 +0000724 // We had a racy condition where we went to send the interrupt
725 // yet we were able to get the lock, so the process must have
726 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000727 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000728 log->Printf ("async: got lock without sending interrupt");
729 // Send the packet normally since we got the lock
Greg Clayton3dedae12013-12-06 21:45:27 +0000730 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000731 }
732 }
733 else
734 {
Greg Clayton644247c2011-07-07 01:59:51 +0000735 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000736 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000737 }
738 }
739 else
740 {
741 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000742 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000743 }
744 }
745 else
746 {
747 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000748 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000749 }
750 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000751 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000752}
753
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000754static const char *end_delimiter = "--end--;";
755static const int end_delimiter_len = 8;
756
757std::string
758GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
759( ProcessGDBRemote *process,
760 StringExtractorGDBRemote& profileDataExtractor
761)
762{
763 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
764 std::stringstream final_output;
765 std::string name, value;
766
767 // Going to assuming thread_used_usec comes first, else bail out.
768 while (profileDataExtractor.GetNameColonValue(name, value))
769 {
770 if (name.compare("thread_used_id") == 0)
771 {
772 StringExtractor threadIDHexExtractor(value.c_str());
773 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
774
775 bool has_used_usec = false;
776 uint32_t curr_used_usec = 0;
777 std::string usec_name, usec_value;
778 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
779 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
780 {
781 if (usec_name.compare("thread_used_usec") == 0)
782 {
783 has_used_usec = true;
784 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
785 }
786 else
787 {
788 // We didn't find what we want, it is probably
789 // an older version. Bail out.
790 profileDataExtractor.SetFilePos(input_file_pos);
791 }
792 }
793
794 if (has_used_usec)
795 {
796 uint32_t prev_used_usec = 0;
797 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
798 if (iterator != m_thread_id_to_used_usec_map.end())
799 {
800 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
801 }
802
803 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
804 // A good first time record is one that runs for at least 0.25 sec
805 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
806 bool good_subsequent_time = (prev_used_usec > 0) &&
807 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
808
809 if (good_first_time || good_subsequent_time)
810 {
811 // We try to avoid doing too many index id reservation,
812 // resulting in fast increase of index ids.
813
814 final_output << name << ":";
815 int32_t index_id = process->AssignIndexIDToThread(thread_id);
816 final_output << index_id << ";";
817
818 final_output << usec_name << ":" << usec_value << ";";
819 }
820 else
821 {
822 // Skip past 'thread_used_name'.
823 std::string local_name, local_value;
824 profileDataExtractor.GetNameColonValue(local_name, local_value);
825 }
826
827 // Store current time as previous time so that they can be compared later.
828 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
829 }
830 else
831 {
832 // Bail out and use old string.
833 final_output << name << ":" << value << ";";
834 }
835 }
836 else
837 {
838 final_output << name << ":" << value << ";";
839 }
840 }
841 final_output << end_delimiter;
842 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
843
844 return final_output.str();
845}
846
Greg Clayton576d8832011-03-22 04:00:09 +0000847StateType
848GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
849(
850 ProcessGDBRemote *process,
851 const char *payload,
852 size_t packet_length,
853 StringExtractorGDBRemote &response
854)
855{
Greg Clayton1f5181a2012-07-02 22:05:25 +0000856 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +0000857 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +0000858 if (log)
859 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
860
861 Mutex::Locker locker(m_sequence_mutex);
862 StateType state = eStateRunning;
863
864 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
865 m_public_is_running.SetValue (true, eBroadcastNever);
866 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +0000867 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +0000868 std::string continue_packet(payload, packet_length);
869
Greg Clayton3f875c52013-02-22 22:23:55 +0000870 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +0000871
Greg Clayton576d8832011-03-22 04:00:09 +0000872 while (state == eStateRunning)
873 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000874 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +0000875 {
876 if (log)
877 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton3dedae12013-12-06 21:45:27 +0000878 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
Greg Claytonaf247d72011-05-19 03:54:16 +0000879 state = eStateInvalid;
Jim Inghamb8cd5752014-04-16 02:24:17 +0000880 else
881 m_interrupt_sent = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000882
Greg Claytone889ad62011-10-27 22:04:16 +0000883 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +0000884 }
885
Greg Clayton3f875c52013-02-22 22:23:55 +0000886 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000887
888 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000889 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +0000890
Greg Clayton3dedae12013-12-06 21:45:27 +0000891 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000892 {
893 if (response.Empty())
894 state = eStateInvalid;
895 else
896 {
897 const char stop_type = response.GetChar();
898 if (log)
899 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
900 switch (stop_type)
901 {
902 case 'T':
903 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +0000904 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000905 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +0000906 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000907 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
908 {
909 lldb::pid_t pid = GetCurrentProcessID ();
910 if (pid != LLDB_INVALID_PROCESS_ID)
911 process->SetID (pid);
912 }
913 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +0000914 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000915
916 // Privately notify any internal threads that we have stopped
917 // in case we wanted to interrupt our process, yet we might
918 // send a packet and continue without returning control to the
919 // user.
920 m_private_is_running.SetValue (false, eBroadcastAlways);
921
922 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
923
Jim Inghambabfc382012-06-06 00:32:39 +0000924 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
925 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +0000926 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000927 // We sent an interrupt packet to stop the inferior process
928 // for an async signal or to send an async packet while running
929 // but we might have been single stepping and received the
930 // stop packet for the step instead of for the interrupt packet.
931 // Typically when an interrupt is sent a SIGINT or SIGSTOP
932 // is used, so if we get anything else, we need to try and
933 // get another stop reply packet that may have been sent
934 // due to sending the interrupt when the target is stopped
935 // which will just re-send a copy of the last stop reply
936 // packet. If we don't do this, then the reply for our
937 // async packet will be the repeat stop reply packet and cause
938 // a lot of trouble for us!
939 if (signo != SIGINT && signo != SIGSTOP)
940 {
Greg Claytonfb72fde2012-05-15 02:50:49 +0000941 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000942
943 // We didn't get a a SIGINT or SIGSTOP, so try for a
944 // very brief time (1 ms) to get another stop reply
945 // packet to make sure it doesn't get in the way
946 StringExtractorGDBRemote extra_stop_reply_packet;
947 uint32_t timeout_usec = 1000;
Greg Clayton3dedae12013-12-06 21:45:27 +0000948 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +0000949 {
950 switch (extra_stop_reply_packet.GetChar())
951 {
952 case 'T':
953 case 'S':
954 // We did get an extra stop reply, which means
955 // our interrupt didn't stop the target so we
956 // shouldn't continue after the async signal
957 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +0000958 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000959 break;
960 }
961 }
962 }
963 }
964
965 if (m_async_signal != -1)
966 {
967 if (log)
968 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
969
970 // Save off the async signal we are supposed to send
971 const int async_signal = m_async_signal;
972 // Clear the async signal member so we don't end up
973 // sending the signal multiple times...
974 m_async_signal = -1;
975 // Check which signal we stopped with
976 if (signo == async_signal)
977 {
978 if (log)
979 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
980
981 // We already stopped with a signal that we wanted
982 // to stop with, so we are done
983 }
984 else
985 {
986 // We stopped with a different signal that the one
987 // we wanted to stop with, so now we must resume
988 // with the signal we want
989 char signal_packet[32];
990 int signal_packet_len = 0;
991 signal_packet_len = ::snprintf (signal_packet,
992 sizeof (signal_packet),
993 "C%2.2x",
994 async_signal);
995
996 if (log)
997 log->Printf ("async: stopped with signal %s, resume with %s",
998 Host::GetSignalAsCString (signo),
999 Host::GetSignalAsCString (async_signal));
1000
1001 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +00001002 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001003 continue_packet.assign(signal_packet, signal_packet_len);
1004 continue;
1005 }
1006 }
1007 else if (m_async_packet_predicate.GetValue())
1008 {
Greg Clayton5160ce52013-03-27 23:08:40 +00001009 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +00001010
1011 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +00001012 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +00001013 m_async_response.Clear();
1014 if (m_async_packet.empty())
1015 {
Jim Inghama6195b72013-12-18 01:24:33 +00001016 m_async_result = PacketResult::ErrorSendFailed;
1017 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001018 packet_log->Printf ("async: error: empty async packet");
1019
1020 }
1021 else
1022 {
1023 if (packet_log)
1024 packet_log->Printf ("async: sending packet");
1025
Jim Inghama6195b72013-12-18 01:24:33 +00001026 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1027 m_async_packet.size(),
1028 m_async_response,
1029 false);
Greg Clayton2687cd12012-03-29 01:55:41 +00001030 }
1031 // Let the other thread that was trying to send the async
1032 // packet know that the packet has been sent and response is
1033 // ready...
1034 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1035
1036 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +00001037 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +00001038
1039 // Set the continue packet to resume if our interrupt
1040 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +00001041 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001042 {
Greg Claytonf1186de2012-05-24 23:42:14 +00001043 // Reverting this for now as it is causing deadlocks
1044 // in programs (<rdar://problem/11529853>). In the future
1045 // we should check our thread list and "do the right thing"
1046 // for new threads that show up while we stop and run async
1047 // packets. Setting the packet to 'c' to continue all threads
1048 // is the right thing to do 99.99% of the time because if a
1049 // thread was single stepping, and we sent an interrupt, we
1050 // will notice above that we didn't stop due to an interrupt
1051 // but stopped due to stepping and we would _not_ continue.
1052 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +00001053 continue;
1054 }
1055 }
1056 // Stop with signal and thread info
1057 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +00001058 }
Greg Clayton576d8832011-03-22 04:00:09 +00001059 break;
1060
1061 case 'W':
1062 case 'X':
1063 // process exited
1064 state = eStateExited;
1065 break;
1066
1067 case 'O':
1068 // STDOUT
1069 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001070 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001071 std::string inferior_stdout;
1072 inferior_stdout.reserve(response.GetBytesLeft () / 2);
1073 char ch;
1074 while ((ch = response.GetHexU8()) != '\0')
1075 inferior_stdout.append(1, ch);
1076 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1077 }
1078 break;
1079
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001080 case 'A':
1081 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1082 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001083 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001084 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1085 if (m_partial_profile_data.length() > 0)
1086 {
1087 m_partial_profile_data.append(input);
1088 input = m_partial_profile_data;
1089 m_partial_profile_data.clear();
1090 }
1091
1092 size_t found, pos = 0, len = input.length();
1093 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1094 {
1095 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +00001096 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1097 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001098
1099 pos = found + end_delimiter_len;
1100 }
1101
1102 if (pos < len)
1103 {
1104 // Last incomplete chunk.
1105 m_partial_profile_data = input.substr(pos);
1106 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001107 }
1108 break;
1109
Greg Clayton576d8832011-03-22 04:00:09 +00001110 case 'E':
1111 // ERROR
1112 state = eStateInvalid;
1113 break;
1114
1115 default:
1116 if (log)
1117 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1118 state = eStateInvalid;
1119 break;
1120 }
1121 }
1122 }
1123 else
1124 {
1125 if (log)
1126 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
1127 state = eStateInvalid;
1128 }
1129 }
1130 if (log)
1131 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1132 response.SetFilePos(0);
1133 m_private_is_running.SetValue (false, eBroadcastAlways);
1134 m_public_is_running.SetValue (false, eBroadcastAlways);
1135 return state;
1136}
1137
1138bool
1139GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1140{
Greg Clayton2687cd12012-03-29 01:55:41 +00001141 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001142 m_async_signal = signo;
1143 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001144 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001145 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001146 return true;
1147 m_async_signal = -1;
1148 return false;
1149}
1150
Greg Clayton37a0a242012-04-11 00:24:49 +00001151// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001152// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1153// (the expected result), then it will send the halt packet. If it does succeed
1154// then the caller that requested the interrupt will want to keep the sequence
1155// locked down so that no one else can send packets while the caller has control.
1156// This function usually gets called when we are running and need to stop the
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001157// target. It can also be used when we are running and we need to do something
Greg Clayton576d8832011-03-22 04:00:09 +00001158// else (like read/write memory), so we need to interrupt the running process
1159// (gdb remote protocol requires this), and do what we need to do, then resume.
1160
1161bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001162GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001163(
1164 Mutex::Locker& locker,
1165 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001166 bool &timed_out
1167)
1168{
Greg Clayton576d8832011-03-22 04:00:09 +00001169 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001170 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001171
1172 if (IsRunning())
1173 {
1174 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001175 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001176 {
1177 if (log)
1178 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1179 }
1180 else
Greg Clayton576d8832011-03-22 04:00:09 +00001181 {
1182 // Someone has the mutex locked waiting for a response or for the
1183 // inferior to stop, so send the interrupt on the down low...
1184 char ctrl_c = '\x03';
1185 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001186 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001187 if (log)
1188 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001189 if (bytes_written > 0)
1190 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001191 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001192 if (seconds_to_wait_for_stop)
1193 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001194 TimeValue timeout;
1195 if (seconds_to_wait_for_stop)
1196 {
1197 timeout = TimeValue::Now();
1198 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1199 }
Greg Clayton576d8832011-03-22 04:00:09 +00001200 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1201 {
1202 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001203 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001204 return true;
1205 }
1206 else
1207 {
1208 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001209 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001210 }
1211 }
1212 else
1213 {
1214 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001215 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001216 return true;
1217 }
1218 }
1219 else
1220 {
1221 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001222 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001223 }
1224 return false;
1225 }
Greg Clayton576d8832011-03-22 04:00:09 +00001226 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001227 else
1228 {
1229 if (log)
1230 log->Printf ("SendInterrupt () - not running");
1231 }
Greg Clayton576d8832011-03-22 04:00:09 +00001232 return true;
1233}
1234
1235lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001236GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +00001237{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001238 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001239 return m_curr_pid;
1240
1241 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001242 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001243 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +00001244 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001245 // We really got it.
1246 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +00001247 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001248 else
1249 {
Todd Fialae24614f2014-05-14 00:15:32 +00001250 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1251 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1252 // The gdb remote protocol documents $qC as returning the thread id, which newer
1253 // debugserver and lldb-gdbserver stubs return correctly.
1254 StringExtractorGDBRemote response;
1255 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001256 {
Todd Fialae24614f2014-05-14 00:15:32 +00001257 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001258 {
Todd Fialae24614f2014-05-14 00:15:32 +00001259 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001260 {
Todd Fialae24614f2014-05-14 00:15:32 +00001261 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1262 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001263 {
Todd Fialae24614f2014-05-14 00:15:32 +00001264 m_curr_pid_is_valid = eLazyBoolYes;
1265 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001266 }
1267 }
1268 }
1269 }
1270 }
1271
Greg Clayton576d8832011-03-22 04:00:09 +00001272 return LLDB_INVALID_PROCESS_ID;
1273}
1274
1275bool
1276GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1277{
1278 error_str.clear();
1279 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001280 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001281 {
1282 if (response.IsOKResponse())
1283 return true;
1284 if (response.GetChar() == 'E')
1285 {
1286 // A string the describes what failed when launching...
1287 error_str = response.GetStringRef().substr(1);
1288 }
1289 else
1290 {
1291 error_str.assign ("unknown error occurred launching process");
1292 }
1293 }
1294 else
1295 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001296 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001297 }
1298 return false;
1299}
1300
1301int
Greg Claytonfbb76342013-11-20 21:07:01 +00001302GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001303{
Greg Claytonfbb76342013-11-20 21:07:01 +00001304 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001305 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +00001306 std::vector<const char *> argv;
1307 FileSpec exe_file = launch_info.GetExecutableFile();
1308 std::string exe_path;
1309 const char *arg = NULL;
1310 const Args &launch_args = launch_info.GetArguments();
1311 if (exe_file)
Chaoren Linf34f4102015-05-09 01:21:32 +00001312 exe_path = exe_file.GetPath();
Greg Claytonfbb76342013-11-20 21:07:01 +00001313 else
1314 {
1315 arg = launch_args.GetArgumentAtIndex(0);
1316 if (arg)
1317 exe_path = arg;
1318 }
1319 if (!exe_path.empty())
1320 {
1321 argv.push_back(exe_path.c_str());
1322 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1323 {
1324 if (arg)
1325 argv.push_back(arg);
1326 }
1327 }
1328 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001329 {
1330 StreamString packet;
1331 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001332 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001333 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001334 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001335 const int arg_len = strlen(arg);
1336 if (i > 0)
1337 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001338 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001339 packet.PutBytesAsRawHex8 (arg, arg_len);
1340 }
1341
1342 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001343 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001344 {
1345 if (response.IsOKResponse())
1346 return 0;
1347 uint8_t error = response.GetError();
1348 if (error)
1349 return error;
1350 }
1351 }
1352 return -1;
1353}
1354
1355int
1356GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1357{
1358 if (name_equal_value && name_equal_value[0])
1359 {
1360 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001361 bool send_hex_encoding = false;
1362 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001363 {
Greg Clayton89600582013-10-10 17:53:50 +00001364 if (isprint(*p))
1365 {
1366 switch (*p)
1367 {
1368 case '$':
1369 case '#':
1370 send_hex_encoding = true;
1371 break;
1372 default:
1373 break;
1374 }
1375 }
1376 else
1377 {
1378 // We have non printable characters, lets hex encode this...
1379 send_hex_encoding = true;
1380 }
1381 }
1382
1383 StringExtractorGDBRemote response;
1384 if (send_hex_encoding)
1385 {
1386 if (m_supports_QEnvironmentHexEncoded)
1387 {
1388 packet.PutCString("QEnvironmentHexEncoded:");
1389 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001390 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001391 {
1392 if (response.IsOKResponse())
1393 return 0;
1394 uint8_t error = response.GetError();
1395 if (error)
1396 return error;
1397 if (response.IsUnsupportedResponse())
1398 m_supports_QEnvironmentHexEncoded = false;
1399 }
1400 }
1401
1402 }
1403 else if (m_supports_QEnvironment)
1404 {
1405 packet.Printf("QEnvironment:%s", 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_QEnvironment = false;
1415 }
Greg Clayton576d8832011-03-22 04:00:09 +00001416 }
1417 }
1418 return -1;
1419}
1420
Greg Claytonc4103b32011-05-08 04:53:50 +00001421int
1422GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1423{
1424 if (arch && arch[0])
1425 {
1426 StreamString packet;
1427 packet.Printf("QLaunchArch:%s", arch);
1428 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001429 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001430 {
1431 if (response.IsOKResponse())
1432 return 0;
1433 uint8_t error = response.GetError();
1434 if (error)
1435 return error;
1436 }
1437 }
1438 return -1;
1439}
1440
Jason Molendaa3329782014-03-29 18:54:20 +00001441int
1442GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1443{
1444 if (data && *data != '\0')
1445 {
1446 StreamString packet;
1447 packet.Printf("QSetProcessEvent:%s", data);
1448 StringExtractorGDBRemote response;
1449 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1450 {
1451 if (response.IsOKResponse())
1452 {
1453 if (was_supported)
1454 *was_supported = true;
1455 return 0;
1456 }
1457 else if (response.IsUnsupportedResponse())
1458 {
1459 if (was_supported)
1460 *was_supported = false;
1461 return -1;
1462 }
1463 else
1464 {
1465 uint8_t error = response.GetError();
1466 if (was_supported)
1467 *was_supported = true;
1468 if (error)
1469 return error;
1470 }
1471 }
1472 }
1473 return -1;
1474}
1475
Greg Clayton576d8832011-03-22 04:00:09 +00001476bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001477GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1478 uint32_t &minor,
1479 uint32_t &update)
1480{
1481 if (GetHostInfo ())
1482 {
1483 if (m_os_version_major != UINT32_MAX)
1484 {
1485 major = m_os_version_major;
1486 minor = m_os_version_minor;
1487 update = m_os_version_update;
1488 return true;
1489 }
1490 }
1491 return false;
1492}
1493
1494bool
1495GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1496{
1497 if (GetHostInfo ())
1498 {
1499 if (!m_os_build.empty())
1500 {
1501 s = m_os_build;
1502 return true;
1503 }
1504 }
1505 s.clear();
1506 return false;
1507}
1508
1509
1510bool
1511GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1512{
1513 if (GetHostInfo ())
1514 {
1515 if (!m_os_kernel.empty())
1516 {
1517 s = m_os_kernel;
1518 return true;
1519 }
1520 }
1521 s.clear();
1522 return false;
1523}
1524
1525bool
1526GDBRemoteCommunicationClient::GetHostname (std::string &s)
1527{
1528 if (GetHostInfo ())
1529 {
1530 if (!m_hostname.empty())
1531 {
1532 s = m_hostname;
1533 return true;
1534 }
1535 }
1536 s.clear();
1537 return false;
1538}
1539
1540ArchSpec
1541GDBRemoteCommunicationClient::GetSystemArchitecture ()
1542{
1543 if (GetHostInfo ())
1544 return m_host_arch;
1545 return ArchSpec();
1546}
1547
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001548const lldb_private::ArchSpec &
1549GDBRemoteCommunicationClient::GetProcessArchitecture ()
1550{
1551 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1552 GetCurrentProcessInfo ();
1553 return m_process_arch;
1554}
1555
Jason Molendaa3329782014-03-29 18:54:20 +00001556bool
1557GDBRemoteCommunicationClient::GetGDBServerVersion()
1558{
1559 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1560 {
1561 m_gdb_server_name.clear();
1562 m_gdb_server_version = 0;
1563 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1564
1565 StringExtractorGDBRemote response;
1566 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1567 {
1568 if (response.IsNormalResponse())
1569 {
1570 std::string name;
1571 std::string value;
1572 bool success = false;
1573 while (response.GetNameColonValue(name, value))
1574 {
1575 if (name.compare("name") == 0)
1576 {
1577 success = true;
1578 m_gdb_server_name.swap(value);
1579 }
1580 else if (name.compare("version") == 0)
1581 {
1582 size_t dot_pos = value.find('.');
1583 if (dot_pos != std::string::npos)
1584 value[dot_pos] = '\0';
Vince Harron5275aaa2015-01-15 20:08:35 +00001585 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molendaa3329782014-03-29 18:54:20 +00001586 if (version != UINT32_MAX)
1587 {
1588 success = true;
1589 m_gdb_server_version = version;
1590 }
1591 }
1592 }
1593 if (success)
1594 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1595 }
1596 }
1597 }
1598 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1599}
1600
1601const char *
1602GDBRemoteCommunicationClient::GetGDBServerProgramName()
1603{
1604 if (GetGDBServerVersion())
1605 {
1606 if (!m_gdb_server_name.empty())
1607 return m_gdb_server_name.c_str();
1608 }
1609 return NULL;
1610}
1611
1612uint32_t
1613GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1614{
1615 if (GetGDBServerVersion())
1616 return m_gdb_server_version;
1617 return 0;
1618}
Greg Clayton1cb64962011-03-24 04:28:38 +00001619
1620bool
Ewan Crawford78baa192015-05-13 09:18:18 +00001621GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1622{
1623 StringExtractorGDBRemote response;
1624 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1625 return false;
1626
1627 if (!response.IsNormalResponse())
1628 return false;
1629
1630 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1631 tid = response.GetHexMaxU32(true, -1);
1632
1633 return true;
1634}
1635
1636bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001637GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001638{
Todd Fialaaf245d12014-06-30 21:05:18 +00001639 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1640
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001641 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001642 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001643 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001644 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001645 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001646 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001647 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001648 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001649 std::string name;
1650 std::string value;
1651 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1652 uint32_t sub = 0;
1653 std::string arch_name;
1654 std::string os_name;
1655 std::string vendor_name;
1656 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001657 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00001658 uint32_t pointer_byte_size = 0;
1659 StringExtractor extractor;
1660 ByteOrder byte_order = eByteOrderInvalid;
1661 uint32_t num_keys_decoded = 0;
1662 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001663 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001664 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001665 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001666 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001667 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001668 if (cpu != LLDB_INVALID_CPUTYPE)
1669 ++num_keys_decoded;
1670 }
1671 else if (name.compare("cpusubtype") == 0)
1672 {
1673 // exception count in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00001674 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001675 if (sub != 0)
1676 ++num_keys_decoded;
1677 }
1678 else if (name.compare("arch") == 0)
1679 {
1680 arch_name.swap (value);
1681 ++num_keys_decoded;
1682 }
1683 else if (name.compare("triple") == 0)
1684 {
Greg Clayton44272a42014-09-18 00:18:32 +00001685 extractor.GetStringRef ().swap (value);
1686 extractor.SetFilePos(0);
1687 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00001688 ++num_keys_decoded;
1689 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001690 else if (name.compare ("distribution_id") == 0)
1691 {
1692 extractor.GetStringRef ().swap (value);
1693 extractor.SetFilePos (0);
1694 extractor.GetHexByteString (distribution_id);
1695 ++num_keys_decoded;
1696 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001697 else if (name.compare("os_build") == 0)
1698 {
1699 extractor.GetStringRef().swap(value);
1700 extractor.SetFilePos(0);
1701 extractor.GetHexByteString (m_os_build);
1702 ++num_keys_decoded;
1703 }
1704 else if (name.compare("hostname") == 0)
1705 {
1706 extractor.GetStringRef().swap(value);
1707 extractor.SetFilePos(0);
1708 extractor.GetHexByteString (m_hostname);
1709 ++num_keys_decoded;
1710 }
1711 else if (name.compare("os_kernel") == 0)
1712 {
1713 extractor.GetStringRef().swap(value);
1714 extractor.SetFilePos(0);
1715 extractor.GetHexByteString (m_os_kernel);
1716 ++num_keys_decoded;
1717 }
1718 else if (name.compare("ostype") == 0)
1719 {
1720 os_name.swap (value);
1721 ++num_keys_decoded;
1722 }
1723 else if (name.compare("vendor") == 0)
1724 {
1725 vendor_name.swap(value);
1726 ++num_keys_decoded;
1727 }
1728 else if (name.compare("endian") == 0)
1729 {
1730 ++num_keys_decoded;
1731 if (value.compare("little") == 0)
1732 byte_order = eByteOrderLittle;
1733 else if (value.compare("big") == 0)
1734 byte_order = eByteOrderBig;
1735 else if (value.compare("pdp") == 0)
1736 byte_order = eByteOrderPDP;
1737 else
1738 --num_keys_decoded;
1739 }
1740 else if (name.compare("ptrsize") == 0)
1741 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001742 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00001743 if (pointer_byte_size != 0)
1744 ++num_keys_decoded;
1745 }
1746 else if (name.compare("os_version") == 0)
1747 {
1748 Args::StringToVersion (value.c_str(),
1749 m_os_version_major,
1750 m_os_version_minor,
1751 m_os_version_update);
1752 if (m_os_version_major != UINT32_MAX)
1753 ++num_keys_decoded;
1754 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001755 else if (name.compare("watchpoint_exceptions_received") == 0)
1756 {
1757 ++num_keys_decoded;
1758 if (strcmp(value.c_str(),"before") == 0)
1759 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1760 else if (strcmp(value.c_str(),"after") == 0)
1761 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1762 else
1763 --num_keys_decoded;
1764 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001765 else if (name.compare("default_packet_timeout") == 0)
1766 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001767 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001768 if (m_default_packet_timeout > 0)
1769 {
1770 SetPacketTimeout(m_default_packet_timeout);
1771 ++num_keys_decoded;
1772 }
1773 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001774
Greg Clayton32e0a752011-03-30 18:16:51 +00001775 }
1776
1777 if (num_keys_decoded > 0)
1778 m_qHostInfo_is_valid = eLazyBoolYes;
1779
1780 if (triple.empty())
1781 {
1782 if (arch_name.empty())
1783 {
1784 if (cpu != LLDB_INVALID_CPUTYPE)
1785 {
1786 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1787 if (pointer_byte_size)
1788 {
1789 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1790 }
1791 if (byte_order != eByteOrderInvalid)
1792 {
1793 assert (byte_order == m_host_arch.GetByteOrder());
1794 }
Greg Clayton70512312012-05-08 01:45:38 +00001795
1796 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1797 {
1798 switch (m_host_arch.GetMachine())
1799 {
Todd Fialad8eaa172014-07-23 14:37:35 +00001800 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00001801 case llvm::Triple::arm:
1802 case llvm::Triple::thumb:
1803 os_name = "ios";
1804 break;
1805 default:
1806 os_name = "macosx";
1807 break;
1808 }
1809 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001810 if (!vendor_name.empty())
1811 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1812 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001813 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001814
1815 }
1816 }
1817 else
1818 {
1819 std::string triple;
1820 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001821 if (!vendor_name.empty() || !os_name.empty())
1822 {
1823 triple += '-';
1824 if (vendor_name.empty())
1825 triple += "unknown";
1826 else
1827 triple += vendor_name;
1828 triple += '-';
1829 if (os_name.empty())
1830 triple += "unknown";
1831 else
1832 triple += os_name;
1833 }
1834 m_host_arch.SetTriple (triple.c_str());
1835
1836 llvm::Triple &host_triple = m_host_arch.GetTriple();
1837 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1838 {
1839 switch (m_host_arch.GetMachine())
1840 {
Todd Fialad8eaa172014-07-23 14:37:35 +00001841 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00001842 case llvm::Triple::arm:
1843 case llvm::Triple::thumb:
1844 host_triple.setOS(llvm::Triple::IOS);
1845 break;
1846 default:
1847 host_triple.setOS(llvm::Triple::MacOSX);
1848 break;
1849 }
1850 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001851 if (pointer_byte_size)
1852 {
1853 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1854 }
1855 if (byte_order != eByteOrderInvalid)
1856 {
1857 assert (byte_order == m_host_arch.GetByteOrder());
1858 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001859
Greg Clayton1cb64962011-03-24 04:28:38 +00001860 }
1861 }
1862 else
1863 {
Greg Clayton70512312012-05-08 01:45:38 +00001864 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001865 if (pointer_byte_size)
1866 {
1867 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1868 }
1869 if (byte_order != eByteOrderInvalid)
1870 {
1871 assert (byte_order == m_host_arch.GetByteOrder());
1872 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001873
1874 if (log)
1875 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 +00001876 }
1877 if (!distribution_id.empty ())
1878 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00001879 }
Greg Clayton576d8832011-03-22 04:00:09 +00001880 }
1881 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001882 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001883}
1884
1885int
1886GDBRemoteCommunicationClient::SendAttach
1887(
1888 lldb::pid_t pid,
1889 StringExtractorGDBRemote& response
1890)
1891{
1892 if (pid != LLDB_INVALID_PROCESS_ID)
1893 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001894 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001895 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001896 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00001897 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001898 {
1899 if (response.IsErrorResponse())
1900 return response.GetError();
1901 return 0;
1902 }
1903 }
1904 return -1;
1905}
1906
Vince Harrone0be4252015-02-06 18:32:57 +00001907int
1908GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
1909{
1910 StreamString packet;
1911 packet.PutCString("I");
1912 packet.PutBytesAsRawHex8(data, data_len);
1913 StringExtractorGDBRemote response;
1914 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1915 {
1916 return 0;
1917 }
1918 return response.GetError();
1919
1920}
1921
Greg Clayton576d8832011-03-22 04:00:09 +00001922const lldb_private::ArchSpec &
1923GDBRemoteCommunicationClient::GetHostArchitecture ()
1924{
Greg Clayton32e0a752011-03-30 18:16:51 +00001925 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001926 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001927 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001928}
1929
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00001930uint32_t
1931GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
1932{
1933 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
1934 GetHostInfo ();
1935 return m_default_packet_timeout;
1936}
1937
Greg Clayton576d8832011-03-22 04:00:09 +00001938addr_t
1939GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1940{
Greg Clayton70b57652011-05-15 01:25:55 +00001941 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001942 {
Greg Clayton70b57652011-05-15 01:25:55 +00001943 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001944 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001945 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001946 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001947 permissions & lldb::ePermissionsReadable ? "r" : "",
1948 permissions & lldb::ePermissionsWritable ? "w" : "",
1949 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001950 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001951 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001952 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001953 {
Todd Fialaf105f582014-06-21 00:48:09 +00001954 if (response.IsUnsupportedResponse())
1955 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1956 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001957 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1958 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001959 else
1960 {
1961 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1962 }
Greg Clayton576d8832011-03-22 04:00:09 +00001963 }
1964 return LLDB_INVALID_ADDRESS;
1965}
1966
1967bool
1968GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1969{
Greg Clayton70b57652011-05-15 01:25:55 +00001970 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001971 {
Greg Clayton70b57652011-05-15 01:25:55 +00001972 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001973 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001974 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001975 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001976 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001977 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00001978 {
Todd Fialaf105f582014-06-21 00:48:09 +00001979 if (response.IsUnsupportedResponse())
1980 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1981 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001982 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001983 }
1984 else
1985 {
1986 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00001987 }
Greg Clayton576d8832011-03-22 04:00:09 +00001988 }
1989 return false;
1990}
1991
Jim Inghamacff8952013-05-02 00:27:30 +00001992Error
1993GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00001994{
Jim Inghamacff8952013-05-02 00:27:30 +00001995 Error error;
1996
1997 if (keep_stopped)
1998 {
1999 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
2000 {
2001 char packet[64];
2002 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002003 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00002004 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002005 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002006 {
2007 m_supports_detach_stay_stopped = eLazyBoolYes;
2008 }
2009 else
2010 {
2011 m_supports_detach_stay_stopped = eLazyBoolNo;
2012 }
2013 }
2014
2015 if (m_supports_detach_stay_stopped == eLazyBoolNo)
2016 {
2017 error.SetErrorString("Stays stopped not supported by this target.");
2018 return error;
2019 }
2020 else
2021 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002022 StringExtractorGDBRemote response;
2023 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002024 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002025 error.SetErrorString ("Sending extended disconnect packet failed.");
2026 }
2027 }
2028 else
2029 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002030 StringExtractorGDBRemote response;
2031 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002032 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002033 error.SetErrorString ("Sending disconnect packet failed.");
2034 }
2035 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00002036}
2037
Greg Clayton46fb5582011-11-18 07:03:08 +00002038Error
2039GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2040 lldb_private::MemoryRegionInfo &region_info)
2041{
2042 Error error;
2043 region_info.Clear();
2044
2045 if (m_supports_memory_region_info != eLazyBoolNo)
2046 {
2047 m_supports_memory_region_info = eLazyBoolYes;
2048 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002049 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002050 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00002051 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002052 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00002053 {
2054 std::string name;
2055 std::string value;
2056 addr_t addr_value;
2057 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00002058 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00002059 while (success && response.GetNameColonValue(name, value))
2060 {
2061 if (name.compare ("start") == 0)
2062 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002063 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002064 if (success)
2065 region_info.GetRange().SetRangeBase(addr_value);
2066 }
2067 else if (name.compare ("size") == 0)
2068 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002069 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002070 if (success)
2071 region_info.GetRange().SetByteSize (addr_value);
2072 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002073 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00002074 {
Jason Molendacb349ee2011-12-13 05:39:38 +00002075 saw_permissions = true;
2076 if (region_info.GetRange().Contains (addr))
2077 {
2078 if (value.find('r') != std::string::npos)
2079 region_info.SetReadable (MemoryRegionInfo::eYes);
2080 else
2081 region_info.SetReadable (MemoryRegionInfo::eNo);
2082
2083 if (value.find('w') != std::string::npos)
2084 region_info.SetWritable (MemoryRegionInfo::eYes);
2085 else
2086 region_info.SetWritable (MemoryRegionInfo::eNo);
2087
2088 if (value.find('x') != std::string::npos)
2089 region_info.SetExecutable (MemoryRegionInfo::eYes);
2090 else
2091 region_info.SetExecutable (MemoryRegionInfo::eNo);
2092 }
2093 else
2094 {
2095 // The reported region does not contain this address -- we're looking at an unmapped page
2096 region_info.SetReadable (MemoryRegionInfo::eNo);
2097 region_info.SetWritable (MemoryRegionInfo::eNo);
2098 region_info.SetExecutable (MemoryRegionInfo::eNo);
2099 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002100 }
2101 else if (name.compare ("error") == 0)
2102 {
2103 StringExtractorGDBRemote name_extractor;
2104 // Swap "value" over into "name_extractor"
2105 name_extractor.GetStringRef().swap(value);
2106 // Now convert the HEX bytes into a string value
2107 name_extractor.GetHexByteString (value);
2108 error.SetErrorString(value.c_str());
2109 }
2110 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002111
2112 // We got a valid address range back but no permissions -- which means this is an unmapped page
2113 if (region_info.GetRange().IsValid() && saw_permissions == false)
2114 {
2115 region_info.SetReadable (MemoryRegionInfo::eNo);
2116 region_info.SetWritable (MemoryRegionInfo::eNo);
2117 region_info.SetExecutable (MemoryRegionInfo::eNo);
2118 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002119 }
2120 else
2121 {
2122 m_supports_memory_region_info = eLazyBoolNo;
2123 }
2124 }
2125
2126 if (m_supports_memory_region_info == eLazyBoolNo)
2127 {
2128 error.SetErrorString("qMemoryRegionInfo is not supported");
2129 }
2130 if (error.Fail())
2131 region_info.Clear();
2132 return error;
2133
2134}
2135
Johnny Chen64637202012-05-23 21:09:52 +00002136Error
2137GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2138{
2139 Error error;
2140
2141 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2142 {
2143 num = m_num_supported_hardware_watchpoints;
2144 return error;
2145 }
2146
2147 // Set num to 0 first.
2148 num = 0;
2149 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2150 {
2151 char packet[64];
2152 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002153 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00002154 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002155 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00002156 {
2157 m_supports_watchpoint_support_info = eLazyBoolYes;
2158 std::string name;
2159 std::string value;
2160 while (response.GetNameColonValue(name, value))
2161 {
2162 if (name.compare ("num") == 0)
2163 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002164 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
Johnny Chen64637202012-05-23 21:09:52 +00002165 m_num_supported_hardware_watchpoints = num;
2166 }
2167 }
2168 }
2169 else
2170 {
2171 m_supports_watchpoint_support_info = eLazyBoolNo;
2172 }
2173 }
2174
2175 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2176 {
2177 error.SetErrorString("qWatchpointSupportInfo is not supported");
2178 }
2179 return error;
2180
2181}
Greg Clayton46fb5582011-11-18 07:03:08 +00002182
Enrico Granataf04a2192012-07-13 23:18:48 +00002183lldb_private::Error
2184GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2185{
2186 Error error(GetWatchpointSupportInfo(num));
2187 if (error.Success())
2188 error = GetWatchpointsTriggerAfterInstruction(after);
2189 return error;
2190}
2191
2192lldb_private::Error
2193GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
2194{
2195 Error error;
2196
2197 // we assume watchpoints will happen after running the relevant opcode
2198 // and we only want to override this behavior if we have explicitly
2199 // received a qHostInfo telling us otherwise
2200 if (m_qHostInfo_is_valid != eLazyBoolYes)
2201 after = true;
2202 else
2203 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
2204 return error;
2205}
2206
Greg Clayton576d8832011-03-22 04:00:09 +00002207int
2208GDBRemoteCommunicationClient::SetSTDIN (char const *path)
2209{
2210 if (path && path[0])
2211 {
2212 StreamString packet;
2213 packet.PutCString("QSetSTDIN:");
2214 packet.PutBytesAsRawHex8(path, strlen(path));
2215
2216 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002217 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002218 {
2219 if (response.IsOKResponse())
2220 return 0;
2221 uint8_t error = response.GetError();
2222 if (error)
2223 return error;
2224 }
2225 }
2226 return -1;
2227}
2228
2229int
2230GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
2231{
2232 if (path && path[0])
2233 {
2234 StreamString packet;
2235 packet.PutCString("QSetSTDOUT:");
2236 packet.PutBytesAsRawHex8(path, strlen(path));
2237
2238 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002239 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002240 {
2241 if (response.IsOKResponse())
2242 return 0;
2243 uint8_t error = response.GetError();
2244 if (error)
2245 return error;
2246 }
2247 }
2248 return -1;
2249}
2250
2251int
2252GDBRemoteCommunicationClient::SetSTDERR (char const *path)
2253{
2254 if (path && path[0])
2255 {
2256 StreamString packet;
2257 packet.PutCString("QSetSTDERR:");
2258 packet.PutBytesAsRawHex8(path, strlen(path));
2259
2260 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002261 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002262 {
2263 if (response.IsOKResponse())
2264 return 0;
2265 uint8_t error = response.GetError();
2266 if (error)
2267 return error;
2268 }
2269 }
2270 return -1;
2271}
2272
Greg Claytonfbb76342013-11-20 21:07:01 +00002273bool
2274GDBRemoteCommunicationClient::GetWorkingDir (std::string &cwd)
2275{
2276 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002277 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002278 {
2279 if (response.IsUnsupportedResponse())
2280 return false;
2281 if (response.IsErrorResponse())
2282 return false;
2283 response.GetHexByteString (cwd);
2284 return !cwd.empty();
2285 }
2286 return false;
2287}
2288
Greg Clayton576d8832011-03-22 04:00:09 +00002289int
2290GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
2291{
2292 if (path && path[0])
2293 {
2294 StreamString packet;
2295 packet.PutCString("QSetWorkingDir:");
2296 packet.PutBytesAsRawHex8(path, strlen(path));
2297
2298 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002299 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002300 {
2301 if (response.IsOKResponse())
2302 return 0;
2303 uint8_t error = response.GetError();
2304 if (error)
2305 return error;
2306 }
2307 }
2308 return -1;
2309}
2310
2311int
2312GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2313{
Greg Clayton32e0a752011-03-30 18:16:51 +00002314 char packet[32];
2315 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002316 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002317 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002318 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002319 {
2320 if (response.IsOKResponse())
2321 return 0;
2322 uint8_t error = response.GetError();
2323 if (error)
2324 return error;
2325 }
2326 return -1;
2327}
Greg Clayton32e0a752011-03-30 18:16:51 +00002328
Jim Ingham106d0282014-06-25 02:32:56 +00002329int
2330GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2331{
2332 char packet[32];
2333 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2334 assert (packet_len < (int)sizeof(packet));
2335 StringExtractorGDBRemote response;
2336 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2337 {
2338 if (response.IsOKResponse())
2339 return 0;
2340 uint8_t error = response.GetError();
2341 if (error)
2342 return error;
2343 }
2344 return -1;
2345}
2346
2347
Greg Clayton32e0a752011-03-30 18:16:51 +00002348bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002349GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002350{
2351 if (response.IsNormalResponse())
2352 {
2353 std::string name;
2354 std::string value;
2355 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002356
2357 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2358 uint32_t sub = 0;
2359 std::string vendor;
2360 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002361
2362 while (response.GetNameColonValue(name, value))
2363 {
2364 if (name.compare("pid") == 0)
2365 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002366 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002367 }
2368 else if (name.compare("ppid") == 0)
2369 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002370 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002371 }
2372 else if (name.compare("uid") == 0)
2373 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002374 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002375 }
2376 else if (name.compare("euid") == 0)
2377 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002378 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002379 }
2380 else if (name.compare("gid") == 0)
2381 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002382 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002383 }
2384 else if (name.compare("egid") == 0)
2385 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002386 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002387 }
2388 else if (name.compare("triple") == 0)
2389 {
Greg Clayton44272a42014-09-18 00:18:32 +00002390 StringExtractor extractor;
2391 extractor.GetStringRef().swap(value);
2392 extractor.SetFilePos(0);
2393 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002394 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002395 }
2396 else if (name.compare("name") == 0)
2397 {
2398 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002399 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002400 // control the characters in a process name
2401 extractor.GetStringRef().swap(value);
2402 extractor.SetFilePos(0);
2403 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002404 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002405 }
Jason Molenda89c37492014-01-27 22:23:20 +00002406 else if (name.compare("cputype") == 0)
2407 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002408 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002409 }
2410 else if (name.compare("cpusubtype") == 0)
2411 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002412 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002413 }
2414 else if (name.compare("vendor") == 0)
2415 {
2416 vendor = value;
2417 }
2418 else if (name.compare("ostype") == 0)
2419 {
2420 os_type = value;
2421 }
2422 }
2423
2424 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2425 {
2426 if (vendor == "apple")
2427 {
2428 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2429 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2430 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2431 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002432 }
2433
2434 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2435 return true;
2436 }
2437 return false;
2438}
2439
2440bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002441GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002442{
2443 process_info.Clear();
2444
2445 if (m_supports_qProcessInfoPID)
2446 {
2447 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002448 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002449 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002450 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002451 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002452 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002453 return DecodeProcessInfoResponse (response, process_info);
2454 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002455 else
2456 {
2457 m_supports_qProcessInfoPID = false;
2458 return false;
2459 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002460 }
2461 return false;
2462}
2463
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002464bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002465GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002466{
Todd Fiala3daa1762014-09-15 16:01:29 +00002467 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2468
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002469 if (allow_lazy)
2470 {
2471 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2472 return true;
2473 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2474 return false;
2475 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002476
2477 GetHostInfo ();
2478
2479 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002480 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002481 {
2482 if (response.IsNormalResponse())
2483 {
2484 std::string name;
2485 std::string value;
2486 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2487 uint32_t sub = 0;
2488 std::string arch_name;
2489 std::string os_name;
2490 std::string vendor_name;
2491 std::string triple;
2492 uint32_t pointer_byte_size = 0;
2493 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002494 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002495 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002496 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002497 while (response.GetNameColonValue(name, value))
2498 {
2499 if (name.compare("cputype") == 0)
2500 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002501 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002502 if (cpu != LLDB_INVALID_CPUTYPE)
2503 ++num_keys_decoded;
2504 }
2505 else if (name.compare("cpusubtype") == 0)
2506 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002507 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002508 if (sub != 0)
2509 ++num_keys_decoded;
2510 }
Todd Fialac540dd02014-08-26 18:21:02 +00002511 else if (name.compare("triple") == 0)
2512 {
Greg Clayton44272a42014-09-18 00:18:32 +00002513 StringExtractor extractor;
2514 extractor.GetStringRef().swap(value);
2515 extractor.SetFilePos(0);
2516 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002517 ++num_keys_decoded;
2518 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002519 else if (name.compare("ostype") == 0)
2520 {
2521 os_name.swap (value);
2522 ++num_keys_decoded;
2523 }
2524 else if (name.compare("vendor") == 0)
2525 {
2526 vendor_name.swap(value);
2527 ++num_keys_decoded;
2528 }
2529 else if (name.compare("endian") == 0)
2530 {
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002531 ++num_keys_decoded;
2532 if (value.compare("little") == 0)
2533 byte_order = eByteOrderLittle;
2534 else if (value.compare("big") == 0)
2535 byte_order = eByteOrderBig;
2536 else if (value.compare("pdp") == 0)
2537 byte_order = eByteOrderPDP;
2538 else
2539 --num_keys_decoded;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002540 }
2541 else if (name.compare("ptrsize") == 0)
2542 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002543 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002544 if (pointer_byte_size != 0)
2545 ++num_keys_decoded;
2546 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002547 else if (name.compare("pid") == 0)
2548 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002549 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002550 if (pid != LLDB_INVALID_PROCESS_ID)
2551 ++num_keys_decoded;
2552 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002553 }
2554 if (num_keys_decoded > 0)
2555 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002556 if (pid != LLDB_INVALID_PROCESS_ID)
2557 {
2558 m_curr_pid_is_valid = eLazyBoolYes;
2559 m_curr_pid = pid;
2560 }
Todd Fialac540dd02014-08-26 18:21:02 +00002561
2562 // Set the ArchSpec from the triple if we have it.
2563 if (!triple.empty ())
2564 {
2565 m_process_arch.SetTriple (triple.c_str ());
2566 if (pointer_byte_size)
2567 {
2568 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2569 }
2570 }
2571 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002572 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002573 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2574
2575 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2576 switch (triple.getObjectFormat()) {
2577 case llvm::Triple::MachO:
2578 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2579 break;
2580 case llvm::Triple::ELF:
2581 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2582 break;
2583 case llvm::Triple::COFF:
2584 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2585 break;
2586 case llvm::Triple::UnknownObjectFormat:
2587 if (log)
2588 log->Printf("error: failed to determine target architecture");
2589 return false;
2590 }
2591
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002592 if (pointer_byte_size)
2593 {
2594 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2595 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002596 if (byte_order != eByteOrderInvalid)
2597 {
2598 assert (byte_order == m_process_arch.GetByteOrder());
2599 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002600 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002601 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002602 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2603 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002604 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002605 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002606 }
2607 }
2608 else
2609 {
2610 m_qProcessInfo_is_valid = eLazyBoolNo;
2611 }
2612
2613 return false;
2614}
2615
2616
Greg Clayton32e0a752011-03-30 18:16:51 +00002617uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002618GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2619 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002620{
2621 process_infos.Clear();
2622
2623 if (m_supports_qfProcessInfo)
2624 {
2625 StreamString packet;
2626 packet.PutCString ("qfProcessInfo");
2627 if (!match_info.MatchAllProcesses())
2628 {
2629 packet.PutChar (':');
2630 const char *name = match_info.GetProcessInfo().GetName();
2631 bool has_name_match = false;
2632 if (name && name[0])
2633 {
2634 has_name_match = true;
2635 NameMatchType name_match_type = match_info.GetNameMatchType();
2636 switch (name_match_type)
2637 {
2638 case eNameMatchIgnore:
2639 has_name_match = false;
2640 break;
2641
2642 case eNameMatchEquals:
2643 packet.PutCString ("name_match:equals;");
2644 break;
2645
2646 case eNameMatchContains:
2647 packet.PutCString ("name_match:contains;");
2648 break;
2649
2650 case eNameMatchStartsWith:
2651 packet.PutCString ("name_match:starts_with;");
2652 break;
2653
2654 case eNameMatchEndsWith:
2655 packet.PutCString ("name_match:ends_with;");
2656 break;
2657
2658 case eNameMatchRegularExpression:
2659 packet.PutCString ("name_match:regex;");
2660 break;
2661 }
2662 if (has_name_match)
2663 {
2664 packet.PutCString ("name:");
2665 packet.PutBytesAsRawHex8(name, ::strlen(name));
2666 packet.PutChar (';');
2667 }
2668 }
2669
2670 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002671 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002672 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00002673 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00002674 if (match_info.GetProcessInfo().UserIDIsValid())
2675 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
2676 if (match_info.GetProcessInfo().GroupIDIsValid())
2677 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00002678 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
2679 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
2680 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2681 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
2682 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
2683 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
2684 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
2685 {
2686 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
2687 const llvm::Triple &triple = match_arch.GetTriple();
2688 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00002689 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002690 packet.PutChar (';');
2691 }
2692 }
2693 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00002694 // Increase timeout as the first qfProcessInfo packet takes a long time
2695 // on Android. The value of 1min was arrived at empirically.
2696 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00002697 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002698 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002699 do
2700 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002701 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002702 if (!DecodeProcessInfoResponse (response, process_info))
2703 break;
2704 process_infos.Append(process_info);
2705 response.GetStringRef().clear();
2706 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00002707 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00002708 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002709 else
2710 {
2711 m_supports_qfProcessInfo = false;
2712 return 0;
2713 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002714 }
2715 return process_infos.GetSize();
2716
2717}
2718
2719bool
2720GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2721{
2722 if (m_supports_qUserName)
2723 {
2724 char packet[32];
2725 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002726 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002727 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002728 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002729 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002730 if (response.IsNormalResponse())
2731 {
2732 // Make sure we parsed the right number of characters. The response is
2733 // the hex encoded user name and should make up the entire packet.
2734 // If there are any non-hex ASCII bytes, the length won't match below..
2735 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2736 return true;
2737 }
2738 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002739 else
2740 {
2741 m_supports_qUserName = false;
2742 return false;
2743 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002744 }
2745 return false;
2746
2747}
2748
2749bool
2750GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2751{
2752 if (m_supports_qGroupName)
2753 {
2754 char packet[32];
2755 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002756 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002757 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002758 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002759 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002760 if (response.IsNormalResponse())
2761 {
2762 // Make sure we parsed the right number of characters. The response is
2763 // the hex encoded group name and should make up the entire packet.
2764 // If there are any non-hex ASCII bytes, the length won't match below..
2765 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2766 return true;
2767 }
2768 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002769 else
2770 {
2771 m_supports_qGroupName = false;
2772 return false;
2773 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002774 }
2775 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002776}
Greg Clayton32e0a752011-03-30 18:16:51 +00002777
Ewan Crawford78baa192015-05-13 09:18:18 +00002778bool
2779GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
2780{
2781 // Form non-stop packet request
2782 char packet[32];
2783 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
2784 assert(packet_len < (int)sizeof(packet));
2785
2786 StringExtractorGDBRemote response;
2787 // Send to target
2788 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
2789 if (response.IsOKResponse())
2790 return true;
2791
2792 // Failed or not supported
2793 return false;
2794
2795}
2796
Greg Claytone034a042015-05-21 20:52:06 +00002797static void
2798MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
2799{
2800 packet.Clear();
2801 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2802 uint32_t bytes_left = send_size;
2803 while (bytes_left > 0)
2804 {
2805 if (bytes_left >= 26)
2806 {
2807 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2808 bytes_left -= 26;
2809 }
2810 else
2811 {
2812 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2813 bytes_left = 0;
2814 }
2815 }
2816}
2817
2818template<typename T>
2819T calculate_standard_deviation(const std::vector<T> &v)
2820{
2821 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
2822 T mean = sum / (T)v.size();
2823 T accum = T(0);
2824 std::for_each (std::begin(v), std::end(v), [&](const T d) {
2825 T delta = d - mean;
2826 accum += delta * delta;
2827 });
2828
2829 T stdev = sqrt(accum / (v.size()-1));
2830 return stdev;
2831}
2832
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002833void
Greg Claytone034a042015-05-21 20:52:06 +00002834GDBRemoteCommunicationClient::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 +00002835{
2836 uint32_t i;
2837 TimeValue start_time, end_time;
2838 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002839 if (SendSpeedTestPacket (0, 0))
2840 {
Greg Claytone034a042015-05-21 20:52:06 +00002841 StreamString packet;
2842 if (json)
2843 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
2844 else
2845 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
2846 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00002847
Greg Claytone034a042015-05-21 20:52:06 +00002848 uint32_t result_idx = 0;
2849 uint32_t send_size;
2850 std::vector<float> packet_times;
2851
2852 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
2853 {
2854 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
2855 {
2856 MakeSpeedTestPacket (packet, send_size, recv_size);
2857
2858 packet_times.clear();
2859 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00002860 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00002861 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00002862 {
Greg Claytone034a042015-05-21 20:52:06 +00002863 TimeValue packet_start_time = TimeValue::Now();
2864 StringExtractorGDBRemote response;
2865 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2866 TimeValue packet_end_time = TimeValue::Now();
2867 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
2868 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002869 }
2870 end_time = TimeValue::Now();
2871 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00002872
2873 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2874 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
2875 float average_ms_per_packet = total_ms / num_packets;
2876 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
2877 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00002878 {
Greg Claytone034a042015-05-21 20:52:06 +00002879 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);
2880 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00002881 }
2882 else
2883 {
Greg Claytone034a042015-05-21 20:52:06 +00002884 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",
2885 send_size,
2886 recv_size,
2887 total_time_nsec / TimeValue::NanoSecPerSec,
2888 total_time_nsec % TimeValue::NanoSecPerSec,
2889 packets_per_second,
2890 average_ms_per_packet,
2891 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00002892 }
Greg Claytone034a042015-05-21 20:52:06 +00002893 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002894 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002895 }
Greg Claytone034a042015-05-21 20:52:06 +00002896
2897 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
2898
2899 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
2900 if (json)
2901 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
2902 else
2903 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
2904 strm.Flush();
2905 send_size = 0;
2906 result_idx = 0;
2907 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
2908 {
2909 MakeSpeedTestPacket (packet, send_size, recv_size);
2910
2911 // If we have a receive size, test how long it takes to receive 4MB of data
2912 if (recv_size > 0)
2913 {
2914 start_time = TimeValue::Now();
2915 uint32_t bytes_read = 0;
2916 uint32_t packet_count = 0;
2917 while (bytes_read < k_recv_amount)
2918 {
2919 StringExtractorGDBRemote response;
2920 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
2921 bytes_read += recv_size;
2922 ++packet_count;
2923 }
2924 end_time = TimeValue::Now();
2925 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
2926 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
2927 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
2928 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
2929 float average_ms_per_packet = total_ms / packet_count;
2930
2931 if (json)
2932 {
2933 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);
2934 ++result_idx;
2935 }
2936 else
2937 {
2938 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",
2939 send_size,
2940 recv_size,
2941 packet_count,
2942 k_recv_amount_mb,
2943 total_time_nsec / TimeValue::NanoSecPerSec,
2944 total_time_nsec % TimeValue::NanoSecPerSec,
2945 mb_second,
2946 packets_per_second,
2947 average_ms_per_packet);
2948 }
2949 strm.Flush();
2950 }
2951 }
2952 if (json)
2953 strm.Printf("\n ]\n }\n}\n");
2954 else
2955 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002956 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002957}
2958
2959bool
2960GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2961{
2962 StreamString packet;
2963 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2964 uint32_t bytes_left = send_size;
2965 while (bytes_left > 0)
2966 {
2967 if (bytes_left >= 26)
2968 {
2969 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2970 bytes_left -= 26;
2971 }
2972 else
2973 {
2974 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2975 bytes_left = 0;
2976 }
2977 }
2978
2979 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002980 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00002981}
Greg Clayton8b82f082011-04-12 05:54:46 +00002982
2983uint16_t
Greg Claytondbf04572013-12-04 19:40:33 +00002984GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid, const char *remote_accept_hostname)
Greg Clayton8b82f082011-04-12 05:54:46 +00002985{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002986 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00002987 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002988 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00002989 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002990 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00002991 if (remote_accept_hostname && remote_accept_hostname[0])
2992 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002993 else
2994 {
Zachary Turner97a14e62014-08-19 17:18:29 +00002995 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00002996 {
2997 // Make the GDB server we launch only accept connections from this host
2998 stream.Printf("host:%s;", hostname.c_str());
2999 }
3000 else
3001 {
3002 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
3003 stream.Printf("host:*;");
3004 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003005 }
3006 const char *packet = stream.GetData();
3007 int packet_len = stream.GetSize();
3008
Vince Harron1b5a74e2015-01-21 22:42:49 +00003009 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00003010 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
3011
3012 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003013 {
3014 std::string name;
3015 std::string value;
3016 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00003017 while (response.GetNameColonValue(name, value))
3018 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00003019 if (name.compare("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003020 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003021 else if (name.compare("pid") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003022 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00003023 }
3024 return port;
3025 }
3026 return 0;
3027}
3028
3029bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00003030GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
3031{
3032 StreamString stream;
3033 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
3034 const char *packet = stream.GetData();
3035 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00003036
Daniel Maleae0f8f572013-08-26 23:57:52 +00003037 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003038 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003039 {
3040 if (response.IsOKResponse())
3041 return true;
3042 }
3043 return false;
3044}
3045
3046bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003047GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003048{
3049 if (m_curr_tid == tid)
3050 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003051
Greg Clayton8b82f082011-04-12 05:54:46 +00003052 char packet[32];
3053 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003054 if (tid == UINT64_MAX)
3055 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003056 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003057 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003058 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003059 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003060 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003061 {
3062 if (response.IsOKResponse())
3063 {
3064 m_curr_tid = tid;
3065 return true;
3066 }
3067 }
3068 return false;
3069}
3070
3071bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003072GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003073{
3074 if (m_curr_tid_run == tid)
3075 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003076
Greg Clayton8b82f082011-04-12 05:54:46 +00003077 char packet[32];
3078 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003079 if (tid == UINT64_MAX)
3080 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003081 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003082 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3083
Andy Gibbsa297a972013-06-19 19:04:53 +00003084 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003085 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003086 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003087 {
3088 if (response.IsOKResponse())
3089 {
3090 m_curr_tid_run = tid;
3091 return true;
3092 }
3093 }
3094 return false;
3095}
3096
3097bool
3098GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3099{
Greg Clayton3dedae12013-12-06 21:45:27 +00003100 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003101 return response.IsNormalResponse();
3102 return false;
3103}
3104
3105bool
Greg Claytonf402f782012-10-13 02:11:55 +00003106GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00003107{
3108 if (m_supports_qThreadStopInfo)
3109 {
3110 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00003111 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003112 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00003113 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003114 {
Greg Claytonef8180a2013-10-15 00:14:28 +00003115 if (response.IsUnsupportedResponse())
3116 m_supports_qThreadStopInfo = false;
3117 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003118 return true;
3119 else
3120 return false;
3121 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003122 else
3123 {
3124 m_supports_qThreadStopInfo = false;
3125 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003126 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003127 return false;
3128}
3129
3130
3131uint8_t
3132GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
3133{
Todd Fiala616b8272014-10-09 00:55:04 +00003134 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3135 if (log)
3136 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3137 __FUNCTION__, insert ? "add" : "remove", addr);
3138
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003139 // Check if the stub is known not to support this breakpoint type
3140 if (!SupportsGDBStoppointPacket(type))
3141 return UINT8_MAX;
3142 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00003143 char packet[64];
3144 const int packet_len = ::snprintf (packet,
3145 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00003146 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00003147 insert ? 'Z' : 'z',
3148 type,
3149 addr,
3150 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003151 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00003152 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003153 StringExtractorGDBRemote response;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003154 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00003155 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003156 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003157 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00003158 if (response.IsOKResponse())
3159 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003160
3161 // Error while setting breakpoint, send back specific error
3162 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003163 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003164
3165 // Empty packet informs us that breakpoint is not supported
3166 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00003167 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003168 // Disable this breakpoint type since it is unsupported
3169 switch (type)
3170 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00003171 case eBreakpointSoftware: m_supports_z0 = false; break;
3172 case eBreakpointHardware: m_supports_z1 = false; break;
3173 case eWatchpointWrite: m_supports_z2 = false; break;
3174 case eWatchpointRead: m_supports_z3 = false; break;
3175 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00003176 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003177 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003178 }
3179 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003180 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00003181 return UINT8_MAX;
3182}
Greg Claytonadc00cb2011-05-20 23:38:13 +00003183
3184size_t
3185GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3186 bool &sequence_mutex_unavailable)
3187{
3188 Mutex::Locker locker;
3189 thread_ids.clear();
3190
Jim Ingham4ceb9282012-06-08 22:50:40 +00003191 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003192 {
3193 sequence_mutex_unavailable = false;
3194 StringExtractorGDBRemote response;
3195
Greg Clayton3dedae12013-12-06 21:45:27 +00003196 PacketResult packet_result;
3197 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3198 packet_result == PacketResult::Success && response.IsNormalResponse();
3199 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003200 {
3201 char ch = response.GetChar();
3202 if (ch == 'l')
3203 break;
3204 if (ch == 'm')
3205 {
3206 do
3207 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00003208 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00003209
3210 if (tid != LLDB_INVALID_THREAD_ID)
3211 {
3212 thread_ids.push_back (tid);
3213 }
3214 ch = response.GetChar(); // Skip the command separator
3215 } while (ch == ','); // Make sure we got a comma separator
3216 }
3217 }
3218 }
3219 else
3220 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00003221#if defined (LLDB_CONFIGURATION_DEBUG)
3222 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3223#else
Greg Clayton5160ce52013-03-27 23:08:40 +00003224 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00003225 if (log)
3226 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00003227#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00003228 sequence_mutex_unavailable = true;
3229 }
3230 return thread_ids.size();
3231}
Greg Clayton37a0a242012-04-11 00:24:49 +00003232
3233lldb::addr_t
3234GDBRemoteCommunicationClient::GetShlibInfoAddr()
3235{
3236 if (!IsRunning())
3237 {
3238 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003239 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00003240 {
3241 if (response.IsNormalResponse())
3242 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3243 }
3244 }
3245 return LLDB_INVALID_ADDRESS;
3246}
3247
Daniel Maleae0f8f572013-08-26 23:57:52 +00003248lldb_private::Error
3249GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL
3250 const char *working_dir, // Pass NULL to use the current working directory
3251 int *status_ptr, // Pass NULL if you don't want the process exit status
3252 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3253 std::string *command_output, // Pass NULL if you don't want the command output
3254 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
3255{
3256 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003257 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003258 stream.PutBytesAsRawHex8(command, strlen(command));
3259 stream.PutChar(',');
3260 stream.PutHex32(timeout_sec);
3261 if (working_dir && *working_dir)
3262 {
3263 stream.PutChar(',');
3264 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
3265 }
3266 const char *packet = stream.GetData();
3267 int packet_len = stream.GetSize();
3268 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003269 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003270 {
3271 if (response.GetChar() != 'F')
3272 return Error("malformed reply");
3273 if (response.GetChar() != ',')
3274 return Error("malformed reply");
3275 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3276 if (exitcode == UINT32_MAX)
3277 return Error("unable to run remote process");
3278 else if (status_ptr)
3279 *status_ptr = exitcode;
3280 if (response.GetChar() != ',')
3281 return Error("malformed reply");
3282 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3283 if (signo_ptr)
3284 *signo_ptr = signo;
3285 if (response.GetChar() != ',')
3286 return Error("malformed reply");
3287 std::string output;
3288 response.GetEscapedBinaryData(output);
3289 if (command_output)
3290 command_output->assign(output);
3291 return Error();
3292 }
3293 return Error("unable to send packet");
3294}
3295
Greg Claytonfbb76342013-11-20 21:07:01 +00003296Error
3297GDBRemoteCommunicationClient::MakeDirectory (const char *path,
3298 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003299{
3300 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003301 stream.PutCString("qPlatform_mkdir:");
3302 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003303 stream.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00003304 stream.PutBytesAsRawHex8(path, strlen(path));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003305 const char *packet = stream.GetData();
3306 int packet_len = stream.GetSize();
3307 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003308
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003309 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3310 return Error("failed to send '%s' packet", packet);
3311
3312 if (response.GetChar() != 'F')
3313 return Error("invalid response to '%s' packet", packet);
3314
3315 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003316}
3317
Greg Claytonfbb76342013-11-20 21:07:01 +00003318Error
3319GDBRemoteCommunicationClient::SetFilePermissions (const char *path,
3320 uint32_t file_permissions)
3321{
3322 lldb_private::StreamString stream;
3323 stream.PutCString("qPlatform_chmod:");
3324 stream.PutHex32(file_permissions);
3325 stream.PutChar(',');
3326 stream.PutBytesAsRawHex8(path, strlen(path));
3327 const char *packet = stream.GetData();
3328 int packet_len = stream.GetSize();
3329 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003330
3331 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3332 return Error("failed to send '%s' packet", packet);
3333
3334 if (response.GetChar() != 'F')
3335 return Error("invalid response to '%s' packet", packet);
3336
Chaoren Lince36c4c2015-05-05 18:43:19 +00003337 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003338}
3339
Daniel Maleae0f8f572013-08-26 23:57:52 +00003340static uint64_t
3341ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3342 uint64_t fail_result,
3343 Error &error)
3344{
3345 response.SetFilePos(0);
3346 if (response.GetChar() != 'F')
3347 return fail_result;
3348 int32_t result = response.GetS32 (-2);
3349 if (result == -2)
3350 return fail_result;
3351 if (response.GetChar() == ',')
3352 {
3353 int result_errno = response.GetS32 (-2);
3354 if (result_errno != -2)
3355 error.SetError(result_errno, eErrorTypePOSIX);
3356 else
3357 error.SetError(-1, eErrorTypeGeneric);
3358 }
3359 else
3360 error.Clear();
3361 return result;
3362}
3363lldb::user_id_t
3364GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3365 uint32_t flags,
3366 mode_t mode,
3367 Error &error)
3368{
3369 lldb_private::StreamString stream;
3370 stream.PutCString("vFile:open:");
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00003371 std::string path (file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003372 if (path.empty())
3373 return UINT64_MAX;
3374 stream.PutCStringAsRawHex8(path.c_str());
3375 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003376 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003377 stream.PutChar(',');
3378 stream.PutHex32(mode);
3379 const char* packet = stream.GetData();
3380 int packet_len = stream.GetSize();
3381 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003382 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003383 {
3384 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3385 }
3386 return UINT64_MAX;
3387}
3388
3389bool
3390GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3391 Error &error)
3392{
3393 lldb_private::StreamString stream;
3394 stream.Printf("vFile:close:%i", (int)fd);
3395 const char* packet = stream.GetData();
3396 int packet_len = stream.GetSize();
3397 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003398 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003399 {
3400 return ParseHostIOPacketResponse (response, -1, error) == 0;
3401 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003402 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003403}
3404
3405// Extension of host I/O packets to get the file size.
3406lldb::user_id_t
3407GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3408{
3409 lldb_private::StreamString stream;
3410 stream.PutCString("vFile:size:");
3411 std::string path (file_spec.GetPath());
3412 stream.PutCStringAsRawHex8(path.c_str());
3413 const char* packet = stream.GetData();
3414 int packet_len = stream.GetSize();
3415 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003416 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003417 {
3418 if (response.GetChar() != 'F')
3419 return UINT64_MAX;
3420 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3421 return retcode;
3422 }
3423 return UINT64_MAX;
3424}
3425
Greg Claytonfbb76342013-11-20 21:07:01 +00003426Error
3427GDBRemoteCommunicationClient::GetFilePermissions(const char *path, uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003428{
Greg Claytonfbb76342013-11-20 21:07:01 +00003429 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003430 lldb_private::StreamString stream;
3431 stream.PutCString("vFile:mode:");
Greg Claytonfbb76342013-11-20 21:07:01 +00003432 stream.PutCStringAsRawHex8(path);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003433 const char* packet = stream.GetData();
3434 int packet_len = stream.GetSize();
3435 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003436 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003437 {
3438 if (response.GetChar() != 'F')
3439 {
3440 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003441 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003442 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003443 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003444 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003445 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003446 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003447 if (response.GetChar() == ',')
3448 {
3449 int response_errno = response.GetS32(-1);
3450 if (response_errno > 0)
3451 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3452 else
3453 error.SetErrorToGenericError();
3454 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003455 else
3456 error.SetErrorToGenericError();
3457 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003458 else
3459 {
3460 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3461 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003462 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003463 }
3464 else
3465 {
3466 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3467 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003468 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003469}
3470
3471uint64_t
3472GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3473 uint64_t offset,
3474 void *dst,
3475 uint64_t dst_len,
3476 Error &error)
3477{
3478 lldb_private::StreamString stream;
3479 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3480 const char* packet = stream.GetData();
3481 int packet_len = stream.GetSize();
3482 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003483 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003484 {
3485 if (response.GetChar() != 'F')
3486 return 0;
3487 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3488 if (retcode == UINT32_MAX)
3489 return retcode;
3490 const char next = (response.Peek() ? *response.Peek() : 0);
3491 if (next == ',')
3492 return 0;
3493 if (next == ';')
3494 {
3495 response.GetChar(); // skip the semicolon
3496 std::string buffer;
3497 if (response.GetEscapedBinaryData(buffer))
3498 {
3499 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3500 if (data_to_write > 0)
3501 memcpy(dst, &buffer[0], data_to_write);
3502 return data_to_write;
3503 }
3504 }
3505 }
3506 return 0;
3507}
3508
3509uint64_t
3510GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3511 uint64_t offset,
3512 const void* src,
3513 uint64_t src_len,
3514 Error &error)
3515{
3516 lldb_private::StreamGDBRemote stream;
3517 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3518 stream.PutEscapedBytes(src, src_len);
3519 const char* packet = stream.GetData();
3520 int packet_len = stream.GetSize();
3521 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003522 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003523 {
3524 if (response.GetChar() != 'F')
3525 {
3526 error.SetErrorStringWithFormat("write file failed");
3527 return 0;
3528 }
3529 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3530 if (bytes_written == UINT64_MAX)
3531 {
3532 error.SetErrorToGenericError();
3533 if (response.GetChar() == ',')
3534 {
3535 int response_errno = response.GetS32(-1);
3536 if (response_errno > 0)
3537 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3538 }
3539 return 0;
3540 }
3541 return bytes_written;
3542 }
3543 else
3544 {
3545 error.SetErrorString ("failed to send vFile:pwrite packet");
3546 }
3547 return 0;
3548}
3549
Greg Claytonfbb76342013-11-20 21:07:01 +00003550Error
3551GDBRemoteCommunicationClient::CreateSymlink (const char *src, const char *dst)
3552{
3553 Error error;
3554 lldb_private::StreamGDBRemote stream;
3555 stream.PutCString("vFile:symlink:");
3556 // the unix symlink() command reverses its parameters where the dst if first,
3557 // so we follow suit here
3558 stream.PutCStringAsRawHex8(dst);
3559 stream.PutChar(',');
3560 stream.PutCStringAsRawHex8(src);
3561 const char* packet = stream.GetData();
3562 int packet_len = stream.GetSize();
3563 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003564 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003565 {
3566 if (response.GetChar() == 'F')
3567 {
3568 uint32_t result = response.GetU32(UINT32_MAX);
3569 if (result != 0)
3570 {
3571 error.SetErrorToGenericError();
3572 if (response.GetChar() == ',')
3573 {
3574 int response_errno = response.GetS32(-1);
3575 if (response_errno > 0)
3576 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3577 }
3578 }
3579 }
3580 else
3581 {
3582 // Should have returned with 'F<result>[,<errno>]'
3583 error.SetErrorStringWithFormat("symlink failed");
3584 }
3585 }
3586 else
3587 {
3588 error.SetErrorString ("failed to send vFile:symlink packet");
3589 }
3590 return error;
3591}
3592
3593Error
3594GDBRemoteCommunicationClient::Unlink (const char *path)
3595{
3596 Error error;
3597 lldb_private::StreamGDBRemote stream;
3598 stream.PutCString("vFile:unlink:");
3599 // the unix symlink() command reverses its parameters where the dst if first,
3600 // so we follow suit here
3601 stream.PutCStringAsRawHex8(path);
3602 const char* packet = stream.GetData();
3603 int packet_len = stream.GetSize();
3604 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003605 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00003606 {
3607 if (response.GetChar() == 'F')
3608 {
3609 uint32_t result = response.GetU32(UINT32_MAX);
3610 if (result != 0)
3611 {
3612 error.SetErrorToGenericError();
3613 if (response.GetChar() == ',')
3614 {
3615 int response_errno = response.GetS32(-1);
3616 if (response_errno > 0)
3617 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3618 }
3619 }
3620 }
3621 else
3622 {
3623 // Should have returned with 'F<result>[,<errno>]'
3624 error.SetErrorStringWithFormat("unlink failed");
3625 }
3626 }
3627 else
3628 {
3629 error.SetErrorString ("failed to send vFile:unlink packet");
3630 }
3631 return error;
3632}
3633
Daniel Maleae0f8f572013-08-26 23:57:52 +00003634// Extension of host I/O packets to get whether a file exists.
3635bool
3636GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
3637{
3638 lldb_private::StreamString stream;
3639 stream.PutCString("vFile:exists:");
3640 std::string path (file_spec.GetPath());
3641 stream.PutCStringAsRawHex8(path.c_str());
3642 const char* packet = stream.GetData();
3643 int packet_len = stream.GetSize();
3644 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003645 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003646 {
3647 if (response.GetChar() != 'F')
3648 return false;
3649 if (response.GetChar() != ',')
3650 return false;
3651 bool retcode = (response.GetChar() != '0');
3652 return retcode;
3653 }
3654 return false;
3655}
3656
3657bool
3658GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
3659 uint64_t &high,
3660 uint64_t &low)
3661{
3662 lldb_private::StreamString stream;
3663 stream.PutCString("vFile:MD5:");
3664 std::string path (file_spec.GetPath());
3665 stream.PutCStringAsRawHex8(path.c_str());
3666 const char* packet = stream.GetData();
3667 int packet_len = stream.GetSize();
3668 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003669 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003670 {
3671 if (response.GetChar() != 'F')
3672 return false;
3673 if (response.GetChar() != ',')
3674 return false;
3675 if (response.Peek() && *response.Peek() == 'x')
3676 return false;
3677 low = response.GetHexMaxU64(false, UINT64_MAX);
3678 high = response.GetHexMaxU64(false, UINT64_MAX);
3679 return true;
3680 }
3681 return false;
3682}
Greg Claytonf74cf862013-11-13 23:28:31 +00003683
3684bool
Jason Molendaa3329782014-03-29 18:54:20 +00003685GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
3686{
3687 // Some targets have issues with g/G packets and we need to avoid using them
3688 if (m_avoid_g_packets == eLazyBoolCalculate)
3689 {
3690 if (process)
3691 {
3692 m_avoid_g_packets = eLazyBoolNo;
3693 const ArchSpec &arch = process->GetTarget().GetArchitecture();
3694 if (arch.IsValid()
3695 && arch.GetTriple().getVendor() == llvm::Triple::Apple
3696 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00003697 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00003698 {
3699 m_avoid_g_packets = eLazyBoolYes;
3700 uint32_t gdb_server_version = GetGDBServerProgramVersion();
3701 if (gdb_server_version != 0)
3702 {
3703 const char *gdb_server_name = GetGDBServerProgramName();
3704 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
3705 {
3706 if (gdb_server_version >= 310)
3707 m_avoid_g_packets = eLazyBoolNo;
3708 }
3709 }
3710 }
3711 }
3712 }
3713 return m_avoid_g_packets == eLazyBoolYes;
3714}
3715
3716bool
Greg Claytonf74cf862013-11-13 23:28:31 +00003717GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
3718{
3719 Mutex::Locker locker;
3720 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
3721 {
3722 const bool thread_suffix_supported = GetThreadSuffixSupported();
3723
3724 if (thread_suffix_supported || SetCurrentThread(tid))
3725 {
3726 char packet[64];
3727 int packet_len = 0;
3728 if (thread_suffix_supported)
3729 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
3730 else
3731 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
3732 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003733 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003734 }
3735 }
3736 return false;
3737
3738}
3739
3740
3741bool
3742GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
3743{
3744 Mutex::Locker locker;
3745 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
3746 {
3747 const bool thread_suffix_supported = GetThreadSuffixSupported();
3748
3749 if (thread_suffix_supported || SetCurrentThread(tid))
3750 {
3751 char packet[64];
3752 int packet_len = 0;
3753 // Get all registers in one packet
3754 if (thread_suffix_supported)
3755 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
3756 else
3757 packet_len = ::snprintf (packet, sizeof(packet), "g");
3758 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00003759 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00003760 }
3761 }
3762 return false;
3763}
3764bool
3765GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
3766{
3767 save_id = 0; // Set to invalid save ID
3768 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3769 return false;
3770
3771 m_supports_QSaveRegisterState = eLazyBoolYes;
3772 Mutex::Locker locker;
3773 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
3774 {
3775 const bool thread_suffix_supported = GetThreadSuffixSupported();
3776 if (thread_suffix_supported || SetCurrentThread(tid))
3777 {
3778 char packet[256];
3779 if (thread_suffix_supported)
3780 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
3781 else
Ilia K686b1fe2015-02-27 19:43:08 +00003782 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
Greg Claytonf74cf862013-11-13 23:28:31 +00003783
3784 StringExtractorGDBRemote response;
3785
Greg Clayton3dedae12013-12-06 21:45:27 +00003786 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003787 {
3788 if (response.IsUnsupportedResponse())
3789 {
3790 // This packet isn't supported, don't try calling it again
3791 m_supports_QSaveRegisterState = eLazyBoolNo;
3792 }
3793
3794 const uint32_t response_save_id = response.GetU32(0);
3795 if (response_save_id != 0)
3796 {
3797 save_id = response_save_id;
3798 return true;
3799 }
3800 }
3801 }
3802 }
3803 return false;
3804}
3805
3806bool
3807GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
3808{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003809 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00003810 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
3811 // order to be useful
3812 if (m_supports_QSaveRegisterState == eLazyBoolNo)
3813 return false;
3814
3815 Mutex::Locker locker;
3816 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
3817 {
3818 const bool thread_suffix_supported = GetThreadSuffixSupported();
3819 if (thread_suffix_supported || SetCurrentThread(tid))
3820 {
3821 char packet[256];
3822 if (thread_suffix_supported)
3823 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
3824 else
3825 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
3826
3827 StringExtractorGDBRemote response;
3828
Greg Clayton3dedae12013-12-06 21:45:27 +00003829 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00003830 {
3831 if (response.IsOKResponse())
3832 {
3833 return true;
3834 }
3835 else if (response.IsUnsupportedResponse())
3836 {
3837 // This packet isn't supported, don't try calling this packet or
3838 // QSaveRegisterState again...
3839 m_supports_QSaveRegisterState = eLazyBoolNo;
3840 }
3841 }
3842 }
3843 }
3844 return false;
3845}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003846
3847bool
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003848GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003849 const lldb_private::ArchSpec& arch_spec,
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003850 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003851{
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00003852 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003853 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003854 return false;
3855
3856 StreamString packet;
3857 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003858 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003859 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00003860 const auto& triple = arch_spec.GetTriple().getTriple();
3861 packet.PutBytesAsRawHex8(triple.c_str(), triple.size());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003862
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003863 StringExtractorGDBRemote response;
3864 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
3865 return false;
3866
Aidan Doddsdf627e72015-05-05 08:31:55 +00003867 if (response.IsErrorResponse () || response.IsUnsupportedResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003868 return false;
3869
3870 std::string name;
3871 std::string value;
3872 bool success;
3873 StringExtractor extractor;
3874
3875 module_spec.Clear ();
3876 module_spec.GetFileSpec () = module_file_spec;
3877
3878 while (response.GetNameColonValue (name, value))
3879 {
3880 if (name == "uuid" || name == "md5")
3881 {
3882 extractor.GetStringRef ().swap (value);
3883 extractor.SetFilePos (0);
3884 extractor.GetHexByteString (value);
3885 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
3886 }
3887 else if (name == "triple")
3888 {
3889 extractor.GetStringRef ().swap (value);
3890 extractor.SetFilePos (0);
3891 extractor.GetHexByteString (value);
3892 module_spec.GetArchitecture().SetTriple (value.c_str ());
3893 }
3894 else if (name == "file_offset")
3895 {
3896 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
3897 if (success)
3898 module_spec.SetObjectOffset (ival);
3899 }
3900 else if (name == "file_size")
3901 {
3902 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
3903 if (success)
3904 module_spec.SetObjectSize (ival);
3905 }
3906 else if (name == "file_path")
3907 {
3908 extractor.GetStringRef ().swap (value);
3909 extractor.SetFilePos (0);
3910 extractor.GetHexByteString (value);
Chaoren Linf34f4102015-05-09 01:21:32 +00003911 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003912 }
3913 }
3914
3915 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00003916}
Colin Rileyc3c95b22015-04-16 15:51:33 +00003917
3918// query the target remote for extended information using the qXfer packet
3919//
3920// example: object='features', annex='target.xml', out=<xml output>
3921// return: 'true' on success
3922// 'false' on failure (err set)
3923bool
3924GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
3925 const lldb_private::ConstString annex,
3926 std::string & out,
3927 lldb_private::Error & err) {
3928
3929 std::stringstream output;
3930 StringExtractorGDBRemote chunk;
3931
3932 const int size = 0xfff;
3933 int offset = 0;
3934 bool active = true;
3935
3936 // loop until all data has been read
3937 while ( active ) {
3938
3939 // send query extended feature packet
3940 std::stringstream packet;
3941 packet << "qXfer:"
3942 << object.AsCString( ) << ":read:"
3943 << annex.AsCString( ) << ":"
3944 << std::hex << offset << ","
3945 << std::hex << size;
3946
3947 GDBRemoteCommunication::PacketResult res =
3948 SendPacketAndWaitForResponse( packet.str().c_str(),
3949 chunk,
3950 false );
3951
3952 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
3953 err.SetErrorString( "Error sending $qXfer packet" );
3954 return false;
3955 }
3956
3957 const std::string & str = chunk.GetStringRef( );
3958 if ( str.length() == 0 ) {
3959 // should have some data in chunk
3960 err.SetErrorString( "Empty response from $qXfer packet" );
3961 return false;
3962 }
3963
3964 // check packet code
3965 switch ( str[0] ) {
3966 // last chunk
3967 case ( 'l' ):
3968 active = false;
Aidan Doddsed9f6122015-04-29 10:08:17 +00003969 // fall through intentional
Colin Rileyc3c95b22015-04-16 15:51:33 +00003970
3971 // more chunks
3972 case ( 'm' ) :
3973 if ( str.length() > 1 )
3974 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00003975 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00003976 break;
3977
3978 // unknown chunk
3979 default:
3980 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
3981 return false;
3982 }
3983 }
3984
3985 out = output.str( );
3986 err.Success( );
3987 return true;
3988}