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