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