blob: e59cf34f8e37f77e08e5ac583a40c08669ea9a2d [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
12#include "GDBRemoteCommunicationServer.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000013#include "lldb/Core/StreamGDBRemote.h"
Greg Clayton576d8832011-03-22 04:00:09 +000014
15// C Includes
16// C++ Includes
Todd Fialaaf245d12014-06-30 21:05:18 +000017#include <cstring>
Todd Fiala2850b1b2014-06-30 23:51:35 +000018#include <chrono>
19#include <thread>
Todd Fialaaf245d12014-06-30 21:05:18 +000020
Greg Clayton576d8832011-03-22 04:00:09 +000021// Other libraries and framework includes
22#include "llvm/ADT/Triple.h"
23#include "lldb/Interpreter/Args.h"
24#include "lldb/Core/ConnectionFileDescriptor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000025#include "lldb/Core/Debugger.h"
Greg Clayton576d8832011-03-22 04:00:09 +000026#include "lldb/Core/Log.h"
27#include "lldb/Core/State.h"
28#include "lldb/Core/StreamString.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000029#include "lldb/Host/Debug.h"
Enrico Granataf2bbf712011-07-15 02:26:42 +000030#include "lldb/Host/Endian.h"
Daniel Maleae0f8f572013-08-26 23:57:52 +000031#include "lldb/Host/File.h"
Greg Clayton576d8832011-03-22 04:00:09 +000032#include "lldb/Host/Host.h"
33#include "lldb/Host/TimeValue.h"
Todd Fialab8b49ec2014-01-28 00:34:23 +000034#include "lldb/Target/Platform.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000035#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000036#include "lldb/Target/NativeRegisterContext.h"
37#include "../../../Host/common/NativeProcessProtocol.h"
38#include "../../../Host/common/NativeThreadProtocol.h"
Greg Clayton576d8832011-03-22 04:00:09 +000039
40// Project includes
41#include "Utility/StringExtractorGDBRemote.h"
42#include "ProcessGDBRemote.h"
43#include "ProcessGDBRemoteLog.h"
44
45using namespace lldb;
46using namespace lldb_private;
47
48//----------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +000049// GDBRemote Errors
50//----------------------------------------------------------------------
51
52namespace
53{
54 enum GDBRemoteServerError
55 {
56 // Set to the first unused error number in literal form below
57 eErrorFirst = 29,
58 eErrorNoProcess = eErrorFirst,
59 eErrorResume,
60 eErrorExitStatus
61 };
62}
63
64//----------------------------------------------------------------------
Greg Clayton576d8832011-03-22 04:00:09 +000065// GDBRemoteCommunicationServer constructor
66//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +000067GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform) :
68 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
Todd Fialab8b49ec2014-01-28 00:34:23 +000069 m_platform_sp (Platform::GetDefaultPlatform ()),
Greg Clayton8b82f082011-04-12 05:54:46 +000070 m_async_thread (LLDB_INVALID_HOST_THREAD),
71 m_process_launch_info (),
72 m_process_launch_error (),
Daniel Maleae0f8f572013-08-26 23:57:52 +000073 m_spawned_pids (),
74 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton8b82f082011-04-12 05:54:46 +000075 m_proc_infos (),
76 m_proc_infos_index (0),
Greg Clayton2b98c562013-11-22 18:53:12 +000077 m_port_map (),
Todd Fialaaf245d12014-06-30 21:05:18 +000078 m_port_offset(0),
79 m_current_tid (LLDB_INVALID_THREAD_ID),
80 m_continue_tid (LLDB_INVALID_THREAD_ID),
81 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
82 m_debugged_process_sp (),
83 m_debugger_sp (),
84 m_stdio_communication ("process.stdio"),
85 m_exit_now (false),
86 m_inferior_prev_state (StateType::eStateInvalid),
87 m_thread_suffix_supported (false),
88 m_list_threads_in_stop_reply (false),
89 m_active_auxv_buffer_sp (),
90 m_saved_registers_mutex (),
91 m_saved_registers_map (),
92 m_next_saved_registers_id (1)
Greg Clayton576d8832011-03-22 04:00:09 +000093{
Todd Fialaaf245d12014-06-30 21:05:18 +000094 assert(is_platform && "must be lldb-platform if debugger is not specified");
Greg Clayton576d8832011-03-22 04:00:09 +000095}
96
Todd Fialab8b49ec2014-01-28 00:34:23 +000097GDBRemoteCommunicationServer::GDBRemoteCommunicationServer(bool is_platform,
Todd Fialaaf245d12014-06-30 21:05:18 +000098 const lldb::PlatformSP& platform_sp,
99 lldb::DebuggerSP &debugger_sp) :
Todd Fialab8b49ec2014-01-28 00:34:23 +0000100 GDBRemoteCommunication ("gdb-remote.server", "gdb-remote.server.rx_packet", is_platform),
101 m_platform_sp (platform_sp),
102 m_async_thread (LLDB_INVALID_HOST_THREAD),
103 m_process_launch_info (),
104 m_process_launch_error (),
105 m_spawned_pids (),
106 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
107 m_proc_infos (),
108 m_proc_infos_index (0),
109 m_port_map (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000110 m_port_offset(0),
111 m_current_tid (LLDB_INVALID_THREAD_ID),
112 m_continue_tid (LLDB_INVALID_THREAD_ID),
113 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
114 m_debugged_process_sp (),
115 m_debugger_sp (debugger_sp),
116 m_stdio_communication ("process.stdio"),
117 m_exit_now (false),
118 m_inferior_prev_state (StateType::eStateInvalid),
119 m_thread_suffix_supported (false),
120 m_list_threads_in_stop_reply (false),
121 m_active_auxv_buffer_sp (),
122 m_saved_registers_mutex (),
123 m_saved_registers_map (),
124 m_next_saved_registers_id (1)
Todd Fialab8b49ec2014-01-28 00:34:23 +0000125{
126 assert(platform_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000127 assert((is_platform || debugger_sp) && "must specify non-NULL debugger_sp when lldb-gdbserver");
Todd Fialab8b49ec2014-01-28 00:34:23 +0000128}
129
Greg Clayton576d8832011-03-22 04:00:09 +0000130//----------------------------------------------------------------------
131// Destructor
132//----------------------------------------------------------------------
133GDBRemoteCommunicationServer::~GDBRemoteCommunicationServer()
134{
135}
136
Todd Fialaaf245d12014-06-30 21:05:18 +0000137GDBRemoteCommunication::PacketResult
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000138GDBRemoteCommunicationServer::GetPacketAndSendResponse (uint32_t timeout_usec,
Greg Clayton1cb64962011-03-24 04:28:38 +0000139 Error &error,
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000140 bool &interrupt,
Greg Claytond314e812011-03-23 00:09:55 +0000141 bool &quit)
Greg Clayton576d8832011-03-22 04:00:09 +0000142{
143 StringExtractorGDBRemote packet;
Todd Fialaaf245d12014-06-30 21:05:18 +0000144
Greg Clayton3dedae12013-12-06 21:45:27 +0000145 PacketResult packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, timeout_usec);
146 if (packet_result == PacketResult::Success)
Greg Clayton576d8832011-03-22 04:00:09 +0000147 {
148 const StringExtractorGDBRemote::ServerPacketType packet_type = packet.GetServerPacketType ();
149 switch (packet_type)
150 {
Greg Clayton3dedae12013-12-06 21:45:27 +0000151 case StringExtractorGDBRemote::eServerPacketType_nack:
152 case StringExtractorGDBRemote::eServerPacketType_ack:
153 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000154
Greg Clayton3dedae12013-12-06 21:45:27 +0000155 case StringExtractorGDBRemote::eServerPacketType_invalid:
156 error.SetErrorString("invalid packet");
157 quit = true;
158 break;
Greg Claytond314e812011-03-23 00:09:55 +0000159
Greg Clayton3dedae12013-12-06 21:45:27 +0000160 default:
161 case StringExtractorGDBRemote::eServerPacketType_unimplemented:
162 packet_result = SendUnimplementedResponse (packet.GetStringRef().c_str());
163 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000164
Greg Clayton3dedae12013-12-06 21:45:27 +0000165 case StringExtractorGDBRemote::eServerPacketType_A:
166 packet_result = Handle_A (packet);
167 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000168
Greg Clayton3dedae12013-12-06 21:45:27 +0000169 case StringExtractorGDBRemote::eServerPacketType_qfProcessInfo:
170 packet_result = Handle_qfProcessInfo (packet);
171 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000172
Greg Clayton3dedae12013-12-06 21:45:27 +0000173 case StringExtractorGDBRemote::eServerPacketType_qsProcessInfo:
174 packet_result = Handle_qsProcessInfo (packet);
175 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000176
Greg Clayton3dedae12013-12-06 21:45:27 +0000177 case StringExtractorGDBRemote::eServerPacketType_qC:
178 packet_result = Handle_qC (packet);
179 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000180
Greg Clayton3dedae12013-12-06 21:45:27 +0000181 case StringExtractorGDBRemote::eServerPacketType_qHostInfo:
182 packet_result = Handle_qHostInfo (packet);
183 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000184
Greg Clayton3dedae12013-12-06 21:45:27 +0000185 case StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer:
186 packet_result = Handle_qLaunchGDBServer (packet);
187 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000188
Greg Clayton3dedae12013-12-06 21:45:27 +0000189 case StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess:
190 packet_result = Handle_qKillSpawnedProcess (packet);
191 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000192
Todd Fiala403edc52014-01-23 22:05:44 +0000193 case StringExtractorGDBRemote::eServerPacketType_k:
194 packet_result = Handle_k (packet);
Todd Fialaaf245d12014-06-30 21:05:18 +0000195 quit = true;
Todd Fiala403edc52014-01-23 22:05:44 +0000196 break;
197
Greg Clayton3dedae12013-12-06 21:45:27 +0000198 case StringExtractorGDBRemote::eServerPacketType_qLaunchSuccess:
199 packet_result = Handle_qLaunchSuccess (packet);
200 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000201
Greg Clayton3dedae12013-12-06 21:45:27 +0000202 case StringExtractorGDBRemote::eServerPacketType_qGroupName:
203 packet_result = Handle_qGroupName (packet);
204 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000205
Todd Fialaaf245d12014-06-30 21:05:18 +0000206 case StringExtractorGDBRemote::eServerPacketType_qProcessInfo:
207 packet_result = Handle_qProcessInfo (packet);
208 break;
209
Greg Clayton3dedae12013-12-06 21:45:27 +0000210 case StringExtractorGDBRemote::eServerPacketType_qProcessInfoPID:
211 packet_result = Handle_qProcessInfoPID (packet);
212 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000213
Greg Clayton3dedae12013-12-06 21:45:27 +0000214 case StringExtractorGDBRemote::eServerPacketType_qSpeedTest:
215 packet_result = Handle_qSpeedTest (packet);
216 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000217
Greg Clayton3dedae12013-12-06 21:45:27 +0000218 case StringExtractorGDBRemote::eServerPacketType_qUserName:
219 packet_result = Handle_qUserName (packet);
220 break;
Greg Clayton32e0a752011-03-30 18:16:51 +0000221
Greg Clayton3dedae12013-12-06 21:45:27 +0000222 case StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir:
223 packet_result = Handle_qGetWorkingDir(packet);
224 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000225
Greg Clayton3dedae12013-12-06 21:45:27 +0000226 case StringExtractorGDBRemote::eServerPacketType_QEnvironment:
227 packet_result = Handle_QEnvironment (packet);
228 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000229
Greg Clayton3dedae12013-12-06 21:45:27 +0000230 case StringExtractorGDBRemote::eServerPacketType_QLaunchArch:
231 packet_result = Handle_QLaunchArch (packet);
232 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000233
Greg Clayton3dedae12013-12-06 21:45:27 +0000234 case StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR:
235 packet_result = Handle_QSetDisableASLR (packet);
236 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000237
Jim Ingham106d0282014-06-25 02:32:56 +0000238 case StringExtractorGDBRemote::eServerPacketType_QSetDetachOnError:
239 packet_result = Handle_QSetDetachOnError (packet);
240 break;
241
Greg Clayton3dedae12013-12-06 21:45:27 +0000242 case StringExtractorGDBRemote::eServerPacketType_QSetSTDIN:
243 packet_result = Handle_QSetSTDIN (packet);
244 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000245
Greg Clayton3dedae12013-12-06 21:45:27 +0000246 case StringExtractorGDBRemote::eServerPacketType_QSetSTDOUT:
247 packet_result = Handle_QSetSTDOUT (packet);
248 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000249
Greg Clayton3dedae12013-12-06 21:45:27 +0000250 case StringExtractorGDBRemote::eServerPacketType_QSetSTDERR:
251 packet_result = Handle_QSetSTDERR (packet);
252 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000253
Greg Clayton3dedae12013-12-06 21:45:27 +0000254 case StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir:
255 packet_result = Handle_QSetWorkingDir (packet);
256 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000257
Greg Clayton3dedae12013-12-06 21:45:27 +0000258 case StringExtractorGDBRemote::eServerPacketType_QStartNoAckMode:
259 packet_result = Handle_QStartNoAckMode (packet);
260 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000261
Greg Clayton3dedae12013-12-06 21:45:27 +0000262 case StringExtractorGDBRemote::eServerPacketType_qPlatform_mkdir:
263 packet_result = Handle_qPlatform_mkdir (packet);
264 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000265
Greg Clayton3dedae12013-12-06 21:45:27 +0000266 case StringExtractorGDBRemote::eServerPacketType_qPlatform_chmod:
267 packet_result = Handle_qPlatform_chmod (packet);
268 break;
Greg Claytonfbb76342013-11-20 21:07:01 +0000269
Greg Clayton3dedae12013-12-06 21:45:27 +0000270 case StringExtractorGDBRemote::eServerPacketType_qPlatform_shell:
271 packet_result = Handle_qPlatform_shell (packet);
272 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000273
Todd Fialaaf245d12014-06-30 21:05:18 +0000274 case StringExtractorGDBRemote::eServerPacketType_C:
275 packet_result = Handle_C (packet);
276 break;
277
278 case StringExtractorGDBRemote::eServerPacketType_c:
279 packet_result = Handle_c (packet);
280 break;
281
282 case StringExtractorGDBRemote::eServerPacketType_vCont:
283 packet_result = Handle_vCont (packet);
284 break;
285
286 case StringExtractorGDBRemote::eServerPacketType_vCont_actions:
287 packet_result = Handle_vCont_actions (packet);
288 break;
289
290 case StringExtractorGDBRemote::eServerPacketType_stop_reason: // ?
291 packet_result = Handle_stop_reason (packet);
292 break;
293
Greg Clayton3dedae12013-12-06 21:45:27 +0000294 case StringExtractorGDBRemote::eServerPacketType_vFile_open:
295 packet_result = Handle_vFile_Open (packet);
296 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000297
Greg Clayton3dedae12013-12-06 21:45:27 +0000298 case StringExtractorGDBRemote::eServerPacketType_vFile_close:
299 packet_result = Handle_vFile_Close (packet);
300 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000301
Greg Clayton3dedae12013-12-06 21:45:27 +0000302 case StringExtractorGDBRemote::eServerPacketType_vFile_pread:
303 packet_result = Handle_vFile_pRead (packet);
304 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000305
Greg Clayton3dedae12013-12-06 21:45:27 +0000306 case StringExtractorGDBRemote::eServerPacketType_vFile_pwrite:
307 packet_result = Handle_vFile_pWrite (packet);
308 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000309
Greg Clayton3dedae12013-12-06 21:45:27 +0000310 case StringExtractorGDBRemote::eServerPacketType_vFile_size:
311 packet_result = Handle_vFile_Size (packet);
312 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000313
Greg Clayton3dedae12013-12-06 21:45:27 +0000314 case StringExtractorGDBRemote::eServerPacketType_vFile_mode:
315 packet_result = Handle_vFile_Mode (packet);
316 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000317
Greg Clayton3dedae12013-12-06 21:45:27 +0000318 case StringExtractorGDBRemote::eServerPacketType_vFile_exists:
319 packet_result = Handle_vFile_Exists (packet);
320 break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +0000321
Greg Clayton3dedae12013-12-06 21:45:27 +0000322 case StringExtractorGDBRemote::eServerPacketType_vFile_stat:
323 packet_result = Handle_vFile_Stat (packet);
324 break;
Greg Claytonfbb76342013-11-20 21:07:01 +0000325
Greg Clayton3dedae12013-12-06 21:45:27 +0000326 case StringExtractorGDBRemote::eServerPacketType_vFile_md5:
327 packet_result = Handle_vFile_MD5 (packet);
328 break;
329
330 case StringExtractorGDBRemote::eServerPacketType_vFile_symlink:
331 packet_result = Handle_vFile_symlink (packet);
332 break;
333
334 case StringExtractorGDBRemote::eServerPacketType_vFile_unlink:
335 packet_result = Handle_vFile_unlink (packet);
336 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000337
338 case StringExtractorGDBRemote::eServerPacketType_qRegisterInfo:
339 packet_result = Handle_qRegisterInfo (packet);
340 break;
341
342 case StringExtractorGDBRemote::eServerPacketType_qfThreadInfo:
343 packet_result = Handle_qfThreadInfo (packet);
344 break;
345
346 case StringExtractorGDBRemote::eServerPacketType_qsThreadInfo:
347 packet_result = Handle_qsThreadInfo (packet);
348 break;
349
350 case StringExtractorGDBRemote::eServerPacketType_p:
351 packet_result = Handle_p (packet);
352 break;
353
354 case StringExtractorGDBRemote::eServerPacketType_P:
355 packet_result = Handle_P (packet);
356 break;
357
358 case StringExtractorGDBRemote::eServerPacketType_H:
359 packet_result = Handle_H (packet);
360 break;
361
362 case StringExtractorGDBRemote::eServerPacketType_m:
363 packet_result = Handle_m (packet);
364 break;
365
366 case StringExtractorGDBRemote::eServerPacketType_M:
367 packet_result = Handle_M (packet);
368 break;
369
370 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported:
371 packet_result = Handle_qMemoryRegionInfoSupported (packet);
372 break;
373
374 case StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo:
375 packet_result = Handle_qMemoryRegionInfo (packet);
376 break;
377
378 case StringExtractorGDBRemote::eServerPacketType_interrupt:
379 if (IsGdbServer ())
380 packet_result = Handle_interrupt (packet);
381 else
382 {
383 error.SetErrorString("interrupt received");
384 interrupt = true;
385 }
386 break;
387
388 case StringExtractorGDBRemote::eServerPacketType_Z:
389 packet_result = Handle_Z (packet);
390 break;
391
392 case StringExtractorGDBRemote::eServerPacketType_z:
393 packet_result = Handle_z (packet);
394 break;
395
396 case StringExtractorGDBRemote::eServerPacketType_s:
397 packet_result = Handle_s (packet);
398 break;
399
400 case StringExtractorGDBRemote::eServerPacketType_qSupported:
401 packet_result = Handle_qSupported (packet);
402 break;
403
404 case StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported:
405 packet_result = Handle_QThreadSuffixSupported (packet);
406 break;
407
408 case StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply:
409 packet_result = Handle_QListThreadsInStopReply (packet);
410 break;
411
412 case StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read:
413 packet_result = Handle_qXfer_auxv_read (packet);
414 break;
415
416 case StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState:
417 packet_result = Handle_QSaveRegisterState (packet);
418 break;
419
420 case StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState:
421 packet_result = Handle_QRestoreRegisterState (packet);
422 break;
Greg Clayton576d8832011-03-22 04:00:09 +0000423 }
Greg Clayton576d8832011-03-22 04:00:09 +0000424 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000425 else
426 {
427 if (!IsConnected())
Greg Clayton3dedae12013-12-06 21:45:27 +0000428 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000429 error.SetErrorString("lost connection");
Greg Clayton3dedae12013-12-06 21:45:27 +0000430 quit = true;
431 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000432 else
Greg Clayton3dedae12013-12-06 21:45:27 +0000433 {
Greg Clayton1cb64962011-03-24 04:28:38 +0000434 error.SetErrorString("timeout");
Greg Clayton3dedae12013-12-06 21:45:27 +0000435 }
Greg Clayton1cb64962011-03-24 04:28:38 +0000436 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000437
438 // Check if anything occurred that would force us to want to exit.
439 if (m_exit_now)
440 quit = true;
441
442 return packet_result;
Greg Clayton576d8832011-03-22 04:00:09 +0000443}
444
Todd Fiala403edc52014-01-23 22:05:44 +0000445lldb_private::Error
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000446GDBRemoteCommunicationServer::SetLaunchArguments (const char *const args[], int argc)
Todd Fiala403edc52014-01-23 22:05:44 +0000447{
448 if ((argc < 1) || !args || !args[0] || !args[0][0])
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000449 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
Todd Fiala403edc52014-01-23 22:05:44 +0000450
Todd Fiala403edc52014-01-23 22:05:44 +0000451 m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000452 return lldb_private::Error ();
453}
454
455lldb_private::Error
456GDBRemoteCommunicationServer::SetLaunchFlags (unsigned int launch_flags)
457{
Todd Fiala403edc52014-01-23 22:05:44 +0000458 m_process_launch_info.GetFlags ().Set (launch_flags);
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000459 return lldb_private::Error ();
460}
461
462lldb_private::Error
463GDBRemoteCommunicationServer::LaunchProcess ()
464{
Todd Fialaaf245d12014-06-30 21:05:18 +0000465 // FIXME This looks an awful lot like we could override this in
466 // derived classes, one for lldb-platform, the other for lldb-gdbserver.
467 if (IsGdbServer ())
468 return LaunchDebugServerProcess ();
469 else
470 return LaunchPlatformProcess ();
471}
472
473lldb_private::Error
474GDBRemoteCommunicationServer::LaunchDebugServerProcess ()
475{
476 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
477
478 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
479 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
480
481 lldb_private::Error error;
482 {
483 Mutex::Locker locker (m_debugged_process_mutex);
484 assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
485 error = m_platform_sp->LaunchNativeProcess (
486 m_process_launch_info,
487 *this,
488 m_debugged_process_sp);
489 }
490
491 if (!error.Success ())
492 {
493 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
494 return error;
495 }
496
497 // Setup stdout/stderr mapping from inferior.
498 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
499 if (terminal_fd >= 0)
500 {
501 if (log)
502 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
503 error = SetSTDIOFileDescriptor (terminal_fd);
504 if (error.Fail ())
505 return error;
506 }
507 else
508 {
509 if (log)
510 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
511 }
512
513 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
514
515 // Add to list of spawned processes.
516 lldb::pid_t pid;
517 if ((pid = m_process_launch_info.GetProcessID ()) != LLDB_INVALID_PROCESS_ID)
518 {
519 // add to spawned pids
520 {
521 Mutex::Locker locker (m_spawned_pids_mutex);
522 // On an lldb-gdbserver, we would expect there to be only one.
523 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
524 m_spawned_pids.insert (pid);
525 }
526 }
527
528 if (error.Success ())
529 {
530 if (log)
531 log->Printf ("GDBRemoteCommunicationServer::%s beginning check to wait for launched application to hit first stop", __FUNCTION__);
532
533 int iteration = 0;
534 // Wait for the process to hit its first stop state.
535 while (!StateIsStoppedState (m_debugged_process_sp->GetState (), false))
536 {
537 if (log)
538 log->Printf ("GDBRemoteCommunicationServer::%s waiting for launched process to hit first stop (%d)...", __FUNCTION__, iteration++);
539
Todd Fiala2850b1b2014-06-30 23:51:35 +0000540 // FIXME use a finer granularity.
541 std::this_thread::sleep_for(std::chrono::seconds(1));
Todd Fialaaf245d12014-06-30 21:05:18 +0000542 }
543
544 if (log)
545 log->Printf ("GDBRemoteCommunicationServer::%s launched application has hit first stop", __FUNCTION__);
546
547 }
548
549 return error;
550}
551
552lldb_private::Error
553GDBRemoteCommunicationServer::LaunchPlatformProcess ()
554{
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000555 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
556 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
557
558 // specify the process monitor if not already set. This should
559 // generally be what happens since we need to reap started
560 // processes.
561 if (!m_process_launch_info.GetMonitorProcessCallback ())
562 m_process_launch_info.SetMonitorProcessCallback(ReapDebuggedProcess, this, false);
Todd Fiala403edc52014-01-23 22:05:44 +0000563
Todd Fialab8b49ec2014-01-28 00:34:23 +0000564 lldb_private::Error error = m_platform_sp->LaunchProcess (m_process_launch_info);
Todd Fiala403edc52014-01-23 22:05:44 +0000565 if (!error.Success ())
566 {
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000567 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
Todd Fiala403edc52014-01-23 22:05:44 +0000568 return error;
569 }
570
Todd Fiala3e92a2b2014-01-24 00:52:53 +0000571 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 +0000572
573 // add to list of spawned processes. On an lldb-gdbserver, we
574 // would expect there to be only one.
575 lldb::pid_t pid;
576 if ( (pid = m_process_launch_info.GetProcessID()) != LLDB_INVALID_PROCESS_ID )
577 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000578 // add to spawned pids
579 {
580 Mutex::Locker locker (m_spawned_pids_mutex);
581 m_spawned_pids.insert(pid);
582 }
Todd Fiala403edc52014-01-23 22:05:44 +0000583 }
584
585 return error;
586}
587
Todd Fialaaf245d12014-06-30 21:05:18 +0000588lldb_private::Error
589GDBRemoteCommunicationServer::AttachToProcess (lldb::pid_t pid)
590{
591 Error error;
592
593 if (!IsGdbServer ())
594 {
595 error.SetErrorString("cannot AttachToProcess () unless process is lldb-gdbserver");
596 return error;
597 }
598
599 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
600 if (log)
601 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64, __FUNCTION__, pid);
602
603 // Scope for mutex locker.
604 {
605 // Before we try to attach, make sure we aren't already monitoring something else.
606 Mutex::Locker locker (m_spawned_pids_mutex);
607 if (!m_spawned_pids.empty ())
608 {
609 error.SetErrorStringWithFormat ("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, *m_spawned_pids.begin());
610 return error;
611 }
612
613 // Try to attach.
614 error = m_platform_sp->AttachNativeProcess (pid, *this, m_debugged_process_sp);
615 if (!error.Success ())
616 {
617 fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
618 return error;
619 }
620
621 // Setup stdout/stderr mapping from inferior.
622 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
623 if (terminal_fd >= 0)
624 {
625 if (log)
626 log->Printf ("ProcessGDBRemoteCommunicationServer::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
627 error = SetSTDIOFileDescriptor (terminal_fd);
628 if (error.Fail ())
629 return error;
630 }
631 else
632 {
633 if (log)
634 log->Printf ("ProcessGDBRemoteCommunicationServer::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
635 }
636
637 printf ("Attached to process %" PRIu64 "...\n", pid);
638
639 // Add to list of spawned processes.
640 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
641 m_spawned_pids.insert (pid);
642
643 return error;
644 }
645}
646
647void
648GDBRemoteCommunicationServer::InitializeDelegate (lldb_private::NativeProcessProtocol *process)
649{
650 assert (process && "process cannot be NULL");
651 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
652 if (log)
653 {
654 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
655 __FUNCTION__,
656 process->GetID (),
657 StateAsCString (process->GetState ()));
658 }
659}
660
661GDBRemoteCommunication::PacketResult
662GDBRemoteCommunicationServer::SendWResponse (lldb_private::NativeProcessProtocol *process)
663{
664 assert (process && "process cannot be NULL");
665 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
666
667 // send W notification
668 ExitType exit_type = ExitType::eExitTypeInvalid;
669 int return_code = 0;
670 std::string exit_description;
671
672 const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
673 if (!got_exit_info)
674 {
675 if (log)
676 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
677
678 StreamGDBRemote response;
679 response.PutChar ('E');
680 response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
681 return SendPacketNoLock(response.GetData(), response.GetSize());
682 }
683 else
684 {
685 if (log)
686 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 ());
687
688 StreamGDBRemote response;
689
690 char return_type_code;
691 switch (exit_type)
692 {
693 case ExitType::eExitTypeExit: return_type_code = 'W'; break;
694 case ExitType::eExitTypeSignal: return_type_code = 'X'; break;
695 case ExitType::eExitTypeStop: return_type_code = 'S'; break;
696
697 case ExitType::eExitTypeInvalid:
698 default: return_type_code = 'E'; break;
699 }
700 response.PutChar (return_type_code);
701
702 // POSIX exit status limited to unsigned 8 bits.
703 response.PutHex8 (return_code);
704
705 return SendPacketNoLock(response.GetData(), response.GetSize());
706 }
707}
708
709static void
710AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
711{
712 int64_t i;
713 if (swap)
714 {
715 for (i = buf_size-1; i >= 0; i--)
716 response.PutHex8 (buf[i]);
717 }
718 else
719 {
720 for (i = 0; i < buf_size; i++)
721 response.PutHex8 (buf[i]);
722 }
723}
724
725static void
726WriteRegisterValueInHexFixedWidth (StreamString &response,
727 NativeRegisterContextSP &reg_ctx_sp,
728 const RegisterInfo &reg_info,
729 const RegisterValue *reg_value_p)
730{
731 RegisterValue reg_value;
732 if (!reg_value_p)
733 {
734 Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
735 if (error.Success ())
736 reg_value_p = &reg_value;
737 // else log.
738 }
739
740 if (reg_value_p)
741 {
742 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
743 }
744 else
745 {
746 // Zero-out any unreadable values.
747 if (reg_info.byte_size > 0)
748 {
749 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
750 AppendHexValue (response, zeros.data(), zeros.size(), false);
751 }
752 }
753}
754
755// WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
756
757
758static void
759WriteGdbRegnumWithFixedWidthHexRegisterValue (StreamString &response,
760 NativeRegisterContextSP &reg_ctx_sp,
761 const RegisterInfo &reg_info,
762 const RegisterValue &reg_value)
763{
764 // Output the register number as 'NN:VVVVVVVV;' where NN is a 2 bytes HEX
765 // gdb register number, and VVVVVVVV is the correct number of hex bytes
766 // as ASCII for the register value.
767 if (reg_info.kinds[eRegisterKindGDB] == LLDB_INVALID_REGNUM)
768 return;
769
770 response.Printf ("%.02x:", reg_info.kinds[eRegisterKindGDB]);
771 WriteRegisterValueInHexFixedWidth (response, reg_ctx_sp, reg_info, &reg_value);
772 response.PutChar (';');
773}
774
775
776GDBRemoteCommunication::PacketResult
777GDBRemoteCommunicationServer::SendStopReplyPacketForThread (lldb::tid_t tid)
778{
779 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
780
781 // Ensure we're llgs.
782 if (!IsGdbServer ())
783 {
784 // Only supported on llgs
785 return SendUnimplementedResponse ("");
786 }
787
788 // Ensure we have a debugged process.
789 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
790 return SendErrorResponse (50);
791
792 if (log)
793 log->Printf ("GDBRemoteCommunicationServer::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
794 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
795
796 // Ensure we can get info on the given thread.
797 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
798 if (!thread_sp)
799 return SendErrorResponse (51);
800
801 // Grab the reason this thread stopped.
802 struct ThreadStopInfo tid_stop_info;
803 if (!thread_sp->GetStopReason (tid_stop_info))
804 return SendErrorResponse (52);
805
806 const bool did_exec = tid_stop_info.reason == eStopReasonExec;
807 // FIXME implement register handling for exec'd inferiors.
808 // if (did_exec)
809 // {
810 // const bool force = true;
811 // InitializeRegisters(force);
812 // }
813
814 StreamString response;
815 // Output the T packet with the thread
816 response.PutChar ('T');
817 int signum = tid_stop_info.details.signal.signo;
818 if (log)
819 {
820 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
821 __FUNCTION__,
822 m_debugged_process_sp->GetID (),
823 tid,
824 signum,
825 tid_stop_info.reason,
826 tid_stop_info.details.exception.type);
827 }
828
829 switch (tid_stop_info.reason)
830 {
831 case eStopReasonSignal:
832 case eStopReasonException:
833 signum = thread_sp->TranslateStopInfoToGdbSignal (tid_stop_info);
834 break;
835 default:
836 signum = 0;
837 if (log)
838 {
839 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " has stop reason %d, using signo = 0 in stop reply response",
840 __FUNCTION__,
841 m_debugged_process_sp->GetID (),
842 tid,
843 tid_stop_info.reason);
844 }
845 break;
846 }
847
848 // Print the signal number.
849 response.PutHex8 (signum & 0xff);
850
851 // Include the tid.
852 response.Printf ("thread:%" PRIx64 ";", tid);
853
854 // Include the thread name if there is one.
855 const char *thread_name = thread_sp->GetName ();
856 if (thread_name && thread_name[0])
857 {
858 size_t thread_name_len = strlen(thread_name);
859
860 if (::strcspn (thread_name, "$#+-;:") == thread_name_len)
861 {
862 response.PutCString ("name:");
863 response.PutCString (thread_name);
864 }
865 else
866 {
867 // The thread name contains special chars, send as hex bytes.
868 response.PutCString ("hexname:");
869 response.PutCStringAsRawHex8 (thread_name);
870 }
871 response.PutChar (';');
872 }
873
874 // FIXME look for analog
875 // thread_identifier_info_data_t thread_ident_info;
876 // if (DNBThreadGetIdentifierInfo (pid, tid, &thread_ident_info))
877 // {
878 // if (thread_ident_info.dispatch_qaddr != 0)
879 // ostrm << std::hex << "qaddr:" << thread_ident_info.dispatch_qaddr << ';';
880 // }
881
882 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
883 // will send all thread IDs back in the "threads" key whose value is
884 // a listc of hex thread IDs separated by commas:
885 // "threads:10a,10b,10c;"
886 // This will save the debugger from having to send a pair of qfThreadInfo
887 // and qsThreadInfo packets, but it also might take a lot of room in the
888 // stop reply packet, so it must be enabled only on systems where there
889 // are no limits on packet lengths.
890 if (m_list_threads_in_stop_reply)
891 {
892 response.PutCString ("threads:");
893
894 uint32_t thread_index = 0;
895 NativeThreadProtocolSP listed_thread_sp;
896 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))
897 {
898 if (thread_index > 0)
899 response.PutChar (',');
900 response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
901 }
902 response.PutChar (';');
903 }
904
905 //
906 // Expedite registers.
907 //
908
909 // Grab the register context.
910 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
911 if (reg_ctx_sp)
912 {
913 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
914 const RegisterSet *reg_set_p;
915 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
916 {
917 if (log)
918 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);
919
920 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
921 {
922 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
923 if (reg_info_p == nullptr)
924 {
925 if (log)
926 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);
927 }
928 else if (reg_info_p->value_regs == nullptr)
929 {
930 // Only expediate registers that are not contained in other registers.
931 RegisterValue reg_value;
932 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
933 if (error.Success ())
934 WriteGdbRegnumWithFixedWidthHexRegisterValue (response, reg_ctx_sp, *reg_info_p, reg_value);
935 else
936 {
937 if (log)
938 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 ());
939
940 }
941 }
942 }
943 }
944 }
945
946 if (did_exec)
947 {
948 response.PutCString ("reason:exec;");
949 }
950 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
951 {
952 response.PutCString ("metype:");
953 response.PutHex64 (tid_stop_info.details.exception.type);
954 response.PutCString (";mecount:");
955 response.PutHex32 (tid_stop_info.details.exception.data_count);
956 response.PutChar (';');
957
958 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
959 {
960 response.PutCString ("medata:");
961 response.PutHex64 (tid_stop_info.details.exception.data[i]);
962 response.PutChar (';');
963 }
964 }
965
966 return SendPacketNoLock (response.GetData(), response.GetSize());
967}
968
969void
970GDBRemoteCommunicationServer::HandleInferiorState_Exited (lldb_private::NativeProcessProtocol *process)
971{
972 assert (process && "process cannot be NULL");
973
974 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
975 if (log)
976 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
977
978 // Send the exit result, and don't flush output.
979 // Note: flushing output here would join the inferior stdio reflection thread, which
980 // would gunk up the waitpid monitor thread that is calling this.
981 PacketResult result = SendStopReasonForState (StateType::eStateExited, false);
982 if (result != PacketResult::Success)
983 {
984 if (log)
985 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
986 }
987
988 // Remove the process from the list of spawned pids.
989 {
990 Mutex::Locker locker (m_spawned_pids_mutex);
991 if (m_spawned_pids.erase (process->GetID ()) < 1)
992 {
993 if (log)
994 log->Printf ("GDBRemoteCommunicationServer::%s failed to remove PID %" PRIu64 " from the spawned pids list", __FUNCTION__, process->GetID ());
995
996 }
997 }
998
999 // FIXME can't do this yet - since process state propagation is currently
1000 // synchronous, it is running off the NativeProcessProtocol's innards and
1001 // will tear down the NPP while it still has code to execute.
1002#if 0
1003 // Clear the NativeProcessProtocol pointer.
1004 {
1005 Mutex::Locker locker (m_debugged_process_mutex);
1006 m_debugged_process_sp.reset();
1007 }
1008#endif
1009
1010 // Close the pipe to the inferior terminal i/o if we launched it
1011 // and set one up. Otherwise, 'k' and its flush of stdio could
1012 // end up waiting on a thread join that will never end. Consider
1013 // adding a timeout to the connection thread join call so we
1014 // can avoid that scenario altogether.
1015 MaybeCloseInferiorTerminalConnection ();
1016
1017 // We are ready to exit the debug monitor.
1018 m_exit_now = true;
1019}
1020
1021void
1022GDBRemoteCommunicationServer::HandleInferiorState_Stopped (lldb_private::NativeProcessProtocol *process)
1023{
1024 assert (process && "process cannot be NULL");
1025
1026 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1027 if (log)
1028 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
1029
1030 // Send the stop reason unless this is the stop after the
1031 // launch or attach.
1032 switch (m_inferior_prev_state)
1033 {
1034 case eStateLaunching:
1035 case eStateAttaching:
1036 // Don't send anything per debugserver behavior.
1037 break;
1038 default:
1039 // In all other cases, send the stop reason.
1040 PacketResult result = SendStopReasonForState (StateType::eStateStopped, false);
1041 if (result != PacketResult::Success)
1042 {
1043 if (log)
1044 log->Printf ("GDBRemoteCommunicationServer::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
1045 }
1046 break;
1047 }
1048}
1049
1050void
1051GDBRemoteCommunicationServer::ProcessStateChanged (lldb_private::NativeProcessProtocol *process, lldb::StateType state)
1052{
1053 assert (process && "process cannot be NULL");
1054 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1055 if (log)
1056 {
1057 log->Printf ("GDBRemoteCommunicationServer::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
1058 __FUNCTION__,
1059 process->GetID (),
1060 StateAsCString (state));
1061 }
1062
1063 switch (state)
1064 {
1065 case StateType::eStateExited:
1066 HandleInferiorState_Exited (process);
1067 break;
1068
1069 case StateType::eStateStopped:
1070 HandleInferiorState_Stopped (process);
1071 break;
1072
1073 default:
1074 if (log)
1075 {
1076 log->Printf ("GDBRemoteCommunicationServer::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
1077 __FUNCTION__,
1078 process->GetID (),
1079 StateAsCString (state));
1080 }
1081 break;
1082 }
1083
1084 // Remember the previous state reported to us.
1085 m_inferior_prev_state = state;
1086}
1087
1088GDBRemoteCommunication::PacketResult
1089GDBRemoteCommunicationServer::SendONotification (const char *buffer, uint32_t len)
1090{
1091 if ((buffer == nullptr) || (len == 0))
1092 {
1093 // Nothing to send.
1094 return PacketResult::Success;
1095 }
1096
1097 StreamString response;
1098 response.PutChar ('O');
1099 response.PutBytesAsRawHex8 (buffer, len);
1100
1101 return SendPacketNoLock (response.GetData (), response.GetSize ());
1102}
1103
1104lldb_private::Error
1105GDBRemoteCommunicationServer::SetSTDIOFileDescriptor (int fd)
1106{
1107 Error error;
1108
1109 // Set up the Read Thread for reading/handling process I/O
1110 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
1111 if (!conn_up)
1112 {
1113 error.SetErrorString ("failed to create ConnectionFileDescriptor");
1114 return error;
1115 }
1116
1117 m_stdio_communication.SetConnection (conn_up.release());
1118 if (!m_stdio_communication.IsConnected ())
1119 {
1120 error.SetErrorString ("failed to set connection for inferior I/O communication");
1121 return error;
1122 }
1123
1124 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
1125 m_stdio_communication.StartReadThread();
1126
1127 return error;
1128}
1129
1130void
1131GDBRemoteCommunicationServer::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
1132{
1133 GDBRemoteCommunicationServer *server = reinterpret_cast<GDBRemoteCommunicationServer*> (baton);
1134 static_cast<void> (server->SendONotification (static_cast<const char *>(src), src_len));
1135}
1136
Greg Clayton3dedae12013-12-06 21:45:27 +00001137GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001138GDBRemoteCommunicationServer::SendUnimplementedResponse (const char *)
Greg Clayton576d8832011-03-22 04:00:09 +00001139{
Greg Clayton32e0a752011-03-30 18:16:51 +00001140 // TODO: Log the packet we aren't handling...
Greg Clayton37a0a242012-04-11 00:24:49 +00001141 return SendPacketNoLock ("", 0);
Greg Clayton576d8832011-03-22 04:00:09 +00001142}
1143
Todd Fialaaf245d12014-06-30 21:05:18 +00001144
Greg Clayton3dedae12013-12-06 21:45:27 +00001145GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001146GDBRemoteCommunicationServer::SendErrorResponse (uint8_t err)
1147{
1148 char packet[16];
1149 int packet_len = ::snprintf (packet, sizeof(packet), "E%2.2x", err);
Andy Gibbsa297a972013-06-19 19:04:53 +00001150 assert (packet_len < (int)sizeof(packet));
Greg Clayton37a0a242012-04-11 00:24:49 +00001151 return SendPacketNoLock (packet, packet_len);
Greg Clayton32e0a752011-03-30 18:16:51 +00001152}
1153
Todd Fialaaf245d12014-06-30 21:05:18 +00001154GDBRemoteCommunication::PacketResult
1155GDBRemoteCommunicationServer::SendIllFormedResponse (const StringExtractorGDBRemote &failed_packet, const char *message)
1156{
1157 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
1158 if (log)
1159 log->Printf ("GDBRemoteCommunicationServer::%s: ILLFORMED: '%s' (%s)", __FUNCTION__, failed_packet.GetStringRef ().c_str (), message ? message : "");
1160 return SendErrorResponse (0x03);
1161}
Greg Clayton32e0a752011-03-30 18:16:51 +00001162
Greg Clayton3dedae12013-12-06 21:45:27 +00001163GDBRemoteCommunication::PacketResult
Greg Clayton1cb64962011-03-24 04:28:38 +00001164GDBRemoteCommunicationServer::SendOKResponse ()
1165{
Greg Clayton37a0a242012-04-11 00:24:49 +00001166 return SendPacketNoLock ("OK", 2);
Greg Clayton1cb64962011-03-24 04:28:38 +00001167}
1168
1169bool
1170GDBRemoteCommunicationServer::HandshakeWithClient(Error *error_ptr)
1171{
Greg Clayton3dedae12013-12-06 21:45:27 +00001172 return GetAck() == PacketResult::Success;
Greg Clayton1cb64962011-03-24 04:28:38 +00001173}
Greg Clayton576d8832011-03-22 04:00:09 +00001174
Greg Clayton3dedae12013-12-06 21:45:27 +00001175GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001176GDBRemoteCommunicationServer::Handle_qHostInfo (StringExtractorGDBRemote &packet)
Greg Clayton576d8832011-03-22 04:00:09 +00001177{
1178 StreamString response;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001179
Greg Clayton576d8832011-03-22 04:00:09 +00001180 // $cputype:16777223;cpusubtype:3;ostype:Darwin;vendor:apple;endian:little;ptrsize:8;#00
1181
1182 ArchSpec host_arch (Host::GetArchitecture ());
Greg Clayton576d8832011-03-22 04:00:09 +00001183 const llvm::Triple &host_triple = host_arch.GetTriple();
Greg Clayton1cb64962011-03-24 04:28:38 +00001184 response.PutCString("triple:");
1185 response.PutCStringAsRawHex8(host_triple.getTriple().c_str());
1186 response.Printf (";ptrsize:%u;",host_arch.GetAddressByteSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001187
Todd Fialaa9ddb0e2014-01-18 03:02:39 +00001188 const char* distribution_id = host_arch.GetDistributionId ().AsCString ();
1189 if (distribution_id)
1190 {
1191 response.PutCString("distribution_id:");
1192 response.PutCStringAsRawHex8(distribution_id);
1193 response.PutCString(";");
1194 }
1195
Todd Fialaaf245d12014-06-30 21:05:18 +00001196 // Only send out MachO info when lldb-platform/llgs is running on a MachO host.
1197#if defined(__APPLE__)
Greg Clayton1cb64962011-03-24 04:28:38 +00001198 uint32_t cpu = host_arch.GetMachOCPUType();
1199 uint32_t sub = host_arch.GetMachOCPUSubType();
1200 if (cpu != LLDB_INVALID_CPUTYPE)
1201 response.Printf ("cputype:%u;", cpu);
1202 if (sub != LLDB_INVALID_CPUTYPE)
1203 response.Printf ("cpusubtype:%u;", sub);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001204
Enrico Granata1c5431a2012-07-13 23:55:22 +00001205 if (cpu == ArchSpec::kCore_arm_any)
Enrico Granataf04a2192012-07-13 23:18:48 +00001206 response.Printf("watchpoint_exceptions_received:before;"); // On armv7 we use "synchronous" watchpoints which means the exception is delivered before the instruction executes.
1207 else
1208 response.Printf("watchpoint_exceptions_received:after;");
Todd Fialaaf245d12014-06-30 21:05:18 +00001209#else
1210 response.Printf("watchpoint_exceptions_received:after;");
1211#endif
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001212
Greg Clayton576d8832011-03-22 04:00:09 +00001213 switch (lldb::endian::InlHostByteOrder())
1214 {
1215 case eByteOrderBig: response.PutCString ("endian:big;"); break;
1216 case eByteOrderLittle: response.PutCString ("endian:little;"); break;
1217 case eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1218 default: response.PutCString ("endian:unknown;"); break;
1219 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001220
Greg Clayton1cb64962011-03-24 04:28:38 +00001221 uint32_t major = UINT32_MAX;
1222 uint32_t minor = UINT32_MAX;
1223 uint32_t update = UINT32_MAX;
1224 if (Host::GetOSVersion (major, minor, update))
1225 {
1226 if (major != UINT32_MAX)
1227 {
1228 response.Printf("os_version:%u", major);
1229 if (minor != UINT32_MAX)
1230 {
1231 response.Printf(".%u", minor);
1232 if (update != UINT32_MAX)
1233 response.Printf(".%u", update);
1234 }
1235 response.PutChar(';');
1236 }
1237 }
1238
1239 std::string s;
1240 if (Host::GetOSBuildString (s))
1241 {
1242 response.PutCString ("os_build:");
1243 response.PutCStringAsRawHex8(s.c_str());
1244 response.PutChar(';');
1245 }
1246 if (Host::GetOSKernelDescription (s))
1247 {
1248 response.PutCString ("os_kernel:");
1249 response.PutCStringAsRawHex8(s.c_str());
1250 response.PutChar(';');
1251 }
Greg Clayton2b98c562013-11-22 18:53:12 +00001252#if defined(__APPLE__)
1253
Jason Molendaa3329782014-03-29 18:54:20 +00001254#if defined(__arm__) || defined(__arm64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001255 // For iOS devices, we are connected through a USB Mux so we never pretend
1256 // to actually have a hostname as far as the remote lldb that is connecting
1257 // to this lldb-platform is concerned
1258 response.PutCString ("hostname:");
Greg Clayton16810922014-02-27 19:38:18 +00001259 response.PutCStringAsRawHex8("127.0.0.1");
Greg Clayton2b98c562013-11-22 18:53:12 +00001260 response.PutChar(';');
Jason Molendaa3329782014-03-29 18:54:20 +00001261#else // #if defined(__arm__) || defined(__arm64__)
Greg Clayton1cb64962011-03-24 04:28:38 +00001262 if (Host::GetHostname (s))
1263 {
1264 response.PutCString ("hostname:");
1265 response.PutCStringAsRawHex8(s.c_str());
1266 response.PutChar(';');
1267 }
Jason Molendaa3329782014-03-29 18:54:20 +00001268#endif // #if defined(__arm__) || defined(__arm64__)
Greg Clayton2b98c562013-11-22 18:53:12 +00001269
1270#else // #if defined(__APPLE__)
1271 if (Host::GetHostname (s))
1272 {
1273 response.PutCString ("hostname:");
1274 response.PutCStringAsRawHex8(s.c_str());
1275 response.PutChar(';');
1276 }
1277#endif // #if defined(__APPLE__)
1278
Greg Clayton3dedae12013-12-06 21:45:27 +00001279 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton576d8832011-03-22 04:00:09 +00001280}
Greg Clayton1cb64962011-03-24 04:28:38 +00001281
Greg Clayton32e0a752011-03-30 18:16:51 +00001282static void
Greg Clayton8b82f082011-04-12 05:54:46 +00001283CreateProcessInfoResponse (const ProcessInstanceInfo &proc_info, StreamString &response)
Greg Clayton32e0a752011-03-30 18:16:51 +00001284{
Daniel Malead01b2952012-11-29 21:49:15 +00001285 response.Printf ("pid:%" PRIu64 ";ppid:%" PRIu64 ";uid:%i;gid:%i;euid:%i;egid:%i;",
Greg Clayton32e0a752011-03-30 18:16:51 +00001286 proc_info.GetProcessID(),
1287 proc_info.GetParentProcessID(),
Greg Clayton8b82f082011-04-12 05:54:46 +00001288 proc_info.GetUserID(),
1289 proc_info.GetGroupID(),
Greg Clayton32e0a752011-03-30 18:16:51 +00001290 proc_info.GetEffectiveUserID(),
1291 proc_info.GetEffectiveGroupID());
1292 response.PutCString ("name:");
1293 response.PutCStringAsRawHex8(proc_info.GetName());
1294 response.PutChar(';');
1295 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1296 if (proc_arch.IsValid())
1297 {
1298 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1299 response.PutCString("triple:");
1300 response.PutCStringAsRawHex8(proc_triple.getTriple().c_str());
1301 response.PutChar(';');
1302 }
1303}
Greg Clayton1cb64962011-03-24 04:28:38 +00001304
Todd Fialaaf245d12014-06-30 21:05:18 +00001305static void
1306CreateProcessInfoResponse_DebugServerStyle (const ProcessInstanceInfo &proc_info, StreamString &response)
1307{
1308 response.Printf ("pid:%" PRIx64 ";parent-pid:%" PRIx64 ";real-uid:%x;real-gid:%x;effective-uid:%x;effective-gid:%x;",
1309 proc_info.GetProcessID(),
1310 proc_info.GetParentProcessID(),
1311 proc_info.GetUserID(),
1312 proc_info.GetGroupID(),
1313 proc_info.GetEffectiveUserID(),
1314 proc_info.GetEffectiveGroupID());
1315
1316 const ArchSpec &proc_arch = proc_info.GetArchitecture();
1317 if (proc_arch.IsValid())
1318 {
1319 const uint32_t cpu_type = proc_arch.GetMachOCPUType();
1320 if (cpu_type != 0)
1321 response.Printf ("cputype:%" PRIx32 ";", cpu_type);
1322
1323 const uint32_t cpu_subtype = proc_arch.GetMachOCPUSubType();
1324 if (cpu_subtype != 0)
1325 response.Printf ("cpusubtype:%" PRIx32 ";", cpu_subtype);
1326
1327 const llvm::Triple &proc_triple = proc_arch.GetTriple();
1328 const std::string vendor = proc_triple.getVendorName ();
1329 if (!vendor.empty ())
1330 response.Printf ("vendor:%s;", vendor.c_str ());
1331
1332 std::string ostype = proc_triple.getOSName ();
1333 // Adjust so ostype reports ios for Apple/ARM and Apple/ARM64.
1334 if (proc_triple.getVendor () == llvm::Triple::Apple)
1335 {
1336 switch (proc_triple.getArch ())
1337 {
1338 case llvm::Triple::arm:
1339 case llvm::Triple::arm64:
1340 ostype = "ios";
1341 break;
1342 default:
1343 // No change.
1344 break;
1345 }
1346 }
1347 response.Printf ("ostype:%s;", ostype.c_str ());
1348
1349
1350 switch (proc_arch.GetByteOrder ())
1351 {
1352 case lldb::eByteOrderLittle: response.PutCString ("endian:little;"); break;
1353 case lldb::eByteOrderBig: response.PutCString ("endian:big;"); break;
1354 case lldb::eByteOrderPDP: response.PutCString ("endian:pdp;"); break;
1355 default:
1356 // Nothing.
1357 break;
1358 }
1359
1360 if (proc_triple.isArch64Bit ())
1361 response.PutCString ("ptrsize:8;");
1362 else if (proc_triple.isArch32Bit ())
1363 response.PutCString ("ptrsize:4;");
1364 else if (proc_triple.isArch16Bit ())
1365 response.PutCString ("ptrsize:2;");
1366 }
1367
1368}
1369
1370
1371GDBRemoteCommunication::PacketResult
1372GDBRemoteCommunicationServer::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1373{
1374 // Only the gdb server handles this.
1375 if (!IsGdbServer ())
1376 return SendUnimplementedResponse (packet.GetStringRef ().c_str ());
1377
1378 // Fail if we don't have a current process.
1379 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1380 return SendErrorResponse (68);
1381
1382 ProcessInstanceInfo proc_info;
1383 if (Host::GetProcessInfo (m_debugged_process_sp->GetID (), proc_info))
1384 {
1385 StreamString response;
1386 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1387 return SendPacketNoLock (response.GetData (), response.GetSize ());
1388 }
1389
1390 return SendErrorResponse (1);
1391}
1392
Greg Clayton3dedae12013-12-06 21:45:27 +00001393GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001394GDBRemoteCommunicationServer::Handle_qProcessInfoPID (StringExtractorGDBRemote &packet)
Greg Clayton1cb64962011-03-24 04:28:38 +00001395{
Greg Clayton32e0a752011-03-30 18:16:51 +00001396 // Packet format: "qProcessInfoPID:%i" where %i is the pid
Greg Clayton8b82f082011-04-12 05:54:46 +00001397 packet.SetFilePos(::strlen ("qProcessInfoPID:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001398 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID);
1399 if (pid != LLDB_INVALID_PROCESS_ID)
1400 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001401 ProcessInstanceInfo proc_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00001402 if (Host::GetProcessInfo(pid, proc_info))
1403 {
1404 StreamString response;
1405 CreateProcessInfoResponse (proc_info, response);
Greg Clayton37a0a242012-04-11 00:24:49 +00001406 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001407 }
1408 }
1409 return SendErrorResponse (1);
1410}
1411
Greg Clayton3dedae12013-12-06 21:45:27 +00001412GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001413GDBRemoteCommunicationServer::Handle_qfProcessInfo (StringExtractorGDBRemote &packet)
1414{
1415 m_proc_infos_index = 0;
1416 m_proc_infos.Clear();
1417
Greg Clayton8b82f082011-04-12 05:54:46 +00001418 ProcessInstanceInfoMatch match_info;
1419 packet.SetFilePos(::strlen ("qfProcessInfo"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001420 if (packet.GetChar() == ':')
1421 {
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001422
Greg Clayton32e0a752011-03-30 18:16:51 +00001423 std::string key;
1424 std::string value;
1425 while (packet.GetNameColonValue(key, value))
1426 {
1427 bool success = true;
1428 if (key.compare("name") == 0)
1429 {
1430 StringExtractor extractor;
1431 extractor.GetStringRef().swap(value);
1432 extractor.GetHexByteString (value);
Greg Clayton144f3a92011-11-15 03:53:30 +00001433 match_info.GetProcessInfo().GetExecutableFile().SetFile(value.c_str(), false);
Greg Clayton32e0a752011-03-30 18:16:51 +00001434 }
1435 else if (key.compare("name_match") == 0)
1436 {
1437 if (value.compare("equals") == 0)
1438 {
1439 match_info.SetNameMatchType (eNameMatchEquals);
1440 }
1441 else if (value.compare("starts_with") == 0)
1442 {
1443 match_info.SetNameMatchType (eNameMatchStartsWith);
1444 }
1445 else if (value.compare("ends_with") == 0)
1446 {
1447 match_info.SetNameMatchType (eNameMatchEndsWith);
1448 }
1449 else if (value.compare("contains") == 0)
1450 {
1451 match_info.SetNameMatchType (eNameMatchContains);
1452 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001453 else if (value.compare("regex") == 0)
Greg Clayton32e0a752011-03-30 18:16:51 +00001454 {
1455 match_info.SetNameMatchType (eNameMatchRegularExpression);
1456 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001457 else
Greg Clayton32e0a752011-03-30 18:16:51 +00001458 {
1459 success = false;
1460 }
1461 }
1462 else if (key.compare("pid") == 0)
1463 {
1464 match_info.GetProcessInfo().SetProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1465 }
1466 else if (key.compare("parent_pid") == 0)
1467 {
1468 match_info.GetProcessInfo().SetParentProcessID (Args::StringToUInt32(value.c_str(), LLDB_INVALID_PROCESS_ID, 0, &success));
1469 }
1470 else if (key.compare("uid") == 0)
1471 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001472 match_info.GetProcessInfo().SetUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001473 }
1474 else if (key.compare("gid") == 0)
1475 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001476 match_info.GetProcessInfo().SetGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
Greg Clayton32e0a752011-03-30 18:16:51 +00001477 }
1478 else if (key.compare("euid") == 0)
1479 {
1480 match_info.GetProcessInfo().SetEffectiveUserID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1481 }
1482 else if (key.compare("egid") == 0)
1483 {
1484 match_info.GetProcessInfo().SetEffectiveGroupID (Args::StringToUInt32(value.c_str(), UINT32_MAX, 0, &success));
1485 }
1486 else if (key.compare("all_users") == 0)
1487 {
1488 match_info.SetMatchAllUsers(Args::StringToBoolean(value.c_str(), false, &success));
1489 }
1490 else if (key.compare("triple") == 0)
1491 {
Greg Claytoneb0103f2011-04-07 22:46:35 +00001492 match_info.GetProcessInfo().GetArchitecture().SetTriple (value.c_str(), NULL);
Greg Clayton32e0a752011-03-30 18:16:51 +00001493 }
1494 else
1495 {
1496 success = false;
1497 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001498
Greg Clayton32e0a752011-03-30 18:16:51 +00001499 if (!success)
1500 return SendErrorResponse (2);
1501 }
1502 }
1503
1504 if (Host::FindProcesses (match_info, m_proc_infos))
1505 {
1506 // We found something, return the first item by calling the get
1507 // subsequent process info packet handler...
1508 return Handle_qsProcessInfo (packet);
1509 }
1510 return SendErrorResponse (3);
1511}
1512
Greg Clayton3dedae12013-12-06 21:45:27 +00001513GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001514GDBRemoteCommunicationServer::Handle_qsProcessInfo (StringExtractorGDBRemote &packet)
1515{
1516 if (m_proc_infos_index < m_proc_infos.GetSize())
1517 {
1518 StreamString response;
1519 CreateProcessInfoResponse (m_proc_infos.GetProcessInfoAtIndex(m_proc_infos_index), response);
1520 ++m_proc_infos_index;
Greg Clayton37a0a242012-04-11 00:24:49 +00001521 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001522 }
1523 return SendErrorResponse (4);
1524}
1525
Greg Clayton3dedae12013-12-06 21:45:27 +00001526GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001527GDBRemoteCommunicationServer::Handle_qUserName (StringExtractorGDBRemote &packet)
1528{
1529 // Packet format: "qUserName:%i" where %i is the uid
Greg Clayton8b82f082011-04-12 05:54:46 +00001530 packet.SetFilePos(::strlen ("qUserName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001531 uint32_t uid = packet.GetU32 (UINT32_MAX);
1532 if (uid != UINT32_MAX)
1533 {
1534 std::string name;
1535 if (Host::GetUserName (uid, name))
1536 {
1537 StreamString response;
1538 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001539 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001540 }
1541 }
1542 return SendErrorResponse (5);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001543
Greg Clayton32e0a752011-03-30 18:16:51 +00001544}
1545
Greg Clayton3dedae12013-12-06 21:45:27 +00001546GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00001547GDBRemoteCommunicationServer::Handle_qGroupName (StringExtractorGDBRemote &packet)
1548{
1549 // Packet format: "qGroupName:%i" where %i is the gid
Greg Clayton8b82f082011-04-12 05:54:46 +00001550 packet.SetFilePos(::strlen ("qGroupName:"));
Greg Clayton32e0a752011-03-30 18:16:51 +00001551 uint32_t gid = packet.GetU32 (UINT32_MAX);
1552 if (gid != UINT32_MAX)
1553 {
1554 std::string name;
1555 if (Host::GetGroupName (gid, name))
1556 {
1557 StreamString response;
1558 response.PutCStringAsRawHex8 (name.c_str());
Greg Clayton37a0a242012-04-11 00:24:49 +00001559 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton32e0a752011-03-30 18:16:51 +00001560 }
1561 }
1562 return SendErrorResponse (6);
1563}
1564
Greg Clayton3dedae12013-12-06 21:45:27 +00001565GDBRemoteCommunication::PacketResult
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001566GDBRemoteCommunicationServer::Handle_qSpeedTest (StringExtractorGDBRemote &packet)
1567{
Greg Clayton8b82f082011-04-12 05:54:46 +00001568 packet.SetFilePos(::strlen ("qSpeedTest:"));
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001569
1570 std::string key;
1571 std::string value;
1572 bool success = packet.GetNameColonValue(key, value);
1573 if (success && key.compare("response_size") == 0)
1574 {
1575 uint32_t response_size = Args::StringToUInt32(value.c_str(), 0, 0, &success);
1576 if (success)
1577 {
1578 if (response_size == 0)
1579 return SendOKResponse();
1580 StreamString response;
1581 uint32_t bytes_left = response_size;
1582 response.PutCString("data:");
1583 while (bytes_left > 0)
1584 {
1585 if (bytes_left >= 26)
1586 {
1587 response.PutCString("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1588 bytes_left -= 26;
1589 }
1590 else
1591 {
1592 response.Printf ("%*.*s;", bytes_left, bytes_left, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
1593 bytes_left = 0;
1594 }
1595 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001596 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton9b1e1cd2011-04-04 18:18:57 +00001597 }
1598 }
1599 return SendErrorResponse (7);
1600}
Greg Clayton8b82f082011-04-12 05:54:46 +00001601
Greg Clayton8b82f082011-04-12 05:54:46 +00001602//
1603//static bool
1604//WaitForProcessToSIGSTOP (const lldb::pid_t pid, const int timeout_in_seconds)
1605//{
1606// const int time_delta_usecs = 100000;
1607// const int num_retries = timeout_in_seconds/time_delta_usecs;
1608// for (int i=0; i<num_retries; i++)
1609// {
1610// struct proc_bsdinfo bsd_info;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001611// int error = ::proc_pidinfo (pid, PROC_PIDTBSDINFO,
1612// (uint64_t) 0,
1613// &bsd_info,
Greg Clayton8b82f082011-04-12 05:54:46 +00001614// PROC_PIDTBSDINFO_SIZE);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001615//
Greg Clayton8b82f082011-04-12 05:54:46 +00001616// switch (error)
1617// {
1618// case EINVAL:
1619// case ENOTSUP:
1620// case ESRCH:
1621// case EPERM:
1622// return false;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001623//
Greg Clayton8b82f082011-04-12 05:54:46 +00001624// default:
1625// break;
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001626//
Greg Clayton8b82f082011-04-12 05:54:46 +00001627// case 0:
1628// if (bsd_info.pbi_status == SSTOP)
1629// return true;
1630// }
1631// ::usleep (time_delta_usecs);
1632// }
1633// return false;
1634//}
1635
Greg Clayton3dedae12013-12-06 21:45:27 +00001636GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001637GDBRemoteCommunicationServer::Handle_A (StringExtractorGDBRemote &packet)
1638{
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001639 // The 'A' packet is the most over designed packet ever here with
1640 // redundant argument indexes, redundant argument lengths and needed hex
1641 // encoded argument string values. Really all that is needed is a comma
Greg Clayton8b82f082011-04-12 05:54:46 +00001642 // separated hex encoded argument value list, but we will stay true to the
1643 // documented version of the 'A' packet here...
1644
Todd Fialaaf245d12014-06-30 21:05:18 +00001645 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1646 int actual_arg_index = 0;
1647
Greg Clayton8b82f082011-04-12 05:54:46 +00001648 packet.SetFilePos(1); // Skip the 'A'
1649 bool success = true;
1650 while (success && packet.GetBytesLeft() > 0)
1651 {
1652 // Decode the decimal argument string length. This length is the
1653 // number of hex nibbles in the argument string value.
1654 const uint32_t arg_len = packet.GetU32(UINT32_MAX);
1655 if (arg_len == UINT32_MAX)
1656 success = false;
1657 else
1658 {
1659 // Make sure the argument hex string length is followed by a comma
1660 if (packet.GetChar() != ',')
1661 success = false;
1662 else
1663 {
1664 // Decode the argument index. We ignore this really becuase
1665 // who would really send down the arguments in a random order???
1666 const uint32_t arg_idx = packet.GetU32(UINT32_MAX);
1667 if (arg_idx == UINT32_MAX)
1668 success = false;
1669 else
1670 {
1671 // Make sure the argument index is followed by a comma
1672 if (packet.GetChar() != ',')
1673 success = false;
1674 else
1675 {
1676 // Decode the argument string value from hex bytes
1677 // back into a UTF8 string and make sure the length
1678 // matches the one supplied in the packet
1679 std::string arg;
Todd Fialaaf245d12014-06-30 21:05:18 +00001680 if (packet.GetHexByteStringFixedLength(arg, arg_len) != (arg_len / 2))
Greg Clayton8b82f082011-04-12 05:54:46 +00001681 success = false;
1682 else
1683 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001684 // If there are any bytes left
Greg Clayton8b82f082011-04-12 05:54:46 +00001685 if (packet.GetBytesLeft())
1686 {
1687 if (packet.GetChar() != ',')
1688 success = false;
1689 }
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001690
Greg Clayton8b82f082011-04-12 05:54:46 +00001691 if (success)
1692 {
1693 if (arg_idx == 0)
1694 m_process_launch_info.GetExecutableFile().SetFile(arg.c_str(), false);
1695 m_process_launch_info.GetArguments().AppendArgument(arg.c_str());
Todd Fialaaf245d12014-06-30 21:05:18 +00001696 if (log)
1697 log->Printf ("GDBRemoteCommunicationServer::%s added arg %d: \"%s\"", __FUNCTION__, actual_arg_index, arg.c_str ());
1698 ++actual_arg_index;
Greg Clayton8b82f082011-04-12 05:54:46 +00001699 }
1700 }
1701 }
1702 }
1703 }
1704 }
1705 }
1706
1707 if (success)
1708 {
Todd Fiala9f377372014-01-27 20:44:50 +00001709 m_process_launch_error = LaunchProcess ();
Greg Clayton8b82f082011-04-12 05:54:46 +00001710 if (m_process_launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1711 {
1712 return SendOKResponse ();
1713 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001714 else
1715 {
1716 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1717 if (log)
1718 log->Printf("GDBRemoteCommunicationServer::%s failed to launch exe: %s",
1719 __FUNCTION__,
1720 m_process_launch_error.AsCString());
1721
1722 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001723 }
1724 return SendErrorResponse (8);
1725}
1726
Greg Clayton3dedae12013-12-06 21:45:27 +00001727GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001728GDBRemoteCommunicationServer::Handle_qC (StringExtractorGDBRemote &packet)
1729{
Greg Clayton8b82f082011-04-12 05:54:46 +00001730 StreamString response;
Todd Fialaaf245d12014-06-30 21:05:18 +00001731
1732 if (IsGdbServer ())
Greg Clayton8b82f082011-04-12 05:54:46 +00001733 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001734 // Fail if we don't have a current process.
1735 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1736 return SendErrorResponse (68);
1737
1738 // Make sure we set the current thread so g and p packets return
1739 // the data the gdb will expect.
1740 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1741 SetCurrentThreadID (tid);
1742
1743 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1744 if (!thread_sp)
1745 return SendErrorResponse (69);
1746
1747 response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1748 }
1749 else
1750 {
1751 // NOTE: lldb should now be using qProcessInfo for process IDs. This path here
1752 // should not be used. It is reporting process id instead of thread id. The
1753 // correct answer doesn't seem to make much sense for lldb-platform.
1754 // CONSIDER: flip to "unsupported".
1755 lldb::pid_t pid = m_process_launch_info.GetProcessID();
1756 response.Printf("QC%" PRIx64, pid);
1757
1758 // this should always be platform here
1759 assert (m_is_platform && "this code path should only be traversed for lldb-platform");
1760
1761 if (m_is_platform)
Greg Clayton8b82f082011-04-12 05:54:46 +00001762 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001763 // If we launch a process and this GDB server is acting as a platform,
1764 // then we need to clear the process launch state so we can start
1765 // launching another process. In order to launch a process a bunch or
1766 // packets need to be sent: environment packets, working directory,
1767 // disable ASLR, and many more settings. When we launch a process we
1768 // then need to know when to clear this information. Currently we are
1769 // selecting the 'qC' packet as that packet which seems to make the most
1770 // sense.
1771 if (pid != LLDB_INVALID_PROCESS_ID)
1772 {
1773 m_process_launch_info.Clear();
1774 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001775 }
1776 }
Greg Clayton37a0a242012-04-11 00:24:49 +00001777 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00001778}
1779
1780bool
Daniel Maleae0f8f572013-08-26 23:57:52 +00001781GDBRemoteCommunicationServer::DebugserverProcessReaped (lldb::pid_t pid)
1782{
1783 Mutex::Locker locker (m_spawned_pids_mutex);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001784 FreePortForProcess(pid);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001785 return m_spawned_pids.erase(pid) > 0;
1786}
1787bool
1788GDBRemoteCommunicationServer::ReapDebugserverProcess (void *callback_baton,
1789 lldb::pid_t pid,
1790 bool exited,
1791 int signal, // Zero for no signal
1792 int status) // Exit value of process if signal is zero
1793{
1794 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1795 server->DebugserverProcessReaped (pid);
1796 return true;
1797}
1798
Todd Fiala3e92a2b2014-01-24 00:52:53 +00001799bool
1800GDBRemoteCommunicationServer::DebuggedProcessReaped (lldb::pid_t pid)
1801{
1802 // reap a process that we were debugging (but not debugserver)
1803 Mutex::Locker locker (m_spawned_pids_mutex);
1804 return m_spawned_pids.erase(pid) > 0;
1805}
1806
1807bool
1808GDBRemoteCommunicationServer::ReapDebuggedProcess (void *callback_baton,
1809 lldb::pid_t pid,
1810 bool exited,
1811 int signal, // Zero for no signal
1812 int status) // Exit value of process if signal is zero
1813{
1814 GDBRemoteCommunicationServer *server = (GDBRemoteCommunicationServer *)callback_baton;
1815 server->DebuggedProcessReaped (pid);
1816 return true;
1817}
1818
Greg Clayton3dedae12013-12-06 21:45:27 +00001819GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00001820GDBRemoteCommunicationServer::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet)
1821{
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001822#ifdef _WIN32
Deepak Panickal263fde02014-01-14 11:34:44 +00001823 return SendErrorResponse(9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001824#else
Greg Clayton8b82f082011-04-12 05:54:46 +00001825 // Spawn a local debugserver as a platform so we can then attach or launch
1826 // a process...
1827
1828 if (m_is_platform)
1829 {
1830 // Sleep and wait a bit for debugserver to start to listen...
1831 ConnectionFileDescriptor file_conn;
Greg Clayton8b82f082011-04-12 05:54:46 +00001832 Error error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001833 std::string hostname;
Sylvestre Ledrufaa63ce2013-09-28 15:57:37 +00001834 // TODO: /tmp/ should not be hardcoded. User might want to override /tmp
1835 // with the TMPDIR environnement variable
Greg Clayton29b8fc42013-11-21 01:44:58 +00001836 packet.SetFilePos(::strlen ("qLaunchGDBServer;"));
1837 std::string name;
1838 std::string value;
1839 uint16_t port = UINT16_MAX;
1840 while (packet.GetNameColonValue(name, value))
Greg Clayton8b82f082011-04-12 05:54:46 +00001841 {
Greg Clayton29b8fc42013-11-21 01:44:58 +00001842 if (name.compare ("host") == 0)
1843 hostname.swap(value);
1844 else if (name.compare ("port") == 0)
1845 port = Args::StringToUInt32(value.c_str(), 0, 0);
Greg Clayton8b82f082011-04-12 05:54:46 +00001846 }
Greg Clayton29b8fc42013-11-21 01:44:58 +00001847 if (port == UINT16_MAX)
1848 port = GetNextAvailablePort();
1849
1850 // Spawn a new thread to accept the port that gets bound after
1851 // binding to port 0 (zero).
Greg Claytonfbb76342013-11-20 21:07:01 +00001852
Greg Clayton29b8fc42013-11-21 01:44:58 +00001853 if (error.Success())
1854 {
1855 // Spawn a debugserver and try to get the port it listens to.
1856 ProcessLaunchInfo debugserver_launch_info;
Greg Clayton29b8fc42013-11-21 01:44:58 +00001857 if (hostname.empty())
Greg Clayton16810922014-02-27 19:38:18 +00001858 hostname = "127.0.0.1";
Greg Clayton29b8fc42013-11-21 01:44:58 +00001859 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
1860 if (log)
Greg Claytonfda4fab2014-01-10 22:24:11 +00001861 log->Printf("Launching debugserver with: %s:%u...\n", hostname.c_str(), port);
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001862
Greg Clayton29b8fc42013-11-21 01:44:58 +00001863 debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false);
1864
Greg Claytonfda4fab2014-01-10 22:24:11 +00001865 error = StartDebugserverProcess (hostname.empty() ? NULL : hostname.c_str(),
1866 port,
Greg Clayton00fe87b2013-12-05 22:58:22 +00001867 debugserver_launch_info,
1868 port);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001869
1870 lldb::pid_t debugserver_pid = debugserver_launch_info.GetProcessID();
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001871
Greg Claytonfbb76342013-11-20 21:07:01 +00001872
Greg Clayton29b8fc42013-11-21 01:44:58 +00001873 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1874 {
1875 Mutex::Locker locker (m_spawned_pids_mutex);
1876 m_spawned_pids.insert(debugserver_pid);
1877 if (port > 0)
1878 AssociatePortWithProcess(port, debugserver_pid);
1879 }
1880 else
1881 {
1882 if (port > 0)
1883 FreePort (port);
1884 }
1885
1886 if (error.Success())
1887 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001888 char response[256];
1889 const int response_len = ::snprintf (response, sizeof(response), "pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset);
Ed Masted494b292014-03-20 17:34:26 +00001890 assert (response_len < (int)sizeof(response));
Greg Clayton3dedae12013-12-06 21:45:27 +00001891 PacketResult packet_result = SendPacketNoLock (response, response_len);
Greg Clayton29b8fc42013-11-21 01:44:58 +00001892
Greg Clayton3dedae12013-12-06 21:45:27 +00001893 if (packet_result != PacketResult::Success)
Greg Clayton29b8fc42013-11-21 01:44:58 +00001894 {
1895 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
1896 ::kill (debugserver_pid, SIGINT);
1897 }
Greg Clayton3dedae12013-12-06 21:45:27 +00001898 return packet_result;
Greg Clayton29b8fc42013-11-21 01:44:58 +00001899 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001900 }
1901 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00001902 return SendErrorResponse (9);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001903#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00001904}
1905
Todd Fiala403edc52014-01-23 22:05:44 +00001906bool
1907GDBRemoteCommunicationServer::KillSpawnedProcess (lldb::pid_t pid)
1908{
1909 // make sure we know about this process
1910 {
1911 Mutex::Locker locker (m_spawned_pids_mutex);
1912 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1913 return false;
1914 }
1915
1916 // first try a SIGTERM (standard kill)
1917 Host::Kill (pid, SIGTERM);
1918
1919 // check if that worked
1920 for (size_t i=0; i<10; ++i)
1921 {
1922 {
1923 Mutex::Locker locker (m_spawned_pids_mutex);
1924 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1925 {
1926 // it is now killed
1927 return true;
1928 }
1929 }
1930 usleep (10000);
1931 }
1932
1933 // check one more time after the final usleep
1934 {
1935 Mutex::Locker locker (m_spawned_pids_mutex);
1936 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1937 return true;
1938 }
1939
1940 // the launched process still lives. Now try killling it again,
1941 // this time with an unblockable signal.
1942 Host::Kill (pid, SIGKILL);
1943
1944 for (size_t i=0; i<10; ++i)
1945 {
1946 {
1947 Mutex::Locker locker (m_spawned_pids_mutex);
1948 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1949 {
1950 // it is now killed
1951 return true;
1952 }
1953 }
1954 usleep (10000);
1955 }
1956
1957 // check one more time after the final usleep
1958 // Scope for locker
1959 {
1960 Mutex::Locker locker (m_spawned_pids_mutex);
1961 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
1962 return true;
1963 }
1964
1965 // no luck - the process still lives
1966 return false;
1967}
1968
Greg Clayton3dedae12013-12-06 21:45:27 +00001969GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00001970GDBRemoteCommunicationServer::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet)
1971{
Todd Fiala403edc52014-01-23 22:05:44 +00001972 packet.SetFilePos(::strlen ("qKillSpawnedProcess:"));
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00001973
Todd Fiala403edc52014-01-23 22:05:44 +00001974 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
1975
1976 // verify that we know anything about this pid.
1977 // Scope for locker
Daniel Maleae0f8f572013-08-26 23:57:52 +00001978 {
Todd Fiala403edc52014-01-23 22:05:44 +00001979 Mutex::Locker locker (m_spawned_pids_mutex);
1980 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
Daniel Maleae0f8f572013-08-26 23:57:52 +00001981 {
Todd Fiala403edc52014-01-23 22:05:44 +00001982 // not a pid we know about
1983 return SendErrorResponse (10);
Daniel Maleae0f8f572013-08-26 23:57:52 +00001984 }
1985 }
Todd Fiala403edc52014-01-23 22:05:44 +00001986
1987 // go ahead and attempt to kill the spawned process
1988 if (KillSpawnedProcess (pid))
1989 return SendOKResponse ();
1990 else
1991 return SendErrorResponse (11);
1992}
1993
1994GDBRemoteCommunication::PacketResult
1995GDBRemoteCommunicationServer::Handle_k (StringExtractorGDBRemote &packet)
1996{
1997 // ignore for now if we're lldb_platform
1998 if (m_is_platform)
1999 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2000
2001 // shutdown all spawned processes
2002 std::set<lldb::pid_t> spawned_pids_copy;
2003
2004 // copy pids
2005 {
2006 Mutex::Locker locker (m_spawned_pids_mutex);
2007 spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ());
2008 }
2009
2010 // nuke the spawned processes
2011 for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it)
2012 {
2013 lldb::pid_t spawned_pid = *it;
2014 if (!KillSpawnedProcess (spawned_pid))
2015 {
2016 fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid);
2017 }
2018 }
2019
Todd Fialaaf245d12014-06-30 21:05:18 +00002020 FlushInferiorOutput ();
2021
2022 // No OK response for kill packet.
2023 // return SendOKResponse ();
2024 return PacketResult::Success;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002025}
2026
Greg Clayton3dedae12013-12-06 21:45:27 +00002027GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002028GDBRemoteCommunicationServer::Handle_qLaunchSuccess (StringExtractorGDBRemote &packet)
2029{
2030 if (m_process_launch_error.Success())
2031 return SendOKResponse();
Sylvestre Ledrub027bd22013-09-28 14:35:00 +00002032 StreamString response;
Greg Clayton8b82f082011-04-12 05:54:46 +00002033 response.PutChar('E');
2034 response.PutCString(m_process_launch_error.AsCString("<unknown error>"));
Greg Clayton37a0a242012-04-11 00:24:49 +00002035 return SendPacketNoLock (response.GetData(), response.GetSize());
Greg Clayton8b82f082011-04-12 05:54:46 +00002036}
2037
Greg Clayton3dedae12013-12-06 21:45:27 +00002038GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002039GDBRemoteCommunicationServer::Handle_QEnvironment (StringExtractorGDBRemote &packet)
2040{
2041 packet.SetFilePos(::strlen ("QEnvironment:"));
2042 const uint32_t bytes_left = packet.GetBytesLeft();
2043 if (bytes_left > 0)
2044 {
2045 m_process_launch_info.GetEnvironmentEntries ().AppendArgument (packet.Peek());
2046 return SendOKResponse ();
2047 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002048 return SendErrorResponse (12);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002049}
2050
Greg Clayton3dedae12013-12-06 21:45:27 +00002051GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002052GDBRemoteCommunicationServer::Handle_QLaunchArch (StringExtractorGDBRemote &packet)
2053{
2054 packet.SetFilePos(::strlen ("QLaunchArch:"));
2055 const uint32_t bytes_left = packet.GetBytesLeft();
2056 if (bytes_left > 0)
2057 {
2058 const char* arch_triple = packet.Peek();
2059 ArchSpec arch_spec(arch_triple,NULL);
2060 m_process_launch_info.SetArchitecture(arch_spec);
2061 return SendOKResponse();
2062 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002063 return SendErrorResponse(13);
Greg Clayton8b82f082011-04-12 05:54:46 +00002064}
2065
Greg Clayton3dedae12013-12-06 21:45:27 +00002066GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002067GDBRemoteCommunicationServer::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
2068{
2069 packet.SetFilePos(::strlen ("QSetDisableASLR:"));
2070 if (packet.GetU32(0))
2071 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
2072 else
2073 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
2074 return SendOKResponse ();
2075}
2076
Greg Clayton3dedae12013-12-06 21:45:27 +00002077GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002078GDBRemoteCommunicationServer::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
2079{
2080 packet.SetFilePos(::strlen ("QSetWorkingDir:"));
2081 std::string path;
2082 packet.GetHexByteString(path);
Greg Claytonfbb76342013-11-20 21:07:01 +00002083 if (m_is_platform)
2084 {
Colin Riley909bb7a2013-11-26 15:10:46 +00002085#ifdef _WIN32
2086 // Not implemented on Windows
2087 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_QSetWorkingDir unimplemented");
2088#else
Greg Claytonfbb76342013-11-20 21:07:01 +00002089 // If this packet is sent to a platform, then change the current working directory
2090 if (::chdir(path.c_str()) != 0)
2091 return SendErrorResponse(errno);
Colin Riley909bb7a2013-11-26 15:10:46 +00002092#endif
Greg Claytonfbb76342013-11-20 21:07:01 +00002093 }
2094 else
2095 {
2096 m_process_launch_info.SwapWorkingDirectory (path);
2097 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002098 return SendOKResponse ();
2099}
2100
Greg Clayton3dedae12013-12-06 21:45:27 +00002101GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002102GDBRemoteCommunicationServer::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
2103{
2104 StreamString response;
2105
2106 if (m_is_platform)
2107 {
2108 // If this packet is sent to a platform, then change the current working directory
2109 char cwd[PATH_MAX];
2110 if (getcwd(cwd, sizeof(cwd)) == NULL)
2111 {
2112 return SendErrorResponse(errno);
2113 }
2114 else
2115 {
2116 response.PutBytesAsRawHex8(cwd, strlen(cwd));
Greg Clayton3dedae12013-12-06 21:45:27 +00002117 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002118 }
2119 }
2120 else
2121 {
2122 const char *working_dir = m_process_launch_info.GetWorkingDirectory();
2123 if (working_dir && working_dir[0])
2124 {
2125 response.PutBytesAsRawHex8(working_dir, strlen(working_dir));
Greg Clayton3dedae12013-12-06 21:45:27 +00002126 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002127 }
2128 else
2129 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002130 return SendErrorResponse(14);
Greg Claytonfbb76342013-11-20 21:07:01 +00002131 }
2132 }
2133}
2134
Greg Clayton3dedae12013-12-06 21:45:27 +00002135GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002136GDBRemoteCommunicationServer::Handle_QSetSTDIN (StringExtractorGDBRemote &packet)
2137{
2138 packet.SetFilePos(::strlen ("QSetSTDIN:"));
2139 ProcessLaunchInfo::FileAction file_action;
2140 std::string path;
2141 packet.GetHexByteString(path);
2142 const bool read = false;
2143 const bool write = true;
2144 if (file_action.Open(STDIN_FILENO, path.c_str(), read, write))
2145 {
2146 m_process_launch_info.AppendFileAction(file_action);
2147 return SendOKResponse ();
2148 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002149 return SendErrorResponse (15);
Greg Clayton8b82f082011-04-12 05:54:46 +00002150}
2151
Greg Clayton3dedae12013-12-06 21:45:27 +00002152GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002153GDBRemoteCommunicationServer::Handle_QSetSTDOUT (StringExtractorGDBRemote &packet)
2154{
2155 packet.SetFilePos(::strlen ("QSetSTDOUT:"));
2156 ProcessLaunchInfo::FileAction file_action;
2157 std::string path;
2158 packet.GetHexByteString(path);
2159 const bool read = true;
2160 const bool write = false;
2161 if (file_action.Open(STDOUT_FILENO, path.c_str(), read, write))
2162 {
2163 m_process_launch_info.AppendFileAction(file_action);
2164 return SendOKResponse ();
2165 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002166 return SendErrorResponse (16);
Greg Clayton8b82f082011-04-12 05:54:46 +00002167}
2168
Greg Clayton3dedae12013-12-06 21:45:27 +00002169GDBRemoteCommunication::PacketResult
Greg Clayton8b82f082011-04-12 05:54:46 +00002170GDBRemoteCommunicationServer::Handle_QSetSTDERR (StringExtractorGDBRemote &packet)
2171{
2172 packet.SetFilePos(::strlen ("QSetSTDERR:"));
2173 ProcessLaunchInfo::FileAction file_action;
2174 std::string path;
2175 packet.GetHexByteString(path);
2176 const bool read = true;
Greg Clayton9845a8d2012-03-06 04:01:04 +00002177 const bool write = false;
Greg Clayton8b82f082011-04-12 05:54:46 +00002178 if (file_action.Open(STDERR_FILENO, path.c_str(), read, write))
2179 {
2180 m_process_launch_info.AppendFileAction(file_action);
2181 return SendOKResponse ();
2182 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002183 return SendErrorResponse (17);
Greg Clayton8b82f082011-04-12 05:54:46 +00002184}
2185
Greg Clayton3dedae12013-12-06 21:45:27 +00002186GDBRemoteCommunication::PacketResult
Todd Fialaaf245d12014-06-30 21:05:18 +00002187GDBRemoteCommunicationServer::Handle_C (StringExtractorGDBRemote &packet)
2188{
2189 if (!IsGdbServer ())
2190 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2191
2192 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2193 if (log)
2194 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2195
2196 // Ensure we have a native process.
2197 if (!m_debugged_process_sp)
2198 {
2199 if (log)
2200 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2201 return SendErrorResponse (0x36);
2202 }
2203
2204 // Pull out the signal number.
2205 packet.SetFilePos (::strlen ("C"));
2206 if (packet.GetBytesLeft () < 1)
2207 {
2208 // Shouldn't be using a C without a signal.
2209 return SendIllFormedResponse (packet, "C packet specified without signal.");
2210 }
2211 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2212 if (signo == std::numeric_limits<uint32_t>::max ())
2213 return SendIllFormedResponse (packet, "failed to parse signal number");
2214
2215 // Handle optional continue address.
2216 if (packet.GetBytesLeft () > 0)
2217 {
2218 // FIXME add continue at address support for $C{signo}[;{continue-address}].
2219 if (*packet.Peek () == ';')
2220 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2221 else
2222 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
2223 }
2224
2225 lldb_private::ResumeActionList resume_actions (StateType::eStateRunning, 0);
2226 Error error;
2227
2228 // We have two branches: what to do if a continue thread is specified (in which case we target
2229 // sending the signal to that thread), or when we don't have a continue thread set (in which
2230 // case we send a signal to the process).
2231
2232 // TODO discuss with Greg Clayton, make sure this makes sense.
2233
2234 lldb::tid_t signal_tid = GetContinueThreadID ();
2235 if (signal_tid != LLDB_INVALID_THREAD_ID)
2236 {
2237 // The resume action for the continue thread (or all threads if a continue thread is not set).
2238 lldb_private::ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
2239
2240 // Add the action for the continue thread (or all threads when the continue thread isn't present).
2241 resume_actions.Append (action);
2242 }
2243 else
2244 {
2245 // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
2246 error = m_debugged_process_sp->Signal (signo);
2247 if (error.Fail ())
2248 {
2249 if (log)
2250 log->Printf ("GDBRemoteCommunicationServer::%s failed to send signal for process %" PRIu64 ": %s",
2251 __FUNCTION__,
2252 m_debugged_process_sp->GetID (),
2253 error.AsCString ());
2254
2255 return SendErrorResponse (0x52);
2256 }
2257 }
2258
2259 // Resume the threads.
2260 error = m_debugged_process_sp->Resume (resume_actions);
2261 if (error.Fail ())
2262 {
2263 if (log)
2264 log->Printf ("GDBRemoteCommunicationServer::%s failed to resume threads for process %" PRIu64 ": %s",
2265 __FUNCTION__,
2266 m_debugged_process_sp->GetID (),
2267 error.AsCString ());
2268
2269 return SendErrorResponse (0x38);
2270 }
2271
2272 // Don't send an "OK" packet; response is the stopped/exited message.
2273 return PacketResult::Success;
2274}
2275
2276GDBRemoteCommunication::PacketResult
2277GDBRemoteCommunicationServer::Handle_c (StringExtractorGDBRemote &packet, bool skip_file_pos_adjustment)
2278{
2279 if (!IsGdbServer ())
2280 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2281
2282 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2283 if (log)
2284 log->Printf ("GDBRemoteCommunicationServer::%s called", __FUNCTION__);
2285
2286 // We reuse this method in vCont - don't double adjust the file position.
2287 if (!skip_file_pos_adjustment)
2288 packet.SetFilePos (::strlen ("c"));
2289
2290 // For now just support all continue.
2291 const bool has_continue_address = (packet.GetBytesLeft () > 0);
2292 if (has_continue_address)
2293 {
2294 if (log)
2295 log->Printf ("GDBRemoteCommunicationServer::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
2296 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2297 }
2298
2299 // Ensure we have a native process.
2300 if (!m_debugged_process_sp)
2301 {
2302 if (log)
2303 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2304 return SendErrorResponse (0x36);
2305 }
2306
2307 // Build the ResumeActionList
2308 lldb_private::ResumeActionList actions (StateType::eStateRunning, 0);
2309
2310 Error error = m_debugged_process_sp->Resume (actions);
2311 if (error.Fail ())
2312 {
2313 if (log)
2314 {
2315 log->Printf ("GDBRemoteCommunicationServer::%s c failed for process %" PRIu64 ": %s",
2316 __FUNCTION__,
2317 m_debugged_process_sp->GetID (),
2318 error.AsCString ());
2319 }
2320 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2321 }
2322
2323 if (log)
2324 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2325
2326 // No response required from continue.
2327 return PacketResult::Success;
2328}
2329
2330GDBRemoteCommunication::PacketResult
2331GDBRemoteCommunicationServer::Handle_vCont_actions (StringExtractorGDBRemote &packet)
2332{
2333 if (!IsGdbServer ())
2334 {
2335 // only llgs supports $vCont.
2336 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2337 }
2338
2339 // We handle $vCont messages for c.
2340 // TODO add C, s and S.
2341 StreamString response;
2342 response.Printf("vCont;c;C;s;S");
2343
2344 return SendPacketNoLock(response.GetData(), response.GetSize());
2345}
2346
2347GDBRemoteCommunication::PacketResult
2348GDBRemoteCommunicationServer::Handle_vCont (StringExtractorGDBRemote &packet)
2349{
2350 if (!IsGdbServer ())
2351 {
2352 // only llgs supports $vCont
2353 return SendUnimplementedResponse (packet.GetStringRef().c_str());
2354 }
2355
2356 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2357 if (log)
2358 log->Printf ("GDBRemoteCommunicationServer::%s handling vCont packet", __FUNCTION__);
2359
2360 packet.SetFilePos (::strlen ("vCont"));
2361
2362 // Check if this is all continue (no options or ";c").
2363 if (!packet.GetBytesLeft () || (::strcmp (packet.Peek (), ";c") == 0))
2364 {
2365 // Move the packet past the ";c".
2366 if (packet.GetBytesLeft ())
2367 packet.SetFilePos (packet.GetFilePos () + ::strlen (";c"));
2368
2369 const bool skip_file_pos_adjustment = true;
2370 return Handle_c (packet, skip_file_pos_adjustment);
2371 }
2372 else if (::strcmp (packet.Peek (), ";s") == 0)
2373 {
2374 // Move past the ';', then do a simple 's'.
2375 packet.SetFilePos (packet.GetFilePos () + 1);
2376 return Handle_s (packet);
2377 }
2378
2379 // Ensure we have a native process.
2380 if (!m_debugged_process_sp)
2381 {
2382 if (log)
2383 log->Printf ("GDBRemoteCommunicationServer::%s no debugged process shared pointer", __FUNCTION__);
2384 return SendErrorResponse (0x36);
2385 }
2386
2387 ResumeActionList thread_actions;
2388
2389 while (packet.GetBytesLeft () && *packet.Peek () == ';')
2390 {
2391 // Skip the semi-colon.
2392 packet.GetChar ();
2393
2394 // Build up the thread action.
2395 ResumeAction thread_action;
2396 thread_action.tid = LLDB_INVALID_THREAD_ID;
2397 thread_action.state = eStateInvalid;
2398 thread_action.signal = 0;
2399
2400 const char action = packet.GetChar ();
2401 switch (action)
2402 {
2403 case 'C':
2404 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2405 if (thread_action.signal == 0)
2406 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
2407 // Fall through to next case...
2408
2409 case 'c':
2410 // Continue
2411 thread_action.state = eStateRunning;
2412 break;
2413
2414 case 'S':
2415 thread_action.signal = packet.GetHexMaxU32 (false, 0);
2416 if (thread_action.signal == 0)
2417 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
2418 // Fall through to next case...
2419
2420 case 's':
2421 // Step
2422 thread_action.state = eStateStepping;
2423 break;
2424
2425 default:
2426 return SendIllFormedResponse (packet, "Unsupported vCont action");
2427 break;
2428 }
2429
2430 // Parse out optional :{thread-id} value.
2431 if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
2432 {
2433 // Consume the separator.
2434 packet.GetChar ();
2435
2436 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2437 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
2438 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
2439 }
2440
2441 thread_actions.Append (thread_action);
2442 }
2443
2444 // If a default action for all other threads wasn't mentioned
2445 // then we should stop the threads.
2446 thread_actions.SetDefaultThreadActionIfNeeded (eStateStopped, 0);
2447
2448 Error error = m_debugged_process_sp->Resume (thread_actions);
2449 if (error.Fail ())
2450 {
2451 if (log)
2452 {
2453 log->Printf ("GDBRemoteCommunicationServer::%s vCont failed for process %" PRIu64 ": %s",
2454 __FUNCTION__,
2455 m_debugged_process_sp->GetID (),
2456 error.AsCString ());
2457 }
2458 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
2459 }
2460
2461 if (log)
2462 log->Printf ("GDBRemoteCommunicationServer::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
2463
2464 // No response required from vCont.
2465 return PacketResult::Success;
2466}
2467
2468GDBRemoteCommunication::PacketResult
Greg Clayton32e0a752011-03-30 18:16:51 +00002469GDBRemoteCommunicationServer::Handle_QStartNoAckMode (StringExtractorGDBRemote &packet)
2470{
2471 // Send response first before changing m_send_acks to we ack this packet
Greg Clayton3dedae12013-12-06 21:45:27 +00002472 PacketResult packet_result = SendOKResponse ();
Greg Clayton1cb64962011-03-24 04:28:38 +00002473 m_send_acks = false;
Greg Clayton3dedae12013-12-06 21:45:27 +00002474 return packet_result;
Greg Clayton1cb64962011-03-24 04:28:38 +00002475}
Daniel Maleae0f8f572013-08-26 23:57:52 +00002476
Greg Clayton3dedae12013-12-06 21:45:27 +00002477GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002478GDBRemoteCommunicationServer::Handle_qPlatform_mkdir (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002479{
Greg Claytonfbb76342013-11-20 21:07:01 +00002480 packet.SetFilePos(::strlen("qPlatform_mkdir:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002481 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002482 if (packet.GetChar() == ',')
2483 {
2484 std::string path;
2485 packet.GetHexByteString(path);
2486 Error error = Host::MakeDirectory(path.c_str(),mode);
2487 if (error.Success())
2488 return SendPacketNoLock ("OK", 2);
2489 else
2490 return SendErrorResponse(error.GetError());
2491 }
2492 return SendErrorResponse(20);
Greg Claytonfbb76342013-11-20 21:07:01 +00002493}
2494
Greg Clayton3dedae12013-12-06 21:45:27 +00002495GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002496GDBRemoteCommunicationServer::Handle_qPlatform_chmod (StringExtractorGDBRemote &packet)
2497{
2498 packet.SetFilePos(::strlen("qPlatform_chmod:"));
2499
2500 mode_t mode = packet.GetHexMaxU32(false, UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002501 if (packet.GetChar() == ',')
2502 {
2503 std::string path;
2504 packet.GetHexByteString(path);
2505 Error error = Host::SetFilePermissions (path.c_str(), mode);
2506 if (error.Success())
2507 return SendPacketNoLock ("OK", 2);
2508 else
2509 return SendErrorResponse(error.GetError());
2510 }
2511 return SendErrorResponse(19);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002512}
2513
Greg Clayton3dedae12013-12-06 21:45:27 +00002514GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002515GDBRemoteCommunicationServer::Handle_vFile_Open (StringExtractorGDBRemote &packet)
2516{
2517 packet.SetFilePos(::strlen("vFile:open:"));
2518 std::string path;
2519 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002520 if (!path.empty())
2521 {
2522 if (packet.GetChar() == ',')
2523 {
2524 uint32_t flags = packet.GetHexMaxU32(false, 0);
2525 if (packet.GetChar() == ',')
2526 {
2527 mode_t mode = packet.GetHexMaxU32(false, 0600);
2528 Error error;
2529 int fd = ::open (path.c_str(), flags, mode);
Greg Clayton2b98c562013-11-22 18:53:12 +00002530 const int save_errno = fd == -1 ? errno : 0;
2531 StreamString response;
2532 response.PutChar('F');
2533 response.Printf("%i", fd);
2534 if (save_errno)
2535 response.Printf(",%i", save_errno);
2536 return SendPacketNoLock(response.GetData(), response.GetSize());
2537 }
2538 }
2539 }
2540 return SendErrorResponse(18);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002541}
2542
Greg Clayton3dedae12013-12-06 21:45:27 +00002543GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002544GDBRemoteCommunicationServer::Handle_vFile_Close (StringExtractorGDBRemote &packet)
2545{
2546 packet.SetFilePos(::strlen("vFile:close:"));
2547 int fd = packet.GetS32(-1);
2548 Error error;
2549 int err = -1;
2550 int save_errno = 0;
2551 if (fd >= 0)
2552 {
2553 err = close(fd);
2554 save_errno = err == -1 ? errno : 0;
2555 }
2556 else
2557 {
2558 save_errno = EINVAL;
2559 }
2560 StreamString response;
2561 response.PutChar('F');
2562 response.Printf("%i", err);
2563 if (save_errno)
2564 response.Printf(",%i", save_errno);
Greg Clayton2b98c562013-11-22 18:53:12 +00002565 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002566}
2567
Greg Clayton3dedae12013-12-06 21:45:27 +00002568GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002569GDBRemoteCommunicationServer::Handle_vFile_pRead (StringExtractorGDBRemote &packet)
2570{
Virgile Belloae12a362013-08-27 16:21:49 +00002571#ifdef _WIN32
2572 // Not implemented on Windows
Greg Clayton2b98c562013-11-22 18:53:12 +00002573 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pRead() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002574#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002575 StreamGDBRemote response;
2576 packet.SetFilePos(::strlen("vFile:pread:"));
2577 int fd = packet.GetS32(-1);
Greg Clayton2b98c562013-11-22 18:53:12 +00002578 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002579 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002580 uint64_t count = packet.GetU64(UINT64_MAX);
2581 if (packet.GetChar() == ',')
2582 {
2583 uint64_t offset = packet.GetU64(UINT32_MAX);
2584 if (count == UINT64_MAX)
2585 {
2586 response.Printf("F-1:%i", EINVAL);
2587 return SendPacketNoLock(response.GetData(), response.GetSize());
2588 }
2589
2590 std::string buffer(count, 0);
2591 const ssize_t bytes_read = ::pread (fd, &buffer[0], buffer.size(), offset);
2592 const int save_errno = bytes_read == -1 ? errno : 0;
2593 response.PutChar('F');
2594 response.Printf("%zi", bytes_read);
2595 if (save_errno)
2596 response.Printf(",%i", save_errno);
2597 else
2598 {
2599 response.PutChar(';');
2600 response.PutEscapedBytes(&buffer[0], bytes_read);
2601 }
2602 return SendPacketNoLock(response.GetData(), response.GetSize());
2603 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002604 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002605 return SendErrorResponse(21);
2606
Virgile Belloae12a362013-08-27 16:21:49 +00002607#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002608}
2609
Greg Clayton3dedae12013-12-06 21:45:27 +00002610GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002611GDBRemoteCommunicationServer::Handle_vFile_pWrite (StringExtractorGDBRemote &packet)
2612{
Virgile Belloae12a362013-08-27 16:21:49 +00002613#ifdef _WIN32
Greg Clayton2b98c562013-11-22 18:53:12 +00002614 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_pWrite() unimplemented");
Virgile Belloae12a362013-08-27 16:21:49 +00002615#else
Daniel Maleae0f8f572013-08-26 23:57:52 +00002616 packet.SetFilePos(::strlen("vFile:pwrite:"));
2617
2618 StreamGDBRemote response;
2619 response.PutChar('F');
2620
2621 int fd = packet.GetU32(UINT32_MAX);
Greg Clayton2b98c562013-11-22 18:53:12 +00002622 if (packet.GetChar() == ',')
Daniel Maleae0f8f572013-08-26 23:57:52 +00002623 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002624 off_t offset = packet.GetU64(UINT32_MAX);
2625 if (packet.GetChar() == ',')
2626 {
2627 std::string buffer;
2628 if (packet.GetEscapedBinaryData(buffer))
2629 {
2630 const ssize_t bytes_written = ::pwrite (fd, buffer.data(), buffer.size(), offset);
2631 const int save_errno = bytes_written == -1 ? errno : 0;
2632 response.Printf("%zi", bytes_written);
2633 if (save_errno)
2634 response.Printf(",%i", save_errno);
2635 }
2636 else
2637 {
2638 response.Printf ("-1,%i", EINVAL);
2639 }
2640 return SendPacketNoLock(response.GetData(), response.GetSize());
2641 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002642 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002643 return SendErrorResponse(27);
Virgile Belloae12a362013-08-27 16:21:49 +00002644#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002645}
2646
Greg Clayton3dedae12013-12-06 21:45:27 +00002647GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002648GDBRemoteCommunicationServer::Handle_vFile_Size (StringExtractorGDBRemote &packet)
2649{
2650 packet.SetFilePos(::strlen("vFile:size:"));
2651 std::string path;
2652 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002653 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002654 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002655 lldb::user_id_t retcode = Host::GetFileSize(FileSpec(path.c_str(), false));
2656 StreamString response;
2657 response.PutChar('F');
2658 response.PutHex64(retcode);
2659 if (retcode == UINT64_MAX)
2660 {
2661 response.PutChar(',');
2662 response.PutHex64(retcode); // TODO: replace with Host::GetSyswideErrorCode()
2663 }
2664 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002665 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002666 return SendErrorResponse(22);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002667}
2668
Greg Clayton3dedae12013-12-06 21:45:27 +00002669GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002670GDBRemoteCommunicationServer::Handle_vFile_Mode (StringExtractorGDBRemote &packet)
2671{
2672 packet.SetFilePos(::strlen("vFile:mode:"));
2673 std::string path;
2674 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002675 if (!path.empty())
2676 {
2677 Error error;
2678 const uint32_t mode = File::GetPermissions(path.c_str(), error);
2679 StreamString response;
2680 response.Printf("F%u", mode);
2681 if (mode == 0 || error.Fail())
2682 response.Printf(",%i", (int)error.GetError());
2683 return SendPacketNoLock(response.GetData(), response.GetSize());
2684 }
2685 return SendErrorResponse(23);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002686}
2687
Greg Clayton3dedae12013-12-06 21:45:27 +00002688GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002689GDBRemoteCommunicationServer::Handle_vFile_Exists (StringExtractorGDBRemote &packet)
2690{
2691 packet.SetFilePos(::strlen("vFile:exists:"));
2692 std::string path;
2693 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002694 if (!path.empty())
2695 {
2696 bool retcode = Host::GetFileExists(FileSpec(path.c_str(), false));
2697 StreamString response;
2698 response.PutChar('F');
2699 response.PutChar(',');
2700 if (retcode)
2701 response.PutChar('1');
2702 else
2703 response.PutChar('0');
2704 return SendPacketNoLock(response.GetData(), response.GetSize());
2705 }
2706 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002707}
2708
Greg Clayton3dedae12013-12-06 21:45:27 +00002709GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002710GDBRemoteCommunicationServer::Handle_vFile_symlink (StringExtractorGDBRemote &packet)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002711{
Greg Claytonfbb76342013-11-20 21:07:01 +00002712 packet.SetFilePos(::strlen("vFile:symlink:"));
2713 std::string dst, src;
2714 packet.GetHexByteStringTerminatedBy(dst, ',');
2715 packet.GetChar(); // Skip ',' char
2716 packet.GetHexByteString(src);
2717 Error error = Host::Symlink(src.c_str(), dst.c_str());
2718 StreamString response;
2719 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002720 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002721}
2722
Greg Clayton3dedae12013-12-06 21:45:27 +00002723GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002724GDBRemoteCommunicationServer::Handle_vFile_unlink (StringExtractorGDBRemote &packet)
2725{
2726 packet.SetFilePos(::strlen("vFile:unlink:"));
2727 std::string path;
2728 packet.GetHexByteString(path);
2729 Error error = Host::Unlink(path.c_str());
2730 StreamString response;
2731 response.Printf("F%u,%u", error.GetError(), error.GetError());
Greg Clayton2b98c562013-11-22 18:53:12 +00002732 return SendPacketNoLock(response.GetData(), response.GetSize());
Greg Claytonfbb76342013-11-20 21:07:01 +00002733}
2734
Greg Clayton3dedae12013-12-06 21:45:27 +00002735GDBRemoteCommunication::PacketResult
Greg Claytonfbb76342013-11-20 21:07:01 +00002736GDBRemoteCommunicationServer::Handle_qPlatform_shell (StringExtractorGDBRemote &packet)
2737{
2738 packet.SetFilePos(::strlen("qPlatform_shell:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002739 std::string path;
2740 std::string working_dir;
2741 packet.GetHexByteStringTerminatedBy(path,',');
Greg Clayton2b98c562013-11-22 18:53:12 +00002742 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002743 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002744 if (packet.GetChar() == ',')
2745 {
2746 // FIXME: add timeout to qPlatform_shell packet
2747 // uint32_t timeout = packet.GetHexMaxU32(false, 32);
2748 uint32_t timeout = 10;
2749 if (packet.GetChar() == ',')
2750 packet.GetHexByteString(working_dir);
2751 int status, signo;
2752 std::string output;
2753 Error err = Host::RunShellCommand(path.c_str(),
2754 working_dir.empty() ? NULL : working_dir.c_str(),
2755 &status, &signo, &output, timeout);
2756 StreamGDBRemote response;
2757 if (err.Fail())
2758 {
2759 response.PutCString("F,");
2760 response.PutHex32(UINT32_MAX);
2761 }
2762 else
2763 {
2764 response.PutCString("F,");
2765 response.PutHex32(status);
2766 response.PutChar(',');
2767 response.PutHex32(signo);
2768 response.PutChar(',');
2769 response.PutEscapedBytes(output.c_str(), output.size());
2770 }
2771 return SendPacketNoLock(response.GetData(), response.GetSize());
2772 }
Daniel Maleae0f8f572013-08-26 23:57:52 +00002773 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002774 return SendErrorResponse(24);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002775}
2776
Todd Fialaaf245d12014-06-30 21:05:18 +00002777void
2778GDBRemoteCommunicationServer::SetCurrentThreadID (lldb::tid_t tid)
2779{
2780 assert (IsGdbServer () && "SetCurrentThreadID() called when not GdbServer code");
2781
2782 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2783 if (log)
2784 log->Printf ("GDBRemoteCommunicationServer::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
2785
2786 m_current_tid = tid;
2787 if (m_debugged_process_sp)
2788 m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
2789}
2790
2791void
2792GDBRemoteCommunicationServer::SetContinueThreadID (lldb::tid_t tid)
2793{
2794 assert (IsGdbServer () && "SetContinueThreadID() called when not GdbServer code");
2795
2796 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
2797 if (log)
2798 log->Printf ("GDBRemoteCommunicationServer::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
2799
2800 m_continue_tid = tid;
2801}
2802
2803GDBRemoteCommunication::PacketResult
2804GDBRemoteCommunicationServer::Handle_stop_reason (StringExtractorGDBRemote &packet)
2805{
2806 // Handle the $? gdbremote command.
2807 if (!IsGdbServer ())
2808 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_stop_reason() unimplemented");
2809
2810 // If no process, indicate error
2811 if (!m_debugged_process_sp)
2812 return SendErrorResponse (02);
2813
2814 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
2815}
2816
2817GDBRemoteCommunication::PacketResult
2818GDBRemoteCommunicationServer::SendStopReasonForState (lldb::StateType process_state, bool flush_on_exit)
2819{
2820 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2821
2822 switch (process_state)
2823 {
2824 case eStateAttaching:
2825 case eStateLaunching:
2826 case eStateRunning:
2827 case eStateStepping:
2828 case eStateDetached:
2829 // NOTE: gdb protocol doc looks like it should return $OK
2830 // when everything is running (i.e. no stopped result).
2831 return PacketResult::Success; // Ignore
2832
2833 case eStateSuspended:
2834 case eStateStopped:
2835 case eStateCrashed:
2836 {
2837 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
2838 // Make sure we set the current thread so g and p packets return
2839 // the data the gdb will expect.
2840 SetCurrentThreadID (tid);
2841 return SendStopReplyPacketForThread (tid);
2842 }
2843
2844 case eStateInvalid:
2845 case eStateUnloaded:
2846 case eStateExited:
2847 if (flush_on_exit)
2848 FlushInferiorOutput ();
2849 return SendWResponse(m_debugged_process_sp.get());
2850
2851 default:
2852 if (log)
2853 {
2854 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 ", current state reporting not handled: %s",
2855 __FUNCTION__,
2856 m_debugged_process_sp->GetID (),
2857 StateAsCString (process_state));
2858 }
2859 break;
2860 }
2861
2862 return SendErrorResponse (0);
2863}
2864
Greg Clayton3dedae12013-12-06 21:45:27 +00002865GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002866GDBRemoteCommunicationServer::Handle_vFile_Stat (StringExtractorGDBRemote &packet)
2867{
Greg Clayton2b98c562013-11-22 18:53:12 +00002868 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_vFile_Stat() unimplemented");
Daniel Maleae0f8f572013-08-26 23:57:52 +00002869}
2870
Greg Clayton3dedae12013-12-06 21:45:27 +00002871GDBRemoteCommunication::PacketResult
Daniel Maleae0f8f572013-08-26 23:57:52 +00002872GDBRemoteCommunicationServer::Handle_vFile_MD5 (StringExtractorGDBRemote &packet)
2873{
Greg Clayton2b98c562013-11-22 18:53:12 +00002874 packet.SetFilePos(::strlen("vFile:MD5:"));
Daniel Maleae0f8f572013-08-26 23:57:52 +00002875 std::string path;
2876 packet.GetHexByteString(path);
Greg Clayton2b98c562013-11-22 18:53:12 +00002877 if (!path.empty())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002878 {
Greg Clayton2b98c562013-11-22 18:53:12 +00002879 uint64_t a,b;
2880 StreamGDBRemote response;
2881 if (Host::CalculateMD5(FileSpec(path.c_str(),false),a,b) == false)
2882 {
2883 response.PutCString("F,");
2884 response.PutCString("x");
2885 }
2886 else
2887 {
2888 response.PutCString("F,");
2889 response.PutHex64(a);
2890 response.PutHex64(b);
2891 }
2892 return SendPacketNoLock(response.GetData(), response.GetSize());
Daniel Maleae0f8f572013-08-26 23:57:52 +00002893 }
Greg Clayton2b98c562013-11-22 18:53:12 +00002894 return SendErrorResponse(25);
Daniel Maleae0f8f572013-08-26 23:57:52 +00002895}
Greg Clayton2b98c562013-11-22 18:53:12 +00002896
Todd Fialaaf245d12014-06-30 21:05:18 +00002897GDBRemoteCommunication::PacketResult
2898GDBRemoteCommunicationServer::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
2899{
2900 // Ensure we're llgs.
2901 if (!IsGdbServer())
2902 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qRegisterInfo() unimplemented");
2903
2904 // Fail if we don't have a current process.
2905 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2906 return SendErrorResponse (68);
2907
2908 // Ensure we have a thread.
2909 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
2910 if (!thread_sp)
2911 return SendErrorResponse (69);
2912
2913 // Get the register context for the first thread.
2914 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2915 if (!reg_context_sp)
2916 return SendErrorResponse (69);
2917
2918 // Parse out the register number from the request.
2919 packet.SetFilePos (strlen("qRegisterInfo"));
2920 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2921 if (reg_index == std::numeric_limits<uint32_t>::max ())
2922 return SendErrorResponse (69);
2923
2924 // Return the end of registers response if we've iterated one past the end of the register set.
2925 if (reg_index >= reg_context_sp->GetRegisterCount ())
2926 return SendErrorResponse (69);
2927
2928 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2929 if (!reg_info)
2930 return SendErrorResponse (69);
2931
2932 // Build the reginfos response.
2933 StreamGDBRemote response;
2934
2935 response.PutCString ("name:");
2936 response.PutCString (reg_info->name);
2937 response.PutChar (';');
2938
2939 if (reg_info->alt_name && reg_info->alt_name[0])
2940 {
2941 response.PutCString ("alt-name:");
2942 response.PutCString (reg_info->alt_name);
2943 response.PutChar (';');
2944 }
2945
2946 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
2947
2948 switch (reg_info->encoding)
2949 {
2950 case eEncodingUint: response.PutCString ("encoding:uint;"); break;
2951 case eEncodingSint: response.PutCString ("encoding:sint;"); break;
2952 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
2953 case eEncodingVector: response.PutCString ("encoding:vector;"); break;
2954 default: break;
2955 }
2956
2957 switch (reg_info->format)
2958 {
2959 case eFormatBinary: response.PutCString ("format:binary;"); break;
2960 case eFormatDecimal: response.PutCString ("format:decimal;"); break;
2961 case eFormatHex: response.PutCString ("format:hex;"); break;
2962 case eFormatFloat: response.PutCString ("format:float;"); break;
2963 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break;
2964 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break;
2965 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break;
2966 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break;
2967 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break;
2968 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break;
2969 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
2970 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
2971 default: break;
2972 };
2973
2974 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
2975 if (register_set_name)
2976 {
2977 response.PutCString ("set:");
2978 response.PutCString (register_set_name);
2979 response.PutChar (';');
2980 }
2981
2982 if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM)
2983 response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]);
2984
2985 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
2986 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
2987
2988 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
2989 {
2990 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break;
2991 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break;
2992 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break;
2993 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break;
2994 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break;
2995 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break;
2996 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break;
2997 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break;
2998 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break;
2999 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break;
3000 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break;
3001 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break;
3002 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break;
3003 default: break;
3004 }
3005
3006 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
3007 {
3008 response.PutCString ("container-regs:");
3009 int i = 0;
3010 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3011 {
3012 if (i > 0)
3013 response.PutChar (',');
3014 response.Printf ("%" PRIx32, *reg_num);
3015 }
3016 response.PutChar (';');
3017 }
3018
3019 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
3020 {
3021 response.PutCString ("invalidate-regs:");
3022 int i = 0;
3023 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
3024 {
3025 if (i > 0)
3026 response.PutChar (',');
3027 response.Printf ("%" PRIx32, *reg_num);
3028 }
3029 response.PutChar (';');
3030 }
3031
3032 return SendPacketNoLock(response.GetData(), response.GetSize());
3033}
3034
3035GDBRemoteCommunication::PacketResult
3036GDBRemoteCommunicationServer::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
3037{
3038 // Ensure we're llgs.
3039 if (!IsGdbServer())
3040 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_qfThreadInfo() unimplemented");
3041
3042 // Fail if we don't have a current process.
3043 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3044 return SendErrorResponse (68);
3045
3046 StreamGDBRemote response;
3047 response.PutChar ('m');
3048
3049 NativeThreadProtocolSP thread_sp;
3050 uint32_t thread_index;
3051 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
3052 thread_sp;
3053 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
3054 {
3055 if (thread_index > 0)
3056 response.PutChar(',');
3057 response.Printf ("%" PRIx64, thread_sp->GetID ());
3058 }
3059
3060 return SendPacketNoLock(response.GetData(), response.GetSize());
3061}
3062
3063GDBRemoteCommunication::PacketResult
3064GDBRemoteCommunicationServer::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
3065{
3066 // Ensure we're llgs.
3067 if (!IsGdbServer())
3068 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_qsThreadInfo() unimplemented");
3069
3070 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
3071 return SendPacketNoLock ("l", 1);
3072}
3073
3074GDBRemoteCommunication::PacketResult
3075GDBRemoteCommunicationServer::Handle_p (StringExtractorGDBRemote &packet)
3076{
3077 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3078
3079 // Ensure we're llgs.
3080 if (!IsGdbServer())
3081 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_p() unimplemented");
3082
3083 // Parse out the register number from the request.
3084 packet.SetFilePos (strlen("p"));
3085 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3086 if (reg_index == std::numeric_limits<uint32_t>::max ())
3087 {
3088 if (log)
3089 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3090 return SendErrorResponse (0x15);
3091 }
3092
3093 // Get the thread to use.
3094 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3095 if (!thread_sp)
3096 {
3097 if (log)
3098 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available", __FUNCTION__);
3099 return SendErrorResponse (0x15);
3100 }
3101
3102 // Get the thread's register context.
3103 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3104 if (!reg_context_sp)
3105 {
3106 if (log)
3107 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 ());
3108 return SendErrorResponse (0x15);
3109 }
3110
3111 // Return the end of registers response if we've iterated one past the end of the register set.
3112 if (reg_index >= reg_context_sp->GetRegisterCount ())
3113 {
3114 if (log)
3115 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ());
3116 return SendErrorResponse (0x15);
3117 }
3118
3119 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3120 if (!reg_info)
3121 {
3122 if (log)
3123 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3124 return SendErrorResponse (0x15);
3125 }
3126
3127 // Build the reginfos response.
3128 StreamGDBRemote response;
3129
3130 // Retrieve the value
3131 RegisterValue reg_value;
3132 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
3133 if (error.Fail ())
3134 {
3135 if (log)
3136 log->Printf ("GDBRemoteCommunicationServer::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3137 return SendErrorResponse (0x15);
3138 }
3139
3140 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
3141 if (!data)
3142 {
3143 if (log)
3144 log->Printf ("GDBRemoteCommunicationServer::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
3145 return SendErrorResponse (0x15);
3146 }
3147
3148 // FIXME flip as needed to get data in big/little endian format for this host.
3149 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
3150 response.PutHex8 (data[i]);
3151
3152 return SendPacketNoLock (response.GetData (), response.GetSize ());
3153}
3154
3155GDBRemoteCommunication::PacketResult
3156GDBRemoteCommunicationServer::Handle_P (StringExtractorGDBRemote &packet)
3157{
3158 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3159
3160 // Ensure we're llgs.
3161 if (!IsGdbServer())
3162 return SendUnimplementedResponse ("GDBRemoteCommunicationServer::Handle_P() unimplemented");
3163
3164 // Ensure there is more content.
3165 if (packet.GetBytesLeft () < 1)
3166 return SendIllFormedResponse (packet, "Empty P packet");
3167
3168 // Parse out the register number from the request.
3169 packet.SetFilePos (strlen("P"));
3170 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3171 if (reg_index == std::numeric_limits<uint32_t>::max ())
3172 {
3173 if (log)
3174 log->Printf ("GDBRemoteCommunicationServer::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
3175 return SendErrorResponse (0x29);
3176 }
3177
3178 // Note debugserver would send an E30 here.
3179 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
3180 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
3181
3182 // Get process architecture.
3183 ArchSpec process_arch;
3184 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
3185 {
3186 if (log)
3187 log->Printf ("GDBRemoteCommunicationServer::%s failed to retrieve inferior architecture", __FUNCTION__);
3188 return SendErrorResponse (0x49);
3189 }
3190
3191 // Parse out the value.
3192 const uint64_t raw_value = packet.GetHexMaxU64 (process_arch.GetByteOrder () == lldb::eByteOrderLittle, std::numeric_limits<uint64_t>::max ());
3193
3194 // Get the thread to use.
3195 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3196 if (!thread_sp)
3197 {
3198 if (log)
3199 log->Printf ("GDBRemoteCommunicationServer::%s failed, no thread available (thread index 0)", __FUNCTION__);
3200 return SendErrorResponse (0x28);
3201 }
3202
3203 // Get the thread's register context.
3204 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3205 if (!reg_context_sp)
3206 {
3207 if (log)
3208 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 ());
3209 return SendErrorResponse (0x15);
3210 }
3211
3212 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
3213 if (!reg_info)
3214 {
3215 if (log)
3216 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
3217 return SendErrorResponse (0x48);
3218 }
3219
3220 // Return the end of registers response if we've iterated one past the end of the register set.
3221 if (reg_index >= reg_context_sp->GetRegisterCount ())
3222 {
3223 if (log)
3224 log->Printf ("GDBRemoteCommunicationServer::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetRegisterCount ());
3225 return SendErrorResponse (0x47);
3226 }
3227
3228
3229 // Build the reginfos response.
3230 StreamGDBRemote response;
3231
3232 // FIXME Could be suffixed with a thread: parameter.
3233 // That thread then needs to be fed back into the reg context retrieval above.
3234 Error error = reg_context_sp->WriteRegisterFromUnsigned (reg_info, raw_value);
3235 if (error.Fail ())
3236 {
3237 if (log)
3238 log->Printf ("GDBRemoteCommunicationServer::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
3239 return SendErrorResponse (0x32);
3240 }
3241
3242 return SendOKResponse();
3243}
3244
3245GDBRemoteCommunicationServer::PacketResult
3246GDBRemoteCommunicationServer::Handle_H (StringExtractorGDBRemote &packet)
3247{
3248 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3249
3250 // Ensure we're llgs.
3251 if (!IsGdbServer())
3252 return SendUnimplementedResponse("GDBRemoteCommunicationServer::Handle_H() unimplemented");
3253
3254 // Fail if we don't have a current process.
3255 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3256 {
3257 if (log)
3258 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3259 return SendErrorResponse (0x15);
3260 }
3261
3262 // Parse out which variant of $H is requested.
3263 packet.SetFilePos (strlen("H"));
3264 if (packet.GetBytesLeft () < 1)
3265 {
3266 if (log)
3267 log->Printf ("GDBRemoteCommunicationServer::%s failed, H command missing {g,c} variant", __FUNCTION__);
3268 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
3269 }
3270
3271 const char h_variant = packet.GetChar ();
3272 switch (h_variant)
3273 {
3274 case 'g':
3275 break;
3276
3277 case 'c':
3278 break;
3279
3280 default:
3281 if (log)
3282 log->Printf ("GDBRemoteCommunicationServer::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
3283 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3284 }
3285
3286 // Parse out the thread number.
3287 // FIXME return a parse success/fail value. All values are valid here.
3288 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
3289
3290 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
3291 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
3292 {
3293 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
3294 if (!thread_sp)
3295 {
3296 if (log)
3297 log->Printf ("GDBRemoteCommunicationServer::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
3298 return SendErrorResponse (0x15);
3299 }
3300 }
3301
3302 // Now switch the given thread type.
3303 switch (h_variant)
3304 {
3305 case 'g':
3306 SetCurrentThreadID (tid);
3307 break;
3308
3309 case 'c':
3310 SetContinueThreadID (tid);
3311 break;
3312
3313 default:
3314 assert (false && "unsupported $H variant - shouldn't get here");
3315 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
3316 }
3317
3318 return SendOKResponse();
3319}
3320
3321GDBRemoteCommunicationServer::PacketResult
3322GDBRemoteCommunicationServer::Handle_interrupt (StringExtractorGDBRemote &packet)
3323{
3324 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3325
3326 // Ensure we're llgs.
3327 if (!IsGdbServer())
3328 {
3329 // Only supported on llgs
3330 return SendUnimplementedResponse ("");
3331 }
3332
3333 // Fail if we don't have a current process.
3334 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3335 {
3336 if (log)
3337 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3338 return SendErrorResponse (0x15);
3339 }
3340
3341 // Build the ResumeActionList - stop everything.
3342 lldb_private::ResumeActionList actions (StateType::eStateStopped, 0);
3343
3344 Error error = m_debugged_process_sp->Resume (actions);
3345 if (error.Fail ())
3346 {
3347 if (log)
3348 {
3349 log->Printf ("GDBRemoteCommunicationServer::%s failed for process %" PRIu64 ": %s",
3350 __FUNCTION__,
3351 m_debugged_process_sp->GetID (),
3352 error.AsCString ());
3353 }
3354 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
3355 }
3356
3357 if (log)
3358 log->Printf ("GDBRemoteCommunicationServer::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
3359
3360 // No response required from stop all.
3361 return PacketResult::Success;
3362}
3363
3364GDBRemoteCommunicationServer::PacketResult
3365GDBRemoteCommunicationServer::Handle_m (StringExtractorGDBRemote &packet)
3366{
3367 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3368
3369 // Ensure we're llgs.
3370 if (!IsGdbServer())
3371 {
3372 // Only supported on llgs
3373 return SendUnimplementedResponse ("");
3374 }
3375
3376 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3377 {
3378 if (log)
3379 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3380 return SendErrorResponse (0x15);
3381 }
3382
3383 // Parse out the memory address.
3384 packet.SetFilePos (strlen("m"));
3385 if (packet.GetBytesLeft() < 1)
3386 return SendIllFormedResponse(packet, "Too short m packet");
3387
3388 // Read the address. Punting on validation.
3389 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3390 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3391
3392 // Validate comma.
3393 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3394 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
3395
3396 // Get # bytes to read.
3397 if (packet.GetBytesLeft() < 1)
3398 return SendIllFormedResponse(packet, "Length missing in m packet");
3399
3400 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3401 if (byte_count == 0)
3402 {
3403 if (log)
3404 log->Printf ("GDBRemoteCommunicationServer::%s nothing to read: zero-length packet", __FUNCTION__);
3405 return PacketResult::Success;
3406 }
3407
3408 // Allocate the response buffer.
3409 std::string buf(byte_count, '\0');
3410 if (buf.empty())
3411 return SendErrorResponse (0x78);
3412
3413
3414 // Retrieve the process memory.
3415 lldb::addr_t bytes_read = 0;
3416 lldb_private::Error error = m_debugged_process_sp->ReadMemory (read_addr, &buf[0], byte_count, bytes_read);
3417 if (error.Fail ())
3418 {
3419 if (log)
3420 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
3421 return SendErrorResponse (0x08);
3422 }
3423
3424 if (bytes_read == 0)
3425 {
3426 if (log)
3427 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);
3428 return SendErrorResponse (0x08);
3429 }
3430
3431 StreamGDBRemote response;
3432 for (lldb::addr_t i = 0; i < bytes_read; ++i)
3433 response.PutHex8(buf[i]);
3434
3435 return SendPacketNoLock(response.GetData(), response.GetSize());
3436}
3437
3438GDBRemoteCommunication::PacketResult
3439GDBRemoteCommunicationServer::Handle_QSetDetachOnError (StringExtractorGDBRemote &packet)
3440{
3441 packet.SetFilePos(::strlen ("QSetDetachOnError:"));
3442 if (packet.GetU32(0))
3443 m_process_launch_info.GetFlags().Set (eLaunchFlagDetachOnError);
3444 else
3445 m_process_launch_info.GetFlags().Clear (eLaunchFlagDetachOnError);
3446 return SendOKResponse ();
3447}
3448
3449GDBRemoteCommunicationServer::PacketResult
3450GDBRemoteCommunicationServer::Handle_M (StringExtractorGDBRemote &packet)
3451{
3452 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3453
3454 // Ensure we're llgs.
3455 if (!IsGdbServer())
3456 {
3457 // Only supported on llgs
3458 return SendUnimplementedResponse ("");
3459 }
3460
3461 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3462 {
3463 if (log)
3464 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3465 return SendErrorResponse (0x15);
3466 }
3467
3468 // Parse out the memory address.
3469 packet.SetFilePos (strlen("M"));
3470 if (packet.GetBytesLeft() < 1)
3471 return SendIllFormedResponse(packet, "Too short M packet");
3472
3473 // Read the address. Punting on validation.
3474 // FIXME replace with Hex U64 read with no default value that fails on failed read.
3475 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
3476
3477 // Validate comma.
3478 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
3479 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
3480
3481 // Get # bytes to read.
3482 if (packet.GetBytesLeft() < 1)
3483 return SendIllFormedResponse(packet, "Length missing in M packet");
3484
3485 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
3486 if (byte_count == 0)
3487 {
3488 if (log)
3489 log->Printf ("GDBRemoteCommunicationServer::%s nothing to write: zero-length packet", __FUNCTION__);
3490 return PacketResult::Success;
3491 }
3492
3493 // Validate colon.
3494 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
3495 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
3496
3497 // Allocate the conversion buffer.
3498 std::vector<uint8_t> buf(byte_count, 0);
3499 if (buf.empty())
3500 return SendErrorResponse (0x78);
3501
3502 // Convert the hex memory write contents to bytes.
3503 StreamGDBRemote response;
3504 const uint64_t convert_count = static_cast<uint64_t> (packet.GetHexBytes (&buf[0], byte_count, 0));
3505 if (convert_count != byte_count)
3506 {
3507 if (log)
3508 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);
3509 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
3510 }
3511
3512 // Write the process memory.
3513 lldb::addr_t bytes_written = 0;
3514 lldb_private::Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
3515 if (error.Fail ())
3516 {
3517 if (log)
3518 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
3519 return SendErrorResponse (0x09);
3520 }
3521
3522 if (bytes_written == 0)
3523 {
3524 if (log)
3525 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);
3526 return SendErrorResponse (0x09);
3527 }
3528
3529 return SendOKResponse ();
3530}
3531
3532GDBRemoteCommunicationServer::PacketResult
3533GDBRemoteCommunicationServer::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
3534{
3535 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3536
3537 // We don't support if we're not llgs.
3538 if (!IsGdbServer())
3539 return SendUnimplementedResponse ("");
3540
3541 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
3542 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
3543 // client only asks this when a process is being debugged.
3544
3545 // Ensure we have a process running; otherwise, we can't figure this out
3546 // since we won't have a NativeProcessProtocol.
3547 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3548 {
3549 if (log)
3550 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3551 return SendErrorResponse (0x15);
3552 }
3553
3554 // Test if we can get any region back when asking for the region around NULL.
3555 MemoryRegionInfo region_info;
3556 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
3557 if (error.Fail ())
3558 {
3559 // We don't support memory region info collection for this NativeProcessProtocol.
3560 return SendUnimplementedResponse ("");
3561 }
3562
3563 return SendOKResponse();
3564}
3565
3566GDBRemoteCommunicationServer::PacketResult
3567GDBRemoteCommunicationServer::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
3568{
3569 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3570
3571 // We don't support if we're not llgs.
3572 if (!IsGdbServer())
3573 return SendUnimplementedResponse ("");
3574
3575 // Ensure we have a process.
3576 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3577 {
3578 if (log)
3579 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3580 return SendErrorResponse (0x15);
3581 }
3582
3583 // Parse out the memory address.
3584 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
3585 if (packet.GetBytesLeft() < 1)
3586 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
3587
3588 // Read the address. Punting on validation.
3589 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
3590
3591 StreamGDBRemote response;
3592
3593 // Get the memory region info for the target address.
3594 MemoryRegionInfo region_info;
3595 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
3596 if (error.Fail ())
3597 {
3598 // Return the error message.
3599
3600 response.PutCString ("error:");
3601 response.PutCStringAsRawHex8 (error.AsCString ());
3602 response.PutChar (';');
3603 }
3604 else
3605 {
3606 // Range start and size.
3607 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
3608
3609 // Permissions.
3610 if (region_info.GetReadable () ||
3611 region_info.GetWritable () ||
3612 region_info.GetExecutable ())
3613 {
3614 // Write permissions info.
3615 response.PutCString ("permissions:");
3616
3617 if (region_info.GetReadable ())
3618 response.PutChar ('r');
3619 if (region_info.GetWritable ())
3620 response.PutChar('w');
3621 if (region_info.GetExecutable())
3622 response.PutChar ('x');
3623
3624 response.PutChar (';');
3625 }
3626 }
3627
3628 return SendPacketNoLock(response.GetData(), response.GetSize());
3629}
3630
3631GDBRemoteCommunicationServer::PacketResult
3632GDBRemoteCommunicationServer::Handle_Z (StringExtractorGDBRemote &packet)
3633{
3634 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3635
3636 // We don't support if we're not llgs.
3637 if (!IsGdbServer())
3638 return SendUnimplementedResponse ("");
3639
3640 // Ensure we have a process.
3641 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3642 {
3643 if (log)
3644 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3645 return SendErrorResponse (0x15);
3646 }
3647
3648 // Parse out software or hardware breakpoint requested.
3649 packet.SetFilePos (strlen("Z"));
3650 if (packet.GetBytesLeft() < 1)
3651 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
3652
3653 bool want_breakpoint = true;
3654 bool want_hardware = false;
3655
3656 const char breakpoint_type_char = packet.GetChar ();
3657 switch (breakpoint_type_char)
3658 {
3659 case '0': want_hardware = false; want_breakpoint = true; break;
3660 case '1': want_hardware = true; want_breakpoint = true; break;
3661 case '2': want_breakpoint = false; break;
3662 case '3': want_breakpoint = false; break;
3663 default:
3664 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
3665
3666 }
3667
3668 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3669 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after breakpoint type");
3670
3671 // FIXME implement watchpoint support.
3672 if (!want_breakpoint)
3673 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3674
3675 // Parse out the breakpoint address.
3676 if (packet.GetBytesLeft() < 1)
3677 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
3678 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3679
3680 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3681 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
3682
3683 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3684 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3685 if (kind == std::numeric_limits<uint32_t>::max ())
3686 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse kind argument");
3687
3688 if (want_breakpoint)
3689 {
3690 // Try to set the breakpoint.
3691 const Error error = m_debugged_process_sp->SetBreakpoint (breakpoint_addr, kind, want_hardware);
3692 if (error.Success ())
3693 return SendOKResponse ();
3694 else
3695 {
3696 if (log)
3697 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to set breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3698 return SendErrorResponse (0x09);
3699 }
3700 }
3701
3702 // FIXME fix up after watchpoints are handled.
3703 return SendUnimplementedResponse ("");
3704}
3705
3706GDBRemoteCommunicationServer::PacketResult
3707GDBRemoteCommunicationServer::Handle_z (StringExtractorGDBRemote &packet)
3708{
3709 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
3710
3711 // We don't support if we're not llgs.
3712 if (!IsGdbServer())
3713 return SendUnimplementedResponse ("");
3714
3715 // Ensure we have a process.
3716 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3717 {
3718 if (log)
3719 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3720 return SendErrorResponse (0x15);
3721 }
3722
3723 // Parse out software or hardware breakpoint requested.
3724 packet.SetFilePos (strlen("Z"));
3725 if (packet.GetBytesLeft() < 1)
3726 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
3727
3728 bool want_breakpoint = true;
3729
3730 const char breakpoint_type_char = packet.GetChar ();
3731 switch (breakpoint_type_char)
3732 {
3733 case '0': want_breakpoint = true; break;
3734 case '1': want_breakpoint = true; break;
3735 case '2': want_breakpoint = false; break;
3736 case '3': want_breakpoint = false; break;
3737 default:
3738 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
3739
3740 }
3741
3742 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3743 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after breakpoint type");
3744
3745 // FIXME implement watchpoint support.
3746 if (!want_breakpoint)
3747 return SendUnimplementedResponse ("watchpoint support not yet implemented");
3748
3749 // Parse out the breakpoint address.
3750 if (packet.GetBytesLeft() < 1)
3751 return SendIllFormedResponse(packet, "Too short z packet, missing address");
3752 const lldb::addr_t breakpoint_addr = packet.GetHexMaxU64(false, 0);
3753
3754 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
3755 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
3756
3757 // Parse out the breakpoint kind (i.e. size hint for opcode size).
3758 const uint32_t kind = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
3759 if (kind == std::numeric_limits<uint32_t>::max ())
3760 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse kind argument");
3761
3762 if (want_breakpoint)
3763 {
3764 // Try to set the breakpoint.
3765 const Error error = m_debugged_process_sp->RemoveBreakpoint (breakpoint_addr);
3766 if (error.Success ())
3767 return SendOKResponse ();
3768 else
3769 {
3770 if (log)
3771 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to remove breakpoint: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
3772 return SendErrorResponse (0x09);
3773 }
3774 }
3775
3776 // FIXME fix up after watchpoints are handled.
3777 return SendUnimplementedResponse ("");
3778}
3779
3780GDBRemoteCommunicationServer::PacketResult
3781GDBRemoteCommunicationServer::Handle_s (StringExtractorGDBRemote &packet)
3782{
3783 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
3784
3785 // We don't support if we're not llgs.
3786 if (!IsGdbServer())
3787 return SendUnimplementedResponse ("");
3788
3789 // Ensure we have a process.
3790 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3791 {
3792 if (log)
3793 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3794 return SendErrorResponse (0x32);
3795 }
3796
3797 // We first try to use a continue thread id. If any one or any all set, use the current thread.
3798 // Bail out if we don't have a thread id.
3799 lldb::tid_t tid = GetContinueThreadID ();
3800 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3801 tid = GetCurrentThreadID ();
3802 if (tid == LLDB_INVALID_THREAD_ID)
3803 return SendErrorResponse (0x33);
3804
3805 // Double check that we have such a thread.
3806 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3807 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
3808 if (!thread_sp || thread_sp->GetID () != tid)
3809 return SendErrorResponse (0x33);
3810
3811 // Create the step action for the given thread.
3812 lldb_private::ResumeAction action = { tid, eStateStepping, 0 };
3813
3814 // Setup the actions list.
3815 lldb_private::ResumeActionList actions;
3816 actions.Append (action);
3817
3818 // All other threads stop while we're single stepping a thread.
3819 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
3820 Error error = m_debugged_process_sp->Resume (actions);
3821 if (error.Fail ())
3822 {
3823 if (log)
3824 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
3825 return SendErrorResponse(0x49);
3826 }
3827
3828 // No response here - the stop or exit will come from the resulting action.
3829 return PacketResult::Success;
3830}
3831
3832GDBRemoteCommunicationServer::PacketResult
3833GDBRemoteCommunicationServer::Handle_qSupported (StringExtractorGDBRemote &packet)
3834{
3835 StreamGDBRemote response;
3836
3837 // Features common to lldb-platform and llgs.
3838 uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet size--debugger can always use less
3839 response.Printf ("PacketSize=%x", max_packet_size);
3840
3841 response.PutCString (";QStartNoAckMode+");
3842 response.PutCString (";QThreadSuffixSupported+");
3843 response.PutCString (";QListThreadsInStopReply+");
3844#if defined(__linux__)
3845 response.PutCString (";qXfer:auxv:read+");
3846#endif
3847
3848 return SendPacketNoLock(response.GetData(), response.GetSize());
3849}
3850
3851GDBRemoteCommunicationServer::PacketResult
3852GDBRemoteCommunicationServer::Handle_QThreadSuffixSupported (StringExtractorGDBRemote &packet)
3853{
3854 m_thread_suffix_supported = true;
3855 return SendOKResponse();
3856}
3857
3858GDBRemoteCommunicationServer::PacketResult
3859GDBRemoteCommunicationServer::Handle_QListThreadsInStopReply (StringExtractorGDBRemote &packet)
3860{
3861 m_list_threads_in_stop_reply = true;
3862 return SendOKResponse();
3863}
3864
3865GDBRemoteCommunicationServer::PacketResult
3866GDBRemoteCommunicationServer::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
3867{
3868 // We don't support if we're not llgs.
3869 if (!IsGdbServer())
3870 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
3871
3872 // *BSD impls should be able to do this too.
3873#if defined(__linux__)
3874 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3875
3876 // Parse out the offset.
3877 packet.SetFilePos (strlen("qXfer:auxv:read::"));
3878 if (packet.GetBytesLeft () < 1)
3879 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3880
3881 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3882 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
3883 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
3884
3885 // Parse out comma.
3886 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
3887 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
3888
3889 // Parse out the length.
3890 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
3891 if (auxv_length == std::numeric_limits<uint64_t>::max ())
3892 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
3893
3894 // Grab the auxv data if we need it.
3895 if (!m_active_auxv_buffer_sp)
3896 {
3897 // Make sure we have a valid process.
3898 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
3899 {
3900 if (log)
3901 log->Printf ("GDBRemoteCommunicationServer::%s failed, no process available", __FUNCTION__);
3902 return SendErrorResponse (0x10);
3903 }
3904
3905 // Grab the auxv data.
3906 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
3907 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
3908 {
3909 // Hmm, no auxv data, call that an error.
3910 if (log)
3911 log->Printf ("GDBRemoteCommunicationServer::%s failed, no auxv data retrieved", __FUNCTION__);
3912 m_active_auxv_buffer_sp.reset ();
3913 return SendErrorResponse (0x11);
3914 }
3915 }
3916
3917 // FIXME find out if/how I lock the stream here.
3918
3919 StreamGDBRemote response;
3920 bool done_with_buffer = false;
3921
3922 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
3923 {
3924 // We have nothing left to send. Mark the buffer as complete.
3925 response.PutChar ('l');
3926 done_with_buffer = true;
3927 }
3928 else
3929 {
3930 // Figure out how many bytes are available starting at the given offset.
3931 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
3932
3933 // Figure out how many bytes we're going to read.
3934 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
3935
3936 // Mark the response type according to whether we're reading the remainder of the auxv data.
3937 if (bytes_to_read >= bytes_remaining)
3938 {
3939 // There will be nothing left to read after this
3940 response.PutChar ('l');
3941 done_with_buffer = true;
3942 }
3943 else
3944 {
3945 // There will still be bytes to read after this request.
3946 response.PutChar ('m');
3947 }
3948
3949 // Now write the data in encoded binary form.
3950 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
3951 }
3952
3953 if (done_with_buffer)
3954 m_active_auxv_buffer_sp.reset ();
3955
3956 return SendPacketNoLock(response.GetData(), response.GetSize());
3957#else
3958 return SendUnimplementedResponse ("not implemented on this platform");
3959#endif
3960}
3961
3962GDBRemoteCommunicationServer::PacketResult
3963GDBRemoteCommunicationServer::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
3964{
3965 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
3966
3967 // We don't support if we're not llgs.
3968 if (!IsGdbServer())
3969 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
3970
3971 // Move past packet name.
3972 packet.SetFilePos (strlen ("QSaveRegisterState"));
3973
3974 // Get the thread to use.
3975 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
3976 if (!thread_sp)
3977 {
3978 if (m_thread_suffix_supported)
3979 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
3980 else
3981 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
3982 }
3983
3984 // Grab the register context for the thread.
3985 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
3986 if (!reg_context_sp)
3987 {
3988 if (log)
3989 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 ());
3990 return SendErrorResponse (0x15);
3991 }
3992
3993 // Save registers to a buffer.
3994 DataBufferSP register_data_sp;
3995 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
3996 if (error.Fail ())
3997 {
3998 if (log)
3999 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4000 return SendErrorResponse (0x75);
4001 }
4002
4003 // Allocate a new save id.
4004 const uint32_t save_id = GetNextSavedRegistersID ();
4005 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
4006
4007 // Save the register data buffer under the save id.
4008 {
4009 Mutex::Locker locker (m_saved_registers_mutex);
4010 m_saved_registers_map[save_id] = register_data_sp;
4011 }
4012
4013 // Write the response.
4014 StreamGDBRemote response;
4015 response.Printf ("%" PRIu32, save_id);
4016 return SendPacketNoLock(response.GetData(), response.GetSize());
4017}
4018
4019GDBRemoteCommunicationServer::PacketResult
4020GDBRemoteCommunicationServer::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
4021{
4022 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4023
4024 // We don't support if we're not llgs.
4025 if (!IsGdbServer())
4026 return SendUnimplementedResponse ("only supported for lldb-gdbserver");
4027
4028 // Parse out save id.
4029 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
4030 if (packet.GetBytesLeft () < 1)
4031 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
4032
4033 const uint32_t save_id = packet.GetU32 (0);
4034 if (save_id == 0)
4035 {
4036 if (log)
4037 log->Printf ("GDBRemoteCommunicationServer::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
4038 return SendErrorResponse (0x76);
4039 }
4040
4041 // Get the thread to use.
4042 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
4043 if (!thread_sp)
4044 {
4045 if (m_thread_suffix_supported)
4046 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
4047 else
4048 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
4049 }
4050
4051 // Grab the register context for the thread.
4052 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
4053 if (!reg_context_sp)
4054 {
4055 if (log)
4056 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 ());
4057 return SendErrorResponse (0x15);
4058 }
4059
4060 // Retrieve register state buffer, then remove from the list.
4061 DataBufferSP register_data_sp;
4062 {
4063 Mutex::Locker locker (m_saved_registers_mutex);
4064
4065 // Find the register set buffer for the given save id.
4066 auto it = m_saved_registers_map.find (save_id);
4067 if (it == m_saved_registers_map.end ())
4068 {
4069 if (log)
4070 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);
4071 return SendErrorResponse (0x77);
4072 }
4073 register_data_sp = it->second;
4074
4075 // Remove it from the map.
4076 m_saved_registers_map.erase (it);
4077 }
4078
4079 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
4080 if (error.Fail ())
4081 {
4082 if (log)
4083 log->Printf ("GDBRemoteCommunicationServer::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
4084 return SendErrorResponse (0x77);
4085 }
4086
4087 return SendOKResponse();
4088}
4089
4090void
4091GDBRemoteCommunicationServer::FlushInferiorOutput ()
4092{
4093 // If we're not monitoring an inferior's terminal, ignore this.
4094 if (!m_stdio_communication.IsConnected())
4095 return;
4096
4097 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
4098 if (log)
4099 log->Printf ("GDBRemoteCommunicationServer::%s() called", __FUNCTION__);
4100
4101 // FIXME implement a timeout on the join.
4102 m_stdio_communication.JoinReadThread();
4103}
4104
4105void
4106GDBRemoteCommunicationServer::MaybeCloseInferiorTerminalConnection ()
4107{
4108 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
4109
4110 // Tell the stdio connection to shut down.
4111 if (m_stdio_communication.IsConnected())
4112 {
4113 auto connection = m_stdio_communication.GetConnection();
4114 if (connection)
4115 {
4116 Error error;
4117 connection->Disconnect (&error);
4118
4119 if (error.Success ())
4120 {
4121 if (log)
4122 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
4123 }
4124 else
4125 {
4126 if (log)
4127 log->Printf ("GDBRemoteCommunicationServer::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
4128 }
4129 }
4130 }
4131}
4132
4133
4134lldb_private::NativeThreadProtocolSP
4135GDBRemoteCommunicationServer::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
4136{
4137 NativeThreadProtocolSP thread_sp;
4138
4139 // We have no thread if we don't have a process.
4140 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
4141 return thread_sp;
4142
4143 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
4144 // Use the current thread in that case.
4145 if (!m_thread_suffix_supported)
4146 {
4147 const lldb::tid_t current_tid = GetCurrentThreadID ();
4148 if (current_tid == LLDB_INVALID_THREAD_ID)
4149 return thread_sp;
4150 else if (current_tid == 0)
4151 {
4152 // Pick a thread.
4153 return m_debugged_process_sp->GetThreadAtIndex (0);
4154 }
4155 else
4156 return m_debugged_process_sp->GetThreadByID (current_tid);
4157 }
4158
4159 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
4160
4161 // Parse out the ';'.
4162 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
4163 {
4164 if (log)
4165 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4166 return thread_sp;
4167 }
4168
4169 if (!packet.GetBytesLeft ())
4170 return thread_sp;
4171
4172 // Parse out thread: portion.
4173 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
4174 {
4175 if (log)
4176 log->Printf ("GDBRemoteCommunicationServer::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
4177 return thread_sp;
4178 }
4179 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
4180 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4181 if (tid != 0)
4182 return m_debugged_process_sp->GetThreadByID (tid);
4183
4184 return thread_sp;
4185}
4186
4187lldb::tid_t
4188GDBRemoteCommunicationServer::GetCurrentThreadID () const
4189{
4190 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
4191 {
4192 // Use whatever the debug process says is the current thread id
4193 // since the protocol either didn't specify or specified we want
4194 // any/all threads marked as the current thread.
4195 if (!m_debugged_process_sp)
4196 return LLDB_INVALID_THREAD_ID;
4197 return m_debugged_process_sp->GetCurrentThreadID ();
4198 }
4199 // Use the specific current thread id set by the gdb remote protocol.
4200 return m_current_tid;
4201}
4202
4203uint32_t
4204GDBRemoteCommunicationServer::GetNextSavedRegistersID ()
4205{
4206 Mutex::Locker locker (m_saved_registers_mutex);
4207 return m_next_saved_registers_id++;
4208}
4209