blob: 9b7143b792ed525f7b4b09d0bc35f6e6b39c0167 [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"
Greg Clayton0b90be12015-06-23 21:27:50 +000036#include "lldb/Symbol/Symbol.h"
Jason Molendaa3329782014-03-29 18:54:20 +000037#include "lldb/Target/Target.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000038#include "lldb/Target/MemoryRegionInfo.h"
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +000039#include "lldb/Target/UnixSignals.h"
Greg Clayton576d8832011-03-22 04:00:09 +000040
41// Project includes
42#include "Utility/StringExtractorGDBRemote.h"
43#include "ProcessGDBRemote.h"
44#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000045#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000046
Jason Molenda91ffe0a2015-06-18 21:46:06 +000047#if defined (HAVE_LIBCOMPRESSION)
48#include <compression.h>
49#endif
50
Greg Clayton576d8832011-03-22 04:00:09 +000051using namespace lldb;
52using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000053using namespace lldb_private::process_gdb_remote;
Greg Clayton576d8832011-03-22 04:00:09 +000054
55//----------------------------------------------------------------------
56// GDBRemoteCommunicationClient constructor
57//----------------------------------------------------------------------
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000058GDBRemoteCommunicationClient::GDBRemoteCommunicationClient()
59 : GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet"),
60 m_supports_not_sending_acks(eLazyBoolCalculate),
61 m_supports_thread_suffix(eLazyBoolCalculate),
62 m_supports_threads_in_stop_reply(eLazyBoolCalculate),
63 m_supports_vCont_all(eLazyBoolCalculate),
64 m_supports_vCont_any(eLazyBoolCalculate),
65 m_supports_vCont_c(eLazyBoolCalculate),
66 m_supports_vCont_C(eLazyBoolCalculate),
67 m_supports_vCont_s(eLazyBoolCalculate),
68 m_supports_vCont_S(eLazyBoolCalculate),
69 m_qHostInfo_is_valid(eLazyBoolCalculate),
70 m_curr_pid_is_valid(eLazyBoolCalculate),
71 m_qProcessInfo_is_valid(eLazyBoolCalculate),
72 m_qGDBServerVersion_is_valid(eLazyBoolCalculate),
73 m_supports_alloc_dealloc_memory(eLazyBoolCalculate),
74 m_supports_memory_region_info(eLazyBoolCalculate),
75 m_supports_watchpoint_support_info(eLazyBoolCalculate),
76 m_supports_detach_stay_stopped(eLazyBoolCalculate),
77 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
78 m_attach_or_wait_reply(eLazyBoolCalculate),
79 m_prepare_for_reg_writing_reply(eLazyBoolCalculate),
80 m_supports_p(eLazyBoolCalculate),
81 m_supports_x(eLazyBoolCalculate),
82 m_avoid_g_packets(eLazyBoolCalculate),
83 m_supports_QSaveRegisterState(eLazyBoolCalculate),
84 m_supports_qXfer_auxv_read(eLazyBoolCalculate),
85 m_supports_qXfer_libraries_read(eLazyBoolCalculate),
86 m_supports_qXfer_libraries_svr4_read(eLazyBoolCalculate),
87 m_supports_qXfer_features_read(eLazyBoolCalculate),
88 m_supports_augmented_libraries_svr4_read(eLazyBoolCalculate),
89 m_supports_jThreadExtendedInfo(eLazyBoolCalculate),
90 m_supports_jLoadedDynamicLibrariesInfos(eLazyBoolCalculate),
91 m_supports_qProcessInfoPID(true),
92 m_supports_qfProcessInfo(true),
93 m_supports_qUserName(true),
94 m_supports_qGroupName(true),
95 m_supports_qThreadStopInfo(true),
96 m_supports_z0(true),
97 m_supports_z1(true),
98 m_supports_z2(true),
99 m_supports_z3(true),
100 m_supports_z4(true),
101 m_supports_QEnvironment(true),
102 m_supports_QEnvironmentHexEncoded(true),
103 m_supports_qSymbol(true),
104 m_qSymbol_requests_done(false),
105 m_supports_qModuleInfo(true),
106 m_supports_jThreadsInfo(true),
107 m_curr_pid(LLDB_INVALID_PROCESS_ID),
108 m_curr_tid(LLDB_INVALID_THREAD_ID),
109 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
110 m_num_supported_hardware_watchpoints(0),
111 m_async_mutex(),
112 m_async_packet_predicate(false),
113 m_async_packet(),
114 m_async_result(PacketResult::Success),
115 m_async_response(),
116 m_async_signal(-1),
117 m_interrupt_sent(false),
118 m_thread_id_to_used_usec_map(),
119 m_host_arch(),
120 m_process_arch(),
121 m_os_version_major(UINT32_MAX),
122 m_os_version_minor(UINT32_MAX),
123 m_os_version_update(UINT32_MAX),
124 m_os_build(),
125 m_os_kernel(),
126 m_hostname(),
127 m_gdb_server_name(),
128 m_gdb_server_version(UINT32_MAX),
129 m_default_packet_timeout(0),
130 m_max_packet_size(0)
Greg Clayton576d8832011-03-22 04:00:09 +0000131{
Greg Clayton576d8832011-03-22 04:00:09 +0000132}
133
134//----------------------------------------------------------------------
135// Destructor
136//----------------------------------------------------------------------
137GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
138{
Greg Clayton576d8832011-03-22 04:00:09 +0000139 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000140 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000141}
142
143bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000144GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
145{
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000146 ResetDiscoverableSettings(false);
Greg Claytonfb909312013-11-23 01:58:15 +0000147
Greg Clayton1cb64962011-03-24 04:28:38 +0000148 // Start the read thread after we send the handshake ack since if we
149 // fail to send the handshake ack, there is no reason to continue...
150 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000151 {
Ed Maste48f986f2013-12-18 15:31:45 +0000152 // Wait for any responses that might have been queued up in the remote
153 // GDB server and flush them all
154 StringExtractorGDBRemote response;
155 PacketResult packet_result = PacketResult::Success;
156 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
157 while (packet_result == PacketResult::Success)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000158 packet_result = ReadPacket (response, timeout_usec, false);
Ed Maste48f986f2013-12-18 15:31:45 +0000159
Greg Claytonfb909312013-11-23 01:58:15 +0000160 // The return value from QueryNoAckModeSupported() is true if the packet
161 // was sent and _any_ response (including UNIMPLEMENTED) was received),
162 // or false if no response was received. This quickly tells us if we have
163 // a live connection to a remote GDB server...
164 if (QueryNoAckModeSupported())
165 {
166 return true;
167 }
168 else
169 {
170 if (error_ptr)
171 error_ptr->SetErrorString("failed to get reply to handshake packet");
172 }
173 }
174 else
175 {
176 if (error_ptr)
177 error_ptr->SetErrorString("failed to send the handshake ack");
178 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000179 return false;
180}
181
Greg Claytonfb909312013-11-23 01:58:15 +0000182bool
Greg Claytonb30c50c2015-05-29 00:01:55 +0000183GDBRemoteCommunicationClient::GetEchoSupported ()
184{
185 if (m_supports_qEcho == eLazyBoolCalculate)
186 {
187 GetRemoteQSupported();
188 }
189 return m_supports_qEcho == eLazyBoolYes;
190}
191
192
193bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000194GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
195{
196 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
197 {
198 GetRemoteQSupported();
199 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000200 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000201}
202
203bool
204GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
205{
206 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
207 {
208 GetRemoteQSupported();
209 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000210 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000211}
212
213bool
214GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
215{
216 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
217 {
218 GetRemoteQSupported();
219 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000220 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000221}
222
Steve Pucci03904ac2014-03-04 23:18:46 +0000223bool
224GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
225{
226 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
227 {
228 GetRemoteQSupported();
229 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000230 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000231}
232
Colin Rileyc3c95b22015-04-16 15:51:33 +0000233bool
234GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported ()
235{
236 if (m_supports_qXfer_features_read == eLazyBoolCalculate)
237 {
238 GetRemoteQSupported();
239 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000240 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000241}
242
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000243uint64_t
244GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
245{
246 if (m_max_packet_size == 0)
247 {
248 GetRemoteQSupported();
249 }
250 return m_max_packet_size;
251}
252
253bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000254GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000255{
256 if (m_supports_not_sending_acks == eLazyBoolCalculate)
257 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000258 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000259 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000260
Jason Molenda36a216e2014-07-24 01:36:24 +0000261 // This is the first real packet that we'll send in a debug session and it may take a little
262 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
263
264 const uint32_t minimum_timeout = 6;
265 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000266 GDBRemoteCommunication::ScopedTimeout timeout (*this, std::max (old_timeout, minimum_timeout));
Jason Molenda36a216e2014-07-24 01:36:24 +0000267
Greg Clayton1cb64962011-03-24 04:28:38 +0000268 StringExtractorGDBRemote response;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000269 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000270 {
271 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000272 {
273 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000274 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000275 }
Greg Claytonfb909312013-11-23 01:58:15 +0000276 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000277 }
278 }
Greg Claytonfb909312013-11-23 01:58:15 +0000279 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000280}
281
282void
Greg Clayton44633992012-04-10 03:22:03 +0000283GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
284{
285 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
286 {
287 m_supports_threads_in_stop_reply = eLazyBoolNo;
288
289 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000290 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000291 {
292 if (response.IsOKResponse())
293 m_supports_threads_in_stop_reply = eLazyBoolYes;
294 }
295 }
296}
297
Jim Inghamcd16df92012-07-20 21:37:13 +0000298bool
299GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
300{
301 if (m_attach_or_wait_reply == eLazyBoolCalculate)
302 {
303 m_attach_or_wait_reply = eLazyBoolNo;
304
305 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000306 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000307 {
308 if (response.IsOKResponse())
309 m_attach_or_wait_reply = eLazyBoolYes;
310 }
311 }
312 if (m_attach_or_wait_reply == eLazyBoolYes)
313 return true;
314 else
315 return false;
316}
317
Jim Ingham279ceec2012-07-25 21:12:43 +0000318bool
319GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
320{
321 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
322 {
323 m_prepare_for_reg_writing_reply = eLazyBoolNo;
324
325 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000326 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000327 {
328 if (response.IsOKResponse())
329 m_prepare_for_reg_writing_reply = eLazyBoolYes;
330 }
331 }
332 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
333 return true;
334 else
335 return false;
336}
337
Greg Clayton44633992012-04-10 03:22:03 +0000338
339void
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000340GDBRemoteCommunicationClient::ResetDiscoverableSettings (bool did_exec)
Greg Clayton576d8832011-03-22 04:00:09 +0000341{
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000342 if (did_exec == false)
343 {
344 // Hard reset everything, this is when we first connect to a GDB server
345 m_supports_not_sending_acks = eLazyBoolCalculate;
346 m_supports_thread_suffix = eLazyBoolCalculate;
347 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
348 m_supports_vCont_c = eLazyBoolCalculate;
349 m_supports_vCont_C = eLazyBoolCalculate;
350 m_supports_vCont_s = eLazyBoolCalculate;
351 m_supports_vCont_S = eLazyBoolCalculate;
352 m_supports_p = eLazyBoolCalculate;
353 m_supports_x = eLazyBoolCalculate;
354 m_supports_QSaveRegisterState = eLazyBoolCalculate;
355 m_qHostInfo_is_valid = eLazyBoolCalculate;
356 m_curr_pid_is_valid = eLazyBoolCalculate;
357 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
358 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
359 m_supports_memory_region_info = eLazyBoolCalculate;
360 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
361 m_attach_or_wait_reply = eLazyBoolCalculate;
362 m_avoid_g_packets = eLazyBoolCalculate;
363 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
364 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
365 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
366 m_supports_qXfer_features_read = eLazyBoolCalculate;
367 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
368 m_supports_qProcessInfoPID = true;
369 m_supports_qfProcessInfo = true;
370 m_supports_qUserName = true;
371 m_supports_qGroupName = true;
372 m_supports_qThreadStopInfo = true;
373 m_supports_z0 = true;
374 m_supports_z1 = true;
375 m_supports_z2 = true;
376 m_supports_z3 = true;
377 m_supports_z4 = true;
378 m_supports_QEnvironment = true;
379 m_supports_QEnvironmentHexEncoded = true;
380 m_supports_qSymbol = true;
Jason Molenda50018d32016-01-13 04:08:10 +0000381 m_qSymbol_requests_done = false;
Stephane Sezer6f455292016-01-08 00:00:17 +0000382 m_supports_qModuleInfo = true;
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000383 m_host_arch.Clear();
384 m_os_version_major = UINT32_MAX;
385 m_os_version_minor = UINT32_MAX;
386 m_os_version_update = UINT32_MAX;
387 m_os_build.clear();
388 m_os_kernel.clear();
389 m_hostname.clear();
390 m_gdb_server_name.clear();
391 m_gdb_server_version = UINT32_MAX;
392 m_default_packet_timeout = 0;
393 m_max_packet_size = 0;
394 }
395
396 // These flags should be reset when we first connect to a GDB server
397 // and when our inferior process execs
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000398 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000399 m_process_arch.Clear();
Greg Clayton576d8832011-03-22 04:00:09 +0000400}
401
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000402void
403GDBRemoteCommunicationClient::GetRemoteQSupported ()
404{
405 // Clear out any capabilities we expect to see in the qSupported response
Steve Pucci03904ac2014-03-04 23:18:46 +0000406 m_supports_qXfer_auxv_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000407 m_supports_qXfer_libraries_read = eLazyBoolNo;
Steve Pucci03904ac2014-03-04 23:18:46 +0000408 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000409 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000410 m_supports_qXfer_features_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000411 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
412
Colin Rileyc3c95b22015-04-16 15:51:33 +0000413 // build the qSupported packet
414 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
415 StreamString packet;
416 packet.PutCString( "qSupported" );
417 for ( uint32_t i = 0; i < features.size( ); ++i )
418 {
419 packet.PutCString( i==0 ? ":" : ";");
420 packet.PutCString( features[i].c_str( ) );
421 }
422
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000423 StringExtractorGDBRemote response;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000424 if (SendPacketAndWaitForResponse(packet.GetData(),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000425 response,
426 /*send_async=*/false) == PacketResult::Success)
427 {
428 const char *response_cstr = response.GetStringRef().c_str();
Steve Pucci03904ac2014-03-04 23:18:46 +0000429 if (::strstr (response_cstr, "qXfer:auxv:read+"))
430 m_supports_qXfer_auxv_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000431 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
432 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
433 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
434 {
435 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
436 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
437 }
438 if (::strstr (response_cstr, "qXfer:libraries:read+"))
439 m_supports_qXfer_libraries_read = eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000440 if (::strstr (response_cstr, "qXfer:features:read+"))
441 m_supports_qXfer_features_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000442
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000443
444 // Look for a list of compressions in the features list e.g.
445 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
446 const char *features_list = ::strstr (response_cstr, "qXfer:features:");
447 if (features_list)
448 {
449 const char *compressions = ::strstr (features_list, "SupportedCompressions=");
450 if (compressions)
451 {
452 std::vector<std::string> supported_compressions;
453 compressions += sizeof ("SupportedCompressions=") - 1;
454 const char *end_of_compressions = strchr (compressions, ';');
455 if (end_of_compressions == NULL)
456 {
457 end_of_compressions = strchr (compressions, '\0');
458 }
459 const char *current_compression = compressions;
460 while (current_compression < end_of_compressions)
461 {
462 const char *next_compression_name = strchr (current_compression, ',');
463 const char *end_of_this_word = next_compression_name;
464 if (next_compression_name == NULL || end_of_compressions < next_compression_name)
465 {
466 end_of_this_word = end_of_compressions;
467 }
468
469 if (end_of_this_word)
470 {
471 if (end_of_this_word == current_compression)
472 {
473 current_compression++;
474 }
475 else
476 {
477 std::string this_compression (current_compression, end_of_this_word - current_compression);
478 supported_compressions.push_back (this_compression);
479 current_compression = end_of_this_word + 1;
480 }
481 }
482 else
483 {
484 supported_compressions.push_back (current_compression);
485 current_compression = end_of_compressions;
486 }
487 }
488
489 if (supported_compressions.size() > 0)
490 {
491 MaybeEnableCompression (supported_compressions);
492 }
493 }
494 }
495
Greg Claytonb30c50c2015-05-29 00:01:55 +0000496 if (::strstr (response_cstr, "qEcho"))
497 m_supports_qEcho = eLazyBoolYes;
498 else
499 m_supports_qEcho = eLazyBoolNo;
500
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000501 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
502 if (packet_size_str)
503 {
504 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
505 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
506 if (m_max_packet_size == 0)
507 {
508 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
509 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
510 if (log)
511 log->Printf ("Garbled PacketSize spec in qSupported response");
512 }
513 }
514 }
515}
Greg Clayton576d8832011-03-22 04:00:09 +0000516
517bool
518GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
519{
520 if (m_supports_thread_suffix == eLazyBoolCalculate)
521 {
522 StringExtractorGDBRemote response;
523 m_supports_thread_suffix = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000524 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000525 {
526 if (response.IsOKResponse())
527 m_supports_thread_suffix = eLazyBoolYes;
528 }
529 }
530 return m_supports_thread_suffix;
531}
532bool
533GDBRemoteCommunicationClient::GetVContSupported (char flavor)
534{
535 if (m_supports_vCont_c == eLazyBoolCalculate)
536 {
537 StringExtractorGDBRemote response;
538 m_supports_vCont_any = eLazyBoolNo;
539 m_supports_vCont_all = eLazyBoolNo;
540 m_supports_vCont_c = eLazyBoolNo;
541 m_supports_vCont_C = eLazyBoolNo;
542 m_supports_vCont_s = eLazyBoolNo;
543 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000544 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000545 {
546 const char *response_cstr = response.GetStringRef().c_str();
547 if (::strstr (response_cstr, ";c"))
548 m_supports_vCont_c = eLazyBoolYes;
549
550 if (::strstr (response_cstr, ";C"))
551 m_supports_vCont_C = eLazyBoolYes;
552
553 if (::strstr (response_cstr, ";s"))
554 m_supports_vCont_s = eLazyBoolYes;
555
556 if (::strstr (response_cstr, ";S"))
557 m_supports_vCont_S = eLazyBoolYes;
558
559 if (m_supports_vCont_c == eLazyBoolYes &&
560 m_supports_vCont_C == eLazyBoolYes &&
561 m_supports_vCont_s == eLazyBoolYes &&
562 m_supports_vCont_S == eLazyBoolYes)
563 {
564 m_supports_vCont_all = eLazyBoolYes;
565 }
566
567 if (m_supports_vCont_c == eLazyBoolYes ||
568 m_supports_vCont_C == eLazyBoolYes ||
569 m_supports_vCont_s == eLazyBoolYes ||
570 m_supports_vCont_S == eLazyBoolYes)
571 {
572 m_supports_vCont_any = eLazyBoolYes;
573 }
574 }
575 }
576
577 switch (flavor)
578 {
579 case 'a': return m_supports_vCont_any;
580 case 'A': return m_supports_vCont_all;
581 case 'c': return m_supports_vCont_c;
582 case 'C': return m_supports_vCont_C;
583 case 's': return m_supports_vCont_s;
584 case 'S': return m_supports_vCont_S;
585 default: break;
586 }
587 return false;
588}
589
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000590// Check if the target supports 'p' packet. It sends out a 'p'
591// packet and checks the response. A normal packet will tell us
592// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000593//
594// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000595bool
Sean Callananb1de1142013-09-04 23:24:15 +0000596GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000597{
598 if (m_supports_p == eLazyBoolCalculate)
599 {
600 StringExtractorGDBRemote response;
601 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000602 char packet[256];
603 if (GetThreadSuffixSupported())
604 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
605 else
606 snprintf(packet, sizeof(packet), "p0");
607
Greg Clayton3dedae12013-12-06 21:45:27 +0000608 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000609 {
610 if (response.IsNormalResponse())
611 m_supports_p = eLazyBoolYes;
612 }
613 }
614 return m_supports_p;
615}
Greg Clayton576d8832011-03-22 04:00:09 +0000616
Greg Clayton358cf1e2015-06-25 21:46:34 +0000617StructuredData::ObjectSP
618GDBRemoteCommunicationClient::GetThreadsInfo()
619{
620 // Get information on all threads at one using the "jThreadsInfo" packet
621 StructuredData::ObjectSP object_sp;
622
623 if (m_supports_jThreadsInfo)
624 {
625 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +0000626 response.SetResponseValidatorToJSON();
Greg Clayton358cf1e2015-06-25 21:46:34 +0000627 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) == PacketResult::Success)
628 {
629 if (response.IsUnsupportedResponse())
630 {
631 m_supports_jThreadsInfo = false;
632 }
633 else if (!response.Empty())
634 {
635 object_sp = StructuredData::ParseJSON (response.GetStringRef());
636 }
637 }
638 }
639 return object_sp;
640}
641
642
Jason Molendabdc4f122014-05-06 02:59:39 +0000643bool
Jason Molenda705b1802014-06-13 02:37:02 +0000644GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
645{
646 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
647 {
648 StringExtractorGDBRemote response;
649 m_supports_jThreadExtendedInfo = eLazyBoolNo;
650 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
651 {
652 if (response.IsOKResponse())
653 {
654 m_supports_jThreadExtendedInfo = eLazyBoolYes;
655 }
656 }
657 }
658 return m_supports_jThreadExtendedInfo;
659}
660
661bool
Jason Molenda20ee21b2015-07-10 23:15:22 +0000662GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported ()
663{
664 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate)
665 {
666 StringExtractorGDBRemote response;
667 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
668 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:", response, false) == PacketResult::Success)
669 {
670 if (response.IsOKResponse())
671 {
672 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
673 }
674 }
675 }
676 return m_supports_jLoadedDynamicLibrariesInfos;
677}
678
679bool
Jason Molendabdc4f122014-05-06 02:59:39 +0000680GDBRemoteCommunicationClient::GetxPacketSupported ()
681{
682 if (m_supports_x == eLazyBoolCalculate)
683 {
684 StringExtractorGDBRemote response;
685 m_supports_x = eLazyBoolNo;
686 char packet[256];
687 snprintf (packet, sizeof (packet), "x0,0");
688 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
689 {
690 if (response.IsOKResponse())
691 m_supports_x = eLazyBoolYes;
692 }
693 }
694 return m_supports_x;
695}
696
Greg Clayton3dedae12013-12-06 21:45:27 +0000697GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000698GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
699(
700 const char *payload_prefix,
701 std::string &response_string
702)
703{
704 Mutex::Locker locker;
705 if (!GetSequenceMutex(locker,
706 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
707 {
708 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
709 if (log)
710 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
711 payload_prefix);
712 return PacketResult::ErrorNoSequenceLock;
713 }
714
715 response_string = "";
716 std::string payload_prefix_str(payload_prefix);
717 unsigned int response_size = 0x1000;
718 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
719 response_size = GetRemoteMaxPacketSize();
720 }
721
722 for (unsigned int offset = 0; true; offset += response_size)
723 {
724 StringExtractorGDBRemote this_response;
725 // Construct payload
726 char sizeDescriptor[128];
727 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
728 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
729 this_response,
730 /*send_async=*/false);
731 if (result != PacketResult::Success)
732 return result;
733
734 const std::string &this_string = this_response.GetStringRef();
735
736 // Check for m or l as first character; l seems to mean this is the last chunk
737 char first_char = *this_string.c_str();
738 if (first_char != 'm' && first_char != 'l')
739 {
740 return PacketResult::ErrorReplyInvalid;
741 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000742 // Concatenate the result so far (skipping 'm' or 'l')
743 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000744 if (first_char == 'l')
745 // We're done
746 return PacketResult::Success;
747 }
748}
749
750GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000751GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
752(
753 const char *payload,
754 StringExtractorGDBRemote &response,
755 bool send_async
756)
757{
758 return SendPacketAndWaitForResponse (payload,
759 ::strlen (payload),
760 response,
761 send_async);
762}
763
Greg Clayton3dedae12013-12-06 21:45:27 +0000764GDBRemoteCommunicationClient::PacketResult
765GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
766 size_t payload_length,
767 StringExtractorGDBRemote &response)
768{
Greg Clayton830c81d2016-04-01 00:41:29 +0000769 PacketResult packet_result = SendPacketNoLock(payload, payload_length);
Greg Clayton3dedae12013-12-06 21:45:27 +0000770 if (packet_result == PacketResult::Success)
Greg Clayton830c81d2016-04-01 00:41:29 +0000771 {
772 const size_t max_response_retries = 3;
773 for (size_t i=0; i<max_response_retries; ++i)
774 {
775 packet_result = ReadPacket(response, GetPacketTimeoutInMicroSeconds (), true);
776 // Make sure we received a response
777 if (packet_result != PacketResult::Success)
778 return packet_result;
779 // Make sure our response is valid for the payload that was sent
780 if (response.ValidateResponse())
781 return packet_result;
782 // Response says it wasn't valid
783 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS);
784 if (log)
785 log->Printf("error: packet with payload \"%*s\" got invalid response \"%s\": %s",
786 (int)payload_length,
787 payload,
788 response.GetStringRef().c_str(),
789 (i == (max_response_retries - 1)) ? "using invalid response and giving up" : "ignoring response and waiting for another");
790 }
791 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000792 return packet_result;
793}
794
795GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000796GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
797(
798 const char *payload,
799 size_t payload_length,
800 StringExtractorGDBRemote &response,
801 bool send_async
802)
803{
Greg Clayton3dedae12013-12-06 21:45:27 +0000804 PacketResult packet_result = PacketResult::ErrorSendFailed;
Greg Clayton576d8832011-03-22 04:00:09 +0000805 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000806 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000807
808 // In order to stop async notifications from being processed in the middle of the
Bruce Mitchenere171da52015-07-22 00:16:02 +0000809 // send/receive sequence Hijack the broadcast. Then rebroadcast any events when we are done.
Jim Ingham583bbb12016-03-07 21:50:25 +0000810 static ListenerSP hijack_listener_sp(Listener::MakeListener("lldb.NotifyHijacker"));
811 HijackBroadcaster(hijack_listener_sp, eBroadcastBitGdbReadThreadGotNotify);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000812
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000813 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000814 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000815 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000816 }
817 else
818 {
819 if (send_async)
820 {
Greg Claytond3544052012-05-31 21:24:20 +0000821 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000822 {
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000823 std::lock_guard<std::recursive_mutex> guard(m_async_mutex);
Greg Claytond3544052012-05-31 21:24:20 +0000824 m_async_packet.assign(payload, payload_length);
Greg Clayton830c81d2016-04-01 00:41:29 +0000825 m_async_response.CopyResponseValidator(response);
Greg Claytond3544052012-05-31 21:24:20 +0000826 m_async_packet_predicate.SetValue (true, eBroadcastNever);
827
828 if (log)
829 log->Printf ("async: async packet = %s", m_async_packet.c_str());
830
831 bool timed_out = false;
832 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000833 {
Greg Claytond3544052012-05-31 21:24:20 +0000834 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000835 {
Jim Inghambabfc382012-06-06 00:32:39 +0000836 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000837 TimeValue timeout_time;
838 timeout_time = TimeValue::Now();
839 timeout_time.OffsetWithSeconds (m_packet_timeout);
840
Greg Clayton576d8832011-03-22 04:00:09 +0000841 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000842 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000843
Greg Claytond3544052012-05-31 21:24:20 +0000844 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000845 {
Greg Claytond3544052012-05-31 21:24:20 +0000846 if (log)
847 log->Printf ("async: got response");
848
849 // Swap the response buffer to avoid malloc and string copy
850 response.GetStringRef().swap (m_async_response.GetStringRef());
Jim Inghama6195b72013-12-18 01:24:33 +0000851 packet_result = m_async_result;
Greg Claytond3544052012-05-31 21:24:20 +0000852 }
853 else
854 {
855 if (log)
856 log->Printf ("async: timed out waiting for response");
857 }
858
859 // Make sure we wait until the continue packet has been sent again...
860 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
861 {
862 if (log)
863 {
864 if (timed_out)
865 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
866 else
867 log->Printf ("async: async packet sent");
868 }
869 }
870 else
871 {
872 if (log)
873 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000874 }
875 }
876 else
877 {
Greg Claytond3544052012-05-31 21:24:20 +0000878 // We had a racy condition where we went to send the interrupt
879 // yet we were able to get the lock, so the process must have
880 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000881 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000882 log->Printf ("async: got lock without sending interrupt");
883 // Send the packet normally since we got the lock
Greg Clayton3dedae12013-12-06 21:45:27 +0000884 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000885 }
886 }
887 else
888 {
Greg Clayton644247c2011-07-07 01:59:51 +0000889 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000890 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000891 }
Greg Clayton830c81d2016-04-01 00:41:29 +0000892
893 m_async_response.SetResponseValidator(nullptr, nullptr);
894
Greg Clayton576d8832011-03-22 04:00:09 +0000895 }
896 else
897 {
898 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000899 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000900 }
901 }
902 else
903 {
904 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000905 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000906 }
907 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000908
Bruce Mitchenere171da52015-07-22 00:16:02 +0000909 // Remove our Hijacking listener from the broadcast.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000910 RestoreBroadcaster();
911
Bruce Mitchenere171da52015-07-22 00:16:02 +0000912 // If a notification event occurred, rebroadcast since it can now be processed safely.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000913 EventSP event_sp;
Jim Ingham583bbb12016-03-07 21:50:25 +0000914 if (hijack_listener_sp->GetNextEvent(event_sp))
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000915 BroadcastEvent(event_sp);
916
Greg Clayton3dedae12013-12-06 21:45:27 +0000917 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000918}
919
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000920static const char *end_delimiter = "--end--;";
921static const int end_delimiter_len = 8;
922
923std::string
924GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
925( ProcessGDBRemote *process,
926 StringExtractorGDBRemote& profileDataExtractor
927)
928{
929 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
930 std::stringstream final_output;
931 std::string name, value;
932
933 // Going to assuming thread_used_usec comes first, else bail out.
934 while (profileDataExtractor.GetNameColonValue(name, value))
935 {
936 if (name.compare("thread_used_id") == 0)
937 {
938 StringExtractor threadIDHexExtractor(value.c_str());
939 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
940
941 bool has_used_usec = false;
942 uint32_t curr_used_usec = 0;
943 std::string usec_name, usec_value;
944 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
945 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
946 {
947 if (usec_name.compare("thread_used_usec") == 0)
948 {
949 has_used_usec = true;
950 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
951 }
952 else
953 {
954 // We didn't find what we want, it is probably
955 // an older version. Bail out.
956 profileDataExtractor.SetFilePos(input_file_pos);
957 }
958 }
959
960 if (has_used_usec)
961 {
962 uint32_t prev_used_usec = 0;
963 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
964 if (iterator != m_thread_id_to_used_usec_map.end())
965 {
966 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
967 }
968
969 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
970 // A good first time record is one that runs for at least 0.25 sec
971 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
972 bool good_subsequent_time = (prev_used_usec > 0) &&
973 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
974
975 if (good_first_time || good_subsequent_time)
976 {
977 // We try to avoid doing too many index id reservation,
978 // resulting in fast increase of index ids.
979
980 final_output << name << ":";
981 int32_t index_id = process->AssignIndexIDToThread(thread_id);
982 final_output << index_id << ";";
983
984 final_output << usec_name << ":" << usec_value << ";";
985 }
986 else
987 {
988 // Skip past 'thread_used_name'.
989 std::string local_name, local_value;
990 profileDataExtractor.GetNameColonValue(local_name, local_value);
991 }
992
993 // Store current time as previous time so that they can be compared later.
994 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
995 }
996 else
997 {
998 // Bail out and use old string.
999 final_output << name << ":" << value << ";";
1000 }
1001 }
1002 else
1003 {
1004 final_output << name << ":" << value << ";";
1005 }
1006 }
1007 final_output << end_delimiter;
1008 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
1009
1010 return final_output.str();
1011}
1012
Ewan Crawford76df2882015-06-23 12:32:06 +00001013bool
1014GDBRemoteCommunicationClient::SendvContPacket
1015(
1016 ProcessGDBRemote *process,
1017 const char *payload,
1018 size_t packet_length,
1019 StringExtractorGDBRemote &response
1020)
1021{
1022
1023 m_curr_tid = LLDB_INVALID_THREAD_ID;
1024 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1025 if (log)
1026 log->Printf("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
1027
1028 // we want to lock down packet sending while we continue
1029 Mutex::Locker locker(m_sequence_mutex);
1030
1031 // here we broadcast this before we even send the packet!!
1032 // this signals doContinue() to exit
1033 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1034
1035 // set the public state to running
1036 m_public_is_running.SetValue(true, eBroadcastNever);
1037
1038 // Set the starting continue packet into "continue_packet". This packet
1039 // may change if we are interrupted and we continue after an async packet...
1040 std::string continue_packet(payload, packet_length);
1041
1042 if (log)
1043 log->Printf("GDBRemoteCommunicationClient::%s () sending vCont packet: %s", __FUNCTION__, continue_packet.c_str());
1044
1045 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
1046 return false;
1047
1048 // set the private state to running and broadcast this
1049 m_private_is_running.SetValue(true, eBroadcastAlways);
1050
1051 if (log)
1052 log->Printf("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
1053
1054 // wait for the response to the vCont
1055 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
1056 {
1057 if (response.IsOKResponse())
1058 return true;
1059 }
1060
1061 return false;
1062}
1063
Greg Clayton576d8832011-03-22 04:00:09 +00001064StateType
1065GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
1066(
1067 ProcessGDBRemote *process,
1068 const char *payload,
1069 size_t packet_length,
1070 StringExtractorGDBRemote &response
1071)
1072{
Greg Clayton1f5181a2012-07-02 22:05:25 +00001073 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +00001074 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +00001075 if (log)
1076 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
1077
1078 Mutex::Locker locker(m_sequence_mutex);
1079 StateType state = eStateRunning;
1080
Greg Clayton576d8832011-03-22 04:00:09 +00001081 m_public_is_running.SetValue (true, eBroadcastNever);
1082 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +00001083 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +00001084 std::string continue_packet(payload, packet_length);
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001085
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001086 const auto sigstop_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGSTOP");
1087 const auto sigint_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGINT");
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001088
Greg Clayton3f875c52013-02-22 22:23:55 +00001089 bool got_async_packet = false;
Pavel Labath9e131f72015-10-27 09:23:55 +00001090 bool broadcast_sent = false;
Greg Claytonaf247d72011-05-19 03:54:16 +00001091
Greg Clayton576d8832011-03-22 04:00:09 +00001092 while (state == eStateRunning)
1093 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001094 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +00001095 {
1096 if (log)
1097 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton3dedae12013-12-06 21:45:27 +00001098 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
Greg Claytonaf247d72011-05-19 03:54:16 +00001099 state = eStateInvalid;
Jim Inghamb8cd5752014-04-16 02:24:17 +00001100 else
1101 m_interrupt_sent = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001102
Pavel Labath9e131f72015-10-27 09:23:55 +00001103 if (! broadcast_sent)
1104 {
1105 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1106 broadcast_sent = true;
1107 }
1108
Greg Claytone889ad62011-10-27 22:04:16 +00001109 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +00001110 }
1111
Greg Clayton3f875c52013-02-22 22:23:55 +00001112 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001113
1114 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001115 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00001116
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001117 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001118 {
1119 if (response.Empty())
1120 state = eStateInvalid;
1121 else
1122 {
1123 const char stop_type = response.GetChar();
1124 if (log)
1125 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
1126 switch (stop_type)
1127 {
1128 case 'T':
1129 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +00001130 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001131 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +00001132 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001133 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
1134 {
1135 lldb::pid_t pid = GetCurrentProcessID ();
1136 if (pid != LLDB_INVALID_PROCESS_ID)
1137 process->SetID (pid);
1138 }
1139 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +00001140 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001141
1142 // Privately notify any internal threads that we have stopped
1143 // in case we wanted to interrupt our process, yet we might
1144 // send a packet and continue without returning control to the
1145 // user.
1146 m_private_is_running.SetValue (false, eBroadcastAlways);
1147
1148 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
1149
Jim Inghambabfc382012-06-06 00:32:39 +00001150 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
1151 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +00001152 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001153 // We sent an interrupt packet to stop the inferior process
1154 // for an async signal or to send an async packet while running
1155 // but we might have been single stepping and received the
1156 // stop packet for the step instead of for the interrupt packet.
1157 // Typically when an interrupt is sent a SIGINT or SIGSTOP
1158 // is used, so if we get anything else, we need to try and
1159 // get another stop reply packet that may have been sent
1160 // due to sending the interrupt when the target is stopped
1161 // which will just re-send a copy of the last stop reply
1162 // packet. If we don't do this, then the reply for our
1163 // async packet will be the repeat stop reply packet and cause
Greg Clayton830c81d2016-04-01 00:41:29 +00001164 // a lot of trouble for us! We also have some debugserver
1165 // binaries that would send two stop replies anytime the process
1166 // was interrupted, so we need to also check for an extra
1167 // stop reply packet if we interrupted the process
Oleksiy Vyalovbdea8dd2016-04-08 20:44:28 +00001168 const bool received_nonstop_signal = signo != sigint_signo && signo != sigstop_signo;
1169 if (m_interrupt_sent || received_nonstop_signal)
Greg Clayton2687cd12012-03-29 01:55:41 +00001170 {
Oleksiy Vyalovbdea8dd2016-04-08 20:44:28 +00001171 if (received_nonstop_signal)
1172 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001173
Oleksiy Vyalovbdea8dd2016-04-08 20:44:28 +00001174 // Try for a very brief time (0.1s) to get another stop reply
Greg Clayton2687cd12012-03-29 01:55:41 +00001175 // packet to make sure it doesn't get in the way
1176 StringExtractorGDBRemote extra_stop_reply_packet;
Jason Molendada9765b2015-08-26 04:07:30 +00001177 uint32_t timeout_usec = 100000;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001178 if (ReadPacket (extra_stop_reply_packet, timeout_usec, false) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +00001179 {
1180 switch (extra_stop_reply_packet.GetChar())
1181 {
1182 case 'T':
1183 case 'S':
1184 // We did get an extra stop reply, which means
1185 // our interrupt didn't stop the target so we
1186 // shouldn't continue after the async signal
1187 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +00001188 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001189 break;
1190 }
1191 }
1192 }
1193 }
1194
1195 if (m_async_signal != -1)
1196 {
1197 if (log)
1198 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
1199
1200 // Save off the async signal we are supposed to send
1201 const int async_signal = m_async_signal;
1202 // Clear the async signal member so we don't end up
1203 // sending the signal multiple times...
1204 m_async_signal = -1;
1205 // Check which signal we stopped with
1206 if (signo == async_signal)
1207 {
1208 if (log)
1209 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
1210
1211 // We already stopped with a signal that we wanted
1212 // to stop with, so we are done
1213 }
1214 else
1215 {
1216 // We stopped with a different signal that the one
1217 // we wanted to stop with, so now we must resume
1218 // with the signal we want
1219 char signal_packet[32];
1220 int signal_packet_len = 0;
1221 signal_packet_len = ::snprintf (signal_packet,
1222 sizeof (signal_packet),
1223 "C%2.2x",
1224 async_signal);
1225
1226 if (log)
1227 log->Printf ("async: stopped with signal %s, resume with %s",
1228 Host::GetSignalAsCString (signo),
1229 Host::GetSignalAsCString (async_signal));
1230
1231 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +00001232 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001233 continue_packet.assign(signal_packet, signal_packet_len);
1234 continue;
1235 }
1236 }
1237 else if (m_async_packet_predicate.GetValue())
1238 {
Greg Clayton5160ce52013-03-27 23:08:40 +00001239 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +00001240
1241 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +00001242 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +00001243 m_async_response.Clear();
1244 if (m_async_packet.empty())
1245 {
Jim Inghama6195b72013-12-18 01:24:33 +00001246 m_async_result = PacketResult::ErrorSendFailed;
1247 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001248 packet_log->Printf ("async: error: empty async packet");
1249
1250 }
1251 else
1252 {
1253 if (packet_log)
1254 packet_log->Printf ("async: sending packet");
1255
Jim Inghama6195b72013-12-18 01:24:33 +00001256 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1257 m_async_packet.size(),
1258 m_async_response,
1259 false);
Greg Clayton2687cd12012-03-29 01:55:41 +00001260 }
1261 // Let the other thread that was trying to send the async
1262 // packet know that the packet has been sent and response is
1263 // ready...
1264 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1265
1266 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +00001267 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +00001268
1269 // Set the continue packet to resume if our interrupt
1270 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +00001271 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001272 {
Greg Claytonf1186de2012-05-24 23:42:14 +00001273 // Reverting this for now as it is causing deadlocks
1274 // in programs (<rdar://problem/11529853>). In the future
1275 // we should check our thread list and "do the right thing"
1276 // for new threads that show up while we stop and run async
1277 // packets. Setting the packet to 'c' to continue all threads
1278 // is the right thing to do 99.99% of the time because if a
1279 // thread was single stepping, and we sent an interrupt, we
1280 // will notice above that we didn't stop due to an interrupt
1281 // but stopped due to stepping and we would _not_ continue.
1282 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +00001283 continue;
1284 }
1285 }
1286 // Stop with signal and thread info
1287 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +00001288 }
Greg Clayton576d8832011-03-22 04:00:09 +00001289 break;
1290
1291 case 'W':
1292 case 'X':
1293 // process exited
1294 state = eStateExited;
1295 break;
1296
1297 case 'O':
1298 // STDOUT
1299 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001300 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001301 std::string inferior_stdout;
1302 inferior_stdout.reserve(response.GetBytesLeft () / 2);
Dawn Perchik554a8572015-09-17 17:55:32 +00001303
1304 uint8_t ch;
1305 while (response.GetHexU8Ex(ch))
1306 {
1307 if (ch != 0)
1308 inferior_stdout.append(1, (char)ch);
1309 }
Greg Clayton576d8832011-03-22 04:00:09 +00001310 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1311 }
1312 break;
1313
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001314 case 'A':
1315 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1316 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001317 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001318 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1319 if (m_partial_profile_data.length() > 0)
1320 {
1321 m_partial_profile_data.append(input);
1322 input = m_partial_profile_data;
1323 m_partial_profile_data.clear();
1324 }
1325
1326 size_t found, pos = 0, len = input.length();
1327 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1328 {
1329 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +00001330 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1331 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001332
1333 pos = found + end_delimiter_len;
1334 }
1335
1336 if (pos < len)
1337 {
1338 // Last incomplete chunk.
1339 m_partial_profile_data = input.substr(pos);
1340 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001341 }
1342 break;
1343
Greg Clayton576d8832011-03-22 04:00:09 +00001344 case 'E':
1345 // ERROR
1346 state = eStateInvalid;
1347 break;
1348
1349 default:
1350 if (log)
1351 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1352 state = eStateInvalid;
1353 break;
1354 }
1355 }
1356 }
1357 else
1358 {
1359 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001360 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(...) => false", __FUNCTION__);
Greg Clayton576d8832011-03-22 04:00:09 +00001361 state = eStateInvalid;
1362 }
1363 }
1364 if (log)
1365 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1366 response.SetFilePos(0);
1367 m_private_is_running.SetValue (false, eBroadcastAlways);
1368 m_public_is_running.SetValue (false, eBroadcastAlways);
1369 return state;
1370}
1371
1372bool
1373GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1374{
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00001375 std::lock_guard<std::recursive_mutex> guard(m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001376 m_async_signal = signo;
1377 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001378 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001379 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001380 return true;
1381 m_async_signal = -1;
1382 return false;
1383}
1384
Greg Clayton37a0a242012-04-11 00:24:49 +00001385// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001386// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1387// (the expected result), then it will send the halt packet. If it does succeed
1388// then the caller that requested the interrupt will want to keep the sequence
1389// locked down so that no one else can send packets while the caller has control.
1390// This function usually gets called when we are running and need to stop the
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001391// target. It can also be used when we are running and we need to do something
Greg Clayton576d8832011-03-22 04:00:09 +00001392// else (like read/write memory), so we need to interrupt the running process
1393// (gdb remote protocol requires this), and do what we need to do, then resume.
1394
1395bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001396GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001397(
1398 Mutex::Locker& locker,
1399 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001400 bool &timed_out
1401)
1402{
Greg Clayton576d8832011-03-22 04:00:09 +00001403 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001404 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001405
1406 if (IsRunning())
1407 {
1408 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001409 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001410 {
1411 if (log)
1412 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1413 }
1414 else
Greg Clayton576d8832011-03-22 04:00:09 +00001415 {
1416 // Someone has the mutex locked waiting for a response or for the
1417 // inferior to stop, so send the interrupt on the down low...
1418 char ctrl_c = '\x03';
1419 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001420 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001421 if (log)
1422 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001423 if (bytes_written > 0)
1424 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001425 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001426 if (seconds_to_wait_for_stop)
1427 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001428 TimeValue timeout;
1429 if (seconds_to_wait_for_stop)
1430 {
1431 timeout = TimeValue::Now();
1432 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1433 }
Greg Clayton576d8832011-03-22 04:00:09 +00001434 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1435 {
1436 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001437 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001438 return true;
1439 }
1440 else
1441 {
1442 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001443 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001444 }
1445 }
1446 else
1447 {
1448 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001449 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001450 return true;
1451 }
1452 }
1453 else
1454 {
1455 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001456 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001457 }
1458 return false;
1459 }
Greg Clayton576d8832011-03-22 04:00:09 +00001460 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001461 else
1462 {
1463 if (log)
1464 log->Printf ("SendInterrupt () - not running");
1465 }
Greg Clayton576d8832011-03-22 04:00:09 +00001466 return true;
1467}
1468
1469lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001470GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +00001471{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001472 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001473 return m_curr_pid;
1474
1475 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001476 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001477 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +00001478 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001479 // We really got it.
1480 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +00001481 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001482 else
1483 {
Todd Fialae24614f2014-05-14 00:15:32 +00001484 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1485 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1486 // The gdb remote protocol documents $qC as returning the thread id, which newer
1487 // debugserver and lldb-gdbserver stubs return correctly.
1488 StringExtractorGDBRemote response;
1489 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001490 {
Todd Fialae24614f2014-05-14 00:15:32 +00001491 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001492 {
Todd Fialae24614f2014-05-14 00:15:32 +00001493 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001494 {
Todd Fialae24614f2014-05-14 00:15:32 +00001495 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1496 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001497 {
Todd Fialae24614f2014-05-14 00:15:32 +00001498 m_curr_pid_is_valid = eLazyBoolYes;
1499 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001500 }
1501 }
1502 }
1503 }
Jaydeep Patil1142f832015-08-13 03:46:36 +00001504
1505 // If we don't get a response for $qC, check if $qfThreadID gives us a result.
1506 if (m_curr_pid == LLDB_INVALID_PROCESS_ID)
1507 {
1508 std::vector<lldb::tid_t> thread_ids;
1509 bool sequence_mutex_unavailable;
1510 size_t size;
1511 size = GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1512 if (size && sequence_mutex_unavailable == false)
1513 {
1514 m_curr_pid = thread_ids.front();
1515 m_curr_pid_is_valid = eLazyBoolYes;
1516 return m_curr_pid;
1517 }
1518 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001519 }
1520
Greg Clayton576d8832011-03-22 04:00:09 +00001521 return LLDB_INVALID_PROCESS_ID;
1522}
1523
1524bool
1525GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1526{
1527 error_str.clear();
1528 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001529 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001530 {
1531 if (response.IsOKResponse())
1532 return true;
1533 if (response.GetChar() == 'E')
1534 {
1535 // A string the describes what failed when launching...
1536 error_str = response.GetStringRef().substr(1);
1537 }
1538 else
1539 {
1540 error_str.assign ("unknown error occurred launching process");
1541 }
1542 }
1543 else
1544 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001545 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001546 }
1547 return false;
1548}
1549
1550int
Greg Claytonfbb76342013-11-20 21:07:01 +00001551GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001552{
Greg Claytonfbb76342013-11-20 21:07:01 +00001553 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001554 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +00001555 std::vector<const char *> argv;
1556 FileSpec exe_file = launch_info.GetExecutableFile();
1557 std::string exe_path;
1558 const char *arg = NULL;
1559 const Args &launch_args = launch_info.GetArguments();
1560 if (exe_file)
Chaoren Lind3173f32015-05-29 19:52:29 +00001561 exe_path = exe_file.GetPath(false);
Greg Claytonfbb76342013-11-20 21:07:01 +00001562 else
1563 {
1564 arg = launch_args.GetArgumentAtIndex(0);
1565 if (arg)
1566 exe_path = arg;
1567 }
1568 if (!exe_path.empty())
1569 {
1570 argv.push_back(exe_path.c_str());
1571 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1572 {
1573 if (arg)
1574 argv.push_back(arg);
1575 }
1576 }
1577 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001578 {
1579 StreamString packet;
1580 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001581 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001582 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001583 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001584 const int arg_len = strlen(arg);
1585 if (i > 0)
1586 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001587 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001588 packet.PutBytesAsRawHex8 (arg, arg_len);
1589 }
1590
1591 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001592 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001593 {
1594 if (response.IsOKResponse())
1595 return 0;
1596 uint8_t error = response.GetError();
1597 if (error)
1598 return error;
1599 }
1600 }
1601 return -1;
1602}
1603
1604int
1605GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1606{
1607 if (name_equal_value && name_equal_value[0])
1608 {
1609 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001610 bool send_hex_encoding = false;
1611 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001612 {
Greg Clayton89600582013-10-10 17:53:50 +00001613 if (isprint(*p))
1614 {
1615 switch (*p)
1616 {
1617 case '$':
1618 case '#':
Jason Molenda60bdafb2015-11-05 23:51:05 +00001619 case '*':
Tim Northover974ff612015-11-09 22:05:05 +00001620 case '}':
Greg Clayton89600582013-10-10 17:53:50 +00001621 send_hex_encoding = true;
1622 break;
1623 default:
1624 break;
1625 }
1626 }
1627 else
1628 {
1629 // We have non printable characters, lets hex encode this...
1630 send_hex_encoding = true;
1631 }
1632 }
1633
1634 StringExtractorGDBRemote response;
1635 if (send_hex_encoding)
1636 {
1637 if (m_supports_QEnvironmentHexEncoded)
1638 {
1639 packet.PutCString("QEnvironmentHexEncoded:");
1640 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001641 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001642 {
1643 if (response.IsOKResponse())
1644 return 0;
1645 uint8_t error = response.GetError();
1646 if (error)
1647 return error;
1648 if (response.IsUnsupportedResponse())
1649 m_supports_QEnvironmentHexEncoded = false;
1650 }
1651 }
1652
1653 }
1654 else if (m_supports_QEnvironment)
1655 {
1656 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +00001657 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001658 {
1659 if (response.IsOKResponse())
1660 return 0;
1661 uint8_t error = response.GetError();
1662 if (error)
1663 return error;
1664 if (response.IsUnsupportedResponse())
1665 m_supports_QEnvironment = false;
1666 }
Greg Clayton576d8832011-03-22 04:00:09 +00001667 }
1668 }
1669 return -1;
1670}
1671
Greg Claytonc4103b32011-05-08 04:53:50 +00001672int
1673GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1674{
1675 if (arch && arch[0])
1676 {
1677 StreamString packet;
1678 packet.Printf("QLaunchArch:%s", arch);
1679 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001680 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001681 {
1682 if (response.IsOKResponse())
1683 return 0;
1684 uint8_t error = response.GetError();
1685 if (error)
1686 return error;
1687 }
1688 }
1689 return -1;
1690}
1691
Jason Molendaa3329782014-03-29 18:54:20 +00001692int
1693GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1694{
1695 if (data && *data != '\0')
1696 {
1697 StreamString packet;
1698 packet.Printf("QSetProcessEvent:%s", data);
1699 StringExtractorGDBRemote response;
1700 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1701 {
1702 if (response.IsOKResponse())
1703 {
1704 if (was_supported)
1705 *was_supported = true;
1706 return 0;
1707 }
1708 else if (response.IsUnsupportedResponse())
1709 {
1710 if (was_supported)
1711 *was_supported = false;
1712 return -1;
1713 }
1714 else
1715 {
1716 uint8_t error = response.GetError();
1717 if (was_supported)
1718 *was_supported = true;
1719 if (error)
1720 return error;
1721 }
1722 }
1723 }
1724 return -1;
1725}
1726
Greg Clayton576d8832011-03-22 04:00:09 +00001727bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001728GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1729 uint32_t &minor,
1730 uint32_t &update)
1731{
1732 if (GetHostInfo ())
1733 {
1734 if (m_os_version_major != UINT32_MAX)
1735 {
1736 major = m_os_version_major;
1737 minor = m_os_version_minor;
1738 update = m_os_version_update;
1739 return true;
1740 }
1741 }
1742 return false;
1743}
1744
1745bool
1746GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1747{
1748 if (GetHostInfo ())
1749 {
1750 if (!m_os_build.empty())
1751 {
1752 s = m_os_build;
1753 return true;
1754 }
1755 }
1756 s.clear();
1757 return false;
1758}
1759
1760
1761bool
1762GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1763{
1764 if (GetHostInfo ())
1765 {
1766 if (!m_os_kernel.empty())
1767 {
1768 s = m_os_kernel;
1769 return true;
1770 }
1771 }
1772 s.clear();
1773 return false;
1774}
1775
1776bool
1777GDBRemoteCommunicationClient::GetHostname (std::string &s)
1778{
1779 if (GetHostInfo ())
1780 {
1781 if (!m_hostname.empty())
1782 {
1783 s = m_hostname;
1784 return true;
1785 }
1786 }
1787 s.clear();
1788 return false;
1789}
1790
1791ArchSpec
1792GDBRemoteCommunicationClient::GetSystemArchitecture ()
1793{
1794 if (GetHostInfo ())
1795 return m_host_arch;
1796 return ArchSpec();
1797}
1798
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001799const lldb_private::ArchSpec &
1800GDBRemoteCommunicationClient::GetProcessArchitecture ()
1801{
1802 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1803 GetCurrentProcessInfo ();
1804 return m_process_arch;
1805}
1806
Jason Molendaa3329782014-03-29 18:54:20 +00001807bool
1808GDBRemoteCommunicationClient::GetGDBServerVersion()
1809{
1810 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1811 {
1812 m_gdb_server_name.clear();
1813 m_gdb_server_version = 0;
1814 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1815
1816 StringExtractorGDBRemote response;
1817 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1818 {
1819 if (response.IsNormalResponse())
1820 {
1821 std::string name;
1822 std::string value;
1823 bool success = false;
1824 while (response.GetNameColonValue(name, value))
1825 {
1826 if (name.compare("name") == 0)
1827 {
1828 success = true;
1829 m_gdb_server_name.swap(value);
1830 }
1831 else if (name.compare("version") == 0)
1832 {
1833 size_t dot_pos = value.find('.');
1834 if (dot_pos != std::string::npos)
1835 value[dot_pos] = '\0';
Vince Harron5275aaa2015-01-15 20:08:35 +00001836 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molendaa3329782014-03-29 18:54:20 +00001837 if (version != UINT32_MAX)
1838 {
1839 success = true;
1840 m_gdb_server_version = version;
1841 }
1842 }
1843 }
1844 if (success)
1845 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1846 }
1847 }
1848 }
1849 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1850}
1851
Jason Molenda91ffe0a2015-06-18 21:46:06 +00001852void
1853GDBRemoteCommunicationClient::MaybeEnableCompression (std::vector<std::string> supported_compressions)
1854{
1855 CompressionType avail_type = CompressionType::None;
1856 std::string avail_name;
1857
1858#if defined (HAVE_LIBCOMPRESSION)
1859 // libcompression is weak linked so test if compression_decode_buffer() is available
1860 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1861 {
1862 for (auto compression : supported_compressions)
1863 {
1864 if (compression == "lzfse")
1865 {
1866 avail_type = CompressionType::LZFSE;
1867 avail_name = compression;
1868 break;
1869 }
1870 }
1871 }
1872#endif
1873
1874#if defined (HAVE_LIBCOMPRESSION)
1875 // libcompression is weak linked so test if compression_decode_buffer() is available
1876 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1877 {
1878 for (auto compression : supported_compressions)
1879 {
1880 if (compression == "zlib-deflate")
1881 {
1882 avail_type = CompressionType::ZlibDeflate;
1883 avail_name = compression;
1884 break;
1885 }
1886 }
1887 }
1888#endif
1889
1890#if defined (HAVE_LIBZ)
1891 if (avail_type == CompressionType::None)
1892 {
1893 for (auto compression : supported_compressions)
1894 {
1895 if (compression == "zlib-deflate")
1896 {
1897 avail_type = CompressionType::ZlibDeflate;
1898 avail_name = compression;
1899 break;
1900 }
1901 }
1902 }
1903#endif
1904
1905#if defined (HAVE_LIBCOMPRESSION)
1906 // libcompression is weak linked so test if compression_decode_buffer() is available
1907 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1908 {
1909 for (auto compression : supported_compressions)
1910 {
1911 if (compression == "lz4")
1912 {
1913 avail_type = CompressionType::LZ4;
1914 avail_name = compression;
1915 break;
1916 }
1917 }
1918 }
1919#endif
1920
1921#if defined (HAVE_LIBCOMPRESSION)
1922 // libcompression is weak linked so test if compression_decode_buffer() is available
1923 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1924 {
1925 for (auto compression : supported_compressions)
1926 {
1927 if (compression == "lzma")
1928 {
1929 avail_type = CompressionType::LZMA;
1930 avail_name = compression;
1931 break;
1932 }
1933 }
1934 }
1935#endif
1936
1937 if (avail_type != CompressionType::None)
1938 {
1939 StringExtractorGDBRemote response;
1940 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1941 if (SendPacketAndWaitForResponse (packet.c_str(), response, false) != PacketResult::Success)
1942 return;
1943
1944 if (response.IsOKResponse())
1945 {
1946 m_compression_type = avail_type;
1947 }
1948 }
1949}
1950
Jason Molendaa3329782014-03-29 18:54:20 +00001951const char *
1952GDBRemoteCommunicationClient::GetGDBServerProgramName()
1953{
1954 if (GetGDBServerVersion())
1955 {
1956 if (!m_gdb_server_name.empty())
1957 return m_gdb_server_name.c_str();
1958 }
1959 return NULL;
1960}
1961
1962uint32_t
1963GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1964{
1965 if (GetGDBServerVersion())
1966 return m_gdb_server_version;
1967 return 0;
1968}
Greg Clayton1cb64962011-03-24 04:28:38 +00001969
1970bool
Ewan Crawford78baa192015-05-13 09:18:18 +00001971GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1972{
1973 StringExtractorGDBRemote response;
1974 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1975 return false;
1976
1977 if (!response.IsNormalResponse())
1978 return false;
1979
1980 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
1981 tid = response.GetHexMaxU32(true, -1);
1982
1983 return true;
1984}
1985
1986bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001987GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001988{
Todd Fialaaf245d12014-06-30 21:05:18 +00001989 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
1990
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001991 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001992 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001993 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001994 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001995 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001996 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001997 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001998 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001999 std::string name;
2000 std::string value;
2001 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2002 uint32_t sub = 0;
2003 std::string arch_name;
2004 std::string os_name;
2005 std::string vendor_name;
2006 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00002007 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00002008 uint32_t pointer_byte_size = 0;
2009 StringExtractor extractor;
2010 ByteOrder byte_order = eByteOrderInvalid;
2011 uint32_t num_keys_decoded = 0;
2012 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00002013 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002014 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00002015 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002016 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002017 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00002018 if (cpu != LLDB_INVALID_CPUTYPE)
2019 ++num_keys_decoded;
2020 }
2021 else if (name.compare("cpusubtype") == 0)
2022 {
2023 // exception count in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002024 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00002025 if (sub != 0)
2026 ++num_keys_decoded;
2027 }
2028 else if (name.compare("arch") == 0)
2029 {
2030 arch_name.swap (value);
2031 ++num_keys_decoded;
2032 }
2033 else if (name.compare("triple") == 0)
2034 {
Greg Clayton44272a42014-09-18 00:18:32 +00002035 extractor.GetStringRef ().swap (value);
2036 extractor.SetFilePos(0);
2037 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00002038 ++num_keys_decoded;
2039 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00002040 else if (name.compare ("distribution_id") == 0)
2041 {
2042 extractor.GetStringRef ().swap (value);
2043 extractor.SetFilePos (0);
2044 extractor.GetHexByteString (distribution_id);
2045 ++num_keys_decoded;
2046 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002047 else if (name.compare("os_build") == 0)
2048 {
2049 extractor.GetStringRef().swap(value);
2050 extractor.SetFilePos(0);
2051 extractor.GetHexByteString (m_os_build);
2052 ++num_keys_decoded;
2053 }
2054 else if (name.compare("hostname") == 0)
2055 {
2056 extractor.GetStringRef().swap(value);
2057 extractor.SetFilePos(0);
2058 extractor.GetHexByteString (m_hostname);
2059 ++num_keys_decoded;
2060 }
2061 else if (name.compare("os_kernel") == 0)
2062 {
2063 extractor.GetStringRef().swap(value);
2064 extractor.SetFilePos(0);
2065 extractor.GetHexByteString (m_os_kernel);
2066 ++num_keys_decoded;
2067 }
2068 else if (name.compare("ostype") == 0)
2069 {
2070 os_name.swap (value);
2071 ++num_keys_decoded;
2072 }
2073 else if (name.compare("vendor") == 0)
2074 {
2075 vendor_name.swap(value);
2076 ++num_keys_decoded;
2077 }
2078 else if (name.compare("endian") == 0)
2079 {
2080 ++num_keys_decoded;
2081 if (value.compare("little") == 0)
2082 byte_order = eByteOrderLittle;
2083 else if (value.compare("big") == 0)
2084 byte_order = eByteOrderBig;
2085 else if (value.compare("pdp") == 0)
2086 byte_order = eByteOrderPDP;
2087 else
2088 --num_keys_decoded;
2089 }
2090 else if (name.compare("ptrsize") == 0)
2091 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002092 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00002093 if (pointer_byte_size != 0)
2094 ++num_keys_decoded;
2095 }
Greg Clayton17499dd2016-01-28 00:16:11 +00002096 else if ((name.compare("os_version") == 0) ||
2097 (name.compare("version") == 0)) // Older debugserver binaries used the "version" key instead of "os_version"...
Greg Clayton32e0a752011-03-30 18:16:51 +00002098 {
2099 Args::StringToVersion (value.c_str(),
2100 m_os_version_major,
2101 m_os_version_minor,
2102 m_os_version_update);
2103 if (m_os_version_major != UINT32_MAX)
2104 ++num_keys_decoded;
2105 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002106 else if (name.compare("watchpoint_exceptions_received") == 0)
2107 {
2108 ++num_keys_decoded;
2109 if (strcmp(value.c_str(),"before") == 0)
2110 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2111 else if (strcmp(value.c_str(),"after") == 0)
2112 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
2113 else
2114 --num_keys_decoded;
2115 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002116 else if (name.compare("default_packet_timeout") == 0)
2117 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002118 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002119 if (m_default_packet_timeout > 0)
2120 {
2121 SetPacketTimeout(m_default_packet_timeout);
2122 ++num_keys_decoded;
2123 }
2124 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002125
Greg Clayton32e0a752011-03-30 18:16:51 +00002126 }
2127
2128 if (num_keys_decoded > 0)
2129 m_qHostInfo_is_valid = eLazyBoolYes;
2130
2131 if (triple.empty())
2132 {
2133 if (arch_name.empty())
2134 {
2135 if (cpu != LLDB_INVALID_CPUTYPE)
2136 {
2137 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2138 if (pointer_byte_size)
2139 {
2140 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2141 }
2142 if (byte_order != eByteOrderInvalid)
2143 {
2144 assert (byte_order == m_host_arch.GetByteOrder());
2145 }
Greg Clayton70512312012-05-08 01:45:38 +00002146
Greg Clayton32e0a752011-03-30 18:16:51 +00002147 if (!vendor_name.empty())
2148 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2149 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00002150 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00002151
2152 }
2153 }
2154 else
2155 {
2156 std::string triple;
2157 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00002158 if (!vendor_name.empty() || !os_name.empty())
2159 {
2160 triple += '-';
2161 if (vendor_name.empty())
2162 triple += "unknown";
2163 else
2164 triple += vendor_name;
2165 triple += '-';
2166 if (os_name.empty())
2167 triple += "unknown";
2168 else
2169 triple += os_name;
2170 }
2171 m_host_arch.SetTriple (triple.c_str());
2172
2173 llvm::Triple &host_triple = m_host_arch.GetTriple();
2174 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
2175 {
2176 switch (m_host_arch.GetMachine())
2177 {
Todd Fialad8eaa172014-07-23 14:37:35 +00002178 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00002179 case llvm::Triple::arm:
2180 case llvm::Triple::thumb:
2181 host_triple.setOS(llvm::Triple::IOS);
2182 break;
2183 default:
2184 host_triple.setOS(llvm::Triple::MacOSX);
2185 break;
2186 }
2187 }
Greg Clayton1cb64962011-03-24 04:28:38 +00002188 if (pointer_byte_size)
2189 {
2190 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2191 }
2192 if (byte_order != eByteOrderInvalid)
2193 {
2194 assert (byte_order == m_host_arch.GetByteOrder());
2195 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002196
Greg Clayton1cb64962011-03-24 04:28:38 +00002197 }
2198 }
2199 else
2200 {
Greg Clayton70512312012-05-08 01:45:38 +00002201 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00002202 if (pointer_byte_size)
2203 {
2204 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2205 }
2206 if (byte_order != eByteOrderInvalid)
2207 {
2208 assert (byte_order == m_host_arch.GetByteOrder());
2209 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002210
2211 if (log)
2212 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 +00002213 }
2214 if (!distribution_id.empty ())
2215 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00002216 }
Greg Clayton576d8832011-03-22 04:00:09 +00002217 }
2218 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002219 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00002220}
2221
2222int
2223GDBRemoteCommunicationClient::SendAttach
2224(
2225 lldb::pid_t pid,
2226 StringExtractorGDBRemote& response
2227)
2228{
2229 if (pid != LLDB_INVALID_PROCESS_ID)
2230 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002231 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002232 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002233 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002234 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002235 {
2236 if (response.IsErrorResponse())
2237 return response.GetError();
2238 return 0;
2239 }
2240 }
2241 return -1;
2242}
2243
Vince Harrone0be4252015-02-06 18:32:57 +00002244int
2245GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
2246{
2247 StreamString packet;
2248 packet.PutCString("I");
2249 packet.PutBytesAsRawHex8(data, data_len);
2250 StringExtractorGDBRemote response;
2251 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2252 {
2253 return 0;
2254 }
2255 return response.GetError();
2256
2257}
2258
Greg Clayton576d8832011-03-22 04:00:09 +00002259const lldb_private::ArchSpec &
2260GDBRemoteCommunicationClient::GetHostArchitecture ()
2261{
Greg Clayton32e0a752011-03-30 18:16:51 +00002262 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00002263 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00002264 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00002265}
2266
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002267uint32_t
2268GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
2269{
2270 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
2271 GetHostInfo ();
2272 return m_default_packet_timeout;
2273}
2274
Greg Clayton576d8832011-03-22 04:00:09 +00002275addr_t
2276GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
2277{
Greg Clayton70b57652011-05-15 01:25:55 +00002278 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002279 {
Greg Clayton70b57652011-05-15 01:25:55 +00002280 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002281 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002282 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00002283 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00002284 permissions & lldb::ePermissionsReadable ? "r" : "",
2285 permissions & lldb::ePermissionsWritable ? "w" : "",
2286 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00002287 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002288 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002289 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002290 {
Todd Fialaf105f582014-06-21 00:48:09 +00002291 if (response.IsUnsupportedResponse())
2292 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2293 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002294 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2295 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002296 else
2297 {
2298 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2299 }
Greg Clayton576d8832011-03-22 04:00:09 +00002300 }
2301 return LLDB_INVALID_ADDRESS;
2302}
2303
2304bool
2305GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
2306{
Greg Clayton70b57652011-05-15 01:25:55 +00002307 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002308 {
Greg Clayton70b57652011-05-15 01:25:55 +00002309 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002310 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002311 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002312 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002313 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002314 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002315 {
Todd Fialaf105f582014-06-21 00:48:09 +00002316 if (response.IsUnsupportedResponse())
2317 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2318 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002319 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002320 }
2321 else
2322 {
2323 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00002324 }
Greg Clayton576d8832011-03-22 04:00:09 +00002325 }
2326 return false;
2327}
2328
Jim Inghamacff8952013-05-02 00:27:30 +00002329Error
2330GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00002331{
Jim Inghamacff8952013-05-02 00:27:30 +00002332 Error error;
2333
2334 if (keep_stopped)
2335 {
2336 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
2337 {
2338 char packet[64];
2339 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002340 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00002341 StringExtractorGDBRemote response;
Jim Ingham4920a4e2015-07-15 00:59:25 +00002342 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success
2343 && response.IsOKResponse())
Jim Inghamacff8952013-05-02 00:27:30 +00002344 {
2345 m_supports_detach_stay_stopped = eLazyBoolYes;
2346 }
2347 else
2348 {
2349 m_supports_detach_stay_stopped = eLazyBoolNo;
2350 }
2351 }
2352
2353 if (m_supports_detach_stay_stopped == eLazyBoolNo)
2354 {
2355 error.SetErrorString("Stays stopped not supported by this target.");
2356 return error;
2357 }
2358 else
2359 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002360 StringExtractorGDBRemote response;
Jason Molenda2a667382015-07-15 00:16:09 +00002361 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 2, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002362 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002363 error.SetErrorString ("Sending extended disconnect packet failed.");
2364 }
2365 }
2366 else
2367 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002368 StringExtractorGDBRemote response;
2369 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002370 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002371 error.SetErrorString ("Sending disconnect packet failed.");
2372 }
2373 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00002374}
2375
Greg Clayton46fb5582011-11-18 07:03:08 +00002376Error
2377GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2378 lldb_private::MemoryRegionInfo &region_info)
2379{
2380 Error error;
2381 region_info.Clear();
2382
2383 if (m_supports_memory_region_info != eLazyBoolNo)
2384 {
2385 m_supports_memory_region_info = eLazyBoolYes;
2386 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002387 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002388 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00002389 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002390 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00002391 {
2392 std::string name;
2393 std::string value;
2394 addr_t addr_value;
2395 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00002396 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00002397 while (success && response.GetNameColonValue(name, value))
2398 {
2399 if (name.compare ("start") == 0)
2400 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002401 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002402 if (success)
2403 region_info.GetRange().SetRangeBase(addr_value);
2404 }
2405 else if (name.compare ("size") == 0)
2406 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002407 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002408 if (success)
2409 region_info.GetRange().SetByteSize (addr_value);
2410 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002411 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00002412 {
Jason Molendacb349ee2011-12-13 05:39:38 +00002413 saw_permissions = true;
2414 if (region_info.GetRange().Contains (addr))
2415 {
2416 if (value.find('r') != std::string::npos)
2417 region_info.SetReadable (MemoryRegionInfo::eYes);
2418 else
2419 region_info.SetReadable (MemoryRegionInfo::eNo);
2420
2421 if (value.find('w') != std::string::npos)
2422 region_info.SetWritable (MemoryRegionInfo::eYes);
2423 else
2424 region_info.SetWritable (MemoryRegionInfo::eNo);
2425
2426 if (value.find('x') != std::string::npos)
2427 region_info.SetExecutable (MemoryRegionInfo::eYes);
2428 else
2429 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00002430
2431 region_info.SetMapped(MemoryRegionInfo::eYes);
Jason Molendacb349ee2011-12-13 05:39:38 +00002432 }
2433 else
2434 {
2435 // The reported region does not contain this address -- we're looking at an unmapped page
2436 region_info.SetReadable (MemoryRegionInfo::eNo);
2437 region_info.SetWritable (MemoryRegionInfo::eNo);
2438 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00002439 region_info.SetMapped(MemoryRegionInfo::eNo);
Jason Molendacb349ee2011-12-13 05:39:38 +00002440 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002441 }
2442 else if (name.compare ("error") == 0)
2443 {
2444 StringExtractorGDBRemote name_extractor;
2445 // Swap "value" over into "name_extractor"
2446 name_extractor.GetStringRef().swap(value);
2447 // Now convert the HEX bytes into a string value
2448 name_extractor.GetHexByteString (value);
2449 error.SetErrorString(value.c_str());
2450 }
2451 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002452
2453 // We got a valid address range back but no permissions -- which means this is an unmapped page
2454 if (region_info.GetRange().IsValid() && saw_permissions == false)
2455 {
2456 region_info.SetReadable (MemoryRegionInfo::eNo);
2457 region_info.SetWritable (MemoryRegionInfo::eNo);
2458 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00002459 region_info.SetMapped(MemoryRegionInfo::eNo);
Jason Molendacb349ee2011-12-13 05:39:38 +00002460 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002461 }
2462 else
2463 {
2464 m_supports_memory_region_info = eLazyBoolNo;
2465 }
2466 }
2467
2468 if (m_supports_memory_region_info == eLazyBoolNo)
2469 {
2470 error.SetErrorString("qMemoryRegionInfo is not supported");
2471 }
2472 if (error.Fail())
2473 region_info.Clear();
2474 return error;
2475
2476}
2477
Johnny Chen64637202012-05-23 21:09:52 +00002478Error
2479GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2480{
2481 Error error;
2482
2483 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2484 {
2485 num = m_num_supported_hardware_watchpoints;
2486 return error;
2487 }
2488
2489 // Set num to 0 first.
2490 num = 0;
2491 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2492 {
2493 char packet[64];
2494 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002495 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00002496 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002497 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00002498 {
2499 m_supports_watchpoint_support_info = eLazyBoolYes;
2500 std::string name;
2501 std::string value;
2502 while (response.GetNameColonValue(name, value))
2503 {
2504 if (name.compare ("num") == 0)
2505 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002506 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
Johnny Chen64637202012-05-23 21:09:52 +00002507 m_num_supported_hardware_watchpoints = num;
2508 }
2509 }
2510 }
2511 else
2512 {
2513 m_supports_watchpoint_support_info = eLazyBoolNo;
2514 }
2515 }
2516
2517 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2518 {
2519 error.SetErrorString("qWatchpointSupportInfo is not supported");
2520 }
2521 return error;
2522
2523}
Greg Clayton46fb5582011-11-18 07:03:08 +00002524
Enrico Granataf04a2192012-07-13 23:18:48 +00002525lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00002526GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00002527{
2528 Error error(GetWatchpointSupportInfo(num));
2529 if (error.Success())
Jaydeep Patil725666c2015-08-13 03:46:01 +00002530 error = GetWatchpointsTriggerAfterInstruction(after, arch);
Enrico Granataf04a2192012-07-13 23:18:48 +00002531 return error;
2532}
2533
2534lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00002535GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00002536{
2537 Error error;
Jaydeep Patil725666c2015-08-13 03:46:01 +00002538 llvm::Triple::ArchType atype = arch.GetMachine();
Enrico Granataf04a2192012-07-13 23:18:48 +00002539
2540 // we assume watchpoints will happen after running the relevant opcode
2541 // and we only want to override this behavior if we have explicitly
2542 // received a qHostInfo telling us otherwise
2543 if (m_qHostInfo_is_valid != eLazyBoolYes)
Jaydeep Patil725666c2015-08-13 03:46:01 +00002544 {
2545 // On targets like MIPS, watchpoint exceptions are always generated
2546 // before the instruction is executed. The connected target may not
2547 // support qHostInfo or qWatchpointSupportInfo packets.
2548 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
2549 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
2550 after = false;
2551 else
2552 after = true;
2553 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002554 else
Jaydeep Patil725666c2015-08-13 03:46:01 +00002555 {
2556 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
2557 // if it is not calculated before.
2558 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
2559 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
2560 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
2561 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2562
Enrico Granataf04a2192012-07-13 23:18:48 +00002563 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
Jaydeep Patil725666c2015-08-13 03:46:01 +00002564 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002565 return error;
2566}
2567
Greg Clayton576d8832011-03-22 04:00:09 +00002568int
Chaoren Lind3173f32015-05-29 19:52:29 +00002569GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002570{
Chaoren Lind3173f32015-05-29 19:52:29 +00002571 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002572 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002573 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002574 StreamString packet;
2575 packet.PutCString("QSetSTDIN:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002576 packet.PutCStringAsRawHex8(path.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00002577
2578 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002579 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002580 {
2581 if (response.IsOKResponse())
2582 return 0;
2583 uint8_t error = response.GetError();
2584 if (error)
2585 return error;
2586 }
2587 }
2588 return -1;
2589}
2590
2591int
Chaoren Lind3173f32015-05-29 19:52:29 +00002592GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002593{
Chaoren Lind3173f32015-05-29 19:52:29 +00002594 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002595 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002596 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002597 StreamString packet;
2598 packet.PutCString("QSetSTDOUT:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002599 packet.PutCStringAsRawHex8(path.c_str());
2600
Greg Clayton576d8832011-03-22 04:00:09 +00002601 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002602 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002603 {
2604 if (response.IsOKResponse())
2605 return 0;
2606 uint8_t error = response.GetError();
2607 if (error)
2608 return error;
2609 }
2610 }
2611 return -1;
2612}
2613
2614int
Chaoren Lind3173f32015-05-29 19:52:29 +00002615GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002616{
Chaoren Lind3173f32015-05-29 19:52:29 +00002617 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002618 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002619 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002620 StreamString packet;
2621 packet.PutCString("QSetSTDERR:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002622 packet.PutCStringAsRawHex8(path.c_str());
2623
Greg Clayton576d8832011-03-22 04:00:09 +00002624 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002625 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002626 {
2627 if (response.IsOKResponse())
2628 return 0;
2629 uint8_t error = response.GetError();
2630 if (error)
2631 return error;
2632 }
2633 }
2634 return -1;
2635}
2636
Greg Claytonfbb76342013-11-20 21:07:01 +00002637bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002638GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
Greg Claytonfbb76342013-11-20 21:07:01 +00002639{
2640 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002641 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002642 {
2643 if (response.IsUnsupportedResponse())
2644 return false;
2645 if (response.IsErrorResponse())
2646 return false;
Chaoren Lind3173f32015-05-29 19:52:29 +00002647 std::string cwd;
2648 response.GetHexByteString(cwd);
Chaoren Lin44145d72015-05-29 19:52:37 +00002649 working_dir.SetFile(cwd, false, GetHostArchitecture());
Greg Claytonfbb76342013-11-20 21:07:01 +00002650 return !cwd.empty();
2651 }
2652 return false;
2653}
2654
Greg Clayton576d8832011-03-22 04:00:09 +00002655int
Chaoren Lind3173f32015-05-29 19:52:29 +00002656GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002657{
Chaoren Lind3173f32015-05-29 19:52:29 +00002658 if (working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002659 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002660 std::string path{working_dir.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002661 StreamString packet;
2662 packet.PutCString("QSetWorkingDir:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002663 packet.PutCStringAsRawHex8(path.c_str());
2664
Greg Clayton576d8832011-03-22 04:00:09 +00002665 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002666 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002667 {
2668 if (response.IsOKResponse())
2669 return 0;
2670 uint8_t error = response.GetError();
2671 if (error)
2672 return error;
2673 }
2674 }
2675 return -1;
2676}
2677
2678int
2679GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2680{
Greg Clayton32e0a752011-03-30 18:16:51 +00002681 char packet[32];
2682 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002683 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002684 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002685 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002686 {
2687 if (response.IsOKResponse())
2688 return 0;
2689 uint8_t error = response.GetError();
2690 if (error)
2691 return error;
2692 }
2693 return -1;
2694}
Greg Clayton32e0a752011-03-30 18:16:51 +00002695
Jim Ingham106d0282014-06-25 02:32:56 +00002696int
2697GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2698{
2699 char packet[32];
2700 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2701 assert (packet_len < (int)sizeof(packet));
2702 StringExtractorGDBRemote response;
2703 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2704 {
2705 if (response.IsOKResponse())
2706 return 0;
2707 uint8_t error = response.GetError();
2708 if (error)
2709 return error;
2710 }
2711 return -1;
2712}
2713
2714
Greg Clayton32e0a752011-03-30 18:16:51 +00002715bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002716GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002717{
2718 if (response.IsNormalResponse())
2719 {
2720 std::string name;
2721 std::string value;
2722 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002723
2724 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2725 uint32_t sub = 0;
2726 std::string vendor;
2727 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002728
2729 while (response.GetNameColonValue(name, value))
2730 {
2731 if (name.compare("pid") == 0)
2732 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002733 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002734 }
2735 else if (name.compare("ppid") == 0)
2736 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002737 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002738 }
2739 else if (name.compare("uid") == 0)
2740 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002741 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002742 }
2743 else if (name.compare("euid") == 0)
2744 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002745 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002746 }
2747 else if (name.compare("gid") == 0)
2748 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002749 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002750 }
2751 else if (name.compare("egid") == 0)
2752 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002753 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002754 }
2755 else if (name.compare("triple") == 0)
2756 {
Greg Clayton44272a42014-09-18 00:18:32 +00002757 StringExtractor extractor;
2758 extractor.GetStringRef().swap(value);
2759 extractor.SetFilePos(0);
2760 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002761 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002762 }
2763 else if (name.compare("name") == 0)
2764 {
2765 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002766 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002767 // control the characters in a process name
2768 extractor.GetStringRef().swap(value);
2769 extractor.SetFilePos(0);
2770 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002771 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002772 }
Jason Molenda89c37492014-01-27 22:23:20 +00002773 else if (name.compare("cputype") == 0)
2774 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002775 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002776 }
2777 else if (name.compare("cpusubtype") == 0)
2778 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002779 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002780 }
2781 else if (name.compare("vendor") == 0)
2782 {
2783 vendor = value;
2784 }
2785 else if (name.compare("ostype") == 0)
2786 {
2787 os_type = value;
2788 }
2789 }
2790
2791 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2792 {
2793 if (vendor == "apple")
2794 {
2795 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2796 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2797 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2798 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002799 }
2800
2801 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2802 return true;
2803 }
2804 return false;
2805}
2806
2807bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002808GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002809{
2810 process_info.Clear();
2811
2812 if (m_supports_qProcessInfoPID)
2813 {
2814 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002815 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002816 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002817 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002818 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002819 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002820 return DecodeProcessInfoResponse (response, process_info);
2821 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002822 else
2823 {
2824 m_supports_qProcessInfoPID = false;
2825 return false;
2826 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002827 }
2828 return false;
2829}
2830
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002831bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002832GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002833{
Todd Fiala3daa1762014-09-15 16:01:29 +00002834 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2835
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002836 if (allow_lazy)
2837 {
2838 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2839 return true;
2840 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2841 return false;
2842 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002843
2844 GetHostInfo ();
2845
2846 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002847 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002848 {
2849 if (response.IsNormalResponse())
2850 {
2851 std::string name;
2852 std::string value;
2853 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2854 uint32_t sub = 0;
2855 std::string arch_name;
2856 std::string os_name;
2857 std::string vendor_name;
2858 std::string triple;
2859 uint32_t pointer_byte_size = 0;
2860 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002861 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002862 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002863 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002864 while (response.GetNameColonValue(name, value))
2865 {
2866 if (name.compare("cputype") == 0)
2867 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002868 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002869 if (cpu != LLDB_INVALID_CPUTYPE)
2870 ++num_keys_decoded;
2871 }
2872 else if (name.compare("cpusubtype") == 0)
2873 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002874 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002875 if (sub != 0)
2876 ++num_keys_decoded;
2877 }
Todd Fialac540dd02014-08-26 18:21:02 +00002878 else if (name.compare("triple") == 0)
2879 {
Greg Clayton44272a42014-09-18 00:18:32 +00002880 StringExtractor extractor;
2881 extractor.GetStringRef().swap(value);
2882 extractor.SetFilePos(0);
2883 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002884 ++num_keys_decoded;
2885 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002886 else if (name.compare("ostype") == 0)
2887 {
2888 os_name.swap (value);
2889 ++num_keys_decoded;
2890 }
2891 else if (name.compare("vendor") == 0)
2892 {
2893 vendor_name.swap(value);
2894 ++num_keys_decoded;
2895 }
2896 else if (name.compare("endian") == 0)
2897 {
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002898 ++num_keys_decoded;
2899 if (value.compare("little") == 0)
2900 byte_order = eByteOrderLittle;
2901 else if (value.compare("big") == 0)
2902 byte_order = eByteOrderBig;
2903 else if (value.compare("pdp") == 0)
2904 byte_order = eByteOrderPDP;
2905 else
2906 --num_keys_decoded;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002907 }
2908 else if (name.compare("ptrsize") == 0)
2909 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002910 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002911 if (pointer_byte_size != 0)
2912 ++num_keys_decoded;
2913 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002914 else if (name.compare("pid") == 0)
2915 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002916 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002917 if (pid != LLDB_INVALID_PROCESS_ID)
2918 ++num_keys_decoded;
2919 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002920 }
2921 if (num_keys_decoded > 0)
2922 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002923 if (pid != LLDB_INVALID_PROCESS_ID)
2924 {
2925 m_curr_pid_is_valid = eLazyBoolYes;
2926 m_curr_pid = pid;
2927 }
Todd Fialac540dd02014-08-26 18:21:02 +00002928
2929 // Set the ArchSpec from the triple if we have it.
2930 if (!triple.empty ())
2931 {
2932 m_process_arch.SetTriple (triple.c_str ());
2933 if (pointer_byte_size)
2934 {
2935 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2936 }
2937 }
2938 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002939 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002940 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2941
2942 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2943 switch (triple.getObjectFormat()) {
2944 case llvm::Triple::MachO:
2945 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2946 break;
2947 case llvm::Triple::ELF:
2948 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2949 break;
2950 case llvm::Triple::COFF:
2951 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2952 break;
2953 case llvm::Triple::UnknownObjectFormat:
2954 if (log)
2955 log->Printf("error: failed to determine target architecture");
2956 return false;
2957 }
2958
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002959 if (pointer_byte_size)
2960 {
2961 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2962 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002963 if (byte_order != eByteOrderInvalid)
2964 {
2965 assert (byte_order == m_process_arch.GetByteOrder());
2966 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002967 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002968 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002969 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2970 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002971 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002972 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002973 }
2974 }
2975 else
2976 {
2977 m_qProcessInfo_is_valid = eLazyBoolNo;
2978 }
2979
2980 return false;
2981}
2982
2983
Greg Clayton32e0a752011-03-30 18:16:51 +00002984uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00002985GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
2986 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00002987{
2988 process_infos.Clear();
2989
2990 if (m_supports_qfProcessInfo)
2991 {
2992 StreamString packet;
2993 packet.PutCString ("qfProcessInfo");
2994 if (!match_info.MatchAllProcesses())
2995 {
2996 packet.PutChar (':');
2997 const char *name = match_info.GetProcessInfo().GetName();
2998 bool has_name_match = false;
2999 if (name && name[0])
3000 {
3001 has_name_match = true;
3002 NameMatchType name_match_type = match_info.GetNameMatchType();
3003 switch (name_match_type)
3004 {
3005 case eNameMatchIgnore:
3006 has_name_match = false;
3007 break;
3008
3009 case eNameMatchEquals:
3010 packet.PutCString ("name_match:equals;");
3011 break;
3012
3013 case eNameMatchContains:
3014 packet.PutCString ("name_match:contains;");
3015 break;
3016
3017 case eNameMatchStartsWith:
3018 packet.PutCString ("name_match:starts_with;");
3019 break;
3020
3021 case eNameMatchEndsWith:
3022 packet.PutCString ("name_match:ends_with;");
3023 break;
3024
3025 case eNameMatchRegularExpression:
3026 packet.PutCString ("name_match:regex;");
3027 break;
3028 }
3029 if (has_name_match)
3030 {
3031 packet.PutCString ("name:");
3032 packet.PutBytesAsRawHex8(name, ::strlen(name));
3033 packet.PutChar (';');
3034 }
3035 }
3036
3037 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00003038 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00003039 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00003040 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00003041 if (match_info.GetProcessInfo().UserIDIsValid())
3042 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
3043 if (match_info.GetProcessInfo().GroupIDIsValid())
3044 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00003045 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
3046 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
3047 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3048 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
3049 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3050 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
3051 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
3052 {
3053 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
3054 const llvm::Triple &triple = match_arch.GetTriple();
3055 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00003056 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00003057 packet.PutChar (';');
3058 }
3059 }
3060 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00003061 // Increase timeout as the first qfProcessInfo packet takes a long time
3062 // on Android. The value of 1min was arrived at empirically.
3063 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00003064 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003065 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003066 do
3067 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003068 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00003069 if (!DecodeProcessInfoResponse (response, process_info))
3070 break;
3071 process_infos.Append(process_info);
3072 response.GetStringRef().clear();
3073 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00003074 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00003075 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003076 else
3077 {
3078 m_supports_qfProcessInfo = false;
3079 return 0;
3080 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003081 }
3082 return process_infos.GetSize();
3083
3084}
3085
3086bool
3087GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
3088{
3089 if (m_supports_qUserName)
3090 {
3091 char packet[32];
3092 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003093 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003094 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003095 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003096 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003097 if (response.IsNormalResponse())
3098 {
3099 // Make sure we parsed the right number of characters. The response is
3100 // the hex encoded user name and should make up the entire packet.
3101 // If there are any non-hex ASCII bytes, the length won't match below..
3102 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3103 return true;
3104 }
3105 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003106 else
3107 {
3108 m_supports_qUserName = false;
3109 return false;
3110 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003111 }
3112 return false;
3113
3114}
3115
3116bool
3117GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
3118{
3119 if (m_supports_qGroupName)
3120 {
3121 char packet[32];
3122 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003123 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003124 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003125 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003126 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003127 if (response.IsNormalResponse())
3128 {
3129 // Make sure we parsed the right number of characters. The response is
3130 // the hex encoded group name and should make up the entire packet.
3131 // If there are any non-hex ASCII bytes, the length won't match below..
3132 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3133 return true;
3134 }
3135 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003136 else
3137 {
3138 m_supports_qGroupName = false;
3139 return false;
3140 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003141 }
3142 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003143}
Greg Clayton32e0a752011-03-30 18:16:51 +00003144
Ewan Crawford78baa192015-05-13 09:18:18 +00003145bool
3146GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
3147{
3148 // Form non-stop packet request
3149 char packet[32];
3150 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
3151 assert(packet_len < (int)sizeof(packet));
3152
3153 StringExtractorGDBRemote response;
3154 // Send to target
3155 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3156 if (response.IsOKResponse())
3157 return true;
3158
3159 // Failed or not supported
3160 return false;
3161
3162}
3163
Greg Claytone034a042015-05-21 20:52:06 +00003164static void
3165MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
3166{
3167 packet.Clear();
3168 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3169 uint32_t bytes_left = send_size;
3170 while (bytes_left > 0)
3171 {
3172 if (bytes_left >= 26)
3173 {
3174 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3175 bytes_left -= 26;
3176 }
3177 else
3178 {
3179 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3180 bytes_left = 0;
3181 }
3182 }
3183}
3184
3185template<typename T>
3186T calculate_standard_deviation(const std::vector<T> &v)
3187{
3188 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
3189 T mean = sum / (T)v.size();
3190 T accum = T(0);
3191 std::for_each (std::begin(v), std::end(v), [&](const T d) {
3192 T delta = d - mean;
3193 accum += delta * delta;
3194 });
3195
3196 T stdev = sqrt(accum / (v.size()-1));
3197 return stdev;
3198}
3199
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003200void
Greg Claytone034a042015-05-21 20:52:06 +00003201GDBRemoteCommunicationClient::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 +00003202{
3203 uint32_t i;
3204 TimeValue start_time, end_time;
3205 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003206 if (SendSpeedTestPacket (0, 0))
3207 {
Greg Claytone034a042015-05-21 20:52:06 +00003208 StreamString packet;
3209 if (json)
3210 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
3211 else
3212 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
3213 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00003214
Greg Claytone034a042015-05-21 20:52:06 +00003215 uint32_t result_idx = 0;
3216 uint32_t send_size;
3217 std::vector<float> packet_times;
3218
3219 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
3220 {
3221 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
3222 {
3223 MakeSpeedTestPacket (packet, send_size, recv_size);
3224
3225 packet_times.clear();
3226 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00003227 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00003228 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00003229 {
Greg Claytone034a042015-05-21 20:52:06 +00003230 TimeValue packet_start_time = TimeValue::Now();
3231 StringExtractorGDBRemote response;
3232 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3233 TimeValue packet_end_time = TimeValue::Now();
3234 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
3235 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003236 }
3237 end_time = TimeValue::Now();
3238 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00003239
3240 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3241 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3242 float average_ms_per_packet = total_ms / num_packets;
3243 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
3244 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00003245 {
Greg Claytone034a042015-05-21 20:52:06 +00003246 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);
3247 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00003248 }
3249 else
3250 {
Greg Claytone034a042015-05-21 20:52:06 +00003251 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",
3252 send_size,
3253 recv_size,
3254 total_time_nsec / TimeValue::NanoSecPerSec,
3255 total_time_nsec % TimeValue::NanoSecPerSec,
3256 packets_per_second,
3257 average_ms_per_packet,
3258 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00003259 }
Greg Claytone034a042015-05-21 20:52:06 +00003260 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003261 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003262 }
Greg Claytone034a042015-05-21 20:52:06 +00003263
3264 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
3265
3266 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
3267 if (json)
3268 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
3269 else
3270 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
3271 strm.Flush();
3272 send_size = 0;
3273 result_idx = 0;
3274 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
3275 {
3276 MakeSpeedTestPacket (packet, send_size, recv_size);
3277
3278 // If we have a receive size, test how long it takes to receive 4MB of data
3279 if (recv_size > 0)
3280 {
3281 start_time = TimeValue::Now();
3282 uint32_t bytes_read = 0;
3283 uint32_t packet_count = 0;
3284 while (bytes_read < k_recv_amount)
3285 {
3286 StringExtractorGDBRemote response;
3287 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3288 bytes_read += recv_size;
3289 ++packet_count;
3290 }
3291 end_time = TimeValue::Now();
3292 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3293 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
3294 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3295 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3296 float average_ms_per_packet = total_ms / packet_count;
3297
3298 if (json)
3299 {
3300 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);
3301 ++result_idx;
3302 }
3303 else
3304 {
3305 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",
3306 send_size,
3307 recv_size,
3308 packet_count,
3309 k_recv_amount_mb,
3310 total_time_nsec / TimeValue::NanoSecPerSec,
3311 total_time_nsec % TimeValue::NanoSecPerSec,
3312 mb_second,
3313 packets_per_second,
3314 average_ms_per_packet);
3315 }
3316 strm.Flush();
3317 }
3318 }
3319 if (json)
3320 strm.Printf("\n ]\n }\n}\n");
3321 else
3322 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003323 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003324}
3325
3326bool
3327GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
3328{
3329 StreamString packet;
3330 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3331 uint32_t bytes_left = send_size;
3332 while (bytes_left > 0)
3333 {
3334 if (bytes_left >= 26)
3335 {
3336 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3337 bytes_left -= 26;
3338 }
3339 else
3340 {
3341 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3342 bytes_left = 0;
3343 }
3344 }
3345
3346 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003347 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00003348}
Greg Clayton8b82f082011-04-12 05:54:46 +00003349
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003350bool
3351GDBRemoteCommunicationClient::LaunchGDBServer (const char *remote_accept_hostname,
3352 lldb::pid_t &pid,
3353 uint16_t &port,
3354 std::string &socket_name)
Greg Clayton8b82f082011-04-12 05:54:46 +00003355{
Daniel Maleae0f8f572013-08-26 23:57:52 +00003356 pid = LLDB_INVALID_PROCESS_ID;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003357 port = 0;
3358 socket_name.clear();
3359
Greg Clayton8b82f082011-04-12 05:54:46 +00003360 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003361 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00003362 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003363 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00003364 if (remote_accept_hostname && remote_accept_hostname[0])
3365 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003366 else
3367 {
Zachary Turner97a14e62014-08-19 17:18:29 +00003368 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00003369 {
3370 // Make the GDB server we launch only accept connections from this host
3371 stream.Printf("host:%s;", hostname.c_str());
3372 }
3373 else
3374 {
3375 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
3376 stream.Printf("host:*;");
3377 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003378 }
3379 const char *packet = stream.GetData();
3380 int packet_len = stream.GetSize();
3381
Vince Harron1b5a74e2015-01-21 22:42:49 +00003382 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00003383 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003384
Tamas Berghammer912800c2015-02-24 10:23:39 +00003385 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003386 {
3387 std::string name;
3388 std::string value;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003389 StringExtractor extractor;
Greg Clayton8b82f082011-04-12 05:54:46 +00003390 while (response.GetNameColonValue(name, value))
3391 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00003392 if (name.compare("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003393 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003394 else if (name.compare("pid") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003395 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003396 else if (name.compare("socket_name") == 0)
3397 {
3398 extractor.GetStringRef().swap(value);
3399 extractor.SetFilePos(0);
3400 extractor.GetHexByteString(value);
3401
3402 socket_name = value;
3403 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003404 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003405 return true;
Greg Clayton8b82f082011-04-12 05:54:46 +00003406 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003407 return false;
Greg Clayton8b82f082011-04-12 05:54:46 +00003408}
3409
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00003410size_t
3411GDBRemoteCommunicationClient::QueryGDBServer (std::vector<std::pair<uint16_t, std::string>>& connection_urls)
3412{
3413 connection_urls.clear();
3414
3415 StringExtractorGDBRemote response;
3416 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) != PacketResult::Success)
3417 return 0;
3418
3419 StructuredData::ObjectSP data = StructuredData::ParseJSON(response.GetStringRef());
3420 if (!data)
3421 return 0;
3422
3423 StructuredData::Array* array = data->GetAsArray();
3424 if (!array)
3425 return 0;
3426
3427 for (size_t i = 0, count = array->GetSize(); i < count; ++i)
3428 {
3429 StructuredData::Dictionary* element = nullptr;
3430 if (!array->GetItemAtIndexAsDictionary(i, element))
3431 continue;
3432
3433 uint16_t port = 0;
3434 if (StructuredData::ObjectSP port_osp = element->GetValueForKey(llvm::StringRef("port")))
3435 port = port_osp->GetIntegerValue(0);
3436
3437 std::string socket_name;
3438 if (StructuredData::ObjectSP socket_name_osp = element->GetValueForKey(llvm::StringRef("socket_name")))
3439 socket_name = socket_name_osp->GetStringValue();
3440
3441 if (port != 0 || !socket_name.empty())
3442 connection_urls.emplace_back(port, socket_name);
3443 }
3444 return connection_urls.size();
3445}
3446
Greg Clayton8b82f082011-04-12 05:54:46 +00003447bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00003448GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
3449{
3450 StreamString stream;
3451 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
3452 const char *packet = stream.GetData();
3453 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00003454
Daniel Maleae0f8f572013-08-26 23:57:52 +00003455 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003456 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003457 {
3458 if (response.IsOKResponse())
3459 return true;
3460 }
3461 return false;
3462}
3463
3464bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003465GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003466{
3467 if (m_curr_tid == tid)
3468 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003469
Greg Clayton8b82f082011-04-12 05:54:46 +00003470 char packet[32];
3471 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003472 if (tid == UINT64_MAX)
3473 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003474 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003475 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003476 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003477 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003478 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003479 {
3480 if (response.IsOKResponse())
3481 {
3482 m_curr_tid = tid;
3483 return true;
3484 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003485
3486 /*
3487 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hg packet.
3488 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3489 * give us pid and/or tid. Assume pid=tid=1 in such cases.
3490 */
3491 if (response.IsUnsupportedResponse() && IsConnected())
3492 {
3493 m_curr_tid = 1;
3494 return true;
3495 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003496 }
3497 return false;
3498}
3499
3500bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003501GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003502{
3503 if (m_curr_tid_run == tid)
3504 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003505
Greg Clayton8b82f082011-04-12 05:54:46 +00003506 char packet[32];
3507 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003508 if (tid == UINT64_MAX)
3509 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003510 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003511 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3512
Andy Gibbsa297a972013-06-19 19:04:53 +00003513 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003514 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003515 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003516 {
3517 if (response.IsOKResponse())
3518 {
3519 m_curr_tid_run = tid;
3520 return true;
3521 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003522
3523 /*
3524 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hc packet.
3525 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3526 * give us pid and/or tid. Assume pid=tid=1 in such cases.
3527 */
3528 if (response.IsUnsupportedResponse() && IsConnected())
3529 {
3530 m_curr_tid_run = 1;
3531 return true;
3532 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003533 }
3534 return false;
3535}
3536
3537bool
3538GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3539{
Greg Clayton3dedae12013-12-06 21:45:27 +00003540 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003541 return response.IsNormalResponse();
3542 return false;
3543}
3544
3545bool
Greg Claytonf402f782012-10-13 02:11:55 +00003546GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00003547{
3548 if (m_supports_qThreadStopInfo)
3549 {
3550 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00003551 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003552 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00003553 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003554 {
Greg Claytonef8180a2013-10-15 00:14:28 +00003555 if (response.IsUnsupportedResponse())
3556 m_supports_qThreadStopInfo = false;
3557 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003558 return true;
3559 else
3560 return false;
3561 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003562 else
3563 {
3564 m_supports_qThreadStopInfo = false;
3565 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003566 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003567 return false;
3568}
3569
3570
3571uint8_t
3572GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
3573{
Todd Fiala616b8272014-10-09 00:55:04 +00003574 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3575 if (log)
3576 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3577 __FUNCTION__, insert ? "add" : "remove", addr);
3578
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003579 // Check if the stub is known not to support this breakpoint type
3580 if (!SupportsGDBStoppointPacket(type))
3581 return UINT8_MAX;
3582 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00003583 char packet[64];
3584 const int packet_len = ::snprintf (packet,
3585 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00003586 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00003587 insert ? 'Z' : 'z',
3588 type,
3589 addr,
3590 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003591 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00003592 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003593 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +00003594 // Make sure the response is either "OK", "EXX" where XX are two hex digits, or "" (unsupported)
3595 response.SetResponseValidatorToOKErrorNotSupported();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003596 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00003597 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003598 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003599 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00003600 if (response.IsOKResponse())
3601 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003602
3603 // Error while setting breakpoint, send back specific error
3604 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003605 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003606
3607 // Empty packet informs us that breakpoint is not supported
3608 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00003609 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003610 // Disable this breakpoint type since it is unsupported
3611 switch (type)
3612 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00003613 case eBreakpointSoftware: m_supports_z0 = false; break;
3614 case eBreakpointHardware: m_supports_z1 = false; break;
3615 case eWatchpointWrite: m_supports_z2 = false; break;
3616 case eWatchpointRead: m_supports_z3 = false; break;
3617 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00003618 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003619 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003620 }
3621 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003622 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00003623 return UINT8_MAX;
3624}
Greg Claytonadc00cb2011-05-20 23:38:13 +00003625
3626size_t
3627GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3628 bool &sequence_mutex_unavailable)
3629{
3630 Mutex::Locker locker;
3631 thread_ids.clear();
3632
Jim Ingham4ceb9282012-06-08 22:50:40 +00003633 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003634 {
3635 sequence_mutex_unavailable = false;
3636 StringExtractorGDBRemote response;
3637
Greg Clayton3dedae12013-12-06 21:45:27 +00003638 PacketResult packet_result;
3639 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3640 packet_result == PacketResult::Success && response.IsNormalResponse();
3641 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003642 {
3643 char ch = response.GetChar();
3644 if (ch == 'l')
3645 break;
3646 if (ch == 'm')
3647 {
3648 do
3649 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00003650 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00003651
3652 if (tid != LLDB_INVALID_THREAD_ID)
3653 {
3654 thread_ids.push_back (tid);
3655 }
3656 ch = response.GetChar(); // Skip the command separator
3657 } while (ch == ','); // Make sure we got a comma separator
3658 }
3659 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003660
3661 /*
3662 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
3663 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet could
3664 * be as simple as 'S05'. There is no packet which can give us pid and/or tid.
3665 * Assume pid=tid=1 in such cases.
3666 */
3667 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 && IsConnected())
3668 {
3669 thread_ids.push_back (1);
3670 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00003671 }
3672 else
3673 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00003674#if defined (LLDB_CONFIGURATION_DEBUG)
3675 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3676#else
Greg Clayton5160ce52013-03-27 23:08:40 +00003677 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00003678 if (log)
3679 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00003680#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00003681 sequence_mutex_unavailable = true;
3682 }
3683 return thread_ids.size();
3684}
Greg Clayton37a0a242012-04-11 00:24:49 +00003685
3686lldb::addr_t
3687GDBRemoteCommunicationClient::GetShlibInfoAddr()
3688{
3689 if (!IsRunning())
3690 {
3691 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003692 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00003693 {
3694 if (response.IsNormalResponse())
3695 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3696 }
3697 }
3698 return LLDB_INVALID_ADDRESS;
3699}
3700
Daniel Maleae0f8f572013-08-26 23:57:52 +00003701lldb_private::Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003702GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3703 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3704 int *status_ptr, // Pass NULL if you don't want the process exit status
3705 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3706 std::string *command_output, // Pass NULL if you don't want the command output
3707 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
Daniel Maleae0f8f572013-08-26 23:57:52 +00003708{
3709 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003710 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003711 stream.PutBytesAsRawHex8(command, strlen(command));
3712 stream.PutChar(',');
3713 stream.PutHex32(timeout_sec);
Chaoren Lind3173f32015-05-29 19:52:29 +00003714 if (working_dir)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003715 {
Chaoren Lind3173f32015-05-29 19:52:29 +00003716 std::string path{working_dir.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003717 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003718 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003719 }
3720 const char *packet = stream.GetData();
3721 int packet_len = stream.GetSize();
3722 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003723 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003724 {
3725 if (response.GetChar() != 'F')
3726 return Error("malformed reply");
3727 if (response.GetChar() != ',')
3728 return Error("malformed reply");
3729 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3730 if (exitcode == UINT32_MAX)
3731 return Error("unable to run remote process");
3732 else if (status_ptr)
3733 *status_ptr = exitcode;
3734 if (response.GetChar() != ',')
3735 return Error("malformed reply");
3736 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3737 if (signo_ptr)
3738 *signo_ptr = signo;
3739 if (response.GetChar() != ',')
3740 return Error("malformed reply");
3741 std::string output;
3742 response.GetEscapedBinaryData(output);
3743 if (command_output)
3744 command_output->assign(output);
3745 return Error();
3746 }
3747 return Error("unable to send packet");
3748}
3749
Greg Claytonfbb76342013-11-20 21:07:01 +00003750Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003751GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3752 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003753{
Chaoren Lind3173f32015-05-29 19:52:29 +00003754 std::string path{file_spec.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003755 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003756 stream.PutCString("qPlatform_mkdir:");
3757 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003758 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003759 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003760 const char *packet = stream.GetData();
3761 int packet_len = stream.GetSize();
3762 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003763
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003764 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3765 return Error("failed to send '%s' packet", packet);
3766
3767 if (response.GetChar() != 'F')
3768 return Error("invalid response to '%s' packet", packet);
3769
3770 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003771}
3772
Greg Claytonfbb76342013-11-20 21:07:01 +00003773Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003774GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3775 uint32_t file_permissions)
Greg Claytonfbb76342013-11-20 21:07:01 +00003776{
Chaoren Lind3173f32015-05-29 19:52:29 +00003777 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003778 lldb_private::StreamString stream;
3779 stream.PutCString("qPlatform_chmod:");
3780 stream.PutHex32(file_permissions);
3781 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003782 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003783 const char *packet = stream.GetData();
3784 int packet_len = stream.GetSize();
3785 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003786
3787 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3788 return Error("failed to send '%s' packet", packet);
3789
3790 if (response.GetChar() != 'F')
3791 return Error("invalid response to '%s' packet", packet);
3792
Chaoren Lince36c4c2015-05-05 18:43:19 +00003793 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003794}
3795
Daniel Maleae0f8f572013-08-26 23:57:52 +00003796static uint64_t
3797ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3798 uint64_t fail_result,
3799 Error &error)
3800{
3801 response.SetFilePos(0);
3802 if (response.GetChar() != 'F')
3803 return fail_result;
3804 int32_t result = response.GetS32 (-2);
3805 if (result == -2)
3806 return fail_result;
3807 if (response.GetChar() == ',')
3808 {
3809 int result_errno = response.GetS32 (-2);
3810 if (result_errno != -2)
3811 error.SetError(result_errno, eErrorTypePOSIX);
3812 else
3813 error.SetError(-1, eErrorTypeGeneric);
3814 }
3815 else
3816 error.Clear();
3817 return result;
3818}
3819lldb::user_id_t
3820GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3821 uint32_t flags,
3822 mode_t mode,
3823 Error &error)
3824{
Chaoren Lind3173f32015-05-29 19:52:29 +00003825 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003826 lldb_private::StreamString stream;
3827 stream.PutCString("vFile:open:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003828 if (path.empty())
3829 return UINT64_MAX;
3830 stream.PutCStringAsRawHex8(path.c_str());
3831 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003832 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003833 stream.PutChar(',');
3834 stream.PutHex32(mode);
3835 const char* packet = stream.GetData();
3836 int packet_len = stream.GetSize();
3837 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003838 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003839 {
3840 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3841 }
3842 return UINT64_MAX;
3843}
3844
3845bool
3846GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3847 Error &error)
3848{
3849 lldb_private::StreamString stream;
3850 stream.Printf("vFile:close:%i", (int)fd);
3851 const char* packet = stream.GetData();
3852 int packet_len = stream.GetSize();
3853 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003854 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003855 {
3856 return ParseHostIOPacketResponse (response, -1, error) == 0;
3857 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003858 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003859}
3860
3861// Extension of host I/O packets to get the file size.
3862lldb::user_id_t
3863GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3864{
Chaoren Lind3173f32015-05-29 19:52:29 +00003865 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003866 lldb_private::StreamString stream;
3867 stream.PutCString("vFile:size:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003868 stream.PutCStringAsRawHex8(path.c_str());
3869 const char* packet = stream.GetData();
3870 int packet_len = stream.GetSize();
3871 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003872 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003873 {
3874 if (response.GetChar() != 'F')
3875 return UINT64_MAX;
3876 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3877 return retcode;
3878 }
3879 return UINT64_MAX;
3880}
3881
Greg Claytonfbb76342013-11-20 21:07:01 +00003882Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003883GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3884 uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003885{
Chaoren Lind3173f32015-05-29 19:52:29 +00003886 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003887 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003888 lldb_private::StreamString stream;
3889 stream.PutCString("vFile:mode:");
Chaoren Lind3173f32015-05-29 19:52:29 +00003890 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003891 const char* packet = stream.GetData();
3892 int packet_len = stream.GetSize();
3893 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003894 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003895 {
3896 if (response.GetChar() != 'F')
3897 {
3898 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003899 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003900 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003901 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003902 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003903 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003904 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003905 if (response.GetChar() == ',')
3906 {
3907 int response_errno = response.GetS32(-1);
3908 if (response_errno > 0)
3909 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3910 else
3911 error.SetErrorToGenericError();
3912 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003913 else
3914 error.SetErrorToGenericError();
3915 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003916 else
3917 {
3918 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3919 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003920 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003921 }
3922 else
3923 {
3924 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3925 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003926 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003927}
3928
3929uint64_t
3930GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3931 uint64_t offset,
3932 void *dst,
3933 uint64_t dst_len,
3934 Error &error)
3935{
3936 lldb_private::StreamString stream;
3937 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3938 const char* packet = stream.GetData();
3939 int packet_len = stream.GetSize();
3940 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003941 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003942 {
3943 if (response.GetChar() != 'F')
3944 return 0;
3945 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3946 if (retcode == UINT32_MAX)
3947 return retcode;
3948 const char next = (response.Peek() ? *response.Peek() : 0);
3949 if (next == ',')
3950 return 0;
3951 if (next == ';')
3952 {
3953 response.GetChar(); // skip the semicolon
3954 std::string buffer;
3955 if (response.GetEscapedBinaryData(buffer))
3956 {
3957 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3958 if (data_to_write > 0)
3959 memcpy(dst, &buffer[0], data_to_write);
3960 return data_to_write;
3961 }
3962 }
3963 }
3964 return 0;
3965}
3966
3967uint64_t
3968GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3969 uint64_t offset,
3970 const void* src,
3971 uint64_t src_len,
3972 Error &error)
3973{
3974 lldb_private::StreamGDBRemote stream;
3975 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3976 stream.PutEscapedBytes(src, src_len);
3977 const char* packet = stream.GetData();
3978 int packet_len = stream.GetSize();
3979 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003980 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003981 {
3982 if (response.GetChar() != 'F')
3983 {
3984 error.SetErrorStringWithFormat("write file failed");
3985 return 0;
3986 }
3987 uint64_t bytes_written = response.GetU64(UINT64_MAX);
3988 if (bytes_written == UINT64_MAX)
3989 {
3990 error.SetErrorToGenericError();
3991 if (response.GetChar() == ',')
3992 {
3993 int response_errno = response.GetS32(-1);
3994 if (response_errno > 0)
3995 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3996 }
3997 return 0;
3998 }
3999 return bytes_written;
4000 }
4001 else
4002 {
4003 error.SetErrorString ("failed to send vFile:pwrite packet");
4004 }
4005 return 0;
4006}
4007
Greg Claytonfbb76342013-11-20 21:07:01 +00004008Error
Chaoren Lind3173f32015-05-29 19:52:29 +00004009GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
Greg Claytonfbb76342013-11-20 21:07:01 +00004010{
Chaoren Lind3173f32015-05-29 19:52:29 +00004011 std::string src_path{src.GetPath(false)},
4012 dst_path{dst.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00004013 Error error;
4014 lldb_private::StreamGDBRemote stream;
4015 stream.PutCString("vFile:symlink:");
4016 // the unix symlink() command reverses its parameters where the dst if first,
4017 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00004018 stream.PutCStringAsRawHex8(dst_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00004019 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00004020 stream.PutCStringAsRawHex8(src_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00004021 const char* packet = stream.GetData();
4022 int packet_len = stream.GetSize();
4023 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004024 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00004025 {
4026 if (response.GetChar() == 'F')
4027 {
4028 uint32_t result = response.GetU32(UINT32_MAX);
4029 if (result != 0)
4030 {
4031 error.SetErrorToGenericError();
4032 if (response.GetChar() == ',')
4033 {
4034 int response_errno = response.GetS32(-1);
4035 if (response_errno > 0)
4036 error.SetError(response_errno, lldb::eErrorTypePOSIX);
4037 }
4038 }
4039 }
4040 else
4041 {
4042 // Should have returned with 'F<result>[,<errno>]'
4043 error.SetErrorStringWithFormat("symlink failed");
4044 }
4045 }
4046 else
4047 {
4048 error.SetErrorString ("failed to send vFile:symlink packet");
4049 }
4050 return error;
4051}
4052
4053Error
Chaoren Lind3173f32015-05-29 19:52:29 +00004054GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
Greg Claytonfbb76342013-11-20 21:07:01 +00004055{
Chaoren Lind3173f32015-05-29 19:52:29 +00004056 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00004057 Error error;
4058 lldb_private::StreamGDBRemote stream;
4059 stream.PutCString("vFile:unlink:");
4060 // the unix symlink() command reverses its parameters where the dst if first,
4061 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00004062 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00004063 const char* packet = stream.GetData();
4064 int packet_len = stream.GetSize();
4065 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004066 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00004067 {
4068 if (response.GetChar() == 'F')
4069 {
4070 uint32_t result = response.GetU32(UINT32_MAX);
4071 if (result != 0)
4072 {
4073 error.SetErrorToGenericError();
4074 if (response.GetChar() == ',')
4075 {
4076 int response_errno = response.GetS32(-1);
4077 if (response_errno > 0)
4078 error.SetError(response_errno, lldb::eErrorTypePOSIX);
4079 }
4080 }
4081 }
4082 else
4083 {
4084 // Should have returned with 'F<result>[,<errno>]'
4085 error.SetErrorStringWithFormat("unlink failed");
4086 }
4087 }
4088 else
4089 {
4090 error.SetErrorString ("failed to send vFile:unlink packet");
4091 }
4092 return error;
4093}
4094
Daniel Maleae0f8f572013-08-26 23:57:52 +00004095// Extension of host I/O packets to get whether a file exists.
4096bool
4097GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
4098{
Chaoren Lind3173f32015-05-29 19:52:29 +00004099 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00004100 lldb_private::StreamString stream;
4101 stream.PutCString("vFile:exists:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00004102 stream.PutCStringAsRawHex8(path.c_str());
4103 const char* packet = stream.GetData();
4104 int packet_len = stream.GetSize();
4105 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004106 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00004107 {
4108 if (response.GetChar() != 'F')
4109 return false;
4110 if (response.GetChar() != ',')
4111 return false;
4112 bool retcode = (response.GetChar() != '0');
4113 return retcode;
4114 }
4115 return false;
4116}
4117
4118bool
4119GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
4120 uint64_t &high,
4121 uint64_t &low)
4122{
Chaoren Lind3173f32015-05-29 19:52:29 +00004123 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00004124 lldb_private::StreamString stream;
4125 stream.PutCString("vFile:MD5:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00004126 stream.PutCStringAsRawHex8(path.c_str());
4127 const char* packet = stream.GetData();
4128 int packet_len = stream.GetSize();
4129 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004130 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00004131 {
4132 if (response.GetChar() != 'F')
4133 return false;
4134 if (response.GetChar() != ',')
4135 return false;
4136 if (response.Peek() && *response.Peek() == 'x')
4137 return false;
4138 low = response.GetHexMaxU64(false, UINT64_MAX);
4139 high = response.GetHexMaxU64(false, UINT64_MAX);
4140 return true;
4141 }
4142 return false;
4143}
Greg Claytonf74cf862013-11-13 23:28:31 +00004144
4145bool
Jason Molendaa3329782014-03-29 18:54:20 +00004146GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
4147{
4148 // Some targets have issues with g/G packets and we need to avoid using them
4149 if (m_avoid_g_packets == eLazyBoolCalculate)
4150 {
4151 if (process)
4152 {
4153 m_avoid_g_packets = eLazyBoolNo;
4154 const ArchSpec &arch = process->GetTarget().GetArchitecture();
4155 if (arch.IsValid()
4156 && arch.GetTriple().getVendor() == llvm::Triple::Apple
4157 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00004158 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00004159 {
4160 m_avoid_g_packets = eLazyBoolYes;
4161 uint32_t gdb_server_version = GetGDBServerProgramVersion();
4162 if (gdb_server_version != 0)
4163 {
4164 const char *gdb_server_name = GetGDBServerProgramName();
4165 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
4166 {
4167 if (gdb_server_version >= 310)
4168 m_avoid_g_packets = eLazyBoolNo;
4169 }
4170 }
4171 }
4172 }
4173 }
4174 return m_avoid_g_packets == eLazyBoolYes;
4175}
4176
4177bool
Greg Claytonf74cf862013-11-13 23:28:31 +00004178GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
4179{
4180 Mutex::Locker locker;
4181 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
4182 {
4183 const bool thread_suffix_supported = GetThreadSuffixSupported();
4184
4185 if (thread_suffix_supported || SetCurrentThread(tid))
4186 {
4187 char packet[64];
4188 int packet_len = 0;
4189 if (thread_suffix_supported)
4190 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
4191 else
4192 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
4193 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004194 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004195 }
4196 }
4197 return false;
4198
4199}
4200
4201
4202bool
4203GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
4204{
4205 Mutex::Locker locker;
4206 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
4207 {
4208 const bool thread_suffix_supported = GetThreadSuffixSupported();
4209
4210 if (thread_suffix_supported || SetCurrentThread(tid))
4211 {
4212 char packet[64];
4213 int packet_len = 0;
4214 // Get all registers in one packet
4215 if (thread_suffix_supported)
4216 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
4217 else
4218 packet_len = ::snprintf (packet, sizeof(packet), "g");
4219 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004220 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004221 }
4222 }
4223 return false;
4224}
4225bool
4226GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
4227{
4228 save_id = 0; // Set to invalid save ID
4229 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4230 return false;
4231
4232 m_supports_QSaveRegisterState = eLazyBoolYes;
4233 Mutex::Locker locker;
4234 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
4235 {
4236 const bool thread_suffix_supported = GetThreadSuffixSupported();
4237 if (thread_suffix_supported || SetCurrentThread(tid))
4238 {
4239 char packet[256];
4240 if (thread_suffix_supported)
4241 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
4242 else
Ilia K686b1fe2015-02-27 19:43:08 +00004243 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
Greg Claytonf74cf862013-11-13 23:28:31 +00004244
4245 StringExtractorGDBRemote response;
4246
Greg Clayton3dedae12013-12-06 21:45:27 +00004247 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004248 {
4249 if (response.IsUnsupportedResponse())
4250 {
4251 // This packet isn't supported, don't try calling it again
4252 m_supports_QSaveRegisterState = eLazyBoolNo;
4253 }
4254
4255 const uint32_t response_save_id = response.GetU32(0);
4256 if (response_save_id != 0)
4257 {
4258 save_id = response_save_id;
4259 return true;
4260 }
4261 }
4262 }
4263 }
4264 return false;
4265}
4266
4267bool
4268GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
4269{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004270 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00004271 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
4272 // order to be useful
4273 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4274 return false;
4275
4276 Mutex::Locker locker;
4277 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
4278 {
4279 const bool thread_suffix_supported = GetThreadSuffixSupported();
4280 if (thread_suffix_supported || SetCurrentThread(tid))
4281 {
4282 char packet[256];
4283 if (thread_suffix_supported)
4284 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
4285 else
4286 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
4287
4288 StringExtractorGDBRemote response;
4289
Greg Clayton3dedae12013-12-06 21:45:27 +00004290 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004291 {
4292 if (response.IsOKResponse())
4293 {
4294 return true;
4295 }
4296 else if (response.IsUnsupportedResponse())
4297 {
4298 // This packet isn't supported, don't try calling this packet or
4299 // QSaveRegisterState again...
4300 m_supports_QSaveRegisterState = eLazyBoolNo;
4301 }
4302 }
4303 }
4304 }
4305 return false;
4306}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004307
4308bool
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004309GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004310 const lldb_private::ArchSpec& arch_spec,
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004311 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004312{
Stephane Sezer6f455292016-01-08 00:00:17 +00004313 if (!m_supports_qModuleInfo)
4314 return false;
4315
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00004316 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004317 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004318 return false;
4319
4320 StreamString packet;
4321 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004322 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004323 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00004324 const auto& triple = arch_spec.GetTriple().getTriple();
Chaoren Lind3173f32015-05-29 19:52:29 +00004325 packet.PutCStringAsRawHex8(triple.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004326
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004327 StringExtractorGDBRemote response;
4328 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
4329 return false;
4330
Stephane Sezer6f455292016-01-08 00:00:17 +00004331 if (response.IsErrorResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004332 return false;
4333
Stephane Sezer6f455292016-01-08 00:00:17 +00004334 if (response.IsUnsupportedResponse ())
4335 {
4336 m_supports_qModuleInfo = false;
4337 return false;
4338 }
4339
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004340 std::string name;
4341 std::string value;
4342 bool success;
4343 StringExtractor extractor;
4344
4345 module_spec.Clear ();
4346 module_spec.GetFileSpec () = module_file_spec;
4347
4348 while (response.GetNameColonValue (name, value))
4349 {
4350 if (name == "uuid" || name == "md5")
4351 {
4352 extractor.GetStringRef ().swap (value);
4353 extractor.SetFilePos (0);
4354 extractor.GetHexByteString (value);
4355 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
4356 }
4357 else if (name == "triple")
4358 {
4359 extractor.GetStringRef ().swap (value);
4360 extractor.SetFilePos (0);
4361 extractor.GetHexByteString (value);
4362 module_spec.GetArchitecture().SetTriple (value.c_str ());
4363 }
4364 else if (name == "file_offset")
4365 {
4366 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4367 if (success)
4368 module_spec.SetObjectOffset (ival);
4369 }
4370 else if (name == "file_size")
4371 {
4372 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4373 if (success)
4374 module_spec.SetObjectSize (ival);
4375 }
4376 else if (name == "file_path")
4377 {
4378 extractor.GetStringRef ().swap (value);
4379 extractor.SetFilePos (0);
4380 extractor.GetHexByteString (value);
Chaoren Linf34f4102015-05-09 01:21:32 +00004381 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004382 }
4383 }
4384
4385 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004386}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004387
4388// query the target remote for extended information using the qXfer packet
4389//
4390// example: object='features', annex='target.xml', out=<xml output>
4391// return: 'true' on success
4392// 'false' on failure (err set)
4393bool
4394GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
4395 const lldb_private::ConstString annex,
4396 std::string & out,
4397 lldb_private::Error & err) {
4398
4399 std::stringstream output;
4400 StringExtractorGDBRemote chunk;
4401
Greg Claytond04f0ed2015-05-26 18:00:51 +00004402 uint64_t size = GetRemoteMaxPacketSize();
4403 if (size == 0)
4404 size = 0x1000;
4405 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4406 int offset = 0;
4407 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004408
4409 // loop until all data has been read
4410 while ( active ) {
4411
4412 // send query extended feature packet
4413 std::stringstream packet;
4414 packet << "qXfer:"
Ewan Crawford682e8422015-06-26 09:38:27 +00004415 << object.AsCString("") << ":read:"
4416 << annex.AsCString("") << ":"
Colin Rileyc3c95b22015-04-16 15:51:33 +00004417 << std::hex << offset << ","
4418 << std::hex << size;
4419
4420 GDBRemoteCommunication::PacketResult res =
4421 SendPacketAndWaitForResponse( packet.str().c_str(),
4422 chunk,
4423 false );
4424
4425 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
4426 err.SetErrorString( "Error sending $qXfer packet" );
4427 return false;
4428 }
4429
4430 const std::string & str = chunk.GetStringRef( );
4431 if ( str.length() == 0 ) {
4432 // should have some data in chunk
4433 err.SetErrorString( "Empty response from $qXfer packet" );
4434 return false;
4435 }
4436
4437 // check packet code
4438 switch ( str[0] ) {
4439 // last chunk
4440 case ( 'l' ):
4441 active = false;
Jason Molenda62e06812016-02-16 04:14:33 +00004442 LLVM_FALLTHROUGH;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004443
4444 // more chunks
4445 case ( 'm' ) :
4446 if ( str.length() > 1 )
4447 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00004448 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004449 break;
4450
4451 // unknown chunk
4452 default:
4453 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
4454 return false;
4455 }
4456 }
4457
4458 out = output.str( );
4459 err.Success( );
4460 return true;
4461}
Greg Clayton0b90be12015-06-23 21:27:50 +00004462
4463// Notify the target that gdb is prepared to serve symbol lookup requests.
4464// packet: "qSymbol::"
4465// reply:
4466// OK The target does not need to look up any (more) symbols.
4467// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded).
4468// LLDB may provide the value by sending another qSymbol packet
4469// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00004470//
4471// Three examples:
4472//
4473// lldb sends: qSymbol::
4474// lldb receives: OK
4475// Remote gdb stub does not need to know the addresses of any symbols, lldb does not
4476// need to ask again in this session.
4477//
4478// lldb sends: qSymbol::
4479// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4480// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
4481// lldb receives: OK
4482// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does not know
4483// the address at this time. lldb needs to send qSymbol:: again when it has more
4484// solibs loaded.
4485//
4486// lldb sends: qSymbol::
4487// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4488// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
4489// lldb receives: OK
4490// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says that it
4491// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it does not
4492// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00004493
4494void
4495GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
4496{
Jason Molenda50018d32016-01-13 04:08:10 +00004497 // Set to true once we've resolved a symbol to an address for the remote stub.
4498 // If we get an 'OK' response after this, the remote stub doesn't need any more
4499 // symbols and we can stop asking.
4500 bool symbol_response_provided = false;
4501
Ed Maste75500e72016-07-19 15:28:02 +00004502 // Is this the initial qSymbol:: packet?
Jason Molenda50018d32016-01-13 04:08:10 +00004503 bool first_qsymbol_query = true;
4504
4505 if (m_supports_qSymbol && m_qSymbol_requests_done == false)
Greg Clayton0b90be12015-06-23 21:27:50 +00004506 {
4507 Mutex::Locker locker;
4508 if (GetSequenceMutex(locker, "GDBRemoteCommunicationClient::ServeSymbolLookups() failed due to not getting the sequence mutex"))
4509 {
4510 StreamString packet;
4511 packet.PutCString ("qSymbol::");
Greg Clayton42b01482015-08-11 22:07:46 +00004512 StringExtractorGDBRemote response;
4513 while (SendPacketAndWaitForResponseNoLock(packet.GetData(), packet.GetSize(), response) == PacketResult::Success)
Greg Clayton0b90be12015-06-23 21:27:50 +00004514 {
Greg Clayton42b01482015-08-11 22:07:46 +00004515 if (response.IsOKResponse())
Greg Clayton0b90be12015-06-23 21:27:50 +00004516 {
Jason Molenda50018d32016-01-13 04:08:10 +00004517 if (symbol_response_provided || first_qsymbol_query)
4518 {
4519 m_qSymbol_requests_done = true;
4520 }
4521
Greg Clayton42b01482015-08-11 22:07:46 +00004522 // We are done serving symbols requests
4523 return;
4524 }
Jason Molenda50018d32016-01-13 04:08:10 +00004525 first_qsymbol_query = false;
Greg Clayton0b90be12015-06-23 21:27:50 +00004526
Greg Clayton42b01482015-08-11 22:07:46 +00004527 if (response.IsUnsupportedResponse())
4528 {
4529 // qSymbol is not supported by the current GDB server we are connected to
4530 m_supports_qSymbol = false;
4531 return;
4532 }
4533 else
4534 {
4535 llvm::StringRef response_str(response.GetStringRef());
4536 if (response_str.startswith("qSymbol:"))
Greg Clayton0b90be12015-06-23 21:27:50 +00004537 {
Greg Clayton42b01482015-08-11 22:07:46 +00004538 response.SetFilePos(strlen("qSymbol:"));
4539 std::string symbol_name;
4540 if (response.GetHexByteString(symbol_name))
Greg Clayton0b90be12015-06-23 21:27:50 +00004541 {
Greg Clayton42b01482015-08-11 22:07:46 +00004542 if (symbol_name.empty())
4543 return;
4544
4545 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4546 lldb_private::SymbolContextList sc_list;
4547 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
Greg Clayton0b90be12015-06-23 21:27:50 +00004548 {
Greg Clayton42b01482015-08-11 22:07:46 +00004549 const size_t num_scs = sc_list.GetSize();
4550 for (size_t sc_idx=0; sc_idx<num_scs && symbol_load_addr == LLDB_INVALID_ADDRESS; ++sc_idx)
Greg Clayton0b90be12015-06-23 21:27:50 +00004551 {
Greg Clayton42b01482015-08-11 22:07:46 +00004552 SymbolContext sc;
4553 if (sc_list.GetContextAtIndex(sc_idx, sc))
Greg Clayton0b90be12015-06-23 21:27:50 +00004554 {
Greg Clayton42b01482015-08-11 22:07:46 +00004555 if (sc.symbol)
Greg Clayton358cf1e2015-06-25 21:46:34 +00004556 {
Greg Clayton42b01482015-08-11 22:07:46 +00004557 switch (sc.symbol->GetType())
Greg Clayton358cf1e2015-06-25 21:46:34 +00004558 {
Greg Clayton42b01482015-08-11 22:07:46 +00004559 case eSymbolTypeInvalid:
4560 case eSymbolTypeAbsolute:
4561 case eSymbolTypeUndefined:
4562 case eSymbolTypeSourceFile:
4563 case eSymbolTypeHeaderFile:
4564 case eSymbolTypeObjectFile:
4565 case eSymbolTypeCommonBlock:
4566 case eSymbolTypeBlock:
4567 case eSymbolTypeLocal:
4568 case eSymbolTypeParam:
4569 case eSymbolTypeVariable:
4570 case eSymbolTypeVariableType:
4571 case eSymbolTypeLineEntry:
4572 case eSymbolTypeLineHeader:
4573 case eSymbolTypeScopeBegin:
4574 case eSymbolTypeScopeEnd:
4575 case eSymbolTypeAdditional:
4576 case eSymbolTypeCompiler:
4577 case eSymbolTypeInstrumentation:
4578 case eSymbolTypeTrampoline:
4579 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00004580
Greg Clayton42b01482015-08-11 22:07:46 +00004581 case eSymbolTypeCode:
4582 case eSymbolTypeResolver:
4583 case eSymbolTypeData:
4584 case eSymbolTypeRuntime:
4585 case eSymbolTypeException:
4586 case eSymbolTypeObjCClass:
4587 case eSymbolTypeObjCMetaClass:
4588 case eSymbolTypeObjCIVar:
4589 case eSymbolTypeReExported:
4590 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
4591 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00004592 }
4593 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004594 }
4595 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004596 }
Greg Clayton42b01482015-08-11 22:07:46 +00004597 // This is the normal path where our symbol lookup was successful and we want
4598 // to send a packet with the new symbol value and see if another lookup needs to be
4599 // done.
4600
4601 // Change "packet" to contain the requested symbol value and name
4602 packet.Clear();
4603 packet.PutCString("qSymbol:");
4604 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
Jason Molenda50018d32016-01-13 04:08:10 +00004605 {
Greg Clayton42b01482015-08-11 22:07:46 +00004606 packet.Printf("%" PRIx64, symbol_load_addr);
Jason Molenda50018d32016-01-13 04:08:10 +00004607 symbol_response_provided = true;
4608 }
4609 else
4610 {
4611 symbol_response_provided = false;
4612 }
Greg Clayton42b01482015-08-11 22:07:46 +00004613 packet.PutCString(":");
4614 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4615 continue; // go back to the while loop and send "packet" and wait for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00004616 }
4617 }
4618 }
4619 }
4620 // If we make it here, the symbol request packet response wasn't valid or
4621 // our symbol lookup failed so we must abort
4622 return;
4623
4624 }
4625 }
4626}
4627