blob: 754cdb03de5a8ab70d5d9b685cc06546c94f3efb [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
Tamas Berghammere13c2732015-02-11 10:29:30 +000019#include <chrono>
Kate Stoneb9c1b512016-09-06 20:57:50 +000020#include <cstring>
Tamas Berghammere13c2732015-02-11 10:29:30 +000021#include <thread>
22
23// Other libraries and framework includes
Zachary Turner90aff472015-03-03 23:36:51 +000024#include "lldb/Core/DataBuffer.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000025#include "lldb/Core/Log.h"
Tamas Berghammer9c9ecce2015-05-27 13:34:04 +000026#include "lldb/Core/RegisterValue.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000027#include "lldb/Core/State.h"
28#include "lldb/Core/StreamString.h"
29#include "lldb/Host/ConnectionFileDescriptor.h"
30#include "lldb/Host/Debug.h"
31#include "lldb/Host/Endian.h"
32#include "lldb/Host/File.h"
33#include "lldb/Host/FileSystem.h"
34#include "lldb/Host/Host.h"
35#include "lldb/Host/HostInfo.h"
36#include "lldb/Host/StringConvert.h"
Pavel Labath1eb0d422016-08-08 12:54:36 +000037#include "lldb/Host/common/NativeProcessProtocol.h"
38#include "lldb/Host/common/NativeRegisterContext.h"
39#include "lldb/Host/common/NativeThreadProtocol.h"
40#include "lldb/Interpreter/Args.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000041#include "lldb/Target/FileAction.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000042#include "lldb/Target/MemoryRegionInfo.h"
Pavel Labath4a4bb122015-07-16 14:14:35 +000043#include "lldb/Utility/JSON.h"
Pavel Labathabadc222015-11-27 13:33:29 +000044#include "lldb/Utility/LLDBAssert.h"
Pavel Labath1eb0d422016-08-08 12:54:36 +000045#include "llvm/ADT/Triple.h"
46#include "llvm/Support/ScopedPrinter.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000047
48// Project includes
Tamas Berghammere13c2732015-02-11 10:29:30 +000049#include "ProcessGDBRemote.h"
50#include "ProcessGDBRemoteLog.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000051#include "Utility/StringExtractorGDBRemote.h"
52#include "Utility/UriParser.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000053
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
Kate Stoneb9c1b512016-09-06 20:57:50 +000063namespace {
64enum GDBRemoteServerError {
65 // Set to the first unused error number in literal form below
66 eErrorFirst = 29,
67 eErrorNoProcess = eErrorFirst,
68 eErrorResume,
69 eErrorExitStatus
70};
Tamas Berghammere13c2732015-02-11 10:29:30 +000071}
72
73//----------------------------------------------------------------------
74// GDBRemoteCommunicationServerLLGS constructor
75//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000076GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
77 MainLoop &mainloop)
78 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
79 "gdb-remote.server.rx_packet"),
80 m_mainloop(mainloop), m_current_tid(LLDB_INVALID_THREAD_ID),
81 m_continue_tid(LLDB_INVALID_THREAD_ID), m_debugged_process_mutex(),
82 m_debugged_process_sp(), m_stdio_communication("process.stdio"),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000083 m_inferior_prev_state(StateType::eStateInvalid),
Kate Stoneb9c1b512016-09-06 20:57:50 +000084 m_active_auxv_buffer_sp(), m_saved_registers_mutex(),
85 m_saved_registers_map(), m_next_saved_registers_id(1),
86 m_handshake_completed(false) {
87 RegisterPacketHandlers();
Tamas Berghammere13c2732015-02-11 10:29:30 +000088}
89
Kate Stoneb9c1b512016-09-06 20:57:50 +000090void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
91 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
92 &GDBRemoteCommunicationServerLLGS::Handle_C);
93 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
94 &GDBRemoteCommunicationServerLLGS::Handle_c);
95 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
96 &GDBRemoteCommunicationServerLLGS::Handle_D);
97 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
98 &GDBRemoteCommunicationServerLLGS::Handle_H);
99 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
100 &GDBRemoteCommunicationServerLLGS::Handle_I);
101 RegisterMemberFunctionHandler(
102 StringExtractorGDBRemote::eServerPacketType_interrupt,
103 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
104 RegisterMemberFunctionHandler(
105 StringExtractorGDBRemote::eServerPacketType_m,
106 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
107 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
108 &GDBRemoteCommunicationServerLLGS::Handle_M);
109 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
110 &GDBRemoteCommunicationServerLLGS::Handle_p);
111 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
112 &GDBRemoteCommunicationServerLLGS::Handle_P);
113 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
114 &GDBRemoteCommunicationServerLLGS::Handle_qC);
115 RegisterMemberFunctionHandler(
116 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
117 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
118 RegisterMemberFunctionHandler(
119 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
120 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
121 RegisterMemberFunctionHandler(
122 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
123 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
124 RegisterMemberFunctionHandler(
125 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
126 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
127 RegisterMemberFunctionHandler(
128 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
129 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
130 RegisterMemberFunctionHandler(
131 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
132 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
133 RegisterMemberFunctionHandler(
134 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
135 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
136 RegisterMemberFunctionHandler(
137 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
138 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
139 RegisterMemberFunctionHandler(
140 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
141 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
142 RegisterMemberFunctionHandler(
143 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
144 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
145 RegisterMemberFunctionHandler(
146 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
147 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
148 RegisterMemberFunctionHandler(
149 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
150 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
151 RegisterMemberFunctionHandler(
152 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
153 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
154 RegisterMemberFunctionHandler(
155 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
156 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
157 RegisterMemberFunctionHandler(
158 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
159 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
160 RegisterMemberFunctionHandler(
161 StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
162 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
163 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
164 &GDBRemoteCommunicationServerLLGS::Handle_s);
165 RegisterMemberFunctionHandler(
166 StringExtractorGDBRemote::eServerPacketType_stop_reason,
167 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
168 RegisterMemberFunctionHandler(
169 StringExtractorGDBRemote::eServerPacketType_vAttach,
170 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
171 RegisterMemberFunctionHandler(
172 StringExtractorGDBRemote::eServerPacketType_vCont,
173 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
174 RegisterMemberFunctionHandler(
175 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
176 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
177 RegisterMemberFunctionHandler(
178 StringExtractorGDBRemote::eServerPacketType_x,
179 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
180 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
181 &GDBRemoteCommunicationServerLLGS::Handle_Z);
182 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
183 &GDBRemoteCommunicationServerLLGS::Handle_z);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000184
Kate Stoneb9c1b512016-09-06 20:57:50 +0000185 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
186 [this](StringExtractorGDBRemote packet, Error &error,
187 bool &interrupt, bool &quit) {
188 quit = true;
189 return this->Handle_k(packet);
190 });
Tamas Berghammere13c2732015-02-11 10:29:30 +0000191}
192
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193Error GDBRemoteCommunicationServerLLGS::SetLaunchArguments(
194 const char *const args[], int argc) {
195 if ((argc < 1) || !args || !args[0] || !args[0][0])
196 return Error("%s: no process command line specified to launch",
197 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 m_process_launch_info.SetArguments(const_cast<const char **>(args), true);
200 return Error();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000201}
202
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203Error GDBRemoteCommunicationServerLLGS::SetLaunchFlags(
204 unsigned int launch_flags) {
205 m_process_launch_info.GetFlags().Set(launch_flags);
206 return Error();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000207}
208
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209Error GDBRemoteCommunicationServerLLGS::LaunchProcess() {
210 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000211
Kate Stoneb9c1b512016-09-06 20:57:50 +0000212 if (!m_process_launch_info.GetArguments().GetArgumentCount())
213 return Error("%s: no process command line specified to launch",
214 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000215
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216 const bool should_forward_stdio =
217 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
218 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
219 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
220 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
221 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
Pavel Labath5ad891f2016-07-21 14:54:03 +0000222
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 const bool default_to_use_pty = true;
224 m_process_launch_info.FinalizeFileActions(nullptr, default_to_use_pty);
Pavel Labath5ad891f2016-07-21 14:54:03 +0000225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226 Error error;
227 {
228 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
229 assert(!m_debugged_process_sp && "lldb-server creating debugged "
230 "process but one already exists");
231 error = NativeProcessProtocol::Launch(m_process_launch_info, *this,
232 m_mainloop, m_debugged_process_sp);
233 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000234
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235 if (!error.Success()) {
236 fprintf(stderr, "%s: failed to launch executable %s", __FUNCTION__,
237 m_process_launch_info.GetArguments().GetArgumentAtIndex(0));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000238 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000240
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
242 // as needed.
243 // llgs local-process debugging may specify PTY paths, which will make these
244 // file actions non-null
245 // process launch -i/e/o will also make these file actions non-null
246 // nullptr means that the traffic is expected to flow over gdb-remote protocol
247 if (should_forward_stdio) {
248 // nullptr means it's not redirected to file or pty (in case of LLGS local)
249 // at least one of stdio will be transferred pty<->gdb-remote
250 // we need to give the pty master handle to this object to read and/or write
Tamas Berghammere13c2732015-02-11 10:29:30 +0000251 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252 log->Printf(
253 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
254 " setting up stdout/stderr redirection via $O gdb-remote commands",
255 __FUNCTION__, m_debugged_process_sp->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000256
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257 // Setup stdout/stderr mapping from inferior to $O
258 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
259 if (terminal_fd >= 0) {
260 if (log)
261 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
262 "inferior STDIO fd to %d",
263 __FUNCTION__, terminal_fd);
264 error = SetSTDIOFileDescriptor(terminal_fd);
265 if (error.Fail())
Tamas Berghammere13c2732015-02-11 10:29:30 +0000266 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267 } else {
268 if (log)
269 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
270 "inferior STDIO since terminal fd reported as %d",
271 __FUNCTION__, terminal_fd);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000272 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000273 } else {
274 if (log)
275 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
276 " skipping stdout/stderr redirection via $O: inferior will "
277 "communicate over client-provided file descriptors",
278 __FUNCTION__, m_debugged_process_sp->GetID());
279 }
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000280
Kate Stoneb9c1b512016-09-06 20:57:50 +0000281 printf("Launched '%s' as process %" PRIu64 "...\n",
282 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
283 m_process_launch_info.GetProcessID());
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000284
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285 return error;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000286}
287
Kate Stoneb9c1b512016-09-06 20:57:50 +0000288Error GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
289 Error error;
290
291 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
292 if (log)
293 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
294 __FUNCTION__, pid);
295
296 // Before we try to attach, make sure we aren't already monitoring something
297 // else.
298 if (m_debugged_process_sp &&
299 m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID)
300 return Error("cannot attach to a process %" PRIu64
301 " when another process with pid %" PRIu64
302 " is being debugged.",
303 pid, m_debugged_process_sp->GetID());
304
305 // Try to attach.
306 error = NativeProcessProtocol::Attach(pid, *this, m_mainloop,
307 m_debugged_process_sp);
308 if (!error.Success()) {
309 fprintf(stderr, "%s: failed to attach to process %" PRIu64 ": %s",
310 __FUNCTION__, pid, error.AsCString());
311 return error;
312 }
313
314 // Setup stdout/stderr mapping from inferior.
315 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
316 if (terminal_fd >= 0) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000317 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000318 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
319 "inferior STDIO fd to %d",
320 __FUNCTION__, terminal_fd);
321 error = SetSTDIOFileDescriptor(terminal_fd);
322 if (error.Fail())
323 return error;
324 } else {
325 if (log)
326 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
327 "inferior STDIO since terminal fd reported as %d",
328 __FUNCTION__, terminal_fd);
329 }
330
331 printf("Attached to process %" PRIu64 "...\n", pid);
332
333 return error;
334}
335
336void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
337 NativeProcessProtocol *process) {
338 assert(process && "process cannot be NULL");
339 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
340 if (log) {
341 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
342 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
343 __FUNCTION__, process->GetID(),
344 StateAsCString(process->GetState()));
345 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000346}
347
348GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349GDBRemoteCommunicationServerLLGS::SendWResponse(
350 NativeProcessProtocol *process) {
351 assert(process && "process cannot be NULL");
352 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000353
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 // send W notification
355 ExitType exit_type = ExitType::eExitTypeInvalid;
356 int return_code = 0;
357 std::string exit_description;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000358
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 const bool got_exit_info =
360 process->GetExitStatus(&exit_type, &return_code, exit_description);
361 if (!got_exit_info) {
362 if (log)
363 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
364 ", failed to retrieve process exit status",
365 __FUNCTION__, process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000366
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 StreamGDBRemote response;
368 response.PutChar('E');
369 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
370 return SendPacketNoLock(response.GetString());
371 } else {
372 if (log)
373 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
374 ", returning exit type %d, return code %d [%s]",
375 __FUNCTION__, process->GetID(), exit_type, return_code,
376 exit_description.c_str());
377
378 StreamGDBRemote response;
379
380 char return_type_code;
381 switch (exit_type) {
382 case ExitType::eExitTypeExit:
383 return_type_code = 'W';
384 break;
385 case ExitType::eExitTypeSignal:
386 return_type_code = 'X';
387 break;
388 case ExitType::eExitTypeStop:
389 return_type_code = 'S';
390 break;
391 case ExitType::eExitTypeInvalid:
392 return_type_code = 'E';
393 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000394 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 response.PutChar(return_type_code);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 // POSIX exit status limited to unsigned 8 bits.
398 response.PutHex8(return_code);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000399
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 return SendPacketNoLock(response.GetString());
401 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000402}
403
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404static void AppendHexValue(StreamString &response, const uint8_t *buf,
405 uint32_t buf_size, bool swap) {
406 int64_t i;
407 if (swap) {
408 for (i = buf_size - 1; i >= 0; i--)
409 response.PutHex8(buf[i]);
410 } else {
411 for (i = 0; i < buf_size; i++)
412 response.PutHex8(buf[i]);
413 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000414}
415
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416static void WriteRegisterValueInHexFixedWidth(
417 StreamString &response, NativeRegisterContextSP &reg_ctx_sp,
418 const RegisterInfo &reg_info, const RegisterValue *reg_value_p) {
419 RegisterValue reg_value;
420 if (!reg_value_p) {
421 Error error = reg_ctx_sp->ReadRegister(&reg_info, reg_value);
422 if (error.Success())
423 reg_value_p = &reg_value;
424 // else log.
425 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000426
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427 if (reg_value_p) {
428 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
429 reg_value_p->GetByteSize(), false);
430 } else {
431 // Zero-out any unreadable values.
432 if (reg_info.byte_size > 0) {
433 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
434 AppendHexValue(response, zeros.data(), zeros.size(), false);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000435 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000437}
438
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread,
440 bool abridged) {
441 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Pavel Labath4a4bb122015-07-16 14:14:35 +0000442
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
444 if (!reg_ctx_sp)
445 return nullptr;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000446
Kate Stoneb9c1b512016-09-06 20:57:50 +0000447 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000448
449#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 // Expedite all registers in the first register set (i.e. should be GPRs) that
451 // are not contained in other registers.
452 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
453 if (!reg_set_p)
454 return nullptr;
455 for (const uint32_t *reg_num_p = reg_set_p->registers;
456 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
457 uint32_t reg_num = *reg_num_p;
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000458#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459 // Expedite only a couple of registers until we figure out why sending
460 // registers is
461 // expensive.
462 static const uint32_t k_expedited_registers[] = {
463 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
464 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
465 static const uint32_t k_abridged_expedited_registers[] = {
466 LLDB_REGNUM_GENERIC_PC, LLDB_INVALID_REGNUM};
Pavel Labathc4645bb2015-10-26 16:25:28 +0000467
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468 for (const uint32_t *generic_reg_p = abridged ? k_abridged_expedited_registers
469 : k_expedited_registers;
470 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
471 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
472 eRegisterKindGeneric, *generic_reg_p);
473 if (reg_num == LLDB_INVALID_REGNUM)
474 continue; // Target does not support the given register.
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000475#endif
476
Kate Stoneb9c1b512016-09-06 20:57:50 +0000477 const RegisterInfo *const reg_info_p =
478 reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
479 if (reg_info_p == nullptr) {
480 if (log)
481 log->Printf(
482 "%s failed to get register info for register index %" PRIu32,
483 __FUNCTION__, reg_num);
484 continue;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000485 }
486
Kate Stoneb9c1b512016-09-06 20:57:50 +0000487 if (reg_info_p->value_regs != nullptr)
488 continue; // Only expedite registers that are not contained in other
489 // registers.
Pavel Labath4a4bb122015-07-16 14:14:35 +0000490
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491 RegisterValue reg_value;
492 Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
493 if (error.Fail()) {
494 if (log)
495 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
Pavel Labath05569f62015-07-23 09:09:29 +0000496 __FUNCTION__,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
498 reg_num, error.AsCString());
499 continue;
Pavel Labath05569f62015-07-23 09:09:29 +0000500 }
501
Kate Stoneb9c1b512016-09-06 20:57:50 +0000502 StreamString stream;
503 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p,
504 &reg_value);
505
506 register_object_sp->SetObject(
507 llvm::to_string(reg_num),
508 std::make_shared<JSONString>(stream.GetString()));
509 }
510
511 return register_object_sp;
Pavel Labath05569f62015-07-23 09:09:29 +0000512}
513
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514static const char *GetStopReasonString(StopReason stop_reason) {
515 switch (stop_reason) {
516 case eStopReasonTrace:
517 return "trace";
518 case eStopReasonBreakpoint:
519 return "breakpoint";
520 case eStopReasonWatchpoint:
521 return "watchpoint";
522 case eStopReasonSignal:
523 return "signal";
524 case eStopReasonException:
525 return "exception";
526 case eStopReasonExec:
527 return "exec";
528 case eStopReasonInstrumentation:
529 case eStopReasonInvalid:
530 case eStopReasonPlanComplete:
531 case eStopReasonThreadExiting:
532 case eStopReasonNone:
533 break; // ignored
534 }
535 return nullptr;
536}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000537
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
539 bool abridged) {
540 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000541
Kate Stoneb9c1b512016-09-06 20:57:50 +0000542 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000543
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 // Ensure we can get info on the given thread.
545 uint32_t thread_idx = 0;
546 for (NativeThreadProtocolSP thread_sp;
547 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
548 ++thread_idx) {
549
550 lldb::tid_t tid = thread_sp->GetID();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000551
552 // Grab the reason this thread stopped.
553 struct ThreadStopInfo tid_stop_info;
554 std::string description;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 if (!thread_sp->GetStopReason(tid_stop_info, description))
556 return nullptr;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000557
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 const int signum = tid_stop_info.details.signal.signo;
559 if (log) {
560 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
561 " tid %" PRIu64
562 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
563 __FUNCTION__, process.GetID(), tid, signum,
564 tid_stop_info.reason, tid_stop_info.details.exception.type);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000565 }
566
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
568 threads_array_sp->AppendObject(thread_obj_sp);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000569
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp, abridged))
571 thread_obj_sp->SetObject("registers", registers_sp);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000572
Kate Stoneb9c1b512016-09-06 20:57:50 +0000573 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
574 if (signum != 0)
575 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000576
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577 const std::string thread_name = thread_sp->GetName();
578 if (!thread_name.empty())
579 thread_obj_sp->SetObject("name",
580 std::make_shared<JSONString>(thread_name));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000581
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
583 thread_obj_sp->SetObject("reason",
584 std::make_shared<JSONString>(stop_reason_str));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000585
586 if (!description.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000587 thread_obj_sp->SetObject("description",
588 std::make_shared<JSONString>(description));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000589
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590 if ((tid_stop_info.reason == eStopReasonException) &&
591 tid_stop_info.details.exception.type) {
592 thread_obj_sp->SetObject(
593 "metype",
594 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
595
596 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
597 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
598 ++i) {
599 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
600 tid_stop_info.details.exception.data[i]));
601 }
602 thread_obj_sp->SetObject("medata", medata_array_sp);
603 }
604
605 // TODO: Expedite interesting regions of inferior memory
606 }
607
608 return threads_array_sp;
609}
610
611GDBRemoteCommunication::PacketResult
612GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
613 lldb::tid_t tid) {
614 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
615
616 // Ensure we have a debugged process.
617 if (!m_debugged_process_sp ||
618 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
619 return SendErrorResponse(50);
620
621 if (log)
622 log->Printf(
623 "GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64
624 " tid %" PRIu64,
625 __FUNCTION__, m_debugged_process_sp->GetID(), tid);
626
627 // Ensure we can get info on the given thread.
628 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
629 if (!thread_sp)
630 return SendErrorResponse(51);
631
632 // Grab the reason this thread stopped.
633 struct ThreadStopInfo tid_stop_info;
634 std::string description;
635 if (!thread_sp->GetStopReason(tid_stop_info, description))
636 return SendErrorResponse(52);
637
638 // FIXME implement register handling for exec'd inferiors.
639 // if (tid_stop_info.reason == eStopReasonExec)
640 // {
641 // const bool force = true;
642 // InitializeRegisters(force);
643 // }
644
645 StreamString response;
646 // Output the T packet with the thread
647 response.PutChar('T');
648 int signum = tid_stop_info.details.signal.signo;
649 if (log) {
650 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
651 " tid %" PRIu64
652 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
653 __FUNCTION__, m_debugged_process_sp->GetID(), tid, signum,
654 tid_stop_info.reason, tid_stop_info.details.exception.type);
655 }
656
657 // Print the signal number.
658 response.PutHex8(signum & 0xff);
659
660 // Include the tid.
661 response.Printf("thread:%" PRIx64 ";", tid);
662
663 // Include the thread name if there is one.
664 const std::string thread_name = thread_sp->GetName();
665 if (!thread_name.empty()) {
666 size_t thread_name_len = thread_name.length();
667
668 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
669 response.PutCString("name:");
670 response.PutCString(thread_name.c_str());
671 } else {
672 // The thread name contains special chars, send as hex bytes.
673 response.PutCString("hexname:");
674 response.PutCStringAsRawHex8(thread_name.c_str());
675 }
676 response.PutChar(';');
677 }
678
679 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
680 // will send all thread IDs back in the "threads" key whose value is
681 // a list of hex thread IDs separated by commas:
682 // "threads:10a,10b,10c;"
683 // This will save the debugger from having to send a pair of qfThreadInfo
684 // and qsThreadInfo packets, but it also might take a lot of room in the
685 // stop reply packet, so it must be enabled only on systems where there
686 // are no limits on packet lengths.
687 if (m_list_threads_in_stop_reply) {
688 response.PutCString("threads:");
689
690 uint32_t thread_index = 0;
691 NativeThreadProtocolSP listed_thread_sp;
692 for (listed_thread_sp =
693 m_debugged_process_sp->GetThreadAtIndex(thread_index);
694 listed_thread_sp; ++thread_index,
695 listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex(
696 thread_index)) {
697 if (thread_index > 0)
698 response.PutChar(',');
699 response.Printf("%" PRIx64, listed_thread_sp->GetID());
700 }
701 response.PutChar(';');
702
703 // Include JSON info that describes the stop reason for any threads
704 // that actually have stop reasons. We use the new "jstopinfo" key
705 // whose values is hex ascii JSON that contains the thread IDs
706 // thread stop info only for threads that have stop reasons. Only send
707 // this if we have more than one thread otherwise this packet has all
708 // the info it needs.
709 if (thread_index > 0) {
710 const bool threads_with_valid_stop_info_only = true;
711 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
712 *m_debugged_process_sp, threads_with_valid_stop_info_only);
713 if (threads_info_sp) {
714 response.PutCString("jstopinfo:");
715 StreamString unescaped_response;
716 threads_info_sp->Write(unescaped_response);
717 response.PutCStringAsRawHex8(unescaped_response.GetData());
718 response.PutChar(';');
719 } else if (log)
720 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
721 "jstopinfo field for pid %" PRIu64,
722 __FUNCTION__, m_debugged_process_sp->GetID());
723 }
724 }
725
726 //
727 // Expedite registers.
728 //
729
730 // Grab the register context.
731 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
732 if (reg_ctx_sp) {
733 // Expedite all registers in the first register set (i.e. should be GPRs)
734 // that are not contained in other registers.
735 const RegisterSet *reg_set_p;
736 if (reg_ctx_sp->GetRegisterSetCount() > 0 &&
737 ((reg_set_p = reg_ctx_sp->GetRegisterSet(0)) != nullptr)) {
738 if (log)
739 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
740 "from set '%s' (registers set count: %zu)",
741 __FUNCTION__,
742 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
743 reg_set_p->num_registers);
744
745 for (const uint32_t *reg_num_p = reg_set_p->registers;
746 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
747 const RegisterInfo *const reg_info_p =
748 reg_ctx_sp->GetRegisterInfoAtIndex(*reg_num_p);
749 if (reg_info_p == nullptr) {
750 if (log)
751 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
752 "register info for register set '%s', register index "
753 "%" PRIu32,
754 __FUNCTION__,
755 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
756 *reg_num_p);
757 } else if (reg_info_p->value_regs == nullptr) {
758 // Only expediate registers that are not contained in other registers.
759 RegisterValue reg_value;
760 Error error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
761 if (error.Success()) {
762 response.Printf("%.02x:", *reg_num_p);
763 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
764 &reg_value);
765 response.PutChar(';');
766 } else {
767 if (log)
768 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
769 "register '%s' index %" PRIu32 ": %s",
770 __FUNCTION__, reg_info_p->name ? reg_info_p->name
771 : "<unnamed-register>",
772 *reg_num_p, error.AsCString());
773 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000774 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000776 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000778
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
780 if (reason_str != nullptr) {
781 response.Printf("reason:%s;", reason_str);
782 }
783
784 if (!description.empty()) {
785 // Description may contains special chars, send as hex bytes.
786 response.PutCString("description:");
787 response.PutCStringAsRawHex8(description.c_str());
788 response.PutChar(';');
789 } else if ((tid_stop_info.reason == eStopReasonException) &&
790 tid_stop_info.details.exception.type) {
791 response.PutCString("metype:");
792 response.PutHex64(tid_stop_info.details.exception.type);
793 response.PutCString(";mecount:");
794 response.PutHex32(tid_stop_info.details.exception.data_count);
795 response.PutChar(';');
796
797 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
798 response.PutCString("medata:");
799 response.PutHex64(tid_stop_info.details.exception.data[i]);
800 response.PutChar(';');
801 }
802 }
803
804 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000805}
806
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
808 NativeProcessProtocol *process) {
809 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000810
Kate Stoneb9c1b512016-09-06 20:57:50 +0000811 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
812 if (log)
813 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
814
815 PacketResult result = SendStopReasonForState(StateType::eStateExited);
816 if (result != PacketResult::Success) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000817 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
819 "notification for PID %" PRIu64 ", state: eStateExited",
820 __FUNCTION__, process->GetID());
821 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000822
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 // Close the pipe to the inferior terminal i/o if we launched it
824 // and set one up.
825 MaybeCloseInferiorTerminalConnection();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000826
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 // We are ready to exit the debug monitor.
828 m_exit_now = true;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000829}
830
Kate Stoneb9c1b512016-09-06 20:57:50 +0000831void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
832 NativeProcessProtocol *process) {
833 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000834
Kate Stoneb9c1b512016-09-06 20:57:50 +0000835 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
836 if (log)
837 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000838
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 // Send the stop reason unless this is the stop after the
840 // launch or attach.
841 switch (m_inferior_prev_state) {
842 case eStateLaunching:
843 case eStateAttaching:
844 // Don't send anything per debugserver behavior.
845 break;
846 default:
847 // In all other cases, send the stop reason.
848 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
849 if (result != PacketResult::Success) {
850 if (log)
851 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
852 "notification for PID %" PRIu64 ", state: eStateExited",
853 __FUNCTION__, process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000854 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855 break;
856 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000857}
858
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
860 NativeProcessProtocol *process, lldb::StateType state) {
861 assert(process && "process cannot be NULL");
862 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
863 if (log) {
864 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
865 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
866 __FUNCTION__, process->GetID(), StateAsCString(state));
867 }
868
869 switch (state) {
870 case StateType::eStateRunning:
871 StartSTDIOForwarding();
872 break;
873
874 case StateType::eStateStopped:
875 // Make sure we get all of the pending stdout/stderr from the inferior
876 // and send it to the lldb host before we send the state change
877 // notification
878 SendProcessOutput();
879 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
880 // does not
881 // interfere with our protocol.
882 StopSTDIOForwarding();
883 HandleInferiorState_Stopped(process);
884 break;
885
886 case StateType::eStateExited:
887 // Same as above
888 SendProcessOutput();
889 StopSTDIOForwarding();
890 HandleInferiorState_Exited(process);
891 break;
892
893 default:
894 if (log) {
895 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
896 "change for pid %" PRIu64 ", new state: %s",
897 __FUNCTION__, process->GetID(), StateAsCString(state));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000898 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000899 break;
900 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000901
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902 // Remember the previous state reported to us.
903 m_inferior_prev_state = state;
904}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000905
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
907 ClearProcessSpecificData();
908}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000909
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
911 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
912
913 if (!m_handshake_completed) {
914 if (!HandshakeWithClient()) {
915 if (log)
916 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
917 "client failed, exiting",
918 __FUNCTION__);
919 m_mainloop.RequestTermination();
920 return;
921 }
922 m_handshake_completed = true;
923 }
924
925 bool interrupt = false;
926 bool done = false;
927 Error error;
928 while (true) {
929 const PacketResult result =
930 GetPacketAndSendResponse(0, error, interrupt, done);
931 if (result == PacketResult::ErrorReplyTimeout)
932 break; // No more packets in the queue
933
934 if ((result != PacketResult::Success)) {
935 if (log)
936 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
937 "failed: %s",
938 __FUNCTION__, error.AsCString());
939 m_mainloop.RequestTermination();
940 break;
941 }
942 }
943}
944
945Error GDBRemoteCommunicationServerLLGS::InitializeConnection(
946 std::unique_ptr<Connection> &&connection) {
947 IOObjectSP read_object_sp = connection->GetReadObject();
948 GDBRemoteCommunicationServer::SetConnection(connection.release());
949
950 Error error;
951 m_network_handle_up = m_mainloop.RegisterReadObject(
952 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
953 error);
954 return error;
955}
956
957GDBRemoteCommunication::PacketResult
958GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
959 uint32_t len) {
960 if ((buffer == nullptr) || (len == 0)) {
961 // Nothing to send.
962 return PacketResult::Success;
963 }
964
965 StreamString response;
966 response.PutChar('O');
967 response.PutBytesAsRawHex8(buffer, len);
968
969 return SendPacketNoLock(response.GetString());
970}
971
972Error GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
973 Error error;
974
975 // Set up the reading/handling of process I/O
976 std::unique_ptr<ConnectionFileDescriptor> conn_up(
977 new ConnectionFileDescriptor(fd, true));
978 if (!conn_up) {
979 error.SetErrorString("failed to create ConnectionFileDescriptor");
980 return error;
981 }
982
983 m_stdio_communication.SetCloseOnEOF(false);
984 m_stdio_communication.SetConnection(conn_up.release());
985 if (!m_stdio_communication.IsConnected()) {
986 error.SetErrorString(
987 "failed to set connection for inferior I/O communication");
988 return error;
989 }
990
991 return Error();
992}
993
994void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
995 // Don't forward if not connected (e.g. when attaching).
996 if (!m_stdio_communication.IsConnected())
997 return;
998
999 Error error;
1000 lldbassert(!m_stdio_handle_up);
1001 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1002 m_stdio_communication.GetConnection()->GetReadObject(),
1003 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1004
1005 if (!m_stdio_handle_up) {
1006 // Not much we can do about the failure. Log it and continue without
1007 // forwarding.
1008 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1009 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1010 "forwarding: %s",
1011 __FUNCTION__, error.AsCString());
1012 }
1013}
1014
1015void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1016 m_stdio_handle_up.reset();
1017}
1018
1019void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1020 char buffer[1024];
1021 ConnectionStatus status;
1022 Error error;
1023 while (true) {
1024 size_t bytes_read =
1025 m_stdio_communication.Read(buffer, sizeof buffer, 0, status, &error);
1026 switch (status) {
1027 case eConnectionStatusSuccess:
1028 SendONotification(buffer, bytes_read);
1029 break;
1030 case eConnectionStatusLostConnection:
1031 case eConnectionStatusEndOfFile:
1032 case eConnectionStatusError:
1033 case eConnectionStatusNoConnection:
1034 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1035 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1036 "forwarding as communication returned status %d (error: "
1037 "%s)",
1038 __FUNCTION__, status, error.AsCString());
1039 m_stdio_handle_up.reset();
1040 return;
1041
1042 case eConnectionStatusInterrupted:
1043 case eConnectionStatusTimedOut:
1044 return;
1045 }
1046 }
1047}
1048
1049GDBRemoteCommunication::PacketResult
1050GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1051 StringExtractorGDBRemote &packet) {
1052 // Fail if we don't have a current process.
1053 if (!m_debugged_process_sp ||
1054 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1055 return SendErrorResponse(68);
1056
1057 lldb::pid_t pid = m_debugged_process_sp->GetID();
1058
1059 if (pid == LLDB_INVALID_PROCESS_ID)
1060 return SendErrorResponse(1);
1061
1062 ProcessInstanceInfo proc_info;
1063 if (!Host::GetProcessInfo(pid, proc_info))
1064 return SendErrorResponse(1);
1065
1066 StreamString response;
1067 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1068 return SendPacketNoLock(response.GetString());
1069}
1070
1071GDBRemoteCommunication::PacketResult
1072GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1073 // Fail if we don't have a current process.
1074 if (!m_debugged_process_sp ||
1075 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1076 return SendErrorResponse(68);
1077
1078 // Make sure we set the current thread so g and p packets return
1079 // the data the gdb will expect.
1080 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1081 SetCurrentThreadID(tid);
1082
1083 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread();
1084 if (!thread_sp)
1085 return SendErrorResponse(69);
1086
1087 StreamString response;
1088 response.Printf("QC%" PRIx64, thread_sp->GetID());
1089
1090 return SendPacketNoLock(response.GetString());
1091}
1092
1093GDBRemoteCommunication::PacketResult
1094GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1095 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1096
1097 StopSTDIOForwarding();
1098
1099 if (!m_debugged_process_sp) {
1100 if (log)
1101 log->Printf(
1102 "GDBRemoteCommunicationServerLLGS::%s No debugged process found.",
1103 __FUNCTION__);
1104 return PacketResult::Success;
1105 }
1106
1107 Error error = m_debugged_process_sp->Kill();
1108 if (error.Fail() && log)
1109 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged "
1110 "process %" PRIu64 ": %s",
1111 __FUNCTION__, m_debugged_process_sp->GetID(),
1112 error.AsCString());
1113
1114 // No OK response for kill packet.
1115 // return SendOKResponse ();
1116 return PacketResult::Success;
1117}
1118
1119GDBRemoteCommunication::PacketResult
1120GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1121 StringExtractorGDBRemote &packet) {
1122 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1123 if (packet.GetU32(0))
1124 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1125 else
1126 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1127 return SendOKResponse();
1128}
1129
1130GDBRemoteCommunication::PacketResult
1131GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1132 StringExtractorGDBRemote &packet) {
1133 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1134 std::string path;
1135 packet.GetHexByteString(path);
1136 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1137 return SendOKResponse();
1138}
1139
1140GDBRemoteCommunication::PacketResult
1141GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1142 StringExtractorGDBRemote &packet) {
1143 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1144 if (working_dir) {
1145 StreamString response;
1146 response.PutCStringAsRawHex8(working_dir.GetCString());
1147 return SendPacketNoLock(response.GetString());
1148 }
1149
1150 return SendErrorResponse(14);
1151}
1152
1153GDBRemoteCommunication::PacketResult
1154GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1155 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1156 if (log)
1157 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1158
1159 // Ensure we have a native process.
1160 if (!m_debugged_process_sp) {
1161 if (log)
1162 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1163 "shared pointer",
1164 __FUNCTION__);
1165 return SendErrorResponse(0x36);
1166 }
1167
1168 // Pull out the signal number.
1169 packet.SetFilePos(::strlen("C"));
1170 if (packet.GetBytesLeft() < 1) {
1171 // Shouldn't be using a C without a signal.
1172 return SendIllFormedResponse(packet, "C packet specified without signal.");
1173 }
1174 const uint32_t signo =
1175 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1176 if (signo == std::numeric_limits<uint32_t>::max())
1177 return SendIllFormedResponse(packet, "failed to parse signal number");
1178
1179 // Handle optional continue address.
1180 if (packet.GetBytesLeft() > 0) {
1181 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1182 if (*packet.Peek() == ';')
1183 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1184 else
1185 return SendIllFormedResponse(
1186 packet, "unexpected content after $C{signal-number}");
1187 }
1188
1189 ResumeActionList resume_actions(StateType::eStateRunning, 0);
1190 Error error;
1191
1192 // We have two branches: what to do if a continue thread is specified (in
1193 // which case we target
1194 // sending the signal to that thread), or when we don't have a continue thread
1195 // set (in which
1196 // case we send a signal to the process).
1197
1198 // TODO discuss with Greg Clayton, make sure this makes sense.
1199
1200 lldb::tid_t signal_tid = GetContinueThreadID();
1201 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1202 // The resume action for the continue thread (or all threads if a continue
1203 // thread is not set).
1204 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1205 static_cast<int>(signo)};
1206
1207 // Add the action for the continue thread (or all threads when the continue
1208 // thread isn't present).
1209 resume_actions.Append(action);
1210 } else {
1211 // Send the signal to the process since we weren't targeting a specific
1212 // continue thread with the signal.
1213 error = m_debugged_process_sp->Signal(signo);
1214 if (error.Fail()) {
1215 if (log)
1216 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send "
1217 "signal for process %" PRIu64 ": %s",
1218 __FUNCTION__, m_debugged_process_sp->GetID(),
1219 error.AsCString());
1220
1221 return SendErrorResponse(0x52);
1222 }
1223 }
1224
1225 // Resume the threads.
1226 error = m_debugged_process_sp->Resume(resume_actions);
1227 if (error.Fail()) {
1228 if (log)
1229 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to resume "
1230 "threads for process %" PRIu64 ": %s",
1231 __FUNCTION__, m_debugged_process_sp->GetID(),
1232 error.AsCString());
1233
1234 return SendErrorResponse(0x38);
1235 }
1236
1237 // Don't send an "OK" packet; response is the stopped/exited message.
1238 return PacketResult::Success;
1239}
1240
1241GDBRemoteCommunication::PacketResult
1242GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1243 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1244 if (log)
1245 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1246
1247 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1248
1249 // For now just support all continue.
1250 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1251 if (has_continue_address) {
1252 if (log)
1253 log->Printf("GDBRemoteCommunicationServerLLGS::%s not implemented for "
1254 "c{address} variant [%s remains]",
1255 __FUNCTION__, packet.Peek());
1256 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1257 }
1258
1259 // Ensure we have a native process.
1260 if (!m_debugged_process_sp) {
1261 if (log)
1262 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1263 "shared pointer",
1264 __FUNCTION__);
1265 return SendErrorResponse(0x36);
1266 }
1267
1268 // Build the ResumeActionList
1269 ResumeActionList actions(StateType::eStateRunning, 0);
1270
1271 Error error = m_debugged_process_sp->Resume(actions);
1272 if (error.Fail()) {
1273 if (log) {
1274 log->Printf(
1275 "GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64
1276 ": %s",
1277 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1278 }
1279 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1280 }
1281
1282 if (log)
1283 log->Printf(
1284 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1285 __FUNCTION__, m_debugged_process_sp->GetID());
1286
1287 // No response required from continue.
1288 return PacketResult::Success;
1289}
1290
1291GDBRemoteCommunication::PacketResult
1292GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1293 StringExtractorGDBRemote &packet) {
1294 StreamString response;
1295 response.Printf("vCont;c;C;s;S");
1296
1297 return SendPacketNoLock(response.GetString());
1298}
1299
1300GDBRemoteCommunication::PacketResult
1301GDBRemoteCommunicationServerLLGS::Handle_vCont(
1302 StringExtractorGDBRemote &packet) {
1303 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1304 if (log)
1305 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1306 __FUNCTION__);
1307
1308 packet.SetFilePos(::strlen("vCont"));
1309
1310 if (packet.GetBytesLeft() == 0) {
1311 if (log)
1312 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1313 "vCont package",
1314 __FUNCTION__);
1315 return SendIllFormedResponse(packet, "Missing action from vCont package");
1316 }
1317
1318 // Check if this is all continue (no options or ";c").
1319 if (::strcmp(packet.Peek(), ";c") == 0) {
1320 // Move past the ';', then do a simple 'c'.
1321 packet.SetFilePos(packet.GetFilePos() + 1);
1322 return Handle_c(packet);
1323 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1324 // Move past the ';', then do a simple 's'.
1325 packet.SetFilePos(packet.GetFilePos() + 1);
1326 return Handle_s(packet);
1327 }
1328
1329 // Ensure we have a native process.
1330 if (!m_debugged_process_sp) {
1331 if (log)
1332 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1333 "shared pointer",
1334 __FUNCTION__);
1335 return SendErrorResponse(0x36);
1336 }
1337
1338 ResumeActionList thread_actions;
1339
1340 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1341 // Skip the semi-colon.
1342 packet.GetChar();
1343
1344 // Build up the thread action.
1345 ResumeAction thread_action;
1346 thread_action.tid = LLDB_INVALID_THREAD_ID;
1347 thread_action.state = eStateInvalid;
1348 thread_action.signal = 0;
1349
1350 const char action = packet.GetChar();
1351 switch (action) {
1352 case 'C':
1353 thread_action.signal = packet.GetHexMaxU32(false, 0);
1354 if (thread_action.signal == 0)
1355 return SendIllFormedResponse(
1356 packet, "Could not parse signal in vCont packet C action");
1357 LLVM_FALLTHROUGH;
1358
1359 case 'c':
1360 // Continue
1361 thread_action.state = eStateRunning;
1362 break;
1363
1364 case 'S':
1365 thread_action.signal = packet.GetHexMaxU32(false, 0);
1366 if (thread_action.signal == 0)
1367 return SendIllFormedResponse(
1368 packet, "Could not parse signal in vCont packet S action");
1369 LLVM_FALLTHROUGH;
1370
1371 case 's':
1372 // Step
1373 thread_action.state = eStateStepping;
1374 break;
Pavel Labathabadc222015-11-27 13:33:29 +00001375
Tamas Berghammere13c2732015-02-11 10:29:30 +00001376 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001377 return SendIllFormedResponse(packet, "Unsupported vCont action");
1378 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00001379 }
1380
Kate Stoneb9c1b512016-09-06 20:57:50 +00001381 // Parse out optional :{thread-id} value.
1382 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1383 // Consume the separator.
1384 packet.GetChar();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001385
Kate Stoneb9c1b512016-09-06 20:57:50 +00001386 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1387 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1388 return SendIllFormedResponse(
1389 packet, "Could not parse thread number in vCont packet");
Pavel Labath77dc9562015-07-13 10:44:55 +00001390 }
1391
Kate Stoneb9c1b512016-09-06 20:57:50 +00001392 thread_actions.Append(thread_action);
1393 }
Pavel Labath77dc9562015-07-13 10:44:55 +00001394
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395 Error error = m_debugged_process_sp->Resume(thread_actions);
1396 if (error.Fail()) {
1397 if (log) {
1398 log->Printf("GDBRemoteCommunicationServerLLGS::%s vCont failed for "
1399 "process %" PRIu64 ": %s",
1400 __FUNCTION__, m_debugged_process_sp->GetID(),
1401 error.AsCString());
Pavel Labath77dc9562015-07-13 10:44:55 +00001402 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001403 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1404 }
1405
1406 if (log)
1407 log->Printf(
1408 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1409 __FUNCTION__, m_debugged_process_sp->GetID());
1410
1411 // No response required from vCont.
1412 return PacketResult::Success;
Pavel Labath77dc9562015-07-13 10:44:55 +00001413}
1414
Kate Stoneb9c1b512016-09-06 20:57:50 +00001415void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1416 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1417 if (log)
1418 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting current thread "
1419 "id to %" PRIu64,
1420 __FUNCTION__, tid);
Pavel Labath77dc9562015-07-13 10:44:55 +00001421
Kate Stoneb9c1b512016-09-06 20:57:50 +00001422 m_current_tid = tid;
1423 if (m_debugged_process_sp)
1424 m_debugged_process_sp->SetCurrentThreadID(m_current_tid);
1425}
1426
1427void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1428 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1429 if (log)
1430 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting continue thread "
1431 "id to %" PRIu64,
1432 __FUNCTION__, tid);
1433
1434 m_continue_tid = tid;
Pavel Labath77dc9562015-07-13 10:44:55 +00001435}
1436
Tamas Berghammere13c2732015-02-11 10:29:30 +00001437GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001438GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1439 StringExtractorGDBRemote &packet) {
1440 // Handle the $? gdbremote command.
Tamas Berghammere13c2732015-02-11 10:29:30 +00001441
Kate Stoneb9c1b512016-09-06 20:57:50 +00001442 // If no process, indicate error
1443 if (!m_debugged_process_sp)
1444 return SendErrorResponse(02);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001445
Kate Stoneb9c1b512016-09-06 20:57:50 +00001446 return SendStopReasonForState(m_debugged_process_sp->GetState());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001447}
1448
1449GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001450GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1451 lldb::StateType process_state) {
1452 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00001453
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454 switch (process_state) {
1455 case eStateAttaching:
1456 case eStateLaunching:
1457 case eStateRunning:
1458 case eStateStepping:
1459 case eStateDetached:
1460 // NOTE: gdb protocol doc looks like it should return $OK
1461 // when everything is running (i.e. no stopped result).
1462 return PacketResult::Success; // Ignore
Tamas Berghammere13c2732015-02-11 10:29:30 +00001463
Kate Stoneb9c1b512016-09-06 20:57:50 +00001464 case eStateSuspended:
1465 case eStateStopped:
1466 case eStateCrashed: {
1467 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001468 // Make sure we set the current thread so g and p packets return
1469 // the data the gdb will expect.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001470 SetCurrentThreadID(tid);
1471 return SendStopReplyPacketForThread(tid);
1472 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001473
Kate Stoneb9c1b512016-09-06 20:57:50 +00001474 case eStateInvalid:
1475 case eStateUnloaded:
1476 case eStateExited:
1477 return SendWResponse(m_debugged_process_sp.get());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001478
Kate Stoneb9c1b512016-09-06 20:57:50 +00001479 default:
1480 if (log) {
1481 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
1482 ", current state reporting not handled: %s",
1483 __FUNCTION__, m_debugged_process_sp->GetID(),
1484 StateAsCString(process_state));
Pavel Labath424b2012015-07-28 09:06:56 +00001485 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001486 break;
1487 }
Pavel Labath424b2012015-07-28 09:06:56 +00001488
Kate Stoneb9c1b512016-09-06 20:57:50 +00001489 return SendErrorResponse(0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001490}
1491
1492GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001493GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1494 StringExtractorGDBRemote &packet) {
1495 // Fail if we don't have a current process.
1496 if (!m_debugged_process_sp ||
1497 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1498 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001499
Kate Stoneb9c1b512016-09-06 20:57:50 +00001500 // Ensure we have a thread.
1501 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadAtIndex(0));
1502 if (!thread_sp)
1503 return SendErrorResponse(69);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001504
Kate Stoneb9c1b512016-09-06 20:57:50 +00001505 // Get the register context for the first thread.
1506 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1507 if (!reg_context_sp)
1508 return SendErrorResponse(69);
1509
1510 // Parse out the register number from the request.
1511 packet.SetFilePos(strlen("qRegisterInfo"));
1512 const uint32_t reg_index =
1513 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1514 if (reg_index == std::numeric_limits<uint32_t>::max())
1515 return SendErrorResponse(69);
1516
1517 // Return the end of registers response if we've iterated one past the end of
1518 // the register set.
1519 if (reg_index >= reg_context_sp->GetUserRegisterCount())
1520 return SendErrorResponse(69);
1521
1522 const RegisterInfo *reg_info =
1523 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1524 if (!reg_info)
1525 return SendErrorResponse(69);
1526
1527 // Build the reginfos response.
1528 StreamGDBRemote response;
1529
1530 response.PutCString("name:");
1531 response.PutCString(reg_info->name);
1532 response.PutChar(';');
1533
1534 if (reg_info->alt_name && reg_info->alt_name[0]) {
1535 response.PutCString("alt-name:");
1536 response.PutCString(reg_info->alt_name);
1537 response.PutChar(';');
1538 }
1539
1540 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1541 reg_info->byte_size * 8, reg_info->byte_offset);
1542
1543 switch (reg_info->encoding) {
1544 case eEncodingUint:
1545 response.PutCString("encoding:uint;");
1546 break;
1547 case eEncodingSint:
1548 response.PutCString("encoding:sint;");
1549 break;
1550 case eEncodingIEEE754:
1551 response.PutCString("encoding:ieee754;");
1552 break;
1553 case eEncodingVector:
1554 response.PutCString("encoding:vector;");
1555 break;
1556 default:
1557 break;
1558 }
1559
1560 switch (reg_info->format) {
1561 case eFormatBinary:
1562 response.PutCString("format:binary;");
1563 break;
1564 case eFormatDecimal:
1565 response.PutCString("format:decimal;");
1566 break;
1567 case eFormatHex:
1568 response.PutCString("format:hex;");
1569 break;
1570 case eFormatFloat:
1571 response.PutCString("format:float;");
1572 break;
1573 case eFormatVectorOfSInt8:
1574 response.PutCString("format:vector-sint8;");
1575 break;
1576 case eFormatVectorOfUInt8:
1577 response.PutCString("format:vector-uint8;");
1578 break;
1579 case eFormatVectorOfSInt16:
1580 response.PutCString("format:vector-sint16;");
1581 break;
1582 case eFormatVectorOfUInt16:
1583 response.PutCString("format:vector-uint16;");
1584 break;
1585 case eFormatVectorOfSInt32:
1586 response.PutCString("format:vector-sint32;");
1587 break;
1588 case eFormatVectorOfUInt32:
1589 response.PutCString("format:vector-uint32;");
1590 break;
1591 case eFormatVectorOfFloat32:
1592 response.PutCString("format:vector-float32;");
1593 break;
Valentina Giusticda0ae42016-09-08 14:16:45 +00001594 case eFormatVectorOfUInt64:
1595 response.PutCString("format:vector-uint64;");
1596 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001597 case eFormatVectorOfUInt128:
1598 response.PutCString("format:vector-uint128;");
1599 break;
1600 default:
1601 break;
1602 };
1603
1604 const char *const register_set_name =
1605 reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1606 if (register_set_name) {
1607 response.PutCString("set:");
1608 response.PutCString(register_set_name);
1609 response.PutChar(';');
1610 }
1611
1612 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1613 LLDB_INVALID_REGNUM)
1614 response.Printf("ehframe:%" PRIu32 ";",
1615 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1616
1617 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1618 response.Printf("dwarf:%" PRIu32 ";",
1619 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1620
1621 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1622 case LLDB_REGNUM_GENERIC_PC:
1623 response.PutCString("generic:pc;");
1624 break;
1625 case LLDB_REGNUM_GENERIC_SP:
1626 response.PutCString("generic:sp;");
1627 break;
1628 case LLDB_REGNUM_GENERIC_FP:
1629 response.PutCString("generic:fp;");
1630 break;
1631 case LLDB_REGNUM_GENERIC_RA:
1632 response.PutCString("generic:ra;");
1633 break;
1634 case LLDB_REGNUM_GENERIC_FLAGS:
1635 response.PutCString("generic:flags;");
1636 break;
1637 case LLDB_REGNUM_GENERIC_ARG1:
1638 response.PutCString("generic:arg1;");
1639 break;
1640 case LLDB_REGNUM_GENERIC_ARG2:
1641 response.PutCString("generic:arg2;");
1642 break;
1643 case LLDB_REGNUM_GENERIC_ARG3:
1644 response.PutCString("generic:arg3;");
1645 break;
1646 case LLDB_REGNUM_GENERIC_ARG4:
1647 response.PutCString("generic:arg4;");
1648 break;
1649 case LLDB_REGNUM_GENERIC_ARG5:
1650 response.PutCString("generic:arg5;");
1651 break;
1652 case LLDB_REGNUM_GENERIC_ARG6:
1653 response.PutCString("generic:arg6;");
1654 break;
1655 case LLDB_REGNUM_GENERIC_ARG7:
1656 response.PutCString("generic:arg7;");
1657 break;
1658 case LLDB_REGNUM_GENERIC_ARG8:
1659 response.PutCString("generic:arg8;");
1660 break;
1661 default:
1662 break;
1663 }
1664
1665 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1666 response.PutCString("container-regs:");
1667 int i = 0;
1668 for (const uint32_t *reg_num = reg_info->value_regs;
1669 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1670 if (i > 0)
1671 response.PutChar(',');
1672 response.Printf("%" PRIx32, *reg_num);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001673 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001674 response.PutChar(';');
1675 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001676
Kate Stoneb9c1b512016-09-06 20:57:50 +00001677 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1678 response.PutCString("invalidate-regs:");
1679 int i = 0;
1680 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1681 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1682 if (i > 0)
1683 response.PutChar(',');
1684 response.Printf("%" PRIx32, *reg_num);
1685 }
1686 response.PutChar(';');
1687 }
1688
1689 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1690 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1691 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1692 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1693 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1694 response.PutChar(';');
1695 }
1696 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001697}
1698
1699GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001700GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1701 StringExtractorGDBRemote &packet) {
1702 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1703
1704 // Fail if we don't have a current process.
1705 if (!m_debugged_process_sp ||
1706 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00001707 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001708 log->Printf("GDBRemoteCommunicationServerLLGS::%s() no process (%s), "
1709 "returning OK",
1710 __FUNCTION__,
1711 m_debugged_process_sp ? "invalid process id"
1712 : "null m_debugged_process_sp");
1713 return SendOKResponse();
1714 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001715
Kate Stoneb9c1b512016-09-06 20:57:50 +00001716 StreamGDBRemote response;
1717 response.PutChar('m');
1718
1719 if (log)
1720 log->Printf(
1721 "GDBRemoteCommunicationServerLLGS::%s() starting thread iteration",
1722 __FUNCTION__);
1723
1724 NativeThreadProtocolSP thread_sp;
1725 uint32_t thread_index;
1726 for (thread_index = 0,
1727 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index);
1728 thread_sp; ++thread_index,
1729 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index)) {
1730 if (log)
1731 log->Printf(
1732 "GDBRemoteCommunicationServerLLGS::%s() iterated thread %" PRIu32
1733 "(%s, tid=0x%" PRIx64 ")",
1734 __FUNCTION__, thread_index, thread_sp ? "is not null" : "null",
1735 thread_sp ? thread_sp->GetID() : LLDB_INVALID_THREAD_ID);
1736 if (thread_index > 0)
1737 response.PutChar(',');
1738 response.Printf("%" PRIx64, thread_sp->GetID());
1739 }
1740
1741 if (log)
1742 log->Printf(
1743 "GDBRemoteCommunicationServerLLGS::%s() finished thread iteration",
1744 __FUNCTION__);
1745
1746 return SendPacketNoLock(response.GetString());
1747}
1748
1749GDBRemoteCommunication::PacketResult
1750GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1751 StringExtractorGDBRemote &packet) {
1752 // FIXME for now we return the full thread list in the initial packet and
1753 // always do nothing here.
1754 return SendPacketNoLock("l");
1755}
1756
1757GDBRemoteCommunication::PacketResult
1758GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
1759 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1760
1761 // Parse out the register number from the request.
1762 packet.SetFilePos(strlen("p"));
1763 const uint32_t reg_index =
1764 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1765 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1766 if (log)
1767 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1768 "parse register number from request \"%s\"",
1769 __FUNCTION__, packet.GetStringRef().c_str());
1770 return SendErrorResponse(0x15);
1771 }
1772
1773 // Get the thread to use.
1774 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
1775 if (!thread_sp) {
1776 if (log)
1777 log->Printf(
1778 "GDBRemoteCommunicationServerLLGS::%s failed, no thread available",
1779 __FUNCTION__);
1780 return SendErrorResponse(0x15);
1781 }
1782
1783 // Get the thread's register context.
1784 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1785 if (!reg_context_sp) {
1786 if (log)
1787 log->Printf(
1788 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
1789 " failed, no register context available for the thread",
1790 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
1791 return SendErrorResponse(0x15);
1792 }
1793
1794 // Return the end of registers response if we've iterated one past the end of
1795 // the register set.
1796 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
1797 if (log)
1798 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1799 "register %" PRIu32 " beyond register count %" PRIu32,
1800 __FUNCTION__, reg_index,
1801 reg_context_sp->GetUserRegisterCount());
1802 return SendErrorResponse(0x15);
1803 }
1804
1805 const RegisterInfo *reg_info =
1806 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1807 if (!reg_info) {
1808 if (log)
1809 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1810 "register %" PRIu32 " returned NULL",
1811 __FUNCTION__, reg_index);
1812 return SendErrorResponse(0x15);
1813 }
1814
1815 // Build the reginfos response.
1816 StreamGDBRemote response;
1817
1818 // Retrieve the value
1819 RegisterValue reg_value;
1820 Error error = reg_context_sp->ReadRegister(reg_info, reg_value);
1821 if (error.Fail()) {
1822 if (log)
1823 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
1824 "requested register %" PRIu32 " (%s) failed: %s",
1825 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
1826 return SendErrorResponse(0x15);
1827 }
1828
1829 const uint8_t *const data =
1830 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
1831 if (!data) {
1832 if (log)
1833 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
1834 "bytes from requested register %" PRIu32,
1835 __FUNCTION__, reg_index);
1836 return SendErrorResponse(0x15);
1837 }
1838
1839 // FIXME flip as needed to get data in big/little endian format for this host.
1840 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
1841 response.PutHex8(data[i]);
1842
1843 return SendPacketNoLock(response.GetString());
1844}
1845
1846GDBRemoteCommunication::PacketResult
1847GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
1848 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1849
1850 // Ensure there is more content.
1851 if (packet.GetBytesLeft() < 1)
1852 return SendIllFormedResponse(packet, "Empty P packet");
1853
1854 // Parse out the register number from the request.
1855 packet.SetFilePos(strlen("P"));
1856 const uint32_t reg_index =
1857 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1858 if (reg_index == std::numeric_limits<uint32_t>::max()) {
1859 if (log)
1860 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
1861 "parse register number from request \"%s\"",
1862 __FUNCTION__, packet.GetStringRef().c_str());
1863 return SendErrorResponse(0x29);
1864 }
1865
1866 // Note debugserver would send an E30 here.
1867 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
1868 return SendIllFormedResponse(
1869 packet, "P packet missing '=' char after register number");
1870
1871 // Get process architecture.
1872 ArchSpec process_arch;
1873 if (!m_debugged_process_sp ||
1874 !m_debugged_process_sp->GetArchitecture(process_arch)) {
1875 if (log)
1876 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to retrieve "
1877 "inferior architecture",
1878 __FUNCTION__);
1879 return SendErrorResponse(0x49);
1880 }
1881
1882 // Parse out the value.
1883 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
1884 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
1885
1886 // Get the thread to use.
1887 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
1888 if (!thread_sp) {
1889 if (log)
1890 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
1891 "available (thread index 0)",
1892 __FUNCTION__);
1893 return SendErrorResponse(0x28);
1894 }
1895
1896 // Get the thread's register context.
1897 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1898 if (!reg_context_sp) {
1899 if (log)
1900 log->Printf(
1901 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
1902 " failed, no register context available for the thread",
1903 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
1904 return SendErrorResponse(0x15);
1905 }
1906
1907 const RegisterInfo *reg_info =
1908 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1909 if (!reg_info) {
1910 if (log)
1911 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1912 "register %" PRIu32 " returned NULL",
1913 __FUNCTION__, reg_index);
1914 return SendErrorResponse(0x48);
1915 }
1916
1917 // Return the end of registers response if we've iterated one past the end of
1918 // the register set.
1919 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
1920 if (log)
1921 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
1922 "register %" PRIu32 " beyond register count %" PRIu32,
1923 __FUNCTION__, reg_index,
1924 reg_context_sp->GetUserRegisterCount());
1925 return SendErrorResponse(0x47);
1926 }
1927
1928 // The dwarf expression are evaluate on host site
1929 // which may cause register size to change
1930 // Hence the reg_size may not be same as reg_info->bytes_size
1931 if ((reg_size != reg_info->byte_size) &&
1932 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
1933 return SendIllFormedResponse(packet, "P packet register size is incorrect");
1934 }
1935
1936 // Build the reginfos response.
1937 StreamGDBRemote response;
1938
1939 RegisterValue reg_value(reg_bytes, reg_size, process_arch.GetByteOrder());
1940 Error error = reg_context_sp->WriteRegister(reg_info, reg_value);
1941 if (error.Fail()) {
1942 if (log)
1943 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
1944 "requested register %" PRIu32 " (%s) failed: %s",
1945 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
1946 return SendErrorResponse(0x32);
1947 }
1948
1949 return SendOKResponse();
1950}
1951
1952GDBRemoteCommunication::PacketResult
1953GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
1954 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1955
1956 // Fail if we don't have a current process.
1957 if (!m_debugged_process_sp ||
1958 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
1959 if (log)
1960 log->Printf(
1961 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
1962 __FUNCTION__);
1963 return SendErrorResponse(0x15);
1964 }
1965
1966 // Parse out which variant of $H is requested.
1967 packet.SetFilePos(strlen("H"));
1968 if (packet.GetBytesLeft() < 1) {
1969 if (log)
1970 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
1971 "missing {g,c} variant",
1972 __FUNCTION__);
1973 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
1974 }
1975
1976 const char h_variant = packet.GetChar();
1977 switch (h_variant) {
1978 case 'g':
1979 break;
1980
1981 case 'c':
1982 break;
1983
1984 default:
1985 if (log)
1986 log->Printf(
1987 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
1988 __FUNCTION__, h_variant);
1989 return SendIllFormedResponse(packet,
1990 "H variant unsupported, should be c or g");
1991 }
1992
1993 // Parse out the thread number.
1994 // FIXME return a parse success/fail value. All values are valid here.
1995 const lldb::tid_t tid =
1996 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
1997
1998 // Ensure we have the given thread when not specifying -1 (all threads) or 0
1999 // (any thread).
2000 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2001 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
2002 if (!thread_sp) {
2003 if (log)
2004 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2005 " not found",
2006 __FUNCTION__, tid);
2007 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002008 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002009 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002010
Kate Stoneb9c1b512016-09-06 20:57:50 +00002011 // Now switch the given thread type.
2012 switch (h_variant) {
2013 case 'g':
2014 SetCurrentThreadID(tid);
2015 break;
2016
2017 case 'c':
2018 SetContinueThreadID(tid);
2019 break;
2020
2021 default:
2022 assert(false && "unsupported $H variant - shouldn't get here");
2023 return SendIllFormedResponse(packet,
2024 "H variant unsupported, should be c or g");
2025 }
2026
2027 return SendOKResponse();
2028}
2029
2030GDBRemoteCommunication::PacketResult
2031GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2032 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2033
2034 // Fail if we don't have a current process.
2035 if (!m_debugged_process_sp ||
2036 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2037 if (log)
2038 log->Printf(
2039 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2040 __FUNCTION__);
2041 return SendErrorResponse(0x15);
2042 }
2043
2044 packet.SetFilePos(::strlen("I"));
2045 uint8_t tmp[4096];
2046 for (;;) {
2047 size_t read = packet.GetHexBytesAvail(tmp);
2048 if (read == 0) {
2049 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002050 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002051 // write directly to stdin *this might block if stdin buffer is full*
2052 // TODO: enqueue this block in circular buffer and send window size to
2053 // remote host
2054 ConnectionStatus status;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002055 Error error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002056 m_stdio_communication.Write(tmp, read, status, &error);
2057 if (error.Fail()) {
2058 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002059 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002060 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002061
Kate Stoneb9c1b512016-09-06 20:57:50 +00002062 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002063}
2064
2065GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002066GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2067 StringExtractorGDBRemote &packet) {
2068 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2069
2070 // Fail if we don't have a current process.
2071 if (!m_debugged_process_sp ||
2072 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002073 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002074 log->Printf(
2075 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2076 __FUNCTION__);
2077 return SendErrorResponse(0x15);
2078 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002079
Kate Stoneb9c1b512016-09-06 20:57:50 +00002080 // Interrupt the process.
2081 Error error = m_debugged_process_sp->Interrupt();
2082 if (error.Fail()) {
2083 if (log) {
2084 log->Printf(
2085 "GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64
2086 ": %s",
2087 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002088 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002089 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2090 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002091
Kate Stoneb9c1b512016-09-06 20:57:50 +00002092 if (log)
2093 log->Printf("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64,
2094 __FUNCTION__, m_debugged_process_sp->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002095
Kate Stoneb9c1b512016-09-06 20:57:50 +00002096 // No response required from stop all.
2097 return PacketResult::Success;
2098}
Tamas Berghammere13c2732015-02-11 10:29:30 +00002099
Kate Stoneb9c1b512016-09-06 20:57:50 +00002100GDBRemoteCommunication::PacketResult
2101GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2102 StringExtractorGDBRemote &packet) {
2103 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002104
Kate Stoneb9c1b512016-09-06 20:57:50 +00002105 if (!m_debugged_process_sp ||
2106 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002107 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002108 log->Printf(
2109 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2110 __FUNCTION__);
2111 return SendErrorResponse(0x15);
2112 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002113
Kate Stoneb9c1b512016-09-06 20:57:50 +00002114 // Parse out the memory address.
2115 packet.SetFilePos(strlen("m"));
2116 if (packet.GetBytesLeft() < 1)
2117 return SendIllFormedResponse(packet, "Too short m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002118
Kate Stoneb9c1b512016-09-06 20:57:50 +00002119 // Read the address. Punting on validation.
2120 // FIXME replace with Hex U64 read with no default value that fails on failed
2121 // read.
2122 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002123
Kate Stoneb9c1b512016-09-06 20:57:50 +00002124 // Validate comma.
2125 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2126 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002127
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128 // Get # bytes to read.
2129 if (packet.GetBytesLeft() < 1)
2130 return SendIllFormedResponse(packet, "Length missing in m packet");
2131
2132 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2133 if (byte_count == 0) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002134 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002135 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2136 "zero-length packet",
2137 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002138 return SendOKResponse();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002139 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002140
Kate Stoneb9c1b512016-09-06 20:57:50 +00002141 // Allocate the response buffer.
2142 std::string buf(byte_count, '\0');
2143 if (buf.empty())
2144 return SendErrorResponse(0x78);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002145
Kate Stoneb9c1b512016-09-06 20:57:50 +00002146 // Retrieve the process memory.
2147 size_t bytes_read = 0;
2148 Error error = m_debugged_process_sp->ReadMemoryWithoutTrap(
2149 read_addr, &buf[0], byte_count, bytes_read);
2150 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002151 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002152 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2153 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2154 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2155 error.AsCString());
2156 return SendErrorResponse(0x08);
2157 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002158
Kate Stoneb9c1b512016-09-06 20:57:50 +00002159 if (bytes_read == 0) {
2160 if (log)
2161 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2162 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2163 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2164 byte_count);
2165 return SendErrorResponse(0x08);
2166 }
2167
2168 StreamGDBRemote response;
2169 packet.SetFilePos(0);
2170 char kind = packet.GetChar('?');
2171 if (kind == 'x')
2172 response.PutEscapedBytes(buf.data(), byte_count);
2173 else {
2174 assert(kind == 'm');
2175 for (size_t i = 0; i < bytes_read; ++i)
2176 response.PutHex8(buf[i]);
2177 }
2178
2179 return SendPacketNoLock(response.GetString());
2180}
2181
2182GDBRemoteCommunication::PacketResult
2183GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2184 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2185
2186 if (!m_debugged_process_sp ||
2187 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2188 if (log)
2189 log->Printf(
2190 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2191 __FUNCTION__);
2192 return SendErrorResponse(0x15);
2193 }
2194
2195 // Parse out the memory address.
2196 packet.SetFilePos(strlen("M"));
2197 if (packet.GetBytesLeft() < 1)
2198 return SendIllFormedResponse(packet, "Too short M packet");
2199
2200 // Read the address. Punting on validation.
2201 // FIXME replace with Hex U64 read with no default value that fails on failed
2202 // read.
2203 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2204
2205 // Validate comma.
2206 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2207 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2208
2209 // Get # bytes to read.
2210 if (packet.GetBytesLeft() < 1)
2211 return SendIllFormedResponse(packet, "Length missing in M packet");
2212
2213 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2214 if (byte_count == 0) {
2215 if (log)
2216 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to write: "
2217 "zero-length packet",
2218 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002219 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002220 }
2221
2222 // Validate colon.
2223 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2224 return SendIllFormedResponse(
2225 packet, "Comma sep missing in M packet after byte length");
2226
2227 // Allocate the conversion buffer.
2228 std::vector<uint8_t> buf(byte_count, 0);
2229 if (buf.empty())
2230 return SendErrorResponse(0x78);
2231
2232 // Convert the hex memory write contents to bytes.
2233 StreamGDBRemote response;
2234 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2235 if (convert_count != byte_count) {
2236 if (log)
2237 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2238 " mem 0x%" PRIx64 ": asked to write %" PRIu64
2239 " bytes, but only found %" PRIu64 " to convert.",
2240 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2241 byte_count, convert_count);
2242 return SendIllFormedResponse(packet, "M content byte length specified did "
2243 "not match hex-encoded content "
2244 "length");
2245 }
2246
2247 // Write the process memory.
2248 size_t bytes_written = 0;
2249 Error error = m_debugged_process_sp->WriteMemory(write_addr, &buf[0],
2250 byte_count, bytes_written);
2251 if (error.Fail()) {
2252 if (log)
2253 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2254 " mem 0x%" PRIx64 ": failed to write. Error: %s",
2255 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2256 error.AsCString());
2257 return SendErrorResponse(0x09);
2258 }
2259
2260 if (bytes_written == 0) {
2261 if (log)
2262 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2263 " mem 0x%" PRIx64 ": wrote 0 of %" PRIu64 " requested bytes",
2264 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2265 byte_count);
2266 return SendErrorResponse(0x09);
2267 }
2268
2269 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002270}
2271
2272GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002273GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2274 StringExtractorGDBRemote &packet) {
2275 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002276
Kate Stoneb9c1b512016-09-06 20:57:50 +00002277 // Currently only the NativeProcessProtocol knows if it can handle a
2278 // qMemoryRegionInfoSupported
2279 // request, but we're not guaranteed to be attached to a process. For now
2280 // we'll assume the
2281 // client only asks this when a process is being debugged.
Tamas Berghammere13c2732015-02-11 10:29:30 +00002282
Kate Stoneb9c1b512016-09-06 20:57:50 +00002283 // Ensure we have a process running; otherwise, we can't figure this out
2284 // since we won't have a NativeProcessProtocol.
2285 if (!m_debugged_process_sp ||
2286 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2287 if (log)
2288 log->Printf(
2289 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2290 __FUNCTION__);
2291 return SendErrorResponse(0x15);
2292 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002293
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294 // Test if we can get any region back when asking for the region around NULL.
2295 MemoryRegionInfo region_info;
2296 const Error error =
2297 m_debugged_process_sp->GetMemoryRegionInfo(0, region_info);
2298 if (error.Fail()) {
2299 // We don't support memory region info collection for this
2300 // NativeProcessProtocol.
2301 return SendUnimplementedResponse("");
2302 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002303
Kate Stoneb9c1b512016-09-06 20:57:50 +00002304 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002305}
2306
2307GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002308GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2309 StringExtractorGDBRemote &packet) {
2310 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002311
Kate Stoneb9c1b512016-09-06 20:57:50 +00002312 // Ensure we have a process.
2313 if (!m_debugged_process_sp ||
2314 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2315 if (log)
2316 log->Printf(
2317 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2318 __FUNCTION__);
2319 return SendErrorResponse(0x15);
2320 }
2321
2322 // Parse out the memory address.
2323 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2324 if (packet.GetBytesLeft() < 1)
2325 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2326
2327 // Read the address. Punting on validation.
2328 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2329
2330 StreamGDBRemote response;
2331
2332 // Get the memory region info for the target address.
2333 MemoryRegionInfo region_info;
2334 const Error error =
2335 m_debugged_process_sp->GetMemoryRegionInfo(read_addr, region_info);
2336 if (error.Fail()) {
2337 // Return the error message.
2338
2339 response.PutCString("error:");
2340 response.PutCStringAsRawHex8(error.AsCString());
2341 response.PutChar(';');
2342 } else {
2343 // Range start and size.
2344 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2345 region_info.GetRange().GetRangeBase(),
2346 region_info.GetRange().GetByteSize());
2347
2348 // Permissions.
2349 if (region_info.GetReadable() || region_info.GetWritable() ||
2350 region_info.GetExecutable()) {
2351 // Write permissions info.
2352 response.PutCString("permissions:");
2353
2354 if (region_info.GetReadable())
2355 response.PutChar('r');
2356 if (region_info.GetWritable())
2357 response.PutChar('w');
2358 if (region_info.GetExecutable())
2359 response.PutChar('x');
2360
2361 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002362 }
2363
Kate Stoneb9c1b512016-09-06 20:57:50 +00002364 // Name
2365 ConstString name = region_info.GetName();
2366 if (name) {
2367 response.PutCString("name:");
2368 response.PutCStringAsRawHex8(name.AsCString());
2369 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002370 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002371 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002372
Kate Stoneb9c1b512016-09-06 20:57:50 +00002373 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002374}
2375
2376GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002377GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2378 // Ensure we have a process.
2379 if (!m_debugged_process_sp ||
2380 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2381 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2382 if (log)
2383 log->Printf(
2384 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2385 __FUNCTION__);
2386 return SendErrorResponse(0x15);
2387 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002388
Kate Stoneb9c1b512016-09-06 20:57:50 +00002389 // Parse out software or hardware breakpoint or watchpoint requested.
2390 packet.SetFilePos(strlen("Z"));
2391 if (packet.GetBytesLeft() < 1)
2392 return SendIllFormedResponse(
2393 packet, "Too short Z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002394
Kate Stoneb9c1b512016-09-06 20:57:50 +00002395 bool want_breakpoint = true;
2396 bool want_hardware = false;
2397 uint32_t watch_flags = 0;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002398
Kate Stoneb9c1b512016-09-06 20:57:50 +00002399 const GDBStoppointType stoppoint_type =
2400 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2401 switch (stoppoint_type) {
2402 case eBreakpointSoftware:
2403 want_hardware = false;
2404 want_breakpoint = true;
2405 break;
2406 case eBreakpointHardware:
2407 want_hardware = true;
2408 want_breakpoint = true;
2409 break;
2410 case eWatchpointWrite:
2411 watch_flags = 1;
2412 want_hardware = true;
2413 want_breakpoint = false;
2414 break;
2415 case eWatchpointRead:
2416 watch_flags = 2;
2417 want_hardware = true;
2418 want_breakpoint = false;
2419 break;
2420 case eWatchpointReadWrite:
2421 watch_flags = 3;
2422 want_hardware = true;
2423 want_breakpoint = false;
2424 break;
2425 case eStoppointInvalid:
2426 return SendIllFormedResponse(
2427 packet, "Z packet had invalid software/hardware specifier");
2428 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002429
Kate Stoneb9c1b512016-09-06 20:57:50 +00002430 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2431 return SendIllFormedResponse(
2432 packet, "Malformed Z packet, expecting comma after stoppoint type");
2433
2434 // Parse out the stoppoint address.
2435 if (packet.GetBytesLeft() < 1)
2436 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2437 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2438
2439 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2440 return SendIllFormedResponse(
2441 packet, "Malformed Z packet, expecting comma after address");
2442
2443 // Parse out the stoppoint size (i.e. size hint for opcode size).
2444 const uint32_t size =
2445 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2446 if (size == std::numeric_limits<uint32_t>::max())
2447 return SendIllFormedResponse(
2448 packet, "Malformed Z packet, failed to parse size argument");
2449
2450 if (want_breakpoint) {
2451 // Try to set the breakpoint.
2452 const Error error =
2453 m_debugged_process_sp->SetBreakpoint(addr, size, want_hardware);
2454 if (error.Success())
2455 return SendOKResponse();
2456 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2457 if (log)
2458 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2459 " failed to set breakpoint: %s",
2460 __FUNCTION__, m_debugged_process_sp->GetID(),
2461 error.AsCString());
2462 return SendErrorResponse(0x09);
2463 } else {
2464 // Try to set the watchpoint.
2465 const Error error = m_debugged_process_sp->SetWatchpoint(
2466 addr, size, watch_flags, want_hardware);
2467 if (error.Success())
2468 return SendOKResponse();
2469 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2470 if (log)
2471 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2472 " failed to set watchpoint: %s",
2473 __FUNCTION__, m_debugged_process_sp->GetID(),
2474 error.AsCString());
2475 return SendErrorResponse(0x09);
2476 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002477}
2478
2479GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002480GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2481 // Ensure we have a process.
2482 if (!m_debugged_process_sp ||
2483 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2484 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2485 if (log)
2486 log->Printf(
2487 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2488 __FUNCTION__);
2489 return SendErrorResponse(0x15);
2490 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002491
Kate Stoneb9c1b512016-09-06 20:57:50 +00002492 // Parse out software or hardware breakpoint or watchpoint requested.
2493 packet.SetFilePos(strlen("z"));
2494 if (packet.GetBytesLeft() < 1)
2495 return SendIllFormedResponse(
2496 packet, "Too short z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002497
Kate Stoneb9c1b512016-09-06 20:57:50 +00002498 bool want_breakpoint = true;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002499
Kate Stoneb9c1b512016-09-06 20:57:50 +00002500 const GDBStoppointType stoppoint_type =
2501 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2502 switch (stoppoint_type) {
2503 case eBreakpointHardware:
2504 want_breakpoint = true;
2505 break;
2506 case eBreakpointSoftware:
2507 want_breakpoint = true;
2508 break;
2509 case eWatchpointWrite:
2510 want_breakpoint = false;
2511 break;
2512 case eWatchpointRead:
2513 want_breakpoint = false;
2514 break;
2515 case eWatchpointReadWrite:
2516 want_breakpoint = false;
2517 break;
2518 default:
2519 return SendIllFormedResponse(
2520 packet, "z packet had invalid software/hardware specifier");
2521 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002522
Kate Stoneb9c1b512016-09-06 20:57:50 +00002523 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2524 return SendIllFormedResponse(
2525 packet, "Malformed z packet, expecting comma after stoppoint type");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002526
Kate Stoneb9c1b512016-09-06 20:57:50 +00002527 // Parse out the stoppoint address.
2528 if (packet.GetBytesLeft() < 1)
2529 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2530 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002531
Kate Stoneb9c1b512016-09-06 20:57:50 +00002532 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2533 return SendIllFormedResponse(
2534 packet, "Malformed z packet, expecting comma after address");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002535
Kate Stoneb9c1b512016-09-06 20:57:50 +00002536 /*
2537 // Parse out the stoppoint size (i.e. size hint for opcode size).
2538 const uint32_t size = packet.GetHexMaxU32 (false,
2539 std::numeric_limits<uint32_t>::max ());
2540 if (size == std::numeric_limits<uint32_t>::max ())
2541 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2542 size argument");
2543 */
Tamas Berghammere13c2732015-02-11 10:29:30 +00002544
Kate Stoneb9c1b512016-09-06 20:57:50 +00002545 if (want_breakpoint) {
2546 // Try to clear the breakpoint.
2547 const Error error = m_debugged_process_sp->RemoveBreakpoint(addr);
2548 if (error.Success())
2549 return SendOKResponse();
2550 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2551 if (log)
2552 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2553 " failed to remove breakpoint: %s",
2554 __FUNCTION__, m_debugged_process_sp->GetID(),
2555 error.AsCString());
2556 return SendErrorResponse(0x09);
2557 } else {
2558 // Try to clear the watchpoint.
2559 const Error error = m_debugged_process_sp->RemoveWatchpoint(addr);
2560 if (error.Success())
2561 return SendOKResponse();
2562 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2563 if (log)
2564 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2565 " failed to remove watchpoint: %s",
2566 __FUNCTION__, m_debugged_process_sp->GetID(),
2567 error.AsCString());
2568 return SendErrorResponse(0x09);
2569 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002570}
2571
2572GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002573GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2574 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002575
Kate Stoneb9c1b512016-09-06 20:57:50 +00002576 // Ensure we have a process.
2577 if (!m_debugged_process_sp ||
2578 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2579 if (log)
2580 log->Printf(
2581 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2582 __FUNCTION__);
2583 return SendErrorResponse(0x32);
2584 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002585
Kate Stoneb9c1b512016-09-06 20:57:50 +00002586 // We first try to use a continue thread id. If any one or any all set, use
2587 // the current thread.
2588 // Bail out if we don't have a thread id.
2589 lldb::tid_t tid = GetContinueThreadID();
2590 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2591 tid = GetCurrentThreadID();
2592 if (tid == LLDB_INVALID_THREAD_ID)
2593 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002594
Kate Stoneb9c1b512016-09-06 20:57:50 +00002595 // Double check that we have such a thread.
2596 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2597 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID(tid);
2598 if (!thread_sp || thread_sp->GetID() != tid)
2599 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002600
Kate Stoneb9c1b512016-09-06 20:57:50 +00002601 // Create the step action for the given thread.
2602 ResumeAction action = {tid, eStateStepping, 0};
Tamas Berghammere13c2732015-02-11 10:29:30 +00002603
Kate Stoneb9c1b512016-09-06 20:57:50 +00002604 // Setup the actions list.
2605 ResumeActionList actions;
2606 actions.Append(action);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002607
Kate Stoneb9c1b512016-09-06 20:57:50 +00002608 // All other threads stop while we're single stepping a thread.
2609 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
2610 Error error = m_debugged_process_sp->Resume(actions);
2611 if (error.Fail()) {
2612 if (log)
2613 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2614 " tid %" PRIu64 " Resume() failed with error: %s",
2615 __FUNCTION__, m_debugged_process_sp->GetID(), tid,
2616 error.AsCString());
2617 return SendErrorResponse(0x49);
2618 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002619
Kate Stoneb9c1b512016-09-06 20:57:50 +00002620 // No response here - the stop or exit will come from the resulting action.
2621 return PacketResult::Success;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002622}
2623
2624GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002625GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2626 StringExtractorGDBRemote &packet) {
2627// *BSD impls should be able to do this too.
Tamas Berghammere13c2732015-02-11 10:29:30 +00002628#if defined(__linux__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002629 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002630
Kate Stoneb9c1b512016-09-06 20:57:50 +00002631 // Parse out the offset.
2632 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2633 if (packet.GetBytesLeft() < 1)
2634 return SendIllFormedResponse(packet,
2635 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002636
Kate Stoneb9c1b512016-09-06 20:57:50 +00002637 const uint64_t auxv_offset =
2638 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2639 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2640 return SendIllFormedResponse(packet,
2641 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002642
Kate Stoneb9c1b512016-09-06 20:57:50 +00002643 // Parse out comma.
2644 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2645 return SendIllFormedResponse(
2646 packet, "qXfer:auxv:read:: packet missing comma after offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002647
Kate Stoneb9c1b512016-09-06 20:57:50 +00002648 // Parse out the length.
2649 const uint64_t auxv_length =
2650 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2651 if (auxv_length == std::numeric_limits<uint64_t>::max())
2652 return SendIllFormedResponse(packet,
2653 "qXfer:auxv:read:: packet missing length");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002654
Kate Stoneb9c1b512016-09-06 20:57:50 +00002655 // Grab the auxv data if we need it.
2656 if (!m_active_auxv_buffer_sp) {
2657 // Make sure we have a valid process.
2658 if (!m_debugged_process_sp ||
2659 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2660 if (log)
2661 log->Printf(
2662 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2663 __FUNCTION__);
2664 return SendErrorResponse(0x10);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002665 }
2666
Kate Stoneb9c1b512016-09-06 20:57:50 +00002667 // Grab the auxv data.
2668 m_active_auxv_buffer_sp = Host::GetAuxvData(m_debugged_process_sp->GetID());
2669 if (!m_active_auxv_buffer_sp ||
2670 m_active_auxv_buffer_sp->GetByteSize() == 0) {
2671 // Hmm, no auxv data, call that an error.
2672 if (log)
2673 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no auxv data "
2674 "retrieved",
2675 __FUNCTION__);
2676 m_active_auxv_buffer_sp.reset();
2677 return SendErrorResponse(0x11);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002678 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002679 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002680
Kate Stoneb9c1b512016-09-06 20:57:50 +00002681 // FIXME find out if/how I lock the stream here.
Tamas Berghammere13c2732015-02-11 10:29:30 +00002682
Kate Stoneb9c1b512016-09-06 20:57:50 +00002683 StreamGDBRemote response;
2684 bool done_with_buffer = false;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002685
Kate Stoneb9c1b512016-09-06 20:57:50 +00002686 if (auxv_offset >= m_active_auxv_buffer_sp->GetByteSize()) {
2687 // We have nothing left to send. Mark the buffer as complete.
2688 response.PutChar('l');
2689 done_with_buffer = true;
2690 } else {
2691 // Figure out how many bytes are available starting at the given offset.
2692 const uint64_t bytes_remaining =
2693 m_active_auxv_buffer_sp->GetByteSize() - auxv_offset;
2694
2695 // Figure out how many bytes we're going to read.
2696 const uint64_t bytes_to_read =
2697 (auxv_length > bytes_remaining) ? bytes_remaining : auxv_length;
2698
2699 // Mark the response type according to whether we're reading the remainder
2700 // of the auxv data.
2701 if (bytes_to_read >= bytes_remaining) {
2702 // There will be nothing left to read after this
2703 response.PutChar('l');
2704 done_with_buffer = true;
2705 } else {
2706 // There will still be bytes to read after this request.
2707 response.PutChar('m');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002708 }
2709
Kate Stoneb9c1b512016-09-06 20:57:50 +00002710 // Now write the data in encoded binary form.
2711 response.PutEscapedBytes(m_active_auxv_buffer_sp->GetBytes() + auxv_offset,
2712 bytes_to_read);
2713 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002714
Kate Stoneb9c1b512016-09-06 20:57:50 +00002715 if (done_with_buffer)
2716 m_active_auxv_buffer_sp.reset();
2717
2718 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002719#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002720 return SendUnimplementedResponse("not implemented on this platform");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002721#endif
2722}
2723
2724GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002725GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2726 StringExtractorGDBRemote &packet) {
2727 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002728
Kate Stoneb9c1b512016-09-06 20:57:50 +00002729 // Move past packet name.
2730 packet.SetFilePos(strlen("QSaveRegisterState"));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002731
Kate Stoneb9c1b512016-09-06 20:57:50 +00002732 // Get the thread to use.
2733 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2734 if (!thread_sp) {
2735 if (m_thread_suffix_supported)
2736 return SendIllFormedResponse(
2737 packet, "No thread specified in QSaveRegisterState packet");
2738 else
2739 return SendIllFormedResponse(packet,
2740 "No thread was is set with the Hg packet");
2741 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002742
Kate Stoneb9c1b512016-09-06 20:57:50 +00002743 // Grab the register context for the thread.
2744 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2745 if (!reg_context_sp) {
2746 if (log)
2747 log->Printf(
2748 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2749 " failed, no register context available for the thread",
2750 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2751 return SendErrorResponse(0x15);
2752 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002753
Kate Stoneb9c1b512016-09-06 20:57:50 +00002754 // Save registers to a buffer.
2755 DataBufferSP register_data_sp;
2756 Error error = reg_context_sp->ReadAllRegisterValues(register_data_sp);
2757 if (error.Fail()) {
2758 if (log)
2759 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2760 " failed to save all register values: %s",
2761 __FUNCTION__, m_debugged_process_sp->GetID(),
2762 error.AsCString());
2763 return SendErrorResponse(0x75);
2764 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002765
Kate Stoneb9c1b512016-09-06 20:57:50 +00002766 // Allocate a new save id.
2767 const uint32_t save_id = GetNextSavedRegistersID();
2768 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
2769 "GetNextRegisterSaveID() returned an existing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002770
Kate Stoneb9c1b512016-09-06 20:57:50 +00002771 // Save the register data buffer under the save id.
2772 {
2773 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2774 m_saved_registers_map[save_id] = register_data_sp;
2775 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002776
Kate Stoneb9c1b512016-09-06 20:57:50 +00002777 // Write the response.
2778 StreamGDBRemote response;
2779 response.Printf("%" PRIu32, save_id);
2780 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002781}
2782
2783GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002784GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
2785 StringExtractorGDBRemote &packet) {
2786 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002787
Kate Stoneb9c1b512016-09-06 20:57:50 +00002788 // Parse out save id.
2789 packet.SetFilePos(strlen("QRestoreRegisterState:"));
2790 if (packet.GetBytesLeft() < 1)
2791 return SendIllFormedResponse(
2792 packet, "QRestoreRegisterState packet missing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002793
Kate Stoneb9c1b512016-09-06 20:57:50 +00002794 const uint32_t save_id = packet.GetU32(0);
2795 if (save_id == 0) {
2796 if (log)
2797 log->Printf("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState "
2798 "packet has malformed save id, expecting decimal uint32_t",
2799 __FUNCTION__);
2800 return SendErrorResponse(0x76);
2801 }
2802
2803 // Get the thread to use.
2804 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2805 if (!thread_sp) {
2806 if (m_thread_suffix_supported)
2807 return SendIllFormedResponse(
2808 packet, "No thread specified in QRestoreRegisterState packet");
2809 else
2810 return SendIllFormedResponse(packet,
2811 "No thread was is set with the Hg packet");
2812 }
2813
2814 // Grab the register context for the thread.
2815 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2816 if (!reg_context_sp) {
2817 if (log)
2818 log->Printf(
2819 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2820 " failed, no register context available for the thread",
2821 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2822 return SendErrorResponse(0x15);
2823 }
2824
2825 // Retrieve register state buffer, then remove from the list.
2826 DataBufferSP register_data_sp;
2827 {
2828 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
2829
2830 // Find the register set buffer for the given save id.
2831 auto it = m_saved_registers_map.find(save_id);
2832 if (it == m_saved_registers_map.end()) {
2833 if (log)
2834 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2835 " does not have a register set save buffer for id %" PRIu32,
2836 __FUNCTION__, m_debugged_process_sp->GetID(), save_id);
2837 return SendErrorResponse(0x77);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002838 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002839 register_data_sp = it->second;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002840
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 // Remove it from the map.
2842 m_saved_registers_map.erase(it);
2843 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002844
Kate Stoneb9c1b512016-09-06 20:57:50 +00002845 Error error = reg_context_sp->WriteAllRegisterValues(register_data_sp);
2846 if (error.Fail()) {
2847 if (log)
2848 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2849 " failed to restore all register values: %s",
2850 __FUNCTION__, m_debugged_process_sp->GetID(),
2851 error.AsCString());
2852 return SendErrorResponse(0x77);
2853 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002854
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002856}
2857
2858GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002859GDBRemoteCommunicationServerLLGS::Handle_vAttach(
2860 StringExtractorGDBRemote &packet) {
2861 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002862
Kate Stoneb9c1b512016-09-06 20:57:50 +00002863 // Consume the ';' after vAttach.
2864 packet.SetFilePos(strlen("vAttach"));
2865 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
2866 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002867
Kate Stoneb9c1b512016-09-06 20:57:50 +00002868 // Grab the PID to which we will attach (assume hex encoding).
2869 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
2870 if (pid == LLDB_INVALID_PROCESS_ID)
2871 return SendIllFormedResponse(packet,
2872 "vAttach failed to parse the process id");
2873
2874 // Attempt to attach.
2875 if (log)
2876 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
2877 "pid %" PRIu64,
2878 __FUNCTION__, pid);
2879
2880 Error error = AttachToProcess(pid);
2881
2882 if (error.Fail()) {
2883 if (log)
2884 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
2885 "pid %" PRIu64 ": %s\n",
2886 __FUNCTION__, pid, error.AsCString());
2887 return SendErrorResponse(0x01);
2888 }
2889
2890 // Notify we attached by sending a stop packet.
2891 return SendStopReasonForState(m_debugged_process_sp->GetState());
2892}
2893
2894GDBRemoteCommunication::PacketResult
2895GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
2896 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2897
2898 StopSTDIOForwarding();
2899
2900 // Fail if we don't have a current process.
2901 if (!m_debugged_process_sp ||
2902 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2903 if (log)
2904 log->Printf(
2905 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2906 __FUNCTION__);
2907 return SendErrorResponse(0x15);
2908 }
2909
2910 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
2911
2912 // Consume the ';' after D.
2913 packet.SetFilePos(1);
2914 if (packet.GetBytesLeft()) {
2915 if (packet.GetChar() != ';')
2916 return SendIllFormedResponse(packet, "D missing expected ';'");
2917
2918 // Grab the PID from which we will detach (assume hex encoding).
2919 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002920 if (pid == LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002921 return SendIllFormedResponse(packet, "D failed to parse the process id");
2922 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002923
Kate Stoneb9c1b512016-09-06 20:57:50 +00002924 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_sp->GetID() != pid) {
2925 return SendIllFormedResponse(packet, "Invalid pid");
2926 }
2927
2928 const Error error = m_debugged_process_sp->Detach();
2929 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002930 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002931 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
2932 "pid %" PRIu64 ": %s\n",
2933 __FUNCTION__, m_debugged_process_sp->GetID(),
2934 error.AsCString());
2935 return SendErrorResponse(0x01);
2936 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002937
Kate Stoneb9c1b512016-09-06 20:57:50 +00002938 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002939}
2940
2941GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002942GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
2943 StringExtractorGDBRemote &packet) {
2944 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002945
Kate Stoneb9c1b512016-09-06 20:57:50 +00002946 packet.SetFilePos(strlen("qThreadStopInfo"));
2947 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
2948 if (tid == LLDB_INVALID_THREAD_ID) {
Pavel Labath4a4bb122015-07-16 14:14:35 +00002949 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002950 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2951 "parse thread id from request \"%s\"",
2952 __FUNCTION__, packet.GetStringRef().c_str());
2953 return SendErrorResponse(0x15);
2954 }
2955 return SendStopReplyPacketForThread(tid);
2956}
2957
2958GDBRemoteCommunication::PacketResult
2959GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
2960 StringExtractorGDBRemote &) {
2961 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2962
2963 // Ensure we have a debugged process.
2964 if (!m_debugged_process_sp ||
2965 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
2966 return SendErrorResponse(50);
2967
2968 if (log)
2969 log->Printf("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid "
2970 "%" PRIu64,
Pavel Labath4a4bb122015-07-16 14:14:35 +00002971 __FUNCTION__, m_debugged_process_sp->GetID());
2972
Kate Stoneb9c1b512016-09-06 20:57:50 +00002973 StreamString response;
2974 const bool threads_with_valid_stop_info_only = false;
2975 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
2976 *m_debugged_process_sp, threads_with_valid_stop_info_only);
2977 if (!threads_array_sp) {
2978 if (log)
2979 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
2980 "packet for pid %" PRIu64,
2981 __FUNCTION__, m_debugged_process_sp->GetID());
2982 return SendErrorResponse(52);
2983 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00002984
Kate Stoneb9c1b512016-09-06 20:57:50 +00002985 threads_array_sp->Write(response);
2986 StreamGDBRemote escaped_response;
2987 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
2988 return SendPacketNoLock(escaped_response.GetString());
Pavel Labath4a4bb122015-07-16 14:14:35 +00002989}
2990
2991GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
2993 StringExtractorGDBRemote &packet) {
2994 // Fail if we don't have a current process.
2995 if (!m_debugged_process_sp ||
2996 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
2997 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002998
Kate Stoneb9c1b512016-09-06 20:57:50 +00002999 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3000 if (packet.GetBytesLeft() == 0)
3001 return SendOKResponse();
3002 if (packet.GetChar() != ':')
3003 return SendErrorResponse(67);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003004
Kate Stoneb9c1b512016-09-06 20:57:50 +00003005 uint32_t num = m_debugged_process_sp->GetMaxWatchpoints();
3006 StreamGDBRemote response;
3007 response.Printf("num:%d;", num);
3008 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00003009}
3010
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003011GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003012GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3013 StringExtractorGDBRemote &packet) {
3014 // Fail if we don't have a current process.
3015 if (!m_debugged_process_sp ||
3016 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3017 return SendErrorResponse(67);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003018
Kate Stoneb9c1b512016-09-06 20:57:50 +00003019 packet.SetFilePos(strlen("qFileLoadAddress:"));
3020 if (packet.GetBytesLeft() == 0)
3021 return SendErrorResponse(68);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003022
Kate Stoneb9c1b512016-09-06 20:57:50 +00003023 std::string file_name;
3024 packet.GetHexByteString(file_name);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003025
Kate Stoneb9c1b512016-09-06 20:57:50 +00003026 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3027 Error error =
3028 m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
3029 if (error.Fail())
3030 return SendErrorResponse(69);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003031
Kate Stoneb9c1b512016-09-06 20:57:50 +00003032 if (file_load_address == LLDB_INVALID_ADDRESS)
3033 return SendErrorResponse(1); // File not loaded
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003034
Kate Stoneb9c1b512016-09-06 20:57:50 +00003035 StreamGDBRemote response;
3036 response.PutHex64(file_load_address);
3037 return SendPacketNoLock(response.GetString());
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003038}
3039
Kate Stoneb9c1b512016-09-06 20:57:50 +00003040void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3041 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003042
Kate Stoneb9c1b512016-09-06 20:57:50 +00003043 // Tell the stdio connection to shut down.
3044 if (m_stdio_communication.IsConnected()) {
3045 auto connection = m_stdio_communication.GetConnection();
3046 if (connection) {
3047 Error error;
3048 connection->Disconnect(&error);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003049
Kate Stoneb9c1b512016-09-06 20:57:50 +00003050 if (error.Success()) {
3051 if (log)
3052 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3053 "terminal stdio - SUCCESS",
3054 __FUNCTION__);
3055 } else {
3056 if (log)
3057 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3058 "terminal stdio - FAIL: %s",
3059 __FUNCTION__, error.AsCString());
3060 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003061 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003062 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003063}
3064
Kate Stoneb9c1b512016-09-06 20:57:50 +00003065NativeThreadProtocolSP GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3066 StringExtractorGDBRemote &packet) {
3067 NativeThreadProtocolSP thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003068
Kate Stoneb9c1b512016-09-06 20:57:50 +00003069 // We have no thread if we don't have a process.
3070 if (!m_debugged_process_sp ||
3071 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
Tamas Berghammere13c2732015-02-11 10:29:30 +00003072 return thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003073
Kate Stoneb9c1b512016-09-06 20:57:50 +00003074 // If the client hasn't asked for thread suffix support, there will not be a
3075 // thread suffix.
3076 // Use the current thread in that case.
3077 if (!m_thread_suffix_supported) {
3078 const lldb::tid_t current_tid = GetCurrentThreadID();
3079 if (current_tid == LLDB_INVALID_THREAD_ID)
3080 return thread_sp;
3081 else if (current_tid == 0) {
3082 // Pick a thread.
3083 return m_debugged_process_sp->GetThreadAtIndex(0);
3084 } else
3085 return m_debugged_process_sp->GetThreadByID(current_tid);
3086 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003087
Kate Stoneb9c1b512016-09-06 20:57:50 +00003088 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003089
Kate Stoneb9c1b512016-09-06 20:57:50 +00003090 // Parse out the ';'.
3091 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
Tamas Berghammere13c2732015-02-11 10:29:30 +00003092 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003093 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3094 "error: expected ';' prior to start of thread suffix: packet "
3095 "contents = '%s'",
3096 __FUNCTION__, packet.GetStringRef().c_str());
3097 return thread_sp;
3098 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003099
Kate Stoneb9c1b512016-09-06 20:57:50 +00003100 if (!packet.GetBytesLeft())
3101 return thread_sp;
3102
3103 // Parse out thread: portion.
3104 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3105 if (log)
3106 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3107 "error: expected 'thread:' but not found, packet contents = "
3108 "'%s'",
3109 __FUNCTION__, packet.GetStringRef().c_str());
3110 return thread_sp;
3111 }
3112 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3113 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3114 if (tid != 0)
3115 return m_debugged_process_sp->GetThreadByID(tid);
3116
3117 return thread_sp;
3118}
3119
3120lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3121 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3122 // Use whatever the debug process says is the current thread id
3123 // since the protocol either didn't specify or specified we want
3124 // any/all threads marked as the current thread.
3125 if (!m_debugged_process_sp)
3126 return LLDB_INVALID_THREAD_ID;
3127 return m_debugged_process_sp->GetCurrentThreadID();
3128 }
3129 // Use the specific current thread id set by the gdb remote protocol.
3130 return m_current_tid;
3131}
3132
3133uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3134 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3135 return m_next_saved_registers_id++;
3136}
3137
3138void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
3139 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | GDBR_LOG_PROCESS));
3140 if (log)
3141 log->Printf("GDBRemoteCommunicationServerLLGS::%s()", __FUNCTION__);
3142
3143// Clear any auxv cached data.
3144// *BSD impls should be able to do this too.
Tamas Berghammere13c2732015-02-11 10:29:30 +00003145#if defined(__linux__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003146 if (log)
3147 log->Printf("GDBRemoteCommunicationServerLLGS::%s clearing auxv buffer "
3148 "(previously %s)",
3149 __FUNCTION__,
3150 m_active_auxv_buffer_sp ? "was set" : "was not set");
3151 m_active_auxv_buffer_sp.reset();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003152#endif
3153}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003154
3155FileSpec
Kate Stoneb9c1b512016-09-06 20:57:50 +00003156GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3157 const ArchSpec &arch) {
3158 if (m_debugged_process_sp) {
3159 FileSpec file_spec;
3160 if (m_debugged_process_sp
3161 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3162 .Success()) {
3163 if (file_spec.Exists())
3164 return file_spec;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003165 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003166 }
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003167
Kate Stoneb9c1b512016-09-06 20:57:50 +00003168 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003169}