blob: 7d0cf5ede8dcafce671a4f7055220ef06a8c4e60 [file] [log] [blame]
Greg Clayton576d8832011-03-22 04:00:09 +00001//===-- GDBRemoteCommunicationServer.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
Sylvestre Ledrud28b9932013-09-28 15:23:41 +000010#include <errno.h>
Greg Clayton576d8832011-03-22 04:00:09 +000011
Zachary Turner0ec7baa2014-07-01 00:18:46 +000012#include "lldb/Host/Config.h"
13
Greg Clayton576d8832011-03-22 04:00:09 +000014#include "GDBRemoteCommunicationServer.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000015#include "lldb/Core/StreamGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000016
17// C Includes
18// C++ Includes
Todd Fialaaf245d12014-06-30 21:05:18 +000019#include <cstring>
Todd Fiala2850b1b2014-06-30 23:51:35 +000020#include <chrono>
21#include <thread>
Todd Fialaaf245d12014-06-30 21:05:18 +000022
Greg Clayton576d8832011-03-22 04:00:09 +000023// Other libraries and framework includes
24#include "llvm/ADT/Triple.h"
25#include "lldb/Interpreter/Args.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000026#include "lldb/Core/Debugger.h"
Greg Clayton576d8832011-03-22 04:00:09 +000027#include "lldb/Core/Log.h"
28#include "lldb/Core/State.h"
29#include "lldb/Core/StreamString.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000030#include "lldb/Host/ConnectionFileDescriptor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000031#include "lldb/Host/Debug.h"
Enrico Granataf2bbf712011-07-15 02:26:42 +000032#include "lldb/Host/Endian.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000033#include "lldb/Host/File.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000034#include "lldb/Host/FileSystem.h"
Greg Clayton576d8832011-03-22 04:00:09 +000035#include "lldb/Host/Host.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000036#include "lldb/Host/HostInfo.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000037#include "lldb/Host/StringConvert.h"
Greg Clayton576d8832011-03-22 04:00:09 +000038#include "lldb/Host/TimeValue.h"
Zachary Turner696b5282014-08-14 16:01:25 +000039#include "lldb/Target/FileAction.h"
Todd Fialab8b49ec2014-01-28 00:34:23 +000040#include "lldb/Target/Platform.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000041#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000042#include "lldb/Target/NativeRegisterContext.h"
Todd Fiala24189d42014-07-14 06:24:44 +000043#include "Host/common/NativeProcessProtocol.h"
44#include "Host/common/NativeThreadProtocol.h"
Greg Clayton576d8832011-03-22 04:00:09 +000045
46// Project includes
47#include "Utility/StringExtractorGDBRemote.h"
Vince Harron1b5a74e2015-01-21 22:42:49 +000048#include "Utility/UriParser.h"
Greg Clayton576d8832011-03-22 04:00:09 +000049#include "ProcessGDBRemote.h"
50#include "ProcessGDBRemoteLog.h"
51
52using namespace lldb;
53using namespace lldb_private;
54
55//----------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +000056// GDBRemote Errors
57//----------------------------------------------------------------------
58
59namespace
60{
61 enum GDBRemoteServerError
62 {
63 // Set to the first unused error number in literal form below
64 eErrorFirst = 29,
65 eErrorNoProcess = eErrorFirst,
66 eErrorResume,
67 eErrorExitStatus
68 };
69}
70
71//----------------------------------------------------------------------
Greg Clayton576d8832011-03-22 04:00:09 +000072// GDBRemoteCommunicationServer constructor
73//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +000074GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform) :
75 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
Greg Clayton615eb7e2014-09-19 20:11:50 +000076 m_platform_sp (Platform::GetHostPlatform ()),
Greg Clayton8b82f082011-04-12 05:54:46 +000077 m_async_thread (LLDB_INVALID_HOST_THREAD),
78 m_process_launch_info (),
79 m_process_launch_error (),
Daniel Maleae0f8f572013-08-26 23:57:52 +000080 m_spawned_pids (),
81 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton8b82f082011-04-12 05:54:46 +000082 m_proc_infos (),
83 m_proc_infos_index (0),
Greg Clayton2b98c562013-11-22 18:53:12 +000084 m_port_map (),
Todd Fialaaf245d12014-06-30 21:05:18 +000085 m_port_offset(0),
86 m_current_tid (LLDB_INVALID_THREAD_ID),
87 m_continue_tid (LLDB_INVALID_THREAD_ID),
88 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
89 m_debugged_process_sp (),
90 m_debugger_sp (),
91 m_stdio_communication ("process.stdio"),
92 m_exit_now (false),
93 m_inferior_prev_state (StateType::eStateInvalid),
94 m_thread_suffix_supported (false),
95 m_list_threads_in_stop_reply (false),
96 m_active_auxv_buffer_sp (),
97 m_saved_registers_mutex (),
98 m_saved_registers_map (),
99 m_next_saved_registers_id (1)
Greg Clayton576d8832011-03-22 04:00:09 +0000100{
Todd Fialaaf245d12014-06-30 21:05:18 +0000101 assert(is_platform && "must be lldb-platform if debugger is not specified");
Greg Clayton576d8832011-03-22 04:00:09 +0000102}
103
Todd Fialab8b49ec2014-01-28 00:34:23 +0000104GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform,
Todd Fialaaf245d12014-06-30 21:05:18 +0000105 const lldb::PlatformSP& platform_sp,
106 lldb::DebuggerSP &debugger_sp) :
Todd Fialab8b49ec2014-01-28 00:34:23 +0000107 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
108 m_platform_sp (platform_sp),
109 m_async_thread (LLDB_INVALID_HOST_THREAD),
110 m_process_launch_info (),
111 m_process_launch_error (),
112 m_spawned_pids (),
113 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
114 m_proc_infos (),
115 m_proc_infos_index (0),
116 m_port_map (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000117 m_port_offset(0),
118 m_current_tid (LLDB_INVALID_THREAD_ID),
119 m_continue_tid (LLDB_INVALID_THREAD_ID),
120 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
121 m_debugged_process_sp (),
122 m_debugger_sp (debugger_sp),
123 m_stdio_communication ("process.stdio"),
124 m_exit_now (false),
125 m_inferior_prev_state (StateType::eStateInvalid),
126 m_thread_suffix_supported (false),
127 m_list_threads_in_stop_reply (false),
128 m_active_auxv_buffer_sp (),
129 m_saved_registers_mutex (),
130 m_saved_registers_map (),
131 m_next_saved_registers_id (1)
Todd Fialab8b49ec2014-01-28 00:34:23 +0000132{
133 assert(platform_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000134 assert((is_platform || debugger_sp) && "must specify non-NULL debugger_sp when lldb-gdbserver");
Todd Fialab8b49ec2014-01-28 00:34:23 +0000135}
136
Greg Clayton576d8832011-03-22 04:00:09 +0000137//----------------------------------------------------------------------
138// Destructor
139//----------------------------------------------------------------------
140GDBRemoteCommunicationServer::~GDBRemoteCommunicationServer()
141{
142}
143
Todd Fialaaf245d12014-06-30 21:05:18 +0000144GDBRemoteCommunication::PacketResult
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000145GDBRemoteCommunicationServer::GetPacketAndSendResponse (uint32_t timeout_usec,
Greg Clayton1cb64962011-03-24 04:28:38 +0000146 Error &error,
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000147 bool &interrupt,
Greg Claytond314e812011-03-23 00:09:55 +0000148 bool &quit)
Greg Clayton576d8832011-03-22 04:00:09 +0000149{
150 StringExtractorGDBRemote packet;
Todd Fialaaf245d12014-06-30 21:05:18 +0000151
Greg Clayton3dedae12013-12-06 21:45:27 +0000152 PacketResult packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, timeout_usec);
153 if (packet_result == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000154 {
155 const StringExtractorGDBRemote::ServerPacketType packet_type = packet.GetServerPacketType ();
156 switch (packet_type)
157 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000158 case StringExtractorGDBRemote::eServerPacketType_nack:
159 case StringExtractorGDBRemote::eServerPacketType_ack:
160 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000161
Greg Clayton3dedae12013-12-06 21:45:27 +0000162 case StringExtractorGDBRemote::eServerPacketType_invalid:
163 error.SetErrorString("invalid packet");
164 quit = true;
165 break;
Greg Claytond314e812011-03-23 00:09:55 +0000166
Greg Clayton3dedae12013-12-06 21:45:27 +0000167 default:
168 case StringExtractorGDBRemote::eServerPacketType_unimplemented:
169 packet_result = SendUnimplementedResponse (packet.GetStringRef().c_str());
170 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000171
Greg Clayton3dedae12013-12-06 21:45:27 +0000172 case StringExtractorGDBRemote::eServerPacketType_A:
173 packet_result = Handle_A (packet);
174 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000175
Greg Clayton3dedae12013-12-06 21:45:27 +0000176 case StringExtractorGDBRemote::eServerPacketType_qfProcessInfo:
177 packet_result = Handle_qfProcessInfo (packet);
178 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000179
Greg Clayton3dedae12013-12-06 21:45:27 +0000180 case StringExtractorGDBRemote::eServerPacketType_qsProcessInfo:
181 packet_result = Handle_qsProcessInfo (packet);
182 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000183
Greg Clayton3dedae12013-12-06 21:45:27 +0000184 case StringExtractorGDBRemote::eServerPacketType_qC:
185 packet_result = Handle_qC (packet);
186 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000187
Greg Clayton3dedae12013-12-06 21:45:27 +0000188 case StringExtractorGDBRemote::eServerPacketType_qHostInfo:
189 packet_result = Handle_qHostInfo (packet);
190 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000191
Greg Clayton3dedae12013-12-06 21:45:27 +0000192 case StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer:
193 packet_result = Handle_qLaunchGDBServer (packet);
194 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000195
Greg Clayton3dedae12013-12-06 21:45:27 +0000196 case StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess:
197 packet_result = Handle_qKillSpawnedProcess (packet);
198 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000199
Todd Fiala403edc52014-01-23 22:05:44 +0000200 case StringExtractorGDBRemote::eServerPacketType_k:
201 packet_result = Handle_k (packet);
Todd Fialaaf245d12014-06-30 21:05:18 +0000202 quit = true;
Todd Fiala403edc52014-01-23 22:05:44 +0000203 break;
204
Greg Clayton3dedae12013-12-06 21:45:27 +0000205 case StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess:
206 packet_result = Handle_qLaunchSuccess (packet);
207 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000208
Greg Clayton3dedae12013-12-06 21:45:27 +0000209 case StringExtractorGDBRemote::eServerPacketType_qGroupName:
210 packet_result = Handle_qGroupName (packet);
211 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000212
Todd Fialaaf245d12014-06-30 21:05:18 +0000213 case StringExtractorGDBRemote::eServerPacketType_qProcessInfo:
214 packet_result = Handle_qProcessInfo (packet);
215 break;
216
Greg Clayton3dedae12013-12-06 21:45:27 +0000217 case StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID:
218 packet_result = Handle_qProcessInfoPID (packet);
219 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000220
Greg Clayton3dedae12013-12-06 21:45:27 +0000221 case StringExtractorGDBRemote::eServerPacketType_qSpeedTest:
222 packet_result = Handle_qSpeedTest (packet);
223 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000224
Greg Clayton3dedae12013-12-06 21:45:27 +0000225 case StringExtractorGDBRemote::eServerPacketType_qUserName:
226 packet_result = Handle_qUserName (packet);
227 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000228
Greg Clayton3dedae12013-12-06 21:45:27 +0000229 case StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir:
230 packet_result = Handle_qGetWorkingDir(packet);
231 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000232
Greg Clayton3dedae12013-12-06 21:45:27 +0000233 case StringExtractorGDBRemote::eServerPacketType_QEnvironment:
234 packet_result = Handle_QEnvironment (packet);
235 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000236
Greg Clayton3dedae12013-12-06 21:45:27 +0000237 case StringExtractorGDBRemote::eServerPacketType_QLaunchArch:
238 packet_result = Handle_QLaunchArch (packet);
239 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000240
Greg Clayton3dedae12013-12-06 21:45:27 +0000241 case StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR:
242 packet_result = Handle_QSetDisableASLR (packet);
243 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000244
Jim Ingham106d0282014-06-25 02:32:56 +0000245 case StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError:
246 packet_result = Handle_QSetDetachOnError (packet);
247 break;
248
Greg Clayton3dedae12013-12-06 21:45:27 +0000249 case StringExtractorGDBRemote::eServerPacketType_QSetSTDIN:
250 packet_result = Handle_QSetSTDIN (packet);
251 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000252
Greg Clayton3dedae12013-12-06 21:45:27 +0000253 case StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT:
254 packet_result = Handle_QSetSTDOUT (packet);
255 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000256
Greg Clayton3dedae12013-12-06 21:45:27 +0000257 case StringExtractorGDBRemote::eServerPacketType_QSetSTDERR:
258 packet_result = Handle_QSetSTDERR (packet);
259 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000260
Greg Clayton3dedae12013-12-06 21:45:27 +0000261 case StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir:
262 packet_result = Handle_QSetWorkingDir (packet);
263 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000264
Greg Clayton3dedae12013-12-06 21:45:27 +0000265 case StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode:
266 packet_result = Handle_QStartNoAckMode (packet);
267 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000268
Greg Clayton3dedae12013-12-06 21:45:27 +0000269 case StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir:
270 packet_result = Handle_qPlatform_mkdir (packet);
271 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000272
Greg Clayton3dedae12013-12-06 21:45:27 +0000273 case StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod:
274 packet_result = Handle_qPlatform_chmod (packet);
275 break;
Greg Claytonfbb76342013-11-20 21:07:01 +0000276
Greg Clayton3dedae12013-12-06 21:45:27 +0000277 case StringExtractorGDBRemote::eServerPacketType_qPlatform_shell:
278 packet_result = Handle_qPlatform_shell (packet);
279 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000280
Todd Fialaaf245d12014-06-30 21:05:18 +0000281 case StringExtractorGDBRemote::eServerPacketType_C:
282 packet_result = Handle_C (packet);
283 break;
284
285 case StringExtractorGDBRemote::eServerPacketType_c:
286 packet_result = Handle_c (packet);
287 break;
288
289 case StringExtractorGDBRemote::eServerPacketType_vCont:
290 packet_result = Handle_vCont (packet);
291 break;
292
293 case StringExtractorGDBRemote::eServerPacketType_vCont_actions:
294 packet_result = Handle_vCont_actions (packet);
295 break;
296
297 case StringExtractorGDBRemote::eServerPacketType_stop_reason: // ?
298 packet_result = Handle_stop_reason (packet);
299 break;
300
Greg Clayton3dedae12013-12-06 21:45:27 +0000301 case StringExtractorGDBRemote::eServerPacketType_vFile_open:
302 packet_result = Handle_vFile_Open (packet);
303 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000304
Greg Clayton3dedae12013-12-06 21:45:27 +0000305 case StringExtractorGDBRemote::eServerPacketType_vFile_close:
306 packet_result = Handle_vFile_Close (packet);
307 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000308
Greg Clayton3dedae12013-12-06 21:45:27 +0000309 case StringExtractorGDBRemote::eServerPacketType_vFile_pread:
310 packet_result = Handle_vFile_pRead (packet);
311 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000312
Greg Clayton3dedae12013-12-06 21:45:27 +0000313 case StringExtractorGDBRemote::eServerPacketType_vFile_pwrite:
314 packet_result = Handle_vFile_pWrite (packet);
315 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000316
Greg Clayton3dedae12013-12-06 21:45:27 +0000317 case StringExtractorGDBRemote::eServerPacketType_vFile_size:
318 packet_result = Handle_vFile_Size (packet);
319 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000320
Greg Clayton3dedae12013-12-06 21:45:27 +0000321 case StringExtractorGDBRemote::eServerPacketType_vFile_mode:
322 packet_result = Handle_vFile_Mode (packet);
323 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000324
Greg Clayton3dedae12013-12-06 21:45:27 +0000325 case StringExtractorGDBRemote::eServerPacketType_vFile_exists:
326 packet_result = Handle_vFile_Exists (packet);
327 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000328
Greg Clayton3dedae12013-12-06 21:45:27 +0000329 case StringExtractorGDBRemote::eServerPacketType_vFile_stat:
330 packet_result = Handle_vFile_Stat (packet);
331 break;
Greg Claytonfbb76342013-11-20 21:07:01 +0000332
Greg Clayton3dedae12013-12-06 21:45:27 +0000333 case StringExtractorGDBRemote::eServerPacketType_vFile_md5:
334 packet_result = Handle_vFile_MD5 (packet);
335 break;
336
337 case StringExtractorGDBRemote::eServerPacketType_vFile_symlink:
338 packet_result = Handle_vFile_symlink (packet);
339 break;
340
341 case StringExtractorGDBRemote::eServerPacketType_vFile_unlink:
342 packet_result = Handle_vFile_unlink (packet);
343 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000344
345 case StringExtractorGDBRemote::eServerPacketType_qRegisterInfo:
346 packet_result = Handle_qRegisterInfo (packet);
347 break;
348
349 case StringExtractorGDBRemote::eServerPacketType_qfThreadInfo:
350 packet_result = Handle_qfThreadInfo (packet);
351 break;
352
353 case StringExtractorGDBRemote::eServerPacketType_qsThreadInfo:
354 packet_result = Handle_qsThreadInfo (packet);
355 break;
356
357 case StringExtractorGDBRemote::eServerPacketType_p:
358 packet_result = Handle_p (packet);
359 break;
360
361 case StringExtractorGDBRemote::eServerPacketType_P:
362 packet_result = Handle_P (packet);
363 break;
364
365 case StringExtractorGDBRemote::eServerPacketType_H:
366 packet_result = Handle_H (packet);
367 break;
368
369 case StringExtractorGDBRemote::eServerPacketType_m:
370 packet_result = Handle_m (packet);
371 break;
372
373 case StringExtractorGDBRemote::eServerPacketType_M:
374 packet_result = Handle_M (packet);
375 break;
376
377 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported:
378 packet_result = Handle_qMemoryRegionInfoSupported (packet);
379 break;
380
381 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo:
382 packet_result = Handle_qMemoryRegionInfo (packet);
383 break;
384
385 case StringExtractorGDBRemote::eServerPacketType_interrupt:
386 if (IsGdbServer ())
387 packet_result = Handle_interrupt (packet);
388 else
389 {
390 error.SetErrorString("interrupt received");
391 interrupt = true;
392 }
393 break;
394
395 case StringExtractorGDBRemote::eServerPacketType_Z:
396 packet_result = Handle_Z (packet);
397 break;
398
399 case StringExtractorGDBRemote::eServerPacketType_z:
400 packet_result = Handle_z (packet);
401 break;
402
403 case StringExtractorGDBRemote::eServerPacketType_s:
404 packet_result = Handle_s (packet);
405 break;
406
407 case StringExtractorGDBRemote::eServerPacketType_qSupported:
408 packet_result = Handle_qSupported (packet);
409 break;
410
411 case StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported:
412 packet_result = Handle_QThreadSuffixSupported (packet);
413 break;
414
415 case StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply:
416 packet_result = Handle_QListThreadsInStopReply (packet);
417 break;
418
419 case StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read:
420 packet_result = Handle_qXfer_auxv_read (packet);
421 break;
422
423 case StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState:
424 packet_result = Handle_QSaveRegisterState (packet);
425 break;
426
427 case StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState:
428 packet_result = Handle_QRestoreRegisterState (packet);
429 break;
Todd Fiala7306cf32014-07-29 22:30:01 +0000430
431 case StringExtractorGDBRemote::eServerPacketType_vAttach:
432 packet_result = Handle_vAttach (packet);
433 break;
Todd Fiala1109ed42014-09-10 21:28:38 +0000434
Oleksiy Vyalov859e4b52014-12-10 01:27:28 +0000435 case StringExtractorGDBRemote::eServerPacketType_D:
436 packet_result = Handle_D (packet);
437 break;
438
Todd Fiala1109ed42014-09-10 21:28:38 +0000439 case StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo:
440 packet_result = Handle_qThreadStopInfo (packet);
441 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000442 }
Greg Clayton576d8832011-03-22 04:00:09 +0000443 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000444 else
445 {
446 if (!IsConnected())
Greg Clayton3dedae12013-12-06 21:45:27 +0000447 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000448 error.SetErrorString("lost connection");
Greg Clayton3dedae12013-12-06 21:45:27 +0000449 quit = true;
450 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000451 else
Greg Clayton3dedae12013-12-06 21:45:27 +0000452 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000453 error.SetErrorString("timeout");
Greg Clayton3dedae12013-12-06 21:45:27 +0000454 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000455 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000456
457 // Check if anything occurred that would force us to want to exit.
458 if (m_exit_now)
459 quit = true;
460
461 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000462}
463
Todd Fiala403edc52014-01-23 22:05:44 +0000464lldb_private::Error
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000465GDBRemoteCommunicationServer::SetLaunchArguments (const char *const args[], int argc)
Todd Fiala403edc52014-01-23 22:05:44 +0000466{
467 if ((argc < 1) || !args || !args[0] || !args[0][0])
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000468 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
Todd Fiala403edc52014-01-23 22:05:44 +0000469
Todd Fiala403edc52014-01-23 22:05:44 +0000470 m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000471 return lldb_private::Error ();
472}
473
474lldb_private::Error
475GDBRemoteCommunicationServer::SetLaunchFlags (unsigned int launch_flags)
476{
Todd Fiala403edc52014-01-23 22:05:44 +0000477 m_process_launch_info.GetFlags ().Set (launch_flags);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000478 return lldb_private::Error ();
479}
480
481lldb_private::Error
482GDBRemoteCommunicationServer::LaunchProcess ()
483{
Todd Fialaaf245d12014-06-30 21:05:18 +0000484 // FIXME This looks an awful lot like we could override this in
485 // derived classes, one for lldb-platform, the other for lldb-gdbserver.
486 if (IsGdbServer ())
Todd Fiala87bac592014-09-18 21:02:03 +0000487 return LaunchProcessForDebugging ();
Todd Fialaaf245d12014-06-30 21:05:18 +0000488 else
489 return LaunchPlatformProcess ();
490}
491
Todd Fiala75f47c32014-10-11 21:42:09 +0000492bool
493GDBRemoteCommunicationServer::ShouldRedirectInferiorOutputOverGdbRemote (const lldb_private::ProcessLaunchInfo &launch_info) const
494{
495 // Retrieve the file actions specified for stdout and stderr.
496 auto stdout_file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
497 auto stderr_file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
498
499 // If neither stdout and stderr file actions are specified, we're not doing anything special, so
500 // assume we want to redirect stdout/stderr over gdb-remote $O messages.
501 if ((stdout_file_action == nullptr) && (stderr_file_action == nullptr))
502 {
503 // Send stdout/stderr over the gdb-remote protocol.
504 return true;
505 }
506
507 // Any other setting for either stdout or stderr implies we are either suppressing
508 // it (with /dev/null) or we've got it set to a PTY. Either way, we don't want the
509 // output over gdb-remote.
510 return false;
511}
512
Todd Fialaaf245d12014-06-30 21:05:18 +0000513lldb_private::Error
Todd Fiala87bac592014-09-18 21:02:03 +0000514GDBRemoteCommunicationServer::LaunchProcessForDebugging ()
Todd Fialaaf245d12014-06-30 21:05:18 +0000515{
516 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
517
518 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
519 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
520
521 lldb_private::Error error;
522 {
523 Mutex::Locker locker (m_debugged_process_mutex);
524 assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
525 error = m_platform_sp->LaunchNativeProcess (
526 m_process_launch_info,
527 *this,
528 m_debugged_process_sp);
529 }
530
531 if (!error.Success ())
532 {
533 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
534 return error;
535 }
536
Todd Fiala75f47c32014-10-11 21:42:09 +0000537 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as needed.
538 // llgs local-process debugging may specify PTYs, which will eliminate the need to reflect inferior
539 // stdout/stderr over the gdb-remote protocol.
540 if (ShouldRedirectInferiorOutputOverGdbRemote (m_process_launch_info))
Todd Fialaaf245d12014-06-30 21:05:18 +0000541 {
542 if (log)
Todd Fiala75f47c32014-10-11 21:42:09 +0000543 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " setting up stdout/stderr redirection via $O gdb-remote commands", __FUNCTION__, m_debugged_process_sp->GetID ());
544
545 // Setup stdout/stderr mapping from inferior to $O
546 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
547 if (terminal_fd >= 0)
548 {
549 if (log)
550 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
551 error = SetSTDIOFileDescriptor (terminal_fd);
552 if (error.Fail ())
553 return error;
554 }
555 else
556 {
557 if (log)
558 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
559 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000560 }
561 else
562 {
563 if (log)
Todd Fiala75f47c32014-10-11 21:42:09 +0000564 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " skipping stdout/stderr redirection via $O: inferior will communicate over client-provided file descriptors", __FUNCTION__, m_debugged_process_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000565 }
566
567 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
568
569 // Add to list of spawned processes.
570 lldb::pid_t pid;
571 if ((pid = m_process_launch_info.GetProcessID ()) != LLDB_INVALID_PROCESS_ID)
572 {
573 // add to spawned pids
Todd Fiala87bac592014-09-18 21:02:03 +0000574 Mutex::Locker locker (m_spawned_pids_mutex);
575 // On an lldb-gdbserver, we would expect there to be only one.
576 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
577 m_spawned_pids.insert (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000578 }
579
580 return error;
581}
582
583lldb_private::Error
584GDBRemoteCommunicationServer::LaunchPlatformProcess ()
585{
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000586 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
587 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
588
589 // specify the process monitor if not already set. This should
590 // generally be what happens since we need to reap started
591 // processes.
592 if (!m_process_launch_info.GetMonitorProcessCallback ())
593 m_process_launch_info.SetMonitorProcessCallback(ReapDebuggedProcess, this, false);
Todd Fiala403edc52014-01-23 22:05:44 +0000594
Todd Fialab8b49ec2014-01-28 00:34:23 +0000595 lldb_private::Error error = m_platform_sp->LaunchProcess (m_process_launch_info);
Todd Fiala403edc52014-01-23 22:05:44 +0000596 if (!error.Success ())
597 {
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000598 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
Todd Fiala403edc52014-01-23 22:05:44 +0000599 return error;
600 }
601
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000602 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID());
Todd Fiala403edc52014-01-23 22:05:44 +0000603
604 // add to list of spawned processes. On an lldb-gdbserver, we
605 // would expect there to be only one.
606 lldb::pid_t pid;
607 if ( (pid = m_process_launch_info.GetProcessID()) != LLDB_INVALID_PROCESS_ID )
608 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000609 // add to spawned pids
610 {
611 Mutex::Locker locker (m_spawned_pids_mutex);
612 m_spawned_pids.insert(pid);
613 }
Todd Fiala403edc52014-01-23 22:05:44 +0000614 }
615
616 return error;
617}
618
Todd Fialaaf245d12014-06-30 21:05:18 +0000619lldb_private::Error
620GDBRemoteCommunicationServer::AttachToProcess (lldb::pid_t pid)
621{
622 Error error;
623
624 if (!IsGdbServer ())
625 {
626 error.SetErrorString("cannot AttachToProcess () unless process is lldb-gdbserver");
627 return error;
628 }
629
630 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
631 if (log)
632 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64, __FUNCTION__, pid);
633
634 // Scope for mutex locker.
635 {
636 // Before we try to attach, make sure we aren't already monitoring something else.
637 Mutex::Locker locker (m_spawned_pids_mutex);
638 if (!m_spawned_pids.empty ())
639 {
640 error.SetErrorStringWithFormat ("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, *m_spawned_pids.begin());
641 return error;
642 }
643
644 // Try to attach.
645 error = m_platform_sp->AttachNativeProcess (pid, *this, m_debugged_process_sp);
646 if (!error.Success ())
647 {
648 fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
649 return error;
650 }
651
652 // Setup stdout/stderr mapping from inferior.
653 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
654 if (terminal_fd >= 0)
655 {
656 if (log)
657 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
658 error = SetSTDIOFileDescriptor (terminal_fd);
659 if (error.Fail ())
660 return error;
661 }
662 else
663 {
664 if (log)
665 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
666 }
667
668 printf ("Attached to process %" PRIu64 "...\n", pid);
669
670 // Add to list of spawned processes.
671 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
672 m_spawned_pids.insert (pid);
673
674 return error;
675 }
676}
677
678void
679GDBRemoteCommunicationServer::InitializeDelegate (lldb_private::NativeProcessProtocol *process)
680{
681 assert (process && "process cannot be NULL");
682 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
683 if (log)
684 {
685 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
686 __FUNCTION__,
687 process->GetID (),
688 StateAsCString (process->GetState ()));
689 }
690}
691
692GDBRemoteCommunication::PacketResult
693GDBRemoteCommunicationServer::SendWResponse (lldb_private::NativeProcessProtocol *process)
694{
695 assert (process && "process cannot be NULL");
696 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
697
698 // send W notification
699 ExitType exit_type = ExitType::eExitTypeInvalid;
700 int return_code = 0;
701 std::string exit_description;
702
703 const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
704 if (!got_exit_info)
705 {
706 if (log)
707 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
708
709 StreamGDBRemote response;
710 response.PutChar ('E');
711 response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
712 return SendPacketNoLock(response.GetData(), response.GetSize());
713 }
714 else
715 {
716 if (log)
717 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", returning exit type %d, return code %d [%s]", __FUNCTION__, process->GetID (), exit_type, return_code, exit_description.c_str ());
718
719 StreamGDBRemote response;
720
721 char return_type_code;
722 switch (exit_type)
723 {
Saleem Abdulrasoola7874222014-09-08 14:59:36 +0000724 case ExitType::eExitTypeExit:
725 return_type_code = 'W';
726 break;
727 case ExitType::eExitTypeSignal:
728 return_type_code = 'X';
729 break;
730 case ExitType::eExitTypeStop:
731 return_type_code = 'S';
732 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000733 case ExitType::eExitTypeInvalid:
Saleem Abdulrasoola7874222014-09-08 14:59:36 +0000734 return_type_code = 'E';
735 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000736 }
737 response.PutChar (return_type_code);
738
739 // POSIX exit status limited to unsigned 8 bits.
740 response.PutHex8 (return_code);
741
742 return SendPacketNoLock(response.GetData(), response.GetSize());
743 }
744}
745
746static void
747AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
748{
749 int64_t i;
750 if (swap)
751 {
752 for (i = buf_size-1; i >= 0; i--)
753 response.PutHex8 (buf[i]);
754 }
755 else
756 {
757 for (i = 0; i < buf_size; i++)
758 response.PutHex8 (buf[i]);
759 }
760}
761
762static void
763WriteRegisterValueInHexFixedWidth (StreamString &response,
764 NativeRegisterContextSP &reg_ctx_sp,
765 const RegisterInfo &reg_info,
766 const RegisterValue *reg_value_p)
767{
768 RegisterValue reg_value;
769 if (!reg_value_p)
770 {
771 Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
772 if (error.Success ())
773 reg_value_p = &reg_value;
774 // else log.
775 }
776
777 if (reg_value_p)
778 {
779 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
780 }
781 else
782 {
783 // Zero-out any unreadable values.
784 if (reg_info.byte_size > 0)
785 {
786 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
787 AppendHexValue (response, zeros.data(), zeros.size(), false);
788 }
789 }
790}
791
792// WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
793
794
795static void
796WriteGdbRegnumWithFixedWidthHexRegisterValue (StreamString &response,
797 NativeRegisterContextSP &reg_ctx_sp,
798 const RegisterInfo &reg_info,
799 const RegisterValue &reg_value)
800{
801 // Output the register number as 'NN:VVVVVVVV;' where NN is a 2 bytes HEX
802 // gdb register number, and VVVVVVVV is the correct number of hex bytes
803 // as ASCII for the register value.
804 if (reg_info.kinds[eRegisterKindGDB] == LLDB_INVALID_REGNUM)
805 return;
806
807 response.Printf ("%.02x:", reg_info.kinds[eRegisterKindGDB]);
808 WriteRegisterValueInHexFixedWidth (response, reg_ctx_sp, reg_info, &reg_value);
809 response.PutChar (';');
810}
811
812
813GDBRemoteCommunication::PacketResult
814GDBRemoteCommunicationServer::SendStopReplyPacketForThread (lldb::tid_t tid)
815{
816 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
817
818 // Ensure we're llgs.
819 if (!IsGdbServer ())
820 {
821 // Only supported on llgs
822 return SendUnimplementedResponse ("");
823 }
824
825 // Ensure we have a debugged process.
826 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
827 return SendErrorResponse (50);
828
829 if (log)
830 log->Printf ("GDBRemoteCommunicationServer::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
831 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
832
833 // Ensure we can get info on the given thread.
834 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
835 if (!thread_sp)
836 return SendErrorResponse (51);
837
838 // Grab the reason this thread stopped.
839 struct ThreadStopInfo tid_stop_info;
840 if (!thread_sp->GetStopReason (tid_stop_info))
841 return SendErrorResponse (52);
842
843 const bool did_exec = tid_stop_info.reason == eStopReasonExec;
844 // FIXME implement register handling for exec'd inferiors.
845 // if (did_exec)
846 // {
847 // const bool force = true;
848 // InitializeRegisters(force);
849 // }
850
851 StreamString response;
852 // Output the T packet with the thread
853 response.PutChar ('T');
854 int signum = tid_stop_info.details.signal.signo;
855 if (log)
856 {
857 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
858 __FUNCTION__,
859 m_debugged_process_sp->GetID (),
860 tid,
861 signum,
862 tid_stop_info.reason,
863 tid_stop_info.details.exception.type);
864 }
865
866 switch (tid_stop_info.reason)
867 {
868 case eStopReasonSignal:
869 case eStopReasonException:
870 signum = thread_sp->TranslateStopInfoToGdbSignal (tid_stop_info);
871 break;
872 default:
873 signum = 0;
874 if (log)
875 {
876 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " has stop reason %d, using signo = 0 in stop reply response",
877 __FUNCTION__,
878 m_debugged_process_sp->GetID (),
879 tid,
880 tid_stop_info.reason);
881 }
882 break;
883 }
884
885 // Print the signal number.
886 response.PutHex8 (signum & 0xff);
887
888 // Include the tid.
889 response.Printf ("thread:%" PRIx64 ";", tid);
890
891 // Include the thread name if there is one.
Todd Fiala7206c6d2014-09-12 22:51:49 +0000892 const std::string thread_name = thread_sp->GetName ();
893 if (!thread_name.empty ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000894 {
Todd Fiala7206c6d2014-09-12 22:51:49 +0000895 size_t thread_name_len = thread_name.length ();
Todd Fialaaf245d12014-06-30 21:05:18 +0000896
Todd Fiala7206c6d2014-09-12 22:51:49 +0000897 if (::strcspn (thread_name.c_str (), "$#+-;:") == thread_name_len)
Todd Fialaaf245d12014-06-30 21:05:18 +0000898 {
899 response.PutCString ("name:");
Todd Fiala7206c6d2014-09-12 22:51:49 +0000900 response.PutCString (thread_name.c_str ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000901 }
902 else
903 {
904 // The thread name contains special chars, send as hex bytes.
905 response.PutCString ("hexname:");
Todd Fiala7206c6d2014-09-12 22:51:49 +0000906 response.PutCStringAsRawHex8 (thread_name.c_str ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000907 }
908 response.PutChar (';');
909 }
910
911 // FIXME look for analog
912 // thread_identifier_info_data_t thread_ident_info;
913 // if (DNBThreadGetIdentifierInfo (pid, tid, &thread_ident_info))
914 // {
915 // if (thread_ident_info.dispatch_qaddr != 0)
916 // ostrm << std::hex << "qaddr:" << thread_ident_info.dispatch_qaddr << ';';
917 // }
918
919 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
920 // will send all thread IDs back in the "threads" key whose value is
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000921 // a list of hex thread IDs separated by commas:
Todd Fialaaf245d12014-06-30 21:05:18 +0000922 // "threads:10a,10b,10c;"
923 // This will save the debugger from having to send a pair of qfThreadInfo
924 // and qsThreadInfo packets, but it also might take a lot of room in the
925 // stop reply packet, so it must be enabled only on systems where there
926 // are no limits on packet lengths.
927 if (m_list_threads_in_stop_reply)
928 {
929 response.PutCString ("threads:");
930
931 uint32_t thread_index = 0;
932 NativeThreadProtocolSP listed_thread_sp;
933 for (listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index); listed_thread_sp; ++thread_index, listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
934 {
935 if (thread_index > 0)
936 response.PutChar (',');
937 response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
938 }
939 response.PutChar (';');
940 }
941
942 //
943 // Expedite registers.
944 //
945
946 // Grab the register context.
947 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
948 if (reg_ctx_sp)
949 {
950 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
951 const RegisterSet *reg_set_p;
952 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
953 {
954 if (log)
955 log->Printf ("GDBRemoteCommunicationServer::%s expediting registers from set '%s' (registers set count: %zu)", __FUNCTION__, reg_set_p->name ? reg_set_p->name : "<unnamed-set>", reg_set_p->num_registers);
956
957 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
958 {
959 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
960 if (reg_info_p == nullptr)
961 {
962 if (log)
963 log->Printf ("GDBRemoteCommunicationServer::%s failed to get register info for register set '%s', register index %" PRIu32, __FUNCTION__, reg_set_p->name ? reg_set_p->name : "<unnamed-set>", *reg_num_p);
964 }
965 else if (reg_info_p->value_regs == nullptr)
966 {
967 // Only expediate registers that are not contained in other registers.
968 RegisterValue reg_value;
969 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
970 if (error.Success ())
971 WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
972 else
973 {
974 if (log)
975 log->Printf ("GDBRemoteCommunicationServer::%s failed to read register '%s' index %" PRIu32 ": %s", __FUNCTION__, reg_info_p->name ? reg_info_p->name : "<unnamed-register>", *reg_num_p, error.AsCString ());
976
977 }
978 }
979 }
980 }
981 }
982
983 if (did_exec)
984 {
985 response.PutCString ("reason:exec;");
986 }
987 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
988 {
989 response.PutCString ("metype:");
990 response.PutHex64 (tid_stop_info.details.exception.type);
991 response.PutCString (";mecount:");
992 response.PutHex32 (tid_stop_info.details.exception.data_count);
993 response.PutChar (';');
994
995 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
996 {
997 response.PutCString ("medata:");
998 response.PutHex64 (tid_stop_info.details.exception.data[i]);
999 response.PutChar (';');
1000 }
1001 }
1002
1003 return SendPacketNoLock (response.GetData(), response.GetSize());
1004}
1005
1006void
1007GDBRemoteCommunicationServer::HandleInferiorState_Exited (lldb_private::NativeProcessProtocol *process)
1008{
1009 assert (process && "process cannot be NULL");
1010
1011 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1012 if (log)
1013 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
1014
1015 // Send the exit result, and don't flush output.
1016 // Note: flushing output here would join the inferior stdio reflection thread, which
1017 // would gunk up the waitpid monitor thread that is calling this.
1018 PacketResult result = SendStopReasonForState (StateType::eStateExited, false);
1019 if (result != PacketResult::Success)
1020 {
1021 if (log)
1022 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1023 }
1024
1025 // Remove the process from the list of spawned pids.
1026 {
1027 Mutex::Locker locker (m_spawned_pids_mutex);
1028 if (m_spawned_pids.erase (process->GetID ()) < 1)
1029 {
1030 if (log)
1031 log->Printf ("GDBRemoteCommunicationServer::%s failed to remove PID %" PRIu64 " from the spawned pids list", __FUNCTION__, process->GetID ());
1032
1033 }
1034 }
1035
1036 // FIXME can't do this yet - since process state propagation is currently
1037 // synchronous, it is running off the NativeProcessProtocol's innards and
1038 // will tear down the NPP while it still has code to execute.
1039#if 0
1040 // Clear the NativeProcessProtocol pointer.
1041 {
1042 Mutex::Locker locker (m_debugged_process_mutex);
1043 m_debugged_process_sp.reset();
1044 }
1045#endif
1046
1047 // Close the pipe to the inferior terminal i/o if we launched it
1048 // and set one up. Otherwise, 'k' and its flush of stdio could
1049 // end up waiting on a thread join that will never end. Consider
1050 // adding a timeout to the connection thread join call so we
1051 // can avoid that scenario altogether.
1052 MaybeCloseInferiorTerminalConnection ();
1053
1054 // We are ready to exit the debug monitor.
1055 m_exit_now = true;
1056}
1057
1058void
1059GDBRemoteCommunicationServer::HandleInferiorState_Stopped (lldb_private::NativeProcessProtocol *process)
1060{
1061 assert (process && "process cannot be NULL");
1062
1063 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1064 if (log)
1065 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
1066
1067 // Send the stop reason unless this is the stop after the
1068 // launch or attach.
1069 switch (m_inferior_prev_state)
1070 {
1071 case eStateLaunching:
1072 case eStateAttaching:
1073 // Don't send anything per debugserver behavior.
1074 break;
1075 default:
1076 // In all other cases, send the stop reason.
1077 PacketResult result = SendStopReasonForState (StateType::eStateStopped, false);
1078 if (result != PacketResult::Success)
1079 {
1080 if (log)
1081 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1082 }
1083 break;
1084 }
1085}
1086
1087void
1088GDBRemoteCommunicationServer::ProcessStateChanged (lldb_private::NativeProcessProtocol *process, lldb::StateType state)
1089{
1090 assert (process && "process cannot be NULL");
1091 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1092 if (log)
1093 {
1094 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
1095 __FUNCTION__,
1096 process->GetID (),
1097 StateAsCString (state));
1098 }
1099
1100 switch (state)
1101 {
1102 case StateType::eStateExited:
1103 HandleInferiorState_Exited (process);
1104 break;
1105
1106 case StateType::eStateStopped:
1107 HandleInferiorState_Stopped (process);
1108 break;
1109
1110 default:
1111 if (log)
1112 {
1113 log->Printf ("GDBRemoteCommunicationServer::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
1114 __FUNCTION__,
1115 process->GetID (),
1116 StateAsCString (state));
1117 }
1118 break;
1119 }
1120
1121 // Remember the previous state reported to us.
1122 m_inferior_prev_state = state;
1123}
1124
Todd Fialaa9882ce2014-08-28 15:46:54 +00001125void
1126GDBRemoteCommunicationServer::DidExec (NativeProcessProtocol *process)
1127{
1128 ClearProcessSpecificData ();
1129}
1130
Todd Fialaaf245d12014-06-30 21:05:18 +00001131GDBRemoteCommunication::PacketResult
1132GDBRemoteCommunicationServer::SendONotification (const char *buffer, uint32_t len)
1133{
1134 if ((buffer == nullptr) || (len == 0))
1135 {
1136 // Nothing to send.
1137 return PacketResult::Success;
1138 }
1139
1140 StreamString response;
1141 response.PutChar ('O');
1142 response.PutBytesAsRawHex8 (buffer, len);
1143
1144 return SendPacketNoLock (response.GetData (), response.GetSize ());
1145}
1146
1147lldb_private::Error
1148GDBRemoteCommunicationServer::SetSTDIOFileDescriptor (int fd)
1149{
1150 Error error;
1151
1152 // Set up the Read Thread for reading/handling process I/O
1153 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
1154 if (!conn_up)
1155 {
1156 error.SetErrorString ("failed to create ConnectionFileDescriptor");
1157 return error;
1158 }
1159
1160 m_stdio_communication.SetConnection (conn_up.release());
1161 if (!m_stdio_communication.IsConnected ())
1162 {
1163 error.SetErrorString ("failed to set connection for inferior I/O communication");
1164 return error;
1165 }
1166
1167 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1168 m_stdio_communication.StartReadThread();
1169
1170 return error;
1171}
1172
1173void
1174GDBRemoteCommunicationServer::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1175{
1176 GDBRemoteCommunicationServer *server = reinterpret_cast<GDBRemoteCommunicationServer*> (baton);
1177 static_cast<void> (server->SendONotification (static_cast<const char *>(src), src_len));
1178}
1179
Greg Clayton3dedae12013-12-06 21:45:27 +00001180GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001181GDBRemoteCommunicationServer::SendUnimplementedResponse (const char *)
Greg Clayton576d8832011-03-22 04:00:09 +00001182{
Greg Clayton32e0a752011-03-30 18:16:51 +00001183 // TODO: Log the packet we aren't handling...
Greg Clayton37a0a242012-04-11 00:24:49 +00001184 return SendPacketNoLock ("", 0);
Greg Clayton576d8832011-03-22 04:00:09 +00001185}
1186
Todd Fialaaf245d12014-06-30 21:05:18 +00001187
Greg Clayton3dedae12013-12-06 21:45:27 +00001188GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001189GDBRemoteCommunicationServer::SendErrorResponse (uint8_t err)
1190{
1191 char packet[16];
1192 int packet_len = ::snprintf (packet, sizeof(packet), "E%2.2x", err);
Andy Gibbsa297a972013-06-19 19:04:53 +00001193 assert (packet_len < (int)sizeof(packet));
Greg Clayton37a0a242012-04-11 00:24:49 +00001194 return SendPacketNoLock (packet, packet_len);
Greg Clayton32e0a752011-03-30 18:16:51 +00001195}
1196
Todd Fialaaf245d12014-06-30 21:05:18 +00001197GDBRemoteCommunication::PacketResult
1198GDBRemoteCommunicationServer::SendIllFormedResponse (const StringExtractorGDBRemote &failed_packet, const char *message)
1199{
1200 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
1201 if (log)
1202 log->Printf ("GDBRemoteCommunicationServer::%s: ILLFORMED: '%s' (%s)", __FUNCTION__, failed_packet.GetStringRef ().c_str (), message ? message : "");
1203 return SendErrorResponse (0x03);
1204}
Greg Clayton32e0a752011-03-30 18:16:51 +00001205
Greg Clayton3dedae12013-12-06 21:45:27 +00001206GDBRemoteCommunication::PacketResult
Greg Clayton1cb64962011-03-24 04:28:38 +00001207GDBRemoteCommunicationServer::SendOKResponse ()
1208{
Greg Clayton37a0a242012-04-11 00:24:49 +00001209 return SendPacketNoLock ("OK", 2);
Greg Clayton1cb64962011-03-24 04:28:38 +00001210}
1211
1212bool
1213GDBRemoteCommunicationServer::HandshakeWithClient(Error *error_ptr)
1214{
Greg Clayton3dedae12013-12-06 21:45:27 +00001215 return GetAck() == PacketResult::Success;
Greg Clayton1cb64962011-03-24 04:28:38 +00001216}
Greg Clayton576d8832011-03-22 04:00:09 +00001217
Greg Clayton3dedae12013-12-06 21:45:27 +00001218GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001219GDBRemoteCommunicationServer::Handle_qHostInfo (StringExtractorGDBRemote &packet)
Greg Clayton576d8832011-03-22 04:00:09 +00001220{
1221 StreamString response;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001222
Greg Clayton576d8832011-03-22 04:00:09 +00001223 // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00
1224
Zachary Turner13b18262014-08-20 16:42:51 +00001225 ArchSpec host_arch(HostInfo::GetArchitecture());
Greg Clayton576d8832011-03-22 04:00:09 +00001226 const llvm::Triple &host_triple = host_arch.GetTriple();
Greg Clayton1cb64962011-03-24 04:28:38 +00001227 response.PutCString("triple:");
Greg Clayton44272a42014-09-18 00:18:32 +00001228 response.PutCStringAsRawHex8(host_triple.getTriple().c_str());
Greg Clayton1cb64962011-03-24 04:28:38 +00001229 response.Printf (";ptrsize:%u;",host_arch.GetAddressByteSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001230
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001231 const char* distribution_id = host_arch.GetDistributionId ().AsCString ();
1232 if (distribution_id)
1233 {
1234 response.PutCString("distribution_id:");
1235 response.PutCStringAsRawHex8(distribution_id);
1236 response.PutCString(";");
1237 }
1238
Todd Fialaaf245d12014-06-30 21:05:18 +00001239 // Only send out MachO info when lldb-platform/llgs is running on a MachO host.
1240#if defined(__APPLE__)
Greg Clayton1cb64962011-03-24 04:28:38 +00001241 uint32_t cpu = host_arch.GetMachOCPUType();
1242 uint32_t sub = host_arch.GetMachOCPUSubType();
1243 if (cpu != LLDB_INVALID_CPUTYPE)
1244 response.Printf ("cputype:%u;", cpu);
1245 if (sub != LLDB_INVALID_CPUTYPE)
1246 response.Printf ("cpusubtype:%u;", sub);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001247
Enrico Granata1c5431a2012-07-13 23:55:22 +00001248 if (cpu == ArchSpec::kCore_arm_any)
Enrico Granataf04a2192012-07-13 23:18:48 +00001249 response.Printf("watchpoint_exceptions_received:before;"); // On armv7 we use "synchronous" watchpoints which means the exception is delivered before the instruction executes.
1250 else
1251 response.Printf("watchpoint_exceptions_received:after;");
Todd Fialaaf245d12014-06-30 21:05:18 +00001252#else
1253 response.Printf("watchpoint_exceptions_received:after;");
1254#endif
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001255
Greg Clayton576d8832011-03-22 04:00:09 +00001256 switch (lldb::endian::InlHostByteOrder())
1257 {
1258 case eByteOrderBig: response.PutCString ("endian:big;"); break;
1259 case eByteOrderLittle: response.PutCString ("endian:little;"); break;
1260 case eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1261 default: response.PutCString ("endian:unknown;"); break;
1262 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001263
Greg Clayton1cb64962011-03-24 04:28:38 +00001264 uint32_t major = UINT32_MAX;
1265 uint32_t minor = UINT32_MAX;
1266 uint32_t update = UINT32_MAX;
Zachary Turner97a14e62014-08-19 17:18:29 +00001267 if (HostInfo::GetOSVersion(major, minor, update))
Greg Clayton1cb64962011-03-24 04:28:38 +00001268 {
1269 if (major != UINT32_MAX)
1270 {
1271 response.Printf("os_version:%u", major);
1272 if (minor != UINT32_MAX)
1273 {
1274 response.Printf(".%u", minor);
1275 if (update != UINT32_MAX)
1276 response.Printf(".%u", update);
1277 }
1278 response.PutChar(';');
1279 }
1280 }
1281
1282 std::string s;
Zachary Turner97a14e62014-08-19 17:18:29 +00001283 if (HostInfo::GetOSBuildString(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001284 {
1285 response.PutCString ("os_build:");
1286 response.PutCStringAsRawHex8(s.c_str());
1287 response.PutChar(';');
1288 }
Zachary Turner97a14e62014-08-19 17:18:29 +00001289 if (HostInfo::GetOSKernelDescription(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001290 {
1291 response.PutCString ("os_kernel:");
1292 response.PutCStringAsRawHex8(s.c_str());
1293 response.PutChar(';');
1294 }
Zachary Turner97a14e62014-08-19 17:18:29 +00001295
Greg Clayton2b98c562013-11-22 18:53:12 +00001296#if defined(__APPLE__)
1297
Todd Fiala013434e2014-07-09 01:29:05 +00001298#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001299 // For iOS devices, we are connected through a USB Mux so we never pretend
1300 // to actually have a hostname as far as the remote lldb that is connecting
1301 // to this lldb-platform is concerned
1302 response.PutCString ("hostname:");
Greg Clayton16810922014-02-27 19:38:18 +00001303 response.PutCStringAsRawHex8("127.0.0.1");
Greg Clayton2b98c562013-11-22 18:53:12 +00001304 response.PutChar(';');
Todd Fiala013434e2014-07-09 01:29:05 +00001305#else // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Zachary Turner97a14e62014-08-19 17:18:29 +00001306 if (HostInfo::GetHostname(s))
Greg Clayton1cb64962011-03-24 04:28:38 +00001307 {
1308 response.PutCString ("hostname:");
1309 response.PutCStringAsRawHex8(s.c_str());
1310 response.PutChar(';');
1311 }
Todd Fiala013434e2014-07-09 01:29:05 +00001312#endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001313
1314#else // #if defined(__APPLE__)
Zachary Turner97a14e62014-08-19 17:18:29 +00001315 if (HostInfo::GetHostname(s))
Greg Clayton2b98c562013-11-22 18:53:12 +00001316 {
1317 response.PutCString ("hostname:");
1318 response.PutCStringAsRawHex8(s.c_str());
1319 response.PutChar(';');
1320 }
1321#endif // #if defined(__APPLE__)
1322
Greg Clayton3dedae12013-12-06 21:45:27 +00001323 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001324}
Greg Clayton1cb64962011-03-24 04:28:38 +00001325
Greg Clayton32e0a752011-03-30 18:16:51 +00001326static void
Greg Clayton8b82f082011-04-12 05:54:46 +00001327CreateProcessInfoResponse (const ProcessInstanceInfo &proc_info, StreamString &response)
Greg Clayton32e0a752011-03-30 18:16:51 +00001328{
Daniel Malead01b2952012-11-29 21:49:15 +00001329 response.Printf ("pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
Greg Clayton32e0a752011-03-30 18:16:51 +00001330 proc_info.GetProcessID(),
1331 proc_info.GetParentProcessID(),
Greg Clayton8b82f082011-04-12 05:54:46 +00001332 proc_info.GetUserID(),
1333 proc_info.GetGroupID(),
Greg Clayton32e0a752011-03-30 18:16:51 +00001334 proc_info.GetEffectiveUserID(),
1335 proc_info.GetEffectiveGroupID());
1336 response.PutCString ("name:");
1337 response.PutCStringAsRawHex8(proc_info.GetName());
1338 response.PutChar(';');
1339 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1340 if (proc_arch.IsValid())
1341 {
1342 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1343 response.PutCString("triple:");
Greg Clayton44272a42014-09-18 00:18:32 +00001344 response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00001345 response.PutChar(';');
1346 }
1347}
Greg Clayton1cb64962011-03-24 04:28:38 +00001348
Todd Fialaaf245d12014-06-30 21:05:18 +00001349static void
1350CreateProcessInfoResponse_DebugServerStyle (const ProcessInstanceInfo &proc_info, StreamString &response)
1351{
1352 response.Printf ("pid:%" PRIx64 ";parent-pid:%" PRIx64 ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1353 proc_info.GetProcessID(),
1354 proc_info.GetParentProcessID(),
1355 proc_info.GetUserID(),
1356 proc_info.GetGroupID(),
1357 proc_info.GetEffectiveUserID(),
1358 proc_info.GetEffectiveGroupID());
1359
1360 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1361 if (proc_arch.IsValid())
1362 {
Todd Fialac540dd02014-08-26 18:21:02 +00001363 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1364#if defined(__APPLE__)
1365 // We'll send cputype/cpusubtype.
Todd Fialaaf245d12014-06-30 21:05:18 +00001366 const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1367 if (cpu_type != 0)
1368 response.Printf ("cputype:%" PRIx32 ";", cpu_type);
1369
1370 const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1371 if (cpu_subtype != 0)
1372 response.Printf ("cpusubtype:%" PRIx32 ";", cpu_subtype);
Todd Fialac540dd02014-08-26 18:21:02 +00001373
Todd Fialaaf245d12014-06-30 21:05:18 +00001374
Todd Fialaaf245d12014-06-30 21:05:18 +00001375 const std::string vendor = proc_triple.getVendorName ();
1376 if (!vendor.empty ())
1377 response.Printf ("vendor:%s;", vendor.c_str ());
Todd Fialac540dd02014-08-26 18:21:02 +00001378#else
1379 // We'll send the triple.
Greg Clayton44272a42014-09-18 00:18:32 +00001380 response.PutCString("triple:");
1381 response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
1382 response.PutChar(';');
1383
Todd Fialac540dd02014-08-26 18:21:02 +00001384#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001385 std::string ostype = proc_triple.getOSName ();
1386 // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1387 if (proc_triple.getVendor () == llvm::Triple::Apple)
1388 {
1389 switch (proc_triple.getArch ())
1390 {
1391 case llvm::Triple::arm:
Todd Fialad8eaa172014-07-23 14:37:35 +00001392 case llvm::Triple::aarch64:
Todd Fialaaf245d12014-06-30 21:05:18 +00001393 ostype = "ios";
1394 break;
1395 default:
1396 // No change.
1397 break;
1398 }
1399 }
1400 response.Printf ("ostype:%s;", ostype.c_str ());
1401
1402
1403 switch (proc_arch.GetByteOrder ())
1404 {
1405 case lldb::eByteOrderLittle: response.PutCString ("endian:little;"); break;
1406 case lldb::eByteOrderBig: response.PutCString ("endian:big;"); break;
1407 case lldb::eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1408 default:
1409 // Nothing.
1410 break;
1411 }
1412
1413 if (proc_triple.isArch64Bit ())
1414 response.PutCString ("ptrsize:8;");
1415 else if (proc_triple.isArch32Bit ())
1416 response.PutCString ("ptrsize:4;");
1417 else if (proc_triple.isArch16Bit ())
1418 response.PutCString ("ptrsize:2;");
1419 }
1420
1421}
1422
1423
1424GDBRemoteCommunication::PacketResult
1425GDBRemoteCommunicationServer::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1426{
1427 // Only the gdb server handles this.
1428 if (!IsGdbServer ())
1429 return SendUnimplementedResponse (packet.GetStringRef ().c_str ());
1430
1431 // Fail if we don't have a current process.
1432 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1433 return SendErrorResponse (68);
1434
1435 ProcessInstanceInfo proc_info;
1436 if (Host::GetProcessInfo (m_debugged_process_sp->GetID (), proc_info))
1437 {
1438 StreamString response;
1439 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1440 return SendPacketNoLock (response.GetData (), response.GetSize ());
1441 }
1442
1443 return SendErrorResponse (1);
1444}
1445
Greg Clayton3dedae12013-12-06 21:45:27 +00001446GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001447GDBRemoteCommunicationServer::Handle_qProcessInfoPID (StringExtractorGDBRemote &packet)
Greg Clayton1cb64962011-03-24 04:28:38 +00001448{
Greg Clayton32e0a752011-03-30 18:16:51 +00001449 // Packet format: "qProcessInfoPID:%i" where %i is the pid
Greg Clayton8b82f082011-04-12 05:54:46 +00001450 packet.SetFilePos(::strlen ("qProcessInfoPID:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001451 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID);
1452 if (pid != LLDB_INVALID_PROCESS_ID)
1453 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001454 ProcessInstanceInfo proc_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00001455 if (Host::GetProcessInfo(pid, proc_info))
1456 {
1457 StreamString response;
1458 CreateProcessInfoResponse (proc_info, response);
Greg Clayton37a0a242012-04-11 00:24:49 +00001459 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001460 }
1461 }
1462 return SendErrorResponse (1);
1463}
1464
Greg Clayton3dedae12013-12-06 21:45:27 +00001465GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001466GDBRemoteCommunicationServer::Handle_qfProcessInfo (StringExtractorGDBRemote &packet)
1467{
1468 m_proc_infos_index = 0;
1469 m_proc_infos.Clear();
1470
Greg Clayton8b82f082011-04-12 05:54:46 +00001471 ProcessInstanceInfoMatch match_info;
1472 packet.SetFilePos(::strlen ("qfProcessInfo"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001473 if (packet.GetChar() == ':')
1474 {
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001475
Greg Clayton32e0a752011-03-30 18:16:51 +00001476 std::string key;
1477 std::string value;
1478 while (packet.GetNameColonValue(key, value))
1479 {
1480 bool success = true;
1481 if (key.compare("name") == 0)
1482 {
1483 StringExtractor extractor;
1484 extractor.GetStringRef().swap(value);
1485 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00001486 match_info.GetProcessInfo().GetExecutableFile().SetFile(value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00001487 }
1488 else if (key.compare("name_match") == 0)
1489 {
1490 if (value.compare("equals") == 0)
1491 {
1492 match_info.SetNameMatchType (eNameMatchEquals);
1493 }
1494 else if (value.compare("starts_with") == 0)
1495 {
1496 match_info.SetNameMatchType (eNameMatchStartsWith);
1497 }
1498 else if (value.compare("ends_with") == 0)
1499 {
1500 match_info.SetNameMatchType (eNameMatchEndsWith);
1501 }
1502 else if (value.compare("contains") == 0)
1503 {
1504 match_info.SetNameMatchType (eNameMatchContains);
1505 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001506 else if (value.compare("regex") == 0)
Greg Clayton32e0a752011-03-30 18:16:51 +00001507 {
1508 match_info.SetNameMatchType (eNameMatchRegularExpression);
1509 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001510 else
Greg Clayton32e0a752011-03-30 18:16:51 +00001511 {
1512 success = false;
1513 }
1514 }
1515 else if (key.compare("pid") == 0)
1516 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001517 match_info.GetProcessInfo().SetProcessID (StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001518 }
1519 else if (key.compare("parent_pid") == 0)
1520 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001521 match_info.GetProcessInfo().SetParentProcessID (StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001522 }
1523 else if (key.compare("uid") == 0)
1524 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001525 match_info.GetProcessInfo().SetUserID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001526 }
1527 else if (key.compare("gid") == 0)
1528 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001529 match_info.GetProcessInfo().SetGroupID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001530 }
1531 else if (key.compare("euid") == 0)
1532 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001533 match_info.GetProcessInfo().SetEffectiveUserID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001534 }
1535 else if (key.compare("egid") == 0)
1536 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001537 match_info.GetProcessInfo().SetEffectiveGroupID (StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001538 }
1539 else if (key.compare("all_users") == 0)
1540 {
1541 match_info.SetMatchAllUsers(Args::StringToBoolean(value.c_str(), false, &success));
1542 }
1543 else if (key.compare("triple") == 0)
1544 {
Greg Claytoneb0103f2011-04-07 22:46:35 +00001545 match_info.GetProcessInfo().GetArchitecture().SetTriple (value.c_str(), NULL);
Greg Clayton32e0a752011-03-30 18:16:51 +00001546 }
1547 else
1548 {
1549 success = false;
1550 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001551
Greg Clayton32e0a752011-03-30 18:16:51 +00001552 if (!success)
1553 return SendErrorResponse (2);
1554 }
1555 }
1556
1557 if (Host::FindProcesses (match_info, m_proc_infos))
1558 {
1559 // We found something, return the first item by calling the get
1560 // subsequent process info packet handler...
1561 return Handle_qsProcessInfo (packet);
1562 }
1563 return SendErrorResponse (3);
1564}
1565
Greg Clayton3dedae12013-12-06 21:45:27 +00001566GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001567GDBRemoteCommunicationServer::Handle_qsProcessInfo (StringExtractorGDBRemote &packet)
1568{
1569 if (m_proc_infos_index < m_proc_infos.GetSize())
1570 {
1571 StreamString response;
1572 CreateProcessInfoResponse (m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
1573 ++m_proc_infos_index;
Greg Clayton37a0a242012-04-11 00:24:49 +00001574 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001575 }
1576 return SendErrorResponse (4);
1577}
1578
Greg Clayton3dedae12013-12-06 21:45:27 +00001579GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001580GDBRemoteCommunicationServer::Handle_qUserName (StringExtractorGDBRemote &packet)
1581{
Zachary Turnerb245eca2014-08-21 20:02:17 +00001582#if !defined(LLDB_DISABLE_POSIX)
Greg Clayton32e0a752011-03-30 18:16:51 +00001583 // Packet format: "qUserName:%i" where %i is the uid
Greg Clayton8b82f082011-04-12 05:54:46 +00001584 packet.SetFilePos(::strlen ("qUserName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001585 uint32_t uid = packet.GetU32 (UINT32_MAX);
1586 if (uid != UINT32_MAX)
1587 {
1588 std::string name;
Zachary Turnerb245eca2014-08-21 20:02:17 +00001589 if (HostInfo::LookupUserName(uid, name))
Greg Clayton32e0a752011-03-30 18:16:51 +00001590 {
1591 StreamString response;
1592 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001593 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001594 }
1595 }
Zachary Turnerb245eca2014-08-21 20:02:17 +00001596#endif
Greg Clayton32e0a752011-03-30 18:16:51 +00001597 return SendErrorResponse (5);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001598
Greg Clayton32e0a752011-03-30 18:16:51 +00001599}
1600
Greg Clayton3dedae12013-12-06 21:45:27 +00001601GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001602GDBRemoteCommunicationServer::Handle_qGroupName (StringExtractorGDBRemote &packet)
1603{
Zachary Turnerb245eca2014-08-21 20:02:17 +00001604#if !defined(LLDB_DISABLE_POSIX)
Greg Clayton32e0a752011-03-30 18:16:51 +00001605 // Packet format: "qGroupName:%i" where %i is the gid
Greg Clayton8b82f082011-04-12 05:54:46 +00001606 packet.SetFilePos(::strlen ("qGroupName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001607 uint32_t gid = packet.GetU32 (UINT32_MAX);
1608 if (gid != UINT32_MAX)
1609 {
1610 std::string name;
Zachary Turnerb245eca2014-08-21 20:02:17 +00001611 if (HostInfo::LookupGroupName(gid, name))
Greg Clayton32e0a752011-03-30 18:16:51 +00001612 {
1613 StreamString response;
1614 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001615 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001616 }
1617 }
Zachary Turnerb245eca2014-08-21 20:02:17 +00001618#endif
Greg Clayton32e0a752011-03-30 18:16:51 +00001619 return SendErrorResponse (6);
1620}
1621
Greg Clayton3dedae12013-12-06 21:45:27 +00001622GDBRemoteCommunication::PacketResult
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001623GDBRemoteCommunicationServer::Handle_qSpeedTest (StringExtractorGDBRemote &packet)
1624{
Greg Clayton8b82f082011-04-12 05:54:46 +00001625 packet.SetFilePos(::strlen ("qSpeedTest:"));
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001626
1627 std::string key;
1628 std::string value;
1629 bool success = packet.GetNameColonValue(key, value);
1630 if (success && key.compare("response_size") == 0)
1631 {
Vince Harron5275aaa2015-01-15 20:08:35 +00001632 uint32_t response_size = StringConvert::ToUInt32(value.c_str(), 0, 0, &success);
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001633 if (success)
1634 {
1635 if (response_size == 0)
1636 return SendOKResponse();
1637 StreamString response;
1638 uint32_t bytes_left = response_size;
1639 response.PutCString("data:");
1640 while (bytes_left > 0)
1641 {
1642 if (bytes_left >= 26)
1643 {
1644 response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1645 bytes_left -= 26;
1646 }
1647 else
1648 {
1649 response.Printf ("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1650 bytes_left = 0;
1651 }
1652 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001653 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001654 }
1655 }
1656 return SendErrorResponse (7);
1657}
Greg Clayton8b82f082011-04-12 05:54:46 +00001658
Greg Clayton8b82f082011-04-12 05:54:46 +00001659//
1660//static bool
1661//WaitForProcessToSIGSTOP (const lldb::pid_t pid, const int timeout_in_seconds)
1662//{
1663// const int time_delta_usecs = 100000;
1664// const int num_retries = timeout_in_seconds/time_delta_usecs;
1665// for (int i=0; i<num_retries; i++)
1666// {
1667// struct proc_bsdinfo bsd_info;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001668// int error = ::proc_pidinfo (pid, PROC_PIDTBSDINFO,
1669// (uint64_t) 0,
1670// &bsd_info,
Greg Clayton8b82f082011-04-12 05:54:46 +00001671// PROC_PIDTBSDINFO_SIZE);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001672//
Greg Clayton8b82f082011-04-12 05:54:46 +00001673// switch (error)
1674// {
1675// case EINVAL:
1676// case ENOTSUP:
1677// case ESRCH:
1678// case EPERM:
1679// return false;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001680//
Greg Clayton8b82f082011-04-12 05:54:46 +00001681// default:
1682// break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001683//
Greg Clayton8b82f082011-04-12 05:54:46 +00001684// case 0:
1685// if (bsd_info.pbi_status == SSTOP)
1686// return true;
1687// }
1688// ::usleep (time_delta_usecs);
1689// }
1690// return false;
1691//}
1692
Greg Clayton3dedae12013-12-06 21:45:27 +00001693GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001694GDBRemoteCommunicationServer::Handle_A (StringExtractorGDBRemote &packet)
1695{
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001696 // The 'A' packet is the most over designed packet ever here with
1697 // redundant argument indexes, redundant argument lengths and needed hex
1698 // encoded argument string values. Really all that is needed is a comma
Greg Clayton8b82f082011-04-12 05:54:46 +00001699 // separated hex encoded argument value list, but we will stay true to the
1700 // documented version of the 'A' packet here...
1701
Todd Fialaaf245d12014-06-30 21:05:18 +00001702 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1703 int actual_arg_index = 0;
1704
Greg Clayton8b82f082011-04-12 05:54:46 +00001705 packet.SetFilePos(1); // Skip the 'A'
1706 bool success = true;
1707 while (success && packet.GetBytesLeft() > 0)
1708 {
1709 // Decode the decimal argument string length. This length is the
1710 // number of hex nibbles in the argument string value.
1711 const uint32_t arg_len = packet.GetU32(UINT32_MAX);
1712 if (arg_len == UINT32_MAX)
1713 success = false;
1714 else
1715 {
1716 // Make sure the argument hex string length is followed by a comma
1717 if (packet.GetChar() != ',')
1718 success = false;
1719 else
1720 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001721 // Decode the argument index. We ignore this really because
Greg Clayton8b82f082011-04-12 05:54:46 +00001722 // who would really send down the arguments in a random order???
1723 const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
1724 if (arg_idx == UINT32_MAX)
1725 success = false;
1726 else
1727 {
1728 // Make sure the argument index is followed by a comma
1729 if (packet.GetChar() != ',')
1730 success = false;
1731 else
1732 {
1733 // Decode the argument string value from hex bytes
1734 // back into a UTF8 string and make sure the length
1735 // matches the one supplied in the packet
1736 std::string arg;
Todd Fialaaf245d12014-06-30 21:05:18 +00001737 if (packet.GetHexByteStringFixedLength(arg, arg_len) != (arg_len / 2))
Greg Clayton8b82f082011-04-12 05:54:46 +00001738 success = false;
1739 else
1740 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001741 // If there are any bytes left
Greg Clayton8b82f082011-04-12 05:54:46 +00001742 if (packet.GetBytesLeft())
1743 {
1744 if (packet.GetChar() != ',')
1745 success = false;
1746 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001747
Greg Clayton8b82f082011-04-12 05:54:46 +00001748 if (success)
1749 {
1750 if (arg_idx == 0)
1751 m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), false);
1752 m_process_launch_info.GetArguments().AppendArgument(arg.c_str());
Todd Fialaaf245d12014-06-30 21:05:18 +00001753 if (log)
1754 log->Printf ("GDBRemoteCommunicationServer::%s added arg %d: \"%s\"", __FUNCTION__, actual_arg_index, arg.c_str ());
1755 ++actual_arg_index;
Greg Clayton8b82f082011-04-12 05:54:46 +00001756 }
1757 }
1758 }
1759 }
1760 }
1761 }
1762 }
1763
1764 if (success)
1765 {
Todd Fiala9f377372014-01-27 20:44:50 +00001766 m_process_launch_error = LaunchProcess ();
Greg Clayton8b82f082011-04-12 05:54:46 +00001767 if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1768 {
1769 return SendOKResponse ();
1770 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001771 else
1772 {
1773 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1774 if (log)
1775 log->Printf("GDBRemoteCommunicationServer::%s failed to launch exe: %s",
1776 __FUNCTION__,
1777 m_process_launch_error.AsCString());
1778
1779 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001780 }
1781 return SendErrorResponse (8);
1782}
1783
Greg Clayton3dedae12013-12-06 21:45:27 +00001784GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001785GDBRemoteCommunicationServer::Handle_qC (StringExtractorGDBRemote &packet)
1786{
Greg Clayton8b82f082011-04-12 05:54:46 +00001787 StreamString response;
Todd Fialaaf245d12014-06-30 21:05:18 +00001788
1789 if (IsGdbServer ())
Greg Clayton8b82f082011-04-12 05:54:46 +00001790 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001791 // Fail if we don't have a current process.
1792 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1793 return SendErrorResponse (68);
1794
1795 // Make sure we set the current thread so g and p packets return
1796 // the data the gdb will expect.
1797 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1798 SetCurrentThreadID (tid);
1799
1800 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1801 if (!thread_sp)
1802 return SendErrorResponse (69);
1803
1804 response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1805 }
1806 else
1807 {
1808 // NOTE: lldb should now be using qProcessInfo for process IDs. This path here
1809 // should not be used. It is reporting process id instead of thread id. The
1810 // correct answer doesn't seem to make much sense for lldb-platform.
1811 // CONSIDER: flip to "unsupported".
1812 lldb::pid_t pid = m_process_launch_info.GetProcessID();
1813 response.Printf("QC%" PRIx64, pid);
1814
1815 // this should always be platform here
1816 assert (m_is_platform && "this code path should only be traversed for lldb-platform");
1817
1818 if (m_is_platform)
Greg Clayton8b82f082011-04-12 05:54:46 +00001819 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001820 // If we launch a process and this GDB server is acting as a platform,
1821 // then we need to clear the process launch state so we can start
1822 // launching another process. In order to launch a process a bunch or
1823 // packets need to be sent: environment packets, working directory,
1824 // disable ASLR, and many more settings. When we launch a process we
1825 // then need to know when to clear this information. Currently we are
1826 // selecting the 'qC' packet as that packet which seems to make the most
1827 // sense.
1828 if (pid != LLDB_INVALID_PROCESS_ID)
1829 {
1830 m_process_launch_info.Clear();
1831 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001832 }
1833 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001834 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00001835}
1836
1837bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00001838GDBRemoteCommunicationServer::DebugserverProcessReaped (lldb::pid_t pid)
1839{
1840 Mutex::Locker locker (m_spawned_pids_mutex);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001841 FreePortForProcess(pid);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001842 return m_spawned_pids.erase(pid) > 0;
1843}
1844bool
1845GDBRemoteCommunicationServer::ReapDebugserverProcess (void *callback_baton,
1846 lldb::pid_t pid,
1847 bool exited,
1848 int signal, // Zero for no signal
1849 int status) // Exit value of process if signal is zero
1850{
1851 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1852 server->DebugserverProcessReaped (pid);
1853 return true;
1854}
1855
Todd Fiala3e92a2b2014-01-24 00:52:53 +00001856bool
1857GDBRemoteCommunicationServer::DebuggedProcessReaped (lldb::pid_t pid)
1858{
1859 // reap a process that we were debugging (but not debugserver)
1860 Mutex::Locker locker (m_spawned_pids_mutex);
1861 return m_spawned_pids.erase(pid) > 0;
1862}
1863
1864bool
1865GDBRemoteCommunicationServer::ReapDebuggedProcess (void *callback_baton,
1866 lldb::pid_t pid,
1867 bool exited,
1868 int signal, // Zero for no signal
1869 int status) // Exit value of process if signal is zero
1870{
1871 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1872 server->DebuggedProcessReaped (pid);
1873 return true;
1874}
1875
Greg Clayton3dedae12013-12-06 21:45:27 +00001876GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001877GDBRemoteCommunicationServer::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet)
1878{
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001879#ifdef _WIN32
Deepak Panickal263fde02014-01-14 11:34:44 +00001880 return SendErrorResponse(9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001881#else
Todd Fiala015d8182014-07-22 23:41:36 +00001882 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
1883
Greg Clayton8b82f082011-04-12 05:54:46 +00001884 // Spawn a local debugserver as a platform so we can then attach or launch
1885 // a process...
1886
1887 if (m_is_platform)
1888 {
Todd Fiala015d8182014-07-22 23:41:36 +00001889 if (log)
1890 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
1891
Greg Clayton8b82f082011-04-12 05:54:46 +00001892 // Sleep and wait a bit for debugserver to start to listen...
1893 ConnectionFileDescriptor file_conn;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001894 std::string hostname;
Sylvestre Ledrufaa63ce2013-09-28 15:57:37 +00001895 // TODO: /tmp/ should not be hardcoded. User might want to override /tmp
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001896 // with the TMPDIR environment variable
Greg Clayton29b8fc42013-11-21 01:44:58 +00001897 packet.SetFilePos(::strlen ("qLaunchGDBServer;"));
1898 std::string name;
1899 std::string value;
1900 uint16_t port = UINT16_MAX;
1901 while (packet.GetNameColonValue(name, value))
Greg Clayton8b82f082011-04-12 05:54:46 +00001902 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001903 if (name.compare ("host") == 0)
1904 hostname.swap(value);
1905 else if (name.compare ("port") == 0)
Vince Harron5275aaa2015-01-15 20:08:35 +00001906 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00001907 }
Greg Clayton29b8fc42013-11-21 01:44:58 +00001908 if (port == UINT16_MAX)
1909 port = GetNextAvailablePort();
1910
1911 // Spawn a new thread to accept the port that gets bound after
1912 // binding to port 0 (zero).
Greg Claytonfbb76342013-11-20 21:07:01 +00001913
Vince Harron1b5a74e2015-01-21 22:42:49 +00001914 // ignore the hostname send from the remote end, just use the ip address
1915 // that we're currently communicating with as the hostname
1916
Todd Fiala015d8182014-07-22 23:41:36 +00001917 // Spawn a debugserver and try to get the port it listens to.
1918 ProcessLaunchInfo debugserver_launch_info;
1919 if (hostname.empty())
1920 hostname = "127.0.0.1";
1921 if (log)
1922 log->Printf("Launching debugserver with: %s:%u...\n", hostname.c_str(), port);
1923
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001924 // Do not run in a new session so that it can not linger after the
1925 // platform closes.
1926 debugserver_launch_info.SetLaunchInSeparateProcessGroup(false);
Todd Fiala015d8182014-07-22 23:41:36 +00001927 debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false);
1928
Vince Harron1b5a74e2015-01-21 22:42:49 +00001929 std::string platform_scheme;
1930 std::string platform_ip;
1931 int platform_port;
1932 std::string platform_path;
1933 bool ok = UriParser::Parse(GetConnection()->GetURI().c_str(), platform_scheme, platform_ip, platform_port, platform_path);
1934 assert(ok);
1935 Error error = StartDebugserverProcess (
1936 platform_ip.c_str(),
Todd Fiala015d8182014-07-22 23:41:36 +00001937 port,
1938 debugserver_launch_info,
1939 port);
1940
1941 lldb::pid_t debugserver_pid = debugserver_launch_info.GetProcessID();
1942
1943
1944 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1945 {
1946 Mutex::Locker locker (m_spawned_pids_mutex);
1947 m_spawned_pids.insert(debugserver_pid);
1948 if (port > 0)
1949 AssociatePortWithProcess(port, debugserver_pid);
1950 }
1951 else
1952 {
1953 if (port > 0)
1954 FreePort (port);
1955 }
1956
Greg Clayton29b8fc42013-11-21 01:44:58 +00001957 if (error.Success())
1958 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001959 if (log)
Todd Fiala015d8182014-07-22 23:41:36 +00001960 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launched successfully as pid %" PRIu64, __FUNCTION__, debugserver_pid);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001961
Todd Fiala015d8182014-07-22 23:41:36 +00001962 char response[256];
1963 const int response_len = ::snprintf (response, sizeof(response), "pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset);
1964 assert (response_len < (int)sizeof(response));
1965 PacketResult packet_result = SendPacketNoLock (response, response_len);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001966
Todd Fiala015d8182014-07-22 23:41:36 +00001967 if (packet_result != PacketResult::Success)
Greg Clayton29b8fc42013-11-21 01:44:58 +00001968 {
Todd Fiala015d8182014-07-22 23:41:36 +00001969 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1970 ::kill (debugserver_pid, SIGINT);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001971 }
Todd Fiala015d8182014-07-22 23:41:36 +00001972 return packet_result;
1973 }
1974 else
1975 {
1976 if (log)
1977 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launch failed: %s", __FUNCTION__, error.AsCString ());
Greg Clayton8b82f082011-04-12 05:54:46 +00001978 }
1979 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00001980 return SendErrorResponse (9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001981#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00001982}
1983
Todd Fiala403edc52014-01-23 22:05:44 +00001984bool
1985GDBRemoteCommunicationServer::KillSpawnedProcess (lldb::pid_t pid)
1986{
1987 // make sure we know about this process
1988 {
1989 Mutex::Locker locker (m_spawned_pids_mutex);
1990 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1991 return false;
1992 }
1993
1994 // first try a SIGTERM (standard kill)
1995 Host::Kill (pid, SIGTERM);
1996
1997 // check if that worked
1998 for (size_t i=0; i<10; ++i)
1999 {
2000 {
2001 Mutex::Locker locker (m_spawned_pids_mutex);
2002 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2003 {
2004 // it is now killed
2005 return true;
2006 }
2007 }
2008 usleep (10000);
2009 }
2010
2011 // check one more time after the final usleep
2012 {
2013 Mutex::Locker locker (m_spawned_pids_mutex);
2014 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2015 return true;
2016 }
2017
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002018 // the launched process still lives. Now try killing it again,
Todd Fiala403edc52014-01-23 22:05:44 +00002019 // this time with an unblockable signal.
2020 Host::Kill (pid, SIGKILL);
2021
2022 for (size_t i=0; i<10; ++i)
2023 {
2024 {
2025 Mutex::Locker locker (m_spawned_pids_mutex);
2026 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2027 {
2028 // it is now killed
2029 return true;
2030 }
2031 }
2032 usleep (10000);
2033 }
2034
2035 // check one more time after the final usleep
2036 // Scope for locker
2037 {
2038 Mutex::Locker locker (m_spawned_pids_mutex);
2039 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
2040 return true;
2041 }
2042
2043 // no luck - the process still lives
2044 return false;
2045}
2046
Greg Clayton3dedae12013-12-06 21:45:27 +00002047GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002048GDBRemoteCommunicationServer::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet)
2049{
Todd Fiala403edc52014-01-23 22:05:44 +00002050 packet.SetFilePos(::strlen ("qKillSpawnedProcess:"));
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00002051
Todd Fiala403edc52014-01-23 22:05:44 +00002052 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
2053
2054 // verify that we know anything about this pid.
2055 // Scope for locker
Daniel Maleae0f8f572013-08-26 23:57:52 +00002056 {
Todd Fiala403edc52014-01-23 22:05:44 +00002057 Mutex::Locker locker (m_spawned_pids_mutex);
2058 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002059 {
Todd Fiala403edc52014-01-23 22:05:44 +00002060 // not a pid we know about
2061 return SendErrorResponse (10);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002062 }
2063 }
Todd Fiala403edc52014-01-23 22:05:44 +00002064
2065 // go ahead and attempt to kill the spawned process
2066 if (KillSpawnedProcess (pid))
2067 return SendOKResponse ();
2068 else
2069 return SendErrorResponse (11);
2070}
2071
2072GDBRemoteCommunication::PacketResult
2073GDBRemoteCommunicationServer::Handle_k (StringExtractorGDBRemote &packet)
2074{
2075 // ignore for now if we're lldb_platform
2076 if (m_is_platform)
2077 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2078
2079 // shutdown all spawned processes
2080 std::set<lldb::pid_t> spawned_pids_copy;
2081
2082 // copy pids
2083 {
2084 Mutex::Locker locker (m_spawned_pids_mutex);
2085 spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ());
2086 }
2087
2088 // nuke the spawned processes
2089 for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it)
2090 {
2091 lldb::pid_t spawned_pid = *it;
2092 if (!KillSpawnedProcess (spawned_pid))
2093 {
2094 fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid);
2095 }
2096 }
2097
Todd Fialaaf245d12014-06-30 21:05:18 +00002098 FlushInferiorOutput ();
2099
2100 // No OK response for kill packet.
2101 // return SendOKResponse ();
2102 return PacketResult::Success;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002103}
2104
Greg Clayton3dedae12013-12-06 21:45:27 +00002105GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002106GDBRemoteCommunicationServer::Handle_qLaunchSuccess (StringExtractorGDBRemote &packet)
2107{
2108 if (m_process_launch_error.Success())
2109 return SendOKResponse();
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00002110 StreamString response;
Greg Clayton8b82f082011-04-12 05:54:46 +00002111 response.PutChar('E');
2112 response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
Greg Clayton37a0a242012-04-11 00:24:49 +00002113 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00002114}
2115
Greg Clayton3dedae12013-12-06 21:45:27 +00002116GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002117GDBRemoteCommunicationServer::Handle_QEnvironment (StringExtractorGDBRemote &packet)
2118{
2119 packet.SetFilePos(::strlen ("QEnvironment:"));
2120 const uint32_t bytes_left = packet.GetBytesLeft();
2121 if (bytes_left > 0)
2122 {
2123 m_process_launch_info.GetEnvironmentEntries ().AppendArgument (packet.Peek());
2124 return SendOKResponse ();
2125 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002126 return SendErrorResponse (12);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002127}
2128
Greg Clayton3dedae12013-12-06 21:45:27 +00002129GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002130GDBRemoteCommunicationServer::Handle_QLaunchArch (StringExtractorGDBRemote &packet)
2131{
2132 packet.SetFilePos(::strlen ("QLaunchArch:"));
2133 const uint32_t bytes_left = packet.GetBytesLeft();
2134 if (bytes_left > 0)
2135 {
2136 const char* arch_triple = packet.Peek();
2137 ArchSpec arch_spec(arch_triple,NULL);
2138 m_process_launch_info.SetArchitecture(arch_spec);
2139 return SendOKResponse();
2140 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002141 return SendErrorResponse(13);
Greg Clayton8b82f082011-04-12 05:54:46 +00002142}
2143
Greg Clayton3dedae12013-12-06 21:45:27 +00002144GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002145GDBRemoteCommunicationServer::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
2146{
2147 packet.SetFilePos(::strlen ("QSetDisableASLR:"));
2148 if (packet.GetU32(0))
2149 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
2150 else
2151 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
2152 return SendOKResponse ();
2153}
2154
Greg Clayton3dedae12013-12-06 21:45:27 +00002155GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002156GDBRemoteCommunicationServer::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
2157{
2158 packet.SetFilePos(::strlen ("QSetWorkingDir:"));
2159 std::string path;
2160 packet.GetHexByteString(path);
Greg Claytonfbb76342013-11-20 21:07:01 +00002161 if (m_is_platform)
2162 {
Colin Riley909bb7a2013-11-26 15:10:46 +00002163#ifdef _WIN32
2164 // Not implemented on Windows
2165 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_QSetWorkingDir unimplemented");
2166#else
Greg Claytonfbb76342013-11-20 21:07:01 +00002167 // If this packet is sent to a platform, then change the current working directory
2168 if (::chdir(path.c_str()) != 0)
2169 return SendErrorResponse(errno);
Colin Riley909bb7a2013-11-26 15:10:46 +00002170#endif
Greg Claytonfbb76342013-11-20 21:07:01 +00002171 }
2172 else
2173 {
2174 m_process_launch_info.SwapWorkingDirectory (path);
2175 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002176 return SendOKResponse ();
2177}
2178
Greg Clayton3dedae12013-12-06 21:45:27 +00002179GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002180GDBRemoteCommunicationServer::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
2181{
2182 StreamString response;
2183
2184 if (m_is_platform)
2185 {
2186 // If this packet is sent to a platform, then change the current working directory
2187 char cwd[PATH_MAX];
2188 if (getcwd(cwd, sizeof(cwd)) == NULL)
2189 {
2190 return SendErrorResponse(errno);
2191 }
2192 else
2193 {
2194 response.PutBytesAsRawHex8(cwd, strlen(cwd));
Greg Clayton3dedae12013-12-06 21:45:27 +00002195 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002196 }
2197 }
2198 else
2199 {
2200 const char *working_dir = m_process_launch_info.GetWorkingDirectory();
2201 if (working_dir && working_dir[0])
2202 {
2203 response.PutBytesAsRawHex8(working_dir, strlen(working_dir));
Greg Clayton3dedae12013-12-06 21:45:27 +00002204 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002205 }
2206 else
2207 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002208 return SendErrorResponse(14);
Greg Claytonfbb76342013-11-20 21:07:01 +00002209 }
2210 }
2211}
2212
Greg Clayton3dedae12013-12-06 21:45:27 +00002213GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002214GDBRemoteCommunicationServer::Handle_QSetSTDIN (StringExtractorGDBRemote &packet)
2215{
2216 packet.SetFilePos(::strlen ("QSetSTDIN:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002217 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002218 std::string path;
2219 packet.GetHexByteString(path);
2220 const bool read = false;
2221 const bool write = true;
2222 if (file_action.Open(STDIN_FILENO, path.c_str(), read, write))
2223 {
2224 m_process_launch_info.AppendFileAction(file_action);
2225 return SendOKResponse ();
2226 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002227 return SendErrorResponse (15);
Greg Clayton8b82f082011-04-12 05:54:46 +00002228}
2229
Greg Clayton3dedae12013-12-06 21:45:27 +00002230GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002231GDBRemoteCommunicationServer::Handle_QSetSTDOUT (StringExtractorGDBRemote &packet)
2232{
2233 packet.SetFilePos(::strlen ("QSetSTDOUT:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002234 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002235 std::string path;
2236 packet.GetHexByteString(path);
2237 const bool read = true;
2238 const bool write = false;
2239 if (file_action.Open(STDOUT_FILENO, path.c_str(), read, write))
2240 {
2241 m_process_launch_info.AppendFileAction(file_action);
2242 return SendOKResponse ();
2243 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002244 return SendErrorResponse (16);
Greg Clayton8b82f082011-04-12 05:54:46 +00002245}
2246
Greg Clayton3dedae12013-12-06 21:45:27 +00002247GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002248GDBRemoteCommunicationServer::Handle_QSetSTDERR (StringExtractorGDBRemote &packet)
2249{
2250 packet.SetFilePos(::strlen ("QSetSTDERR:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002251 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002252 std::string path;
2253 packet.GetHexByteString(path);
2254 const bool read = true;
Greg Clayton9845a8d2012-03-06 04:01:04 +00002255 const bool write = false;
Greg Clayton8b82f082011-04-12 05:54:46 +00002256 if (file_action.Open(STDERR_FILENO, path.c_str(), read, write))
2257 {
2258 m_process_launch_info.AppendFileAction(file_action);
2259 return SendOKResponse ();
2260 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002261 return SendErrorResponse (17);
Greg Clayton8b82f082011-04-12 05:54:46 +00002262}
2263
Greg Clayton3dedae12013-12-06 21:45:27 +00002264GDBRemoteCommunication::PacketResult
Todd Fialaaf245d12014-06-30 21:05:18 +00002265GDBRemoteCommunicationServer::Handle_C (StringExtractorGDBRemote &packet)
2266{
2267 if (!IsGdbServer ())
2268 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2269
2270 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2271 if (log)
2272 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2273
2274 // Ensure we have a native process.
2275 if (!m_debugged_process_sp)
2276 {
2277 if (log)
2278 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2279 return SendErrorResponse (0x36);
2280 }
2281
2282 // Pull out the signal number.
2283 packet.SetFilePos (::strlen ("C"));
2284 if (packet.GetBytesLeft () < 1)
2285 {
2286 // Shouldn't be using a C without a signal.
2287 return SendIllFormedResponse (packet, "C packet specified without signal.");
2288 }
2289 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2290 if (signo == std::numeric_limits<uint32_t>::max ())
2291 return SendIllFormedResponse (packet, "failed to parse signal number");
2292
2293 // Handle optional continue address.
2294 if (packet.GetBytesLeft () > 0)
2295 {
2296 // FIXME add continue at address support for $C{signo}[;{continue-address}].
2297 if (*packet.Peek () == ';')
2298 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2299 else
2300 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
2301 }
2302
2303 lldb_private::ResumeActionList resume_actions (StateType::eStateRunning, 0);
2304 Error error;
2305
2306 // We have two branches: what to do if a continue thread is specified (in which case we target
2307 // sending the signal to that thread), or when we don't have a continue thread set (in which
2308 // case we send a signal to the process).
2309
2310 // TODO discuss with Greg Clayton, make sure this makes sense.
2311
2312 lldb::tid_t signal_tid = GetContinueThreadID ();
2313 if (signal_tid != LLDB_INVALID_THREAD_ID)
2314 {
2315 // The resume action for the continue thread (or all threads if a continue thread is not set).
2316 lldb_private::ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
2317
2318 // Add the action for the continue thread (or all threads when the continue thread isn't present).
2319 resume_actions.Append (action);
2320 }
2321 else
2322 {
2323 // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
2324 error = m_debugged_process_sp->Signal (signo);
2325 if (error.Fail ())
2326 {
2327 if (log)
2328 log->Printf ("GDBRemoteCommunicationServer::%s failed to send signal for process %" PRIu64 ": %s",
2329 __FUNCTION__,
2330 m_debugged_process_sp->GetID (),
2331 error.AsCString ());
2332
2333 return SendErrorResponse (0x52);
2334 }
2335 }
2336
2337 // Resume the threads.
2338 error = m_debugged_process_sp->Resume (resume_actions);
2339 if (error.Fail ())
2340 {
2341 if (log)
2342 log->Printf ("GDBRemoteCommunicationServer::%s failed to resume threads for process %" PRIu64 ": %s",
2343 __FUNCTION__,
2344 m_debugged_process_sp->GetID (),
2345 error.AsCString ());
2346
2347 return SendErrorResponse (0x38);
2348 }
2349
2350 // Don't send an "OK" packet; response is the stopped/exited message.
2351 return PacketResult::Success;
2352}
2353
2354GDBRemoteCommunication::PacketResult
2355GDBRemoteCommunicationServer::Handle_c (StringExtractorGDBRemote &packet, bool skip_file_pos_adjustment)
2356{
2357 if (!IsGdbServer ())
2358 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2359
2360 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2361 if (log)
2362 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2363
2364 // We reuse this method in vCont - don't double adjust the file position.
2365 if (!skip_file_pos_adjustment)
2366 packet.SetFilePos (::strlen ("c"));
2367
2368 // For now just support all continue.
2369 const bool has_continue_address = (packet.GetBytesLeft () > 0);
2370 if (has_continue_address)
2371 {
2372 if (log)
2373 log->Printf ("GDBRemoteCommunicationServer::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
2374 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2375 }
2376
2377 // Ensure we have a native process.
2378 if (!m_debugged_process_sp)
2379 {
2380 if (log)
2381 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2382 return SendErrorResponse (0x36);
2383 }
2384
2385 // Build the ResumeActionList
2386 lldb_private::ResumeActionList actions (StateType::eStateRunning, 0);
2387
2388 Error error = m_debugged_process_sp->Resume (actions);
2389 if (error.Fail ())
2390 {
2391 if (log)
2392 {
2393 log->Printf ("GDBRemoteCommunicationServer::%s c failed for process %" PRIu64 ": %s",
2394 __FUNCTION__,
2395 m_debugged_process_sp->GetID (),
2396 error.AsCString ());
2397 }
2398 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2399 }
2400
2401 if (log)
2402 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2403
2404 // No response required from continue.
2405 return PacketResult::Success;
2406}
2407
2408GDBRemoteCommunication::PacketResult
2409GDBRemoteCommunicationServer::Handle_vCont_actions (StringExtractorGDBRemote &packet)
2410{
2411 if (!IsGdbServer ())
2412 {
2413 // only llgs supports $vCont.
2414 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2415 }
2416
Todd Fialaaf245d12014-06-30 21:05:18 +00002417 StreamString response;
2418 response.Printf("vCont;c;C;s;S");
2419
2420 return SendPacketNoLock(response.GetData(), response.GetSize());
2421}
2422
2423GDBRemoteCommunication::PacketResult
2424GDBRemoteCommunicationServer::Handle_vCont (StringExtractorGDBRemote &packet)
2425{
2426 if (!IsGdbServer ())
2427 {
2428 // only llgs supports $vCont
2429 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2430 }
2431
2432 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2433 if (log)
2434 log->Printf ("GDBRemoteCommunicationServer::%s handling vCont packet", __FUNCTION__);
2435
2436 packet.SetFilePos (::strlen ("vCont"));
2437
2438 // Check if this is all continue (no options or ";c").
2439 if (!packet.GetBytesLeft () || (::strcmp (packet.Peek (), ";c") == 0))
2440 {
2441 // Move the packet past the ";c".
2442 if (packet.GetBytesLeft ())
2443 packet.SetFilePos (packet.GetFilePos () + ::strlen (";c"));
2444
2445 const bool skip_file_pos_adjustment = true;
2446 return Handle_c (packet, skip_file_pos_adjustment);
2447 }
2448 else if (::strcmp (packet.Peek (), ";s") == 0)
2449 {
2450 // Move past the ';', then do a simple 's'.
2451 packet.SetFilePos (packet.GetFilePos () + 1);
2452 return Handle_s (packet);
2453 }
2454
2455 // Ensure we have a native process.
2456 if (!m_debugged_process_sp)
2457 {
2458 if (log)
2459 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2460 return SendErrorResponse (0x36);
2461 }
2462
2463 ResumeActionList thread_actions;
2464
2465 while (packet.GetBytesLeft () && *packet.Peek () == ';')
2466 {
2467 // Skip the semi-colon.
2468 packet.GetChar ();
2469
2470 // Build up the thread action.
2471 ResumeAction thread_action;
2472 thread_action.tid = LLDB_INVALID_THREAD_ID;
2473 thread_action.state = eStateInvalid;
2474 thread_action.signal = 0;
2475
2476 const char action = packet.GetChar ();
2477 switch (action)
2478 {
2479 case 'C':
2480 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2481 if (thread_action.signal == 0)
2482 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
2483 // Fall through to next case...
2484
2485 case 'c':
2486 // Continue
2487 thread_action.state = eStateRunning;
2488 break;
2489
2490 case 'S':
2491 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2492 if (thread_action.signal == 0)
2493 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
2494 // Fall through to next case...
2495
2496 case 's':
2497 // Step
2498 thread_action.state = eStateStepping;
2499 break;
2500
2501 default:
2502 return SendIllFormedResponse (packet, "Unsupported vCont action");
2503 break;
2504 }
2505
2506 // Parse out optional :{thread-id} value.
2507 if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
2508 {
2509 // Consume the separator.
2510 packet.GetChar ();
2511
2512 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2513 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
2514 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
2515 }
2516
2517 thread_actions.Append (thread_action);
2518 }
2519
2520 // If a default action for all other threads wasn't mentioned
2521 // then we should stop the threads.
2522 thread_actions.SetDefaultThreadActionIfNeeded (eStateStopped, 0);
2523
2524 Error error = m_debugged_process_sp->Resume (thread_actions);
2525 if (error.Fail ())
2526 {
2527 if (log)
2528 {
2529 log->Printf ("GDBRemoteCommunicationServer::%s vCont failed for process %" PRIu64 ": %s",
2530 __FUNCTION__,
2531 m_debugged_process_sp->GetID (),
2532 error.AsCString ());
2533 }
2534 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2535 }
2536
2537 if (log)
2538 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2539
2540 // No response required from vCont.
2541 return PacketResult::Success;
2542}
2543
2544GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00002545GDBRemoteCommunicationServer::Handle_QStartNoAckMode (StringExtractorGDBRemote &packet)
2546{
2547 // Send response first before changing m_send_acks to we ack this packet
Greg Clayton3dedae12013-12-06 21:45:27 +00002548 PacketResult packet_result = SendOKResponse ();
Greg Clayton1cb64962011-03-24 04:28:38 +00002549 m_send_acks = false;
Greg Clayton3dedae12013-12-06 21:45:27 +00002550 return packet_result;
Greg Clayton1cb64962011-03-24 04:28:38 +00002551}
Daniel Maleae0f8f572013-08-26 23:57:52 +00002552
Greg Clayton3dedae12013-12-06 21:45:27 +00002553GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002554GDBRemoteCommunicationServer::Handle_qPlatform_mkdir (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002555{
Greg Claytonfbb76342013-11-20 21:07:01 +00002556 packet.SetFilePos(::strlen("qPlatform_mkdir:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002557 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002558 if (packet.GetChar() == ',')
2559 {
2560 std::string path;
2561 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002562 Error error = FileSystem::MakeDirectory(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002563 if (error.Success())
2564 return SendPacketNoLock ("OK", 2);
2565 else
2566 return SendErrorResponse(error.GetError());
2567 }
2568 return SendErrorResponse(20);
Greg Claytonfbb76342013-11-20 21:07:01 +00002569}
2570
Greg Clayton3dedae12013-12-06 21:45:27 +00002571GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002572GDBRemoteCommunicationServer::Handle_qPlatform_chmod (StringExtractorGDBRemote &packet)
2573{
2574 packet.SetFilePos(::strlen("qPlatform_chmod:"));
2575
2576 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002577 if (packet.GetChar() == ',')
2578 {
2579 std::string path;
2580 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002581 Error error = FileSystem::SetFilePermissions(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002582 if (error.Success())
2583 return SendPacketNoLock ("OK", 2);
2584 else
2585 return SendErrorResponse(error.GetError());
2586 }
2587 return SendErrorResponse(19);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002588}
2589
Greg Clayton3dedae12013-12-06 21:45:27 +00002590GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002591GDBRemoteCommunicationServer::Handle_vFile_Open (StringExtractorGDBRemote &packet)
2592{
2593 packet.SetFilePos(::strlen("vFile:open:"));
2594 std::string path;
2595 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002596 if (!path.empty())
2597 {
2598 if (packet.GetChar() == ',')
2599 {
2600 uint32_t flags = packet.GetHexMaxU32(false, 0);
2601 if (packet.GetChar() == ',')
2602 {
2603 mode_t mode = packet.GetHexMaxU32(false, 0600);
2604 Error error;
2605 int fd = ::open (path.c_str(), flags, mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002606 const int save_errno = fd == -1 ? errno : 0;
2607 StreamString response;
2608 response.PutChar('F');
2609 response.Printf("%i", fd);
2610 if (save_errno)
2611 response.Printf(",%i", save_errno);
2612 return SendPacketNoLock(response.GetData(), response.GetSize());
2613 }
2614 }
2615 }
2616 return SendErrorResponse(18);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002617}
2618
Greg Clayton3dedae12013-12-06 21:45:27 +00002619GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002620GDBRemoteCommunicationServer::Handle_vFile_Close (StringExtractorGDBRemote &packet)
2621{
2622 packet.SetFilePos(::strlen("vFile:close:"));
2623 int fd = packet.GetS32(-1);
2624 Error error;
2625 int err = -1;
2626 int save_errno = 0;
2627 if (fd >= 0)
2628 {
2629 err = close(fd);
2630 save_errno = err == -1 ? errno : 0;
2631 }
2632 else
2633 {
2634 save_errno = EINVAL;
2635 }
2636 StreamString response;
2637 response.PutChar('F');
2638 response.Printf("%i", err);
2639 if (save_errno)
2640 response.Printf(",%i", save_errno);
Greg Clayton2b98c562013-11-22 18:53:12 +00002641 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002642}
2643
Greg Clayton3dedae12013-12-06 21:45:27 +00002644GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002645GDBRemoteCommunicationServer::Handle_vFile_pRead (StringExtractorGDBRemote &packet)
2646{
Virgile Belloae12a362013-08-27 16:21:49 +00002647#ifdef _WIN32
2648 // Not implemented on Windows
Greg Clayton2b98c562013-11-22 18:53:12 +00002649 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pRead() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002650#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002651 StreamGDBRemote response;
2652 packet.SetFilePos(::strlen("vFile:pread:"));
2653 int fd = packet.GetS32(-1);
Greg Clayton2b98c562013-11-22 18:53:12 +00002654 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002655 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002656 uint64_t count = packet.GetU64(UINT64_MAX);
2657 if (packet.GetChar() == ',')
2658 {
2659 uint64_t offset = packet.GetU64(UINT32_MAX);
2660 if (count == UINT64_MAX)
2661 {
2662 response.Printf("F-1:%i", EINVAL);
2663 return SendPacketNoLock(response.GetData(), response.GetSize());
2664 }
2665
2666 std::string buffer(count, 0);
2667 const ssize_t bytes_read = ::pread (fd, &buffer[0], buffer.size(), offset);
2668 const int save_errno = bytes_read == -1 ? errno : 0;
2669 response.PutChar('F');
2670 response.Printf("%zi", bytes_read);
2671 if (save_errno)
2672 response.Printf(",%i", save_errno);
2673 else
2674 {
2675 response.PutChar(';');
2676 response.PutEscapedBytes(&buffer[0], bytes_read);
2677 }
2678 return SendPacketNoLock(response.GetData(), response.GetSize());
2679 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002680 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002681 return SendErrorResponse(21);
2682
Virgile Belloae12a362013-08-27 16:21:49 +00002683#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002684}
2685
Greg Clayton3dedae12013-12-06 21:45:27 +00002686GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002687GDBRemoteCommunicationServer::Handle_vFile_pWrite (StringExtractorGDBRemote &packet)
2688{
Virgile Belloae12a362013-08-27 16:21:49 +00002689#ifdef _WIN32
Greg Clayton2b98c562013-11-22 18:53:12 +00002690 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pWrite() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002691#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002692 packet.SetFilePos(::strlen("vFile:pwrite:"));
2693
2694 StreamGDBRemote response;
2695 response.PutChar('F');
2696
2697 int fd = packet.GetU32(UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002698 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002699 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002700 off_t offset = packet.GetU64(UINT32_MAX);
2701 if (packet.GetChar() == ',')
2702 {
2703 std::string buffer;
2704 if (packet.GetEscapedBinaryData(buffer))
2705 {
2706 const ssize_t bytes_written = ::pwrite (fd, buffer.data(), buffer.size(), offset);
2707 const int save_errno = bytes_written == -1 ? errno : 0;
2708 response.Printf("%zi", bytes_written);
2709 if (save_errno)
2710 response.Printf(",%i", save_errno);
2711 }
2712 else
2713 {
2714 response.Printf ("-1,%i", EINVAL);
2715 }
2716 return SendPacketNoLock(response.GetData(), response.GetSize());
2717 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002718 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002719 return SendErrorResponse(27);
Virgile Belloae12a362013-08-27 16:21:49 +00002720#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002721}
2722
Greg Clayton3dedae12013-12-06 21:45:27 +00002723GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002724GDBRemoteCommunicationServer::Handle_vFile_Size (StringExtractorGDBRemote &packet)
2725{
2726 packet.SetFilePos(::strlen("vFile:size:"));
2727 std::string path;
2728 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002729 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002730 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002731 lldb::user_id_t retcode = FileSystem::GetFileSize(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002732 StreamString response;
2733 response.PutChar('F');
2734 response.PutHex64(retcode);
2735 if (retcode == UINT64_MAX)
2736 {
2737 response.PutChar(',');
2738 response.PutHex64(retcode); // TODO: replace with Host::GetSyswideErrorCode()
2739 }
2740 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002741 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002742 return SendErrorResponse(22);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002743}
2744
Greg Clayton3dedae12013-12-06 21:45:27 +00002745GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002746GDBRemoteCommunicationServer::Handle_vFile_Mode (StringExtractorGDBRemote &packet)
2747{
2748 packet.SetFilePos(::strlen("vFile:mode:"));
2749 std::string path;
2750 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002751 if (!path.empty())
2752 {
2753 Error error;
2754 const uint32_t mode = File::GetPermissions(path.c_str(), error);
2755 StreamString response;
2756 response.Printf("F%u", mode);
2757 if (mode == 0 || error.Fail())
2758 response.Printf(",%i", (int)error.GetError());
2759 return SendPacketNoLock(response.GetData(), response.GetSize());
2760 }
2761 return SendErrorResponse(23);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002762}
2763
Greg Clayton3dedae12013-12-06 21:45:27 +00002764GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002765GDBRemoteCommunicationServer::Handle_vFile_Exists (StringExtractorGDBRemote &packet)
2766{
2767 packet.SetFilePos(::strlen("vFile:exists:"));
2768 std::string path;
2769 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002770 if (!path.empty())
2771 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002772 bool retcode = FileSystem::GetFileExists(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002773 StreamString response;
2774 response.PutChar('F');
2775 response.PutChar(',');
2776 if (retcode)
2777 response.PutChar('1');
2778 else
2779 response.PutChar('0');
2780 return SendPacketNoLock(response.GetData(), response.GetSize());
2781 }
2782 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002783}
2784
Greg Clayton3dedae12013-12-06 21:45:27 +00002785GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002786GDBRemoteCommunicationServer::Handle_vFile_symlink (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002787{
Greg Claytonfbb76342013-11-20 21:07:01 +00002788 packet.SetFilePos(::strlen("vFile:symlink:"));
2789 std::string dst, src;
2790 packet.GetHexByteStringTerminatedBy(dst, ',');
2791 packet.GetChar(); // Skip ',' char
2792 packet.GetHexByteString(src);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002793 Error error = FileSystem::Symlink(src.c_str(), dst.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002794 StreamString response;
2795 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002796 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002797}
2798
Greg Clayton3dedae12013-12-06 21:45:27 +00002799GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002800GDBRemoteCommunicationServer::Handle_vFile_unlink (StringExtractorGDBRemote &packet)
2801{
2802 packet.SetFilePos(::strlen("vFile:unlink:"));
2803 std::string path;
2804 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002805 Error error = FileSystem::Unlink(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002806 StreamString response;
2807 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002808 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002809}
2810
Greg Clayton3dedae12013-12-06 21:45:27 +00002811GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002812GDBRemoteCommunicationServer::Handle_qPlatform_shell (StringExtractorGDBRemote &packet)
2813{
2814 packet.SetFilePos(::strlen("qPlatform_shell:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002815 std::string path;
2816 std::string working_dir;
2817 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002818 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002819 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002820 if (packet.GetChar() == ',')
2821 {
2822 // FIXME: add timeout to qPlatform_shell packet
2823 // uint32_t timeout = packet.GetHexMaxU32(false, 32);
2824 uint32_t timeout = 10;
2825 if (packet.GetChar() == ',')
2826 packet.GetHexByteString(working_dir);
2827 int status, signo;
2828 std::string output;
2829 Error err = Host::RunShellCommand(path.c_str(),
2830 working_dir.empty() ? NULL : working_dir.c_str(),
2831 &status, &signo, &output, timeout);
2832 StreamGDBRemote response;
2833 if (err.Fail())
2834 {
2835 response.PutCString("F,");
2836 response.PutHex32(UINT32_MAX);
2837 }
2838 else
2839 {
2840 response.PutCString("F,");
2841 response.PutHex32(status);
2842 response.PutChar(',');
2843 response.PutHex32(signo);
2844 response.PutChar(',');
2845 response.PutEscapedBytes(output.c_str(), output.size());
2846 }
2847 return SendPacketNoLock(response.GetData(), response.GetSize());
2848 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002849 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002850 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002851}
2852
Todd Fialaaf245d12014-06-30 21:05:18 +00002853void
2854GDBRemoteCommunicationServer::SetCurrentThreadID (lldb::tid_t tid)
2855{
2856 assert (IsGdbServer () && "SetCurrentThreadID() called when not GdbServer code");
2857
2858 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2859 if (log)
2860 log->Printf ("GDBRemoteCommunicationServer::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
2861
2862 m_current_tid = tid;
2863 if (m_debugged_process_sp)
2864 m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
2865}
2866
2867void
2868GDBRemoteCommunicationServer::SetContinueThreadID (lldb::tid_t tid)
2869{
2870 assert (IsGdbServer () && "SetContinueThreadID() called when not GdbServer code");
2871
2872 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2873 if (log)
2874 log->Printf ("GDBRemoteCommunicationServer::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
2875
2876 m_continue_tid = tid;
2877}
2878
2879GDBRemoteCommunication::PacketResult
2880GDBRemoteCommunicationServer::Handle_stop_reason (StringExtractorGDBRemote &packet)
2881{
2882 // Handle the $? gdbremote command.
2883 if (!IsGdbServer ())
2884 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_stop_reason() unimplemented");
2885
2886 // If no process, indicate error
2887 if (!m_debugged_process_sp)
2888 return SendErrorResponse (02);
2889
2890 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
2891}
2892
2893GDBRemoteCommunication::PacketResult
2894GDBRemoteCommunicationServer::SendStopReasonForState (lldb::StateType process_state, bool flush_on_exit)
2895{
2896 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2897
2898 switch (process_state)
2899 {
2900 case eStateAttaching:
2901 case eStateLaunching:
2902 case eStateRunning:
2903 case eStateStepping:
2904 case eStateDetached:
2905 // NOTE: gdb protocol doc looks like it should return $OK
2906 // when everything is running (i.e. no stopped result).
2907 return PacketResult::Success; // Ignore
2908
2909 case eStateSuspended:
2910 case eStateStopped:
2911 case eStateCrashed:
2912 {
2913 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
2914 // Make sure we set the current thread so g and p packets return
2915 // the data the gdb will expect.
2916 SetCurrentThreadID (tid);
2917 return SendStopReplyPacketForThread (tid);
2918 }
2919
2920 case eStateInvalid:
2921 case eStateUnloaded:
2922 case eStateExited:
2923 if (flush_on_exit)
2924 FlushInferiorOutput ();
2925 return SendWResponse(m_debugged_process_sp.get());
2926
2927 default:
2928 if (log)
2929 {
2930 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", current state reporting not handled: %s",
2931 __FUNCTION__,
2932 m_debugged_process_sp->GetID (),
2933 StateAsCString (process_state));
2934 }
2935 break;
2936 }
2937
2938 return SendErrorResponse (0);
2939}
2940
Greg Clayton3dedae12013-12-06 21:45:27 +00002941GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002942GDBRemoteCommunicationServer::Handle_vFile_Stat (StringExtractorGDBRemote &packet)
2943{
Greg Clayton2b98c562013-11-22 18:53:12 +00002944 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_Stat() unimplemented");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002945}
2946
Greg Clayton3dedae12013-12-06 21:45:27 +00002947GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002948GDBRemoteCommunicationServer::Handle_vFile_MD5 (StringExtractorGDBRemote &packet)
2949{
Greg Clayton2b98c562013-11-22 18:53:12 +00002950 packet.SetFilePos(::strlen("vFile:MD5:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002951 std::string path;
2952 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002953 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002954 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002955 uint64_t a,b;
2956 StreamGDBRemote response;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002957 if (FileSystem::CalculateMD5(FileSpec(path.c_str(), false), a, b) == false)
Greg Clayton2b98c562013-11-22 18:53:12 +00002958 {
2959 response.PutCString("F,");
2960 response.PutCString("x");
2961 }
2962 else
2963 {
2964 response.PutCString("F,");
2965 response.PutHex64(a);
2966 response.PutHex64(b);
2967 }
2968 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002969 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002970 return SendErrorResponse(25);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002971}
Greg Clayton2b98c562013-11-22 18:53:12 +00002972
Todd Fialaaf245d12014-06-30 21:05:18 +00002973GDBRemoteCommunication::PacketResult
2974GDBRemoteCommunicationServer::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
2975{
2976 // Ensure we're llgs.
2977 if (!IsGdbServer())
2978 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qRegisterInfo() unimplemented");
2979
2980 // Fail if we don't have a current process.
2981 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2982 return SendErrorResponse (68);
2983
2984 // Ensure we have a thread.
2985 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
2986 if (!thread_sp)
2987 return SendErrorResponse (69);
2988
2989 // Get the register context for the first thread.
2990 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2991 if (!reg_context_sp)
2992 return SendErrorResponse (69);
2993
2994 // Parse out the register number from the request.
2995 packet.SetFilePos (strlen("qRegisterInfo"));
2996 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2997 if (reg_index == std::numeric_limits<uint32_t>::max ())
2998 return SendErrorResponse (69);
2999
3000 // Return the end of registers response if we've iterated one past the end of the register set.
Vince Harrond40ef992015-01-23 22:57:00 +00003001 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
Todd Fialaaf245d12014-06-30 21:05:18 +00003002 return SendErrorResponse (69);
3003
3004 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3005 if (!reg_info)
3006 return SendErrorResponse (69);
3007
3008 // Build the reginfos response.
3009 StreamGDBRemote response;
3010
3011 response.PutCString ("name:");
3012 response.PutCString (reg_info->name);
3013 response.PutChar (';');
3014
3015 if (reg_info->alt_name && reg_info->alt_name[0])
3016 {
3017 response.PutCString ("alt-name:");
3018 response.PutCString (reg_info->alt_name);
3019 response.PutChar (';');
3020 }
3021
3022 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
3023
3024 switch (reg_info->encoding)
3025 {
3026 case eEncodingUint: response.PutCString ("encoding:uint;"); break;
3027 case eEncodingSint: response.PutCString ("encoding:sint;"); break;
3028 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
3029 case eEncodingVector: response.PutCString ("encoding:vector;"); break;
3030 default: break;
3031 }
3032
3033 switch (reg_info->format)
3034 {
3035 case eFormatBinary: response.PutCString ("format:binary;"); break;
3036 case eFormatDecimal: response.PutCString ("format:decimal;"); break;
3037 case eFormatHex: response.PutCString ("format:hex;"); break;
3038 case eFormatFloat: response.PutCString ("format:float;"); break;
3039 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break;
3040 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break;
3041 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break;
3042 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break;
3043 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break;
3044 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break;
3045 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
3046 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
3047 default: break;
3048 };
3049
3050 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
3051 if (register_set_name)
3052 {
3053 response.PutCString ("set:");
3054 response.PutCString (register_set_name);
3055 response.PutChar (';');
3056 }
3057
3058 if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM)
3059 response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]);
3060
3061 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
3062 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3063
3064 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
3065 {
3066 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break;
3067 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break;
3068 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break;
3069 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break;
3070 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break;
3071 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break;
3072 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break;
3073 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break;
3074 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break;
3075 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break;
3076 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break;
3077 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break;
3078 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break;
3079 default: break;
3080 }
3081
3082 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
3083 {
3084 response.PutCString ("container-regs:");
3085 int i = 0;
3086 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3087 {
3088 if (i > 0)
3089 response.PutChar (',');
3090 response.Printf ("%" PRIx32, *reg_num);
3091 }
3092 response.PutChar (';');
3093 }
3094
3095 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
3096 {
3097 response.PutCString ("invalidate-regs:");
3098 int i = 0;
3099 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3100 {
3101 if (i > 0)
3102 response.PutChar (',');
3103 response.Printf ("%" PRIx32, *reg_num);
3104 }
3105 response.PutChar (';');
3106 }
3107
3108 return SendPacketNoLock(response.GetData(), response.GetSize());
3109}
3110
3111GDBRemoteCommunication::PacketResult
3112GDBRemoteCommunicationServer::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
3113{
3114 // Ensure we're llgs.
3115 if (!IsGdbServer())
3116 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qfThreadInfo() unimplemented");
3117
Todd Fiala24189d42014-07-14 06:24:44 +00003118 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3119
Todd Fialaaf245d12014-06-30 21:05:18 +00003120 // Fail if we don't have a current process.
3121 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
Todd Fiala24189d42014-07-14 06:24:44 +00003122 {
3123 if (log)
3124 log->Printf ("GDBRemoteCommunicationServer::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
3125 return SendOKResponse ();
3126 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003127
3128 StreamGDBRemote response;
3129 response.PutChar ('m');
3130
Todd Fiala24189d42014-07-14 06:24:44 +00003131 if (log)
3132 log->Printf ("GDBRemoteCommunicationServer::%s() starting thread iteration", __FUNCTION__);
3133
Todd Fialaaf245d12014-06-30 21:05:18 +00003134 NativeThreadProtocolSP thread_sp;
3135 uint32_t thread_index;
3136 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
3137 thread_sp;
3138 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
3139 {
Todd Fiala24189d42014-07-14 06:24:44 +00003140 if (log)
3141 log->Printf ("GDBRemoteCommunicationServer::%s() iterated thread %" PRIu32 "(%s, tid=0x%" PRIx64 ")", __FUNCTION__, thread_index, thread_sp ? "is not null" : "null", thread_sp ? thread_sp->GetID () : LLDB_INVALID_THREAD_ID);
Todd Fialaaf245d12014-06-30 21:05:18 +00003142 if (thread_index > 0)
3143 response.PutChar(',');
3144 response.Printf ("%" PRIx64, thread_sp->GetID ());
3145 }
3146
Todd Fiala24189d42014-07-14 06:24:44 +00003147 if (log)
3148 log->Printf ("GDBRemoteCommunicationServer::%s() finished thread iteration", __FUNCTION__);
3149
Todd Fialaaf245d12014-06-30 21:05:18 +00003150 return SendPacketNoLock(response.GetData(), response.GetSize());
3151}
3152
3153GDBRemoteCommunication::PacketResult
3154GDBRemoteCommunicationServer::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
3155{
3156 // Ensure we're llgs.
3157 if (!IsGdbServer())
3158 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_qsThreadInfo() unimplemented");
3159
3160 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
3161 return SendPacketNoLock ("l", 1);
3162}
3163
3164GDBRemoteCommunication::PacketResult
3165GDBRemoteCommunicationServer::Handle_p (StringExtractorGDBRemote &packet)
3166{
3167 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3168
3169 // Ensure we're llgs.
3170 if (!IsGdbServer())
3171 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_p() unimplemented");
3172
3173 // Parse out the register number from the request.
3174 packet.SetFilePos (strlen("p"));
3175 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3176 if (reg_index == std::numeric_limits<uint32_t>::max ())
3177 {
3178 if (log)
3179 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3180 return SendErrorResponse (0x15);
3181 }
3182
3183 // Get the thread to use.
3184 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3185 if (!thread_sp)
3186 {
3187 if (log)
3188 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available", __FUNCTION__);
3189 return SendErrorResponse (0x15);
3190 }
3191
3192 // Get the thread's register context.
3193 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3194 if (!reg_context_sp)
3195 {
3196 if (log)
3197 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
3198 return SendErrorResponse (0x15);
3199 }
3200
3201 // Return the end of registers response if we've iterated one past the end of the register set.
Vince Harrond40ef992015-01-23 22:57:00 +00003202 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
Todd Fialaaf245d12014-06-30 21:05:18 +00003203 {
3204 if (log)
Vince Harrond40ef992015-01-23 22:57:00 +00003205 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
Todd Fialaaf245d12014-06-30 21:05:18 +00003206 return SendErrorResponse (0x15);
3207 }
3208
3209 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3210 if (!reg_info)
3211 {
3212 if (log)
3213 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3214 return SendErrorResponse (0x15);
3215 }
3216
3217 // Build the reginfos response.
3218 StreamGDBRemote response;
3219
3220 // Retrieve the value
3221 RegisterValue reg_value;
3222 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
3223 if (error.Fail ())
3224 {
3225 if (log)
3226 log->Printf ("GDBRemoteCommunicationServer::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3227 return SendErrorResponse (0x15);
3228 }
3229
3230 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
3231 if (!data)
3232 {
3233 if (log)
3234 log->Printf ("GDBRemoteCommunicationServer::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
3235 return SendErrorResponse (0x15);
3236 }
3237
3238 // FIXME flip as needed to get data in big/little endian format for this host.
3239 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
3240 response.PutHex8 (data[i]);
3241
3242 return SendPacketNoLock (response.GetData (), response.GetSize ());
3243}
3244
3245GDBRemoteCommunication::PacketResult
3246GDBRemoteCommunicationServer::Handle_P (StringExtractorGDBRemote &packet)
3247{
3248 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3249
3250 // Ensure we're llgs.
3251 if (!IsGdbServer())
3252 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_P() unimplemented");
3253
3254 // Ensure there is more content.
3255 if (packet.GetBytesLeft () < 1)
3256 return SendIllFormedResponse (packet, "Empty P packet");
3257
3258 // Parse out the register number from the request.
3259 packet.SetFilePos (strlen("P"));
3260 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3261 if (reg_index == std::numeric_limits<uint32_t>::max ())
3262 {
3263 if (log)
3264 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3265 return SendErrorResponse (0x29);
3266 }
3267
3268 // Note debugserver would send an E30 here.
3269 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
3270 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
3271
3272 // Get process architecture.
3273 ArchSpec process_arch;
3274 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
3275 {
3276 if (log)
3277 log->Printf ("GDBRemoteCommunicationServer::%s failed to retrieve inferior architecture", __FUNCTION__);
3278 return SendErrorResponse (0x49);
3279 }
3280
3281 // Parse out the value.
Chaoren Lin6626b5c2015-02-03 01:51:03 +00003282 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
3283 size_t reg_size = packet.GetHexBytesAvail (reg_bytes, sizeof(reg_bytes));
Todd Fialaaf245d12014-06-30 21:05:18 +00003284
3285 // Get the thread to use.
3286 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3287 if (!thread_sp)
3288 {
3289 if (log)
3290 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available (thread index 0)", __FUNCTION__);
3291 return SendErrorResponse (0x28);
3292 }
3293
3294 // Get the thread's register context.
3295 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3296 if (!reg_context_sp)
3297 {
3298 if (log)
3299 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
3300 return SendErrorResponse (0x15);
3301 }
3302
Chaoren Lin6626b5c2015-02-03 01:51:03 +00003303 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex (reg_index);
Todd Fialaaf245d12014-06-30 21:05:18 +00003304 if (!reg_info)
3305 {
3306 if (log)
3307 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3308 return SendErrorResponse (0x48);
3309 }
3310
3311 // Return the end of registers response if we've iterated one past the end of the register set.
Vince Harrond40ef992015-01-23 22:57:00 +00003312 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
Todd Fialaaf245d12014-06-30 21:05:18 +00003313 {
3314 if (log)
Vince Harrond40ef992015-01-23 22:57:00 +00003315 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
Todd Fialaaf245d12014-06-30 21:05:18 +00003316 return SendErrorResponse (0x47);
3317 }
3318
Chaoren Lin6626b5c2015-02-03 01:51:03 +00003319 if (reg_size != reg_info->byte_size)
3320 {
3321 return SendIllFormedResponse (packet, "P packet register size is incorrect");
3322 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003323
3324 // Build the reginfos response.
3325 StreamGDBRemote response;
3326
Chaoren Lin6626b5c2015-02-03 01:51:03 +00003327 RegisterValue reg_value (reg_bytes, reg_size, process_arch.GetByteOrder ());
3328 Error error = reg_context_sp->WriteRegister (reg_info, reg_value);
Todd Fialaaf245d12014-06-30 21:05:18 +00003329 if (error.Fail ())
3330 {
3331 if (log)
3332 log->Printf ("GDBRemoteCommunicationServer::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3333 return SendErrorResponse (0x32);
3334 }
3335
3336 return SendOKResponse();
3337}
3338
3339GDBRemoteCommunicationServer::PacketResult
3340GDBRemoteCommunicationServer::Handle_H (StringExtractorGDBRemote &packet)
3341{
3342 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3343
3344 // Ensure we're llgs.
3345 if (!IsGdbServer())
3346 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_H() unimplemented");
3347
3348 // Fail if we don't have a current process.
3349 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3350 {
3351 if (log)
3352 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3353 return SendErrorResponse (0x15);
3354 }
3355
3356 // Parse out which variant of $H is requested.
3357 packet.SetFilePos (strlen("H"));
3358 if (packet.GetBytesLeft () < 1)
3359 {
3360 if (log)
3361 log->Printf ("GDBRemoteCommunicationServer::%s failed, H command missing {g,c} variant", __FUNCTION__);
3362 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
3363 }
3364
3365 const char h_variant = packet.GetChar ();
3366 switch (h_variant)
3367 {
3368 case 'g':
3369 break;
3370
3371 case 'c':
3372 break;
3373
3374 default:
3375 if (log)
3376 log->Printf ("GDBRemoteCommunicationServer::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
3377 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3378 }
3379
3380 // Parse out the thread number.
3381 // FIXME return a parse success/fail value. All values are valid here.
3382 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
3383
3384 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
3385 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
3386 {
3387 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
3388 if (!thread_sp)
3389 {
3390 if (log)
3391 log->Printf ("GDBRemoteCommunicationServer::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
3392 return SendErrorResponse (0x15);
3393 }
3394 }
3395
3396 // Now switch the given thread type.
3397 switch (h_variant)
3398 {
3399 case 'g':
3400 SetCurrentThreadID (tid);
3401 break;
3402
3403 case 'c':
3404 SetContinueThreadID (tid);
3405 break;
3406
3407 default:
3408 assert (false && "unsupported $H variant - shouldn't get here");
3409 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3410 }
3411
3412 return SendOKResponse();
3413}
3414
3415GDBRemoteCommunicationServer::PacketResult
3416GDBRemoteCommunicationServer::Handle_interrupt (StringExtractorGDBRemote &packet)
3417{
3418 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3419
3420 // Ensure we're llgs.
3421 if (!IsGdbServer())
3422 {
3423 // Only supported on llgs
3424 return SendUnimplementedResponse ("");
3425 }
3426
3427 // Fail if we don't have a current process.
3428 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3429 {
3430 if (log)
3431 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3432 return SendErrorResponse (0x15);
3433 }
3434
Todd Fiala511e5cd2014-09-11 23:29:14 +00003435 // Interrupt the process.
3436 Error error = m_debugged_process_sp->Interrupt ();
Todd Fialaaf245d12014-06-30 21:05:18 +00003437 if (error.Fail ())
3438 {
3439 if (log)
3440 {
3441 log->Printf ("GDBRemoteCommunicationServer::%s failed for process %" PRIu64 ": %s",
3442 __FUNCTION__,
3443 m_debugged_process_sp->GetID (),
3444 error.AsCString ());
3445 }
3446 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
3447 }
3448
3449 if (log)
3450 log->Printf ("GDBRemoteCommunicationServer::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
3451
3452 // No response required from stop all.
3453 return PacketResult::Success;
3454}
3455
3456GDBRemoteCommunicationServer::PacketResult
3457GDBRemoteCommunicationServer::Handle_m (StringExtractorGDBRemote &packet)
3458{
3459 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3460
3461 // Ensure we're llgs.
3462 if (!IsGdbServer())
3463 {
3464 // Only supported on llgs
3465 return SendUnimplementedResponse ("");
3466 }
3467
3468 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3469 {
3470 if (log)
3471 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3472 return SendErrorResponse (0x15);
3473 }
3474
3475 // Parse out the memory address.
3476 packet.SetFilePos (strlen("m"));
3477 if (packet.GetBytesLeft() < 1)
3478 return SendIllFormedResponse(packet, "Too short m packet");
3479
3480 // Read the address. Punting on validation.
3481 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3482 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3483
3484 // Validate comma.
3485 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3486 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
3487
3488 // Get # bytes to read.
3489 if (packet.GetBytesLeft() < 1)
3490 return SendIllFormedResponse(packet, "Length missing in m packet");
3491
3492 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3493 if (byte_count == 0)
3494 {
3495 if (log)
3496 log->Printf ("GDBRemoteCommunicationServer::%s nothing to read: zero-length packet", __FUNCTION__);
3497 return PacketResult::Success;
3498 }
3499
3500 // Allocate the response buffer.
3501 std::string buf(byte_count, '\0');
3502 if (buf.empty())
3503 return SendErrorResponse (0x78);
3504
3505
3506 // Retrieve the process memory.
3507 lldb::addr_t bytes_read = 0;
3508 lldb_private::Error error = m_debugged_process_sp->ReadMemory (read_addr, &buf[0], byte_count, bytes_read);
3509 if (error.Fail ())
3510 {
3511 if (log)
3512 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
3513 return SendErrorResponse (0x08);
3514 }
3515
3516 if (bytes_read == 0)
3517 {
3518 if (log)
3519 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": read %" PRIu64 " of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, bytes_read, byte_count);
3520 return SendErrorResponse (0x08);
3521 }
3522
3523 StreamGDBRemote response;
3524 for (lldb::addr_t i = 0; i < bytes_read; ++i)
3525 response.PutHex8(buf[i]);
3526
3527 return SendPacketNoLock(response.GetData(), response.GetSize());
3528}
3529
3530GDBRemoteCommunication::PacketResult
3531GDBRemoteCommunicationServer::Handle_QSetDetachOnError (StringExtractorGDBRemote &packet)
3532{
3533 packet.SetFilePos(::strlen ("QSetDetachOnError:"));
3534 if (packet.GetU32(0))
3535 m_process_launch_info.GetFlags().Set (eLaunchFlagDetachOnError);
3536 else
3537 m_process_launch_info.GetFlags().Clear (eLaunchFlagDetachOnError);
3538 return SendOKResponse ();
3539}
3540
3541GDBRemoteCommunicationServer::PacketResult
3542GDBRemoteCommunicationServer::Handle_M (StringExtractorGDBRemote &packet)
3543{
3544 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3545
3546 // Ensure we're llgs.
3547 if (!IsGdbServer())
3548 {
3549 // Only supported on llgs
3550 return SendUnimplementedResponse ("");
3551 }
3552
3553 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3554 {
3555 if (log)
3556 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3557 return SendErrorResponse (0x15);
3558 }
3559
3560 // Parse out the memory address.
3561 packet.SetFilePos (strlen("M"));
3562 if (packet.GetBytesLeft() < 1)
3563 return SendIllFormedResponse(packet, "Too short M packet");
3564
3565 // Read the address. Punting on validation.
3566 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3567 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
3568
3569 // Validate comma.
3570 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3571 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
3572
3573 // Get # bytes to read.
3574 if (packet.GetBytesLeft() < 1)
3575 return SendIllFormedResponse(packet, "Length missing in M packet");
3576
3577 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3578 if (byte_count == 0)
3579 {
3580 if (log)
3581 log->Printf ("GDBRemoteCommunicationServer::%s nothing to write: zero-length packet", __FUNCTION__);
3582 return PacketResult::Success;
3583 }
3584
3585 // Validate colon.
3586 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
3587 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
3588
3589 // Allocate the conversion buffer.
3590 std::vector<uint8_t> buf(byte_count, 0);
3591 if (buf.empty())
3592 return SendErrorResponse (0x78);
3593
3594 // Convert the hex memory write contents to bytes.
3595 StreamGDBRemote response;
3596 const uint64_t convert_count = static_cast<uint64_t> (packet.GetHexBytes (&buf[0], byte_count, 0));
3597 if (convert_count != byte_count)
3598 {
3599 if (log)
3600 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": asked to write %" PRIu64 " bytes, but only found %" PRIu64 " to convert.", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, byte_count, convert_count);
3601 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
3602 }
3603
3604 // Write the process memory.
3605 lldb::addr_t bytes_written = 0;
3606 lldb_private::Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
3607 if (error.Fail ())
3608 {
3609 if (log)
3610 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
3611 return SendErrorResponse (0x09);
3612 }
3613
3614 if (bytes_written == 0)
3615 {
3616 if (log)
3617 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": wrote %" PRIu64 " of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, bytes_written, byte_count);
3618 return SendErrorResponse (0x09);
3619 }
3620
3621 return SendOKResponse ();
3622}
3623
3624GDBRemoteCommunicationServer::PacketResult
3625GDBRemoteCommunicationServer::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
3626{
3627 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3628
3629 // We don't support if we're not llgs.
3630 if (!IsGdbServer())
3631 return SendUnimplementedResponse ("");
3632
3633 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
3634 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
3635 // client only asks this when a process is being debugged.
3636
3637 // Ensure we have a process running; otherwise, we can't figure this out
3638 // since we won't have a NativeProcessProtocol.
3639 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3640 {
3641 if (log)
3642 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3643 return SendErrorResponse (0x15);
3644 }
3645
3646 // Test if we can get any region back when asking for the region around NULL.
3647 MemoryRegionInfo region_info;
3648 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
3649 if (error.Fail ())
3650 {
3651 // We don't support memory region info collection for this NativeProcessProtocol.
3652 return SendUnimplementedResponse ("");
3653 }
3654
3655 return SendOKResponse();
3656}
3657
3658GDBRemoteCommunicationServer::PacketResult
3659GDBRemoteCommunicationServer::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
3660{
3661 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3662
3663 // We don't support if we're not llgs.
3664 if (!IsGdbServer())
3665 return SendUnimplementedResponse ("");
3666
3667 // Ensure we have a process.
3668 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3669 {
3670 if (log)
3671 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3672 return SendErrorResponse (0x15);
3673 }
3674
3675 // Parse out the memory address.
3676 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
3677 if (packet.GetBytesLeft() < 1)
3678 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
3679
3680 // Read the address. Punting on validation.
3681 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3682
3683 StreamGDBRemote response;
3684
3685 // Get the memory region info for the target address.
3686 MemoryRegionInfo region_info;
3687 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
3688 if (error.Fail ())
3689 {
3690 // Return the error message.
3691
3692 response.PutCString ("error:");
3693 response.PutCStringAsRawHex8 (error.AsCString ());
3694 response.PutChar (';');
3695 }
3696 else
3697 {
3698 // Range start and size.
3699 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
3700
3701 // Permissions.
3702 if (region_info.GetReadable () ||
3703 region_info.GetWritable () ||
3704 region_info.GetExecutable ())
3705 {
3706 // Write permissions info.
3707 response.PutCString ("permissions:");
3708
3709 if (region_info.GetReadable ())
3710 response.PutChar ('r');
3711 if (region_info.GetWritable ())
3712 response.PutChar('w');
3713 if (region_info.GetExecutable())
3714 response.PutChar ('x');
3715
3716 response.PutChar (';');
3717 }
3718 }
3719
3720 return SendPacketNoLock(response.GetData(), response.GetSize());
3721}
3722
3723GDBRemoteCommunicationServer::PacketResult
3724GDBRemoteCommunicationServer::Handle_Z (StringExtractorGDBRemote &packet)
3725{
3726 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3727
3728 // We don't support if we're not llgs.
3729 if (!IsGdbServer())
3730 return SendUnimplementedResponse ("");
3731
3732 // Ensure we have a process.
3733 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3734 {
3735 if (log)
3736 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3737 return SendErrorResponse (0x15);
3738 }
3739
3740 // Parse out software or hardware breakpoint requested.
3741 packet.SetFilePos (strlen("Z"));
3742 if (packet.GetBytesLeft() < 1)
3743 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
3744
3745 bool want_breakpoint = true;
3746 bool want_hardware = false;
3747
3748 const char breakpoint_type_char = packet.GetChar ();
3749 switch (breakpoint_type_char)
3750 {
3751 case '0': want_hardware = false; want_breakpoint = true; break;
3752 case '1': want_hardware = true; want_breakpoint = true; break;
3753 case '2': want_breakpoint = false; break;
3754 case '3': want_breakpoint = false; break;
3755 default:
3756 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
3757
3758 }
3759
3760 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3761 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after breakpoint type");
3762
3763 // FIXME implement watchpoint support.
3764 if (!want_breakpoint)
3765 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3766
3767 // Parse out the breakpoint address.
3768 if (packet.GetBytesLeft() < 1)
3769 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
3770 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3771
3772 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3773 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
3774
3775 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3776 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3777 if (kind == std::numeric_limits<uint32_t>::max ())
3778 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse kind argument");
3779
3780 if (want_breakpoint)
3781 {
3782 // Try to set the breakpoint.
3783 const Error error = m_debugged_process_sp->SetBreakpoint (breakpoint_addr, kind, want_hardware);
3784 if (error.Success ())
3785 return SendOKResponse ();
3786 else
3787 {
3788 if (log)
3789 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to set breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3790 return SendErrorResponse (0x09);
3791 }
3792 }
3793
3794 // FIXME fix up after watchpoints are handled.
3795 return SendUnimplementedResponse ("");
3796}
3797
3798GDBRemoteCommunicationServer::PacketResult
3799GDBRemoteCommunicationServer::Handle_z (StringExtractorGDBRemote &packet)
3800{
3801 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3802
3803 // We don't support if we're not llgs.
3804 if (!IsGdbServer())
3805 return SendUnimplementedResponse ("");
3806
3807 // Ensure we have a process.
3808 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3809 {
3810 if (log)
3811 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3812 return SendErrorResponse (0x15);
3813 }
3814
3815 // Parse out software or hardware breakpoint requested.
Todd Fiala75f47c32014-10-11 21:42:09 +00003816 packet.SetFilePos (strlen("z"));
Todd Fialaaf245d12014-06-30 21:05:18 +00003817 if (packet.GetBytesLeft() < 1)
3818 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
3819
3820 bool want_breakpoint = true;
3821
3822 const char breakpoint_type_char = packet.GetChar ();
3823 switch (breakpoint_type_char)
3824 {
3825 case '0': want_breakpoint = true; break;
3826 case '1': want_breakpoint = true; break;
3827 case '2': want_breakpoint = false; break;
3828 case '3': want_breakpoint = false; break;
3829 default:
3830 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
3831
3832 }
3833
3834 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3835 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after breakpoint type");
3836
3837 // FIXME implement watchpoint support.
3838 if (!want_breakpoint)
3839 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3840
3841 // Parse out the breakpoint address.
3842 if (packet.GetBytesLeft() < 1)
3843 return SendIllFormedResponse(packet, "Too short z packet, missing address");
3844 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3845
3846 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3847 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
3848
3849 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3850 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3851 if (kind == std::numeric_limits<uint32_t>::max ())
3852 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse kind argument");
3853
3854 if (want_breakpoint)
3855 {
Todd Fiala75f47c32014-10-11 21:42:09 +00003856 // Try to clear the breakpoint.
Todd Fialaaf245d12014-06-30 21:05:18 +00003857 const Error error = m_debugged_process_sp->RemoveBreakpoint (breakpoint_addr);
3858 if (error.Success ())
3859 return SendOKResponse ();
3860 else
3861 {
3862 if (log)
3863 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to remove breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3864 return SendErrorResponse (0x09);
3865 }
3866 }
3867
3868 // FIXME fix up after watchpoints are handled.
3869 return SendUnimplementedResponse ("");
3870}
3871
3872GDBRemoteCommunicationServer::PacketResult
3873GDBRemoteCommunicationServer::Handle_s (StringExtractorGDBRemote &packet)
3874{
3875 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
3876
3877 // We don't support if we're not llgs.
3878 if (!IsGdbServer())
3879 return SendUnimplementedResponse ("");
3880
3881 // Ensure we have a process.
3882 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3883 {
3884 if (log)
3885 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3886 return SendErrorResponse (0x32);
3887 }
3888
3889 // We first try to use a continue thread id. If any one or any all set, use the current thread.
3890 // Bail out if we don't have a thread id.
3891 lldb::tid_t tid = GetContinueThreadID ();
3892 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3893 tid = GetCurrentThreadID ();
3894 if (tid == LLDB_INVALID_THREAD_ID)
3895 return SendErrorResponse (0x33);
3896
3897 // Double check that we have such a thread.
3898 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3899 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
3900 if (!thread_sp || thread_sp->GetID () != tid)
3901 return SendErrorResponse (0x33);
3902
3903 // Create the step action for the given thread.
3904 lldb_private::ResumeAction action = { tid, eStateStepping, 0 };
3905
3906 // Setup the actions list.
3907 lldb_private::ResumeActionList actions;
3908 actions.Append (action);
3909
3910 // All other threads stop while we're single stepping a thread.
3911 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
3912 Error error = m_debugged_process_sp->Resume (actions);
3913 if (error.Fail ())
3914 {
3915 if (log)
3916 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
3917 return SendErrorResponse(0x49);
3918 }
3919
3920 // No response here - the stop or exit will come from the resulting action.
3921 return PacketResult::Success;
3922}
3923
3924GDBRemoteCommunicationServer::PacketResult
3925GDBRemoteCommunicationServer::Handle_qSupported (StringExtractorGDBRemote &packet)
3926{
3927 StreamGDBRemote response;
3928
3929 // Features common to lldb-platform and llgs.
3930 uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet size--debugger can always use less
3931 response.Printf ("PacketSize=%x", max_packet_size);
3932
3933 response.PutCString (";QStartNoAckMode+");
3934 response.PutCString (";QThreadSuffixSupported+");
3935 response.PutCString (";QListThreadsInStopReply+");
3936#if defined(__linux__)
3937 response.PutCString (";qXfer:auxv:read+");
3938#endif
3939
3940 return SendPacketNoLock(response.GetData(), response.GetSize());
3941}
3942
3943GDBRemoteCommunicationServer::PacketResult
3944GDBRemoteCommunicationServer::Handle_QThreadSuffixSupported (StringExtractorGDBRemote &packet)
3945{
3946 m_thread_suffix_supported = true;
3947 return SendOKResponse();
3948}
3949
3950GDBRemoteCommunicationServer::PacketResult
3951GDBRemoteCommunicationServer::Handle_QListThreadsInStopReply (StringExtractorGDBRemote &packet)
3952{
3953 m_list_threads_in_stop_reply = true;
3954 return SendOKResponse();
3955}
3956
3957GDBRemoteCommunicationServer::PacketResult
3958GDBRemoteCommunicationServer::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
3959{
3960 // We don't support if we're not llgs.
3961 if (!IsGdbServer())
3962 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
3963
3964 // *BSD impls should be able to do this too.
3965#if defined(__linux__)
3966 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3967
3968 // Parse out the offset.
3969 packet.SetFilePos (strlen("qXfer:auxv:read::"));
3970 if (packet.GetBytesLeft () < 1)
3971 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3972
3973 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3974 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
3975 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3976
3977 // Parse out comma.
3978 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
3979 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
3980
3981 // Parse out the length.
3982 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3983 if (auxv_length == std::numeric_limits<uint64_t>::max ())
3984 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
3985
3986 // Grab the auxv data if we need it.
3987 if (!m_active_auxv_buffer_sp)
3988 {
3989 // Make sure we have a valid process.
3990 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3991 {
3992 if (log)
3993 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3994 return SendErrorResponse (0x10);
3995 }
3996
3997 // Grab the auxv data.
3998 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
3999 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
4000 {
4001 // Hmm, no auxv data, call that an error.
4002 if (log)
4003 log->Printf ("GDBRemoteCommunicationServer::%s failed, no auxv data retrieved", __FUNCTION__);
4004 m_active_auxv_buffer_sp.reset ();
4005 return SendErrorResponse (0x11);
4006 }
4007 }
4008
4009 // FIXME find out if/how I lock the stream here.
4010
4011 StreamGDBRemote response;
4012 bool done_with_buffer = false;
4013
4014 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
4015 {
4016 // We have nothing left to send. Mark the buffer as complete.
4017 response.PutChar ('l');
4018 done_with_buffer = true;
4019 }
4020 else
4021 {
4022 // Figure out how many bytes are available starting at the given offset.
4023 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
4024
4025 // Figure out how many bytes we're going to read.
4026 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
4027
4028 // Mark the response type according to whether we're reading the remainder of the auxv data.
4029 if (bytes_to_read >= bytes_remaining)
4030 {
4031 // There will be nothing left to read after this
4032 response.PutChar ('l');
4033 done_with_buffer = true;
4034 }
4035 else
4036 {
4037 // There will still be bytes to read after this request.
4038 response.PutChar ('m');
4039 }
4040
4041 // Now write the data in encoded binary form.
4042 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
4043 }
4044
4045 if (done_with_buffer)
4046 m_active_auxv_buffer_sp.reset ();
4047
4048 return SendPacketNoLock(response.GetData(), response.GetSize());
4049#else
4050 return SendUnimplementedResponse ("not implemented on this platform");
4051#endif
4052}
4053
4054GDBRemoteCommunicationServer::PacketResult
4055GDBRemoteCommunicationServer::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
4056{
4057 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4058
4059 // We don't support if we're not llgs.
4060 if (!IsGdbServer())
4061 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4062
4063 // Move past packet name.
4064 packet.SetFilePos (strlen ("QSaveRegisterState"));
4065
4066 // Get the thread to use.
4067 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4068 if (!thread_sp)
4069 {
4070 if (m_thread_suffix_supported)
4071 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
4072 else
4073 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4074 }
4075
4076 // Grab the register context for the thread.
4077 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4078 if (!reg_context_sp)
4079 {
4080 if (log)
4081 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
4082 return SendErrorResponse (0x15);
4083 }
4084
4085 // Save registers to a buffer.
4086 DataBufferSP register_data_sp;
4087 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
4088 if (error.Fail ())
4089 {
4090 if (log)
4091 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4092 return SendErrorResponse (0x75);
4093 }
4094
4095 // Allocate a new save id.
4096 const uint32_t save_id = GetNextSavedRegistersID ();
4097 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
4098
4099 // Save the register data buffer under the save id.
4100 {
4101 Mutex::Locker locker (m_saved_registers_mutex);
4102 m_saved_registers_map[save_id] = register_data_sp;
4103 }
4104
4105 // Write the response.
4106 StreamGDBRemote response;
4107 response.Printf ("%" PRIu32, save_id);
4108 return SendPacketNoLock(response.GetData(), response.GetSize());
4109}
4110
4111GDBRemoteCommunicationServer::PacketResult
4112GDBRemoteCommunicationServer::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
4113{
4114 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4115
4116 // We don't support if we're not llgs.
4117 if (!IsGdbServer())
4118 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4119
4120 // Parse out save id.
4121 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
4122 if (packet.GetBytesLeft () < 1)
4123 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
4124
4125 const uint32_t save_id = packet.GetU32 (0);
4126 if (save_id == 0)
4127 {
4128 if (log)
4129 log->Printf ("GDBRemoteCommunicationServer::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
4130 return SendErrorResponse (0x76);
4131 }
4132
4133 // Get the thread to use.
4134 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4135 if (!thread_sp)
4136 {
4137 if (m_thread_suffix_supported)
4138 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
4139 else
4140 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4141 }
4142
4143 // Grab the register context for the thread.
4144 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4145 if (!reg_context_sp)
4146 {
4147 if (log)
4148 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
4149 return SendErrorResponse (0x15);
4150 }
4151
4152 // Retrieve register state buffer, then remove from the list.
4153 DataBufferSP register_data_sp;
4154 {
4155 Mutex::Locker locker (m_saved_registers_mutex);
4156
4157 // Find the register set buffer for the given save id.
4158 auto it = m_saved_registers_map.find (save_id);
4159 if (it == m_saved_registers_map.end ())
4160 {
4161 if (log)
4162 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " does not have a register set save buffer for id %" PRIu32, __FUNCTION__, m_debugged_process_sp->GetID (), save_id);
4163 return SendErrorResponse (0x77);
4164 }
4165 register_data_sp = it->second;
4166
4167 // Remove it from the map.
4168 m_saved_registers_map.erase (it);
4169 }
4170
4171 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
4172 if (error.Fail ())
4173 {
4174 if (log)
4175 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4176 return SendErrorResponse (0x77);
4177 }
4178
4179 return SendOKResponse();
4180}
4181
Todd Fiala7306cf32014-07-29 22:30:01 +00004182GDBRemoteCommunicationServer::PacketResult
4183GDBRemoteCommunicationServer::Handle_vAttach (StringExtractorGDBRemote &packet)
4184{
4185 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4186
4187 // We don't support if we're not llgs.
4188 if (!IsGdbServer())
4189 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4190
4191 // Consume the ';' after vAttach.
4192 packet.SetFilePos (strlen ("vAttach"));
4193 if (!packet.GetBytesLeft () || packet.GetChar () != ';')
4194 return SendIllFormedResponse (packet, "vAttach missing expected ';'");
4195
4196 // Grab the PID to which we will attach (assume hex encoding).
4197 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
4198 if (pid == LLDB_INVALID_PROCESS_ID)
4199 return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
4200
4201 // Attempt to attach.
4202 if (log)
4203 log->Printf ("GDBRemoteCommunicationServer::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
4204
4205 Error error = AttachToProcess (pid);
4206
4207 if (error.Fail ())
4208 {
4209 if (log)
4210 log->Printf ("GDBRemoteCommunicationServer::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
4211 return SendErrorResponse (0x01);
4212 }
4213
4214 // Notify we attached by sending a stop packet.
4215 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
Oleksiy Vyalov859e4b52014-12-10 01:27:28 +00004216}
Todd Fiala7306cf32014-07-29 22:30:01 +00004217
Oleksiy Vyalov859e4b52014-12-10 01:27:28 +00004218GDBRemoteCommunicationServer::PacketResult
4219GDBRemoteCommunicationServer::Handle_D (StringExtractorGDBRemote &packet)
4220{
4221 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
4222
4223 // We don't support if we're not llgs.
4224 if (!IsGdbServer())
4225 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4226
4227 // Scope for mutex locker.
4228 Mutex::Locker locker (m_spawned_pids_mutex);
4229
4230 // Fail if we don't have a current process.
4231 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
4232 {
4233 if (log)
4234 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
4235 return SendErrorResponse (0x15);
4236 }
4237
4238 if (m_spawned_pids.find(m_debugged_process_sp->GetID ()) == m_spawned_pids.end())
4239 {
4240 if (log)
4241 log->Printf ("GDBRemoteCommunicationServer::%s failed to find PID %" PRIu64 " in spawned pids list",
4242 __FUNCTION__, m_debugged_process_sp->GetID ());
4243 return SendErrorResponse (0x1);
4244 }
4245
4246 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
4247
4248 // Consume the ';' after D.
4249 packet.SetFilePos (1);
4250 if (packet.GetBytesLeft ())
4251 {
4252 if (packet.GetChar () != ';')
4253 return SendIllFormedResponse (packet, "D missing expected ';'");
4254
4255 // Grab the PID from which we will detach (assume hex encoding).
4256 pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
4257 if (pid == LLDB_INVALID_PROCESS_ID)
4258 return SendIllFormedResponse (packet, "D failed to parse the process id");
4259 }
4260
4261 if (pid != LLDB_INVALID_PROCESS_ID &&
4262 m_debugged_process_sp->GetID () != pid)
4263 {
4264 return SendIllFormedResponse (packet, "Invalid pid");
4265 }
4266
4267 if (m_stdio_communication.IsConnected ())
4268 {
4269 m_stdio_communication.StopReadThread ();
4270 }
4271
4272 const Error error = m_debugged_process_sp->Detach ();
4273 if (error.Fail ())
4274 {
4275 if (log)
4276 log->Printf ("GDBRemoteCommunicationServer::%s failed to detach from pid %" PRIu64 ": %s\n",
4277 __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4278 return SendErrorResponse (0x01);
4279 }
4280
4281 m_spawned_pids.erase (m_debugged_process_sp->GetID ());
4282 return SendOKResponse ();
Todd Fiala7306cf32014-07-29 22:30:01 +00004283}
4284
Todd Fiala1109ed42014-09-10 21:28:38 +00004285GDBRemoteCommunicationServer::PacketResult
4286GDBRemoteCommunicationServer::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet)
4287{
4288 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4289
4290 // We don't support if we're not llgs.
4291 if (!IsGdbServer())
4292 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4293
4294 packet.SetFilePos (strlen("qThreadStopInfo"));
4295 const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
4296 if (tid == LLDB_INVALID_THREAD_ID)
4297 {
4298 if (log)
4299 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
4300 return SendErrorResponse (0x15);
4301 }
4302 return SendStopReplyPacketForThread (tid);
4303}
4304
Todd Fialaaf245d12014-06-30 21:05:18 +00004305void
4306GDBRemoteCommunicationServer::FlushInferiorOutput ()
4307{
4308 // If we're not monitoring an inferior's terminal, ignore this.
4309 if (!m_stdio_communication.IsConnected())
4310 return;
4311
4312 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
4313 if (log)
4314 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
4315
4316 // FIXME implement a timeout on the join.
4317 m_stdio_communication.JoinReadThread();
4318}
4319
4320void
4321GDBRemoteCommunicationServer::MaybeCloseInferiorTerminalConnection ()
4322{
4323 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4324
4325 // Tell the stdio connection to shut down.
4326 if (m_stdio_communication.IsConnected())
4327 {
4328 auto connection = m_stdio_communication.GetConnection();
4329 if (connection)
4330 {
4331 Error error;
4332 connection->Disconnect (&error);
4333
4334 if (error.Success ())
4335 {
4336 if (log)
4337 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
4338 }
4339 else
4340 {
4341 if (log)
4342 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
4343 }
4344 }
4345 }
4346}
4347
4348
4349lldb_private::NativeThreadProtocolSP
4350GDBRemoteCommunicationServer::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
4351{
4352 NativeThreadProtocolSP thread_sp;
4353
4354 // We have no thread if we don't have a process.
4355 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
4356 return thread_sp;
4357
4358 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
4359 // Use the current thread in that case.
4360 if (!m_thread_suffix_supported)
4361 {
4362 const lldb::tid_t current_tid = GetCurrentThreadID ();
4363 if (current_tid == LLDB_INVALID_THREAD_ID)
4364 return thread_sp;
4365 else if (current_tid == 0)
4366 {
4367 // Pick a thread.
4368 return m_debugged_process_sp->GetThreadAtIndex (0);
4369 }
4370 else
4371 return m_debugged_process_sp->GetThreadByID (current_tid);
4372 }
4373
4374 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4375
4376 // Parse out the ';'.
4377 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
4378 {
4379 if (log)
4380 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4381 return thread_sp;
4382 }
4383
4384 if (!packet.GetBytesLeft ())
4385 return thread_sp;
4386
4387 // Parse out thread: portion.
4388 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
4389 {
4390 if (log)
4391 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4392 return thread_sp;
4393 }
4394 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
4395 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4396 if (tid != 0)
4397 return m_debugged_process_sp->GetThreadByID (tid);
4398
4399 return thread_sp;
4400}
4401
4402lldb::tid_t
4403GDBRemoteCommunicationServer::GetCurrentThreadID () const
4404{
4405 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
4406 {
4407 // Use whatever the debug process says is the current thread id
4408 // since the protocol either didn't specify or specified we want
4409 // any/all threads marked as the current thread.
4410 if (!m_debugged_process_sp)
4411 return LLDB_INVALID_THREAD_ID;
4412 return m_debugged_process_sp->GetCurrentThreadID ();
4413 }
4414 // Use the specific current thread id set by the gdb remote protocol.
4415 return m_current_tid;
4416}
4417
4418uint32_t
4419GDBRemoteCommunicationServer::GetNextSavedRegistersID ()
4420{
4421 Mutex::Locker locker (m_saved_registers_mutex);
4422 return m_next_saved_registers_id++;
4423}
4424
Todd Fialaa9882ce2014-08-28 15:46:54 +00004425void
4426GDBRemoteCommunicationServer::ClearProcessSpecificData ()
4427{
4428 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
4429 if (log)
4430 log->Printf ("GDBRemoteCommunicationServer::%s()", __FUNCTION__);
4431
4432 // Clear any auxv cached data.
4433 // *BSD impls should be able to do this too.
4434#if defined(__linux__)
4435 if (log)
4436 log->Printf ("GDBRemoteCommunicationServer::%s clearing auxv buffer (previously %s)",
4437 __FUNCTION__,
4438 m_active_auxv_buffer_sp ? "was set" : "was not set");
4439 m_active_auxv_buffer_sp.reset ();
4440#endif
4441}