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