blob: ac76889079a629c6f96e9cae1bc3fef524ea07cb [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),
Jason Molenda37397352016-07-22 00:17:55 +000091 m_supports_jGetSharedCacheInfo (eLazyBoolCalculate),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000092 m_supports_qProcessInfoPID(true),
93 m_supports_qfProcessInfo(true),
94 m_supports_qUserName(true),
95 m_supports_qGroupName(true),
96 m_supports_qThreadStopInfo(true),
97 m_supports_z0(true),
98 m_supports_z1(true),
99 m_supports_z2(true),
100 m_supports_z3(true),
101 m_supports_z4(true),
102 m_supports_QEnvironment(true),
103 m_supports_QEnvironmentHexEncoded(true),
104 m_supports_qSymbol(true),
105 m_qSymbol_requests_done(false),
106 m_supports_qModuleInfo(true),
107 m_supports_jThreadsInfo(true),
108 m_curr_pid(LLDB_INVALID_PROCESS_ID),
109 m_curr_tid(LLDB_INVALID_THREAD_ID),
110 m_curr_tid_run(LLDB_INVALID_THREAD_ID),
111 m_num_supported_hardware_watchpoints(0),
112 m_async_mutex(),
113 m_async_packet_predicate(false),
114 m_async_packet(),
115 m_async_result(PacketResult::Success),
116 m_async_response(),
117 m_async_signal(-1),
118 m_interrupt_sent(false),
119 m_thread_id_to_used_usec_map(),
120 m_host_arch(),
121 m_process_arch(),
122 m_os_version_major(UINT32_MAX),
123 m_os_version_minor(UINT32_MAX),
124 m_os_version_update(UINT32_MAX),
125 m_os_build(),
126 m_os_kernel(),
127 m_hostname(),
128 m_gdb_server_name(),
129 m_gdb_server_version(UINT32_MAX),
130 m_default_packet_timeout(0),
131 m_max_packet_size(0)
Greg Clayton576d8832011-03-22 04:00:09 +0000132{
Greg Clayton576d8832011-03-22 04:00:09 +0000133}
134
135//----------------------------------------------------------------------
136// Destructor
137//----------------------------------------------------------------------
138GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
139{
Greg Clayton576d8832011-03-22 04:00:09 +0000140 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000141 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000142}
143
144bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000145GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
146{
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000147 ResetDiscoverableSettings(false);
Greg Claytonfb909312013-11-23 01:58:15 +0000148
Greg Clayton1cb64962011-03-24 04:28:38 +0000149 // Start the read thread after we send the handshake ack since if we
150 // fail to send the handshake ack, there is no reason to continue...
151 if (SendAck())
Greg Claytonfb909312013-11-23 01:58:15 +0000152 {
Ed Maste48f986f2013-12-18 15:31:45 +0000153 // Wait for any responses that might have been queued up in the remote
154 // GDB server and flush them all
155 StringExtractorGDBRemote response;
156 PacketResult packet_result = PacketResult::Success;
157 const uint32_t timeout_usec = 10 * 1000; // Wait for 10 ms for a response
158 while (packet_result == PacketResult::Success)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000159 packet_result = ReadPacket (response, timeout_usec, false);
Ed Maste48f986f2013-12-18 15:31:45 +0000160
Greg Claytonfb909312013-11-23 01:58:15 +0000161 // The return value from QueryNoAckModeSupported() is true if the packet
162 // was sent and _any_ response (including UNIMPLEMENTED) was received),
163 // or false if no response was received. This quickly tells us if we have
164 // a live connection to a remote GDB server...
165 if (QueryNoAckModeSupported())
166 {
167 return true;
168 }
169 else
170 {
171 if (error_ptr)
172 error_ptr->SetErrorString("failed to get reply to handshake packet");
173 }
174 }
175 else
176 {
177 if (error_ptr)
178 error_ptr->SetErrorString("failed to send the handshake ack");
179 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000180 return false;
181}
182
Greg Claytonfb909312013-11-23 01:58:15 +0000183bool
Greg Claytonb30c50c2015-05-29 00:01:55 +0000184GDBRemoteCommunicationClient::GetEchoSupported ()
185{
186 if (m_supports_qEcho == eLazyBoolCalculate)
187 {
188 GetRemoteQSupported();
189 }
190 return m_supports_qEcho == eLazyBoolYes;
191}
192
193
194bool
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000195GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported ()
196{
197 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate)
198 {
199 GetRemoteQSupported();
200 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000201 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000202}
203
204bool
205GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported ()
206{
207 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate)
208 {
209 GetRemoteQSupported();
210 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000211 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000212}
213
214bool
215GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported ()
216{
217 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate)
218 {
219 GetRemoteQSupported();
220 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000221 return m_supports_qXfer_libraries_read == eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000222}
223
Steve Pucci03904ac2014-03-04 23:18:46 +0000224bool
225GDBRemoteCommunicationClient::GetQXferAuxvReadSupported ()
226{
227 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate)
228 {
229 GetRemoteQSupported();
230 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000231 return m_supports_qXfer_auxv_read == eLazyBoolYes;
Steve Pucci03904ac2014-03-04 23:18:46 +0000232}
233
Colin Rileyc3c95b22015-04-16 15:51:33 +0000234bool
235GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported ()
236{
237 if (m_supports_qXfer_features_read == eLazyBoolCalculate)
238 {
239 GetRemoteQSupported();
240 }
Greg Claytonb30c50c2015-05-29 00:01:55 +0000241 return m_supports_qXfer_features_read == eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000242}
243
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000244uint64_t
245GDBRemoteCommunicationClient::GetRemoteMaxPacketSize()
246{
247 if (m_max_packet_size == 0)
248 {
249 GetRemoteQSupported();
250 }
251 return m_max_packet_size;
252}
253
254bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000255GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000256{
257 if (m_supports_not_sending_acks == eLazyBoolCalculate)
258 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000259 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000260 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000261
Jason Molenda36a216e2014-07-24 01:36:24 +0000262 // This is the first real packet that we'll send in a debug session and it may take a little
263 // longer than normal to receive a reply. Wait at least 6 seconds for a reply to this packet.
264
265 const uint32_t minimum_timeout = 6;
266 uint32_t old_timeout = GetPacketTimeoutInMicroSeconds() / lldb_private::TimeValue::MicroSecPerSec;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000267 GDBRemoteCommunication::ScopedTimeout timeout (*this, std::max (old_timeout, minimum_timeout));
Jason Molenda36a216e2014-07-24 01:36:24 +0000268
Greg Clayton1cb64962011-03-24 04:28:38 +0000269 StringExtractorGDBRemote response;
Tamas Berghammer912800c2015-02-24 10:23:39 +0000270 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000271 {
272 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000273 {
274 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000275 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000276 }
Greg Claytonfb909312013-11-23 01:58:15 +0000277 return true;
Greg Clayton576d8832011-03-22 04:00:09 +0000278 }
279 }
Greg Claytonfb909312013-11-23 01:58:15 +0000280 return false;
Greg Clayton576d8832011-03-22 04:00:09 +0000281}
282
283void
Greg Clayton44633992012-04-10 03:22:03 +0000284GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
285{
286 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
287 {
288 m_supports_threads_in_stop_reply = eLazyBoolNo;
289
290 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000291 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false) == PacketResult::Success)
Greg Clayton44633992012-04-10 03:22:03 +0000292 {
293 if (response.IsOKResponse())
294 m_supports_threads_in_stop_reply = eLazyBoolYes;
295 }
296 }
297}
298
Jim Inghamcd16df92012-07-20 21:37:13 +0000299bool
300GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
301{
302 if (m_attach_or_wait_reply == eLazyBoolCalculate)
303 {
304 m_attach_or_wait_reply = eLazyBoolNo;
305
306 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000307 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false) == PacketResult::Success)
Jim Inghamcd16df92012-07-20 21:37:13 +0000308 {
309 if (response.IsOKResponse())
310 m_attach_or_wait_reply = eLazyBoolYes;
311 }
312 }
313 if (m_attach_or_wait_reply == eLazyBoolYes)
314 return true;
315 else
316 return false;
317}
318
Jim Ingham279ceec2012-07-25 21:12:43 +0000319bool
320GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
321{
322 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
323 {
324 m_prepare_for_reg_writing_reply = eLazyBoolNo;
325
326 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +0000327 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false) == PacketResult::Success)
Jim Ingham279ceec2012-07-25 21:12:43 +0000328 {
329 if (response.IsOKResponse())
330 m_prepare_for_reg_writing_reply = eLazyBoolYes;
331 }
332 }
333 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
334 return true;
335 else
336 return false;
337}
338
Greg Clayton44633992012-04-10 03:22:03 +0000339
340void
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000341GDBRemoteCommunicationClient::ResetDiscoverableSettings (bool did_exec)
Greg Clayton576d8832011-03-22 04:00:09 +0000342{
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000343 if (did_exec == false)
344 {
345 // Hard reset everything, this is when we first connect to a GDB server
346 m_supports_not_sending_acks = eLazyBoolCalculate;
347 m_supports_thread_suffix = eLazyBoolCalculate;
348 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
349 m_supports_vCont_c = eLazyBoolCalculate;
350 m_supports_vCont_C = eLazyBoolCalculate;
351 m_supports_vCont_s = eLazyBoolCalculate;
352 m_supports_vCont_S = eLazyBoolCalculate;
353 m_supports_p = eLazyBoolCalculate;
354 m_supports_x = eLazyBoolCalculate;
355 m_supports_QSaveRegisterState = eLazyBoolCalculate;
356 m_qHostInfo_is_valid = eLazyBoolCalculate;
357 m_curr_pid_is_valid = eLazyBoolCalculate;
358 m_qGDBServerVersion_is_valid = eLazyBoolCalculate;
359 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
360 m_supports_memory_region_info = eLazyBoolCalculate;
361 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
362 m_attach_or_wait_reply = eLazyBoolCalculate;
363 m_avoid_g_packets = eLazyBoolCalculate;
364 m_supports_qXfer_auxv_read = eLazyBoolCalculate;
365 m_supports_qXfer_libraries_read = eLazyBoolCalculate;
366 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate;
367 m_supports_qXfer_features_read = eLazyBoolCalculate;
368 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate;
369 m_supports_qProcessInfoPID = true;
370 m_supports_qfProcessInfo = true;
371 m_supports_qUserName = true;
372 m_supports_qGroupName = true;
373 m_supports_qThreadStopInfo = true;
374 m_supports_z0 = true;
375 m_supports_z1 = true;
376 m_supports_z2 = true;
377 m_supports_z3 = true;
378 m_supports_z4 = true;
379 m_supports_QEnvironment = true;
380 m_supports_QEnvironmentHexEncoded = true;
381 m_supports_qSymbol = true;
Jason Molenda50018d32016-01-13 04:08:10 +0000382 m_qSymbol_requests_done = false;
Stephane Sezer6f455292016-01-08 00:00:17 +0000383 m_supports_qModuleInfo = true;
Greg Clayton2e59d4f2015-06-29 20:08:51 +0000384 m_host_arch.Clear();
385 m_os_version_major = UINT32_MAX;
386 m_os_version_minor = UINT32_MAX;
387 m_os_version_update = UINT32_MAX;
388 m_os_build.clear();
389 m_os_kernel.clear();
390 m_hostname.clear();
391 m_gdb_server_name.clear();
392 m_gdb_server_version = UINT32_MAX;
393 m_default_packet_timeout = 0;
394 m_max_packet_size = 0;
395 }
396
397 // These flags should be reset when we first connect to a GDB server
398 // and when our inferior process execs
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000399 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000400 m_process_arch.Clear();
Greg Clayton576d8832011-03-22 04:00:09 +0000401}
402
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000403void
404GDBRemoteCommunicationClient::GetRemoteQSupported ()
405{
406 // Clear out any capabilities we expect to see in the qSupported response
Steve Pucci03904ac2014-03-04 23:18:46 +0000407 m_supports_qXfer_auxv_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000408 m_supports_qXfer_libraries_read = eLazyBoolNo;
Steve Pucci03904ac2014-03-04 23:18:46 +0000409 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000410 m_supports_augmented_libraries_svr4_read = eLazyBoolNo;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000411 m_supports_qXfer_features_read = eLazyBoolNo;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000412 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if not, we assume no limit
413
Colin Rileyc3c95b22015-04-16 15:51:33 +0000414 // build the qSupported packet
415 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips"};
416 StreamString packet;
417 packet.PutCString( "qSupported" );
418 for ( uint32_t i = 0; i < features.size( ); ++i )
419 {
420 packet.PutCString( i==0 ? ":" : ";");
421 packet.PutCString( features[i].c_str( ) );
422 }
423
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000424 StringExtractorGDBRemote response;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000425 if (SendPacketAndWaitForResponse(packet.GetData(),
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000426 response,
427 /*send_async=*/false) == PacketResult::Success)
428 {
429 const char *response_cstr = response.GetStringRef().c_str();
Steve Pucci03904ac2014-03-04 23:18:46 +0000430 if (::strstr (response_cstr, "qXfer:auxv:read+"))
431 m_supports_qXfer_auxv_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000432 if (::strstr (response_cstr, "qXfer:libraries-svr4:read+"))
433 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes;
434 if (::strstr (response_cstr, "augmented-libraries-svr4-read"))
435 {
436 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied
437 m_supports_augmented_libraries_svr4_read = eLazyBoolYes;
438 }
439 if (::strstr (response_cstr, "qXfer:libraries:read+"))
440 m_supports_qXfer_libraries_read = eLazyBoolYes;
Colin Rileyc3c95b22015-04-16 15:51:33 +0000441 if (::strstr (response_cstr, "qXfer:features:read+"))
442 m_supports_qXfer_features_read = eLazyBoolYes;
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000443
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000444
445 // Look for a list of compressions in the features list e.g.
446 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib-deflate,lzma
447 const char *features_list = ::strstr (response_cstr, "qXfer:features:");
448 if (features_list)
449 {
450 const char *compressions = ::strstr (features_list, "SupportedCompressions=");
451 if (compressions)
452 {
453 std::vector<std::string> supported_compressions;
454 compressions += sizeof ("SupportedCompressions=") - 1;
455 const char *end_of_compressions = strchr (compressions, ';');
456 if (end_of_compressions == NULL)
457 {
458 end_of_compressions = strchr (compressions, '\0');
459 }
460 const char *current_compression = compressions;
461 while (current_compression < end_of_compressions)
462 {
463 const char *next_compression_name = strchr (current_compression, ',');
464 const char *end_of_this_word = next_compression_name;
465 if (next_compression_name == NULL || end_of_compressions < next_compression_name)
466 {
467 end_of_this_word = end_of_compressions;
468 }
469
470 if (end_of_this_word)
471 {
472 if (end_of_this_word == current_compression)
473 {
474 current_compression++;
475 }
476 else
477 {
478 std::string this_compression (current_compression, end_of_this_word - current_compression);
479 supported_compressions.push_back (this_compression);
480 current_compression = end_of_this_word + 1;
481 }
482 }
483 else
484 {
485 supported_compressions.push_back (current_compression);
486 current_compression = end_of_compressions;
487 }
488 }
489
490 if (supported_compressions.size() > 0)
491 {
492 MaybeEnableCompression (supported_compressions);
493 }
494 }
495 }
496
Greg Claytonb30c50c2015-05-29 00:01:55 +0000497 if (::strstr (response_cstr, "qEcho"))
498 m_supports_qEcho = eLazyBoolYes;
499 else
500 m_supports_qEcho = eLazyBoolNo;
501
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000502 const char *packet_size_str = ::strstr (response_cstr, "PacketSize=");
503 if (packet_size_str)
504 {
505 StringExtractorGDBRemote packet_response(packet_size_str + strlen("PacketSize="));
506 m_max_packet_size = packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX);
507 if (m_max_packet_size == 0)
508 {
509 m_max_packet_size = UINT64_MAX; // Must have been a garbled response
510 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
511 if (log)
512 log->Printf ("Garbled PacketSize spec in qSupported response");
513 }
514 }
515 }
516}
Greg Clayton576d8832011-03-22 04:00:09 +0000517
518bool
519GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
520{
521 if (m_supports_thread_suffix == eLazyBoolCalculate)
522 {
523 StringExtractorGDBRemote response;
524 m_supports_thread_suffix = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000525 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000526 {
527 if (response.IsOKResponse())
528 m_supports_thread_suffix = eLazyBoolYes;
529 }
530 }
531 return m_supports_thread_suffix;
532}
533bool
534GDBRemoteCommunicationClient::GetVContSupported (char flavor)
535{
536 if (m_supports_vCont_c == eLazyBoolCalculate)
537 {
538 StringExtractorGDBRemote response;
539 m_supports_vCont_any = eLazyBoolNo;
540 m_supports_vCont_all = eLazyBoolNo;
541 m_supports_vCont_c = eLazyBoolNo;
542 m_supports_vCont_C = eLazyBoolNo;
543 m_supports_vCont_s = eLazyBoolNo;
544 m_supports_vCont_S = eLazyBoolNo;
Greg Clayton3dedae12013-12-06 21:45:27 +0000545 if (SendPacketAndWaitForResponse("vCont?", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000546 {
547 const char *response_cstr = response.GetStringRef().c_str();
548 if (::strstr (response_cstr, ";c"))
549 m_supports_vCont_c = eLazyBoolYes;
550
551 if (::strstr (response_cstr, ";C"))
552 m_supports_vCont_C = eLazyBoolYes;
553
554 if (::strstr (response_cstr, ";s"))
555 m_supports_vCont_s = eLazyBoolYes;
556
557 if (::strstr (response_cstr, ";S"))
558 m_supports_vCont_S = eLazyBoolYes;
559
560 if (m_supports_vCont_c == eLazyBoolYes &&
561 m_supports_vCont_C == eLazyBoolYes &&
562 m_supports_vCont_s == eLazyBoolYes &&
563 m_supports_vCont_S == eLazyBoolYes)
564 {
565 m_supports_vCont_all = eLazyBoolYes;
566 }
567
568 if (m_supports_vCont_c == eLazyBoolYes ||
569 m_supports_vCont_C == eLazyBoolYes ||
570 m_supports_vCont_s == eLazyBoolYes ||
571 m_supports_vCont_S == eLazyBoolYes)
572 {
573 m_supports_vCont_any = eLazyBoolYes;
574 }
575 }
576 }
577
578 switch (flavor)
579 {
580 case 'a': return m_supports_vCont_any;
581 case 'A': return m_supports_vCont_all;
582 case 'c': return m_supports_vCont_c;
583 case 'C': return m_supports_vCont_C;
584 case 's': return m_supports_vCont_s;
585 case 'S': return m_supports_vCont_S;
586 default: break;
587 }
588 return false;
589}
590
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000591// Check if the target supports 'p' packet. It sends out a 'p'
592// packet and checks the response. A normal packet will tell us
593// that support is available.
Sean Callananb1de1142013-09-04 23:24:15 +0000594//
595// Takes a valid thread ID because p needs to apply to a thread.
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000596bool
Sean Callananb1de1142013-09-04 23:24:15 +0000597GDBRemoteCommunicationClient::GetpPacketSupported (lldb::tid_t tid)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000598{
599 if (m_supports_p == eLazyBoolCalculate)
600 {
601 StringExtractorGDBRemote response;
602 m_supports_p = eLazyBoolNo;
Sean Callananb1de1142013-09-04 23:24:15 +0000603 char packet[256];
604 if (GetThreadSuffixSupported())
605 snprintf(packet, sizeof(packet), "p0;thread:%" PRIx64 ";", tid);
606 else
607 snprintf(packet, sizeof(packet), "p0");
608
Greg Clayton3dedae12013-12-06 21:45:27 +0000609 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000610 {
611 if (response.IsNormalResponse())
612 m_supports_p = eLazyBoolYes;
613 }
614 }
615 return m_supports_p;
616}
Greg Clayton576d8832011-03-22 04:00:09 +0000617
Greg Clayton358cf1e2015-06-25 21:46:34 +0000618StructuredData::ObjectSP
619GDBRemoteCommunicationClient::GetThreadsInfo()
620{
621 // Get information on all threads at one using the "jThreadsInfo" packet
622 StructuredData::ObjectSP object_sp;
623
624 if (m_supports_jThreadsInfo)
625 {
626 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +0000627 response.SetResponseValidatorToJSON();
Greg Clayton358cf1e2015-06-25 21:46:34 +0000628 if (SendPacketAndWaitForResponse("jThreadsInfo", response, false) == PacketResult::Success)
629 {
630 if (response.IsUnsupportedResponse())
631 {
632 m_supports_jThreadsInfo = false;
633 }
634 else if (!response.Empty())
635 {
636 object_sp = StructuredData::ParseJSON (response.GetStringRef());
637 }
638 }
639 }
640 return object_sp;
641}
642
643
Jason Molendabdc4f122014-05-06 02:59:39 +0000644bool
Jason Molenda705b1802014-06-13 02:37:02 +0000645GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported ()
646{
647 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate)
648 {
649 StringExtractorGDBRemote response;
650 m_supports_jThreadExtendedInfo = eLazyBoolNo;
651 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response, false) == PacketResult::Success)
652 {
653 if (response.IsOKResponse())
654 {
655 m_supports_jThreadExtendedInfo = eLazyBoolYes;
656 }
657 }
658 }
659 return m_supports_jThreadExtendedInfo;
660}
661
662bool
Jason Molenda20ee21b2015-07-10 23:15:22 +0000663GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported ()
664{
665 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate)
666 {
667 StringExtractorGDBRemote response;
668 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo;
669 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:", response, false) == PacketResult::Success)
670 {
671 if (response.IsOKResponse())
672 {
673 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes;
674 }
675 }
676 }
677 return m_supports_jLoadedDynamicLibrariesInfos;
678}
679
680bool
Jason Molenda37397352016-07-22 00:17:55 +0000681GDBRemoteCommunicationClient::GetSharedCacheInfoSupported ()
682{
683 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate)
684 {
685 StringExtractorGDBRemote response;
686 m_supports_jGetSharedCacheInfo = eLazyBoolNo;
687 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response, false) == PacketResult::Success)
688 {
689 if (response.IsOKResponse())
690 {
691 m_supports_jGetSharedCacheInfo = eLazyBoolYes;
692 }
693 }
694 }
695 return m_supports_jGetSharedCacheInfo;
696}
697
698bool
Jason Molendabdc4f122014-05-06 02:59:39 +0000699GDBRemoteCommunicationClient::GetxPacketSupported ()
700{
701 if (m_supports_x == eLazyBoolCalculate)
702 {
703 StringExtractorGDBRemote response;
704 m_supports_x = eLazyBoolNo;
705 char packet[256];
706 snprintf (packet, sizeof (packet), "x0,0");
707 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
708 {
709 if (response.IsOKResponse())
710 m_supports_x = eLazyBoolYes;
711 }
712 }
713 return m_supports_x;
714}
715
Greg Clayton3dedae12013-12-06 21:45:27 +0000716GDBRemoteCommunicationClient::PacketResult
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000717GDBRemoteCommunicationClient::SendPacketsAndConcatenateResponses
718(
719 const char *payload_prefix,
720 std::string &response_string
721)
722{
723 Mutex::Locker locker;
724 if (!GetSequenceMutex(locker,
725 "ProcessGDBRemote::SendPacketsAndConcatenateResponses() failed due to not getting the sequence mutex"))
726 {
727 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
728 if (log)
729 log->Printf("error: failed to get packet sequence mutex, not sending packets with prefix '%s'",
730 payload_prefix);
731 return PacketResult::ErrorNoSequenceLock;
732 }
733
734 response_string = "";
735 std::string payload_prefix_str(payload_prefix);
736 unsigned int response_size = 0x1000;
737 if (response_size > GetRemoteMaxPacketSize()) { // May send qSupported packet
738 response_size = GetRemoteMaxPacketSize();
739 }
740
741 for (unsigned int offset = 0; true; offset += response_size)
742 {
743 StringExtractorGDBRemote this_response;
744 // Construct payload
745 char sizeDescriptor[128];
746 snprintf(sizeDescriptor, sizeof(sizeDescriptor), "%x,%x", offset, response_size);
747 PacketResult result = SendPacketAndWaitForResponse((payload_prefix_str + sizeDescriptor).c_str(),
748 this_response,
749 /*send_async=*/false);
750 if (result != PacketResult::Success)
751 return result;
752
753 const std::string &this_string = this_response.GetStringRef();
754
755 // Check for m or l as first character; l seems to mean this is the last chunk
756 char first_char = *this_string.c_str();
757 if (first_char != 'm' && first_char != 'l')
758 {
759 return PacketResult::ErrorReplyInvalid;
760 }
Steve Pucci03904ac2014-03-04 23:18:46 +0000761 // Concatenate the result so far (skipping 'm' or 'l')
762 response_string.append(this_string, 1, std::string::npos);
Steve Pucci5ae54ae2014-01-25 05:46:51 +0000763 if (first_char == 'l')
764 // We're done
765 return PacketResult::Success;
766 }
767}
768
769GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000770GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
771(
772 const char *payload,
773 StringExtractorGDBRemote &response,
774 bool send_async
775)
776{
777 return SendPacketAndWaitForResponse (payload,
778 ::strlen (payload),
779 response,
780 send_async);
781}
782
Greg Clayton3dedae12013-12-06 21:45:27 +0000783GDBRemoteCommunicationClient::PacketResult
784GDBRemoteCommunicationClient::SendPacketAndWaitForResponseNoLock (const char *payload,
785 size_t payload_length,
786 StringExtractorGDBRemote &response)
787{
Greg Clayton830c81d2016-04-01 00:41:29 +0000788 PacketResult packet_result = SendPacketNoLock(payload, payload_length);
Greg Clayton3dedae12013-12-06 21:45:27 +0000789 if (packet_result == PacketResult::Success)
Greg Clayton830c81d2016-04-01 00:41:29 +0000790 {
791 const size_t max_response_retries = 3;
792 for (size_t i=0; i<max_response_retries; ++i)
793 {
794 packet_result = ReadPacket(response, GetPacketTimeoutInMicroSeconds (), true);
795 // Make sure we received a response
796 if (packet_result != PacketResult::Success)
797 return packet_result;
798 // Make sure our response is valid for the payload that was sent
799 if (response.ValidateResponse())
800 return packet_result;
801 // Response says it wasn't valid
802 Log *log = ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS);
803 if (log)
804 log->Printf("error: packet with payload \"%*s\" got invalid response \"%s\": %s",
805 (int)payload_length,
806 payload,
807 response.GetStringRef().c_str(),
808 (i == (max_response_retries - 1)) ? "using invalid response and giving up" : "ignoring response and waiting for another");
809 }
810 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000811 return packet_result;
812}
813
814GDBRemoteCommunicationClient::PacketResult
Greg Clayton576d8832011-03-22 04:00:09 +0000815GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
816(
817 const char *payload,
818 size_t payload_length,
819 StringExtractorGDBRemote &response,
820 bool send_async
821)
822{
Greg Clayton3dedae12013-12-06 21:45:27 +0000823 PacketResult packet_result = PacketResult::ErrorSendFailed;
Greg Clayton576d8832011-03-22 04:00:09 +0000824 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000825 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000826
827 // In order to stop async notifications from being processed in the middle of the
Bruce Mitchenere171da52015-07-22 00:16:02 +0000828 // send/receive sequence Hijack the broadcast. Then rebroadcast any events when we are done.
Jim Ingham583bbb12016-03-07 21:50:25 +0000829 static ListenerSP hijack_listener_sp(Listener::MakeListener("lldb.NotifyHijacker"));
830 HijackBroadcaster(hijack_listener_sp, eBroadcastBitGdbReadThreadGotNotify);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000831
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000832 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000833 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000834 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000835 }
836 else
837 {
838 if (send_async)
839 {
Greg Claytond3544052012-05-31 21:24:20 +0000840 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000841 {
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000842 std::lock_guard<std::recursive_mutex> guard(m_async_mutex);
Greg Claytond3544052012-05-31 21:24:20 +0000843 m_async_packet.assign(payload, payload_length);
Greg Clayton830c81d2016-04-01 00:41:29 +0000844 m_async_response.CopyResponseValidator(response);
Greg Claytond3544052012-05-31 21:24:20 +0000845 m_async_packet_predicate.SetValue (true, eBroadcastNever);
846
847 if (log)
848 log->Printf ("async: async packet = %s", m_async_packet.c_str());
849
850 bool timed_out = false;
851 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000852 {
Greg Claytond3544052012-05-31 21:24:20 +0000853 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000854 {
Jim Inghambabfc382012-06-06 00:32:39 +0000855 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000856 TimeValue timeout_time;
857 timeout_time = TimeValue::Now();
858 timeout_time.OffsetWithSeconds (m_packet_timeout);
859
Greg Clayton576d8832011-03-22 04:00:09 +0000860 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000861 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000862
Greg Claytond3544052012-05-31 21:24:20 +0000863 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000864 {
Greg Claytond3544052012-05-31 21:24:20 +0000865 if (log)
866 log->Printf ("async: got response");
867
868 // Swap the response buffer to avoid malloc and string copy
869 response.GetStringRef().swap (m_async_response.GetStringRef());
Jim Inghama6195b72013-12-18 01:24:33 +0000870 packet_result = m_async_result;
Greg Claytond3544052012-05-31 21:24:20 +0000871 }
872 else
873 {
874 if (log)
875 log->Printf ("async: timed out waiting for response");
876 }
877
878 // Make sure we wait until the continue packet has been sent again...
879 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
880 {
881 if (log)
882 {
883 if (timed_out)
884 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
885 else
886 log->Printf ("async: async packet sent");
887 }
888 }
889 else
890 {
891 if (log)
892 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000893 }
894 }
895 else
896 {
Greg Claytond3544052012-05-31 21:24:20 +0000897 // We had a racy condition where we went to send the interrupt
898 // yet we were able to get the lock, so the process must have
899 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000900 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000901 log->Printf ("async: got lock without sending interrupt");
902 // Send the packet normally since we got the lock
Greg Clayton3dedae12013-12-06 21:45:27 +0000903 packet_result = SendPacketAndWaitForResponseNoLock (payload, payload_length, response);
Greg Clayton576d8832011-03-22 04:00:09 +0000904 }
905 }
906 else
907 {
Greg Clayton644247c2011-07-07 01:59:51 +0000908 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000909 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000910 }
Greg Clayton830c81d2016-04-01 00:41:29 +0000911
912 m_async_response.SetResponseValidator(nullptr, nullptr);
913
Greg Clayton576d8832011-03-22 04:00:09 +0000914 }
915 else
916 {
917 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000918 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000919 }
920 }
921 else
922 {
923 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000924 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000925 }
926 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000927
Bruce Mitchenere171da52015-07-22 00:16:02 +0000928 // Remove our Hijacking listener from the broadcast.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000929 RestoreBroadcaster();
930
Bruce Mitchenere171da52015-07-22 00:16:02 +0000931 // If a notification event occurred, rebroadcast since it can now be processed safely.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000932 EventSP event_sp;
Jim Ingham583bbb12016-03-07 21:50:25 +0000933 if (hijack_listener_sp->GetNextEvent(event_sp))
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000934 BroadcastEvent(event_sp);
935
Greg Clayton3dedae12013-12-06 21:45:27 +0000936 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000937}
938
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000939static const char *end_delimiter = "--end--;";
940static const int end_delimiter_len = 8;
941
942std::string
943GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
944( ProcessGDBRemote *process,
945 StringExtractorGDBRemote& profileDataExtractor
946)
947{
948 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
949 std::stringstream final_output;
950 std::string name, value;
951
952 // Going to assuming thread_used_usec comes first, else bail out.
953 while (profileDataExtractor.GetNameColonValue(name, value))
954 {
955 if (name.compare("thread_used_id") == 0)
956 {
957 StringExtractor threadIDHexExtractor(value.c_str());
958 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
959
960 bool has_used_usec = false;
961 uint32_t curr_used_usec = 0;
962 std::string usec_name, usec_value;
963 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
964 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
965 {
966 if (usec_name.compare("thread_used_usec") == 0)
967 {
968 has_used_usec = true;
969 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
970 }
971 else
972 {
973 // We didn't find what we want, it is probably
974 // an older version. Bail out.
975 profileDataExtractor.SetFilePos(input_file_pos);
976 }
977 }
978
979 if (has_used_usec)
980 {
981 uint32_t prev_used_usec = 0;
982 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
983 if (iterator != m_thread_id_to_used_usec_map.end())
984 {
985 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
986 }
987
988 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
989 // A good first time record is one that runs for at least 0.25 sec
990 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
991 bool good_subsequent_time = (prev_used_usec > 0) &&
992 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
993
994 if (good_first_time || good_subsequent_time)
995 {
996 // We try to avoid doing too many index id reservation,
997 // resulting in fast increase of index ids.
998
999 final_output << name << ":";
1000 int32_t index_id = process->AssignIndexIDToThread(thread_id);
1001 final_output << index_id << ";";
1002
1003 final_output << usec_name << ":" << usec_value << ";";
1004 }
1005 else
1006 {
1007 // Skip past 'thread_used_name'.
1008 std::string local_name, local_value;
1009 profileDataExtractor.GetNameColonValue(local_name, local_value);
1010 }
1011
1012 // Store current time as previous time so that they can be compared later.
1013 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
1014 }
1015 else
1016 {
1017 // Bail out and use old string.
1018 final_output << name << ":" << value << ";";
1019 }
1020 }
1021 else
1022 {
1023 final_output << name << ":" << value << ";";
1024 }
1025 }
1026 final_output << end_delimiter;
1027 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
1028
1029 return final_output.str();
1030}
1031
Ewan Crawford76df2882015-06-23 12:32:06 +00001032bool
1033GDBRemoteCommunicationClient::SendvContPacket
1034(
1035 ProcessGDBRemote *process,
1036 const char *payload,
1037 size_t packet_length,
1038 StringExtractorGDBRemote &response
1039)
1040{
1041
1042 m_curr_tid = LLDB_INVALID_THREAD_ID;
1043 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1044 if (log)
1045 log->Printf("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
1046
1047 // we want to lock down packet sending while we continue
1048 Mutex::Locker locker(m_sequence_mutex);
1049
1050 // here we broadcast this before we even send the packet!!
1051 // this signals doContinue() to exit
1052 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1053
1054 // set the public state to running
1055 m_public_is_running.SetValue(true, eBroadcastNever);
1056
1057 // Set the starting continue packet into "continue_packet". This packet
1058 // may change if we are interrupted and we continue after an async packet...
1059 std::string continue_packet(payload, packet_length);
1060
1061 if (log)
1062 log->Printf("GDBRemoteCommunicationClient::%s () sending vCont packet: %s", __FUNCTION__, continue_packet.c_str());
1063
1064 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
1065 return false;
1066
1067 // set the private state to running and broadcast this
1068 m_private_is_running.SetValue(true, eBroadcastAlways);
1069
1070 if (log)
1071 log->Printf("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
1072
1073 // wait for the response to the vCont
1074 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
1075 {
1076 if (response.IsOKResponse())
1077 return true;
1078 }
1079
1080 return false;
1081}
1082
Greg Clayton576d8832011-03-22 04:00:09 +00001083StateType
1084GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
1085(
1086 ProcessGDBRemote *process,
1087 const char *payload,
1088 size_t packet_length,
1089 StringExtractorGDBRemote &response
1090)
1091{
Greg Clayton1f5181a2012-07-02 22:05:25 +00001092 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +00001093 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +00001094 if (log)
1095 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
1096
1097 Mutex::Locker locker(m_sequence_mutex);
1098 StateType state = eStateRunning;
1099
Greg Clayton576d8832011-03-22 04:00:09 +00001100 m_public_is_running.SetValue (true, eBroadcastNever);
1101 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +00001102 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +00001103 std::string continue_packet(payload, packet_length);
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001104
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001105 const auto sigstop_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGSTOP");
1106 const auto sigint_signo = process->GetUnixSignals()->GetSignalNumberFromName("SIGINT");
Oleksiy Vyalov755d58a2015-05-22 23:14:39 +00001107
Greg Clayton3f875c52013-02-22 22:23:55 +00001108 bool got_async_packet = false;
Pavel Labath9e131f72015-10-27 09:23:55 +00001109 bool broadcast_sent = false;
Greg Claytonaf247d72011-05-19 03:54:16 +00001110
Greg Clayton576d8832011-03-22 04:00:09 +00001111 while (state == eStateRunning)
1112 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001113 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +00001114 {
1115 if (log)
1116 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton3dedae12013-12-06 21:45:27 +00001117 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) != PacketResult::Success)
Greg Claytonaf247d72011-05-19 03:54:16 +00001118 state = eStateInvalid;
Jim Inghamb8cd5752014-04-16 02:24:17 +00001119 else
1120 m_interrupt_sent = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001121
Pavel Labath9e131f72015-10-27 09:23:55 +00001122 if (! broadcast_sent)
1123 {
1124 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
1125 broadcast_sent = true;
1126 }
1127
Greg Claytone889ad62011-10-27 22:04:16 +00001128 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +00001129 }
1130
Greg Clayton3f875c52013-02-22 22:23:55 +00001131 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001132
1133 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001134 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00001135
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001136 if (ReadPacket(response, UINT32_MAX, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001137 {
1138 if (response.Empty())
1139 state = eStateInvalid;
1140 else
1141 {
1142 const char stop_type = response.GetChar();
1143 if (log)
1144 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
1145 switch (stop_type)
1146 {
1147 case 'T':
1148 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +00001149 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001150 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +00001151 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001152 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
1153 {
1154 lldb::pid_t pid = GetCurrentProcessID ();
1155 if (pid != LLDB_INVALID_PROCESS_ID)
1156 process->SetID (pid);
1157 }
1158 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +00001159 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001160
1161 // Privately notify any internal threads that we have stopped
1162 // in case we wanted to interrupt our process, yet we might
1163 // send a packet and continue without returning control to the
1164 // user.
1165 m_private_is_running.SetValue (false, eBroadcastAlways);
1166
1167 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
1168
Jim Inghambabfc382012-06-06 00:32:39 +00001169 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
1170 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +00001171 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001172 // We sent an interrupt packet to stop the inferior process
1173 // for an async signal or to send an async packet while running
1174 // but we might have been single stepping and received the
1175 // stop packet for the step instead of for the interrupt packet.
1176 // Typically when an interrupt is sent a SIGINT or SIGSTOP
1177 // is used, so if we get anything else, we need to try and
1178 // get another stop reply packet that may have been sent
1179 // due to sending the interrupt when the target is stopped
1180 // which will just re-send a copy of the last stop reply
1181 // packet. If we don't do this, then the reply for our
1182 // async packet will be the repeat stop reply packet and cause
Greg Clayton830c81d2016-04-01 00:41:29 +00001183 // a lot of trouble for us! We also have some debugserver
1184 // binaries that would send two stop replies anytime the process
1185 // was interrupted, so we need to also check for an extra
1186 // stop reply packet if we interrupted the process
Oleksiy Vyalovbdea8dd2016-04-08 20:44:28 +00001187 const bool received_nonstop_signal = signo != sigint_signo && signo != sigstop_signo;
1188 if (m_interrupt_sent || received_nonstop_signal)
Greg Clayton2687cd12012-03-29 01:55:41 +00001189 {
Oleksiy Vyalovbdea8dd2016-04-08 20:44:28 +00001190 if (received_nonstop_signal)
1191 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001192
Oleksiy Vyalovbdea8dd2016-04-08 20:44:28 +00001193 // Try for a very brief time (0.1s) to get another stop reply
Greg Clayton2687cd12012-03-29 01:55:41 +00001194 // packet to make sure it doesn't get in the way
1195 StringExtractorGDBRemote extra_stop_reply_packet;
Jason Molendada9765b2015-08-26 04:07:30 +00001196 uint32_t timeout_usec = 100000;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001197 if (ReadPacket (extra_stop_reply_packet, timeout_usec, false) == PacketResult::Success)
Greg Clayton2687cd12012-03-29 01:55:41 +00001198 {
1199 switch (extra_stop_reply_packet.GetChar())
1200 {
1201 case 'T':
1202 case 'S':
1203 // We did get an extra stop reply, which means
1204 // our interrupt didn't stop the target so we
1205 // shouldn't continue after the async signal
1206 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +00001207 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +00001208 break;
1209 }
1210 }
1211 }
1212 }
1213
1214 if (m_async_signal != -1)
1215 {
1216 if (log)
1217 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
1218
1219 // Save off the async signal we are supposed to send
1220 const int async_signal = m_async_signal;
1221 // Clear the async signal member so we don't end up
1222 // sending the signal multiple times...
1223 m_async_signal = -1;
1224 // Check which signal we stopped with
1225 if (signo == async_signal)
1226 {
1227 if (log)
1228 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
1229
1230 // We already stopped with a signal that we wanted
1231 // to stop with, so we are done
1232 }
1233 else
1234 {
1235 // We stopped with a different signal that the one
1236 // we wanted to stop with, so now we must resume
1237 // with the signal we want
1238 char signal_packet[32];
1239 int signal_packet_len = 0;
1240 signal_packet_len = ::snprintf (signal_packet,
1241 sizeof (signal_packet),
1242 "C%2.2x",
1243 async_signal);
1244
1245 if (log)
1246 log->Printf ("async: stopped with signal %s, resume with %s",
1247 Host::GetSignalAsCString (signo),
1248 Host::GetSignalAsCString (async_signal));
1249
1250 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +00001251 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001252 continue_packet.assign(signal_packet, signal_packet_len);
1253 continue;
1254 }
1255 }
1256 else if (m_async_packet_predicate.GetValue())
1257 {
Greg Clayton5160ce52013-03-27 23:08:40 +00001258 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +00001259
1260 // We are supposed to send an asynchronous packet while
Jim Inghama6195b72013-12-18 01:24:33 +00001261 // we are running.
Greg Clayton2687cd12012-03-29 01:55:41 +00001262 m_async_response.Clear();
1263 if (m_async_packet.empty())
1264 {
Jim Inghama6195b72013-12-18 01:24:33 +00001265 m_async_result = PacketResult::ErrorSendFailed;
1266 if (packet_log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001267 packet_log->Printf ("async: error: empty async packet");
1268
1269 }
1270 else
1271 {
1272 if (packet_log)
1273 packet_log->Printf ("async: sending packet");
1274
Jim Inghama6195b72013-12-18 01:24:33 +00001275 m_async_result = SendPacketAndWaitForResponse (&m_async_packet[0],
1276 m_async_packet.size(),
1277 m_async_response,
1278 false);
Greg Clayton2687cd12012-03-29 01:55:41 +00001279 }
1280 // Let the other thread that was trying to send the async
1281 // packet know that the packet has been sent and response is
1282 // ready...
1283 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
1284
1285 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +00001286 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +00001287
1288 // Set the continue packet to resume if our interrupt
1289 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +00001290 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +00001291 {
Greg Claytonf1186de2012-05-24 23:42:14 +00001292 // Reverting this for now as it is causing deadlocks
1293 // in programs (<rdar://problem/11529853>). In the future
1294 // we should check our thread list and "do the right thing"
1295 // for new threads that show up while we stop and run async
1296 // packets. Setting the packet to 'c' to continue all threads
1297 // is the right thing to do 99.99% of the time because if a
1298 // thread was single stepping, and we sent an interrupt, we
1299 // will notice above that we didn't stop due to an interrupt
1300 // but stopped due to stepping and we would _not_ continue.
1301 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +00001302 continue;
1303 }
1304 }
1305 // Stop with signal and thread info
1306 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +00001307 }
Greg Clayton576d8832011-03-22 04:00:09 +00001308 break;
1309
1310 case 'W':
1311 case 'X':
1312 // process exited
1313 state = eStateExited;
1314 break;
1315
1316 case 'O':
1317 // STDOUT
1318 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001319 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001320 std::string inferior_stdout;
1321 inferior_stdout.reserve(response.GetBytesLeft () / 2);
Dawn Perchik554a8572015-09-17 17:55:32 +00001322
1323 uint8_t ch;
1324 while (response.GetHexU8Ex(ch))
1325 {
1326 if (ch != 0)
1327 inferior_stdout.append(1, (char)ch);
1328 }
Greg Clayton576d8832011-03-22 04:00:09 +00001329 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
1330 }
1331 break;
1332
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001333 case 'A':
1334 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
1335 {
Greg Clayton3f875c52013-02-22 22:23:55 +00001336 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001337 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
1338 if (m_partial_profile_data.length() > 0)
1339 {
1340 m_partial_profile_data.append(input);
1341 input = m_partial_profile_data;
1342 m_partial_profile_data.clear();
1343 }
1344
1345 size_t found, pos = 0, len = input.length();
1346 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
1347 {
1348 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +00001349 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
1350 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00001351
1352 pos = found + end_delimiter_len;
1353 }
1354
1355 if (pos < len)
1356 {
1357 // Last incomplete chunk.
1358 m_partial_profile_data = input.substr(pos);
1359 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001360 }
1361 break;
1362
Greg Clayton576d8832011-03-22 04:00:09 +00001363 case 'E':
1364 // ERROR
1365 state = eStateInvalid;
1366 break;
1367
1368 default:
1369 if (log)
1370 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
1371 state = eStateInvalid;
1372 break;
1373 }
1374 }
1375 }
1376 else
1377 {
1378 if (log)
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001379 log->Printf ("GDBRemoteCommunicationClient::%s () ReadPacket(...) => false", __FUNCTION__);
Greg Clayton576d8832011-03-22 04:00:09 +00001380 state = eStateInvalid;
1381 }
1382 }
1383 if (log)
1384 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
1385 response.SetFilePos(0);
1386 m_private_is_running.SetValue (false, eBroadcastAlways);
1387 m_public_is_running.SetValue (false, eBroadcastAlways);
1388 return state;
1389}
1390
1391bool
1392GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
1393{
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00001394 std::lock_guard<std::recursive_mutex> guard(m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +00001395 m_async_signal = signo;
1396 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +00001397 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +00001398 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +00001399 return true;
1400 m_async_signal = -1;
1401 return false;
1402}
1403
Greg Clayton37a0a242012-04-11 00:24:49 +00001404// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +00001405// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
1406// (the expected result), then it will send the halt packet. If it does succeed
1407// then the caller that requested the interrupt will want to keep the sequence
1408// locked down so that no one else can send packets while the caller has control.
1409// This function usually gets called when we are running and need to stop the
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001410// target. It can also be used when we are running and we need to do something
Greg Clayton576d8832011-03-22 04:00:09 +00001411// else (like read/write memory), so we need to interrupt the running process
1412// (gdb remote protocol requires this), and do what we need to do, then resume.
1413
1414bool
Greg Clayton2687cd12012-03-29 01:55:41 +00001415GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +00001416(
1417 Mutex::Locker& locker,
1418 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +00001419 bool &timed_out
1420)
1421{
Greg Clayton576d8832011-03-22 04:00:09 +00001422 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +00001423 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +00001424
1425 if (IsRunning())
1426 {
1427 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00001428 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +00001429 {
1430 if (log)
1431 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
1432 }
1433 else
Greg Clayton576d8832011-03-22 04:00:09 +00001434 {
1435 // Someone has the mutex locked waiting for a response or for the
1436 // inferior to stop, so send the interrupt on the down low...
1437 char ctrl_c = '\x03';
1438 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +00001439 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +00001440 if (log)
1441 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +00001442 if (bytes_written > 0)
1443 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001444 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +00001445 if (seconds_to_wait_for_stop)
1446 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001447 TimeValue timeout;
1448 if (seconds_to_wait_for_stop)
1449 {
1450 timeout = TimeValue::Now();
1451 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
1452 }
Greg Clayton576d8832011-03-22 04:00:09 +00001453 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
1454 {
1455 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001456 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +00001457 return true;
1458 }
1459 else
1460 {
1461 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001462 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +00001463 }
1464 }
1465 else
1466 {
1467 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001468 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +00001469 return true;
1470 }
1471 }
1472 else
1473 {
1474 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +00001475 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +00001476 }
1477 return false;
1478 }
Greg Clayton576d8832011-03-22 04:00:09 +00001479 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001480 else
1481 {
1482 if (log)
1483 log->Printf ("SendInterrupt () - not running");
1484 }
Greg Clayton576d8832011-03-22 04:00:09 +00001485 return true;
1486}
1487
1488lldb::pid_t
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001489GDBRemoteCommunicationClient::GetCurrentProcessID (bool allow_lazy)
Greg Clayton576d8832011-03-22 04:00:09 +00001490{
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001491 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001492 return m_curr_pid;
1493
1494 // First try to retrieve the pid via the qProcessInfo request.
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00001495 GetCurrentProcessInfo (allow_lazy);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001496 if (m_curr_pid_is_valid == eLazyBoolYes)
Greg Clayton576d8832011-03-22 04:00:09 +00001497 {
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001498 // We really got it.
1499 return m_curr_pid;
Greg Clayton576d8832011-03-22 04:00:09 +00001500 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001501 else
1502 {
Todd Fialae24614f2014-05-14 00:15:32 +00001503 // If we don't get a response for qProcessInfo, check if $qC gives us a result.
1504 // $qC only returns a real process id on older debugserver and lldb-platform stubs.
1505 // The gdb remote protocol documents $qC as returning the thread id, which newer
1506 // debugserver and lldb-gdbserver stubs return correctly.
1507 StringExtractorGDBRemote response;
1508 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false) == PacketResult::Success)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001509 {
Todd Fialae24614f2014-05-14 00:15:32 +00001510 if (response.GetChar() == 'Q')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001511 {
Todd Fialae24614f2014-05-14 00:15:32 +00001512 if (response.GetChar() == 'C')
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001513 {
Todd Fialae24614f2014-05-14 00:15:32 +00001514 m_curr_pid = response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
1515 if (m_curr_pid != LLDB_INVALID_PROCESS_ID)
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001516 {
Todd Fialae24614f2014-05-14 00:15:32 +00001517 m_curr_pid_is_valid = eLazyBoolYes;
1518 return m_curr_pid;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001519 }
1520 }
1521 }
1522 }
Jaydeep Patil1142f832015-08-13 03:46:36 +00001523
1524 // If we don't get a response for $qC, check if $qfThreadID gives us a result.
1525 if (m_curr_pid == LLDB_INVALID_PROCESS_ID)
1526 {
1527 std::vector<lldb::tid_t> thread_ids;
1528 bool sequence_mutex_unavailable;
1529 size_t size;
1530 size = GetCurrentThreadIDs (thread_ids, sequence_mutex_unavailable);
1531 if (size && sequence_mutex_unavailable == false)
1532 {
1533 m_curr_pid = thread_ids.front();
1534 m_curr_pid_is_valid = eLazyBoolYes;
1535 return m_curr_pid;
1536 }
1537 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00001538 }
1539
Greg Clayton576d8832011-03-22 04:00:09 +00001540 return LLDB_INVALID_PROCESS_ID;
1541}
1542
1543bool
1544GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
1545{
1546 error_str.clear();
1547 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001548 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001549 {
1550 if (response.IsOKResponse())
1551 return true;
1552 if (response.GetChar() == 'E')
1553 {
1554 // A string the describes what failed when launching...
1555 error_str = response.GetStringRef().substr(1);
1556 }
1557 else
1558 {
1559 error_str.assign ("unknown error occurred launching process");
1560 }
1561 }
1562 else
1563 {
Jim Ingham98d6da52012-06-28 20:30:23 +00001564 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +00001565 }
1566 return false;
1567}
1568
1569int
Greg Claytonfbb76342013-11-20 21:07:01 +00001570GDBRemoteCommunicationClient::SendArgumentsPacket (const ProcessLaunchInfo &launch_info)
Greg Clayton576d8832011-03-22 04:00:09 +00001571{
Greg Claytonfbb76342013-11-20 21:07:01 +00001572 // Since we don't get the send argv0 separate from the executable path, we need to
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001573 // make sure to use the actual executable path found in the launch_info...
Greg Claytonfbb76342013-11-20 21:07:01 +00001574 std::vector<const char *> argv;
1575 FileSpec exe_file = launch_info.GetExecutableFile();
1576 std::string exe_path;
1577 const char *arg = NULL;
1578 const Args &launch_args = launch_info.GetArguments();
1579 if (exe_file)
Chaoren Lind3173f32015-05-29 19:52:29 +00001580 exe_path = exe_file.GetPath(false);
Greg Claytonfbb76342013-11-20 21:07:01 +00001581 else
1582 {
1583 arg = launch_args.GetArgumentAtIndex(0);
1584 if (arg)
1585 exe_path = arg;
1586 }
1587 if (!exe_path.empty())
1588 {
1589 argv.push_back(exe_path.c_str());
1590 for (uint32_t i=1; (arg = launch_args.GetArgumentAtIndex(i)) != NULL; ++i)
1591 {
1592 if (arg)
1593 argv.push_back(arg);
1594 }
1595 }
1596 if (!argv.empty())
Greg Clayton576d8832011-03-22 04:00:09 +00001597 {
1598 StreamString packet;
1599 packet.PutChar('A');
Greg Claytonfbb76342013-11-20 21:07:01 +00001600 for (size_t i = 0, n = argv.size(); i < n; ++i)
Greg Clayton576d8832011-03-22 04:00:09 +00001601 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001602 arg = argv[i];
Greg Clayton576d8832011-03-22 04:00:09 +00001603 const int arg_len = strlen(arg);
1604 if (i > 0)
1605 packet.PutChar(',');
Greg Claytonfbb76342013-11-20 21:07:01 +00001606 packet.Printf("%i,%i,", arg_len * 2, (int)i);
Greg Clayton576d8832011-03-22 04:00:09 +00001607 packet.PutBytesAsRawHex8 (arg, arg_len);
1608 }
1609
1610 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001611 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00001612 {
1613 if (response.IsOKResponse())
1614 return 0;
1615 uint8_t error = response.GetError();
1616 if (error)
1617 return error;
1618 }
1619 }
1620 return -1;
1621}
1622
1623int
1624GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1625{
1626 if (name_equal_value && name_equal_value[0])
1627 {
1628 StreamString packet;
Greg Clayton89600582013-10-10 17:53:50 +00001629 bool send_hex_encoding = false;
1630 for (const char *p = name_equal_value; *p != '\0' && send_hex_encoding == false; ++p)
Greg Clayton576d8832011-03-22 04:00:09 +00001631 {
Greg Clayton89600582013-10-10 17:53:50 +00001632 if (isprint(*p))
1633 {
1634 switch (*p)
1635 {
1636 case '$':
1637 case '#':
Jason Molenda60bdafb2015-11-05 23:51:05 +00001638 case '*':
Tim Northover974ff612015-11-09 22:05:05 +00001639 case '}':
Greg Clayton89600582013-10-10 17:53:50 +00001640 send_hex_encoding = true;
1641 break;
1642 default:
1643 break;
1644 }
1645 }
1646 else
1647 {
1648 // We have non printable characters, lets hex encode this...
1649 send_hex_encoding = true;
1650 }
1651 }
1652
1653 StringExtractorGDBRemote response;
1654 if (send_hex_encoding)
1655 {
1656 if (m_supports_QEnvironmentHexEncoded)
1657 {
1658 packet.PutCString("QEnvironmentHexEncoded:");
1659 packet.PutBytesAsRawHex8 (name_equal_value, strlen(name_equal_value));
Greg Clayton3dedae12013-12-06 21:45:27 +00001660 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001661 {
1662 if (response.IsOKResponse())
1663 return 0;
1664 uint8_t error = response.GetError();
1665 if (error)
1666 return error;
1667 if (response.IsUnsupportedResponse())
1668 m_supports_QEnvironmentHexEncoded = false;
1669 }
1670 }
1671
1672 }
1673 else if (m_supports_QEnvironment)
1674 {
1675 packet.Printf("QEnvironment:%s", name_equal_value);
Greg Clayton3dedae12013-12-06 21:45:27 +00001676 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton89600582013-10-10 17:53:50 +00001677 {
1678 if (response.IsOKResponse())
1679 return 0;
1680 uint8_t error = response.GetError();
1681 if (error)
1682 return error;
1683 if (response.IsUnsupportedResponse())
1684 m_supports_QEnvironment = false;
1685 }
Greg Clayton576d8832011-03-22 04:00:09 +00001686 }
1687 }
1688 return -1;
1689}
1690
Greg Claytonc4103b32011-05-08 04:53:50 +00001691int
1692GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1693{
1694 if (arch && arch[0])
1695 {
1696 StreamString packet;
1697 packet.Printf("QLaunchArch:%s", arch);
1698 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00001699 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Claytonc4103b32011-05-08 04:53:50 +00001700 {
1701 if (response.IsOKResponse())
1702 return 0;
1703 uint8_t error = response.GetError();
1704 if (error)
1705 return error;
1706 }
1707 }
1708 return -1;
1709}
1710
Jason Molendaa3329782014-03-29 18:54:20 +00001711int
1712GDBRemoteCommunicationClient::SendLaunchEventDataPacket (char const *data, bool *was_supported)
1713{
1714 if (data && *data != '\0')
1715 {
1716 StreamString packet;
1717 packet.Printf("QSetProcessEvent:%s", data);
1718 StringExtractorGDBRemote response;
1719 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
1720 {
1721 if (response.IsOKResponse())
1722 {
1723 if (was_supported)
1724 *was_supported = true;
1725 return 0;
1726 }
1727 else if (response.IsUnsupportedResponse())
1728 {
1729 if (was_supported)
1730 *was_supported = false;
1731 return -1;
1732 }
1733 else
1734 {
1735 uint8_t error = response.GetError();
1736 if (was_supported)
1737 *was_supported = true;
1738 if (error)
1739 return error;
1740 }
1741 }
1742 }
1743 return -1;
1744}
1745
Greg Clayton576d8832011-03-22 04:00:09 +00001746bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001747GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1748 uint32_t &minor,
1749 uint32_t &update)
1750{
1751 if (GetHostInfo ())
1752 {
1753 if (m_os_version_major != UINT32_MAX)
1754 {
1755 major = m_os_version_major;
1756 minor = m_os_version_minor;
1757 update = m_os_version_update;
1758 return true;
1759 }
1760 }
1761 return false;
1762}
1763
1764bool
1765GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1766{
1767 if (GetHostInfo ())
1768 {
1769 if (!m_os_build.empty())
1770 {
1771 s = m_os_build;
1772 return true;
1773 }
1774 }
1775 s.clear();
1776 return false;
1777}
1778
1779
1780bool
1781GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1782{
1783 if (GetHostInfo ())
1784 {
1785 if (!m_os_kernel.empty())
1786 {
1787 s = m_os_kernel;
1788 return true;
1789 }
1790 }
1791 s.clear();
1792 return false;
1793}
1794
1795bool
1796GDBRemoteCommunicationClient::GetHostname (std::string &s)
1797{
1798 if (GetHostInfo ())
1799 {
1800 if (!m_hostname.empty())
1801 {
1802 s = m_hostname;
1803 return true;
1804 }
1805 }
1806 s.clear();
1807 return false;
1808}
1809
1810ArchSpec
1811GDBRemoteCommunicationClient::GetSystemArchitecture ()
1812{
1813 if (GetHostInfo ())
1814 return m_host_arch;
1815 return ArchSpec();
1816}
1817
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001818const lldb_private::ArchSpec &
1819GDBRemoteCommunicationClient::GetProcessArchitecture ()
1820{
1821 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1822 GetCurrentProcessInfo ();
1823 return m_process_arch;
1824}
1825
Jason Molendaa3329782014-03-29 18:54:20 +00001826bool
1827GDBRemoteCommunicationClient::GetGDBServerVersion()
1828{
1829 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate)
1830 {
1831 m_gdb_server_name.clear();
1832 m_gdb_server_version = 0;
1833 m_qGDBServerVersion_is_valid = eLazyBoolNo;
1834
1835 StringExtractorGDBRemote response;
1836 if (SendPacketAndWaitForResponse ("qGDBServerVersion", response, false) == PacketResult::Success)
1837 {
1838 if (response.IsNormalResponse())
1839 {
1840 std::string name;
1841 std::string value;
1842 bool success = false;
1843 while (response.GetNameColonValue(name, value))
1844 {
1845 if (name.compare("name") == 0)
1846 {
1847 success = true;
1848 m_gdb_server_name.swap(value);
1849 }
1850 else if (name.compare("version") == 0)
1851 {
1852 size_t dot_pos = value.find('.');
1853 if (dot_pos != std::string::npos)
1854 value[dot_pos] = '\0';
Vince Harron5275aaa2015-01-15 20:08:35 +00001855 const uint32_t version = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molendaa3329782014-03-29 18:54:20 +00001856 if (version != UINT32_MAX)
1857 {
1858 success = true;
1859 m_gdb_server_version = version;
1860 }
1861 }
1862 }
1863 if (success)
1864 m_qGDBServerVersion_is_valid = eLazyBoolYes;
1865 }
1866 }
1867 }
1868 return m_qGDBServerVersion_is_valid == eLazyBoolYes;
1869}
1870
Jason Molenda91ffe0a2015-06-18 21:46:06 +00001871void
1872GDBRemoteCommunicationClient::MaybeEnableCompression (std::vector<std::string> supported_compressions)
1873{
1874 CompressionType avail_type = CompressionType::None;
1875 std::string avail_name;
1876
1877#if defined (HAVE_LIBCOMPRESSION)
1878 // libcompression is weak linked so test if compression_decode_buffer() is available
1879 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1880 {
1881 for (auto compression : supported_compressions)
1882 {
1883 if (compression == "lzfse")
1884 {
1885 avail_type = CompressionType::LZFSE;
1886 avail_name = compression;
1887 break;
1888 }
1889 }
1890 }
1891#endif
1892
1893#if defined (HAVE_LIBCOMPRESSION)
1894 // libcompression is weak linked so test if compression_decode_buffer() is available
1895 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1896 {
1897 for (auto compression : supported_compressions)
1898 {
1899 if (compression == "zlib-deflate")
1900 {
1901 avail_type = CompressionType::ZlibDeflate;
1902 avail_name = compression;
1903 break;
1904 }
1905 }
1906 }
1907#endif
1908
1909#if defined (HAVE_LIBZ)
1910 if (avail_type == CompressionType::None)
1911 {
1912 for (auto compression : supported_compressions)
1913 {
1914 if (compression == "zlib-deflate")
1915 {
1916 avail_type = CompressionType::ZlibDeflate;
1917 avail_name = compression;
1918 break;
1919 }
1920 }
1921 }
1922#endif
1923
1924#if defined (HAVE_LIBCOMPRESSION)
1925 // libcompression is weak linked so test if compression_decode_buffer() is available
1926 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1927 {
1928 for (auto compression : supported_compressions)
1929 {
1930 if (compression == "lz4")
1931 {
1932 avail_type = CompressionType::LZ4;
1933 avail_name = compression;
1934 break;
1935 }
1936 }
1937 }
1938#endif
1939
1940#if defined (HAVE_LIBCOMPRESSION)
1941 // libcompression is weak linked so test if compression_decode_buffer() is available
1942 if (compression_decode_buffer != NULL && avail_type == CompressionType::None)
1943 {
1944 for (auto compression : supported_compressions)
1945 {
1946 if (compression == "lzma")
1947 {
1948 avail_type = CompressionType::LZMA;
1949 avail_name = compression;
1950 break;
1951 }
1952 }
1953 }
1954#endif
1955
1956 if (avail_type != CompressionType::None)
1957 {
1958 StringExtractorGDBRemote response;
1959 std::string packet = "QEnableCompression:type:" + avail_name + ";";
1960 if (SendPacketAndWaitForResponse (packet.c_str(), response, false) != PacketResult::Success)
1961 return;
1962
1963 if (response.IsOKResponse())
1964 {
1965 m_compression_type = avail_type;
1966 }
1967 }
1968}
1969
Jason Molendaa3329782014-03-29 18:54:20 +00001970const char *
1971GDBRemoteCommunicationClient::GetGDBServerProgramName()
1972{
1973 if (GetGDBServerVersion())
1974 {
1975 if (!m_gdb_server_name.empty())
1976 return m_gdb_server_name.c_str();
1977 }
1978 return NULL;
1979}
1980
1981uint32_t
1982GDBRemoteCommunicationClient::GetGDBServerProgramVersion()
1983{
1984 if (GetGDBServerVersion())
1985 return m_gdb_server_version;
1986 return 0;
1987}
Greg Clayton1cb64962011-03-24 04:28:38 +00001988
1989bool
Ewan Crawford78baa192015-05-13 09:18:18 +00001990GDBRemoteCommunicationClient::GetDefaultThreadId (lldb::tid_t &tid)
1991{
1992 StringExtractorGDBRemote response;
1993 if (SendPacketAndWaitForResponse("qC",response,false) != PacketResult::Success)
1994 return false;
1995
1996 if (!response.IsNormalResponse())
1997 return false;
1998
1999 if (response.GetChar() == 'Q' && response.GetChar() == 'C')
2000 tid = response.GetHexMaxU32(true, -1);
2001
2002 return true;
2003}
2004
2005bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002006GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00002007{
Todd Fialaaf245d12014-06-30 21:05:18 +00002008 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS));
2009
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002010 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00002011 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002012 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00002013 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002014 if (SendPacketAndWaitForResponse ("qHostInfo", response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002015 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00002016 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00002017 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002018 std::string name;
2019 std::string value;
2020 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2021 uint32_t sub = 0;
2022 std::string arch_name;
2023 std::string os_name;
2024 std::string vendor_name;
2025 std::string triple;
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00002026 std::string distribution_id;
Greg Clayton32e0a752011-03-30 18:16:51 +00002027 uint32_t pointer_byte_size = 0;
2028 StringExtractor extractor;
2029 ByteOrder byte_order = eByteOrderInvalid;
2030 uint32_t num_keys_decoded = 0;
2031 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00002032 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002033 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00002034 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002035 // exception type in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002036 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00002037 if (cpu != LLDB_INVALID_CPUTYPE)
2038 ++num_keys_decoded;
2039 }
2040 else if (name.compare("cpusubtype") == 0)
2041 {
2042 // exception count in big endian hex
Vince Harron5275aaa2015-01-15 20:08:35 +00002043 sub = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00002044 if (sub != 0)
2045 ++num_keys_decoded;
2046 }
2047 else if (name.compare("arch") == 0)
2048 {
2049 arch_name.swap (value);
2050 ++num_keys_decoded;
2051 }
2052 else if (name.compare("triple") == 0)
2053 {
Greg Clayton44272a42014-09-18 00:18:32 +00002054 extractor.GetStringRef ().swap (value);
2055 extractor.SetFilePos(0);
2056 extractor.GetHexByteString (triple);
Greg Clayton32e0a752011-03-30 18:16:51 +00002057 ++num_keys_decoded;
2058 }
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00002059 else if (name.compare ("distribution_id") == 0)
2060 {
2061 extractor.GetStringRef ().swap (value);
2062 extractor.SetFilePos (0);
2063 extractor.GetHexByteString (distribution_id);
2064 ++num_keys_decoded;
2065 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002066 else if (name.compare("os_build") == 0)
2067 {
2068 extractor.GetStringRef().swap(value);
2069 extractor.SetFilePos(0);
2070 extractor.GetHexByteString (m_os_build);
2071 ++num_keys_decoded;
2072 }
2073 else if (name.compare("hostname") == 0)
2074 {
2075 extractor.GetStringRef().swap(value);
2076 extractor.SetFilePos(0);
2077 extractor.GetHexByteString (m_hostname);
2078 ++num_keys_decoded;
2079 }
2080 else if (name.compare("os_kernel") == 0)
2081 {
2082 extractor.GetStringRef().swap(value);
2083 extractor.SetFilePos(0);
2084 extractor.GetHexByteString (m_os_kernel);
2085 ++num_keys_decoded;
2086 }
2087 else if (name.compare("ostype") == 0)
2088 {
2089 os_name.swap (value);
2090 ++num_keys_decoded;
2091 }
2092 else if (name.compare("vendor") == 0)
2093 {
2094 vendor_name.swap(value);
2095 ++num_keys_decoded;
2096 }
2097 else if (name.compare("endian") == 0)
2098 {
2099 ++num_keys_decoded;
2100 if (value.compare("little") == 0)
2101 byte_order = eByteOrderLittle;
2102 else if (value.compare("big") == 0)
2103 byte_order = eByteOrderBig;
2104 else if (value.compare("pdp") == 0)
2105 byte_order = eByteOrderPDP;
2106 else
2107 --num_keys_decoded;
2108 }
2109 else if (name.compare("ptrsize") == 0)
2110 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002111 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 0);
Greg Clayton32e0a752011-03-30 18:16:51 +00002112 if (pointer_byte_size != 0)
2113 ++num_keys_decoded;
2114 }
Greg Clayton17499dd2016-01-28 00:16:11 +00002115 else if ((name.compare("os_version") == 0) ||
2116 (name.compare("version") == 0)) // Older debugserver binaries used the "version" key instead of "os_version"...
Greg Clayton32e0a752011-03-30 18:16:51 +00002117 {
2118 Args::StringToVersion (value.c_str(),
2119 m_os_version_major,
2120 m_os_version_minor,
2121 m_os_version_update);
2122 if (m_os_version_major != UINT32_MAX)
2123 ++num_keys_decoded;
2124 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002125 else if (name.compare("watchpoint_exceptions_received") == 0)
2126 {
2127 ++num_keys_decoded;
2128 if (strcmp(value.c_str(),"before") == 0)
2129 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2130 else if (strcmp(value.c_str(),"after") == 0)
2131 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
2132 else
2133 --num_keys_decoded;
2134 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002135 else if (name.compare("default_packet_timeout") == 0)
2136 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002137 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0);
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002138 if (m_default_packet_timeout > 0)
2139 {
2140 SetPacketTimeout(m_default_packet_timeout);
2141 ++num_keys_decoded;
2142 }
2143 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002144
Greg Clayton32e0a752011-03-30 18:16:51 +00002145 }
2146
2147 if (num_keys_decoded > 0)
2148 m_qHostInfo_is_valid = eLazyBoolYes;
2149
2150 if (triple.empty())
2151 {
2152 if (arch_name.empty())
2153 {
2154 if (cpu != LLDB_INVALID_CPUTYPE)
2155 {
2156 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2157 if (pointer_byte_size)
2158 {
2159 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2160 }
2161 if (byte_order != eByteOrderInvalid)
2162 {
2163 assert (byte_order == m_host_arch.GetByteOrder());
2164 }
Greg Clayton70512312012-05-08 01:45:38 +00002165
Greg Clayton32e0a752011-03-30 18:16:51 +00002166 if (!vendor_name.empty())
2167 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2168 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00002169 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00002170
2171 }
2172 }
2173 else
2174 {
2175 std::string triple;
2176 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00002177 if (!vendor_name.empty() || !os_name.empty())
2178 {
2179 triple += '-';
2180 if (vendor_name.empty())
2181 triple += "unknown";
2182 else
2183 triple += vendor_name;
2184 triple += '-';
2185 if (os_name.empty())
2186 triple += "unknown";
2187 else
2188 triple += os_name;
2189 }
2190 m_host_arch.SetTriple (triple.c_str());
2191
2192 llvm::Triple &host_triple = m_host_arch.GetTriple();
2193 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
2194 {
2195 switch (m_host_arch.GetMachine())
2196 {
Todd Fialad8eaa172014-07-23 14:37:35 +00002197 case llvm::Triple::aarch64:
Greg Clayton70512312012-05-08 01:45:38 +00002198 case llvm::Triple::arm:
2199 case llvm::Triple::thumb:
2200 host_triple.setOS(llvm::Triple::IOS);
2201 break;
2202 default:
2203 host_triple.setOS(llvm::Triple::MacOSX);
2204 break;
2205 }
2206 }
Greg Clayton1cb64962011-03-24 04:28:38 +00002207 if (pointer_byte_size)
2208 {
2209 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2210 }
2211 if (byte_order != eByteOrderInvalid)
2212 {
2213 assert (byte_order == m_host_arch.GetByteOrder());
2214 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002215
Greg Clayton1cb64962011-03-24 04:28:38 +00002216 }
2217 }
2218 else
2219 {
Greg Clayton70512312012-05-08 01:45:38 +00002220 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00002221 if (pointer_byte_size)
2222 {
2223 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
2224 }
2225 if (byte_order != eByteOrderInvalid)
2226 {
2227 assert (byte_order == m_host_arch.GetByteOrder());
2228 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002229
2230 if (log)
2231 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 +00002232 }
2233 if (!distribution_id.empty ())
2234 m_host_arch.SetDistributionId (distribution_id.c_str ());
Greg Claytond314e812011-03-23 00:09:55 +00002235 }
Greg Clayton576d8832011-03-22 04:00:09 +00002236 }
2237 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002238 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00002239}
2240
2241int
2242GDBRemoteCommunicationClient::SendAttach
2243(
2244 lldb::pid_t pid,
2245 StringExtractorGDBRemote& response
2246)
2247{
2248 if (pid != LLDB_INVALID_PROCESS_ID)
2249 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002250 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002251 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002252 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00002253 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002254 {
2255 if (response.IsErrorResponse())
2256 return response.GetError();
2257 return 0;
2258 }
2259 }
2260 return -1;
2261}
2262
Vince Harrone0be4252015-02-06 18:32:57 +00002263int
2264GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len)
2265{
2266 StreamString packet;
2267 packet.PutCString("I");
2268 packet.PutBytesAsRawHex8(data, data_len);
2269 StringExtractorGDBRemote response;
2270 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
2271 {
2272 return 0;
2273 }
2274 return response.GetError();
2275
2276}
2277
Greg Clayton576d8832011-03-22 04:00:09 +00002278const lldb_private::ArchSpec &
2279GDBRemoteCommunicationClient::GetHostArchitecture ()
2280{
Greg Clayton32e0a752011-03-30 18:16:51 +00002281 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00002282 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00002283 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00002284}
2285
Greg Clayton9ac6d2d2013-10-25 18:13:17 +00002286uint32_t
2287GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout ()
2288{
2289 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
2290 GetHostInfo ();
2291 return m_default_packet_timeout;
2292}
2293
Greg Clayton576d8832011-03-22 04:00:09 +00002294addr_t
2295GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
2296{
Greg Clayton70b57652011-05-15 01:25:55 +00002297 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002298 {
Greg Clayton70b57652011-05-15 01:25:55 +00002299 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002300 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002301 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00002302 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00002303 permissions & lldb::ePermissionsReadable ? "r" : "",
2304 permissions & lldb::ePermissionsWritable ? "w" : "",
2305 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00002306 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002307 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002308 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002309 {
Todd Fialaf105f582014-06-21 00:48:09 +00002310 if (response.IsUnsupportedResponse())
2311 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2312 else if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002313 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2314 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002315 else
2316 {
2317 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2318 }
Greg Clayton576d8832011-03-22 04:00:09 +00002319 }
2320 return LLDB_INVALID_ADDRESS;
2321}
2322
2323bool
2324GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
2325{
Greg Clayton70b57652011-05-15 01:25:55 +00002326 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00002327 {
Greg Clayton70b57652011-05-15 01:25:55 +00002328 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00002329 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002330 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002331 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00002332 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002333 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton2a48f522011-05-14 01:50:35 +00002334 {
Todd Fialaf105f582014-06-21 00:48:09 +00002335 if (response.IsUnsupportedResponse())
2336 m_supports_alloc_dealloc_memory = eLazyBoolNo;
2337 else if (response.IsOKResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00002338 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002339 }
2340 else
2341 {
2342 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00002343 }
Greg Clayton576d8832011-03-22 04:00:09 +00002344 }
2345 return false;
2346}
2347
Jim Inghamacff8952013-05-02 00:27:30 +00002348Error
2349GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00002350{
Jim Inghamacff8952013-05-02 00:27:30 +00002351 Error error;
2352
2353 if (keep_stopped)
2354 {
2355 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
2356 {
2357 char packet[64];
2358 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002359 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00002360 StringExtractorGDBRemote response;
Jim Ingham4920a4e2015-07-15 00:59:25 +00002361 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success
2362 && response.IsOKResponse())
Jim Inghamacff8952013-05-02 00:27:30 +00002363 {
2364 m_supports_detach_stay_stopped = eLazyBoolYes;
2365 }
2366 else
2367 {
2368 m_supports_detach_stay_stopped = eLazyBoolNo;
2369 }
2370 }
2371
2372 if (m_supports_detach_stay_stopped == eLazyBoolNo)
2373 {
2374 error.SetErrorString("Stays stopped not supported by this target.");
2375 return error;
2376 }
2377 else
2378 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002379 StringExtractorGDBRemote response;
Jason Molenda2a667382015-07-15 00:16:09 +00002380 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 2, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002381 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002382 error.SetErrorString ("Sending extended disconnect packet failed.");
2383 }
2384 }
2385 else
2386 {
Jim Ingham6c8824d2014-03-28 20:00:07 +00002387 StringExtractorGDBRemote response;
2388 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false);
Greg Clayton3dedae12013-12-06 21:45:27 +00002389 if (packet_result != PacketResult::Success)
Jim Inghamacff8952013-05-02 00:27:30 +00002390 error.SetErrorString ("Sending disconnect packet failed.");
2391 }
2392 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00002393}
2394
Greg Clayton46fb5582011-11-18 07:03:08 +00002395Error
2396GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
2397 lldb_private::MemoryRegionInfo &region_info)
2398{
2399 Error error;
2400 region_info.Clear();
2401
2402 if (m_supports_memory_region_info != eLazyBoolNo)
2403 {
2404 m_supports_memory_region_info = eLazyBoolYes;
2405 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002406 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00002407 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00002408 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002409 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton46fb5582011-11-18 07:03:08 +00002410 {
2411 std::string name;
2412 std::string value;
2413 addr_t addr_value;
2414 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00002415 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00002416 while (success && response.GetNameColonValue(name, value))
2417 {
2418 if (name.compare ("start") == 0)
2419 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002420 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002421 if (success)
2422 region_info.GetRange().SetRangeBase(addr_value);
2423 }
2424 else if (name.compare ("size") == 0)
2425 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002426 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success);
Greg Clayton46fb5582011-11-18 07:03:08 +00002427 if (success)
2428 region_info.GetRange().SetByteSize (addr_value);
2429 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002430 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00002431 {
Jason Molendacb349ee2011-12-13 05:39:38 +00002432 saw_permissions = true;
2433 if (region_info.GetRange().Contains (addr))
2434 {
2435 if (value.find('r') != std::string::npos)
2436 region_info.SetReadable (MemoryRegionInfo::eYes);
2437 else
2438 region_info.SetReadable (MemoryRegionInfo::eNo);
2439
2440 if (value.find('w') != std::string::npos)
2441 region_info.SetWritable (MemoryRegionInfo::eYes);
2442 else
2443 region_info.SetWritable (MemoryRegionInfo::eNo);
2444
2445 if (value.find('x') != std::string::npos)
2446 region_info.SetExecutable (MemoryRegionInfo::eYes);
2447 else
2448 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00002449
2450 region_info.SetMapped(MemoryRegionInfo::eYes);
Jason Molendacb349ee2011-12-13 05:39:38 +00002451 }
2452 else
2453 {
2454 // The reported region does not contain this address -- we're looking at an unmapped page
2455 region_info.SetReadable (MemoryRegionInfo::eNo);
2456 region_info.SetWritable (MemoryRegionInfo::eNo);
2457 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00002458 region_info.SetMapped(MemoryRegionInfo::eNo);
Jason Molendacb349ee2011-12-13 05:39:38 +00002459 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002460 }
2461 else if (name.compare ("error") == 0)
2462 {
2463 StringExtractorGDBRemote name_extractor;
2464 // Swap "value" over into "name_extractor"
2465 name_extractor.GetStringRef().swap(value);
2466 // Now convert the HEX bytes into a string value
2467 name_extractor.GetHexByteString (value);
2468 error.SetErrorString(value.c_str());
2469 }
2470 }
Jason Molendacb349ee2011-12-13 05:39:38 +00002471
2472 // We got a valid address range back but no permissions -- which means this is an unmapped page
2473 if (region_info.GetRange().IsValid() && saw_permissions == false)
2474 {
2475 region_info.SetReadable (MemoryRegionInfo::eNo);
2476 region_info.SetWritable (MemoryRegionInfo::eNo);
2477 region_info.SetExecutable (MemoryRegionInfo::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00002478 region_info.SetMapped(MemoryRegionInfo::eNo);
Jason Molendacb349ee2011-12-13 05:39:38 +00002479 }
Greg Clayton46fb5582011-11-18 07:03:08 +00002480 }
2481 else
2482 {
2483 m_supports_memory_region_info = eLazyBoolNo;
2484 }
2485 }
2486
2487 if (m_supports_memory_region_info == eLazyBoolNo)
2488 {
2489 error.SetErrorString("qMemoryRegionInfo is not supported");
2490 }
2491 if (error.Fail())
2492 region_info.Clear();
2493 return error;
2494
2495}
2496
Johnny Chen64637202012-05-23 21:09:52 +00002497Error
2498GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
2499{
2500 Error error;
2501
2502 if (m_supports_watchpoint_support_info == eLazyBoolYes)
2503 {
2504 num = m_num_supported_hardware_watchpoints;
2505 return error;
2506 }
2507
2508 // Set num to 0 first.
2509 num = 0;
2510 if (m_supports_watchpoint_support_info != eLazyBoolNo)
2511 {
2512 char packet[64];
2513 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00002514 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00002515 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002516 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Johnny Chen64637202012-05-23 21:09:52 +00002517 {
2518 m_supports_watchpoint_support_info = eLazyBoolYes;
2519 std::string name;
2520 std::string value;
2521 while (response.GetNameColonValue(name, value))
2522 {
2523 if (name.compare ("num") == 0)
2524 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002525 num = StringConvert::ToUInt32(value.c_str(), 0, 0);
Johnny Chen64637202012-05-23 21:09:52 +00002526 m_num_supported_hardware_watchpoints = num;
2527 }
2528 }
2529 }
2530 else
2531 {
2532 m_supports_watchpoint_support_info = eLazyBoolNo;
2533 }
2534 }
2535
2536 if (m_supports_watchpoint_support_info == eLazyBoolNo)
2537 {
2538 error.SetErrorString("qWatchpointSupportInfo is not supported");
2539 }
2540 return error;
2541
2542}
Greg Clayton46fb5582011-11-18 07:03:08 +00002543
Enrico Granataf04a2192012-07-13 23:18:48 +00002544lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00002545GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00002546{
2547 Error error(GetWatchpointSupportInfo(num));
2548 if (error.Success())
Jaydeep Patil725666c2015-08-13 03:46:01 +00002549 error = GetWatchpointsTriggerAfterInstruction(after, arch);
Enrico Granataf04a2192012-07-13 23:18:48 +00002550 return error;
2551}
2552
2553lldb_private::Error
Jaydeep Patil725666c2015-08-13 03:46:01 +00002554GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after, const ArchSpec &arch)
Enrico Granataf04a2192012-07-13 23:18:48 +00002555{
2556 Error error;
Jaydeep Patil725666c2015-08-13 03:46:01 +00002557 llvm::Triple::ArchType atype = arch.GetMachine();
Enrico Granataf04a2192012-07-13 23:18:48 +00002558
2559 // we assume watchpoints will happen after running the relevant opcode
2560 // and we only want to override this behavior if we have explicitly
2561 // received a qHostInfo telling us otherwise
2562 if (m_qHostInfo_is_valid != eLazyBoolYes)
Jaydeep Patil725666c2015-08-13 03:46:01 +00002563 {
2564 // On targets like MIPS, watchpoint exceptions are always generated
2565 // before the instruction is executed. The connected target may not
2566 // support qHostInfo or qWatchpointSupportInfo packets.
2567 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
2568 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)
2569 after = false;
2570 else
2571 after = true;
2572 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002573 else
Jaydeep Patil725666c2015-08-13 03:46:01 +00002574 {
2575 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo
2576 // if it is not calculated before.
2577 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate &&
2578 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel
2579 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el))
2580 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
2581
Enrico Granataf04a2192012-07-13 23:18:48 +00002582 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
Jaydeep Patil725666c2015-08-13 03:46:01 +00002583 }
Enrico Granataf04a2192012-07-13 23:18:48 +00002584 return error;
2585}
2586
Greg Clayton576d8832011-03-22 04:00:09 +00002587int
Chaoren Lind3173f32015-05-29 19:52:29 +00002588GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002589{
Chaoren Lind3173f32015-05-29 19:52:29 +00002590 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002591 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002592 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002593 StreamString packet;
2594 packet.PutCString("QSetSTDIN:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002595 packet.PutCStringAsRawHex8(path.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +00002596
2597 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002598 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002599 {
2600 if (response.IsOKResponse())
2601 return 0;
2602 uint8_t error = response.GetError();
2603 if (error)
2604 return error;
2605 }
2606 }
2607 return -1;
2608}
2609
2610int
Chaoren Lind3173f32015-05-29 19:52:29 +00002611GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002612{
Chaoren Lind3173f32015-05-29 19:52:29 +00002613 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002614 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002615 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002616 StreamString packet;
2617 packet.PutCString("QSetSTDOUT:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002618 packet.PutCStringAsRawHex8(path.c_str());
2619
Greg Clayton576d8832011-03-22 04:00:09 +00002620 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002621 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002622 {
2623 if (response.IsOKResponse())
2624 return 0;
2625 uint8_t error = response.GetError();
2626 if (error)
2627 return error;
2628 }
2629 }
2630 return -1;
2631}
2632
2633int
Chaoren Lind3173f32015-05-29 19:52:29 +00002634GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002635{
Chaoren Lind3173f32015-05-29 19:52:29 +00002636 if (file_spec)
Greg Clayton576d8832011-03-22 04:00:09 +00002637 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002638 std::string path{file_spec.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002639 StreamString packet;
2640 packet.PutCString("QSetSTDERR:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002641 packet.PutCStringAsRawHex8(path.c_str());
2642
Greg Clayton576d8832011-03-22 04:00:09 +00002643 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002644 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002645 {
2646 if (response.IsOKResponse())
2647 return 0;
2648 uint8_t error = response.GetError();
2649 if (error)
2650 return error;
2651 }
2652 }
2653 return -1;
2654}
2655
Greg Claytonfbb76342013-11-20 21:07:01 +00002656bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002657GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir)
Greg Claytonfbb76342013-11-20 21:07:01 +00002658{
2659 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002660 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00002661 {
2662 if (response.IsUnsupportedResponse())
2663 return false;
2664 if (response.IsErrorResponse())
2665 return false;
Chaoren Lind3173f32015-05-29 19:52:29 +00002666 std::string cwd;
2667 response.GetHexByteString(cwd);
Chaoren Lin44145d72015-05-29 19:52:37 +00002668 working_dir.SetFile(cwd, false, GetHostArchitecture());
Greg Claytonfbb76342013-11-20 21:07:01 +00002669 return !cwd.empty();
2670 }
2671 return false;
2672}
2673
Greg Clayton576d8832011-03-22 04:00:09 +00002674int
Chaoren Lind3173f32015-05-29 19:52:29 +00002675GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002676{
Chaoren Lind3173f32015-05-29 19:52:29 +00002677 if (working_dir)
Greg Clayton576d8832011-03-22 04:00:09 +00002678 {
Chaoren Lind3173f32015-05-29 19:52:29 +00002679 std::string path{working_dir.GetPath(false)};
Greg Clayton576d8832011-03-22 04:00:09 +00002680 StreamString packet;
2681 packet.PutCString("QSetWorkingDir:");
Chaoren Lind3173f32015-05-29 19:52:29 +00002682 packet.PutCStringAsRawHex8(path.c_str());
2683
Greg Clayton576d8832011-03-22 04:00:09 +00002684 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002685 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), 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 }
2694 return -1;
2695}
2696
2697int
2698GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
2699{
Greg Clayton32e0a752011-03-30 18:16:51 +00002700 char packet[32];
2701 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00002702 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00002703 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002704 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +00002705 {
2706 if (response.IsOKResponse())
2707 return 0;
2708 uint8_t error = response.GetError();
2709 if (error)
2710 return error;
2711 }
2712 return -1;
2713}
Greg Clayton32e0a752011-03-30 18:16:51 +00002714
Jim Ingham106d0282014-06-25 02:32:56 +00002715int
2716GDBRemoteCommunicationClient::SetDetachOnError (bool enable)
2717{
2718 char packet[32];
2719 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0);
2720 assert (packet_len < (int)sizeof(packet));
2721 StringExtractorGDBRemote response;
2722 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
2723 {
2724 if (response.IsOKResponse())
2725 return 0;
2726 uint8_t error = response.GetError();
2727 if (error)
2728 return error;
2729 }
2730 return -1;
2731}
2732
2733
Greg Clayton32e0a752011-03-30 18:16:51 +00002734bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002735GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002736{
2737 if (response.IsNormalResponse())
2738 {
2739 std::string name;
2740 std::string value;
2741 StringExtractor extractor;
Jason Molenda89c37492014-01-27 22:23:20 +00002742
2743 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2744 uint32_t sub = 0;
2745 std::string vendor;
2746 std::string os_type;
Greg Clayton32e0a752011-03-30 18:16:51 +00002747
2748 while (response.GetNameColonValue(name, value))
2749 {
2750 if (name.compare("pid") == 0)
2751 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002752 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002753 }
2754 else if (name.compare("ppid") == 0)
2755 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002756 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002757 }
2758 else if (name.compare("uid") == 0)
2759 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002760 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002761 }
2762 else if (name.compare("euid") == 0)
2763 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002764 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002765 }
2766 else if (name.compare("gid") == 0)
2767 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002768 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002769 }
2770 else if (name.compare("egid") == 0)
2771 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002772 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00002773 }
2774 else if (name.compare("triple") == 0)
2775 {
Greg Clayton44272a42014-09-18 00:18:32 +00002776 StringExtractor extractor;
2777 extractor.GetStringRef().swap(value);
2778 extractor.SetFilePos(0);
2779 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00002780 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00002781 }
2782 else if (name.compare("name") == 0)
2783 {
2784 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00002785 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00002786 // control the characters in a process name
2787 extractor.GetStringRef().swap(value);
2788 extractor.SetFilePos(0);
2789 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00002790 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00002791 }
Jason Molenda89c37492014-01-27 22:23:20 +00002792 else if (name.compare("cputype") == 0)
2793 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002794 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002795 }
2796 else if (name.compare("cpusubtype") == 0)
2797 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002798 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molenda89c37492014-01-27 22:23:20 +00002799 }
2800 else if (name.compare("vendor") == 0)
2801 {
2802 vendor = value;
2803 }
2804 else if (name.compare("ostype") == 0)
2805 {
2806 os_type = value;
2807 }
2808 }
2809
2810 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty())
2811 {
2812 if (vendor == "apple")
2813 {
2814 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub);
2815 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor));
2816 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type));
2817 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002818 }
2819
2820 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
2821 return true;
2822 }
2823 return false;
2824}
2825
2826bool
Greg Clayton8b82f082011-04-12 05:54:46 +00002827GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00002828{
2829 process_info.Clear();
2830
2831 if (m_supports_qProcessInfoPID)
2832 {
2833 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00002834 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002835 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002836 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002837 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00002838 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002839 return DecodeProcessInfoResponse (response, process_info);
2840 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002841 else
2842 {
2843 m_supports_qProcessInfoPID = false;
2844 return false;
2845 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002846 }
2847 return false;
2848}
2849
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002850bool
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002851GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002852{
Todd Fiala3daa1762014-09-15 16:01:29 +00002853 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
2854
Oleksiy Vyalov1ef7b2c2015-02-04 23:19:15 +00002855 if (allow_lazy)
2856 {
2857 if (m_qProcessInfo_is_valid == eLazyBoolYes)
2858 return true;
2859 if (m_qProcessInfo_is_valid == eLazyBoolNo)
2860 return false;
2861 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002862
2863 GetHostInfo ();
2864
2865 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002866 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success)
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002867 {
2868 if (response.IsNormalResponse())
2869 {
2870 std::string name;
2871 std::string value;
2872 uint32_t cpu = LLDB_INVALID_CPUTYPE;
2873 uint32_t sub = 0;
2874 std::string arch_name;
2875 std::string os_name;
2876 std::string vendor_name;
2877 std::string triple;
2878 uint32_t pointer_byte_size = 0;
2879 StringExtractor extractor;
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002880 ByteOrder byte_order = eByteOrderInvalid;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002881 uint32_t num_keys_decoded = 0;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002882 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002883 while (response.GetNameColonValue(name, value))
2884 {
2885 if (name.compare("cputype") == 0)
2886 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002887 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002888 if (cpu != LLDB_INVALID_CPUTYPE)
2889 ++num_keys_decoded;
2890 }
2891 else if (name.compare("cpusubtype") == 0)
2892 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002893 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002894 if (sub != 0)
2895 ++num_keys_decoded;
2896 }
Todd Fialac540dd02014-08-26 18:21:02 +00002897 else if (name.compare("triple") == 0)
2898 {
Greg Clayton44272a42014-09-18 00:18:32 +00002899 StringExtractor extractor;
2900 extractor.GetStringRef().swap(value);
2901 extractor.SetFilePos(0);
2902 extractor.GetHexByteString (triple);
Todd Fialac540dd02014-08-26 18:21:02 +00002903 ++num_keys_decoded;
2904 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002905 else if (name.compare("ostype") == 0)
2906 {
2907 os_name.swap (value);
2908 ++num_keys_decoded;
2909 }
2910 else if (name.compare("vendor") == 0)
2911 {
2912 vendor_name.swap(value);
2913 ++num_keys_decoded;
2914 }
2915 else if (name.compare("endian") == 0)
2916 {
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002917 ++num_keys_decoded;
2918 if (value.compare("little") == 0)
2919 byte_order = eByteOrderLittle;
2920 else if (value.compare("big") == 0)
2921 byte_order = eByteOrderBig;
2922 else if (value.compare("pdp") == 0)
2923 byte_order = eByteOrderPDP;
2924 else
2925 --num_keys_decoded;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002926 }
2927 else if (name.compare("ptrsize") == 0)
2928 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002929 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16);
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002930 if (pointer_byte_size != 0)
2931 ++num_keys_decoded;
2932 }
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002933 else if (name.compare("pid") == 0)
2934 {
Vince Harron5275aaa2015-01-15 20:08:35 +00002935 pid = StringConvert::ToUInt64(value.c_str(), 0, 16);
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002936 if (pid != LLDB_INVALID_PROCESS_ID)
2937 ++num_keys_decoded;
2938 }
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002939 }
2940 if (num_keys_decoded > 0)
2941 m_qProcessInfo_is_valid = eLazyBoolYes;
Todd Fiala9f72b3a2014-05-07 19:28:21 +00002942 if (pid != LLDB_INVALID_PROCESS_ID)
2943 {
2944 m_curr_pid_is_valid = eLazyBoolYes;
2945 m_curr_pid = pid;
2946 }
Todd Fialac540dd02014-08-26 18:21:02 +00002947
2948 // Set the ArchSpec from the triple if we have it.
2949 if (!triple.empty ())
2950 {
2951 m_process_arch.SetTriple (triple.c_str ());
2952 if (pointer_byte_size)
2953 {
2954 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2955 }
2956 }
2957 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002958 {
Todd Fiala3daa1762014-09-15 16:01:29 +00002959 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name);
2960
2961 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat);
2962 switch (triple.getObjectFormat()) {
2963 case llvm::Triple::MachO:
2964 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
2965 break;
2966 case llvm::Triple::ELF:
2967 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub);
2968 break;
2969 case llvm::Triple::COFF:
2970 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub);
2971 break;
2972 case llvm::Triple::UnknownObjectFormat:
2973 if (log)
2974 log->Printf("error: failed to determine target architecture");
2975 return false;
2976 }
2977
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002978 if (pointer_byte_size)
2979 {
2980 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
2981 }
Todd Fiala5c9d5bf2014-09-15 15:31:11 +00002982 if (byte_order != eByteOrderInvalid)
2983 {
2984 assert (byte_order == m_process_arch.GetByteOrder());
2985 }
Todd Fiala0cc371c2014-09-05 14:56:13 +00002986 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
Greg Clayton7ab7f892014-05-29 21:33:45 +00002987 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002988 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
2989 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002990 }
Greg Clayton7ab7f892014-05-29 21:33:45 +00002991 return true;
Jason Molendaf17b5ac2012-12-19 02:54:03 +00002992 }
2993 }
2994 else
2995 {
2996 m_qProcessInfo_is_valid = eLazyBoolNo;
2997 }
2998
2999 return false;
3000}
3001
3002
Greg Clayton32e0a752011-03-30 18:16:51 +00003003uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00003004GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
3005 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00003006{
3007 process_infos.Clear();
3008
3009 if (m_supports_qfProcessInfo)
3010 {
3011 StreamString packet;
3012 packet.PutCString ("qfProcessInfo");
3013 if (!match_info.MatchAllProcesses())
3014 {
3015 packet.PutChar (':');
3016 const char *name = match_info.GetProcessInfo().GetName();
3017 bool has_name_match = false;
3018 if (name && name[0])
3019 {
3020 has_name_match = true;
3021 NameMatchType name_match_type = match_info.GetNameMatchType();
3022 switch (name_match_type)
3023 {
3024 case eNameMatchIgnore:
3025 has_name_match = false;
3026 break;
3027
3028 case eNameMatchEquals:
3029 packet.PutCString ("name_match:equals;");
3030 break;
3031
3032 case eNameMatchContains:
3033 packet.PutCString ("name_match:contains;");
3034 break;
3035
3036 case eNameMatchStartsWith:
3037 packet.PutCString ("name_match:starts_with;");
3038 break;
3039
3040 case eNameMatchEndsWith:
3041 packet.PutCString ("name_match:ends_with;");
3042 break;
3043
3044 case eNameMatchRegularExpression:
3045 packet.PutCString ("name_match:regex;");
3046 break;
3047 }
3048 if (has_name_match)
3049 {
3050 packet.PutCString ("name:");
3051 packet.PutBytesAsRawHex8(name, ::strlen(name));
3052 packet.PutChar (';');
3053 }
3054 }
3055
3056 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00003057 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00003058 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00003059 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00003060 if (match_info.GetProcessInfo().UserIDIsValid())
3061 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
3062 if (match_info.GetProcessInfo().GroupIDIsValid())
3063 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00003064 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
3065 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
3066 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3067 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
3068 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
3069 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
3070 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
3071 {
3072 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
3073 const llvm::Triple &triple = match_arch.GetTriple();
3074 packet.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00003075 packet.PutCString(triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00003076 packet.PutChar (';');
3077 }
3078 }
3079 StringExtractorGDBRemote response;
Siva Chandra8fd94c92015-05-20 00:30:31 +00003080 // Increase timeout as the first qfProcessInfo packet takes a long time
3081 // on Android. The value of 1min was arrived at empirically.
3082 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60);
Greg Clayton3dedae12013-12-06 21:45:27 +00003083 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003084 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003085 do
3086 {
Greg Clayton8b82f082011-04-12 05:54:46 +00003087 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00003088 if (!DecodeProcessInfoResponse (response, process_info))
3089 break;
3090 process_infos.Append(process_info);
3091 response.GetStringRef().clear();
3092 response.SetFilePos(0);
Greg Clayton3dedae12013-12-06 21:45:27 +00003093 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success);
Greg Clayton32e0a752011-03-30 18:16:51 +00003094 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003095 else
3096 {
3097 m_supports_qfProcessInfo = false;
3098 return 0;
3099 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003100 }
3101 return process_infos.GetSize();
3102
3103}
3104
3105bool
3106GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
3107{
3108 if (m_supports_qUserName)
3109 {
3110 char packet[32];
3111 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003112 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003113 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003114 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003115 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003116 if (response.IsNormalResponse())
3117 {
3118 // Make sure we parsed the right number of characters. The response is
3119 // the hex encoded user name and should make up the entire packet.
3120 // If there are any non-hex ASCII bytes, the length won't match below..
3121 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3122 return true;
3123 }
3124 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003125 else
3126 {
3127 m_supports_qUserName = false;
3128 return false;
3129 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003130 }
3131 return false;
3132
3133}
3134
3135bool
3136GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
3137{
3138 if (m_supports_qGroupName)
3139 {
3140 char packet[32];
3141 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003142 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00003143 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003144 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton32e0a752011-03-30 18:16:51 +00003145 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003146 if (response.IsNormalResponse())
3147 {
3148 // Make sure we parsed the right number of characters. The response is
3149 // the hex encoded group name and should make up the entire packet.
3150 // If there are any non-hex ASCII bytes, the length won't match below..
3151 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
3152 return true;
3153 }
3154 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003155 else
3156 {
3157 m_supports_qGroupName = false;
3158 return false;
3159 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003160 }
3161 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003162}
Greg Clayton32e0a752011-03-30 18:16:51 +00003163
Ewan Crawford78baa192015-05-13 09:18:18 +00003164bool
3165GDBRemoteCommunicationClient::SetNonStopMode (const bool enable)
3166{
3167 // Form non-stop packet request
3168 char packet[32];
3169 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable);
3170 assert(packet_len < (int)sizeof(packet));
3171
3172 StringExtractorGDBRemote response;
3173 // Send to target
3174 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
3175 if (response.IsOKResponse())
3176 return true;
3177
3178 // Failed or not supported
3179 return false;
3180
3181}
3182
Greg Claytone034a042015-05-21 20:52:06 +00003183static void
3184MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size)
3185{
3186 packet.Clear();
3187 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3188 uint32_t bytes_left = send_size;
3189 while (bytes_left > 0)
3190 {
3191 if (bytes_left >= 26)
3192 {
3193 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3194 bytes_left -= 26;
3195 }
3196 else
3197 {
3198 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3199 bytes_left = 0;
3200 }
3201 }
3202}
3203
3204template<typename T>
3205T calculate_standard_deviation(const std::vector<T> &v)
3206{
3207 T sum = std::accumulate(std::begin(v), std::end(v), T(0));
3208 T mean = sum / (T)v.size();
3209 T accum = T(0);
3210 std::for_each (std::begin(v), std::end(v), [&](const T d) {
3211 T delta = d - mean;
3212 accum += delta * delta;
3213 });
3214
3215 T stdev = sqrt(accum / (v.size()-1));
3216 return stdev;
3217}
3218
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003219void
Greg Claytone034a042015-05-21 20:52:06 +00003220GDBRemoteCommunicationClient::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 +00003221{
3222 uint32_t i;
3223 TimeValue start_time, end_time;
3224 uint64_t total_time_nsec;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003225 if (SendSpeedTestPacket (0, 0))
3226 {
Greg Claytone034a042015-05-21 20:52:06 +00003227 StreamString packet;
3228 if (json)
3229 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets);
3230 else
3231 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets);
3232 strm.Flush();
Greg Clayton700e5082014-02-21 19:11:28 +00003233
Greg Claytone034a042015-05-21 20:52:06 +00003234 uint32_t result_idx = 0;
3235 uint32_t send_size;
3236 std::vector<float> packet_times;
3237
3238 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4)
3239 {
3240 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4)
3241 {
3242 MakeSpeedTestPacket (packet, send_size, recv_size);
3243
3244 packet_times.clear();
3245 // Test how long it takes to send 'num_packets' packets
Greg Clayton700e5082014-02-21 19:11:28 +00003246 start_time = TimeValue::Now();
Greg Claytone034a042015-05-21 20:52:06 +00003247 for (i=0; i<num_packets; ++i)
Greg Clayton700e5082014-02-21 19:11:28 +00003248 {
Greg Claytone034a042015-05-21 20:52:06 +00003249 TimeValue packet_start_time = TimeValue::Now();
3250 StringExtractorGDBRemote response;
3251 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3252 TimeValue packet_end_time = TimeValue::Now();
3253 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970();
3254 packet_times.push_back((float)packet_time_nsec);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003255 }
3256 end_time = TimeValue::Now();
3257 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Greg Claytone034a042015-05-21 20:52:06 +00003258
3259 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3260 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3261 float average_ms_per_packet = total_ms / num_packets;
3262 const float standard_deviation = calculate_standard_deviation<float>(packet_times);
3263 if (json)
Greg Clayton700e5082014-02-21 19:11:28 +00003264 {
Greg Claytone034a042015-05-21 20:52:06 +00003265 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);
3266 ++result_idx;
Greg Clayton700e5082014-02-21 19:11:28 +00003267 }
3268 else
3269 {
Greg Claytone034a042015-05-21 20:52:06 +00003270 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",
3271 send_size,
3272 recv_size,
3273 total_time_nsec / TimeValue::NanoSecPerSec,
3274 total_time_nsec % TimeValue::NanoSecPerSec,
3275 packets_per_second,
3276 average_ms_per_packet,
3277 standard_deviation/(float)TimeValue::NanoSecPerMilliSec);
Greg Clayton700e5082014-02-21 19:11:28 +00003278 }
Greg Claytone034a042015-05-21 20:52:06 +00003279 strm.Flush();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003280 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003281 }
Greg Claytone034a042015-05-21 20:52:06 +00003282
3283 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes
3284
3285 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f);
3286 if (json)
3287 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount);
3288 else
3289 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb);
3290 strm.Flush();
3291 send_size = 0;
3292 result_idx = 0;
3293 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2)
3294 {
3295 MakeSpeedTestPacket (packet, send_size, recv_size);
3296
3297 // If we have a receive size, test how long it takes to receive 4MB of data
3298 if (recv_size > 0)
3299 {
3300 start_time = TimeValue::Now();
3301 uint32_t bytes_read = 0;
3302 uint32_t packet_count = 0;
3303 while (bytes_read < k_recv_amount)
3304 {
3305 StringExtractorGDBRemote response;
3306 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false);
3307 bytes_read += recv_size;
3308 ++packet_count;
3309 }
3310 end_time = TimeValue::Now();
3311 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
3312 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0);
3313 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
3314 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec;
3315 float average_ms_per_packet = total_ms / packet_count;
3316
3317 if (json)
3318 {
3319 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);
3320 ++result_idx;
3321 }
3322 else
3323 {
3324 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",
3325 send_size,
3326 recv_size,
3327 packet_count,
3328 k_recv_amount_mb,
3329 total_time_nsec / TimeValue::NanoSecPerSec,
3330 total_time_nsec % TimeValue::NanoSecPerSec,
3331 mb_second,
3332 packets_per_second,
3333 average_ms_per_packet);
3334 }
3335 strm.Flush();
3336 }
3337 }
3338 if (json)
3339 strm.Printf("\n ]\n }\n}\n");
3340 else
3341 strm.EOL();
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003342 }
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00003343}
3344
3345bool
3346GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
3347{
3348 StreamString packet;
3349 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
3350 uint32_t bytes_left = send_size;
3351 while (bytes_left > 0)
3352 {
3353 if (bytes_left >= 26)
3354 {
3355 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
3356 bytes_left -= 26;
3357 }
3358 else
3359 {
3360 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
3361 bytes_left = 0;
3362 }
3363 }
3364
3365 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003366 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success;
Greg Clayton32e0a752011-03-30 18:16:51 +00003367}
Greg Clayton8b82f082011-04-12 05:54:46 +00003368
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003369bool
3370GDBRemoteCommunicationClient::LaunchGDBServer (const char *remote_accept_hostname,
3371 lldb::pid_t &pid,
3372 uint16_t &port,
3373 std::string &socket_name)
Greg Clayton8b82f082011-04-12 05:54:46 +00003374{
Daniel Maleae0f8f572013-08-26 23:57:52 +00003375 pid = LLDB_INVALID_PROCESS_ID;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003376 port = 0;
3377 socket_name.clear();
3378
Greg Clayton8b82f082011-04-12 05:54:46 +00003379 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003380 StreamString stream;
Greg Clayton29b8fc42013-11-21 01:44:58 +00003381 stream.PutCString("qLaunchGDBServer;");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003382 std::string hostname;
Greg Claytondbf04572013-12-04 19:40:33 +00003383 if (remote_accept_hostname && remote_accept_hostname[0])
3384 hostname = remote_accept_hostname;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003385 else
3386 {
Zachary Turner97a14e62014-08-19 17:18:29 +00003387 if (HostInfo::GetHostname(hostname))
Greg Claytondbf04572013-12-04 19:40:33 +00003388 {
3389 // Make the GDB server we launch only accept connections from this host
3390 stream.Printf("host:%s;", hostname.c_str());
3391 }
3392 else
3393 {
3394 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
3395 stream.Printf("host:*;");
3396 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003397 }
3398 const char *packet = stream.GetData();
3399 int packet_len = stream.GetSize();
3400
Vince Harron1b5a74e2015-01-21 22:42:49 +00003401 // give the process a few seconds to startup
Tamas Berghammer912800c2015-02-24 10:23:39 +00003402 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003403
Tamas Berghammer912800c2015-02-24 10:23:39 +00003404 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003405 {
3406 std::string name;
3407 std::string value;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003408 StringExtractor extractor;
Greg Clayton8b82f082011-04-12 05:54:46 +00003409 while (response.GetNameColonValue(name, value))
3410 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00003411 if (name.compare("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003412 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003413 else if (name.compare("pid") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00003414 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003415 else if (name.compare("socket_name") == 0)
3416 {
3417 extractor.GetStringRef().swap(value);
3418 extractor.SetFilePos(0);
3419 extractor.GetHexByteString(value);
3420
3421 socket_name = value;
3422 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003423 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003424 return true;
Greg Clayton8b82f082011-04-12 05:54:46 +00003425 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00003426 return false;
Greg Clayton8b82f082011-04-12 05:54:46 +00003427}
3428
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00003429size_t
3430GDBRemoteCommunicationClient::QueryGDBServer (std::vector<std::pair<uint16_t, std::string>>& connection_urls)
3431{
3432 connection_urls.clear();
3433
3434 StringExtractorGDBRemote response;
3435 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) != PacketResult::Success)
3436 return 0;
3437
3438 StructuredData::ObjectSP data = StructuredData::ParseJSON(response.GetStringRef());
3439 if (!data)
3440 return 0;
3441
3442 StructuredData::Array* array = data->GetAsArray();
3443 if (!array)
3444 return 0;
3445
3446 for (size_t i = 0, count = array->GetSize(); i < count; ++i)
3447 {
3448 StructuredData::Dictionary* element = nullptr;
3449 if (!array->GetItemAtIndexAsDictionary(i, element))
3450 continue;
3451
3452 uint16_t port = 0;
3453 if (StructuredData::ObjectSP port_osp = element->GetValueForKey(llvm::StringRef("port")))
3454 port = port_osp->GetIntegerValue(0);
3455
3456 std::string socket_name;
3457 if (StructuredData::ObjectSP socket_name_osp = element->GetValueForKey(llvm::StringRef("socket_name")))
3458 socket_name = socket_name_osp->GetStringValue();
3459
3460 if (port != 0 || !socket_name.empty())
3461 connection_urls.emplace_back(port, socket_name);
3462 }
3463 return connection_urls.size();
3464}
3465
Greg Clayton8b82f082011-04-12 05:54:46 +00003466bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00003467GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
3468{
3469 StreamString stream;
3470 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
3471 const char *packet = stream.GetData();
3472 int packet_len = stream.GetSize();
Sylvestre Ledrufd654c42013-10-06 09:51:02 +00003473
Daniel Maleae0f8f572013-08-26 23:57:52 +00003474 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003475 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003476 {
3477 if (response.IsOKResponse())
3478 return true;
3479 }
3480 return false;
3481}
3482
3483bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003484GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003485{
3486 if (m_curr_tid == tid)
3487 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003488
Greg Clayton8b82f082011-04-12 05:54:46 +00003489 char packet[32];
3490 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003491 if (tid == UINT64_MAX)
3492 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003493 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003494 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003495 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003496 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003497 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003498 {
3499 if (response.IsOKResponse())
3500 {
3501 m_curr_tid = tid;
3502 return true;
3503 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003504
3505 /*
3506 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hg packet.
3507 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3508 * give us pid and/or tid. Assume pid=tid=1 in such cases.
3509 */
3510 if (response.IsUnsupportedResponse() && IsConnected())
3511 {
3512 m_curr_tid = 1;
3513 return true;
3514 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003515 }
3516 return false;
3517}
3518
3519bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00003520GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00003521{
3522 if (m_curr_tid_run == tid)
3523 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003524
Greg Clayton8b82f082011-04-12 05:54:46 +00003525 char packet[32];
3526 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00003527 if (tid == UINT64_MAX)
3528 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00003529 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00003530 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
3531
Andy Gibbsa297a972013-06-19 19:04:53 +00003532 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003533 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003534 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003535 {
3536 if (response.IsOKResponse())
3537 {
3538 m_curr_tid_run = tid;
3539 return true;
3540 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003541
3542 /*
3543 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hc packet.
3544 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can
3545 * give us pid and/or tid. Assume pid=tid=1 in such cases.
3546 */
3547 if (response.IsUnsupportedResponse() && IsConnected())
3548 {
3549 m_curr_tid_run = 1;
3550 return true;
3551 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003552 }
3553 return false;
3554}
3555
3556bool
3557GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
3558{
Greg Clayton3dedae12013-12-06 21:45:27 +00003559 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003560 return response.IsNormalResponse();
3561 return false;
3562}
3563
3564bool
Greg Claytonf402f782012-10-13 02:11:55 +00003565GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00003566{
3567 if (m_supports_qThreadStopInfo)
3568 {
3569 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00003570 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00003571 assert (packet_len < (int)sizeof(packet));
Greg Clayton3dedae12013-12-06 21:45:27 +00003572 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003573 {
Greg Claytonef8180a2013-10-15 00:14:28 +00003574 if (response.IsUnsupportedResponse())
3575 m_supports_qThreadStopInfo = false;
3576 else if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003577 return true;
3578 else
3579 return false;
3580 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003581 else
3582 {
3583 m_supports_qThreadStopInfo = false;
3584 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003585 }
Greg Clayton8b82f082011-04-12 05:54:46 +00003586 return false;
3587}
3588
3589
3590uint8_t
3591GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
3592{
Todd Fiala616b8272014-10-09 00:55:04 +00003593 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3594 if (log)
3595 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64,
3596 __FUNCTION__, insert ? "add" : "remove", addr);
3597
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003598 // Check if the stub is known not to support this breakpoint type
3599 if (!SupportsGDBStoppointPacket(type))
3600 return UINT8_MAX;
3601 // Construct the breakpoint packet
Greg Clayton8b82f082011-04-12 05:54:46 +00003602 char packet[64];
3603 const int packet_len = ::snprintf (packet,
3604 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00003605 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00003606 insert ? 'Z' : 'z',
3607 type,
3608 addr,
3609 length);
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003610 // Check we haven't overwritten the end of the packet buffer
Andy Gibbsa297a972013-06-19 19:04:53 +00003611 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00003612 StringExtractorGDBRemote response;
Greg Clayton830c81d2016-04-01 00:41:29 +00003613 // Make sure the response is either "OK", "EXX" where XX are two hex digits, or "" (unsupported)
3614 response.SetResponseValidatorToOKErrorNotSupported();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003615 // Try to send the breakpoint packet, and check that it was correctly sent
Greg Clayton3dedae12013-12-06 21:45:27 +00003616 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success)
Greg Clayton8b82f082011-04-12 05:54:46 +00003617 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003618 // Receive and OK packet when the breakpoint successfully placed
Greg Clayton8b82f082011-04-12 05:54:46 +00003619 if (response.IsOKResponse())
3620 return 0;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003621
3622 // Error while setting breakpoint, send back specific error
3623 if (response.IsErrorResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00003624 return response.GetError();
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003625
3626 // Empty packet informs us that breakpoint is not supported
3627 if (response.IsUnsupportedResponse())
Greg Clayton17a0cb62011-05-15 23:46:54 +00003628 {
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003629 // Disable this breakpoint type since it is unsupported
3630 switch (type)
3631 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00003632 case eBreakpointSoftware: m_supports_z0 = false; break;
3633 case eBreakpointHardware: m_supports_z1 = false; break;
3634 case eWatchpointWrite: m_supports_z2 = false; break;
3635 case eWatchpointRead: m_supports_z3 = false; break;
3636 case eWatchpointReadWrite: m_supports_z4 = false; break;
Chaoren Lin0be9ebb2015-02-03 01:51:50 +00003637 case eStoppointInvalid: return UINT8_MAX;
Deepak Panickalb98a2bb2014-02-24 11:50:46 +00003638 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00003639 }
3640 }
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003641 // Signal generic failure
Greg Clayton8b82f082011-04-12 05:54:46 +00003642 return UINT8_MAX;
3643}
Greg Claytonadc00cb2011-05-20 23:38:13 +00003644
3645size_t
3646GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
3647 bool &sequence_mutex_unavailable)
3648{
3649 Mutex::Locker locker;
3650 thread_ids.clear();
3651
Jim Ingham4ceb9282012-06-08 22:50:40 +00003652 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003653 {
3654 sequence_mutex_unavailable = false;
3655 StringExtractorGDBRemote response;
3656
Greg Clayton3dedae12013-12-06 21:45:27 +00003657 PacketResult packet_result;
3658 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response);
3659 packet_result == PacketResult::Success && response.IsNormalResponse();
3660 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response))
Greg Claytonadc00cb2011-05-20 23:38:13 +00003661 {
3662 char ch = response.GetChar();
3663 if (ch == 'l')
3664 break;
3665 if (ch == 'm')
3666 {
3667 do
3668 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00003669 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00003670
3671 if (tid != LLDB_INVALID_THREAD_ID)
3672 {
3673 thread_ids.push_back (tid);
3674 }
3675 ch = response.GetChar(); // Skip the command separator
3676 } while (ch == ','); // Make sure we got a comma separator
3677 }
3678 }
Jaydeep Patil630dd7f2015-09-18 05:32:54 +00003679
3680 /*
3681 * Connected bare-iron target (like YAMON gdb-stub) may not have support for
3682 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet could
3683 * be as simple as 'S05'. There is no packet which can give us pid and/or tid.
3684 * Assume pid=tid=1 in such cases.
3685 */
3686 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 && IsConnected())
3687 {
3688 thread_ids.push_back (1);
3689 }
Greg Claytonadc00cb2011-05-20 23:38:13 +00003690 }
3691 else
3692 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00003693#if defined (LLDB_CONFIGURATION_DEBUG)
3694 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
3695#else
Greg Clayton5160ce52013-03-27 23:08:40 +00003696 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00003697 if (log)
3698 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00003699#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00003700 sequence_mutex_unavailable = true;
3701 }
3702 return thread_ids.size();
3703}
Greg Clayton37a0a242012-04-11 00:24:49 +00003704
3705lldb::addr_t
3706GDBRemoteCommunicationClient::GetShlibInfoAddr()
3707{
3708 if (!IsRunning())
3709 {
3710 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003711 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success)
Greg Clayton37a0a242012-04-11 00:24:49 +00003712 {
3713 if (response.IsNormalResponse())
3714 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3715 }
3716 }
3717 return LLDB_INVALID_ADDRESS;
3718}
3719
Daniel Maleae0f8f572013-08-26 23:57:52 +00003720lldb_private::Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003721GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL
3722 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
3723 int *status_ptr, // Pass NULL if you don't want the process exit status
3724 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
3725 std::string *command_output, // Pass NULL if you don't want the command output
3726 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
Daniel Maleae0f8f572013-08-26 23:57:52 +00003727{
3728 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003729 stream.PutCString("qPlatform_shell:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003730 stream.PutBytesAsRawHex8(command, strlen(command));
3731 stream.PutChar(',');
3732 stream.PutHex32(timeout_sec);
Chaoren Lind3173f32015-05-29 19:52:29 +00003733 if (working_dir)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003734 {
Chaoren Lind3173f32015-05-29 19:52:29 +00003735 std::string path{working_dir.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003736 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003737 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003738 }
3739 const char *packet = stream.GetData();
3740 int packet_len = stream.GetSize();
3741 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003742 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003743 {
3744 if (response.GetChar() != 'F')
3745 return Error("malformed reply");
3746 if (response.GetChar() != ',')
3747 return Error("malformed reply");
3748 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
3749 if (exitcode == UINT32_MAX)
3750 return Error("unable to run remote process");
3751 else if (status_ptr)
3752 *status_ptr = exitcode;
3753 if (response.GetChar() != ',')
3754 return Error("malformed reply");
3755 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
3756 if (signo_ptr)
3757 *signo_ptr = signo;
3758 if (response.GetChar() != ',')
3759 return Error("malformed reply");
3760 std::string output;
3761 response.GetEscapedBinaryData(output);
3762 if (command_output)
3763 command_output->assign(output);
3764 return Error();
3765 }
3766 return Error("unable to send packet");
3767}
3768
Greg Claytonfbb76342013-11-20 21:07:01 +00003769Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003770GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec,
3771 uint32_t file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003772{
Chaoren Lind3173f32015-05-29 19:52:29 +00003773 std::string path{file_spec.GetPath(false)};
Daniel Maleae0f8f572013-08-26 23:57:52 +00003774 lldb_private::StreamString stream;
Greg Claytonfbb76342013-11-20 21:07:01 +00003775 stream.PutCString("qPlatform_mkdir:");
3776 stream.PutHex32(file_permissions);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003777 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003778 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003779 const char *packet = stream.GetData();
3780 int packet_len = stream.GetSize();
3781 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003782
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003783 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3784 return Error("failed to send '%s' packet", packet);
3785
3786 if (response.GetChar() != 'F')
3787 return Error("invalid response to '%s' packet", packet);
3788
3789 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003790}
3791
Greg Claytonfbb76342013-11-20 21:07:01 +00003792Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003793GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec,
3794 uint32_t file_permissions)
Greg Claytonfbb76342013-11-20 21:07:01 +00003795{
Chaoren Lind3173f32015-05-29 19:52:29 +00003796 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003797 lldb_private::StreamString stream;
3798 stream.PutCString("qPlatform_chmod:");
3799 stream.PutHex32(file_permissions);
3800 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00003801 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00003802 const char *packet = stream.GetData();
3803 int packet_len = stream.GetSize();
3804 StringExtractorGDBRemote response;
Tamas Berghammer0f86b742015-02-23 11:03:08 +00003805
3806 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success)
3807 return Error("failed to send '%s' packet", packet);
3808
3809 if (response.GetChar() != 'F')
3810 return Error("invalid response to '%s' packet", packet);
3811
Chaoren Lince36c4c2015-05-05 18:43:19 +00003812 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX);
Greg Claytonfbb76342013-11-20 21:07:01 +00003813}
3814
Daniel Maleae0f8f572013-08-26 23:57:52 +00003815static uint64_t
3816ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
3817 uint64_t fail_result,
3818 Error &error)
3819{
3820 response.SetFilePos(0);
3821 if (response.GetChar() != 'F')
3822 return fail_result;
3823 int32_t result = response.GetS32 (-2);
3824 if (result == -2)
3825 return fail_result;
3826 if (response.GetChar() == ',')
3827 {
3828 int result_errno = response.GetS32 (-2);
3829 if (result_errno != -2)
3830 error.SetError(result_errno, eErrorTypePOSIX);
3831 else
3832 error.SetError(-1, eErrorTypeGeneric);
3833 }
3834 else
3835 error.Clear();
3836 return result;
3837}
3838lldb::user_id_t
3839GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
3840 uint32_t flags,
3841 mode_t mode,
3842 Error &error)
3843{
Chaoren Lind3173f32015-05-29 19:52:29 +00003844 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003845 lldb_private::StreamString stream;
3846 stream.PutCString("vFile:open:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003847 if (path.empty())
3848 return UINT64_MAX;
3849 stream.PutCStringAsRawHex8(path.c_str());
3850 stream.PutChar(',');
Robert Flackebc56092015-03-18 13:55:48 +00003851 stream.PutHex32(flags);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003852 stream.PutChar(',');
3853 stream.PutHex32(mode);
3854 const char* packet = stream.GetData();
3855 int packet_len = stream.GetSize();
3856 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003857 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003858 {
3859 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
3860 }
3861 return UINT64_MAX;
3862}
3863
3864bool
3865GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
3866 Error &error)
3867{
3868 lldb_private::StreamString stream;
3869 stream.Printf("vFile:close:%i", (int)fd);
3870 const char* packet = stream.GetData();
3871 int packet_len = stream.GetSize();
3872 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003873 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003874 {
3875 return ParseHostIOPacketResponse (response, -1, error) == 0;
3876 }
Deepak Panickald66b50c2013-10-22 12:27:43 +00003877 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003878}
3879
3880// Extension of host I/O packets to get the file size.
3881lldb::user_id_t
3882GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
3883{
Chaoren Lind3173f32015-05-29 19:52:29 +00003884 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00003885 lldb_private::StreamString stream;
3886 stream.PutCString("vFile:size:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00003887 stream.PutCStringAsRawHex8(path.c_str());
3888 const char* packet = stream.GetData();
3889 int packet_len = stream.GetSize();
3890 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003891 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003892 {
3893 if (response.GetChar() != 'F')
3894 return UINT64_MAX;
3895 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
3896 return retcode;
3897 }
3898 return UINT64_MAX;
3899}
3900
Greg Claytonfbb76342013-11-20 21:07:01 +00003901Error
Chaoren Lind3173f32015-05-29 19:52:29 +00003902GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec,
3903 uint32_t &file_permissions)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003904{
Chaoren Lind3173f32015-05-29 19:52:29 +00003905 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00003906 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003907 lldb_private::StreamString stream;
3908 stream.PutCString("vFile:mode:");
Chaoren Lind3173f32015-05-29 19:52:29 +00003909 stream.PutCStringAsRawHex8(path.c_str());
Daniel Maleae0f8f572013-08-26 23:57:52 +00003910 const char* packet = stream.GetData();
3911 int packet_len = stream.GetSize();
3912 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003913 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003914 {
3915 if (response.GetChar() != 'F')
3916 {
3917 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
Daniel Maleae0f8f572013-08-26 23:57:52 +00003918 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003919 else
Daniel Maleae0f8f572013-08-26 23:57:52 +00003920 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003921 const uint32_t mode = response.GetS32(-1);
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00003922 if (static_cast<int32_t>(mode) == -1)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003923 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003924 if (response.GetChar() == ',')
3925 {
3926 int response_errno = response.GetS32(-1);
3927 if (response_errno > 0)
3928 error.SetError(response_errno, lldb::eErrorTypePOSIX);
3929 else
3930 error.SetErrorToGenericError();
3931 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003932 else
3933 error.SetErrorToGenericError();
3934 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003935 else
3936 {
3937 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO);
3938 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003939 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00003940 }
3941 else
3942 {
3943 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
3944 }
Greg Claytonfbb76342013-11-20 21:07:01 +00003945 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00003946}
3947
3948uint64_t
3949GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
3950 uint64_t offset,
3951 void *dst,
3952 uint64_t dst_len,
3953 Error &error)
3954{
3955 lldb_private::StreamString stream;
3956 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
3957 const char* packet = stream.GetData();
3958 int packet_len = stream.GetSize();
3959 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003960 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00003961 {
3962 if (response.GetChar() != 'F')
3963 return 0;
3964 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
3965 if (retcode == UINT32_MAX)
3966 return retcode;
3967 const char next = (response.Peek() ? *response.Peek() : 0);
3968 if (next == ',')
3969 return 0;
3970 if (next == ';')
3971 {
3972 response.GetChar(); // skip the semicolon
3973 std::string buffer;
3974 if (response.GetEscapedBinaryData(buffer))
3975 {
3976 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
3977 if (data_to_write > 0)
3978 memcpy(dst, &buffer[0], data_to_write);
3979 return data_to_write;
3980 }
3981 }
3982 }
3983 return 0;
3984}
3985
3986uint64_t
3987GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
3988 uint64_t offset,
3989 const void* src,
3990 uint64_t src_len,
3991 Error &error)
3992{
3993 lldb_private::StreamGDBRemote stream;
3994 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
3995 stream.PutEscapedBytes(src, src_len);
3996 const char* packet = stream.GetData();
3997 int packet_len = stream.GetSize();
3998 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00003999 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00004000 {
4001 if (response.GetChar() != 'F')
4002 {
4003 error.SetErrorStringWithFormat("write file failed");
4004 return 0;
4005 }
4006 uint64_t bytes_written = response.GetU64(UINT64_MAX);
4007 if (bytes_written == UINT64_MAX)
4008 {
4009 error.SetErrorToGenericError();
4010 if (response.GetChar() == ',')
4011 {
4012 int response_errno = response.GetS32(-1);
4013 if (response_errno > 0)
4014 error.SetError(response_errno, lldb::eErrorTypePOSIX);
4015 }
4016 return 0;
4017 }
4018 return bytes_written;
4019 }
4020 else
4021 {
4022 error.SetErrorString ("failed to send vFile:pwrite packet");
4023 }
4024 return 0;
4025}
4026
Greg Claytonfbb76342013-11-20 21:07:01 +00004027Error
Chaoren Lind3173f32015-05-29 19:52:29 +00004028GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst)
Greg Claytonfbb76342013-11-20 21:07:01 +00004029{
Chaoren Lind3173f32015-05-29 19:52:29 +00004030 std::string src_path{src.GetPath(false)},
4031 dst_path{dst.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00004032 Error error;
4033 lldb_private::StreamGDBRemote stream;
4034 stream.PutCString("vFile:symlink:");
4035 // the unix symlink() command reverses its parameters where the dst if first,
4036 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00004037 stream.PutCStringAsRawHex8(dst_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00004038 stream.PutChar(',');
Chaoren Lind3173f32015-05-29 19:52:29 +00004039 stream.PutCStringAsRawHex8(src_path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00004040 const char* packet = stream.GetData();
4041 int packet_len = stream.GetSize();
4042 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004043 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00004044 {
4045 if (response.GetChar() == 'F')
4046 {
4047 uint32_t result = response.GetU32(UINT32_MAX);
4048 if (result != 0)
4049 {
4050 error.SetErrorToGenericError();
4051 if (response.GetChar() == ',')
4052 {
4053 int response_errno = response.GetS32(-1);
4054 if (response_errno > 0)
4055 error.SetError(response_errno, lldb::eErrorTypePOSIX);
4056 }
4057 }
4058 }
4059 else
4060 {
4061 // Should have returned with 'F<result>[,<errno>]'
4062 error.SetErrorStringWithFormat("symlink failed");
4063 }
4064 }
4065 else
4066 {
4067 error.SetErrorString ("failed to send vFile:symlink packet");
4068 }
4069 return error;
4070}
4071
4072Error
Chaoren Lind3173f32015-05-29 19:52:29 +00004073GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec)
Greg Claytonfbb76342013-11-20 21:07:01 +00004074{
Chaoren Lind3173f32015-05-29 19:52:29 +00004075 std::string path{file_spec.GetPath(false)};
Greg Claytonfbb76342013-11-20 21:07:01 +00004076 Error error;
4077 lldb_private::StreamGDBRemote stream;
4078 stream.PutCString("vFile:unlink:");
4079 // the unix symlink() command reverses its parameters where the dst if first,
4080 // so we follow suit here
Chaoren Lind3173f32015-05-29 19:52:29 +00004081 stream.PutCStringAsRawHex8(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00004082 const char* packet = stream.GetData();
4083 int packet_len = stream.GetSize();
4084 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004085 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Greg Claytonfbb76342013-11-20 21:07:01 +00004086 {
4087 if (response.GetChar() == 'F')
4088 {
4089 uint32_t result = response.GetU32(UINT32_MAX);
4090 if (result != 0)
4091 {
4092 error.SetErrorToGenericError();
4093 if (response.GetChar() == ',')
4094 {
4095 int response_errno = response.GetS32(-1);
4096 if (response_errno > 0)
4097 error.SetError(response_errno, lldb::eErrorTypePOSIX);
4098 }
4099 }
4100 }
4101 else
4102 {
4103 // Should have returned with 'F<result>[,<errno>]'
4104 error.SetErrorStringWithFormat("unlink failed");
4105 }
4106 }
4107 else
4108 {
4109 error.SetErrorString ("failed to send vFile:unlink packet");
4110 }
4111 return error;
4112}
4113
Daniel Maleae0f8f572013-08-26 23:57:52 +00004114// Extension of host I/O packets to get whether a file exists.
4115bool
4116GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
4117{
Chaoren Lind3173f32015-05-29 19:52:29 +00004118 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00004119 lldb_private::StreamString stream;
4120 stream.PutCString("vFile:exists:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00004121 stream.PutCStringAsRawHex8(path.c_str());
4122 const char* packet = stream.GetData();
4123 int packet_len = stream.GetSize();
4124 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004125 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00004126 {
4127 if (response.GetChar() != 'F')
4128 return false;
4129 if (response.GetChar() != ',')
4130 return false;
4131 bool retcode = (response.GetChar() != '0');
4132 return retcode;
4133 }
4134 return false;
4135}
4136
4137bool
4138GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
4139 uint64_t &high,
4140 uint64_t &low)
4141{
Chaoren Lind3173f32015-05-29 19:52:29 +00004142 std::string path(file_spec.GetPath(false));
Daniel Maleae0f8f572013-08-26 23:57:52 +00004143 lldb_private::StreamString stream;
4144 stream.PutCString("vFile:MD5:");
Daniel Maleae0f8f572013-08-26 23:57:52 +00004145 stream.PutCStringAsRawHex8(path.c_str());
4146 const char* packet = stream.GetData();
4147 int packet_len = stream.GetSize();
4148 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00004149 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success)
Daniel Maleae0f8f572013-08-26 23:57:52 +00004150 {
4151 if (response.GetChar() != 'F')
4152 return false;
4153 if (response.GetChar() != ',')
4154 return false;
4155 if (response.Peek() && *response.Peek() == 'x')
4156 return false;
4157 low = response.GetHexMaxU64(false, UINT64_MAX);
4158 high = response.GetHexMaxU64(false, UINT64_MAX);
4159 return true;
4160 }
4161 return false;
4162}
Greg Claytonf74cf862013-11-13 23:28:31 +00004163
4164bool
Jason Molendaa3329782014-03-29 18:54:20 +00004165GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process)
4166{
4167 // Some targets have issues with g/G packets and we need to avoid using them
4168 if (m_avoid_g_packets == eLazyBoolCalculate)
4169 {
4170 if (process)
4171 {
4172 m_avoid_g_packets = eLazyBoolNo;
4173 const ArchSpec &arch = process->GetTarget().GetArchitecture();
4174 if (arch.IsValid()
4175 && arch.GetTriple().getVendor() == llvm::Triple::Apple
4176 && arch.GetTriple().getOS() == llvm::Triple::IOS
Todd Fialad8eaa172014-07-23 14:37:35 +00004177 && arch.GetTriple().getArch() == llvm::Triple::aarch64)
Jason Molendaa3329782014-03-29 18:54:20 +00004178 {
4179 m_avoid_g_packets = eLazyBoolYes;
4180 uint32_t gdb_server_version = GetGDBServerProgramVersion();
4181 if (gdb_server_version != 0)
4182 {
4183 const char *gdb_server_name = GetGDBServerProgramName();
4184 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0)
4185 {
4186 if (gdb_server_version >= 310)
4187 m_avoid_g_packets = eLazyBoolNo;
4188 }
4189 }
4190 }
4191 }
4192 }
4193 return m_avoid_g_packets == eLazyBoolYes;
4194}
4195
4196bool
Greg Claytonf74cf862013-11-13 23:28:31 +00004197GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response)
4198{
4199 Mutex::Locker locker;
4200 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet."))
4201 {
4202 const bool thread_suffix_supported = GetThreadSuffixSupported();
4203
4204 if (thread_suffix_supported || SetCurrentThread(tid))
4205 {
4206 char packet[64];
4207 int packet_len = 0;
4208 if (thread_suffix_supported)
4209 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid);
4210 else
4211 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg);
4212 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004213 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004214 }
4215 }
4216 return false;
4217
4218}
4219
4220
4221bool
4222GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response)
4223{
4224 Mutex::Locker locker;
4225 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet."))
4226 {
4227 const bool thread_suffix_supported = GetThreadSuffixSupported();
4228
4229 if (thread_suffix_supported || SetCurrentThread(tid))
4230 {
4231 char packet[64];
4232 int packet_len = 0;
4233 // Get all registers in one packet
4234 if (thread_suffix_supported)
4235 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid);
4236 else
4237 packet_len = ::snprintf (packet, sizeof(packet), "g");
4238 assert (packet_len < ((int)sizeof(packet) - 1));
Greg Clayton3dedae12013-12-06 21:45:27 +00004239 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success;
Greg Claytonf74cf862013-11-13 23:28:31 +00004240 }
4241 }
4242 return false;
4243}
4244bool
4245GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id)
4246{
4247 save_id = 0; // Set to invalid save ID
4248 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4249 return false;
4250
4251 m_supports_QSaveRegisterState = eLazyBoolYes;
4252 Mutex::Locker locker;
4253 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState."))
4254 {
4255 const bool thread_suffix_supported = GetThreadSuffixSupported();
4256 if (thread_suffix_supported || SetCurrentThread(tid))
4257 {
4258 char packet[256];
4259 if (thread_suffix_supported)
4260 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid);
4261 else
Ilia K686b1fe2015-02-27 19:43:08 +00004262 ::snprintf(packet, sizeof(packet), "QSaveRegisterState");
Greg Claytonf74cf862013-11-13 23:28:31 +00004263
4264 StringExtractorGDBRemote response;
4265
Greg Clayton3dedae12013-12-06 21:45:27 +00004266 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004267 {
4268 if (response.IsUnsupportedResponse())
4269 {
4270 // This packet isn't supported, don't try calling it again
4271 m_supports_QSaveRegisterState = eLazyBoolNo;
4272 }
4273
4274 const uint32_t response_save_id = response.GetU32(0);
4275 if (response_save_id != 0)
4276 {
4277 save_id = response_save_id;
4278 return true;
4279 }
4280 }
4281 }
4282 }
4283 return false;
4284}
4285
4286bool
4287GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id)
4288{
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004289 // We use the "m_supports_QSaveRegisterState" variable here because the
Greg Claytonf74cf862013-11-13 23:28:31 +00004290 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in
4291 // order to be useful
4292 if (m_supports_QSaveRegisterState == eLazyBoolNo)
4293 return false;
4294
4295 Mutex::Locker locker;
4296 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState."))
4297 {
4298 const bool thread_suffix_supported = GetThreadSuffixSupported();
4299 if (thread_suffix_supported || SetCurrentThread(tid))
4300 {
4301 char packet[256];
4302 if (thread_suffix_supported)
4303 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid);
4304 else
4305 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id);
4306
4307 StringExtractorGDBRemote response;
4308
Greg Clayton3dedae12013-12-06 21:45:27 +00004309 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success)
Greg Claytonf74cf862013-11-13 23:28:31 +00004310 {
4311 if (response.IsOKResponse())
4312 {
4313 return true;
4314 }
4315 else if (response.IsUnsupportedResponse())
4316 {
4317 // This packet isn't supported, don't try calling this packet or
4318 // QSaveRegisterState again...
4319 m_supports_QSaveRegisterState = eLazyBoolNo;
4320 }
4321 }
4322 }
4323 }
4324 return false;
4325}
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004326
4327bool
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004328GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec,
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004329 const lldb_private::ArchSpec& arch_spec,
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004330 ModuleSpec &module_spec)
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004331{
Stephane Sezer6f455292016-01-08 00:00:17 +00004332 if (!m_supports_qModuleInfo)
4333 return false;
4334
Oleksiy Vyalov7d9d9412015-04-16 07:02:56 +00004335 std::string module_path = module_file_spec.GetPath (false);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004336 if (module_path.empty ())
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004337 return false;
4338
4339 StreamString packet;
4340 packet.PutCString("qModuleInfo:");
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004341 packet.PutCStringAsRawHex8(module_path.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004342 packet.PutCString(";");
Chaoren Linf34f4102015-05-09 01:21:32 +00004343 const auto& triple = arch_spec.GetTriple().getTriple();
Chaoren Lind3173f32015-05-29 19:52:29 +00004344 packet.PutCStringAsRawHex8(triple.c_str());
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004345
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004346 StringExtractorGDBRemote response;
4347 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success)
4348 return false;
4349
Stephane Sezer6f455292016-01-08 00:00:17 +00004350 if (response.IsErrorResponse ())
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004351 return false;
4352
Stephane Sezer6f455292016-01-08 00:00:17 +00004353 if (response.IsUnsupportedResponse ())
4354 {
4355 m_supports_qModuleInfo = false;
4356 return false;
4357 }
4358
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004359 std::string name;
4360 std::string value;
4361 bool success;
4362 StringExtractor extractor;
4363
4364 module_spec.Clear ();
4365 module_spec.GetFileSpec () = module_file_spec;
4366
4367 while (response.GetNameColonValue (name, value))
4368 {
4369 if (name == "uuid" || name == "md5")
4370 {
4371 extractor.GetStringRef ().swap (value);
4372 extractor.SetFilePos (0);
4373 extractor.GetHexByteString (value);
4374 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2);
4375 }
4376 else if (name == "triple")
4377 {
4378 extractor.GetStringRef ().swap (value);
4379 extractor.SetFilePos (0);
4380 extractor.GetHexByteString (value);
4381 module_spec.GetArchitecture().SetTriple (value.c_str ());
4382 }
4383 else if (name == "file_offset")
4384 {
4385 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4386 if (success)
4387 module_spec.SetObjectOffset (ival);
4388 }
4389 else if (name == "file_size")
4390 {
4391 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success);
4392 if (success)
4393 module_spec.SetObjectSize (ival);
4394 }
4395 else if (name == "file_path")
4396 {
4397 extractor.GetStringRef ().swap (value);
4398 extractor.SetFilePos (0);
4399 extractor.GetHexByteString (value);
Chaoren Linf34f4102015-05-09 01:21:32 +00004400 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004401 }
4402 }
4403
4404 return true;
Oleksiy Vyalov6801be32015-02-25 22:15:44 +00004405}
Colin Rileyc3c95b22015-04-16 15:51:33 +00004406
4407// query the target remote for extended information using the qXfer packet
4408//
4409// example: object='features', annex='target.xml', out=<xml output>
4410// return: 'true' on success
4411// 'false' on failure (err set)
4412bool
4413GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object,
4414 const lldb_private::ConstString annex,
4415 std::string & out,
4416 lldb_private::Error & err) {
4417
4418 std::stringstream output;
4419 StringExtractorGDBRemote chunk;
4420
Greg Claytond04f0ed2015-05-26 18:00:51 +00004421 uint64_t size = GetRemoteMaxPacketSize();
4422 if (size == 0)
4423 size = 0x1000;
4424 size = size - 1; // Leave space for the 'm' or 'l' character in the response
4425 int offset = 0;
4426 bool active = true;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004427
4428 // loop until all data has been read
4429 while ( active ) {
4430
4431 // send query extended feature packet
4432 std::stringstream packet;
4433 packet << "qXfer:"
Ewan Crawford682e8422015-06-26 09:38:27 +00004434 << object.AsCString("") << ":read:"
4435 << annex.AsCString("") << ":"
Colin Rileyc3c95b22015-04-16 15:51:33 +00004436 << std::hex << offset << ","
4437 << std::hex << size;
4438
4439 GDBRemoteCommunication::PacketResult res =
4440 SendPacketAndWaitForResponse( packet.str().c_str(),
4441 chunk,
4442 false );
4443
4444 if ( res != GDBRemoteCommunication::PacketResult::Success ) {
4445 err.SetErrorString( "Error sending $qXfer packet" );
4446 return false;
4447 }
4448
4449 const std::string & str = chunk.GetStringRef( );
4450 if ( str.length() == 0 ) {
4451 // should have some data in chunk
4452 err.SetErrorString( "Empty response from $qXfer packet" );
4453 return false;
4454 }
4455
4456 // check packet code
4457 switch ( str[0] ) {
4458 // last chunk
4459 case ( 'l' ):
4460 active = false;
Jason Molenda62e06812016-02-16 04:14:33 +00004461 LLVM_FALLTHROUGH;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004462
4463 // more chunks
4464 case ( 'm' ) :
4465 if ( str.length() > 1 )
4466 output << &str[1];
Aidan Doddsed9f6122015-04-29 10:08:17 +00004467 offset += size;
Colin Rileyc3c95b22015-04-16 15:51:33 +00004468 break;
4469
4470 // unknown chunk
4471 default:
4472 err.SetErrorString( "Invalid continuation code from $qXfer packet" );
4473 return false;
4474 }
4475 }
4476
4477 out = output.str( );
4478 err.Success( );
4479 return true;
4480}
Greg Clayton0b90be12015-06-23 21:27:50 +00004481
4482// Notify the target that gdb is prepared to serve symbol lookup requests.
4483// packet: "qSymbol::"
4484// reply:
4485// OK The target does not need to look up any (more) symbols.
4486// qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded).
4487// LLDB may provide the value by sending another qSymbol packet
4488// in the form of"qSymbol:<sym_value>:<sym_name>".
Jason Molenda50018d32016-01-13 04:08:10 +00004489//
4490// Three examples:
4491//
4492// lldb sends: qSymbol::
4493// lldb receives: OK
4494// Remote gdb stub does not need to know the addresses of any symbols, lldb does not
4495// need to ask again in this session.
4496//
4497// lldb sends: qSymbol::
4498// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4499// lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473
4500// lldb receives: OK
4501// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does not know
4502// the address at this time. lldb needs to send qSymbol:: again when it has more
4503// solibs loaded.
4504//
4505// lldb sends: qSymbol::
4506// lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473
4507// lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473
4508// lldb receives: OK
4509// Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says that it
4510// is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it does not
4511// need any more symbols. lldb does not need to ask again in this session.
Greg Clayton0b90be12015-06-23 21:27:50 +00004512
4513void
4514GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process)
4515{
Jason Molenda50018d32016-01-13 04:08:10 +00004516 // Set to true once we've resolved a symbol to an address for the remote stub.
4517 // If we get an 'OK' response after this, the remote stub doesn't need any more
4518 // symbols and we can stop asking.
4519 bool symbol_response_provided = false;
4520
Ed Maste75500e72016-07-19 15:28:02 +00004521 // Is this the initial qSymbol:: packet?
Jason Molenda50018d32016-01-13 04:08:10 +00004522 bool first_qsymbol_query = true;
4523
4524 if (m_supports_qSymbol && m_qSymbol_requests_done == false)
Greg Clayton0b90be12015-06-23 21:27:50 +00004525 {
4526 Mutex::Locker locker;
4527 if (GetSequenceMutex(locker, "GDBRemoteCommunicationClient::ServeSymbolLookups() failed due to not getting the sequence mutex"))
4528 {
4529 StreamString packet;
4530 packet.PutCString ("qSymbol::");
Greg Clayton42b01482015-08-11 22:07:46 +00004531 StringExtractorGDBRemote response;
4532 while (SendPacketAndWaitForResponseNoLock(packet.GetData(), packet.GetSize(), response) == PacketResult::Success)
Greg Clayton0b90be12015-06-23 21:27:50 +00004533 {
Greg Clayton42b01482015-08-11 22:07:46 +00004534 if (response.IsOKResponse())
Greg Clayton0b90be12015-06-23 21:27:50 +00004535 {
Jason Molenda50018d32016-01-13 04:08:10 +00004536 if (symbol_response_provided || first_qsymbol_query)
4537 {
4538 m_qSymbol_requests_done = true;
4539 }
4540
Greg Clayton42b01482015-08-11 22:07:46 +00004541 // We are done serving symbols requests
4542 return;
4543 }
Jason Molenda50018d32016-01-13 04:08:10 +00004544 first_qsymbol_query = false;
Greg Clayton0b90be12015-06-23 21:27:50 +00004545
Greg Clayton42b01482015-08-11 22:07:46 +00004546 if (response.IsUnsupportedResponse())
4547 {
4548 // qSymbol is not supported by the current GDB server we are connected to
4549 m_supports_qSymbol = false;
4550 return;
4551 }
4552 else
4553 {
4554 llvm::StringRef response_str(response.GetStringRef());
4555 if (response_str.startswith("qSymbol:"))
Greg Clayton0b90be12015-06-23 21:27:50 +00004556 {
Greg Clayton42b01482015-08-11 22:07:46 +00004557 response.SetFilePos(strlen("qSymbol:"));
4558 std::string symbol_name;
4559 if (response.GetHexByteString(symbol_name))
Greg Clayton0b90be12015-06-23 21:27:50 +00004560 {
Greg Clayton42b01482015-08-11 22:07:46 +00004561 if (symbol_name.empty())
4562 return;
4563
4564 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS;
4565 lldb_private::SymbolContextList sc_list;
4566 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list))
Greg Clayton0b90be12015-06-23 21:27:50 +00004567 {
Greg Clayton42b01482015-08-11 22:07:46 +00004568 const size_t num_scs = sc_list.GetSize();
4569 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 +00004570 {
Greg Clayton42b01482015-08-11 22:07:46 +00004571 SymbolContext sc;
4572 if (sc_list.GetContextAtIndex(sc_idx, sc))
Greg Clayton0b90be12015-06-23 21:27:50 +00004573 {
Greg Clayton42b01482015-08-11 22:07:46 +00004574 if (sc.symbol)
Greg Clayton358cf1e2015-06-25 21:46:34 +00004575 {
Greg Clayton42b01482015-08-11 22:07:46 +00004576 switch (sc.symbol->GetType())
Greg Clayton358cf1e2015-06-25 21:46:34 +00004577 {
Greg Clayton42b01482015-08-11 22:07:46 +00004578 case eSymbolTypeInvalid:
4579 case eSymbolTypeAbsolute:
4580 case eSymbolTypeUndefined:
4581 case eSymbolTypeSourceFile:
4582 case eSymbolTypeHeaderFile:
4583 case eSymbolTypeObjectFile:
4584 case eSymbolTypeCommonBlock:
4585 case eSymbolTypeBlock:
4586 case eSymbolTypeLocal:
4587 case eSymbolTypeParam:
4588 case eSymbolTypeVariable:
4589 case eSymbolTypeVariableType:
4590 case eSymbolTypeLineEntry:
4591 case eSymbolTypeLineHeader:
4592 case eSymbolTypeScopeBegin:
4593 case eSymbolTypeScopeEnd:
4594 case eSymbolTypeAdditional:
4595 case eSymbolTypeCompiler:
4596 case eSymbolTypeInstrumentation:
4597 case eSymbolTypeTrampoline:
4598 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00004599
Greg Clayton42b01482015-08-11 22:07:46 +00004600 case eSymbolTypeCode:
4601 case eSymbolTypeResolver:
4602 case eSymbolTypeData:
4603 case eSymbolTypeRuntime:
4604 case eSymbolTypeException:
4605 case eSymbolTypeObjCClass:
4606 case eSymbolTypeObjCMetaClass:
4607 case eSymbolTypeObjCIVar:
4608 case eSymbolTypeReExported:
4609 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget());
4610 break;
Greg Clayton358cf1e2015-06-25 21:46:34 +00004611 }
4612 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004613 }
4614 }
Greg Clayton0b90be12015-06-23 21:27:50 +00004615 }
Greg Clayton42b01482015-08-11 22:07:46 +00004616 // This is the normal path where our symbol lookup was successful and we want
4617 // to send a packet with the new symbol value and see if another lookup needs to be
4618 // done.
4619
4620 // Change "packet" to contain the requested symbol value and name
4621 packet.Clear();
4622 packet.PutCString("qSymbol:");
4623 if (symbol_load_addr != LLDB_INVALID_ADDRESS)
Jason Molenda50018d32016-01-13 04:08:10 +00004624 {
Greg Clayton42b01482015-08-11 22:07:46 +00004625 packet.Printf("%" PRIx64, symbol_load_addr);
Jason Molenda50018d32016-01-13 04:08:10 +00004626 symbol_response_provided = true;
4627 }
4628 else
4629 {
4630 symbol_response_provided = false;
4631 }
Greg Clayton42b01482015-08-11 22:07:46 +00004632 packet.PutCString(":");
4633 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size());
4634 continue; // go back to the while loop and send "packet" and wait for another response
Greg Clayton0b90be12015-06-23 21:27:50 +00004635 }
4636 }
4637 }
4638 }
4639 // If we make it here, the symbol request packet response wasn't valid or
4640 // our symbol lookup failed so we must abort
4641 return;
4642
4643 }
4644 }
4645}
4646