blob: c2aa2616a9623f0e2cc739e950098adb4eecf7f4 [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(
Pavel Labath96e600f2017-07-07 11:02:19 +000076 MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
Kate Stoneb9c1b512016-09-06 20:57:50 +000077 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
78 "gdb-remote.server.rx_packet"),
Pavel Labath96e600f2017-07-07 11:02:19 +000079 m_mainloop(mainloop), m_process_factory(process_factory),
80 m_stdio_communication("process.stdio") {
Kate Stoneb9c1b512016-09-06 20:57:50 +000081 RegisterPacketHandlers();
Tamas Berghammere13c2732015-02-11 10:29:30 +000082}
83
Kate Stoneb9c1b512016-09-06 20:57:50 +000084void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
85 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
86 &GDBRemoteCommunicationServerLLGS::Handle_C);
87 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
88 &GDBRemoteCommunicationServerLLGS::Handle_c);
89 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
90 &GDBRemoteCommunicationServerLLGS::Handle_D);
91 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
92 &GDBRemoteCommunicationServerLLGS::Handle_H);
93 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
94 &GDBRemoteCommunicationServerLLGS::Handle_I);
95 RegisterMemberFunctionHandler(
96 StringExtractorGDBRemote::eServerPacketType_interrupt,
97 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
98 RegisterMemberFunctionHandler(
99 StringExtractorGDBRemote::eServerPacketType_m,
100 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
101 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
102 &GDBRemoteCommunicationServerLLGS::Handle_M);
103 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
104 &GDBRemoteCommunicationServerLLGS::Handle_p);
105 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
106 &GDBRemoteCommunicationServerLLGS::Handle_P);
107 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
108 &GDBRemoteCommunicationServerLLGS::Handle_qC);
109 RegisterMemberFunctionHandler(
110 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
111 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
112 RegisterMemberFunctionHandler(
113 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
114 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
115 RegisterMemberFunctionHandler(
116 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
117 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
118 RegisterMemberFunctionHandler(
119 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
120 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
121 RegisterMemberFunctionHandler(
122 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
123 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
124 RegisterMemberFunctionHandler(
125 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
126 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
127 RegisterMemberFunctionHandler(
128 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
129 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
130 RegisterMemberFunctionHandler(
131 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
132 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
133 RegisterMemberFunctionHandler(
134 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
135 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
136 RegisterMemberFunctionHandler(
137 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
138 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
139 RegisterMemberFunctionHandler(
140 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
141 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
142 RegisterMemberFunctionHandler(
143 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
144 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
145 RegisterMemberFunctionHandler(
146 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
147 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
148 RegisterMemberFunctionHandler(
149 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
150 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
151 RegisterMemberFunctionHandler(
152 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
153 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
154 RegisterMemberFunctionHandler(
155 StringExtractorGDBRemote::eServerPacketType_qXfer_auxv_read,
156 &GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read);
157 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
158 &GDBRemoteCommunicationServerLLGS::Handle_s);
159 RegisterMemberFunctionHandler(
160 StringExtractorGDBRemote::eServerPacketType_stop_reason,
161 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
162 RegisterMemberFunctionHandler(
163 StringExtractorGDBRemote::eServerPacketType_vAttach,
164 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
165 RegisterMemberFunctionHandler(
166 StringExtractorGDBRemote::eServerPacketType_vCont,
167 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
168 RegisterMemberFunctionHandler(
169 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
170 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
171 RegisterMemberFunctionHandler(
172 StringExtractorGDBRemote::eServerPacketType_x,
173 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
174 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
175 &GDBRemoteCommunicationServerLLGS::Handle_Z);
176 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
177 &GDBRemoteCommunicationServerLLGS::Handle_z);
Pavel Labath4a705e72017-02-24 09:29:14 +0000178 RegisterMemberFunctionHandler(
179 StringExtractorGDBRemote::eServerPacketType_QPassSignals,
180 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000181
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +0000182 RegisterMemberFunctionHandler(
183 StringExtractorGDBRemote::eServerPacketType_jTraceStart,
184 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStart);
185 RegisterMemberFunctionHandler(
186 StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead,
187 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
188 RegisterMemberFunctionHandler(
189 StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead,
190 &GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
191 RegisterMemberFunctionHandler(
192 StringExtractorGDBRemote::eServerPacketType_jTraceStop,
193 &GDBRemoteCommunicationServerLLGS::Handle_jTraceStop);
194 RegisterMemberFunctionHandler(
195 StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead,
196 &GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead);
197
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
Zachary Turner97206d52017-05-12 04:51:55 +0000199 [this](StringExtractorGDBRemote packet, Status &error,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200 bool &interrupt, bool &quit) {
201 quit = true;
202 return this->Handle_k(packet);
203 });
Tamas Berghammere13c2732015-02-11 10:29:30 +0000204}
205
Zachary Turner97206d52017-05-12 04:51:55 +0000206Status
207GDBRemoteCommunicationServerLLGS::SetLaunchArguments(const char *const args[],
208 int argc) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209 if ((argc < 1) || !args || !args[0] || !args[0][0])
Zachary Turner97206d52017-05-12 04:51:55 +0000210 return Status("%s: no process command line specified to launch",
211 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000212
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213 m_process_launch_info.SetArguments(const_cast<const char **>(args), true);
Zachary Turner97206d52017-05-12 04:51:55 +0000214 return Status();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000215}
216
Zachary Turner97206d52017-05-12 04:51:55 +0000217Status
218GDBRemoteCommunicationServerLLGS::SetLaunchFlags(unsigned int launch_flags) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219 m_process_launch_info.GetFlags().Set(launch_flags);
Zachary Turner97206d52017-05-12 04:51:55 +0000220 return Status();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000221}
222
Zachary Turner97206d52017-05-12 04:51:55 +0000223Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000224 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226 if (!m_process_launch_info.GetArguments().GetArgumentCount())
Zachary Turner97206d52017-05-12 04:51:55 +0000227 return Status("%s: no process command line specified to launch",
228 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000229
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 const bool should_forward_stdio =
231 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
232 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
233 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
234 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
235 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
Pavel Labath5ad891f2016-07-21 14:54:03 +0000236
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 const bool default_to_use_pty = true;
238 m_process_launch_info.FinalizeFileActions(nullptr, default_to_use_pty);
Pavel Labath5ad891f2016-07-21 14:54:03 +0000239
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240 {
241 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
242 assert(!m_debugged_process_sp && "lldb-server creating debugged "
243 "process but one already exists");
Pavel Labath96e600f2017-07-07 11:02:19 +0000244 auto process_or =
245 m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
246 if (!process_or) {
247 Status status(process_or.takeError());
248 llvm::errs() << llvm::formatv(
249 "failed to launch executable `{0}`: {1}",
250 m_process_launch_info.GetArguments().GetArgumentAtIndex(0), status);
251 return status;
252 }
253 m_debugged_process_sp = *process_or;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000254 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000255
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol
257 // as needed.
258 // llgs local-process debugging may specify PTY paths, which will make these
259 // file actions non-null
260 // process launch -i/e/o will also make these file actions non-null
261 // nullptr means that the traffic is expected to flow over gdb-remote protocol
262 if (should_forward_stdio) {
263 // nullptr means it's not redirected to file or pty (in case of LLGS local)
264 // at least one of stdio will be transferred pty<->gdb-remote
265 // we need to give the pty master handle to this object to read and/or write
Tamas Berghammere13c2732015-02-11 10:29:30 +0000266 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267 log->Printf(
268 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
269 " setting up stdout/stderr redirection via $O gdb-remote commands",
270 __FUNCTION__, m_debugged_process_sp->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000271
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 // Setup stdout/stderr mapping from inferior to $O
273 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
274 if (terminal_fd >= 0) {
275 if (log)
276 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
277 "inferior STDIO fd to %d",
278 __FUNCTION__, terminal_fd);
Pavel Labath96e600f2017-07-07 11:02:19 +0000279 Status status = SetSTDIOFileDescriptor(terminal_fd);
280 if (status.Fail())
281 return status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 } else {
283 if (log)
284 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
285 "inferior STDIO since terminal fd reported as %d",
286 __FUNCTION__, terminal_fd);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000287 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000288 } else {
289 if (log)
290 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
291 " skipping stdout/stderr redirection via $O: inferior will "
292 "communicate over client-provided file descriptors",
293 __FUNCTION__, m_debugged_process_sp->GetID());
294 }
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000295
Kate Stoneb9c1b512016-09-06 20:57:50 +0000296 printf("Launched '%s' as process %" PRIu64 "...\n",
297 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
Pavel Labath96e600f2017-07-07 11:02:19 +0000298 m_debugged_process_sp->GetID());
Pavel Labath6e4f19d2015-07-29 12:33:31 +0000299
Pavel Labath96e600f2017-07-07 11:02:19 +0000300 return Status();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000301}
302
Zachary Turner97206d52017-05-12 04:51:55 +0000303Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000304 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
305 if (log)
306 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
307 __FUNCTION__, pid);
308
309 // Before we try to attach, make sure we aren't already monitoring something
310 // else.
311 if (m_debugged_process_sp &&
312 m_debugged_process_sp->GetID() != LLDB_INVALID_PROCESS_ID)
Zachary Turner97206d52017-05-12 04:51:55 +0000313 return Status("cannot attach to a process %" PRIu64
314 " when another process with pid %" PRIu64
315 " is being debugged.",
316 pid, m_debugged_process_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317
318 // Try to attach.
Pavel Labath96e600f2017-07-07 11:02:19 +0000319 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
320 if (!process_or) {
321 Status status(process_or.takeError());
322 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid,
323 status);
324 return status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 }
Pavel Labath96e600f2017-07-07 11:02:19 +0000326 m_debugged_process_sp = *process_or;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327
328 // Setup stdout/stderr mapping from inferior.
329 auto terminal_fd = m_debugged_process_sp->GetTerminalFileDescriptor();
330 if (terminal_fd >= 0) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000331 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s setting "
333 "inferior STDIO fd to %d",
334 __FUNCTION__, terminal_fd);
Pavel Labath96e600f2017-07-07 11:02:19 +0000335 Status status = SetSTDIOFileDescriptor(terminal_fd);
336 if (status.Fail())
337 return status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338 } else {
339 if (log)
340 log->Printf("ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
341 "inferior STDIO since terminal fd reported as %d",
342 __FUNCTION__, terminal_fd);
343 }
344
345 printf("Attached to process %" PRIu64 "...\n", pid);
Pavel Labath96e600f2017-07-07 11:02:19 +0000346 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347}
348
349void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
350 NativeProcessProtocol *process) {
351 assert(process && "process cannot be NULL");
352 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
353 if (log) {
354 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
355 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
356 __FUNCTION__, process->GetID(),
357 StateAsCString(process->GetState()));
358 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000359}
360
361GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362GDBRemoteCommunicationServerLLGS::SendWResponse(
363 NativeProcessProtocol *process) {
364 assert(process && "process cannot be NULL");
365 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000366
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 // send W notification
Pavel Labath3508fc82017-06-19 12:47:50 +0000368 auto wait_status = process->GetExitStatus();
369 if (!wait_status) {
370 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
371 process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000372
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 StreamGDBRemote response;
374 response.PutChar('E');
375 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
376 return SendPacketNoLock(response.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 }
Pavel Labath3508fc82017-06-19 12:47:50 +0000378
379 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
380 *wait_status);
381
382 StreamGDBRemote response;
383 response.Format("{0:g}", *wait_status);
384 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000385}
386
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387static void AppendHexValue(StreamString &response, const uint8_t *buf,
388 uint32_t buf_size, bool swap) {
389 int64_t i;
390 if (swap) {
391 for (i = buf_size - 1; i >= 0; i--)
392 response.PutHex8(buf[i]);
393 } else {
394 for (i = 0; i < buf_size; i++)
395 response.PutHex8(buf[i]);
396 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000397}
398
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399static void WriteRegisterValueInHexFixedWidth(
400 StreamString &response, NativeRegisterContextSP &reg_ctx_sp,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000401 const RegisterInfo &reg_info, const RegisterValue *reg_value_p,
402 lldb::ByteOrder byte_order) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 RegisterValue reg_value;
404 if (!reg_value_p) {
Zachary Turner97206d52017-05-12 04:51:55 +0000405 Status error = reg_ctx_sp->ReadRegister(&reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 if (error.Success())
407 reg_value_p = &reg_value;
408 // else log.
409 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000410
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411 if (reg_value_p) {
412 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
Pavel Labathe0a5b572017-01-20 14:17:16 +0000413 reg_value_p->GetByteSize(),
414 byte_order == lldb::eByteOrderLittle);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 } else {
416 // Zero-out any unreadable values.
417 if (reg_info.byte_size > 0) {
418 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
419 AppendHexValue(response, zeros.data(), zeros.size(), false);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000420 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000422}
423
Pavel Labathe0a5b572017-01-20 14:17:16 +0000424static JSONObject::SP GetRegistersAsJSON(NativeThreadProtocol &thread) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Pavel Labath4a4bb122015-07-16 14:14:35 +0000426
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427 NativeRegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
428 if (!reg_ctx_sp)
429 return nullptr;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000430
Kate Stoneb9c1b512016-09-06 20:57:50 +0000431 JSONObject::SP register_object_sp = std::make_shared<JSONObject>();
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000432
433#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434 // Expedite all registers in the first register set (i.e. should be GPRs) that
435 // are not contained in other registers.
436 const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
437 if (!reg_set_p)
438 return nullptr;
439 for (const uint32_t *reg_num_p = reg_set_p->registers;
440 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
441 uint32_t reg_num = *reg_num_p;
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000442#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443 // Expedite only a couple of registers until we figure out why sending
444 // registers is
445 // expensive.
446 static const uint32_t k_expedited_registers[] = {
447 LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
448 LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
Pavel Labathc4645bb2015-10-26 16:25:28 +0000449
Pavel Labathe0a5b572017-01-20 14:17:16 +0000450 for (const uint32_t *generic_reg_p = k_expedited_registers;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000451 *generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
452 uint32_t reg_num = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
453 eRegisterKindGeneric, *generic_reg_p);
454 if (reg_num == LLDB_INVALID_REGNUM)
455 continue; // Target does not support the given register.
Pavel Labathe4fc4ef2015-07-17 10:27:42 +0000456#endif
457
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458 const RegisterInfo *const reg_info_p =
459 reg_ctx_sp->GetRegisterInfoAtIndex(reg_num);
460 if (reg_info_p == nullptr) {
461 if (log)
462 log->Printf(
463 "%s failed to get register info for register index %" PRIu32,
464 __FUNCTION__, reg_num);
465 continue;
Pavel Labath4a4bb122015-07-16 14:14:35 +0000466 }
467
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468 if (reg_info_p->value_regs != nullptr)
469 continue; // Only expedite registers that are not contained in other
470 // registers.
Pavel Labath4a4bb122015-07-16 14:14:35 +0000471
Kate Stoneb9c1b512016-09-06 20:57:50 +0000472 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000473 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000474 if (error.Fail()) {
475 if (log)
476 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
Pavel Labath05569f62015-07-23 09:09:29 +0000477 __FUNCTION__,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
479 reg_num, error.AsCString());
480 continue;
Pavel Labath05569f62015-07-23 09:09:29 +0000481 }
482
Kate Stoneb9c1b512016-09-06 20:57:50 +0000483 StreamString stream;
484 WriteRegisterValueInHexFixedWidth(stream, reg_ctx_sp, *reg_info_p,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000485 &reg_value, lldb::eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486
487 register_object_sp->SetObject(
488 llvm::to_string(reg_num),
489 std::make_shared<JSONString>(stream.GetString()));
490 }
491
492 return register_object_sp;
Pavel Labath05569f62015-07-23 09:09:29 +0000493}
494
Kate Stoneb9c1b512016-09-06 20:57:50 +0000495static const char *GetStopReasonString(StopReason stop_reason) {
496 switch (stop_reason) {
497 case eStopReasonTrace:
498 return "trace";
499 case eStopReasonBreakpoint:
500 return "breakpoint";
501 case eStopReasonWatchpoint:
502 return "watchpoint";
503 case eStopReasonSignal:
504 return "signal";
505 case eStopReasonException:
506 return "exception";
507 case eStopReasonExec:
508 return "exec";
509 case eStopReasonInstrumentation:
510 case eStopReasonInvalid:
511 case eStopReasonPlanComplete:
512 case eStopReasonThreadExiting:
513 case eStopReasonNone:
514 break; // ignored
515 }
516 return nullptr;
517}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000518
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519static JSONArray::SP GetJSONThreadsInfo(NativeProcessProtocol &process,
520 bool abridged) {
521 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000522
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523 JSONArray::SP threads_array_sp = std::make_shared<JSONArray>();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000524
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 // Ensure we can get info on the given thread.
526 uint32_t thread_idx = 0;
527 for (NativeThreadProtocolSP thread_sp;
528 (thread_sp = process.GetThreadAtIndex(thread_idx)) != nullptr;
529 ++thread_idx) {
530
531 lldb::tid_t tid = thread_sp->GetID();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000532
533 // Grab the reason this thread stopped.
534 struct ThreadStopInfo tid_stop_info;
535 std::string description;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536 if (!thread_sp->GetStopReason(tid_stop_info, description))
537 return nullptr;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000538
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539 const int signum = tid_stop_info.details.signal.signo;
540 if (log) {
541 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
542 " tid %" PRIu64
543 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
544 __FUNCTION__, process.GetID(), tid, signum,
545 tid_stop_info.reason, tid_stop_info.details.exception.type);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000546 }
547
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 JSONObject::SP thread_obj_sp = std::make_shared<JSONObject>();
549 threads_array_sp->AppendObject(thread_obj_sp);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000550
Pavel Labathe0a5b572017-01-20 14:17:16 +0000551 if (!abridged) {
552 if (JSONObject::SP registers_sp = GetRegistersAsJSON(*thread_sp))
553 thread_obj_sp->SetObject("registers", registers_sp);
554 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 thread_obj_sp->SetObject("tid", std::make_shared<JSONNumber>(tid));
557 if (signum != 0)
558 thread_obj_sp->SetObject("signal", std::make_shared<JSONNumber>(signum));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000559
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 const std::string thread_name = thread_sp->GetName();
561 if (!thread_name.empty())
562 thread_obj_sp->SetObject("name",
563 std::make_shared<JSONString>(thread_name));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000564
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 if (const char *stop_reason_str = GetStopReasonString(tid_stop_info.reason))
566 thread_obj_sp->SetObject("reason",
567 std::make_shared<JSONString>(stop_reason_str));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000568
569 if (!description.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 thread_obj_sp->SetObject("description",
571 std::make_shared<JSONString>(description));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000572
Kate Stoneb9c1b512016-09-06 20:57:50 +0000573 if ((tid_stop_info.reason == eStopReasonException) &&
574 tid_stop_info.details.exception.type) {
575 thread_obj_sp->SetObject(
576 "metype",
577 std::make_shared<JSONNumber>(tid_stop_info.details.exception.type));
578
579 JSONArray::SP medata_array_sp = std::make_shared<JSONArray>();
580 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
581 ++i) {
582 medata_array_sp->AppendObject(std::make_shared<JSONNumber>(
583 tid_stop_info.details.exception.data[i]));
584 }
585 thread_obj_sp->SetObject("medata", medata_array_sp);
586 }
587
588 // TODO: Expedite interesting regions of inferior memory
589 }
590
591 return threads_array_sp;
592}
593
594GDBRemoteCommunication::PacketResult
595GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
596 lldb::tid_t tid) {
597 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
598
599 // Ensure we have a debugged process.
600 if (!m_debugged_process_sp ||
601 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
602 return SendErrorResponse(50);
603
604 if (log)
605 log->Printf(
606 "GDBRemoteCommunicationServerLLGS::%s preparing packet for pid %" PRIu64
607 " tid %" PRIu64,
608 __FUNCTION__, m_debugged_process_sp->GetID(), tid);
609
610 // Ensure we can get info on the given thread.
611 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
612 if (!thread_sp)
613 return SendErrorResponse(51);
614
615 // Grab the reason this thread stopped.
616 struct ThreadStopInfo tid_stop_info;
617 std::string description;
618 if (!thread_sp->GetStopReason(tid_stop_info, description))
619 return SendErrorResponse(52);
620
621 // FIXME implement register handling for exec'd inferiors.
622 // if (tid_stop_info.reason == eStopReasonExec)
623 // {
624 // const bool force = true;
625 // InitializeRegisters(force);
626 // }
627
628 StreamString response;
629 // Output the T packet with the thread
630 response.PutChar('T');
631 int signum = tid_stop_info.details.signal.signo;
632 if (log) {
633 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
634 " tid %" PRIu64
635 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
636 __FUNCTION__, m_debugged_process_sp->GetID(), tid, signum,
637 tid_stop_info.reason, tid_stop_info.details.exception.type);
638 }
639
640 // Print the signal number.
641 response.PutHex8(signum & 0xff);
642
643 // Include the tid.
644 response.Printf("thread:%" PRIx64 ";", tid);
645
646 // Include the thread name if there is one.
647 const std::string thread_name = thread_sp->GetName();
648 if (!thread_name.empty()) {
649 size_t thread_name_len = thread_name.length();
650
651 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
652 response.PutCString("name:");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000653 response.PutCString(thread_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000654 } else {
655 // The thread name contains special chars, send as hex bytes.
656 response.PutCString("hexname:");
657 response.PutCStringAsRawHex8(thread_name.c_str());
658 }
659 response.PutChar(';');
660 }
661
662 // If a 'QListThreadsInStopReply' was sent to enable this feature, we
663 // will send all thread IDs back in the "threads" key whose value is
664 // a list of hex thread IDs separated by commas:
665 // "threads:10a,10b,10c;"
666 // This will save the debugger from having to send a pair of qfThreadInfo
667 // and qsThreadInfo packets, but it also might take a lot of room in the
668 // stop reply packet, so it must be enabled only on systems where there
669 // are no limits on packet lengths.
670 if (m_list_threads_in_stop_reply) {
671 response.PutCString("threads:");
672
673 uint32_t thread_index = 0;
674 NativeThreadProtocolSP listed_thread_sp;
675 for (listed_thread_sp =
676 m_debugged_process_sp->GetThreadAtIndex(thread_index);
677 listed_thread_sp; ++thread_index,
678 listed_thread_sp = m_debugged_process_sp->GetThreadAtIndex(
679 thread_index)) {
680 if (thread_index > 0)
681 response.PutChar(',');
682 response.Printf("%" PRIx64, listed_thread_sp->GetID());
683 }
684 response.PutChar(';');
685
686 // Include JSON info that describes the stop reason for any threads
687 // that actually have stop reasons. We use the new "jstopinfo" key
688 // whose values is hex ascii JSON that contains the thread IDs
689 // thread stop info only for threads that have stop reasons. Only send
690 // this if we have more than one thread otherwise this packet has all
691 // the info it needs.
692 if (thread_index > 0) {
693 const bool threads_with_valid_stop_info_only = true;
694 JSONArray::SP threads_info_sp = GetJSONThreadsInfo(
695 *m_debugged_process_sp, threads_with_valid_stop_info_only);
696 if (threads_info_sp) {
697 response.PutCString("jstopinfo:");
698 StreamString unescaped_response;
699 threads_info_sp->Write(unescaped_response);
700 response.PutCStringAsRawHex8(unescaped_response.GetData());
701 response.PutChar(';');
702 } else if (log)
703 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
704 "jstopinfo field for pid %" PRIu64,
705 __FUNCTION__, m_debugged_process_sp->GetID());
706 }
Pavel Labathe0a5b572017-01-20 14:17:16 +0000707
708 uint32_t i = 0;
709 response.PutCString("thread-pcs");
710 char delimiter = ':';
711 for (NativeThreadProtocolSP thread_sp;
712 (thread_sp = m_debugged_process_sp->GetThreadAtIndex(i)) != nullptr;
713 ++i) {
714 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
715 if (!reg_ctx_sp)
716 continue;
717
718 uint32_t reg_to_read = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
719 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
720 const RegisterInfo *const reg_info_p =
721 reg_ctx_sp->GetRegisterInfoAtIndex(reg_to_read);
722
723 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000724 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Pavel Labathe0a5b572017-01-20 14:17:16 +0000725 if (error.Fail()) {
726 if (log)
727 log->Printf("%s failed to read register '%s' index %" PRIu32 ": %s",
728 __FUNCTION__,
729 reg_info_p->name ? reg_info_p->name
730 : "<unnamed-register>",
731 reg_to_read, error.AsCString());
732 continue;
733 }
734
735 response.PutChar(delimiter);
736 delimiter = ',';
737 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
738 &reg_value, endian::InlHostByteOrder());
739 }
740
741 response.PutChar(';');
Kate Stoneb9c1b512016-09-06 20:57:50 +0000742 }
743
744 //
745 // Expedite registers.
746 //
747
748 // Grab the register context.
749 NativeRegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
750 if (reg_ctx_sp) {
751 // Expedite all registers in the first register set (i.e. should be GPRs)
752 // that are not contained in other registers.
753 const RegisterSet *reg_set_p;
754 if (reg_ctx_sp->GetRegisterSetCount() > 0 &&
755 ((reg_set_p = reg_ctx_sp->GetRegisterSet(0)) != nullptr)) {
756 if (log)
757 log->Printf("GDBRemoteCommunicationServerLLGS::%s expediting registers "
758 "from set '%s' (registers set count: %zu)",
759 __FUNCTION__,
760 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
761 reg_set_p->num_registers);
762
763 for (const uint32_t *reg_num_p = reg_set_p->registers;
764 *reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
765 const RegisterInfo *const reg_info_p =
766 reg_ctx_sp->GetRegisterInfoAtIndex(*reg_num_p);
767 if (reg_info_p == nullptr) {
768 if (log)
769 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get "
770 "register info for register set '%s', register index "
771 "%" PRIu32,
772 __FUNCTION__,
773 reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
774 *reg_num_p);
775 } else if (reg_info_p->value_regs == nullptr) {
776 // Only expediate registers that are not contained in other registers.
777 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +0000778 Status error = reg_ctx_sp->ReadRegister(reg_info_p, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779 if (error.Success()) {
780 response.Printf("%.02x:", *reg_num_p);
781 WriteRegisterValueInHexFixedWidth(response, reg_ctx_sp, *reg_info_p,
Pavel Labathe0a5b572017-01-20 14:17:16 +0000782 &reg_value, lldb::eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 response.PutChar(';');
784 } else {
785 if (log)
786 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to read "
787 "register '%s' index %" PRIu32 ": %s",
788 __FUNCTION__, reg_info_p->name ? reg_info_p->name
789 : "<unnamed-register>",
790 *reg_num_p, error.AsCString());
791 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000792 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000793 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000794 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000795 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000796
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
798 if (reason_str != nullptr) {
799 response.Printf("reason:%s;", reason_str);
800 }
801
802 if (!description.empty()) {
803 // Description may contains special chars, send as hex bytes.
804 response.PutCString("description:");
805 response.PutCStringAsRawHex8(description.c_str());
806 response.PutChar(';');
807 } else if ((tid_stop_info.reason == eStopReasonException) &&
808 tid_stop_info.details.exception.type) {
809 response.PutCString("metype:");
810 response.PutHex64(tid_stop_info.details.exception.type);
811 response.PutCString(";mecount:");
812 response.PutHex32(tid_stop_info.details.exception.data_count);
813 response.PutChar(';');
814
815 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
816 response.PutCString("medata:");
817 response.PutHex64(tid_stop_info.details.exception.data[i]);
818 response.PutChar(';');
819 }
820 }
821
822 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000823}
824
Kate Stoneb9c1b512016-09-06 20:57:50 +0000825void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
826 NativeProcessProtocol *process) {
827 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000828
Kate Stoneb9c1b512016-09-06 20:57:50 +0000829 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
830 if (log)
831 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
832
833 PacketResult result = SendStopReasonForState(StateType::eStateExited);
834 if (result != PacketResult::Success) {
Tamas Berghammere13c2732015-02-11 10:29:30 +0000835 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000836 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
837 "notification for PID %" PRIu64 ", state: eStateExited",
838 __FUNCTION__, process->GetID());
839 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000840
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 // Close the pipe to the inferior terminal i/o if we launched it
842 // and set one up.
843 MaybeCloseInferiorTerminalConnection();
Tamas Berghammere13c2732015-02-11 10:29:30 +0000844
Kate Stoneb9c1b512016-09-06 20:57:50 +0000845 // We are ready to exit the debug monitor.
846 m_exit_now = true;
Tamas Berghammere13c2732015-02-11 10:29:30 +0000847}
848
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
850 NativeProcessProtocol *process) {
851 assert(process && "process cannot be NULL");
Tamas Berghammere13c2732015-02-11 10:29:30 +0000852
Kate Stoneb9c1b512016-09-06 20:57:50 +0000853 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
854 if (log)
855 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +0000856
Kate Stoneb9c1b512016-09-06 20:57:50 +0000857 // Send the stop reason unless this is the stop after the
858 // launch or attach.
859 switch (m_inferior_prev_state) {
860 case eStateLaunching:
861 case eStateAttaching:
862 // Don't send anything per debugserver behavior.
863 break;
864 default:
865 // In all other cases, send the stop reason.
866 PacketResult result = SendStopReasonForState(StateType::eStateStopped);
867 if (result != PacketResult::Success) {
868 if (log)
869 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send stop "
870 "notification for PID %" PRIu64 ", state: eStateExited",
871 __FUNCTION__, process->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +0000872 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873 break;
874 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000875}
876
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
878 NativeProcessProtocol *process, lldb::StateType state) {
879 assert(process && "process cannot be NULL");
880 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
881 if (log) {
882 log->Printf("GDBRemoteCommunicationServerLLGS::%s called with "
883 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
884 __FUNCTION__, process->GetID(), StateAsCString(state));
885 }
886
887 switch (state) {
888 case StateType::eStateRunning:
889 StartSTDIOForwarding();
890 break;
891
892 case StateType::eStateStopped:
893 // Make sure we get all of the pending stdout/stderr from the inferior
894 // and send it to the lldb host before we send the state change
895 // notification
896 SendProcessOutput();
897 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
898 // does not
899 // interfere with our protocol.
900 StopSTDIOForwarding();
901 HandleInferiorState_Stopped(process);
902 break;
903
904 case StateType::eStateExited:
905 // Same as above
906 SendProcessOutput();
907 StopSTDIOForwarding();
908 HandleInferiorState_Exited(process);
909 break;
910
911 default:
912 if (log) {
913 log->Printf("GDBRemoteCommunicationServerLLGS::%s didn't handle state "
914 "change for pid %" PRIu64 ", new state: %s",
915 __FUNCTION__, process->GetID(), StateAsCString(state));
Tamas Berghammere13c2732015-02-11 10:29:30 +0000916 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917 break;
918 }
Tamas Berghammere13c2732015-02-11 10:29:30 +0000919
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920 // Remember the previous state reported to us.
921 m_inferior_prev_state = state;
922}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000923
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
925 ClearProcessSpecificData();
926}
Tamas Berghammere13c2732015-02-11 10:29:30 +0000927
Kate Stoneb9c1b512016-09-06 20:57:50 +0000928void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
929 Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
930
931 if (!m_handshake_completed) {
932 if (!HandshakeWithClient()) {
933 if (log)
934 log->Printf("GDBRemoteCommunicationServerLLGS::%s handshake with "
935 "client failed, exiting",
936 __FUNCTION__);
937 m_mainloop.RequestTermination();
938 return;
939 }
940 m_handshake_completed = true;
941 }
942
943 bool interrupt = false;
944 bool done = false;
Zachary Turner97206d52017-05-12 04:51:55 +0000945 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000946 while (true) {
Pavel Labath1eff73c2016-11-24 10:54:49 +0000947 const PacketResult result = GetPacketAndSendResponse(
948 std::chrono::microseconds(0), error, interrupt, done);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 if (result == PacketResult::ErrorReplyTimeout)
950 break; // No more packets in the queue
951
952 if ((result != PacketResult::Success)) {
953 if (log)
954 log->Printf("GDBRemoteCommunicationServerLLGS::%s processing a packet "
955 "failed: %s",
956 __FUNCTION__, error.AsCString());
957 m_mainloop.RequestTermination();
958 break;
959 }
960 }
961}
962
Zachary Turner97206d52017-05-12 04:51:55 +0000963Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964 std::unique_ptr<Connection> &&connection) {
965 IOObjectSP read_object_sp = connection->GetReadObject();
966 GDBRemoteCommunicationServer::SetConnection(connection.release());
967
Zachary Turner97206d52017-05-12 04:51:55 +0000968 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 m_network_handle_up = m_mainloop.RegisterReadObject(
970 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
971 error);
972 return error;
973}
974
975GDBRemoteCommunication::PacketResult
976GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
977 uint32_t len) {
978 if ((buffer == nullptr) || (len == 0)) {
979 // Nothing to send.
980 return PacketResult::Success;
981 }
982
983 StreamString response;
984 response.PutChar('O');
985 response.PutBytesAsRawHex8(buffer, len);
986
987 return SendPacketNoLock(response.GetString());
988}
989
Zachary Turner97206d52017-05-12 04:51:55 +0000990Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
991 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992
993 // Set up the reading/handling of process I/O
994 std::unique_ptr<ConnectionFileDescriptor> conn_up(
995 new ConnectionFileDescriptor(fd, true));
996 if (!conn_up) {
997 error.SetErrorString("failed to create ConnectionFileDescriptor");
998 return error;
999 }
1000
1001 m_stdio_communication.SetCloseOnEOF(false);
1002 m_stdio_communication.SetConnection(conn_up.release());
1003 if (!m_stdio_communication.IsConnected()) {
1004 error.SetErrorString(
1005 "failed to set connection for inferior I/O communication");
1006 return error;
1007 }
1008
Zachary Turner97206d52017-05-12 04:51:55 +00001009 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010}
1011
1012void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1013 // Don't forward if not connected (e.g. when attaching).
1014 if (!m_stdio_communication.IsConnected())
1015 return;
1016
Zachary Turner97206d52017-05-12 04:51:55 +00001017 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 lldbassert(!m_stdio_handle_up);
1019 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1020 m_stdio_communication.GetConnection()->GetReadObject(),
1021 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1022
1023 if (!m_stdio_handle_up) {
1024 // Not much we can do about the failure. Log it and continue without
1025 // forwarding.
1026 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1027 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
1028 "forwarding: %s",
1029 __FUNCTION__, error.AsCString());
1030 }
1031}
1032
1033void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1034 m_stdio_handle_up.reset();
1035}
1036
1037void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1038 char buffer[1024];
1039 ConnectionStatus status;
Zachary Turner97206d52017-05-12 04:51:55 +00001040 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001041 while (true) {
Pavel Labathc4063ee2016-11-25 11:58:44 +00001042 size_t bytes_read = m_stdio_communication.Read(
1043 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044 switch (status) {
1045 case eConnectionStatusSuccess:
1046 SendONotification(buffer, bytes_read);
1047 break;
1048 case eConnectionStatusLostConnection:
1049 case eConnectionStatusEndOfFile:
1050 case eConnectionStatusError:
1051 case eConnectionStatusNoConnection:
1052 if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
1053 log->Printf("GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1054 "forwarding as communication returned status %d (error: "
1055 "%s)",
1056 __FUNCTION__, status, error.AsCString());
1057 m_stdio_handle_up.reset();
1058 return;
1059
1060 case eConnectionStatusInterrupted:
1061 case eConnectionStatusTimedOut:
1062 return;
1063 }
1064 }
1065}
1066
1067GDBRemoteCommunication::PacketResult
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001068GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
1069 StringExtractorGDBRemote &packet) {
1070 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1071 // Fail if we don't have a current process.
1072 if (!m_debugged_process_sp ||
1073 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1074 return SendErrorResponse(68);
1075
1076 if (!packet.ConsumeFront("jTraceStart:"))
1077 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1078
1079 TraceOptions options;
1080 uint64_t type = std::numeric_limits<uint64_t>::max();
1081 uint64_t buffersize = std::numeric_limits<uint64_t>::max();
1082 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1083 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
1084
1085 auto json_object = StructuredData::ParseJSON(packet.Peek());
1086
1087 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001088 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001089 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1090
1091 auto json_dict = json_object->GetAsDictionary();
1092
Pavel Labath4c950232017-05-26 13:53:39 +00001093 json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001094 options.setMetaDataBufferSize(metabuffersize);
1095
Pavel Labath4c950232017-05-26 13:53:39 +00001096 json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001097 options.setTraceBufferSize(buffersize);
1098
Pavel Labath4c950232017-05-26 13:53:39 +00001099 json_dict->GetValueForKeyAsInteger("type", type);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001100 options.setType(static_cast<lldb::TraceType>(type));
1101
Pavel Labath4c950232017-05-26 13:53:39 +00001102 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001103 options.setThreadID(tid);
1104
1105 StructuredData::ObjectSP custom_params_sp =
1106 json_dict->GetValueForKey("params");
1107 if (custom_params_sp &&
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001108 custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001109 return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
1110
1111 options.setTraceParams(
1112 static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
1113
1114 if (buffersize == std::numeric_limits<uint64_t>::max() ||
1115 type != lldb::TraceType::eTraceTypeProcessorTrace) {
1116 LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
1117 type);
1118 return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
1119 }
1120
1121 Status error;
1122 lldb::user_id_t uid = LLDB_INVALID_UID;
1123 uid = m_debugged_process_sp->StartTrace(options, error);
1124 LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
1125 if (error.Fail())
1126 return SendErrorResponse(error.GetError());
1127
1128 StreamGDBRemote response;
1129 response.Printf("%" PRIx64, uid);
1130 return SendPacketNoLock(response.GetString());
1131}
1132
1133GDBRemoteCommunication::PacketResult
1134GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
1135 StringExtractorGDBRemote &packet) {
1136 // Fail if we don't have a current process.
1137 if (!m_debugged_process_sp ||
1138 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1139 return SendErrorResponse(68);
1140
1141 if (!packet.ConsumeFront("jTraceStop:"))
1142 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1143
1144 lldb::user_id_t uid = LLDB_INVALID_UID;
1145 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1146
1147 auto json_object = StructuredData::ParseJSON(packet.Peek());
1148
1149 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001150 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001151 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1152
1153 auto json_dict = json_object->GetAsDictionary();
1154
Pavel Labath4c950232017-05-26 13:53:39 +00001155 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001156 return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
1157
Pavel Labath4c950232017-05-26 13:53:39 +00001158 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001159
1160 Status error = m_debugged_process_sp->StopTrace(uid, tid);
1161
1162 if (error.Fail())
1163 return SendErrorResponse(error.GetError());
1164
1165 return SendOKResponse();
1166}
1167
1168GDBRemoteCommunication::PacketResult
1169GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
1170 StringExtractorGDBRemote &packet) {
1171
1172 // Fail if we don't have a current process.
1173 if (!m_debugged_process_sp ||
1174 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1175 return SendErrorResponse(68);
1176
1177 if (!packet.ConsumeFront("jTraceConfigRead:"))
1178 return SendIllFormedResponse(packet,
1179 "jTraceConfigRead: Ill formed packet ");
1180
1181 lldb::user_id_t uid = LLDB_INVALID_UID;
1182 lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
1183
1184 auto json_object = StructuredData::ParseJSON(packet.Peek());
1185
1186 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001187 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001188 return SendIllFormedResponse(packet,
1189 "jTraceConfigRead: Ill formed packet ");
1190
1191 auto json_dict = json_object->GetAsDictionary();
1192
Pavel Labath4c950232017-05-26 13:53:39 +00001193 if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001194 return SendIllFormedResponse(packet,
1195 "jTraceConfigRead: Ill formed packet ");
1196
Pavel Labath4c950232017-05-26 13:53:39 +00001197 json_dict->GetValueForKeyAsInteger("threadid", threadid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001198
1199 TraceOptions options;
1200 StreamGDBRemote response;
1201
1202 options.setThreadID(threadid);
1203 Status error = m_debugged_process_sp->GetTraceConfig(uid, options);
1204
1205 if (error.Fail())
1206 return SendErrorResponse(error.GetError());
1207
1208 StreamGDBRemote escaped_response;
1209 StructuredData::Dictionary json_packet;
1210
1211 json_packet.AddIntegerItem("type", options.getType());
1212 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
1213 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
1214
1215 StructuredData::DictionarySP custom_params = options.getTraceParams();
1216 if (custom_params)
1217 json_packet.AddItem("params", custom_params);
1218
1219 StreamString json_string;
1220 json_packet.Dump(json_string, false);
1221 escaped_response.PutEscapedBytes(json_string.GetData(),
1222 json_string.GetSize());
1223 return SendPacketNoLock(escaped_response.GetString());
1224}
1225
1226GDBRemoteCommunication::PacketResult
1227GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
1228 StringExtractorGDBRemote &packet) {
1229
1230 // Fail if we don't have a current process.
1231 if (!m_debugged_process_sp ||
1232 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1233 return SendErrorResponse(68);
1234
1235 enum PacketType { MetaData, BufferData };
1236 PacketType tracetype = MetaData;
1237
1238 if (packet.ConsumeFront("jTraceBufferRead:"))
1239 tracetype = BufferData;
1240 else if (packet.ConsumeFront("jTraceMetaRead:"))
1241 tracetype = MetaData;
1242 else {
1243 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1244 }
1245
1246 lldb::user_id_t uid = LLDB_INVALID_UID;
1247
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001248 uint64_t byte_count = std::numeric_limits<uint64_t>::max();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001249 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001250 uint64_t offset = std::numeric_limits<uint64_t>::max();
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001251
1252 auto json_object = StructuredData::ParseJSON(packet.Peek());
1253
1254 if (!json_object ||
Stephan Bergmanncf4321a2017-05-29 08:51:58 +00001255 json_object->GetType() != lldb::eStructuredDataTypeDictionary)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001256 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1257
1258 auto json_dict = json_object->GetAsDictionary();
1259
Pavel Labath4c950232017-05-26 13:53:39 +00001260 if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
1261 !json_dict->GetValueForKeyAsInteger("offset", offset) ||
1262 !json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001263 return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
1264
Pavel Labath4c950232017-05-26 13:53:39 +00001265 json_dict->GetValueForKeyAsInteger("threadid", tid);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001266
1267 // Allocate the response buffer.
Ravitheja Addepally0e62a122017-05-26 14:26:14 +00001268 std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
1269 if (!buffer)
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001270 return SendErrorResponse(0x78);
1271
1272 StreamGDBRemote response;
1273 Status error;
Ravitheja Addepally0e62a122017-05-26 14:26:14 +00001274 llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001275
1276 if (tracetype == BufferData)
1277 error = m_debugged_process_sp->GetData(uid, tid, buf, offset);
1278 else if (tracetype == MetaData)
1279 error = m_debugged_process_sp->GetMetaData(uid, tid, buf, offset);
1280
1281 if (error.Fail())
1282 return SendErrorResponse(error.GetError());
1283
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001284 for (auto i : buf)
1285 response.PutHex8(i);
Ravitheja Addepallye714c4f2017-05-26 11:46:27 +00001286
1287 StreamGDBRemote escaped_response;
1288 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
1289 return SendPacketNoLock(escaped_response.GetString());
1290}
1291
1292GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1294 StringExtractorGDBRemote &packet) {
1295 // Fail if we don't have a current process.
1296 if (!m_debugged_process_sp ||
1297 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1298 return SendErrorResponse(68);
1299
1300 lldb::pid_t pid = m_debugged_process_sp->GetID();
1301
1302 if (pid == LLDB_INVALID_PROCESS_ID)
1303 return SendErrorResponse(1);
1304
1305 ProcessInstanceInfo proc_info;
1306 if (!Host::GetProcessInfo(pid, proc_info))
1307 return SendErrorResponse(1);
1308
1309 StreamString response;
1310 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1311 return SendPacketNoLock(response.GetString());
1312}
1313
1314GDBRemoteCommunication::PacketResult
1315GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1316 // Fail if we don't have a current process.
1317 if (!m_debugged_process_sp ||
1318 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1319 return SendErrorResponse(68);
1320
1321 // Make sure we set the current thread so g and p packets return
1322 // the data the gdb will expect.
1323 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
1324 SetCurrentThreadID(tid);
1325
1326 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetCurrentThread();
1327 if (!thread_sp)
1328 return SendErrorResponse(69);
1329
1330 StreamString response;
1331 response.Printf("QC%" PRIx64, thread_sp->GetID());
1332
1333 return SendPacketNoLock(response.GetString());
1334}
1335
1336GDBRemoteCommunication::PacketResult
1337GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1338 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1339
1340 StopSTDIOForwarding();
1341
1342 if (!m_debugged_process_sp) {
1343 if (log)
1344 log->Printf(
1345 "GDBRemoteCommunicationServerLLGS::%s No debugged process found.",
1346 __FUNCTION__);
1347 return PacketResult::Success;
1348 }
1349
Zachary Turner97206d52017-05-12 04:51:55 +00001350 Status error = m_debugged_process_sp->Kill();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001351 if (error.Fail() && log)
1352 log->Printf("GDBRemoteCommunicationServerLLGS::%s Failed to kill debugged "
1353 "process %" PRIu64 ": %s",
1354 __FUNCTION__, m_debugged_process_sp->GetID(),
1355 error.AsCString());
1356
1357 // No OK response for kill packet.
1358 // return SendOKResponse ();
1359 return PacketResult::Success;
1360}
1361
1362GDBRemoteCommunication::PacketResult
1363GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1364 StringExtractorGDBRemote &packet) {
1365 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1366 if (packet.GetU32(0))
1367 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1368 else
1369 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1370 return SendOKResponse();
1371}
1372
1373GDBRemoteCommunication::PacketResult
1374GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1375 StringExtractorGDBRemote &packet) {
1376 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1377 std::string path;
1378 packet.GetHexByteString(path);
1379 m_process_launch_info.SetWorkingDirectory(FileSpec{path, true});
1380 return SendOKResponse();
1381}
1382
1383GDBRemoteCommunication::PacketResult
1384GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1385 StringExtractorGDBRemote &packet) {
1386 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1387 if (working_dir) {
1388 StreamString response;
1389 response.PutCStringAsRawHex8(working_dir.GetCString());
1390 return SendPacketNoLock(response.GetString());
1391 }
1392
1393 return SendErrorResponse(14);
1394}
1395
1396GDBRemoteCommunication::PacketResult
1397GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1398 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1399 if (log)
1400 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1401
1402 // Ensure we have a native process.
1403 if (!m_debugged_process_sp) {
1404 if (log)
1405 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1406 "shared pointer",
1407 __FUNCTION__);
1408 return SendErrorResponse(0x36);
1409 }
1410
1411 // Pull out the signal number.
1412 packet.SetFilePos(::strlen("C"));
1413 if (packet.GetBytesLeft() < 1) {
1414 // Shouldn't be using a C without a signal.
1415 return SendIllFormedResponse(packet, "C packet specified without signal.");
1416 }
1417 const uint32_t signo =
1418 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1419 if (signo == std::numeric_limits<uint32_t>::max())
1420 return SendIllFormedResponse(packet, "failed to parse signal number");
1421
1422 // Handle optional continue address.
1423 if (packet.GetBytesLeft() > 0) {
1424 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1425 if (*packet.Peek() == ';')
1426 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1427 else
1428 return SendIllFormedResponse(
1429 packet, "unexpected content after $C{signal-number}");
1430 }
1431
1432 ResumeActionList resume_actions(StateType::eStateRunning, 0);
Zachary Turner97206d52017-05-12 04:51:55 +00001433 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001434
1435 // We have two branches: what to do if a continue thread is specified (in
1436 // which case we target
1437 // sending the signal to that thread), or when we don't have a continue thread
1438 // set (in which
1439 // case we send a signal to the process).
1440
1441 // TODO discuss with Greg Clayton, make sure this makes sense.
1442
1443 lldb::tid_t signal_tid = GetContinueThreadID();
1444 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1445 // The resume action for the continue thread (or all threads if a continue
1446 // thread is not set).
1447 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1448 static_cast<int>(signo)};
1449
1450 // Add the action for the continue thread (or all threads when the continue
1451 // thread isn't present).
1452 resume_actions.Append(action);
1453 } else {
1454 // Send the signal to the process since we weren't targeting a specific
1455 // continue thread with the signal.
1456 error = m_debugged_process_sp->Signal(signo);
1457 if (error.Fail()) {
1458 if (log)
1459 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to send "
1460 "signal for process %" PRIu64 ": %s",
1461 __FUNCTION__, m_debugged_process_sp->GetID(),
1462 error.AsCString());
1463
1464 return SendErrorResponse(0x52);
1465 }
1466 }
1467
1468 // Resume the threads.
1469 error = m_debugged_process_sp->Resume(resume_actions);
1470 if (error.Fail()) {
1471 if (log)
1472 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to resume "
1473 "threads for process %" PRIu64 ": %s",
1474 __FUNCTION__, m_debugged_process_sp->GetID(),
1475 error.AsCString());
1476
1477 return SendErrorResponse(0x38);
1478 }
1479
1480 // Don't send an "OK" packet; response is the stopped/exited message.
1481 return PacketResult::Success;
1482}
1483
1484GDBRemoteCommunication::PacketResult
1485GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1486 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1487 if (log)
1488 log->Printf("GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1489
1490 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1491
1492 // For now just support all continue.
1493 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1494 if (has_continue_address) {
1495 if (log)
1496 log->Printf("GDBRemoteCommunicationServerLLGS::%s not implemented for "
1497 "c{address} variant [%s remains]",
1498 __FUNCTION__, packet.Peek());
1499 return SendUnimplementedResponse(packet.GetStringRef().c_str());
1500 }
1501
1502 // Ensure we have a native process.
1503 if (!m_debugged_process_sp) {
1504 if (log)
1505 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1506 "shared pointer",
1507 __FUNCTION__);
1508 return SendErrorResponse(0x36);
1509 }
1510
1511 // Build the ResumeActionList
1512 ResumeActionList actions(StateType::eStateRunning, 0);
1513
Zachary Turner97206d52017-05-12 04:51:55 +00001514 Status error = m_debugged_process_sp->Resume(actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001515 if (error.Fail()) {
1516 if (log) {
1517 log->Printf(
1518 "GDBRemoteCommunicationServerLLGS::%s c failed for process %" PRIu64
1519 ": %s",
1520 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
1521 }
1522 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1523 }
1524
1525 if (log)
1526 log->Printf(
1527 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1528 __FUNCTION__, m_debugged_process_sp->GetID());
1529
1530 // No response required from continue.
1531 return PacketResult::Success;
1532}
1533
1534GDBRemoteCommunication::PacketResult
1535GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1536 StringExtractorGDBRemote &packet) {
1537 StreamString response;
1538 response.Printf("vCont;c;C;s;S");
1539
1540 return SendPacketNoLock(response.GetString());
1541}
1542
1543GDBRemoteCommunication::PacketResult
1544GDBRemoteCommunicationServerLLGS::Handle_vCont(
1545 StringExtractorGDBRemote &packet) {
1546 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1547 if (log)
1548 log->Printf("GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1549 __FUNCTION__);
1550
1551 packet.SetFilePos(::strlen("vCont"));
1552
1553 if (packet.GetBytesLeft() == 0) {
1554 if (log)
1555 log->Printf("GDBRemoteCommunicationServerLLGS::%s missing action from "
1556 "vCont package",
1557 __FUNCTION__);
1558 return SendIllFormedResponse(packet, "Missing action from vCont package");
1559 }
1560
1561 // Check if this is all continue (no options or ";c").
1562 if (::strcmp(packet.Peek(), ";c") == 0) {
1563 // Move past the ';', then do a simple 'c'.
1564 packet.SetFilePos(packet.GetFilePos() + 1);
1565 return Handle_c(packet);
1566 } else if (::strcmp(packet.Peek(), ";s") == 0) {
1567 // Move past the ';', then do a simple 's'.
1568 packet.SetFilePos(packet.GetFilePos() + 1);
1569 return Handle_s(packet);
1570 }
1571
1572 // Ensure we have a native process.
1573 if (!m_debugged_process_sp) {
1574 if (log)
1575 log->Printf("GDBRemoteCommunicationServerLLGS::%s no debugged process "
1576 "shared pointer",
1577 __FUNCTION__);
1578 return SendErrorResponse(0x36);
1579 }
1580
1581 ResumeActionList thread_actions;
1582
1583 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1584 // Skip the semi-colon.
1585 packet.GetChar();
1586
1587 // Build up the thread action.
1588 ResumeAction thread_action;
1589 thread_action.tid = LLDB_INVALID_THREAD_ID;
1590 thread_action.state = eStateInvalid;
1591 thread_action.signal = 0;
1592
1593 const char action = packet.GetChar();
1594 switch (action) {
1595 case 'C':
1596 thread_action.signal = packet.GetHexMaxU32(false, 0);
1597 if (thread_action.signal == 0)
1598 return SendIllFormedResponse(
1599 packet, "Could not parse signal in vCont packet C action");
1600 LLVM_FALLTHROUGH;
1601
1602 case 'c':
1603 // Continue
1604 thread_action.state = eStateRunning;
1605 break;
1606
1607 case 'S':
1608 thread_action.signal = packet.GetHexMaxU32(false, 0);
1609 if (thread_action.signal == 0)
1610 return SendIllFormedResponse(
1611 packet, "Could not parse signal in vCont packet S action");
1612 LLVM_FALLTHROUGH;
1613
1614 case 's':
1615 // Step
1616 thread_action.state = eStateStepping;
1617 break;
Pavel Labathabadc222015-11-27 13:33:29 +00001618
Tamas Berghammere13c2732015-02-11 10:29:30 +00001619 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001620 return SendIllFormedResponse(packet, "Unsupported vCont action");
1621 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00001622 }
1623
Kate Stoneb9c1b512016-09-06 20:57:50 +00001624 // Parse out optional :{thread-id} value.
1625 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1626 // Consume the separator.
1627 packet.GetChar();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001628
Kate Stoneb9c1b512016-09-06 20:57:50 +00001629 thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
1630 if (thread_action.tid == LLDB_INVALID_THREAD_ID)
1631 return SendIllFormedResponse(
1632 packet, "Could not parse thread number in vCont packet");
Pavel Labath77dc9562015-07-13 10:44:55 +00001633 }
1634
Kate Stoneb9c1b512016-09-06 20:57:50 +00001635 thread_actions.Append(thread_action);
1636 }
Pavel Labath77dc9562015-07-13 10:44:55 +00001637
Zachary Turner97206d52017-05-12 04:51:55 +00001638 Status error = m_debugged_process_sp->Resume(thread_actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001639 if (error.Fail()) {
1640 if (log) {
1641 log->Printf("GDBRemoteCommunicationServerLLGS::%s vCont failed for "
1642 "process %" PRIu64 ": %s",
1643 __FUNCTION__, m_debugged_process_sp->GetID(),
1644 error.AsCString());
Pavel Labath77dc9562015-07-13 10:44:55 +00001645 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001646 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1647 }
1648
1649 if (log)
1650 log->Printf(
1651 "GDBRemoteCommunicationServerLLGS::%s continued process %" PRIu64,
1652 __FUNCTION__, m_debugged_process_sp->GetID());
1653
1654 // No response required from vCont.
1655 return PacketResult::Success;
Pavel Labath77dc9562015-07-13 10:44:55 +00001656}
1657
Kate Stoneb9c1b512016-09-06 20:57:50 +00001658void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1659 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1660 if (log)
1661 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting current thread "
1662 "id to %" PRIu64,
1663 __FUNCTION__, tid);
Pavel Labath77dc9562015-07-13 10:44:55 +00001664
Kate Stoneb9c1b512016-09-06 20:57:50 +00001665 m_current_tid = tid;
1666 if (m_debugged_process_sp)
1667 m_debugged_process_sp->SetCurrentThreadID(m_current_tid);
1668}
1669
1670void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1671 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1672 if (log)
1673 log->Printf("GDBRemoteCommunicationServerLLGS::%s setting continue thread "
1674 "id to %" PRIu64,
1675 __FUNCTION__, tid);
1676
1677 m_continue_tid = tid;
Pavel Labath77dc9562015-07-13 10:44:55 +00001678}
1679
Tamas Berghammere13c2732015-02-11 10:29:30 +00001680GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001681GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1682 StringExtractorGDBRemote &packet) {
1683 // Handle the $? gdbremote command.
Tamas Berghammere13c2732015-02-11 10:29:30 +00001684
Kate Stoneb9c1b512016-09-06 20:57:50 +00001685 // If no process, indicate error
1686 if (!m_debugged_process_sp)
1687 return SendErrorResponse(02);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001688
Kate Stoneb9c1b512016-09-06 20:57:50 +00001689 return SendStopReasonForState(m_debugged_process_sp->GetState());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001690}
1691
1692GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001693GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1694 lldb::StateType process_state) {
1695 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00001696
Kate Stoneb9c1b512016-09-06 20:57:50 +00001697 switch (process_state) {
1698 case eStateAttaching:
1699 case eStateLaunching:
1700 case eStateRunning:
1701 case eStateStepping:
1702 case eStateDetached:
1703 // NOTE: gdb protocol doc looks like it should return $OK
1704 // when everything is running (i.e. no stopped result).
1705 return PacketResult::Success; // Ignore
Tamas Berghammere13c2732015-02-11 10:29:30 +00001706
Kate Stoneb9c1b512016-09-06 20:57:50 +00001707 case eStateSuspended:
1708 case eStateStopped:
1709 case eStateCrashed: {
1710 lldb::tid_t tid = m_debugged_process_sp->GetCurrentThreadID();
Tamas Berghammere13c2732015-02-11 10:29:30 +00001711 // Make sure we set the current thread so g and p packets return
1712 // the data the gdb will expect.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001713 SetCurrentThreadID(tid);
1714 return SendStopReplyPacketForThread(tid);
1715 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001716
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717 case eStateInvalid:
1718 case eStateUnloaded:
1719 case eStateExited:
1720 return SendWResponse(m_debugged_process_sp.get());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001721
Kate Stoneb9c1b512016-09-06 20:57:50 +00001722 default:
1723 if (log) {
1724 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
1725 ", current state reporting not handled: %s",
1726 __FUNCTION__, m_debugged_process_sp->GetID(),
1727 StateAsCString(process_state));
Pavel Labath424b2012015-07-28 09:06:56 +00001728 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001729 break;
1730 }
Pavel Labath424b2012015-07-28 09:06:56 +00001731
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732 return SendErrorResponse(0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001733}
1734
1735GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001736GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1737 StringExtractorGDBRemote &packet) {
1738 // Fail if we don't have a current process.
1739 if (!m_debugged_process_sp ||
1740 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
1741 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001742
Kate Stoneb9c1b512016-09-06 20:57:50 +00001743 // Ensure we have a thread.
1744 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadAtIndex(0));
1745 if (!thread_sp)
1746 return SendErrorResponse(69);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001747
Kate Stoneb9c1b512016-09-06 20:57:50 +00001748 // Get the register context for the first thread.
1749 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
1750 if (!reg_context_sp)
1751 return SendErrorResponse(69);
1752
1753 // Parse out the register number from the request.
1754 packet.SetFilePos(strlen("qRegisterInfo"));
1755 const uint32_t reg_index =
1756 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1757 if (reg_index == std::numeric_limits<uint32_t>::max())
1758 return SendErrorResponse(69);
1759
1760 // Return the end of registers response if we've iterated one past the end of
1761 // the register set.
1762 if (reg_index >= reg_context_sp->GetUserRegisterCount())
1763 return SendErrorResponse(69);
1764
1765 const RegisterInfo *reg_info =
1766 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
1767 if (!reg_info)
1768 return SendErrorResponse(69);
1769
1770 // Build the reginfos response.
1771 StreamGDBRemote response;
1772
1773 response.PutCString("name:");
1774 response.PutCString(reg_info->name);
1775 response.PutChar(';');
1776
1777 if (reg_info->alt_name && reg_info->alt_name[0]) {
1778 response.PutCString("alt-name:");
1779 response.PutCString(reg_info->alt_name);
1780 response.PutChar(';');
1781 }
1782
1783 response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
1784 reg_info->byte_size * 8, reg_info->byte_offset);
1785
1786 switch (reg_info->encoding) {
1787 case eEncodingUint:
1788 response.PutCString("encoding:uint;");
1789 break;
1790 case eEncodingSint:
1791 response.PutCString("encoding:sint;");
1792 break;
1793 case eEncodingIEEE754:
1794 response.PutCString("encoding:ieee754;");
1795 break;
1796 case eEncodingVector:
1797 response.PutCString("encoding:vector;");
1798 break;
1799 default:
1800 break;
1801 }
1802
1803 switch (reg_info->format) {
1804 case eFormatBinary:
1805 response.PutCString("format:binary;");
1806 break;
1807 case eFormatDecimal:
1808 response.PutCString("format:decimal;");
1809 break;
1810 case eFormatHex:
1811 response.PutCString("format:hex;");
1812 break;
1813 case eFormatFloat:
1814 response.PutCString("format:float;");
1815 break;
1816 case eFormatVectorOfSInt8:
1817 response.PutCString("format:vector-sint8;");
1818 break;
1819 case eFormatVectorOfUInt8:
1820 response.PutCString("format:vector-uint8;");
1821 break;
1822 case eFormatVectorOfSInt16:
1823 response.PutCString("format:vector-sint16;");
1824 break;
1825 case eFormatVectorOfUInt16:
1826 response.PutCString("format:vector-uint16;");
1827 break;
1828 case eFormatVectorOfSInt32:
1829 response.PutCString("format:vector-sint32;");
1830 break;
1831 case eFormatVectorOfUInt32:
1832 response.PutCString("format:vector-uint32;");
1833 break;
1834 case eFormatVectorOfFloat32:
1835 response.PutCString("format:vector-float32;");
1836 break;
Valentina Giusticda0ae42016-09-08 14:16:45 +00001837 case eFormatVectorOfUInt64:
1838 response.PutCString("format:vector-uint64;");
1839 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001840 case eFormatVectorOfUInt128:
1841 response.PutCString("format:vector-uint128;");
1842 break;
1843 default:
1844 break;
1845 };
1846
1847 const char *const register_set_name =
1848 reg_context_sp->GetRegisterSetNameForRegisterAtIndex(reg_index);
1849 if (register_set_name) {
1850 response.PutCString("set:");
1851 response.PutCString(register_set_name);
1852 response.PutChar(';');
1853 }
1854
1855 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
1856 LLDB_INVALID_REGNUM)
1857 response.Printf("ehframe:%" PRIu32 ";",
1858 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
1859
1860 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
1861 response.Printf("dwarf:%" PRIu32 ";",
1862 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
1863
1864 switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
1865 case LLDB_REGNUM_GENERIC_PC:
1866 response.PutCString("generic:pc;");
1867 break;
1868 case LLDB_REGNUM_GENERIC_SP:
1869 response.PutCString("generic:sp;");
1870 break;
1871 case LLDB_REGNUM_GENERIC_FP:
1872 response.PutCString("generic:fp;");
1873 break;
1874 case LLDB_REGNUM_GENERIC_RA:
1875 response.PutCString("generic:ra;");
1876 break;
1877 case LLDB_REGNUM_GENERIC_FLAGS:
1878 response.PutCString("generic:flags;");
1879 break;
1880 case LLDB_REGNUM_GENERIC_ARG1:
1881 response.PutCString("generic:arg1;");
1882 break;
1883 case LLDB_REGNUM_GENERIC_ARG2:
1884 response.PutCString("generic:arg2;");
1885 break;
1886 case LLDB_REGNUM_GENERIC_ARG3:
1887 response.PutCString("generic:arg3;");
1888 break;
1889 case LLDB_REGNUM_GENERIC_ARG4:
1890 response.PutCString("generic:arg4;");
1891 break;
1892 case LLDB_REGNUM_GENERIC_ARG5:
1893 response.PutCString("generic:arg5;");
1894 break;
1895 case LLDB_REGNUM_GENERIC_ARG6:
1896 response.PutCString("generic:arg6;");
1897 break;
1898 case LLDB_REGNUM_GENERIC_ARG7:
1899 response.PutCString("generic:arg7;");
1900 break;
1901 case LLDB_REGNUM_GENERIC_ARG8:
1902 response.PutCString("generic:arg8;");
1903 break;
1904 default:
1905 break;
1906 }
1907
1908 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
1909 response.PutCString("container-regs:");
1910 int i = 0;
1911 for (const uint32_t *reg_num = reg_info->value_regs;
1912 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1913 if (i > 0)
1914 response.PutChar(',');
1915 response.Printf("%" PRIx32, *reg_num);
Tamas Berghammere13c2732015-02-11 10:29:30 +00001916 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001917 response.PutChar(';');
1918 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001919
Kate Stoneb9c1b512016-09-06 20:57:50 +00001920 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
1921 response.PutCString("invalidate-regs:");
1922 int i = 0;
1923 for (const uint32_t *reg_num = reg_info->invalidate_regs;
1924 *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
1925 if (i > 0)
1926 response.PutChar(',');
1927 response.Printf("%" PRIx32, *reg_num);
1928 }
1929 response.PutChar(';');
1930 }
1931
1932 if (reg_info->dynamic_size_dwarf_expr_bytes) {
1933 const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
1934 response.PutCString("dynamic_size_dwarf_expr_bytes:");
1935 for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
1936 response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
1937 response.PutChar(';');
1938 }
1939 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00001940}
1941
1942GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00001943GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
1944 StringExtractorGDBRemote &packet) {
1945 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
1946
1947 // Fail if we don't have a current process.
1948 if (!m_debugged_process_sp ||
1949 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00001950 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001951 log->Printf("GDBRemoteCommunicationServerLLGS::%s() no process (%s), "
1952 "returning OK",
1953 __FUNCTION__,
1954 m_debugged_process_sp ? "invalid process id"
1955 : "null m_debugged_process_sp");
1956 return SendOKResponse();
1957 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00001958
Kate Stoneb9c1b512016-09-06 20:57:50 +00001959 StreamGDBRemote response;
1960 response.PutChar('m');
1961
1962 if (log)
1963 log->Printf(
1964 "GDBRemoteCommunicationServerLLGS::%s() starting thread iteration",
1965 __FUNCTION__);
1966
1967 NativeThreadProtocolSP thread_sp;
1968 uint32_t thread_index;
1969 for (thread_index = 0,
1970 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index);
1971 thread_sp; ++thread_index,
1972 thread_sp = m_debugged_process_sp->GetThreadAtIndex(thread_index)) {
1973 if (log)
1974 log->Printf(
1975 "GDBRemoteCommunicationServerLLGS::%s() iterated thread %" PRIu32
1976 "(%s, tid=0x%" PRIx64 ")",
1977 __FUNCTION__, thread_index, thread_sp ? "is not null" : "null",
1978 thread_sp ? thread_sp->GetID() : LLDB_INVALID_THREAD_ID);
1979 if (thread_index > 0)
1980 response.PutChar(',');
1981 response.Printf("%" PRIx64, thread_sp->GetID());
1982 }
1983
1984 if (log)
1985 log->Printf(
1986 "GDBRemoteCommunicationServerLLGS::%s() finished thread iteration",
1987 __FUNCTION__);
1988
1989 return SendPacketNoLock(response.GetString());
1990}
1991
1992GDBRemoteCommunication::PacketResult
1993GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
1994 StringExtractorGDBRemote &packet) {
1995 // FIXME for now we return the full thread list in the initial packet and
1996 // always do nothing here.
1997 return SendPacketNoLock("l");
1998}
1999
2000GDBRemoteCommunication::PacketResult
2001GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
2002 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2003
2004 // Parse out the register number from the request.
2005 packet.SetFilePos(strlen("p"));
2006 const uint32_t reg_index =
2007 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2008 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2009 if (log)
2010 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2011 "parse register number from request \"%s\"",
2012 __FUNCTION__, packet.GetStringRef().c_str());
2013 return SendErrorResponse(0x15);
2014 }
2015
2016 // Get the thread to use.
2017 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2018 if (!thread_sp) {
2019 if (log)
2020 log->Printf(
2021 "GDBRemoteCommunicationServerLLGS::%s failed, no thread available",
2022 __FUNCTION__);
2023 return SendErrorResponse(0x15);
2024 }
2025
2026 // Get the thread's register context.
2027 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2028 if (!reg_context_sp) {
2029 if (log)
2030 log->Printf(
2031 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2032 " failed, no register context available for the thread",
2033 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2034 return SendErrorResponse(0x15);
2035 }
2036
2037 // Return the end of registers response if we've iterated one past the end of
2038 // the register set.
2039 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2040 if (log)
2041 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2042 "register %" PRIu32 " beyond register count %" PRIu32,
2043 __FUNCTION__, reg_index,
2044 reg_context_sp->GetUserRegisterCount());
2045 return SendErrorResponse(0x15);
2046 }
2047
2048 const RegisterInfo *reg_info =
2049 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2050 if (!reg_info) {
2051 if (log)
2052 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2053 "register %" PRIu32 " returned NULL",
2054 __FUNCTION__, reg_index);
2055 return SendErrorResponse(0x15);
2056 }
2057
2058 // Build the reginfos response.
2059 StreamGDBRemote response;
2060
2061 // Retrieve the value
2062 RegisterValue reg_value;
Zachary Turner97206d52017-05-12 04:51:55 +00002063 Status error = reg_context_sp->ReadRegister(reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002064 if (error.Fail()) {
2065 if (log)
2066 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, read of "
2067 "requested register %" PRIu32 " (%s) failed: %s",
2068 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2069 return SendErrorResponse(0x15);
2070 }
2071
2072 const uint8_t *const data =
2073 reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
2074 if (!data) {
2075 if (log)
2076 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to get data "
2077 "bytes from requested register %" PRIu32,
2078 __FUNCTION__, reg_index);
2079 return SendErrorResponse(0x15);
2080 }
2081
2082 // FIXME flip as needed to get data in big/little endian format for this host.
2083 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2084 response.PutHex8(data[i]);
2085
2086 return SendPacketNoLock(response.GetString());
2087}
2088
2089GDBRemoteCommunication::PacketResult
2090GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2091 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2092
2093 // Ensure there is more content.
2094 if (packet.GetBytesLeft() < 1)
2095 return SendIllFormedResponse(packet, "Empty P packet");
2096
2097 // Parse out the register number from the request.
2098 packet.SetFilePos(strlen("P"));
2099 const uint32_t reg_index =
2100 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2101 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2102 if (log)
2103 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
2104 "parse register number from request \"%s\"",
2105 __FUNCTION__, packet.GetStringRef().c_str());
2106 return SendErrorResponse(0x29);
2107 }
2108
2109 // Note debugserver would send an E30 here.
2110 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2111 return SendIllFormedResponse(
2112 packet, "P packet missing '=' char after register number");
2113
2114 // Get process architecture.
2115 ArchSpec process_arch;
2116 if (!m_debugged_process_sp ||
2117 !m_debugged_process_sp->GetArchitecture(process_arch)) {
2118 if (log)
2119 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to retrieve "
2120 "inferior architecture",
2121 __FUNCTION__);
2122 return SendErrorResponse(0x49);
2123 }
2124
2125 // Parse out the value.
2126 uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
2127 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2128
2129 // Get the thread to use.
2130 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2131 if (!thread_sp) {
2132 if (log)
2133 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2134 "available (thread index 0)",
2135 __FUNCTION__);
2136 return SendErrorResponse(0x28);
2137 }
2138
2139 // Get the thread's register context.
2140 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2141 if (!reg_context_sp) {
2142 if (log)
2143 log->Printf(
2144 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2145 " failed, no register context available for the thread",
2146 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2147 return SendErrorResponse(0x15);
2148 }
2149
2150 const RegisterInfo *reg_info =
2151 reg_context_sp->GetRegisterInfoAtIndex(reg_index);
2152 if (!reg_info) {
2153 if (log)
2154 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2155 "register %" PRIu32 " returned NULL",
2156 __FUNCTION__, reg_index);
2157 return SendErrorResponse(0x48);
2158 }
2159
2160 // Return the end of registers response if we've iterated one past the end of
2161 // the register set.
2162 if (reg_index >= reg_context_sp->GetUserRegisterCount()) {
2163 if (log)
2164 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, requested "
2165 "register %" PRIu32 " beyond register count %" PRIu32,
2166 __FUNCTION__, reg_index,
2167 reg_context_sp->GetUserRegisterCount());
2168 return SendErrorResponse(0x47);
2169 }
2170
2171 // The dwarf expression are evaluate on host site
2172 // which may cause register size to change
2173 // Hence the reg_size may not be same as reg_info->bytes_size
2174 if ((reg_size != reg_info->byte_size) &&
2175 !(reg_info->dynamic_size_dwarf_expr_bytes)) {
2176 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2177 }
2178
2179 // Build the reginfos response.
2180 StreamGDBRemote response;
2181
2182 RegisterValue reg_value(reg_bytes, reg_size, process_arch.GetByteOrder());
Zachary Turner97206d52017-05-12 04:51:55 +00002183 Status error = reg_context_sp->WriteRegister(reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002184 if (error.Fail()) {
2185 if (log)
2186 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, write of "
2187 "requested register %" PRIu32 " (%s) failed: %s",
2188 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2189 return SendErrorResponse(0x32);
2190 }
2191
2192 return SendOKResponse();
2193}
2194
2195GDBRemoteCommunication::PacketResult
2196GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2197 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2198
2199 // Fail if we don't have a current process.
2200 if (!m_debugged_process_sp ||
2201 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2202 if (log)
2203 log->Printf(
2204 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2205 __FUNCTION__);
2206 return SendErrorResponse(0x15);
2207 }
2208
2209 // Parse out which variant of $H is requested.
2210 packet.SetFilePos(strlen("H"));
2211 if (packet.GetBytesLeft() < 1) {
2212 if (log)
2213 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, H command "
2214 "missing {g,c} variant",
2215 __FUNCTION__);
2216 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2217 }
2218
2219 const char h_variant = packet.GetChar();
2220 switch (h_variant) {
2221 case 'g':
2222 break;
2223
2224 case 'c':
2225 break;
2226
2227 default:
2228 if (log)
2229 log->Printf(
2230 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2231 __FUNCTION__, h_variant);
2232 return SendIllFormedResponse(packet,
2233 "H variant unsupported, should be c or g");
2234 }
2235
2236 // Parse out the thread number.
2237 // FIXME return a parse success/fail value. All values are valid here.
2238 const lldb::tid_t tid =
2239 packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
2240
2241 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2242 // (any thread).
2243 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2244 NativeThreadProtocolSP thread_sp(m_debugged_process_sp->GetThreadByID(tid));
2245 if (!thread_sp) {
2246 if (log)
2247 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2248 " not found",
2249 __FUNCTION__, tid);
2250 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002251 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002252 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002253
Kate Stoneb9c1b512016-09-06 20:57:50 +00002254 // Now switch the given thread type.
2255 switch (h_variant) {
2256 case 'g':
2257 SetCurrentThreadID(tid);
2258 break;
2259
2260 case 'c':
2261 SetContinueThreadID(tid);
2262 break;
2263
2264 default:
2265 assert(false && "unsupported $H variant - shouldn't get here");
2266 return SendIllFormedResponse(packet,
2267 "H variant unsupported, should be c or g");
2268 }
2269
2270 return SendOKResponse();
2271}
2272
2273GDBRemoteCommunication::PacketResult
2274GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2275 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
2276
2277 // Fail if we don't have a current process.
2278 if (!m_debugged_process_sp ||
2279 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2280 if (log)
2281 log->Printf(
2282 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2283 __FUNCTION__);
2284 return SendErrorResponse(0x15);
2285 }
2286
2287 packet.SetFilePos(::strlen("I"));
2288 uint8_t tmp[4096];
2289 for (;;) {
2290 size_t read = packet.GetHexBytesAvail(tmp);
2291 if (read == 0) {
2292 break;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002293 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294 // write directly to stdin *this might block if stdin buffer is full*
2295 // TODO: enqueue this block in circular buffer and send window size to
2296 // remote host
2297 ConnectionStatus status;
Zachary Turner97206d52017-05-12 04:51:55 +00002298 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002299 m_stdio_communication.Write(tmp, read, status, &error);
2300 if (error.Fail()) {
2301 return SendErrorResponse(0x15);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002302 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002303 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002304
Kate Stoneb9c1b512016-09-06 20:57:50 +00002305 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002306}
2307
2308GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002309GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2310 StringExtractorGDBRemote &packet) {
2311 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2312
2313 // Fail if we don't have a current process.
2314 if (!m_debugged_process_sp ||
2315 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002316 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002317 log->Printf(
2318 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2319 __FUNCTION__);
2320 return SendErrorResponse(0x15);
2321 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002322
Kate Stoneb9c1b512016-09-06 20:57:50 +00002323 // Interrupt the process.
Zachary Turner97206d52017-05-12 04:51:55 +00002324 Status error = m_debugged_process_sp->Interrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002325 if (error.Fail()) {
2326 if (log) {
2327 log->Printf(
2328 "GDBRemoteCommunicationServerLLGS::%s failed for process %" PRIu64
2329 ": %s",
2330 __FUNCTION__, m_debugged_process_sp->GetID(), error.AsCString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002331 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002332 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2333 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002334
Kate Stoneb9c1b512016-09-06 20:57:50 +00002335 if (log)
2336 log->Printf("GDBRemoteCommunicationServerLLGS::%s stopped process %" PRIu64,
2337 __FUNCTION__, m_debugged_process_sp->GetID());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002338
Kate Stoneb9c1b512016-09-06 20:57:50 +00002339 // No response required from stop all.
2340 return PacketResult::Success;
2341}
Tamas Berghammere13c2732015-02-11 10:29:30 +00002342
Kate Stoneb9c1b512016-09-06 20:57:50 +00002343GDBRemoteCommunication::PacketResult
2344GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2345 StringExtractorGDBRemote &packet) {
2346 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002347
Kate Stoneb9c1b512016-09-06 20:57:50 +00002348 if (!m_debugged_process_sp ||
2349 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002350 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002351 log->Printf(
2352 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2353 __FUNCTION__);
2354 return SendErrorResponse(0x15);
2355 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002356
Kate Stoneb9c1b512016-09-06 20:57:50 +00002357 // Parse out the memory address.
2358 packet.SetFilePos(strlen("m"));
2359 if (packet.GetBytesLeft() < 1)
2360 return SendIllFormedResponse(packet, "Too short m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002361
Kate Stoneb9c1b512016-09-06 20:57:50 +00002362 // Read the address. Punting on validation.
2363 // FIXME replace with Hex U64 read with no default value that fails on failed
2364 // read.
2365 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002366
Kate Stoneb9c1b512016-09-06 20:57:50 +00002367 // Validate comma.
2368 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2369 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002370
Kate Stoneb9c1b512016-09-06 20:57:50 +00002371 // Get # bytes to read.
2372 if (packet.GetBytesLeft() < 1)
2373 return SendIllFormedResponse(packet, "Length missing in m packet");
2374
2375 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2376 if (byte_count == 0) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002377 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002378 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2379 "zero-length packet",
2380 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002381 return SendOKResponse();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002382 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002383
Kate Stoneb9c1b512016-09-06 20:57:50 +00002384 // Allocate the response buffer.
2385 std::string buf(byte_count, '\0');
2386 if (buf.empty())
2387 return SendErrorResponse(0x78);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002388
Kate Stoneb9c1b512016-09-06 20:57:50 +00002389 // Retrieve the process memory.
2390 size_t bytes_read = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002391 Status error = m_debugged_process_sp->ReadMemoryWithoutTrap(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002392 read_addr, &buf[0], byte_count, bytes_read);
2393 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00002394 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002395 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2396 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2397 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2398 error.AsCString());
2399 return SendErrorResponse(0x08);
2400 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002401
Kate Stoneb9c1b512016-09-06 20:57:50 +00002402 if (bytes_read == 0) {
2403 if (log)
2404 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2405 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2406 __FUNCTION__, m_debugged_process_sp->GetID(), read_addr,
2407 byte_count);
2408 return SendErrorResponse(0x08);
2409 }
2410
2411 StreamGDBRemote response;
2412 packet.SetFilePos(0);
2413 char kind = packet.GetChar('?');
2414 if (kind == 'x')
2415 response.PutEscapedBytes(buf.data(), byte_count);
2416 else {
2417 assert(kind == 'm');
2418 for (size_t i = 0; i < bytes_read; ++i)
2419 response.PutHex8(buf[i]);
2420 }
2421
2422 return SendPacketNoLock(response.GetString());
2423}
2424
2425GDBRemoteCommunication::PacketResult
2426GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2427 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2428
2429 if (!m_debugged_process_sp ||
2430 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2431 if (log)
2432 log->Printf(
2433 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2434 __FUNCTION__);
2435 return SendErrorResponse(0x15);
2436 }
2437
2438 // Parse out the memory address.
2439 packet.SetFilePos(strlen("M"));
2440 if (packet.GetBytesLeft() < 1)
2441 return SendIllFormedResponse(packet, "Too short M packet");
2442
2443 // Read the address. Punting on validation.
2444 // FIXME replace with Hex U64 read with no default value that fails on failed
2445 // read.
2446 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2447
2448 // Validate comma.
2449 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2450 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2451
2452 // Get # bytes to read.
2453 if (packet.GetBytesLeft() < 1)
2454 return SendIllFormedResponse(packet, "Length missing in M packet");
2455
2456 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2457 if (byte_count == 0) {
2458 if (log)
2459 log->Printf("GDBRemoteCommunicationServerLLGS::%s nothing to write: "
2460 "zero-length packet",
2461 __FUNCTION__);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002462 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002463 }
2464
2465 // Validate colon.
2466 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2467 return SendIllFormedResponse(
2468 packet, "Comma sep missing in M packet after byte length");
2469
2470 // Allocate the conversion buffer.
2471 std::vector<uint8_t> buf(byte_count, 0);
2472 if (buf.empty())
2473 return SendErrorResponse(0x78);
2474
2475 // Convert the hex memory write contents to bytes.
2476 StreamGDBRemote response;
2477 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2478 if (convert_count != byte_count) {
2479 if (log)
2480 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2481 " mem 0x%" PRIx64 ": asked to write %" PRIu64
2482 " bytes, but only found %" PRIu64 " to convert.",
2483 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2484 byte_count, convert_count);
2485 return SendIllFormedResponse(packet, "M content byte length specified did "
2486 "not match hex-encoded content "
2487 "length");
2488 }
2489
2490 // Write the process memory.
2491 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002492 Status error = m_debugged_process_sp->WriteMemory(write_addr, &buf[0],
2493 byte_count, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002494 if (error.Fail()) {
2495 if (log)
2496 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2497 " mem 0x%" PRIx64 ": failed to write. Error: %s",
2498 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2499 error.AsCString());
2500 return SendErrorResponse(0x09);
2501 }
2502
2503 if (bytes_written == 0) {
2504 if (log)
2505 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2506 " mem 0x%" PRIx64 ": wrote 0 of %" PRIu64 " requested bytes",
2507 __FUNCTION__, m_debugged_process_sp->GetID(), write_addr,
2508 byte_count);
2509 return SendErrorResponse(0x09);
2510 }
2511
2512 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002513}
2514
2515GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002516GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2517 StringExtractorGDBRemote &packet) {
2518 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002519
Kate Stoneb9c1b512016-09-06 20:57:50 +00002520 // Currently only the NativeProcessProtocol knows if it can handle a
2521 // qMemoryRegionInfoSupported
2522 // request, but we're not guaranteed to be attached to a process. For now
2523 // we'll assume the
2524 // client only asks this when a process is being debugged.
Tamas Berghammere13c2732015-02-11 10:29:30 +00002525
Kate Stoneb9c1b512016-09-06 20:57:50 +00002526 // Ensure we have a process running; otherwise, we can't figure this out
2527 // since we won't have a NativeProcessProtocol.
2528 if (!m_debugged_process_sp ||
2529 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2530 if (log)
2531 log->Printf(
2532 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2533 __FUNCTION__);
2534 return SendErrorResponse(0x15);
2535 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002536
Kate Stoneb9c1b512016-09-06 20:57:50 +00002537 // Test if we can get any region back when asking for the region around NULL.
2538 MemoryRegionInfo region_info;
Zachary Turner97206d52017-05-12 04:51:55 +00002539 const Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00002540 m_debugged_process_sp->GetMemoryRegionInfo(0, region_info);
2541 if (error.Fail()) {
2542 // We don't support memory region info collection for this
2543 // NativeProcessProtocol.
2544 return SendUnimplementedResponse("");
2545 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002546
Kate Stoneb9c1b512016-09-06 20:57:50 +00002547 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00002548}
2549
2550GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002551GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
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 // Ensure we have a process.
2556 if (!m_debugged_process_sp ||
2557 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2558 if (log)
2559 log->Printf(
2560 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2561 __FUNCTION__);
2562 return SendErrorResponse(0x15);
2563 }
2564
2565 // Parse out the memory address.
2566 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2567 if (packet.GetBytesLeft() < 1)
2568 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2569
2570 // Read the address. Punting on validation.
2571 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2572
2573 StreamGDBRemote response;
2574
2575 // Get the memory region info for the target address.
2576 MemoryRegionInfo region_info;
Zachary Turner97206d52017-05-12 04:51:55 +00002577 const Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00002578 m_debugged_process_sp->GetMemoryRegionInfo(read_addr, region_info);
2579 if (error.Fail()) {
2580 // Return the error message.
2581
2582 response.PutCString("error:");
2583 response.PutCStringAsRawHex8(error.AsCString());
2584 response.PutChar(';');
2585 } else {
2586 // Range start and size.
2587 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2588 region_info.GetRange().GetRangeBase(),
2589 region_info.GetRange().GetByteSize());
2590
2591 // Permissions.
2592 if (region_info.GetReadable() || region_info.GetWritable() ||
2593 region_info.GetExecutable()) {
2594 // Write permissions info.
2595 response.PutCString("permissions:");
2596
2597 if (region_info.GetReadable())
2598 response.PutChar('r');
2599 if (region_info.GetWritable())
2600 response.PutChar('w');
2601 if (region_info.GetExecutable())
2602 response.PutChar('x');
2603
2604 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002605 }
2606
Kate Stoneb9c1b512016-09-06 20:57:50 +00002607 // Name
2608 ConstString name = region_info.GetName();
2609 if (name) {
2610 response.PutCString("name:");
2611 response.PutCStringAsRawHex8(name.AsCString());
2612 response.PutChar(';');
Tamas Berghammere13c2732015-02-11 10:29:30 +00002613 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002614 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002615
Kate Stoneb9c1b512016-09-06 20:57:50 +00002616 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002617}
2618
2619GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002620GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2621 // Ensure we have a process.
2622 if (!m_debugged_process_sp ||
2623 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2624 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2625 if (log)
2626 log->Printf(
2627 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2628 __FUNCTION__);
2629 return SendErrorResponse(0x15);
2630 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002631
Kate Stoneb9c1b512016-09-06 20:57:50 +00002632 // Parse out software or hardware breakpoint or watchpoint requested.
2633 packet.SetFilePos(strlen("Z"));
2634 if (packet.GetBytesLeft() < 1)
2635 return SendIllFormedResponse(
2636 packet, "Too short Z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002637
Kate Stoneb9c1b512016-09-06 20:57:50 +00002638 bool want_breakpoint = true;
2639 bool want_hardware = false;
2640 uint32_t watch_flags = 0;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002641
Kate Stoneb9c1b512016-09-06 20:57:50 +00002642 const GDBStoppointType stoppoint_type =
2643 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2644 switch (stoppoint_type) {
2645 case eBreakpointSoftware:
2646 want_hardware = false;
2647 want_breakpoint = true;
2648 break;
2649 case eBreakpointHardware:
2650 want_hardware = true;
2651 want_breakpoint = true;
2652 break;
2653 case eWatchpointWrite:
2654 watch_flags = 1;
2655 want_hardware = true;
2656 want_breakpoint = false;
2657 break;
2658 case eWatchpointRead:
2659 watch_flags = 2;
2660 want_hardware = true;
2661 want_breakpoint = false;
2662 break;
2663 case eWatchpointReadWrite:
2664 watch_flags = 3;
2665 want_hardware = true;
2666 want_breakpoint = false;
2667 break;
2668 case eStoppointInvalid:
2669 return SendIllFormedResponse(
2670 packet, "Z packet had invalid software/hardware specifier");
2671 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002672
Kate Stoneb9c1b512016-09-06 20:57:50 +00002673 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2674 return SendIllFormedResponse(
2675 packet, "Malformed Z packet, expecting comma after stoppoint type");
2676
2677 // Parse out the stoppoint address.
2678 if (packet.GetBytesLeft() < 1)
2679 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2680 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2681
2682 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2683 return SendIllFormedResponse(
2684 packet, "Malformed Z packet, expecting comma after address");
2685
2686 // Parse out the stoppoint size (i.e. size hint for opcode size).
2687 const uint32_t size =
2688 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2689 if (size == std::numeric_limits<uint32_t>::max())
2690 return SendIllFormedResponse(
2691 packet, "Malformed Z packet, failed to parse size argument");
2692
2693 if (want_breakpoint) {
2694 // Try to set the breakpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002695 const Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00002696 m_debugged_process_sp->SetBreakpoint(addr, size, want_hardware);
2697 if (error.Success())
2698 return SendOKResponse();
2699 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2700 if (log)
2701 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2702 " failed to set breakpoint: %s",
2703 __FUNCTION__, m_debugged_process_sp->GetID(),
2704 error.AsCString());
2705 return SendErrorResponse(0x09);
2706 } else {
2707 // Try to set the watchpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002708 const Status error = m_debugged_process_sp->SetWatchpoint(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002709 addr, size, watch_flags, want_hardware);
2710 if (error.Success())
2711 return SendOKResponse();
2712 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2713 if (log)
2714 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2715 " failed to set watchpoint: %s",
2716 __FUNCTION__, m_debugged_process_sp->GetID(),
2717 error.AsCString());
2718 return SendErrorResponse(0x09);
2719 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002720}
2721
2722GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002723GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2724 // Ensure we have a process.
2725 if (!m_debugged_process_sp ||
2726 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2727 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
2728 if (log)
2729 log->Printf(
2730 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2731 __FUNCTION__);
2732 return SendErrorResponse(0x15);
2733 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002734
Kate Stoneb9c1b512016-09-06 20:57:50 +00002735 // Parse out software or hardware breakpoint or watchpoint requested.
2736 packet.SetFilePos(strlen("z"));
2737 if (packet.GetBytesLeft() < 1)
2738 return SendIllFormedResponse(
2739 packet, "Too short z packet, missing software/hardware specifier");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002740
Kate Stoneb9c1b512016-09-06 20:57:50 +00002741 bool want_breakpoint = true;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002742 bool want_hardware = false;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002743
Kate Stoneb9c1b512016-09-06 20:57:50 +00002744 const GDBStoppointType stoppoint_type =
2745 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2746 switch (stoppoint_type) {
2747 case eBreakpointHardware:
2748 want_breakpoint = true;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002749 want_hardware = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002750 break;
2751 case eBreakpointSoftware:
2752 want_breakpoint = true;
2753 break;
2754 case eWatchpointWrite:
2755 want_breakpoint = false;
2756 break;
2757 case eWatchpointRead:
2758 want_breakpoint = false;
2759 break;
2760 case eWatchpointReadWrite:
2761 want_breakpoint = false;
2762 break;
2763 default:
2764 return SendIllFormedResponse(
2765 packet, "z packet had invalid software/hardware specifier");
2766 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002767
Kate Stoneb9c1b512016-09-06 20:57:50 +00002768 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2769 return SendIllFormedResponse(
2770 packet, "Malformed z packet, expecting comma after stoppoint type");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002771
Kate Stoneb9c1b512016-09-06 20:57:50 +00002772 // Parse out the stoppoint address.
2773 if (packet.GetBytesLeft() < 1)
2774 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2775 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002776
Kate Stoneb9c1b512016-09-06 20:57:50 +00002777 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2778 return SendIllFormedResponse(
2779 packet, "Malformed z packet, expecting comma after address");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002780
Kate Stoneb9c1b512016-09-06 20:57:50 +00002781 /*
2782 // Parse out the stoppoint size (i.e. size hint for opcode size).
2783 const uint32_t size = packet.GetHexMaxU32 (false,
2784 std::numeric_limits<uint32_t>::max ());
2785 if (size == std::numeric_limits<uint32_t>::max ())
2786 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2787 size argument");
2788 */
Tamas Berghammere13c2732015-02-11 10:29:30 +00002789
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 if (want_breakpoint) {
2791 // Try to clear the breakpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002792 const Status error =
Omair Javaidd5ffbad2017-02-24 13:27:31 +00002793 m_debugged_process_sp->RemoveBreakpoint(addr, want_hardware);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002794 if (error.Success())
2795 return SendOKResponse();
2796 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2797 if (log)
2798 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2799 " failed to remove breakpoint: %s",
2800 __FUNCTION__, m_debugged_process_sp->GetID(),
2801 error.AsCString());
2802 return SendErrorResponse(0x09);
2803 } else {
2804 // Try to clear the watchpoint.
Zachary Turner97206d52017-05-12 04:51:55 +00002805 const Status error = m_debugged_process_sp->RemoveWatchpoint(addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002806 if (error.Success())
2807 return SendOKResponse();
2808 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
2809 if (log)
2810 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2811 " failed to remove watchpoint: %s",
2812 __FUNCTION__, m_debugged_process_sp->GetID(),
2813 error.AsCString());
2814 return SendErrorResponse(0x09);
2815 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002816}
2817
2818GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002819GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
2820 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002821
Kate Stoneb9c1b512016-09-06 20:57:50 +00002822 // Ensure we have a process.
2823 if (!m_debugged_process_sp ||
2824 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2825 if (log)
2826 log->Printf(
2827 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2828 __FUNCTION__);
2829 return SendErrorResponse(0x32);
2830 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002831
Kate Stoneb9c1b512016-09-06 20:57:50 +00002832 // We first try to use a continue thread id. If any one or any all set, use
2833 // the current thread.
2834 // Bail out if we don't have a thread id.
2835 lldb::tid_t tid = GetContinueThreadID();
2836 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
2837 tid = GetCurrentThreadID();
2838 if (tid == LLDB_INVALID_THREAD_ID)
2839 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002840
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 // Double check that we have such a thread.
2842 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
2843 NativeThreadProtocolSP thread_sp = m_debugged_process_sp->GetThreadByID(tid);
2844 if (!thread_sp || thread_sp->GetID() != tid)
2845 return SendErrorResponse(0x33);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002846
Kate Stoneb9c1b512016-09-06 20:57:50 +00002847 // Create the step action for the given thread.
2848 ResumeAction action = {tid, eStateStepping, 0};
Tamas Berghammere13c2732015-02-11 10:29:30 +00002849
Kate Stoneb9c1b512016-09-06 20:57:50 +00002850 // Setup the actions list.
2851 ResumeActionList actions;
2852 actions.Append(action);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002853
Kate Stoneb9c1b512016-09-06 20:57:50 +00002854 // All other threads stop while we're single stepping a thread.
2855 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
Zachary Turner97206d52017-05-12 04:51:55 +00002856 Status error = m_debugged_process_sp->Resume(actions);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002857 if (error.Fail()) {
2858 if (log)
2859 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2860 " tid %" PRIu64 " Resume() failed with error: %s",
2861 __FUNCTION__, m_debugged_process_sp->GetID(), tid,
2862 error.AsCString());
2863 return SendErrorResponse(0x49);
2864 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002865
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866 // No response here - the stop or exit will come from the resulting action.
2867 return PacketResult::Success;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002868}
2869
2870GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002871GDBRemoteCommunicationServerLLGS::Handle_qXfer_auxv_read(
2872 StringExtractorGDBRemote &packet) {
2873// *BSD impls should be able to do this too.
Kamil Rytarowskic93408a2017-03-21 17:27:59 +00002874#if defined(__linux__) || defined(__NetBSD__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002875 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002876
Kate Stoneb9c1b512016-09-06 20:57:50 +00002877 // Parse out the offset.
2878 packet.SetFilePos(strlen("qXfer:auxv:read::"));
2879 if (packet.GetBytesLeft() < 1)
2880 return SendIllFormedResponse(packet,
2881 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002882
Kate Stoneb9c1b512016-09-06 20:57:50 +00002883 const uint64_t auxv_offset =
2884 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2885 if (auxv_offset == std::numeric_limits<uint64_t>::max())
2886 return SendIllFormedResponse(packet,
2887 "qXfer:auxv:read:: packet missing offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002888
Kate Stoneb9c1b512016-09-06 20:57:50 +00002889 // Parse out comma.
2890 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ',')
2891 return SendIllFormedResponse(
2892 packet, "qXfer:auxv:read:: packet missing comma after offset");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002893
Kate Stoneb9c1b512016-09-06 20:57:50 +00002894 // Parse out the length.
2895 const uint64_t auxv_length =
2896 packet.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
2897 if (auxv_length == std::numeric_limits<uint64_t>::max())
2898 return SendIllFormedResponse(packet,
2899 "qXfer:auxv:read:: packet missing length");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002900
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901 // Grab the auxv data if we need it.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002902 if (!m_active_auxv_buffer_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002903 // Make sure we have a valid process.
2904 if (!m_debugged_process_sp ||
2905 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
2906 if (log)
2907 log->Printf(
2908 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2909 __FUNCTION__);
2910 return SendErrorResponse(0x10);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002911 }
2912
Kate Stoneb9c1b512016-09-06 20:57:50 +00002913 // Grab the auxv data.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002914 auto buffer_or_error = m_debugged_process_sp->GetAuxvData();
2915 if (!buffer_or_error) {
2916 std::error_code ec = buffer_or_error.getError();
2917 LLDB_LOG(log, "no auxv data retrieved: {0}", ec.message());
2918 return SendErrorResponse(ec.value());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002919 }
Pavel Labathb7f0f452017-03-17 11:08:40 +00002920 m_active_auxv_buffer_up = std::move(*buffer_or_error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002921 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002922
Kate Stoneb9c1b512016-09-06 20:57:50 +00002923 StreamGDBRemote response;
2924 bool done_with_buffer = false;
Tamas Berghammere13c2732015-02-11 10:29:30 +00002925
Pavel Labathb7f0f452017-03-17 11:08:40 +00002926 llvm::StringRef buffer = m_active_auxv_buffer_up->getBuffer();
2927 if (auxv_offset >= buffer.size()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002928 // We have nothing left to send. Mark the buffer as complete.
2929 response.PutChar('l');
2930 done_with_buffer = true;
2931 } else {
2932 // Figure out how many bytes are available starting at the given offset.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002933 buffer = buffer.drop_front(auxv_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002934
2935 // Mark the response type according to whether we're reading the remainder
2936 // of the auxv data.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002937 if (auxv_length >= buffer.size()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002938 // There will be nothing left to read after this
2939 response.PutChar('l');
2940 done_with_buffer = true;
2941 } else {
2942 // There will still be bytes to read after this request.
2943 response.PutChar('m');
Pavel Labathb7f0f452017-03-17 11:08:40 +00002944 buffer = buffer.take_front(auxv_length);
Tamas Berghammere13c2732015-02-11 10:29:30 +00002945 }
2946
Kate Stoneb9c1b512016-09-06 20:57:50 +00002947 // Now write the data in encoded binary form.
Pavel Labathb7f0f452017-03-17 11:08:40 +00002948 response.PutEscapedBytes(buffer.data(), buffer.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002949 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002950
Kate Stoneb9c1b512016-09-06 20:57:50 +00002951 if (done_with_buffer)
Pavel Labathb7f0f452017-03-17 11:08:40 +00002952 m_active_auxv_buffer_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002953
2954 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00002955#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002956 return SendUnimplementedResponse("not implemented on this platform");
Tamas Berghammere13c2732015-02-11 10:29:30 +00002957#endif
2958}
2959
2960GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00002961GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
2962 StringExtractorGDBRemote &packet) {
2963 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002964
Kate Stoneb9c1b512016-09-06 20:57:50 +00002965 // Move past packet name.
2966 packet.SetFilePos(strlen("QSaveRegisterState"));
Tamas Berghammere13c2732015-02-11 10:29:30 +00002967
Kate Stoneb9c1b512016-09-06 20:57:50 +00002968 // Get the thread to use.
2969 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
2970 if (!thread_sp) {
2971 if (m_thread_suffix_supported)
2972 return SendIllFormedResponse(
2973 packet, "No thread specified in QSaveRegisterState packet");
2974 else
2975 return SendIllFormedResponse(packet,
2976 "No thread was is set with the Hg packet");
2977 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002978
Kate Stoneb9c1b512016-09-06 20:57:50 +00002979 // Grab the register context for the thread.
2980 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
2981 if (!reg_context_sp) {
2982 if (log)
2983 log->Printf(
2984 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
2985 " failed, no register context available for the thread",
2986 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
2987 return SendErrorResponse(0x15);
2988 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00002989
Kate Stoneb9c1b512016-09-06 20:57:50 +00002990 // Save registers to a buffer.
2991 DataBufferSP register_data_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00002992 Status error = reg_context_sp->ReadAllRegisterValues(register_data_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002993 if (error.Fail()) {
2994 if (log)
2995 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2996 " failed to save all register values: %s",
2997 __FUNCTION__, m_debugged_process_sp->GetID(),
2998 error.AsCString());
2999 return SendErrorResponse(0x75);
3000 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003001
Kate Stoneb9c1b512016-09-06 20:57:50 +00003002 // Allocate a new save id.
3003 const uint32_t save_id = GetNextSavedRegistersID();
3004 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3005 "GetNextRegisterSaveID() returned an existing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00003006
Kate Stoneb9c1b512016-09-06 20:57:50 +00003007 // Save the register data buffer under the save id.
3008 {
3009 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3010 m_saved_registers_map[save_id] = register_data_sp;
3011 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003012
Kate Stoneb9c1b512016-09-06 20:57:50 +00003013 // Write the response.
3014 StreamGDBRemote response;
3015 response.Printf("%" PRIu32, save_id);
3016 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00003017}
3018
3019GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003020GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3021 StringExtractorGDBRemote &packet) {
3022 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003023
Kate Stoneb9c1b512016-09-06 20:57:50 +00003024 // Parse out save id.
3025 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3026 if (packet.GetBytesLeft() < 1)
3027 return SendIllFormedResponse(
3028 packet, "QRestoreRegisterState packet missing register save id");
Tamas Berghammere13c2732015-02-11 10:29:30 +00003029
Kate Stoneb9c1b512016-09-06 20:57:50 +00003030 const uint32_t save_id = packet.GetU32(0);
3031 if (save_id == 0) {
3032 if (log)
3033 log->Printf("GDBRemoteCommunicationServerLLGS::%s QRestoreRegisterState "
3034 "packet has malformed save id, expecting decimal uint32_t",
3035 __FUNCTION__);
3036 return SendErrorResponse(0x76);
3037 }
3038
3039 // Get the thread to use.
3040 NativeThreadProtocolSP thread_sp = GetThreadFromSuffix(packet);
3041 if (!thread_sp) {
3042 if (m_thread_suffix_supported)
3043 return SendIllFormedResponse(
3044 packet, "No thread specified in QRestoreRegisterState packet");
3045 else
3046 return SendIllFormedResponse(packet,
3047 "No thread was is set with the Hg packet");
3048 }
3049
3050 // Grab the register context for the thread.
3051 NativeRegisterContextSP reg_context_sp(thread_sp->GetRegisterContext());
3052 if (!reg_context_sp) {
3053 if (log)
3054 log->Printf(
3055 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64 " tid %" PRIu64
3056 " failed, no register context available for the thread",
3057 __FUNCTION__, m_debugged_process_sp->GetID(), thread_sp->GetID());
3058 return SendErrorResponse(0x15);
3059 }
3060
3061 // Retrieve register state buffer, then remove from the list.
3062 DataBufferSP register_data_sp;
3063 {
3064 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3065
3066 // Find the register set buffer for the given save id.
3067 auto it = m_saved_registers_map.find(save_id);
3068 if (it == m_saved_registers_map.end()) {
3069 if (log)
3070 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3071 " does not have a register set save buffer for id %" PRIu32,
3072 __FUNCTION__, m_debugged_process_sp->GetID(), save_id);
3073 return SendErrorResponse(0x77);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003074 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003075 register_data_sp = it->second;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003076
Kate Stoneb9c1b512016-09-06 20:57:50 +00003077 // Remove it from the map.
3078 m_saved_registers_map.erase(it);
3079 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003080
Zachary Turner97206d52017-05-12 04:51:55 +00003081 Status error = reg_context_sp->WriteAllRegisterValues(register_data_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003082 if (error.Fail()) {
3083 if (log)
3084 log->Printf("GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
3085 " failed to restore all register values: %s",
3086 __FUNCTION__, m_debugged_process_sp->GetID(),
3087 error.AsCString());
3088 return SendErrorResponse(0x77);
3089 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003090
Kate Stoneb9c1b512016-09-06 20:57:50 +00003091 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003092}
3093
3094GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003095GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3096 StringExtractorGDBRemote &packet) {
3097 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003098
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099 // Consume the ';' after vAttach.
3100 packet.SetFilePos(strlen("vAttach"));
3101 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3102 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
Tamas Berghammere13c2732015-02-11 10:29:30 +00003103
Kate Stoneb9c1b512016-09-06 20:57:50 +00003104 // Grab the PID to which we will attach (assume hex encoding).
3105 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3106 if (pid == LLDB_INVALID_PROCESS_ID)
3107 return SendIllFormedResponse(packet,
3108 "vAttach failed to parse the process id");
3109
3110 // Attempt to attach.
3111 if (log)
3112 log->Printf("GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3113 "pid %" PRIu64,
3114 __FUNCTION__, pid);
3115
Zachary Turner97206d52017-05-12 04:51:55 +00003116 Status error = AttachToProcess(pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003117
3118 if (error.Fail()) {
3119 if (log)
3120 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3121 "pid %" PRIu64 ": %s\n",
3122 __FUNCTION__, pid, error.AsCString());
3123 return SendErrorResponse(0x01);
3124 }
3125
3126 // Notify we attached by sending a stop packet.
3127 return SendStopReasonForState(m_debugged_process_sp->GetState());
3128}
3129
3130GDBRemoteCommunication::PacketResult
3131GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3132 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
3133
3134 StopSTDIOForwarding();
3135
3136 // Fail if we don't have a current process.
3137 if (!m_debugged_process_sp ||
3138 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)) {
3139 if (log)
3140 log->Printf(
3141 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3142 __FUNCTION__);
3143 return SendErrorResponse(0x15);
3144 }
3145
3146 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3147
3148 // Consume the ';' after D.
3149 packet.SetFilePos(1);
3150 if (packet.GetBytesLeft()) {
3151 if (packet.GetChar() != ';')
3152 return SendIllFormedResponse(packet, "D missing expected ';'");
3153
3154 // Grab the PID from which we will detach (assume hex encoding).
3155 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003156 if (pid == LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003157 return SendIllFormedResponse(packet, "D failed to parse the process id");
3158 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003159
Kate Stoneb9c1b512016-09-06 20:57:50 +00003160 if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_sp->GetID() != pid) {
3161 return SendIllFormedResponse(packet, "Invalid pid");
3162 }
3163
Zachary Turner97206d52017-05-12 04:51:55 +00003164 const Status error = m_debugged_process_sp->Detach();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003165 if (error.Fail()) {
Tamas Berghammere13c2732015-02-11 10:29:30 +00003166 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003167 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to detach from "
3168 "pid %" PRIu64 ": %s\n",
3169 __FUNCTION__, m_debugged_process_sp->GetID(),
3170 error.AsCString());
3171 return SendErrorResponse(0x01);
3172 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003173
Kate Stoneb9c1b512016-09-06 20:57:50 +00003174 return SendOKResponse();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003175}
3176
3177GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003178GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3179 StringExtractorGDBRemote &packet) {
3180 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003181
Kate Stoneb9c1b512016-09-06 20:57:50 +00003182 packet.SetFilePos(strlen("qThreadStopInfo"));
3183 const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
3184 if (tid == LLDB_INVALID_THREAD_ID) {
Pavel Labath4a4bb122015-07-16 14:14:35 +00003185 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003186 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed, could not "
3187 "parse thread id from request \"%s\"",
3188 __FUNCTION__, packet.GetStringRef().c_str());
3189 return SendErrorResponse(0x15);
3190 }
3191 return SendStopReplyPacketForThread(tid);
3192}
3193
3194GDBRemoteCommunication::PacketResult
3195GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3196 StringExtractorGDBRemote &) {
3197 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3198
3199 // Ensure we have a debugged process.
3200 if (!m_debugged_process_sp ||
3201 (m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID))
3202 return SendErrorResponse(50);
3203
3204 if (log)
3205 log->Printf("GDBRemoteCommunicationServerLLGS::%s preparing packet for pid "
3206 "%" PRIu64,
Pavel Labath4a4bb122015-07-16 14:14:35 +00003207 __FUNCTION__, m_debugged_process_sp->GetID());
3208
Kate Stoneb9c1b512016-09-06 20:57:50 +00003209 StreamString response;
3210 const bool threads_with_valid_stop_info_only = false;
3211 JSONArray::SP threads_array_sp = GetJSONThreadsInfo(
3212 *m_debugged_process_sp, threads_with_valid_stop_info_only);
3213 if (!threads_array_sp) {
3214 if (log)
3215 log->Printf("GDBRemoteCommunicationServerLLGS::%s failed to prepare a "
3216 "packet for pid %" PRIu64,
3217 __FUNCTION__, m_debugged_process_sp->GetID());
3218 return SendErrorResponse(52);
3219 }
Pavel Labath4a4bb122015-07-16 14:14:35 +00003220
Kate Stoneb9c1b512016-09-06 20:57:50 +00003221 threads_array_sp->Write(response);
3222 StreamGDBRemote escaped_response;
3223 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3224 return SendPacketNoLock(escaped_response.GetString());
Pavel Labath4a4bb122015-07-16 14:14:35 +00003225}
3226
3227GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003228GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3229 StringExtractorGDBRemote &packet) {
3230 // Fail if we don't have a current process.
3231 if (!m_debugged_process_sp ||
3232 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3233 return SendErrorResponse(68);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003234
Kate Stoneb9c1b512016-09-06 20:57:50 +00003235 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3236 if (packet.GetBytesLeft() == 0)
3237 return SendOKResponse();
3238 if (packet.GetChar() != ':')
3239 return SendErrorResponse(67);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003240
Omair Javaidd5ffbad2017-02-24 13:27:31 +00003241 auto hw_debug_cap = m_debugged_process_sp->GetHardwareDebugSupportInfo();
3242
Kate Stoneb9c1b512016-09-06 20:57:50 +00003243 StreamGDBRemote response;
Omair Javaidd5ffbad2017-02-24 13:27:31 +00003244 if (hw_debug_cap == llvm::None)
3245 response.Printf("num:0;");
3246 else
3247 response.Printf("num:%d;", hw_debug_cap->second);
3248
Kate Stoneb9c1b512016-09-06 20:57:50 +00003249 return SendPacketNoLock(response.GetString());
Tamas Berghammere13c2732015-02-11 10:29:30 +00003250}
3251
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003252GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +00003253GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3254 StringExtractorGDBRemote &packet) {
3255 // Fail if we don't have a current process.
3256 if (!m_debugged_process_sp ||
3257 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
3258 return SendErrorResponse(67);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003259
Kate Stoneb9c1b512016-09-06 20:57:50 +00003260 packet.SetFilePos(strlen("qFileLoadAddress:"));
3261 if (packet.GetBytesLeft() == 0)
3262 return SendErrorResponse(68);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003263
Kate Stoneb9c1b512016-09-06 20:57:50 +00003264 std::string file_name;
3265 packet.GetHexByteString(file_name);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003266
Kate Stoneb9c1b512016-09-06 20:57:50 +00003267 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00003268 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00003269 m_debugged_process_sp->GetFileLoadAddress(file_name, file_load_address);
3270 if (error.Fail())
3271 return SendErrorResponse(69);
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003272
Kate Stoneb9c1b512016-09-06 20:57:50 +00003273 if (file_load_address == LLDB_INVALID_ADDRESS)
3274 return SendErrorResponse(1); // File not loaded
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003275
Kate Stoneb9c1b512016-09-06 20:57:50 +00003276 StreamGDBRemote response;
3277 response.PutHex64(file_load_address);
3278 return SendPacketNoLock(response.GetString());
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003279}
3280
Pavel Labath4a705e72017-02-24 09:29:14 +00003281GDBRemoteCommunication::PacketResult
3282GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3283 StringExtractorGDBRemote &packet) {
3284 std::vector<int> signals;
3285 packet.SetFilePos(strlen("QPassSignals:"));
3286
3287 // Read sequence of hex signal numbers divided by a semicolon and
3288 // optionally spaces.
3289 while (packet.GetBytesLeft() > 0) {
3290 int signal = packet.GetS32(-1, 16);
3291 if (signal < 0)
3292 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3293 signals.push_back(signal);
3294
3295 packet.SkipSpaces();
3296 char separator = packet.GetChar();
3297 if (separator == '\0')
3298 break; // End of string
3299 if (separator != ';')
3300 return SendIllFormedResponse(packet, "Invalid separator,"
3301 " expected semicolon.");
3302 }
3303
3304 // Fail if we don't have a current process.
3305 if (!m_debugged_process_sp)
3306 return SendErrorResponse(68);
3307
Zachary Turner97206d52017-05-12 04:51:55 +00003308 Status error = m_debugged_process_sp->IgnoreSignals(signals);
Pavel Labath4a705e72017-02-24 09:29:14 +00003309 if (error.Fail())
3310 return SendErrorResponse(69);
3311
3312 return SendOKResponse();
3313}
3314
Kate Stoneb9c1b512016-09-06 20:57:50 +00003315void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
3316 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003317
Kate Stoneb9c1b512016-09-06 20:57:50 +00003318 // Tell the stdio connection to shut down.
3319 if (m_stdio_communication.IsConnected()) {
3320 auto connection = m_stdio_communication.GetConnection();
3321 if (connection) {
Zachary Turner97206d52017-05-12 04:51:55 +00003322 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003323 connection->Disconnect(&error);
Tamas Berghammere13c2732015-02-11 10:29:30 +00003324
Kate Stoneb9c1b512016-09-06 20:57:50 +00003325 if (error.Success()) {
3326 if (log)
3327 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3328 "terminal stdio - SUCCESS",
3329 __FUNCTION__);
3330 } else {
3331 if (log)
3332 log->Printf("GDBRemoteCommunicationServerLLGS::%s disconnect process "
3333 "terminal stdio - FAIL: %s",
3334 __FUNCTION__, error.AsCString());
3335 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003336 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003337 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003338}
3339
Kate Stoneb9c1b512016-09-06 20:57:50 +00003340NativeThreadProtocolSP GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
3341 StringExtractorGDBRemote &packet) {
3342 NativeThreadProtocolSP thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003343
Kate Stoneb9c1b512016-09-06 20:57:50 +00003344 // We have no thread if we don't have a process.
3345 if (!m_debugged_process_sp ||
3346 m_debugged_process_sp->GetID() == LLDB_INVALID_PROCESS_ID)
Tamas Berghammere13c2732015-02-11 10:29:30 +00003347 return thread_sp;
Tamas Berghammere13c2732015-02-11 10:29:30 +00003348
Kate Stoneb9c1b512016-09-06 20:57:50 +00003349 // If the client hasn't asked for thread suffix support, there will not be a
3350 // thread suffix.
3351 // Use the current thread in that case.
3352 if (!m_thread_suffix_supported) {
3353 const lldb::tid_t current_tid = GetCurrentThreadID();
3354 if (current_tid == LLDB_INVALID_THREAD_ID)
3355 return thread_sp;
3356 else if (current_tid == 0) {
3357 // Pick a thread.
3358 return m_debugged_process_sp->GetThreadAtIndex(0);
3359 } else
3360 return m_debugged_process_sp->GetThreadByID(current_tid);
3361 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003362
Kate Stoneb9c1b512016-09-06 20:57:50 +00003363 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
Tamas Berghammere13c2732015-02-11 10:29:30 +00003364
Kate Stoneb9c1b512016-09-06 20:57:50 +00003365 // Parse out the ';'.
3366 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
Tamas Berghammere13c2732015-02-11 10:29:30 +00003367 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003368 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3369 "error: expected ';' prior to start of thread suffix: packet "
3370 "contents = '%s'",
3371 __FUNCTION__, packet.GetStringRef().c_str());
3372 return thread_sp;
3373 }
Tamas Berghammere13c2732015-02-11 10:29:30 +00003374
Kate Stoneb9c1b512016-09-06 20:57:50 +00003375 if (!packet.GetBytesLeft())
3376 return thread_sp;
3377
3378 // Parse out thread: portion.
3379 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
3380 if (log)
3381 log->Printf("GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
3382 "error: expected 'thread:' but not found, packet contents = "
3383 "'%s'",
3384 __FUNCTION__, packet.GetStringRef().c_str());
3385 return thread_sp;
3386 }
3387 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
3388 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
3389 if (tid != 0)
3390 return m_debugged_process_sp->GetThreadByID(tid);
3391
3392 return thread_sp;
3393}
3394
3395lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
3396 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
3397 // Use whatever the debug process says is the current thread id
3398 // since the protocol either didn't specify or specified we want
3399 // any/all threads marked as the current thread.
3400 if (!m_debugged_process_sp)
3401 return LLDB_INVALID_THREAD_ID;
3402 return m_debugged_process_sp->GetCurrentThreadID();
3403 }
3404 // Use the specific current thread id set by the gdb remote protocol.
3405 return m_current_tid;
3406}
3407
3408uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
3409 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3410 return m_next_saved_registers_id++;
3411}
3412
3413void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
Pavel Labathb7f0f452017-03-17 11:08:40 +00003414 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003415
Pavel Labathb7f0f452017-03-17 11:08:40 +00003416 LLDB_LOG(log, "clearing auxv buffer: {0}", m_active_auxv_buffer_up.get());
3417 m_active_auxv_buffer_up.reset();
Tamas Berghammere13c2732015-02-11 10:29:30 +00003418}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003419
3420FileSpec
Kate Stoneb9c1b512016-09-06 20:57:50 +00003421GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
3422 const ArchSpec &arch) {
3423 if (m_debugged_process_sp) {
3424 FileSpec file_spec;
3425 if (m_debugged_process_sp
3426 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
3427 .Success()) {
3428 if (file_spec.Exists())
3429 return file_spec;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003430 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003431 }
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003432
Kate Stoneb9c1b512016-09-06 20:57:50 +00003433 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00003434}