blob: 5aa2f4985790f59fac6e48672630b55f44ee5bac [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"
Zachary Turnerfb1a0a02017-03-06 18:34:25 +000015#include "lldb/Utility/StreamGDBRemote.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000016
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
Tamas Berghammer9c9ecce2015-05-27 13:34:04 +000024#include "lldb/Core/RegisterValue.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000025#include "lldb/Core/State.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000026#include "lldb/Host/ConnectionFileDescriptor.h"
27#include "lldb/Host/Debug.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000028#include "lldb/Host/File.h"
29#include "lldb/Host/FileSystem.h"
30#include "lldb/Host/Host.h"
31#include "lldb/Host/HostInfo.h"
Pavel Labath1eb0d422016-08-08 12:54:36 +000032#include "lldb/Host/common/NativeProcessProtocol.h"
33#include "lldb/Host/common/NativeRegisterContext.h"
34#include "lldb/Host/common/NativeThreadProtocol.h"
35#include "lldb/Interpreter/Args.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000036#include "lldb/Target/FileAction.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000037#include "lldb/Target/MemoryRegionInfo.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000038#include "lldb/Utility/DataBuffer.h"
Zachary Turner01c32432017-02-14 19:06:07 +000039#include "lldb/Utility/Endian.h"
Pavel Labath4a4bb122015-07-16 14:14:35 +000040#include "lldb/Utility/JSON.h"
Pavel Labathabadc222015-11-27 13:33:29 +000041#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000042#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000043#include "lldb/Utility/StreamString.h"
Pavel Labath5f7e5832017-02-10 12:21:22 +000044#include "lldb/Utility/UriParser.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"
Tamas Berghammere13c2732015-02-11 10:29:30 +000052
53using namespace lldb;
54using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000055using namespace lldb_private::process_gdb_remote;
Tamas Berghammer783bfc82015-06-18 20:43:56 +000056using namespace llvm;
Tamas Berghammere13c2732015-02-11 10:29:30 +000057
58//----------------------------------------------------------------------
59// GDBRemote Errors
60//----------------------------------------------------------------------
61
Kate Stoneb9c1b512016-09-06 20:57:50 +000062namespace {
63enum GDBRemoteServerError {
64 // Set to the first unused error number in literal form below
65 eErrorFirst = 29,
66 eErrorNoProcess = eErrorFirst,
67 eErrorResume,
68 eErrorExitStatus
69};
Tamas Berghammere13c2732015-02-11 10:29:30 +000070}
71
72//----------------------------------------------------------------------
73// GDBRemoteCommunicationServerLLGS constructor
74//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000075GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
76 MainLoop &mainloop)
77 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
78 "gdb-remote.server.rx_packet"),
79 m_mainloop(mainloop), m_current_tid(LLDB_INVALID_THREAD_ID),
80 m_continue_tid(LLDB_INVALID_THREAD_ID), m_debugged_process_mutex(),
81 m_debugged_process_sp(), m_stdio_communication("process.stdio"),
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +000082 m_inferior_prev_state(StateType::eStateInvalid),
Kate Stoneb9c1b512016-09-06 20:57:50 +000083 m_saved_registers_map(), m_next_saved_registers_id(1),
84 m_handshake_completed(false) {
85 RegisterPacketHandlers();
Tamas Berghammere13c2732015-02-11 10:29:30 +000086}
87
Kate Stoneb9c1b512016-09-06 20:57:50 +000088void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
89 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
90 &GDBRemoteCommunicationServerLLGS::Handle_C);
91 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
92 &GDBRemoteCommunicationServerLLGS::Handle_c);
93 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
94 &GDBRemoteCommunicationServerLLGS::Handle_D);
95 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
96 &GDBRemoteCommunicationServerLLGS::Handle_H);
97 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
98 &GDBRemoteCommunicationServerLLGS::Handle_I);
99 RegisterMemberFunctionHandler(
100 StringExtractorGDBRemote::eServerPacketType_interrupt,
101 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
102 RegisterMemberFunctionHandler(
103 StringExtractorGDBRemote::eServerPacketType_m,
104 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
105 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
106 &GDBRemoteCommunicationServerLLGS::Handle_M);
107 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
108 &GDBRemoteCommunicationServerLLGS::Handle_p);
109 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
110 &GDBRemoteCommunicationServerLLGS::Handle_P);
111 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
112 &GDBRemoteCommunicationServerLLGS::Handle_qC);
113 RegisterMemberFunctionHandler(
114 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
115 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
116 RegisterMemberFunctionHandler(
117 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
118 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
119 RegisterMemberFunctionHandler(
120 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
121 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
122 RegisterMemberFunctionHandler(
123 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
124 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
125 RegisterMemberFunctionHandler(
126 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
127 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
128 RegisterMemberFunctionHandler(
129 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
130 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
131 RegisterMemberFunctionHandler(
132 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
133 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
134 RegisterMemberFunctionHandler(
135 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
136 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
137 RegisterMemberFunctionHandler(
138 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
139 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
140 RegisterMemberFunctionHandler(
141 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
142 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
143 RegisterMemberFunctionHandler(
144 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
145 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
146 RegisterMemberFunctionHandler(
147 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
148 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
149 RegisterMemberFunctionHandler(
150 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
151 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
152 RegisterMemberFunctionHandler(
153 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
154 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
155 RegisterMemberFunctionHandler(
156 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
157 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
158 RegisterMemberFunctionHandler(
159 StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
160 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
161 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
162 &GDBRemoteCommunicationServerLLGS::Handle_s);
163 RegisterMemberFunctionHandler(
164 StringExtractorGDBRemote::eServerPacketType_stop_reason,
165 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
166 RegisterMemberFunctionHandler(
167 StringExtractorGDBRemote::eServerPacketType_vAttach,
168 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
169 RegisterMemberFunctionHandler(
170 StringExtractorGDBRemote::eServerPacketType_vCont,
171 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
172 RegisterMemberFunctionHandler(
173 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
174 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
175 RegisterMemberFunctionHandler(
176 StringExtractorGDBRemote::eServerPacketType_x,
177 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
178 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
179 &GDBRemoteCommunicationServerLLGS::Handle_Z);
180 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
181 &GDBRemoteCommunicationServerLLGS::Handle_z);
Pavel Labath4a705e72017-02-24 09:29:14 +0000182 RegisterMemberFunctionHandler(
183 StringExtractorGDBRemote::eServerPacketType_QPassSignals,
184 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000185
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +0000186 RegisterMemberFunctionHandler(
187 StringExtractorGDBRemote::eServerPacketType_jTraceStart,
188 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart);
189 RegisterMemberFunctionHandler(
190 StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead,
191 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
192 RegisterMemberFunctionHandler(
193 StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead,
194 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
195 RegisterMemberFunctionHandler(
196 StringExtractorGDBRemote::eServerPacketType_jTraceStop,
197 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop);
198 RegisterMemberFunctionHandler(
199 StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead,
200 &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead);
201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
Zachary Turner97206d52017-05-12 04:51:55 +0000203 [this](StringExtractorGDBRemote packet, Status &error,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204 bool &interrupt, bool &quit) {
205 quit = true;
206 return this->Handle_k(packet);
207 });
Tamas Berghammere13c2732015-02-11 10:29:30 +0000208}
209
Zachary Turner97206d52017-05-12 04:51:55 +0000210Status
211GDBRemoteCommunicationServerLLGS::SetLaunchArguments(const char *const args[],
212 int argc) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213 if ((argc < 1) || !args || !args[0] || !args[0][0])
Zachary Turner97206d52017-05-12 04:51:55 +0000214 return Status("%s: no process command line specified to launch",
215 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000216
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217 m_process_launch_info.SetArguments(const_cast<const char **>(args), true);
Zachary Turner97206d52017-05-12 04:51:55 +0000218 return Status();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000219}
220
Zachary Turner97206d52017-05-12 04:51:55 +0000221Status
222GDBRemoteCommunicationServerLLGS::SetLaunchFlags(unsigned int launch_flags) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 m_process_launch_info.GetFlags().Set(launch_flags);
Zachary Turner97206d52017-05-12 04:51:55 +0000224 return Status();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000225}
226
Zachary Turner97206d52017-05-12 04:51:55 +0000227Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000229
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 if (!m_process_launch_info.GetArguments().GetArgumentCount())
Zachary Turner97206d52017-05-12 04:51:55 +0000231 return Status("%s: no process command line specified to launch",
232 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000233
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234 const bool should_forward_stdio =
235 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
236 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
237 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
238 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
239 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
Pavel Labath5ad891f2016-07-21 14:54:03 +0000240
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241 const bool default_to_use_pty = true;
242 m_process_launch_info.FinalizeFileActions(nullptr, default_to_use_pty);
Pavel Labath5ad891f2016-07-21 14:54:03 +0000243
Zachary Turner97206d52017-05-12 04:51:55 +0000244 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 {
246 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
247 assert(!m_debugged_process_sp && "lldb-server creating debugged "
248 "process but one already exists");
249 error = NativeProcessProtocol::Launch(m_process_launch_info, *this,
250 m_mainloop, m_debugged_process_sp);
251 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000252
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 if (!error.Success()) {
254 fprintf(stderr, "%s: failed to launch executable %s", __FUNCTION__,
255 m_process_launch_info.GetArguments().GetArgumentAtIndex(0));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000256 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000258
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
260 // as needed.
261 // llgs local-process debugging may specify PTY paths, which will make these
262 // file actions non-null
263 // process launch -i/e/o will also make these file actions non-null
264 // nullptr means that the traffic is expected to flow over gdb-remote protocol
265 if (should_forward_stdio) {
266 // nullptr means it's not redirected to file or pty (in case of LLGS local)
267 // at least one of stdio will be transferred pty<->gdb-remote
268 // we need to give the pty master handle to this object to read and/or write
Tamas Berghammere13c2732015-02-11 10:29:30 +0000269 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270 log->Printf(
271 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
272 " setting up stdout/stderr redirection via $O gdb-remote commands",
273 __FUNCTION__, m_debugged_process_sp->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000274
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275 // Setup stdout/stderr mapping from inferior to $O
276 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
277 if (terminal_fd >= 0) {
278 if (log)
279 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
280 "inferior STDIO fd to %d",
281 __FUNCTION__, terminal_fd);
282 error = SetSTDIOFileDescriptor(terminal_fd);
283 if (error.Fail())
Tamas Berghammere13c2732015-02-11 10:29:30 +0000284 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285 } else {
286 if (log)
287 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
288 "inferior STDIO since terminal fd reported as %d",
289 __FUNCTION__, terminal_fd);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000290 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000291 } else {
292 if (log)
293 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
294 " skipping stdout/stderr redirection via $O: inferior will "
295 "communicate over client-provided file descriptors",
296 __FUNCTION__, m_debugged_process_sp->GetID());
297 }
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000298
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299 printf("Launched '%s' as process %" PRIu64 "...\n",
300 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
301 m_process_launch_info.GetProcessID());
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000302
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303 return error;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000304}
305
Zachary Turner97206d52017-05-12 04:51:55 +0000306Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
307 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308
309 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
310 if (log)
311 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
312 __FUNCTION__, pid);
313
314 // Before we try to attach, make sure we aren't already monitoring something
315 // else.
316 if (m_debugged_process_sp &&
317 m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID)
Zachary Turner97206d52017-05-12 04:51:55 +0000318 return Status("cannot attach to a process %" PRIu64
319 " when another process with pid %" PRIu64
320 " is being debugged.",
321 pid, m_debugged_process_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322
323 // Try to attach.
324 error = NativeProcessProtocol::Attach(pid, *this, m_mainloop,
325 m_debugged_process_sp);
326 if (!error.Success()) {
327 fprintf(stderr, "%s: failed to attach to process %" PRIu64 ": %s",
328 __FUNCTION__, pid, error.AsCString());
329 return error;
330 }
331
332 // Setup stdout/stderr mapping from inferior.
333 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
334 if (terminal_fd >= 0) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000335 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
337 "inferior STDIO fd to %d",
338 __FUNCTION__, terminal_fd);
339 error = SetSTDIOFileDescriptor(terminal_fd);
340 if (error.Fail())
341 return error;
342 } else {
343 if (log)
344 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
345 "inferior STDIO since terminal fd reported as %d",
346 __FUNCTION__, terminal_fd);
347 }
348
349 printf("Attached to process %" PRIu64 "...\n", pid);
350
351 return error;
352}
353
354void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
355 NativeProcessProtocol *process) {
356 assert(process && "process cannot be NULL");
357 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
358 if (log) {
359 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
360 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
361 __FUNCTION__, process->GetID(),
362 StateAsCString(process->GetState()));
363 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000364}
365
366GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367GDBRemoteCommunicationServerLLGS::SendWResponse(
368 NativeProcessProtocol *process) {
369 assert(process && "process cannot be NULL");
370 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000371
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372 // send W notification
373 ExitType exit_type = ExitType::eExitTypeInvalid;
374 int return_code = 0;
375 std::string exit_description;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000376
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 const bool got_exit_info =
378 process->GetExitStatus(&exit_type, &return_code, exit_description);
379 if (!got_exit_info) {
380 if (log)
381 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
382 ", failed to retrieve process exit status",
383 __FUNCTION__, process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000384
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 StreamGDBRemote response;
386 response.PutChar('E');
387 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
388 return SendPacketNoLock(response.GetString());
389 } else {
390 if (log)
391 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
392 ", returning exit type %d, return code %d [%s]",
393 __FUNCTION__, process->GetID(), exit_type, return_code,
394 exit_description.c_str());
395
396 StreamGDBRemote response;
397
398 char return_type_code;
399 switch (exit_type) {
400 case ExitType::eExitTypeExit:
401 return_type_code = 'W';
402 break;
403 case ExitType::eExitTypeSignal:
404 return_type_code = 'X';
405 break;
406 case ExitType::eExitTypeStop:
407 return_type_code = 'S';
408 break;
409 case ExitType::eExitTypeInvalid:
410 return_type_code = 'E';
411 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000412 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 response.PutChar(return_type_code);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000414
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 // POSIX exit status limited to unsigned 8 bits.
416 response.PutHex8(return_code);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000417
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418 return SendPacketNoLock(response.GetString());
419 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000420}
421
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422static void AppendHexValue(StreamString &response, const uint8_t *buf,
423 uint32_t buf_size, bool swap) {
424 int64_t i;
425 if (swap) {
426 for (i = buf_size - 1; i >= 0; i--)
427 response.PutHex8(buf[i]);
428 } else {
429 for (i = 0; i < buf_size; i++)
430 response.PutHex8(buf[i]);
431 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000432}
433
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434static void WriteRegisterValueInHexFixedWidth(
435 StreamString &response, NativeRegisterContextSP &reg_ctx_sp,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000436 const RegisterInfo &reg_info, const RegisterValue *reg_value_p,
437 lldb::ByteOrder byte_order) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438 RegisterValue reg_value;
439 if (!reg_value_p) {
Zachary Turner97206d52017-05-12 04:51:55 +0000440 Status error = reg_ctx_sp->ReadRegister(&reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441 if (error.Success())
442 reg_value_p = &reg_value;
443 // else log.
444 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000445
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 if (reg_value_p) {
447 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
Pavel Labathe0a5b572017-01-20 14:17:16 +0000448 reg_value_p->GetByteSize(),
449 byte_order == lldb::eByteOrderLittle);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 } else {
451 // Zero-out any unreadable values.
452 if (reg_info.byte_size > 0) {
453 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
454 AppendHexValue(response, zeros.data(), zeros.size(), false);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000455 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000457}
458
Pavel Labathe0a5b572017-01-20 14:17:16 +0000459static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Pavel Labath4a4bb122015-07-16 14:14:35 +0000461
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
463 if (!reg_ctx_sp)
464 return nullptr;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000465
Kate Stoneb9c1b512016-09-06 20:57:50 +0000466 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000467
468#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 // Expedite all registers in the first register set (i.e. should be GPRs) that
470 // are not contained in other registers.
471 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
472 if (!reg_set_p)
473 return nullptr;
474 for (const uint32_t *reg_num_p = reg_set_p->registers;
475 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
476 uint32_t reg_num = *reg_num_p;
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000477#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478 // Expedite only a couple of registers until we figure out why sending
479 // registers is
480 // expensive.
481 static const uint32_t k_expedited_registers[] = {
482 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
483 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
Pavel Labathc4645bb2015-10-26 16:25:28 +0000484
Pavel Labathe0a5b572017-01-20 14:17:16 +0000485 for (const uint32_t *generic_reg_p = k_expedited_registers;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
487 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
488 eRegisterKindGeneric, *generic_reg_p);
489 if (reg_num == LLDB_INVALID_REGNUM)
490 continue; // Target does not support the given register.
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000491#endif
492
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493 const RegisterInfo *const reg_info_p =
494 reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
495 if (reg_info_p == nullptr) {
496 if (log)
497 log->Printf(
498 "%s failed to get register info for register index %" PRIu32,
499 __FUNCTION__, reg_num);
500 continue;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000501 }
502
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 if (reg_info_p->value_regs != nullptr)
504 continue; // Only expedite registers that are not contained in other
505 // registers.
Pavel Labath4a4bb122015-07-16 14:14:35 +0000506
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000508 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509 if (error.Fail()) {
510 if (log)
511 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
Pavel Labath05569f62015-07-23 09:09:29 +0000512 __FUNCTION__,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000513 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
514 reg_num, error.AsCString());
515 continue;
Pavel Labath05569f62015-07-23 09:09:29 +0000516 }
517
Kate Stoneb9c1b512016-09-06 20:57:50 +0000518 StreamString stream;
519 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000520 &reg_value, lldb::eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521
522 register_object_sp->SetObject(
523 llvm::to_string(reg_num),
524 std::make_shared<JSONString>(stream.GetString()));
525 }
526
527 return register_object_sp;
Pavel Labath05569f62015-07-23 09:09:29 +0000528}
529
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530static const char *GetStopReasonString(StopReason stop_reason) {
531 switch (stop_reason) {
532 case eStopReasonTrace:
533 return "trace";
534 case eStopReasonBreakpoint:
535 return "breakpoint";
536 case eStopReasonWatchpoint:
537 return "watchpoint";
538 case eStopReasonSignal:
539 return "signal";
540 case eStopReasonException:
541 return "exception";
542 case eStopReasonExec:
543 return "exec";
544 case eStopReasonInstrumentation:
545 case eStopReasonInvalid:
546 case eStopReasonPlanComplete:
547 case eStopReasonThreadExiting:
548 case eStopReasonNone:
549 break; // ignored
550 }
551 return nullptr;
552}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000553
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
555 bool abridged) {
556 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000557
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000559
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 // Ensure we can get info on the given thread.
561 uint32_t thread_idx = 0;
562 for (NativeThreadProtocolSP thread_sp;
563 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
564 ++thread_idx) {
565
566 lldb::tid_t tid = thread_sp->GetID();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000567
568 // Grab the reason this thread stopped.
569 struct ThreadStopInfo tid_stop_info;
570 std::string description;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 if (!thread_sp->GetStopReason(tid_stop_info, description))
572 return nullptr;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000573
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 const int signum = tid_stop_info.details.signal.signo;
575 if (log) {
576 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
577 " tid %" PRIu64
578 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
579 __FUNCTION__, process.GetID(), tid, signum,
580 tid_stop_info.reason, tid_stop_info.details.exception.type);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000581 }
582
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
584 threads_array_sp->AppendObject(thread_obj_sp);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000585
Pavel Labathe0a5b572017-01-20 14:17:16 +0000586 if (!abridged) {
587 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp))
588 thread_obj_sp->SetObject("registers", registers_sp);
589 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000590
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
592 if (signum != 0)
593 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000594
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595 const std::string thread_name = thread_sp->GetName();
596 if (!thread_name.empty())
597 thread_obj_sp->SetObject("name",
598 std::make_shared<JSONString>(thread_name));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000599
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
601 thread_obj_sp->SetObject("reason",
602 std::make_shared<JSONString>(stop_reason_str));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000603
604 if (!description.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 thread_obj_sp->SetObject("description",
606 std::make_shared<JSONString>(description));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000607
Kate Stoneb9c1b512016-09-06 20:57:50 +0000608 if ((tid_stop_info.reason == eStopReasonException) &&
609 tid_stop_info.details.exception.type) {
610 thread_obj_sp->SetObject(
611 "metype",
612 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
613
614 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
615 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
616 ++i) {
617 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
618 tid_stop_info.details.exception.data[i]));
619 }
620 thread_obj_sp->SetObject("medata", medata_array_sp);
621 }
622
623 // TODO: Expedite interesting regions of inferior memory
624 }
625
626 return threads_array_sp;
627}
628
629GDBRemoteCommunication::PacketResult
630GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
631 lldb::tid_t tid) {
632 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
633
634 // Ensure we have a debugged process.
635 if (!m_debugged_process_sp ||
636 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
637 return SendErrorResponse(50);
638
639 if (log)
640 log->Printf(
641 "GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64
642 " tid %" PRIu64,
643 __FUNCTION__, m_debugged_process_sp->GetID(), tid);
644
645 // Ensure we can get info on the given thread.
646 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
647 if (!thread_sp)
648 return SendErrorResponse(51);
649
650 // Grab the reason this thread stopped.
651 struct ThreadStopInfo tid_stop_info;
652 std::string description;
653 if (!thread_sp->GetStopReason(tid_stop_info, description))
654 return SendErrorResponse(52);
655
656 // FIXME implement register handling for exec'd inferiors.
657 // if (tid_stop_info.reason == eStopReasonExec)
658 // {
659 // const bool force = true;
660 // InitializeRegisters(force);
661 // }
662
663 StreamString response;
664 // Output the T packet with the thread
665 response.PutChar('T');
666 int signum = tid_stop_info.details.signal.signo;
667 if (log) {
668 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
669 " tid %" PRIu64
670 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
671 __FUNCTION__, m_debugged_process_sp->GetID(), tid, signum,
672 tid_stop_info.reason, tid_stop_info.details.exception.type);
673 }
674
675 // Print the signal number.
676 response.PutHex8(signum & 0xff);
677
678 // Include the tid.
679 response.Printf("thread:%" PRIx64 ";", tid);
680
681 // Include the thread name if there is one.
682 const std::string thread_name = thread_sp->GetName();
683 if (!thread_name.empty()) {
684 size_t thread_name_len = thread_name.length();
685
686 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
687 response.PutCString("name:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000688 response.PutCString(thread_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689 } else {
690 // The thread name contains special chars, send as hex bytes.
691 response.PutCString("hexname:");
692 response.PutCStringAsRawHex8(thread_name.c_str());
693 }
694 response.PutChar(';');
695 }
696
697 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
698 // will send all thread IDs back in the "threads" key whose value is
699 // a list of hex thread IDs separated by commas:
700 // "threads:10a,10b,10c;"
701 // This will save the debugger from having to send a pair of qfThreadInfo
702 // and qsThreadInfo packets, but it also might take a lot of room in the
703 // stop reply packet, so it must be enabled only on systems where there
704 // are no limits on packet lengths.
705 if (m_list_threads_in_stop_reply) {
706 response.PutCString("threads:");
707
708 uint32_t thread_index = 0;
709 NativeThreadProtocolSP listed_thread_sp;
710 for (listed_thread_sp =
711 m_debugged_process_sp->GetThreadAtIndex(thread_index);
712 listed_thread_sp; ++thread_index,
713 listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex(
714 thread_index)) {
715 if (thread_index > 0)
716 response.PutChar(',');
717 response.Printf("%" PRIx64, listed_thread_sp->GetID());
718 }
719 response.PutChar(';');
720
721 // Include JSON info that describes the stop reason for any threads
722 // that actually have stop reasons. We use the new "jstopinfo" key
723 // whose values is hex ascii JSON that contains the thread IDs
724 // thread stop info only for threads that have stop reasons. Only send
725 // this if we have more than one thread otherwise this packet has all
726 // the info it needs.
727 if (thread_index > 0) {
728 const bool threads_with_valid_stop_info_only = true;
729 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
730 *m_debugged_process_sp, threads_with_valid_stop_info_only);
731 if (threads_info_sp) {
732 response.PutCString("jstopinfo:");
733 StreamString unescaped_response;
734 threads_info_sp->Write(unescaped_response);
735 response.PutCStringAsRawHex8(unescaped_response.GetData());
736 response.PutChar(';');
737 } else if (log)
738 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
739 "jstopinfo field for pid %" PRIu64,
740 __FUNCTION__, m_debugged_process_sp->GetID());
741 }
Pavel Labathe0a5b572017-01-20 14:17:16 +0000742
743 uint32_t i = 0;
744 response.PutCString("thread-pcs");
745 char delimiter = ':';
746 for (NativeThreadProtocolSP thread_sp;
747 (thread_sp = m_debugged_process_sp->GetThreadAtIndex(i)) != nullptr;
748 ++i) {
749 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
750 if (!reg_ctx_sp)
751 continue;
752
753 uint32_t reg_to_read = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
754 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
755 const RegisterInfo *const reg_info_p =
756 reg_ctx_sp->GetRegisterInfoAtIndex(reg_to_read);
757
758 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000759 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Pavel Labathe0a5b572017-01-20 14:17:16 +0000760 if (error.Fail()) {
761 if (log)
762 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
763 __FUNCTION__,
764 reg_info_p->name ? reg_info_p->name
765 : "<unnamed-register>",
766 reg_to_read, error.AsCString());
767 continue;
768 }
769
770 response.PutChar(delimiter);
771 delimiter = ',';
772 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
773 &reg_value, endian::InlHostByteOrder());
774 }
775
776 response.PutChar(';');
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777 }
778
779 //
780 // Expedite registers.
781 //
782
783 // Grab the register context.
784 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
785 if (reg_ctx_sp) {
786 // Expedite all registers in the first register set (i.e. should be GPRs)
787 // that are not contained in other registers.
788 const RegisterSet *reg_set_p;
789 if (reg_ctx_sp->GetRegisterSetCount() > 0 &&
790 ((reg_set_p = reg_ctx_sp->GetRegisterSet(0)) != nullptr)) {
791 if (log)
792 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
793 "from set '%s' (registers set count: %zu)",
794 __FUNCTION__,
795 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
796 reg_set_p->num_registers);
797
798 for (const uint32_t *reg_num_p = reg_set_p->registers;
799 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
800 const RegisterInfo *const reg_info_p =
801 reg_ctx_sp->GetRegisterInfoAtIndex(*reg_num_p);
802 if (reg_info_p == nullptr) {
803 if (log)
804 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
805 "register info for register set '%s', register index "
806 "%" PRIu32,
807 __FUNCTION__,
808 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
809 *reg_num_p);
810 } else if (reg_info_p->value_regs == nullptr) {
811 // Only expediate registers that are not contained in other registers.
812 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000813 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 if (error.Success()) {
815 response.Printf("%.02x:", *reg_num_p);
816 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000817 &reg_value, lldb::eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 response.PutChar(';');
819 } else {
820 if (log)
821 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
822 "register '%s' index %" PRIu32 ": %s",
823 __FUNCTION__, reg_info_p->name ? reg_info_p->name
824 : "<unnamed-register>",
825 *reg_num_p, error.AsCString());
826 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000827 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000829 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000831
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
833 if (reason_str != nullptr) {
834 response.Printf("reason:%s;", reason_str);
835 }
836
837 if (!description.empty()) {
838 // Description may contains special chars, send as hex bytes.
839 response.PutCString("description:");
840 response.PutCStringAsRawHex8(description.c_str());
841 response.PutChar(';');
842 } else if ((tid_stop_info.reason == eStopReasonException) &&
843 tid_stop_info.details.exception.type) {
844 response.PutCString("metype:");
845 response.PutHex64(tid_stop_info.details.exception.type);
846 response.PutCString(";mecount:");
847 response.PutHex32(tid_stop_info.details.exception.data_count);
848 response.PutChar(';');
849
850 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
851 response.PutCString("medata:");
852 response.PutHex64(tid_stop_info.details.exception.data[i]);
853 response.PutChar(';');
854 }
855 }
856
857 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000858}
859
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
861 NativeProcessProtocol *process) {
862 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000863
Kate Stoneb9c1b512016-09-06 20:57:50 +0000864 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
865 if (log)
866 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
867
868 PacketResult result = SendStopReasonForState(StateType::eStateExited);
869 if (result != PacketResult::Success) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000870 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000871 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
872 "notification for PID %" PRIu64 ", state: eStateExited",
873 __FUNCTION__, process->GetID());
874 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000875
Kate Stoneb9c1b512016-09-06 20:57:50 +0000876 // Close the pipe to the inferior terminal i/o if we launched it
877 // and set one up.
878 MaybeCloseInferiorTerminalConnection();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000879
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 // We are ready to exit the debug monitor.
881 m_exit_now = true;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000882}
883
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
885 NativeProcessProtocol *process) {
886 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000887
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
889 if (log)
890 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000891
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892 // Send the stop reason unless this is the stop after the
893 // launch or attach.
894 switch (m_inferior_prev_state) {
895 case eStateLaunching:
896 case eStateAttaching:
897 // Don't send anything per debugserver behavior.
898 break;
899 default:
900 // In all other cases, send the stop reason.
901 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
902 if (result != PacketResult::Success) {
903 if (log)
904 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
905 "notification for PID %" PRIu64 ", state: eStateExited",
906 __FUNCTION__, process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000907 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 break;
909 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000910}
911
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
913 NativeProcessProtocol *process, lldb::StateType state) {
914 assert(process && "process cannot be NULL");
915 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
916 if (log) {
917 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
918 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
919 __FUNCTION__, process->GetID(), StateAsCString(state));
920 }
921
922 switch (state) {
923 case StateType::eStateRunning:
924 StartSTDIOForwarding();
925 break;
926
927 case StateType::eStateStopped:
928 // Make sure we get all of the pending stdout/stderr from the inferior
929 // and send it to the lldb host before we send the state change
930 // notification
931 SendProcessOutput();
932 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
933 // does not
934 // interfere with our protocol.
935 StopSTDIOForwarding();
936 HandleInferiorState_Stopped(process);
937 break;
938
939 case StateType::eStateExited:
940 // Same as above
941 SendProcessOutput();
942 StopSTDIOForwarding();
943 HandleInferiorState_Exited(process);
944 break;
945
946 default:
947 if (log) {
948 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
949 "change for pid %" PRIu64 ", new state: %s",
950 __FUNCTION__, process->GetID(), StateAsCString(state));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000951 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 break;
953 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000954
Kate Stoneb9c1b512016-09-06 20:57:50 +0000955 // Remember the previous state reported to us.
956 m_inferior_prev_state = state;
957}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000958
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
960 ClearProcessSpecificData();
961}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000962
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
964 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
965
966 if (!m_handshake_completed) {
967 if (!HandshakeWithClient()) {
968 if (log)
969 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
970 "client failed, exiting",
971 __FUNCTION__);
972 m_mainloop.RequestTermination();
973 return;
974 }
975 m_handshake_completed = true;
976 }
977
978 bool interrupt = false;
979 bool done = false;
Zachary Turner97206d52017-05-12 04:51:55 +0000980 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 while (true) {
Pavel Labath1eff73c2016-11-24 10:54:49 +0000982 const PacketResult result = GetPacketAndSendResponse(
983 std::chrono::microseconds(0), error, interrupt, done);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 if (result == PacketResult::ErrorReplyTimeout)
985 break; // No more packets in the queue
986
987 if ((result != PacketResult::Success)) {
988 if (log)
989 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
990 "failed: %s",
991 __FUNCTION__, error.AsCString());
992 m_mainloop.RequestTermination();
993 break;
994 }
995 }
996}
997
Zachary Turner97206d52017-05-12 04:51:55 +0000998Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 std::unique_ptr<Connection> &&connection) {
1000 IOObjectSP read_object_sp = connection->GetReadObject();
1001 GDBRemoteCommunicationServer::SetConnection(connection.release());
1002
Zachary Turner97206d52017-05-12 04:51:55 +00001003 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004 m_network_handle_up = m_mainloop.RegisterReadObject(
1005 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
1006 error);
1007 return error;
1008}
1009
1010GDBRemoteCommunication::PacketResult
1011GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
1012 uint32_t len) {
1013 if ((buffer == nullptr) || (len == 0)) {
1014 // Nothing to send.
1015 return PacketResult::Success;
1016 }
1017
1018 StreamString response;
1019 response.PutChar('O');
1020 response.PutBytesAsRawHex8(buffer, len);
1021
1022 return SendPacketNoLock(response.GetString());
1023}
1024
Zachary Turner97206d52017-05-12 04:51:55 +00001025Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
1026 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027
1028 // Set up the reading/handling of process I/O
1029 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1030 new ConnectionFileDescriptor(fd, true));
1031 if (!conn_up) {
1032 error.SetErrorString("failed to create ConnectionFileDescriptor");
1033 return error;
1034 }
1035
1036 m_stdio_communication.SetCloseOnEOF(false);
1037 m_stdio_communication.SetConnection(conn_up.release());
1038 if (!m_stdio_communication.IsConnected()) {
1039 error.SetErrorString(
1040 "failed to set connection for inferior I/O communication");
1041 return error;
1042 }
1043
Zachary Turner97206d52017-05-12 04:51:55 +00001044 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045}
1046
1047void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1048 // Don't forward if not connected (e.g. when attaching).
1049 if (!m_stdio_communication.IsConnected())
1050 return;
1051
Zachary Turner97206d52017-05-12 04:51:55 +00001052 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001053 lldbassert(!m_stdio_handle_up);
1054 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1055 m_stdio_communication.GetConnection()->GetReadObject(),
1056 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1057
1058 if (!m_stdio_handle_up) {
1059 // Not much we can do about the failure. Log it and continue without
1060 // forwarding.
1061 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1062 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1063 "forwarding: %s",
1064 __FUNCTION__, error.AsCString());
1065 }
1066}
1067
1068void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1069 m_stdio_handle_up.reset();
1070}
1071
1072void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1073 char buffer[1024];
1074 ConnectionStatus status;
Zachary Turner97206d52017-05-12 04:51:55 +00001075 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076 while (true) {
Pavel Labathc4063ee2016-11-25 11:58:44 +00001077 size_t bytes_read = m_stdio_communication.Read(
1078 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079 switch (status) {
1080 case eConnectionStatusSuccess:
1081 SendONotification(buffer, bytes_read);
1082 break;
1083 case eConnectionStatusLostConnection:
1084 case eConnectionStatusEndOfFile:
1085 case eConnectionStatusError:
1086 case eConnectionStatusNoConnection:
1087 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1088 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1089 "forwarding as communication returned status %d (error: "
1090 "%s)",
1091 __FUNCTION__, status, error.AsCString());
1092 m_stdio_handle_up.reset();
1093 return;
1094
1095 case eConnectionStatusInterrupted:
1096 case eConnectionStatusTimedOut:
1097 return;
1098 }
1099 }
1100}
1101
1102GDBRemoteCommunication::PacketResult
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001103GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1104 StringExtractorGDBRemote &packet) {
1105 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1106 // Fail if we don't have a current process.
1107 if (!m_debugged_process_sp ||
1108 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1109 return SendErrorResponse(68);
1110
1111 if (!packet.ConsumeFront("jTraceStart:"))
1112 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1113
1114 TraceOptions options;
1115 uint64_t type = std::numeric_limits<uint64_t>::max();
1116 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1117 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1118 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1119
1120 auto json_object = StructuredData::ParseJSON(packet.Peek());
1121
1122 if (!json_object ||
1123 json_object->GetType() != StructuredData::Type::eTypeDictionary)
1124 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1125
1126 auto json_dict = json_object->GetAsDictionary();
1127
Pavel Labath4c950232017-05-26 13:53:39 +00001128 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001129 options.setMetaDataBufferSize(metabuffersize);
1130
Pavel Labath4c950232017-05-26 13:53:39 +00001131 json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001132 options.setTraceBufferSize(buffersize);
1133
Pavel Labath4c950232017-05-26 13:53:39 +00001134 json_dict->GetValueForKeyAsInteger("type", type);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001135 options.setType(static_cast<lldb::TraceType>(type));
1136
Pavel Labath4c950232017-05-26 13:53:39 +00001137 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001138 options.setThreadID(tid);
1139
1140 StructuredData::ObjectSP custom_params_sp =
1141 json_dict->GetValueForKey("params");
1142 if (custom_params_sp &&
1143 custom_params_sp->GetType() != StructuredData::Type::eTypeDictionary)
1144 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1145
1146 options.setTraceParams(
1147 static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1148
1149 if (buffersize == std::numeric_limits<uint64_t>::max() ||
1150 type != lldb::TraceType::eTraceTypeProcessorTrace) {
1151 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1152 type);
1153 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1154 }
1155
1156 Status error;
1157 lldb::user_id_t uid = LLDB_INVALID_UID;
1158 uid = m_debugged_process_sp->StartTrace(options, error);
1159 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1160 if (error.Fail())
1161 return SendErrorResponse(error.GetError());
1162
1163 StreamGDBRemote response;
1164 response.Printf("%" PRIx64, uid);
1165 return SendPacketNoLock(response.GetString());
1166}
1167
1168GDBRemoteCommunication::PacketResult
1169GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1170 StringExtractorGDBRemote &packet) {
1171 // Fail if we don't have a current process.
1172 if (!m_debugged_process_sp ||
1173 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1174 return SendErrorResponse(68);
1175
1176 if (!packet.ConsumeFront("jTraceStop:"))
1177 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1178
1179 lldb::user_id_t uid = LLDB_INVALID_UID;
1180 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1181
1182 auto json_object = StructuredData::ParseJSON(packet.Peek());
1183
1184 if (!json_object ||
1185 json_object->GetType() != StructuredData::Type::eTypeDictionary)
1186 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1187
1188 auto json_dict = json_object->GetAsDictionary();
1189
Pavel Labath4c950232017-05-26 13:53:39 +00001190 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001191 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1192
Pavel Labath4c950232017-05-26 13:53:39 +00001193 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001194
1195 Status error = m_debugged_process_sp->StopTrace(uid, tid);
1196
1197 if (error.Fail())
1198 return SendErrorResponse(error.GetError());
1199
1200 return SendOKResponse();
1201}
1202
1203GDBRemoteCommunication::PacketResult
1204GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1205 StringExtractorGDBRemote &packet) {
1206
1207 // Fail if we don't have a current process.
1208 if (!m_debugged_process_sp ||
1209 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1210 return SendErrorResponse(68);
1211
1212 if (!packet.ConsumeFront("jTraceConfigRead:"))
1213 return SendIllFormedResponse(packet,
1214 "jTraceConfigRead: Ill formed packet ");
1215
1216 lldb::user_id_t uid = LLDB_INVALID_UID;
1217 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1218
1219 auto json_object = StructuredData::ParseJSON(packet.Peek());
1220
1221 if (!json_object ||
1222 json_object->GetType() != StructuredData::Type::eTypeDictionary)
1223 return SendIllFormedResponse(packet,
1224 "jTraceConfigRead: Ill formed packet ");
1225
1226 auto json_dict = json_object->GetAsDictionary();
1227
Pavel Labath4c950232017-05-26 13:53:39 +00001228 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001229 return SendIllFormedResponse(packet,
1230 "jTraceConfigRead: Ill formed packet ");
1231
Pavel Labath4c950232017-05-26 13:53:39 +00001232 json_dict->GetValueForKeyAsInteger("threadid", threadid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001233
1234 TraceOptions options;
1235 StreamGDBRemote response;
1236
1237 options.setThreadID(threadid);
1238 Status error = m_debugged_process_sp->GetTraceConfig(uid, options);
1239
1240 if (error.Fail())
1241 return SendErrorResponse(error.GetError());
1242
1243 StreamGDBRemote escaped_response;
1244 StructuredData::Dictionary json_packet;
1245
1246 json_packet.AddIntegerItem("type", options.getType());
1247 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1248 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1249
1250 StructuredData::DictionarySP custom_params = options.getTraceParams();
1251 if (custom_params)
1252 json_packet.AddItem("params", custom_params);
1253
1254 StreamString json_string;
1255 json_packet.Dump(json_string, false);
1256 escaped_response.PutEscapedBytes(json_string.GetData(),
1257 json_string.GetSize());
1258 return SendPacketNoLock(escaped_response.GetString());
1259}
1260
1261GDBRemoteCommunication::PacketResult
1262GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1263 StringExtractorGDBRemote &packet) {
1264
1265 // Fail if we don't have a current process.
1266 if (!m_debugged_process_sp ||
1267 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1268 return SendErrorResponse(68);
1269
1270 enum PacketType { MetaData, BufferData };
1271 PacketType tracetype = MetaData;
1272
1273 if (packet.ConsumeFront("jTraceBufferRead:"))
1274 tracetype = BufferData;
1275 else if (packet.ConsumeFront("jTraceMetaRead:"))
1276 tracetype = MetaData;
1277 else {
1278 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1279 }
1280
1281 lldb::user_id_t uid = LLDB_INVALID_UID;
1282
1283 size_t byte_count = std::numeric_limits<size_t>::max();
1284 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1285 size_t offset = std::numeric_limits<size_t>::max();
1286
1287 auto json_object = StructuredData::ParseJSON(packet.Peek());
1288
1289 if (!json_object ||
1290 json_object->GetType() != StructuredData::Type::eTypeDictionary)
1291 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1292
1293 auto json_dict = json_object->GetAsDictionary();
1294
Pavel Labath4c950232017-05-26 13:53:39 +00001295 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1296 !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1297 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001298 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1299
Pavel Labath4c950232017-05-26 13:53:39 +00001300 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001301
1302 // Allocate the response buffer.
1303 uint8_t *buffer = new (std::nothrow) uint8_t[byte_count];
1304 if (buffer == nullptr)
1305 return SendErrorResponse(0x78);
1306
1307 StreamGDBRemote response;
1308 Status error;
1309 llvm::MutableArrayRef<uint8_t> buf(buffer, byte_count);
1310
1311 if (tracetype == BufferData)
1312 error = m_debugged_process_sp->GetData(uid, tid, buf, offset);
1313 else if (tracetype == MetaData)
1314 error = m_debugged_process_sp->GetMetaData(uid, tid, buf, offset);
1315
1316 if (error.Fail())
1317 return SendErrorResponse(error.GetError());
1318
1319 for (size_t i = 0; i < buf.size(); ++i)
1320 response.PutHex8(buf[i]);
1321
1322 StreamGDBRemote escaped_response;
1323 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1324 return SendPacketNoLock(escaped_response.GetString());
1325}
1326
1327GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001328GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1329 StringExtractorGDBRemote &packet) {
1330 // Fail if we don't have a current process.
1331 if (!m_debugged_process_sp ||
1332 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1333 return SendErrorResponse(68);
1334
1335 lldb::pid_t pid = m_debugged_process_sp->GetID();
1336
1337 if (pid == LLDB_INVALID_PROCESS_ID)
1338 return SendErrorResponse(1);
1339
1340 ProcessInstanceInfo proc_info;
1341 if (!Host::GetProcessInfo(pid, proc_info))
1342 return SendErrorResponse(1);
1343
1344 StreamString response;
1345 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1346 return SendPacketNoLock(response.GetString());
1347}
1348
1349GDBRemoteCommunication::PacketResult
1350GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1351 // Fail if we don't have a current process.
1352 if (!m_debugged_process_sp ||
1353 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1354 return SendErrorResponse(68);
1355
1356 // Make sure we set the current thread so g and p packets return
1357 // the data the gdb will expect.
1358 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1359 SetCurrentThreadID(tid);
1360
1361 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread();
1362 if (!thread_sp)
1363 return SendErrorResponse(69);
1364
1365 StreamString response;
1366 response.Printf("QC%" PRIx64, thread_sp->GetID());
1367
1368 return SendPacketNoLock(response.GetString());
1369}
1370
1371GDBRemoteCommunication::PacketResult
1372GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1373 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1374
1375 StopSTDIOForwarding();
1376
1377 if (!m_debugged_process_sp) {
1378 if (log)
1379 log->Printf(
1380 "GDBRemoteCommunicationServerLLGS::%s No debugged process found.",
1381 __FUNCTION__);
1382 return PacketResult::Success;
1383 }
1384
Zachary Turner97206d52017-05-12 04:51:55 +00001385 Status error = m_debugged_process_sp->Kill();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001386 if (error.Fail() && log)
1387 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged "
1388 "process %" PRIu64 ": %s",
1389 __FUNCTION__, m_debugged_process_sp->GetID(),
1390 error.AsCString());
1391
1392 // No OK response for kill packet.
1393 // return SendOKResponse ();
1394 return PacketResult::Success;
1395}
1396
1397GDBRemoteCommunication::PacketResult
1398GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1399 StringExtractorGDBRemote &packet) {
1400 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1401 if (packet.GetU32(0))
1402 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1403 else
1404 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1405 return SendOKResponse();
1406}
1407
1408GDBRemoteCommunication::PacketResult
1409GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1410 StringExtractorGDBRemote &packet) {
1411 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1412 std::string path;
1413 packet.GetHexByteString(path);
1414 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1415 return SendOKResponse();
1416}
1417
1418GDBRemoteCommunication::PacketResult
1419GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1420 StringExtractorGDBRemote &packet) {
1421 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1422 if (working_dir) {
1423 StreamString response;
1424 response.PutCStringAsRawHex8(working_dir.GetCString());
1425 return SendPacketNoLock(response.GetString());
1426 }
1427
1428 return SendErrorResponse(14);
1429}
1430
1431GDBRemoteCommunication::PacketResult
1432GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1433 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1434 if (log)
1435 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1436
1437 // Ensure we have a native process.
1438 if (!m_debugged_process_sp) {
1439 if (log)
1440 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1441 "shared pointer",
1442 __FUNCTION__);
1443 return SendErrorResponse(0x36);
1444 }
1445
1446 // Pull out the signal number.
1447 packet.SetFilePos(::strlen("C"));
1448 if (packet.GetBytesLeft() < 1) {
1449 // Shouldn't be using a C without a signal.
1450 return SendIllFormedResponse(packet, "C packet specified without signal.");
1451 }
1452 const uint32_t signo =
1453 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1454 if (signo == std::numeric_limits<uint32_t>::max())
1455 return SendIllFormedResponse(packet, "failed to parse signal number");
1456
1457 // Handle optional continue address.
1458 if (packet.GetBytesLeft() > 0) {
1459 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1460 if (*packet.Peek() == ';')
1461 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1462 else
1463 return SendIllFormedResponse(
1464 packet, "unexpected content after $C{signal-number}");
1465 }
1466
1467 ResumeActionList resume_actions(StateType::eStateRunning, 0);
Zachary Turner97206d52017-05-12 04:51:55 +00001468 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001469
1470 // We have two branches: what to do if a continue thread is specified (in
1471 // which case we target
1472 // sending the signal to that thread), or when we don't have a continue thread
1473 // set (in which
1474 // case we send a signal to the process).
1475
1476 // TODO discuss with Greg Clayton, make sure this makes sense.
1477
1478 lldb::tid_t signal_tid = GetContinueThreadID();
1479 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1480 // The resume action for the continue thread (or all threads if a continue
1481 // thread is not set).
1482 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1483 static_cast<int>(signo)};
1484
1485 // Add the action for the continue thread (or all threads when the continue
1486 // thread isn't present).
1487 resume_actions.Append(action);
1488 } else {
1489 // Send the signal to the process since we weren't targeting a specific
1490 // continue thread with the signal.
1491 error = m_debugged_process_sp->Signal(signo);
1492 if (error.Fail()) {
1493 if (log)
1494 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send "
1495 "signal for process %" PRIu64 ": %s",
1496 __FUNCTION__, m_debugged_process_sp->GetID(),
1497 error.AsCString());
1498
1499 return SendErrorResponse(0x52);
1500 }
1501 }
1502
1503 // Resume the threads.
1504 error = m_debugged_process_sp->Resume(resume_actions);
1505 if (error.Fail()) {
1506 if (log)
1507 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to resume "
1508 "threads for process %" PRIu64 ": %s",
1509 __FUNCTION__, m_debugged_process_sp->GetID(),
1510 error.AsCString());
1511
1512 return SendErrorResponse(0x38);
1513 }
1514
1515 // Don't send an "OK" packet; response is the stopped/exited message.
1516 return PacketResult::Success;
1517}
1518
1519GDBRemoteCommunication::PacketResult
1520GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1521 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1522 if (log)
1523 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1524
1525 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1526
1527 // For now just support all continue.
1528 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1529 if (has_continue_address) {
1530 if (log)
1531 log->Printf("GDBRemoteCommunicationServerLLGS::%s not implemented for "
1532 "c{address} variant [%s remains]",
1533 __FUNCTION__, packet.Peek());
1534 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1535 }
1536
1537 // Ensure we have a native process.
1538 if (!m_debugged_process_sp) {
1539 if (log)
1540 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1541 "shared pointer",
1542 __FUNCTION__);
1543 return SendErrorResponse(0x36);
1544 }
1545
1546 // Build the ResumeActionList
1547 ResumeActionList actions(StateType::eStateRunning, 0);
1548
Zachary Turner97206d52017-05-12 04:51:55 +00001549 Status error = m_debugged_process_sp->Resume(actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001550 if (error.Fail()) {
1551 if (log) {
1552 log->Printf(
1553 "GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64
1554 ": %s",
1555 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1556 }
1557 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1558 }
1559
1560 if (log)
1561 log->Printf(
1562 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1563 __FUNCTION__, m_debugged_process_sp->GetID());
1564
1565 // No response required from continue.
1566 return PacketResult::Success;
1567}
1568
1569GDBRemoteCommunication::PacketResult
1570GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1571 StringExtractorGDBRemote &packet) {
1572 StreamString response;
1573 response.Printf("vCont;c;C;s;S");
1574
1575 return SendPacketNoLock(response.GetString());
1576}
1577
1578GDBRemoteCommunication::PacketResult
1579GDBRemoteCommunicationServerLLGS::Handle_vCont(
1580 StringExtractorGDBRemote &packet) {
1581 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1582 if (log)
1583 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1584 __FUNCTION__);
1585
1586 packet.SetFilePos(::strlen("vCont"));
1587
1588 if (packet.GetBytesLeft() == 0) {
1589 if (log)
1590 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1591 "vCont package",
1592 __FUNCTION__);
1593 return SendIllFormedResponse(packet, "Missing action from vCont package");
1594 }
1595
1596 // Check if this is all continue (no options or ";c").
1597 if (::strcmp(packet.Peek(), ";c") == 0) {
1598 // Move past the ';', then do a simple 'c'.
1599 packet.SetFilePos(packet.GetFilePos() + 1);
1600 return Handle_c(packet);
1601 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1602 // Move past the ';', then do a simple 's'.
1603 packet.SetFilePos(packet.GetFilePos() + 1);
1604 return Handle_s(packet);
1605 }
1606
1607 // Ensure we have a native process.
1608 if (!m_debugged_process_sp) {
1609 if (log)
1610 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1611 "shared pointer",
1612 __FUNCTION__);
1613 return SendErrorResponse(0x36);
1614 }
1615
1616 ResumeActionList thread_actions;
1617
1618 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1619 // Skip the semi-colon.
1620 packet.GetChar();
1621
1622 // Build up the thread action.
1623 ResumeAction thread_action;
1624 thread_action.tid = LLDB_INVALID_THREAD_ID;
1625 thread_action.state = eStateInvalid;
1626 thread_action.signal = 0;
1627
1628 const char action = packet.GetChar();
1629 switch (action) {
1630 case 'C':
1631 thread_action.signal = packet.GetHexMaxU32(false, 0);
1632 if (thread_action.signal == 0)
1633 return SendIllFormedResponse(
1634 packet, "Could not parse signal in vCont packet C action");
1635 LLVM_FALLTHROUGH;
1636
1637 case 'c':
1638 // Continue
1639 thread_action.state = eStateRunning;
1640 break;
1641
1642 case 'S':
1643 thread_action.signal = packet.GetHexMaxU32(false, 0);
1644 if (thread_action.signal == 0)
1645 return SendIllFormedResponse(
1646 packet, "Could not parse signal in vCont packet S action");
1647 LLVM_FALLTHROUGH;
1648
1649 case 's':
1650 // Step
1651 thread_action.state = eStateStepping;
1652 break;
Pavel Labathabadc222015-11-27 13:33:29 +00001653
Tamas Berghammere13c2732015-02-11 10:29:30 +00001654 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001655 return SendIllFormedResponse(packet, "Unsupported vCont action");
1656 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00001657 }
1658
Kate Stoneb9c1b512016-09-06 20:57:50 +00001659 // Parse out optional :{thread-id} value.
1660 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1661 // Consume the separator.
1662 packet.GetChar();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001663
Kate Stoneb9c1b512016-09-06 20:57:50 +00001664 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1665 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1666 return SendIllFormedResponse(
1667 packet, "Could not parse thread number in vCont packet");
Pavel Labath77dc9562015-07-13 10:44:55 +00001668 }
1669
Kate Stoneb9c1b512016-09-06 20:57:50 +00001670 thread_actions.Append(thread_action);
1671 }
Pavel Labath77dc9562015-07-13 10:44:55 +00001672
Zachary Turner97206d52017-05-12 04:51:55 +00001673 Status error = m_debugged_process_sp->Resume(thread_actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001674 if (error.Fail()) {
1675 if (log) {
1676 log->Printf("GDBRemoteCommunicationServerLLGS::%s vCont failed for "
1677 "process %" PRIu64 ": %s",
1678 __FUNCTION__, m_debugged_process_sp->GetID(),
1679 error.AsCString());
Pavel Labath77dc9562015-07-13 10:44:55 +00001680 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001681 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1682 }
1683
1684 if (log)
1685 log->Printf(
1686 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1687 __FUNCTION__, m_debugged_process_sp->GetID());
1688
1689 // No response required from vCont.
1690 return PacketResult::Success;
Pavel Labath77dc9562015-07-13 10:44:55 +00001691}
1692
Kate Stoneb9c1b512016-09-06 20:57:50 +00001693void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1694 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1695 if (log)
1696 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting current thread "
1697 "id to %" PRIu64,
1698 __FUNCTION__, tid);
Pavel Labath77dc9562015-07-13 10:44:55 +00001699
Kate Stoneb9c1b512016-09-06 20:57:50 +00001700 m_current_tid = tid;
1701 if (m_debugged_process_sp)
1702 m_debugged_process_sp->SetCurrentThreadID(m_current_tid);
1703}
1704
1705void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1706 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1707 if (log)
1708 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting continue thread "
1709 "id to %" PRIu64,
1710 __FUNCTION__, tid);
1711
1712 m_continue_tid = tid;
Pavel Labath77dc9562015-07-13 10:44:55 +00001713}
1714
Tamas Berghammere13c2732015-02-11 10:29:30 +00001715GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001716GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1717 StringExtractorGDBRemote &packet) {
1718 // Handle the $? gdbremote command.
Tamas Berghammere13c2732015-02-11 10:29:30 +00001719
Kate Stoneb9c1b512016-09-06 20:57:50 +00001720 // If no process, indicate error
1721 if (!m_debugged_process_sp)
1722 return SendErrorResponse(02);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001723
Kate Stoneb9c1b512016-09-06 20:57:50 +00001724 return SendStopReasonForState(m_debugged_process_sp->GetState());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001725}
1726
1727GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001728GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1729 lldb::StateType process_state) {
1730 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00001731
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732 switch (process_state) {
1733 case eStateAttaching:
1734 case eStateLaunching:
1735 case eStateRunning:
1736 case eStateStepping:
1737 case eStateDetached:
1738 // NOTE: gdb protocol doc looks like it should return $OK
1739 // when everything is running (i.e. no stopped result).
1740 return PacketResult::Success; // Ignore
Tamas Berghammere13c2732015-02-11 10:29:30 +00001741
Kate Stoneb9c1b512016-09-06 20:57:50 +00001742 case eStateSuspended:
1743 case eStateStopped:
1744 case eStateCrashed: {
1745 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001746 // Make sure we set the current thread so g and p packets return
1747 // the data the gdb will expect.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001748 SetCurrentThreadID(tid);
1749 return SendStopReplyPacketForThread(tid);
1750 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001751
Kate Stoneb9c1b512016-09-06 20:57:50 +00001752 case eStateInvalid:
1753 case eStateUnloaded:
1754 case eStateExited:
1755 return SendWResponse(m_debugged_process_sp.get());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001756
Kate Stoneb9c1b512016-09-06 20:57:50 +00001757 default:
1758 if (log) {
1759 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
1760 ", current state reporting not handled: %s",
1761 __FUNCTION__, m_debugged_process_sp->GetID(),
1762 StateAsCString(process_state));
Pavel Labath424b2012015-07-28 09:06:56 +00001763 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001764 break;
1765 }
Pavel Labath424b2012015-07-28 09:06:56 +00001766
Kate Stoneb9c1b512016-09-06 20:57:50 +00001767 return SendErrorResponse(0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001768}
1769
1770GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001771GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1772 StringExtractorGDBRemote &packet) {
1773 // Fail if we don't have a current process.
1774 if (!m_debugged_process_sp ||
1775 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1776 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001777
Kate Stoneb9c1b512016-09-06 20:57:50 +00001778 // Ensure we have a thread.
1779 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadAtIndex(0));
1780 if (!thread_sp)
1781 return SendErrorResponse(69);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001782
Kate Stoneb9c1b512016-09-06 20:57:50 +00001783 // Get the register context for the first thread.
1784 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1785 if (!reg_context_sp)
1786 return SendErrorResponse(69);
1787
1788 // Parse out the register number from the request.
1789 packet.SetFilePos(strlen("qRegisterInfo"));
1790 const uint32_t reg_index =
1791 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1792 if (reg_index == std::numeric_limits<uint32_t>::max())
1793 return SendErrorResponse(69);
1794
1795 // Return the end of registers response if we've iterated one past the end of
1796 // the register set.
1797 if (reg_index >= reg_context_sp->GetUserRegisterCount())
1798 return SendErrorResponse(69);
1799
1800 const RegisterInfo *reg_info =
1801 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1802 if (!reg_info)
1803 return SendErrorResponse(69);
1804
1805 // Build the reginfos response.
1806 StreamGDBRemote response;
1807
1808 response.PutCString("name:");
1809 response.PutCString(reg_info->name);
1810 response.PutChar(';');
1811
1812 if (reg_info->alt_name && reg_info->alt_name[0]) {
1813 response.PutCString("alt-name:");
1814 response.PutCString(reg_info->alt_name);
1815 response.PutChar(';');
1816 }
1817
1818 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1819 reg_info->byte_size * 8, reg_info->byte_offset);
1820
1821 switch (reg_info->encoding) {
1822 case eEncodingUint:
1823 response.PutCString("encoding:uint;");
1824 break;
1825 case eEncodingSint:
1826 response.PutCString("encoding:sint;");
1827 break;
1828 case eEncodingIEEE754:
1829 response.PutCString("encoding:ieee754;");
1830 break;
1831 case eEncodingVector:
1832 response.PutCString("encoding:vector;");
1833 break;
1834 default:
1835 break;
1836 }
1837
1838 switch (reg_info->format) {
1839 case eFormatBinary:
1840 response.PutCString("format:binary;");
1841 break;
1842 case eFormatDecimal:
1843 response.PutCString("format:decimal;");
1844 break;
1845 case eFormatHex:
1846 response.PutCString("format:hex;");
1847 break;
1848 case eFormatFloat:
1849 response.PutCString("format:float;");
1850 break;
1851 case eFormatVectorOfSInt8:
1852 response.PutCString("format:vector-sint8;");
1853 break;
1854 case eFormatVectorOfUInt8:
1855 response.PutCString("format:vector-uint8;");
1856 break;
1857 case eFormatVectorOfSInt16:
1858 response.PutCString("format:vector-sint16;");
1859 break;
1860 case eFormatVectorOfUInt16:
1861 response.PutCString("format:vector-uint16;");
1862 break;
1863 case eFormatVectorOfSInt32:
1864 response.PutCString("format:vector-sint32;");
1865 break;
1866 case eFormatVectorOfUInt32:
1867 response.PutCString("format:vector-uint32;");
1868 break;
1869 case eFormatVectorOfFloat32:
1870 response.PutCString("format:vector-float32;");
1871 break;
Valentina Giusticda0ae42016-09-08 14:16:45 +00001872 case eFormatVectorOfUInt64:
1873 response.PutCString("format:vector-uint64;");
1874 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001875 case eFormatVectorOfUInt128:
1876 response.PutCString("format:vector-uint128;");
1877 break;
1878 default:
1879 break;
1880 };
1881
1882 const char *const register_set_name =
1883 reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1884 if (register_set_name) {
1885 response.PutCString("set:");
1886 response.PutCString(register_set_name);
1887 response.PutChar(';');
1888 }
1889
1890 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1891 LLDB_INVALID_REGNUM)
1892 response.Printf("ehframe:%" PRIu32 ";",
1893 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1894
1895 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1896 response.Printf("dwarf:%" PRIu32 ";",
1897 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1898
1899 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1900 case LLDB_REGNUM_GENERIC_PC:
1901 response.PutCString("generic:pc;");
1902 break;
1903 case LLDB_REGNUM_GENERIC_SP:
1904 response.PutCString("generic:sp;");
1905 break;
1906 case LLDB_REGNUM_GENERIC_FP:
1907 response.PutCString("generic:fp;");
1908 break;
1909 case LLDB_REGNUM_GENERIC_RA:
1910 response.PutCString("generic:ra;");
1911 break;
1912 case LLDB_REGNUM_GENERIC_FLAGS:
1913 response.PutCString("generic:flags;");
1914 break;
1915 case LLDB_REGNUM_GENERIC_ARG1:
1916 response.PutCString("generic:arg1;");
1917 break;
1918 case LLDB_REGNUM_GENERIC_ARG2:
1919 response.PutCString("generic:arg2;");
1920 break;
1921 case LLDB_REGNUM_GENERIC_ARG3:
1922 response.PutCString("generic:arg3;");
1923 break;
1924 case LLDB_REGNUM_GENERIC_ARG4:
1925 response.PutCString("generic:arg4;");
1926 break;
1927 case LLDB_REGNUM_GENERIC_ARG5:
1928 response.PutCString("generic:arg5;");
1929 break;
1930 case LLDB_REGNUM_GENERIC_ARG6:
1931 response.PutCString("generic:arg6;");
1932 break;
1933 case LLDB_REGNUM_GENERIC_ARG7:
1934 response.PutCString("generic:arg7;");
1935 break;
1936 case LLDB_REGNUM_GENERIC_ARG8:
1937 response.PutCString("generic:arg8;");
1938 break;
1939 default:
1940 break;
1941 }
1942
1943 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1944 response.PutCString("container-regs:");
1945 int i = 0;
1946 for (const uint32_t *reg_num = reg_info->value_regs;
1947 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1948 if (i > 0)
1949 response.PutChar(',');
1950 response.Printf("%" PRIx32, *reg_num);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001951 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001952 response.PutChar(';');
1953 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001954
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1956 response.PutCString("invalidate-regs:");
1957 int i = 0;
1958 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1959 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1960 if (i > 0)
1961 response.PutChar(',');
1962 response.Printf("%" PRIx32, *reg_num);
1963 }
1964 response.PutChar(';');
1965 }
1966
1967 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1968 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1969 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1970 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1971 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1972 response.PutChar(';');
1973 }
1974 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001975}
1976
1977GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001978GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1979 StringExtractorGDBRemote &packet) {
1980 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1981
1982 // Fail if we don't have a current process.
1983 if (!m_debugged_process_sp ||
1984 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00001985 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001986 log->Printf("GDBRemoteCommunicationServerLLGS::%s() no process (%s), "
1987 "returning OK",
1988 __FUNCTION__,
1989 m_debugged_process_sp ? "invalid process id"
1990 : "null m_debugged_process_sp");
1991 return SendOKResponse();
1992 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001993
Kate Stoneb9c1b512016-09-06 20:57:50 +00001994 StreamGDBRemote response;
1995 response.PutChar('m');
1996
1997 if (log)
1998 log->Printf(
1999 "GDBRemoteCommunicationServerLLGS::%s() starting thread iteration",
2000 __FUNCTION__);
2001
2002 NativeThreadProtocolSP thread_sp;
2003 uint32_t thread_index;
2004 for (thread_index = 0,
2005 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index);
2006 thread_sp; ++thread_index,
2007 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index)) {
2008 if (log)
2009 log->Printf(
2010 "GDBRemoteCommunicationServerLLGS::%s() iterated thread %" PRIu32
2011 "(%s, tid=0x%" PRIx64 ")",
2012 __FUNCTION__, thread_index, thread_sp ? "is not null" : "null",
2013 thread_sp ? thread_sp->GetID() : LLDB_INVALID_THREAD_ID);
2014 if (thread_index > 0)
2015 response.PutChar(',');
2016 response.Printf("%" PRIx64, thread_sp->GetID());
2017 }
2018
2019 if (log)
2020 log->Printf(
2021 "GDBRemoteCommunicationServerLLGS::%s() finished thread iteration",
2022 __FUNCTION__);
2023
2024 return SendPacketNoLock(response.GetString());
2025}
2026
2027GDBRemoteCommunication::PacketResult
2028GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
2029 StringExtractorGDBRemote &packet) {
2030 // FIXME for now we return the full thread list in the initial packet and
2031 // always do nothing here.
2032 return SendPacketNoLock("l");
2033}
2034
2035GDBRemoteCommunication::PacketResult
2036GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
2037 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2038
2039 // Parse out the register number from the request.
2040 packet.SetFilePos(strlen("p"));
2041 const uint32_t reg_index =
2042 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2043 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2044 if (log)
2045 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2046 "parse register number from request \"%s\"",
2047 __FUNCTION__, packet.GetStringRef().c_str());
2048 return SendErrorResponse(0x15);
2049 }
2050
2051 // Get the thread to use.
2052 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2053 if (!thread_sp) {
2054 if (log)
2055 log->Printf(
2056 "GDBRemoteCommunicationServerLLGS::%s failed, no thread available",
2057 __FUNCTION__);
2058 return SendErrorResponse(0x15);
2059 }
2060
2061 // Get the thread's register context.
2062 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2063 if (!reg_context_sp) {
2064 if (log)
2065 log->Printf(
2066 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2067 " failed, no register context available for the thread",
2068 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2069 return SendErrorResponse(0x15);
2070 }
2071
2072 // Return the end of registers response if we've iterated one past the end of
2073 // the register set.
2074 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2075 if (log)
2076 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2077 "register %" PRIu32 " beyond register count %" PRIu32,
2078 __FUNCTION__, reg_index,
2079 reg_context_sp->GetUserRegisterCount());
2080 return SendErrorResponse(0x15);
2081 }
2082
2083 const RegisterInfo *reg_info =
2084 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2085 if (!reg_info) {
2086 if (log)
2087 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2088 "register %" PRIu32 " returned NULL",
2089 __FUNCTION__, reg_index);
2090 return SendErrorResponse(0x15);
2091 }
2092
2093 // Build the reginfos response.
2094 StreamGDBRemote response;
2095
2096 // Retrieve the value
2097 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +00002098 Status error = reg_context_sp->ReadRegister(reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002099 if (error.Fail()) {
2100 if (log)
2101 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
2102 "requested register %" PRIu32 " (%s) failed: %s",
2103 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2104 return SendErrorResponse(0x15);
2105 }
2106
2107 const uint8_t *const data =
2108 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
2109 if (!data) {
2110 if (log)
2111 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
2112 "bytes from requested register %" PRIu32,
2113 __FUNCTION__, reg_index);
2114 return SendErrorResponse(0x15);
2115 }
2116
2117 // FIXME flip as needed to get data in big/little endian format for this host.
2118 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2119 response.PutHex8(data[i]);
2120
2121 return SendPacketNoLock(response.GetString());
2122}
2123
2124GDBRemoteCommunication::PacketResult
2125GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2126 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2127
2128 // Ensure there is more content.
2129 if (packet.GetBytesLeft() < 1)
2130 return SendIllFormedResponse(packet, "Empty P packet");
2131
2132 // Parse out the register number from the request.
2133 packet.SetFilePos(strlen("P"));
2134 const uint32_t reg_index =
2135 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2136 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2137 if (log)
2138 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2139 "parse register number from request \"%s\"",
2140 __FUNCTION__, packet.GetStringRef().c_str());
2141 return SendErrorResponse(0x29);
2142 }
2143
2144 // Note debugserver would send an E30 here.
2145 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2146 return SendIllFormedResponse(
2147 packet, "P packet missing '=' char after register number");
2148
2149 // Get process architecture.
2150 ArchSpec process_arch;
2151 if (!m_debugged_process_sp ||
2152 !m_debugged_process_sp->GetArchitecture(process_arch)) {
2153 if (log)
2154 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to retrieve "
2155 "inferior architecture",
2156 __FUNCTION__);
2157 return SendErrorResponse(0x49);
2158 }
2159
2160 // Parse out the value.
2161 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
2162 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2163
2164 // Get the thread to use.
2165 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2166 if (!thread_sp) {
2167 if (log)
2168 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2169 "available (thread index 0)",
2170 __FUNCTION__);
2171 return SendErrorResponse(0x28);
2172 }
2173
2174 // Get the thread's register context.
2175 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2176 if (!reg_context_sp) {
2177 if (log)
2178 log->Printf(
2179 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2180 " failed, no register context available for the thread",
2181 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2182 return SendErrorResponse(0x15);
2183 }
2184
2185 const RegisterInfo *reg_info =
2186 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2187 if (!reg_info) {
2188 if (log)
2189 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2190 "register %" PRIu32 " returned NULL",
2191 __FUNCTION__, reg_index);
2192 return SendErrorResponse(0x48);
2193 }
2194
2195 // Return the end of registers response if we've iterated one past the end of
2196 // the register set.
2197 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2198 if (log)
2199 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2200 "register %" PRIu32 " beyond register count %" PRIu32,
2201 __FUNCTION__, reg_index,
2202 reg_context_sp->GetUserRegisterCount());
2203 return SendErrorResponse(0x47);
2204 }
2205
2206 // The dwarf expression are evaluate on host site
2207 // which may cause register size to change
2208 // Hence the reg_size may not be same as reg_info->bytes_size
2209 if ((reg_size != reg_info->byte_size) &&
2210 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2211 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2212 }
2213
2214 // Build the reginfos response.
2215 StreamGDBRemote response;
2216
2217 RegisterValue reg_value(reg_bytes, reg_size, process_arch.GetByteOrder());
Zachary Turner97206d52017-05-12 04:51:55 +00002218 Status error = reg_context_sp->WriteRegister(reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002219 if (error.Fail()) {
2220 if (log)
2221 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
2222 "requested register %" PRIu32 " (%s) failed: %s",
2223 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2224 return SendErrorResponse(0x32);
2225 }
2226
2227 return SendOKResponse();
2228}
2229
2230GDBRemoteCommunication::PacketResult
2231GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2232 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2233
2234 // Fail if we don't have a current process.
2235 if (!m_debugged_process_sp ||
2236 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2237 if (log)
2238 log->Printf(
2239 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2240 __FUNCTION__);
2241 return SendErrorResponse(0x15);
2242 }
2243
2244 // Parse out which variant of $H is requested.
2245 packet.SetFilePos(strlen("H"));
2246 if (packet.GetBytesLeft() < 1) {
2247 if (log)
2248 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2249 "missing {g,c} variant",
2250 __FUNCTION__);
2251 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2252 }
2253
2254 const char h_variant = packet.GetChar();
2255 switch (h_variant) {
2256 case 'g':
2257 break;
2258
2259 case 'c':
2260 break;
2261
2262 default:
2263 if (log)
2264 log->Printf(
2265 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2266 __FUNCTION__, h_variant);
2267 return SendIllFormedResponse(packet,
2268 "H variant unsupported, should be c or g");
2269 }
2270
2271 // Parse out the thread number.
2272 // FIXME return a parse success/fail value. All values are valid here.
2273 const lldb::tid_t tid =
2274 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2275
2276 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2277 // (any thread).
2278 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2279 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
2280 if (!thread_sp) {
2281 if (log)
2282 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2283 " not found",
2284 __FUNCTION__, tid);
2285 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002286 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002287 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002288
Kate Stoneb9c1b512016-09-06 20:57:50 +00002289 // Now switch the given thread type.
2290 switch (h_variant) {
2291 case 'g':
2292 SetCurrentThreadID(tid);
2293 break;
2294
2295 case 'c':
2296 SetContinueThreadID(tid);
2297 break;
2298
2299 default:
2300 assert(false && "unsupported $H variant - shouldn't get here");
2301 return SendIllFormedResponse(packet,
2302 "H variant unsupported, should be c or g");
2303 }
2304
2305 return SendOKResponse();
2306}
2307
2308GDBRemoteCommunication::PacketResult
2309GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2310 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2311
2312 // Fail if we don't have a current 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 packet.SetFilePos(::strlen("I"));
2323 uint8_t tmp[4096];
2324 for (;;) {
2325 size_t read = packet.GetHexBytesAvail(tmp);
2326 if (read == 0) {
2327 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002328 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002329 // write directly to stdin *this might block if stdin buffer is full*
2330 // TODO: enqueue this block in circular buffer and send window size to
2331 // remote host
2332 ConnectionStatus status;
Zachary Turner97206d52017-05-12 04:51:55 +00002333 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002334 m_stdio_communication.Write(tmp, read, status, &error);
2335 if (error.Fail()) {
2336 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002337 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002338 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002339
Kate Stoneb9c1b512016-09-06 20:57:50 +00002340 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002341}
2342
2343GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002344GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2345 StringExtractorGDBRemote &packet) {
2346 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2347
2348 // Fail if we don't have a current process.
2349 if (!m_debugged_process_sp ||
2350 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002351 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002352 log->Printf(
2353 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2354 __FUNCTION__);
2355 return SendErrorResponse(0x15);
2356 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002357
Kate Stoneb9c1b512016-09-06 20:57:50 +00002358 // Interrupt the process.
Zachary Turner97206d52017-05-12 04:51:55 +00002359 Status error = m_debugged_process_sp->Interrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002360 if (error.Fail()) {
2361 if (log) {
2362 log->Printf(
2363 "GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64
2364 ": %s",
2365 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002366 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002367 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2368 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002369
Kate Stoneb9c1b512016-09-06 20:57:50 +00002370 if (log)
2371 log->Printf("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64,
2372 __FUNCTION__, m_debugged_process_sp->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002373
Kate Stoneb9c1b512016-09-06 20:57:50 +00002374 // No response required from stop all.
2375 return PacketResult::Success;
2376}
Tamas Berghammere13c2732015-02-11 10:29:30 +00002377
Kate Stoneb9c1b512016-09-06 20:57:50 +00002378GDBRemoteCommunication::PacketResult
2379GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2380 StringExtractorGDBRemote &packet) {
2381 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002382
Kate Stoneb9c1b512016-09-06 20:57:50 +00002383 if (!m_debugged_process_sp ||
2384 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002385 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002386 log->Printf(
2387 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2388 __FUNCTION__);
2389 return SendErrorResponse(0x15);
2390 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002391
Kate Stoneb9c1b512016-09-06 20:57:50 +00002392 // Parse out the memory address.
2393 packet.SetFilePos(strlen("m"));
2394 if (packet.GetBytesLeft() < 1)
2395 return SendIllFormedResponse(packet, "Too short m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002396
Kate Stoneb9c1b512016-09-06 20:57:50 +00002397 // Read the address. Punting on validation.
2398 // FIXME replace with Hex U64 read with no default value that fails on failed
2399 // read.
2400 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002401
Kate Stoneb9c1b512016-09-06 20:57:50 +00002402 // Validate comma.
2403 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2404 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002405
Kate Stoneb9c1b512016-09-06 20:57:50 +00002406 // Get # bytes to read.
2407 if (packet.GetBytesLeft() < 1)
2408 return SendIllFormedResponse(packet, "Length missing in m packet");
2409
2410 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2411 if (byte_count == 0) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002412 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002413 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2414 "zero-length packet",
2415 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002416 return SendOKResponse();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002417 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002418
Kate Stoneb9c1b512016-09-06 20:57:50 +00002419 // Allocate the response buffer.
2420 std::string buf(byte_count, '\0');
2421 if (buf.empty())
2422 return SendErrorResponse(0x78);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002423
Kate Stoneb9c1b512016-09-06 20:57:50 +00002424 // Retrieve the process memory.
2425 size_t bytes_read = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002426 Status error = m_debugged_process_sp->ReadMemoryWithoutTrap(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002427 read_addr, &buf[0], byte_count, bytes_read);
2428 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002429 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002430 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2431 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2432 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2433 error.AsCString());
2434 return SendErrorResponse(0x08);
2435 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002436
Kate Stoneb9c1b512016-09-06 20:57:50 +00002437 if (bytes_read == 0) {
2438 if (log)
2439 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2440 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2441 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2442 byte_count);
2443 return SendErrorResponse(0x08);
2444 }
2445
2446 StreamGDBRemote response;
2447 packet.SetFilePos(0);
2448 char kind = packet.GetChar('?');
2449 if (kind == 'x')
2450 response.PutEscapedBytes(buf.data(), byte_count);
2451 else {
2452 assert(kind == 'm');
2453 for (size_t i = 0; i < bytes_read; ++i)
2454 response.PutHex8(buf[i]);
2455 }
2456
2457 return SendPacketNoLock(response.GetString());
2458}
2459
2460GDBRemoteCommunication::PacketResult
2461GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2462 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2463
2464 if (!m_debugged_process_sp ||
2465 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2466 if (log)
2467 log->Printf(
2468 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2469 __FUNCTION__);
2470 return SendErrorResponse(0x15);
2471 }
2472
2473 // Parse out the memory address.
2474 packet.SetFilePos(strlen("M"));
2475 if (packet.GetBytesLeft() < 1)
2476 return SendIllFormedResponse(packet, "Too short M packet");
2477
2478 // Read the address. Punting on validation.
2479 // FIXME replace with Hex U64 read with no default value that fails on failed
2480 // read.
2481 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2482
2483 // Validate comma.
2484 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2485 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2486
2487 // Get # bytes to read.
2488 if (packet.GetBytesLeft() < 1)
2489 return SendIllFormedResponse(packet, "Length missing in M packet");
2490
2491 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2492 if (byte_count == 0) {
2493 if (log)
2494 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to write: "
2495 "zero-length packet",
2496 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002497 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002498 }
2499
2500 // Validate colon.
2501 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2502 return SendIllFormedResponse(
2503 packet, "Comma sep missing in M packet after byte length");
2504
2505 // Allocate the conversion buffer.
2506 std::vector<uint8_t> buf(byte_count, 0);
2507 if (buf.empty())
2508 return SendErrorResponse(0x78);
2509
2510 // Convert the hex memory write contents to bytes.
2511 StreamGDBRemote response;
2512 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2513 if (convert_count != byte_count) {
2514 if (log)
2515 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2516 " mem 0x%" PRIx64 ": asked to write %" PRIu64
2517 " bytes, but only found %" PRIu64 " to convert.",
2518 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2519 byte_count, convert_count);
2520 return SendIllFormedResponse(packet, "M content byte length specified did "
2521 "not match hex-encoded content "
2522 "length");
2523 }
2524
2525 // Write the process memory.
2526 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002527 Status error = m_debugged_process_sp->WriteMemory(write_addr, &buf[0],
2528 byte_count, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002529 if (error.Fail()) {
2530 if (log)
2531 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2532 " mem 0x%" PRIx64 ": failed to write. Error: %s",
2533 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2534 error.AsCString());
2535 return SendErrorResponse(0x09);
2536 }
2537
2538 if (bytes_written == 0) {
2539 if (log)
2540 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2541 " mem 0x%" PRIx64 ": wrote 0 of %" PRIu64 " requested bytes",
2542 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2543 byte_count);
2544 return SendErrorResponse(0x09);
2545 }
2546
2547 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002548}
2549
2550GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002551GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2552 StringExtractorGDBRemote &packet) {
2553 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002554
Kate Stoneb9c1b512016-09-06 20:57:50 +00002555 // Currently only the NativeProcessProtocol knows if it can handle a
2556 // qMemoryRegionInfoSupported
2557 // request, but we're not guaranteed to be attached to a process. For now
2558 // we'll assume the
2559 // client only asks this when a process is being debugged.
Tamas Berghammere13c2732015-02-11 10:29:30 +00002560
Kate Stoneb9c1b512016-09-06 20:57:50 +00002561 // Ensure we have a process running; otherwise, we can't figure this out
2562 // since we won't have a NativeProcessProtocol.
2563 if (!m_debugged_process_sp ||
2564 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2565 if (log)
2566 log->Printf(
2567 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2568 __FUNCTION__);
2569 return SendErrorResponse(0x15);
2570 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002571
Kate Stoneb9c1b512016-09-06 20:57:50 +00002572 // Test if we can get any region back when asking for the region around NULL.
2573 MemoryRegionInfo region_info;
Zachary Turner97206d52017-05-12 04:51:55 +00002574 const Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00002575 m_debugged_process_sp->GetMemoryRegionInfo(0, region_info);
2576 if (error.Fail()) {
2577 // We don't support memory region info collection for this
2578 // NativeProcessProtocol.
2579 return SendUnimplementedResponse("");
2580 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002581
Kate Stoneb9c1b512016-09-06 20:57:50 +00002582 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002583}
2584
2585GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002586GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2587 StringExtractorGDBRemote &packet) {
2588 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002589
Kate Stoneb9c1b512016-09-06 20:57:50 +00002590 // Ensure we have a process.
2591 if (!m_debugged_process_sp ||
2592 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2593 if (log)
2594 log->Printf(
2595 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2596 __FUNCTION__);
2597 return SendErrorResponse(0x15);
2598 }
2599
2600 // Parse out the memory address.
2601 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2602 if (packet.GetBytesLeft() < 1)
2603 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2604
2605 // Read the address. Punting on validation.
2606 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2607
2608 StreamGDBRemote response;
2609
2610 // Get the memory region info for the target address.
2611 MemoryRegionInfo region_info;
Zachary Turner97206d52017-05-12 04:51:55 +00002612 const Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00002613 m_debugged_process_sp->GetMemoryRegionInfo(read_addr, region_info);
2614 if (error.Fail()) {
2615 // Return the error message.
2616
2617 response.PutCString("error:");
2618 response.PutCStringAsRawHex8(error.AsCString());
2619 response.PutChar(';');
2620 } else {
2621 // Range start and size.
2622 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2623 region_info.GetRange().GetRangeBase(),
2624 region_info.GetRange().GetByteSize());
2625
2626 // Permissions.
2627 if (region_info.GetReadable() || region_info.GetWritable() ||
2628 region_info.GetExecutable()) {
2629 // Write permissions info.
2630 response.PutCString("permissions:");
2631
2632 if (region_info.GetReadable())
2633 response.PutChar('r');
2634 if (region_info.GetWritable())
2635 response.PutChar('w');
2636 if (region_info.GetExecutable())
2637 response.PutChar('x');
2638
2639 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002640 }
2641
Kate Stoneb9c1b512016-09-06 20:57:50 +00002642 // Name
2643 ConstString name = region_info.GetName();
2644 if (name) {
2645 response.PutCString("name:");
2646 response.PutCStringAsRawHex8(name.AsCString());
2647 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002648 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002649 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002650
Kate Stoneb9c1b512016-09-06 20:57:50 +00002651 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002652}
2653
2654GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002655GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2656 // Ensure we have a process.
2657 if (!m_debugged_process_sp ||
2658 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2659 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2660 if (log)
2661 log->Printf(
2662 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2663 __FUNCTION__);
2664 return SendErrorResponse(0x15);
2665 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002666
Kate Stoneb9c1b512016-09-06 20:57:50 +00002667 // Parse out software or hardware breakpoint or watchpoint requested.
2668 packet.SetFilePos(strlen("Z"));
2669 if (packet.GetBytesLeft() < 1)
2670 return SendIllFormedResponse(
2671 packet, "Too short Z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002672
Kate Stoneb9c1b512016-09-06 20:57:50 +00002673 bool want_breakpoint = true;
2674 bool want_hardware = false;
2675 uint32_t watch_flags = 0;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002676
Kate Stoneb9c1b512016-09-06 20:57:50 +00002677 const GDBStoppointType stoppoint_type =
2678 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2679 switch (stoppoint_type) {
2680 case eBreakpointSoftware:
2681 want_hardware = false;
2682 want_breakpoint = true;
2683 break;
2684 case eBreakpointHardware:
2685 want_hardware = true;
2686 want_breakpoint = true;
2687 break;
2688 case eWatchpointWrite:
2689 watch_flags = 1;
2690 want_hardware = true;
2691 want_breakpoint = false;
2692 break;
2693 case eWatchpointRead:
2694 watch_flags = 2;
2695 want_hardware = true;
2696 want_breakpoint = false;
2697 break;
2698 case eWatchpointReadWrite:
2699 watch_flags = 3;
2700 want_hardware = true;
2701 want_breakpoint = false;
2702 break;
2703 case eStoppointInvalid:
2704 return SendIllFormedResponse(
2705 packet, "Z packet had invalid software/hardware specifier");
2706 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002707
Kate Stoneb9c1b512016-09-06 20:57:50 +00002708 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2709 return SendIllFormedResponse(
2710 packet, "Malformed Z packet, expecting comma after stoppoint type");
2711
2712 // Parse out the stoppoint address.
2713 if (packet.GetBytesLeft() < 1)
2714 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2715 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2716
2717 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2718 return SendIllFormedResponse(
2719 packet, "Malformed Z packet, expecting comma after address");
2720
2721 // Parse out the stoppoint size (i.e. size hint for opcode size).
2722 const uint32_t size =
2723 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2724 if (size == std::numeric_limits<uint32_t>::max())
2725 return SendIllFormedResponse(
2726 packet, "Malformed Z packet, failed to parse size argument");
2727
2728 if (want_breakpoint) {
2729 // Try to set the breakpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002730 const Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00002731 m_debugged_process_sp->SetBreakpoint(addr, size, want_hardware);
2732 if (error.Success())
2733 return SendOKResponse();
2734 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2735 if (log)
2736 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2737 " failed to set breakpoint: %s",
2738 __FUNCTION__, m_debugged_process_sp->GetID(),
2739 error.AsCString());
2740 return SendErrorResponse(0x09);
2741 } else {
2742 // Try to set the watchpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002743 const Status error = m_debugged_process_sp->SetWatchpoint(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002744 addr, size, watch_flags, want_hardware);
2745 if (error.Success())
2746 return SendOKResponse();
2747 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2748 if (log)
2749 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2750 " failed to set watchpoint: %s",
2751 __FUNCTION__, m_debugged_process_sp->GetID(),
2752 error.AsCString());
2753 return SendErrorResponse(0x09);
2754 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002755}
2756
2757GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002758GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2759 // Ensure we have a process.
2760 if (!m_debugged_process_sp ||
2761 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2762 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2763 if (log)
2764 log->Printf(
2765 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2766 __FUNCTION__);
2767 return SendErrorResponse(0x15);
2768 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002769
Kate Stoneb9c1b512016-09-06 20:57:50 +00002770 // Parse out software or hardware breakpoint or watchpoint requested.
2771 packet.SetFilePos(strlen("z"));
2772 if (packet.GetBytesLeft() < 1)
2773 return SendIllFormedResponse(
2774 packet, "Too short z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002775
Kate Stoneb9c1b512016-09-06 20:57:50 +00002776 bool want_breakpoint = true;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002777 bool want_hardware = false;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002778
Kate Stoneb9c1b512016-09-06 20:57:50 +00002779 const GDBStoppointType stoppoint_type =
2780 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2781 switch (stoppoint_type) {
2782 case eBreakpointHardware:
2783 want_breakpoint = true;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002784 want_hardware = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002785 break;
2786 case eBreakpointSoftware:
2787 want_breakpoint = true;
2788 break;
2789 case eWatchpointWrite:
2790 want_breakpoint = false;
2791 break;
2792 case eWatchpointRead:
2793 want_breakpoint = false;
2794 break;
2795 case eWatchpointReadWrite:
2796 want_breakpoint = false;
2797 break;
2798 default:
2799 return SendIllFormedResponse(
2800 packet, "z packet had invalid software/hardware specifier");
2801 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002802
Kate Stoneb9c1b512016-09-06 20:57:50 +00002803 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2804 return SendIllFormedResponse(
2805 packet, "Malformed z packet, expecting comma after stoppoint type");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002806
Kate Stoneb9c1b512016-09-06 20:57:50 +00002807 // Parse out the stoppoint address.
2808 if (packet.GetBytesLeft() < 1)
2809 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2810 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002811
Kate Stoneb9c1b512016-09-06 20:57:50 +00002812 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2813 return SendIllFormedResponse(
2814 packet, "Malformed z packet, expecting comma after address");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002815
Kate Stoneb9c1b512016-09-06 20:57:50 +00002816 /*
2817 // Parse out the stoppoint size (i.e. size hint for opcode size).
2818 const uint32_t size = packet.GetHexMaxU32 (false,
2819 std::numeric_limits<uint32_t>::max ());
2820 if (size == std::numeric_limits<uint32_t>::max ())
2821 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2822 size argument");
2823 */
Tamas Berghammere13c2732015-02-11 10:29:30 +00002824
Kate Stoneb9c1b512016-09-06 20:57:50 +00002825 if (want_breakpoint) {
2826 // Try to clear the breakpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002827 const Status error =
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002828 m_debugged_process_sp->RemoveBreakpoint(addr, want_hardware);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002829 if (error.Success())
2830 return SendOKResponse();
2831 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2832 if (log)
2833 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2834 " failed to remove breakpoint: %s",
2835 __FUNCTION__, m_debugged_process_sp->GetID(),
2836 error.AsCString());
2837 return SendErrorResponse(0x09);
2838 } else {
2839 // Try to clear the watchpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002840 const Status error = m_debugged_process_sp->RemoveWatchpoint(addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 if (error.Success())
2842 return SendOKResponse();
2843 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2844 if (log)
2845 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2846 " failed to remove watchpoint: %s",
2847 __FUNCTION__, m_debugged_process_sp->GetID(),
2848 error.AsCString());
2849 return SendErrorResponse(0x09);
2850 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002851}
2852
2853GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002854GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2855 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002856
Kate Stoneb9c1b512016-09-06 20:57:50 +00002857 // Ensure we have a process.
2858 if (!m_debugged_process_sp ||
2859 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2860 if (log)
2861 log->Printf(
2862 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2863 __FUNCTION__);
2864 return SendErrorResponse(0x32);
2865 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002866
Kate Stoneb9c1b512016-09-06 20:57:50 +00002867 // We first try to use a continue thread id. If any one or any all set, use
2868 // the current thread.
2869 // Bail out if we don't have a thread id.
2870 lldb::tid_t tid = GetContinueThreadID();
2871 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2872 tid = GetCurrentThreadID();
2873 if (tid == LLDB_INVALID_THREAD_ID)
2874 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002875
Kate Stoneb9c1b512016-09-06 20:57:50 +00002876 // Double check that we have such a thread.
2877 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2878 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID(tid);
2879 if (!thread_sp || thread_sp->GetID() != tid)
2880 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002881
Kate Stoneb9c1b512016-09-06 20:57:50 +00002882 // Create the step action for the given thread.
2883 ResumeAction action = {tid, eStateStepping, 0};
Tamas Berghammere13c2732015-02-11 10:29:30 +00002884
Kate Stoneb9c1b512016-09-06 20:57:50 +00002885 // Setup the actions list.
2886 ResumeActionList actions;
2887 actions.Append(action);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002888
Kate Stoneb9c1b512016-09-06 20:57:50 +00002889 // All other threads stop while we're single stepping a thread.
2890 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
Zachary Turner97206d52017-05-12 04:51:55 +00002891 Status error = m_debugged_process_sp->Resume(actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002892 if (error.Fail()) {
2893 if (log)
2894 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2895 " tid %" PRIu64 " Resume() failed with error: %s",
2896 __FUNCTION__, m_debugged_process_sp->GetID(), tid,
2897 error.AsCString());
2898 return SendErrorResponse(0x49);
2899 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002900
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901 // No response here - the stop or exit will come from the resulting action.
2902 return PacketResult::Success;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002903}
2904
2905GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002906GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2907 StringExtractorGDBRemote &packet) {
2908// *BSD impls should be able to do this too.
Kamil Rytarowskic93408a2017-03-21 17:27:59 +00002909#if defined(__linux__) || defined(__NetBSD__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002910 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002911
Kate Stoneb9c1b512016-09-06 20:57:50 +00002912 // Parse out the offset.
2913 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2914 if (packet.GetBytesLeft() < 1)
2915 return SendIllFormedResponse(packet,
2916 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002917
Kate Stoneb9c1b512016-09-06 20:57:50 +00002918 const uint64_t auxv_offset =
2919 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2920 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2921 return SendIllFormedResponse(packet,
2922 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002923
Kate Stoneb9c1b512016-09-06 20:57:50 +00002924 // Parse out comma.
2925 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2926 return SendIllFormedResponse(
2927 packet, "qXfer:auxv:read:: packet missing comma after offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002928
Kate Stoneb9c1b512016-09-06 20:57:50 +00002929 // Parse out the length.
2930 const uint64_t auxv_length =
2931 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2932 if (auxv_length == std::numeric_limits<uint64_t>::max())
2933 return SendIllFormedResponse(packet,
2934 "qXfer:auxv:read:: packet missing length");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002935
Kate Stoneb9c1b512016-09-06 20:57:50 +00002936 // Grab the auxv data if we need it.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002937 if (!m_active_auxv_buffer_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002938 // Make sure we have a valid process.
2939 if (!m_debugged_process_sp ||
2940 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2941 if (log)
2942 log->Printf(
2943 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2944 __FUNCTION__);
2945 return SendErrorResponse(0x10);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002946 }
2947
Kate Stoneb9c1b512016-09-06 20:57:50 +00002948 // Grab the auxv data.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002949 auto buffer_or_error = m_debugged_process_sp->GetAuxvData();
2950 if (!buffer_or_error) {
2951 std::error_code ec = buffer_or_error.getError();
2952 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2953 return SendErrorResponse(ec.value());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002954 }
Pavel Labathb7f0f452017-03-17 11:08:40 +00002955 m_active_auxv_buffer_up = std::move(*buffer_or_error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002956 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002957
Kate Stoneb9c1b512016-09-06 20:57:50 +00002958 StreamGDBRemote response;
2959 bool done_with_buffer = false;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002960
Pavel Labathb7f0f452017-03-17 11:08:40 +00002961 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2962 if (auxv_offset >= buffer.size()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002963 // We have nothing left to send. Mark the buffer as complete.
2964 response.PutChar('l');
2965 done_with_buffer = true;
2966 } else {
2967 // Figure out how many bytes are available starting at the given offset.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002968 buffer = buffer.drop_front(auxv_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002969
2970 // Mark the response type according to whether we're reading the remainder
2971 // of the auxv data.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002972 if (auxv_length >= buffer.size()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002973 // There will be nothing left to read after this
2974 response.PutChar('l');
2975 done_with_buffer = true;
2976 } else {
2977 // There will still be bytes to read after this request.
2978 response.PutChar('m');
Pavel Labathb7f0f452017-03-17 11:08:40 +00002979 buffer = buffer.take_front(auxv_length);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002980 }
2981
Kate Stoneb9c1b512016-09-06 20:57:50 +00002982 // Now write the data in encoded binary form.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002983 response.PutEscapedBytes(buffer.data(), buffer.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002984 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002985
Kate Stoneb9c1b512016-09-06 20:57:50 +00002986 if (done_with_buffer)
Pavel Labathb7f0f452017-03-17 11:08:40 +00002987 m_active_auxv_buffer_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002988
2989 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002990#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991 return SendUnimplementedResponse("not implemented on this platform");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002992#endif
2993}
2994
2995GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002996GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2997 StringExtractorGDBRemote &packet) {
2998 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002999
Kate Stoneb9c1b512016-09-06 20:57:50 +00003000 // Move past packet name.
3001 packet.SetFilePos(strlen("QSaveRegisterState"));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003002
Kate Stoneb9c1b512016-09-06 20:57:50 +00003003 // Get the thread to use.
3004 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
3005 if (!thread_sp) {
3006 if (m_thread_suffix_supported)
3007 return SendIllFormedResponse(
3008 packet, "No thread specified in QSaveRegisterState packet");
3009 else
3010 return SendIllFormedResponse(packet,
3011 "No thread was is set with the Hg packet");
3012 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003013
Kate Stoneb9c1b512016-09-06 20:57:50 +00003014 // Grab the register context for the thread.
3015 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
3016 if (!reg_context_sp) {
3017 if (log)
3018 log->Printf(
3019 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
3020 " failed, no register context available for the thread",
3021 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
3022 return SendErrorResponse(0x15);
3023 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003024
Kate Stoneb9c1b512016-09-06 20:57:50 +00003025 // Save registers to a buffer.
3026 DataBufferSP register_data_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003027 Status error = reg_context_sp->ReadAllRegisterValues(register_data_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003028 if (error.Fail()) {
3029 if (log)
3030 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3031 " failed to save all register values: %s",
3032 __FUNCTION__, m_debugged_process_sp->GetID(),
3033 error.AsCString());
3034 return SendErrorResponse(0x75);
3035 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003036
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 // Allocate a new save id.
3038 const uint32_t save_id = GetNextSavedRegistersID();
3039 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3040 "GetNextRegisterSaveID() returned an existing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00003041
Kate Stoneb9c1b512016-09-06 20:57:50 +00003042 // Save the register data buffer under the save id.
3043 {
3044 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3045 m_saved_registers_map[save_id] = register_data_sp;
3046 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003047
Kate Stoneb9c1b512016-09-06 20:57:50 +00003048 // Write the response.
3049 StreamGDBRemote response;
3050 response.Printf("%" PRIu32, save_id);
3051 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00003052}
3053
3054GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003055GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3056 StringExtractorGDBRemote &packet) {
3057 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003058
Kate Stoneb9c1b512016-09-06 20:57:50 +00003059 // Parse out save id.
3060 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3061 if (packet.GetBytesLeft() < 1)
3062 return SendIllFormedResponse(
3063 packet, "QRestoreRegisterState packet missing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00003064
Kate Stoneb9c1b512016-09-06 20:57:50 +00003065 const uint32_t save_id = packet.GetU32(0);
3066 if (save_id == 0) {
3067 if (log)
3068 log->Printf("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState "
3069 "packet has malformed save id, expecting decimal uint32_t",
3070 __FUNCTION__);
3071 return SendErrorResponse(0x76);
3072 }
3073
3074 // Get the thread to use.
3075 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
3076 if (!thread_sp) {
3077 if (m_thread_suffix_supported)
3078 return SendIllFormedResponse(
3079 packet, "No thread specified in QRestoreRegisterState packet");
3080 else
3081 return SendIllFormedResponse(packet,
3082 "No thread was is set with the Hg packet");
3083 }
3084
3085 // Grab the register context for the thread.
3086 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
3087 if (!reg_context_sp) {
3088 if (log)
3089 log->Printf(
3090 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
3091 " failed, no register context available for the thread",
3092 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
3093 return SendErrorResponse(0x15);
3094 }
3095
3096 // Retrieve register state buffer, then remove from the list.
3097 DataBufferSP register_data_sp;
3098 {
3099 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3100
3101 // Find the register set buffer for the given save id.
3102 auto it = m_saved_registers_map.find(save_id);
3103 if (it == m_saved_registers_map.end()) {
3104 if (log)
3105 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3106 " does not have a register set save buffer for id %" PRIu32,
3107 __FUNCTION__, m_debugged_process_sp->GetID(), save_id);
3108 return SendErrorResponse(0x77);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003109 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110 register_data_sp = it->second;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003111
Kate Stoneb9c1b512016-09-06 20:57:50 +00003112 // Remove it from the map.
3113 m_saved_registers_map.erase(it);
3114 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003115
Zachary Turner97206d52017-05-12 04:51:55 +00003116 Status error = reg_context_sp->WriteAllRegisterValues(register_data_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003117 if (error.Fail()) {
3118 if (log)
3119 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3120 " failed to restore all register values: %s",
3121 __FUNCTION__, m_debugged_process_sp->GetID(),
3122 error.AsCString());
3123 return SendErrorResponse(0x77);
3124 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003125
Kate Stoneb9c1b512016-09-06 20:57:50 +00003126 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003127}
3128
3129GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003130GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3131 StringExtractorGDBRemote &packet) {
3132 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003133
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134 // Consume the ';' after vAttach.
3135 packet.SetFilePos(strlen("vAttach"));
3136 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3137 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
Tamas Berghammere13c2732015-02-11 10:29:30 +00003138
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 // Grab the PID to which we will attach (assume hex encoding).
3140 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3141 if (pid == LLDB_INVALID_PROCESS_ID)
3142 return SendIllFormedResponse(packet,
3143 "vAttach failed to parse the process id");
3144
3145 // Attempt to attach.
3146 if (log)
3147 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3148 "pid %" PRIu64,
3149 __FUNCTION__, pid);
3150
Zachary Turner97206d52017-05-12 04:51:55 +00003151 Status error = AttachToProcess(pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003152
3153 if (error.Fail()) {
3154 if (log)
3155 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3156 "pid %" PRIu64 ": %s\n",
3157 __FUNCTION__, pid, error.AsCString());
3158 return SendErrorResponse(0x01);
3159 }
3160
3161 // Notify we attached by sending a stop packet.
3162 return SendStopReasonForState(m_debugged_process_sp->GetState());
3163}
3164
3165GDBRemoteCommunication::PacketResult
3166GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3167 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3168
3169 StopSTDIOForwarding();
3170
3171 // Fail if we don't have a current process.
3172 if (!m_debugged_process_sp ||
3173 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
3174 if (log)
3175 log->Printf(
3176 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3177 __FUNCTION__);
3178 return SendErrorResponse(0x15);
3179 }
3180
3181 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3182
3183 // Consume the ';' after D.
3184 packet.SetFilePos(1);
3185 if (packet.GetBytesLeft()) {
3186 if (packet.GetChar() != ';')
3187 return SendIllFormedResponse(packet, "D missing expected ';'");
3188
3189 // Grab the PID from which we will detach (assume hex encoding).
3190 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003191 if (pid == LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003192 return SendIllFormedResponse(packet, "D failed to parse the process id");
3193 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003194
Kate Stoneb9c1b512016-09-06 20:57:50 +00003195 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_sp->GetID() != pid) {
3196 return SendIllFormedResponse(packet, "Invalid pid");
3197 }
3198
Zachary Turner97206d52017-05-12 04:51:55 +00003199 const Status error = m_debugged_process_sp->Detach();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003200 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00003201 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003202 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
3203 "pid %" PRIu64 ": %s\n",
3204 __FUNCTION__, m_debugged_process_sp->GetID(),
3205 error.AsCString());
3206 return SendErrorResponse(0x01);
3207 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003208
Kate Stoneb9c1b512016-09-06 20:57:50 +00003209 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003210}
3211
3212GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003213GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3214 StringExtractorGDBRemote &packet) {
3215 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003216
Kate Stoneb9c1b512016-09-06 20:57:50 +00003217 packet.SetFilePos(strlen("qThreadStopInfo"));
3218 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
3219 if (tid == LLDB_INVALID_THREAD_ID) {
Pavel Labath4a4bb122015-07-16 14:14:35 +00003220 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003221 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
3222 "parse thread id from request \"%s\"",
3223 __FUNCTION__, packet.GetStringRef().c_str());
3224 return SendErrorResponse(0x15);
3225 }
3226 return SendStopReplyPacketForThread(tid);
3227}
3228
3229GDBRemoteCommunication::PacketResult
3230GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3231 StringExtractorGDBRemote &) {
3232 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3233
3234 // Ensure we have a debugged process.
3235 if (!m_debugged_process_sp ||
3236 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
3237 return SendErrorResponse(50);
3238
3239 if (log)
3240 log->Printf("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid "
3241 "%" PRIu64,
Pavel Labath4a4bb122015-07-16 14:14:35 +00003242 __FUNCTION__, m_debugged_process_sp->GetID());
3243
Kate Stoneb9c1b512016-09-06 20:57:50 +00003244 StreamString response;
3245 const bool threads_with_valid_stop_info_only = false;
3246 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
3247 *m_debugged_process_sp, threads_with_valid_stop_info_only);
3248 if (!threads_array_sp) {
3249 if (log)
3250 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
3251 "packet for pid %" PRIu64,
3252 __FUNCTION__, m_debugged_process_sp->GetID());
3253 return SendErrorResponse(52);
3254 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00003255
Kate Stoneb9c1b512016-09-06 20:57:50 +00003256 threads_array_sp->Write(response);
3257 StreamGDBRemote escaped_response;
3258 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3259 return SendPacketNoLock(escaped_response.GetString());
Pavel Labath4a4bb122015-07-16 14:14:35 +00003260}
3261
3262GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003263GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3264 StringExtractorGDBRemote &packet) {
3265 // Fail if we don't have a current process.
3266 if (!m_debugged_process_sp ||
3267 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3268 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003269
Kate Stoneb9c1b512016-09-06 20:57:50 +00003270 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3271 if (packet.GetBytesLeft() == 0)
3272 return SendOKResponse();
3273 if (packet.GetChar() != ':')
3274 return SendErrorResponse(67);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003275
Omair Javaidd5ffbad2017-02-24 13:27:31 +00003276 auto hw_debug_cap = m_debugged_process_sp->GetHardwareDebugSupportInfo();
3277
Kate Stoneb9c1b512016-09-06 20:57:50 +00003278 StreamGDBRemote response;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00003279 if (hw_debug_cap == llvm::None)
3280 response.Printf("num:0;");
3281 else
3282 response.Printf("num:%d;", hw_debug_cap->second);
3283
Kate Stoneb9c1b512016-09-06 20:57:50 +00003284 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00003285}
3286
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003287GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003288GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3289 StringExtractorGDBRemote &packet) {
3290 // Fail if we don't have a current process.
3291 if (!m_debugged_process_sp ||
3292 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3293 return SendErrorResponse(67);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003294
Kate Stoneb9c1b512016-09-06 20:57:50 +00003295 packet.SetFilePos(strlen("qFileLoadAddress:"));
3296 if (packet.GetBytesLeft() == 0)
3297 return SendErrorResponse(68);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003298
Kate Stoneb9c1b512016-09-06 20:57:50 +00003299 std::string file_name;
3300 packet.GetHexByteString(file_name);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003301
Kate Stoneb9c1b512016-09-06 20:57:50 +00003302 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00003303 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00003304 m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
3305 if (error.Fail())
3306 return SendErrorResponse(69);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003307
Kate Stoneb9c1b512016-09-06 20:57:50 +00003308 if (file_load_address == LLDB_INVALID_ADDRESS)
3309 return SendErrorResponse(1); // File not loaded
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003310
Kate Stoneb9c1b512016-09-06 20:57:50 +00003311 StreamGDBRemote response;
3312 response.PutHex64(file_load_address);
3313 return SendPacketNoLock(response.GetString());
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003314}
3315
Pavel Labath4a705e72017-02-24 09:29:14 +00003316GDBRemoteCommunication::PacketResult
3317GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3318 StringExtractorGDBRemote &packet) {
3319 std::vector<int> signals;
3320 packet.SetFilePos(strlen("QPassSignals:"));
3321
3322 // Read sequence of hex signal numbers divided by a semicolon and
3323 // optionally spaces.
3324 while (packet.GetBytesLeft() > 0) {
3325 int signal = packet.GetS32(-1, 16);
3326 if (signal < 0)
3327 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3328 signals.push_back(signal);
3329
3330 packet.SkipSpaces();
3331 char separator = packet.GetChar();
3332 if (separator == '\0')
3333 break; // End of string
3334 if (separator != ';')
3335 return SendIllFormedResponse(packet, "Invalid separator,"
3336 " expected semicolon.");
3337 }
3338
3339 // Fail if we don't have a current process.
3340 if (!m_debugged_process_sp)
3341 return SendErrorResponse(68);
3342
Zachary Turner97206d52017-05-12 04:51:55 +00003343 Status error = m_debugged_process_sp->IgnoreSignals(signals);
Pavel Labath4a705e72017-02-24 09:29:14 +00003344 if (error.Fail())
3345 return SendErrorResponse(69);
3346
3347 return SendOKResponse();
3348}
3349
Kate Stoneb9c1b512016-09-06 20:57:50 +00003350void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3351 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003352
Kate Stoneb9c1b512016-09-06 20:57:50 +00003353 // Tell the stdio connection to shut down.
3354 if (m_stdio_communication.IsConnected()) {
3355 auto connection = m_stdio_communication.GetConnection();
3356 if (connection) {
Zachary Turner97206d52017-05-12 04:51:55 +00003357 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003358 connection->Disconnect(&error);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003359
Kate Stoneb9c1b512016-09-06 20:57:50 +00003360 if (error.Success()) {
3361 if (log)
3362 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3363 "terminal stdio - SUCCESS",
3364 __FUNCTION__);
3365 } else {
3366 if (log)
3367 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3368 "terminal stdio - FAIL: %s",
3369 __FUNCTION__, error.AsCString());
3370 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003371 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003372 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003373}
3374
Kate Stoneb9c1b512016-09-06 20:57:50 +00003375NativeThreadProtocolSP GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3376 StringExtractorGDBRemote &packet) {
3377 NativeThreadProtocolSP thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003378
Kate Stoneb9c1b512016-09-06 20:57:50 +00003379 // We have no thread if we don't have a process.
3380 if (!m_debugged_process_sp ||
3381 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
Tamas Berghammere13c2732015-02-11 10:29:30 +00003382 return thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003383
Kate Stoneb9c1b512016-09-06 20:57:50 +00003384 // If the client hasn't asked for thread suffix support, there will not be a
3385 // thread suffix.
3386 // Use the current thread in that case.
3387 if (!m_thread_suffix_supported) {
3388 const lldb::tid_t current_tid = GetCurrentThreadID();
3389 if (current_tid == LLDB_INVALID_THREAD_ID)
3390 return thread_sp;
3391 else if (current_tid == 0) {
3392 // Pick a thread.
3393 return m_debugged_process_sp->GetThreadAtIndex(0);
3394 } else
3395 return m_debugged_process_sp->GetThreadByID(current_tid);
3396 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003397
Kate Stoneb9c1b512016-09-06 20:57:50 +00003398 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003399
Kate Stoneb9c1b512016-09-06 20:57:50 +00003400 // Parse out the ';'.
3401 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
Tamas Berghammere13c2732015-02-11 10:29:30 +00003402 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003403 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3404 "error: expected ';' prior to start of thread suffix: packet "
3405 "contents = '%s'",
3406 __FUNCTION__, packet.GetStringRef().c_str());
3407 return thread_sp;
3408 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003409
Kate Stoneb9c1b512016-09-06 20:57:50 +00003410 if (!packet.GetBytesLeft())
3411 return thread_sp;
3412
3413 // Parse out thread: portion.
3414 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3415 if (log)
3416 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3417 "error: expected 'thread:' but not found, packet contents = "
3418 "'%s'",
3419 __FUNCTION__, packet.GetStringRef().c_str());
3420 return thread_sp;
3421 }
3422 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3423 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3424 if (tid != 0)
3425 return m_debugged_process_sp->GetThreadByID(tid);
3426
3427 return thread_sp;
3428}
3429
3430lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3431 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3432 // Use whatever the debug process says is the current thread id
3433 // since the protocol either didn't specify or specified we want
3434 // any/all threads marked as the current thread.
3435 if (!m_debugged_process_sp)
3436 return LLDB_INVALID_THREAD_ID;
3437 return m_debugged_process_sp->GetCurrentThreadID();
3438 }
3439 // Use the specific current thread id set by the gdb remote protocol.
3440 return m_current_tid;
3441}
3442
3443uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3444 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3445 return m_next_saved_registers_id++;
3446}
3447
3448void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
Pavel Labathb7f0f452017-03-17 11:08:40 +00003449 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003450
Pavel Labathb7f0f452017-03-17 11:08:40 +00003451 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3452 m_active_auxv_buffer_up.reset();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003453}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003454
3455FileSpec
Kate Stoneb9c1b512016-09-06 20:57:50 +00003456GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3457 const ArchSpec &arch) {
3458 if (m_debugged_process_sp) {
3459 FileSpec file_spec;
3460 if (m_debugged_process_sp
3461 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3462 .Success()) {
3463 if (file_spec.Exists())
3464 return file_spec;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003465 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003466 }
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003467
Kate Stoneb9c1b512016-09-06 20:57:50 +00003468 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003469}