blob: aab665961dc3b2c982afd2123243985426aec96d [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"
26#include "lldb/Core/ConnectionFileDescriptor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000027#include "lldb/Core/Debugger.h"
Greg Clayton576d8832011-03-22 04:00:09 +000028#include "lldb/Core/Log.h"
29#include "lldb/Core/State.h"
30#include "lldb/Core/StreamString.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"
36#include "lldb/Host/TimeValue.h"
Zachary Turner696b5282014-08-14 16:01:25 +000037#include "lldb/Target/FileAction.h"
Todd Fialab8b49ec2014-01-28 00:34:23 +000038#include "lldb/Target/Platform.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000039#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000040#include "lldb/Target/NativeRegisterContext.h"
Todd Fiala24189d42014-07-14 06:24:44 +000041#include "Host/common/NativeProcessProtocol.h"
42#include "Host/common/NativeThreadProtocol.h"
Greg Clayton576d8832011-03-22 04:00:09 +000043
44// Project includes
45#include "Utility/StringExtractorGDBRemote.h"
46#include "ProcessGDBRemote.h"
47#include "ProcessGDBRemoteLog.h"
48
49using namespace lldb;
50using namespace lldb_private;
51
52//----------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +000053// GDBRemote Errors
54//----------------------------------------------------------------------
55
56namespace
57{
58 enum GDBRemoteServerError
59 {
60 // Set to the first unused error number in literal form below
61 eErrorFirst = 29,
62 eErrorNoProcess = eErrorFirst,
63 eErrorResume,
64 eErrorExitStatus
65 };
66}
67
68//----------------------------------------------------------------------
Greg Clayton576d8832011-03-22 04:00:09 +000069// GDBRemoteCommunicationServer constructor
70//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +000071GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform) :
72 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
Todd Fialab8b49ec2014-01-28 00:34:23 +000073 m_platform_sp (Platform::GetDefaultPlatform ()),
Greg Clayton8b82f082011-04-12 05:54:46 +000074 m_async_thread (LLDB_INVALID_HOST_THREAD),
75 m_process_launch_info (),
76 m_process_launch_error (),
Daniel Maleae0f8f572013-08-26 23:57:52 +000077 m_spawned_pids (),
78 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton8b82f082011-04-12 05:54:46 +000079 m_proc_infos (),
80 m_proc_infos_index (0),
Greg Clayton2b98c562013-11-22 18:53:12 +000081 m_port_map (),
Todd Fialaaf245d12014-06-30 21:05:18 +000082 m_port_offset(0),
83 m_current_tid (LLDB_INVALID_THREAD_ID),
84 m_continue_tid (LLDB_INVALID_THREAD_ID),
85 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
86 m_debugged_process_sp (),
87 m_debugger_sp (),
88 m_stdio_communication ("process.stdio"),
89 m_exit_now (false),
90 m_inferior_prev_state (StateType::eStateInvalid),
91 m_thread_suffix_supported (false),
92 m_list_threads_in_stop_reply (false),
93 m_active_auxv_buffer_sp (),
94 m_saved_registers_mutex (),
95 m_saved_registers_map (),
96 m_next_saved_registers_id (1)
Greg Clayton576d8832011-03-22 04:00:09 +000097{
Todd Fialaaf245d12014-06-30 21:05:18 +000098 assert(is_platform && "must be lldb-platform if debugger is not specified");
Greg Clayton576d8832011-03-22 04:00:09 +000099}
100
Todd Fialab8b49ec2014-01-28 00:34:23 +0000101GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform,
Todd Fialaaf245d12014-06-30 21:05:18 +0000102 const lldb::PlatformSP& platform_sp,
103 lldb::DebuggerSP &debugger_sp) :
Todd Fialab8b49ec2014-01-28 00:34:23 +0000104 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
105 m_platform_sp (platform_sp),
106 m_async_thread (LLDB_INVALID_HOST_THREAD),
107 m_process_launch_info (),
108 m_process_launch_error (),
109 m_spawned_pids (),
110 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
111 m_proc_infos (),
112 m_proc_infos_index (0),
113 m_port_map (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000114 m_port_offset(0),
115 m_current_tid (LLDB_INVALID_THREAD_ID),
116 m_continue_tid (LLDB_INVALID_THREAD_ID),
117 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
118 m_debugged_process_sp (),
119 m_debugger_sp (debugger_sp),
120 m_stdio_communication ("process.stdio"),
121 m_exit_now (false),
122 m_inferior_prev_state (StateType::eStateInvalid),
123 m_thread_suffix_supported (false),
124 m_list_threads_in_stop_reply (false),
125 m_active_auxv_buffer_sp (),
126 m_saved_registers_mutex (),
127 m_saved_registers_map (),
128 m_next_saved_registers_id (1)
Todd Fialab8b49ec2014-01-28 00:34:23 +0000129{
130 assert(platform_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000131 assert((is_platform || debugger_sp) && "must specify non-NULL debugger_sp when lldb-gdbserver");
Todd Fialab8b49ec2014-01-28 00:34:23 +0000132}
133
Greg Clayton576d8832011-03-22 04:00:09 +0000134//----------------------------------------------------------------------
135// Destructor
136//----------------------------------------------------------------------
137GDBRemoteCommunicationServer::~GDBRemoteCommunicationServer()
138{
139}
140
Todd Fialaaf245d12014-06-30 21:05:18 +0000141GDBRemoteCommunication::PacketResult
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000142GDBRemoteCommunicationServer::GetPacketAndSendResponse (uint32_t timeout_usec,
Greg Clayton1cb64962011-03-24 04:28:38 +0000143 Error &error,
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000144 bool &interrupt,
Greg Claytond314e812011-03-23 00:09:55 +0000145 bool &quit)
Greg Clayton576d8832011-03-22 04:00:09 +0000146{
147 StringExtractorGDBRemote packet;
Todd Fialaaf245d12014-06-30 21:05:18 +0000148
Greg Clayton3dedae12013-12-06 21:45:27 +0000149 PacketResult packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, timeout_usec);
150 if (packet_result == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000151 {
152 const StringExtractorGDBRemote::ServerPacketType packet_type = packet.GetServerPacketType ();
153 switch (packet_type)
154 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000155 case StringExtractorGDBRemote::eServerPacketType_nack:
156 case StringExtractorGDBRemote::eServerPacketType_ack:
157 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000158
Greg Clayton3dedae12013-12-06 21:45:27 +0000159 case StringExtractorGDBRemote::eServerPacketType_invalid:
160 error.SetErrorString("invalid packet");
161 quit = true;
162 break;
Greg Claytond314e812011-03-23 00:09:55 +0000163
Greg Clayton3dedae12013-12-06 21:45:27 +0000164 default:
165 case StringExtractorGDBRemote::eServerPacketType_unimplemented:
166 packet_result = SendUnimplementedResponse (packet.GetStringRef().c_str());
167 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000168
Greg Clayton3dedae12013-12-06 21:45:27 +0000169 case StringExtractorGDBRemote::eServerPacketType_A:
170 packet_result = Handle_A (packet);
171 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000172
Greg Clayton3dedae12013-12-06 21:45:27 +0000173 case StringExtractorGDBRemote::eServerPacketType_qfProcessInfo:
174 packet_result = Handle_qfProcessInfo (packet);
175 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000176
Greg Clayton3dedae12013-12-06 21:45:27 +0000177 case StringExtractorGDBRemote::eServerPacketType_qsProcessInfo:
178 packet_result = Handle_qsProcessInfo (packet);
179 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000180
Greg Clayton3dedae12013-12-06 21:45:27 +0000181 case StringExtractorGDBRemote::eServerPacketType_qC:
182 packet_result = Handle_qC (packet);
183 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000184
Greg Clayton3dedae12013-12-06 21:45:27 +0000185 case StringExtractorGDBRemote::eServerPacketType_qHostInfo:
186 packet_result = Handle_qHostInfo (packet);
187 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000188
Greg Clayton3dedae12013-12-06 21:45:27 +0000189 case StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer:
190 packet_result = Handle_qLaunchGDBServer (packet);
191 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000192
Greg Clayton3dedae12013-12-06 21:45:27 +0000193 case StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess:
194 packet_result = Handle_qKillSpawnedProcess (packet);
195 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000196
Todd Fiala403edc52014-01-23 22:05:44 +0000197 case StringExtractorGDBRemote::eServerPacketType_k:
198 packet_result = Handle_k (packet);
Todd Fialaaf245d12014-06-30 21:05:18 +0000199 quit = true;
Todd Fiala403edc52014-01-23 22:05:44 +0000200 break;
201
Greg Clayton3dedae12013-12-06 21:45:27 +0000202 case StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess:
203 packet_result = Handle_qLaunchSuccess (packet);
204 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000205
Greg Clayton3dedae12013-12-06 21:45:27 +0000206 case StringExtractorGDBRemote::eServerPacketType_qGroupName:
207 packet_result = Handle_qGroupName (packet);
208 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000209
Todd Fialaaf245d12014-06-30 21:05:18 +0000210 case StringExtractorGDBRemote::eServerPacketType_qProcessInfo:
211 packet_result = Handle_qProcessInfo (packet);
212 break;
213
Greg Clayton3dedae12013-12-06 21:45:27 +0000214 case StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID:
215 packet_result = Handle_qProcessInfoPID (packet);
216 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000217
Greg Clayton3dedae12013-12-06 21:45:27 +0000218 case StringExtractorGDBRemote::eServerPacketType_qSpeedTest:
219 packet_result = Handle_qSpeedTest (packet);
220 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000221
Greg Clayton3dedae12013-12-06 21:45:27 +0000222 case StringExtractorGDBRemote::eServerPacketType_qUserName:
223 packet_result = Handle_qUserName (packet);
224 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000225
Greg Clayton3dedae12013-12-06 21:45:27 +0000226 case StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir:
227 packet_result = Handle_qGetWorkingDir(packet);
228 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000229
Greg Clayton3dedae12013-12-06 21:45:27 +0000230 case StringExtractorGDBRemote::eServerPacketType_QEnvironment:
231 packet_result = Handle_QEnvironment (packet);
232 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000233
Greg Clayton3dedae12013-12-06 21:45:27 +0000234 case StringExtractorGDBRemote::eServerPacketType_QLaunchArch:
235 packet_result = Handle_QLaunchArch (packet);
236 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000237
Greg Clayton3dedae12013-12-06 21:45:27 +0000238 case StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR:
239 packet_result = Handle_QSetDisableASLR (packet);
240 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000241
Jim Ingham106d0282014-06-25 02:32:56 +0000242 case StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError:
243 packet_result = Handle_QSetDetachOnError (packet);
244 break;
245
Greg Clayton3dedae12013-12-06 21:45:27 +0000246 case StringExtractorGDBRemote::eServerPacketType_QSetSTDIN:
247 packet_result = Handle_QSetSTDIN (packet);
248 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000249
Greg Clayton3dedae12013-12-06 21:45:27 +0000250 case StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT:
251 packet_result = Handle_QSetSTDOUT (packet);
252 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000253
Greg Clayton3dedae12013-12-06 21:45:27 +0000254 case StringExtractorGDBRemote::eServerPacketType_QSetSTDERR:
255 packet_result = Handle_QSetSTDERR (packet);
256 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000257
Greg Clayton3dedae12013-12-06 21:45:27 +0000258 case StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir:
259 packet_result = Handle_QSetWorkingDir (packet);
260 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000261
Greg Clayton3dedae12013-12-06 21:45:27 +0000262 case StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode:
263 packet_result = Handle_QStartNoAckMode (packet);
264 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000265
Greg Clayton3dedae12013-12-06 21:45:27 +0000266 case StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir:
267 packet_result = Handle_qPlatform_mkdir (packet);
268 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000269
Greg Clayton3dedae12013-12-06 21:45:27 +0000270 case StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod:
271 packet_result = Handle_qPlatform_chmod (packet);
272 break;
Greg Claytonfbb76342013-11-20 21:07:01 +0000273
Greg Clayton3dedae12013-12-06 21:45:27 +0000274 case StringExtractorGDBRemote::eServerPacketType_qPlatform_shell:
275 packet_result = Handle_qPlatform_shell (packet);
276 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000277
Todd Fialaaf245d12014-06-30 21:05:18 +0000278 case StringExtractorGDBRemote::eServerPacketType_C:
279 packet_result = Handle_C (packet);
280 break;
281
282 case StringExtractorGDBRemote::eServerPacketType_c:
283 packet_result = Handle_c (packet);
284 break;
285
286 case StringExtractorGDBRemote::eServerPacketType_vCont:
287 packet_result = Handle_vCont (packet);
288 break;
289
290 case StringExtractorGDBRemote::eServerPacketType_vCont_actions:
291 packet_result = Handle_vCont_actions (packet);
292 break;
293
294 case StringExtractorGDBRemote::eServerPacketType_stop_reason: // ?
295 packet_result = Handle_stop_reason (packet);
296 break;
297
Greg Clayton3dedae12013-12-06 21:45:27 +0000298 case StringExtractorGDBRemote::eServerPacketType_vFile_open:
299 packet_result = Handle_vFile_Open (packet);
300 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000301
Greg Clayton3dedae12013-12-06 21:45:27 +0000302 case StringExtractorGDBRemote::eServerPacketType_vFile_close:
303 packet_result = Handle_vFile_Close (packet);
304 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000305
Greg Clayton3dedae12013-12-06 21:45:27 +0000306 case StringExtractorGDBRemote::eServerPacketType_vFile_pread:
307 packet_result = Handle_vFile_pRead (packet);
308 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000309
Greg Clayton3dedae12013-12-06 21:45:27 +0000310 case StringExtractorGDBRemote::eServerPacketType_vFile_pwrite:
311 packet_result = Handle_vFile_pWrite (packet);
312 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000313
Greg Clayton3dedae12013-12-06 21:45:27 +0000314 case StringExtractorGDBRemote::eServerPacketType_vFile_size:
315 packet_result = Handle_vFile_Size (packet);
316 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000317
Greg Clayton3dedae12013-12-06 21:45:27 +0000318 case StringExtractorGDBRemote::eServerPacketType_vFile_mode:
319 packet_result = Handle_vFile_Mode (packet);
320 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000321
Greg Clayton3dedae12013-12-06 21:45:27 +0000322 case StringExtractorGDBRemote::eServerPacketType_vFile_exists:
323 packet_result = Handle_vFile_Exists (packet);
324 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000325
Greg Clayton3dedae12013-12-06 21:45:27 +0000326 case StringExtractorGDBRemote::eServerPacketType_vFile_stat:
327 packet_result = Handle_vFile_Stat (packet);
328 break;
Greg Claytonfbb76342013-11-20 21:07:01 +0000329
Greg Clayton3dedae12013-12-06 21:45:27 +0000330 case StringExtractorGDBRemote::eServerPacketType_vFile_md5:
331 packet_result = Handle_vFile_MD5 (packet);
332 break;
333
334 case StringExtractorGDBRemote::eServerPacketType_vFile_symlink:
335 packet_result = Handle_vFile_symlink (packet);
336 break;
337
338 case StringExtractorGDBRemote::eServerPacketType_vFile_unlink:
339 packet_result = Handle_vFile_unlink (packet);
340 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000341
342 case StringExtractorGDBRemote::eServerPacketType_qRegisterInfo:
343 packet_result = Handle_qRegisterInfo (packet);
344 break;
345
346 case StringExtractorGDBRemote::eServerPacketType_qfThreadInfo:
347 packet_result = Handle_qfThreadInfo (packet);
348 break;
349
350 case StringExtractorGDBRemote::eServerPacketType_qsThreadInfo:
351 packet_result = Handle_qsThreadInfo (packet);
352 break;
353
354 case StringExtractorGDBRemote::eServerPacketType_p:
355 packet_result = Handle_p (packet);
356 break;
357
358 case StringExtractorGDBRemote::eServerPacketType_P:
359 packet_result = Handle_P (packet);
360 break;
361
362 case StringExtractorGDBRemote::eServerPacketType_H:
363 packet_result = Handle_H (packet);
364 break;
365
366 case StringExtractorGDBRemote::eServerPacketType_m:
367 packet_result = Handle_m (packet);
368 break;
369
370 case StringExtractorGDBRemote::eServerPacketType_M:
371 packet_result = Handle_M (packet);
372 break;
373
374 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported:
375 packet_result = Handle_qMemoryRegionInfoSupported (packet);
376 break;
377
378 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo:
379 packet_result = Handle_qMemoryRegionInfo (packet);
380 break;
381
382 case StringExtractorGDBRemote::eServerPacketType_interrupt:
383 if (IsGdbServer ())
384 packet_result = Handle_interrupt (packet);
385 else
386 {
387 error.SetErrorString("interrupt received");
388 interrupt = true;
389 }
390 break;
391
392 case StringExtractorGDBRemote::eServerPacketType_Z:
393 packet_result = Handle_Z (packet);
394 break;
395
396 case StringExtractorGDBRemote::eServerPacketType_z:
397 packet_result = Handle_z (packet);
398 break;
399
400 case StringExtractorGDBRemote::eServerPacketType_s:
401 packet_result = Handle_s (packet);
402 break;
403
404 case StringExtractorGDBRemote::eServerPacketType_qSupported:
405 packet_result = Handle_qSupported (packet);
406 break;
407
408 case StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported:
409 packet_result = Handle_QThreadSuffixSupported (packet);
410 break;
411
412 case StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply:
413 packet_result = Handle_QListThreadsInStopReply (packet);
414 break;
415
416 case StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read:
417 packet_result = Handle_qXfer_auxv_read (packet);
418 break;
419
420 case StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState:
421 packet_result = Handle_QSaveRegisterState (packet);
422 break;
423
424 case StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState:
425 packet_result = Handle_QRestoreRegisterState (packet);
426 break;
Todd Fiala7306cf32014-07-29 22:30:01 +0000427
428 case StringExtractorGDBRemote::eServerPacketType_vAttach:
429 packet_result = Handle_vAttach (packet);
430 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000431 }
Greg Clayton576d8832011-03-22 04:00:09 +0000432 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000433 else
434 {
435 if (!IsConnected())
Greg Clayton3dedae12013-12-06 21:45:27 +0000436 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000437 error.SetErrorString("lost connection");
Greg Clayton3dedae12013-12-06 21:45:27 +0000438 quit = true;
439 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000440 else
Greg Clayton3dedae12013-12-06 21:45:27 +0000441 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000442 error.SetErrorString("timeout");
Greg Clayton3dedae12013-12-06 21:45:27 +0000443 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000444 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000445
446 // Check if anything occurred that would force us to want to exit.
447 if (m_exit_now)
448 quit = true;
449
450 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000451}
452
Todd Fiala403edc52014-01-23 22:05:44 +0000453lldb_private::Error
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000454GDBRemoteCommunicationServer::SetLaunchArguments (const char *const args[], int argc)
Todd Fiala403edc52014-01-23 22:05:44 +0000455{
456 if ((argc < 1) || !args || !args[0] || !args[0][0])
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000457 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
Todd Fiala403edc52014-01-23 22:05:44 +0000458
Todd Fiala403edc52014-01-23 22:05:44 +0000459 m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000460 return lldb_private::Error ();
461}
462
463lldb_private::Error
464GDBRemoteCommunicationServer::SetLaunchFlags (unsigned int launch_flags)
465{
Todd Fiala403edc52014-01-23 22:05:44 +0000466 m_process_launch_info.GetFlags ().Set (launch_flags);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000467 return lldb_private::Error ();
468}
469
470lldb_private::Error
471GDBRemoteCommunicationServer::LaunchProcess ()
472{
Todd Fialaaf245d12014-06-30 21:05:18 +0000473 // FIXME This looks an awful lot like we could override this in
474 // derived classes, one for lldb-platform, the other for lldb-gdbserver.
475 if (IsGdbServer ())
476 return LaunchDebugServerProcess ();
477 else
478 return LaunchPlatformProcess ();
479}
480
481lldb_private::Error
482GDBRemoteCommunicationServer::LaunchDebugServerProcess ()
483{
484 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
485
486 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
487 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
488
489 lldb_private::Error error;
490 {
491 Mutex::Locker locker (m_debugged_process_mutex);
492 assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
493 error = m_platform_sp->LaunchNativeProcess (
494 m_process_launch_info,
495 *this,
496 m_debugged_process_sp);
497 }
498
499 if (!error.Success ())
500 {
501 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
502 return error;
503 }
504
505 // Setup stdout/stderr mapping from inferior.
506 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
507 if (terminal_fd >= 0)
508 {
509 if (log)
510 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
511 error = SetSTDIOFileDescriptor (terminal_fd);
512 if (error.Fail ())
513 return error;
514 }
515 else
516 {
517 if (log)
518 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
519 }
520
521 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
522
523 // Add to list of spawned processes.
524 lldb::pid_t pid;
525 if ((pid = m_process_launch_info.GetProcessID ()) != LLDB_INVALID_PROCESS_ID)
526 {
527 // add to spawned pids
528 {
529 Mutex::Locker locker (m_spawned_pids_mutex);
530 // On an lldb-gdbserver, we would expect there to be only one.
531 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
532 m_spawned_pids.insert (pid);
533 }
534 }
535
536 if (error.Success ())
537 {
538 if (log)
539 log->Printf ("GDBRemoteCommunicationServer::%s beginning check to wait for launched application to hit first stop", __FUNCTION__);
540
541 int iteration = 0;
542 // Wait for the process to hit its first stop state.
543 while (!StateIsStoppedState (m_debugged_process_sp->GetState (), false))
544 {
545 if (log)
546 log->Printf ("GDBRemoteCommunicationServer::%s waiting for launched process to hit first stop (%d)...", __FUNCTION__, iteration++);
547
Todd Fiala2850b1b2014-06-30 23:51:35 +0000548 // FIXME use a finer granularity.
549 std::this_thread::sleep_for(std::chrono::seconds(1));
Todd Fialaaf245d12014-06-30 21:05:18 +0000550 }
551
552 if (log)
553 log->Printf ("GDBRemoteCommunicationServer::%s launched application has hit first stop", __FUNCTION__);
554
555 }
556
557 return error;
558}
559
560lldb_private::Error
561GDBRemoteCommunicationServer::LaunchPlatformProcess ()
562{
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000563 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
564 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
565
566 // specify the process monitor if not already set. This should
567 // generally be what happens since we need to reap started
568 // processes.
569 if (!m_process_launch_info.GetMonitorProcessCallback ())
570 m_process_launch_info.SetMonitorProcessCallback(ReapDebuggedProcess, this, false);
Todd Fiala403edc52014-01-23 22:05:44 +0000571
Todd Fialab8b49ec2014-01-28 00:34:23 +0000572 lldb_private::Error error = m_platform_sp->LaunchProcess (m_process_launch_info);
Todd Fiala403edc52014-01-23 22:05:44 +0000573 if (!error.Success ())
574 {
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000575 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
Todd Fiala403edc52014-01-23 22:05:44 +0000576 return error;
577 }
578
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000579 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 +0000580
581 // add to list of spawned processes. On an lldb-gdbserver, we
582 // would expect there to be only one.
583 lldb::pid_t pid;
584 if ( (pid = m_process_launch_info.GetProcessID()) != LLDB_INVALID_PROCESS_ID )
585 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000586 // add to spawned pids
587 {
588 Mutex::Locker locker (m_spawned_pids_mutex);
589 m_spawned_pids.insert(pid);
590 }
Todd Fiala403edc52014-01-23 22:05:44 +0000591 }
592
593 return error;
594}
595
Todd Fialaaf245d12014-06-30 21:05:18 +0000596lldb_private::Error
597GDBRemoteCommunicationServer::AttachToProcess (lldb::pid_t pid)
598{
599 Error error;
600
601 if (!IsGdbServer ())
602 {
603 error.SetErrorString("cannot AttachToProcess () unless process is lldb-gdbserver");
604 return error;
605 }
606
607 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
608 if (log)
609 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64, __FUNCTION__, pid);
610
611 // Scope for mutex locker.
612 {
613 // Before we try to attach, make sure we aren't already monitoring something else.
614 Mutex::Locker locker (m_spawned_pids_mutex);
615 if (!m_spawned_pids.empty ())
616 {
617 error.SetErrorStringWithFormat ("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, *m_spawned_pids.begin());
618 return error;
619 }
620
621 // Try to attach.
622 error = m_platform_sp->AttachNativeProcess (pid, *this, m_debugged_process_sp);
623 if (!error.Success ())
624 {
625 fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
626 return error;
627 }
628
629 // Setup stdout/stderr mapping from inferior.
630 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
631 if (terminal_fd >= 0)
632 {
633 if (log)
634 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
635 error = SetSTDIOFileDescriptor (terminal_fd);
636 if (error.Fail ())
637 return error;
638 }
639 else
640 {
641 if (log)
642 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
643 }
644
645 printf ("Attached to process %" PRIu64 "...\n", pid);
646
647 // Add to list of spawned processes.
648 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
649 m_spawned_pids.insert (pid);
650
651 return error;
652 }
653}
654
655void
656GDBRemoteCommunicationServer::InitializeDelegate (lldb_private::NativeProcessProtocol *process)
657{
658 assert (process && "process cannot be NULL");
659 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
660 if (log)
661 {
662 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
663 __FUNCTION__,
664 process->GetID (),
665 StateAsCString (process->GetState ()));
666 }
667}
668
669GDBRemoteCommunication::PacketResult
670GDBRemoteCommunicationServer::SendWResponse (lldb_private::NativeProcessProtocol *process)
671{
672 assert (process && "process cannot be NULL");
673 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
674
675 // send W notification
676 ExitType exit_type = ExitType::eExitTypeInvalid;
677 int return_code = 0;
678 std::string exit_description;
679
680 const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
681 if (!got_exit_info)
682 {
683 if (log)
684 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
685
686 StreamGDBRemote response;
687 response.PutChar ('E');
688 response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
689 return SendPacketNoLock(response.GetData(), response.GetSize());
690 }
691 else
692 {
693 if (log)
694 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 ());
695
696 StreamGDBRemote response;
697
698 char return_type_code;
699 switch (exit_type)
700 {
701 case ExitType::eExitTypeExit: return_type_code = 'W'; break;
702 case ExitType::eExitTypeSignal: return_type_code = 'X'; break;
703 case ExitType::eExitTypeStop: return_type_code = 'S'; break;
704
705 case ExitType::eExitTypeInvalid:
706 default: return_type_code = 'E'; break;
707 }
708 response.PutChar (return_type_code);
709
710 // POSIX exit status limited to unsigned 8 bits.
711 response.PutHex8 (return_code);
712
713 return SendPacketNoLock(response.GetData(), response.GetSize());
714 }
715}
716
717static void
718AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
719{
720 int64_t i;
721 if (swap)
722 {
723 for (i = buf_size-1; i >= 0; i--)
724 response.PutHex8 (buf[i]);
725 }
726 else
727 {
728 for (i = 0; i < buf_size; i++)
729 response.PutHex8 (buf[i]);
730 }
731}
732
733static void
734WriteRegisterValueInHexFixedWidth (StreamString &response,
735 NativeRegisterContextSP &reg_ctx_sp,
736 const RegisterInfo &reg_info,
737 const RegisterValue *reg_value_p)
738{
739 RegisterValue reg_value;
740 if (!reg_value_p)
741 {
742 Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
743 if (error.Success ())
744 reg_value_p = &reg_value;
745 // else log.
746 }
747
748 if (reg_value_p)
749 {
750 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
751 }
752 else
753 {
754 // Zero-out any unreadable values.
755 if (reg_info.byte_size > 0)
756 {
757 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
758 AppendHexValue (response, zeros.data(), zeros.size(), false);
759 }
760 }
761}
762
763// WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
764
765
766static void
767WriteGdbRegnumWithFixedWidthHexRegisterValue (StreamString &response,
768 NativeRegisterContextSP &reg_ctx_sp,
769 const RegisterInfo &reg_info,
770 const RegisterValue &reg_value)
771{
772 // Output the register number as 'NN:VVVVVVVV;' where NN is a 2 bytes HEX
773 // gdb register number, and VVVVVVVV is the correct number of hex bytes
774 // as ASCII for the register value.
775 if (reg_info.kinds[eRegisterKindGDB] == LLDB_INVALID_REGNUM)
776 return;
777
778 response.Printf ("%.02x:", reg_info.kinds[eRegisterKindGDB]);
779 WriteRegisterValueInHexFixedWidth (response, reg_ctx_sp, reg_info, &reg_value);
780 response.PutChar (';');
781}
782
783
784GDBRemoteCommunication::PacketResult
785GDBRemoteCommunicationServer::SendStopReplyPacketForThread (lldb::tid_t tid)
786{
787 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
788
789 // Ensure we're llgs.
790 if (!IsGdbServer ())
791 {
792 // Only supported on llgs
793 return SendUnimplementedResponse ("");
794 }
795
796 // Ensure we have a debugged process.
797 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
798 return SendErrorResponse (50);
799
800 if (log)
801 log->Printf ("GDBRemoteCommunicationServer::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
802 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
803
804 // Ensure we can get info on the given thread.
805 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
806 if (!thread_sp)
807 return SendErrorResponse (51);
808
809 // Grab the reason this thread stopped.
810 struct ThreadStopInfo tid_stop_info;
811 if (!thread_sp->GetStopReason (tid_stop_info))
812 return SendErrorResponse (52);
813
814 const bool did_exec = tid_stop_info.reason == eStopReasonExec;
815 // FIXME implement register handling for exec'd inferiors.
816 // if (did_exec)
817 // {
818 // const bool force = true;
819 // InitializeRegisters(force);
820 // }
821
822 StreamString response;
823 // Output the T packet with the thread
824 response.PutChar ('T');
825 int signum = tid_stop_info.details.signal.signo;
826 if (log)
827 {
828 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
829 __FUNCTION__,
830 m_debugged_process_sp->GetID (),
831 tid,
832 signum,
833 tid_stop_info.reason,
834 tid_stop_info.details.exception.type);
835 }
836
837 switch (tid_stop_info.reason)
838 {
839 case eStopReasonSignal:
840 case eStopReasonException:
841 signum = thread_sp->TranslateStopInfoToGdbSignal (tid_stop_info);
842 break;
843 default:
844 signum = 0;
845 if (log)
846 {
847 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " has stop reason %d, using signo = 0 in stop reply response",
848 __FUNCTION__,
849 m_debugged_process_sp->GetID (),
850 tid,
851 tid_stop_info.reason);
852 }
853 break;
854 }
855
856 // Print the signal number.
857 response.PutHex8 (signum & 0xff);
858
859 // Include the tid.
860 response.Printf ("thread:%" PRIx64 ";", tid);
861
862 // Include the thread name if there is one.
863 const char *thread_name = thread_sp->GetName ();
864 if (thread_name && thread_name[0])
865 {
866 size_t thread_name_len = strlen(thread_name);
867
868 if (::strcspn (thread_name, "$#+-;:") == thread_name_len)
869 {
870 response.PutCString ("name:");
871 response.PutCString (thread_name);
872 }
873 else
874 {
875 // The thread name contains special chars, send as hex bytes.
876 response.PutCString ("hexname:");
877 response.PutCStringAsRawHex8 (thread_name);
878 }
879 response.PutChar (';');
880 }
881
882 // FIXME look for analog
883 // thread_identifier_info_data_t thread_ident_info;
884 // if (DNBThreadGetIdentifierInfo (pid, tid, &thread_ident_info))
885 // {
886 // if (thread_ident_info.dispatch_qaddr != 0)
887 // ostrm << std::hex << "qaddr:" << thread_ident_info.dispatch_qaddr << ';';
888 // }
889
890 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
891 // will send all thread IDs back in the "threads" key whose value is
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000892 // a list of hex thread IDs separated by commas:
Todd Fialaaf245d12014-06-30 21:05:18 +0000893 // "threads:10a,10b,10c;"
894 // This will save the debugger from having to send a pair of qfThreadInfo
895 // and qsThreadInfo packets, but it also might take a lot of room in the
896 // stop reply packet, so it must be enabled only on systems where there
897 // are no limits on packet lengths.
898 if (m_list_threads_in_stop_reply)
899 {
900 response.PutCString ("threads:");
901
902 uint32_t thread_index = 0;
903 NativeThreadProtocolSP listed_thread_sp;
904 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))
905 {
906 if (thread_index > 0)
907 response.PutChar (',');
908 response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
909 }
910 response.PutChar (';');
911 }
912
913 //
914 // Expedite registers.
915 //
916
917 // Grab the register context.
918 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
919 if (reg_ctx_sp)
920 {
921 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
922 const RegisterSet *reg_set_p;
923 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
924 {
925 if (log)
926 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);
927
928 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
929 {
930 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
931 if (reg_info_p == nullptr)
932 {
933 if (log)
934 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);
935 }
936 else if (reg_info_p->value_regs == nullptr)
937 {
938 // Only expediate registers that are not contained in other registers.
939 RegisterValue reg_value;
940 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
941 if (error.Success ())
942 WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
943 else
944 {
945 if (log)
946 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 ());
947
948 }
949 }
950 }
951 }
952 }
953
954 if (did_exec)
955 {
956 response.PutCString ("reason:exec;");
957 }
958 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
959 {
960 response.PutCString ("metype:");
961 response.PutHex64 (tid_stop_info.details.exception.type);
962 response.PutCString (";mecount:");
963 response.PutHex32 (tid_stop_info.details.exception.data_count);
964 response.PutChar (';');
965
966 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
967 {
968 response.PutCString ("medata:");
969 response.PutHex64 (tid_stop_info.details.exception.data[i]);
970 response.PutChar (';');
971 }
972 }
973
974 return SendPacketNoLock (response.GetData(), response.GetSize());
975}
976
977void
978GDBRemoteCommunicationServer::HandleInferiorState_Exited (lldb_private::NativeProcessProtocol *process)
979{
980 assert (process && "process cannot be NULL");
981
982 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
983 if (log)
984 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
985
986 // Send the exit result, and don't flush output.
987 // Note: flushing output here would join the inferior stdio reflection thread, which
988 // would gunk up the waitpid monitor thread that is calling this.
989 PacketResult result = SendStopReasonForState (StateType::eStateExited, false);
990 if (result != PacketResult::Success)
991 {
992 if (log)
993 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
994 }
995
996 // Remove the process from the list of spawned pids.
997 {
998 Mutex::Locker locker (m_spawned_pids_mutex);
999 if (m_spawned_pids.erase (process->GetID ()) < 1)
1000 {
1001 if (log)
1002 log->Printf ("GDBRemoteCommunicationServer::%s failed to remove PID %" PRIu64 " from the spawned pids list", __FUNCTION__, process->GetID ());
1003
1004 }
1005 }
1006
1007 // FIXME can't do this yet - since process state propagation is currently
1008 // synchronous, it is running off the NativeProcessProtocol's innards and
1009 // will tear down the NPP while it still has code to execute.
1010#if 0
1011 // Clear the NativeProcessProtocol pointer.
1012 {
1013 Mutex::Locker locker (m_debugged_process_mutex);
1014 m_debugged_process_sp.reset();
1015 }
1016#endif
1017
1018 // Close the pipe to the inferior terminal i/o if we launched it
1019 // and set one up. Otherwise, 'k' and its flush of stdio could
1020 // end up waiting on a thread join that will never end. Consider
1021 // adding a timeout to the connection thread join call so we
1022 // can avoid that scenario altogether.
1023 MaybeCloseInferiorTerminalConnection ();
1024
1025 // We are ready to exit the debug monitor.
1026 m_exit_now = true;
1027}
1028
1029void
1030GDBRemoteCommunicationServer::HandleInferiorState_Stopped (lldb_private::NativeProcessProtocol *process)
1031{
1032 assert (process && "process cannot be NULL");
1033
1034 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1035 if (log)
1036 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
1037
1038 // Send the stop reason unless this is the stop after the
1039 // launch or attach.
1040 switch (m_inferior_prev_state)
1041 {
1042 case eStateLaunching:
1043 case eStateAttaching:
1044 // Don't send anything per debugserver behavior.
1045 break;
1046 default:
1047 // In all other cases, send the stop reason.
1048 PacketResult result = SendStopReasonForState (StateType::eStateStopped, false);
1049 if (result != PacketResult::Success)
1050 {
1051 if (log)
1052 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1053 }
1054 break;
1055 }
1056}
1057
1058void
1059GDBRemoteCommunicationServer::ProcessStateChanged (lldb_private::NativeProcessProtocol *process, lldb::StateType state)
1060{
1061 assert (process && "process cannot be NULL");
1062 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1063 if (log)
1064 {
1065 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
1066 __FUNCTION__,
1067 process->GetID (),
1068 StateAsCString (state));
1069 }
1070
1071 switch (state)
1072 {
1073 case StateType::eStateExited:
1074 HandleInferiorState_Exited (process);
1075 break;
1076
1077 case StateType::eStateStopped:
1078 HandleInferiorState_Stopped (process);
1079 break;
1080
1081 default:
1082 if (log)
1083 {
1084 log->Printf ("GDBRemoteCommunicationServer::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
1085 __FUNCTION__,
1086 process->GetID (),
1087 StateAsCString (state));
1088 }
1089 break;
1090 }
1091
1092 // Remember the previous state reported to us.
1093 m_inferior_prev_state = state;
1094}
1095
1096GDBRemoteCommunication::PacketResult
1097GDBRemoteCommunicationServer::SendONotification (const char *buffer, uint32_t len)
1098{
1099 if ((buffer == nullptr) || (len == 0))
1100 {
1101 // Nothing to send.
1102 return PacketResult::Success;
1103 }
1104
1105 StreamString response;
1106 response.PutChar ('O');
1107 response.PutBytesAsRawHex8 (buffer, len);
1108
1109 return SendPacketNoLock (response.GetData (), response.GetSize ());
1110}
1111
1112lldb_private::Error
1113GDBRemoteCommunicationServer::SetSTDIOFileDescriptor (int fd)
1114{
1115 Error error;
1116
1117 // Set up the Read Thread for reading/handling process I/O
1118 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
1119 if (!conn_up)
1120 {
1121 error.SetErrorString ("failed to create ConnectionFileDescriptor");
1122 return error;
1123 }
1124
1125 m_stdio_communication.SetConnection (conn_up.release());
1126 if (!m_stdio_communication.IsConnected ())
1127 {
1128 error.SetErrorString ("failed to set connection for inferior I/O communication");
1129 return error;
1130 }
1131
1132 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1133 m_stdio_communication.StartReadThread();
1134
1135 return error;
1136}
1137
1138void
1139GDBRemoteCommunicationServer::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1140{
1141 GDBRemoteCommunicationServer *server = reinterpret_cast<GDBRemoteCommunicationServer*> (baton);
1142 static_cast<void> (server->SendONotification (static_cast<const char *>(src), src_len));
1143}
1144
Greg Clayton3dedae12013-12-06 21:45:27 +00001145GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001146GDBRemoteCommunicationServer::SendUnimplementedResponse (const char *)
Greg Clayton576d8832011-03-22 04:00:09 +00001147{
Greg Clayton32e0a752011-03-30 18:16:51 +00001148 // TODO: Log the packet we aren't handling...
Greg Clayton37a0a242012-04-11 00:24:49 +00001149 return SendPacketNoLock ("", 0);
Greg Clayton576d8832011-03-22 04:00:09 +00001150}
1151
Todd Fialaaf245d12014-06-30 21:05:18 +00001152
Greg Clayton3dedae12013-12-06 21:45:27 +00001153GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001154GDBRemoteCommunicationServer::SendErrorResponse (uint8_t err)
1155{
1156 char packet[16];
1157 int packet_len = ::snprintf (packet, sizeof(packet), "E%2.2x", err);
Andy Gibbsa297a972013-06-19 19:04:53 +00001158 assert (packet_len < (int)sizeof(packet));
Greg Clayton37a0a242012-04-11 00:24:49 +00001159 return SendPacketNoLock (packet, packet_len);
Greg Clayton32e0a752011-03-30 18:16:51 +00001160}
1161
Todd Fialaaf245d12014-06-30 21:05:18 +00001162GDBRemoteCommunication::PacketResult
1163GDBRemoteCommunicationServer::SendIllFormedResponse (const StringExtractorGDBRemote &failed_packet, const char *message)
1164{
1165 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
1166 if (log)
1167 log->Printf ("GDBRemoteCommunicationServer::%s: ILLFORMED: '%s' (%s)", __FUNCTION__, failed_packet.GetStringRef ().c_str (), message ? message : "");
1168 return SendErrorResponse (0x03);
1169}
Greg Clayton32e0a752011-03-30 18:16:51 +00001170
Greg Clayton3dedae12013-12-06 21:45:27 +00001171GDBRemoteCommunication::PacketResult
Greg Clayton1cb64962011-03-24 04:28:38 +00001172GDBRemoteCommunicationServer::SendOKResponse ()
1173{
Greg Clayton37a0a242012-04-11 00:24:49 +00001174 return SendPacketNoLock ("OK", 2);
Greg Clayton1cb64962011-03-24 04:28:38 +00001175}
1176
1177bool
1178GDBRemoteCommunicationServer::HandshakeWithClient(Error *error_ptr)
1179{
Greg Clayton3dedae12013-12-06 21:45:27 +00001180 return GetAck() == PacketResult::Success;
Greg Clayton1cb64962011-03-24 04:28:38 +00001181}
Greg Clayton576d8832011-03-22 04:00:09 +00001182
Greg Clayton3dedae12013-12-06 21:45:27 +00001183GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001184GDBRemoteCommunicationServer::Handle_qHostInfo (StringExtractorGDBRemote &packet)
Greg Clayton576d8832011-03-22 04:00:09 +00001185{
1186 StreamString response;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001187
Greg Clayton576d8832011-03-22 04:00:09 +00001188 // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00
1189
1190 ArchSpec host_arch (Host::GetArchitecture ());
Greg Clayton576d8832011-03-22 04:00:09 +00001191 const llvm::Triple &host_triple = host_arch.GetTriple();
Greg Clayton1cb64962011-03-24 04:28:38 +00001192 response.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00001193 response.PutCString(host_triple.getTriple().c_str());
Greg Clayton1cb64962011-03-24 04:28:38 +00001194 response.Printf (";ptrsize:%u;",host_arch.GetAddressByteSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001195
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001196 const char* distribution_id = host_arch.GetDistributionId ().AsCString ();
1197 if (distribution_id)
1198 {
1199 response.PutCString("distribution_id:");
1200 response.PutCStringAsRawHex8(distribution_id);
1201 response.PutCString(";");
1202 }
1203
Todd Fialaaf245d12014-06-30 21:05:18 +00001204 // Only send out MachO info when lldb-platform/llgs is running on a MachO host.
1205#if defined(__APPLE__)
Greg Clayton1cb64962011-03-24 04:28:38 +00001206 uint32_t cpu = host_arch.GetMachOCPUType();
1207 uint32_t sub = host_arch.GetMachOCPUSubType();
1208 if (cpu != LLDB_INVALID_CPUTYPE)
1209 response.Printf ("cputype:%u;", cpu);
1210 if (sub != LLDB_INVALID_CPUTYPE)
1211 response.Printf ("cpusubtype:%u;", sub);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001212
Enrico Granata1c5431a2012-07-13 23:55:22 +00001213 if (cpu == ArchSpec::kCore_arm_any)
Enrico Granataf04a2192012-07-13 23:18:48 +00001214 response.Printf("watchpoint_exceptions_received:before;"); // On armv7 we use "synchronous" watchpoints which means the exception is delivered before the instruction executes.
1215 else
1216 response.Printf("watchpoint_exceptions_received:after;");
Todd Fialaaf245d12014-06-30 21:05:18 +00001217#else
1218 response.Printf("watchpoint_exceptions_received:after;");
1219#endif
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001220
Greg Clayton576d8832011-03-22 04:00:09 +00001221 switch (lldb::endian::InlHostByteOrder())
1222 {
1223 case eByteOrderBig: response.PutCString ("endian:big;"); break;
1224 case eByteOrderLittle: response.PutCString ("endian:little;"); break;
1225 case eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1226 default: response.PutCString ("endian:unknown;"); break;
1227 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001228
Greg Clayton1cb64962011-03-24 04:28:38 +00001229 uint32_t major = UINT32_MAX;
1230 uint32_t minor = UINT32_MAX;
1231 uint32_t update = UINT32_MAX;
1232 if (Host::GetOSVersion (major, minor, update))
1233 {
1234 if (major != UINT32_MAX)
1235 {
1236 response.Printf("os_version:%u", major);
1237 if (minor != UINT32_MAX)
1238 {
1239 response.Printf(".%u", minor);
1240 if (update != UINT32_MAX)
1241 response.Printf(".%u", update);
1242 }
1243 response.PutChar(';');
1244 }
1245 }
1246
1247 std::string s;
1248 if (Host::GetOSBuildString (s))
1249 {
1250 response.PutCString ("os_build:");
1251 response.PutCStringAsRawHex8(s.c_str());
1252 response.PutChar(';');
1253 }
1254 if (Host::GetOSKernelDescription (s))
1255 {
1256 response.PutCString ("os_kernel:");
1257 response.PutCStringAsRawHex8(s.c_str());
1258 response.PutChar(';');
1259 }
Greg Clayton2b98c562013-11-22 18:53:12 +00001260#if defined(__APPLE__)
1261
Todd Fiala013434e2014-07-09 01:29:05 +00001262#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001263 // For iOS devices, we are connected through a USB Mux so we never pretend
1264 // to actually have a hostname as far as the remote lldb that is connecting
1265 // to this lldb-platform is concerned
1266 response.PutCString ("hostname:");
Greg Clayton16810922014-02-27 19:38:18 +00001267 response.PutCStringAsRawHex8("127.0.0.1");
Greg Clayton2b98c562013-11-22 18:53:12 +00001268 response.PutChar(';');
Todd Fiala013434e2014-07-09 01:29:05 +00001269#else // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton1cb64962011-03-24 04:28:38 +00001270 if (Host::GetHostname (s))
1271 {
1272 response.PutCString ("hostname:");
1273 response.PutCStringAsRawHex8(s.c_str());
1274 response.PutChar(';');
1275 }
Todd Fiala013434e2014-07-09 01:29:05 +00001276#endif // #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001277
1278#else // #if defined(__APPLE__)
1279 if (Host::GetHostname (s))
1280 {
1281 response.PutCString ("hostname:");
1282 response.PutCStringAsRawHex8(s.c_str());
1283 response.PutChar(';');
1284 }
1285#endif // #if defined(__APPLE__)
1286
Greg Clayton3dedae12013-12-06 21:45:27 +00001287 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001288}
Greg Clayton1cb64962011-03-24 04:28:38 +00001289
Greg Clayton32e0a752011-03-30 18:16:51 +00001290static void
Greg Clayton8b82f082011-04-12 05:54:46 +00001291CreateProcessInfoResponse (const ProcessInstanceInfo &proc_info, StreamString &response)
Greg Clayton32e0a752011-03-30 18:16:51 +00001292{
Daniel Malead01b2952012-11-29 21:49:15 +00001293 response.Printf ("pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
Greg Clayton32e0a752011-03-30 18:16:51 +00001294 proc_info.GetProcessID(),
1295 proc_info.GetParentProcessID(),
Greg Clayton8b82f082011-04-12 05:54:46 +00001296 proc_info.GetUserID(),
1297 proc_info.GetGroupID(),
Greg Clayton32e0a752011-03-30 18:16:51 +00001298 proc_info.GetEffectiveUserID(),
1299 proc_info.GetEffectiveGroupID());
1300 response.PutCString ("name:");
1301 response.PutCStringAsRawHex8(proc_info.GetName());
1302 response.PutChar(';');
1303 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1304 if (proc_arch.IsValid())
1305 {
1306 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1307 response.PutCString("triple:");
Matthew Gardinerf39ebbe2014-08-01 05:12:23 +00001308 response.PutCString(proc_triple.getTriple().c_str());
Greg Clayton32e0a752011-03-30 18:16:51 +00001309 response.PutChar(';');
1310 }
1311}
Greg Clayton1cb64962011-03-24 04:28:38 +00001312
Todd Fialaaf245d12014-06-30 21:05:18 +00001313static void
1314CreateProcessInfoResponse_DebugServerStyle (const ProcessInstanceInfo &proc_info, StreamString &response)
1315{
1316 response.Printf ("pid:%" PRIx64 ";parent-pid:%" PRIx64 ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1317 proc_info.GetProcessID(),
1318 proc_info.GetParentProcessID(),
1319 proc_info.GetUserID(),
1320 proc_info.GetGroupID(),
1321 proc_info.GetEffectiveUserID(),
1322 proc_info.GetEffectiveGroupID());
1323
1324 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1325 if (proc_arch.IsValid())
1326 {
1327 const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1328 if (cpu_type != 0)
1329 response.Printf ("cputype:%" PRIx32 ";", cpu_type);
1330
1331 const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1332 if (cpu_subtype != 0)
1333 response.Printf ("cpusubtype:%" PRIx32 ";", cpu_subtype);
1334
1335 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1336 const std::string vendor = proc_triple.getVendorName ();
1337 if (!vendor.empty ())
1338 response.Printf ("vendor:%s;", vendor.c_str ());
1339
1340 std::string ostype = proc_triple.getOSName ();
1341 // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1342 if (proc_triple.getVendor () == llvm::Triple::Apple)
1343 {
1344 switch (proc_triple.getArch ())
1345 {
1346 case llvm::Triple::arm:
Todd Fialad8eaa172014-07-23 14:37:35 +00001347 case llvm::Triple::aarch64:
Todd Fialaaf245d12014-06-30 21:05:18 +00001348 ostype = "ios";
1349 break;
1350 default:
1351 // No change.
1352 break;
1353 }
1354 }
1355 response.Printf ("ostype:%s;", ostype.c_str ());
1356
1357
1358 switch (proc_arch.GetByteOrder ())
1359 {
1360 case lldb::eByteOrderLittle: response.PutCString ("endian:little;"); break;
1361 case lldb::eByteOrderBig: response.PutCString ("endian:big;"); break;
1362 case lldb::eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1363 default:
1364 // Nothing.
1365 break;
1366 }
1367
1368 if (proc_triple.isArch64Bit ())
1369 response.PutCString ("ptrsize:8;");
1370 else if (proc_triple.isArch32Bit ())
1371 response.PutCString ("ptrsize:4;");
1372 else if (proc_triple.isArch16Bit ())
1373 response.PutCString ("ptrsize:2;");
1374 }
1375
1376}
1377
1378
1379GDBRemoteCommunication::PacketResult
1380GDBRemoteCommunicationServer::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1381{
1382 // Only the gdb server handles this.
1383 if (!IsGdbServer ())
1384 return SendUnimplementedResponse (packet.GetStringRef ().c_str ());
1385
1386 // Fail if we don't have a current process.
1387 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1388 return SendErrorResponse (68);
1389
1390 ProcessInstanceInfo proc_info;
1391 if (Host::GetProcessInfo (m_debugged_process_sp->GetID (), proc_info))
1392 {
1393 StreamString response;
1394 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1395 return SendPacketNoLock (response.GetData (), response.GetSize ());
1396 }
1397
1398 return SendErrorResponse (1);
1399}
1400
Greg Clayton3dedae12013-12-06 21:45:27 +00001401GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001402GDBRemoteCommunicationServer::Handle_qProcessInfoPID (StringExtractorGDBRemote &packet)
Greg Clayton1cb64962011-03-24 04:28:38 +00001403{
Greg Clayton32e0a752011-03-30 18:16:51 +00001404 // Packet format: "qProcessInfoPID:%i" where %i is the pid
Greg Clayton8b82f082011-04-12 05:54:46 +00001405 packet.SetFilePos(::strlen ("qProcessInfoPID:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001406 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID);
1407 if (pid != LLDB_INVALID_PROCESS_ID)
1408 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001409 ProcessInstanceInfo proc_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00001410 if (Host::GetProcessInfo(pid, proc_info))
1411 {
1412 StreamString response;
1413 CreateProcessInfoResponse (proc_info, response);
Greg Clayton37a0a242012-04-11 00:24:49 +00001414 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001415 }
1416 }
1417 return SendErrorResponse (1);
1418}
1419
Greg Clayton3dedae12013-12-06 21:45:27 +00001420GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001421GDBRemoteCommunicationServer::Handle_qfProcessInfo (StringExtractorGDBRemote &packet)
1422{
1423 m_proc_infos_index = 0;
1424 m_proc_infos.Clear();
1425
Greg Clayton8b82f082011-04-12 05:54:46 +00001426 ProcessInstanceInfoMatch match_info;
1427 packet.SetFilePos(::strlen ("qfProcessInfo"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001428 if (packet.GetChar() == ':')
1429 {
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001430
Greg Clayton32e0a752011-03-30 18:16:51 +00001431 std::string key;
1432 std::string value;
1433 while (packet.GetNameColonValue(key, value))
1434 {
1435 bool success = true;
1436 if (key.compare("name") == 0)
1437 {
1438 StringExtractor extractor;
1439 extractor.GetStringRef().swap(value);
1440 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00001441 match_info.GetProcessInfo().GetExecutableFile().SetFile(value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00001442 }
1443 else if (key.compare("name_match") == 0)
1444 {
1445 if (value.compare("equals") == 0)
1446 {
1447 match_info.SetNameMatchType (eNameMatchEquals);
1448 }
1449 else if (value.compare("starts_with") == 0)
1450 {
1451 match_info.SetNameMatchType (eNameMatchStartsWith);
1452 }
1453 else if (value.compare("ends_with") == 0)
1454 {
1455 match_info.SetNameMatchType (eNameMatchEndsWith);
1456 }
1457 else if (value.compare("contains") == 0)
1458 {
1459 match_info.SetNameMatchType (eNameMatchContains);
1460 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001461 else if (value.compare("regex") == 0)
Greg Clayton32e0a752011-03-30 18:16:51 +00001462 {
1463 match_info.SetNameMatchType (eNameMatchRegularExpression);
1464 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001465 else
Greg Clayton32e0a752011-03-30 18:16:51 +00001466 {
1467 success = false;
1468 }
1469 }
1470 else if (key.compare("pid") == 0)
1471 {
1472 match_info.GetProcessInfo().SetProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1473 }
1474 else if (key.compare("parent_pid") == 0)
1475 {
1476 match_info.GetProcessInfo().SetParentProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1477 }
1478 else if (key.compare("uid") == 0)
1479 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001480 match_info.GetProcessInfo().SetUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001481 }
1482 else if (key.compare("gid") == 0)
1483 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001484 match_info.GetProcessInfo().SetGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001485 }
1486 else if (key.compare("euid") == 0)
1487 {
1488 match_info.GetProcessInfo().SetEffectiveUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1489 }
1490 else if (key.compare("egid") == 0)
1491 {
1492 match_info.GetProcessInfo().SetEffectiveGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1493 }
1494 else if (key.compare("all_users") == 0)
1495 {
1496 match_info.SetMatchAllUsers(Args::StringToBoolean(value.c_str(), false, &success));
1497 }
1498 else if (key.compare("triple") == 0)
1499 {
Greg Claytoneb0103f2011-04-07 22:46:35 +00001500 match_info.GetProcessInfo().GetArchitecture().SetTriple (value.c_str(), NULL);
Greg Clayton32e0a752011-03-30 18:16:51 +00001501 }
1502 else
1503 {
1504 success = false;
1505 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001506
Greg Clayton32e0a752011-03-30 18:16:51 +00001507 if (!success)
1508 return SendErrorResponse (2);
1509 }
1510 }
1511
1512 if (Host::FindProcesses (match_info, m_proc_infos))
1513 {
1514 // We found something, return the first item by calling the get
1515 // subsequent process info packet handler...
1516 return Handle_qsProcessInfo (packet);
1517 }
1518 return SendErrorResponse (3);
1519}
1520
Greg Clayton3dedae12013-12-06 21:45:27 +00001521GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001522GDBRemoteCommunicationServer::Handle_qsProcessInfo (StringExtractorGDBRemote &packet)
1523{
1524 if (m_proc_infos_index < m_proc_infos.GetSize())
1525 {
1526 StreamString response;
1527 CreateProcessInfoResponse (m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
1528 ++m_proc_infos_index;
Greg Clayton37a0a242012-04-11 00:24:49 +00001529 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001530 }
1531 return SendErrorResponse (4);
1532}
1533
Greg Clayton3dedae12013-12-06 21:45:27 +00001534GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001535GDBRemoteCommunicationServer::Handle_qUserName (StringExtractorGDBRemote &packet)
1536{
1537 // Packet format: "qUserName:%i" where %i is the uid
Greg Clayton8b82f082011-04-12 05:54:46 +00001538 packet.SetFilePos(::strlen ("qUserName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001539 uint32_t uid = packet.GetU32 (UINT32_MAX);
1540 if (uid != UINT32_MAX)
1541 {
1542 std::string name;
1543 if (Host::GetUserName (uid, name))
1544 {
1545 StreamString response;
1546 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001547 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001548 }
1549 }
1550 return SendErrorResponse (5);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001551
Greg Clayton32e0a752011-03-30 18:16:51 +00001552}
1553
Greg Clayton3dedae12013-12-06 21:45:27 +00001554GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001555GDBRemoteCommunicationServer::Handle_qGroupName (StringExtractorGDBRemote &packet)
1556{
1557 // Packet format: "qGroupName:%i" where %i is the gid
Greg Clayton8b82f082011-04-12 05:54:46 +00001558 packet.SetFilePos(::strlen ("qGroupName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001559 uint32_t gid = packet.GetU32 (UINT32_MAX);
1560 if (gid != UINT32_MAX)
1561 {
1562 std::string name;
1563 if (Host::GetGroupName (gid, name))
1564 {
1565 StreamString response;
1566 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001567 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001568 }
1569 }
1570 return SendErrorResponse (6);
1571}
1572
Greg Clayton3dedae12013-12-06 21:45:27 +00001573GDBRemoteCommunication::PacketResult
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001574GDBRemoteCommunicationServer::Handle_qSpeedTest (StringExtractorGDBRemote &packet)
1575{
Greg Clayton8b82f082011-04-12 05:54:46 +00001576 packet.SetFilePos(::strlen ("qSpeedTest:"));
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001577
1578 std::string key;
1579 std::string value;
1580 bool success = packet.GetNameColonValue(key, value);
1581 if (success && key.compare("response_size") == 0)
1582 {
1583 uint32_t response_size = Args::StringToUInt32(value.c_str(), 0, 0, &success);
1584 if (success)
1585 {
1586 if (response_size == 0)
1587 return SendOKResponse();
1588 StreamString response;
1589 uint32_t bytes_left = response_size;
1590 response.PutCString("data:");
1591 while (bytes_left > 0)
1592 {
1593 if (bytes_left >= 26)
1594 {
1595 response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1596 bytes_left -= 26;
1597 }
1598 else
1599 {
1600 response.Printf ("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1601 bytes_left = 0;
1602 }
1603 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001604 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001605 }
1606 }
1607 return SendErrorResponse (7);
1608}
Greg Clayton8b82f082011-04-12 05:54:46 +00001609
Greg Clayton8b82f082011-04-12 05:54:46 +00001610//
1611//static bool
1612//WaitForProcessToSIGSTOP (const lldb::pid_t pid, const int timeout_in_seconds)
1613//{
1614// const int time_delta_usecs = 100000;
1615// const int num_retries = timeout_in_seconds/time_delta_usecs;
1616// for (int i=0; i<num_retries; i++)
1617// {
1618// struct proc_bsdinfo bsd_info;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001619// int error = ::proc_pidinfo (pid, PROC_PIDTBSDINFO,
1620// (uint64_t) 0,
1621// &bsd_info,
Greg Clayton8b82f082011-04-12 05:54:46 +00001622// PROC_PIDTBSDINFO_SIZE);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001623//
Greg Clayton8b82f082011-04-12 05:54:46 +00001624// switch (error)
1625// {
1626// case EINVAL:
1627// case ENOTSUP:
1628// case ESRCH:
1629// case EPERM:
1630// return false;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001631//
Greg Clayton8b82f082011-04-12 05:54:46 +00001632// default:
1633// break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001634//
Greg Clayton8b82f082011-04-12 05:54:46 +00001635// case 0:
1636// if (bsd_info.pbi_status == SSTOP)
1637// return true;
1638// }
1639// ::usleep (time_delta_usecs);
1640// }
1641// return false;
1642//}
1643
Greg Clayton3dedae12013-12-06 21:45:27 +00001644GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001645GDBRemoteCommunicationServer::Handle_A (StringExtractorGDBRemote &packet)
1646{
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001647 // The 'A' packet is the most over designed packet ever here with
1648 // redundant argument indexes, redundant argument lengths and needed hex
1649 // encoded argument string values. Really all that is needed is a comma
Greg Clayton8b82f082011-04-12 05:54:46 +00001650 // separated hex encoded argument value list, but we will stay true to the
1651 // documented version of the 'A' packet here...
1652
Todd Fialaaf245d12014-06-30 21:05:18 +00001653 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1654 int actual_arg_index = 0;
1655
Greg Clayton8b82f082011-04-12 05:54:46 +00001656 packet.SetFilePos(1); // Skip the 'A'
1657 bool success = true;
1658 while (success && packet.GetBytesLeft() > 0)
1659 {
1660 // Decode the decimal argument string length. This length is the
1661 // number of hex nibbles in the argument string value.
1662 const uint32_t arg_len = packet.GetU32(UINT32_MAX);
1663 if (arg_len == UINT32_MAX)
1664 success = false;
1665 else
1666 {
1667 // Make sure the argument hex string length is followed by a comma
1668 if (packet.GetChar() != ',')
1669 success = false;
1670 else
1671 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001672 // Decode the argument index. We ignore this really because
Greg Clayton8b82f082011-04-12 05:54:46 +00001673 // who would really send down the arguments in a random order???
1674 const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
1675 if (arg_idx == UINT32_MAX)
1676 success = false;
1677 else
1678 {
1679 // Make sure the argument index is followed by a comma
1680 if (packet.GetChar() != ',')
1681 success = false;
1682 else
1683 {
1684 // Decode the argument string value from hex bytes
1685 // back into a UTF8 string and make sure the length
1686 // matches the one supplied in the packet
1687 std::string arg;
Todd Fialaaf245d12014-06-30 21:05:18 +00001688 if (packet.GetHexByteStringFixedLength(arg, arg_len) != (arg_len / 2))
Greg Clayton8b82f082011-04-12 05:54:46 +00001689 success = false;
1690 else
1691 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001692 // If there are any bytes left
Greg Clayton8b82f082011-04-12 05:54:46 +00001693 if (packet.GetBytesLeft())
1694 {
1695 if (packet.GetChar() != ',')
1696 success = false;
1697 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001698
Greg Clayton8b82f082011-04-12 05:54:46 +00001699 if (success)
1700 {
1701 if (arg_idx == 0)
1702 m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), false);
1703 m_process_launch_info.GetArguments().AppendArgument(arg.c_str());
Todd Fialaaf245d12014-06-30 21:05:18 +00001704 if (log)
1705 log->Printf ("GDBRemoteCommunicationServer::%s added arg %d: \"%s\"", __FUNCTION__, actual_arg_index, arg.c_str ());
1706 ++actual_arg_index;
Greg Clayton8b82f082011-04-12 05:54:46 +00001707 }
1708 }
1709 }
1710 }
1711 }
1712 }
1713 }
1714
1715 if (success)
1716 {
Todd Fiala9f377372014-01-27 20:44:50 +00001717 m_process_launch_error = LaunchProcess ();
Greg Clayton8b82f082011-04-12 05:54:46 +00001718 if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1719 {
1720 return SendOKResponse ();
1721 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001722 else
1723 {
1724 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1725 if (log)
1726 log->Printf("GDBRemoteCommunicationServer::%s failed to launch exe: %s",
1727 __FUNCTION__,
1728 m_process_launch_error.AsCString());
1729
1730 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001731 }
1732 return SendErrorResponse (8);
1733}
1734
Greg Clayton3dedae12013-12-06 21:45:27 +00001735GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001736GDBRemoteCommunicationServer::Handle_qC (StringExtractorGDBRemote &packet)
1737{
Greg Clayton8b82f082011-04-12 05:54:46 +00001738 StreamString response;
Todd Fialaaf245d12014-06-30 21:05:18 +00001739
1740 if (IsGdbServer ())
Greg Clayton8b82f082011-04-12 05:54:46 +00001741 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001742 // Fail if we don't have a current process.
1743 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1744 return SendErrorResponse (68);
1745
1746 // Make sure we set the current thread so g and p packets return
1747 // the data the gdb will expect.
1748 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1749 SetCurrentThreadID (tid);
1750
1751 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1752 if (!thread_sp)
1753 return SendErrorResponse (69);
1754
1755 response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1756 }
1757 else
1758 {
1759 // NOTE: lldb should now be using qProcessInfo for process IDs. This path here
1760 // should not be used. It is reporting process id instead of thread id. The
1761 // correct answer doesn't seem to make much sense for lldb-platform.
1762 // CONSIDER: flip to "unsupported".
1763 lldb::pid_t pid = m_process_launch_info.GetProcessID();
1764 response.Printf("QC%" PRIx64, pid);
1765
1766 // this should always be platform here
1767 assert (m_is_platform && "this code path should only be traversed for lldb-platform");
1768
1769 if (m_is_platform)
Greg Clayton8b82f082011-04-12 05:54:46 +00001770 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001771 // If we launch a process and this GDB server is acting as a platform,
1772 // then we need to clear the process launch state so we can start
1773 // launching another process. In order to launch a process a bunch or
1774 // packets need to be sent: environment packets, working directory,
1775 // disable ASLR, and many more settings. When we launch a process we
1776 // then need to know when to clear this information. Currently we are
1777 // selecting the 'qC' packet as that packet which seems to make the most
1778 // sense.
1779 if (pid != LLDB_INVALID_PROCESS_ID)
1780 {
1781 m_process_launch_info.Clear();
1782 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001783 }
1784 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001785 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00001786}
1787
1788bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00001789GDBRemoteCommunicationServer::DebugserverProcessReaped (lldb::pid_t pid)
1790{
1791 Mutex::Locker locker (m_spawned_pids_mutex);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001792 FreePortForProcess(pid);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001793 return m_spawned_pids.erase(pid) > 0;
1794}
1795bool
1796GDBRemoteCommunicationServer::ReapDebugserverProcess (void *callback_baton,
1797 lldb::pid_t pid,
1798 bool exited,
1799 int signal, // Zero for no signal
1800 int status) // Exit value of process if signal is zero
1801{
1802 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1803 server->DebugserverProcessReaped (pid);
1804 return true;
1805}
1806
Todd Fiala3e92a2b2014-01-24 00:52:53 +00001807bool
1808GDBRemoteCommunicationServer::DebuggedProcessReaped (lldb::pid_t pid)
1809{
1810 // reap a process that we were debugging (but not debugserver)
1811 Mutex::Locker locker (m_spawned_pids_mutex);
1812 return m_spawned_pids.erase(pid) > 0;
1813}
1814
1815bool
1816GDBRemoteCommunicationServer::ReapDebuggedProcess (void *callback_baton,
1817 lldb::pid_t pid,
1818 bool exited,
1819 int signal, // Zero for no signal
1820 int status) // Exit value of process if signal is zero
1821{
1822 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1823 server->DebuggedProcessReaped (pid);
1824 return true;
1825}
1826
Greg Clayton3dedae12013-12-06 21:45:27 +00001827GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001828GDBRemoteCommunicationServer::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet)
1829{
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001830#ifdef _WIN32
Deepak Panickal263fde02014-01-14 11:34:44 +00001831 return SendErrorResponse(9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001832#else
Todd Fiala015d8182014-07-22 23:41:36 +00001833 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
1834
Greg Clayton8b82f082011-04-12 05:54:46 +00001835 // Spawn a local debugserver as a platform so we can then attach or launch
1836 // a process...
1837
1838 if (m_is_platform)
1839 {
Todd Fiala015d8182014-07-22 23:41:36 +00001840 if (log)
1841 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
1842
Greg Clayton8b82f082011-04-12 05:54:46 +00001843 // Sleep and wait a bit for debugserver to start to listen...
1844 ConnectionFileDescriptor file_conn;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001845 std::string hostname;
Sylvestre Ledrufaa63ce2013-09-28 15:57:37 +00001846 // TODO: /tmp/ should not be hardcoded. User might want to override /tmp
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001847 // with the TMPDIR environment variable
Greg Clayton29b8fc42013-11-21 01:44:58 +00001848 packet.SetFilePos(::strlen ("qLaunchGDBServer;"));
1849 std::string name;
1850 std::string value;
1851 uint16_t port = UINT16_MAX;
1852 while (packet.GetNameColonValue(name, value))
Greg Clayton8b82f082011-04-12 05:54:46 +00001853 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001854 if (name.compare ("host") == 0)
1855 hostname.swap(value);
1856 else if (name.compare ("port") == 0)
1857 port = Args::StringToUInt32(value.c_str(), 0, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00001858 }
Greg Clayton29b8fc42013-11-21 01:44:58 +00001859 if (port == UINT16_MAX)
1860 port = GetNextAvailablePort();
1861
1862 // Spawn a new thread to accept the port that gets bound after
1863 // binding to port 0 (zero).
Greg Claytonfbb76342013-11-20 21:07:01 +00001864
Todd Fiala015d8182014-07-22 23:41:36 +00001865 // Spawn a debugserver and try to get the port it listens to.
1866 ProcessLaunchInfo debugserver_launch_info;
1867 if (hostname.empty())
1868 hostname = "127.0.0.1";
1869 if (log)
1870 log->Printf("Launching debugserver with: %s:%u...\n", hostname.c_str(), port);
1871
1872 debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false);
1873
1874 Error error = StartDebugserverProcess (hostname.empty() ? NULL : hostname.c_str(),
1875 port,
1876 debugserver_launch_info,
1877 port);
1878
1879 lldb::pid_t debugserver_pid = debugserver_launch_info.GetProcessID();
1880
1881
1882 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1883 {
1884 Mutex::Locker locker (m_spawned_pids_mutex);
1885 m_spawned_pids.insert(debugserver_pid);
1886 if (port > 0)
1887 AssociatePortWithProcess(port, debugserver_pid);
1888 }
1889 else
1890 {
1891 if (port > 0)
1892 FreePort (port);
1893 }
1894
Greg Clayton29b8fc42013-11-21 01:44:58 +00001895 if (error.Success())
1896 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001897 if (log)
Todd Fiala015d8182014-07-22 23:41:36 +00001898 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launched successfully as pid %" PRIu64, __FUNCTION__, debugserver_pid);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001899
Todd Fiala015d8182014-07-22 23:41:36 +00001900 char response[256];
1901 const int response_len = ::snprintf (response, sizeof(response), "pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset);
1902 assert (response_len < (int)sizeof(response));
1903 PacketResult packet_result = SendPacketNoLock (response, response_len);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001904
Todd Fiala015d8182014-07-22 23:41:36 +00001905 if (packet_result != PacketResult::Success)
Greg Clayton29b8fc42013-11-21 01:44:58 +00001906 {
Todd Fiala015d8182014-07-22 23:41:36 +00001907 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1908 ::kill (debugserver_pid, SIGINT);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001909 }
Todd Fiala015d8182014-07-22 23:41:36 +00001910 return packet_result;
1911 }
1912 else
1913 {
1914 if (log)
1915 log->Printf ("GDBRemoteCommunicationServer::%s() debugserver launch failed: %s", __FUNCTION__, error.AsCString ());
Greg Clayton8b82f082011-04-12 05:54:46 +00001916 }
1917 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00001918 return SendErrorResponse (9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001919#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00001920}
1921
Todd Fiala403edc52014-01-23 22:05:44 +00001922bool
1923GDBRemoteCommunicationServer::KillSpawnedProcess (lldb::pid_t pid)
1924{
1925 // make sure we know about this process
1926 {
1927 Mutex::Locker locker (m_spawned_pids_mutex);
1928 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1929 return false;
1930 }
1931
1932 // first try a SIGTERM (standard kill)
1933 Host::Kill (pid, SIGTERM);
1934
1935 // check if that worked
1936 for (size_t i=0; i<10; ++i)
1937 {
1938 {
1939 Mutex::Locker locker (m_spawned_pids_mutex);
1940 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1941 {
1942 // it is now killed
1943 return true;
1944 }
1945 }
1946 usleep (10000);
1947 }
1948
1949 // check one more time after the final usleep
1950 {
1951 Mutex::Locker locker (m_spawned_pids_mutex);
1952 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1953 return true;
1954 }
1955
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001956 // the launched process still lives. Now try killing it again,
Todd Fiala403edc52014-01-23 22:05:44 +00001957 // this time with an unblockable signal.
1958 Host::Kill (pid, SIGKILL);
1959
1960 for (size_t i=0; i<10; ++i)
1961 {
1962 {
1963 Mutex::Locker locker (m_spawned_pids_mutex);
1964 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1965 {
1966 // it is now killed
1967 return true;
1968 }
1969 }
1970 usleep (10000);
1971 }
1972
1973 // check one more time after the final usleep
1974 // Scope for locker
1975 {
1976 Mutex::Locker locker (m_spawned_pids_mutex);
1977 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1978 return true;
1979 }
1980
1981 // no luck - the process still lives
1982 return false;
1983}
1984
Greg Clayton3dedae12013-12-06 21:45:27 +00001985GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00001986GDBRemoteCommunicationServer::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet)
1987{
Todd Fiala403edc52014-01-23 22:05:44 +00001988 packet.SetFilePos(::strlen ("qKillSpawnedProcess:"));
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001989
Todd Fiala403edc52014-01-23 22:05:44 +00001990 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
1991
1992 // verify that we know anything about this pid.
1993 // Scope for locker
Daniel Maleae0f8f572013-08-26 23:57:52 +00001994 {
Todd Fiala403edc52014-01-23 22:05:44 +00001995 Mutex::Locker locker (m_spawned_pids_mutex);
1996 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
Daniel Maleae0f8f572013-08-26 23:57:52 +00001997 {
Todd Fiala403edc52014-01-23 22:05:44 +00001998 // not a pid we know about
1999 return SendErrorResponse (10);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002000 }
2001 }
Todd Fiala403edc52014-01-23 22:05:44 +00002002
2003 // go ahead and attempt to kill the spawned process
2004 if (KillSpawnedProcess (pid))
2005 return SendOKResponse ();
2006 else
2007 return SendErrorResponse (11);
2008}
2009
2010GDBRemoteCommunication::PacketResult
2011GDBRemoteCommunicationServer::Handle_k (StringExtractorGDBRemote &packet)
2012{
2013 // ignore for now if we're lldb_platform
2014 if (m_is_platform)
2015 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2016
2017 // shutdown all spawned processes
2018 std::set<lldb::pid_t> spawned_pids_copy;
2019
2020 // copy pids
2021 {
2022 Mutex::Locker locker (m_spawned_pids_mutex);
2023 spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ());
2024 }
2025
2026 // nuke the spawned processes
2027 for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it)
2028 {
2029 lldb::pid_t spawned_pid = *it;
2030 if (!KillSpawnedProcess (spawned_pid))
2031 {
2032 fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid);
2033 }
2034 }
2035
Todd Fialaaf245d12014-06-30 21:05:18 +00002036 FlushInferiorOutput ();
2037
2038 // No OK response for kill packet.
2039 // return SendOKResponse ();
2040 return PacketResult::Success;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002041}
2042
Greg Clayton3dedae12013-12-06 21:45:27 +00002043GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002044GDBRemoteCommunicationServer::Handle_qLaunchSuccess (StringExtractorGDBRemote &packet)
2045{
2046 if (m_process_launch_error.Success())
2047 return SendOKResponse();
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00002048 StreamString response;
Greg Clayton8b82f082011-04-12 05:54:46 +00002049 response.PutChar('E');
2050 response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
Greg Clayton37a0a242012-04-11 00:24:49 +00002051 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00002052}
2053
Greg Clayton3dedae12013-12-06 21:45:27 +00002054GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002055GDBRemoteCommunicationServer::Handle_QEnvironment (StringExtractorGDBRemote &packet)
2056{
2057 packet.SetFilePos(::strlen ("QEnvironment:"));
2058 const uint32_t bytes_left = packet.GetBytesLeft();
2059 if (bytes_left > 0)
2060 {
2061 m_process_launch_info.GetEnvironmentEntries ().AppendArgument (packet.Peek());
2062 return SendOKResponse ();
2063 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002064 return SendErrorResponse (12);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002065}
2066
Greg Clayton3dedae12013-12-06 21:45:27 +00002067GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002068GDBRemoteCommunicationServer::Handle_QLaunchArch (StringExtractorGDBRemote &packet)
2069{
2070 packet.SetFilePos(::strlen ("QLaunchArch:"));
2071 const uint32_t bytes_left = packet.GetBytesLeft();
2072 if (bytes_left > 0)
2073 {
2074 const char* arch_triple = packet.Peek();
2075 ArchSpec arch_spec(arch_triple,NULL);
2076 m_process_launch_info.SetArchitecture(arch_spec);
2077 return SendOKResponse();
2078 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002079 return SendErrorResponse(13);
Greg Clayton8b82f082011-04-12 05:54:46 +00002080}
2081
Greg Clayton3dedae12013-12-06 21:45:27 +00002082GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002083GDBRemoteCommunicationServer::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
2084{
2085 packet.SetFilePos(::strlen ("QSetDisableASLR:"));
2086 if (packet.GetU32(0))
2087 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
2088 else
2089 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
2090 return SendOKResponse ();
2091}
2092
Greg Clayton3dedae12013-12-06 21:45:27 +00002093GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002094GDBRemoteCommunicationServer::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
2095{
2096 packet.SetFilePos(::strlen ("QSetWorkingDir:"));
2097 std::string path;
2098 packet.GetHexByteString(path);
Greg Claytonfbb76342013-11-20 21:07:01 +00002099 if (m_is_platform)
2100 {
Colin Riley909bb7a2013-11-26 15:10:46 +00002101#ifdef _WIN32
2102 // Not implemented on Windows
2103 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_QSetWorkingDir unimplemented");
2104#else
Greg Claytonfbb76342013-11-20 21:07:01 +00002105 // If this packet is sent to a platform, then change the current working directory
2106 if (::chdir(path.c_str()) != 0)
2107 return SendErrorResponse(errno);
Colin Riley909bb7a2013-11-26 15:10:46 +00002108#endif
Greg Claytonfbb76342013-11-20 21:07:01 +00002109 }
2110 else
2111 {
2112 m_process_launch_info.SwapWorkingDirectory (path);
2113 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002114 return SendOKResponse ();
2115}
2116
Greg Clayton3dedae12013-12-06 21:45:27 +00002117GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002118GDBRemoteCommunicationServer::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
2119{
2120 StreamString response;
2121
2122 if (m_is_platform)
2123 {
2124 // If this packet is sent to a platform, then change the current working directory
2125 char cwd[PATH_MAX];
2126 if (getcwd(cwd, sizeof(cwd)) == NULL)
2127 {
2128 return SendErrorResponse(errno);
2129 }
2130 else
2131 {
2132 response.PutBytesAsRawHex8(cwd, strlen(cwd));
Greg Clayton3dedae12013-12-06 21:45:27 +00002133 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002134 }
2135 }
2136 else
2137 {
2138 const char *working_dir = m_process_launch_info.GetWorkingDirectory();
2139 if (working_dir && working_dir[0])
2140 {
2141 response.PutBytesAsRawHex8(working_dir, strlen(working_dir));
Greg Clayton3dedae12013-12-06 21:45:27 +00002142 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002143 }
2144 else
2145 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002146 return SendErrorResponse(14);
Greg Claytonfbb76342013-11-20 21:07:01 +00002147 }
2148 }
2149}
2150
Greg Clayton3dedae12013-12-06 21:45:27 +00002151GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002152GDBRemoteCommunicationServer::Handle_QSetSTDIN (StringExtractorGDBRemote &packet)
2153{
2154 packet.SetFilePos(::strlen ("QSetSTDIN:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002155 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002156 std::string path;
2157 packet.GetHexByteString(path);
2158 const bool read = false;
2159 const bool write = true;
2160 if (file_action.Open(STDIN_FILENO, path.c_str(), read, write))
2161 {
2162 m_process_launch_info.AppendFileAction(file_action);
2163 return SendOKResponse ();
2164 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002165 return SendErrorResponse (15);
Greg Clayton8b82f082011-04-12 05:54:46 +00002166}
2167
Greg Clayton3dedae12013-12-06 21:45:27 +00002168GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002169GDBRemoteCommunicationServer::Handle_QSetSTDOUT (StringExtractorGDBRemote &packet)
2170{
2171 packet.SetFilePos(::strlen ("QSetSTDOUT:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002172 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002173 std::string path;
2174 packet.GetHexByteString(path);
2175 const bool read = true;
2176 const bool write = false;
2177 if (file_action.Open(STDOUT_FILENO, path.c_str(), read, write))
2178 {
2179 m_process_launch_info.AppendFileAction(file_action);
2180 return SendOKResponse ();
2181 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002182 return SendErrorResponse (16);
Greg Clayton8b82f082011-04-12 05:54:46 +00002183}
2184
Greg Clayton3dedae12013-12-06 21:45:27 +00002185GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002186GDBRemoteCommunicationServer::Handle_QSetSTDERR (StringExtractorGDBRemote &packet)
2187{
2188 packet.SetFilePos(::strlen ("QSetSTDERR:"));
Zachary Turner696b5282014-08-14 16:01:25 +00002189 FileAction file_action;
Greg Clayton8b82f082011-04-12 05:54:46 +00002190 std::string path;
2191 packet.GetHexByteString(path);
2192 const bool read = true;
Greg Clayton9845a8d2012-03-06 04:01:04 +00002193 const bool write = false;
Greg Clayton8b82f082011-04-12 05:54:46 +00002194 if (file_action.Open(STDERR_FILENO, path.c_str(), read, write))
2195 {
2196 m_process_launch_info.AppendFileAction(file_action);
2197 return SendOKResponse ();
2198 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002199 return SendErrorResponse (17);
Greg Clayton8b82f082011-04-12 05:54:46 +00002200}
2201
Greg Clayton3dedae12013-12-06 21:45:27 +00002202GDBRemoteCommunication::PacketResult
Todd Fialaaf245d12014-06-30 21:05:18 +00002203GDBRemoteCommunicationServer::Handle_C (StringExtractorGDBRemote &packet)
2204{
2205 if (!IsGdbServer ())
2206 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2207
2208 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2209 if (log)
2210 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2211
2212 // Ensure we have a native process.
2213 if (!m_debugged_process_sp)
2214 {
2215 if (log)
2216 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2217 return SendErrorResponse (0x36);
2218 }
2219
2220 // Pull out the signal number.
2221 packet.SetFilePos (::strlen ("C"));
2222 if (packet.GetBytesLeft () < 1)
2223 {
2224 // Shouldn't be using a C without a signal.
2225 return SendIllFormedResponse (packet, "C packet specified without signal.");
2226 }
2227 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2228 if (signo == std::numeric_limits<uint32_t>::max ())
2229 return SendIllFormedResponse (packet, "failed to parse signal number");
2230
2231 // Handle optional continue address.
2232 if (packet.GetBytesLeft () > 0)
2233 {
2234 // FIXME add continue at address support for $C{signo}[;{continue-address}].
2235 if (*packet.Peek () == ';')
2236 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2237 else
2238 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
2239 }
2240
2241 lldb_private::ResumeActionList resume_actions (StateType::eStateRunning, 0);
2242 Error error;
2243
2244 // We have two branches: what to do if a continue thread is specified (in which case we target
2245 // sending the signal to that thread), or when we don't have a continue thread set (in which
2246 // case we send a signal to the process).
2247
2248 // TODO discuss with Greg Clayton, make sure this makes sense.
2249
2250 lldb::tid_t signal_tid = GetContinueThreadID ();
2251 if (signal_tid != LLDB_INVALID_THREAD_ID)
2252 {
2253 // The resume action for the continue thread (or all threads if a continue thread is not set).
2254 lldb_private::ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
2255
2256 // Add the action for the continue thread (or all threads when the continue thread isn't present).
2257 resume_actions.Append (action);
2258 }
2259 else
2260 {
2261 // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
2262 error = m_debugged_process_sp->Signal (signo);
2263 if (error.Fail ())
2264 {
2265 if (log)
2266 log->Printf ("GDBRemoteCommunicationServer::%s failed to send signal for process %" PRIu64 ": %s",
2267 __FUNCTION__,
2268 m_debugged_process_sp->GetID (),
2269 error.AsCString ());
2270
2271 return SendErrorResponse (0x52);
2272 }
2273 }
2274
2275 // Resume the threads.
2276 error = m_debugged_process_sp->Resume (resume_actions);
2277 if (error.Fail ())
2278 {
2279 if (log)
2280 log->Printf ("GDBRemoteCommunicationServer::%s failed to resume threads for process %" PRIu64 ": %s",
2281 __FUNCTION__,
2282 m_debugged_process_sp->GetID (),
2283 error.AsCString ());
2284
2285 return SendErrorResponse (0x38);
2286 }
2287
2288 // Don't send an "OK" packet; response is the stopped/exited message.
2289 return PacketResult::Success;
2290}
2291
2292GDBRemoteCommunication::PacketResult
2293GDBRemoteCommunicationServer::Handle_c (StringExtractorGDBRemote &packet, bool skip_file_pos_adjustment)
2294{
2295 if (!IsGdbServer ())
2296 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2297
2298 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2299 if (log)
2300 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2301
2302 // We reuse this method in vCont - don't double adjust the file position.
2303 if (!skip_file_pos_adjustment)
2304 packet.SetFilePos (::strlen ("c"));
2305
2306 // For now just support all continue.
2307 const bool has_continue_address = (packet.GetBytesLeft () > 0);
2308 if (has_continue_address)
2309 {
2310 if (log)
2311 log->Printf ("GDBRemoteCommunicationServer::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
2312 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2313 }
2314
2315 // Ensure we have a native process.
2316 if (!m_debugged_process_sp)
2317 {
2318 if (log)
2319 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2320 return SendErrorResponse (0x36);
2321 }
2322
2323 // Build the ResumeActionList
2324 lldb_private::ResumeActionList actions (StateType::eStateRunning, 0);
2325
2326 Error error = m_debugged_process_sp->Resume (actions);
2327 if (error.Fail ())
2328 {
2329 if (log)
2330 {
2331 log->Printf ("GDBRemoteCommunicationServer::%s c failed for process %" PRIu64 ": %s",
2332 __FUNCTION__,
2333 m_debugged_process_sp->GetID (),
2334 error.AsCString ());
2335 }
2336 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2337 }
2338
2339 if (log)
2340 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2341
2342 // No response required from continue.
2343 return PacketResult::Success;
2344}
2345
2346GDBRemoteCommunication::PacketResult
2347GDBRemoteCommunicationServer::Handle_vCont_actions (StringExtractorGDBRemote &packet)
2348{
2349 if (!IsGdbServer ())
2350 {
2351 // only llgs supports $vCont.
2352 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2353 }
2354
2355 // We handle $vCont messages for c.
2356 // TODO add C, s and S.
2357 StreamString response;
2358 response.Printf("vCont;c;C;s;S");
2359
2360 return SendPacketNoLock(response.GetData(), response.GetSize());
2361}
2362
2363GDBRemoteCommunication::PacketResult
2364GDBRemoteCommunicationServer::Handle_vCont (StringExtractorGDBRemote &packet)
2365{
2366 if (!IsGdbServer ())
2367 {
2368 // only llgs supports $vCont
2369 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2370 }
2371
2372 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2373 if (log)
2374 log->Printf ("GDBRemoteCommunicationServer::%s handling vCont packet", __FUNCTION__);
2375
2376 packet.SetFilePos (::strlen ("vCont"));
2377
2378 // Check if this is all continue (no options or ";c").
2379 if (!packet.GetBytesLeft () || (::strcmp (packet.Peek (), ";c") == 0))
2380 {
2381 // Move the packet past the ";c".
2382 if (packet.GetBytesLeft ())
2383 packet.SetFilePos (packet.GetFilePos () + ::strlen (";c"));
2384
2385 const bool skip_file_pos_adjustment = true;
2386 return Handle_c (packet, skip_file_pos_adjustment);
2387 }
2388 else if (::strcmp (packet.Peek (), ";s") == 0)
2389 {
2390 // Move past the ';', then do a simple 's'.
2391 packet.SetFilePos (packet.GetFilePos () + 1);
2392 return Handle_s (packet);
2393 }
2394
2395 // Ensure we have a native process.
2396 if (!m_debugged_process_sp)
2397 {
2398 if (log)
2399 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2400 return SendErrorResponse (0x36);
2401 }
2402
2403 ResumeActionList thread_actions;
2404
2405 while (packet.GetBytesLeft () && *packet.Peek () == ';')
2406 {
2407 // Skip the semi-colon.
2408 packet.GetChar ();
2409
2410 // Build up the thread action.
2411 ResumeAction thread_action;
2412 thread_action.tid = LLDB_INVALID_THREAD_ID;
2413 thread_action.state = eStateInvalid;
2414 thread_action.signal = 0;
2415
2416 const char action = packet.GetChar ();
2417 switch (action)
2418 {
2419 case 'C':
2420 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2421 if (thread_action.signal == 0)
2422 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
2423 // Fall through to next case...
2424
2425 case 'c':
2426 // Continue
2427 thread_action.state = eStateRunning;
2428 break;
2429
2430 case 'S':
2431 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2432 if (thread_action.signal == 0)
2433 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
2434 // Fall through to next case...
2435
2436 case 's':
2437 // Step
2438 thread_action.state = eStateStepping;
2439 break;
2440
2441 default:
2442 return SendIllFormedResponse (packet, "Unsupported vCont action");
2443 break;
2444 }
2445
2446 // Parse out optional :{thread-id} value.
2447 if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
2448 {
2449 // Consume the separator.
2450 packet.GetChar ();
2451
2452 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2453 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
2454 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
2455 }
2456
2457 thread_actions.Append (thread_action);
2458 }
2459
2460 // If a default action for all other threads wasn't mentioned
2461 // then we should stop the threads.
2462 thread_actions.SetDefaultThreadActionIfNeeded (eStateStopped, 0);
2463
2464 Error error = m_debugged_process_sp->Resume (thread_actions);
2465 if (error.Fail ())
2466 {
2467 if (log)
2468 {
2469 log->Printf ("GDBRemoteCommunicationServer::%s vCont failed for process %" PRIu64 ": %s",
2470 __FUNCTION__,
2471 m_debugged_process_sp->GetID (),
2472 error.AsCString ());
2473 }
2474 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2475 }
2476
2477 if (log)
2478 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2479
2480 // No response required from vCont.
2481 return PacketResult::Success;
2482}
2483
2484GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00002485GDBRemoteCommunicationServer::Handle_QStartNoAckMode (StringExtractorGDBRemote &packet)
2486{
2487 // Send response first before changing m_send_acks to we ack this packet
Greg Clayton3dedae12013-12-06 21:45:27 +00002488 PacketResult packet_result = SendOKResponse ();
Greg Clayton1cb64962011-03-24 04:28:38 +00002489 m_send_acks = false;
Greg Clayton3dedae12013-12-06 21:45:27 +00002490 return packet_result;
Greg Clayton1cb64962011-03-24 04:28:38 +00002491}
Daniel Maleae0f8f572013-08-26 23:57:52 +00002492
Greg Clayton3dedae12013-12-06 21:45:27 +00002493GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002494GDBRemoteCommunicationServer::Handle_qPlatform_mkdir (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002495{
Greg Claytonfbb76342013-11-20 21:07:01 +00002496 packet.SetFilePos(::strlen("qPlatform_mkdir:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002497 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002498 if (packet.GetChar() == ',')
2499 {
2500 std::string path;
2501 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002502 Error error = FileSystem::MakeDirectory(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002503 if (error.Success())
2504 return SendPacketNoLock ("OK", 2);
2505 else
2506 return SendErrorResponse(error.GetError());
2507 }
2508 return SendErrorResponse(20);
Greg Claytonfbb76342013-11-20 21:07:01 +00002509}
2510
Greg Clayton3dedae12013-12-06 21:45:27 +00002511GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002512GDBRemoteCommunicationServer::Handle_qPlatform_chmod (StringExtractorGDBRemote &packet)
2513{
2514 packet.SetFilePos(::strlen("qPlatform_chmod:"));
2515
2516 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002517 if (packet.GetChar() == ',')
2518 {
2519 std::string path;
2520 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002521 Error error = FileSystem::SetFilePermissions(path.c_str(), mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002522 if (error.Success())
2523 return SendPacketNoLock ("OK", 2);
2524 else
2525 return SendErrorResponse(error.GetError());
2526 }
2527 return SendErrorResponse(19);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002528}
2529
Greg Clayton3dedae12013-12-06 21:45:27 +00002530GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002531GDBRemoteCommunicationServer::Handle_vFile_Open (StringExtractorGDBRemote &packet)
2532{
2533 packet.SetFilePos(::strlen("vFile:open:"));
2534 std::string path;
2535 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002536 if (!path.empty())
2537 {
2538 if (packet.GetChar() == ',')
2539 {
2540 uint32_t flags = packet.GetHexMaxU32(false, 0);
2541 if (packet.GetChar() == ',')
2542 {
2543 mode_t mode = packet.GetHexMaxU32(false, 0600);
2544 Error error;
2545 int fd = ::open (path.c_str(), flags, mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002546 const int save_errno = fd == -1 ? errno : 0;
2547 StreamString response;
2548 response.PutChar('F');
2549 response.Printf("%i", fd);
2550 if (save_errno)
2551 response.Printf(",%i", save_errno);
2552 return SendPacketNoLock(response.GetData(), response.GetSize());
2553 }
2554 }
2555 }
2556 return SendErrorResponse(18);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002557}
2558
Greg Clayton3dedae12013-12-06 21:45:27 +00002559GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002560GDBRemoteCommunicationServer::Handle_vFile_Close (StringExtractorGDBRemote &packet)
2561{
2562 packet.SetFilePos(::strlen("vFile:close:"));
2563 int fd = packet.GetS32(-1);
2564 Error error;
2565 int err = -1;
2566 int save_errno = 0;
2567 if (fd >= 0)
2568 {
2569 err = close(fd);
2570 save_errno = err == -1 ? errno : 0;
2571 }
2572 else
2573 {
2574 save_errno = EINVAL;
2575 }
2576 StreamString response;
2577 response.PutChar('F');
2578 response.Printf("%i", err);
2579 if (save_errno)
2580 response.Printf(",%i", save_errno);
Greg Clayton2b98c562013-11-22 18:53:12 +00002581 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002582}
2583
Greg Clayton3dedae12013-12-06 21:45:27 +00002584GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002585GDBRemoteCommunicationServer::Handle_vFile_pRead (StringExtractorGDBRemote &packet)
2586{
Virgile Belloae12a362013-08-27 16:21:49 +00002587#ifdef _WIN32
2588 // Not implemented on Windows
Greg Clayton2b98c562013-11-22 18:53:12 +00002589 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pRead() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002590#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002591 StreamGDBRemote response;
2592 packet.SetFilePos(::strlen("vFile:pread:"));
2593 int fd = packet.GetS32(-1);
Greg Clayton2b98c562013-11-22 18:53:12 +00002594 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002595 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002596 uint64_t count = packet.GetU64(UINT64_MAX);
2597 if (packet.GetChar() == ',')
2598 {
2599 uint64_t offset = packet.GetU64(UINT32_MAX);
2600 if (count == UINT64_MAX)
2601 {
2602 response.Printf("F-1:%i", EINVAL);
2603 return SendPacketNoLock(response.GetData(), response.GetSize());
2604 }
2605
2606 std::string buffer(count, 0);
2607 const ssize_t bytes_read = ::pread (fd, &buffer[0], buffer.size(), offset);
2608 const int save_errno = bytes_read == -1 ? errno : 0;
2609 response.PutChar('F');
2610 response.Printf("%zi", bytes_read);
2611 if (save_errno)
2612 response.Printf(",%i", save_errno);
2613 else
2614 {
2615 response.PutChar(';');
2616 response.PutEscapedBytes(&buffer[0], bytes_read);
2617 }
2618 return SendPacketNoLock(response.GetData(), response.GetSize());
2619 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002620 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002621 return SendErrorResponse(21);
2622
Virgile Belloae12a362013-08-27 16:21:49 +00002623#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002624}
2625
Greg Clayton3dedae12013-12-06 21:45:27 +00002626GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002627GDBRemoteCommunicationServer::Handle_vFile_pWrite (StringExtractorGDBRemote &packet)
2628{
Virgile Belloae12a362013-08-27 16:21:49 +00002629#ifdef _WIN32
Greg Clayton2b98c562013-11-22 18:53:12 +00002630 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pWrite() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002631#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002632 packet.SetFilePos(::strlen("vFile:pwrite:"));
2633
2634 StreamGDBRemote response;
2635 response.PutChar('F');
2636
2637 int fd = packet.GetU32(UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002638 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002639 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002640 off_t offset = packet.GetU64(UINT32_MAX);
2641 if (packet.GetChar() == ',')
2642 {
2643 std::string buffer;
2644 if (packet.GetEscapedBinaryData(buffer))
2645 {
2646 const ssize_t bytes_written = ::pwrite (fd, buffer.data(), buffer.size(), offset);
2647 const int save_errno = bytes_written == -1 ? errno : 0;
2648 response.Printf("%zi", bytes_written);
2649 if (save_errno)
2650 response.Printf(",%i", save_errno);
2651 }
2652 else
2653 {
2654 response.Printf ("-1,%i", EINVAL);
2655 }
2656 return SendPacketNoLock(response.GetData(), response.GetSize());
2657 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002658 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002659 return SendErrorResponse(27);
Virgile Belloae12a362013-08-27 16:21:49 +00002660#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002661}
2662
Greg Clayton3dedae12013-12-06 21:45:27 +00002663GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002664GDBRemoteCommunicationServer::Handle_vFile_Size (StringExtractorGDBRemote &packet)
2665{
2666 packet.SetFilePos(::strlen("vFile:size:"));
2667 std::string path;
2668 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002669 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002670 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002671 lldb::user_id_t retcode = FileSystem::GetFileSize(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002672 StreamString response;
2673 response.PutChar('F');
2674 response.PutHex64(retcode);
2675 if (retcode == UINT64_MAX)
2676 {
2677 response.PutChar(',');
2678 response.PutHex64(retcode); // TODO: replace with Host::GetSyswideErrorCode()
2679 }
2680 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002681 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002682 return SendErrorResponse(22);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002683}
2684
Greg Clayton3dedae12013-12-06 21:45:27 +00002685GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002686GDBRemoteCommunicationServer::Handle_vFile_Mode (StringExtractorGDBRemote &packet)
2687{
2688 packet.SetFilePos(::strlen("vFile:mode:"));
2689 std::string path;
2690 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002691 if (!path.empty())
2692 {
2693 Error error;
2694 const uint32_t mode = File::GetPermissions(path.c_str(), error);
2695 StreamString response;
2696 response.Printf("F%u", mode);
2697 if (mode == 0 || error.Fail())
2698 response.Printf(",%i", (int)error.GetError());
2699 return SendPacketNoLock(response.GetData(), response.GetSize());
2700 }
2701 return SendErrorResponse(23);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002702}
2703
Greg Clayton3dedae12013-12-06 21:45:27 +00002704GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002705GDBRemoteCommunicationServer::Handle_vFile_Exists (StringExtractorGDBRemote &packet)
2706{
2707 packet.SetFilePos(::strlen("vFile:exists:"));
2708 std::string path;
2709 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002710 if (!path.empty())
2711 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002712 bool retcode = FileSystem::GetFileExists(FileSpec(path.c_str(), false));
Greg Clayton2b98c562013-11-22 18:53:12 +00002713 StreamString response;
2714 response.PutChar('F');
2715 response.PutChar(',');
2716 if (retcode)
2717 response.PutChar('1');
2718 else
2719 response.PutChar('0');
2720 return SendPacketNoLock(response.GetData(), response.GetSize());
2721 }
2722 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002723}
2724
Greg Clayton3dedae12013-12-06 21:45:27 +00002725GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002726GDBRemoteCommunicationServer::Handle_vFile_symlink (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002727{
Greg Claytonfbb76342013-11-20 21:07:01 +00002728 packet.SetFilePos(::strlen("vFile:symlink:"));
2729 std::string dst, src;
2730 packet.GetHexByteStringTerminatedBy(dst, ',');
2731 packet.GetChar(); // Skip ',' char
2732 packet.GetHexByteString(src);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002733 Error error = FileSystem::Symlink(src.c_str(), dst.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002734 StreamString response;
2735 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002736 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002737}
2738
Greg Clayton3dedae12013-12-06 21:45:27 +00002739GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002740GDBRemoteCommunicationServer::Handle_vFile_unlink (StringExtractorGDBRemote &packet)
2741{
2742 packet.SetFilePos(::strlen("vFile:unlink:"));
2743 std::string path;
2744 packet.GetHexByteString(path);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002745 Error error = FileSystem::Unlink(path.c_str());
Greg Claytonfbb76342013-11-20 21:07:01 +00002746 StreamString response;
2747 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002748 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002749}
2750
Greg Clayton3dedae12013-12-06 21:45:27 +00002751GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002752GDBRemoteCommunicationServer::Handle_qPlatform_shell (StringExtractorGDBRemote &packet)
2753{
2754 packet.SetFilePos(::strlen("qPlatform_shell:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002755 std::string path;
2756 std::string working_dir;
2757 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002758 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002759 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002760 if (packet.GetChar() == ',')
2761 {
2762 // FIXME: add timeout to qPlatform_shell packet
2763 // uint32_t timeout = packet.GetHexMaxU32(false, 32);
2764 uint32_t timeout = 10;
2765 if (packet.GetChar() == ',')
2766 packet.GetHexByteString(working_dir);
2767 int status, signo;
2768 std::string output;
2769 Error err = Host::RunShellCommand(path.c_str(),
2770 working_dir.empty() ? NULL : working_dir.c_str(),
2771 &status, &signo, &output, timeout);
2772 StreamGDBRemote response;
2773 if (err.Fail())
2774 {
2775 response.PutCString("F,");
2776 response.PutHex32(UINT32_MAX);
2777 }
2778 else
2779 {
2780 response.PutCString("F,");
2781 response.PutHex32(status);
2782 response.PutChar(',');
2783 response.PutHex32(signo);
2784 response.PutChar(',');
2785 response.PutEscapedBytes(output.c_str(), output.size());
2786 }
2787 return SendPacketNoLock(response.GetData(), response.GetSize());
2788 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002789 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002790 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002791}
2792
Todd Fialaaf245d12014-06-30 21:05:18 +00002793void
2794GDBRemoteCommunicationServer::SetCurrentThreadID (lldb::tid_t tid)
2795{
2796 assert (IsGdbServer () && "SetCurrentThreadID() called when not GdbServer code");
2797
2798 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2799 if (log)
2800 log->Printf ("GDBRemoteCommunicationServer::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
2801
2802 m_current_tid = tid;
2803 if (m_debugged_process_sp)
2804 m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
2805}
2806
2807void
2808GDBRemoteCommunicationServer::SetContinueThreadID (lldb::tid_t tid)
2809{
2810 assert (IsGdbServer () && "SetContinueThreadID() called when not GdbServer code");
2811
2812 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2813 if (log)
2814 log->Printf ("GDBRemoteCommunicationServer::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
2815
2816 m_continue_tid = tid;
2817}
2818
2819GDBRemoteCommunication::PacketResult
2820GDBRemoteCommunicationServer::Handle_stop_reason (StringExtractorGDBRemote &packet)
2821{
2822 // Handle the $? gdbremote command.
2823 if (!IsGdbServer ())
2824 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_stop_reason() unimplemented");
2825
2826 // If no process, indicate error
2827 if (!m_debugged_process_sp)
2828 return SendErrorResponse (02);
2829
2830 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
2831}
2832
2833GDBRemoteCommunication::PacketResult
2834GDBRemoteCommunicationServer::SendStopReasonForState (lldb::StateType process_state, bool flush_on_exit)
2835{
2836 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2837
2838 switch (process_state)
2839 {
2840 case eStateAttaching:
2841 case eStateLaunching:
2842 case eStateRunning:
2843 case eStateStepping:
2844 case eStateDetached:
2845 // NOTE: gdb protocol doc looks like it should return $OK
2846 // when everything is running (i.e. no stopped result).
2847 return PacketResult::Success; // Ignore
2848
2849 case eStateSuspended:
2850 case eStateStopped:
2851 case eStateCrashed:
2852 {
2853 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
2854 // Make sure we set the current thread so g and p packets return
2855 // the data the gdb will expect.
2856 SetCurrentThreadID (tid);
2857 return SendStopReplyPacketForThread (tid);
2858 }
2859
2860 case eStateInvalid:
2861 case eStateUnloaded:
2862 case eStateExited:
2863 if (flush_on_exit)
2864 FlushInferiorOutput ();
2865 return SendWResponse(m_debugged_process_sp.get());
2866
2867 default:
2868 if (log)
2869 {
2870 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", current state reporting not handled: %s",
2871 __FUNCTION__,
2872 m_debugged_process_sp->GetID (),
2873 StateAsCString (process_state));
2874 }
2875 break;
2876 }
2877
2878 return SendErrorResponse (0);
2879}
2880
Greg Clayton3dedae12013-12-06 21:45:27 +00002881GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002882GDBRemoteCommunicationServer::Handle_vFile_Stat (StringExtractorGDBRemote &packet)
2883{
Greg Clayton2b98c562013-11-22 18:53:12 +00002884 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_Stat() unimplemented");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002885}
2886
Greg Clayton3dedae12013-12-06 21:45:27 +00002887GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002888GDBRemoteCommunicationServer::Handle_vFile_MD5 (StringExtractorGDBRemote &packet)
2889{
Greg Clayton2b98c562013-11-22 18:53:12 +00002890 packet.SetFilePos(::strlen("vFile:MD5:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002891 std::string path;
2892 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002893 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002894 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002895 uint64_t a,b;
2896 StreamGDBRemote response;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002897 if (FileSystem::CalculateMD5(FileSpec(path.c_str(), false), a, b) == false)
Greg Clayton2b98c562013-11-22 18:53:12 +00002898 {
2899 response.PutCString("F,");
2900 response.PutCString("x");
2901 }
2902 else
2903 {
2904 response.PutCString("F,");
2905 response.PutHex64(a);
2906 response.PutHex64(b);
2907 }
2908 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002909 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002910 return SendErrorResponse(25);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002911}
Greg Clayton2b98c562013-11-22 18:53:12 +00002912
Todd Fialaaf245d12014-06-30 21:05:18 +00002913GDBRemoteCommunication::PacketResult
2914GDBRemoteCommunicationServer::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
2915{
2916 // Ensure we're llgs.
2917 if (!IsGdbServer())
2918 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qRegisterInfo() unimplemented");
2919
2920 // Fail if we don't have a current process.
2921 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2922 return SendErrorResponse (68);
2923
2924 // Ensure we have a thread.
2925 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
2926 if (!thread_sp)
2927 return SendErrorResponse (69);
2928
2929 // Get the register context for the first thread.
2930 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2931 if (!reg_context_sp)
2932 return SendErrorResponse (69);
2933
2934 // Parse out the register number from the request.
2935 packet.SetFilePos (strlen("qRegisterInfo"));
2936 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2937 if (reg_index == std::numeric_limits<uint32_t>::max ())
2938 return SendErrorResponse (69);
2939
2940 // Return the end of registers response if we've iterated one past the end of the register set.
2941 if (reg_index >= reg_context_sp->GetRegisterCount ())
2942 return SendErrorResponse (69);
2943
2944 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2945 if (!reg_info)
2946 return SendErrorResponse (69);
2947
2948 // Build the reginfos response.
2949 StreamGDBRemote response;
2950
2951 response.PutCString ("name:");
2952 response.PutCString (reg_info->name);
2953 response.PutChar (';');
2954
2955 if (reg_info->alt_name && reg_info->alt_name[0])
2956 {
2957 response.PutCString ("alt-name:");
2958 response.PutCString (reg_info->alt_name);
2959 response.PutChar (';');
2960 }
2961
2962 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
2963
2964 switch (reg_info->encoding)
2965 {
2966 case eEncodingUint: response.PutCString ("encoding:uint;"); break;
2967 case eEncodingSint: response.PutCString ("encoding:sint;"); break;
2968 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
2969 case eEncodingVector: response.PutCString ("encoding:vector;"); break;
2970 default: break;
2971 }
2972
2973 switch (reg_info->format)
2974 {
2975 case eFormatBinary: response.PutCString ("format:binary;"); break;
2976 case eFormatDecimal: response.PutCString ("format:decimal;"); break;
2977 case eFormatHex: response.PutCString ("format:hex;"); break;
2978 case eFormatFloat: response.PutCString ("format:float;"); break;
2979 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break;
2980 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break;
2981 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break;
2982 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break;
2983 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break;
2984 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break;
2985 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
2986 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
2987 default: break;
2988 };
2989
2990 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
2991 if (register_set_name)
2992 {
2993 response.PutCString ("set:");
2994 response.PutCString (register_set_name);
2995 response.PutChar (';');
2996 }
2997
2998 if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM)
2999 response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]);
3000
3001 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
3002 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3003
3004 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
3005 {
3006 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break;
3007 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break;
3008 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break;
3009 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break;
3010 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break;
3011 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break;
3012 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break;
3013 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break;
3014 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break;
3015 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break;
3016 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break;
3017 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break;
3018 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break;
3019 default: break;
3020 }
3021
3022 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
3023 {
3024 response.PutCString ("container-regs:");
3025 int i = 0;
3026 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3027 {
3028 if (i > 0)
3029 response.PutChar (',');
3030 response.Printf ("%" PRIx32, *reg_num);
3031 }
3032 response.PutChar (';');
3033 }
3034
3035 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
3036 {
3037 response.PutCString ("invalidate-regs:");
3038 int i = 0;
3039 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3040 {
3041 if (i > 0)
3042 response.PutChar (',');
3043 response.Printf ("%" PRIx32, *reg_num);
3044 }
3045 response.PutChar (';');
3046 }
3047
3048 return SendPacketNoLock(response.GetData(), response.GetSize());
3049}
3050
3051GDBRemoteCommunication::PacketResult
3052GDBRemoteCommunicationServer::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
3053{
3054 // Ensure we're llgs.
3055 if (!IsGdbServer())
3056 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qfThreadInfo() unimplemented");
3057
Todd Fiala24189d42014-07-14 06:24:44 +00003058 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3059
Todd Fialaaf245d12014-06-30 21:05:18 +00003060 // Fail if we don't have a current process.
3061 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
Todd Fiala24189d42014-07-14 06:24:44 +00003062 {
3063 if (log)
3064 log->Printf ("GDBRemoteCommunicationServer::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
3065 return SendOKResponse ();
3066 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003067
3068 StreamGDBRemote response;
3069 response.PutChar ('m');
3070
Todd Fiala24189d42014-07-14 06:24:44 +00003071 if (log)
3072 log->Printf ("GDBRemoteCommunicationServer::%s() starting thread iteration", __FUNCTION__);
3073
Todd Fialaaf245d12014-06-30 21:05:18 +00003074 NativeThreadProtocolSP thread_sp;
3075 uint32_t thread_index;
3076 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
3077 thread_sp;
3078 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
3079 {
Todd Fiala24189d42014-07-14 06:24:44 +00003080 if (log)
3081 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 +00003082 if (thread_index > 0)
3083 response.PutChar(',');
3084 response.Printf ("%" PRIx64, thread_sp->GetID ());
3085 }
3086
Todd Fiala24189d42014-07-14 06:24:44 +00003087 if (log)
3088 log->Printf ("GDBRemoteCommunicationServer::%s() finished thread iteration", __FUNCTION__);
3089
Todd Fialaaf245d12014-06-30 21:05:18 +00003090 return SendPacketNoLock(response.GetData(), response.GetSize());
3091}
3092
3093GDBRemoteCommunication::PacketResult
3094GDBRemoteCommunicationServer::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
3095{
3096 // Ensure we're llgs.
3097 if (!IsGdbServer())
3098 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_qsThreadInfo() unimplemented");
3099
3100 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
3101 return SendPacketNoLock ("l", 1);
3102}
3103
3104GDBRemoteCommunication::PacketResult
3105GDBRemoteCommunicationServer::Handle_p (StringExtractorGDBRemote &packet)
3106{
3107 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3108
3109 // Ensure we're llgs.
3110 if (!IsGdbServer())
3111 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_p() unimplemented");
3112
3113 // Parse out the register number from the request.
3114 packet.SetFilePos (strlen("p"));
3115 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3116 if (reg_index == std::numeric_limits<uint32_t>::max ())
3117 {
3118 if (log)
3119 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3120 return SendErrorResponse (0x15);
3121 }
3122
3123 // Get the thread to use.
3124 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3125 if (!thread_sp)
3126 {
3127 if (log)
3128 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available", __FUNCTION__);
3129 return SendErrorResponse (0x15);
3130 }
3131
3132 // Get the thread's register context.
3133 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3134 if (!reg_context_sp)
3135 {
3136 if (log)
3137 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 ());
3138 return SendErrorResponse (0x15);
3139 }
3140
3141 // Return the end of registers response if we've iterated one past the end of the register set.
3142 if (reg_index >= reg_context_sp->GetRegisterCount ())
3143 {
3144 if (log)
3145 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ());
3146 return SendErrorResponse (0x15);
3147 }
3148
3149 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3150 if (!reg_info)
3151 {
3152 if (log)
3153 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3154 return SendErrorResponse (0x15);
3155 }
3156
3157 // Build the reginfos response.
3158 StreamGDBRemote response;
3159
3160 // Retrieve the value
3161 RegisterValue reg_value;
3162 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
3163 if (error.Fail ())
3164 {
3165 if (log)
3166 log->Printf ("GDBRemoteCommunicationServer::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3167 return SendErrorResponse (0x15);
3168 }
3169
3170 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
3171 if (!data)
3172 {
3173 if (log)
3174 log->Printf ("GDBRemoteCommunicationServer::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
3175 return SendErrorResponse (0x15);
3176 }
3177
3178 // FIXME flip as needed to get data in big/little endian format for this host.
3179 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
3180 response.PutHex8 (data[i]);
3181
3182 return SendPacketNoLock (response.GetData (), response.GetSize ());
3183}
3184
3185GDBRemoteCommunication::PacketResult
3186GDBRemoteCommunicationServer::Handle_P (StringExtractorGDBRemote &packet)
3187{
3188 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3189
3190 // Ensure we're llgs.
3191 if (!IsGdbServer())
3192 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_P() unimplemented");
3193
3194 // Ensure there is more content.
3195 if (packet.GetBytesLeft () < 1)
3196 return SendIllFormedResponse (packet, "Empty P packet");
3197
3198 // Parse out the register number from the request.
3199 packet.SetFilePos (strlen("P"));
3200 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3201 if (reg_index == std::numeric_limits<uint32_t>::max ())
3202 {
3203 if (log)
3204 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3205 return SendErrorResponse (0x29);
3206 }
3207
3208 // Note debugserver would send an E30 here.
3209 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
3210 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
3211
3212 // Get process architecture.
3213 ArchSpec process_arch;
3214 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
3215 {
3216 if (log)
3217 log->Printf ("GDBRemoteCommunicationServer::%s failed to retrieve inferior architecture", __FUNCTION__);
3218 return SendErrorResponse (0x49);
3219 }
3220
3221 // Parse out the value.
3222 const uint64_t raw_value = packet.GetHexMaxU64 (process_arch.GetByteOrder () == lldb::eByteOrderLittle, std::numeric_limits<uint64_t>::max ());
3223
3224 // Get the thread to use.
3225 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3226 if (!thread_sp)
3227 {
3228 if (log)
3229 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available (thread index 0)", __FUNCTION__);
3230 return SendErrorResponse (0x28);
3231 }
3232
3233 // Get the thread's register context.
3234 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3235 if (!reg_context_sp)
3236 {
3237 if (log)
3238 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 ());
3239 return SendErrorResponse (0x15);
3240 }
3241
3242 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3243 if (!reg_info)
3244 {
3245 if (log)
3246 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3247 return SendErrorResponse (0x48);
3248 }
3249
3250 // Return the end of registers response if we've iterated one past the end of the register set.
3251 if (reg_index >= reg_context_sp->GetRegisterCount ())
3252 {
3253 if (log)
3254 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ());
3255 return SendErrorResponse (0x47);
3256 }
3257
3258
3259 // Build the reginfos response.
3260 StreamGDBRemote response;
3261
3262 // FIXME Could be suffixed with a thread: parameter.
3263 // That thread then needs to be fed back into the reg context retrieval above.
3264 Error error = reg_context_sp->WriteRegisterFromUnsigned (reg_info, raw_value);
3265 if (error.Fail ())
3266 {
3267 if (log)
3268 log->Printf ("GDBRemoteCommunicationServer::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3269 return SendErrorResponse (0x32);
3270 }
3271
3272 return SendOKResponse();
3273}
3274
3275GDBRemoteCommunicationServer::PacketResult
3276GDBRemoteCommunicationServer::Handle_H (StringExtractorGDBRemote &packet)
3277{
3278 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3279
3280 // Ensure we're llgs.
3281 if (!IsGdbServer())
3282 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_H() unimplemented");
3283
3284 // Fail if we don't have a current process.
3285 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3286 {
3287 if (log)
3288 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3289 return SendErrorResponse (0x15);
3290 }
3291
3292 // Parse out which variant of $H is requested.
3293 packet.SetFilePos (strlen("H"));
3294 if (packet.GetBytesLeft () < 1)
3295 {
3296 if (log)
3297 log->Printf ("GDBRemoteCommunicationServer::%s failed, H command missing {g,c} variant", __FUNCTION__);
3298 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
3299 }
3300
3301 const char h_variant = packet.GetChar ();
3302 switch (h_variant)
3303 {
3304 case 'g':
3305 break;
3306
3307 case 'c':
3308 break;
3309
3310 default:
3311 if (log)
3312 log->Printf ("GDBRemoteCommunicationServer::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
3313 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3314 }
3315
3316 // Parse out the thread number.
3317 // FIXME return a parse success/fail value. All values are valid here.
3318 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
3319
3320 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
3321 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
3322 {
3323 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
3324 if (!thread_sp)
3325 {
3326 if (log)
3327 log->Printf ("GDBRemoteCommunicationServer::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
3328 return SendErrorResponse (0x15);
3329 }
3330 }
3331
3332 // Now switch the given thread type.
3333 switch (h_variant)
3334 {
3335 case 'g':
3336 SetCurrentThreadID (tid);
3337 break;
3338
3339 case 'c':
3340 SetContinueThreadID (tid);
3341 break;
3342
3343 default:
3344 assert (false && "unsupported $H variant - shouldn't get here");
3345 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3346 }
3347
3348 return SendOKResponse();
3349}
3350
3351GDBRemoteCommunicationServer::PacketResult
3352GDBRemoteCommunicationServer::Handle_interrupt (StringExtractorGDBRemote &packet)
3353{
3354 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3355
3356 // Ensure we're llgs.
3357 if (!IsGdbServer())
3358 {
3359 // Only supported on llgs
3360 return SendUnimplementedResponse ("");
3361 }
3362
3363 // Fail if we don't have a current process.
3364 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3365 {
3366 if (log)
3367 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3368 return SendErrorResponse (0x15);
3369 }
3370
3371 // Build the ResumeActionList - stop everything.
3372 lldb_private::ResumeActionList actions (StateType::eStateStopped, 0);
3373
3374 Error error = m_debugged_process_sp->Resume (actions);
3375 if (error.Fail ())
3376 {
3377 if (log)
3378 {
3379 log->Printf ("GDBRemoteCommunicationServer::%s failed for process %" PRIu64 ": %s",
3380 __FUNCTION__,
3381 m_debugged_process_sp->GetID (),
3382 error.AsCString ());
3383 }
3384 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
3385 }
3386
3387 if (log)
3388 log->Printf ("GDBRemoteCommunicationServer::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
3389
3390 // No response required from stop all.
3391 return PacketResult::Success;
3392}
3393
3394GDBRemoteCommunicationServer::PacketResult
3395GDBRemoteCommunicationServer::Handle_m (StringExtractorGDBRemote &packet)
3396{
3397 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3398
3399 // Ensure we're llgs.
3400 if (!IsGdbServer())
3401 {
3402 // Only supported on llgs
3403 return SendUnimplementedResponse ("");
3404 }
3405
3406 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3407 {
3408 if (log)
3409 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3410 return SendErrorResponse (0x15);
3411 }
3412
3413 // Parse out the memory address.
3414 packet.SetFilePos (strlen("m"));
3415 if (packet.GetBytesLeft() < 1)
3416 return SendIllFormedResponse(packet, "Too short m packet");
3417
3418 // Read the address. Punting on validation.
3419 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3420 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3421
3422 // Validate comma.
3423 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3424 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
3425
3426 // Get # bytes to read.
3427 if (packet.GetBytesLeft() < 1)
3428 return SendIllFormedResponse(packet, "Length missing in m packet");
3429
3430 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3431 if (byte_count == 0)
3432 {
3433 if (log)
3434 log->Printf ("GDBRemoteCommunicationServer::%s nothing to read: zero-length packet", __FUNCTION__);
3435 return PacketResult::Success;
3436 }
3437
3438 // Allocate the response buffer.
3439 std::string buf(byte_count, '\0');
3440 if (buf.empty())
3441 return SendErrorResponse (0x78);
3442
3443
3444 // Retrieve the process memory.
3445 lldb::addr_t bytes_read = 0;
3446 lldb_private::Error error = m_debugged_process_sp->ReadMemory (read_addr, &buf[0], byte_count, bytes_read);
3447 if (error.Fail ())
3448 {
3449 if (log)
3450 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
3451 return SendErrorResponse (0x08);
3452 }
3453
3454 if (bytes_read == 0)
3455 {
3456 if (log)
3457 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);
3458 return SendErrorResponse (0x08);
3459 }
3460
3461 StreamGDBRemote response;
3462 for (lldb::addr_t i = 0; i < bytes_read; ++i)
3463 response.PutHex8(buf[i]);
3464
3465 return SendPacketNoLock(response.GetData(), response.GetSize());
3466}
3467
3468GDBRemoteCommunication::PacketResult
3469GDBRemoteCommunicationServer::Handle_QSetDetachOnError (StringExtractorGDBRemote &packet)
3470{
3471 packet.SetFilePos(::strlen ("QSetDetachOnError:"));
3472 if (packet.GetU32(0))
3473 m_process_launch_info.GetFlags().Set (eLaunchFlagDetachOnError);
3474 else
3475 m_process_launch_info.GetFlags().Clear (eLaunchFlagDetachOnError);
3476 return SendOKResponse ();
3477}
3478
3479GDBRemoteCommunicationServer::PacketResult
3480GDBRemoteCommunicationServer::Handle_M (StringExtractorGDBRemote &packet)
3481{
3482 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3483
3484 // Ensure we're llgs.
3485 if (!IsGdbServer())
3486 {
3487 // Only supported on llgs
3488 return SendUnimplementedResponse ("");
3489 }
3490
3491 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3492 {
3493 if (log)
3494 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3495 return SendErrorResponse (0x15);
3496 }
3497
3498 // Parse out the memory address.
3499 packet.SetFilePos (strlen("M"));
3500 if (packet.GetBytesLeft() < 1)
3501 return SendIllFormedResponse(packet, "Too short M packet");
3502
3503 // Read the address. Punting on validation.
3504 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3505 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
3506
3507 // Validate comma.
3508 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3509 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
3510
3511 // Get # bytes to read.
3512 if (packet.GetBytesLeft() < 1)
3513 return SendIllFormedResponse(packet, "Length missing in M packet");
3514
3515 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3516 if (byte_count == 0)
3517 {
3518 if (log)
3519 log->Printf ("GDBRemoteCommunicationServer::%s nothing to write: zero-length packet", __FUNCTION__);
3520 return PacketResult::Success;
3521 }
3522
3523 // Validate colon.
3524 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
3525 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
3526
3527 // Allocate the conversion buffer.
3528 std::vector<uint8_t> buf(byte_count, 0);
3529 if (buf.empty())
3530 return SendErrorResponse (0x78);
3531
3532 // Convert the hex memory write contents to bytes.
3533 StreamGDBRemote response;
3534 const uint64_t convert_count = static_cast<uint64_t> (packet.GetHexBytes (&buf[0], byte_count, 0));
3535 if (convert_count != byte_count)
3536 {
3537 if (log)
3538 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);
3539 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
3540 }
3541
3542 // Write the process memory.
3543 lldb::addr_t bytes_written = 0;
3544 lldb_private::Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
3545 if (error.Fail ())
3546 {
3547 if (log)
3548 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
3549 return SendErrorResponse (0x09);
3550 }
3551
3552 if (bytes_written == 0)
3553 {
3554 if (log)
3555 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);
3556 return SendErrorResponse (0x09);
3557 }
3558
3559 return SendOKResponse ();
3560}
3561
3562GDBRemoteCommunicationServer::PacketResult
3563GDBRemoteCommunicationServer::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
3564{
3565 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3566
3567 // We don't support if we're not llgs.
3568 if (!IsGdbServer())
3569 return SendUnimplementedResponse ("");
3570
3571 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
3572 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
3573 // client only asks this when a process is being debugged.
3574
3575 // Ensure we have a process running; otherwise, we can't figure this out
3576 // since we won't have a NativeProcessProtocol.
3577 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3578 {
3579 if (log)
3580 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3581 return SendErrorResponse (0x15);
3582 }
3583
3584 // Test if we can get any region back when asking for the region around NULL.
3585 MemoryRegionInfo region_info;
3586 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
3587 if (error.Fail ())
3588 {
3589 // We don't support memory region info collection for this NativeProcessProtocol.
3590 return SendUnimplementedResponse ("");
3591 }
3592
3593 return SendOKResponse();
3594}
3595
3596GDBRemoteCommunicationServer::PacketResult
3597GDBRemoteCommunicationServer::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
3598{
3599 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3600
3601 // We don't support if we're not llgs.
3602 if (!IsGdbServer())
3603 return SendUnimplementedResponse ("");
3604
3605 // Ensure we have a process.
3606 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3607 {
3608 if (log)
3609 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3610 return SendErrorResponse (0x15);
3611 }
3612
3613 // Parse out the memory address.
3614 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
3615 if (packet.GetBytesLeft() < 1)
3616 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
3617
3618 // Read the address. Punting on validation.
3619 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3620
3621 StreamGDBRemote response;
3622
3623 // Get the memory region info for the target address.
3624 MemoryRegionInfo region_info;
3625 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
3626 if (error.Fail ())
3627 {
3628 // Return the error message.
3629
3630 response.PutCString ("error:");
3631 response.PutCStringAsRawHex8 (error.AsCString ());
3632 response.PutChar (';');
3633 }
3634 else
3635 {
3636 // Range start and size.
3637 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
3638
3639 // Permissions.
3640 if (region_info.GetReadable () ||
3641 region_info.GetWritable () ||
3642 region_info.GetExecutable ())
3643 {
3644 // Write permissions info.
3645 response.PutCString ("permissions:");
3646
3647 if (region_info.GetReadable ())
3648 response.PutChar ('r');
3649 if (region_info.GetWritable ())
3650 response.PutChar('w');
3651 if (region_info.GetExecutable())
3652 response.PutChar ('x');
3653
3654 response.PutChar (';');
3655 }
3656 }
3657
3658 return SendPacketNoLock(response.GetData(), response.GetSize());
3659}
3660
3661GDBRemoteCommunicationServer::PacketResult
3662GDBRemoteCommunicationServer::Handle_Z (StringExtractorGDBRemote &packet)
3663{
3664 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3665
3666 // We don't support if we're not llgs.
3667 if (!IsGdbServer())
3668 return SendUnimplementedResponse ("");
3669
3670 // Ensure we have a process.
3671 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3672 {
3673 if (log)
3674 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3675 return SendErrorResponse (0x15);
3676 }
3677
3678 // Parse out software or hardware breakpoint requested.
3679 packet.SetFilePos (strlen("Z"));
3680 if (packet.GetBytesLeft() < 1)
3681 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
3682
3683 bool want_breakpoint = true;
3684 bool want_hardware = false;
3685
3686 const char breakpoint_type_char = packet.GetChar ();
3687 switch (breakpoint_type_char)
3688 {
3689 case '0': want_hardware = false; want_breakpoint = true; break;
3690 case '1': want_hardware = true; want_breakpoint = true; break;
3691 case '2': want_breakpoint = false; break;
3692 case '3': want_breakpoint = false; break;
3693 default:
3694 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
3695
3696 }
3697
3698 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3699 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after breakpoint type");
3700
3701 // FIXME implement watchpoint support.
3702 if (!want_breakpoint)
3703 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3704
3705 // Parse out the breakpoint address.
3706 if (packet.GetBytesLeft() < 1)
3707 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
3708 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3709
3710 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3711 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
3712
3713 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3714 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3715 if (kind == std::numeric_limits<uint32_t>::max ())
3716 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse kind argument");
3717
3718 if (want_breakpoint)
3719 {
3720 // Try to set the breakpoint.
3721 const Error error = m_debugged_process_sp->SetBreakpoint (breakpoint_addr, kind, want_hardware);
3722 if (error.Success ())
3723 return SendOKResponse ();
3724 else
3725 {
3726 if (log)
3727 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to set breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3728 return SendErrorResponse (0x09);
3729 }
3730 }
3731
3732 // FIXME fix up after watchpoints are handled.
3733 return SendUnimplementedResponse ("");
3734}
3735
3736GDBRemoteCommunicationServer::PacketResult
3737GDBRemoteCommunicationServer::Handle_z (StringExtractorGDBRemote &packet)
3738{
3739 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3740
3741 // We don't support if we're not llgs.
3742 if (!IsGdbServer())
3743 return SendUnimplementedResponse ("");
3744
3745 // Ensure we have a process.
3746 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3747 {
3748 if (log)
3749 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3750 return SendErrorResponse (0x15);
3751 }
3752
3753 // Parse out software or hardware breakpoint requested.
3754 packet.SetFilePos (strlen("Z"));
3755 if (packet.GetBytesLeft() < 1)
3756 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
3757
3758 bool want_breakpoint = true;
3759
3760 const char breakpoint_type_char = packet.GetChar ();
3761 switch (breakpoint_type_char)
3762 {
3763 case '0': want_breakpoint = true; break;
3764 case '1': want_breakpoint = true; break;
3765 case '2': want_breakpoint = false; break;
3766 case '3': want_breakpoint = false; break;
3767 default:
3768 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
3769
3770 }
3771
3772 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3773 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after breakpoint type");
3774
3775 // FIXME implement watchpoint support.
3776 if (!want_breakpoint)
3777 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3778
3779 // Parse out the breakpoint address.
3780 if (packet.GetBytesLeft() < 1)
3781 return SendIllFormedResponse(packet, "Too short z packet, missing address");
3782 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3783
3784 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3785 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
3786
3787 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3788 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3789 if (kind == std::numeric_limits<uint32_t>::max ())
3790 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse kind argument");
3791
3792 if (want_breakpoint)
3793 {
3794 // Try to set the breakpoint.
3795 const Error error = m_debugged_process_sp->RemoveBreakpoint (breakpoint_addr);
3796 if (error.Success ())
3797 return SendOKResponse ();
3798 else
3799 {
3800 if (log)
3801 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to remove breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3802 return SendErrorResponse (0x09);
3803 }
3804 }
3805
3806 // FIXME fix up after watchpoints are handled.
3807 return SendUnimplementedResponse ("");
3808}
3809
3810GDBRemoteCommunicationServer::PacketResult
3811GDBRemoteCommunicationServer::Handle_s (StringExtractorGDBRemote &packet)
3812{
3813 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
3814
3815 // We don't support if we're not llgs.
3816 if (!IsGdbServer())
3817 return SendUnimplementedResponse ("");
3818
3819 // Ensure we have a process.
3820 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3821 {
3822 if (log)
3823 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3824 return SendErrorResponse (0x32);
3825 }
3826
3827 // We first try to use a continue thread id. If any one or any all set, use the current thread.
3828 // Bail out if we don't have a thread id.
3829 lldb::tid_t tid = GetContinueThreadID ();
3830 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3831 tid = GetCurrentThreadID ();
3832 if (tid == LLDB_INVALID_THREAD_ID)
3833 return SendErrorResponse (0x33);
3834
3835 // Double check that we have such a thread.
3836 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3837 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
3838 if (!thread_sp || thread_sp->GetID () != tid)
3839 return SendErrorResponse (0x33);
3840
3841 // Create the step action for the given thread.
3842 lldb_private::ResumeAction action = { tid, eStateStepping, 0 };
3843
3844 // Setup the actions list.
3845 lldb_private::ResumeActionList actions;
3846 actions.Append (action);
3847
3848 // All other threads stop while we're single stepping a thread.
3849 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
3850 Error error = m_debugged_process_sp->Resume (actions);
3851 if (error.Fail ())
3852 {
3853 if (log)
3854 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
3855 return SendErrorResponse(0x49);
3856 }
3857
3858 // No response here - the stop or exit will come from the resulting action.
3859 return PacketResult::Success;
3860}
3861
3862GDBRemoteCommunicationServer::PacketResult
3863GDBRemoteCommunicationServer::Handle_qSupported (StringExtractorGDBRemote &packet)
3864{
3865 StreamGDBRemote response;
3866
3867 // Features common to lldb-platform and llgs.
3868 uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet size--debugger can always use less
3869 response.Printf ("PacketSize=%x", max_packet_size);
3870
3871 response.PutCString (";QStartNoAckMode+");
3872 response.PutCString (";QThreadSuffixSupported+");
3873 response.PutCString (";QListThreadsInStopReply+");
3874#if defined(__linux__)
3875 response.PutCString (";qXfer:auxv:read+");
3876#endif
3877
3878 return SendPacketNoLock(response.GetData(), response.GetSize());
3879}
3880
3881GDBRemoteCommunicationServer::PacketResult
3882GDBRemoteCommunicationServer::Handle_QThreadSuffixSupported (StringExtractorGDBRemote &packet)
3883{
3884 m_thread_suffix_supported = true;
3885 return SendOKResponse();
3886}
3887
3888GDBRemoteCommunicationServer::PacketResult
3889GDBRemoteCommunicationServer::Handle_QListThreadsInStopReply (StringExtractorGDBRemote &packet)
3890{
3891 m_list_threads_in_stop_reply = true;
3892 return SendOKResponse();
3893}
3894
3895GDBRemoteCommunicationServer::PacketResult
3896GDBRemoteCommunicationServer::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
3897{
3898 // We don't support if we're not llgs.
3899 if (!IsGdbServer())
3900 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
3901
3902 // *BSD impls should be able to do this too.
3903#if defined(__linux__)
3904 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3905
3906 // Parse out the offset.
3907 packet.SetFilePos (strlen("qXfer:auxv:read::"));
3908 if (packet.GetBytesLeft () < 1)
3909 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3910
3911 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3912 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
3913 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3914
3915 // Parse out comma.
3916 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
3917 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
3918
3919 // Parse out the length.
3920 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3921 if (auxv_length == std::numeric_limits<uint64_t>::max ())
3922 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
3923
3924 // Grab the auxv data if we need it.
3925 if (!m_active_auxv_buffer_sp)
3926 {
3927 // Make sure we have a valid process.
3928 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3929 {
3930 if (log)
3931 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3932 return SendErrorResponse (0x10);
3933 }
3934
3935 // Grab the auxv data.
3936 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
3937 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
3938 {
3939 // Hmm, no auxv data, call that an error.
3940 if (log)
3941 log->Printf ("GDBRemoteCommunicationServer::%s failed, no auxv data retrieved", __FUNCTION__);
3942 m_active_auxv_buffer_sp.reset ();
3943 return SendErrorResponse (0x11);
3944 }
3945 }
3946
3947 // FIXME find out if/how I lock the stream here.
3948
3949 StreamGDBRemote response;
3950 bool done_with_buffer = false;
3951
3952 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
3953 {
3954 // We have nothing left to send. Mark the buffer as complete.
3955 response.PutChar ('l');
3956 done_with_buffer = true;
3957 }
3958 else
3959 {
3960 // Figure out how many bytes are available starting at the given offset.
3961 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
3962
3963 // Figure out how many bytes we're going to read.
3964 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
3965
3966 // Mark the response type according to whether we're reading the remainder of the auxv data.
3967 if (bytes_to_read >= bytes_remaining)
3968 {
3969 // There will be nothing left to read after this
3970 response.PutChar ('l');
3971 done_with_buffer = true;
3972 }
3973 else
3974 {
3975 // There will still be bytes to read after this request.
3976 response.PutChar ('m');
3977 }
3978
3979 // Now write the data in encoded binary form.
3980 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
3981 }
3982
3983 if (done_with_buffer)
3984 m_active_auxv_buffer_sp.reset ();
3985
3986 return SendPacketNoLock(response.GetData(), response.GetSize());
3987#else
3988 return SendUnimplementedResponse ("not implemented on this platform");
3989#endif
3990}
3991
3992GDBRemoteCommunicationServer::PacketResult
3993GDBRemoteCommunicationServer::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
3994{
3995 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3996
3997 // We don't support if we're not llgs.
3998 if (!IsGdbServer())
3999 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4000
4001 // Move past packet name.
4002 packet.SetFilePos (strlen ("QSaveRegisterState"));
4003
4004 // Get the thread to use.
4005 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4006 if (!thread_sp)
4007 {
4008 if (m_thread_suffix_supported)
4009 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
4010 else
4011 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4012 }
4013
4014 // Grab the register context for the thread.
4015 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4016 if (!reg_context_sp)
4017 {
4018 if (log)
4019 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 ());
4020 return SendErrorResponse (0x15);
4021 }
4022
4023 // Save registers to a buffer.
4024 DataBufferSP register_data_sp;
4025 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
4026 if (error.Fail ())
4027 {
4028 if (log)
4029 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4030 return SendErrorResponse (0x75);
4031 }
4032
4033 // Allocate a new save id.
4034 const uint32_t save_id = GetNextSavedRegistersID ();
4035 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
4036
4037 // Save the register data buffer under the save id.
4038 {
4039 Mutex::Locker locker (m_saved_registers_mutex);
4040 m_saved_registers_map[save_id] = register_data_sp;
4041 }
4042
4043 // Write the response.
4044 StreamGDBRemote response;
4045 response.Printf ("%" PRIu32, save_id);
4046 return SendPacketNoLock(response.GetData(), response.GetSize());
4047}
4048
4049GDBRemoteCommunicationServer::PacketResult
4050GDBRemoteCommunicationServer::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
4051{
4052 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4053
4054 // We don't support if we're not llgs.
4055 if (!IsGdbServer())
4056 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4057
4058 // Parse out save id.
4059 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
4060 if (packet.GetBytesLeft () < 1)
4061 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
4062
4063 const uint32_t save_id = packet.GetU32 (0);
4064 if (save_id == 0)
4065 {
4066 if (log)
4067 log->Printf ("GDBRemoteCommunicationServer::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
4068 return SendErrorResponse (0x76);
4069 }
4070
4071 // Get the thread to use.
4072 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4073 if (!thread_sp)
4074 {
4075 if (m_thread_suffix_supported)
4076 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
4077 else
4078 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4079 }
4080
4081 // Grab the register context for the thread.
4082 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4083 if (!reg_context_sp)
4084 {
4085 if (log)
4086 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 ());
4087 return SendErrorResponse (0x15);
4088 }
4089
4090 // Retrieve register state buffer, then remove from the list.
4091 DataBufferSP register_data_sp;
4092 {
4093 Mutex::Locker locker (m_saved_registers_mutex);
4094
4095 // Find the register set buffer for the given save id.
4096 auto it = m_saved_registers_map.find (save_id);
4097 if (it == m_saved_registers_map.end ())
4098 {
4099 if (log)
4100 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);
4101 return SendErrorResponse (0x77);
4102 }
4103 register_data_sp = it->second;
4104
4105 // Remove it from the map.
4106 m_saved_registers_map.erase (it);
4107 }
4108
4109 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
4110 if (error.Fail ())
4111 {
4112 if (log)
4113 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4114 return SendErrorResponse (0x77);
4115 }
4116
4117 return SendOKResponse();
4118}
4119
Todd Fiala7306cf32014-07-29 22:30:01 +00004120GDBRemoteCommunicationServer::PacketResult
4121GDBRemoteCommunicationServer::Handle_vAttach (StringExtractorGDBRemote &packet)
4122{
4123 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4124
4125 // We don't support if we're not llgs.
4126 if (!IsGdbServer())
4127 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4128
4129 // Consume the ';' after vAttach.
4130 packet.SetFilePos (strlen ("vAttach"));
4131 if (!packet.GetBytesLeft () || packet.GetChar () != ';')
4132 return SendIllFormedResponse (packet, "vAttach missing expected ';'");
4133
4134 // Grab the PID to which we will attach (assume hex encoding).
4135 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
4136 if (pid == LLDB_INVALID_PROCESS_ID)
4137 return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
4138
4139 // Attempt to attach.
4140 if (log)
4141 log->Printf ("GDBRemoteCommunicationServer::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
4142
4143 Error error = AttachToProcess (pid);
4144
4145 if (error.Fail ())
4146 {
4147 if (log)
4148 log->Printf ("GDBRemoteCommunicationServer::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
4149 return SendErrorResponse (0x01);
4150 }
4151
4152 // Notify we attached by sending a stop packet.
4153 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
4154
4155 return PacketResult::Success;
4156}
4157
Todd Fialaaf245d12014-06-30 21:05:18 +00004158void
4159GDBRemoteCommunicationServer::FlushInferiorOutput ()
4160{
4161 // If we're not monitoring an inferior's terminal, ignore this.
4162 if (!m_stdio_communication.IsConnected())
4163 return;
4164
4165 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
4166 if (log)
4167 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
4168
4169 // FIXME implement a timeout on the join.
4170 m_stdio_communication.JoinReadThread();
4171}
4172
4173void
4174GDBRemoteCommunicationServer::MaybeCloseInferiorTerminalConnection ()
4175{
4176 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4177
4178 // Tell the stdio connection to shut down.
4179 if (m_stdio_communication.IsConnected())
4180 {
4181 auto connection = m_stdio_communication.GetConnection();
4182 if (connection)
4183 {
4184 Error error;
4185 connection->Disconnect (&error);
4186
4187 if (error.Success ())
4188 {
4189 if (log)
4190 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
4191 }
4192 else
4193 {
4194 if (log)
4195 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
4196 }
4197 }
4198 }
4199}
4200
4201
4202lldb_private::NativeThreadProtocolSP
4203GDBRemoteCommunicationServer::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
4204{
4205 NativeThreadProtocolSP thread_sp;
4206
4207 // We have no thread if we don't have a process.
4208 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
4209 return thread_sp;
4210
4211 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
4212 // Use the current thread in that case.
4213 if (!m_thread_suffix_supported)
4214 {
4215 const lldb::tid_t current_tid = GetCurrentThreadID ();
4216 if (current_tid == LLDB_INVALID_THREAD_ID)
4217 return thread_sp;
4218 else if (current_tid == 0)
4219 {
4220 // Pick a thread.
4221 return m_debugged_process_sp->GetThreadAtIndex (0);
4222 }
4223 else
4224 return m_debugged_process_sp->GetThreadByID (current_tid);
4225 }
4226
4227 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4228
4229 // Parse out the ';'.
4230 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
4231 {
4232 if (log)
4233 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4234 return thread_sp;
4235 }
4236
4237 if (!packet.GetBytesLeft ())
4238 return thread_sp;
4239
4240 // Parse out thread: portion.
4241 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
4242 {
4243 if (log)
4244 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4245 return thread_sp;
4246 }
4247 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
4248 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4249 if (tid != 0)
4250 return m_debugged_process_sp->GetThreadByID (tid);
4251
4252 return thread_sp;
4253}
4254
4255lldb::tid_t
4256GDBRemoteCommunicationServer::GetCurrentThreadID () const
4257{
4258 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
4259 {
4260 // Use whatever the debug process says is the current thread id
4261 // since the protocol either didn't specify or specified we want
4262 // any/all threads marked as the current thread.
4263 if (!m_debugged_process_sp)
4264 return LLDB_INVALID_THREAD_ID;
4265 return m_debugged_process_sp->GetCurrentThreadID ();
4266 }
4267 // Use the specific current thread id set by the gdb remote protocol.
4268 return m_current_tid;
4269}
4270
4271uint32_t
4272GDBRemoteCommunicationServer::GetNextSavedRegistersID ()
4273{
4274 Mutex::Locker locker (m_saved_registers_mutex);
4275 return m_next_saved_registers_id++;
4276}
4277