blob: aed0992bbe2b13b34d5141c31274304c46cfd50d [file] [log] [blame]
Tamas Berghammere13c2732015-02-11 10:29:30 +00001//===-- GDBRemoteCommunicationServerLLGS.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
10#include <errno.h>
11
12#include "lldb/Host/Config.h"
13
14#include "GDBRemoteCommunicationServerLLGS.h"
15#include "lldb/Core/StreamGDBRemote.h"
16
17// C Includes
18// C++ Includes
19#include <cstring>
20#include <chrono>
21#include <thread>
22
23// Other libraries and framework includes
24#include "llvm/ADT/Triple.h"
25#include "lldb/Interpreter/Args.h"
Zachary Turner90aff472015-03-03 23:36:51 +000026#include "lldb/Core/DataBuffer.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000027#include "lldb/Core/Debugger.h"
28#include "lldb/Core/Log.h"
29#include "lldb/Core/State.h"
30#include "lldb/Core/StreamString.h"
31#include "lldb/Host/ConnectionFileDescriptor.h"
32#include "lldb/Host/Debug.h"
33#include "lldb/Host/Endian.h"
34#include "lldb/Host/File.h"
35#include "lldb/Host/FileSystem.h"
36#include "lldb/Host/Host.h"
37#include "lldb/Host/HostInfo.h"
38#include "lldb/Host/StringConvert.h"
39#include "lldb/Host/TimeValue.h"
40#include "lldb/Target/FileAction.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000041#include "lldb/Target/MemoryRegionInfo.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000042#include "lldb/Target/Platform.h"
43#include "lldb/Target/Process.h"
44#include "lldb/Host/common/NativeRegisterContext.h"
45#include "lldb/Host/common/NativeProcessProtocol.h"
46#include "lldb/Host/common/NativeThreadProtocol.h"
47
48// Project includes
49#include "Utility/StringExtractorGDBRemote.h"
50#include "Utility/UriParser.h"
51#include "ProcessGDBRemote.h"
52#include "ProcessGDBRemoteLog.h"
53
54using namespace lldb;
55using namespace lldb_private;
56
57//----------------------------------------------------------------------
58// GDBRemote Errors
59//----------------------------------------------------------------------
60
61namespace
62{
63 enum GDBRemoteServerError
64 {
65 // Set to the first unused error number in literal form below
66 eErrorFirst = 29,
67 eErrorNoProcess = eErrorFirst,
68 eErrorResume,
69 eErrorExitStatus
70 };
71}
72
73//----------------------------------------------------------------------
74// GDBRemoteCommunicationServerLLGS constructor
75//----------------------------------------------------------------------
76GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
77 const lldb::PlatformSP& platform_sp,
78 lldb::DebuggerSP &debugger_sp) :
79 GDBRemoteCommunicationServerCommon ("gdb-remote.server", "gdb-remote.server.rx_packet"),
80 m_platform_sp (platform_sp),
81 m_async_thread (LLDB_INVALID_HOST_THREAD),
82 m_current_tid (LLDB_INVALID_THREAD_ID),
83 m_continue_tid (LLDB_INVALID_THREAD_ID),
84 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
85 m_debugged_process_sp (),
86 m_debugger_sp (debugger_sp),
87 m_stdio_communication ("process.stdio"),
88 m_inferior_prev_state (StateType::eStateInvalid),
89 m_active_auxv_buffer_sp (),
90 m_saved_registers_mutex (),
91 m_saved_registers_map (),
92 m_next_saved_registers_id (1)
93{
94 assert(platform_sp);
95 assert(debugger_sp && "must specify non-NULL debugger_sp for lldb-gdbserver");
96 RegisterPacketHandlers();
97}
98
99//----------------------------------------------------------------------
100// Destructor
101//----------------------------------------------------------------------
102GDBRemoteCommunicationServerLLGS::~GDBRemoteCommunicationServerLLGS()
103{
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +0000104 Mutex::Locker locker (m_debugged_process_mutex);
105
106 if (m_debugged_process_sp)
107 {
108 m_debugged_process_sp->Terminate ();
109 m_debugged_process_sp.reset ();
110 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000111}
112
113void
114GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers()
115{
116 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_A,
117 &GDBRemoteCommunicationServerLLGS::Handle_A);
118 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
119 &GDBRemoteCommunicationServerLLGS::Handle_C);
120 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
121 &GDBRemoteCommunicationServerLLGS::Handle_c);
122 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
123 &GDBRemoteCommunicationServerLLGS::Handle_D);
124 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
125 &GDBRemoteCommunicationServerLLGS::Handle_H);
126 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
127 &GDBRemoteCommunicationServerLLGS::Handle_I);
128 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_interrupt,
129 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
130 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_m,
131 &GDBRemoteCommunicationServerLLGS::Handle_m);
132 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
133 &GDBRemoteCommunicationServerLLGS::Handle_M);
134 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
135 &GDBRemoteCommunicationServerLLGS::Handle_p);
136 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
137 &GDBRemoteCommunicationServerLLGS::Handle_P);
138 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
139 &GDBRemoteCommunicationServerLLGS::Handle_qC);
140 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
141 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
142 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
143 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
144 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
145 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
146 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
147 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
148 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
149 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
150 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
151 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
152 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
153 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
154 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
155 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
156 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
157 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
158 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
159 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
160 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
161 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
162 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
163 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
164 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
165 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
166 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
167 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
168 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
169 &GDBRemoteCommunicationServerLLGS::Handle_s);
170 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_stop_reason,
171 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
172 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vAttach,
173 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
174 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont,
175 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
176 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont_actions,
177 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
178 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
179 &GDBRemoteCommunicationServerLLGS::Handle_Z);
180 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
181 &GDBRemoteCommunicationServerLLGS::Handle_z);
182
183 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
184 [this](StringExtractorGDBRemote packet,
185 Error &error,
186 bool &interrupt,
187 bool &quit)
188 {
189 quit = true;
190 return this->Handle_k (packet);
191 });
192}
193
194lldb_private::Error
195GDBRemoteCommunicationServerLLGS::SetLaunchArguments (const char *const args[], int argc)
196{
197 if ((argc < 1) || !args || !args[0] || !args[0][0])
198 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
199
200 m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
201 return lldb_private::Error ();
202}
203
204lldb_private::Error
205GDBRemoteCommunicationServerLLGS::SetLaunchFlags (unsigned int launch_flags)
206{
207 m_process_launch_info.GetFlags ().Set (launch_flags);
208 return lldb_private::Error ();
209}
210
211lldb_private::Error
212GDBRemoteCommunicationServerLLGS::LaunchProcess ()
213{
214 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
215
216 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
217 return lldb_private::Error ("%s: no process command line specified to launch", __FUNCTION__);
218
219 lldb_private::Error error;
220 {
221 Mutex::Locker locker (m_debugged_process_mutex);
222 assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
223 error = m_platform_sp->LaunchNativeProcess (
224 m_process_launch_info,
225 *this,
226 m_debugged_process_sp);
227 }
228
229 if (!error.Success ())
230 {
231 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
232 return error;
233 }
234
Vince Harron4a8abd32015-02-13 19:15:24 +0000235 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
236 // as needed.
237 // llgs local-process debugging may specify PTY paths, which will make these
238 // file actions non-null
239 // process launch -i/e/o will also make these file actions non-null
240 // nullptr means that the traffic is expected to flow over gdb-remote protocol
241 if (
242 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
243 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
244 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr
245 )
Tamas Berghammere13c2732015-02-11 10:29:30 +0000246 {
Vince Harron4a8abd32015-02-13 19:15:24 +0000247 // nullptr means it's not redirected to file or pty (in case of LLGS local)
248 // at least one of stdio will be transferred pty<->gdb-remote
249 // we need to give the pty master handle to this object to read and/or write
Tamas Berghammere13c2732015-02-11 10:29:30 +0000250 if (log)
251 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " setting up stdout/stderr redirection via $O gdb-remote commands", __FUNCTION__, m_debugged_process_sp->GetID ());
252
253 // Setup stdout/stderr mapping from inferior to $O
254 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
255 if (terminal_fd >= 0)
256 {
257 if (log)
258 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
259 error = SetSTDIOFileDescriptor (terminal_fd);
260 if (error.Fail ())
261 return error;
262 }
263 else
264 {
265 if (log)
266 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
267 }
268 }
269 else
270 {
271 if (log)
272 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " skipping stdout/stderr redirection via $O: inferior will communicate over client-provided file descriptors", __FUNCTION__, m_debugged_process_sp->GetID ());
273 }
274
275 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
276
277 // Add to list of spawned processes.
278 lldb::pid_t pid;
279 if ((pid = m_process_launch_info.GetProcessID ()) != LLDB_INVALID_PROCESS_ID)
280 {
281 // add to spawned pids
282 Mutex::Locker locker (m_spawned_pids_mutex);
283 // On an lldb-gdbserver, we would expect there to be only one.
284 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
285 m_spawned_pids.insert (pid);
286 }
287
288 return error;
289}
290
Tamas Berghammere13c2732015-02-11 10:29:30 +0000291lldb_private::Error
292GDBRemoteCommunicationServerLLGS::AttachToProcess (lldb::pid_t pid)
293{
294 Error error;
295
296 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
297 if (log)
298 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64, __FUNCTION__, pid);
299
300 // Scope for mutex locker.
301 {
302 // Before we try to attach, make sure we aren't already monitoring something else.
303 Mutex::Locker locker (m_spawned_pids_mutex);
304 if (!m_spawned_pids.empty ())
305 {
306 error.SetErrorStringWithFormat ("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, *m_spawned_pids.begin());
307 return error;
308 }
309
310 // Try to attach.
311 error = m_platform_sp->AttachNativeProcess (pid, *this, m_debugged_process_sp);
312 if (!error.Success ())
313 {
314 fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
315 return error;
316 }
317
318 // Setup stdout/stderr mapping from inferior.
319 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
320 if (terminal_fd >= 0)
321 {
322 if (log)
323 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
324 error = SetSTDIOFileDescriptor (terminal_fd);
325 if (error.Fail ())
326 return error;
327 }
328 else
329 {
330 if (log)
331 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
332 }
333
334 printf ("Attached to process %" PRIu64 "...\n", pid);
335
336 // Add to list of spawned processes.
337 assert (m_spawned_pids.empty () && "lldb-gdbserver adding tracked process but one already existed");
338 m_spawned_pids.insert (pid);
339
340 return error;
341 }
342}
343
344void
345GDBRemoteCommunicationServerLLGS::InitializeDelegate (lldb_private::NativeProcessProtocol *process)
346{
347 assert (process && "process cannot be NULL");
348 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
349 if (log)
350 {
351 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
352 __FUNCTION__,
353 process->GetID (),
354 StateAsCString (process->GetState ()));
355 }
356}
357
358GDBRemoteCommunication::PacketResult
359GDBRemoteCommunicationServerLLGS::SendWResponse (lldb_private::NativeProcessProtocol *process)
360{
361 assert (process && "process cannot be NULL");
362 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
363
364 // send W notification
365 ExitType exit_type = ExitType::eExitTypeInvalid;
366 int return_code = 0;
367 std::string exit_description;
368
369 const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
370 if (!got_exit_info)
371 {
372 if (log)
373 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
374
375 StreamGDBRemote response;
376 response.PutChar ('E');
377 response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
378 return SendPacketNoLock(response.GetData(), response.GetSize());
379 }
380 else
381 {
382 if (log)
383 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", returning exit type %d, return code %d [%s]", __FUNCTION__, process->GetID (), exit_type, return_code, exit_description.c_str ());
384
385 StreamGDBRemote response;
386
387 char return_type_code;
388 switch (exit_type)
389 {
390 case ExitType::eExitTypeExit:
391 return_type_code = 'W';
392 break;
393 case ExitType::eExitTypeSignal:
394 return_type_code = 'X';
395 break;
396 case ExitType::eExitTypeStop:
397 return_type_code = 'S';
398 break;
399 case ExitType::eExitTypeInvalid:
400 return_type_code = 'E';
401 break;
402 }
403 response.PutChar (return_type_code);
404
405 // POSIX exit status limited to unsigned 8 bits.
406 response.PutHex8 (return_code);
407
408 return SendPacketNoLock(response.GetData(), response.GetSize());
409 }
410}
411
412static void
413AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
414{
415 int64_t i;
416 if (swap)
417 {
418 for (i = buf_size-1; i >= 0; i--)
419 response.PutHex8 (buf[i]);
420 }
421 else
422 {
423 for (i = 0; i < buf_size; i++)
424 response.PutHex8 (buf[i]);
425 }
426}
427
428static void
429WriteRegisterValueInHexFixedWidth (StreamString &response,
430 NativeRegisterContextSP &reg_ctx_sp,
431 const RegisterInfo &reg_info,
432 const RegisterValue *reg_value_p)
433{
434 RegisterValue reg_value;
435 if (!reg_value_p)
436 {
437 Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
438 if (error.Success ())
439 reg_value_p = &reg_value;
440 // else log.
441 }
442
443 if (reg_value_p)
444 {
445 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
446 }
447 else
448 {
449 // Zero-out any unreadable values.
450 if (reg_info.byte_size > 0)
451 {
452 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
453 AppendHexValue (response, zeros.data(), zeros.size(), false);
454 }
455 }
456}
457
Tamas Berghammere13c2732015-02-11 10:29:30 +0000458GDBRemoteCommunication::PacketResult
459GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread (lldb::tid_t tid)
460{
461 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
462
463 // Ensure we have a debugged process.
464 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
465 return SendErrorResponse (50);
466
467 if (log)
468 log->Printf ("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
469 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
470
471 // Ensure we can get info on the given thread.
472 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
473 if (!thread_sp)
474 return SendErrorResponse (51);
475
476 // Grab the reason this thread stopped.
477 struct ThreadStopInfo tid_stop_info;
478 std::string description;
479 if (!thread_sp->GetStopReason (tid_stop_info, description))
480 return SendErrorResponse (52);
481
482 // FIXME implement register handling for exec'd inferiors.
483 // if (tid_stop_info.reason == eStopReasonExec)
484 // {
485 // const bool force = true;
486 // InitializeRegisters(force);
487 // }
488
489 StreamString response;
490 // Output the T packet with the thread
491 response.PutChar ('T');
492 int signum = tid_stop_info.details.signal.signo;
493 if (log)
494 {
495 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
496 __FUNCTION__,
497 m_debugged_process_sp->GetID (),
498 tid,
499 signum,
500 tid_stop_info.reason,
501 tid_stop_info.details.exception.type);
502 }
503
504 // Print the signal number.
505 response.PutHex8 (signum & 0xff);
506
507 // Include the tid.
508 response.Printf ("thread:%" PRIx64 ";", tid);
509
510 // Include the thread name if there is one.
511 const std::string thread_name = thread_sp->GetName ();
512 if (!thread_name.empty ())
513 {
514 size_t thread_name_len = thread_name.length ();
515
516 if (::strcspn (thread_name.c_str (), "$#+-;:") == thread_name_len)
517 {
518 response.PutCString ("name:");
519 response.PutCString (thread_name.c_str ());
520 }
521 else
522 {
523 // The thread name contains special chars, send as hex bytes.
524 response.PutCString ("hexname:");
525 response.PutCStringAsRawHex8 (thread_name.c_str ());
526 }
527 response.PutChar (';');
528 }
529
530 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
531 // will send all thread IDs back in the "threads" key whose value is
532 // a list of hex thread IDs separated by commas:
533 // "threads:10a,10b,10c;"
534 // This will save the debugger from having to send a pair of qfThreadInfo
535 // and qsThreadInfo packets, but it also might take a lot of room in the
536 // stop reply packet, so it must be enabled only on systems where there
537 // are no limits on packet lengths.
538 if (m_list_threads_in_stop_reply)
539 {
540 response.PutCString ("threads:");
541
542 uint32_t thread_index = 0;
543 NativeThreadProtocolSP listed_thread_sp;
544 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))
545 {
546 if (thread_index > 0)
547 response.PutChar (',');
548 response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
549 }
550 response.PutChar (';');
551 }
552
553 //
554 // Expedite registers.
555 //
556
557 // Grab the register context.
558 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
559 if (reg_ctx_sp)
560 {
561 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
562 const RegisterSet *reg_set_p;
563 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
564 {
565 if (log)
566 log->Printf ("GDBRemoteCommunicationServerLLGS::%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);
567
568 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
569 {
570 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
571 if (reg_info_p == nullptr)
572 {
573 if (log)
574 log->Printf ("GDBRemoteCommunicationServerLLGS::%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);
575 }
576 else if (reg_info_p->value_regs == nullptr)
577 {
578 // Only expediate registers that are not contained in other registers.
579 RegisterValue reg_value;
580 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
581 if (error.Success ())
Chaoren Lincaf31142015-02-17 15:41:28 +0000582 {
583 response.Printf ("%.02x:", *reg_num_p);
584 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p, &reg_value);
585 response.PutChar (';');
586 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000587 else
588 {
589 if (log)
590 log->Printf ("GDBRemoteCommunicationServerLLGS::%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 ());
591
592 }
593 }
594 }
595 }
596 }
597
598 const char* reason_str = nullptr;
599 switch (tid_stop_info.reason)
600 {
601 case eStopReasonTrace:
602 reason_str = "trace";
603 break;
604 case eStopReasonBreakpoint:
605 reason_str = "breakpoint";
606 break;
607 case eStopReasonWatchpoint:
608 reason_str = "watchpoint";
609 break;
610 case eStopReasonSignal:
611 reason_str = "signal";
612 break;
613 case eStopReasonException:
614 reason_str = "exception";
615 break;
616 case eStopReasonExec:
617 reason_str = "exec";
618 break;
619 case eStopReasonInstrumentation:
620 case eStopReasonInvalid:
621 case eStopReasonPlanComplete:
622 case eStopReasonThreadExiting:
623 case eStopReasonNone:
624 break;
625 }
626 if (reason_str != nullptr)
627 {
628 response.Printf ("reason:%s;", reason_str);
629 }
630
631 if (!description.empty())
632 {
633 // Description may contains special chars, send as hex bytes.
634 response.PutCString ("description:");
635 response.PutCStringAsRawHex8 (description.c_str ());
636 response.PutChar (';');
637 }
638 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
639 {
640 response.PutCString ("metype:");
641 response.PutHex64 (tid_stop_info.details.exception.type);
642 response.PutCString (";mecount:");
643 response.PutHex32 (tid_stop_info.details.exception.data_count);
644 response.PutChar (';');
645
646 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
647 {
648 response.PutCString ("medata:");
649 response.PutHex64 (tid_stop_info.details.exception.data[i]);
650 response.PutChar (';');
651 }
652 }
653
654 return SendPacketNoLock (response.GetData(), response.GetSize());
655}
656
657void
658GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited (lldb_private::NativeProcessProtocol *process)
659{
660 assert (process && "process cannot be NULL");
661
662 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
663 if (log)
664 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
665
666 // Send the exit result, and don't flush output.
667 // Note: flushing output here would join the inferior stdio reflection thread, which
668 // would gunk up the waitpid monitor thread that is calling this.
669 PacketResult result = SendStopReasonForState (StateType::eStateExited, false);
670 if (result != PacketResult::Success)
671 {
672 if (log)
673 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
674 }
675
676 // Remove the process from the list of spawned pids.
677 {
678 Mutex::Locker locker (m_spawned_pids_mutex);
679 if (m_spawned_pids.erase (process->GetID ()) < 1)
680 {
681 if (log)
682 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to remove PID %" PRIu64 " from the spawned pids list", __FUNCTION__, process->GetID ());
683
684 }
685 }
686
687 // FIXME can't do this yet - since process state propagation is currently
688 // synchronous, it is running off the NativeProcessProtocol's innards and
689 // will tear down the NPP while it still has code to execute.
690#if 0
691 // Clear the NativeProcessProtocol pointer.
692 {
693 Mutex::Locker locker (m_debugged_process_mutex);
694 m_debugged_process_sp.reset();
695 }
696#endif
697
698 // Close the pipe to the inferior terminal i/o if we launched it
699 // and set one up. Otherwise, 'k' and its flush of stdio could
700 // end up waiting on a thread join that will never end. Consider
701 // adding a timeout to the connection thread join call so we
702 // can avoid that scenario altogether.
703 MaybeCloseInferiorTerminalConnection ();
704
705 // We are ready to exit the debug monitor.
706 m_exit_now = true;
707}
708
709void
710GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped (lldb_private::NativeProcessProtocol *process)
711{
712 assert (process && "process cannot be NULL");
713
714 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
715 if (log)
716 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
717
718 // Send the stop reason unless this is the stop after the
719 // launch or attach.
720 switch (m_inferior_prev_state)
721 {
722 case eStateLaunching:
723 case eStateAttaching:
724 // Don't send anything per debugserver behavior.
725 break;
726 default:
727 // In all other cases, send the stop reason.
728 PacketResult result = SendStopReasonForState (StateType::eStateStopped, false);
729 if (result != PacketResult::Success)
730 {
731 if (log)
732 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
733 }
734 break;
735 }
736}
737
738void
739GDBRemoteCommunicationServerLLGS::ProcessStateChanged (lldb_private::NativeProcessProtocol *process, lldb::StateType state)
740{
741 assert (process && "process cannot be NULL");
742 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
743 if (log)
744 {
745 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
746 __FUNCTION__,
747 process->GetID (),
748 StateAsCString (state));
749 }
750
751 switch (state)
752 {
753 case StateType::eStateExited:
754 HandleInferiorState_Exited (process);
755 break;
756
757 case StateType::eStateStopped:
758 HandleInferiorState_Stopped (process);
759 break;
760
761 default:
762 if (log)
763 {
764 log->Printf ("GDBRemoteCommunicationServerLLGS::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
765 __FUNCTION__,
766 process->GetID (),
767 StateAsCString (state));
768 }
769 break;
770 }
771
772 // Remember the previous state reported to us.
773 m_inferior_prev_state = state;
774}
775
776void
777GDBRemoteCommunicationServerLLGS::DidExec (NativeProcessProtocol *process)
778{
779 ClearProcessSpecificData ();
780}
781
782GDBRemoteCommunication::PacketResult
783GDBRemoteCommunicationServerLLGS::SendONotification (const char *buffer, uint32_t len)
784{
785 if ((buffer == nullptr) || (len == 0))
786 {
787 // Nothing to send.
788 return PacketResult::Success;
789 }
790
791 StreamString response;
792 response.PutChar ('O');
793 response.PutBytesAsRawHex8 (buffer, len);
794
795 return SendPacketNoLock (response.GetData (), response.GetSize ());
796}
797
798lldb_private::Error
799GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor (int fd)
800{
801 Error error;
802
803 // Set up the Read Thread for reading/handling process I/O
804 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
805 if (!conn_up)
806 {
807 error.SetErrorString ("failed to create ConnectionFileDescriptor");
808 return error;
809 }
810
811 m_stdio_communication.SetConnection (conn_up.release());
812 if (!m_stdio_communication.IsConnected ())
813 {
814 error.SetErrorString ("failed to set connection for inferior I/O communication");
815 return error;
816 }
817
Vince Harron4a8abd32015-02-13 19:15:24 +0000818 // llgs local-process debugging may specify PTY paths, which will make these
819 // file actions non-null
820 // process launch -e/o will also make these file actions non-null
821 // nullptr means that the traffic is expected to flow over gdb-remote protocol
822 if (
823 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
824 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr
825 )
826 {
827 // output from the process must be forwarded over gdb-remote
828 // create a thread to read the handle and send the data
829 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
830 m_stdio_communication.StartReadThread();
831 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000832
833 return error;
834}
835
836void
837GDBRemoteCommunicationServerLLGS::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
838{
839 GDBRemoteCommunicationServerLLGS *server = reinterpret_cast<GDBRemoteCommunicationServerLLGS*> (baton);
840 static_cast<void> (server->SendONotification (static_cast<const char *>(src), src_len));
841}
842
843GDBRemoteCommunication::PacketResult
844GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
845{
846 // Fail if we don't have a current process.
847 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
848 return SendErrorResponse (68);
849
850 lldb::pid_t pid = m_debugged_process_sp->GetID ();
851
852 if (pid == LLDB_INVALID_PROCESS_ID)
853 return SendErrorResponse (1);
854
855 ProcessInstanceInfo proc_info;
856 if (!Host::GetProcessInfo (pid, proc_info))
857 return SendErrorResponse (1);
858
859 StreamString response;
860 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
861 return SendPacketNoLock (response.GetData (), response.GetSize ());
862}
863
864GDBRemoteCommunication::PacketResult
865GDBRemoteCommunicationServerLLGS::Handle_qC (StringExtractorGDBRemote &packet)
866{
867 // Fail if we don't have a current process.
868 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
869 return SendErrorResponse (68);
870
871 // Make sure we set the current thread so g and p packets return
872 // the data the gdb will expect.
873 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
874 SetCurrentThreadID (tid);
875
876 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
877 if (!thread_sp)
878 return SendErrorResponse (69);
879
880 StreamString response;
881 response.Printf ("QC%" PRIx64, thread_sp->GetID ());
882
883 return SendPacketNoLock (response.GetData(), response.GetSize());
884}
885
886bool
887GDBRemoteCommunicationServerLLGS::DebuggedProcessReaped (lldb::pid_t pid)
888{
889 // reap a process that we were debugging (but not debugserver)
890 Mutex::Locker locker (m_spawned_pids_mutex);
891 return m_spawned_pids.erase(pid) > 0;
892}
893
894bool
895GDBRemoteCommunicationServerLLGS::ReapDebuggedProcess (void *callback_baton,
896 lldb::pid_t pid,
897 bool exited,
898 int signal, // Zero for no signal
899 int status) // Exit value of process if signal is zero
900{
901 GDBRemoteCommunicationServerLLGS *server = (GDBRemoteCommunicationServerLLGS *)callback_baton;
902 server->DebuggedProcessReaped (pid);
903 return true;
904}
905
906GDBRemoteCommunication::PacketResult
907GDBRemoteCommunicationServerLLGS::Handle_k (StringExtractorGDBRemote &packet)
908{
909 // shutdown all spawned processes
910 std::set<lldb::pid_t> spawned_pids_copy;
911
912 // copy pids
913 {
914 Mutex::Locker locker (m_spawned_pids_mutex);
915 spawned_pids_copy.insert (m_spawned_pids.begin (), m_spawned_pids.end ());
916 }
917
918 // nuke the spawned processes
919 for (auto it = spawned_pids_copy.begin (); it != spawned_pids_copy.end (); ++it)
920 {
921 lldb::pid_t spawned_pid = *it;
922 if (!KillSpawnedProcess (spawned_pid))
923 {
924 fprintf (stderr, "%s: failed to kill spawned pid %" PRIu64 ", ignoring.\n", __FUNCTION__, spawned_pid);
925 }
926 }
927
928 FlushInferiorOutput ();
929
930 // No OK response for kill packet.
931 // return SendOKResponse ();
932 return PacketResult::Success;
933}
934
935GDBRemoteCommunication::PacketResult
936GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
937{
938 packet.SetFilePos(::strlen ("QSetDisableASLR:"));
939 if (packet.GetU32(0))
940 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
941 else
942 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
943 return SendOKResponse ();
944}
945
946GDBRemoteCommunication::PacketResult
947GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
948{
949 packet.SetFilePos (::strlen ("QSetWorkingDir:"));
950 std::string path;
951 packet.GetHexByteString (path);
952 m_process_launch_info.SwapWorkingDirectory (path);
953 return SendOKResponse ();
954}
955
956GDBRemoteCommunication::PacketResult
957GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
958{
959 const char *working_dir = m_process_launch_info.GetWorkingDirectory();
960 if (working_dir && working_dir[0])
961 {
962 StreamString response;
963 response.PutBytesAsRawHex8(working_dir, strlen(working_dir));
964 return SendPacketNoLock(response.GetData(), response.GetSize());
965 }
966
967 return SendErrorResponse(14);
968}
969
970GDBRemoteCommunication::PacketResult
971GDBRemoteCommunicationServerLLGS::Handle_C (StringExtractorGDBRemote &packet)
972{
973 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
974 if (log)
975 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
976
977 // Ensure we have a native process.
978 if (!m_debugged_process_sp)
979 {
980 if (log)
981 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
982 return SendErrorResponse (0x36);
983 }
984
985 // Pull out the signal number.
986 packet.SetFilePos (::strlen ("C"));
987 if (packet.GetBytesLeft () < 1)
988 {
989 // Shouldn't be using a C without a signal.
990 return SendIllFormedResponse (packet, "C packet specified without signal.");
991 }
992 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
993 if (signo == std::numeric_limits<uint32_t>::max ())
994 return SendIllFormedResponse (packet, "failed to parse signal number");
995
996 // Handle optional continue address.
997 if (packet.GetBytesLeft () > 0)
998 {
999 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1000 if (*packet.Peek () == ';')
1001 return SendUnimplementedResponse (packet.GetStringRef().c_str());
1002 else
1003 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
1004 }
1005
1006 lldb_private::ResumeActionList resume_actions (StateType::eStateRunning, 0);
1007 Error error;
1008
1009 // We have two branches: what to do if a continue thread is specified (in which case we target
1010 // sending the signal to that thread), or when we don't have a continue thread set (in which
1011 // case we send a signal to the process).
1012
1013 // TODO discuss with Greg Clayton, make sure this makes sense.
1014
1015 lldb::tid_t signal_tid = GetContinueThreadID ();
1016 if (signal_tid != LLDB_INVALID_THREAD_ID)
1017 {
1018 // The resume action for the continue thread (or all threads if a continue thread is not set).
1019 lldb_private::ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
1020
1021 // Add the action for the continue thread (or all threads when the continue thread isn't present).
1022 resume_actions.Append (action);
1023 }
1024 else
1025 {
1026 // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
1027 error = m_debugged_process_sp->Signal (signo);
1028 if (error.Fail ())
1029 {
1030 if (log)
1031 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send signal for process %" PRIu64 ": %s",
1032 __FUNCTION__,
1033 m_debugged_process_sp->GetID (),
1034 error.AsCString ());
1035
1036 return SendErrorResponse (0x52);
1037 }
1038 }
1039
1040 // Resume the threads.
1041 error = m_debugged_process_sp->Resume (resume_actions);
1042 if (error.Fail ())
1043 {
1044 if (log)
1045 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to resume threads for process %" PRIu64 ": %s",
1046 __FUNCTION__,
1047 m_debugged_process_sp->GetID (),
1048 error.AsCString ());
1049
1050 return SendErrorResponse (0x38);
1051 }
1052
1053 // Don't send an "OK" packet; response is the stopped/exited message.
1054 return PacketResult::Success;
1055}
1056
1057GDBRemoteCommunication::PacketResult
1058GDBRemoteCommunicationServerLLGS::Handle_c (StringExtractorGDBRemote &packet)
1059{
1060 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
1061 if (log)
1062 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1063
1064 packet.SetFilePos (packet.GetFilePos() + ::strlen ("c"));
1065
1066 // For now just support all continue.
1067 const bool has_continue_address = (packet.GetBytesLeft () > 0);
1068 if (has_continue_address)
1069 {
1070 if (log)
1071 log->Printf ("GDBRemoteCommunicationServerLLGS::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
1072 return SendUnimplementedResponse (packet.GetStringRef().c_str());
1073 }
1074
1075 // Ensure we have a native process.
1076 if (!m_debugged_process_sp)
1077 {
1078 if (log)
1079 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1080 return SendErrorResponse (0x36);
1081 }
1082
1083 // Build the ResumeActionList
1084 lldb_private::ResumeActionList actions (StateType::eStateRunning, 0);
1085
1086 Error error = m_debugged_process_sp->Resume (actions);
1087 if (error.Fail ())
1088 {
1089 if (log)
1090 {
1091 log->Printf ("GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64 ": %s",
1092 __FUNCTION__,
1093 m_debugged_process_sp->GetID (),
1094 error.AsCString ());
1095 }
1096 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1097 }
1098
1099 if (log)
1100 log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1101
1102 // No response required from continue.
1103 return PacketResult::Success;
1104}
1105
1106GDBRemoteCommunication::PacketResult
1107GDBRemoteCommunicationServerLLGS::Handle_vCont_actions (StringExtractorGDBRemote &packet)
1108{
1109 StreamString response;
1110 response.Printf("vCont;c;C;s;S");
1111
1112 return SendPacketNoLock(response.GetData(), response.GetSize());
1113}
1114
1115GDBRemoteCommunication::PacketResult
1116GDBRemoteCommunicationServerLLGS::Handle_vCont (StringExtractorGDBRemote &packet)
1117{
1118 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1119 if (log)
1120 log->Printf ("GDBRemoteCommunicationServerLLGS::%s handling vCont packet", __FUNCTION__);
1121
1122 packet.SetFilePos (::strlen ("vCont"));
1123
1124 if (packet.GetBytesLeft() == 0)
1125 {
1126 if (log)
1127 log->Printf ("GDBRemoteCommunicationServerLLGS::%s missing action from vCont package", __FUNCTION__);
1128 return SendIllFormedResponse (packet, "Missing action from vCont package");
1129 }
1130
1131 // Check if this is all continue (no options or ";c").
1132 if (::strcmp (packet.Peek (), ";c") == 0)
1133 {
1134 // Move past the ';', then do a simple 'c'.
1135 packet.SetFilePos (packet.GetFilePos () + 1);
1136 return Handle_c (packet);
1137 }
1138 else if (::strcmp (packet.Peek (), ";s") == 0)
1139 {
1140 // Move past the ';', then do a simple 's'.
1141 packet.SetFilePos (packet.GetFilePos () + 1);
1142 return Handle_s (packet);
1143 }
1144
1145 // Ensure we have a native process.
1146 if (!m_debugged_process_sp)
1147 {
1148 if (log)
1149 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1150 return SendErrorResponse (0x36);
1151 }
1152
1153 ResumeActionList thread_actions;
1154
1155 while (packet.GetBytesLeft () && *packet.Peek () == ';')
1156 {
1157 // Skip the semi-colon.
1158 packet.GetChar ();
1159
1160 // Build up the thread action.
1161 ResumeAction thread_action;
1162 thread_action.tid = LLDB_INVALID_THREAD_ID;
1163 thread_action.state = eStateInvalid;
1164 thread_action.signal = 0;
1165
1166 const char action = packet.GetChar ();
1167 switch (action)
1168 {
1169 case 'C':
1170 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1171 if (thread_action.signal == 0)
1172 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
1173 // Fall through to next case...
1174
1175 case 'c':
1176 // Continue
1177 thread_action.state = eStateRunning;
1178 break;
1179
1180 case 'S':
1181 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1182 if (thread_action.signal == 0)
1183 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
1184 // Fall through to next case...
1185
1186 case 's':
1187 // Step
1188 thread_action.state = eStateStepping;
1189 break;
1190
1191 default:
1192 return SendIllFormedResponse (packet, "Unsupported vCont action");
1193 break;
1194 }
1195
1196 // Parse out optional :{thread-id} value.
1197 if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
1198 {
1199 // Consume the separator.
1200 packet.GetChar ();
1201
1202 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
1203 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1204 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
1205 }
1206
1207 thread_actions.Append (thread_action);
1208 }
1209
1210 Error error = m_debugged_process_sp->Resume (thread_actions);
1211 if (error.Fail ())
1212 {
1213 if (log)
1214 {
1215 log->Printf ("GDBRemoteCommunicationServerLLGS::%s vCont failed for process %" PRIu64 ": %s",
1216 __FUNCTION__,
1217 m_debugged_process_sp->GetID (),
1218 error.AsCString ());
1219 }
1220 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1221 }
1222
1223 if (log)
1224 log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1225
1226 // No response required from vCont.
1227 return PacketResult::Success;
1228}
1229
1230void
1231GDBRemoteCommunicationServerLLGS::SetCurrentThreadID (lldb::tid_t tid)
1232{
1233 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1234 if (log)
1235 log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
1236
1237 m_current_tid = tid;
1238 if (m_debugged_process_sp)
1239 m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
1240}
1241
1242void
1243GDBRemoteCommunicationServerLLGS::SetContinueThreadID (lldb::tid_t tid)
1244{
1245 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1246 if (log)
1247 log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
1248
1249 m_continue_tid = tid;
1250}
1251
1252GDBRemoteCommunication::PacketResult
1253GDBRemoteCommunicationServerLLGS::Handle_stop_reason (StringExtractorGDBRemote &packet)
1254{
1255 // Handle the $? gdbremote command.
1256
1257 // If no process, indicate error
1258 if (!m_debugged_process_sp)
1259 return SendErrorResponse (02);
1260
1261 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
1262}
1263
1264GDBRemoteCommunication::PacketResult
1265GDBRemoteCommunicationServerLLGS::SendStopReasonForState (lldb::StateType process_state, bool flush_on_exit)
1266{
1267 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1268
1269 switch (process_state)
1270 {
1271 case eStateAttaching:
1272 case eStateLaunching:
1273 case eStateRunning:
1274 case eStateStepping:
1275 case eStateDetached:
1276 // NOTE: gdb protocol doc looks like it should return $OK
1277 // when everything is running (i.e. no stopped result).
1278 return PacketResult::Success; // Ignore
1279
1280 case eStateSuspended:
1281 case eStateStopped:
1282 case eStateCrashed:
1283 {
1284 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1285 // Make sure we set the current thread so g and p packets return
1286 // the data the gdb will expect.
1287 SetCurrentThreadID (tid);
1288 return SendStopReplyPacketForThread (tid);
1289 }
1290
1291 case eStateInvalid:
1292 case eStateUnloaded:
1293 case eStateExited:
1294 if (flush_on_exit)
1295 FlushInferiorOutput ();
1296 return SendWResponse(m_debugged_process_sp.get());
1297
1298 default:
1299 if (log)
1300 {
1301 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", current state reporting not handled: %s",
1302 __FUNCTION__,
1303 m_debugged_process_sp->GetID (),
1304 StateAsCString (process_state));
1305 }
1306 break;
1307 }
1308
1309 return SendErrorResponse (0);
1310}
1311
1312GDBRemoteCommunication::PacketResult
1313GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
1314{
1315 // Fail if we don't have a current process.
1316 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1317 return SendErrorResponse (68);
1318
1319 // Ensure we have a thread.
1320 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
1321 if (!thread_sp)
1322 return SendErrorResponse (69);
1323
1324 // Get the register context for the first thread.
1325 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1326 if (!reg_context_sp)
1327 return SendErrorResponse (69);
1328
1329 // Parse out the register number from the request.
1330 packet.SetFilePos (strlen("qRegisterInfo"));
1331 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1332 if (reg_index == std::numeric_limits<uint32_t>::max ())
1333 return SendErrorResponse (69);
1334
1335 // Return the end of registers response if we've iterated one past the end of the register set.
1336 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1337 return SendErrorResponse (69);
1338
1339 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1340 if (!reg_info)
1341 return SendErrorResponse (69);
1342
1343 // Build the reginfos response.
1344 StreamGDBRemote response;
1345
1346 response.PutCString ("name:");
1347 response.PutCString (reg_info->name);
1348 response.PutChar (';');
1349
1350 if (reg_info->alt_name && reg_info->alt_name[0])
1351 {
1352 response.PutCString ("alt-name:");
1353 response.PutCString (reg_info->alt_name);
1354 response.PutChar (';');
1355 }
1356
1357 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
1358
1359 switch (reg_info->encoding)
1360 {
1361 case eEncodingUint: response.PutCString ("encoding:uint;"); break;
1362 case eEncodingSint: response.PutCString ("encoding:sint;"); break;
1363 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
1364 case eEncodingVector: response.PutCString ("encoding:vector;"); break;
1365 default: break;
1366 }
1367
1368 switch (reg_info->format)
1369 {
1370 case eFormatBinary: response.PutCString ("format:binary;"); break;
1371 case eFormatDecimal: response.PutCString ("format:decimal;"); break;
1372 case eFormatHex: response.PutCString ("format:hex;"); break;
1373 case eFormatFloat: response.PutCString ("format:float;"); break;
1374 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break;
1375 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break;
1376 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break;
1377 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break;
1378 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break;
1379 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break;
1380 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
1381 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
1382 default: break;
1383 };
1384
1385 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1386 if (register_set_name)
1387 {
1388 response.PutCString ("set:");
1389 response.PutCString (register_set_name);
1390 response.PutChar (';');
1391 }
1392
1393 if (reg_info->kinds[RegisterKind::eRegisterKindGCC] != LLDB_INVALID_REGNUM)
1394 response.Printf ("gcc:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindGCC]);
1395
1396 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1397 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1398
1399 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
1400 {
1401 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break;
1402 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break;
1403 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break;
1404 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break;
1405 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break;
1406 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break;
1407 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break;
1408 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break;
1409 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break;
1410 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break;
1411 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break;
1412 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break;
1413 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break;
1414 default: break;
1415 }
1416
1417 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
1418 {
1419 response.PutCString ("container-regs:");
1420 int i = 0;
1421 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1422 {
1423 if (i > 0)
1424 response.PutChar (',');
1425 response.Printf ("%" PRIx32, *reg_num);
1426 }
1427 response.PutChar (';');
1428 }
1429
1430 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
1431 {
1432 response.PutCString ("invalidate-regs:");
1433 int i = 0;
1434 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1435 {
1436 if (i > 0)
1437 response.PutChar (',');
1438 response.Printf ("%" PRIx32, *reg_num);
1439 }
1440 response.PutChar (';');
1441 }
1442
1443 return SendPacketNoLock(response.GetData(), response.GetSize());
1444}
1445
1446GDBRemoteCommunication::PacketResult
1447GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
1448{
1449 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1450
1451 // Fail if we don't have a current process.
1452 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1453 {
1454 if (log)
1455 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
1456 return SendOKResponse ();
1457 }
1458
1459 StreamGDBRemote response;
1460 response.PutChar ('m');
1461
1462 if (log)
1463 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() starting thread iteration", __FUNCTION__);
1464
1465 NativeThreadProtocolSP thread_sp;
1466 uint32_t thread_index;
1467 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
1468 thread_sp;
1469 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
1470 {
1471 if (log)
1472 log->Printf ("GDBRemoteCommunicationServerLLGS::%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);
1473 if (thread_index > 0)
1474 response.PutChar(',');
1475 response.Printf ("%" PRIx64, thread_sp->GetID ());
1476 }
1477
1478 if (log)
1479 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() finished thread iteration", __FUNCTION__);
1480
1481 return SendPacketNoLock(response.GetData(), response.GetSize());
1482}
1483
1484GDBRemoteCommunication::PacketResult
1485GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
1486{
1487 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
1488 return SendPacketNoLock ("l", 1);
1489}
1490
1491GDBRemoteCommunication::PacketResult
1492GDBRemoteCommunicationServerLLGS::Handle_p (StringExtractorGDBRemote &packet)
1493{
1494 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1495
1496 // Parse out the register number from the request.
1497 packet.SetFilePos (strlen("p"));
1498 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1499 if (reg_index == std::numeric_limits<uint32_t>::max ())
1500 {
1501 if (log)
1502 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1503 return SendErrorResponse (0x15);
1504 }
1505
1506 // Get the thread to use.
1507 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1508 if (!thread_sp)
1509 {
1510 if (log)
1511 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available", __FUNCTION__);
1512 return SendErrorResponse (0x15);
1513 }
1514
1515 // Get the thread's register context.
1516 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1517 if (!reg_context_sp)
1518 {
1519 if (log)
1520 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
1521 return SendErrorResponse (0x15);
1522 }
1523
1524 // Return the end of registers response if we've iterated one past the end of the register set.
1525 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1526 {
1527 if (log)
1528 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1529 return SendErrorResponse (0x15);
1530 }
1531
1532 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1533 if (!reg_info)
1534 {
1535 if (log)
1536 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1537 return SendErrorResponse (0x15);
1538 }
1539
1540 // Build the reginfos response.
1541 StreamGDBRemote response;
1542
1543 // Retrieve the value
1544 RegisterValue reg_value;
1545 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
1546 if (error.Fail ())
1547 {
1548 if (log)
1549 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1550 return SendErrorResponse (0x15);
1551 }
1552
1553 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
1554 if (!data)
1555 {
1556 if (log)
1557 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
1558 return SendErrorResponse (0x15);
1559 }
1560
1561 // FIXME flip as needed to get data in big/little endian format for this host.
1562 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
1563 response.PutHex8 (data[i]);
1564
1565 return SendPacketNoLock (response.GetData (), response.GetSize ());
1566}
1567
1568GDBRemoteCommunication::PacketResult
1569GDBRemoteCommunicationServerLLGS::Handle_P (StringExtractorGDBRemote &packet)
1570{
1571 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1572
1573 // Ensure there is more content.
1574 if (packet.GetBytesLeft () < 1)
1575 return SendIllFormedResponse (packet, "Empty P packet");
1576
1577 // Parse out the register number from the request.
1578 packet.SetFilePos (strlen("P"));
1579 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1580 if (reg_index == std::numeric_limits<uint32_t>::max ())
1581 {
1582 if (log)
1583 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1584 return SendErrorResponse (0x29);
1585 }
1586
1587 // Note debugserver would send an E30 here.
1588 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
1589 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
1590
1591 // Get process architecture.
1592 ArchSpec process_arch;
1593 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
1594 {
1595 if (log)
1596 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to retrieve inferior architecture", __FUNCTION__);
1597 return SendErrorResponse (0x49);
1598 }
1599
1600 // Parse out the value.
1601 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
1602 size_t reg_size = packet.GetHexBytesAvail (reg_bytes, sizeof(reg_bytes));
1603
1604 // Get the thread to use.
1605 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1606 if (!thread_sp)
1607 {
1608 if (log)
1609 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available (thread index 0)", __FUNCTION__);
1610 return SendErrorResponse (0x28);
1611 }
1612
1613 // Get the thread's register context.
1614 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1615 if (!reg_context_sp)
1616 {
1617 if (log)
1618 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
1619 return SendErrorResponse (0x15);
1620 }
1621
1622 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex (reg_index);
1623 if (!reg_info)
1624 {
1625 if (log)
1626 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1627 return SendErrorResponse (0x48);
1628 }
1629
1630 // Return the end of registers response if we've iterated one past the end of the register set.
1631 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1632 {
1633 if (log)
1634 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1635 return SendErrorResponse (0x47);
1636 }
1637
1638 if (reg_size != reg_info->byte_size)
1639 {
1640 return SendIllFormedResponse (packet, "P packet register size is incorrect");
1641 }
1642
1643 // Build the reginfos response.
1644 StreamGDBRemote response;
1645
1646 RegisterValue reg_value (reg_bytes, reg_size, process_arch.GetByteOrder ());
1647 Error error = reg_context_sp->WriteRegister (reg_info, reg_value);
1648 if (error.Fail ())
1649 {
1650 if (log)
1651 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1652 return SendErrorResponse (0x32);
1653 }
1654
1655 return SendOKResponse();
1656}
1657
1658GDBRemoteCommunication::PacketResult
1659GDBRemoteCommunicationServerLLGS::Handle_H (StringExtractorGDBRemote &packet)
1660{
1661 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1662
1663 // Fail if we don't have a current process.
1664 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1665 {
1666 if (log)
1667 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1668 return SendErrorResponse (0x15);
1669 }
1670
1671 // Parse out which variant of $H is requested.
1672 packet.SetFilePos (strlen("H"));
1673 if (packet.GetBytesLeft () < 1)
1674 {
1675 if (log)
1676 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, H command missing {g,c} variant", __FUNCTION__);
1677 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
1678 }
1679
1680 const char h_variant = packet.GetChar ();
1681 switch (h_variant)
1682 {
1683 case 'g':
1684 break;
1685
1686 case 'c':
1687 break;
1688
1689 default:
1690 if (log)
1691 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
1692 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1693 }
1694
1695 // Parse out the thread number.
1696 // FIXME return a parse success/fail value. All values are valid here.
1697 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
1698
1699 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
1700 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
1701 {
1702 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
1703 if (!thread_sp)
1704 {
1705 if (log)
1706 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
1707 return SendErrorResponse (0x15);
1708 }
1709 }
1710
1711 // Now switch the given thread type.
1712 switch (h_variant)
1713 {
1714 case 'g':
1715 SetCurrentThreadID (tid);
1716 break;
1717
1718 case 'c':
1719 SetContinueThreadID (tid);
1720 break;
1721
1722 default:
1723 assert (false && "unsupported $H variant - shouldn't get here");
1724 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1725 }
1726
1727 return SendOKResponse();
1728}
1729
1730GDBRemoteCommunication::PacketResult
1731GDBRemoteCommunicationServerLLGS::Handle_I (StringExtractorGDBRemote &packet)
1732{
1733 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1734
1735 // Fail if we don't have a current process.
1736 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1737 {
1738 if (log)
1739 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1740 return SendErrorResponse (0x15);
1741 }
1742
1743 packet.SetFilePos (::strlen("I"));
1744 char tmp[4096];
1745 for (;;)
1746 {
1747 size_t read = packet.GetHexBytesAvail(tmp, sizeof(tmp));
1748 if (read == 0)
1749 {
1750 break;
1751 }
1752 // write directly to stdin *this might block if stdin buffer is full*
1753 // TODO: enqueue this block in circular buffer and send window size to remote host
1754 ConnectionStatus status;
1755 Error error;
1756 m_stdio_communication.Write(tmp, read, status, &error);
1757 if (error.Fail())
1758 {
1759 return SendErrorResponse (0x15);
1760 }
1761 }
1762
1763 return SendOKResponse();
1764}
1765
1766GDBRemoteCommunication::PacketResult
1767GDBRemoteCommunicationServerLLGS::Handle_interrupt (StringExtractorGDBRemote &packet)
1768{
1769 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1770
1771 // Fail if we don't have a current process.
1772 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1773 {
1774 if (log)
1775 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1776 return SendErrorResponse (0x15);
1777 }
1778
1779 // Interrupt the process.
1780 Error error = m_debugged_process_sp->Interrupt ();
1781 if (error.Fail ())
1782 {
1783 if (log)
1784 {
1785 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64 ": %s",
1786 __FUNCTION__,
1787 m_debugged_process_sp->GetID (),
1788 error.AsCString ());
1789 }
1790 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1791 }
1792
1793 if (log)
1794 log->Printf ("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1795
1796 // No response required from stop all.
1797 return PacketResult::Success;
1798}
1799
1800GDBRemoteCommunication::PacketResult
1801GDBRemoteCommunicationServerLLGS::Handle_m (StringExtractorGDBRemote &packet)
1802{
1803 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1804
1805 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1806 {
1807 if (log)
1808 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1809 return SendErrorResponse (0x15);
1810 }
1811
1812 // Parse out the memory address.
1813 packet.SetFilePos (strlen("m"));
1814 if (packet.GetBytesLeft() < 1)
1815 return SendIllFormedResponse(packet, "Too short m packet");
1816
1817 // Read the address. Punting on validation.
1818 // FIXME replace with Hex U64 read with no default value that fails on failed read.
1819 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
1820
1821 // Validate comma.
1822 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
1823 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
1824
1825 // Get # bytes to read.
1826 if (packet.GetBytesLeft() < 1)
1827 return SendIllFormedResponse(packet, "Length missing in m packet");
1828
1829 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
1830 if (byte_count == 0)
1831 {
1832 if (log)
1833 log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to read: zero-length packet", __FUNCTION__);
1834 return PacketResult::Success;
1835 }
1836
1837 // Allocate the response buffer.
1838 std::string buf(byte_count, '\0');
1839 if (buf.empty())
1840 return SendErrorResponse (0x78);
1841
1842
1843 // Retrieve the process memory.
1844 lldb::addr_t bytes_read = 0;
1845 lldb_private::Error error = m_debugged_process_sp->ReadMemory (read_addr, &buf[0], byte_count, bytes_read);
1846 if (error.Fail ())
1847 {
1848 if (log)
1849 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
1850 return SendErrorResponse (0x08);
1851 }
1852
1853 if (bytes_read == 0)
1854 {
1855 if (log)
1856 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": read %" PRIu64 " of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, bytes_read, byte_count);
1857 return SendErrorResponse (0x08);
1858 }
1859
1860 StreamGDBRemote response;
1861 for (lldb::addr_t i = 0; i < bytes_read; ++i)
1862 response.PutHex8(buf[i]);
1863
1864 return SendPacketNoLock(response.GetData(), response.GetSize());
1865}
1866
1867GDBRemoteCommunication::PacketResult
1868GDBRemoteCommunicationServerLLGS::Handle_M (StringExtractorGDBRemote &packet)
1869{
1870 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1871
1872 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1873 {
1874 if (log)
1875 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1876 return SendErrorResponse (0x15);
1877 }
1878
1879 // Parse out the memory address.
1880 packet.SetFilePos (strlen("M"));
1881 if (packet.GetBytesLeft() < 1)
1882 return SendIllFormedResponse(packet, "Too short M packet");
1883
1884 // Read the address. Punting on validation.
1885 // FIXME replace with Hex U64 read with no default value that fails on failed read.
1886 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
1887
1888 // Validate comma.
1889 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
1890 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
1891
1892 // Get # bytes to read.
1893 if (packet.GetBytesLeft() < 1)
1894 return SendIllFormedResponse(packet, "Length missing in M packet");
1895
1896 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
1897 if (byte_count == 0)
1898 {
1899 if (log)
1900 log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to write: zero-length packet", __FUNCTION__);
1901 return PacketResult::Success;
1902 }
1903
1904 // Validate colon.
1905 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
1906 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
1907
1908 // Allocate the conversion buffer.
1909 std::vector<uint8_t> buf(byte_count, 0);
1910 if (buf.empty())
1911 return SendErrorResponse (0x78);
1912
1913 // Convert the hex memory write contents to bytes.
1914 StreamGDBRemote response;
1915 const uint64_t convert_count = static_cast<uint64_t> (packet.GetHexBytes (&buf[0], byte_count, 0));
1916 if (convert_count != byte_count)
1917 {
1918 if (log)
1919 log->Printf ("GDBRemoteCommunicationServerLLGS::%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);
1920 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
1921 }
1922
1923 // Write the process memory.
1924 lldb::addr_t bytes_written = 0;
1925 lldb_private::Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
1926 if (error.Fail ())
1927 {
1928 if (log)
1929 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
1930 return SendErrorResponse (0x09);
1931 }
1932
1933 if (bytes_written == 0)
1934 {
1935 if (log)
1936 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": wrote %" PRIu64 " of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, bytes_written, byte_count);
1937 return SendErrorResponse (0x09);
1938 }
1939
1940 return SendOKResponse ();
1941}
1942
1943GDBRemoteCommunication::PacketResult
1944GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
1945{
1946 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1947
1948 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
1949 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
1950 // client only asks this when a process is being debugged.
1951
1952 // Ensure we have a process running; otherwise, we can't figure this out
1953 // since we won't have a NativeProcessProtocol.
1954 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1955 {
1956 if (log)
1957 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1958 return SendErrorResponse (0x15);
1959 }
1960
1961 // Test if we can get any region back when asking for the region around NULL.
1962 MemoryRegionInfo region_info;
1963 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
1964 if (error.Fail ())
1965 {
1966 // We don't support memory region info collection for this NativeProcessProtocol.
1967 return SendUnimplementedResponse ("");
1968 }
1969
1970 return SendOKResponse();
1971}
1972
1973GDBRemoteCommunication::PacketResult
1974GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
1975{
1976 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1977
1978 // Ensure we have a process.
1979 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1980 {
1981 if (log)
1982 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1983 return SendErrorResponse (0x15);
1984 }
1985
1986 // Parse out the memory address.
1987 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
1988 if (packet.GetBytesLeft() < 1)
1989 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
1990
1991 // Read the address. Punting on validation.
1992 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
1993
1994 StreamGDBRemote response;
1995
1996 // Get the memory region info for the target address.
1997 MemoryRegionInfo region_info;
1998 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
1999 if (error.Fail ())
2000 {
2001 // Return the error message.
2002
2003 response.PutCString ("error:");
2004 response.PutCStringAsRawHex8 (error.AsCString ());
2005 response.PutChar (';');
2006 }
2007 else
2008 {
2009 // Range start and size.
2010 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
2011
2012 // Permissions.
2013 if (region_info.GetReadable () ||
2014 region_info.GetWritable () ||
2015 region_info.GetExecutable ())
2016 {
2017 // Write permissions info.
2018 response.PutCString ("permissions:");
2019
2020 if (region_info.GetReadable ())
2021 response.PutChar ('r');
2022 if (region_info.GetWritable ())
2023 response.PutChar('w');
2024 if (region_info.GetExecutable())
2025 response.PutChar ('x');
2026
2027 response.PutChar (';');
2028 }
2029 }
2030
2031 return SendPacketNoLock(response.GetData(), response.GetSize());
2032}
2033
2034GDBRemoteCommunication::PacketResult
2035GDBRemoteCommunicationServerLLGS::Handle_Z (StringExtractorGDBRemote &packet)
2036{
2037 // Ensure we have a process.
2038 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2039 {
2040 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2041 if (log)
2042 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2043 return SendErrorResponse (0x15);
2044 }
2045
2046 // Parse out software or hardware breakpoint or watchpoint requested.
2047 packet.SetFilePos (strlen("Z"));
2048 if (packet.GetBytesLeft() < 1)
2049 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
2050
2051 bool want_breakpoint = true;
2052 bool want_hardware = false;
2053
2054 const GDBStoppointType stoppoint_type =
2055 GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2056 switch (stoppoint_type)
2057 {
2058 case eBreakpointSoftware:
2059 want_hardware = false; want_breakpoint = true; break;
2060 case eBreakpointHardware:
2061 want_hardware = true; want_breakpoint = true; break;
2062 case eWatchpointWrite:
2063 want_hardware = true; want_breakpoint = false; break;
2064 case eWatchpointRead:
2065 want_hardware = true; want_breakpoint = false; break;
2066 case eWatchpointReadWrite:
2067 want_hardware = true; want_breakpoint = false; break;
2068 case eStoppointInvalid:
2069 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
2070
2071 }
2072
2073 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2074 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after stoppoint type");
2075
2076 // Parse out the stoppoint address.
2077 if (packet.GetBytesLeft() < 1)
2078 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2079 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2080
2081 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2082 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
2083
2084 // Parse out the stoppoint size (i.e. size hint for opcode size).
2085 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2086 if (size == std::numeric_limits<uint32_t>::max ())
2087 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse size argument");
2088
2089 if (want_breakpoint)
2090 {
2091 // Try to set the breakpoint.
2092 const Error error = m_debugged_process_sp->SetBreakpoint (addr, size, want_hardware);
2093 if (error.Success ())
2094 return SendOKResponse ();
2095 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2096 if (log)
2097 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2098 " failed to set breakpoint: %s",
2099 __FUNCTION__,
2100 m_debugged_process_sp->GetID (),
2101 error.AsCString ());
2102 return SendErrorResponse (0x09);
2103 }
2104 else
2105 {
2106 uint32_t watch_flags =
2107 stoppoint_type == eWatchpointWrite
Chaoren Line0c6ab52015-02-17 15:41:23 +00002108 ? 0x1 // Write
2109 : 0x3; // ReadWrite
Tamas Berghammere13c2732015-02-11 10:29:30 +00002110
2111 // Try to set the watchpoint.
2112 const Error error = m_debugged_process_sp->SetWatchpoint (
2113 addr, size, watch_flags, want_hardware);
2114 if (error.Success ())
2115 return SendOKResponse ();
2116 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2117 if (log)
2118 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2119 " failed to set watchpoint: %s",
2120 __FUNCTION__,
2121 m_debugged_process_sp->GetID (),
2122 error.AsCString ());
2123 return SendErrorResponse (0x09);
2124 }
2125}
2126
2127GDBRemoteCommunication::PacketResult
2128GDBRemoteCommunicationServerLLGS::Handle_z (StringExtractorGDBRemote &packet)
2129{
2130 // Ensure we have a process.
2131 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2132 {
2133 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2134 if (log)
2135 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2136 return SendErrorResponse (0x15);
2137 }
2138
2139 // Parse out software or hardware breakpoint or watchpoint requested.
2140 packet.SetFilePos (strlen("z"));
2141 if (packet.GetBytesLeft() < 1)
2142 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
2143
2144 bool want_breakpoint = true;
2145
2146 const GDBStoppointType stoppoint_type =
2147 GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2148 switch (stoppoint_type)
2149 {
2150 case eBreakpointHardware: want_breakpoint = true; break;
2151 case eBreakpointSoftware: want_breakpoint = true; break;
2152 case eWatchpointWrite: want_breakpoint = false; break;
2153 case eWatchpointRead: want_breakpoint = false; break;
2154 case eWatchpointReadWrite: want_breakpoint = false; break;
2155 default:
2156 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
2157
2158 }
2159
2160 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2161 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after stoppoint type");
2162
2163 // Parse out the stoppoint address.
2164 if (packet.GetBytesLeft() < 1)
2165 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2166 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2167
2168 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2169 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
2170
2171 /*
2172 // Parse out the stoppoint size (i.e. size hint for opcode size).
2173 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2174 if (size == std::numeric_limits<uint32_t>::max ())
2175 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse size argument");
2176 */
2177
2178 if (want_breakpoint)
2179 {
2180 // Try to clear the breakpoint.
2181 const Error error = m_debugged_process_sp->RemoveBreakpoint (addr);
2182 if (error.Success ())
2183 return SendOKResponse ();
2184 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2185 if (log)
2186 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2187 " failed to remove breakpoint: %s",
2188 __FUNCTION__,
2189 m_debugged_process_sp->GetID (),
2190 error.AsCString ());
2191 return SendErrorResponse (0x09);
2192 }
2193 else
2194 {
2195 // Try to clear the watchpoint.
2196 const Error error = m_debugged_process_sp->RemoveWatchpoint (addr);
2197 if (error.Success ())
2198 return SendOKResponse ();
2199 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2200 if (log)
2201 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2202 " failed to remove watchpoint: %s",
2203 __FUNCTION__,
2204 m_debugged_process_sp->GetID (),
2205 error.AsCString ());
2206 return SendErrorResponse (0x09);
2207 }
2208}
2209
2210GDBRemoteCommunication::PacketResult
2211GDBRemoteCommunicationServerLLGS::Handle_s (StringExtractorGDBRemote &packet)
2212{
2213 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2214
2215 // Ensure we have a process.
2216 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2217 {
2218 if (log)
2219 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2220 return SendErrorResponse (0x32);
2221 }
2222
2223 // We first try to use a continue thread id. If any one or any all set, use the current thread.
2224 // Bail out if we don't have a thread id.
2225 lldb::tid_t tid = GetContinueThreadID ();
2226 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2227 tid = GetCurrentThreadID ();
2228 if (tid == LLDB_INVALID_THREAD_ID)
2229 return SendErrorResponse (0x33);
2230
2231 // Double check that we have such a thread.
2232 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2233 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
2234 if (!thread_sp || thread_sp->GetID () != tid)
2235 return SendErrorResponse (0x33);
2236
2237 // Create the step action for the given thread.
2238 lldb_private::ResumeAction action = { tid, eStateStepping, 0 };
2239
2240 // Setup the actions list.
2241 lldb_private::ResumeActionList actions;
2242 actions.Append (action);
2243
2244 // All other threads stop while we're single stepping a thread.
2245 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2246 Error error = m_debugged_process_sp->Resume (actions);
2247 if (error.Fail ())
2248 {
2249 if (log)
2250 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
2251 return SendErrorResponse(0x49);
2252 }
2253
2254 // No response here - the stop or exit will come from the resulting action.
2255 return PacketResult::Success;
2256}
2257
2258GDBRemoteCommunication::PacketResult
2259GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
2260{
2261 // *BSD impls should be able to do this too.
2262#if defined(__linux__)
2263 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2264
2265 // Parse out the offset.
2266 packet.SetFilePos (strlen("qXfer:auxv:read::"));
2267 if (packet.GetBytesLeft () < 1)
2268 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2269
2270 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2271 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
2272 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2273
2274 // Parse out comma.
2275 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
2276 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
2277
2278 // Parse out the length.
2279 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2280 if (auxv_length == std::numeric_limits<uint64_t>::max ())
2281 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
2282
2283 // Grab the auxv data if we need it.
2284 if (!m_active_auxv_buffer_sp)
2285 {
2286 // Make sure we have a valid process.
2287 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2288 {
2289 if (log)
2290 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2291 return SendErrorResponse (0x10);
2292 }
2293
2294 // Grab the auxv data.
2295 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
2296 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
2297 {
2298 // Hmm, no auxv data, call that an error.
2299 if (log)
2300 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no auxv data retrieved", __FUNCTION__);
2301 m_active_auxv_buffer_sp.reset ();
2302 return SendErrorResponse (0x11);
2303 }
2304 }
2305
2306 // FIXME find out if/how I lock the stream here.
2307
2308 StreamGDBRemote response;
2309 bool done_with_buffer = false;
2310
2311 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
2312 {
2313 // We have nothing left to send. Mark the buffer as complete.
2314 response.PutChar ('l');
2315 done_with_buffer = true;
2316 }
2317 else
2318 {
2319 // Figure out how many bytes are available starting at the given offset.
2320 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
2321
2322 // Figure out how many bytes we're going to read.
2323 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
2324
2325 // Mark the response type according to whether we're reading the remainder of the auxv data.
2326 if (bytes_to_read >= bytes_remaining)
2327 {
2328 // There will be nothing left to read after this
2329 response.PutChar ('l');
2330 done_with_buffer = true;
2331 }
2332 else
2333 {
2334 // There will still be bytes to read after this request.
2335 response.PutChar ('m');
2336 }
2337
2338 // Now write the data in encoded binary form.
2339 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
2340 }
2341
2342 if (done_with_buffer)
2343 m_active_auxv_buffer_sp.reset ();
2344
2345 return SendPacketNoLock(response.GetData(), response.GetSize());
2346#else
2347 return SendUnimplementedResponse ("not implemented on this platform");
2348#endif
2349}
2350
2351GDBRemoteCommunication::PacketResult
2352GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
2353{
2354 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2355
2356 // Move past packet name.
2357 packet.SetFilePos (strlen ("QSaveRegisterState"));
2358
2359 // Get the thread to use.
2360 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2361 if (!thread_sp)
2362 {
2363 if (m_thread_suffix_supported)
2364 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
2365 else
2366 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2367 }
2368
2369 // Grab the register context for the thread.
2370 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2371 if (!reg_context_sp)
2372 {
2373 if (log)
2374 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
2375 return SendErrorResponse (0x15);
2376 }
2377
2378 // Save registers to a buffer.
2379 DataBufferSP register_data_sp;
2380 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
2381 if (error.Fail ())
2382 {
2383 if (log)
2384 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2385 return SendErrorResponse (0x75);
2386 }
2387
2388 // Allocate a new save id.
2389 const uint32_t save_id = GetNextSavedRegistersID ();
2390 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
2391
2392 // Save the register data buffer under the save id.
2393 {
2394 Mutex::Locker locker (m_saved_registers_mutex);
2395 m_saved_registers_map[save_id] = register_data_sp;
2396 }
2397
2398 // Write the response.
2399 StreamGDBRemote response;
2400 response.Printf ("%" PRIu32, save_id);
2401 return SendPacketNoLock(response.GetData(), response.GetSize());
2402}
2403
2404GDBRemoteCommunication::PacketResult
2405GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
2406{
2407 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2408
2409 // Parse out save id.
2410 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
2411 if (packet.GetBytesLeft () < 1)
2412 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
2413
2414 const uint32_t save_id = packet.GetU32 (0);
2415 if (save_id == 0)
2416 {
2417 if (log)
2418 log->Printf ("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
2419 return SendErrorResponse (0x76);
2420 }
2421
2422 // Get the thread to use.
2423 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2424 if (!thread_sp)
2425 {
2426 if (m_thread_suffix_supported)
2427 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
2428 else
2429 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2430 }
2431
2432 // Grab the register context for the thread.
2433 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2434 if (!reg_context_sp)
2435 {
2436 if (log)
2437 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " failed, no register context available for the thread", __FUNCTION__, m_debugged_process_sp->GetID (), thread_sp->GetID ());
2438 return SendErrorResponse (0x15);
2439 }
2440
2441 // Retrieve register state buffer, then remove from the list.
2442 DataBufferSP register_data_sp;
2443 {
2444 Mutex::Locker locker (m_saved_registers_mutex);
2445
2446 // Find the register set buffer for the given save id.
2447 auto it = m_saved_registers_map.find (save_id);
2448 if (it == m_saved_registers_map.end ())
2449 {
2450 if (log)
2451 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " does not have a register set save buffer for id %" PRIu32, __FUNCTION__, m_debugged_process_sp->GetID (), save_id);
2452 return SendErrorResponse (0x77);
2453 }
2454 register_data_sp = it->second;
2455
2456 // Remove it from the map.
2457 m_saved_registers_map.erase (it);
2458 }
2459
2460 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
2461 if (error.Fail ())
2462 {
2463 if (log)
2464 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2465 return SendErrorResponse (0x77);
2466 }
2467
2468 return SendOKResponse();
2469}
2470
2471GDBRemoteCommunication::PacketResult
2472GDBRemoteCommunicationServerLLGS::Handle_vAttach (StringExtractorGDBRemote &packet)
2473{
2474 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2475
2476 // Consume the ';' after vAttach.
2477 packet.SetFilePos (strlen ("vAttach"));
2478 if (!packet.GetBytesLeft () || packet.GetChar () != ';')
2479 return SendIllFormedResponse (packet, "vAttach missing expected ';'");
2480
2481 // Grab the PID to which we will attach (assume hex encoding).
2482 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2483 if (pid == LLDB_INVALID_PROCESS_ID)
2484 return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
2485
2486 // Attempt to attach.
2487 if (log)
2488 log->Printf ("GDBRemoteCommunicationServerLLGS::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
2489
2490 Error error = AttachToProcess (pid);
2491
2492 if (error.Fail ())
2493 {
2494 if (log)
2495 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
2496 return SendErrorResponse (0x01);
2497 }
2498
2499 // Notify we attached by sending a stop packet.
2500 return SendStopReasonForState (m_debugged_process_sp->GetState (), true);
2501}
2502
2503GDBRemoteCommunication::PacketResult
2504GDBRemoteCommunicationServerLLGS::Handle_D (StringExtractorGDBRemote &packet)
2505{
2506 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2507
2508 // Scope for mutex locker.
2509 Mutex::Locker locker (m_spawned_pids_mutex);
2510
2511 // Fail if we don't have a current process.
2512 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2513 {
2514 if (log)
2515 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2516 return SendErrorResponse (0x15);
2517 }
2518
2519 if (m_spawned_pids.find(m_debugged_process_sp->GetID ()) == m_spawned_pids.end())
2520 {
2521 if (log)
2522 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to find PID %" PRIu64 " in spawned pids list",
2523 __FUNCTION__, m_debugged_process_sp->GetID ());
2524 return SendErrorResponse (0x1);
2525 }
2526
2527 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2528
2529 // Consume the ';' after D.
2530 packet.SetFilePos (1);
2531 if (packet.GetBytesLeft ())
2532 {
2533 if (packet.GetChar () != ';')
2534 return SendIllFormedResponse (packet, "D missing expected ';'");
2535
2536 // Grab the PID from which we will detach (assume hex encoding).
2537 pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2538 if (pid == LLDB_INVALID_PROCESS_ID)
2539 return SendIllFormedResponse (packet, "D failed to parse the process id");
2540 }
2541
2542 if (pid != LLDB_INVALID_PROCESS_ID &&
2543 m_debugged_process_sp->GetID () != pid)
2544 {
2545 return SendIllFormedResponse (packet, "Invalid pid");
2546 }
2547
2548 if (m_stdio_communication.IsConnected ())
2549 {
2550 m_stdio_communication.StopReadThread ();
2551 }
2552
2553 const Error error = m_debugged_process_sp->Detach ();
2554 if (error.Fail ())
2555 {
2556 if (log)
2557 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to detach from pid %" PRIu64 ": %s\n",
2558 __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2559 return SendErrorResponse (0x01);
2560 }
2561
2562 m_spawned_pids.erase (m_debugged_process_sp->GetID ());
2563 return SendOKResponse ();
2564}
2565
2566GDBRemoteCommunication::PacketResult
2567GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet)
2568{
2569 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2570
2571 packet.SetFilePos (strlen("qThreadStopInfo"));
2572 const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2573 if (tid == LLDB_INVALID_THREAD_ID)
2574 {
2575 if (log)
2576 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
2577 return SendErrorResponse (0x15);
2578 }
2579 return SendStopReplyPacketForThread (tid);
2580}
2581
2582GDBRemoteCommunication::PacketResult
2583GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo (StringExtractorGDBRemote &packet)
2584{
2585 // Fail if we don't have a current process.
2586 if (!m_debugged_process_sp ||
2587 m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2588 return SendErrorResponse (68);
2589
2590 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
2591 if (packet.GetBytesLeft() == 0)
2592 return SendOKResponse();
2593 if (packet.GetChar() != ':')
2594 return SendErrorResponse(67);
2595
2596 uint32_t num = m_debugged_process_sp->GetMaxWatchpoints();
2597 StreamGDBRemote response;
2598 response.Printf ("num:%d;", num);
2599 return SendPacketNoLock(response.GetData(), response.GetSize());
2600}
2601
2602void
2603GDBRemoteCommunicationServerLLGS::FlushInferiorOutput ()
2604{
2605 // If we're not monitoring an inferior's terminal, ignore this.
2606 if (!m_stdio_communication.IsConnected())
2607 return;
2608
2609 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2610 if (log)
2611 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() called", __FUNCTION__);
2612
2613 // FIXME implement a timeout on the join.
2614 m_stdio_communication.JoinReadThread();
2615}
2616
2617void
2618GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection ()
2619{
2620 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2621
2622 // Tell the stdio connection to shut down.
2623 if (m_stdio_communication.IsConnected())
2624 {
2625 auto connection = m_stdio_communication.GetConnection();
2626 if (connection)
2627 {
2628 Error error;
2629 connection->Disconnect (&error);
2630
2631 if (error.Success ())
2632 {
2633 if (log)
2634 log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
2635 }
2636 else
2637 {
2638 if (log)
2639 log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
2640 }
2641 }
2642 }
2643}
2644
2645
2646lldb_private::NativeThreadProtocolSP
2647GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
2648{
2649 NativeThreadProtocolSP thread_sp;
2650
2651 // We have no thread if we don't have a process.
2652 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2653 return thread_sp;
2654
2655 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
2656 // Use the current thread in that case.
2657 if (!m_thread_suffix_supported)
2658 {
2659 const lldb::tid_t current_tid = GetCurrentThreadID ();
2660 if (current_tid == LLDB_INVALID_THREAD_ID)
2661 return thread_sp;
2662 else if (current_tid == 0)
2663 {
2664 // Pick a thread.
2665 return m_debugged_process_sp->GetThreadAtIndex (0);
2666 }
2667 else
2668 return m_debugged_process_sp->GetThreadByID (current_tid);
2669 }
2670
2671 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2672
2673 // Parse out the ';'.
2674 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
2675 {
2676 if (log)
2677 log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2678 return thread_sp;
2679 }
2680
2681 if (!packet.GetBytesLeft ())
2682 return thread_sp;
2683
2684 // Parse out thread: portion.
2685 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
2686 {
2687 if (log)
2688 log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2689 return thread_sp;
2690 }
2691 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
2692 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
2693 if (tid != 0)
2694 return m_debugged_process_sp->GetThreadByID (tid);
2695
2696 return thread_sp;
2697}
2698
2699lldb::tid_t
2700GDBRemoteCommunicationServerLLGS::GetCurrentThreadID () const
2701{
2702 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
2703 {
2704 // Use whatever the debug process says is the current thread id
2705 // since the protocol either didn't specify or specified we want
2706 // any/all threads marked as the current thread.
2707 if (!m_debugged_process_sp)
2708 return LLDB_INVALID_THREAD_ID;
2709 return m_debugged_process_sp->GetCurrentThreadID ();
2710 }
2711 // Use the specific current thread id set by the gdb remote protocol.
2712 return m_current_tid;
2713}
2714
2715uint32_t
2716GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID ()
2717{
2718 Mutex::Locker locker (m_saved_registers_mutex);
2719 return m_next_saved_registers_id++;
2720}
2721
2722void
2723GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData ()
2724{
2725 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
2726 if (log)
2727 log->Printf ("GDBRemoteCommunicationServerLLGS::%s()", __FUNCTION__);
2728
2729 // Clear any auxv cached data.
2730 // *BSD impls should be able to do this too.
2731#if defined(__linux__)
2732 if (log)
2733 log->Printf ("GDBRemoteCommunicationServerLLGS::%s clearing auxv buffer (previously %s)",
2734 __FUNCTION__,
2735 m_active_auxv_buffer_sp ? "was set" : "was not set");
2736 m_active_auxv_buffer_sp.reset ();
2737#endif
2738}