blob: b0d931ba196ce273b4d683bc6d950f894775aa0e [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/Log.h"
Tamas Berghammer9c9ecce2015-05-27 13:34:04 +000028#include "lldb/Core/RegisterValue.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000029#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"
Tamas Berghammere13c2732015-02-11 10:29:30 +000043#include "lldb/Host/common/NativeRegisterContext.h"
44#include "lldb/Host/common/NativeProcessProtocol.h"
45#include "lldb/Host/common/NativeThreadProtocol.h"
Pavel Labath4a4bb122015-07-16 14:14:35 +000046#include "lldb/Utility/JSON.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000047
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;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000056using namespace lldb_private::process_gdb_remote;
Tamas Berghammer783bfc82015-06-18 20:43:56 +000057using namespace llvm;
Tamas Berghammere13c2732015-02-11 10:29:30 +000058
59//----------------------------------------------------------------------
60// GDBRemote Errors
61//----------------------------------------------------------------------
62
63namespace
64{
65 enum GDBRemoteServerError
66 {
67 // Set to the first unused error number in literal form below
68 eErrorFirst = 29,
69 eErrorNoProcess = eErrorFirst,
70 eErrorResume,
71 eErrorExitStatus
72 };
73}
74
75//----------------------------------------------------------------------
76// GDBRemoteCommunicationServerLLGS constructor
77//----------------------------------------------------------------------
78GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
Pavel Labath77dc9562015-07-13 10:44:55 +000079 const lldb::PlatformSP& platform_sp,
80 MainLoop &mainloop) :
Tamas Berghammere13c2732015-02-11 10:29:30 +000081 GDBRemoteCommunicationServerCommon ("gdb-remote.server", "gdb-remote.server.rx_packet"),
82 m_platform_sp (platform_sp),
Pavel Labath77dc9562015-07-13 10:44:55 +000083 m_mainloop (mainloop),
Tamas Berghammere13c2732015-02-11 10:29:30 +000084 m_current_tid (LLDB_INVALID_THREAD_ID),
85 m_continue_tid (LLDB_INVALID_THREAD_ID),
86 m_debugged_process_mutex (Mutex::eMutexTypeRecursive),
87 m_debugged_process_sp (),
Tamas Berghammere13c2732015-02-11 10:29:30 +000088 m_stdio_communication ("process.stdio"),
89 m_inferior_prev_state (StateType::eStateInvalid),
90 m_active_auxv_buffer_sp (),
91 m_saved_registers_mutex (),
92 m_saved_registers_map (),
Pavel Labath77dc9562015-07-13 10:44:55 +000093 m_next_saved_registers_id (1),
94 m_handshake_completed (false)
Tamas Berghammere13c2732015-02-11 10:29:30 +000095{
96 assert(platform_sp);
Tamas Berghammere13c2732015-02-11 10:29:30 +000097 RegisterPacketHandlers();
98}
99
Tamas Berghammere13c2732015-02-11 10:29:30 +0000100void
101GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers()
102{
Tamas Berghammere13c2732015-02-11 10:29:30 +0000103 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
104 &GDBRemoteCommunicationServerLLGS::Handle_C);
105 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
106 &GDBRemoteCommunicationServerLLGS::Handle_c);
107 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
108 &GDBRemoteCommunicationServerLLGS::Handle_D);
109 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
110 &GDBRemoteCommunicationServerLLGS::Handle_H);
111 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
112 &GDBRemoteCommunicationServerLLGS::Handle_I);
113 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_interrupt,
114 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
115 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_m,
Pavel Labath3bf11252015-10-14 12:59:37 +0000116 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000117 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
118 &GDBRemoteCommunicationServerLLGS::Handle_M);
119 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
120 &GDBRemoteCommunicationServerLLGS::Handle_p);
121 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
122 &GDBRemoteCommunicationServerLLGS::Handle_P);
123 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
124 &GDBRemoteCommunicationServerLLGS::Handle_qC);
125 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
126 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
Tamas Berghammer783bfc82015-06-18 20:43:56 +0000127 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
128 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000129 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
130 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
131 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
132 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
133 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
134 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
135 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
136 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
137 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
138 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
139 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
140 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
141 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
142 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
143 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
144 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
145 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
146 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
147 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
148 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
149 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
150 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
Pavel Labath4a4bb122015-07-16 14:14:35 +0000151 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
152 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000153 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
154 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
155 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
156 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
157 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
158 &GDBRemoteCommunicationServerLLGS::Handle_s);
159 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_stop_reason,
160 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
161 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vAttach,
162 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
163 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont,
164 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
165 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_vCont_actions,
166 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
Pavel Labath3bf11252015-10-14 12:59:37 +0000167 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_x,
168 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000169 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
170 &GDBRemoteCommunicationServerLLGS::Handle_Z);
171 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
172 &GDBRemoteCommunicationServerLLGS::Handle_z);
173
174 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
175 [this](StringExtractorGDBRemote packet,
176 Error &error,
177 bool &interrupt,
178 bool &quit)
179 {
180 quit = true;
181 return this->Handle_k (packet);
182 });
183}
184
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000185Error
Tamas Berghammere13c2732015-02-11 10:29:30 +0000186GDBRemoteCommunicationServerLLGS::SetLaunchArguments (const char *const args[], int argc)
187{
188 if ((argc < 1) || !args || !args[0] || !args[0][0])
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000189 return Error ("%s: no process command line specified to launch", __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000190
191 m_process_launch_info.SetArguments (const_cast<const char**> (args), true);
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000192 return Error ();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000193}
194
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000195Error
Tamas Berghammere13c2732015-02-11 10:29:30 +0000196GDBRemoteCommunicationServerLLGS::SetLaunchFlags (unsigned int launch_flags)
197{
198 m_process_launch_info.GetFlags ().Set (launch_flags);
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000199 return Error ();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000200}
201
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000202Error
Tamas Berghammere13c2732015-02-11 10:29:30 +0000203GDBRemoteCommunicationServerLLGS::LaunchProcess ()
204{
205 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
206
207 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000208 return Error ("%s: no process command line specified to launch", __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000209
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000210 Error error;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000211 {
212 Mutex::Locker locker (m_debugged_process_mutex);
213 assert (!m_debugged_process_sp && "lldb-gdbserver creating debugged process but one already exists");
Pavel Labathd5b310f2015-07-09 11:51:11 +0000214 error = NativeProcessProtocol::Launch(
Tamas Berghammere13c2732015-02-11 10:29:30 +0000215 m_process_launch_info,
216 *this,
Pavel Labath19cbe962015-07-21 13:20:32 +0000217 m_mainloop,
Tamas Berghammere13c2732015-02-11 10:29:30 +0000218 m_debugged_process_sp);
219 }
220
221 if (!error.Success ())
222 {
223 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
224 return error;
225 }
226
Vince Harron4a8abd32015-02-13 19:15:24 +0000227 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
228 // as needed.
229 // llgs local-process debugging may specify PTY paths, which will make these
230 // file actions non-null
231 // process launch -i/e/o will also make these file actions non-null
232 // nullptr means that the traffic is expected to flow over gdb-remote protocol
233 if (
234 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
235 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
236 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr
237 )
Tamas Berghammere13c2732015-02-11 10:29:30 +0000238 {
Vince Harron4a8abd32015-02-13 19:15:24 +0000239 // nullptr means it's not redirected to file or pty (in case of LLGS local)
240 // at least one of stdio will be transferred pty<->gdb-remote
241 // we need to give the pty master handle to this object to read and/or write
Tamas Berghammere13c2732015-02-11 10:29:30 +0000242 if (log)
243 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " setting up stdout/stderr redirection via $O gdb-remote commands", __FUNCTION__, m_debugged_process_sp->GetID ());
244
245 // Setup stdout/stderr mapping from inferior to $O
246 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
247 if (terminal_fd >= 0)
248 {
249 if (log)
250 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
251 error = SetSTDIOFileDescriptor (terminal_fd);
252 if (error.Fail ())
253 return error;
254 }
255 else
256 {
257 if (log)
258 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
259 }
260 }
261 else
262 {
263 if (log)
264 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 ());
265 }
266
267 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID ());
268
Tamas Berghammere13c2732015-02-11 10:29:30 +0000269 return error;
270}
271
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000272Error
Tamas Berghammere13c2732015-02-11 10:29:30 +0000273GDBRemoteCommunicationServerLLGS::AttachToProcess (lldb::pid_t pid)
274{
275 Error error;
276
277 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
278 if (log)
279 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64, __FUNCTION__, pid);
280
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000281 // Before we try to attach, make sure we aren't already monitoring something else.
282 if (m_debugged_process_sp && m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID)
283 return Error("cannot attach to a process %" PRIu64 " when another process with pid %" PRIu64 " is being debugged.", pid, m_debugged_process_sp->GetID());
284
285 // Try to attach.
286 error = NativeProcessProtocol::Attach(pid, *this, m_mainloop, m_debugged_process_sp);
287 if (!error.Success ())
Tamas Berghammere13c2732015-02-11 10:29:30 +0000288 {
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000289 fprintf (stderr, "%s: failed to attach to process %" PRIu64 ": %s", __FUNCTION__, pid, error.AsCString ());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000290 return error;
291 }
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000292
293 // Setup stdout/stderr mapping from inferior.
294 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor ();
295 if (terminal_fd >= 0)
296 {
297 if (log)
298 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s setting inferior STDIO fd to %d", __FUNCTION__, terminal_fd);
299 error = SetSTDIOFileDescriptor (terminal_fd);
300 if (error.Fail ())
301 return error;
302 }
303 else
304 {
305 if (log)
306 log->Printf ("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring inferior STDIO since terminal fd reported as %d", __FUNCTION__, terminal_fd);
307 }
308
309 printf ("Attached to process %" PRIu64 "...\n", pid);
310
311 return error;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000312}
313
314void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000315GDBRemoteCommunicationServerLLGS::InitializeDelegate (NativeProcessProtocol *process)
Tamas Berghammere13c2732015-02-11 10:29:30 +0000316{
317 assert (process && "process cannot be NULL");
318 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
319 if (log)
320 {
321 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called with NativeProcessProtocol pid %" PRIu64 ", current state: %s",
322 __FUNCTION__,
323 process->GetID (),
324 StateAsCString (process->GetState ()));
325 }
326}
327
328GDBRemoteCommunication::PacketResult
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000329GDBRemoteCommunicationServerLLGS::SendWResponse (NativeProcessProtocol *process)
Tamas Berghammere13c2732015-02-11 10:29:30 +0000330{
331 assert (process && "process cannot be NULL");
332 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
333
334 // send W notification
335 ExitType exit_type = ExitType::eExitTypeInvalid;
336 int return_code = 0;
337 std::string exit_description;
338
339 const bool got_exit_info = process->GetExitStatus (&exit_type, &return_code, exit_description);
340 if (!got_exit_info)
341 {
342 if (log)
343 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", failed to retrieve process exit status", __FUNCTION__, process->GetID ());
344
345 StreamGDBRemote response;
346 response.PutChar ('E');
347 response.PutHex8 (GDBRemoteServerError::eErrorExitStatus);
348 return SendPacketNoLock(response.GetData(), response.GetSize());
349 }
350 else
351 {
352 if (log)
353 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 ());
354
355 StreamGDBRemote response;
356
357 char return_type_code;
358 switch (exit_type)
359 {
360 case ExitType::eExitTypeExit:
361 return_type_code = 'W';
362 break;
363 case ExitType::eExitTypeSignal:
364 return_type_code = 'X';
365 break;
366 case ExitType::eExitTypeStop:
367 return_type_code = 'S';
368 break;
369 case ExitType::eExitTypeInvalid:
370 return_type_code = 'E';
371 break;
372 }
373 response.PutChar (return_type_code);
374
375 // POSIX exit status limited to unsigned 8 bits.
376 response.PutHex8 (return_code);
377
378 return SendPacketNoLock(response.GetData(), response.GetSize());
379 }
380}
381
382static void
383AppendHexValue (StreamString &response, const uint8_t* buf, uint32_t buf_size, bool swap)
384{
385 int64_t i;
386 if (swap)
387 {
388 for (i = buf_size-1; i >= 0; i--)
389 response.PutHex8 (buf[i]);
390 }
391 else
392 {
393 for (i = 0; i < buf_size; i++)
394 response.PutHex8 (buf[i]);
395 }
396}
397
398static void
399WriteRegisterValueInHexFixedWidth (StreamString &response,
400 NativeRegisterContextSP &reg_ctx_sp,
401 const RegisterInfo &reg_info,
402 const RegisterValue *reg_value_p)
403{
404 RegisterValue reg_value;
405 if (!reg_value_p)
406 {
407 Error error = reg_ctx_sp->ReadRegister (&reg_info, reg_value);
408 if (error.Success ())
409 reg_value_p = &reg_value;
410 // else log.
411 }
412
413 if (reg_value_p)
414 {
415 AppendHexValue (response, (const uint8_t*) reg_value_p->GetBytes (), reg_value_p->GetByteSize (), false);
416 }
417 else
418 {
419 // Zero-out any unreadable values.
420 if (reg_info.byte_size > 0)
421 {
422 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
423 AppendHexValue (response, zeros.data(), zeros.size(), false);
424 }
425 }
426}
427
Pavel Labath4a4bb122015-07-16 14:14:35 +0000428static JSONObject::SP
429GetRegistersAsJSON(NativeThreadProtocol &thread)
430{
431 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
432
433 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext ();
434 if (! reg_ctx_sp)
435 return nullptr;
436
437 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000438
439#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
Pavel Labath4a4bb122015-07-16 14:14:35 +0000440 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
441 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
442 if (! reg_set_p)
443 return nullptr;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000444 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
445 {
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000446 uint32_t reg_num = *reg_num_p;
447#else
448 // Expedite only a couple of registers until we figure out why sending registers is
449 // expensive.
450 static const uint32_t k_expedited_registers[] = {
451 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP, LLDB_REGNUM_GENERIC_RA
452 };
453 for (uint32_t generic_reg: k_expedited_registers)
454 {
455 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric, generic_reg);
456 if (reg_num == LLDB_INVALID_REGNUM)
457 continue; // Target does not support the given register.
458#endif
459
460 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
Pavel Labath4a4bb122015-07-16 14:14:35 +0000461 if (reg_info_p == nullptr)
462 {
463 if (log)
464 log->Printf("%s failed to get register info for register index %" PRIu32,
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000465 __FUNCTION__, reg_num);
Pavel Labath4a4bb122015-07-16 14:14:35 +0000466 continue;
467 }
468
469 if (reg_info_p->value_regs != nullptr)
470 continue; // Only expedite registers that are not contained in other registers.
471
472 RegisterValue reg_value;
473 Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
474 if (error.Fail())
475 {
476 if (log)
477 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s", __FUNCTION__,
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000478 reg_info_p->name ? reg_info_p->name : "<unnamed-register>", reg_num,
Pavel Labath4a4bb122015-07-16 14:14:35 +0000479 error.AsCString ());
480 continue;
481 }
482
483 StreamString stream;
484 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p, &reg_value);
485
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000486 register_object_sp->SetObject(std::to_string(reg_num),
Pavel Labath4a4bb122015-07-16 14:14:35 +0000487 std::make_shared<JSONString>(stream.GetString()));
488 }
489
490 return register_object_sp;
491}
492
493static const char *
494GetStopReasonString(StopReason stop_reason)
495{
496 switch (stop_reason)
497 {
498 case eStopReasonTrace:
499 return "trace";
500 case eStopReasonBreakpoint:
501 return "breakpoint";
502 case eStopReasonWatchpoint:
503 return "watchpoint";
504 case eStopReasonSignal:
505 return "signal";
506 case eStopReasonException:
507 return "exception";
508 case eStopReasonExec:
509 return "exec";
510 case eStopReasonInstrumentation:
511 case eStopReasonInvalid:
512 case eStopReasonPlanComplete:
513 case eStopReasonThreadExiting:
514 case eStopReasonNone:
515 break; // ignored
516 }
517 return nullptr;
518}
519
Pavel Labath05569f62015-07-23 09:09:29 +0000520static JSONArray::SP
521GetJSONThreadsInfo(NativeProcessProtocol &process, bool threads_with_valid_stop_info_only)
522{
523 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
524
525 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
526
527 // Ensure we can get info on the given thread.
528 uint32_t thread_idx = 0;
529 for ( NativeThreadProtocolSP thread_sp;
530 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
531 ++thread_idx)
532 {
533
534 lldb::tid_t tid = thread_sp->GetID();
535
536 // Grab the reason this thread stopped.
537 struct ThreadStopInfo tid_stop_info;
538 std::string description;
539 if (!thread_sp->GetStopReason (tid_stop_info, description))
540 return nullptr;
541
542 const int signum = tid_stop_info.details.signal.signo;
543 if (log)
544 {
545 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
546 __FUNCTION__,
547 process.GetID (),
548 tid,
549 signum,
550 tid_stop_info.reason,
551 tid_stop_info.details.exception.type);
552 }
553
554 if (threads_with_valid_stop_info_only && tid_stop_info.reason == eStopReasonNone)
555 continue; // No stop reason, skip this thread completely.
556
557 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
558 threads_array_sp->AppendObject(thread_obj_sp);
559
560 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
561 if (signum != 0)
562 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(uint64_t(signum)));
563
564 const std::string thread_name = thread_sp->GetName ();
565 if (! thread_name.empty())
566 thread_obj_sp->SetObject("name", std::make_shared<JSONString>(thread_name));
567
568 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
569 thread_obj_sp->SetObject("reason", std::make_shared<JSONString>(stop_reason_str));
570
571 if (! description.empty())
572 thread_obj_sp->SetObject("description", std::make_shared<JSONString>(description));
573
574 if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
575 {
576 thread_obj_sp->SetObject("metype",
577 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
578
579 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
580 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
581 {
582 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
583 tid_stop_info.details.exception.data[i]));
584 }
585 thread_obj_sp->SetObject("medata", medata_array_sp);
586 }
587
588 if (threads_with_valid_stop_info_only)
589 continue; // Only send the abridged stop info.
590
591 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp))
592 thread_obj_sp->SetObject("registers", registers_sp);
593
594 // TODO: Expedite interesting regions of inferior memory
595 }
596
597 return threads_array_sp;
598}
599
Tamas Berghammere13c2732015-02-11 10:29:30 +0000600GDBRemoteCommunication::PacketResult
601GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread (lldb::tid_t tid)
602{
603 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
604
605 // Ensure we have a debugged process.
606 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
607 return SendErrorResponse (50);
608
609 if (log)
610 log->Printf ("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64 " tid %" PRIu64,
611 __FUNCTION__, m_debugged_process_sp->GetID (), tid);
612
613 // Ensure we can get info on the given thread.
614 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
615 if (!thread_sp)
616 return SendErrorResponse (51);
617
618 // Grab the reason this thread stopped.
619 struct ThreadStopInfo tid_stop_info;
620 std::string description;
621 if (!thread_sp->GetStopReason (tid_stop_info, description))
622 return SendErrorResponse (52);
623
624 // FIXME implement register handling for exec'd inferiors.
625 // if (tid_stop_info.reason == eStopReasonExec)
626 // {
627 // const bool force = true;
628 // InitializeRegisters(force);
629 // }
630
631 StreamString response;
632 // Output the T packet with the thread
633 response.PutChar ('T');
634 int signum = tid_stop_info.details.signal.signo;
635 if (log)
636 {
637 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
638 __FUNCTION__,
639 m_debugged_process_sp->GetID (),
640 tid,
641 signum,
642 tid_stop_info.reason,
643 tid_stop_info.details.exception.type);
644 }
645
646 // Print the signal number.
647 response.PutHex8 (signum & 0xff);
648
649 // Include the tid.
650 response.Printf ("thread:%" PRIx64 ";", tid);
651
652 // Include the thread name if there is one.
653 const std::string thread_name = thread_sp->GetName ();
654 if (!thread_name.empty ())
655 {
656 size_t thread_name_len = thread_name.length ();
657
658 if (::strcspn (thread_name.c_str (), "$#+-;:") == thread_name_len)
659 {
660 response.PutCString ("name:");
661 response.PutCString (thread_name.c_str ());
662 }
663 else
664 {
665 // The thread name contains special chars, send as hex bytes.
666 response.PutCString ("hexname:");
667 response.PutCStringAsRawHex8 (thread_name.c_str ());
668 }
669 response.PutChar (';');
670 }
671
672 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
673 // will send all thread IDs back in the "threads" key whose value is
674 // a list of hex thread IDs separated by commas:
675 // "threads:10a,10b,10c;"
676 // This will save the debugger from having to send a pair of qfThreadInfo
677 // and qsThreadInfo packets, but it also might take a lot of room in the
678 // stop reply packet, so it must be enabled only on systems where there
679 // are no limits on packet lengths.
680 if (m_list_threads_in_stop_reply)
681 {
682 response.PutCString ("threads:");
683
684 uint32_t thread_index = 0;
685 NativeThreadProtocolSP listed_thread_sp;
686 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))
687 {
688 if (thread_index > 0)
689 response.PutChar (',');
690 response.Printf ("%" PRIx64, listed_thread_sp->GetID ());
691 }
692 response.PutChar (';');
Pavel Labath05569f62015-07-23 09:09:29 +0000693
694 // Include JSON info that describes the stop reason for any threads
695 // that actually have stop reasons. We use the new "jstopinfo" key
696 // whose values is hex ascii JSON that contains the thread IDs
697 // thread stop info only for threads that have stop reasons. Only send
698 // this if we have more than one thread otherwise this packet has all
699 // the info it needs.
700 if (thread_index > 0)
701 {
702 const bool threads_with_valid_stop_info_only = true;
703 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(*m_debugged_process_sp,
704 threads_with_valid_stop_info_only);
705 if (threads_info_sp)
706 {
707 response.PutCString("jstopinfo:");
708 StreamString unescaped_response;
709 threads_info_sp->Write(unescaped_response);
710 response.PutCStringAsRawHex8(unescaped_response.GetData());
711 response.PutChar(';');
712 }
713 else if (log)
714 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to prepare a jstopinfo field for pid %" PRIu64,
715 __FUNCTION__, m_debugged_process_sp->GetID());
716
717 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000718 }
719
720 //
721 // Expedite registers.
722 //
723
724 // Grab the register context.
725 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext ();
726 if (reg_ctx_sp)
727 {
728 // Expedite all registers in the first register set (i.e. should be GPRs) that are not contained in other registers.
729 const RegisterSet *reg_set_p;
730 if (reg_ctx_sp->GetRegisterSetCount () > 0 && ((reg_set_p = reg_ctx_sp->GetRegisterSet (0)) != nullptr))
731 {
732 if (log)
733 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);
734
735 for (const uint32_t *reg_num_p = reg_set_p->registers; *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p)
736 {
737 const RegisterInfo *const reg_info_p = reg_ctx_sp->GetRegisterInfoAtIndex (*reg_num_p);
738 if (reg_info_p == nullptr)
739 {
740 if (log)
741 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);
742 }
743 else if (reg_info_p->value_regs == nullptr)
744 {
745 // Only expediate registers that are not contained in other registers.
746 RegisterValue reg_value;
747 Error error = reg_ctx_sp->ReadRegister (reg_info_p, reg_value);
748 if (error.Success ())
Chaoren Lincaf31142015-02-17 15:41:28 +0000749 {
750 response.Printf ("%.02x:", *reg_num_p);
751 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p, &reg_value);
752 response.PutChar (';');
753 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000754 else
755 {
756 if (log)
757 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 ());
758
759 }
760 }
761 }
762 }
763 }
764
Pavel Labath4a4bb122015-07-16 14:14:35 +0000765 const char* reason_str = GetStopReasonString(tid_stop_info.reason);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000766 if (reason_str != nullptr)
767 {
768 response.Printf ("reason:%s;", reason_str);
769 }
770
771 if (!description.empty())
772 {
773 // Description may contains special chars, send as hex bytes.
774 response.PutCString ("description:");
775 response.PutCStringAsRawHex8 (description.c_str ());
776 response.PutChar (';');
777 }
778 else if ((tid_stop_info.reason == eStopReasonException) && tid_stop_info.details.exception.type)
779 {
780 response.PutCString ("metype:");
781 response.PutHex64 (tid_stop_info.details.exception.type);
782 response.PutCString (";mecount:");
783 response.PutHex32 (tid_stop_info.details.exception.data_count);
784 response.PutChar (';');
785
786 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i)
787 {
788 response.PutCString ("medata:");
789 response.PutHex64 (tid_stop_info.details.exception.data[i]);
790 response.PutChar (';');
791 }
792 }
793
794 return SendPacketNoLock (response.GetData(), response.GetSize());
795}
796
797void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000798GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited (NativeProcessProtocol *process)
Tamas Berghammere13c2732015-02-11 10:29:30 +0000799{
800 assert (process && "process cannot be NULL");
801
802 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
803 if (log)
804 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
805
Pavel Labathc7749c32015-07-21 13:20:25 +0000806 PacketResult result = SendStopReasonForState(StateType::eStateExited);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000807 if (result != PacketResult::Success)
808 {
809 if (log)
810 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
811 }
812
Tamas Berghammere13c2732015-02-11 10:29:30 +0000813 // Close the pipe to the inferior terminal i/o if we launched it
Pavel Labathc7749c32015-07-21 13:20:25 +0000814 // and set one up.
Tamas Berghammere13c2732015-02-11 10:29:30 +0000815 MaybeCloseInferiorTerminalConnection ();
816
817 // We are ready to exit the debug monitor.
818 m_exit_now = true;
819}
820
821void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000822GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped (NativeProcessProtocol *process)
Tamas Berghammere13c2732015-02-11 10:29:30 +0000823{
824 assert (process && "process cannot be NULL");
825
826 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
827 if (log)
828 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
829
830 // Send the stop reason unless this is the stop after the
831 // launch or attach.
832 switch (m_inferior_prev_state)
833 {
834 case eStateLaunching:
835 case eStateAttaching:
836 // Don't send anything per debugserver behavior.
837 break;
838 default:
839 // In all other cases, send the stop reason.
Pavel Labathc7749c32015-07-21 13:20:25 +0000840 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000841 if (result != PacketResult::Success)
842 {
843 if (log)
844 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send stop notification for PID %" PRIu64 ", state: eStateExited", __FUNCTION__, process->GetID ());
845 }
846 break;
847 }
848}
849
850void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000851GDBRemoteCommunicationServerLLGS::ProcessStateChanged (NativeProcessProtocol *process, lldb::StateType state)
Tamas Berghammere13c2732015-02-11 10:29:30 +0000852{
853 assert (process && "process cannot be NULL");
854 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
855 if (log)
856 {
857 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called with NativeProcessProtocol pid %" PRIu64 ", state: %s",
858 __FUNCTION__,
859 process->GetID (),
860 StateAsCString (state));
861 }
862
Vince Harron43d79052015-04-15 10:40:51 +0000863 // Make sure we get all of the pending stdout/stderr from the inferior
864 // and send it to the lldb host before we send the state change
865 // notification
Pavel Labathc7749c32015-07-21 13:20:25 +0000866 SendProcessOutput();
Vince Harron43d79052015-04-15 10:40:51 +0000867
Tamas Berghammere13c2732015-02-11 10:29:30 +0000868 switch (state)
869 {
870 case StateType::eStateExited:
871 HandleInferiorState_Exited (process);
872 break;
873
874 case StateType::eStateStopped:
875 HandleInferiorState_Stopped (process);
876 break;
877
878 default:
879 if (log)
880 {
881 log->Printf ("GDBRemoteCommunicationServerLLGS::%s didn't handle state change for pid %" PRIu64 ", new state: %s",
882 __FUNCTION__,
883 process->GetID (),
884 StateAsCString (state));
885 }
886 break;
887 }
888
889 // Remember the previous state reported to us.
890 m_inferior_prev_state = state;
891}
892
893void
894GDBRemoteCommunicationServerLLGS::DidExec (NativeProcessProtocol *process)
895{
896 ClearProcessSpecificData ();
897}
898
Pavel Labath77dc9562015-07-13 10:44:55 +0000899void
900GDBRemoteCommunicationServerLLGS::DataAvailableCallback ()
901{
902 Log *log (GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
903
904 if (! m_handshake_completed)
905 {
906 if (! HandshakeWithClient())
907 {
908 if(log)
909 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with client failed, exiting",
910 __FUNCTION__);
Pavel Labath77dc9562015-07-13 10:44:55 +0000911 m_mainloop.RequestTermination();
912 return;
913 }
914 m_handshake_completed = true;
915 }
916
917 bool interrupt = false;
918 bool done = false;
919 Error error;
920 while (true)
921 {
922 const PacketResult result = GetPacketAndSendResponse (0, error, interrupt, done);
923 if (result == PacketResult::ErrorReplyTimeout)
924 break; // No more packets in the queue
925
926 if ((result != PacketResult::Success))
927 {
928 if(log)
929 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet failed: %s",
930 __FUNCTION__, error.AsCString());
Pavel Labath77dc9562015-07-13 10:44:55 +0000931 m_mainloop.RequestTermination();
932 break;
933 }
934 }
935}
936
937Error
938GDBRemoteCommunicationServerLLGS::InitializeConnection (std::unique_ptr<Connection> &&connection)
939{
940 IOObjectSP read_object_sp = connection->GetReadObject();
941 GDBRemoteCommunicationServer::SetConnection(connection.release());
942
943 Error error;
Pavel Labathc7749c32015-07-21 13:20:25 +0000944 m_network_handle_up = m_mainloop.RegisterReadObject(read_object_sp,
Pavel Labath77dc9562015-07-13 10:44:55 +0000945 [this] (MainLoopBase &) { DataAvailableCallback(); }, error);
946 return error;
947}
948
Tamas Berghammere13c2732015-02-11 10:29:30 +0000949GDBRemoteCommunication::PacketResult
950GDBRemoteCommunicationServerLLGS::SendONotification (const char *buffer, uint32_t len)
951{
952 if ((buffer == nullptr) || (len == 0))
953 {
954 // Nothing to send.
955 return PacketResult::Success;
956 }
957
958 StreamString response;
959 response.PutChar ('O');
960 response.PutBytesAsRawHex8 (buffer, len);
961
962 return SendPacketNoLock (response.GetData (), response.GetSize ());
963}
964
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000965Error
Tamas Berghammere13c2732015-02-11 10:29:30 +0000966GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor (int fd)
967{
968 Error error;
969
Pavel Labathc7749c32015-07-21 13:20:25 +0000970 // Set up the reading/handling of process I/O
Tamas Berghammere13c2732015-02-11 10:29:30 +0000971 std::unique_ptr<ConnectionFileDescriptor> conn_up (new ConnectionFileDescriptor (fd, true));
972 if (!conn_up)
973 {
974 error.SetErrorString ("failed to create ConnectionFileDescriptor");
975 return error;
976 }
977
Pavel Labathc7749c32015-07-21 13:20:25 +0000978 Mutex::Locker locker(m_stdio_communication_mutex);
Tamas Berghammer00bdca62015-03-19 14:58:36 +0000979 m_stdio_communication.SetCloseOnEOF (false);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000980 m_stdio_communication.SetConnection (conn_up.release());
981 if (!m_stdio_communication.IsConnected ())
982 {
983 error.SetErrorString ("failed to set connection for inferior I/O communication");
984 return error;
985 }
986
Vince Harron4a8abd32015-02-13 19:15:24 +0000987 // llgs local-process debugging may specify PTY paths, which will make these
988 // file actions non-null
989 // process launch -e/o will also make these file actions non-null
990 // nullptr means that the traffic is expected to flow over gdb-remote protocol
991 if (
992 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
993 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr
994 )
995 {
996 // output from the process must be forwarded over gdb-remote
Pavel Labathc7749c32015-07-21 13:20:25 +0000997 m_stdio_handle_up = m_mainloop.RegisterReadObject(
998 m_stdio_communication.GetConnection()->GetReadObject(),
999 [this] (MainLoopBase &) { SendProcessOutput(); }, error);
1000 if (! m_stdio_handle_up)
1001 {
1002 m_stdio_communication.Disconnect();
1003 return error;
1004 }
Vince Harron4a8abd32015-02-13 19:15:24 +00001005 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001006
Pavel Labathc7749c32015-07-21 13:20:25 +00001007 return Error();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001008}
1009
1010void
Pavel Labathc7749c32015-07-21 13:20:25 +00001011GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding()
Tamas Berghammere13c2732015-02-11 10:29:30 +00001012{
Pavel Labathc7749c32015-07-21 13:20:25 +00001013 Mutex::Locker locker(m_stdio_communication_mutex);
1014 m_stdio_handle_up.reset();
1015}
1016
1017void
1018GDBRemoteCommunicationServerLLGS::SendProcessOutput()
1019{
1020 char buffer[1024];
1021 ConnectionStatus status;
1022 Error error;
1023 Mutex::Locker locker(m_stdio_communication_mutex);
1024 while (true)
1025 {
1026 size_t bytes_read = m_stdio_communication.Read(buffer, sizeof buffer, 0, status, &error);
1027 switch (status)
1028 {
1029 case eConnectionStatusSuccess:
1030 SendONotification(buffer, bytes_read);
1031 break;
1032 case eConnectionStatusLostConnection:
1033 case eConnectionStatusEndOfFile:
1034 case eConnectionStatusError:
1035 case eConnectionStatusNoConnection:
1036 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1037 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio forwarding as communication returned status %d (error: %s)", __FUNCTION__, status, error.AsCString());
1038 m_stdio_handle_up.reset();
1039 return;
1040
1041 case eConnectionStatusInterrupted:
1042 case eConnectionStatusTimedOut:
1043 return;
1044 }
1045 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001046}
1047
1048GDBRemoteCommunication::PacketResult
1049GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
1050{
1051 // Fail if we don't have a current process.
1052 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1053 return SendErrorResponse (68);
1054
1055 lldb::pid_t pid = m_debugged_process_sp->GetID ();
1056
1057 if (pid == LLDB_INVALID_PROCESS_ID)
1058 return SendErrorResponse (1);
1059
1060 ProcessInstanceInfo proc_info;
1061 if (!Host::GetProcessInfo (pid, proc_info))
1062 return SendErrorResponse (1);
1063
1064 StreamString response;
1065 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1066 return SendPacketNoLock (response.GetData (), response.GetSize ());
1067}
1068
1069GDBRemoteCommunication::PacketResult
1070GDBRemoteCommunicationServerLLGS::Handle_qC (StringExtractorGDBRemote &packet)
1071{
1072 // Fail if we don't have a current process.
1073 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1074 return SendErrorResponse (68);
1075
1076 // Make sure we set the current thread so g and p packets return
1077 // the data the gdb will expect.
1078 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1079 SetCurrentThreadID (tid);
1080
1081 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread ();
1082 if (!thread_sp)
1083 return SendErrorResponse (69);
1084
1085 StreamString response;
1086 response.Printf ("QC%" PRIx64, thread_sp->GetID ());
1087
1088 return SendPacketNoLock (response.GetData(), response.GetSize());
1089}
1090
Tamas Berghammere13c2732015-02-11 10:29:30 +00001091GDBRemoteCommunication::PacketResult
1092GDBRemoteCommunicationServerLLGS::Handle_k (StringExtractorGDBRemote &packet)
1093{
Pavel Labath424b2012015-07-28 09:06:56 +00001094 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00001095
Pavel Labathc7749c32015-07-21 13:20:25 +00001096 StopSTDIOForwarding();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001097
Pavel Labath424b2012015-07-28 09:06:56 +00001098 if (! m_debugged_process_sp)
1099 {
1100 if (log)
1101 log->Printf("GDBRemoteCommunicationServerLLGS::%s No debugged process found.", __FUNCTION__);
1102 return PacketResult::Success;
1103 }
1104
1105 Error error = m_debugged_process_sp->Kill();
1106 if (error.Fail() && log)
1107 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged process %" PRIu64 ": %s",
1108 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1109
Tamas Berghammere13c2732015-02-11 10:29:30 +00001110 // No OK response for kill packet.
1111 // return SendOKResponse ();
1112 return PacketResult::Success;
1113}
1114
1115GDBRemoteCommunication::PacketResult
1116GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR (StringExtractorGDBRemote &packet)
1117{
1118 packet.SetFilePos(::strlen ("QSetDisableASLR:"));
1119 if (packet.GetU32(0))
1120 m_process_launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
1121 else
1122 m_process_launch_info.GetFlags().Clear (eLaunchFlagDisableASLR);
1123 return SendOKResponse ();
1124}
1125
1126GDBRemoteCommunication::PacketResult
1127GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
1128{
1129 packet.SetFilePos (::strlen ("QSetWorkingDir:"));
1130 std::string path;
1131 packet.GetHexByteString (path);
Chaoren Lind3173f32015-05-29 19:52:29 +00001132 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
Tamas Berghammere13c2732015-02-11 10:29:30 +00001133 return SendOKResponse ();
1134}
1135
1136GDBRemoteCommunication::PacketResult
1137GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
1138{
Chaoren Lind3173f32015-05-29 19:52:29 +00001139 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1140 if (working_dir)
Tamas Berghammere13c2732015-02-11 10:29:30 +00001141 {
1142 StreamString response;
Chaoren Lind3173f32015-05-29 19:52:29 +00001143 response.PutCStringAsRawHex8(working_dir.GetCString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001144 return SendPacketNoLock(response.GetData(), response.GetSize());
1145 }
1146
1147 return SendErrorResponse(14);
1148}
1149
1150GDBRemoteCommunication::PacketResult
1151GDBRemoteCommunicationServerLLGS::Handle_C (StringExtractorGDBRemote &packet)
1152{
1153 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
1154 if (log)
1155 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1156
1157 // Ensure we have a native process.
1158 if (!m_debugged_process_sp)
1159 {
1160 if (log)
1161 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1162 return SendErrorResponse (0x36);
1163 }
1164
1165 // Pull out the signal number.
1166 packet.SetFilePos (::strlen ("C"));
1167 if (packet.GetBytesLeft () < 1)
1168 {
1169 // Shouldn't be using a C without a signal.
1170 return SendIllFormedResponse (packet, "C packet specified without signal.");
1171 }
1172 const uint32_t signo = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1173 if (signo == std::numeric_limits<uint32_t>::max ())
1174 return SendIllFormedResponse (packet, "failed to parse signal number");
1175
1176 // Handle optional continue address.
1177 if (packet.GetBytesLeft () > 0)
1178 {
1179 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1180 if (*packet.Peek () == ';')
1181 return SendUnimplementedResponse (packet.GetStringRef().c_str());
1182 else
1183 return SendIllFormedResponse (packet, "unexpected content after $C{signal-number}");
1184 }
1185
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001186 ResumeActionList resume_actions (StateType::eStateRunning, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001187 Error error;
1188
1189 // We have two branches: what to do if a continue thread is specified (in which case we target
1190 // sending the signal to that thread), or when we don't have a continue thread set (in which
1191 // case we send a signal to the process).
1192
1193 // TODO discuss with Greg Clayton, make sure this makes sense.
1194
1195 lldb::tid_t signal_tid = GetContinueThreadID ();
1196 if (signal_tid != LLDB_INVALID_THREAD_ID)
1197 {
1198 // The resume action for the continue thread (or all threads if a continue thread is not set).
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001199 ResumeAction action = { GetContinueThreadID (), StateType::eStateRunning, static_cast<int> (signo) };
Tamas Berghammere13c2732015-02-11 10:29:30 +00001200
1201 // Add the action for the continue thread (or all threads when the continue thread isn't present).
1202 resume_actions.Append (action);
1203 }
1204 else
1205 {
1206 // Send the signal to the process since we weren't targeting a specific continue thread with the signal.
1207 error = m_debugged_process_sp->Signal (signo);
1208 if (error.Fail ())
1209 {
1210 if (log)
1211 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to send signal for process %" PRIu64 ": %s",
1212 __FUNCTION__,
1213 m_debugged_process_sp->GetID (),
1214 error.AsCString ());
1215
1216 return SendErrorResponse (0x52);
1217 }
1218 }
1219
1220 // Resume the threads.
1221 error = m_debugged_process_sp->Resume (resume_actions);
1222 if (error.Fail ())
1223 {
1224 if (log)
1225 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to resume threads for process %" PRIu64 ": %s",
1226 __FUNCTION__,
1227 m_debugged_process_sp->GetID (),
1228 error.AsCString ());
1229
1230 return SendErrorResponse (0x38);
1231 }
1232
1233 // Don't send an "OK" packet; response is the stopped/exited message.
1234 return PacketResult::Success;
1235}
1236
1237GDBRemoteCommunication::PacketResult
1238GDBRemoteCommunicationServerLLGS::Handle_c (StringExtractorGDBRemote &packet)
1239{
1240 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
1241 if (log)
1242 log->Printf ("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1243
1244 packet.SetFilePos (packet.GetFilePos() + ::strlen ("c"));
1245
1246 // For now just support all continue.
1247 const bool has_continue_address = (packet.GetBytesLeft () > 0);
1248 if (has_continue_address)
1249 {
1250 if (log)
1251 log->Printf ("GDBRemoteCommunicationServerLLGS::%s not implemented for c{address} variant [%s remains]", __FUNCTION__, packet.Peek ());
1252 return SendUnimplementedResponse (packet.GetStringRef().c_str());
1253 }
1254
1255 // Ensure we have a native process.
1256 if (!m_debugged_process_sp)
1257 {
1258 if (log)
1259 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1260 return SendErrorResponse (0x36);
1261 }
1262
1263 // Build the ResumeActionList
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001264 ResumeActionList actions (StateType::eStateRunning, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001265
1266 Error error = m_debugged_process_sp->Resume (actions);
1267 if (error.Fail ())
1268 {
1269 if (log)
1270 {
1271 log->Printf ("GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64 ": %s",
1272 __FUNCTION__,
1273 m_debugged_process_sp->GetID (),
1274 error.AsCString ());
1275 }
1276 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1277 }
1278
1279 if (log)
1280 log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1281
1282 // No response required from continue.
1283 return PacketResult::Success;
1284}
1285
1286GDBRemoteCommunication::PacketResult
1287GDBRemoteCommunicationServerLLGS::Handle_vCont_actions (StringExtractorGDBRemote &packet)
1288{
1289 StreamString response;
1290 response.Printf("vCont;c;C;s;S");
1291
1292 return SendPacketNoLock(response.GetData(), response.GetSize());
1293}
1294
1295GDBRemoteCommunication::PacketResult
1296GDBRemoteCommunicationServerLLGS::Handle_vCont (StringExtractorGDBRemote &packet)
1297{
1298 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1299 if (log)
1300 log->Printf ("GDBRemoteCommunicationServerLLGS::%s handling vCont packet", __FUNCTION__);
1301
1302 packet.SetFilePos (::strlen ("vCont"));
1303
1304 if (packet.GetBytesLeft() == 0)
1305 {
1306 if (log)
1307 log->Printf ("GDBRemoteCommunicationServerLLGS::%s missing action from vCont package", __FUNCTION__);
1308 return SendIllFormedResponse (packet, "Missing action from vCont package");
1309 }
1310
1311 // Check if this is all continue (no options or ";c").
1312 if (::strcmp (packet.Peek (), ";c") == 0)
1313 {
1314 // Move past the ';', then do a simple 'c'.
1315 packet.SetFilePos (packet.GetFilePos () + 1);
1316 return Handle_c (packet);
1317 }
1318 else if (::strcmp (packet.Peek (), ";s") == 0)
1319 {
1320 // Move past the ';', then do a simple 's'.
1321 packet.SetFilePos (packet.GetFilePos () + 1);
1322 return Handle_s (packet);
1323 }
1324
1325 // Ensure we have a native process.
1326 if (!m_debugged_process_sp)
1327 {
1328 if (log)
1329 log->Printf ("GDBRemoteCommunicationServerLLGS::%s no debugged process shared pointer", __FUNCTION__);
1330 return SendErrorResponse (0x36);
1331 }
1332
1333 ResumeActionList thread_actions;
1334
1335 while (packet.GetBytesLeft () && *packet.Peek () == ';')
1336 {
1337 // Skip the semi-colon.
1338 packet.GetChar ();
1339
1340 // Build up the thread action.
1341 ResumeAction thread_action;
1342 thread_action.tid = LLDB_INVALID_THREAD_ID;
1343 thread_action.state = eStateInvalid;
1344 thread_action.signal = 0;
1345
1346 const char action = packet.GetChar ();
1347 switch (action)
1348 {
1349 case 'C':
1350 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1351 if (thread_action.signal == 0)
1352 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet C action");
1353 // Fall through to next case...
1354
1355 case 'c':
1356 // Continue
1357 thread_action.state = eStateRunning;
1358 break;
1359
1360 case 'S':
1361 thread_action.signal = packet.GetHexMaxU32 (false, 0);
1362 if (thread_action.signal == 0)
1363 return SendIllFormedResponse (packet, "Could not parse signal in vCont packet S action");
1364 // Fall through to next case...
1365
1366 case 's':
1367 // Step
1368 thread_action.state = eStateStepping;
1369 break;
1370
1371 default:
1372 return SendIllFormedResponse (packet, "Unsupported vCont action");
1373 break;
1374 }
1375
1376 // Parse out optional :{thread-id} value.
1377 if (packet.GetBytesLeft () && (*packet.Peek () == ':'))
1378 {
1379 // Consume the separator.
1380 packet.GetChar ();
1381
1382 thread_action.tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
1383 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1384 return SendIllFormedResponse (packet, "Could not parse thread number in vCont packet");
1385 }
1386
1387 thread_actions.Append (thread_action);
1388 }
1389
1390 Error error = m_debugged_process_sp->Resume (thread_actions);
1391 if (error.Fail ())
1392 {
1393 if (log)
1394 {
1395 log->Printf ("GDBRemoteCommunicationServerLLGS::%s vCont failed for process %" PRIu64 ": %s",
1396 __FUNCTION__,
1397 m_debugged_process_sp->GetID (),
1398 error.AsCString ());
1399 }
1400 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1401 }
1402
1403 if (log)
1404 log->Printf ("GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1405
1406 // No response required from vCont.
1407 return PacketResult::Success;
1408}
1409
1410void
1411GDBRemoteCommunicationServerLLGS::SetCurrentThreadID (lldb::tid_t tid)
1412{
1413 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1414 if (log)
1415 log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting current thread id to %" PRIu64, __FUNCTION__, tid);
1416
1417 m_current_tid = tid;
1418 if (m_debugged_process_sp)
1419 m_debugged_process_sp->SetCurrentThreadID (m_current_tid);
1420}
1421
1422void
1423GDBRemoteCommunicationServerLLGS::SetContinueThreadID (lldb::tid_t tid)
1424{
1425 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_THREAD));
1426 if (log)
1427 log->Printf ("GDBRemoteCommunicationServerLLGS::%s setting continue thread id to %" PRIu64, __FUNCTION__, tid);
1428
1429 m_continue_tid = tid;
1430}
1431
1432GDBRemoteCommunication::PacketResult
1433GDBRemoteCommunicationServerLLGS::Handle_stop_reason (StringExtractorGDBRemote &packet)
1434{
1435 // Handle the $? gdbremote command.
1436
1437 // If no process, indicate error
1438 if (!m_debugged_process_sp)
1439 return SendErrorResponse (02);
1440
Pavel Labathc7749c32015-07-21 13:20:25 +00001441 return SendStopReasonForState (m_debugged_process_sp->GetState());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001442}
1443
1444GDBRemoteCommunication::PacketResult
Pavel Labathc7749c32015-07-21 13:20:25 +00001445GDBRemoteCommunicationServerLLGS::SendStopReasonForState (lldb::StateType process_state)
Tamas Berghammere13c2732015-02-11 10:29:30 +00001446{
1447 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1448
1449 switch (process_state)
1450 {
1451 case eStateAttaching:
1452 case eStateLaunching:
1453 case eStateRunning:
1454 case eStateStepping:
1455 case eStateDetached:
1456 // NOTE: gdb protocol doc looks like it should return $OK
1457 // when everything is running (i.e. no stopped result).
1458 return PacketResult::Success; // Ignore
1459
1460 case eStateSuspended:
1461 case eStateStopped:
1462 case eStateCrashed:
1463 {
1464 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID ();
1465 // Make sure we set the current thread so g and p packets return
1466 // the data the gdb will expect.
1467 SetCurrentThreadID (tid);
1468 return SendStopReplyPacketForThread (tid);
1469 }
1470
1471 case eStateInvalid:
1472 case eStateUnloaded:
1473 case eStateExited:
Tamas Berghammere13c2732015-02-11 10:29:30 +00001474 return SendWResponse(m_debugged_process_sp.get());
1475
1476 default:
1477 if (log)
1478 {
1479 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 ", current state reporting not handled: %s",
1480 __FUNCTION__,
1481 m_debugged_process_sp->GetID (),
1482 StateAsCString (process_state));
1483 }
1484 break;
1485 }
1486
1487 return SendErrorResponse (0);
1488}
1489
1490GDBRemoteCommunication::PacketResult
1491GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo (StringExtractorGDBRemote &packet)
1492{
1493 // Fail if we don't have a current process.
1494 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1495 return SendErrorResponse (68);
1496
1497 // Ensure we have a thread.
1498 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadAtIndex (0));
1499 if (!thread_sp)
1500 return SendErrorResponse (69);
1501
1502 // Get the register context for the first thread.
1503 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1504 if (!reg_context_sp)
1505 return SendErrorResponse (69);
1506
1507 // Parse out the register number from the request.
1508 packet.SetFilePos (strlen("qRegisterInfo"));
1509 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1510 if (reg_index == std::numeric_limits<uint32_t>::max ())
1511 return SendErrorResponse (69);
1512
1513 // Return the end of registers response if we've iterated one past the end of the register set.
1514 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1515 return SendErrorResponse (69);
1516
1517 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1518 if (!reg_info)
1519 return SendErrorResponse (69);
1520
1521 // Build the reginfos response.
1522 StreamGDBRemote response;
1523
1524 response.PutCString ("name:");
1525 response.PutCString (reg_info->name);
1526 response.PutChar (';');
1527
1528 if (reg_info->alt_name && reg_info->alt_name[0])
1529 {
1530 response.PutCString ("alt-name:");
1531 response.PutCString (reg_info->alt_name);
1532 response.PutChar (';');
1533 }
1534
1535 response.Printf ("bitsize:%" PRIu32 ";offset:%" PRIu32 ";", reg_info->byte_size * 8, reg_info->byte_offset);
1536
1537 switch (reg_info->encoding)
1538 {
1539 case eEncodingUint: response.PutCString ("encoding:uint;"); break;
1540 case eEncodingSint: response.PutCString ("encoding:sint;"); break;
1541 case eEncodingIEEE754: response.PutCString ("encoding:ieee754;"); break;
1542 case eEncodingVector: response.PutCString ("encoding:vector;"); break;
1543 default: break;
1544 }
1545
1546 switch (reg_info->format)
1547 {
1548 case eFormatBinary: response.PutCString ("format:binary;"); break;
1549 case eFormatDecimal: response.PutCString ("format:decimal;"); break;
1550 case eFormatHex: response.PutCString ("format:hex;"); break;
1551 case eFormatFloat: response.PutCString ("format:float;"); break;
1552 case eFormatVectorOfSInt8: response.PutCString ("format:vector-sint8;"); break;
1553 case eFormatVectorOfUInt8: response.PutCString ("format:vector-uint8;"); break;
1554 case eFormatVectorOfSInt16: response.PutCString ("format:vector-sint16;"); break;
1555 case eFormatVectorOfUInt16: response.PutCString ("format:vector-uint16;"); break;
1556 case eFormatVectorOfSInt32: response.PutCString ("format:vector-sint32;"); break;
1557 case eFormatVectorOfUInt32: response.PutCString ("format:vector-uint32;"); break;
1558 case eFormatVectorOfFloat32: response.PutCString ("format:vector-float32;"); break;
1559 case eFormatVectorOfUInt128: response.PutCString ("format:vector-uint128;"); break;
1560 default: break;
1561 };
1562
1563 const char *const register_set_name = reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1564 if (register_set_name)
1565 {
1566 response.PutCString ("set:");
1567 response.PutCString (register_set_name);
1568 response.PutChar (';');
1569 }
1570
Jason Molendaa18f7072015-08-15 01:21:01 +00001571 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] != LLDB_INVALID_REGNUM)
Jason Molenda63bd0db2015-09-15 23:20:34 +00001572 response.Printf ("ehframe:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001573
1574 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1575 response.Printf ("dwarf:%" PRIu32 ";", reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1576
1577 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric])
1578 {
1579 case LLDB_REGNUM_GENERIC_PC: response.PutCString("generic:pc;"); break;
1580 case LLDB_REGNUM_GENERIC_SP: response.PutCString("generic:sp;"); break;
1581 case LLDB_REGNUM_GENERIC_FP: response.PutCString("generic:fp;"); break;
1582 case LLDB_REGNUM_GENERIC_RA: response.PutCString("generic:ra;"); break;
1583 case LLDB_REGNUM_GENERIC_FLAGS: response.PutCString("generic:flags;"); break;
1584 case LLDB_REGNUM_GENERIC_ARG1: response.PutCString("generic:arg1;"); break;
1585 case LLDB_REGNUM_GENERIC_ARG2: response.PutCString("generic:arg2;"); break;
1586 case LLDB_REGNUM_GENERIC_ARG3: response.PutCString("generic:arg3;"); break;
1587 case LLDB_REGNUM_GENERIC_ARG4: response.PutCString("generic:arg4;"); break;
1588 case LLDB_REGNUM_GENERIC_ARG5: response.PutCString("generic:arg5;"); break;
1589 case LLDB_REGNUM_GENERIC_ARG6: response.PutCString("generic:arg6;"); break;
1590 case LLDB_REGNUM_GENERIC_ARG7: response.PutCString("generic:arg7;"); break;
1591 case LLDB_REGNUM_GENERIC_ARG8: response.PutCString("generic:arg8;"); break;
1592 default: break;
1593 }
1594
1595 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM)
1596 {
1597 response.PutCString ("container-regs:");
1598 int i = 0;
1599 for (const uint32_t *reg_num = reg_info->value_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1600 {
1601 if (i > 0)
1602 response.PutChar (',');
1603 response.Printf ("%" PRIx32, *reg_num);
1604 }
1605 response.PutChar (';');
1606 }
1607
1608 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0])
1609 {
1610 response.PutCString ("invalidate-regs:");
1611 int i = 0;
1612 for (const uint32_t *reg_num = reg_info->invalidate_regs; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i)
1613 {
1614 if (i > 0)
1615 response.PutChar (',');
1616 response.Printf ("%" PRIx32, *reg_num);
1617 }
1618 response.PutChar (';');
1619 }
1620
1621 return SendPacketNoLock(response.GetData(), response.GetSize());
1622}
1623
1624GDBRemoteCommunication::PacketResult
1625GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo (StringExtractorGDBRemote &packet)
1626{
1627 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1628
1629 // Fail if we don't have a current process.
1630 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1631 {
1632 if (log)
1633 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() no process (%s), returning OK", __FUNCTION__, m_debugged_process_sp ? "invalid process id" : "null m_debugged_process_sp");
1634 return SendOKResponse ();
1635 }
1636
1637 StreamGDBRemote response;
1638 response.PutChar ('m');
1639
1640 if (log)
1641 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() starting thread iteration", __FUNCTION__);
1642
1643 NativeThreadProtocolSP thread_sp;
1644 uint32_t thread_index;
1645 for (thread_index = 0, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index);
1646 thread_sp;
1647 ++thread_index, thread_sp = m_debugged_process_sp->GetThreadAtIndex (thread_index))
1648 {
1649 if (log)
1650 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);
1651 if (thread_index > 0)
1652 response.PutChar(',');
1653 response.Printf ("%" PRIx64, thread_sp->GetID ());
1654 }
1655
1656 if (log)
1657 log->Printf ("GDBRemoteCommunicationServerLLGS::%s() finished thread iteration", __FUNCTION__);
1658
1659 return SendPacketNoLock(response.GetData(), response.GetSize());
1660}
1661
1662GDBRemoteCommunication::PacketResult
1663GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo (StringExtractorGDBRemote &packet)
1664{
1665 // FIXME for now we return the full thread list in the initial packet and always do nothing here.
1666 return SendPacketNoLock ("l", 1);
1667}
1668
1669GDBRemoteCommunication::PacketResult
1670GDBRemoteCommunicationServerLLGS::Handle_p (StringExtractorGDBRemote &packet)
1671{
1672 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1673
1674 // Parse out the register number from the request.
1675 packet.SetFilePos (strlen("p"));
1676 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1677 if (reg_index == std::numeric_limits<uint32_t>::max ())
1678 {
1679 if (log)
1680 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1681 return SendErrorResponse (0x15);
1682 }
1683
1684 // Get the thread to use.
1685 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1686 if (!thread_sp)
1687 {
1688 if (log)
1689 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available", __FUNCTION__);
1690 return SendErrorResponse (0x15);
1691 }
1692
1693 // Get the thread's register context.
1694 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1695 if (!reg_context_sp)
1696 {
1697 if (log)
1698 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 ());
1699 return SendErrorResponse (0x15);
1700 }
1701
1702 // Return the end of registers response if we've iterated one past the end of the register set.
1703 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1704 {
1705 if (log)
1706 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1707 return SendErrorResponse (0x15);
1708 }
1709
1710 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1711 if (!reg_info)
1712 {
1713 if (log)
1714 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1715 return SendErrorResponse (0x15);
1716 }
1717
1718 // Build the reginfos response.
1719 StreamGDBRemote response;
1720
1721 // Retrieve the value
1722 RegisterValue reg_value;
1723 Error error = reg_context_sp->ReadRegister (reg_info, reg_value);
1724 if (error.Fail ())
1725 {
1726 if (log)
1727 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, read of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1728 return SendErrorResponse (0x15);
1729 }
1730
1731 const uint8_t *const data = reinterpret_cast<const uint8_t*> (reg_value.GetBytes ());
1732 if (!data)
1733 {
1734 if (log)
1735 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to get data bytes from requested register %" PRIu32, __FUNCTION__, reg_index);
1736 return SendErrorResponse (0x15);
1737 }
1738
1739 // FIXME flip as needed to get data in big/little endian format for this host.
1740 for (uint32_t i = 0; i < reg_value.GetByteSize (); ++i)
1741 response.PutHex8 (data[i]);
1742
1743 return SendPacketNoLock (response.GetData (), response.GetSize ());
1744}
1745
1746GDBRemoteCommunication::PacketResult
1747GDBRemoteCommunicationServerLLGS::Handle_P (StringExtractorGDBRemote &packet)
1748{
1749 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1750
1751 // Ensure there is more content.
1752 if (packet.GetBytesLeft () < 1)
1753 return SendIllFormedResponse (packet, "Empty P packet");
1754
1755 // Parse out the register number from the request.
1756 packet.SetFilePos (strlen("P"));
1757 const uint32_t reg_index = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
1758 if (reg_index == std::numeric_limits<uint32_t>::max ())
1759 {
1760 if (log)
1761 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse register number from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
1762 return SendErrorResponse (0x29);
1763 }
1764
1765 // Note debugserver would send an E30 here.
1766 if ((packet.GetBytesLeft () < 1) || (packet.GetChar () != '='))
1767 return SendIllFormedResponse (packet, "P packet missing '=' char after register number");
1768
1769 // Get process architecture.
1770 ArchSpec process_arch;
1771 if (!m_debugged_process_sp || !m_debugged_process_sp->GetArchitecture (process_arch))
1772 {
1773 if (log)
1774 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to retrieve inferior architecture", __FUNCTION__);
1775 return SendErrorResponse (0x49);
1776 }
1777
1778 // Parse out the value.
1779 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
1780 size_t reg_size = packet.GetHexBytesAvail (reg_bytes, sizeof(reg_bytes));
1781
1782 // Get the thread to use.
1783 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
1784 if (!thread_sp)
1785 {
1786 if (log)
1787 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no thread available (thread index 0)", __FUNCTION__);
1788 return SendErrorResponse (0x28);
1789 }
1790
1791 // Get the thread's register context.
1792 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
1793 if (!reg_context_sp)
1794 {
1795 if (log)
1796 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 ());
1797 return SendErrorResponse (0x15);
1798 }
1799
1800 const RegisterInfo *reg_info = reg_context_sp->GetRegisterInfoAtIndex (reg_index);
1801 if (!reg_info)
1802 {
1803 if (log)
1804 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " returned NULL", __FUNCTION__, reg_index);
1805 return SendErrorResponse (0x48);
1806 }
1807
1808 // Return the end of registers response if we've iterated one past the end of the register set.
1809 if (reg_index >= reg_context_sp->GetUserRegisterCount ())
1810 {
1811 if (log)
1812 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, requested register %" PRIu32 " beyond register count %" PRIu32, __FUNCTION__, reg_index, reg_context_sp->GetUserRegisterCount ());
1813 return SendErrorResponse (0x47);
1814 }
1815
1816 if (reg_size != reg_info->byte_size)
1817 {
1818 return SendIllFormedResponse (packet, "P packet register size is incorrect");
1819 }
1820
1821 // Build the reginfos response.
1822 StreamGDBRemote response;
1823
1824 RegisterValue reg_value (reg_bytes, reg_size, process_arch.GetByteOrder ());
1825 Error error = reg_context_sp->WriteRegister (reg_info, reg_value);
1826 if (error.Fail ())
1827 {
1828 if (log)
1829 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, write of requested register %" PRIu32 " (%s) failed: %s", __FUNCTION__, reg_index, reg_info->name, error.AsCString ());
1830 return SendErrorResponse (0x32);
1831 }
1832
1833 return SendOKResponse();
1834}
1835
1836GDBRemoteCommunication::PacketResult
1837GDBRemoteCommunicationServerLLGS::Handle_H (StringExtractorGDBRemote &packet)
1838{
1839 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1840
1841 // Fail if we don't have a current process.
1842 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1843 {
1844 if (log)
1845 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1846 return SendErrorResponse (0x15);
1847 }
1848
1849 // Parse out which variant of $H is requested.
1850 packet.SetFilePos (strlen("H"));
1851 if (packet.GetBytesLeft () < 1)
1852 {
1853 if (log)
1854 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, H command missing {g,c} variant", __FUNCTION__);
1855 return SendIllFormedResponse (packet, "H command missing {g,c} variant");
1856 }
1857
1858 const char h_variant = packet.GetChar ();
1859 switch (h_variant)
1860 {
1861 case 'g':
1862 break;
1863
1864 case 'c':
1865 break;
1866
1867 default:
1868 if (log)
1869 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c", __FUNCTION__, h_variant);
1870 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1871 }
1872
1873 // Parse out the thread number.
1874 // FIXME return a parse success/fail value. All values are valid here.
1875 const lldb::tid_t tid = packet.GetHexMaxU64 (false, std::numeric_limits<lldb::tid_t>::max ());
1876
1877 // Ensure we have the given thread when not specifying -1 (all threads) or 0 (any thread).
1878 if (tid != LLDB_INVALID_THREAD_ID && tid != 0)
1879 {
1880 NativeThreadProtocolSP thread_sp (m_debugged_process_sp->GetThreadByID (tid));
1881 if (!thread_sp)
1882 {
1883 if (log)
1884 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64 " not found", __FUNCTION__, tid);
1885 return SendErrorResponse (0x15);
1886 }
1887 }
1888
1889 // Now switch the given thread type.
1890 switch (h_variant)
1891 {
1892 case 'g':
1893 SetCurrentThreadID (tid);
1894 break;
1895
1896 case 'c':
1897 SetContinueThreadID (tid);
1898 break;
1899
1900 default:
1901 assert (false && "unsupported $H variant - shouldn't get here");
1902 return SendIllFormedResponse (packet, "H variant unsupported, should be c or g");
1903 }
1904
1905 return SendOKResponse();
1906}
1907
1908GDBRemoteCommunication::PacketResult
1909GDBRemoteCommunicationServerLLGS::Handle_I (StringExtractorGDBRemote &packet)
1910{
1911 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1912
1913 // Fail if we don't have a current process.
1914 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1915 {
1916 if (log)
1917 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1918 return SendErrorResponse (0x15);
1919 }
1920
1921 packet.SetFilePos (::strlen("I"));
1922 char tmp[4096];
1923 for (;;)
1924 {
1925 size_t read = packet.GetHexBytesAvail(tmp, sizeof(tmp));
1926 if (read == 0)
1927 {
1928 break;
1929 }
1930 // write directly to stdin *this might block if stdin buffer is full*
1931 // TODO: enqueue this block in circular buffer and send window size to remote host
1932 ConnectionStatus status;
1933 Error error;
Pavel Labathc7749c32015-07-21 13:20:25 +00001934 Mutex::Locker locker(m_stdio_communication_mutex);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001935 m_stdio_communication.Write(tmp, read, status, &error);
1936 if (error.Fail())
1937 {
1938 return SendErrorResponse (0x15);
1939 }
1940 }
1941
1942 return SendOKResponse();
1943}
1944
1945GDBRemoteCommunication::PacketResult
1946GDBRemoteCommunicationServerLLGS::Handle_interrupt (StringExtractorGDBRemote &packet)
1947{
1948 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1949
1950 // Fail if we don't have a current process.
1951 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1952 {
1953 if (log)
1954 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1955 return SendErrorResponse (0x15);
1956 }
1957
1958 // Interrupt the process.
1959 Error error = m_debugged_process_sp->Interrupt ();
1960 if (error.Fail ())
1961 {
1962 if (log)
1963 {
1964 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64 ": %s",
1965 __FUNCTION__,
1966 m_debugged_process_sp->GetID (),
1967 error.AsCString ());
1968 }
1969 return SendErrorResponse (GDBRemoteServerError::eErrorResume);
1970 }
1971
1972 if (log)
1973 log->Printf ("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64, __FUNCTION__, m_debugged_process_sp->GetID ());
1974
1975 // No response required from stop all.
1976 return PacketResult::Success;
1977}
1978
1979GDBRemoteCommunication::PacketResult
Pavel Labath3bf11252015-10-14 12:59:37 +00001980GDBRemoteCommunicationServerLLGS::Handle_memory_read(StringExtractorGDBRemote &packet)
Tamas Berghammere13c2732015-02-11 10:29:30 +00001981{
1982 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1983
1984 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
1985 {
1986 if (log)
1987 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
1988 return SendErrorResponse (0x15);
1989 }
1990
1991 // Parse out the memory address.
1992 packet.SetFilePos (strlen("m"));
1993 if (packet.GetBytesLeft() < 1)
1994 return SendIllFormedResponse(packet, "Too short m packet");
1995
1996 // Read the address. Punting on validation.
1997 // FIXME replace with Hex U64 read with no default value that fails on failed read.
1998 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
1999
2000 // Validate comma.
2001 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2002 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2003
2004 // Get # bytes to read.
2005 if (packet.GetBytesLeft() < 1)
2006 return SendIllFormedResponse(packet, "Length missing in m packet");
2007
2008 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2009 if (byte_count == 0)
2010 {
2011 if (log)
2012 log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to read: zero-length packet", __FUNCTION__);
Pavel Labath3bf11252015-10-14 12:59:37 +00002013 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002014 }
2015
2016 // Allocate the response buffer.
2017 std::string buf(byte_count, '\0');
2018 if (buf.empty())
2019 return SendErrorResponse (0x78);
2020
2021
2022 // Retrieve the process memory.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002023 size_t bytes_read = 0;
2024 Error error = m_debugged_process_sp->ReadMemoryWithoutTrap(read_addr, &buf[0], byte_count, bytes_read);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002025 if (error.Fail ())
2026 {
2027 if (log)
2028 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to read. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, error.AsCString ());
2029 return SendErrorResponse (0x08);
2030 }
2031
2032 if (bytes_read == 0)
2033 {
2034 if (log)
Ilia Kd50ea2f2015-05-15 09:15:27 +00002035 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), read_addr, byte_count);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002036 return SendErrorResponse (0x08);
2037 }
2038
2039 StreamGDBRemote response;
Pavel Labath3bf11252015-10-14 12:59:37 +00002040 packet.SetFilePos(0);
2041 char kind = packet.GetChar('?');
2042 if (kind == 'x')
2043 response.PutEscapedBytes(buf.data(), byte_count);
2044 else
2045 {
2046 assert(kind == 'm');
2047 for (size_t i = 0; i < bytes_read; ++i)
2048 response.PutHex8(buf[i]);
2049 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002050
2051 return SendPacketNoLock(response.GetData(), response.GetSize());
2052}
2053
2054GDBRemoteCommunication::PacketResult
2055GDBRemoteCommunicationServerLLGS::Handle_M (StringExtractorGDBRemote &packet)
2056{
2057 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2058
2059 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2060 {
2061 if (log)
2062 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2063 return SendErrorResponse (0x15);
2064 }
2065
2066 // Parse out the memory address.
2067 packet.SetFilePos (strlen("M"));
2068 if (packet.GetBytesLeft() < 1)
2069 return SendIllFormedResponse(packet, "Too short M packet");
2070
2071 // Read the address. Punting on validation.
2072 // FIXME replace with Hex U64 read with no default value that fails on failed read.
2073 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2074
2075 // Validate comma.
2076 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2077 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2078
2079 // Get # bytes to read.
2080 if (packet.GetBytesLeft() < 1)
2081 return SendIllFormedResponse(packet, "Length missing in M packet");
2082
2083 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2084 if (byte_count == 0)
2085 {
2086 if (log)
2087 log->Printf ("GDBRemoteCommunicationServerLLGS::%s nothing to write: zero-length packet", __FUNCTION__);
2088 return PacketResult::Success;
2089 }
2090
2091 // Validate colon.
2092 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2093 return SendIllFormedResponse(packet, "Comma sep missing in M packet after byte length");
2094
2095 // Allocate the conversion buffer.
2096 std::vector<uint8_t> buf(byte_count, 0);
2097 if (buf.empty())
2098 return SendErrorResponse (0x78);
2099
2100 // Convert the hex memory write contents to bytes.
2101 StreamGDBRemote response;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002102 const uint64_t convert_count = packet.GetHexBytes(&buf[0], byte_count, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002103 if (convert_count != byte_count)
2104 {
2105 if (log)
2106 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);
2107 return SendIllFormedResponse (packet, "M content byte length specified did not match hex-encoded content length");
2108 }
2109
2110 // Write the process memory.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002111 size_t bytes_written = 0;
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002112 Error error = m_debugged_process_sp->WriteMemory (write_addr, &buf[0], byte_count, bytes_written);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002113 if (error.Fail ())
2114 {
2115 if (log)
2116 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": failed to write. Error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, error.AsCString ());
2117 return SendErrorResponse (0x09);
2118 }
2119
2120 if (bytes_written == 0)
2121 {
2122 if (log)
Ilia Kd50ea2f2015-05-15 09:15:27 +00002123 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " mem 0x%" PRIx64 ": wrote 0 of %" PRIu64 " requested bytes", __FUNCTION__, m_debugged_process_sp->GetID (), write_addr, byte_count);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002124 return SendErrorResponse (0x09);
2125 }
2126
2127 return SendOKResponse ();
2128}
2129
2130GDBRemoteCommunication::PacketResult
2131GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported (StringExtractorGDBRemote &packet)
2132{
2133 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2134
2135 // Currently only the NativeProcessProtocol knows if it can handle a qMemoryRegionInfoSupported
2136 // request, but we're not guaranteed to be attached to a process. For now we'll assume the
2137 // client only asks this when a process is being debugged.
2138
2139 // Ensure we have a process running; otherwise, we can't figure this out
2140 // since we won't have a NativeProcessProtocol.
2141 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2142 {
2143 if (log)
2144 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2145 return SendErrorResponse (0x15);
2146 }
2147
2148 // Test if we can get any region back when asking for the region around NULL.
2149 MemoryRegionInfo region_info;
2150 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (0, region_info);
2151 if (error.Fail ())
2152 {
2153 // We don't support memory region info collection for this NativeProcessProtocol.
2154 return SendUnimplementedResponse ("");
2155 }
2156
2157 return SendOKResponse();
2158}
2159
2160GDBRemoteCommunication::PacketResult
2161GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo (StringExtractorGDBRemote &packet)
2162{
2163 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2164
2165 // Ensure we have a process.
2166 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2167 {
2168 if (log)
2169 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2170 return SendErrorResponse (0x15);
2171 }
2172
2173 // Parse out the memory address.
2174 packet.SetFilePos (strlen("qMemoryRegionInfo:"));
2175 if (packet.GetBytesLeft() < 1)
2176 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2177
2178 // Read the address. Punting on validation.
2179 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2180
2181 StreamGDBRemote response;
2182
2183 // Get the memory region info for the target address.
2184 MemoryRegionInfo region_info;
2185 const Error error = m_debugged_process_sp->GetMemoryRegionInfo (read_addr, region_info);
2186 if (error.Fail ())
2187 {
2188 // Return the error message.
2189
2190 response.PutCString ("error:");
2191 response.PutCStringAsRawHex8 (error.AsCString ());
2192 response.PutChar (';');
2193 }
2194 else
2195 {
2196 // Range start and size.
2197 response.Printf ("start:%" PRIx64 ";size:%" PRIx64 ";", region_info.GetRange ().GetRangeBase (), region_info.GetRange ().GetByteSize ());
2198
2199 // Permissions.
2200 if (region_info.GetReadable () ||
2201 region_info.GetWritable () ||
2202 region_info.GetExecutable ())
2203 {
2204 // Write permissions info.
2205 response.PutCString ("permissions:");
2206
2207 if (region_info.GetReadable ())
2208 response.PutChar ('r');
2209 if (region_info.GetWritable ())
2210 response.PutChar('w');
2211 if (region_info.GetExecutable())
2212 response.PutChar ('x');
2213
2214 response.PutChar (';');
2215 }
2216 }
2217
2218 return SendPacketNoLock(response.GetData(), response.GetSize());
2219}
2220
2221GDBRemoteCommunication::PacketResult
2222GDBRemoteCommunicationServerLLGS::Handle_Z (StringExtractorGDBRemote &packet)
2223{
2224 // Ensure we have a process.
2225 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2226 {
2227 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2228 if (log)
2229 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2230 return SendErrorResponse (0x15);
2231 }
2232
2233 // Parse out software or hardware breakpoint or watchpoint requested.
2234 packet.SetFilePos (strlen("Z"));
2235 if (packet.GetBytesLeft() < 1)
2236 return SendIllFormedResponse(packet, "Too short Z packet, missing software/hardware specifier");
2237
2238 bool want_breakpoint = true;
2239 bool want_hardware = false;
Omair Javaidcf8eb9d2015-08-12 11:30:21 +00002240 uint32_t watch_flags = 0;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002241
2242 const GDBStoppointType stoppoint_type =
2243 GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2244 switch (stoppoint_type)
2245 {
2246 case eBreakpointSoftware:
2247 want_hardware = false; want_breakpoint = true; break;
2248 case eBreakpointHardware:
2249 want_hardware = true; want_breakpoint = true; break;
2250 case eWatchpointWrite:
Omair Javaidcf8eb9d2015-08-12 11:30:21 +00002251 watch_flags = 1;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002252 want_hardware = true; want_breakpoint = false; break;
2253 case eWatchpointRead:
Omair Javaidcf8eb9d2015-08-12 11:30:21 +00002254 watch_flags = 2;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002255 want_hardware = true; want_breakpoint = false; break;
2256 case eWatchpointReadWrite:
Omair Javaidcf8eb9d2015-08-12 11:30:21 +00002257 watch_flags = 3;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002258 want_hardware = true; want_breakpoint = false; break;
2259 case eStoppointInvalid:
2260 return SendIllFormedResponse(packet, "Z packet had invalid software/hardware specifier");
2261
2262 }
2263
2264 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2265 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after stoppoint type");
2266
2267 // Parse out the stoppoint address.
2268 if (packet.GetBytesLeft() < 1)
2269 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2270 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2271
2272 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2273 return SendIllFormedResponse(packet, "Malformed Z packet, expecting comma after address");
2274
2275 // Parse out the stoppoint size (i.e. size hint for opcode size).
2276 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2277 if (size == std::numeric_limits<uint32_t>::max ())
2278 return SendIllFormedResponse(packet, "Malformed Z packet, failed to parse size argument");
2279
2280 if (want_breakpoint)
2281 {
2282 // Try to set the breakpoint.
2283 const Error error = m_debugged_process_sp->SetBreakpoint (addr, size, want_hardware);
2284 if (error.Success ())
2285 return SendOKResponse ();
2286 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2287 if (log)
2288 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2289 " failed to set breakpoint: %s",
2290 __FUNCTION__,
2291 m_debugged_process_sp->GetID (),
2292 error.AsCString ());
2293 return SendErrorResponse (0x09);
2294 }
2295 else
2296 {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002297 // Try to set the watchpoint.
2298 const Error error = m_debugged_process_sp->SetWatchpoint (
2299 addr, size, watch_flags, want_hardware);
2300 if (error.Success ())
2301 return SendOKResponse ();
2302 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2303 if (log)
2304 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2305 " failed to set watchpoint: %s",
2306 __FUNCTION__,
2307 m_debugged_process_sp->GetID (),
2308 error.AsCString ());
2309 return SendErrorResponse (0x09);
2310 }
2311}
2312
2313GDBRemoteCommunication::PacketResult
2314GDBRemoteCommunicationServerLLGS::Handle_z (StringExtractorGDBRemote &packet)
2315{
2316 // Ensure we have a process.
2317 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2318 {
2319 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2320 if (log)
2321 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2322 return SendErrorResponse (0x15);
2323 }
2324
2325 // Parse out software or hardware breakpoint or watchpoint requested.
2326 packet.SetFilePos (strlen("z"));
2327 if (packet.GetBytesLeft() < 1)
2328 return SendIllFormedResponse(packet, "Too short z packet, missing software/hardware specifier");
2329
2330 bool want_breakpoint = true;
2331
2332 const GDBStoppointType stoppoint_type =
2333 GDBStoppointType(packet.GetS32 (eStoppointInvalid));
2334 switch (stoppoint_type)
2335 {
2336 case eBreakpointHardware: want_breakpoint = true; break;
2337 case eBreakpointSoftware: want_breakpoint = true; break;
2338 case eWatchpointWrite: want_breakpoint = false; break;
2339 case eWatchpointRead: want_breakpoint = false; break;
2340 case eWatchpointReadWrite: want_breakpoint = false; break;
2341 default:
2342 return SendIllFormedResponse(packet, "z packet had invalid software/hardware specifier");
2343
2344 }
2345
2346 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2347 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after stoppoint type");
2348
2349 // Parse out the stoppoint address.
2350 if (packet.GetBytesLeft() < 1)
2351 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2352 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2353
2354 if ((packet.GetBytesLeft() < 1) || packet.GetChar () != ',')
2355 return SendIllFormedResponse(packet, "Malformed z packet, expecting comma after address");
2356
2357 /*
2358 // Parse out the stoppoint size (i.e. size hint for opcode size).
2359 const uint32_t size = packet.GetHexMaxU32 (false, std::numeric_limits<uint32_t>::max ());
2360 if (size == std::numeric_limits<uint32_t>::max ())
2361 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse size argument");
2362 */
2363
2364 if (want_breakpoint)
2365 {
2366 // Try to clear the breakpoint.
2367 const Error error = m_debugged_process_sp->RemoveBreakpoint (addr);
2368 if (error.Success ())
2369 return SendOKResponse ();
2370 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2371 if (log)
2372 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2373 " failed to remove breakpoint: %s",
2374 __FUNCTION__,
2375 m_debugged_process_sp->GetID (),
2376 error.AsCString ());
2377 return SendErrorResponse (0x09);
2378 }
2379 else
2380 {
2381 // Try to clear the watchpoint.
2382 const Error error = m_debugged_process_sp->RemoveWatchpoint (addr);
2383 if (error.Success ())
2384 return SendOKResponse ();
2385 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2386 if (log)
2387 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2388 " failed to remove watchpoint: %s",
2389 __FUNCTION__,
2390 m_debugged_process_sp->GetID (),
2391 error.AsCString ());
2392 return SendErrorResponse (0x09);
2393 }
2394}
2395
2396GDBRemoteCommunication::PacketResult
2397GDBRemoteCommunicationServerLLGS::Handle_s (StringExtractorGDBRemote &packet)
2398{
2399 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_THREAD));
2400
2401 // Ensure we have a process.
2402 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2403 {
2404 if (log)
2405 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2406 return SendErrorResponse (0x32);
2407 }
2408
2409 // We first try to use a continue thread id. If any one or any all set, use the current thread.
2410 // Bail out if we don't have a thread id.
2411 lldb::tid_t tid = GetContinueThreadID ();
2412 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2413 tid = GetCurrentThreadID ();
2414 if (tid == LLDB_INVALID_THREAD_ID)
2415 return SendErrorResponse (0x33);
2416
2417 // Double check that we have such a thread.
2418 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2419 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID (tid);
2420 if (!thread_sp || thread_sp->GetID () != tid)
2421 return SendErrorResponse (0x33);
2422
2423 // Create the step action for the given thread.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002424 ResumeAction action = { tid, eStateStepping, 0 };
Tamas Berghammere13c2732015-02-11 10:29:30 +00002425
2426 // Setup the actions list.
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002427 ResumeActionList actions;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002428 actions.Append (action);
2429
2430 // All other threads stop while we're single stepping a thread.
2431 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2432 Error error = m_debugged_process_sp->Resume (actions);
2433 if (error.Fail ())
2434 {
2435 if (log)
2436 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64 " Resume() failed with error: %s", __FUNCTION__, m_debugged_process_sp->GetID (), tid, error.AsCString ());
2437 return SendErrorResponse(0x49);
2438 }
2439
2440 // No response here - the stop or exit will come from the resulting action.
2441 return PacketResult::Success;
2442}
2443
2444GDBRemoteCommunication::PacketResult
2445GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read (StringExtractorGDBRemote &packet)
2446{
2447 // *BSD impls should be able to do this too.
2448#if defined(__linux__)
2449 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2450
2451 // Parse out the offset.
2452 packet.SetFilePos (strlen("qXfer:auxv:read::"));
2453 if (packet.GetBytesLeft () < 1)
2454 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2455
2456 const uint64_t auxv_offset = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2457 if (auxv_offset == std::numeric_limits<uint64_t>::max ())
2458 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing offset");
2459
2460 // Parse out comma.
2461 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ',')
2462 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing comma after offset");
2463
2464 // Parse out the length.
2465 const uint64_t auxv_length = packet.GetHexMaxU64 (false, std::numeric_limits<uint64_t>::max ());
2466 if (auxv_length == std::numeric_limits<uint64_t>::max ())
2467 return SendIllFormedResponse (packet, "qXfer:auxv:read:: packet missing length");
2468
2469 // Grab the auxv data if we need it.
2470 if (!m_active_auxv_buffer_sp)
2471 {
2472 // Make sure we have a valid process.
2473 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2474 {
2475 if (log)
2476 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2477 return SendErrorResponse (0x10);
2478 }
2479
2480 // Grab the auxv data.
2481 m_active_auxv_buffer_sp = Host::GetAuxvData (m_debugged_process_sp->GetID ());
2482 if (!m_active_auxv_buffer_sp || m_active_auxv_buffer_sp->GetByteSize () == 0)
2483 {
2484 // Hmm, no auxv data, call that an error.
2485 if (log)
2486 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no auxv data retrieved", __FUNCTION__);
2487 m_active_auxv_buffer_sp.reset ();
2488 return SendErrorResponse (0x11);
2489 }
2490 }
2491
2492 // FIXME find out if/how I lock the stream here.
2493
2494 StreamGDBRemote response;
2495 bool done_with_buffer = false;
2496
2497 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize ())
2498 {
2499 // We have nothing left to send. Mark the buffer as complete.
2500 response.PutChar ('l');
2501 done_with_buffer = true;
2502 }
2503 else
2504 {
2505 // Figure out how many bytes are available starting at the given offset.
2506 const uint64_t bytes_remaining = m_active_auxv_buffer_sp->GetByteSize () - auxv_offset;
2507
2508 // Figure out how many bytes we're going to read.
2509 const uint64_t bytes_to_read = (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
2510
2511 // Mark the response type according to whether we're reading the remainder of the auxv data.
2512 if (bytes_to_read >= bytes_remaining)
2513 {
2514 // There will be nothing left to read after this
2515 response.PutChar ('l');
2516 done_with_buffer = true;
2517 }
2518 else
2519 {
2520 // There will still be bytes to read after this request.
2521 response.PutChar ('m');
2522 }
2523
2524 // Now write the data in encoded binary form.
2525 response.PutEscapedBytes (m_active_auxv_buffer_sp->GetBytes () + auxv_offset, bytes_to_read);
2526 }
2527
2528 if (done_with_buffer)
2529 m_active_auxv_buffer_sp.reset ();
2530
2531 return SendPacketNoLock(response.GetData(), response.GetSize());
2532#else
2533 return SendUnimplementedResponse ("not implemented on this platform");
2534#endif
2535}
2536
2537GDBRemoteCommunication::PacketResult
2538GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState (StringExtractorGDBRemote &packet)
2539{
2540 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2541
2542 // Move past packet name.
2543 packet.SetFilePos (strlen ("QSaveRegisterState"));
2544
2545 // Get the thread to use.
2546 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2547 if (!thread_sp)
2548 {
2549 if (m_thread_suffix_supported)
2550 return SendIllFormedResponse (packet, "No thread specified in QSaveRegisterState packet");
2551 else
2552 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2553 }
2554
2555 // Grab the register context for the thread.
2556 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2557 if (!reg_context_sp)
2558 {
2559 if (log)
2560 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 ());
2561 return SendErrorResponse (0x15);
2562 }
2563
2564 // Save registers to a buffer.
2565 DataBufferSP register_data_sp;
2566 Error error = reg_context_sp->ReadAllRegisterValues (register_data_sp);
2567 if (error.Fail ())
2568 {
2569 if (log)
2570 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to save all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2571 return SendErrorResponse (0x75);
2572 }
2573
2574 // Allocate a new save id.
2575 const uint32_t save_id = GetNextSavedRegistersID ();
2576 assert ((m_saved_registers_map.find (save_id) == m_saved_registers_map.end ()) && "GetNextRegisterSaveID() returned an existing register save id");
2577
2578 // Save the register data buffer under the save id.
2579 {
2580 Mutex::Locker locker (m_saved_registers_mutex);
2581 m_saved_registers_map[save_id] = register_data_sp;
2582 }
2583
2584 // Write the response.
2585 StreamGDBRemote response;
2586 response.Printf ("%" PRIu32, save_id);
2587 return SendPacketNoLock(response.GetData(), response.GetSize());
2588}
2589
2590GDBRemoteCommunication::PacketResult
2591GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState (StringExtractorGDBRemote &packet)
2592{
2593 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2594
2595 // Parse out save id.
2596 packet.SetFilePos (strlen ("QRestoreRegisterState:"));
2597 if (packet.GetBytesLeft () < 1)
2598 return SendIllFormedResponse (packet, "QRestoreRegisterState packet missing register save id");
2599
2600 const uint32_t save_id = packet.GetU32 (0);
2601 if (save_id == 0)
2602 {
2603 if (log)
2604 log->Printf ("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState packet has malformed save id, expecting decimal uint32_t", __FUNCTION__);
2605 return SendErrorResponse (0x76);
2606 }
2607
2608 // Get the thread to use.
2609 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix (packet);
2610 if (!thread_sp)
2611 {
2612 if (m_thread_suffix_supported)
2613 return SendIllFormedResponse (packet, "No thread specified in QRestoreRegisterState packet");
2614 else
2615 return SendIllFormedResponse (packet, "No thread was is set with the Hg packet");
2616 }
2617
2618 // Grab the register context for the thread.
2619 NativeRegisterContextSP reg_context_sp (thread_sp->GetRegisterContext ());
2620 if (!reg_context_sp)
2621 {
2622 if (log)
2623 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 ());
2624 return SendErrorResponse (0x15);
2625 }
2626
2627 // Retrieve register state buffer, then remove from the list.
2628 DataBufferSP register_data_sp;
2629 {
2630 Mutex::Locker locker (m_saved_registers_mutex);
2631
2632 // Find the register set buffer for the given save id.
2633 auto it = m_saved_registers_map.find (save_id);
2634 if (it == m_saved_registers_map.end ())
2635 {
2636 if (log)
2637 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);
2638 return SendErrorResponse (0x77);
2639 }
2640 register_data_sp = it->second;
2641
2642 // Remove it from the map.
2643 m_saved_registers_map.erase (it);
2644 }
2645
2646 Error error = reg_context_sp->WriteAllRegisterValues (register_data_sp);
2647 if (error.Fail ())
2648 {
2649 if (log)
2650 log->Printf ("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " failed to restore all register values: %s", __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2651 return SendErrorResponse (0x77);
2652 }
2653
2654 return SendOKResponse();
2655}
2656
2657GDBRemoteCommunication::PacketResult
2658GDBRemoteCommunicationServerLLGS::Handle_vAttach (StringExtractorGDBRemote &packet)
2659{
2660 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2661
2662 // Consume the ';' after vAttach.
2663 packet.SetFilePos (strlen ("vAttach"));
2664 if (!packet.GetBytesLeft () || packet.GetChar () != ';')
2665 return SendIllFormedResponse (packet, "vAttach missing expected ';'");
2666
2667 // Grab the PID to which we will attach (assume hex encoding).
2668 lldb::pid_t pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2669 if (pid == LLDB_INVALID_PROCESS_ID)
2670 return SendIllFormedResponse (packet, "vAttach failed to parse the process id");
2671
2672 // Attempt to attach.
2673 if (log)
2674 log->Printf ("GDBRemoteCommunicationServerLLGS::%s attempting to attach to pid %" PRIu64, __FUNCTION__, pid);
2675
2676 Error error = AttachToProcess (pid);
2677
2678 if (error.Fail ())
2679 {
2680 if (log)
2681 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to attach to pid %" PRIu64 ": %s\n", __FUNCTION__, pid, error.AsCString());
2682 return SendErrorResponse (0x01);
2683 }
2684
2685 // Notify we attached by sending a stop packet.
Pavel Labathc7749c32015-07-21 13:20:25 +00002686 return SendStopReasonForState (m_debugged_process_sp->GetState ());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002687}
2688
2689GDBRemoteCommunication::PacketResult
2690GDBRemoteCommunicationServerLLGS::Handle_D (StringExtractorGDBRemote &packet)
2691{
2692 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2693
Pavel Labathc7749c32015-07-21 13:20:25 +00002694 StopSTDIOForwarding();
2695
Tamas Berghammere13c2732015-02-11 10:29:30 +00002696 // Fail if we don't have a current process.
2697 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2698 {
2699 if (log)
2700 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, no process available", __FUNCTION__);
2701 return SendErrorResponse (0x15);
2702 }
2703
Tamas Berghammere13c2732015-02-11 10:29:30 +00002704 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2705
2706 // Consume the ';' after D.
2707 packet.SetFilePos (1);
2708 if (packet.GetBytesLeft ())
2709 {
2710 if (packet.GetChar () != ';')
2711 return SendIllFormedResponse (packet, "D missing expected ';'");
2712
2713 // Grab the PID from which we will detach (assume hex encoding).
2714 pid = packet.GetU32 (LLDB_INVALID_PROCESS_ID, 16);
2715 if (pid == LLDB_INVALID_PROCESS_ID)
2716 return SendIllFormedResponse (packet, "D failed to parse the process id");
2717 }
2718
2719 if (pid != LLDB_INVALID_PROCESS_ID &&
2720 m_debugged_process_sp->GetID () != pid)
2721 {
2722 return SendIllFormedResponse (packet, "Invalid pid");
2723 }
2724
Tamas Berghammere13c2732015-02-11 10:29:30 +00002725 const Error error = m_debugged_process_sp->Detach ();
2726 if (error.Fail ())
2727 {
2728 if (log)
2729 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to detach from pid %" PRIu64 ": %s\n",
2730 __FUNCTION__, m_debugged_process_sp->GetID (), error.AsCString ());
2731 return SendErrorResponse (0x01);
2732 }
2733
Tamas Berghammere13c2732015-02-11 10:29:30 +00002734 return SendOKResponse ();
2735}
2736
2737GDBRemoteCommunication::PacketResult
2738GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo (StringExtractorGDBRemote &packet)
2739{
2740 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2741
2742 packet.SetFilePos (strlen("qThreadStopInfo"));
2743 const lldb::tid_t tid = packet.GetHexMaxU32 (false, LLDB_INVALID_THREAD_ID);
2744 if (tid == LLDB_INVALID_THREAD_ID)
2745 {
2746 if (log)
2747 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed, could not parse thread id from request \"%s\"", __FUNCTION__, packet.GetStringRef ().c_str ());
2748 return SendErrorResponse (0x15);
2749 }
2750 return SendStopReplyPacketForThread (tid);
2751}
2752
2753GDBRemoteCommunication::PacketResult
Pavel Labath4a4bb122015-07-16 14:14:35 +00002754GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo (StringExtractorGDBRemote &)
2755{
2756 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2757
2758 // Ensure we have a debugged process.
2759 if (!m_debugged_process_sp || (m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID))
2760 return SendErrorResponse (50);
2761
2762 if (log)
2763 log->Printf ("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64,
2764 __FUNCTION__, m_debugged_process_sp->GetID());
2765
Pavel Labath4a4bb122015-07-16 14:14:35 +00002766
2767 StreamString response;
Pavel Labath05569f62015-07-23 09:09:29 +00002768 const bool threads_with_valid_stop_info_only = false;
2769 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(*m_debugged_process_sp,
2770 threads_with_valid_stop_info_only);
2771 if (! threads_array_sp)
2772 {
2773 if (log)
2774 log->Printf ("GDBRemoteCommunicationServerLLGS::%s failed to prepare a packet for pid %" PRIu64,
2775 __FUNCTION__, m_debugged_process_sp->GetID());
2776 return SendErrorResponse(52);
2777 }
2778
2779 threads_array_sp->Write(response);
Pavel Labath4a4bb122015-07-16 14:14:35 +00002780 StreamGDBRemote escaped_response;
2781 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
2782 return SendPacketNoLock (escaped_response.GetData(), escaped_response.GetSize());
2783}
2784
2785GDBRemoteCommunication::PacketResult
Tamas Berghammere13c2732015-02-11 10:29:30 +00002786GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo (StringExtractorGDBRemote &packet)
2787{
2788 // Fail if we don't have a current process.
2789 if (!m_debugged_process_sp ||
2790 m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2791 return SendErrorResponse (68);
2792
2793 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
2794 if (packet.GetBytesLeft() == 0)
2795 return SendOKResponse();
2796 if (packet.GetChar() != ':')
2797 return SendErrorResponse(67);
2798
2799 uint32_t num = m_debugged_process_sp->GetMaxWatchpoints();
2800 StreamGDBRemote response;
2801 response.Printf ("num:%d;", num);
2802 return SendPacketNoLock(response.GetData(), response.GetSize());
2803}
2804
Tamas Berghammer783bfc82015-06-18 20:43:56 +00002805GDBRemoteCommunication::PacketResult
2806GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress (StringExtractorGDBRemote &packet)
2807{
2808 // Fail if we don't have a current process.
2809 if (!m_debugged_process_sp ||
2810 m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2811 return SendErrorResponse(67);
2812
2813 packet.SetFilePos(strlen("qFileLoadAddress:"));
2814 if (packet.GetBytesLeft() == 0)
2815 return SendErrorResponse(68);
2816
2817 std::string file_name;
2818 packet.GetHexByteString(file_name);
2819
2820 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
2821 Error error = m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
2822 if (error.Fail())
2823 return SendErrorResponse(69);
2824
2825 if (file_load_address == LLDB_INVALID_ADDRESS)
2826 return SendErrorResponse(1); // File not loaded
2827
2828 StreamGDBRemote response;
2829 response.PutHex64(file_load_address);
2830 return SendPacketNoLock(response.GetData(), response.GetSize());
2831}
2832
Tamas Berghammere13c2732015-02-11 10:29:30 +00002833void
Tamas Berghammere13c2732015-02-11 10:29:30 +00002834GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection ()
2835{
2836 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2837
Pavel Labathc7749c32015-07-21 13:20:25 +00002838 Mutex::Locker locker(m_stdio_communication_mutex);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002839 // Tell the stdio connection to shut down.
2840 if (m_stdio_communication.IsConnected())
2841 {
2842 auto connection = m_stdio_communication.GetConnection();
2843 if (connection)
2844 {
2845 Error error;
2846 connection->Disconnect (&error);
2847
2848 if (error.Success ())
2849 {
2850 if (log)
2851 log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - SUCCESS", __FUNCTION__);
2852 }
2853 else
2854 {
2855 if (log)
2856 log->Printf ("GDBRemoteCommunicationServerLLGS::%s disconnect process terminal stdio - FAIL: %s", __FUNCTION__, error.AsCString ());
2857 }
2858 }
2859 }
2860}
2861
2862
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002863NativeThreadProtocolSP
Tamas Berghammere13c2732015-02-11 10:29:30 +00002864GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix (StringExtractorGDBRemote &packet)
2865{
2866 NativeThreadProtocolSP thread_sp;
2867
2868 // We have no thread if we don't have a process.
2869 if (!m_debugged_process_sp || m_debugged_process_sp->GetID () == LLDB_INVALID_PROCESS_ID)
2870 return thread_sp;
2871
2872 // If the client hasn't asked for thread suffix support, there will not be a thread suffix.
2873 // Use the current thread in that case.
2874 if (!m_thread_suffix_supported)
2875 {
2876 const lldb::tid_t current_tid = GetCurrentThreadID ();
2877 if (current_tid == LLDB_INVALID_THREAD_ID)
2878 return thread_sp;
2879 else if (current_tid == 0)
2880 {
2881 // Pick a thread.
2882 return m_debugged_process_sp->GetThreadAtIndex (0);
2883 }
2884 else
2885 return m_debugged_process_sp->GetThreadByID (current_tid);
2886 }
2887
2888 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2889
2890 // Parse out the ';'.
2891 if (packet.GetBytesLeft () < 1 || packet.GetChar () != ';')
2892 {
2893 if (log)
2894 log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected ';' prior to start of thread suffix: packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2895 return thread_sp;
2896 }
2897
2898 if (!packet.GetBytesLeft ())
2899 return thread_sp;
2900
2901 // Parse out thread: portion.
2902 if (strncmp (packet.Peek (), "thread:", strlen("thread:")) != 0)
2903 {
2904 if (log)
2905 log->Printf ("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse error: expected 'thread:' but not found, packet contents = '%s'", __FUNCTION__, packet.GetStringRef ().c_str ());
2906 return thread_sp;
2907 }
2908 packet.SetFilePos (packet.GetFilePos () + strlen("thread:"));
2909 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
2910 if (tid != 0)
2911 return m_debugged_process_sp->GetThreadByID (tid);
2912
2913 return thread_sp;
2914}
2915
2916lldb::tid_t
2917GDBRemoteCommunicationServerLLGS::GetCurrentThreadID () const
2918{
2919 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID)
2920 {
2921 // Use whatever the debug process says is the current thread id
2922 // since the protocol either didn't specify or specified we want
2923 // any/all threads marked as the current thread.
2924 if (!m_debugged_process_sp)
2925 return LLDB_INVALID_THREAD_ID;
2926 return m_debugged_process_sp->GetCurrentThreadID ();
2927 }
2928 // Use the specific current thread id set by the gdb remote protocol.
2929 return m_current_tid;
2930}
2931
2932uint32_t
2933GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID ()
2934{
2935 Mutex::Locker locker (m_saved_registers_mutex);
2936 return m_next_saved_registers_id++;
2937}
2938
2939void
2940GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData ()
2941{
2942 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS|GDBR_LOG_PROCESS));
2943 if (log)
2944 log->Printf ("GDBRemoteCommunicationServerLLGS::%s()", __FUNCTION__);
2945
2946 // Clear any auxv cached data.
2947 // *BSD impls should be able to do this too.
2948#if defined(__linux__)
2949 if (log)
2950 log->Printf ("GDBRemoteCommunicationServerLLGS::%s clearing auxv buffer (previously %s)",
2951 __FUNCTION__,
2952 m_active_auxv_buffer_sp ? "was set" : "was not set");
2953 m_active_auxv_buffer_sp.reset ();
2954#endif
2955}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002956
2957FileSpec
2958GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string& module_path,
2959 const ArchSpec& arch)
2960{
2961 if (m_debugged_process_sp)
2962 {
2963 FileSpec file_spec;
2964 if (m_debugged_process_sp->GetLoadedModuleFileSpec(module_path.c_str(), file_spec).Success())
2965 {
2966 if (file_spec.Exists())
2967 return file_spec;
2968 }
2969 }
2970
2971 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
2972}