blob: 67cdbfd588abef5f2eb2193f31c653aff7c3044c [file] [log] [blame]
Greg Clayton576d8832011-03-22 04:00:09 +00001//===-- GDBRemoteCommunicationClient.cpp ------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10
11#include "GDBRemoteCommunicationClient.h"
12
13// C Includes
Daniel Maleab89d0492013-08-28 16:06:16 +000014#include <sys/stat.h>
15
Greg Clayton576d8832011-03-22 04:00:09 +000016// C++ Includes
Han Ming Ong4b6459f2013-01-18 23:11:53 +000017#include <sstream>
18
Greg Clayton576d8832011-03-22 04:00:09 +000019// Other libraries and framework includes
20#include "llvm/ADT/Triple.h"
21#include "lldb/Interpreter/Args.h"
22#include "lldb/Core/ConnectionFileDescriptor.h"
23#include "lldb/Core/Log.h"
24#include "lldb/Core/State.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000025#include "lldb/Core/StreamGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000026#include "lldb/Core/StreamString.h"
27#include "lldb/Host/Endian.h"
28#include "lldb/Host/Host.h"
29#include "lldb/Host/TimeValue.h"
30
31// Project includes
32#include "Utility/StringExtractorGDBRemote.h"
33#include "ProcessGDBRemote.h"
34#include "ProcessGDBRemoteLog.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000035#include "lldb/Host/Config.h"
Greg Clayton576d8832011-03-22 04:00:09 +000036
37using namespace lldb;
38using namespace lldb_private;
39
Virgile Bellob2f1fb22013-08-23 12:44:05 +000040#ifdef LLDB_DISABLE_POSIX
41#define SIGSTOP 17
42#endif
43
Greg Clayton576d8832011-03-22 04:00:09 +000044//----------------------------------------------------------------------
45// GDBRemoteCommunicationClient constructor
46//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +000047GDBRemoteCommunicationClient::GDBRemoteCommunicationClient(bool is_platform) :
48 GDBRemoteCommunication("gdb-remote.client", "gdb-remote.client.rx_packet", is_platform),
Greg Clayton576d8832011-03-22 04:00:09 +000049 m_supports_not_sending_acks (eLazyBoolCalculate),
50 m_supports_thread_suffix (eLazyBoolCalculate),
Greg Clayton44633992012-04-10 03:22:03 +000051 m_supports_threads_in_stop_reply (eLazyBoolCalculate),
Greg Clayton576d8832011-03-22 04:00:09 +000052 m_supports_vCont_all (eLazyBoolCalculate),
53 m_supports_vCont_any (eLazyBoolCalculate),
54 m_supports_vCont_c (eLazyBoolCalculate),
55 m_supports_vCont_C (eLazyBoolCalculate),
56 m_supports_vCont_s (eLazyBoolCalculate),
57 m_supports_vCont_S (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000058 m_qHostInfo_is_valid (eLazyBoolCalculate),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000059 m_qProcessInfo_is_valid (eLazyBoolCalculate),
Greg Clayton70b57652011-05-15 01:25:55 +000060 m_supports_alloc_dealloc_memory (eLazyBoolCalculate),
Greg Clayton46fb5582011-11-18 07:03:08 +000061 m_supports_memory_region_info (eLazyBoolCalculate),
Johnny Chen64637202012-05-23 21:09:52 +000062 m_supports_watchpoint_support_info (eLazyBoolCalculate),
Jim Inghamacff8952013-05-02 00:27:30 +000063 m_supports_detach_stay_stopped (eLazyBoolCalculate),
Enrico Granataf04a2192012-07-13 23:18:48 +000064 m_watchpoints_trigger_after_instruction(eLazyBoolCalculate),
Jim Inghamcd16df92012-07-20 21:37:13 +000065 m_attach_or_wait_reply(eLazyBoolCalculate),
Jim Ingham279ceec2012-07-25 21:12:43 +000066 m_prepare_for_reg_writing_reply (eLazyBoolCalculate),
Eric Christopher2490f5c2013-08-30 17:50:57 +000067 m_supports_p (eLazyBoolCalculate),
Greg Clayton32e0a752011-03-30 18:16:51 +000068 m_supports_qProcessInfoPID (true),
69 m_supports_qfProcessInfo (true),
70 m_supports_qUserName (true),
71 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000072 m_supports_qThreadStopInfo (true),
73 m_supports_z0 (true),
74 m_supports_z1 (true),
75 m_supports_z2 (true),
76 m_supports_z3 (true),
77 m_supports_z4 (true),
78 m_curr_tid (LLDB_INVALID_THREAD_ID),
79 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +000080 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +000081 m_async_mutex (Mutex::eMutexTypeRecursive),
82 m_async_packet_predicate (false),
83 m_async_packet (),
84 m_async_response (),
85 m_async_signal (-1),
Han Ming Ong4b6459f2013-01-18 23:11:53 +000086 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +000087 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000088 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +000089 m_os_version_major (UINT32_MAX),
90 m_os_version_minor (UINT32_MAX),
91 m_os_version_update (UINT32_MAX)
Greg Clayton576d8832011-03-22 04:00:09 +000092{
Greg Clayton576d8832011-03-22 04:00:09 +000093}
94
95//----------------------------------------------------------------------
96// Destructor
97//----------------------------------------------------------------------
98GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
99{
Greg Clayton576d8832011-03-22 04:00:09 +0000100 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000101 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000102}
103
104bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000105GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
106{
107 // Start the read thread after we send the handshake ack since if we
108 // fail to send the handshake ack, there is no reason to continue...
109 if (SendAck())
Greg Clayton73bf5db2011-06-17 01:22:15 +0000110 return true;
Greg Clayton1cb64962011-03-24 04:28:38 +0000111
112 if (error_ptr)
113 error_ptr->SetErrorString("failed to send the handshake ack");
114 return false;
115}
116
117void
118GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000119{
120 if (m_supports_not_sending_acks == eLazyBoolCalculate)
121 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000122 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000123 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000124
125 StringExtractorGDBRemote response;
Greg Clayton576d8832011-03-22 04:00:09 +0000126 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false))
127 {
128 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000129 {
130 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000131 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000132 }
Greg Clayton576d8832011-03-22 04:00:09 +0000133 }
134 }
Greg Clayton576d8832011-03-22 04:00:09 +0000135}
136
137void
Greg Clayton44633992012-04-10 03:22:03 +0000138GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
139{
140 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
141 {
142 m_supports_threads_in_stop_reply = eLazyBoolNo;
143
144 StringExtractorGDBRemote response;
145 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false))
146 {
147 if (response.IsOKResponse())
148 m_supports_threads_in_stop_reply = eLazyBoolYes;
149 }
150 }
151}
152
Jim Inghamcd16df92012-07-20 21:37:13 +0000153bool
154GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
155{
156 if (m_attach_or_wait_reply == eLazyBoolCalculate)
157 {
158 m_attach_or_wait_reply = eLazyBoolNo;
159
160 StringExtractorGDBRemote response;
161 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false))
162 {
163 if (response.IsOKResponse())
164 m_attach_or_wait_reply = eLazyBoolYes;
165 }
166 }
167 if (m_attach_or_wait_reply == eLazyBoolYes)
168 return true;
169 else
170 return false;
171}
172
Jim Ingham279ceec2012-07-25 21:12:43 +0000173bool
174GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
175{
176 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
177 {
178 m_prepare_for_reg_writing_reply = eLazyBoolNo;
179
180 StringExtractorGDBRemote response;
181 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false))
182 {
183 if (response.IsOKResponse())
184 m_prepare_for_reg_writing_reply = eLazyBoolYes;
185 }
186 }
187 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
188 return true;
189 else
190 return false;
191}
192
Greg Clayton44633992012-04-10 03:22:03 +0000193
194void
Greg Clayton576d8832011-03-22 04:00:09 +0000195GDBRemoteCommunicationClient::ResetDiscoverableSettings()
196{
197 m_supports_not_sending_acks = eLazyBoolCalculate;
198 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton44633992012-04-10 03:22:03 +0000199 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
Greg Clayton576d8832011-03-22 04:00:09 +0000200 m_supports_vCont_c = eLazyBoolCalculate;
201 m_supports_vCont_C = eLazyBoolCalculate;
202 m_supports_vCont_s = eLazyBoolCalculate;
203 m_supports_vCont_S = eLazyBoolCalculate;
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000204 m_supports_p = eLazyBoolCalculate;
Greg Clayton32e0a752011-03-30 18:16:51 +0000205 m_qHostInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000206 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Greg Clayton70b57652011-05-15 01:25:55 +0000207 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton46fb5582011-11-18 07:03:08 +0000208 m_supports_memory_region_info = eLazyBoolCalculate;
Jim Ingham279ceec2012-07-25 21:12:43 +0000209 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
210 m_attach_or_wait_reply = eLazyBoolCalculate;
Greg Clayton2a48f522011-05-14 01:50:35 +0000211
Greg Clayton32e0a752011-03-30 18:16:51 +0000212 m_supports_qProcessInfoPID = true;
213 m_supports_qfProcessInfo = true;
214 m_supports_qUserName = true;
215 m_supports_qGroupName = true;
Greg Clayton8b82f082011-04-12 05:54:46 +0000216 m_supports_qThreadStopInfo = true;
217 m_supports_z0 = true;
218 m_supports_z1 = true;
219 m_supports_z2 = true;
220 m_supports_z3 = true;
221 m_supports_z4 = true;
Greg Claytond314e812011-03-23 00:09:55 +0000222 m_host_arch.Clear();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000223 m_process_arch.Clear();
Greg Clayton576d8832011-03-22 04:00:09 +0000224}
225
226
227bool
228GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
229{
230 if (m_supports_thread_suffix == eLazyBoolCalculate)
231 {
232 StringExtractorGDBRemote response;
233 m_supports_thread_suffix = eLazyBoolNo;
234 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false))
235 {
236 if (response.IsOKResponse())
237 m_supports_thread_suffix = eLazyBoolYes;
238 }
239 }
240 return m_supports_thread_suffix;
241}
242bool
243GDBRemoteCommunicationClient::GetVContSupported (char flavor)
244{
245 if (m_supports_vCont_c == eLazyBoolCalculate)
246 {
247 StringExtractorGDBRemote response;
248 m_supports_vCont_any = eLazyBoolNo;
249 m_supports_vCont_all = eLazyBoolNo;
250 m_supports_vCont_c = eLazyBoolNo;
251 m_supports_vCont_C = eLazyBoolNo;
252 m_supports_vCont_s = eLazyBoolNo;
253 m_supports_vCont_S = eLazyBoolNo;
254 if (SendPacketAndWaitForResponse("vCont?", response, false))
255 {
256 const char *response_cstr = response.GetStringRef().c_str();
257 if (::strstr (response_cstr, ";c"))
258 m_supports_vCont_c = eLazyBoolYes;
259
260 if (::strstr (response_cstr, ";C"))
261 m_supports_vCont_C = eLazyBoolYes;
262
263 if (::strstr (response_cstr, ";s"))
264 m_supports_vCont_s = eLazyBoolYes;
265
266 if (::strstr (response_cstr, ";S"))
267 m_supports_vCont_S = eLazyBoolYes;
268
269 if (m_supports_vCont_c == eLazyBoolYes &&
270 m_supports_vCont_C == eLazyBoolYes &&
271 m_supports_vCont_s == eLazyBoolYes &&
272 m_supports_vCont_S == eLazyBoolYes)
273 {
274 m_supports_vCont_all = eLazyBoolYes;
275 }
276
277 if (m_supports_vCont_c == eLazyBoolYes ||
278 m_supports_vCont_C == eLazyBoolYes ||
279 m_supports_vCont_s == eLazyBoolYes ||
280 m_supports_vCont_S == eLazyBoolYes)
281 {
282 m_supports_vCont_any = eLazyBoolYes;
283 }
284 }
285 }
286
287 switch (flavor)
288 {
289 case 'a': return m_supports_vCont_any;
290 case 'A': return m_supports_vCont_all;
291 case 'c': return m_supports_vCont_c;
292 case 'C': return m_supports_vCont_C;
293 case 's': return m_supports_vCont_s;
294 case 'S': return m_supports_vCont_S;
295 default: break;
296 }
297 return false;
298}
299
Hafiz Abid Qadeer9a78cdf2013-08-29 09:09:45 +0000300// Check if the target supports 'p' packet. It sends out a 'p'
301// packet and checks the response. A normal packet will tell us
302// that support is available.
303bool
304GDBRemoteCommunicationClient::GetpPacketSupported ()
305{
306 if (m_supports_p == eLazyBoolCalculate)
307 {
308 StringExtractorGDBRemote response;
309 m_supports_p = eLazyBoolNo;
310 if (SendPacketAndWaitForResponse("p0", response, false))
311 {
312 if (response.IsNormalResponse())
313 m_supports_p = eLazyBoolYes;
314 }
315 }
316 return m_supports_p;
317}
Greg Clayton576d8832011-03-22 04:00:09 +0000318
319size_t
320GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
321(
322 const char *payload,
323 StringExtractorGDBRemote &response,
324 bool send_async
325)
326{
327 return SendPacketAndWaitForResponse (payload,
328 ::strlen (payload),
329 response,
330 send_async);
331}
332
333size_t
334GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
335(
336 const char *payload,
337 size_t payload_length,
338 StringExtractorGDBRemote &response,
339 bool send_async
340)
341{
342 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000343 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton644247c2011-07-07 01:59:51 +0000344 size_t response_len = 0;
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000345 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000346 {
Greg Clayton5fe15d22011-05-20 03:15:54 +0000347 if (SendPacketNoLock (payload, payload_length))
Greg Clayton644247c2011-07-07 01:59:51 +0000348 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
349 else
350 {
351 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000352 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
Greg Clayton644247c2011-07-07 01:59:51 +0000353 }
Greg Clayton576d8832011-03-22 04:00:09 +0000354 }
355 else
356 {
357 if (send_async)
358 {
Greg Claytond3544052012-05-31 21:24:20 +0000359 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000360 {
Greg Claytond3544052012-05-31 21:24:20 +0000361 Mutex::Locker async_locker (m_async_mutex);
362 m_async_packet.assign(payload, payload_length);
363 m_async_packet_predicate.SetValue (true, eBroadcastNever);
364
365 if (log)
366 log->Printf ("async: async packet = %s", m_async_packet.c_str());
367
368 bool timed_out = false;
369 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000370 {
Greg Claytond3544052012-05-31 21:24:20 +0000371 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000372 {
Jim Inghambabfc382012-06-06 00:32:39 +0000373 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000374 TimeValue timeout_time;
375 timeout_time = TimeValue::Now();
376 timeout_time.OffsetWithSeconds (m_packet_timeout);
377
Greg Clayton576d8832011-03-22 04:00:09 +0000378 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000379 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000380
Greg Claytond3544052012-05-31 21:24:20 +0000381 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000382 {
Greg Claytond3544052012-05-31 21:24:20 +0000383 if (log)
384 log->Printf ("async: got response");
385
386 // Swap the response buffer to avoid malloc and string copy
387 response.GetStringRef().swap (m_async_response.GetStringRef());
388 response_len = response.GetStringRef().size();
389 }
390 else
391 {
392 if (log)
393 log->Printf ("async: timed out waiting for response");
394 }
395
396 // Make sure we wait until the continue packet has been sent again...
397 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
398 {
399 if (log)
400 {
401 if (timed_out)
402 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
403 else
404 log->Printf ("async: async packet sent");
405 }
406 }
407 else
408 {
409 if (log)
410 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000411 }
412 }
413 else
414 {
Greg Claytond3544052012-05-31 21:24:20 +0000415 // We had a racy condition where we went to send the interrupt
416 // yet we were able to get the lock, so the process must have
417 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000418 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000419 log->Printf ("async: got lock without sending interrupt");
420 // Send the packet normally since we got the lock
421 if (SendPacketNoLock (payload, payload_length))
422 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
423 else
424 {
425 if (log)
426 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
427 }
Greg Clayton576d8832011-03-22 04:00:09 +0000428 }
429 }
430 else
431 {
Greg Clayton644247c2011-07-07 01:59:51 +0000432 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000433 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000434 }
435 }
436 else
437 {
438 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000439 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000440 }
441 }
442 else
443 {
444 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000445 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000446 }
447 }
Greg Clayton644247c2011-07-07 01:59:51 +0000448 if (response_len == 0)
449 {
450 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000451 log->Printf("error: failed to get response for '%*s'", (int) payload_length, payload);
Greg Clayton644247c2011-07-07 01:59:51 +0000452 }
453 return response_len;
Greg Clayton576d8832011-03-22 04:00:09 +0000454}
455
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000456static const char *end_delimiter = "--end--;";
457static const int end_delimiter_len = 8;
458
459std::string
460GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
461( ProcessGDBRemote *process,
462 StringExtractorGDBRemote& profileDataExtractor
463)
464{
465 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
466 std::stringstream final_output;
467 std::string name, value;
468
469 // Going to assuming thread_used_usec comes first, else bail out.
470 while (profileDataExtractor.GetNameColonValue(name, value))
471 {
472 if (name.compare("thread_used_id") == 0)
473 {
474 StringExtractor threadIDHexExtractor(value.c_str());
475 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
476
477 bool has_used_usec = false;
478 uint32_t curr_used_usec = 0;
479 std::string usec_name, usec_value;
480 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
481 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
482 {
483 if (usec_name.compare("thread_used_usec") == 0)
484 {
485 has_used_usec = true;
486 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
487 }
488 else
489 {
490 // We didn't find what we want, it is probably
491 // an older version. Bail out.
492 profileDataExtractor.SetFilePos(input_file_pos);
493 }
494 }
495
496 if (has_used_usec)
497 {
498 uint32_t prev_used_usec = 0;
499 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
500 if (iterator != m_thread_id_to_used_usec_map.end())
501 {
502 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
503 }
504
505 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
506 // A good first time record is one that runs for at least 0.25 sec
507 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
508 bool good_subsequent_time = (prev_used_usec > 0) &&
509 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
510
511 if (good_first_time || good_subsequent_time)
512 {
513 // We try to avoid doing too many index id reservation,
514 // resulting in fast increase of index ids.
515
516 final_output << name << ":";
517 int32_t index_id = process->AssignIndexIDToThread(thread_id);
518 final_output << index_id << ";";
519
520 final_output << usec_name << ":" << usec_value << ";";
521 }
522 else
523 {
524 // Skip past 'thread_used_name'.
525 std::string local_name, local_value;
526 profileDataExtractor.GetNameColonValue(local_name, local_value);
527 }
528
529 // Store current time as previous time so that they can be compared later.
530 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
531 }
532 else
533 {
534 // Bail out and use old string.
535 final_output << name << ":" << value << ";";
536 }
537 }
538 else
539 {
540 final_output << name << ":" << value << ";";
541 }
542 }
543 final_output << end_delimiter;
544 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
545
546 return final_output.str();
547}
548
Greg Clayton576d8832011-03-22 04:00:09 +0000549StateType
550GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
551(
552 ProcessGDBRemote *process,
553 const char *payload,
554 size_t packet_length,
555 StringExtractorGDBRemote &response
556)
557{
Greg Clayton1f5181a2012-07-02 22:05:25 +0000558 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +0000559 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +0000560 if (log)
561 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
562
563 Mutex::Locker locker(m_sequence_mutex);
564 StateType state = eStateRunning;
565
566 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
567 m_public_is_running.SetValue (true, eBroadcastNever);
568 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +0000569 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +0000570 std::string continue_packet(payload, packet_length);
571
Greg Clayton3f875c52013-02-22 22:23:55 +0000572 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +0000573
Greg Clayton576d8832011-03-22 04:00:09 +0000574 while (state == eStateRunning)
575 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000576 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +0000577 {
578 if (log)
579 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +0000580 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) == 0)
Greg Claytonaf247d72011-05-19 03:54:16 +0000581 state = eStateInvalid;
Greg Clayton576d8832011-03-22 04:00:09 +0000582
Greg Claytone889ad62011-10-27 22:04:16 +0000583 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +0000584 }
585
Greg Clayton3f875c52013-02-22 22:23:55 +0000586 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000587
588 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000589 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +0000590
Greg Clayton37a0a242012-04-11 00:24:49 +0000591 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX))
Greg Clayton576d8832011-03-22 04:00:09 +0000592 {
593 if (response.Empty())
594 state = eStateInvalid;
595 else
596 {
597 const char stop_type = response.GetChar();
598 if (log)
599 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
600 switch (stop_type)
601 {
602 case 'T':
603 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +0000604 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000605 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +0000606 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000607 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
608 {
609 lldb::pid_t pid = GetCurrentProcessID ();
610 if (pid != LLDB_INVALID_PROCESS_ID)
611 process->SetID (pid);
612 }
613 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +0000614 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000615
616 // Privately notify any internal threads that we have stopped
617 // in case we wanted to interrupt our process, yet we might
618 // send a packet and continue without returning control to the
619 // user.
620 m_private_is_running.SetValue (false, eBroadcastAlways);
621
622 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
623
Jim Inghambabfc382012-06-06 00:32:39 +0000624 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
625 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +0000626 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000627 // We sent an interrupt packet to stop the inferior process
628 // for an async signal or to send an async packet while running
629 // but we might have been single stepping and received the
630 // stop packet for the step instead of for the interrupt packet.
631 // Typically when an interrupt is sent a SIGINT or SIGSTOP
632 // is used, so if we get anything else, we need to try and
633 // get another stop reply packet that may have been sent
634 // due to sending the interrupt when the target is stopped
635 // which will just re-send a copy of the last stop reply
636 // packet. If we don't do this, then the reply for our
637 // async packet will be the repeat stop reply packet and cause
638 // a lot of trouble for us!
639 if (signo != SIGINT && signo != SIGSTOP)
640 {
Greg Claytonfb72fde2012-05-15 02:50:49 +0000641 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000642
643 // We didn't get a a SIGINT or SIGSTOP, so try for a
644 // very brief time (1 ms) to get another stop reply
645 // packet to make sure it doesn't get in the way
646 StringExtractorGDBRemote extra_stop_reply_packet;
647 uint32_t timeout_usec = 1000;
648 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec))
649 {
650 switch (extra_stop_reply_packet.GetChar())
651 {
652 case 'T':
653 case 'S':
654 // We did get an extra stop reply, which means
655 // our interrupt didn't stop the target so we
656 // shouldn't continue after the async signal
657 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +0000658 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000659 break;
660 }
661 }
662 }
663 }
664
665 if (m_async_signal != -1)
666 {
667 if (log)
668 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
669
670 // Save off the async signal we are supposed to send
671 const int async_signal = m_async_signal;
672 // Clear the async signal member so we don't end up
673 // sending the signal multiple times...
674 m_async_signal = -1;
675 // Check which signal we stopped with
676 if (signo == async_signal)
677 {
678 if (log)
679 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
680
681 // We already stopped with a signal that we wanted
682 // to stop with, so we are done
683 }
684 else
685 {
686 // We stopped with a different signal that the one
687 // we wanted to stop with, so now we must resume
688 // with the signal we want
689 char signal_packet[32];
690 int signal_packet_len = 0;
691 signal_packet_len = ::snprintf (signal_packet,
692 sizeof (signal_packet),
693 "C%2.2x",
694 async_signal);
695
696 if (log)
697 log->Printf ("async: stopped with signal %s, resume with %s",
698 Host::GetSignalAsCString (signo),
699 Host::GetSignalAsCString (async_signal));
700
701 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +0000702 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000703 continue_packet.assign(signal_packet, signal_packet_len);
704 continue;
705 }
706 }
707 else if (m_async_packet_predicate.GetValue())
708 {
Greg Clayton5160ce52013-03-27 23:08:40 +0000709 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +0000710
711 // We are supposed to send an asynchronous packet while
712 // we are running.
713 m_async_response.Clear();
714 if (m_async_packet.empty())
715 {
716 if (packet_log)
717 packet_log->Printf ("async: error: empty async packet");
718
719 }
720 else
721 {
722 if (packet_log)
723 packet_log->Printf ("async: sending packet");
724
725 SendPacketAndWaitForResponse (&m_async_packet[0],
726 m_async_packet.size(),
727 m_async_response,
728 false);
729 }
730 // Let the other thread that was trying to send the async
731 // packet know that the packet has been sent and response is
732 // ready...
733 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
734
735 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +0000736 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +0000737
738 // Set the continue packet to resume if our interrupt
739 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +0000740 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000741 {
Greg Claytonf1186de2012-05-24 23:42:14 +0000742 // Reverting this for now as it is causing deadlocks
743 // in programs (<rdar://problem/11529853>). In the future
744 // we should check our thread list and "do the right thing"
745 // for new threads that show up while we stop and run async
746 // packets. Setting the packet to 'c' to continue all threads
747 // is the right thing to do 99.99% of the time because if a
748 // thread was single stepping, and we sent an interrupt, we
749 // will notice above that we didn't stop due to an interrupt
750 // but stopped due to stepping and we would _not_ continue.
751 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +0000752 continue;
753 }
754 }
755 // Stop with signal and thread info
756 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +0000757 }
Greg Clayton576d8832011-03-22 04:00:09 +0000758 break;
759
760 case 'W':
761 case 'X':
762 // process exited
763 state = eStateExited;
764 break;
765
766 case 'O':
767 // STDOUT
768 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000769 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000770 std::string inferior_stdout;
771 inferior_stdout.reserve(response.GetBytesLeft () / 2);
772 char ch;
773 while ((ch = response.GetHexU8()) != '\0')
774 inferior_stdout.append(1, ch);
775 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
776 }
777 break;
778
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000779 case 'A':
780 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
781 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000782 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000783 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
784 if (m_partial_profile_data.length() > 0)
785 {
786 m_partial_profile_data.append(input);
787 input = m_partial_profile_data;
788 m_partial_profile_data.clear();
789 }
790
791 size_t found, pos = 0, len = input.length();
792 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
793 {
794 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +0000795 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
796 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000797
798 pos = found + end_delimiter_len;
799 }
800
801 if (pos < len)
802 {
803 // Last incomplete chunk.
804 m_partial_profile_data = input.substr(pos);
805 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000806 }
807 break;
808
Greg Clayton576d8832011-03-22 04:00:09 +0000809 case 'E':
810 // ERROR
811 state = eStateInvalid;
812 break;
813
814 default:
815 if (log)
816 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
817 state = eStateInvalid;
818 break;
819 }
820 }
821 }
822 else
823 {
824 if (log)
825 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
826 state = eStateInvalid;
827 }
828 }
829 if (log)
830 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
831 response.SetFilePos(0);
832 m_private_is_running.SetValue (false, eBroadcastAlways);
833 m_public_is_running.SetValue (false, eBroadcastAlways);
834 return state;
835}
836
837bool
838GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
839{
Greg Clayton2687cd12012-03-29 01:55:41 +0000840 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +0000841 m_async_signal = signo;
842 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000843 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +0000844 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000845 return true;
846 m_async_signal = -1;
847 return false;
848}
849
Greg Clayton37a0a242012-04-11 00:24:49 +0000850// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +0000851// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
852// (the expected result), then it will send the halt packet. If it does succeed
853// then the caller that requested the interrupt will want to keep the sequence
854// locked down so that no one else can send packets while the caller has control.
855// This function usually gets called when we are running and need to stop the
856// target. It can also be used when we are running and and we need to do something
857// else (like read/write memory), so we need to interrupt the running process
858// (gdb remote protocol requires this), and do what we need to do, then resume.
859
860bool
Greg Clayton2687cd12012-03-29 01:55:41 +0000861GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +0000862(
863 Mutex::Locker& locker,
864 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +0000865 bool &timed_out
866)
867{
Greg Clayton576d8832011-03-22 04:00:09 +0000868 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +0000869 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +0000870
871 if (IsRunning())
872 {
873 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000874 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +0000875 {
876 if (log)
877 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
878 }
879 else
Greg Clayton576d8832011-03-22 04:00:09 +0000880 {
881 // Someone has the mutex locked waiting for a response or for the
882 // inferior to stop, so send the interrupt on the down low...
883 char ctrl_c = '\x03';
884 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +0000885 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +0000886 if (log)
887 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +0000888 if (bytes_written > 0)
889 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000890 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000891 if (seconds_to_wait_for_stop)
892 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000893 TimeValue timeout;
894 if (seconds_to_wait_for_stop)
895 {
896 timeout = TimeValue::Now();
897 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
898 }
Greg Clayton576d8832011-03-22 04:00:09 +0000899 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
900 {
901 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000902 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +0000903 return true;
904 }
905 else
906 {
907 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000908 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +0000909 }
910 }
911 else
912 {
913 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000914 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +0000915 return true;
916 }
917 }
918 else
919 {
920 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000921 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000922 }
923 return false;
924 }
Greg Clayton576d8832011-03-22 04:00:09 +0000925 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000926 else
927 {
928 if (log)
929 log->Printf ("SendInterrupt () - not running");
930 }
Greg Clayton576d8832011-03-22 04:00:09 +0000931 return true;
932}
933
934lldb::pid_t
935GDBRemoteCommunicationClient::GetCurrentProcessID ()
936{
937 StringExtractorGDBRemote response;
938 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false))
939 {
940 if (response.GetChar() == 'Q')
941 if (response.GetChar() == 'C')
942 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
943 }
944 return LLDB_INVALID_PROCESS_ID;
945}
946
947bool
948GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
949{
950 error_str.clear();
951 StringExtractorGDBRemote response;
952 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false))
953 {
954 if (response.IsOKResponse())
955 return true;
956 if (response.GetChar() == 'E')
957 {
958 // A string the describes what failed when launching...
959 error_str = response.GetStringRef().substr(1);
960 }
961 else
962 {
963 error_str.assign ("unknown error occurred launching process");
964 }
965 }
966 else
967 {
Jim Ingham98d6da52012-06-28 20:30:23 +0000968 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +0000969 }
970 return false;
971}
972
973int
974GDBRemoteCommunicationClient::SendArgumentsPacket (char const *argv[])
975{
976 if (argv && argv[0])
977 {
978 StreamString packet;
979 packet.PutChar('A');
980 const char *arg;
981 for (uint32_t i = 0; (arg = argv[i]) != NULL; ++i)
982 {
983 const int arg_len = strlen(arg);
984 if (i > 0)
985 packet.PutChar(',');
986 packet.Printf("%i,%i,", arg_len * 2, i);
987 packet.PutBytesAsRawHex8 (arg, arg_len);
988 }
989
990 StringExtractorGDBRemote response;
991 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
992 {
993 if (response.IsOKResponse())
994 return 0;
995 uint8_t error = response.GetError();
996 if (error)
997 return error;
998 }
999 }
1000 return -1;
1001}
1002
1003int
1004GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
1005{
1006 if (name_equal_value && name_equal_value[0])
1007 {
1008 StreamString packet;
1009 packet.Printf("QEnvironment:%s", name_equal_value);
1010 StringExtractorGDBRemote response;
1011 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1012 {
1013 if (response.IsOKResponse())
1014 return 0;
1015 uint8_t error = response.GetError();
1016 if (error)
1017 return error;
1018 }
1019 }
1020 return -1;
1021}
1022
Greg Claytonc4103b32011-05-08 04:53:50 +00001023int
1024GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1025{
1026 if (arch && arch[0])
1027 {
1028 StreamString packet;
1029 packet.Printf("QLaunchArch:%s", arch);
1030 StringExtractorGDBRemote response;
1031 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1032 {
1033 if (response.IsOKResponse())
1034 return 0;
1035 uint8_t error = response.GetError();
1036 if (error)
1037 return error;
1038 }
1039 }
1040 return -1;
1041}
1042
Greg Clayton576d8832011-03-22 04:00:09 +00001043bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001044GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1045 uint32_t &minor,
1046 uint32_t &update)
1047{
1048 if (GetHostInfo ())
1049 {
1050 if (m_os_version_major != UINT32_MAX)
1051 {
1052 major = m_os_version_major;
1053 minor = m_os_version_minor;
1054 update = m_os_version_update;
1055 return true;
1056 }
1057 }
1058 return false;
1059}
1060
1061bool
1062GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1063{
1064 if (GetHostInfo ())
1065 {
1066 if (!m_os_build.empty())
1067 {
1068 s = m_os_build;
1069 return true;
1070 }
1071 }
1072 s.clear();
1073 return false;
1074}
1075
1076
1077bool
1078GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1079{
1080 if (GetHostInfo ())
1081 {
1082 if (!m_os_kernel.empty())
1083 {
1084 s = m_os_kernel;
1085 return true;
1086 }
1087 }
1088 s.clear();
1089 return false;
1090}
1091
1092bool
1093GDBRemoteCommunicationClient::GetHostname (std::string &s)
1094{
1095 if (GetHostInfo ())
1096 {
1097 if (!m_hostname.empty())
1098 {
1099 s = m_hostname;
1100 return true;
1101 }
1102 }
1103 s.clear();
1104 return false;
1105}
1106
1107ArchSpec
1108GDBRemoteCommunicationClient::GetSystemArchitecture ()
1109{
1110 if (GetHostInfo ())
1111 return m_host_arch;
1112 return ArchSpec();
1113}
1114
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001115const lldb_private::ArchSpec &
1116GDBRemoteCommunicationClient::GetProcessArchitecture ()
1117{
1118 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1119 GetCurrentProcessInfo ();
1120 return m_process_arch;
1121}
1122
Greg Clayton1cb64962011-03-24 04:28:38 +00001123
1124bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001125GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001126{
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001127 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001128 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001129 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001130 StringExtractorGDBRemote response;
1131 if (SendPacketAndWaitForResponse ("qHostInfo", response, false))
1132 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001133 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001134 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001135 std::string name;
1136 std::string value;
1137 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1138 uint32_t sub = 0;
1139 std::string arch_name;
1140 std::string os_name;
1141 std::string vendor_name;
1142 std::string triple;
1143 uint32_t pointer_byte_size = 0;
1144 StringExtractor extractor;
1145 ByteOrder byte_order = eByteOrderInvalid;
1146 uint32_t num_keys_decoded = 0;
1147 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001148 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001149 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001150 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001151 // exception type in big endian hex
1152 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1153 if (cpu != LLDB_INVALID_CPUTYPE)
1154 ++num_keys_decoded;
1155 }
1156 else if (name.compare("cpusubtype") == 0)
1157 {
1158 // exception count in big endian hex
1159 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
1160 if (sub != 0)
1161 ++num_keys_decoded;
1162 }
1163 else if (name.compare("arch") == 0)
1164 {
1165 arch_name.swap (value);
1166 ++num_keys_decoded;
1167 }
1168 else if (name.compare("triple") == 0)
1169 {
1170 // The triple comes as ASCII hex bytes since it contains '-' chars
1171 extractor.GetStringRef().swap(value);
1172 extractor.SetFilePos(0);
1173 extractor.GetHexByteString (triple);
1174 ++num_keys_decoded;
1175 }
1176 else if (name.compare("os_build") == 0)
1177 {
1178 extractor.GetStringRef().swap(value);
1179 extractor.SetFilePos(0);
1180 extractor.GetHexByteString (m_os_build);
1181 ++num_keys_decoded;
1182 }
1183 else if (name.compare("hostname") == 0)
1184 {
1185 extractor.GetStringRef().swap(value);
1186 extractor.SetFilePos(0);
1187 extractor.GetHexByteString (m_hostname);
1188 ++num_keys_decoded;
1189 }
1190 else if (name.compare("os_kernel") == 0)
1191 {
1192 extractor.GetStringRef().swap(value);
1193 extractor.SetFilePos(0);
1194 extractor.GetHexByteString (m_os_kernel);
1195 ++num_keys_decoded;
1196 }
1197 else if (name.compare("ostype") == 0)
1198 {
1199 os_name.swap (value);
1200 ++num_keys_decoded;
1201 }
1202 else if (name.compare("vendor") == 0)
1203 {
1204 vendor_name.swap(value);
1205 ++num_keys_decoded;
1206 }
1207 else if (name.compare("endian") == 0)
1208 {
1209 ++num_keys_decoded;
1210 if (value.compare("little") == 0)
1211 byte_order = eByteOrderLittle;
1212 else if (value.compare("big") == 0)
1213 byte_order = eByteOrderBig;
1214 else if (value.compare("pdp") == 0)
1215 byte_order = eByteOrderPDP;
1216 else
1217 --num_keys_decoded;
1218 }
1219 else if (name.compare("ptrsize") == 0)
1220 {
1221 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1222 if (pointer_byte_size != 0)
1223 ++num_keys_decoded;
1224 }
1225 else if (name.compare("os_version") == 0)
1226 {
1227 Args::StringToVersion (value.c_str(),
1228 m_os_version_major,
1229 m_os_version_minor,
1230 m_os_version_update);
1231 if (m_os_version_major != UINT32_MAX)
1232 ++num_keys_decoded;
1233 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001234 else if (name.compare("watchpoint_exceptions_received") == 0)
1235 {
1236 ++num_keys_decoded;
1237 if (strcmp(value.c_str(),"before") == 0)
1238 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1239 else if (strcmp(value.c_str(),"after") == 0)
1240 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1241 else
1242 --num_keys_decoded;
1243 }
1244
Greg Clayton32e0a752011-03-30 18:16:51 +00001245 }
1246
1247 if (num_keys_decoded > 0)
1248 m_qHostInfo_is_valid = eLazyBoolYes;
1249
1250 if (triple.empty())
1251 {
1252 if (arch_name.empty())
1253 {
1254 if (cpu != LLDB_INVALID_CPUTYPE)
1255 {
1256 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1257 if (pointer_byte_size)
1258 {
1259 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1260 }
1261 if (byte_order != eByteOrderInvalid)
1262 {
1263 assert (byte_order == m_host_arch.GetByteOrder());
1264 }
Greg Clayton70512312012-05-08 01:45:38 +00001265
1266 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1267 {
1268 switch (m_host_arch.GetMachine())
1269 {
1270 case llvm::Triple::arm:
1271 case llvm::Triple::thumb:
1272 os_name = "ios";
1273 break;
1274 default:
1275 os_name = "macosx";
1276 break;
1277 }
1278 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001279 if (!vendor_name.empty())
1280 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1281 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001282 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001283
1284 }
1285 }
1286 else
1287 {
1288 std::string triple;
1289 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001290 if (!vendor_name.empty() || !os_name.empty())
1291 {
1292 triple += '-';
1293 if (vendor_name.empty())
1294 triple += "unknown";
1295 else
1296 triple += vendor_name;
1297 triple += '-';
1298 if (os_name.empty())
1299 triple += "unknown";
1300 else
1301 triple += os_name;
1302 }
1303 m_host_arch.SetTriple (triple.c_str());
1304
1305 llvm::Triple &host_triple = m_host_arch.GetTriple();
1306 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1307 {
1308 switch (m_host_arch.GetMachine())
1309 {
1310 case llvm::Triple::arm:
1311 case llvm::Triple::thumb:
1312 host_triple.setOS(llvm::Triple::IOS);
1313 break;
1314 default:
1315 host_triple.setOS(llvm::Triple::MacOSX);
1316 break;
1317 }
1318 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001319 if (pointer_byte_size)
1320 {
1321 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1322 }
1323 if (byte_order != eByteOrderInvalid)
1324 {
1325 assert (byte_order == m_host_arch.GetByteOrder());
1326 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001327
Greg Clayton1cb64962011-03-24 04:28:38 +00001328 }
1329 }
1330 else
1331 {
Greg Clayton70512312012-05-08 01:45:38 +00001332 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001333 if (pointer_byte_size)
1334 {
1335 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1336 }
1337 if (byte_order != eByteOrderInvalid)
1338 {
1339 assert (byte_order == m_host_arch.GetByteOrder());
1340 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001341 }
Greg Claytond314e812011-03-23 00:09:55 +00001342 }
Greg Clayton576d8832011-03-22 04:00:09 +00001343 }
1344 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001345 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001346}
1347
1348int
1349GDBRemoteCommunicationClient::SendAttach
1350(
1351 lldb::pid_t pid,
1352 StringExtractorGDBRemote& response
1353)
1354{
1355 if (pid != LLDB_INVALID_PROCESS_ID)
1356 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001357 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001358 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001359 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00001360 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton576d8832011-03-22 04:00:09 +00001361 {
1362 if (response.IsErrorResponse())
1363 return response.GetError();
1364 return 0;
1365 }
1366 }
1367 return -1;
1368}
1369
1370const lldb_private::ArchSpec &
1371GDBRemoteCommunicationClient::GetHostArchitecture ()
1372{
Greg Clayton32e0a752011-03-30 18:16:51 +00001373 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001374 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001375 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001376}
1377
1378addr_t
1379GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1380{
Greg Clayton70b57652011-05-15 01:25:55 +00001381 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001382 {
Greg Clayton70b57652011-05-15 01:25:55 +00001383 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001384 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001385 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001386 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001387 permissions & lldb::ePermissionsReadable ? "r" : "",
1388 permissions & lldb::ePermissionsWritable ? "w" : "",
1389 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001390 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001391 StringExtractorGDBRemote response;
1392 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1393 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001394 if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001395 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1396 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001397 else
1398 {
1399 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1400 }
Greg Clayton576d8832011-03-22 04:00:09 +00001401 }
1402 return LLDB_INVALID_ADDRESS;
1403}
1404
1405bool
1406GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1407{
Greg Clayton70b57652011-05-15 01:25:55 +00001408 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001409 {
Greg Clayton70b57652011-05-15 01:25:55 +00001410 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001411 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001412 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001413 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001414 StringExtractorGDBRemote response;
1415 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1416 {
1417 if (response.IsOKResponse())
1418 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001419 }
1420 else
1421 {
1422 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00001423 }
Greg Clayton576d8832011-03-22 04:00:09 +00001424 }
1425 return false;
1426}
1427
Jim Inghamacff8952013-05-02 00:27:30 +00001428Error
1429GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00001430{
Jim Inghamacff8952013-05-02 00:27:30 +00001431 Error error;
1432
1433 if (keep_stopped)
1434 {
1435 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1436 {
1437 char packet[64];
1438 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001439 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00001440 StringExtractorGDBRemote response;
1441 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1442 {
1443 m_supports_detach_stay_stopped = eLazyBoolYes;
1444 }
1445 else
1446 {
1447 m_supports_detach_stay_stopped = eLazyBoolNo;
1448 }
1449 }
1450
1451 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1452 {
1453 error.SetErrorString("Stays stopped not supported by this target.");
1454 return error;
1455 }
1456 else
1457 {
1458 size_t num_sent = SendPacket ("D1", 2);
1459 if (num_sent == 0)
1460 error.SetErrorString ("Sending extended disconnect packet failed.");
1461 }
1462 }
1463 else
1464 {
1465 size_t num_sent = SendPacket ("D", 1);
1466 if (num_sent == 0)
1467 error.SetErrorString ("Sending disconnect packet failed.");
1468 }
1469 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001470}
1471
Greg Clayton46fb5582011-11-18 07:03:08 +00001472Error
1473GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1474 lldb_private::MemoryRegionInfo &region_info)
1475{
1476 Error error;
1477 region_info.Clear();
1478
1479 if (m_supports_memory_region_info != eLazyBoolNo)
1480 {
1481 m_supports_memory_region_info = eLazyBoolYes;
1482 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001483 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001484 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00001485 StringExtractorGDBRemote response;
1486 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1487 {
1488 std::string name;
1489 std::string value;
1490 addr_t addr_value;
1491 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00001492 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00001493 while (success && response.GetNameColonValue(name, value))
1494 {
1495 if (name.compare ("start") == 0)
1496 {
1497 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1498 if (success)
1499 region_info.GetRange().SetRangeBase(addr_value);
1500 }
1501 else if (name.compare ("size") == 0)
1502 {
1503 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1504 if (success)
1505 region_info.GetRange().SetByteSize (addr_value);
1506 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001507 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00001508 {
Jason Molendacb349ee2011-12-13 05:39:38 +00001509 saw_permissions = true;
1510 if (region_info.GetRange().Contains (addr))
1511 {
1512 if (value.find('r') != std::string::npos)
1513 region_info.SetReadable (MemoryRegionInfo::eYes);
1514 else
1515 region_info.SetReadable (MemoryRegionInfo::eNo);
1516
1517 if (value.find('w') != std::string::npos)
1518 region_info.SetWritable (MemoryRegionInfo::eYes);
1519 else
1520 region_info.SetWritable (MemoryRegionInfo::eNo);
1521
1522 if (value.find('x') != std::string::npos)
1523 region_info.SetExecutable (MemoryRegionInfo::eYes);
1524 else
1525 region_info.SetExecutable (MemoryRegionInfo::eNo);
1526 }
1527 else
1528 {
1529 // The reported region does not contain this address -- we're looking at an unmapped page
1530 region_info.SetReadable (MemoryRegionInfo::eNo);
1531 region_info.SetWritable (MemoryRegionInfo::eNo);
1532 region_info.SetExecutable (MemoryRegionInfo::eNo);
1533 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001534 }
1535 else if (name.compare ("error") == 0)
1536 {
1537 StringExtractorGDBRemote name_extractor;
1538 // Swap "value" over into "name_extractor"
1539 name_extractor.GetStringRef().swap(value);
1540 // Now convert the HEX bytes into a string value
1541 name_extractor.GetHexByteString (value);
1542 error.SetErrorString(value.c_str());
1543 }
1544 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001545
1546 // We got a valid address range back but no permissions -- which means this is an unmapped page
1547 if (region_info.GetRange().IsValid() && saw_permissions == false)
1548 {
1549 region_info.SetReadable (MemoryRegionInfo::eNo);
1550 region_info.SetWritable (MemoryRegionInfo::eNo);
1551 region_info.SetExecutable (MemoryRegionInfo::eNo);
1552 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001553 }
1554 else
1555 {
1556 m_supports_memory_region_info = eLazyBoolNo;
1557 }
1558 }
1559
1560 if (m_supports_memory_region_info == eLazyBoolNo)
1561 {
1562 error.SetErrorString("qMemoryRegionInfo is not supported");
1563 }
1564 if (error.Fail())
1565 region_info.Clear();
1566 return error;
1567
1568}
1569
Johnny Chen64637202012-05-23 21:09:52 +00001570Error
1571GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1572{
1573 Error error;
1574
1575 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1576 {
1577 num = m_num_supported_hardware_watchpoints;
1578 return error;
1579 }
1580
1581 // Set num to 0 first.
1582 num = 0;
1583 if (m_supports_watchpoint_support_info != eLazyBoolNo)
1584 {
1585 char packet[64];
1586 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001587 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00001588 StringExtractorGDBRemote response;
1589 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1590 {
1591 m_supports_watchpoint_support_info = eLazyBoolYes;
1592 std::string name;
1593 std::string value;
1594 while (response.GetNameColonValue(name, value))
1595 {
1596 if (name.compare ("num") == 0)
1597 {
1598 num = Args::StringToUInt32(value.c_str(), 0, 0);
1599 m_num_supported_hardware_watchpoints = num;
1600 }
1601 }
1602 }
1603 else
1604 {
1605 m_supports_watchpoint_support_info = eLazyBoolNo;
1606 }
1607 }
1608
1609 if (m_supports_watchpoint_support_info == eLazyBoolNo)
1610 {
1611 error.SetErrorString("qWatchpointSupportInfo is not supported");
1612 }
1613 return error;
1614
1615}
Greg Clayton46fb5582011-11-18 07:03:08 +00001616
Enrico Granataf04a2192012-07-13 23:18:48 +00001617lldb_private::Error
1618GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
1619{
1620 Error error(GetWatchpointSupportInfo(num));
1621 if (error.Success())
1622 error = GetWatchpointsTriggerAfterInstruction(after);
1623 return error;
1624}
1625
1626lldb_private::Error
1627GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
1628{
1629 Error error;
1630
1631 // we assume watchpoints will happen after running the relevant opcode
1632 // and we only want to override this behavior if we have explicitly
1633 // received a qHostInfo telling us otherwise
1634 if (m_qHostInfo_is_valid != eLazyBoolYes)
1635 after = true;
1636 else
1637 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1638 return error;
1639}
1640
Greg Clayton576d8832011-03-22 04:00:09 +00001641int
1642GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1643{
1644 if (path && path[0])
1645 {
1646 StreamString packet;
1647 packet.PutCString("QSetSTDIN:");
1648 packet.PutBytesAsRawHex8(path, strlen(path));
1649
1650 StringExtractorGDBRemote response;
1651 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1652 {
1653 if (response.IsOKResponse())
1654 return 0;
1655 uint8_t error = response.GetError();
1656 if (error)
1657 return error;
1658 }
1659 }
1660 return -1;
1661}
1662
1663int
1664GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1665{
1666 if (path && path[0])
1667 {
1668 StreamString packet;
1669 packet.PutCString("QSetSTDOUT:");
1670 packet.PutBytesAsRawHex8(path, strlen(path));
1671
1672 StringExtractorGDBRemote response;
1673 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1674 {
1675 if (response.IsOKResponse())
1676 return 0;
1677 uint8_t error = response.GetError();
1678 if (error)
1679 return error;
1680 }
1681 }
1682 return -1;
1683}
1684
1685int
1686GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1687{
1688 if (path && path[0])
1689 {
1690 StreamString packet;
1691 packet.PutCString("QSetSTDERR:");
1692 packet.PutBytesAsRawHex8(path, strlen(path));
1693
1694 StringExtractorGDBRemote response;
1695 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1696 {
1697 if (response.IsOKResponse())
1698 return 0;
1699 uint8_t error = response.GetError();
1700 if (error)
1701 return error;
1702 }
1703 }
1704 return -1;
1705}
1706
1707int
1708GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
1709{
1710 if (path && path[0])
1711 {
1712 StreamString packet;
1713 packet.PutCString("QSetWorkingDir:");
1714 packet.PutBytesAsRawHex8(path, strlen(path));
1715
1716 StringExtractorGDBRemote response;
1717 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1718 {
1719 if (response.IsOKResponse())
1720 return 0;
1721 uint8_t error = response.GetError();
1722 if (error)
1723 return error;
1724 }
1725 }
1726 return -1;
1727}
1728
1729int
1730GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1731{
Greg Clayton32e0a752011-03-30 18:16:51 +00001732 char packet[32];
1733 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00001734 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00001735 StringExtractorGDBRemote response;
Greg Clayton32e0a752011-03-30 18:16:51 +00001736 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton576d8832011-03-22 04:00:09 +00001737 {
1738 if (response.IsOKResponse())
1739 return 0;
1740 uint8_t error = response.GetError();
1741 if (error)
1742 return error;
1743 }
1744 return -1;
1745}
Greg Clayton32e0a752011-03-30 18:16:51 +00001746
1747bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001748GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00001749{
1750 if (response.IsNormalResponse())
1751 {
1752 std::string name;
1753 std::string value;
1754 StringExtractor extractor;
1755
1756 while (response.GetNameColonValue(name, value))
1757 {
1758 if (name.compare("pid") == 0)
1759 {
1760 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1761 }
1762 else if (name.compare("ppid") == 0)
1763 {
1764 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1765 }
1766 else if (name.compare("uid") == 0)
1767 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001768 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00001769 }
1770 else if (name.compare("euid") == 0)
1771 {
1772 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1773 }
1774 else if (name.compare("gid") == 0)
1775 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001776 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00001777 }
1778 else if (name.compare("egid") == 0)
1779 {
1780 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1781 }
1782 else if (name.compare("triple") == 0)
1783 {
1784 // The triple comes as ASCII hex bytes since it contains '-' chars
1785 extractor.GetStringRef().swap(value);
1786 extractor.SetFilePos(0);
1787 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00001788 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00001789 }
1790 else if (name.compare("name") == 0)
1791 {
1792 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00001793 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00001794 // control the characters in a process name
1795 extractor.GetStringRef().swap(value);
1796 extractor.SetFilePos(0);
1797 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00001798 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00001799 }
1800 }
1801
1802 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1803 return true;
1804 }
1805 return false;
1806}
1807
1808bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001809GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00001810{
1811 process_info.Clear();
1812
1813 if (m_supports_qProcessInfoPID)
1814 {
1815 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00001816 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001817 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00001818 StringExtractorGDBRemote response;
1819 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1820 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001821 return DecodeProcessInfoResponse (response, process_info);
1822 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001823 else
1824 {
1825 m_supports_qProcessInfoPID = false;
1826 return false;
1827 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001828 }
1829 return false;
1830}
1831
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001832bool
1833GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
1834{
1835 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1836 return true;
1837 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1838 return false;
1839
1840 GetHostInfo ();
1841
1842 StringExtractorGDBRemote response;
1843 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false))
1844 {
1845 if (response.IsNormalResponse())
1846 {
1847 std::string name;
1848 std::string value;
1849 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1850 uint32_t sub = 0;
1851 std::string arch_name;
1852 std::string os_name;
1853 std::string vendor_name;
1854 std::string triple;
1855 uint32_t pointer_byte_size = 0;
1856 StringExtractor extractor;
1857 ByteOrder byte_order = eByteOrderInvalid;
1858 uint32_t num_keys_decoded = 0;
1859 while (response.GetNameColonValue(name, value))
1860 {
1861 if (name.compare("cputype") == 0)
1862 {
1863 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
1864 if (cpu != LLDB_INVALID_CPUTYPE)
1865 ++num_keys_decoded;
1866 }
1867 else if (name.compare("cpusubtype") == 0)
1868 {
1869 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
1870 if (sub != 0)
1871 ++num_keys_decoded;
1872 }
1873 else if (name.compare("ostype") == 0)
1874 {
1875 os_name.swap (value);
1876 ++num_keys_decoded;
1877 }
1878 else if (name.compare("vendor") == 0)
1879 {
1880 vendor_name.swap(value);
1881 ++num_keys_decoded;
1882 }
1883 else if (name.compare("endian") == 0)
1884 {
1885 ++num_keys_decoded;
1886 if (value.compare("little") == 0)
1887 byte_order = eByteOrderLittle;
1888 else if (value.compare("big") == 0)
1889 byte_order = eByteOrderBig;
1890 else if (value.compare("pdp") == 0)
1891 byte_order = eByteOrderPDP;
1892 else
1893 --num_keys_decoded;
1894 }
1895 else if (name.compare("ptrsize") == 0)
1896 {
1897 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
1898 if (pointer_byte_size != 0)
1899 ++num_keys_decoded;
1900 }
1901 }
1902 if (num_keys_decoded > 0)
1903 m_qProcessInfo_is_valid = eLazyBoolYes;
1904 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
1905 {
1906 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1907 if (pointer_byte_size)
1908 {
1909 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
1910 }
1911 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1912 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1913 return true;
1914 }
1915 }
1916 }
1917 else
1918 {
1919 m_qProcessInfo_is_valid = eLazyBoolNo;
1920 }
1921
1922 return false;
1923}
1924
1925
Greg Clayton32e0a752011-03-30 18:16:51 +00001926uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001927GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
1928 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00001929{
1930 process_infos.Clear();
1931
1932 if (m_supports_qfProcessInfo)
1933 {
1934 StreamString packet;
1935 packet.PutCString ("qfProcessInfo");
1936 if (!match_info.MatchAllProcesses())
1937 {
1938 packet.PutChar (':');
1939 const char *name = match_info.GetProcessInfo().GetName();
1940 bool has_name_match = false;
1941 if (name && name[0])
1942 {
1943 has_name_match = true;
1944 NameMatchType name_match_type = match_info.GetNameMatchType();
1945 switch (name_match_type)
1946 {
1947 case eNameMatchIgnore:
1948 has_name_match = false;
1949 break;
1950
1951 case eNameMatchEquals:
1952 packet.PutCString ("name_match:equals;");
1953 break;
1954
1955 case eNameMatchContains:
1956 packet.PutCString ("name_match:contains;");
1957 break;
1958
1959 case eNameMatchStartsWith:
1960 packet.PutCString ("name_match:starts_with;");
1961 break;
1962
1963 case eNameMatchEndsWith:
1964 packet.PutCString ("name_match:ends_with;");
1965 break;
1966
1967 case eNameMatchRegularExpression:
1968 packet.PutCString ("name_match:regex;");
1969 break;
1970 }
1971 if (has_name_match)
1972 {
1973 packet.PutCString ("name:");
1974 packet.PutBytesAsRawHex8(name, ::strlen(name));
1975 packet.PutChar (';');
1976 }
1977 }
1978
1979 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00001980 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00001981 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00001982 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00001983 if (match_info.GetProcessInfo().UserIDIsValid())
1984 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
1985 if (match_info.GetProcessInfo().GroupIDIsValid())
1986 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00001987 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
1988 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
1989 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1990 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
1991 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1992 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
1993 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
1994 {
1995 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
1996 const llvm::Triple &triple = match_arch.GetTriple();
1997 packet.PutCString("triple:");
1998 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
1999 packet.PutChar (';');
2000 }
2001 }
2002 StringExtractorGDBRemote response;
2003 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
2004 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002005 do
2006 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002007 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002008 if (!DecodeProcessInfoResponse (response, process_info))
2009 break;
2010 process_infos.Append(process_info);
2011 response.GetStringRef().clear();
2012 response.SetFilePos(0);
2013 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false));
2014 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002015 else
2016 {
2017 m_supports_qfProcessInfo = false;
2018 return 0;
2019 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002020 }
2021 return process_infos.GetSize();
2022
2023}
2024
2025bool
2026GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2027{
2028 if (m_supports_qUserName)
2029 {
2030 char packet[32];
2031 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002032 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002033 StringExtractorGDBRemote response;
2034 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2035 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002036 if (response.IsNormalResponse())
2037 {
2038 // Make sure we parsed the right number of characters. The response is
2039 // the hex encoded user name and should make up the entire packet.
2040 // If there are any non-hex ASCII bytes, the length won't match below..
2041 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2042 return true;
2043 }
2044 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002045 else
2046 {
2047 m_supports_qUserName = false;
2048 return false;
2049 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002050 }
2051 return false;
2052
2053}
2054
2055bool
2056GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2057{
2058 if (m_supports_qGroupName)
2059 {
2060 char packet[32];
2061 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002062 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002063 StringExtractorGDBRemote response;
2064 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2065 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002066 if (response.IsNormalResponse())
2067 {
2068 // Make sure we parsed the right number of characters. The response is
2069 // the hex encoded group name and should make up the entire packet.
2070 // If there are any non-hex ASCII bytes, the length won't match below..
2071 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2072 return true;
2073 }
2074 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002075 else
2076 {
2077 m_supports_qGroupName = false;
2078 return false;
2079 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002080 }
2081 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002082}
Greg Clayton32e0a752011-03-30 18:16:51 +00002083
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002084void
2085GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2086{
2087 uint32_t i;
2088 TimeValue start_time, end_time;
2089 uint64_t total_time_nsec;
2090 float packets_per_second;
2091 if (SendSpeedTestPacket (0, 0))
2092 {
2093 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2)
2094 {
2095 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2)
2096 {
2097 start_time = TimeValue::Now();
2098 for (i=0; i<num_packets; ++i)
2099 {
2100 SendSpeedTestPacket (send_size, recv_size);
2101 }
2102 end_time = TimeValue::Now();
2103 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002104 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Daniel Malead01b2952012-11-29 21:49:15 +00002105 printf ("%u qSpeedTest(send=%-5u, recv=%-5u) in %" PRIu64 ".%9.9" PRIu64 " sec for %f packets/sec.\n",
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002106 num_packets,
2107 send_size,
2108 recv_size,
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002109 total_time_nsec / TimeValue::NanoSecPerSec,
2110 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002111 packets_per_second);
2112 if (recv_size == 0)
2113 recv_size = 32;
2114 }
2115 if (send_size == 0)
2116 send_size = 32;
2117 }
2118 }
2119 else
2120 {
2121 start_time = TimeValue::Now();
2122 for (i=0; i<num_packets; ++i)
2123 {
2124 GetCurrentProcessID ();
2125 }
2126 end_time = TimeValue::Now();
2127 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002128 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Daniel Malead01b2952012-11-29 21:49:15 +00002129 printf ("%u 'qC' packets packets in 0x%" PRIu64 "%9.9" PRIu64 " sec for %f packets/sec.\n",
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002130 num_packets,
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002131 total_time_nsec / TimeValue::NanoSecPerSec,
2132 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002133 packets_per_second);
2134 }
2135}
2136
2137bool
2138GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2139{
2140 StreamString packet;
2141 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2142 uint32_t bytes_left = send_size;
2143 while (bytes_left > 0)
2144 {
2145 if (bytes_left >= 26)
2146 {
2147 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2148 bytes_left -= 26;
2149 }
2150 else
2151 {
2152 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2153 bytes_left = 0;
2154 }
2155 }
2156
2157 StringExtractorGDBRemote response;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002158 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) > 0;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002159 return false;
Greg Clayton32e0a752011-03-30 18:16:51 +00002160}
Greg Clayton8b82f082011-04-12 05:54:46 +00002161
2162uint16_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002163GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002164{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002165 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00002166 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002167 StreamString stream;
2168 stream.PutCString("qLaunchGDBServer:port:0;");
2169 std::string hostname;
2170 if (Host::GetHostname (hostname))
2171 {
2172 // Make the GDB server we launch only accept connections from this host
2173 stream.Printf("host:%s;", hostname.c_str());
2174 }
2175 else
2176 {
2177 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2178 stream.Printf("host:*;");
2179 }
2180 const char *packet = stream.GetData();
2181 int packet_len = stream.GetSize();
2182
2183 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
Greg Clayton8b82f082011-04-12 05:54:46 +00002184 {
2185 std::string name;
2186 std::string value;
2187 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002188 while (response.GetNameColonValue(name, value))
2189 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00002190 if (name.compare("port") == 0)
Greg Clayton8b82f082011-04-12 05:54:46 +00002191 port = Args::StringToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002192 else if (name.compare("pid") == 0)
2193 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00002194 }
2195 return port;
2196 }
2197 return 0;
2198}
2199
2200bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00002201GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2202{
2203 StreamString stream;
2204 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2205 const char *packet = stream.GetData();
2206 int packet_len = stream.GetSize();
2207 pid = LLDB_INVALID_PROCESS_ID;
2208 StringExtractorGDBRemote response;
2209 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2210 {
2211 if (response.IsOKResponse())
2212 return true;
2213 }
2214 return false;
2215}
2216
2217bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002218GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002219{
2220 if (m_curr_tid == tid)
2221 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002222
Greg Clayton8b82f082011-04-12 05:54:46 +00002223 char packet[32];
2224 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002225 if (tid == UINT64_MAX)
2226 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002227 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002228 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002229 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002230 StringExtractorGDBRemote response;
2231 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2232 {
2233 if (response.IsOKResponse())
2234 {
2235 m_curr_tid = tid;
2236 return true;
2237 }
2238 }
2239 return false;
2240}
2241
2242bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002243GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002244{
2245 if (m_curr_tid_run == tid)
2246 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002247
Greg Clayton8b82f082011-04-12 05:54:46 +00002248 char packet[32];
2249 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002250 if (tid == UINT64_MAX)
2251 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002252 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002253 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2254
Andy Gibbsa297a972013-06-19 19:04:53 +00002255 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002256 StringExtractorGDBRemote response;
2257 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2258 {
2259 if (response.IsOKResponse())
2260 {
2261 m_curr_tid_run = tid;
2262 return true;
2263 }
2264 }
2265 return false;
2266}
2267
2268bool
2269GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2270{
2271 if (SendPacketAndWaitForResponse("?", 1, response, false))
2272 return response.IsNormalResponse();
2273 return false;
2274}
2275
2276bool
Greg Claytonf402f782012-10-13 02:11:55 +00002277GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00002278{
2279 if (m_supports_qThreadStopInfo)
2280 {
2281 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00002282 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002283 assert (packet_len < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002284 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2285 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00002286 if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002287 return true;
2288 else
2289 return false;
2290 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002291 else
2292 {
2293 m_supports_qThreadStopInfo = false;
2294 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002295 }
Greg Clayton5fe15d22011-05-20 03:15:54 +00002296// if (SetCurrentThread (tid))
2297// return GetStopReply (response);
Greg Clayton8b82f082011-04-12 05:54:46 +00002298 return false;
2299}
2300
2301
2302uint8_t
2303GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2304{
2305 switch (type)
2306 {
2307 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break;
2308 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break;
2309 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break;
2310 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break;
2311 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break;
Greg Clayton8b82f082011-04-12 05:54:46 +00002312 }
2313
2314 char packet[64];
2315 const int packet_len = ::snprintf (packet,
2316 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00002317 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00002318 insert ? 'Z' : 'z',
2319 type,
2320 addr,
2321 length);
2322
Andy Gibbsa297a972013-06-19 19:04:53 +00002323 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002324 StringExtractorGDBRemote response;
2325 if (SendPacketAndWaitForResponse(packet, packet_len, response, true))
2326 {
2327 if (response.IsOKResponse())
2328 return 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002329 else if (response.IsErrorResponse())
2330 return response.GetError();
2331 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002332 else
2333 {
2334 switch (type)
2335 {
2336 case eBreakpointSoftware: m_supports_z0 = false; break;
2337 case eBreakpointHardware: m_supports_z1 = false; break;
2338 case eWatchpointWrite: m_supports_z2 = false; break;
2339 case eWatchpointRead: m_supports_z3 = false; break;
2340 case eWatchpointReadWrite: m_supports_z4 = false; break;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002341 }
2342 }
2343
Greg Clayton8b82f082011-04-12 05:54:46 +00002344 return UINT8_MAX;
2345}
Greg Claytonadc00cb2011-05-20 23:38:13 +00002346
2347size_t
2348GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2349 bool &sequence_mutex_unavailable)
2350{
2351 Mutex::Locker locker;
2352 thread_ids.clear();
2353
Jim Ingham4ceb9282012-06-08 22:50:40 +00002354 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002355 {
2356 sequence_mutex_unavailable = false;
2357 StringExtractorGDBRemote response;
2358
Greg Clayton73bf5db2011-06-17 01:22:15 +00002359 for (SendPacketNoLock ("qfThreadInfo", strlen("qfThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
Greg Claytonadc00cb2011-05-20 23:38:13 +00002360 response.IsNormalResponse();
Greg Clayton73bf5db2011-06-17 01:22:15 +00002361 SendPacketNoLock ("qsThreadInfo", strlen("qsThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ()))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002362 {
2363 char ch = response.GetChar();
2364 if (ch == 'l')
2365 break;
2366 if (ch == 'm')
2367 {
2368 do
2369 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00002370 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00002371
2372 if (tid != LLDB_INVALID_THREAD_ID)
2373 {
2374 thread_ids.push_back (tid);
2375 }
2376 ch = response.GetChar(); // Skip the command separator
2377 } while (ch == ','); // Make sure we got a comma separator
2378 }
2379 }
2380 }
2381 else
2382 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00002383#if defined (LLDB_CONFIGURATION_DEBUG)
2384 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2385#else
Greg Clayton5160ce52013-03-27 23:08:40 +00002386 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00002387 if (log)
2388 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00002389#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00002390 sequence_mutex_unavailable = true;
2391 }
2392 return thread_ids.size();
2393}
Greg Clayton37a0a242012-04-11 00:24:49 +00002394
2395lldb::addr_t
2396GDBRemoteCommunicationClient::GetShlibInfoAddr()
2397{
2398 if (!IsRunning())
2399 {
2400 StringExtractorGDBRemote response;
2401 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
2402 {
2403 if (response.IsNormalResponse())
2404 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2405 }
2406 }
2407 return LLDB_INVALID_ADDRESS;
2408}
2409
Daniel Maleae0f8f572013-08-26 23:57:52 +00002410lldb_private::Error
2411GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL
2412 const char *working_dir, // Pass NULL to use the current working directory
2413 int *status_ptr, // Pass NULL if you don't want the process exit status
2414 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
2415 std::string *command_output, // Pass NULL if you don't want the command output
2416 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
2417{
2418 lldb_private::StreamString stream;
2419 stream.PutCString("qPlatform_RunCommand:");
2420 stream.PutBytesAsRawHex8(command, strlen(command));
2421 stream.PutChar(',');
2422 stream.PutHex32(timeout_sec);
2423 if (working_dir && *working_dir)
2424 {
2425 stream.PutChar(',');
2426 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
2427 }
2428 const char *packet = stream.GetData();
2429 int packet_len = stream.GetSize();
2430 StringExtractorGDBRemote response;
2431 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2432 {
2433 if (response.GetChar() != 'F')
2434 return Error("malformed reply");
2435 if (response.GetChar() != ',')
2436 return Error("malformed reply");
2437 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2438 if (exitcode == UINT32_MAX)
2439 return Error("unable to run remote process");
2440 else if (status_ptr)
2441 *status_ptr = exitcode;
2442 if (response.GetChar() != ',')
2443 return Error("malformed reply");
2444 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2445 if (signo_ptr)
2446 *signo_ptr = signo;
2447 if (response.GetChar() != ',')
2448 return Error("malformed reply");
2449 std::string output;
2450 response.GetEscapedBinaryData(output);
2451 if (command_output)
2452 command_output->assign(output);
2453 return Error();
2454 }
2455 return Error("unable to send packet");
2456}
2457
2458uint32_t
2459GDBRemoteCommunicationClient::MakeDirectory (const std::string &path,
2460 mode_t mode)
2461{
2462 lldb_private::StreamString stream;
2463 stream.PutCString("qPlatform_IO_MkDir:");
2464 stream.PutHex32(mode);
2465 stream.PutChar(',');
2466 stream.PutBytesAsRawHex8(path.c_str(), path.size());
2467 const char *packet = stream.GetData();
2468 int packet_len = stream.GetSize();
2469 StringExtractorGDBRemote response;
2470 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2471 {
2472 return response.GetHexMaxU32(false, UINT32_MAX);
2473 }
2474 return UINT32_MAX;
2475
2476}
2477
2478static uint64_t
2479ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
2480 uint64_t fail_result,
2481 Error &error)
2482{
2483 response.SetFilePos(0);
2484 if (response.GetChar() != 'F')
2485 return fail_result;
2486 int32_t result = response.GetS32 (-2);
2487 if (result == -2)
2488 return fail_result;
2489 if (response.GetChar() == ',')
2490 {
2491 int result_errno = response.GetS32 (-2);
2492 if (result_errno != -2)
2493 error.SetError(result_errno, eErrorTypePOSIX);
2494 else
2495 error.SetError(-1, eErrorTypeGeneric);
2496 }
2497 else
2498 error.Clear();
2499 return result;
2500}
2501lldb::user_id_t
2502GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
2503 uint32_t flags,
2504 mode_t mode,
2505 Error &error)
2506{
2507 lldb_private::StreamString stream;
2508 stream.PutCString("vFile:open:");
2509 std::string path (file_spec.GetPath());
2510 if (path.empty())
2511 return UINT64_MAX;
2512 stream.PutCStringAsRawHex8(path.c_str());
2513 stream.PutChar(',');
2514 const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags);
2515 stream.PutHex32(posix_open_flags);
2516 stream.PutChar(',');
2517 stream.PutHex32(mode);
2518 const char* packet = stream.GetData();
2519 int packet_len = stream.GetSize();
2520 StringExtractorGDBRemote response;
2521 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2522 {
2523 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
2524 }
2525 return UINT64_MAX;
2526}
2527
2528bool
2529GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
2530 Error &error)
2531{
2532 lldb_private::StreamString stream;
2533 stream.Printf("vFile:close:%i", (int)fd);
2534 const char* packet = stream.GetData();
2535 int packet_len = stream.GetSize();
2536 StringExtractorGDBRemote response;
2537 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2538 {
2539 return ParseHostIOPacketResponse (response, -1, error) == 0;
2540 }
2541 return UINT64_MAX;
2542}
2543
2544// Extension of host I/O packets to get the file size.
2545lldb::user_id_t
2546GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
2547{
2548 lldb_private::StreamString stream;
2549 stream.PutCString("vFile:size:");
2550 std::string path (file_spec.GetPath());
2551 stream.PutCStringAsRawHex8(path.c_str());
2552 const char* packet = stream.GetData();
2553 int packet_len = stream.GetSize();
2554 StringExtractorGDBRemote response;
2555 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2556 {
2557 if (response.GetChar() != 'F')
2558 return UINT64_MAX;
2559 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2560 return retcode;
2561 }
2562 return UINT64_MAX;
2563}
2564
2565uint32_t
2566GDBRemoteCommunicationClient::GetFilePermissions(const lldb_private::FileSpec& file_spec, Error &error)
2567{
2568 lldb_private::StreamString stream;
2569 stream.PutCString("vFile:mode:");
2570 std::string path (file_spec.GetPath());
2571 stream.PutCStringAsRawHex8(path.c_str());
2572 const char* packet = stream.GetData();
2573 int packet_len = stream.GetSize();
2574 StringExtractorGDBRemote response;
2575 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2576 {
2577 if (response.GetChar() != 'F')
2578 {
2579 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
2580 return 0;
2581 }
2582 const uint32_t mode = response.GetS32(-1);
2583 if (mode == -1)
2584 {
2585 if (response.GetChar() == ',')
2586 {
2587 int response_errno = response.GetS32(-1);
2588 if (response_errno > 0)
2589 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2590 else
2591 error.SetErrorToGenericError();
2592 }
2593 }
2594 else
2595 error.Clear();
2596 return mode & (S_IRWXU|S_IRWXG|S_IRWXO);
2597 }
2598 else
2599 {
2600 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
2601 }
2602 return 0;
2603}
2604
2605uint64_t
2606GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
2607 uint64_t offset,
2608 void *dst,
2609 uint64_t dst_len,
2610 Error &error)
2611{
2612 lldb_private::StreamString stream;
2613 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
2614 const char* packet = stream.GetData();
2615 int packet_len = stream.GetSize();
2616 StringExtractorGDBRemote response;
2617 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2618 {
2619 if (response.GetChar() != 'F')
2620 return 0;
2621 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2622 if (retcode == UINT32_MAX)
2623 return retcode;
2624 const char next = (response.Peek() ? *response.Peek() : 0);
2625 if (next == ',')
2626 return 0;
2627 if (next == ';')
2628 {
2629 response.GetChar(); // skip the semicolon
2630 std::string buffer;
2631 if (response.GetEscapedBinaryData(buffer))
2632 {
2633 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
2634 if (data_to_write > 0)
2635 memcpy(dst, &buffer[0], data_to_write);
2636 return data_to_write;
2637 }
2638 }
2639 }
2640 return 0;
2641}
2642
2643uint64_t
2644GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
2645 uint64_t offset,
2646 const void* src,
2647 uint64_t src_len,
2648 Error &error)
2649{
2650 lldb_private::StreamGDBRemote stream;
2651 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2652 stream.PutEscapedBytes(src, src_len);
2653 const char* packet = stream.GetData();
2654 int packet_len = stream.GetSize();
2655 StringExtractorGDBRemote response;
2656 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2657 {
2658 if (response.GetChar() != 'F')
2659 {
2660 error.SetErrorStringWithFormat("write file failed");
2661 return 0;
2662 }
2663 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2664 if (bytes_written == UINT64_MAX)
2665 {
2666 error.SetErrorToGenericError();
2667 if (response.GetChar() == ',')
2668 {
2669 int response_errno = response.GetS32(-1);
2670 if (response_errno > 0)
2671 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2672 }
2673 return 0;
2674 }
2675 return bytes_written;
2676 }
2677 else
2678 {
2679 error.SetErrorString ("failed to send vFile:pwrite packet");
2680 }
2681 return 0;
2682}
2683
2684// Extension of host I/O packets to get whether a file exists.
2685bool
2686GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
2687{
2688 lldb_private::StreamString stream;
2689 stream.PutCString("vFile:exists:");
2690 std::string path (file_spec.GetPath());
2691 stream.PutCStringAsRawHex8(path.c_str());
2692 const char* packet = stream.GetData();
2693 int packet_len = stream.GetSize();
2694 StringExtractorGDBRemote response;
2695 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2696 {
2697 if (response.GetChar() != 'F')
2698 return false;
2699 if (response.GetChar() != ',')
2700 return false;
2701 bool retcode = (response.GetChar() != '0');
2702 return retcode;
2703 }
2704 return false;
2705}
2706
2707bool
2708GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
2709 uint64_t &high,
2710 uint64_t &low)
2711{
2712 lldb_private::StreamString stream;
2713 stream.PutCString("vFile:MD5:");
2714 std::string path (file_spec.GetPath());
2715 stream.PutCStringAsRawHex8(path.c_str());
2716 const char* packet = stream.GetData();
2717 int packet_len = stream.GetSize();
2718 StringExtractorGDBRemote response;
2719 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2720 {
2721 if (response.GetChar() != 'F')
2722 return false;
2723 if (response.GetChar() != ',')
2724 return false;
2725 if (response.Peek() && *response.Peek() == 'x')
2726 return false;
2727 low = response.GetHexMaxU64(false, UINT64_MAX);
2728 high = response.GetHexMaxU64(false, UINT64_MAX);
2729 return true;
2730 }
2731 return false;
2732}