blob: 3f702be1b57f4358ee05da1a8f26e429a2339464 [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),
Greg Clayton32e0a752011-03-30 18:16:51 +000067 m_supports_qProcessInfoPID (true),
68 m_supports_qfProcessInfo (true),
69 m_supports_qUserName (true),
70 m_supports_qGroupName (true),
Greg Clayton8b82f082011-04-12 05:54:46 +000071 m_supports_qThreadStopInfo (true),
72 m_supports_z0 (true),
73 m_supports_z1 (true),
74 m_supports_z2 (true),
75 m_supports_z3 (true),
76 m_supports_z4 (true),
77 m_curr_tid (LLDB_INVALID_THREAD_ID),
78 m_curr_tid_run (LLDB_INVALID_THREAD_ID),
Johnny Chen64637202012-05-23 21:09:52 +000079 m_num_supported_hardware_watchpoints (0),
Greg Clayton576d8832011-03-22 04:00:09 +000080 m_async_mutex (Mutex::eMutexTypeRecursive),
81 m_async_packet_predicate (false),
82 m_async_packet (),
83 m_async_response (),
84 m_async_signal (-1),
Han Ming Ong4b6459f2013-01-18 23:11:53 +000085 m_thread_id_to_used_usec_map (),
Greg Clayton1cb64962011-03-24 04:28:38 +000086 m_host_arch(),
Jason Molendaf17b5ac2012-12-19 02:54:03 +000087 m_process_arch(),
Greg Clayton1cb64962011-03-24 04:28:38 +000088 m_os_version_major (UINT32_MAX),
89 m_os_version_minor (UINT32_MAX),
90 m_os_version_update (UINT32_MAX)
Greg Clayton576d8832011-03-22 04:00:09 +000091{
Greg Clayton576d8832011-03-22 04:00:09 +000092}
93
94//----------------------------------------------------------------------
95// Destructor
96//----------------------------------------------------------------------
97GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient()
98{
Greg Clayton576d8832011-03-22 04:00:09 +000099 if (IsConnected())
Greg Clayton576d8832011-03-22 04:00:09 +0000100 Disconnect();
Greg Clayton576d8832011-03-22 04:00:09 +0000101}
102
103bool
Greg Clayton1cb64962011-03-24 04:28:38 +0000104GDBRemoteCommunicationClient::HandshakeWithServer (Error *error_ptr)
105{
106 // Start the read thread after we send the handshake ack since if we
107 // fail to send the handshake ack, there is no reason to continue...
108 if (SendAck())
Greg Clayton73bf5db2011-06-17 01:22:15 +0000109 return true;
Greg Clayton1cb64962011-03-24 04:28:38 +0000110
111 if (error_ptr)
112 error_ptr->SetErrorString("failed to send the handshake ack");
113 return false;
114}
115
116void
117GDBRemoteCommunicationClient::QueryNoAckModeSupported ()
Greg Clayton576d8832011-03-22 04:00:09 +0000118{
119 if (m_supports_not_sending_acks == eLazyBoolCalculate)
120 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000121 m_send_acks = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000122 m_supports_not_sending_acks = eLazyBoolNo;
Greg Clayton1cb64962011-03-24 04:28:38 +0000123
124 StringExtractorGDBRemote response;
Greg Clayton576d8832011-03-22 04:00:09 +0000125 if (SendPacketAndWaitForResponse("QStartNoAckMode", response, false))
126 {
127 if (response.IsOKResponse())
Greg Clayton1cb64962011-03-24 04:28:38 +0000128 {
129 m_send_acks = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000130 m_supports_not_sending_acks = eLazyBoolYes;
Greg Clayton1cb64962011-03-24 04:28:38 +0000131 }
Greg Clayton576d8832011-03-22 04:00:09 +0000132 }
133 }
Greg Clayton576d8832011-03-22 04:00:09 +0000134}
135
136void
Greg Clayton44633992012-04-10 03:22:03 +0000137GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported ()
138{
139 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate)
140 {
141 m_supports_threads_in_stop_reply = eLazyBoolNo;
142
143 StringExtractorGDBRemote response;
144 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response, false))
145 {
146 if (response.IsOKResponse())
147 m_supports_threads_in_stop_reply = eLazyBoolYes;
148 }
149 }
150}
151
Jim Inghamcd16df92012-07-20 21:37:13 +0000152bool
153GDBRemoteCommunicationClient::GetVAttachOrWaitSupported ()
154{
155 if (m_attach_or_wait_reply == eLazyBoolCalculate)
156 {
157 m_attach_or_wait_reply = eLazyBoolNo;
158
159 StringExtractorGDBRemote response;
160 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response, false))
161 {
162 if (response.IsOKResponse())
163 m_attach_or_wait_reply = eLazyBoolYes;
164 }
165 }
166 if (m_attach_or_wait_reply == eLazyBoolYes)
167 return true;
168 else
169 return false;
170}
171
Jim Ingham279ceec2012-07-25 21:12:43 +0000172bool
173GDBRemoteCommunicationClient::GetSyncThreadStateSupported ()
174{
175 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate)
176 {
177 m_prepare_for_reg_writing_reply = eLazyBoolNo;
178
179 StringExtractorGDBRemote response;
180 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response, false))
181 {
182 if (response.IsOKResponse())
183 m_prepare_for_reg_writing_reply = eLazyBoolYes;
184 }
185 }
186 if (m_prepare_for_reg_writing_reply == eLazyBoolYes)
187 return true;
188 else
189 return false;
190}
191
Greg Clayton44633992012-04-10 03:22:03 +0000192
193void
Greg Clayton576d8832011-03-22 04:00:09 +0000194GDBRemoteCommunicationClient::ResetDiscoverableSettings()
195{
196 m_supports_not_sending_acks = eLazyBoolCalculate;
197 m_supports_thread_suffix = eLazyBoolCalculate;
Greg Clayton44633992012-04-10 03:22:03 +0000198 m_supports_threads_in_stop_reply = eLazyBoolCalculate;
Greg Clayton576d8832011-03-22 04:00:09 +0000199 m_supports_vCont_c = eLazyBoolCalculate;
200 m_supports_vCont_C = eLazyBoolCalculate;
201 m_supports_vCont_s = eLazyBoolCalculate;
202 m_supports_vCont_S = eLazyBoolCalculate;
Greg Clayton32e0a752011-03-30 18:16:51 +0000203 m_qHostInfo_is_valid = eLazyBoolCalculate;
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000204 m_qProcessInfo_is_valid = eLazyBoolCalculate;
Greg Clayton70b57652011-05-15 01:25:55 +0000205 m_supports_alloc_dealloc_memory = eLazyBoolCalculate;
Greg Clayton46fb5582011-11-18 07:03:08 +0000206 m_supports_memory_region_info = eLazyBoolCalculate;
Jim Ingham279ceec2012-07-25 21:12:43 +0000207 m_prepare_for_reg_writing_reply = eLazyBoolCalculate;
208 m_attach_or_wait_reply = eLazyBoolCalculate;
Greg Clayton2a48f522011-05-14 01:50:35 +0000209
Greg Clayton32e0a752011-03-30 18:16:51 +0000210 m_supports_qProcessInfoPID = true;
211 m_supports_qfProcessInfo = true;
212 m_supports_qUserName = true;
213 m_supports_qGroupName = true;
Greg Clayton8b82f082011-04-12 05:54:46 +0000214 m_supports_qThreadStopInfo = true;
215 m_supports_z0 = true;
216 m_supports_z1 = true;
217 m_supports_z2 = true;
218 m_supports_z3 = true;
219 m_supports_z4 = true;
Greg Claytond314e812011-03-23 00:09:55 +0000220 m_host_arch.Clear();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000221 m_process_arch.Clear();
Greg Clayton576d8832011-03-22 04:00:09 +0000222}
223
224
225bool
226GDBRemoteCommunicationClient::GetThreadSuffixSupported ()
227{
228 if (m_supports_thread_suffix == eLazyBoolCalculate)
229 {
230 StringExtractorGDBRemote response;
231 m_supports_thread_suffix = eLazyBoolNo;
232 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response, false))
233 {
234 if (response.IsOKResponse())
235 m_supports_thread_suffix = eLazyBoolYes;
236 }
237 }
238 return m_supports_thread_suffix;
239}
240bool
241GDBRemoteCommunicationClient::GetVContSupported (char flavor)
242{
243 if (m_supports_vCont_c == eLazyBoolCalculate)
244 {
245 StringExtractorGDBRemote response;
246 m_supports_vCont_any = eLazyBoolNo;
247 m_supports_vCont_all = eLazyBoolNo;
248 m_supports_vCont_c = eLazyBoolNo;
249 m_supports_vCont_C = eLazyBoolNo;
250 m_supports_vCont_s = eLazyBoolNo;
251 m_supports_vCont_S = eLazyBoolNo;
252 if (SendPacketAndWaitForResponse("vCont?", response, false))
253 {
254 const char *response_cstr = response.GetStringRef().c_str();
255 if (::strstr (response_cstr, ";c"))
256 m_supports_vCont_c = eLazyBoolYes;
257
258 if (::strstr (response_cstr, ";C"))
259 m_supports_vCont_C = eLazyBoolYes;
260
261 if (::strstr (response_cstr, ";s"))
262 m_supports_vCont_s = eLazyBoolYes;
263
264 if (::strstr (response_cstr, ";S"))
265 m_supports_vCont_S = eLazyBoolYes;
266
267 if (m_supports_vCont_c == eLazyBoolYes &&
268 m_supports_vCont_C == eLazyBoolYes &&
269 m_supports_vCont_s == eLazyBoolYes &&
270 m_supports_vCont_S == eLazyBoolYes)
271 {
272 m_supports_vCont_all = eLazyBoolYes;
273 }
274
275 if (m_supports_vCont_c == eLazyBoolYes ||
276 m_supports_vCont_C == eLazyBoolYes ||
277 m_supports_vCont_s == eLazyBoolYes ||
278 m_supports_vCont_S == eLazyBoolYes)
279 {
280 m_supports_vCont_any = eLazyBoolYes;
281 }
282 }
283 }
284
285 switch (flavor)
286 {
287 case 'a': return m_supports_vCont_any;
288 case 'A': return m_supports_vCont_all;
289 case 'c': return m_supports_vCont_c;
290 case 'C': return m_supports_vCont_C;
291 case 's': return m_supports_vCont_s;
292 case 'S': return m_supports_vCont_S;
293 default: break;
294 }
295 return false;
296}
297
298
299size_t
300GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
301(
302 const char *payload,
303 StringExtractorGDBRemote &response,
304 bool send_async
305)
306{
307 return SendPacketAndWaitForResponse (payload,
308 ::strlen (payload),
309 response,
310 send_async);
311}
312
313size_t
314GDBRemoteCommunicationClient::SendPacketAndWaitForResponse
315(
316 const char *payload,
317 size_t payload_length,
318 StringExtractorGDBRemote &response,
319 bool send_async
320)
321{
322 Mutex::Locker locker;
Greg Clayton5160ce52013-03-27 23:08:40 +0000323 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton644247c2011-07-07 01:59:51 +0000324 size_t response_len = 0;
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000325 if (GetSequenceMutex (locker))
Greg Clayton576d8832011-03-22 04:00:09 +0000326 {
Greg Clayton5fe15d22011-05-20 03:15:54 +0000327 if (SendPacketNoLock (payload, payload_length))
Greg Clayton644247c2011-07-07 01:59:51 +0000328 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
329 else
330 {
331 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000332 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
Greg Clayton644247c2011-07-07 01:59:51 +0000333 }
Greg Clayton576d8832011-03-22 04:00:09 +0000334 }
335 else
336 {
337 if (send_async)
338 {
Greg Claytond3544052012-05-31 21:24:20 +0000339 if (IsRunning())
Greg Clayton576d8832011-03-22 04:00:09 +0000340 {
Greg Claytond3544052012-05-31 21:24:20 +0000341 Mutex::Locker async_locker (m_async_mutex);
342 m_async_packet.assign(payload, payload_length);
343 m_async_packet_predicate.SetValue (true, eBroadcastNever);
344
345 if (log)
346 log->Printf ("async: async packet = %s", m_async_packet.c_str());
347
348 bool timed_out = false;
349 if (SendInterrupt(locker, 2, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000350 {
Greg Claytond3544052012-05-31 21:24:20 +0000351 if (m_interrupt_sent)
Greg Clayton576d8832011-03-22 04:00:09 +0000352 {
Jim Inghambabfc382012-06-06 00:32:39 +0000353 m_interrupt_sent = false;
Greg Claytond3544052012-05-31 21:24:20 +0000354 TimeValue timeout_time;
355 timeout_time = TimeValue::Now();
356 timeout_time.OffsetWithSeconds (m_packet_timeout);
357
Greg Clayton576d8832011-03-22 04:00:09 +0000358 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000359 log->Printf ("async: sent interrupt");
Greg Clayton644247c2011-07-07 01:59:51 +0000360
Greg Claytond3544052012-05-31 21:24:20 +0000361 if (m_async_packet_predicate.WaitForValueEqualTo (false, &timeout_time, &timed_out))
Greg Claytone889ad62011-10-27 22:04:16 +0000362 {
Greg Claytond3544052012-05-31 21:24:20 +0000363 if (log)
364 log->Printf ("async: got response");
365
366 // Swap the response buffer to avoid malloc and string copy
367 response.GetStringRef().swap (m_async_response.GetStringRef());
368 response_len = response.GetStringRef().size();
369 }
370 else
371 {
372 if (log)
373 log->Printf ("async: timed out waiting for response");
374 }
375
376 // Make sure we wait until the continue packet has been sent again...
377 if (m_private_is_running.WaitForValueEqualTo (true, &timeout_time, &timed_out))
378 {
379 if (log)
380 {
381 if (timed_out)
382 log->Printf ("async: timed out waiting for process to resume, but process was resumed");
383 else
384 log->Printf ("async: async packet sent");
385 }
386 }
387 else
388 {
389 if (log)
390 log->Printf ("async: timed out waiting for process to resume");
Greg Claytone889ad62011-10-27 22:04:16 +0000391 }
392 }
393 else
394 {
Greg Claytond3544052012-05-31 21:24:20 +0000395 // We had a racy condition where we went to send the interrupt
396 // yet we were able to get the lock, so the process must have
397 // just stopped?
Greg Clayton576d8832011-03-22 04:00:09 +0000398 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000399 log->Printf ("async: got lock without sending interrupt");
400 // Send the packet normally since we got the lock
401 if (SendPacketNoLock (payload, payload_length))
402 response_len = WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
403 else
404 {
405 if (log)
406 log->Printf("error: failed to send '%*s'", (int) payload_length, payload);
407 }
Greg Clayton576d8832011-03-22 04:00:09 +0000408 }
409 }
410 else
411 {
Greg Clayton644247c2011-07-07 01:59:51 +0000412 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000413 log->Printf ("async: failed to interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000414 }
415 }
416 else
417 {
418 if (log)
Greg Claytond3544052012-05-31 21:24:20 +0000419 log->Printf ("async: not running, async is ignored");
Greg Clayton576d8832011-03-22 04:00:09 +0000420 }
421 }
422 else
423 {
424 if (log)
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000425 log->Printf("error: failed to get packet sequence mutex, not sending packet '%*s'", (int) payload_length, payload);
Greg Clayton576d8832011-03-22 04:00:09 +0000426 }
427 }
Greg Clayton644247c2011-07-07 01:59:51 +0000428 if (response_len == 0)
429 {
430 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000431 log->Printf("error: failed to get response for '%*s'", (int) payload_length, payload);
Greg Clayton644247c2011-07-07 01:59:51 +0000432 }
433 return response_len;
Greg Clayton576d8832011-03-22 04:00:09 +0000434}
435
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000436static const char *end_delimiter = "--end--;";
437static const int end_delimiter_len = 8;
438
439std::string
440GDBRemoteCommunicationClient::HarmonizeThreadIdsForProfileData
441( ProcessGDBRemote *process,
442 StringExtractorGDBRemote& profileDataExtractor
443)
444{
445 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
446 std::stringstream final_output;
447 std::string name, value;
448
449 // Going to assuming thread_used_usec comes first, else bail out.
450 while (profileDataExtractor.GetNameColonValue(name, value))
451 {
452 if (name.compare("thread_used_id") == 0)
453 {
454 StringExtractor threadIDHexExtractor(value.c_str());
455 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
456
457 bool has_used_usec = false;
458 uint32_t curr_used_usec = 0;
459 std::string usec_name, usec_value;
460 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
461 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value))
462 {
463 if (usec_name.compare("thread_used_usec") == 0)
464 {
465 has_used_usec = true;
466 curr_used_usec = strtoull(usec_value.c_str(), NULL, 0);
467 }
468 else
469 {
470 // We didn't find what we want, it is probably
471 // an older version. Bail out.
472 profileDataExtractor.SetFilePos(input_file_pos);
473 }
474 }
475
476 if (has_used_usec)
477 {
478 uint32_t prev_used_usec = 0;
479 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id);
480 if (iterator != m_thread_id_to_used_usec_map.end())
481 {
482 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
483 }
484
485 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
486 // A good first time record is one that runs for at least 0.25 sec
487 bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000);
488 bool good_subsequent_time = (prev_used_usec > 0) &&
489 ((real_used_usec > 0) || (process->HasAssignedIndexIDToThread(thread_id)));
490
491 if (good_first_time || good_subsequent_time)
492 {
493 // We try to avoid doing too many index id reservation,
494 // resulting in fast increase of index ids.
495
496 final_output << name << ":";
497 int32_t index_id = process->AssignIndexIDToThread(thread_id);
498 final_output << index_id << ";";
499
500 final_output << usec_name << ":" << usec_value << ";";
501 }
502 else
503 {
504 // Skip past 'thread_used_name'.
505 std::string local_name, local_value;
506 profileDataExtractor.GetNameColonValue(local_name, local_value);
507 }
508
509 // Store current time as previous time so that they can be compared later.
510 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
511 }
512 else
513 {
514 // Bail out and use old string.
515 final_output << name << ":" << value << ";";
516 }
517 }
518 else
519 {
520 final_output << name << ":" << value << ";";
521 }
522 }
523 final_output << end_delimiter;
524 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
525
526 return final_output.str();
527}
528
Greg Clayton576d8832011-03-22 04:00:09 +0000529StateType
530GDBRemoteCommunicationClient::SendContinuePacketAndWaitForResponse
531(
532 ProcessGDBRemote *process,
533 const char *payload,
534 size_t packet_length,
535 StringExtractorGDBRemote &response
536)
537{
Greg Clayton1f5181a2012-07-02 22:05:25 +0000538 m_curr_tid = LLDB_INVALID_THREAD_ID;
Greg Clayton5160ce52013-03-27 23:08:40 +0000539 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton576d8832011-03-22 04:00:09 +0000540 if (log)
541 log->Printf ("GDBRemoteCommunicationClient::%s ()", __FUNCTION__);
542
543 Mutex::Locker locker(m_sequence_mutex);
544 StateType state = eStateRunning;
545
546 BroadcastEvent(eBroadcastBitRunPacketSent, NULL);
547 m_public_is_running.SetValue (true, eBroadcastNever);
548 // Set the starting continue packet into "continue_packet". This packet
Jim Inghambabfc382012-06-06 00:32:39 +0000549 // may change if we are interrupted and we continue after an async packet...
Greg Clayton576d8832011-03-22 04:00:09 +0000550 std::string continue_packet(payload, packet_length);
551
Greg Clayton3f875c52013-02-22 22:23:55 +0000552 bool got_async_packet = false;
Greg Claytonaf247d72011-05-19 03:54:16 +0000553
Greg Clayton576d8832011-03-22 04:00:09 +0000554 while (state == eStateRunning)
555 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000556 if (!got_async_packet)
Greg Claytonaf247d72011-05-19 03:54:16 +0000557 {
558 if (log)
559 log->Printf ("GDBRemoteCommunicationClient::%s () sending continue packet: %s", __FUNCTION__, continue_packet.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +0000560 if (SendPacketNoLock(continue_packet.c_str(), continue_packet.size()) == 0)
Greg Claytonaf247d72011-05-19 03:54:16 +0000561 state = eStateInvalid;
Greg Clayton576d8832011-03-22 04:00:09 +0000562
Greg Claytone889ad62011-10-27 22:04:16 +0000563 m_private_is_running.SetValue (true, eBroadcastAlways);
Greg Claytonaf247d72011-05-19 03:54:16 +0000564 }
565
Greg Clayton3f875c52013-02-22 22:23:55 +0000566 got_async_packet = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000567
568 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000569 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(%s)", __FUNCTION__, continue_packet.c_str());
Greg Clayton576d8832011-03-22 04:00:09 +0000570
Greg Clayton37a0a242012-04-11 00:24:49 +0000571 if (WaitForPacketWithTimeoutMicroSecondsNoLock(response, UINT32_MAX))
Greg Clayton576d8832011-03-22 04:00:09 +0000572 {
573 if (response.Empty())
574 state = eStateInvalid;
575 else
576 {
577 const char stop_type = response.GetChar();
578 if (log)
579 log->Printf ("GDBRemoteCommunicationClient::%s () got packet: %s", __FUNCTION__, response.GetStringRef().c_str());
580 switch (stop_type)
581 {
582 case 'T':
583 case 'S':
Greg Clayton576d8832011-03-22 04:00:09 +0000584 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000585 if (process->GetStopID() == 0)
Greg Clayton576d8832011-03-22 04:00:09 +0000586 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000587 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
588 {
589 lldb::pid_t pid = GetCurrentProcessID ();
590 if (pid != LLDB_INVALID_PROCESS_ID)
591 process->SetID (pid);
592 }
593 process->BuildDynamicRegisterInfo (true);
Greg Clayton576d8832011-03-22 04:00:09 +0000594 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000595
596 // Privately notify any internal threads that we have stopped
597 // in case we wanted to interrupt our process, yet we might
598 // send a packet and continue without returning control to the
599 // user.
600 m_private_is_running.SetValue (false, eBroadcastAlways);
601
602 const uint8_t signo = response.GetHexU8 (UINT8_MAX);
603
Jim Inghambabfc382012-06-06 00:32:39 +0000604 bool continue_after_async = m_async_signal != -1 || m_async_packet_predicate.GetValue();
605 if (continue_after_async || m_interrupt_sent)
Greg Clayton2687cd12012-03-29 01:55:41 +0000606 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000607 // We sent an interrupt packet to stop the inferior process
608 // for an async signal or to send an async packet while running
609 // but we might have been single stepping and received the
610 // stop packet for the step instead of for the interrupt packet.
611 // Typically when an interrupt is sent a SIGINT or SIGSTOP
612 // is used, so if we get anything else, we need to try and
613 // get another stop reply packet that may have been sent
614 // due to sending the interrupt when the target is stopped
615 // which will just re-send a copy of the last stop reply
616 // packet. If we don't do this, then the reply for our
617 // async packet will be the repeat stop reply packet and cause
618 // a lot of trouble for us!
619 if (signo != SIGINT && signo != SIGSTOP)
620 {
Greg Claytonfb72fde2012-05-15 02:50:49 +0000621 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000622
623 // We didn't get a a SIGINT or SIGSTOP, so try for a
624 // very brief time (1 ms) to get another stop reply
625 // packet to make sure it doesn't get in the way
626 StringExtractorGDBRemote extra_stop_reply_packet;
627 uint32_t timeout_usec = 1000;
628 if (WaitForPacketWithTimeoutMicroSecondsNoLock (extra_stop_reply_packet, timeout_usec))
629 {
630 switch (extra_stop_reply_packet.GetChar())
631 {
632 case 'T':
633 case 'S':
634 // We did get an extra stop reply, which means
635 // our interrupt didn't stop the target so we
636 // shouldn't continue after the async signal
637 // or packet is sent...
Greg Claytonfb72fde2012-05-15 02:50:49 +0000638 continue_after_async = false;
Greg Clayton2687cd12012-03-29 01:55:41 +0000639 break;
640 }
641 }
642 }
643 }
644
645 if (m_async_signal != -1)
646 {
647 if (log)
648 log->Printf ("async: send signo = %s", Host::GetSignalAsCString (m_async_signal));
649
650 // Save off the async signal we are supposed to send
651 const int async_signal = m_async_signal;
652 // Clear the async signal member so we don't end up
653 // sending the signal multiple times...
654 m_async_signal = -1;
655 // Check which signal we stopped with
656 if (signo == async_signal)
657 {
658 if (log)
659 log->Printf ("async: stopped with signal %s, we are done running", Host::GetSignalAsCString (signo));
660
661 // We already stopped with a signal that we wanted
662 // to stop with, so we are done
663 }
664 else
665 {
666 // We stopped with a different signal that the one
667 // we wanted to stop with, so now we must resume
668 // with the signal we want
669 char signal_packet[32];
670 int signal_packet_len = 0;
671 signal_packet_len = ::snprintf (signal_packet,
672 sizeof (signal_packet),
673 "C%2.2x",
674 async_signal);
675
676 if (log)
677 log->Printf ("async: stopped with signal %s, resume with %s",
678 Host::GetSignalAsCString (signo),
679 Host::GetSignalAsCString (async_signal));
680
681 // Set the continue packet to resume even if the
Greg Claytonfb72fde2012-05-15 02:50:49 +0000682 // interrupt didn't cause our stop (ignore continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000683 continue_packet.assign(signal_packet, signal_packet_len);
684 continue;
685 }
686 }
687 else if (m_async_packet_predicate.GetValue())
688 {
Greg Clayton5160ce52013-03-27 23:08:40 +0000689 Log * packet_log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton2687cd12012-03-29 01:55:41 +0000690
691 // We are supposed to send an asynchronous packet while
692 // we are running.
693 m_async_response.Clear();
694 if (m_async_packet.empty())
695 {
696 if (packet_log)
697 packet_log->Printf ("async: error: empty async packet");
698
699 }
700 else
701 {
702 if (packet_log)
703 packet_log->Printf ("async: sending packet");
704
705 SendPacketAndWaitForResponse (&m_async_packet[0],
706 m_async_packet.size(),
707 m_async_response,
708 false);
709 }
710 // Let the other thread that was trying to send the async
711 // packet know that the packet has been sent and response is
712 // ready...
713 m_async_packet_predicate.SetValue(false, eBroadcastAlways);
714
715 if (packet_log)
Greg Claytonfb72fde2012-05-15 02:50:49 +0000716 packet_log->Printf ("async: sent packet, continue_after_async = %i", continue_after_async);
Greg Clayton2687cd12012-03-29 01:55:41 +0000717
718 // Set the continue packet to resume if our interrupt
719 // for the async packet did cause the stop
Greg Claytonfb72fde2012-05-15 02:50:49 +0000720 if (continue_after_async)
Greg Clayton2687cd12012-03-29 01:55:41 +0000721 {
Greg Claytonf1186de2012-05-24 23:42:14 +0000722 // Reverting this for now as it is causing deadlocks
723 // in programs (<rdar://problem/11529853>). In the future
724 // we should check our thread list and "do the right thing"
725 // for new threads that show up while we stop and run async
726 // packets. Setting the packet to 'c' to continue all threads
727 // is the right thing to do 99.99% of the time because if a
728 // thread was single stepping, and we sent an interrupt, we
729 // will notice above that we didn't stop due to an interrupt
730 // but stopped due to stepping and we would _not_ continue.
731 continue_packet.assign (1, 'c');
Greg Clayton2687cd12012-03-29 01:55:41 +0000732 continue;
733 }
734 }
735 // Stop with signal and thread info
736 state = eStateStopped;
Greg Clayton576d8832011-03-22 04:00:09 +0000737 }
Greg Clayton576d8832011-03-22 04:00:09 +0000738 break;
739
740 case 'W':
741 case 'X':
742 // process exited
743 state = eStateExited;
744 break;
745
746 case 'O':
747 // STDOUT
748 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000749 got_async_packet = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000750 std::string inferior_stdout;
751 inferior_stdout.reserve(response.GetBytesLeft () / 2);
752 char ch;
753 while ((ch = response.GetHexU8()) != '\0')
754 inferior_stdout.append(1, ch);
755 process->AppendSTDOUT (inferior_stdout.c_str(), inferior_stdout.size());
756 }
757 break;
758
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000759 case 'A':
760 // Async miscellaneous reply. Right now, only profile data is coming through this channel.
761 {
Greg Clayton3f875c52013-02-22 22:23:55 +0000762 got_async_packet = true;
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000763 std::string input = response.GetStringRef().substr(1); // '1' to move beyond 'A'
764 if (m_partial_profile_data.length() > 0)
765 {
766 m_partial_profile_data.append(input);
767 input = m_partial_profile_data;
768 m_partial_profile_data.clear();
769 }
770
771 size_t found, pos = 0, len = input.length();
772 while ((found = input.find(end_delimiter, pos)) != std::string::npos)
773 {
774 StringExtractorGDBRemote profileDataExtractor(input.substr(pos, found).c_str());
Han Ming Ong91ed6b82013-06-24 18:15:05 +0000775 std::string profile_data = HarmonizeThreadIdsForProfileData(process, profileDataExtractor);
776 process->BroadcastAsyncProfileData (profile_data);
Han Ming Ong4b6459f2013-01-18 23:11:53 +0000777
778 pos = found + end_delimiter_len;
779 }
780
781 if (pos < len)
782 {
783 // Last incomplete chunk.
784 m_partial_profile_data = input.substr(pos);
785 }
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000786 }
787 break;
788
Greg Clayton576d8832011-03-22 04:00:09 +0000789 case 'E':
790 // ERROR
791 state = eStateInvalid;
792 break;
793
794 default:
795 if (log)
796 log->Printf ("GDBRemoteCommunicationClient::%s () unrecognized async packet", __FUNCTION__);
797 state = eStateInvalid;
798 break;
799 }
800 }
801 }
802 else
803 {
804 if (log)
805 log->Printf ("GDBRemoteCommunicationClient::%s () WaitForPacket(...) => false", __FUNCTION__);
806 state = eStateInvalid;
807 }
808 }
809 if (log)
810 log->Printf ("GDBRemoteCommunicationClient::%s () => %s", __FUNCTION__, StateAsCString(state));
811 response.SetFilePos(0);
812 m_private_is_running.SetValue (false, eBroadcastAlways);
813 m_public_is_running.SetValue (false, eBroadcastAlways);
814 return state;
815}
816
817bool
818GDBRemoteCommunicationClient::SendAsyncSignal (int signo)
819{
Greg Clayton2687cd12012-03-29 01:55:41 +0000820 Mutex::Locker async_locker (m_async_mutex);
Greg Clayton576d8832011-03-22 04:00:09 +0000821 m_async_signal = signo;
822 bool timed_out = false;
Greg Clayton576d8832011-03-22 04:00:09 +0000823 Mutex::Locker locker;
Greg Clayton2687cd12012-03-29 01:55:41 +0000824 if (SendInterrupt (locker, 1, timed_out))
Greg Clayton576d8832011-03-22 04:00:09 +0000825 return true;
826 m_async_signal = -1;
827 return false;
828}
829
Greg Clayton37a0a242012-04-11 00:24:49 +0000830// This function takes a mutex locker as a parameter in case the GetSequenceMutex
Greg Clayton576d8832011-03-22 04:00:09 +0000831// actually succeeds. If it doesn't succeed in acquiring the sequence mutex
832// (the expected result), then it will send the halt packet. If it does succeed
833// then the caller that requested the interrupt will want to keep the sequence
834// locked down so that no one else can send packets while the caller has control.
835// This function usually gets called when we are running and need to stop the
836// target. It can also be used when we are running and and we need to do something
837// else (like read/write memory), so we need to interrupt the running process
838// (gdb remote protocol requires this), and do what we need to do, then resume.
839
840bool
Greg Clayton2687cd12012-03-29 01:55:41 +0000841GDBRemoteCommunicationClient::SendInterrupt
Greg Clayton576d8832011-03-22 04:00:09 +0000842(
843 Mutex::Locker& locker,
844 uint32_t seconds_to_wait_for_stop,
Greg Clayton576d8832011-03-22 04:00:09 +0000845 bool &timed_out
846)
847{
Greg Clayton576d8832011-03-22 04:00:09 +0000848 timed_out = false;
Greg Clayton5160ce52013-03-27 23:08:40 +0000849 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Clayton576d8832011-03-22 04:00:09 +0000850
851 if (IsRunning())
852 {
853 // Only send an interrupt if our debugserver is running...
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000854 if (GetSequenceMutex (locker))
Greg Clayton37a0a242012-04-11 00:24:49 +0000855 {
856 if (log)
857 log->Printf ("SendInterrupt () - got sequence mutex without having to interrupt");
858 }
859 else
Greg Clayton576d8832011-03-22 04:00:09 +0000860 {
861 // Someone has the mutex locked waiting for a response or for the
862 // inferior to stop, so send the interrupt on the down low...
863 char ctrl_c = '\x03';
864 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton576d8832011-03-22 04:00:09 +0000865 size_t bytes_written = Write (&ctrl_c, 1, status, NULL);
Greg Clayton2687cd12012-03-29 01:55:41 +0000866 if (log)
867 log->PutCString("send packet: \\x03");
Greg Clayton576d8832011-03-22 04:00:09 +0000868 if (bytes_written > 0)
869 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000870 m_interrupt_sent = true;
Greg Clayton576d8832011-03-22 04:00:09 +0000871 if (seconds_to_wait_for_stop)
872 {
Greg Clayton2687cd12012-03-29 01:55:41 +0000873 TimeValue timeout;
874 if (seconds_to_wait_for_stop)
875 {
876 timeout = TimeValue::Now();
877 timeout.OffsetWithSeconds (seconds_to_wait_for_stop);
878 }
Greg Clayton576d8832011-03-22 04:00:09 +0000879 if (m_private_is_running.WaitForValueEqualTo (false, &timeout, &timed_out))
880 {
881 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000882 log->PutCString ("SendInterrupt () - sent interrupt, private state stopped");
Greg Clayton576d8832011-03-22 04:00:09 +0000883 return true;
884 }
885 else
886 {
887 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000888 log->Printf ("SendInterrupt () - sent interrupt, timed out wating for async thread resume");
Greg Clayton576d8832011-03-22 04:00:09 +0000889 }
890 }
891 else
892 {
893 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000894 log->Printf ("SendInterrupt () - sent interrupt, not waiting for stop...");
Greg Clayton576d8832011-03-22 04:00:09 +0000895 return true;
896 }
897 }
898 else
899 {
900 if (log)
Greg Clayton2687cd12012-03-29 01:55:41 +0000901 log->Printf ("SendInterrupt () - failed to write interrupt");
Greg Clayton576d8832011-03-22 04:00:09 +0000902 }
903 return false;
904 }
Greg Clayton576d8832011-03-22 04:00:09 +0000905 }
Greg Clayton2687cd12012-03-29 01:55:41 +0000906 else
907 {
908 if (log)
909 log->Printf ("SendInterrupt () - not running");
910 }
Greg Clayton576d8832011-03-22 04:00:09 +0000911 return true;
912}
913
914lldb::pid_t
915GDBRemoteCommunicationClient::GetCurrentProcessID ()
916{
917 StringExtractorGDBRemote response;
918 if (SendPacketAndWaitForResponse("qC", strlen("qC"), response, false))
919 {
920 if (response.GetChar() == 'Q')
921 if (response.GetChar() == 'C')
922 return response.GetHexMaxU32 (false, LLDB_INVALID_PROCESS_ID);
923 }
924 return LLDB_INVALID_PROCESS_ID;
925}
926
927bool
928GDBRemoteCommunicationClient::GetLaunchSuccess (std::string &error_str)
929{
930 error_str.clear();
931 StringExtractorGDBRemote response;
932 if (SendPacketAndWaitForResponse("qLaunchSuccess", strlen("qLaunchSuccess"), response, false))
933 {
934 if (response.IsOKResponse())
935 return true;
936 if (response.GetChar() == 'E')
937 {
938 // A string the describes what failed when launching...
939 error_str = response.GetStringRef().substr(1);
940 }
941 else
942 {
943 error_str.assign ("unknown error occurred launching process");
944 }
945 }
946 else
947 {
Jim Ingham98d6da52012-06-28 20:30:23 +0000948 error_str.assign ("timed out waiting for app to launch");
Greg Clayton576d8832011-03-22 04:00:09 +0000949 }
950 return false;
951}
952
953int
954GDBRemoteCommunicationClient::SendArgumentsPacket (char const *argv[])
955{
956 if (argv && argv[0])
957 {
958 StreamString packet;
959 packet.PutChar('A');
960 const char *arg;
961 for (uint32_t i = 0; (arg = argv[i]) != NULL; ++i)
962 {
963 const int arg_len = strlen(arg);
964 if (i > 0)
965 packet.PutChar(',');
966 packet.Printf("%i,%i,", arg_len * 2, i);
967 packet.PutBytesAsRawHex8 (arg, arg_len);
968 }
969
970 StringExtractorGDBRemote response;
971 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
972 {
973 if (response.IsOKResponse())
974 return 0;
975 uint8_t error = response.GetError();
976 if (error)
977 return error;
978 }
979 }
980 return -1;
981}
982
983int
984GDBRemoteCommunicationClient::SendEnvironmentPacket (char const *name_equal_value)
985{
986 if (name_equal_value && name_equal_value[0])
987 {
988 StreamString packet;
989 packet.Printf("QEnvironment:%s", name_equal_value);
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
Greg Claytonc4103b32011-05-08 04:53:50 +00001003int
1004GDBRemoteCommunicationClient::SendLaunchArchPacket (char const *arch)
1005{
1006 if (arch && arch[0])
1007 {
1008 StreamString packet;
1009 packet.Printf("QLaunchArch:%s", arch);
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 Clayton576d8832011-03-22 04:00:09 +00001023bool
Greg Clayton1cb64962011-03-24 04:28:38 +00001024GDBRemoteCommunicationClient::GetOSVersion (uint32_t &major,
1025 uint32_t &minor,
1026 uint32_t &update)
1027{
1028 if (GetHostInfo ())
1029 {
1030 if (m_os_version_major != UINT32_MAX)
1031 {
1032 major = m_os_version_major;
1033 minor = m_os_version_minor;
1034 update = m_os_version_update;
1035 return true;
1036 }
1037 }
1038 return false;
1039}
1040
1041bool
1042GDBRemoteCommunicationClient::GetOSBuildString (std::string &s)
1043{
1044 if (GetHostInfo ())
1045 {
1046 if (!m_os_build.empty())
1047 {
1048 s = m_os_build;
1049 return true;
1050 }
1051 }
1052 s.clear();
1053 return false;
1054}
1055
1056
1057bool
1058GDBRemoteCommunicationClient::GetOSKernelDescription (std::string &s)
1059{
1060 if (GetHostInfo ())
1061 {
1062 if (!m_os_kernel.empty())
1063 {
1064 s = m_os_kernel;
1065 return true;
1066 }
1067 }
1068 s.clear();
1069 return false;
1070}
1071
1072bool
1073GDBRemoteCommunicationClient::GetHostname (std::string &s)
1074{
1075 if (GetHostInfo ())
1076 {
1077 if (!m_hostname.empty())
1078 {
1079 s = m_hostname;
1080 return true;
1081 }
1082 }
1083 s.clear();
1084 return false;
1085}
1086
1087ArchSpec
1088GDBRemoteCommunicationClient::GetSystemArchitecture ()
1089{
1090 if (GetHostInfo ())
1091 return m_host_arch;
1092 return ArchSpec();
1093}
1094
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001095const lldb_private::ArchSpec &
1096GDBRemoteCommunicationClient::GetProcessArchitecture ()
1097{
1098 if (m_qProcessInfo_is_valid == eLazyBoolCalculate)
1099 GetCurrentProcessInfo ();
1100 return m_process_arch;
1101}
1102
Greg Clayton1cb64962011-03-24 04:28:38 +00001103
1104bool
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001105GDBRemoteCommunicationClient::GetHostInfo (bool force)
Greg Clayton576d8832011-03-22 04:00:09 +00001106{
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001107 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001108 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001109 m_qHostInfo_is_valid = eLazyBoolNo;
Greg Clayton576d8832011-03-22 04:00:09 +00001110 StringExtractorGDBRemote response;
1111 if (SendPacketAndWaitForResponse ("qHostInfo", response, false))
1112 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001113 if (response.IsNormalResponse())
Greg Claytond314e812011-03-23 00:09:55 +00001114 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001115 std::string name;
1116 std::string value;
1117 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1118 uint32_t sub = 0;
1119 std::string arch_name;
1120 std::string os_name;
1121 std::string vendor_name;
1122 std::string triple;
1123 uint32_t pointer_byte_size = 0;
1124 StringExtractor extractor;
1125 ByteOrder byte_order = eByteOrderInvalid;
1126 uint32_t num_keys_decoded = 0;
1127 while (response.GetNameColonValue(name, value))
Greg Claytond314e812011-03-23 00:09:55 +00001128 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001129 if (name.compare("cputype") == 0)
Greg Clayton1cb64962011-03-24 04:28:38 +00001130 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001131 // exception type in big endian hex
1132 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 0);
1133 if (cpu != LLDB_INVALID_CPUTYPE)
1134 ++num_keys_decoded;
1135 }
1136 else if (name.compare("cpusubtype") == 0)
1137 {
1138 // exception count in big endian hex
1139 sub = Args::StringToUInt32 (value.c_str(), 0, 0);
1140 if (sub != 0)
1141 ++num_keys_decoded;
1142 }
1143 else if (name.compare("arch") == 0)
1144 {
1145 arch_name.swap (value);
1146 ++num_keys_decoded;
1147 }
1148 else if (name.compare("triple") == 0)
1149 {
1150 // The triple comes as ASCII hex bytes since it contains '-' chars
1151 extractor.GetStringRef().swap(value);
1152 extractor.SetFilePos(0);
1153 extractor.GetHexByteString (triple);
1154 ++num_keys_decoded;
1155 }
1156 else if (name.compare("os_build") == 0)
1157 {
1158 extractor.GetStringRef().swap(value);
1159 extractor.SetFilePos(0);
1160 extractor.GetHexByteString (m_os_build);
1161 ++num_keys_decoded;
1162 }
1163 else if (name.compare("hostname") == 0)
1164 {
1165 extractor.GetStringRef().swap(value);
1166 extractor.SetFilePos(0);
1167 extractor.GetHexByteString (m_hostname);
1168 ++num_keys_decoded;
1169 }
1170 else if (name.compare("os_kernel") == 0)
1171 {
1172 extractor.GetStringRef().swap(value);
1173 extractor.SetFilePos(0);
1174 extractor.GetHexByteString (m_os_kernel);
1175 ++num_keys_decoded;
1176 }
1177 else if (name.compare("ostype") == 0)
1178 {
1179 os_name.swap (value);
1180 ++num_keys_decoded;
1181 }
1182 else if (name.compare("vendor") == 0)
1183 {
1184 vendor_name.swap(value);
1185 ++num_keys_decoded;
1186 }
1187 else if (name.compare("endian") == 0)
1188 {
1189 ++num_keys_decoded;
1190 if (value.compare("little") == 0)
1191 byte_order = eByteOrderLittle;
1192 else if (value.compare("big") == 0)
1193 byte_order = eByteOrderBig;
1194 else if (value.compare("pdp") == 0)
1195 byte_order = eByteOrderPDP;
1196 else
1197 --num_keys_decoded;
1198 }
1199 else if (name.compare("ptrsize") == 0)
1200 {
1201 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 0);
1202 if (pointer_byte_size != 0)
1203 ++num_keys_decoded;
1204 }
1205 else if (name.compare("os_version") == 0)
1206 {
1207 Args::StringToVersion (value.c_str(),
1208 m_os_version_major,
1209 m_os_version_minor,
1210 m_os_version_update);
1211 if (m_os_version_major != UINT32_MAX)
1212 ++num_keys_decoded;
1213 }
Enrico Granataf04a2192012-07-13 23:18:48 +00001214 else if (name.compare("watchpoint_exceptions_received") == 0)
1215 {
1216 ++num_keys_decoded;
1217 if (strcmp(value.c_str(),"before") == 0)
1218 m_watchpoints_trigger_after_instruction = eLazyBoolNo;
1219 else if (strcmp(value.c_str(),"after") == 0)
1220 m_watchpoints_trigger_after_instruction = eLazyBoolYes;
1221 else
1222 --num_keys_decoded;
1223 }
1224
Greg Clayton32e0a752011-03-30 18:16:51 +00001225 }
1226
1227 if (num_keys_decoded > 0)
1228 m_qHostInfo_is_valid = eLazyBoolYes;
1229
1230 if (triple.empty())
1231 {
1232 if (arch_name.empty())
1233 {
1234 if (cpu != LLDB_INVALID_CPUTYPE)
1235 {
1236 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1237 if (pointer_byte_size)
1238 {
1239 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1240 }
1241 if (byte_order != eByteOrderInvalid)
1242 {
1243 assert (byte_order == m_host_arch.GetByteOrder());
1244 }
Greg Clayton70512312012-05-08 01:45:38 +00001245
1246 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0)
1247 {
1248 switch (m_host_arch.GetMachine())
1249 {
1250 case llvm::Triple::arm:
1251 case llvm::Triple::thumb:
1252 os_name = "ios";
1253 break;
1254 default:
1255 os_name = "macosx";
1256 break;
1257 }
1258 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001259 if (!vendor_name.empty())
1260 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1261 if (!os_name.empty())
Greg Claytone1dadb82011-09-15 00:21:03 +00001262 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
Greg Clayton32e0a752011-03-30 18:16:51 +00001263
1264 }
1265 }
1266 else
1267 {
1268 std::string triple;
1269 triple += arch_name;
Greg Clayton70512312012-05-08 01:45:38 +00001270 if (!vendor_name.empty() || !os_name.empty())
1271 {
1272 triple += '-';
1273 if (vendor_name.empty())
1274 triple += "unknown";
1275 else
1276 triple += vendor_name;
1277 triple += '-';
1278 if (os_name.empty())
1279 triple += "unknown";
1280 else
1281 triple += os_name;
1282 }
1283 m_host_arch.SetTriple (triple.c_str());
1284
1285 llvm::Triple &host_triple = m_host_arch.GetTriple();
1286 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin)
1287 {
1288 switch (m_host_arch.GetMachine())
1289 {
1290 case llvm::Triple::arm:
1291 case llvm::Triple::thumb:
1292 host_triple.setOS(llvm::Triple::IOS);
1293 break;
1294 default:
1295 host_triple.setOS(llvm::Triple::MacOSX);
1296 break;
1297 }
1298 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001299 if (pointer_byte_size)
1300 {
1301 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1302 }
1303 if (byte_order != eByteOrderInvalid)
1304 {
1305 assert (byte_order == m_host_arch.GetByteOrder());
1306 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001307
Greg Clayton1cb64962011-03-24 04:28:38 +00001308 }
1309 }
1310 else
1311 {
Greg Clayton70512312012-05-08 01:45:38 +00001312 m_host_arch.SetTriple (triple.c_str());
Greg Claytond314e812011-03-23 00:09:55 +00001313 if (pointer_byte_size)
1314 {
1315 assert (pointer_byte_size == m_host_arch.GetAddressByteSize());
1316 }
1317 if (byte_order != eByteOrderInvalid)
1318 {
1319 assert (byte_order == m_host_arch.GetByteOrder());
1320 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001321 }
Greg Claytond314e812011-03-23 00:09:55 +00001322 }
Greg Clayton576d8832011-03-22 04:00:09 +00001323 }
1324 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001325 return m_qHostInfo_is_valid == eLazyBoolYes;
Greg Clayton576d8832011-03-22 04:00:09 +00001326}
1327
1328int
1329GDBRemoteCommunicationClient::SendAttach
1330(
1331 lldb::pid_t pid,
1332 StringExtractorGDBRemote& response
1333)
1334{
1335 if (pid != LLDB_INVALID_PROCESS_ID)
1336 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001337 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001338 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001339 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00001340 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton576d8832011-03-22 04:00:09 +00001341 {
1342 if (response.IsErrorResponse())
1343 return response.GetError();
1344 return 0;
1345 }
1346 }
1347 return -1;
1348}
1349
1350const lldb_private::ArchSpec &
1351GDBRemoteCommunicationClient::GetHostArchitecture ()
1352{
Greg Clayton32e0a752011-03-30 18:16:51 +00001353 if (m_qHostInfo_is_valid == eLazyBoolCalculate)
Greg Clayton576d8832011-03-22 04:00:09 +00001354 GetHostInfo ();
Greg Claytond314e812011-03-23 00:09:55 +00001355 return m_host_arch;
Greg Clayton576d8832011-03-22 04:00:09 +00001356}
1357
1358addr_t
1359GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions)
1360{
Greg Clayton70b57652011-05-15 01:25:55 +00001361 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001362 {
Greg Clayton70b57652011-05-15 01:25:55 +00001363 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001364 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001365 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s",
Greg Clayton43e0af02012-09-18 18:04:04 +00001366 (uint64_t)size,
Greg Clayton2a48f522011-05-14 01:50:35 +00001367 permissions & lldb::ePermissionsReadable ? "r" : "",
1368 permissions & lldb::ePermissionsWritable ? "w" : "",
1369 permissions & lldb::ePermissionsExecutable ? "x" : "");
Andy Gibbsa297a972013-06-19 19:04:53 +00001370 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001371 StringExtractorGDBRemote response;
1372 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1373 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00001374 if (!response.IsErrorResponse())
Greg Clayton2a48f522011-05-14 01:50:35 +00001375 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
1376 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001377 else
1378 {
1379 m_supports_alloc_dealloc_memory = eLazyBoolNo;
1380 }
Greg Clayton576d8832011-03-22 04:00:09 +00001381 }
1382 return LLDB_INVALID_ADDRESS;
1383}
1384
1385bool
1386GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr)
1387{
Greg Clayton70b57652011-05-15 01:25:55 +00001388 if (m_supports_alloc_dealloc_memory != eLazyBoolNo)
Greg Clayton576d8832011-03-22 04:00:09 +00001389 {
Greg Clayton70b57652011-05-15 01:25:55 +00001390 m_supports_alloc_dealloc_memory = eLazyBoolYes;
Greg Clayton2a48f522011-05-14 01:50:35 +00001391 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001392 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001393 assert (packet_len < (int)sizeof(packet));
Greg Clayton2a48f522011-05-14 01:50:35 +00001394 StringExtractorGDBRemote response;
1395 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1396 {
1397 if (response.IsOKResponse())
1398 return true;
Greg Clayton17a0cb62011-05-15 23:46:54 +00001399 }
1400 else
1401 {
1402 m_supports_alloc_dealloc_memory = eLazyBoolNo;
Greg Clayton2a48f522011-05-14 01:50:35 +00001403 }
Greg Clayton576d8832011-03-22 04:00:09 +00001404 }
1405 return false;
1406}
1407
Jim Inghamacff8952013-05-02 00:27:30 +00001408Error
1409GDBRemoteCommunicationClient::Detach (bool keep_stopped)
Greg Clayton37a0a242012-04-11 00:24:49 +00001410{
Jim Inghamacff8952013-05-02 00:27:30 +00001411 Error error;
1412
1413 if (keep_stopped)
1414 {
1415 if (m_supports_detach_stay_stopped == eLazyBoolCalculate)
1416 {
1417 char packet[64];
1418 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001419 assert (packet_len < (int)sizeof(packet));
Jim Inghamacff8952013-05-02 00:27:30 +00001420 StringExtractorGDBRemote response;
1421 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1422 {
1423 m_supports_detach_stay_stopped = eLazyBoolYes;
1424 }
1425 else
1426 {
1427 m_supports_detach_stay_stopped = eLazyBoolNo;
1428 }
1429 }
1430
1431 if (m_supports_detach_stay_stopped == eLazyBoolNo)
1432 {
1433 error.SetErrorString("Stays stopped not supported by this target.");
1434 return error;
1435 }
1436 else
1437 {
1438 size_t num_sent = SendPacket ("D1", 2);
1439 if (num_sent == 0)
1440 error.SetErrorString ("Sending extended disconnect packet failed.");
1441 }
1442 }
1443 else
1444 {
1445 size_t num_sent = SendPacket ("D", 1);
1446 if (num_sent == 0)
1447 error.SetErrorString ("Sending disconnect packet failed.");
1448 }
1449 return error;
Greg Clayton37a0a242012-04-11 00:24:49 +00001450}
1451
Greg Clayton46fb5582011-11-18 07:03:08 +00001452Error
1453GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr,
1454 lldb_private::MemoryRegionInfo &region_info)
1455{
1456 Error error;
1457 region_info.Clear();
1458
1459 if (m_supports_memory_region_info != eLazyBoolNo)
1460 {
1461 m_supports_memory_region_info = eLazyBoolYes;
1462 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001463 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr);
Andy Gibbsa297a972013-06-19 19:04:53 +00001464 assert (packet_len < (int)sizeof(packet));
Greg Clayton46fb5582011-11-18 07:03:08 +00001465 StringExtractorGDBRemote response;
1466 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1467 {
1468 std::string name;
1469 std::string value;
1470 addr_t addr_value;
1471 bool success = true;
Jason Molendacb349ee2011-12-13 05:39:38 +00001472 bool saw_permissions = false;
Greg Clayton46fb5582011-11-18 07:03:08 +00001473 while (success && response.GetNameColonValue(name, value))
1474 {
1475 if (name.compare ("start") == 0)
1476 {
1477 addr_value = Args::StringToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success);
1478 if (success)
1479 region_info.GetRange().SetRangeBase(addr_value);
1480 }
1481 else if (name.compare ("size") == 0)
1482 {
1483 addr_value = Args::StringToUInt64(value.c_str(), 0, 16, &success);
1484 if (success)
1485 region_info.GetRange().SetByteSize (addr_value);
1486 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001487 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid())
Greg Clayton46fb5582011-11-18 07:03:08 +00001488 {
Jason Molendacb349ee2011-12-13 05:39:38 +00001489 saw_permissions = true;
1490 if (region_info.GetRange().Contains (addr))
1491 {
1492 if (value.find('r') != std::string::npos)
1493 region_info.SetReadable (MemoryRegionInfo::eYes);
1494 else
1495 region_info.SetReadable (MemoryRegionInfo::eNo);
1496
1497 if (value.find('w') != std::string::npos)
1498 region_info.SetWritable (MemoryRegionInfo::eYes);
1499 else
1500 region_info.SetWritable (MemoryRegionInfo::eNo);
1501
1502 if (value.find('x') != std::string::npos)
1503 region_info.SetExecutable (MemoryRegionInfo::eYes);
1504 else
1505 region_info.SetExecutable (MemoryRegionInfo::eNo);
1506 }
1507 else
1508 {
1509 // The reported region does not contain this address -- we're looking at an unmapped page
1510 region_info.SetReadable (MemoryRegionInfo::eNo);
1511 region_info.SetWritable (MemoryRegionInfo::eNo);
1512 region_info.SetExecutable (MemoryRegionInfo::eNo);
1513 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001514 }
1515 else if (name.compare ("error") == 0)
1516 {
1517 StringExtractorGDBRemote name_extractor;
1518 // Swap "value" over into "name_extractor"
1519 name_extractor.GetStringRef().swap(value);
1520 // Now convert the HEX bytes into a string value
1521 name_extractor.GetHexByteString (value);
1522 error.SetErrorString(value.c_str());
1523 }
1524 }
Jason Molendacb349ee2011-12-13 05:39:38 +00001525
1526 // We got a valid address range back but no permissions -- which means this is an unmapped page
1527 if (region_info.GetRange().IsValid() && saw_permissions == false)
1528 {
1529 region_info.SetReadable (MemoryRegionInfo::eNo);
1530 region_info.SetWritable (MemoryRegionInfo::eNo);
1531 region_info.SetExecutable (MemoryRegionInfo::eNo);
1532 }
Greg Clayton46fb5582011-11-18 07:03:08 +00001533 }
1534 else
1535 {
1536 m_supports_memory_region_info = eLazyBoolNo;
1537 }
1538 }
1539
1540 if (m_supports_memory_region_info == eLazyBoolNo)
1541 {
1542 error.SetErrorString("qMemoryRegionInfo is not supported");
1543 }
1544 if (error.Fail())
1545 region_info.Clear();
1546 return error;
1547
1548}
1549
Johnny Chen64637202012-05-23 21:09:52 +00001550Error
1551GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num)
1552{
1553 Error error;
1554
1555 if (m_supports_watchpoint_support_info == eLazyBoolYes)
1556 {
1557 num = m_num_supported_hardware_watchpoints;
1558 return error;
1559 }
1560
1561 // Set num to 0 first.
1562 num = 0;
1563 if (m_supports_watchpoint_support_info != eLazyBoolNo)
1564 {
1565 char packet[64];
1566 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:");
Andy Gibbsa297a972013-06-19 19:04:53 +00001567 assert (packet_len < (int)sizeof(packet));
Johnny Chen64637202012-05-23 21:09:52 +00001568 StringExtractorGDBRemote response;
1569 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1570 {
1571 m_supports_watchpoint_support_info = eLazyBoolYes;
1572 std::string name;
1573 std::string value;
1574 while (response.GetNameColonValue(name, value))
1575 {
1576 if (name.compare ("num") == 0)
1577 {
1578 num = Args::StringToUInt32(value.c_str(), 0, 0);
1579 m_num_supported_hardware_watchpoints = num;
1580 }
1581 }
1582 }
1583 else
1584 {
1585 m_supports_watchpoint_support_info = eLazyBoolNo;
1586 }
1587 }
1588
1589 if (m_supports_watchpoint_support_info == eLazyBoolNo)
1590 {
1591 error.SetErrorString("qWatchpointSupportInfo is not supported");
1592 }
1593 return error;
1594
1595}
Greg Clayton46fb5582011-11-18 07:03:08 +00001596
Enrico Granataf04a2192012-07-13 23:18:48 +00001597lldb_private::Error
1598GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after)
1599{
1600 Error error(GetWatchpointSupportInfo(num));
1601 if (error.Success())
1602 error = GetWatchpointsTriggerAfterInstruction(after);
1603 return error;
1604}
1605
1606lldb_private::Error
1607GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after)
1608{
1609 Error error;
1610
1611 // we assume watchpoints will happen after running the relevant opcode
1612 // and we only want to override this behavior if we have explicitly
1613 // received a qHostInfo telling us otherwise
1614 if (m_qHostInfo_is_valid != eLazyBoolYes)
1615 after = true;
1616 else
1617 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo);
1618 return error;
1619}
1620
Greg Clayton576d8832011-03-22 04:00:09 +00001621int
1622GDBRemoteCommunicationClient::SetSTDIN (char const *path)
1623{
1624 if (path && path[0])
1625 {
1626 StreamString packet;
1627 packet.PutCString("QSetSTDIN:");
1628 packet.PutBytesAsRawHex8(path, strlen(path));
1629
1630 StringExtractorGDBRemote response;
1631 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1632 {
1633 if (response.IsOKResponse())
1634 return 0;
1635 uint8_t error = response.GetError();
1636 if (error)
1637 return error;
1638 }
1639 }
1640 return -1;
1641}
1642
1643int
1644GDBRemoteCommunicationClient::SetSTDOUT (char const *path)
1645{
1646 if (path && path[0])
1647 {
1648 StreamString packet;
1649 packet.PutCString("QSetSTDOUT:");
1650 packet.PutBytesAsRawHex8(path, strlen(path));
1651
1652 StringExtractorGDBRemote response;
1653 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1654 {
1655 if (response.IsOKResponse())
1656 return 0;
1657 uint8_t error = response.GetError();
1658 if (error)
1659 return error;
1660 }
1661 }
1662 return -1;
1663}
1664
1665int
1666GDBRemoteCommunicationClient::SetSTDERR (char const *path)
1667{
1668 if (path && path[0])
1669 {
1670 StreamString packet;
1671 packet.PutCString("QSetSTDERR:");
1672 packet.PutBytesAsRawHex8(path, strlen(path));
1673
1674 StringExtractorGDBRemote response;
1675 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1676 {
1677 if (response.IsOKResponse())
1678 return 0;
1679 uint8_t error = response.GetError();
1680 if (error)
1681 return error;
1682 }
1683 }
1684 return -1;
1685}
1686
1687int
1688GDBRemoteCommunicationClient::SetWorkingDir (char const *path)
1689{
1690 if (path && path[0])
1691 {
1692 StreamString packet;
1693 packet.PutCString("QSetWorkingDir:");
1694 packet.PutBytesAsRawHex8(path, strlen(path));
1695
1696 StringExtractorGDBRemote response;
1697 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1698 {
1699 if (response.IsOKResponse())
1700 return 0;
1701 uint8_t error = response.GetError();
1702 if (error)
1703 return error;
1704 }
1705 }
1706 return -1;
1707}
1708
1709int
1710GDBRemoteCommunicationClient::SetDisableASLR (bool enable)
1711{
Greg Clayton32e0a752011-03-30 18:16:51 +00001712 char packet[32];
1713 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0);
Andy Gibbsa297a972013-06-19 19:04:53 +00001714 assert (packet_len < (int)sizeof(packet));
Greg Clayton576d8832011-03-22 04:00:09 +00001715 StringExtractorGDBRemote response;
Greg Clayton32e0a752011-03-30 18:16:51 +00001716 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
Greg Clayton576d8832011-03-22 04:00:09 +00001717 {
1718 if (response.IsOKResponse())
1719 return 0;
1720 uint8_t error = response.GetError();
1721 if (error)
1722 return error;
1723 }
1724 return -1;
1725}
Greg Clayton32e0a752011-03-30 18:16:51 +00001726
1727bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001728GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00001729{
1730 if (response.IsNormalResponse())
1731 {
1732 std::string name;
1733 std::string value;
1734 StringExtractor extractor;
1735
1736 while (response.GetNameColonValue(name, value))
1737 {
1738 if (name.compare("pid") == 0)
1739 {
1740 process_info.SetProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1741 }
1742 else if (name.compare("ppid") == 0)
1743 {
1744 process_info.SetParentProcessID (Args::StringToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0));
1745 }
1746 else if (name.compare("uid") == 0)
1747 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001748 process_info.SetUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00001749 }
1750 else if (name.compare("euid") == 0)
1751 {
1752 process_info.SetEffectiveUserID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1753 }
1754 else if (name.compare("gid") == 0)
1755 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001756 process_info.SetGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
Greg Clayton32e0a752011-03-30 18:16:51 +00001757 }
1758 else if (name.compare("egid") == 0)
1759 {
1760 process_info.SetEffectiveGroupID (Args::StringToUInt32 (value.c_str(), UINT32_MAX, 0));
1761 }
1762 else if (name.compare("triple") == 0)
1763 {
1764 // The triple comes as ASCII hex bytes since it contains '-' chars
1765 extractor.GetStringRef().swap(value);
1766 extractor.SetFilePos(0);
1767 extractor.GetHexByteString (value);
Greg Clayton70512312012-05-08 01:45:38 +00001768 process_info.GetArchitecture ().SetTriple (value.c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00001769 }
1770 else if (name.compare("name") == 0)
1771 {
1772 StringExtractor extractor;
Filipe Cabecinhasf86cf782012-05-07 09:30:51 +00001773 // The process name from ASCII hex bytes since we can't
Greg Clayton32e0a752011-03-30 18:16:51 +00001774 // control the characters in a process name
1775 extractor.GetStringRef().swap(value);
1776 extractor.SetFilePos(0);
1777 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00001778 process_info.GetExecutableFile().SetFile (value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00001779 }
1780 }
1781
1782 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1783 return true;
1784 }
1785 return false;
1786}
1787
1788bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001789GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton32e0a752011-03-30 18:16:51 +00001790{
1791 process_info.Clear();
1792
1793 if (m_supports_qProcessInfoPID)
1794 {
1795 char packet[32];
Daniel Malead01b2952012-11-29 21:49:15 +00001796 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid);
Andy Gibbsa297a972013-06-19 19:04:53 +00001797 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00001798 StringExtractorGDBRemote response;
1799 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
1800 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001801 return DecodeProcessInfoResponse (response, process_info);
1802 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001803 else
1804 {
1805 m_supports_qProcessInfoPID = false;
1806 return false;
1807 }
Greg Clayton32e0a752011-03-30 18:16:51 +00001808 }
1809 return false;
1810}
1811
Jason Molendaf17b5ac2012-12-19 02:54:03 +00001812bool
1813GDBRemoteCommunicationClient::GetCurrentProcessInfo ()
1814{
1815 if (m_qProcessInfo_is_valid == eLazyBoolYes)
1816 return true;
1817 if (m_qProcessInfo_is_valid == eLazyBoolNo)
1818 return false;
1819
1820 GetHostInfo ();
1821
1822 StringExtractorGDBRemote response;
1823 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false))
1824 {
1825 if (response.IsNormalResponse())
1826 {
1827 std::string name;
1828 std::string value;
1829 uint32_t cpu = LLDB_INVALID_CPUTYPE;
1830 uint32_t sub = 0;
1831 std::string arch_name;
1832 std::string os_name;
1833 std::string vendor_name;
1834 std::string triple;
1835 uint32_t pointer_byte_size = 0;
1836 StringExtractor extractor;
1837 ByteOrder byte_order = eByteOrderInvalid;
1838 uint32_t num_keys_decoded = 0;
1839 while (response.GetNameColonValue(name, value))
1840 {
1841 if (name.compare("cputype") == 0)
1842 {
1843 cpu = Args::StringToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16);
1844 if (cpu != LLDB_INVALID_CPUTYPE)
1845 ++num_keys_decoded;
1846 }
1847 else if (name.compare("cpusubtype") == 0)
1848 {
1849 sub = Args::StringToUInt32 (value.c_str(), 0, 16);
1850 if (sub != 0)
1851 ++num_keys_decoded;
1852 }
1853 else if (name.compare("ostype") == 0)
1854 {
1855 os_name.swap (value);
1856 ++num_keys_decoded;
1857 }
1858 else if (name.compare("vendor") == 0)
1859 {
1860 vendor_name.swap(value);
1861 ++num_keys_decoded;
1862 }
1863 else if (name.compare("endian") == 0)
1864 {
1865 ++num_keys_decoded;
1866 if (value.compare("little") == 0)
1867 byte_order = eByteOrderLittle;
1868 else if (value.compare("big") == 0)
1869 byte_order = eByteOrderBig;
1870 else if (value.compare("pdp") == 0)
1871 byte_order = eByteOrderPDP;
1872 else
1873 --num_keys_decoded;
1874 }
1875 else if (name.compare("ptrsize") == 0)
1876 {
1877 pointer_byte_size = Args::StringToUInt32 (value.c_str(), 0, 16);
1878 if (pointer_byte_size != 0)
1879 ++num_keys_decoded;
1880 }
1881 }
1882 if (num_keys_decoded > 0)
1883 m_qProcessInfo_is_valid = eLazyBoolYes;
1884 if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty())
1885 {
1886 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub);
1887 if (pointer_byte_size)
1888 {
1889 assert (pointer_byte_size == m_process_arch.GetAddressByteSize());
1890 }
1891 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name));
1892 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name));
1893 return true;
1894 }
1895 }
1896 }
1897 else
1898 {
1899 m_qProcessInfo_is_valid = eLazyBoolNo;
1900 }
1901
1902 return false;
1903}
1904
1905
Greg Clayton32e0a752011-03-30 18:16:51 +00001906uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001907GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info,
1908 ProcessInstanceInfoList &process_infos)
Greg Clayton32e0a752011-03-30 18:16:51 +00001909{
1910 process_infos.Clear();
1911
1912 if (m_supports_qfProcessInfo)
1913 {
1914 StreamString packet;
1915 packet.PutCString ("qfProcessInfo");
1916 if (!match_info.MatchAllProcesses())
1917 {
1918 packet.PutChar (':');
1919 const char *name = match_info.GetProcessInfo().GetName();
1920 bool has_name_match = false;
1921 if (name && name[0])
1922 {
1923 has_name_match = true;
1924 NameMatchType name_match_type = match_info.GetNameMatchType();
1925 switch (name_match_type)
1926 {
1927 case eNameMatchIgnore:
1928 has_name_match = false;
1929 break;
1930
1931 case eNameMatchEquals:
1932 packet.PutCString ("name_match:equals;");
1933 break;
1934
1935 case eNameMatchContains:
1936 packet.PutCString ("name_match:contains;");
1937 break;
1938
1939 case eNameMatchStartsWith:
1940 packet.PutCString ("name_match:starts_with;");
1941 break;
1942
1943 case eNameMatchEndsWith:
1944 packet.PutCString ("name_match:ends_with;");
1945 break;
1946
1947 case eNameMatchRegularExpression:
1948 packet.PutCString ("name_match:regex;");
1949 break;
1950 }
1951 if (has_name_match)
1952 {
1953 packet.PutCString ("name:");
1954 packet.PutBytesAsRawHex8(name, ::strlen(name));
1955 packet.PutChar (';');
1956 }
1957 }
1958
1959 if (match_info.GetProcessInfo().ProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00001960 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID());
Greg Clayton32e0a752011-03-30 18:16:51 +00001961 if (match_info.GetProcessInfo().ParentProcessIDIsValid())
Daniel Malead01b2952012-11-29 21:49:15 +00001962 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID());
Greg Clayton8b82f082011-04-12 05:54:46 +00001963 if (match_info.GetProcessInfo().UserIDIsValid())
1964 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID());
1965 if (match_info.GetProcessInfo().GroupIDIsValid())
1966 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID());
Greg Clayton32e0a752011-03-30 18:16:51 +00001967 if (match_info.GetProcessInfo().EffectiveUserIDIsValid())
1968 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID());
1969 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1970 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID());
1971 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid())
1972 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0);
1973 if (match_info.GetProcessInfo().GetArchitecture().IsValid())
1974 {
1975 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture();
1976 const llvm::Triple &triple = match_arch.GetTriple();
1977 packet.PutCString("triple:");
1978 packet.PutCStringAsRawHex8(triple.getTriple().c_str());
1979 packet.PutChar (';');
1980 }
1981 }
1982 StringExtractorGDBRemote response;
1983 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false))
1984 {
Greg Clayton32e0a752011-03-30 18:16:51 +00001985 do
1986 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001987 ProcessInstanceInfo process_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00001988 if (!DecodeProcessInfoResponse (response, process_info))
1989 break;
1990 process_infos.Append(process_info);
1991 response.GetStringRef().clear();
1992 response.SetFilePos(0);
1993 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false));
1994 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00001995 else
1996 {
1997 m_supports_qfProcessInfo = false;
1998 return 0;
1999 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002000 }
2001 return process_infos.GetSize();
2002
2003}
2004
2005bool
2006GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name)
2007{
2008 if (m_supports_qUserName)
2009 {
2010 char packet[32];
2011 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002012 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002013 StringExtractorGDBRemote response;
2014 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2015 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002016 if (response.IsNormalResponse())
2017 {
2018 // Make sure we parsed the right number of characters. The response is
2019 // the hex encoded user name and should make up the entire packet.
2020 // If there are any non-hex ASCII bytes, the length won't match below..
2021 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2022 return true;
2023 }
2024 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002025 else
2026 {
2027 m_supports_qUserName = false;
2028 return false;
2029 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002030 }
2031 return false;
2032
2033}
2034
2035bool
2036GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name)
2037{
2038 if (m_supports_qGroupName)
2039 {
2040 char packet[32];
2041 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002042 assert (packet_len < (int)sizeof(packet));
Greg Clayton32e0a752011-03-30 18:16:51 +00002043 StringExtractorGDBRemote response;
2044 if (SendPacketAndWaitForResponse (packet, packet_len, response, false))
2045 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002046 if (response.IsNormalResponse())
2047 {
2048 // Make sure we parsed the right number of characters. The response is
2049 // the hex encoded group name and should make up the entire packet.
2050 // If there are any non-hex ASCII bytes, the length won't match below..
2051 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size())
2052 return true;
2053 }
2054 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002055 else
2056 {
2057 m_supports_qGroupName = false;
2058 return false;
2059 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002060 }
2061 return false;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002062}
Greg Clayton32e0a752011-03-30 18:16:51 +00002063
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002064void
2065GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets)
2066{
2067 uint32_t i;
2068 TimeValue start_time, end_time;
2069 uint64_t total_time_nsec;
2070 float packets_per_second;
2071 if (SendSpeedTestPacket (0, 0))
2072 {
2073 for (uint32_t send_size = 0; send_size <= 1024; send_size *= 2)
2074 {
2075 for (uint32_t recv_size = 0; recv_size <= 1024; recv_size *= 2)
2076 {
2077 start_time = TimeValue::Now();
2078 for (i=0; i<num_packets; ++i)
2079 {
2080 SendSpeedTestPacket (send_size, recv_size);
2081 }
2082 end_time = TimeValue::Now();
2083 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002084 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Daniel Malead01b2952012-11-29 21:49:15 +00002085 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 +00002086 num_packets,
2087 send_size,
2088 recv_size,
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002089 total_time_nsec / TimeValue::NanoSecPerSec,
2090 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002091 packets_per_second);
2092 if (recv_size == 0)
2093 recv_size = 32;
2094 }
2095 if (send_size == 0)
2096 send_size = 32;
2097 }
2098 }
2099 else
2100 {
2101 start_time = TimeValue::Now();
2102 for (i=0; i<num_packets; ++i)
2103 {
2104 GetCurrentProcessID ();
2105 }
2106 end_time = TimeValue::Now();
2107 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970();
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002108 packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec;
Daniel Malead01b2952012-11-29 21:49:15 +00002109 printf ("%u 'qC' packets packets in 0x%" PRIu64 "%9.9" PRIu64 " sec for %f packets/sec.\n",
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002110 num_packets,
Peter Collingbourneba23ca02011-06-18 23:52:14 +00002111 total_time_nsec / TimeValue::NanoSecPerSec,
2112 total_time_nsec % TimeValue::NanoSecPerSec,
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002113 packets_per_second);
2114 }
2115}
2116
2117bool
2118GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size)
2119{
2120 StreamString packet;
2121 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size);
2122 uint32_t bytes_left = send_size;
2123 while (bytes_left > 0)
2124 {
2125 if (bytes_left >= 26)
2126 {
2127 packet.PutCString("abcdefghijklmnopqrstuvwxyz");
2128 bytes_left -= 26;
2129 }
2130 else
2131 {
2132 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz");
2133 bytes_left = 0;
2134 }
2135 }
2136
2137 StringExtractorGDBRemote response;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002138 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) > 0;
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00002139 return false;
Greg Clayton32e0a752011-03-30 18:16:51 +00002140}
Greg Clayton8b82f082011-04-12 05:54:46 +00002141
2142uint16_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002143GDBRemoteCommunicationClient::LaunchGDBserverAndGetPort (lldb::pid_t &pid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002144{
Daniel Maleae0f8f572013-08-26 23:57:52 +00002145 pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton8b82f082011-04-12 05:54:46 +00002146 StringExtractorGDBRemote response;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002147 StreamString stream;
2148 stream.PutCString("qLaunchGDBServer:port:0;");
2149 std::string hostname;
2150 if (Host::GetHostname (hostname))
2151 {
2152 // Make the GDB server we launch only accept connections from this host
2153 stream.Printf("host:%s;", hostname.c_str());
2154 }
2155 else
2156 {
2157 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname
2158 stream.Printf("host:*;");
2159 }
2160 const char *packet = stream.GetData();
2161 int packet_len = stream.GetSize();
2162
2163 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
Greg Clayton8b82f082011-04-12 05:54:46 +00002164 {
2165 std::string name;
2166 std::string value;
2167 uint16_t port = 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002168 while (response.GetNameColonValue(name, value))
2169 {
Daniel Maleae0f8f572013-08-26 23:57:52 +00002170 if (name.compare("port") == 0)
Greg Clayton8b82f082011-04-12 05:54:46 +00002171 port = Args::StringToUInt32(value.c_str(), 0, 0);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002172 else if (name.compare("pid") == 0)
2173 pid = Args::StringToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00002174 }
2175 return port;
2176 }
2177 return 0;
2178}
2179
2180bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00002181GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid)
2182{
2183 StreamString stream;
2184 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid);
2185 const char *packet = stream.GetData();
2186 int packet_len = stream.GetSize();
2187 pid = LLDB_INVALID_PROCESS_ID;
2188 StringExtractorGDBRemote response;
2189 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2190 {
2191 if (response.IsOKResponse())
2192 return true;
2193 }
2194 return false;
2195}
2196
2197bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002198GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002199{
2200 if (m_curr_tid == tid)
2201 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002202
Greg Clayton8b82f082011-04-12 05:54:46 +00002203 char packet[32];
2204 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002205 if (tid == UINT64_MAX)
2206 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002207 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002208 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002209 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002210 StringExtractorGDBRemote response;
2211 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2212 {
2213 if (response.IsOKResponse())
2214 {
2215 m_curr_tid = tid;
2216 return true;
2217 }
2218 }
2219 return false;
2220}
2221
2222bool
Jason Molendae9ca4af2013-02-23 02:04:45 +00002223GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid)
Greg Clayton8b82f082011-04-12 05:54:46 +00002224{
2225 if (m_curr_tid_run == tid)
2226 return true;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002227
Greg Clayton8b82f082011-04-12 05:54:46 +00002228 char packet[32];
2229 int packet_len;
Jason Molendae9ca4af2013-02-23 02:04:45 +00002230 if (tid == UINT64_MAX)
2231 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1");
Greg Clayton8b82f082011-04-12 05:54:46 +00002232 else
Jason Molendae9ca4af2013-02-23 02:04:45 +00002233 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid);
2234
Andy Gibbsa297a972013-06-19 19:04:53 +00002235 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002236 StringExtractorGDBRemote response;
2237 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2238 {
2239 if (response.IsOKResponse())
2240 {
2241 m_curr_tid_run = tid;
2242 return true;
2243 }
2244 }
2245 return false;
2246}
2247
2248bool
2249GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response)
2250{
2251 if (SendPacketAndWaitForResponse("?", 1, response, false))
2252 return response.IsNormalResponse();
2253 return false;
2254}
2255
2256bool
Greg Claytonf402f782012-10-13 02:11:55 +00002257GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response)
Greg Clayton8b82f082011-04-12 05:54:46 +00002258{
2259 if (m_supports_qThreadStopInfo)
2260 {
2261 char packet[256];
Daniel Malead01b2952012-11-29 21:49:15 +00002262 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid);
Andy Gibbsa297a972013-06-19 19:04:53 +00002263 assert (packet_len < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002264 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2265 {
Greg Clayton17a0cb62011-05-15 23:46:54 +00002266 if (response.IsNormalResponse())
Greg Clayton8b82f082011-04-12 05:54:46 +00002267 return true;
2268 else
2269 return false;
2270 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002271 else
2272 {
2273 m_supports_qThreadStopInfo = false;
2274 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002275 }
Greg Clayton5fe15d22011-05-20 03:15:54 +00002276// if (SetCurrentThread (tid))
2277// return GetStopReply (response);
Greg Clayton8b82f082011-04-12 05:54:46 +00002278 return false;
2279}
2280
2281
2282uint8_t
2283GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length)
2284{
2285 switch (type)
2286 {
2287 case eBreakpointSoftware: if (!m_supports_z0) return UINT8_MAX; break;
2288 case eBreakpointHardware: if (!m_supports_z1) return UINT8_MAX; break;
2289 case eWatchpointWrite: if (!m_supports_z2) return UINT8_MAX; break;
2290 case eWatchpointRead: if (!m_supports_z3) return UINT8_MAX; break;
2291 case eWatchpointReadWrite: if (!m_supports_z4) return UINT8_MAX; break;
Greg Clayton8b82f082011-04-12 05:54:46 +00002292 }
2293
2294 char packet[64];
2295 const int packet_len = ::snprintf (packet,
2296 sizeof(packet),
Daniel Malead01b2952012-11-29 21:49:15 +00002297 "%c%i,%" PRIx64 ",%x",
Greg Clayton8b82f082011-04-12 05:54:46 +00002298 insert ? 'Z' : 'z',
2299 type,
2300 addr,
2301 length);
2302
Andy Gibbsa297a972013-06-19 19:04:53 +00002303 assert (packet_len + 1 < (int)sizeof(packet));
Greg Clayton8b82f082011-04-12 05:54:46 +00002304 StringExtractorGDBRemote response;
2305 if (SendPacketAndWaitForResponse(packet, packet_len, response, true))
2306 {
2307 if (response.IsOKResponse())
2308 return 0;
Greg Clayton8b82f082011-04-12 05:54:46 +00002309 else if (response.IsErrorResponse())
2310 return response.GetError();
2311 }
Greg Clayton17a0cb62011-05-15 23:46:54 +00002312 else
2313 {
2314 switch (type)
2315 {
2316 case eBreakpointSoftware: m_supports_z0 = false; break;
2317 case eBreakpointHardware: m_supports_z1 = false; break;
2318 case eWatchpointWrite: m_supports_z2 = false; break;
2319 case eWatchpointRead: m_supports_z3 = false; break;
2320 case eWatchpointReadWrite: m_supports_z4 = false; break;
Greg Clayton17a0cb62011-05-15 23:46:54 +00002321 }
2322 }
2323
Greg Clayton8b82f082011-04-12 05:54:46 +00002324 return UINT8_MAX;
2325}
Greg Claytonadc00cb2011-05-20 23:38:13 +00002326
2327size_t
2328GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids,
2329 bool &sequence_mutex_unavailable)
2330{
2331 Mutex::Locker locker;
2332 thread_ids.clear();
2333
Jim Ingham4ceb9282012-06-08 22:50:40 +00002334 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002335 {
2336 sequence_mutex_unavailable = false;
2337 StringExtractorGDBRemote response;
2338
Greg Clayton73bf5db2011-06-17 01:22:15 +00002339 for (SendPacketNoLock ("qfThreadInfo", strlen("qfThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ());
Greg Claytonadc00cb2011-05-20 23:38:13 +00002340 response.IsNormalResponse();
Greg Clayton73bf5db2011-06-17 01:22:15 +00002341 SendPacketNoLock ("qsThreadInfo", strlen("qsThreadInfo")) && WaitForPacketWithTimeoutMicroSecondsNoLock (response, GetPacketTimeoutInMicroSeconds ()))
Greg Claytonadc00cb2011-05-20 23:38:13 +00002342 {
2343 char ch = response.GetChar();
2344 if (ch == 'l')
2345 break;
2346 if (ch == 'm')
2347 {
2348 do
2349 {
Jason Molendae9ca4af2013-02-23 02:04:45 +00002350 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
Greg Claytonadc00cb2011-05-20 23:38:13 +00002351
2352 if (tid != LLDB_INVALID_THREAD_ID)
2353 {
2354 thread_ids.push_back (tid);
2355 }
2356 ch = response.GetChar(); // Skip the command separator
2357 } while (ch == ','); // Make sure we got a comma separator
2358 }
2359 }
2360 }
2361 else
2362 {
Jim Ingham4ceb9282012-06-08 22:50:40 +00002363#if defined (LLDB_CONFIGURATION_DEBUG)
2364 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex");
2365#else
Greg Clayton5160ce52013-03-27 23:08:40 +00002366 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS));
Greg Claytonc3c0b0e2012-04-12 19:04:34 +00002367 if (log)
2368 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'");
Jim Ingham4ceb9282012-06-08 22:50:40 +00002369#endif
Greg Claytonadc00cb2011-05-20 23:38:13 +00002370 sequence_mutex_unavailable = true;
2371 }
2372 return thread_ids.size();
2373}
Greg Clayton37a0a242012-04-11 00:24:49 +00002374
2375lldb::addr_t
2376GDBRemoteCommunicationClient::GetShlibInfoAddr()
2377{
2378 if (!IsRunning())
2379 {
2380 StringExtractorGDBRemote response;
2381 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false))
2382 {
2383 if (response.IsNormalResponse())
2384 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2385 }
2386 }
2387 return LLDB_INVALID_ADDRESS;
2388}
2389
Daniel Maleae0f8f572013-08-26 23:57:52 +00002390lldb_private::Error
2391GDBRemoteCommunicationClient::RunShellCommand (const char *command, // Shouldn't be NULL
2392 const char *working_dir, // Pass NULL to use the current working directory
2393 int *status_ptr, // Pass NULL if you don't want the process exit status
2394 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit
2395 std::string *command_output, // Pass NULL if you don't want the command output
2396 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
2397{
2398 lldb_private::StreamString stream;
2399 stream.PutCString("qPlatform_RunCommand:");
2400 stream.PutBytesAsRawHex8(command, strlen(command));
2401 stream.PutChar(',');
2402 stream.PutHex32(timeout_sec);
2403 if (working_dir && *working_dir)
2404 {
2405 stream.PutChar(',');
2406 stream.PutBytesAsRawHex8(working_dir, strlen(working_dir));
2407 }
2408 const char *packet = stream.GetData();
2409 int packet_len = stream.GetSize();
2410 StringExtractorGDBRemote response;
2411 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2412 {
2413 if (response.GetChar() != 'F')
2414 return Error("malformed reply");
2415 if (response.GetChar() != ',')
2416 return Error("malformed reply");
2417 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX);
2418 if (exitcode == UINT32_MAX)
2419 return Error("unable to run remote process");
2420 else if (status_ptr)
2421 *status_ptr = exitcode;
2422 if (response.GetChar() != ',')
2423 return Error("malformed reply");
2424 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX);
2425 if (signo_ptr)
2426 *signo_ptr = signo;
2427 if (response.GetChar() != ',')
2428 return Error("malformed reply");
2429 std::string output;
2430 response.GetEscapedBinaryData(output);
2431 if (command_output)
2432 command_output->assign(output);
2433 return Error();
2434 }
2435 return Error("unable to send packet");
2436}
2437
2438uint32_t
2439GDBRemoteCommunicationClient::MakeDirectory (const std::string &path,
2440 mode_t mode)
2441{
2442 lldb_private::StreamString stream;
2443 stream.PutCString("qPlatform_IO_MkDir:");
2444 stream.PutHex32(mode);
2445 stream.PutChar(',');
2446 stream.PutBytesAsRawHex8(path.c_str(), path.size());
2447 const char *packet = stream.GetData();
2448 int packet_len = stream.GetSize();
2449 StringExtractorGDBRemote response;
2450 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2451 {
2452 return response.GetHexMaxU32(false, UINT32_MAX);
2453 }
2454 return UINT32_MAX;
2455
2456}
2457
2458static uint64_t
2459ParseHostIOPacketResponse (StringExtractorGDBRemote &response,
2460 uint64_t fail_result,
2461 Error &error)
2462{
2463 response.SetFilePos(0);
2464 if (response.GetChar() != 'F')
2465 return fail_result;
2466 int32_t result = response.GetS32 (-2);
2467 if (result == -2)
2468 return fail_result;
2469 if (response.GetChar() == ',')
2470 {
2471 int result_errno = response.GetS32 (-2);
2472 if (result_errno != -2)
2473 error.SetError(result_errno, eErrorTypePOSIX);
2474 else
2475 error.SetError(-1, eErrorTypeGeneric);
2476 }
2477 else
2478 error.Clear();
2479 return result;
2480}
2481lldb::user_id_t
2482GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec,
2483 uint32_t flags,
2484 mode_t mode,
2485 Error &error)
2486{
2487 lldb_private::StreamString stream;
2488 stream.PutCString("vFile:open:");
2489 std::string path (file_spec.GetPath());
2490 if (path.empty())
2491 return UINT64_MAX;
2492 stream.PutCStringAsRawHex8(path.c_str());
2493 stream.PutChar(',');
2494 const uint32_t posix_open_flags = File::ConvertOpenOptionsForPOSIXOpen(flags);
2495 stream.PutHex32(posix_open_flags);
2496 stream.PutChar(',');
2497 stream.PutHex32(mode);
2498 const char* packet = stream.GetData();
2499 int packet_len = stream.GetSize();
2500 StringExtractorGDBRemote response;
2501 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2502 {
2503 return ParseHostIOPacketResponse (response, UINT64_MAX, error);
2504 }
2505 return UINT64_MAX;
2506}
2507
2508bool
2509GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd,
2510 Error &error)
2511{
2512 lldb_private::StreamString stream;
2513 stream.Printf("vFile:close:%i", (int)fd);
2514 const char* packet = stream.GetData();
2515 int packet_len = stream.GetSize();
2516 StringExtractorGDBRemote response;
2517 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2518 {
2519 return ParseHostIOPacketResponse (response, -1, error) == 0;
2520 }
2521 return UINT64_MAX;
2522}
2523
2524// Extension of host I/O packets to get the file size.
2525lldb::user_id_t
2526GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec)
2527{
2528 lldb_private::StreamString stream;
2529 stream.PutCString("vFile:size:");
2530 std::string path (file_spec.GetPath());
2531 stream.PutCStringAsRawHex8(path.c_str());
2532 const char* packet = stream.GetData();
2533 int packet_len = stream.GetSize();
2534 StringExtractorGDBRemote response;
2535 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2536 {
2537 if (response.GetChar() != 'F')
2538 return UINT64_MAX;
2539 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX);
2540 return retcode;
2541 }
2542 return UINT64_MAX;
2543}
2544
2545uint32_t
2546GDBRemoteCommunicationClient::GetFilePermissions(const lldb_private::FileSpec& file_spec, Error &error)
2547{
2548 lldb_private::StreamString stream;
2549 stream.PutCString("vFile:mode:");
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 {
2559 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet);
2560 return 0;
2561 }
2562 const uint32_t mode = response.GetS32(-1);
2563 if (mode == -1)
2564 {
2565 if (response.GetChar() == ',')
2566 {
2567 int response_errno = response.GetS32(-1);
2568 if (response_errno > 0)
2569 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2570 else
2571 error.SetErrorToGenericError();
2572 }
2573 }
2574 else
2575 error.Clear();
2576 return mode & (S_IRWXU|S_IRWXG|S_IRWXO);
2577 }
2578 else
2579 {
2580 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet);
2581 }
2582 return 0;
2583}
2584
2585uint64_t
2586GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd,
2587 uint64_t offset,
2588 void *dst,
2589 uint64_t dst_len,
2590 Error &error)
2591{
2592 lldb_private::StreamString stream;
2593 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset);
2594 const char* packet = stream.GetData();
2595 int packet_len = stream.GetSize();
2596 StringExtractorGDBRemote response;
2597 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2598 {
2599 if (response.GetChar() != 'F')
2600 return 0;
2601 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX);
2602 if (retcode == UINT32_MAX)
2603 return retcode;
2604 const char next = (response.Peek() ? *response.Peek() : 0);
2605 if (next == ',')
2606 return 0;
2607 if (next == ';')
2608 {
2609 response.GetChar(); // skip the semicolon
2610 std::string buffer;
2611 if (response.GetEscapedBinaryData(buffer))
2612 {
2613 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size());
2614 if (data_to_write > 0)
2615 memcpy(dst, &buffer[0], data_to_write);
2616 return data_to_write;
2617 }
2618 }
2619 }
2620 return 0;
2621}
2622
2623uint64_t
2624GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd,
2625 uint64_t offset,
2626 const void* src,
2627 uint64_t src_len,
2628 Error &error)
2629{
2630 lldb_private::StreamGDBRemote stream;
2631 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset);
2632 stream.PutEscapedBytes(src, src_len);
2633 const char* packet = stream.GetData();
2634 int packet_len = stream.GetSize();
2635 StringExtractorGDBRemote response;
2636 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2637 {
2638 if (response.GetChar() != 'F')
2639 {
2640 error.SetErrorStringWithFormat("write file failed");
2641 return 0;
2642 }
2643 uint64_t bytes_written = response.GetU64(UINT64_MAX);
2644 if (bytes_written == UINT64_MAX)
2645 {
2646 error.SetErrorToGenericError();
2647 if (response.GetChar() == ',')
2648 {
2649 int response_errno = response.GetS32(-1);
2650 if (response_errno > 0)
2651 error.SetError(response_errno, lldb::eErrorTypePOSIX);
2652 }
2653 return 0;
2654 }
2655 return bytes_written;
2656 }
2657 else
2658 {
2659 error.SetErrorString ("failed to send vFile:pwrite packet");
2660 }
2661 return 0;
2662}
2663
2664// Extension of host I/O packets to get whether a file exists.
2665bool
2666GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec)
2667{
2668 lldb_private::StreamString stream;
2669 stream.PutCString("vFile:exists:");
2670 std::string path (file_spec.GetPath());
2671 stream.PutCStringAsRawHex8(path.c_str());
2672 const char* packet = stream.GetData();
2673 int packet_len = stream.GetSize();
2674 StringExtractorGDBRemote response;
2675 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2676 {
2677 if (response.GetChar() != 'F')
2678 return false;
2679 if (response.GetChar() != ',')
2680 return false;
2681 bool retcode = (response.GetChar() != '0');
2682 return retcode;
2683 }
2684 return false;
2685}
2686
2687bool
2688GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec,
2689 uint64_t &high,
2690 uint64_t &low)
2691{
2692 lldb_private::StreamString stream;
2693 stream.PutCString("vFile:MD5:");
2694 std::string path (file_spec.GetPath());
2695 stream.PutCStringAsRawHex8(path.c_str());
2696 const char* packet = stream.GetData();
2697 int packet_len = stream.GetSize();
2698 StringExtractorGDBRemote response;
2699 if (SendPacketAndWaitForResponse(packet, packet_len, response, false))
2700 {
2701 if (response.GetChar() != 'F')
2702 return false;
2703 if (response.GetChar() != ',')
2704 return false;
2705 if (response.Peek() && *response.Peek() == 'x')
2706 return false;
2707 low = response.GetHexMaxU64(false, UINT64_MAX);
2708 high = response.GetHexMaxU64(false, UINT64_MAX);
2709 return true;
2710 }
2711 return false;
2712}