1 //===-- GDBRemoteCommunicationServerLLGS.cpp ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include <cerrno>
10
11 #include "lldb/Host/Config.h"
12
13 #include <chrono>
14 #include <cstring>
15 #include <limits>
16 #include <optional>
17 #include <thread>
18
19 #include "GDBRemoteCommunicationServerLLGS.h"
20 #include "lldb/Host/ConnectionFileDescriptor.h"
21 #include "lldb/Host/Debug.h"
22 #include "lldb/Host/File.h"
23 #include "lldb/Host/FileAction.h"
24 #include "lldb/Host/FileSystem.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/HostInfo.h"
27 #include "lldb/Host/PosixApi.h"
28 #include "lldb/Host/Socket.h"
29 #include "lldb/Host/common/NativeProcessProtocol.h"
30 #include "lldb/Host/common/NativeRegisterContext.h"
31 #include "lldb/Host/common/NativeThreadProtocol.h"
32 #include "lldb/Target/MemoryRegionInfo.h"
33 #include "lldb/Utility/Args.h"
34 #include "lldb/Utility/DataBuffer.h"
35 #include "lldb/Utility/Endian.h"
36 #include "lldb/Utility/GDBRemote.h"
37 #include "lldb/Utility/LLDBAssert.h"
38 #include "lldb/Utility/LLDBLog.h"
39 #include "lldb/Utility/Log.h"
40 #include "lldb/Utility/RegisterValue.h"
41 #include "lldb/Utility/State.h"
42 #include "lldb/Utility/StreamString.h"
43 #include "lldb/Utility/UnimplementedError.h"
44 #include "lldb/Utility/UriParser.h"
45 #include "llvm/ADT/Triple.h"
46 #include "llvm/Support/JSON.h"
47 #include "llvm/Support/ScopedPrinter.h"
48
49 #include "ProcessGDBRemote.h"
50 #include "ProcessGDBRemoteLog.h"
51 #include "lldb/Utility/StringExtractorGDBRemote.h"
52
53 using namespace lldb;
54 using namespace lldb_private;
55 using namespace lldb_private::process_gdb_remote;
56 using namespace llvm;
57
58 // GDBRemote Errors
59
60 namespace {
61 enum GDBRemoteServerError {
62 // Set to the first unused error number in literal form below
63 eErrorFirst = 29,
64 eErrorNoProcess = eErrorFirst,
65 eErrorResume,
66 eErrorExitStatus
67 };
68 }
69
70 // GDBRemoteCommunicationServerLLGS constructor
GDBRemoteCommunicationServerLLGS(MainLoop & mainloop,const NativeProcessProtocol::Factory & process_factory)71 GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
72 MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
73 : GDBRemoteCommunicationServerCommon(), m_mainloop(mainloop),
74 m_process_factory(process_factory), m_current_process(nullptr),
75 m_continue_process(nullptr), m_stdio_communication() {
76 RegisterPacketHandlers();
77 }
78
RegisterPacketHandlers()79 void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
80 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
81 &GDBRemoteCommunicationServerLLGS::Handle_C);
82 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
83 &GDBRemoteCommunicationServerLLGS::Handle_c);
84 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
85 &GDBRemoteCommunicationServerLLGS::Handle_D);
86 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
87 &GDBRemoteCommunicationServerLLGS::Handle_H);
88 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
89 &GDBRemoteCommunicationServerLLGS::Handle_I);
90 RegisterMemberFunctionHandler(
91 StringExtractorGDBRemote::eServerPacketType_interrupt,
92 &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
93 RegisterMemberFunctionHandler(
94 StringExtractorGDBRemote::eServerPacketType_m,
95 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
96 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
97 &GDBRemoteCommunicationServerLLGS::Handle_M);
98 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__M,
99 &GDBRemoteCommunicationServerLLGS::Handle__M);
100 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__m,
101 &GDBRemoteCommunicationServerLLGS::Handle__m);
102 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
103 &GDBRemoteCommunicationServerLLGS::Handle_p);
104 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
105 &GDBRemoteCommunicationServerLLGS::Handle_P);
106 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
107 &GDBRemoteCommunicationServerLLGS::Handle_qC);
108 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_T,
109 &GDBRemoteCommunicationServerLLGS::Handle_T);
110 RegisterMemberFunctionHandler(
111 StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
112 &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
113 RegisterMemberFunctionHandler(
114 StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
115 &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
116 RegisterMemberFunctionHandler(
117 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
118 &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
119 RegisterMemberFunctionHandler(
120 StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported,
121 &GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported);
122 RegisterMemberFunctionHandler(
123 StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply,
124 &GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply);
125 RegisterMemberFunctionHandler(
126 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
127 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
128 RegisterMemberFunctionHandler(
129 StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
130 &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
131 RegisterMemberFunctionHandler(
132 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
133 &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
134 RegisterMemberFunctionHandler(
135 StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
136 &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
137 RegisterMemberFunctionHandler(
138 StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
139 &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
140 RegisterMemberFunctionHandler(
141 StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
142 &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
143 RegisterMemberFunctionHandler(
144 StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
145 &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
146 RegisterMemberFunctionHandler(
147 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
148 &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
149 RegisterMemberFunctionHandler(
150 StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
151 &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
152 RegisterMemberFunctionHandler(
153 StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
154 &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
155 RegisterMemberFunctionHandler(
156 StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
157 &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
158 RegisterMemberFunctionHandler(
159 StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
160 &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
161 RegisterMemberFunctionHandler(
162 StringExtractorGDBRemote::eServerPacketType_qXfer,
163 &GDBRemoteCommunicationServerLLGS::Handle_qXfer);
164 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
165 &GDBRemoteCommunicationServerLLGS::Handle_s);
166 RegisterMemberFunctionHandler(
167 StringExtractorGDBRemote::eServerPacketType_stop_reason,
168 &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
169 RegisterMemberFunctionHandler(
170 StringExtractorGDBRemote::eServerPacketType_vAttach,
171 &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
172 RegisterMemberFunctionHandler(
173 StringExtractorGDBRemote::eServerPacketType_vAttachWait,
174 &GDBRemoteCommunicationServerLLGS::Handle_vAttachWait);
175 RegisterMemberFunctionHandler(
176 StringExtractorGDBRemote::eServerPacketType_qVAttachOrWaitSupported,
177 &GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported);
178 RegisterMemberFunctionHandler(
179 StringExtractorGDBRemote::eServerPacketType_vAttachOrWait,
180 &GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait);
181 RegisterMemberFunctionHandler(
182 StringExtractorGDBRemote::eServerPacketType_vCont,
183 &GDBRemoteCommunicationServerLLGS::Handle_vCont);
184 RegisterMemberFunctionHandler(
185 StringExtractorGDBRemote::eServerPacketType_vCont_actions,
186 &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
187 RegisterMemberFunctionHandler(
188 StringExtractorGDBRemote::eServerPacketType_vRun,
189 &GDBRemoteCommunicationServerLLGS::Handle_vRun);
190 RegisterMemberFunctionHandler(
191 StringExtractorGDBRemote::eServerPacketType_x,
192 &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
193 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
194 &GDBRemoteCommunicationServerLLGS::Handle_Z);
195 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
196 &GDBRemoteCommunicationServerLLGS::Handle_z);
197 RegisterMemberFunctionHandler(
198 StringExtractorGDBRemote::eServerPacketType_QPassSignals,
199 &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
200
201 RegisterMemberFunctionHandler(
202 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceSupported,
203 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported);
204 RegisterMemberFunctionHandler(
205 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStart,
206 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart);
207 RegisterMemberFunctionHandler(
208 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStop,
209 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop);
210 RegisterMemberFunctionHandler(
211 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetState,
212 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState);
213 RegisterMemberFunctionHandler(
214 StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetBinaryData,
215 &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData);
216
217 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g,
218 &GDBRemoteCommunicationServerLLGS::Handle_g);
219
220 RegisterMemberFunctionHandler(
221 StringExtractorGDBRemote::eServerPacketType_qMemTags,
222 &GDBRemoteCommunicationServerLLGS::Handle_qMemTags);
223
224 RegisterMemberFunctionHandler(
225 StringExtractorGDBRemote::eServerPacketType_QMemTags,
226 &GDBRemoteCommunicationServerLLGS::Handle_QMemTags);
227
228 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
229 [this](StringExtractorGDBRemote packet, Status &error,
230 bool &interrupt, bool &quit) {
231 quit = true;
232 return this->Handle_k(packet);
233 });
234
235 RegisterMemberFunctionHandler(
236 StringExtractorGDBRemote::eServerPacketType_vKill,
237 &GDBRemoteCommunicationServerLLGS::Handle_vKill);
238
239 RegisterMemberFunctionHandler(
240 StringExtractorGDBRemote::eServerPacketType_qLLDBSaveCore,
241 &GDBRemoteCommunicationServerLLGS::Handle_qSaveCore);
242
243 RegisterMemberFunctionHandler(
244 StringExtractorGDBRemote::eServerPacketType_QNonStop,
245 &GDBRemoteCommunicationServerLLGS::Handle_QNonStop);
246 RegisterMemberFunctionHandler(
247 StringExtractorGDBRemote::eServerPacketType_vStdio,
248 &GDBRemoteCommunicationServerLLGS::Handle_vStdio);
249 RegisterMemberFunctionHandler(
250 StringExtractorGDBRemote::eServerPacketType_vStopped,
251 &GDBRemoteCommunicationServerLLGS::Handle_vStopped);
252 RegisterMemberFunctionHandler(
253 StringExtractorGDBRemote::eServerPacketType_vCtrlC,
254 &GDBRemoteCommunicationServerLLGS::Handle_vCtrlC);
255 }
256
SetLaunchInfo(const ProcessLaunchInfo & info)257 void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) {
258 m_process_launch_info = info;
259 }
260
LaunchProcess()261 Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
262 Log *log = GetLog(LLDBLog::Process);
263
264 if (!m_process_launch_info.GetArguments().GetArgumentCount())
265 return Status("%s: no process command line specified to launch",
266 __FUNCTION__);
267
268 const bool should_forward_stdio =
269 m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
270 m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
271 m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
272 m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
273 m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
274
275 if (should_forward_stdio) {
276 // Temporarily relax the following for Windows until we can take advantage
277 // of the recently added pty support. This doesn't really affect the use of
278 // lldb-server on Windows.
279 #if !defined(_WIN32)
280 if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
281 return Status(std::move(Err));
282 #endif
283 }
284
285 {
286 std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
287 assert(m_debugged_processes.empty() && "lldb-server creating debugged "
288 "process but one already exists");
289 auto process_or =
290 m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
291 if (!process_or)
292 return Status(process_or.takeError());
293 m_continue_process = m_current_process = process_or->get();
294 m_debugged_processes.emplace(
295 m_current_process->GetID(),
296 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});
297 }
298
299 SetEnabledExtensions(*m_current_process);
300
301 // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as
302 // needed. llgs local-process debugging may specify PTY paths, which will
303 // make these file actions non-null process launch -i/e/o will also make
304 // these file actions non-null nullptr means that the traffic is expected to
305 // flow over gdb-remote protocol
306 if (should_forward_stdio) {
307 // nullptr means it's not redirected to file or pty (in case of LLGS local)
308 // at least one of stdio will be transferred pty<->gdb-remote we need to
309 // give the pty primary handle to this object to read and/or write
310 LLDB_LOG(log,
311 "pid = {0}: setting up stdout/stderr redirection via $O "
312 "gdb-remote commands",
313 m_current_process->GetID());
314
315 // Setup stdout/stderr mapping from inferior to $O
316 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
317 if (terminal_fd >= 0) {
318 LLDB_LOGF(log,
319 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
320 "inferior STDIO fd to %d",
321 __FUNCTION__, terminal_fd);
322 Status status = SetSTDIOFileDescriptor(terminal_fd);
323 if (status.Fail())
324 return status;
325 } else {
326 LLDB_LOGF(log,
327 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
328 "inferior STDIO since terminal fd reported as %d",
329 __FUNCTION__, terminal_fd);
330 }
331 } else {
332 LLDB_LOG(log,
333 "pid = {0} skipping stdout/stderr redirection via $O: inferior "
334 "will communicate over client-provided file descriptors",
335 m_current_process->GetID());
336 }
337
338 printf("Launched '%s' as process %" PRIu64 "...\n",
339 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
340 m_current_process->GetID());
341
342 return Status();
343 }
344
AttachToProcess(lldb::pid_t pid)345 Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
346 Log *log = GetLog(LLDBLog::Process);
347 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
348 __FUNCTION__, pid);
349
350 // Before we try to attach, make sure we aren't already monitoring something
351 // else.
352 if (!m_debugged_processes.empty())
353 return Status("cannot attach to process %" PRIu64
354 " when another process with pid %" PRIu64
355 " is being debugged.",
356 pid, m_current_process->GetID());
357
358 // Try to attach.
359 auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
360 if (!process_or) {
361 Status status(process_or.takeError());
362 llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}\n", pid,
363 status);
364 return status;
365 }
366 m_continue_process = m_current_process = process_or->get();
367 m_debugged_processes.emplace(
368 m_current_process->GetID(),
369 DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});
370 SetEnabledExtensions(*m_current_process);
371
372 // Setup stdout/stderr mapping from inferior.
373 auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
374 if (terminal_fd >= 0) {
375 LLDB_LOGF(log,
376 "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
377 "inferior STDIO fd to %d",
378 __FUNCTION__, terminal_fd);
379 Status status = SetSTDIOFileDescriptor(terminal_fd);
380 if (status.Fail())
381 return status;
382 } else {
383 LLDB_LOGF(log,
384 "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
385 "inferior STDIO since terminal fd reported as %d",
386 __FUNCTION__, terminal_fd);
387 }
388
389 printf("Attached to process %" PRIu64 "...\n", pid);
390 return Status();
391 }
392
AttachWaitProcess(llvm::StringRef process_name,bool include_existing)393 Status GDBRemoteCommunicationServerLLGS::AttachWaitProcess(
394 llvm::StringRef process_name, bool include_existing) {
395 Log *log = GetLog(LLDBLog::Process);
396
397 std::chrono::milliseconds polling_interval = std::chrono::milliseconds(1);
398
399 // Create the matcher used to search the process list.
400 ProcessInstanceInfoList exclusion_list;
401 ProcessInstanceInfoMatch match_info;
402 match_info.GetProcessInfo().GetExecutableFile().SetFile(
403 process_name, llvm::sys::path::Style::native);
404 match_info.SetNameMatchType(NameMatch::Equals);
405
406 if (include_existing) {
407 LLDB_LOG(log, "including existing processes in search");
408 } else {
409 // Create the excluded process list before polling begins.
410 Host::FindProcesses(match_info, exclusion_list);
411 LLDB_LOG(log, "placed '{0}' processes in the exclusion list.",
412 exclusion_list.size());
413 }
414
415 LLDB_LOG(log, "waiting for '{0}' to appear", process_name);
416
417 auto is_in_exclusion_list =
418 [&exclusion_list](const ProcessInstanceInfo &info) {
419 for (auto &excluded : exclusion_list) {
420 if (excluded.GetProcessID() == info.GetProcessID())
421 return true;
422 }
423 return false;
424 };
425
426 ProcessInstanceInfoList loop_process_list;
427 while (true) {
428 loop_process_list.clear();
429 if (Host::FindProcesses(match_info, loop_process_list)) {
430 // Remove all the elements that are in the exclusion list.
431 llvm::erase_if(loop_process_list, is_in_exclusion_list);
432
433 // One match! We found the desired process.
434 if (loop_process_list.size() == 1) {
435 auto matching_process_pid = loop_process_list[0].GetProcessID();
436 LLDB_LOG(log, "found pid {0}", matching_process_pid);
437 return AttachToProcess(matching_process_pid);
438 }
439
440 // Multiple matches! Return an error reporting the PIDs we found.
441 if (loop_process_list.size() > 1) {
442 StreamString error_stream;
443 error_stream.Format(
444 "Multiple executables with name: '{0}' found. Pids: ",
445 process_name);
446 for (size_t i = 0; i < loop_process_list.size() - 1; ++i) {
447 error_stream.Format("{0}, ", loop_process_list[i].GetProcessID());
448 }
449 error_stream.Format("{0}.", loop_process_list.back().GetProcessID());
450
451 Status error;
452 error.SetErrorString(error_stream.GetString());
453 return error;
454 }
455 }
456 // No matches, we have not found the process. Sleep until next poll.
457 LLDB_LOG(log, "sleep {0} seconds", polling_interval);
458 std::this_thread::sleep_for(polling_interval);
459 }
460 }
461
InitializeDelegate(NativeProcessProtocol * process)462 void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
463 NativeProcessProtocol *process) {
464 assert(process && "process cannot be NULL");
465 Log *log = GetLog(LLDBLog::Process);
466 if (log) {
467 LLDB_LOGF(log,
468 "GDBRemoteCommunicationServerLLGS::%s called with "
469 "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
470 __FUNCTION__, process->GetID(),
471 StateAsCString(process->GetState()));
472 }
473 }
474
475 GDBRemoteCommunication::PacketResult
SendWResponse(NativeProcessProtocol * process)476 GDBRemoteCommunicationServerLLGS::SendWResponse(
477 NativeProcessProtocol *process) {
478 assert(process && "process cannot be NULL");
479 Log *log = GetLog(LLDBLog::Process);
480
481 // send W notification
482 auto wait_status = process->GetExitStatus();
483 if (!wait_status) {
484 LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
485 process->GetID());
486
487 StreamGDBRemote response;
488 response.PutChar('E');
489 response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
490 return SendPacketNoLock(response.GetString());
491 }
492
493 LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
494 *wait_status);
495
496 // If the process was killed through vKill, return "OK".
497 if (bool(m_debugged_processes.at(process->GetID()).flags &
498 DebuggedProcess::Flag::vkilled))
499 return SendOKResponse();
500
501 StreamGDBRemote response;
502 response.Format("{0:g}", *wait_status);
503 if (bool(m_extensions_supported &
504 NativeProcessProtocol::Extension::multiprocess))
505 response.Format(";process:{0:x-}", process->GetID());
506 if (m_non_stop)
507 return SendNotificationPacketNoLock("Stop", m_stop_notification_queue,
508 response.GetString());
509 return SendPacketNoLock(response.GetString());
510 }
511
AppendHexValue(StreamString & response,const uint8_t * buf,uint32_t buf_size,bool swap)512 static void AppendHexValue(StreamString &response, const uint8_t *buf,
513 uint32_t buf_size, bool swap) {
514 int64_t i;
515 if (swap) {
516 for (i = buf_size - 1; i >= 0; i--)
517 response.PutHex8(buf[i]);
518 } else {
519 for (i = 0; i < buf_size; i++)
520 response.PutHex8(buf[i]);
521 }
522 }
523
GetEncodingNameOrEmpty(const RegisterInfo & reg_info)524 static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo ®_info) {
525 switch (reg_info.encoding) {
526 case eEncodingUint:
527 return "uint";
528 case eEncodingSint:
529 return "sint";
530 case eEncodingIEEE754:
531 return "ieee754";
532 case eEncodingVector:
533 return "vector";
534 default:
535 return "";
536 }
537 }
538
GetFormatNameOrEmpty(const RegisterInfo & reg_info)539 static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo ®_info) {
540 switch (reg_info.format) {
541 case eFormatBinary:
542 return "binary";
543 case eFormatDecimal:
544 return "decimal";
545 case eFormatHex:
546 return "hex";
547 case eFormatFloat:
548 return "float";
549 case eFormatVectorOfSInt8:
550 return "vector-sint8";
551 case eFormatVectorOfUInt8:
552 return "vector-uint8";
553 case eFormatVectorOfSInt16:
554 return "vector-sint16";
555 case eFormatVectorOfUInt16:
556 return "vector-uint16";
557 case eFormatVectorOfSInt32:
558 return "vector-sint32";
559 case eFormatVectorOfUInt32:
560 return "vector-uint32";
561 case eFormatVectorOfFloat32:
562 return "vector-float32";
563 case eFormatVectorOfUInt64:
564 return "vector-uint64";
565 case eFormatVectorOfUInt128:
566 return "vector-uint128";
567 default:
568 return "";
569 };
570 }
571
GetKindGenericOrEmpty(const RegisterInfo & reg_info)572 static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo ®_info) {
573 switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) {
574 case LLDB_REGNUM_GENERIC_PC:
575 return "pc";
576 case LLDB_REGNUM_GENERIC_SP:
577 return "sp";
578 case LLDB_REGNUM_GENERIC_FP:
579 return "fp";
580 case LLDB_REGNUM_GENERIC_RA:
581 return "ra";
582 case LLDB_REGNUM_GENERIC_FLAGS:
583 return "flags";
584 case LLDB_REGNUM_GENERIC_ARG1:
585 return "arg1";
586 case LLDB_REGNUM_GENERIC_ARG2:
587 return "arg2";
588 case LLDB_REGNUM_GENERIC_ARG3:
589 return "arg3";
590 case LLDB_REGNUM_GENERIC_ARG4:
591 return "arg4";
592 case LLDB_REGNUM_GENERIC_ARG5:
593 return "arg5";
594 case LLDB_REGNUM_GENERIC_ARG6:
595 return "arg6";
596 case LLDB_REGNUM_GENERIC_ARG7:
597 return "arg7";
598 case LLDB_REGNUM_GENERIC_ARG8:
599 return "arg8";
600 default:
601 return "";
602 }
603 }
604
CollectRegNums(const uint32_t * reg_num,StreamString & response,bool usehex)605 static void CollectRegNums(const uint32_t *reg_num, StreamString &response,
606 bool usehex) {
607 for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
608 if (i > 0)
609 response.PutChar(',');
610 if (usehex)
611 response.Printf("%" PRIx32, *reg_num);
612 else
613 response.Printf("%" PRIu32, *reg_num);
614 }
615 }
616
WriteRegisterValueInHexFixedWidth(StreamString & response,NativeRegisterContext & reg_ctx,const RegisterInfo & reg_info,const RegisterValue * reg_value_p,lldb::ByteOrder byte_order)617 static void WriteRegisterValueInHexFixedWidth(
618 StreamString &response, NativeRegisterContext ®_ctx,
619 const RegisterInfo ®_info, const RegisterValue *reg_value_p,
620 lldb::ByteOrder byte_order) {
621 RegisterValue reg_value;
622 if (!reg_value_p) {
623 Status error = reg_ctx.ReadRegister(®_info, reg_value);
624 if (error.Success())
625 reg_value_p = ®_value;
626 // else log.
627 }
628
629 if (reg_value_p) {
630 AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
631 reg_value_p->GetByteSize(),
632 byte_order == lldb::eByteOrderLittle);
633 } else {
634 // Zero-out any unreadable values.
635 if (reg_info.byte_size > 0) {
636 std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
637 AppendHexValue(response, zeros.data(), zeros.size(), false);
638 }
639 }
640 }
641
642 static std::optional<json::Object>
GetRegistersAsJSON(NativeThreadProtocol & thread)643 GetRegistersAsJSON(NativeThreadProtocol &thread) {
644 Log *log = GetLog(LLDBLog::Thread);
645
646 NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
647
648 json::Object register_object;
649
650 #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
651 const auto expedited_regs =
652 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);
653 #else
654 const auto expedited_regs =
655 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Minimal);
656 #endif
657 if (expedited_regs.empty())
658 return std::nullopt;
659
660 for (auto ®_num : expedited_regs) {
661 const RegisterInfo *const reg_info_p =
662 reg_ctx.GetRegisterInfoAtIndex(reg_num);
663 if (reg_info_p == nullptr) {
664 LLDB_LOGF(log,
665 "%s failed to get register info for register index %" PRIu32,
666 __FUNCTION__, reg_num);
667 continue;
668 }
669
670 if (reg_info_p->value_regs != nullptr)
671 continue; // Only expedite registers that are not contained in other
672 // registers.
673
674 RegisterValue reg_value;
675 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
676 if (error.Fail()) {
677 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
678 __FUNCTION__,
679 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
680 reg_num, error.AsCString());
681 continue;
682 }
683
684 StreamString stream;
685 WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
686 ®_value, lldb::eByteOrderBig);
687
688 register_object.try_emplace(llvm::to_string(reg_num),
689 stream.GetString().str());
690 }
691
692 return register_object;
693 }
694
GetStopReasonString(StopReason stop_reason)695 static const char *GetStopReasonString(StopReason stop_reason) {
696 switch (stop_reason) {
697 case eStopReasonTrace:
698 return "trace";
699 case eStopReasonBreakpoint:
700 return "breakpoint";
701 case eStopReasonWatchpoint:
702 return "watchpoint";
703 case eStopReasonSignal:
704 return "signal";
705 case eStopReasonException:
706 return "exception";
707 case eStopReasonExec:
708 return "exec";
709 case eStopReasonProcessorTrace:
710 return "processor trace";
711 case eStopReasonFork:
712 return "fork";
713 case eStopReasonVFork:
714 return "vfork";
715 case eStopReasonVForkDone:
716 return "vforkdone";
717 case eStopReasonInstrumentation:
718 case eStopReasonInvalid:
719 case eStopReasonPlanComplete:
720 case eStopReasonThreadExiting:
721 case eStopReasonNone:
722 break; // ignored
723 }
724 return nullptr;
725 }
726
727 static llvm::Expected<json::Array>
GetJSONThreadsInfo(NativeProcessProtocol & process,bool abridged)728 GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) {
729 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
730
731 json::Array threads_array;
732
733 // Ensure we can get info on the given thread.
734 for (NativeThreadProtocol &thread : process.Threads()) {
735 lldb::tid_t tid = thread.GetID();
736 // Grab the reason this thread stopped.
737 struct ThreadStopInfo tid_stop_info;
738 std::string description;
739 if (!thread.GetStopReason(tid_stop_info, description))
740 return llvm::make_error<llvm::StringError>(
741 "failed to get stop reason", llvm::inconvertibleErrorCode());
742
743 const int signum = tid_stop_info.signo;
744 if (log) {
745 LLDB_LOGF(log,
746 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
747 " tid %" PRIu64
748 " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
749 __FUNCTION__, process.GetID(), tid, signum,
750 tid_stop_info.reason, tid_stop_info.details.exception.type);
751 }
752
753 json::Object thread_obj;
754
755 if (!abridged) {
756 if (std::optional<json::Object> registers = GetRegistersAsJSON(thread))
757 thread_obj.try_emplace("registers", std::move(*registers));
758 }
759
760 thread_obj.try_emplace("tid", static_cast<int64_t>(tid));
761
762 if (signum != 0)
763 thread_obj.try_emplace("signal", signum);
764
765 const std::string thread_name = thread.GetName();
766 if (!thread_name.empty())
767 thread_obj.try_emplace("name", thread_name);
768
769 const char *stop_reason = GetStopReasonString(tid_stop_info.reason);
770 if (stop_reason)
771 thread_obj.try_emplace("reason", stop_reason);
772
773 if (!description.empty())
774 thread_obj.try_emplace("description", description);
775
776 if ((tid_stop_info.reason == eStopReasonException) &&
777 tid_stop_info.details.exception.type) {
778 thread_obj.try_emplace(
779 "metype", static_cast<int64_t>(tid_stop_info.details.exception.type));
780
781 json::Array medata_array;
782 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
783 ++i) {
784 medata_array.push_back(
785 static_cast<int64_t>(tid_stop_info.details.exception.data[i]));
786 }
787 thread_obj.try_emplace("medata", std::move(medata_array));
788 }
789 threads_array.push_back(std::move(thread_obj));
790 }
791 return threads_array;
792 }
793
794 StreamString
PrepareStopReplyPacketForThread(NativeThreadProtocol & thread)795 GDBRemoteCommunicationServerLLGS::PrepareStopReplyPacketForThread(
796 NativeThreadProtocol &thread) {
797 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
798
799 NativeProcessProtocol &process = thread.GetProcess();
800
801 LLDB_LOG(log, "preparing packet for pid {0} tid {1}", process.GetID(),
802 thread.GetID());
803
804 // Grab the reason this thread stopped.
805 StreamString response;
806 struct ThreadStopInfo tid_stop_info;
807 std::string description;
808 if (!thread.GetStopReason(tid_stop_info, description))
809 return response;
810
811 // FIXME implement register handling for exec'd inferiors.
812 // if (tid_stop_info.reason == eStopReasonExec) {
813 // const bool force = true;
814 // InitializeRegisters(force);
815 // }
816
817 // Output the T packet with the thread
818 response.PutChar('T');
819 int signum = tid_stop_info.signo;
820 LLDB_LOG(
821 log,
822 "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
823 process.GetID(), thread.GetID(), signum, int(tid_stop_info.reason),
824 tid_stop_info.details.exception.type);
825
826 // Print the signal number.
827 response.PutHex8(signum & 0xff);
828
829 // Include the (pid and) tid.
830 response.PutCString("thread:");
831 AppendThreadIDToResponse(response, process.GetID(), thread.GetID());
832 response.PutChar(';');
833
834 // Include the thread name if there is one.
835 const std::string thread_name = thread.GetName();
836 if (!thread_name.empty()) {
837 size_t thread_name_len = thread_name.length();
838
839 if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
840 response.PutCString("name:");
841 response.PutCString(thread_name);
842 } else {
843 // The thread name contains special chars, send as hex bytes.
844 response.PutCString("hexname:");
845 response.PutStringAsRawHex8(thread_name);
846 }
847 response.PutChar(';');
848 }
849
850 // If a 'QListThreadsInStopReply' was sent to enable this feature, we will
851 // send all thread IDs back in the "threads" key whose value is a list of hex
852 // thread IDs separated by commas:
853 // "threads:10a,10b,10c;"
854 // This will save the debugger from having to send a pair of qfThreadInfo and
855 // qsThreadInfo packets, but it also might take a lot of room in the stop
856 // reply packet, so it must be enabled only on systems where there are no
857 // limits on packet lengths.
858 if (m_list_threads_in_stop_reply) {
859 response.PutCString("threads:");
860
861 uint32_t thread_num = 0;
862 for (NativeThreadProtocol &listed_thread : process.Threads()) {
863 if (thread_num > 0)
864 response.PutChar(',');
865 response.Printf("%" PRIx64, listed_thread.GetID());
866 ++thread_num;
867 }
868 response.PutChar(';');
869
870 // Include JSON info that describes the stop reason for any threads that
871 // actually have stop reasons. We use the new "jstopinfo" key whose values
872 // is hex ascii JSON that contains the thread IDs thread stop info only for
873 // threads that have stop reasons. Only send this if we have more than one
874 // thread otherwise this packet has all the info it needs.
875 if (thread_num > 1) {
876 const bool threads_with_valid_stop_info_only = true;
877 llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo(
878 *m_current_process, threads_with_valid_stop_info_only);
879 if (threads_info) {
880 response.PutCString("jstopinfo:");
881 StreamString unescaped_response;
882 unescaped_response.AsRawOstream() << std::move(*threads_info);
883 response.PutStringAsRawHex8(unescaped_response.GetData());
884 response.PutChar(';');
885 } else {
886 LLDB_LOG_ERROR(log, threads_info.takeError(),
887 "failed to prepare a jstopinfo field for pid {1}: {0}",
888 process.GetID());
889 }
890 }
891
892 response.PutCString("thread-pcs");
893 char delimiter = ':';
894 for (NativeThreadProtocol &thread : process.Threads()) {
895 NativeRegisterContext ®_ctx = thread.GetRegisterContext();
896
897 uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
898 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
899 const RegisterInfo *const reg_info_p =
900 reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
901
902 RegisterValue reg_value;
903 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
904 if (error.Fail()) {
905 LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
906 __FUNCTION__,
907 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
908 reg_to_read, error.AsCString());
909 continue;
910 }
911
912 response.PutChar(delimiter);
913 delimiter = ',';
914 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
915 ®_value, endian::InlHostByteOrder());
916 }
917
918 response.PutChar(';');
919 }
920
921 //
922 // Expedite registers.
923 //
924
925 // Grab the register context.
926 NativeRegisterContext ®_ctx = thread.GetRegisterContext();
927 const auto expedited_regs =
928 reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);
929
930 for (auto ®_num : expedited_regs) {
931 const RegisterInfo *const reg_info_p =
932 reg_ctx.GetRegisterInfoAtIndex(reg_num);
933 // Only expediate registers that are not contained in other registers.
934 if (reg_info_p != nullptr && reg_info_p->value_regs == nullptr) {
935 RegisterValue reg_value;
936 Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
937 if (error.Success()) {
938 response.Printf("%.02x:", reg_num);
939 WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
940 ®_value, lldb::eByteOrderBig);
941 response.PutChar(';');
942 } else {
943 LLDB_LOGF(log,
944 "GDBRemoteCommunicationServerLLGS::%s failed to read "
945 "register '%s' index %" PRIu32 ": %s",
946 __FUNCTION__,
947 reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
948 reg_num, error.AsCString());
949 }
950 }
951 }
952
953 const char *reason_str = GetStopReasonString(tid_stop_info.reason);
954 if (reason_str != nullptr) {
955 response.Printf("reason:%s;", reason_str);
956 }
957
958 if (!description.empty()) {
959 // Description may contains special chars, send as hex bytes.
960 response.PutCString("description:");
961 response.PutStringAsRawHex8(description);
962 response.PutChar(';');
963 } else if ((tid_stop_info.reason == eStopReasonException) &&
964 tid_stop_info.details.exception.type) {
965 response.PutCString("metype:");
966 response.PutHex64(tid_stop_info.details.exception.type);
967 response.PutCString(";mecount:");
968 response.PutHex32(tid_stop_info.details.exception.data_count);
969 response.PutChar(';');
970
971 for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
972 response.PutCString("medata:");
973 response.PutHex64(tid_stop_info.details.exception.data[i]);
974 response.PutChar(';');
975 }
976 }
977
978 // Include child process PID/TID for forks.
979 if (tid_stop_info.reason == eStopReasonFork ||
980 tid_stop_info.reason == eStopReasonVFork) {
981 assert(bool(m_extensions_supported &
982 NativeProcessProtocol::Extension::multiprocess));
983 if (tid_stop_info.reason == eStopReasonFork)
984 assert(bool(m_extensions_supported &
985 NativeProcessProtocol::Extension::fork));
986 if (tid_stop_info.reason == eStopReasonVFork)
987 assert(bool(m_extensions_supported &
988 NativeProcessProtocol::Extension::vfork));
989 response.Printf("%s:p%" PRIx64 ".%" PRIx64 ";", reason_str,
990 tid_stop_info.details.fork.child_pid,
991 tid_stop_info.details.fork.child_tid);
992 }
993
994 return response;
995 }
996
997 GDBRemoteCommunication::PacketResult
SendStopReplyPacketForThread(NativeProcessProtocol & process,lldb::tid_t tid,bool force_synchronous)998 GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
999 NativeProcessProtocol &process, lldb::tid_t tid, bool force_synchronous) {
1000 // Ensure we can get info on the given thread.
1001 NativeThreadProtocol *thread = process.GetThreadByID(tid);
1002 if (!thread)
1003 return SendErrorResponse(51);
1004
1005 StreamString response = PrepareStopReplyPacketForThread(*thread);
1006 if (response.Empty())
1007 return SendErrorResponse(42);
1008
1009 if (m_non_stop && !force_synchronous) {
1010 PacketResult ret = SendNotificationPacketNoLock(
1011 "Stop", m_stop_notification_queue, response.GetString());
1012 // Queue notification events for the remaining threads.
1013 EnqueueStopReplyPackets(tid);
1014 return ret;
1015 }
1016
1017 return SendPacketNoLock(response.GetString());
1018 }
1019
EnqueueStopReplyPackets(lldb::tid_t thread_to_skip)1020 void GDBRemoteCommunicationServerLLGS::EnqueueStopReplyPackets(
1021 lldb::tid_t thread_to_skip) {
1022 if (!m_non_stop)
1023 return;
1024
1025 for (NativeThreadProtocol &listed_thread : m_current_process->Threads()) {
1026 if (listed_thread.GetID() != thread_to_skip) {
1027 StreamString stop_reply = PrepareStopReplyPacketForThread(listed_thread);
1028 if (!stop_reply.Empty())
1029 m_stop_notification_queue.push_back(stop_reply.GetString().str());
1030 }
1031 }
1032 }
1033
HandleInferiorState_Exited(NativeProcessProtocol * process)1034 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
1035 NativeProcessProtocol *process) {
1036 assert(process && "process cannot be NULL");
1037
1038 Log *log = GetLog(LLDBLog::Process);
1039 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1040
1041 PacketResult result = SendStopReasonForState(
1042 *process, StateType::eStateExited, /*force_synchronous=*/false);
1043 if (result != PacketResult::Success) {
1044 LLDB_LOGF(log,
1045 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1046 "notification for PID %" PRIu64 ", state: eStateExited",
1047 __FUNCTION__, process->GetID());
1048 }
1049
1050 if (m_current_process == process)
1051 m_current_process = nullptr;
1052 if (m_continue_process == process)
1053 m_continue_process = nullptr;
1054
1055 lldb::pid_t pid = process->GetID();
1056 m_mainloop.AddPendingCallback([this, pid](MainLoopBase &loop) {
1057 auto find_it = m_debugged_processes.find(pid);
1058 assert(find_it != m_debugged_processes.end());
1059 bool vkilled = bool(find_it->second.flags & DebuggedProcess::Flag::vkilled);
1060 m_debugged_processes.erase(find_it);
1061 // Terminate the main loop only if vKill has not been used.
1062 // When running in non-stop mode, wait for the vStopped to clear
1063 // the notification queue.
1064 if (m_debugged_processes.empty() && !m_non_stop && !vkilled) {
1065 // Close the pipe to the inferior terminal i/o if we launched it and set
1066 // one up.
1067 MaybeCloseInferiorTerminalConnection();
1068
1069 // We are ready to exit the debug monitor.
1070 m_exit_now = true;
1071 loop.RequestTermination();
1072 }
1073 });
1074 }
1075
HandleInferiorState_Stopped(NativeProcessProtocol * process)1076 void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
1077 NativeProcessProtocol *process) {
1078 assert(process && "process cannot be NULL");
1079
1080 Log *log = GetLog(LLDBLog::Process);
1081 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1082
1083 PacketResult result = SendStopReasonForState(
1084 *process, StateType::eStateStopped, /*force_synchronous=*/false);
1085 if (result != PacketResult::Success) {
1086 LLDB_LOGF(log,
1087 "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1088 "notification for PID %" PRIu64 ", state: eStateExited",
1089 __FUNCTION__, process->GetID());
1090 }
1091 }
1092
ProcessStateChanged(NativeProcessProtocol * process,lldb::StateType state)1093 void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
1094 NativeProcessProtocol *process, lldb::StateType state) {
1095 assert(process && "process cannot be NULL");
1096 Log *log = GetLog(LLDBLog::Process);
1097 if (log) {
1098 LLDB_LOGF(log,
1099 "GDBRemoteCommunicationServerLLGS::%s called with "
1100 "NativeProcessProtocol pid %" PRIu64 ", state: %s",
1101 __FUNCTION__, process->GetID(), StateAsCString(state));
1102 }
1103
1104 switch (state) {
1105 case StateType::eStateRunning:
1106 break;
1107
1108 case StateType::eStateStopped:
1109 // Make sure we get all of the pending stdout/stderr from the inferior and
1110 // send it to the lldb host before we send the state change notification
1111 SendProcessOutput();
1112 // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
1113 // does not interfere with our protocol.
1114 if (!m_non_stop)
1115 StopSTDIOForwarding();
1116 HandleInferiorState_Stopped(process);
1117 break;
1118
1119 case StateType::eStateExited:
1120 // Same as above
1121 SendProcessOutput();
1122 if (!m_non_stop)
1123 StopSTDIOForwarding();
1124 HandleInferiorState_Exited(process);
1125 break;
1126
1127 default:
1128 if (log) {
1129 LLDB_LOGF(log,
1130 "GDBRemoteCommunicationServerLLGS::%s didn't handle state "
1131 "change for pid %" PRIu64 ", new state: %s",
1132 __FUNCTION__, process->GetID(), StateAsCString(state));
1133 }
1134 break;
1135 }
1136 }
1137
DidExec(NativeProcessProtocol * process)1138 void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
1139 ClearProcessSpecificData();
1140 }
1141
NewSubprocess(NativeProcessProtocol * parent_process,std::unique_ptr<NativeProcessProtocol> child_process)1142 void GDBRemoteCommunicationServerLLGS::NewSubprocess(
1143 NativeProcessProtocol *parent_process,
1144 std::unique_ptr<NativeProcessProtocol> child_process) {
1145 lldb::pid_t child_pid = child_process->GetID();
1146 assert(child_pid != LLDB_INVALID_PROCESS_ID);
1147 assert(m_debugged_processes.find(child_pid) == m_debugged_processes.end());
1148 m_debugged_processes.emplace(
1149 child_pid,
1150 DebuggedProcess{std::move(child_process), DebuggedProcess::Flag{}});
1151 }
1152
DataAvailableCallback()1153 void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
1154 Log *log = GetLog(GDBRLog::Comm);
1155
1156 bool interrupt = false;
1157 bool done = false;
1158 Status error;
1159 while (true) {
1160 const PacketResult result = GetPacketAndSendResponse(
1161 std::chrono::microseconds(0), error, interrupt, done);
1162 if (result == PacketResult::ErrorReplyTimeout)
1163 break; // No more packets in the queue
1164
1165 if ((result != PacketResult::Success)) {
1166 LLDB_LOGF(log,
1167 "GDBRemoteCommunicationServerLLGS::%s processing a packet "
1168 "failed: %s",
1169 __FUNCTION__, error.AsCString());
1170 m_mainloop.RequestTermination();
1171 break;
1172 }
1173 }
1174 }
1175
InitializeConnection(std::unique_ptr<Connection> connection)1176 Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
1177 std::unique_ptr<Connection> connection) {
1178 IOObjectSP read_object_sp = connection->GetReadObject();
1179 GDBRemoteCommunicationServer::SetConnection(std::move(connection));
1180
1181 Status error;
1182 m_network_handle_up = m_mainloop.RegisterReadObject(
1183 read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
1184 error);
1185 return error;
1186 }
1187
1188 GDBRemoteCommunication::PacketResult
SendONotification(const char * buffer,uint32_t len)1189 GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
1190 uint32_t len) {
1191 if ((buffer == nullptr) || (len == 0)) {
1192 // Nothing to send.
1193 return PacketResult::Success;
1194 }
1195
1196 StreamString response;
1197 response.PutChar('O');
1198 response.PutBytesAsRawHex8(buffer, len);
1199
1200 if (m_non_stop)
1201 return SendNotificationPacketNoLock("Stdio", m_stdio_notification_queue,
1202 response.GetString());
1203 return SendPacketNoLock(response.GetString());
1204 }
1205
SetSTDIOFileDescriptor(int fd)1206 Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
1207 Status error;
1208
1209 // Set up the reading/handling of process I/O
1210 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1211 new ConnectionFileDescriptor(fd, true));
1212 if (!conn_up) {
1213 error.SetErrorString("failed to create ConnectionFileDescriptor");
1214 return error;
1215 }
1216
1217 m_stdio_communication.SetCloseOnEOF(false);
1218 m_stdio_communication.SetConnection(std::move(conn_up));
1219 if (!m_stdio_communication.IsConnected()) {
1220 error.SetErrorString(
1221 "failed to set connection for inferior I/O communication");
1222 return error;
1223 }
1224
1225 return Status();
1226 }
1227
StartSTDIOForwarding()1228 void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1229 // Don't forward if not connected (e.g. when attaching).
1230 if (!m_stdio_communication.IsConnected())
1231 return;
1232
1233 Status error;
1234 assert(!m_stdio_handle_up);
1235 m_stdio_handle_up = m_mainloop.RegisterReadObject(
1236 m_stdio_communication.GetConnection()->GetReadObject(),
1237 [this](MainLoopBase &) { SendProcessOutput(); }, error);
1238
1239 if (!m_stdio_handle_up) {
1240 // Not much we can do about the failure. Log it and continue without
1241 // forwarding.
1242 if (Log *log = GetLog(LLDBLog::Process))
1243 LLDB_LOG(log, "Failed to set up stdio forwarding: {0}", error);
1244 }
1245 }
1246
StopSTDIOForwarding()1247 void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1248 m_stdio_handle_up.reset();
1249 }
1250
SendProcessOutput()1251 void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1252 char buffer[1024];
1253 ConnectionStatus status;
1254 Status error;
1255 while (true) {
1256 size_t bytes_read = m_stdio_communication.Read(
1257 buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1258 switch (status) {
1259 case eConnectionStatusSuccess:
1260 SendONotification(buffer, bytes_read);
1261 break;
1262 case eConnectionStatusLostConnection:
1263 case eConnectionStatusEndOfFile:
1264 case eConnectionStatusError:
1265 case eConnectionStatusNoConnection:
1266 if (Log *log = GetLog(LLDBLog::Process))
1267 LLDB_LOGF(log,
1268 "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1269 "forwarding as communication returned status %d (error: "
1270 "%s)",
1271 __FUNCTION__, status, error.AsCString());
1272 m_stdio_handle_up.reset();
1273 return;
1274
1275 case eConnectionStatusInterrupted:
1276 case eConnectionStatusTimedOut:
1277 return;
1278 }
1279 }
1280 }
1281
1282 GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceSupported(StringExtractorGDBRemote & packet)1283 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported(
1284 StringExtractorGDBRemote &packet) {
1285
1286 // Fail if we don't have a current process.
1287 if (!m_current_process ||
1288 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1289 return SendErrorResponse(Status("Process not running."));
1290
1291 return SendJSONResponse(m_current_process->TraceSupported());
1292 }
1293
1294 GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceStop(StringExtractorGDBRemote & packet)1295 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop(
1296 StringExtractorGDBRemote &packet) {
1297 // Fail if we don't have a current process.
1298 if (!m_current_process ||
1299 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1300 return SendErrorResponse(Status("Process not running."));
1301
1302 packet.ConsumeFront("jLLDBTraceStop:");
1303 Expected<TraceStopRequest> stop_request =
1304 json::parse<TraceStopRequest>(packet.Peek(), "TraceStopRequest");
1305 if (!stop_request)
1306 return SendErrorResponse(stop_request.takeError());
1307
1308 if (Error err = m_current_process->TraceStop(*stop_request))
1309 return SendErrorResponse(std::move(err));
1310
1311 return SendOKResponse();
1312 }
1313
1314 GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceStart(StringExtractorGDBRemote & packet)1315 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart(
1316 StringExtractorGDBRemote &packet) {
1317
1318 // Fail if we don't have a current process.
1319 if (!m_current_process ||
1320 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1321 return SendErrorResponse(Status("Process not running."));
1322
1323 packet.ConsumeFront("jLLDBTraceStart:");
1324 Expected<TraceStartRequest> request =
1325 json::parse<TraceStartRequest>(packet.Peek(), "TraceStartRequest");
1326 if (!request)
1327 return SendErrorResponse(request.takeError());
1328
1329 if (Error err = m_current_process->TraceStart(packet.Peek(), request->type))
1330 return SendErrorResponse(std::move(err));
1331
1332 return SendOKResponse();
1333 }
1334
1335 GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceGetState(StringExtractorGDBRemote & packet)1336 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState(
1337 StringExtractorGDBRemote &packet) {
1338
1339 // Fail if we don't have a current process.
1340 if (!m_current_process ||
1341 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1342 return SendErrorResponse(Status("Process not running."));
1343
1344 packet.ConsumeFront("jLLDBTraceGetState:");
1345 Expected<TraceGetStateRequest> request =
1346 json::parse<TraceGetStateRequest>(packet.Peek(), "TraceGetStateRequest");
1347 if (!request)
1348 return SendErrorResponse(request.takeError());
1349
1350 return SendJSONResponse(m_current_process->TraceGetState(request->type));
1351 }
1352
1353 GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceGetBinaryData(StringExtractorGDBRemote & packet)1354 GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData(
1355 StringExtractorGDBRemote &packet) {
1356
1357 // Fail if we don't have a current process.
1358 if (!m_current_process ||
1359 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1360 return SendErrorResponse(Status("Process not running."));
1361
1362 packet.ConsumeFront("jLLDBTraceGetBinaryData:");
1363 llvm::Expected<TraceGetBinaryDataRequest> request =
1364 llvm::json::parse<TraceGetBinaryDataRequest>(packet.Peek(),
1365 "TraceGetBinaryDataRequest");
1366 if (!request)
1367 return SendErrorResponse(Status(request.takeError()));
1368
1369 if (Expected<std::vector<uint8_t>> bytes =
1370 m_current_process->TraceGetBinaryData(*request)) {
1371 StreamGDBRemote response;
1372 response.PutEscapedBytes(bytes->data(), bytes->size());
1373 return SendPacketNoLock(response.GetString());
1374 } else
1375 return SendErrorResponse(bytes.takeError());
1376 }
1377
1378 GDBRemoteCommunication::PacketResult
Handle_qProcessInfo(StringExtractorGDBRemote & packet)1379 GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1380 StringExtractorGDBRemote &packet) {
1381 // Fail if we don't have a current process.
1382 if (!m_current_process ||
1383 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1384 return SendErrorResponse(68);
1385
1386 lldb::pid_t pid = m_current_process->GetID();
1387
1388 if (pid == LLDB_INVALID_PROCESS_ID)
1389 return SendErrorResponse(1);
1390
1391 ProcessInstanceInfo proc_info;
1392 if (!Host::GetProcessInfo(pid, proc_info))
1393 return SendErrorResponse(1);
1394
1395 StreamString response;
1396 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
1397 return SendPacketNoLock(response.GetString());
1398 }
1399
1400 GDBRemoteCommunication::PacketResult
Handle_qC(StringExtractorGDBRemote & packet)1401 GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1402 // Fail if we don't have a current process.
1403 if (!m_current_process ||
1404 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1405 return SendErrorResponse(68);
1406
1407 // Make sure we set the current thread so g and p packets return the data the
1408 // gdb will expect.
1409 lldb::tid_t tid = m_current_process->GetCurrentThreadID();
1410 SetCurrentThreadID(tid);
1411
1412 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
1413 if (!thread)
1414 return SendErrorResponse(69);
1415
1416 StreamString response;
1417 response.PutCString("QC");
1418 AppendThreadIDToResponse(response, m_current_process->GetID(),
1419 thread->GetID());
1420
1421 return SendPacketNoLock(response.GetString());
1422 }
1423
1424 GDBRemoteCommunication::PacketResult
Handle_k(StringExtractorGDBRemote & packet)1425 GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1426 Log *log = GetLog(LLDBLog::Process);
1427
1428 if (!m_non_stop)
1429 StopSTDIOForwarding();
1430
1431 if (m_debugged_processes.empty()) {
1432 LLDB_LOG(log, "No debugged process found.");
1433 return PacketResult::Success;
1434 }
1435
1436 for (auto it = m_debugged_processes.begin(); it != m_debugged_processes.end();
1437 ++it) {
1438 LLDB_LOG(log, "Killing process {0}", it->first);
1439 Status error = it->second.process_up->Kill();
1440 if (error.Fail())
1441 LLDB_LOG(log, "Failed to kill debugged process {0}: {1}", it->first,
1442 error);
1443 }
1444
1445 // The response to kill packet is undefined per the spec. LLDB
1446 // follows the same rules as for continue packets, i.e. no response
1447 // in all-stop mode, and "OK" in non-stop mode; in both cases this
1448 // is followed by the actual stop reason.
1449 return SendContinueSuccessResponse();
1450 }
1451
1452 GDBRemoteCommunication::PacketResult
Handle_vKill(StringExtractorGDBRemote & packet)1453 GDBRemoteCommunicationServerLLGS::Handle_vKill(
1454 StringExtractorGDBRemote &packet) {
1455 if (!m_non_stop)
1456 StopSTDIOForwarding();
1457
1458 packet.SetFilePos(6); // vKill;
1459 uint32_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
1460 if (pid == LLDB_INVALID_PROCESS_ID)
1461 return SendIllFormedResponse(packet,
1462 "vKill failed to parse the process id");
1463
1464 auto it = m_debugged_processes.find(pid);
1465 if (it == m_debugged_processes.end())
1466 return SendErrorResponse(42);
1467
1468 Status error = it->second.process_up->Kill();
1469 if (error.Fail())
1470 return SendErrorResponse(error.ToError());
1471
1472 // OK response is sent when the process dies.
1473 it->second.flags |= DebuggedProcess::Flag::vkilled;
1474 return PacketResult::Success;
1475 }
1476
1477 GDBRemoteCommunication::PacketResult
Handle_QSetDisableASLR(StringExtractorGDBRemote & packet)1478 GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1479 StringExtractorGDBRemote &packet) {
1480 packet.SetFilePos(::strlen("QSetDisableASLR:"));
1481 if (packet.GetU32(0))
1482 m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1483 else
1484 m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1485 return SendOKResponse();
1486 }
1487
1488 GDBRemoteCommunication::PacketResult
Handle_QSetWorkingDir(StringExtractorGDBRemote & packet)1489 GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1490 StringExtractorGDBRemote &packet) {
1491 packet.SetFilePos(::strlen("QSetWorkingDir:"));
1492 std::string path;
1493 packet.GetHexByteString(path);
1494 m_process_launch_info.SetWorkingDirectory(FileSpec(path));
1495 return SendOKResponse();
1496 }
1497
1498 GDBRemoteCommunication::PacketResult
Handle_qGetWorkingDir(StringExtractorGDBRemote & packet)1499 GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1500 StringExtractorGDBRemote &packet) {
1501 FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1502 if (working_dir) {
1503 StreamString response;
1504 response.PutStringAsRawHex8(working_dir.GetPath().c_str());
1505 return SendPacketNoLock(response.GetString());
1506 }
1507
1508 return SendErrorResponse(14);
1509 }
1510
1511 GDBRemoteCommunication::PacketResult
Handle_QThreadSuffixSupported(StringExtractorGDBRemote & packet)1512 GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported(
1513 StringExtractorGDBRemote &packet) {
1514 m_thread_suffix_supported = true;
1515 return SendOKResponse();
1516 }
1517
1518 GDBRemoteCommunication::PacketResult
Handle_QListThreadsInStopReply(StringExtractorGDBRemote & packet)1519 GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply(
1520 StringExtractorGDBRemote &packet) {
1521 m_list_threads_in_stop_reply = true;
1522 return SendOKResponse();
1523 }
1524
1525 GDBRemoteCommunication::PacketResult
ResumeProcess(NativeProcessProtocol & process,const ResumeActionList & actions)1526 GDBRemoteCommunicationServerLLGS::ResumeProcess(
1527 NativeProcessProtocol &process, const ResumeActionList &actions) {
1528 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
1529
1530 // In non-stop protocol mode, the process could be running already.
1531 // We do not support resuming threads independently, so just error out.
1532 if (!process.CanResume()) {
1533 LLDB_LOG(log, "process {0} cannot be resumed (state={1})", process.GetID(),
1534 process.GetState());
1535 return SendErrorResponse(0x37);
1536 }
1537
1538 Status error = process.Resume(actions);
1539 if (error.Fail()) {
1540 LLDB_LOG(log, "process {0} failed to resume: {1}", process.GetID(), error);
1541 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1542 }
1543
1544 LLDB_LOG(log, "process {0} resumed", process.GetID());
1545
1546 return PacketResult::Success;
1547 }
1548
1549 GDBRemoteCommunication::PacketResult
Handle_C(StringExtractorGDBRemote & packet)1550 GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1551 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
1552 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1553
1554 // Ensure we have a native process.
1555 if (!m_continue_process) {
1556 LLDB_LOGF(log,
1557 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1558 "shared pointer",
1559 __FUNCTION__);
1560 return SendErrorResponse(0x36);
1561 }
1562
1563 // Pull out the signal number.
1564 packet.SetFilePos(::strlen("C"));
1565 if (packet.GetBytesLeft() < 1) {
1566 // Shouldn't be using a C without a signal.
1567 return SendIllFormedResponse(packet, "C packet specified without signal.");
1568 }
1569 const uint32_t signo =
1570 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1571 if (signo == std::numeric_limits<uint32_t>::max())
1572 return SendIllFormedResponse(packet, "failed to parse signal number");
1573
1574 // Handle optional continue address.
1575 if (packet.GetBytesLeft() > 0) {
1576 // FIXME add continue at address support for $C{signo}[;{continue-address}].
1577 if (*packet.Peek() == ';')
1578 return SendUnimplementedResponse(packet.GetStringRef().data());
1579 else
1580 return SendIllFormedResponse(
1581 packet, "unexpected content after $C{signal-number}");
1582 }
1583
1584 // In non-stop protocol mode, the process could be running already.
1585 // We do not support resuming threads independently, so just error out.
1586 if (!m_continue_process->CanResume()) {
1587 LLDB_LOG(log, "process cannot be resumed (state={0})",
1588 m_continue_process->GetState());
1589 return SendErrorResponse(0x37);
1590 }
1591
1592 ResumeActionList resume_actions(StateType::eStateRunning,
1593 LLDB_INVALID_SIGNAL_NUMBER);
1594 Status error;
1595
1596 // We have two branches: what to do if a continue thread is specified (in
1597 // which case we target sending the signal to that thread), or when we don't
1598 // have a continue thread set (in which case we send a signal to the
1599 // process).
1600
1601 // TODO discuss with Greg Clayton, make sure this makes sense.
1602
1603 lldb::tid_t signal_tid = GetContinueThreadID();
1604 if (signal_tid != LLDB_INVALID_THREAD_ID) {
1605 // The resume action for the continue thread (or all threads if a continue
1606 // thread is not set).
1607 ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1608 static_cast<int>(signo)};
1609
1610 // Add the action for the continue thread (or all threads when the continue
1611 // thread isn't present).
1612 resume_actions.Append(action);
1613 } else {
1614 // Send the signal to the process since we weren't targeting a specific
1615 // continue thread with the signal.
1616 error = m_continue_process->Signal(signo);
1617 if (error.Fail()) {
1618 LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1619 m_continue_process->GetID(), error);
1620
1621 return SendErrorResponse(0x52);
1622 }
1623 }
1624
1625 // NB: this checks CanResume() twice but using a single code path for
1626 // resuming still seems worth it.
1627 PacketResult resume_res = ResumeProcess(*m_continue_process, resume_actions);
1628 if (resume_res != PacketResult::Success)
1629 return resume_res;
1630
1631 // Don't send an "OK" packet, except in non-stop mode;
1632 // otherwise, the response is the stopped/exited message.
1633 return SendContinueSuccessResponse();
1634 }
1635
1636 GDBRemoteCommunication::PacketResult
Handle_c(StringExtractorGDBRemote & packet)1637 GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1638 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
1639 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1640
1641 packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1642
1643 // For now just support all continue.
1644 const bool has_continue_address = (packet.GetBytesLeft() > 0);
1645 if (has_continue_address) {
1646 LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
1647 packet.Peek());
1648 return SendUnimplementedResponse(packet.GetStringRef().data());
1649 }
1650
1651 // Ensure we have a native process.
1652 if (!m_continue_process) {
1653 LLDB_LOGF(log,
1654 "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1655 "shared pointer",
1656 __FUNCTION__);
1657 return SendErrorResponse(0x36);
1658 }
1659
1660 // Build the ResumeActionList
1661 ResumeActionList actions(StateType::eStateRunning,
1662 LLDB_INVALID_SIGNAL_NUMBER);
1663
1664 PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
1665 if (resume_res != PacketResult::Success)
1666 return resume_res;
1667
1668 return SendContinueSuccessResponse();
1669 }
1670
1671 GDBRemoteCommunication::PacketResult
Handle_vCont_actions(StringExtractorGDBRemote & packet)1672 GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1673 StringExtractorGDBRemote &packet) {
1674 StreamString response;
1675 response.Printf("vCont;c;C;s;S;t");
1676
1677 return SendPacketNoLock(response.GetString());
1678 }
1679
ResumeActionListStopsAllThreads(ResumeActionList & actions)1680 static bool ResumeActionListStopsAllThreads(ResumeActionList &actions) {
1681 // We're doing a stop-all if and only if our only action is a "t" for all
1682 // threads.
1683 if (const ResumeAction *default_action =
1684 actions.GetActionForThread(LLDB_INVALID_THREAD_ID, false)) {
1685 if (default_action->state == eStateSuspended && actions.GetSize() == 1)
1686 return true;
1687 }
1688
1689 return false;
1690 }
1691
1692 GDBRemoteCommunication::PacketResult
Handle_vCont(StringExtractorGDBRemote & packet)1693 GDBRemoteCommunicationServerLLGS::Handle_vCont(
1694 StringExtractorGDBRemote &packet) {
1695 Log *log = GetLog(LLDBLog::Process);
1696 LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1697 __FUNCTION__);
1698
1699 packet.SetFilePos(::strlen("vCont"));
1700
1701 if (packet.GetBytesLeft() == 0) {
1702 LLDB_LOGF(log,
1703 "GDBRemoteCommunicationServerLLGS::%s missing action from "
1704 "vCont package",
1705 __FUNCTION__);
1706 return SendIllFormedResponse(packet, "Missing action from vCont package");
1707 }
1708
1709 if (::strcmp(packet.Peek(), ";s") == 0) {
1710 // Move past the ';', then do a simple 's'.
1711 packet.SetFilePos(packet.GetFilePos() + 1);
1712 return Handle_s(packet);
1713 }
1714
1715 std::unordered_map<lldb::pid_t, ResumeActionList> thread_actions;
1716
1717 while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1718 // Skip the semi-colon.
1719 packet.GetChar();
1720
1721 // Build up the thread action.
1722 ResumeAction thread_action;
1723 thread_action.tid = LLDB_INVALID_THREAD_ID;
1724 thread_action.state = eStateInvalid;
1725 thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;
1726
1727 const char action = packet.GetChar();
1728 switch (action) {
1729 case 'C':
1730 thread_action.signal = packet.GetHexMaxU32(false, 0);
1731 if (thread_action.signal == 0)
1732 return SendIllFormedResponse(
1733 packet, "Could not parse signal in vCont packet C action");
1734 [[fallthrough]];
1735
1736 case 'c':
1737 // Continue
1738 thread_action.state = eStateRunning;
1739 break;
1740
1741 case 'S':
1742 thread_action.signal = packet.GetHexMaxU32(false, 0);
1743 if (thread_action.signal == 0)
1744 return SendIllFormedResponse(
1745 packet, "Could not parse signal in vCont packet S action");
1746 [[fallthrough]];
1747
1748 case 's':
1749 // Step
1750 thread_action.state = eStateStepping;
1751 break;
1752
1753 case 't':
1754 // Stop
1755 thread_action.state = eStateSuspended;
1756 break;
1757
1758 default:
1759 return SendIllFormedResponse(packet, "Unsupported vCont action");
1760 break;
1761 }
1762
1763 // If there's no thread-id (e.g. "vCont;c"), it's "p-1.-1".
1764 lldb::pid_t pid = StringExtractorGDBRemote::AllProcesses;
1765 lldb::tid_t tid = StringExtractorGDBRemote::AllThreads;
1766
1767 // Parse out optional :{thread-id} value.
1768 if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1769 // Consume the separator.
1770 packet.GetChar();
1771
1772 auto pid_tid = packet.GetPidTid(LLDB_INVALID_PROCESS_ID);
1773 if (!pid_tid)
1774 return SendIllFormedResponse(packet, "Malformed thread-id");
1775
1776 pid = pid_tid->first;
1777 tid = pid_tid->second;
1778 }
1779
1780 if (thread_action.state == eStateSuspended &&
1781 tid != StringExtractorGDBRemote::AllThreads) {
1782 return SendIllFormedResponse(
1783 packet, "'t' action not supported for individual threads");
1784 }
1785
1786 // If we get TID without PID, it's the current process.
1787 if (pid == LLDB_INVALID_PROCESS_ID) {
1788 if (!m_continue_process) {
1789 LLDB_LOG(log, "no process selected via Hc");
1790 return SendErrorResponse(0x36);
1791 }
1792 pid = m_continue_process->GetID();
1793 }
1794
1795 assert(pid != LLDB_INVALID_PROCESS_ID);
1796 if (tid == StringExtractorGDBRemote::AllThreads)
1797 tid = LLDB_INVALID_THREAD_ID;
1798 thread_action.tid = tid;
1799
1800 if (pid == StringExtractorGDBRemote::AllProcesses) {
1801 if (tid != LLDB_INVALID_THREAD_ID)
1802 return SendIllFormedResponse(
1803 packet, "vCont: p-1 is not valid with a specific tid");
1804 for (auto &process_it : m_debugged_processes)
1805 thread_actions[process_it.first].Append(thread_action);
1806 } else
1807 thread_actions[pid].Append(thread_action);
1808 }
1809
1810 assert(thread_actions.size() >= 1);
1811 if (thread_actions.size() > 1 && !m_non_stop)
1812 return SendIllFormedResponse(
1813 packet,
1814 "Resuming multiple processes is supported in non-stop mode only");
1815
1816 for (std::pair<lldb::pid_t, ResumeActionList> x : thread_actions) {
1817 auto process_it = m_debugged_processes.find(x.first);
1818 if (process_it == m_debugged_processes.end()) {
1819 LLDB_LOG(log, "vCont failed for process {0}: process not debugged",
1820 x.first);
1821 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1822 }
1823
1824 // There are four possible scenarios here. These are:
1825 // 1. vCont on a stopped process that resumes at least one thread.
1826 // In this case, we call Resume().
1827 // 2. vCont on a stopped process that leaves all threads suspended.
1828 // A no-op.
1829 // 3. vCont on a running process that requests suspending all
1830 // running threads. In this case, we call Interrupt().
1831 // 4. vCont on a running process that requests suspending a subset
1832 // of running threads or resuming a subset of suspended threads.
1833 // Since we do not support full nonstop mode, this is unsupported
1834 // and we return an error.
1835
1836 assert(process_it->second.process_up);
1837 if (ResumeActionListStopsAllThreads(x.second)) {
1838 if (process_it->second.process_up->IsRunning()) {
1839 assert(m_non_stop);
1840
1841 Status error = process_it->second.process_up->Interrupt();
1842 if (error.Fail()) {
1843 LLDB_LOG(log, "vCont failed to halt process {0}: {1}", x.first,
1844 error);
1845 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1846 }
1847
1848 LLDB_LOG(log, "halted process {0}", x.first);
1849
1850 // hack to avoid enabling stdio forwarding after stop
1851 // TODO: remove this when we improve stdio forwarding for nonstop
1852 assert(thread_actions.size() == 1);
1853 return SendOKResponse();
1854 }
1855 } else {
1856 PacketResult resume_res =
1857 ResumeProcess(*process_it->second.process_up, x.second);
1858 if (resume_res != PacketResult::Success)
1859 return resume_res;
1860 }
1861 }
1862
1863 return SendContinueSuccessResponse();
1864 }
1865
SetCurrentThreadID(lldb::tid_t tid)1866 void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1867 Log *log = GetLog(LLDBLog::Thread);
1868 LLDB_LOG(log, "setting current thread id to {0}", tid);
1869
1870 m_current_tid = tid;
1871 if (m_current_process)
1872 m_current_process->SetCurrentThreadID(m_current_tid);
1873 }
1874
SetContinueThreadID(lldb::tid_t tid)1875 void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1876 Log *log = GetLog(LLDBLog::Thread);
1877 LLDB_LOG(log, "setting continue thread id to {0}", tid);
1878
1879 m_continue_tid = tid;
1880 }
1881
1882 GDBRemoteCommunication::PacketResult
Handle_stop_reason(StringExtractorGDBRemote & packet)1883 GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1884 StringExtractorGDBRemote &packet) {
1885 // Handle the $? gdbremote command.
1886
1887 if (m_non_stop) {
1888 // Clear the notification queue first, except for pending exit
1889 // notifications.
1890 llvm::erase_if(m_stop_notification_queue, [](const std::string &x) {
1891 return x.front() != 'W' && x.front() != 'X';
1892 });
1893
1894 if (m_current_process) {
1895 // Queue stop reply packets for all active threads. Start with
1896 // the current thread (for clients that don't actually support multiple
1897 // stop reasons).
1898 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
1899 if (thread) {
1900 StreamString stop_reply = PrepareStopReplyPacketForThread(*thread);
1901 if (!stop_reply.Empty())
1902 m_stop_notification_queue.push_back(stop_reply.GetString().str());
1903 }
1904 EnqueueStopReplyPackets(thread ? thread->GetID()
1905 : LLDB_INVALID_THREAD_ID);
1906 }
1907
1908 // If the notification queue is empty (i.e. everything is running), send OK.
1909 if (m_stop_notification_queue.empty())
1910 return SendOKResponse();
1911
1912 // Send the first item from the new notification queue synchronously.
1913 return SendPacketNoLock(m_stop_notification_queue.front());
1914 }
1915
1916 // If no process, indicate error
1917 if (!m_current_process)
1918 return SendErrorResponse(02);
1919
1920 return SendStopReasonForState(*m_current_process,
1921 m_current_process->GetState(),
1922 /*force_synchronous=*/true);
1923 }
1924
1925 GDBRemoteCommunication::PacketResult
SendStopReasonForState(NativeProcessProtocol & process,lldb::StateType process_state,bool force_synchronous)1926 GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1927 NativeProcessProtocol &process, lldb::StateType process_state,
1928 bool force_synchronous) {
1929 Log *log = GetLog(LLDBLog::Process);
1930
1931 if (m_disabling_non_stop) {
1932 // Check if we are waiting for any more processes to stop. If we are,
1933 // do not send the OK response yet.
1934 for (const auto &it : m_debugged_processes) {
1935 if (it.second.process_up->IsRunning())
1936 return PacketResult::Success;
1937 }
1938
1939 // If all expected processes were stopped after a QNonStop:0 request,
1940 // send the OK response.
1941 m_disabling_non_stop = false;
1942 return SendOKResponse();
1943 }
1944
1945 switch (process_state) {
1946 case eStateAttaching:
1947 case eStateLaunching:
1948 case eStateRunning:
1949 case eStateStepping:
1950 case eStateDetached:
1951 // NOTE: gdb protocol doc looks like it should return $OK
1952 // when everything is running (i.e. no stopped result).
1953 return PacketResult::Success; // Ignore
1954
1955 case eStateSuspended:
1956 case eStateStopped:
1957 case eStateCrashed: {
1958 lldb::tid_t tid = process.GetCurrentThreadID();
1959 // Make sure we set the current thread so g and p packets return the data
1960 // the gdb will expect.
1961 SetCurrentThreadID(tid);
1962 return SendStopReplyPacketForThread(process, tid, force_synchronous);
1963 }
1964
1965 case eStateInvalid:
1966 case eStateUnloaded:
1967 case eStateExited:
1968 return SendWResponse(&process);
1969
1970 default:
1971 LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1972 process.GetID(), process_state);
1973 break;
1974 }
1975
1976 return SendErrorResponse(0);
1977 }
1978
1979 GDBRemoteCommunication::PacketResult
Handle_qRegisterInfo(StringExtractorGDBRemote & packet)1980 GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1981 StringExtractorGDBRemote &packet) {
1982 // Fail if we don't have a current process.
1983 if (!m_current_process ||
1984 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1985 return SendErrorResponse(68);
1986
1987 // Ensure we have a thread.
1988 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
1989 if (!thread)
1990 return SendErrorResponse(69);
1991
1992 // Get the register context for the first thread.
1993 NativeRegisterContext ®_context = thread->GetRegisterContext();
1994
1995 // Parse out the register number from the request.
1996 packet.SetFilePos(strlen("qRegisterInfo"));
1997 const uint32_t reg_index =
1998 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1999 if (reg_index == std::numeric_limits<uint32_t>::max())
2000 return SendErrorResponse(69);
2001
2002 // Return the end of registers response if we've iterated one past the end of
2003 // the register set.
2004 if (reg_index >= reg_context.GetUserRegisterCount())
2005 return SendErrorResponse(69);
2006
2007 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2008 if (!reg_info)
2009 return SendErrorResponse(69);
2010
2011 // Build the reginfos response.
2012 StreamGDBRemote response;
2013
2014 response.PutCString("name:");
2015 response.PutCString(reg_info->name);
2016 response.PutChar(';');
2017
2018 if (reg_info->alt_name && reg_info->alt_name[0]) {
2019 response.PutCString("alt-name:");
2020 response.PutCString(reg_info->alt_name);
2021 response.PutChar(';');
2022 }
2023
2024 response.Printf("bitsize:%" PRIu32 ";", reg_info->byte_size * 8);
2025
2026 if (!reg_context.RegisterOffsetIsDynamic())
2027 response.Printf("offset:%" PRIu32 ";", reg_info->byte_offset);
2028
2029 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
2030 if (!encoding.empty())
2031 response << "encoding:" << encoding << ';';
2032
2033 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
2034 if (!format.empty())
2035 response << "format:" << format << ';';
2036
2037 const char *const register_set_name =
2038 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
2039 if (register_set_name)
2040 response << "set:" << register_set_name << ';';
2041
2042 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
2043 LLDB_INVALID_REGNUM)
2044 response.Printf("ehframe:%" PRIu32 ";",
2045 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
2046
2047 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
2048 response.Printf("dwarf:%" PRIu32 ";",
2049 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
2050
2051 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
2052 if (!kind_generic.empty())
2053 response << "generic:" << kind_generic << ';';
2054
2055 if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
2056 response.PutCString("container-regs:");
2057 CollectRegNums(reg_info->value_regs, response, true);
2058 response.PutChar(';');
2059 }
2060
2061 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
2062 response.PutCString("invalidate-regs:");
2063 CollectRegNums(reg_info->invalidate_regs, response, true);
2064 response.PutChar(';');
2065 }
2066
2067 return SendPacketNoLock(response.GetString());
2068 }
2069
AddProcessThreads(StreamGDBRemote & response,NativeProcessProtocol & process,bool & had_any)2070 void GDBRemoteCommunicationServerLLGS::AddProcessThreads(
2071 StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) {
2072 Log *log = GetLog(LLDBLog::Thread);
2073
2074 lldb::pid_t pid = process.GetID();
2075 if (pid == LLDB_INVALID_PROCESS_ID)
2076 return;
2077
2078 LLDB_LOG(log, "iterating over threads of process {0}", process.GetID());
2079 for (NativeThreadProtocol &thread : process.Threads()) {
2080 LLDB_LOG(log, "iterated thread tid={0}", thread.GetID());
2081 response.PutChar(had_any ? ',' : 'm');
2082 AppendThreadIDToResponse(response, pid, thread.GetID());
2083 had_any = true;
2084 }
2085 }
2086
2087 GDBRemoteCommunication::PacketResult
Handle_qfThreadInfo(StringExtractorGDBRemote & packet)2088 GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
2089 StringExtractorGDBRemote &packet) {
2090 assert(m_debugged_processes.size() == 1 ||
2091 bool(m_extensions_supported &
2092 NativeProcessProtocol::Extension::multiprocess));
2093
2094 bool had_any = false;
2095 StreamGDBRemote response;
2096
2097 for (auto &pid_ptr : m_debugged_processes)
2098 AddProcessThreads(response, *pid_ptr.second.process_up, had_any);
2099
2100 if (!had_any)
2101 return SendOKResponse();
2102 return SendPacketNoLock(response.GetString());
2103 }
2104
2105 GDBRemoteCommunication::PacketResult
Handle_qsThreadInfo(StringExtractorGDBRemote & packet)2106 GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
2107 StringExtractorGDBRemote &packet) {
2108 // FIXME for now we return the full thread list in the initial packet and
2109 // always do nothing here.
2110 return SendPacketNoLock("l");
2111 }
2112
2113 GDBRemoteCommunication::PacketResult
Handle_g(StringExtractorGDBRemote & packet)2114 GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) {
2115 Log *log = GetLog(LLDBLog::Thread);
2116
2117 // Move past packet name.
2118 packet.SetFilePos(strlen("g"));
2119
2120 // Get the thread to use.
2121 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2122 if (!thread) {
2123 LLDB_LOG(log, "failed, no thread available");
2124 return SendErrorResponse(0x15);
2125 }
2126
2127 // Get the thread's register context.
2128 NativeRegisterContext ®_ctx = thread->GetRegisterContext();
2129
2130 std::vector<uint8_t> regs_buffer;
2131 for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
2132 ++reg_num) {
2133 const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
2134
2135 if (reg_info == nullptr) {
2136 LLDB_LOG(log, "failed to get register info for register index {0}",
2137 reg_num);
2138 return SendErrorResponse(0x15);
2139 }
2140
2141 if (reg_info->value_regs != nullptr)
2142 continue; // skip registers that are contained in other registers
2143
2144 RegisterValue reg_value;
2145 Status error = reg_ctx.ReadRegister(reg_info, reg_value);
2146 if (error.Fail()) {
2147 LLDB_LOG(log, "failed to read register at index {0}", reg_num);
2148 return SendErrorResponse(0x15);
2149 }
2150
2151 if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
2152 // Resize the buffer to guarantee it can store the register offsetted
2153 // data.
2154 regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
2155
2156 // Copy the register offsetted data to the buffer.
2157 memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
2158 reg_info->byte_size);
2159 }
2160
2161 // Write the response.
2162 StreamGDBRemote response;
2163 response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
2164
2165 return SendPacketNoLock(response.GetString());
2166 }
2167
2168 GDBRemoteCommunication::PacketResult
Handle_p(StringExtractorGDBRemote & packet)2169 GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
2170 Log *log = GetLog(LLDBLog::Thread);
2171
2172 // Parse out the register number from the request.
2173 packet.SetFilePos(strlen("p"));
2174 const uint32_t reg_index =
2175 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2176 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2177 LLDB_LOGF(log,
2178 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2179 "parse register number from request \"%s\"",
2180 __FUNCTION__, packet.GetStringRef().data());
2181 return SendErrorResponse(0x15);
2182 }
2183
2184 // Get the thread to use.
2185 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2186 if (!thread) {
2187 LLDB_LOG(log, "failed, no thread available");
2188 return SendErrorResponse(0x15);
2189 }
2190
2191 // Get the thread's register context.
2192 NativeRegisterContext ®_context = thread->GetRegisterContext();
2193
2194 // Return the end of registers response if we've iterated one past the end of
2195 // the register set.
2196 if (reg_index >= reg_context.GetUserRegisterCount()) {
2197 LLDB_LOGF(log,
2198 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2199 "register %" PRIu32 " beyond register count %" PRIu32,
2200 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2201 return SendErrorResponse(0x15);
2202 }
2203
2204 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2205 if (!reg_info) {
2206 LLDB_LOGF(log,
2207 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2208 "register %" PRIu32 " returned NULL",
2209 __FUNCTION__, reg_index);
2210 return SendErrorResponse(0x15);
2211 }
2212
2213 // Build the reginfos response.
2214 StreamGDBRemote response;
2215
2216 // Retrieve the value
2217 RegisterValue reg_value;
2218 Status error = reg_context.ReadRegister(reg_info, reg_value);
2219 if (error.Fail()) {
2220 LLDB_LOGF(log,
2221 "GDBRemoteCommunicationServerLLGS::%s failed, read of "
2222 "requested register %" PRIu32 " (%s) failed: %s",
2223 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2224 return SendErrorResponse(0x15);
2225 }
2226
2227 const uint8_t *const data =
2228 static_cast<const uint8_t *>(reg_value.GetBytes());
2229 if (!data) {
2230 LLDB_LOGF(log,
2231 "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2232 "bytes from requested register %" PRIu32,
2233 __FUNCTION__, reg_index);
2234 return SendErrorResponse(0x15);
2235 }
2236
2237 // FIXME flip as needed to get data in big/little endian format for this host.
2238 for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2239 response.PutHex8(data[i]);
2240
2241 return SendPacketNoLock(response.GetString());
2242 }
2243
2244 GDBRemoteCommunication::PacketResult
Handle_P(StringExtractorGDBRemote & packet)2245 GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2246 Log *log = GetLog(LLDBLog::Thread);
2247
2248 // Ensure there is more content.
2249 if (packet.GetBytesLeft() < 1)
2250 return SendIllFormedResponse(packet, "Empty P packet");
2251
2252 // Parse out the register number from the request.
2253 packet.SetFilePos(strlen("P"));
2254 const uint32_t reg_index =
2255 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2256 if (reg_index == std::numeric_limits<uint32_t>::max()) {
2257 LLDB_LOGF(log,
2258 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2259 "parse register number from request \"%s\"",
2260 __FUNCTION__, packet.GetStringRef().data());
2261 return SendErrorResponse(0x29);
2262 }
2263
2264 // Note debugserver would send an E30 here.
2265 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2266 return SendIllFormedResponse(
2267 packet, "P packet missing '=' char after register number");
2268
2269 // Parse out the value.
2270 uint8_t reg_bytes[RegisterValue::kMaxRegisterByteSize];
2271 size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2272
2273 // Get the thread to use.
2274 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2275 if (!thread) {
2276 LLDB_LOGF(log,
2277 "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2278 "available (thread index 0)",
2279 __FUNCTION__);
2280 return SendErrorResponse(0x28);
2281 }
2282
2283 // Get the thread's register context.
2284 NativeRegisterContext ®_context = thread->GetRegisterContext();
2285 const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2286 if (!reg_info) {
2287 LLDB_LOGF(log,
2288 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2289 "register %" PRIu32 " returned NULL",
2290 __FUNCTION__, reg_index);
2291 return SendErrorResponse(0x48);
2292 }
2293
2294 // Return the end of registers response if we've iterated one past the end of
2295 // the register set.
2296 if (reg_index >= reg_context.GetUserRegisterCount()) {
2297 LLDB_LOGF(log,
2298 "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2299 "register %" PRIu32 " beyond register count %" PRIu32,
2300 __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2301 return SendErrorResponse(0x47);
2302 }
2303
2304 if (reg_size != reg_info->byte_size)
2305 return SendIllFormedResponse(packet, "P packet register size is incorrect");
2306
2307 // Build the reginfos response.
2308 StreamGDBRemote response;
2309
2310 RegisterValue reg_value(ArrayRef(reg_bytes, reg_size),
2311 m_current_process->GetArchitecture().GetByteOrder());
2312 Status error = reg_context.WriteRegister(reg_info, reg_value);
2313 if (error.Fail()) {
2314 LLDB_LOGF(log,
2315 "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2316 "requested register %" PRIu32 " (%s) failed: %s",
2317 __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2318 return SendErrorResponse(0x32);
2319 }
2320
2321 return SendOKResponse();
2322 }
2323
2324 GDBRemoteCommunication::PacketResult
Handle_H(StringExtractorGDBRemote & packet)2325 GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2326 Log *log = GetLog(LLDBLog::Thread);
2327
2328 // Parse out which variant of $H is requested.
2329 packet.SetFilePos(strlen("H"));
2330 if (packet.GetBytesLeft() < 1) {
2331 LLDB_LOGF(log,
2332 "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2333 "missing {g,c} variant",
2334 __FUNCTION__);
2335 return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2336 }
2337
2338 const char h_variant = packet.GetChar();
2339 NativeProcessProtocol *default_process;
2340 switch (h_variant) {
2341 case 'g':
2342 default_process = m_current_process;
2343 break;
2344
2345 case 'c':
2346 default_process = m_continue_process;
2347 break;
2348
2349 default:
2350 LLDB_LOGF(
2351 log,
2352 "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2353 __FUNCTION__, h_variant);
2354 return SendIllFormedResponse(packet,
2355 "H variant unsupported, should be c or g");
2356 }
2357
2358 // Parse out the thread number.
2359 auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID()
2360 : LLDB_INVALID_PROCESS_ID);
2361 if (!pid_tid)
2362 return SendErrorResponse(llvm::make_error<StringError>(
2363 inconvertibleErrorCode(), "Malformed thread-id"));
2364
2365 lldb::pid_t pid = pid_tid->first;
2366 lldb::tid_t tid = pid_tid->second;
2367
2368 if (pid == StringExtractorGDBRemote::AllProcesses)
2369 return SendUnimplementedResponse("Selecting all processes not supported");
2370 if (pid == LLDB_INVALID_PROCESS_ID)
2371 return SendErrorResponse(llvm::make_error<StringError>(
2372 inconvertibleErrorCode(), "No current process and no PID provided"));
2373
2374 // Check the process ID and find respective process instance.
2375 auto new_process_it = m_debugged_processes.find(pid);
2376 if (new_process_it == m_debugged_processes.end())
2377 return SendErrorResponse(llvm::make_error<StringError>(
2378 inconvertibleErrorCode(),
2379 llvm::formatv("No process with PID {0} debugged", pid)));
2380
2381 // Ensure we have the given thread when not specifying -1 (all threads) or 0
2382 // (any thread).
2383 if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2384 NativeThreadProtocol *thread =
2385 new_process_it->second.process_up->GetThreadByID(tid);
2386 if (!thread) {
2387 LLDB_LOGF(log,
2388 "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2389 " not found",
2390 __FUNCTION__, tid);
2391 return SendErrorResponse(0x15);
2392 }
2393 }
2394
2395 // Now switch the given process and thread type.
2396 switch (h_variant) {
2397 case 'g':
2398 m_current_process = new_process_it->second.process_up.get();
2399 SetCurrentThreadID(tid);
2400 break;
2401
2402 case 'c':
2403 m_continue_process = new_process_it->second.process_up.get();
2404 SetContinueThreadID(tid);
2405 break;
2406
2407 default:
2408 assert(false && "unsupported $H variant - shouldn't get here");
2409 return SendIllFormedResponse(packet,
2410 "H variant unsupported, should be c or g");
2411 }
2412
2413 return SendOKResponse();
2414 }
2415
2416 GDBRemoteCommunication::PacketResult
Handle_I(StringExtractorGDBRemote & packet)2417 GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2418 Log *log = GetLog(LLDBLog::Thread);
2419
2420 // Fail if we don't have a current process.
2421 if (!m_current_process ||
2422 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2423 LLDB_LOGF(
2424 log,
2425 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2426 __FUNCTION__);
2427 return SendErrorResponse(0x15);
2428 }
2429
2430 packet.SetFilePos(::strlen("I"));
2431 uint8_t tmp[4096];
2432 for (;;) {
2433 size_t read = packet.GetHexBytesAvail(tmp);
2434 if (read == 0) {
2435 break;
2436 }
2437 // write directly to stdin *this might block if stdin buffer is full*
2438 // TODO: enqueue this block in circular buffer and send window size to
2439 // remote host
2440 ConnectionStatus status;
2441 Status error;
2442 m_stdio_communication.WriteAll(tmp, read, status, &error);
2443 if (error.Fail()) {
2444 return SendErrorResponse(0x15);
2445 }
2446 }
2447
2448 return SendOKResponse();
2449 }
2450
2451 GDBRemoteCommunication::PacketResult
Handle_interrupt(StringExtractorGDBRemote & packet)2452 GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2453 StringExtractorGDBRemote &packet) {
2454 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
2455
2456 // Fail if we don't have a current process.
2457 if (!m_current_process ||
2458 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2459 LLDB_LOG(log, "failed, no process available");
2460 return SendErrorResponse(0x15);
2461 }
2462
2463 // Interrupt the process.
2464 Status error = m_current_process->Interrupt();
2465 if (error.Fail()) {
2466 LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(),
2467 error);
2468 return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2469 }
2470
2471 LLDB_LOG(log, "stopped process {0}", m_current_process->GetID());
2472
2473 // No response required from stop all.
2474 return PacketResult::Success;
2475 }
2476
2477 GDBRemoteCommunication::PacketResult
Handle_memory_read(StringExtractorGDBRemote & packet)2478 GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2479 StringExtractorGDBRemote &packet) {
2480 Log *log = GetLog(LLDBLog::Process);
2481
2482 if (!m_current_process ||
2483 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2484 LLDB_LOGF(
2485 log,
2486 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2487 __FUNCTION__);
2488 return SendErrorResponse(0x15);
2489 }
2490
2491 // Parse out the memory address.
2492 packet.SetFilePos(strlen("m"));
2493 if (packet.GetBytesLeft() < 1)
2494 return SendIllFormedResponse(packet, "Too short m packet");
2495
2496 // Read the address. Punting on validation.
2497 // FIXME replace with Hex U64 read with no default value that fails on failed
2498 // read.
2499 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2500
2501 // Validate comma.
2502 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2503 return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2504
2505 // Get # bytes to read.
2506 if (packet.GetBytesLeft() < 1)
2507 return SendIllFormedResponse(packet, "Length missing in m packet");
2508
2509 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2510 if (byte_count == 0) {
2511 LLDB_LOGF(log,
2512 "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2513 "zero-length packet",
2514 __FUNCTION__);
2515 return SendOKResponse();
2516 }
2517
2518 // Allocate the response buffer.
2519 std::string buf(byte_count, '\0');
2520 if (buf.empty())
2521 return SendErrorResponse(0x78);
2522
2523 // Retrieve the process memory.
2524 size_t bytes_read = 0;
2525 Status error = m_current_process->ReadMemoryWithoutTrap(
2526 read_addr, &buf[0], byte_count, bytes_read);
2527 if (error.Fail()) {
2528 LLDB_LOGF(log,
2529 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2530 " mem 0x%" PRIx64 ": failed to read. Error: %s",
2531 __FUNCTION__, m_current_process->GetID(), read_addr,
2532 error.AsCString());
2533 return SendErrorResponse(0x08);
2534 }
2535
2536 if (bytes_read == 0) {
2537 LLDB_LOGF(log,
2538 "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2539 " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2540 __FUNCTION__, m_current_process->GetID(), read_addr, byte_count);
2541 return SendErrorResponse(0x08);
2542 }
2543
2544 StreamGDBRemote response;
2545 packet.SetFilePos(0);
2546 char kind = packet.GetChar('?');
2547 if (kind == 'x')
2548 response.PutEscapedBytes(buf.data(), byte_count);
2549 else {
2550 assert(kind == 'm');
2551 for (size_t i = 0; i < bytes_read; ++i)
2552 response.PutHex8(buf[i]);
2553 }
2554
2555 return SendPacketNoLock(response.GetString());
2556 }
2557
2558 GDBRemoteCommunication::PacketResult
Handle__M(StringExtractorGDBRemote & packet)2559 GDBRemoteCommunicationServerLLGS::Handle__M(StringExtractorGDBRemote &packet) {
2560 Log *log = GetLog(LLDBLog::Process);
2561
2562 if (!m_current_process ||
2563 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2564 LLDB_LOGF(
2565 log,
2566 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2567 __FUNCTION__);
2568 return SendErrorResponse(0x15);
2569 }
2570
2571 // Parse out the memory address.
2572 packet.SetFilePos(strlen("_M"));
2573 if (packet.GetBytesLeft() < 1)
2574 return SendIllFormedResponse(packet, "Too short _M packet");
2575
2576 const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2577 if (size == LLDB_INVALID_ADDRESS)
2578 return SendIllFormedResponse(packet, "Address not valid");
2579 if (packet.GetChar() != ',')
2580 return SendIllFormedResponse(packet, "Bad packet");
2581 Permissions perms = {};
2582 while (packet.GetBytesLeft() > 0) {
2583 switch (packet.GetChar()) {
2584 case 'r':
2585 perms |= ePermissionsReadable;
2586 break;
2587 case 'w':
2588 perms |= ePermissionsWritable;
2589 break;
2590 case 'x':
2591 perms |= ePermissionsExecutable;
2592 break;
2593 default:
2594 return SendIllFormedResponse(packet, "Bad permissions");
2595 }
2596 }
2597
2598 llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms);
2599 if (!addr)
2600 return SendErrorResponse(addr.takeError());
2601
2602 StreamGDBRemote response;
2603 response.PutHex64(*addr);
2604 return SendPacketNoLock(response.GetString());
2605 }
2606
2607 GDBRemoteCommunication::PacketResult
Handle__m(StringExtractorGDBRemote & packet)2608 GDBRemoteCommunicationServerLLGS::Handle__m(StringExtractorGDBRemote &packet) {
2609 Log *log = GetLog(LLDBLog::Process);
2610
2611 if (!m_current_process ||
2612 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2613 LLDB_LOGF(
2614 log,
2615 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2616 __FUNCTION__);
2617 return SendErrorResponse(0x15);
2618 }
2619
2620 // Parse out the memory address.
2621 packet.SetFilePos(strlen("_m"));
2622 if (packet.GetBytesLeft() < 1)
2623 return SendIllFormedResponse(packet, "Too short m packet");
2624
2625 const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2626 if (addr == LLDB_INVALID_ADDRESS)
2627 return SendIllFormedResponse(packet, "Address not valid");
2628
2629 if (llvm::Error Err = m_current_process->DeallocateMemory(addr))
2630 return SendErrorResponse(std::move(Err));
2631
2632 return SendOKResponse();
2633 }
2634
2635 GDBRemoteCommunication::PacketResult
Handle_M(StringExtractorGDBRemote & packet)2636 GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2637 Log *log = GetLog(LLDBLog::Process);
2638
2639 if (!m_current_process ||
2640 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2641 LLDB_LOGF(
2642 log,
2643 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2644 __FUNCTION__);
2645 return SendErrorResponse(0x15);
2646 }
2647
2648 // Parse out the memory address.
2649 packet.SetFilePos(strlen("M"));
2650 if (packet.GetBytesLeft() < 1)
2651 return SendIllFormedResponse(packet, "Too short M packet");
2652
2653 // Read the address. Punting on validation.
2654 // FIXME replace with Hex U64 read with no default value that fails on failed
2655 // read.
2656 const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2657
2658 // Validate comma.
2659 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2660 return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2661
2662 // Get # bytes to read.
2663 if (packet.GetBytesLeft() < 1)
2664 return SendIllFormedResponse(packet, "Length missing in M packet");
2665
2666 const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2667 if (byte_count == 0) {
2668 LLDB_LOG(log, "nothing to write: zero-length packet");
2669 return PacketResult::Success;
2670 }
2671
2672 // Validate colon.
2673 if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2674 return SendIllFormedResponse(
2675 packet, "Comma sep missing in M packet after byte length");
2676
2677 // Allocate the conversion buffer.
2678 std::vector<uint8_t> buf(byte_count, 0);
2679 if (buf.empty())
2680 return SendErrorResponse(0x78);
2681
2682 // Convert the hex memory write contents to bytes.
2683 StreamGDBRemote response;
2684 const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2685 if (convert_count != byte_count) {
2686 LLDB_LOG(log,
2687 "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
2688 "to convert.",
2689 m_current_process->GetID(), write_addr, byte_count, convert_count);
2690 return SendIllFormedResponse(packet, "M content byte length specified did "
2691 "not match hex-encoded content "
2692 "length");
2693 }
2694
2695 // Write the process memory.
2696 size_t bytes_written = 0;
2697 Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count,
2698 bytes_written);
2699 if (error.Fail()) {
2700 LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2701 m_current_process->GetID(), write_addr, error);
2702 return SendErrorResponse(0x09);
2703 }
2704
2705 if (bytes_written == 0) {
2706 LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2707 m_current_process->GetID(), write_addr, byte_count);
2708 return SendErrorResponse(0x09);
2709 }
2710
2711 return SendOKResponse();
2712 }
2713
2714 GDBRemoteCommunication::PacketResult
Handle_qMemoryRegionInfoSupported(StringExtractorGDBRemote & packet)2715 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2716 StringExtractorGDBRemote &packet) {
2717 Log *log = GetLog(LLDBLog::Process);
2718
2719 // Currently only the NativeProcessProtocol knows if it can handle a
2720 // qMemoryRegionInfoSupported request, but we're not guaranteed to be
2721 // attached to a process. For now we'll assume the client only asks this
2722 // when a process is being debugged.
2723
2724 // Ensure we have a process running; otherwise, we can't figure this out
2725 // since we won't have a NativeProcessProtocol.
2726 if (!m_current_process ||
2727 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2728 LLDB_LOGF(
2729 log,
2730 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2731 __FUNCTION__);
2732 return SendErrorResponse(0x15);
2733 }
2734
2735 // Test if we can get any region back when asking for the region around NULL.
2736 MemoryRegionInfo region_info;
2737 const Status error = m_current_process->GetMemoryRegionInfo(0, region_info);
2738 if (error.Fail()) {
2739 // We don't support memory region info collection for this
2740 // NativeProcessProtocol.
2741 return SendUnimplementedResponse("");
2742 }
2743
2744 return SendOKResponse();
2745 }
2746
2747 GDBRemoteCommunication::PacketResult
Handle_qMemoryRegionInfo(StringExtractorGDBRemote & packet)2748 GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2749 StringExtractorGDBRemote &packet) {
2750 Log *log = GetLog(LLDBLog::Process);
2751
2752 // Ensure we have a process.
2753 if (!m_current_process ||
2754 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2755 LLDB_LOGF(
2756 log,
2757 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2758 __FUNCTION__);
2759 return SendErrorResponse(0x15);
2760 }
2761
2762 // Parse out the memory address.
2763 packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2764 if (packet.GetBytesLeft() < 1)
2765 return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2766
2767 // Read the address. Punting on validation.
2768 const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2769
2770 StreamGDBRemote response;
2771
2772 // Get the memory region info for the target address.
2773 MemoryRegionInfo region_info;
2774 const Status error =
2775 m_current_process->GetMemoryRegionInfo(read_addr, region_info);
2776 if (error.Fail()) {
2777 // Return the error message.
2778
2779 response.PutCString("error:");
2780 response.PutStringAsRawHex8(error.AsCString());
2781 response.PutChar(';');
2782 } else {
2783 // Range start and size.
2784 response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2785 region_info.GetRange().GetRangeBase(),
2786 region_info.GetRange().GetByteSize());
2787
2788 // Permissions.
2789 if (region_info.GetReadable() || region_info.GetWritable() ||
2790 region_info.GetExecutable()) {
2791 // Write permissions info.
2792 response.PutCString("permissions:");
2793
2794 if (region_info.GetReadable())
2795 response.PutChar('r');
2796 if (region_info.GetWritable())
2797 response.PutChar('w');
2798 if (region_info.GetExecutable())
2799 response.PutChar('x');
2800
2801 response.PutChar(';');
2802 }
2803
2804 // Flags
2805 MemoryRegionInfo::OptionalBool memory_tagged =
2806 region_info.GetMemoryTagged();
2807 if (memory_tagged != MemoryRegionInfo::eDontKnow) {
2808 response.PutCString("flags:");
2809 if (memory_tagged == MemoryRegionInfo::eYes) {
2810 response.PutCString("mt");
2811 }
2812 response.PutChar(';');
2813 }
2814
2815 // Name
2816 ConstString name = region_info.GetName();
2817 if (name) {
2818 response.PutCString("name:");
2819 response.PutStringAsRawHex8(name.GetStringRef());
2820 response.PutChar(';');
2821 }
2822 }
2823
2824 return SendPacketNoLock(response.GetString());
2825 }
2826
2827 GDBRemoteCommunication::PacketResult
Handle_Z(StringExtractorGDBRemote & packet)2828 GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2829 // Ensure we have a process.
2830 if (!m_current_process ||
2831 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2832 Log *log = GetLog(LLDBLog::Process);
2833 LLDB_LOG(log, "failed, no process available");
2834 return SendErrorResponse(0x15);
2835 }
2836
2837 // Parse out software or hardware breakpoint or watchpoint requested.
2838 packet.SetFilePos(strlen("Z"));
2839 if (packet.GetBytesLeft() < 1)
2840 return SendIllFormedResponse(
2841 packet, "Too short Z packet, missing software/hardware specifier");
2842
2843 bool want_breakpoint = true;
2844 bool want_hardware = false;
2845 uint32_t watch_flags = 0;
2846
2847 const GDBStoppointType stoppoint_type =
2848 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2849 switch (stoppoint_type) {
2850 case eBreakpointSoftware:
2851 want_hardware = false;
2852 want_breakpoint = true;
2853 break;
2854 case eBreakpointHardware:
2855 want_hardware = true;
2856 want_breakpoint = true;
2857 break;
2858 case eWatchpointWrite:
2859 watch_flags = 1;
2860 want_hardware = true;
2861 want_breakpoint = false;
2862 break;
2863 case eWatchpointRead:
2864 watch_flags = 2;
2865 want_hardware = true;
2866 want_breakpoint = false;
2867 break;
2868 case eWatchpointReadWrite:
2869 watch_flags = 3;
2870 want_hardware = true;
2871 want_breakpoint = false;
2872 break;
2873 case eStoppointInvalid:
2874 return SendIllFormedResponse(
2875 packet, "Z packet had invalid software/hardware specifier");
2876 }
2877
2878 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2879 return SendIllFormedResponse(
2880 packet, "Malformed Z packet, expecting comma after stoppoint type");
2881
2882 // Parse out the stoppoint address.
2883 if (packet.GetBytesLeft() < 1)
2884 return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2885 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2886
2887 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2888 return SendIllFormedResponse(
2889 packet, "Malformed Z packet, expecting comma after address");
2890
2891 // Parse out the stoppoint size (i.e. size hint for opcode size).
2892 const uint32_t size =
2893 packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2894 if (size == std::numeric_limits<uint32_t>::max())
2895 return SendIllFormedResponse(
2896 packet, "Malformed Z packet, failed to parse size argument");
2897
2898 if (want_breakpoint) {
2899 // Try to set the breakpoint.
2900 const Status error =
2901 m_current_process->SetBreakpoint(addr, size, want_hardware);
2902 if (error.Success())
2903 return SendOKResponse();
2904 Log *log = GetLog(LLDBLog::Breakpoints);
2905 LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2906 m_current_process->GetID(), error);
2907 return SendErrorResponse(0x09);
2908 } else {
2909 // Try to set the watchpoint.
2910 const Status error = m_current_process->SetWatchpoint(
2911 addr, size, watch_flags, want_hardware);
2912 if (error.Success())
2913 return SendOKResponse();
2914 Log *log = GetLog(LLDBLog::Watchpoints);
2915 LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2916 m_current_process->GetID(), error);
2917 return SendErrorResponse(0x09);
2918 }
2919 }
2920
2921 GDBRemoteCommunication::PacketResult
Handle_z(StringExtractorGDBRemote & packet)2922 GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2923 // Ensure we have a process.
2924 if (!m_current_process ||
2925 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2926 Log *log = GetLog(LLDBLog::Process);
2927 LLDB_LOG(log, "failed, no process available");
2928 return SendErrorResponse(0x15);
2929 }
2930
2931 // Parse out software or hardware breakpoint or watchpoint requested.
2932 packet.SetFilePos(strlen("z"));
2933 if (packet.GetBytesLeft() < 1)
2934 return SendIllFormedResponse(
2935 packet, "Too short z packet, missing software/hardware specifier");
2936
2937 bool want_breakpoint = true;
2938 bool want_hardware = false;
2939
2940 const GDBStoppointType stoppoint_type =
2941 GDBStoppointType(packet.GetS32(eStoppointInvalid));
2942 switch (stoppoint_type) {
2943 case eBreakpointHardware:
2944 want_breakpoint = true;
2945 want_hardware = true;
2946 break;
2947 case eBreakpointSoftware:
2948 want_breakpoint = true;
2949 break;
2950 case eWatchpointWrite:
2951 want_breakpoint = false;
2952 break;
2953 case eWatchpointRead:
2954 want_breakpoint = false;
2955 break;
2956 case eWatchpointReadWrite:
2957 want_breakpoint = false;
2958 break;
2959 default:
2960 return SendIllFormedResponse(
2961 packet, "z packet had invalid software/hardware specifier");
2962 }
2963
2964 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2965 return SendIllFormedResponse(
2966 packet, "Malformed z packet, expecting comma after stoppoint type");
2967
2968 // Parse out the stoppoint address.
2969 if (packet.GetBytesLeft() < 1)
2970 return SendIllFormedResponse(packet, "Too short z packet, missing address");
2971 const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2972
2973 if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2974 return SendIllFormedResponse(
2975 packet, "Malformed z packet, expecting comma after address");
2976
2977 /*
2978 // Parse out the stoppoint size (i.e. size hint for opcode size).
2979 const uint32_t size = packet.GetHexMaxU32 (false,
2980 std::numeric_limits<uint32_t>::max ());
2981 if (size == std::numeric_limits<uint32_t>::max ())
2982 return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2983 size argument");
2984 */
2985
2986 if (want_breakpoint) {
2987 // Try to clear the breakpoint.
2988 const Status error =
2989 m_current_process->RemoveBreakpoint(addr, want_hardware);
2990 if (error.Success())
2991 return SendOKResponse();
2992 Log *log = GetLog(LLDBLog::Breakpoints);
2993 LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2994 m_current_process->GetID(), error);
2995 return SendErrorResponse(0x09);
2996 } else {
2997 // Try to clear the watchpoint.
2998 const Status error = m_current_process->RemoveWatchpoint(addr);
2999 if (error.Success())
3000 return SendOKResponse();
3001 Log *log = GetLog(LLDBLog::Watchpoints);
3002 LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
3003 m_current_process->GetID(), error);
3004 return SendErrorResponse(0x09);
3005 }
3006 }
3007
3008 GDBRemoteCommunication::PacketResult
Handle_s(StringExtractorGDBRemote & packet)3009 GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
3010 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
3011
3012 // Ensure we have a process.
3013 if (!m_continue_process ||
3014 (m_continue_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3015 LLDB_LOGF(
3016 log,
3017 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3018 __FUNCTION__);
3019 return SendErrorResponse(0x32);
3020 }
3021
3022 // We first try to use a continue thread id. If any one or any all set, use
3023 // the current thread. Bail out if we don't have a thread id.
3024 lldb::tid_t tid = GetContinueThreadID();
3025 if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3026 tid = GetCurrentThreadID();
3027 if (tid == LLDB_INVALID_THREAD_ID)
3028 return SendErrorResponse(0x33);
3029
3030 // Double check that we have such a thread.
3031 // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3032 NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid);
3033 if (!thread)
3034 return SendErrorResponse(0x33);
3035
3036 // Create the step action for the given thread.
3037 ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER};
3038
3039 // Setup the actions list.
3040 ResumeActionList actions;
3041 actions.Append(action);
3042
3043 // All other threads stop while we're single stepping a thread.
3044 actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
3045
3046 PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
3047 if (resume_res != PacketResult::Success)
3048 return resume_res;
3049
3050 // No response here, unless in non-stop mode.
3051 // Otherwise, the stop or exit will come from the resulting action.
3052 return SendContinueSuccessResponse();
3053 }
3054
3055 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
BuildTargetXml()3056 GDBRemoteCommunicationServerLLGS::BuildTargetXml() {
3057 // Ensure we have a thread.
3058 NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
3059 if (!thread)
3060 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3061 "No thread available");
3062
3063 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
3064 // Get the register context for the first thread.
3065 NativeRegisterContext ®_context = thread->GetRegisterContext();
3066
3067 StreamString response;
3068
3069 response.Printf("<?xml version=\"1.0\"?>\n");
3070 response.Printf("<target version=\"1.0\">\n");
3071 response.IndentMore();
3072
3073 response.Indent();
3074 response.Printf("<architecture>%s</architecture>\n",
3075 m_current_process->GetArchitecture()
3076 .GetTriple()
3077 .getArchName()
3078 .str()
3079 .c_str());
3080
3081 response.Indent("<feature>\n");
3082
3083 const int registers_count = reg_context.GetUserRegisterCount();
3084 if (registers_count)
3085 response.IndentMore();
3086
3087 for (int reg_index = 0; reg_index < registers_count; reg_index++) {
3088 const RegisterInfo *reg_info =
3089 reg_context.GetRegisterInfoAtIndex(reg_index);
3090
3091 if (!reg_info) {
3092 LLDB_LOGF(log,
3093 "%s failed to get register info for register index %" PRIu32,
3094 "target.xml", reg_index);
3095 continue;
3096 }
3097
3098 response.Indent();
3099 response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32
3100 "\" regnum=\"%d\" ",
3101 reg_info->name, reg_info->byte_size * 8, reg_index);
3102
3103 if (!reg_context.RegisterOffsetIsDynamic())
3104 response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset);
3105
3106 if (reg_info->alt_name && reg_info->alt_name[0])
3107 response.Printf("altname=\"%s\" ", reg_info->alt_name);
3108
3109 llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
3110 if (!encoding.empty())
3111 response << "encoding=\"" << encoding << "\" ";
3112
3113 llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
3114 if (!format.empty())
3115 response << "format=\"" << format << "\" ";
3116
3117 const char *const register_set_name =
3118 reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
3119 if (register_set_name)
3120 response << "group=\"" << register_set_name << "\" ";
3121
3122 if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
3123 LLDB_INVALID_REGNUM)
3124 response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",
3125 reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
3126
3127 if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=
3128 LLDB_INVALID_REGNUM)
3129 response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",
3130 reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3131
3132 llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
3133 if (!kind_generic.empty())
3134 response << "generic=\"" << kind_generic << "\" ";
3135
3136 if (reg_info->value_regs &&
3137 reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
3138 response.PutCString("value_regnums=\"");
3139 CollectRegNums(reg_info->value_regs, response, false);
3140 response.Printf("\" ");
3141 }
3142
3143 if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
3144 response.PutCString("invalidate_regnums=\"");
3145 CollectRegNums(reg_info->invalidate_regs, response, false);
3146 response.Printf("\" ");
3147 }
3148
3149 response.Printf("/>\n");
3150 }
3151
3152 if (registers_count)
3153 response.IndentLess();
3154
3155 response.Indent("</feature>\n");
3156 response.IndentLess();
3157 response.Indent("</target>\n");
3158 return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");
3159 }
3160
3161 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
ReadXferObject(llvm::StringRef object,llvm::StringRef annex)3162 GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object,
3163 llvm::StringRef annex) {
3164 // Make sure we have a valid process.
3165 if (!m_current_process ||
3166 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3167 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3168 "No process available");
3169 }
3170
3171 if (object == "auxv") {
3172 // Grab the auxv data.
3173 auto buffer_or_error = m_current_process->GetAuxvData();
3174 if (!buffer_or_error)
3175 return llvm::errorCodeToError(buffer_or_error.getError());
3176 return std::move(*buffer_or_error);
3177 }
3178
3179 if (object == "siginfo") {
3180 NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
3181 if (!thread)
3182 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3183 "no current thread");
3184
3185 auto buffer_or_error = thread->GetSiginfo();
3186 if (!buffer_or_error)
3187 return buffer_or_error.takeError();
3188 return std::move(*buffer_or_error);
3189 }
3190
3191 if (object == "libraries-svr4") {
3192 auto library_list = m_current_process->GetLoadedSVR4Libraries();
3193 if (!library_list)
3194 return library_list.takeError();
3195
3196 StreamString response;
3197 response.Printf("<library-list-svr4 version=\"1.0\">");
3198 for (auto const &library : *library_list) {
3199 response.Printf("<library name=\"%s\" ",
3200 XMLEncodeAttributeValue(library.name.c_str()).c_str());
3201 response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
3202 response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
3203 response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
3204 }
3205 response.Printf("</library-list-svr4>");
3206 return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
3207 }
3208
3209 if (object == "features" && annex == "target.xml")
3210 return BuildTargetXml();
3211
3212 return llvm::make_error<UnimplementedError>();
3213 }
3214
3215 GDBRemoteCommunication::PacketResult
Handle_qXfer(StringExtractorGDBRemote & packet)3216 GDBRemoteCommunicationServerLLGS::Handle_qXfer(
3217 StringExtractorGDBRemote &packet) {
3218 SmallVector<StringRef, 5> fields;
3219 // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
3220 StringRef(packet.GetStringRef()).split(fields, ':', 4);
3221 if (fields.size() != 5)
3222 return SendIllFormedResponse(packet, "malformed qXfer packet");
3223 StringRef &xfer_object = fields[1];
3224 StringRef &xfer_action = fields[2];
3225 StringRef &xfer_annex = fields[3];
3226 StringExtractor offset_data(fields[4]);
3227 if (xfer_action != "read")
3228 return SendUnimplementedResponse("qXfer action not supported");
3229 // Parse offset.
3230 const uint64_t xfer_offset =
3231 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3232 if (xfer_offset == std::numeric_limits<uint64_t>::max())
3233 return SendIllFormedResponse(packet, "qXfer packet missing offset");
3234 // Parse out comma.
3235 if (offset_data.GetChar() != ',')
3236 return SendIllFormedResponse(packet,
3237 "qXfer packet missing comma after offset");
3238 // Parse out the length.
3239 const uint64_t xfer_length =
3240 offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
3241 if (xfer_length == std::numeric_limits<uint64_t>::max())
3242 return SendIllFormedResponse(packet, "qXfer packet missing length");
3243
3244 // Get a previously constructed buffer if it exists or create it now.
3245 std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
3246 auto buffer_it = m_xfer_buffer_map.find(buffer_key);
3247 if (buffer_it == m_xfer_buffer_map.end()) {
3248 auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
3249 if (!buffer_up)
3250 return SendErrorResponse(buffer_up.takeError());
3251 buffer_it = m_xfer_buffer_map
3252 .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
3253 .first;
3254 }
3255
3256 // Send back the response
3257 StreamGDBRemote response;
3258 bool done_with_buffer = false;
3259 llvm::StringRef buffer = buffer_it->second->getBuffer();
3260 if (xfer_offset >= buffer.size()) {
3261 // We have nothing left to send. Mark the buffer as complete.
3262 response.PutChar('l');
3263 done_with_buffer = true;
3264 } else {
3265 // Figure out how many bytes are available starting at the given offset.
3266 buffer = buffer.drop_front(xfer_offset);
3267 // Mark the response type according to whether we're reading the remainder
3268 // of the data.
3269 if (xfer_length >= buffer.size()) {
3270 // There will be nothing left to read after this
3271 response.PutChar('l');
3272 done_with_buffer = true;
3273 } else {
3274 // There will still be bytes to read after this request.
3275 response.PutChar('m');
3276 buffer = buffer.take_front(xfer_length);
3277 }
3278 // Now write the data in encoded binary form.
3279 response.PutEscapedBytes(buffer.data(), buffer.size());
3280 }
3281
3282 if (done_with_buffer)
3283 m_xfer_buffer_map.erase(buffer_it);
3284
3285 return SendPacketNoLock(response.GetString());
3286 }
3287
3288 GDBRemoteCommunication::PacketResult
Handle_QSaveRegisterState(StringExtractorGDBRemote & packet)3289 GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
3290 StringExtractorGDBRemote &packet) {
3291 Log *log = GetLog(LLDBLog::Thread);
3292
3293 // Move past packet name.
3294 packet.SetFilePos(strlen("QSaveRegisterState"));
3295
3296 // Get the thread to use.
3297 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3298 if (!thread) {
3299 if (m_thread_suffix_supported)
3300 return SendIllFormedResponse(
3301 packet, "No thread specified in QSaveRegisterState packet");
3302 else
3303 return SendIllFormedResponse(packet,
3304 "No thread was is set with the Hg packet");
3305 }
3306
3307 // Grab the register context for the thread.
3308 NativeRegisterContext& reg_context = thread->GetRegisterContext();
3309
3310 // Save registers to a buffer.
3311 WritableDataBufferSP register_data_sp;
3312 Status error = reg_context.ReadAllRegisterValues(register_data_sp);
3313 if (error.Fail()) {
3314 LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
3315 m_current_process->GetID(), error);
3316 return SendErrorResponse(0x75);
3317 }
3318
3319 // Allocate a new save id.
3320 const uint32_t save_id = GetNextSavedRegistersID();
3321 assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3322 "GetNextRegisterSaveID() returned an existing register save id");
3323
3324 // Save the register data buffer under the save id.
3325 {
3326 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3327 m_saved_registers_map[save_id] = register_data_sp;
3328 }
3329
3330 // Write the response.
3331 StreamGDBRemote response;
3332 response.Printf("%" PRIu32, save_id);
3333 return SendPacketNoLock(response.GetString());
3334 }
3335
3336 GDBRemoteCommunication::PacketResult
Handle_QRestoreRegisterState(StringExtractorGDBRemote & packet)3337 GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3338 StringExtractorGDBRemote &packet) {
3339 Log *log = GetLog(LLDBLog::Thread);
3340
3341 // Parse out save id.
3342 packet.SetFilePos(strlen("QRestoreRegisterState:"));
3343 if (packet.GetBytesLeft() < 1)
3344 return SendIllFormedResponse(
3345 packet, "QRestoreRegisterState packet missing register save id");
3346
3347 const uint32_t save_id = packet.GetU32(0);
3348 if (save_id == 0) {
3349 LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
3350 "expecting decimal uint32_t");
3351 return SendErrorResponse(0x76);
3352 }
3353
3354 // Get the thread to use.
3355 NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3356 if (!thread) {
3357 if (m_thread_suffix_supported)
3358 return SendIllFormedResponse(
3359 packet, "No thread specified in QRestoreRegisterState packet");
3360 else
3361 return SendIllFormedResponse(packet,
3362 "No thread was is set with the Hg packet");
3363 }
3364
3365 // Grab the register context for the thread.
3366 NativeRegisterContext ®_context = thread->GetRegisterContext();
3367
3368 // Retrieve register state buffer, then remove from the list.
3369 DataBufferSP register_data_sp;
3370 {
3371 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3372
3373 // Find the register set buffer for the given save id.
3374 auto it = m_saved_registers_map.find(save_id);
3375 if (it == m_saved_registers_map.end()) {
3376 LLDB_LOG(log,
3377 "pid {0} does not have a register set save buffer for id {1}",
3378 m_current_process->GetID(), save_id);
3379 return SendErrorResponse(0x77);
3380 }
3381 register_data_sp = it->second;
3382
3383 // Remove it from the map.
3384 m_saved_registers_map.erase(it);
3385 }
3386
3387 Status error = reg_context.WriteAllRegisterValues(register_data_sp);
3388 if (error.Fail()) {
3389 LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
3390 m_current_process->GetID(), error);
3391 return SendErrorResponse(0x77);
3392 }
3393
3394 return SendOKResponse();
3395 }
3396
3397 GDBRemoteCommunication::PacketResult
Handle_vAttach(StringExtractorGDBRemote & packet)3398 GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3399 StringExtractorGDBRemote &packet) {
3400 Log *log = GetLog(LLDBLog::Process);
3401
3402 // Consume the ';' after vAttach.
3403 packet.SetFilePos(strlen("vAttach"));
3404 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3405 return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3406
3407 // Grab the PID to which we will attach (assume hex encoding).
3408 lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3409 if (pid == LLDB_INVALID_PROCESS_ID)
3410 return SendIllFormedResponse(packet,
3411 "vAttach failed to parse the process id");
3412
3413 // Attempt to attach.
3414 LLDB_LOGF(log,
3415 "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3416 "pid %" PRIu64,
3417 __FUNCTION__, pid);
3418
3419 Status error = AttachToProcess(pid);
3420
3421 if (error.Fail()) {
3422 LLDB_LOGF(log,
3423 "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3424 "pid %" PRIu64 ": %s\n",
3425 __FUNCTION__, pid, error.AsCString());
3426 return SendErrorResponse(error);
3427 }
3428
3429 // Notify we attached by sending a stop packet.
3430 assert(m_current_process);
3431 return SendStopReasonForState(*m_current_process,
3432 m_current_process->GetState(),
3433 /*force_synchronous=*/false);
3434 }
3435
3436 GDBRemoteCommunication::PacketResult
Handle_vAttachWait(StringExtractorGDBRemote & packet)3437 GDBRemoteCommunicationServerLLGS::Handle_vAttachWait(
3438 StringExtractorGDBRemote &packet) {
3439 Log *log = GetLog(LLDBLog::Process);
3440
3441 // Consume the ';' after the identifier.
3442 packet.SetFilePos(strlen("vAttachWait"));
3443
3444 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3445 return SendIllFormedResponse(packet, "vAttachWait missing expected ';'");
3446
3447 // Allocate the buffer for the process name from vAttachWait.
3448 std::string process_name;
3449 if (!packet.GetHexByteString(process_name))
3450 return SendIllFormedResponse(packet,
3451 "vAttachWait failed to parse process name");
3452
3453 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3454
3455 Status error = AttachWaitProcess(process_name, false);
3456 if (error.Fail()) {
3457 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3458 error);
3459 return SendErrorResponse(error);
3460 }
3461
3462 // Notify we attached by sending a stop packet.
3463 assert(m_current_process);
3464 return SendStopReasonForState(*m_current_process,
3465 m_current_process->GetState(),
3466 /*force_synchronous=*/false);
3467 }
3468
3469 GDBRemoteCommunication::PacketResult
Handle_qVAttachOrWaitSupported(StringExtractorGDBRemote & packet)3470 GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported(
3471 StringExtractorGDBRemote &packet) {
3472 return SendOKResponse();
3473 }
3474
3475 GDBRemoteCommunication::PacketResult
Handle_vAttachOrWait(StringExtractorGDBRemote & packet)3476 GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait(
3477 StringExtractorGDBRemote &packet) {
3478 Log *log = GetLog(LLDBLog::Process);
3479
3480 // Consume the ';' after the identifier.
3481 packet.SetFilePos(strlen("vAttachOrWait"));
3482
3483 if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3484 return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'");
3485
3486 // Allocate the buffer for the process name from vAttachWait.
3487 std::string process_name;
3488 if (!packet.GetHexByteString(process_name))
3489 return SendIllFormedResponse(packet,
3490 "vAttachOrWait failed to parse process name");
3491
3492 LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
3493
3494 Status error = AttachWaitProcess(process_name, true);
3495 if (error.Fail()) {
3496 LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
3497 error);
3498 return SendErrorResponse(error);
3499 }
3500
3501 // Notify we attached by sending a stop packet.
3502 assert(m_current_process);
3503 return SendStopReasonForState(*m_current_process,
3504 m_current_process->GetState(),
3505 /*force_synchronous=*/false);
3506 }
3507
3508 GDBRemoteCommunication::PacketResult
Handle_vRun(StringExtractorGDBRemote & packet)3509 GDBRemoteCommunicationServerLLGS::Handle_vRun(
3510 StringExtractorGDBRemote &packet) {
3511 Log *log = GetLog(LLDBLog::Process);
3512
3513 llvm::StringRef s = packet.GetStringRef();
3514 if (!s.consume_front("vRun;"))
3515 return SendErrorResponse(8);
3516
3517 llvm::SmallVector<llvm::StringRef, 16> argv;
3518 s.split(argv, ';');
3519
3520 for (llvm::StringRef hex_arg : argv) {
3521 StringExtractor arg_ext{hex_arg};
3522 std::string arg;
3523 arg_ext.GetHexByteString(arg);
3524 m_process_launch_info.GetArguments().AppendArgument(arg);
3525 LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__,
3526 arg.c_str());
3527 }
3528
3529 if (argv.empty())
3530 return SendErrorResponse(Status("No arguments"));
3531 m_process_launch_info.GetExecutableFile().SetFile(
3532 m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native);
3533 m_process_launch_error = LaunchProcess();
3534 if (m_process_launch_error.Fail())
3535 return SendErrorResponse(m_process_launch_error);
3536 assert(m_current_process);
3537 return SendStopReasonForState(*m_current_process,
3538 m_current_process->GetState(),
3539 /*force_synchronous=*/true);
3540 }
3541
3542 GDBRemoteCommunication::PacketResult
Handle_D(StringExtractorGDBRemote & packet)3543 GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
3544 Log *log = GetLog(LLDBLog::Process);
3545 if (!m_non_stop)
3546 StopSTDIOForwarding();
3547
3548 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3549
3550 // Consume the ';' after D.
3551 packet.SetFilePos(1);
3552 if (packet.GetBytesLeft()) {
3553 if (packet.GetChar() != ';')
3554 return SendIllFormedResponse(packet, "D missing expected ';'");
3555
3556 // Grab the PID from which we will detach (assume hex encoding).
3557 pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3558 if (pid == LLDB_INVALID_PROCESS_ID)
3559 return SendIllFormedResponse(packet, "D failed to parse the process id");
3560 }
3561
3562 // Detach forked children if their PID was specified *or* no PID was requested
3563 // (i.e. detach-all packet).
3564 llvm::Error detach_error = llvm::Error::success();
3565 bool detached = false;
3566 for (auto it = m_debugged_processes.begin();
3567 it != m_debugged_processes.end();) {
3568 if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) {
3569 LLDB_LOGF(log,
3570 "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64,
3571 __FUNCTION__, it->first);
3572 if (llvm::Error e = it->second.process_up->Detach().ToError())
3573 detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));
3574 else {
3575 if (it->second.process_up.get() == m_current_process)
3576 m_current_process = nullptr;
3577 if (it->second.process_up.get() == m_continue_process)
3578 m_continue_process = nullptr;
3579 it = m_debugged_processes.erase(it);
3580 detached = true;
3581 continue;
3582 }
3583 }
3584 ++it;
3585 }
3586
3587 if (detach_error)
3588 return SendErrorResponse(std::move(detach_error));
3589 if (!detached)
3590 return SendErrorResponse(Status("PID %" PRIu64 " not traced", pid));
3591 return SendOKResponse();
3592 }
3593
3594 GDBRemoteCommunication::PacketResult
Handle_qThreadStopInfo(StringExtractorGDBRemote & packet)3595 GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3596 StringExtractorGDBRemote &packet) {
3597 Log *log = GetLog(LLDBLog::Thread);
3598
3599 if (!m_current_process ||
3600 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3601 return SendErrorResponse(50);
3602
3603 packet.SetFilePos(strlen("qThreadStopInfo"));
3604 const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3605 if (tid == LLDB_INVALID_THREAD_ID) {
3606 LLDB_LOGF(log,
3607 "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3608 "parse thread id from request \"%s\"",
3609 __FUNCTION__, packet.GetStringRef().data());
3610 return SendErrorResponse(0x15);
3611 }
3612 return SendStopReplyPacketForThread(*m_current_process, tid,
3613 /*force_synchronous=*/true);
3614 }
3615
3616 GDBRemoteCommunication::PacketResult
Handle_jThreadsInfo(StringExtractorGDBRemote &)3617 GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3618 StringExtractorGDBRemote &) {
3619 Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
3620
3621 // Ensure we have a debugged process.
3622 if (!m_current_process ||
3623 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3624 return SendErrorResponse(50);
3625 LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID());
3626
3627 StreamString response;
3628 const bool threads_with_valid_stop_info_only = false;
3629 llvm::Expected<json::Value> threads_info =
3630 GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only);
3631 if (!threads_info) {
3632 LLDB_LOG_ERROR(log, threads_info.takeError(),
3633 "failed to prepare a packet for pid {1}: {0}",
3634 m_current_process->GetID());
3635 return SendErrorResponse(52);
3636 }
3637
3638 response.AsRawOstream() << *threads_info;
3639 StreamGDBRemote escaped_response;
3640 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
3641 return SendPacketNoLock(escaped_response.GetString());
3642 }
3643
3644 GDBRemoteCommunication::PacketResult
Handle_qWatchpointSupportInfo(StringExtractorGDBRemote & packet)3645 GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3646 StringExtractorGDBRemote &packet) {
3647 // Fail if we don't have a current process.
3648 if (!m_current_process ||
3649 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3650 return SendErrorResponse(68);
3651
3652 packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3653 if (packet.GetBytesLeft() == 0)
3654 return SendOKResponse();
3655 if (packet.GetChar() != ':')
3656 return SendErrorResponse(67);
3657
3658 auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo();
3659
3660 StreamGDBRemote response;
3661 if (hw_debug_cap == std::nullopt)
3662 response.Printf("num:0;");
3663 else
3664 response.Printf("num:%d;", hw_debug_cap->second);
3665
3666 return SendPacketNoLock(response.GetString());
3667 }
3668
3669 GDBRemoteCommunication::PacketResult
Handle_qFileLoadAddress(StringExtractorGDBRemote & packet)3670 GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3671 StringExtractorGDBRemote &packet) {
3672 // Fail if we don't have a current process.
3673 if (!m_current_process ||
3674 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3675 return SendErrorResponse(67);
3676
3677 packet.SetFilePos(strlen("qFileLoadAddress:"));
3678 if (packet.GetBytesLeft() == 0)
3679 return SendErrorResponse(68);
3680
3681 std::string file_name;
3682 packet.GetHexByteString(file_name);
3683
3684 lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
3685 Status error =
3686 m_current_process->GetFileLoadAddress(file_name, file_load_address);
3687 if (error.Fail())
3688 return SendErrorResponse(69);
3689
3690 if (file_load_address == LLDB_INVALID_ADDRESS)
3691 return SendErrorResponse(1); // File not loaded
3692
3693 StreamGDBRemote response;
3694 response.PutHex64(file_load_address);
3695 return SendPacketNoLock(response.GetString());
3696 }
3697
3698 GDBRemoteCommunication::PacketResult
Handle_QPassSignals(StringExtractorGDBRemote & packet)3699 GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
3700 StringExtractorGDBRemote &packet) {
3701 std::vector<int> signals;
3702 packet.SetFilePos(strlen("QPassSignals:"));
3703
3704 // Read sequence of hex signal numbers divided by a semicolon and optionally
3705 // spaces.
3706 while (packet.GetBytesLeft() > 0) {
3707 int signal = packet.GetS32(-1, 16);
3708 if (signal < 0)
3709 return SendIllFormedResponse(packet, "Failed to parse signal number.");
3710 signals.push_back(signal);
3711
3712 packet.SkipSpaces();
3713 char separator = packet.GetChar();
3714 if (separator == '\0')
3715 break; // End of string
3716 if (separator != ';')
3717 return SendIllFormedResponse(packet, "Invalid separator,"
3718 " expected semicolon.");
3719 }
3720
3721 // Fail if we don't have a current process.
3722 if (!m_current_process)
3723 return SendErrorResponse(68);
3724
3725 Status error = m_current_process->IgnoreSignals(signals);
3726 if (error.Fail())
3727 return SendErrorResponse(69);
3728
3729 return SendOKResponse();
3730 }
3731
3732 GDBRemoteCommunication::PacketResult
Handle_qMemTags(StringExtractorGDBRemote & packet)3733 GDBRemoteCommunicationServerLLGS::Handle_qMemTags(
3734 StringExtractorGDBRemote &packet) {
3735 Log *log = GetLog(LLDBLog::Process);
3736
3737 // Ensure we have a process.
3738 if (!m_current_process ||
3739 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3740 LLDB_LOGF(
3741 log,
3742 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3743 __FUNCTION__);
3744 return SendErrorResponse(1);
3745 }
3746
3747 // We are expecting
3748 // qMemTags:<hex address>,<hex length>:<hex type>
3749
3750 // Address
3751 packet.SetFilePos(strlen("qMemTags:"));
3752 const char *current_char = packet.Peek();
3753 if (!current_char || *current_char == ',')
3754 return SendIllFormedResponse(packet, "Missing address in qMemTags packet");
3755 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3756
3757 // Length
3758 char previous_char = packet.GetChar();
3759 current_char = packet.Peek();
3760 // If we don't have a separator or the length field is empty
3761 if (previous_char != ',' || (current_char && *current_char == ':'))
3762 return SendIllFormedResponse(packet,
3763 "Invalid addr,length pair in qMemTags packet");
3764
3765 if (packet.GetBytesLeft() < 1)
3766 return SendIllFormedResponse(
3767 packet, "Too short qMemtags: packet (looking for length)");
3768 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3769
3770 // Type
3771 const char *invalid_type_err = "Invalid type field in qMemTags: packet";
3772 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3773 return SendIllFormedResponse(packet, invalid_type_err);
3774
3775 // Type is a signed integer but packed into the packet as its raw bytes.
3776 // However, our GetU64 uses strtoull which allows +/-. We do not want this.
3777 const char *first_type_char = packet.Peek();
3778 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
3779 return SendIllFormedResponse(packet, invalid_type_err);
3780
3781 // Extract type as unsigned then cast to signed.
3782 // Using a uint64_t here so that we have some value outside of the 32 bit
3783 // range to use as the invalid return value.
3784 uint64_t raw_type =
3785 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
3786
3787 if ( // Make sure the cast below would be valid
3788 raw_type > std::numeric_limits<uint32_t>::max() ||
3789 // To catch inputs like "123aardvark" that will parse but clearly aren't
3790 // valid in this case.
3791 packet.GetBytesLeft()) {
3792 return SendIllFormedResponse(packet, invalid_type_err);
3793 }
3794
3795 // First narrow to 32 bits otherwise the copy into type would take
3796 // the wrong 4 bytes on big endian.
3797 uint32_t raw_type_32 = raw_type;
3798 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
3799
3800 StreamGDBRemote response;
3801 std::vector<uint8_t> tags;
3802 Status error = m_current_process->ReadMemoryTags(type, addr, length, tags);
3803 if (error.Fail())
3804 return SendErrorResponse(1);
3805
3806 // This m is here in case we want to support multi part replies in the future.
3807 // In the same manner as qfThreadInfo/qsThreadInfo.
3808 response.PutChar('m');
3809 response.PutBytesAsRawHex8(tags.data(), tags.size());
3810 return SendPacketNoLock(response.GetString());
3811 }
3812
3813 GDBRemoteCommunication::PacketResult
Handle_QMemTags(StringExtractorGDBRemote & packet)3814 GDBRemoteCommunicationServerLLGS::Handle_QMemTags(
3815 StringExtractorGDBRemote &packet) {
3816 Log *log = GetLog(LLDBLog::Process);
3817
3818 // Ensure we have a process.
3819 if (!m_current_process ||
3820 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3821 LLDB_LOGF(
3822 log,
3823 "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3824 __FUNCTION__);
3825 return SendErrorResponse(1);
3826 }
3827
3828 // We are expecting
3829 // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes>
3830
3831 // Address
3832 packet.SetFilePos(strlen("QMemTags:"));
3833 const char *current_char = packet.Peek();
3834 if (!current_char || *current_char == ',')
3835 return SendIllFormedResponse(packet, "Missing address in QMemTags packet");
3836 const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3837
3838 // Length
3839 char previous_char = packet.GetChar();
3840 current_char = packet.Peek();
3841 // If we don't have a separator or the length field is empty
3842 if (previous_char != ',' || (current_char && *current_char == ':'))
3843 return SendIllFormedResponse(packet,
3844 "Invalid addr,length pair in QMemTags packet");
3845
3846 if (packet.GetBytesLeft() < 1)
3847 return SendIllFormedResponse(
3848 packet, "Too short QMemtags: packet (looking for length)");
3849 const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3850
3851 // Type
3852 const char *invalid_type_err = "Invalid type field in QMemTags: packet";
3853 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3854 return SendIllFormedResponse(packet, invalid_type_err);
3855
3856 // Our GetU64 uses strtoull which allows leading +/-, we don't want that.
3857 const char *first_type_char = packet.Peek();
3858 if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
3859 return SendIllFormedResponse(packet, invalid_type_err);
3860
3861 // The type is a signed integer but is in the packet as its raw bytes.
3862 // So parse first as unsigned then cast to signed later.
3863 // We extract to 64 bit, even though we only expect 32, so that we've
3864 // got some invalid value we can check for.
3865 uint64_t raw_type =
3866 packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
3867 if (raw_type > std::numeric_limits<uint32_t>::max())
3868 return SendIllFormedResponse(packet, invalid_type_err);
3869
3870 // First narrow to 32 bits. Otherwise the copy below would get the wrong
3871 // 4 bytes on big endian.
3872 uint32_t raw_type_32 = raw_type;
3873 int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
3874
3875 // Tag data
3876 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3877 return SendIllFormedResponse(packet,
3878 "Missing tag data in QMemTags: packet");
3879
3880 // Must be 2 chars per byte
3881 const char *invalid_data_err = "Invalid tag data in QMemTags: packet";
3882 if (packet.GetBytesLeft() % 2)
3883 return SendIllFormedResponse(packet, invalid_data_err);
3884
3885 // This is bytes here and is unpacked into target specific tags later
3886 // We cannot assume that number of bytes == length here because the server
3887 // can repeat tags to fill a given range.
3888 std::vector<uint8_t> tag_data;
3889 // Zero length writes will not have any tag data
3890 // (but we pass them on because it will still check that tagging is enabled)
3891 if (packet.GetBytesLeft()) {
3892 size_t byte_count = packet.GetBytesLeft() / 2;
3893 tag_data.resize(byte_count);
3894 size_t converted_bytes = packet.GetHexBytes(tag_data, 0);
3895 if (converted_bytes != byte_count) {
3896 return SendIllFormedResponse(packet, invalid_data_err);
3897 }
3898 }
3899
3900 Status status =
3901 m_current_process->WriteMemoryTags(type, addr, length, tag_data);
3902 return status.Success() ? SendOKResponse() : SendErrorResponse(1);
3903 }
3904
3905 GDBRemoteCommunication::PacketResult
Handle_qSaveCore(StringExtractorGDBRemote & packet)3906 GDBRemoteCommunicationServerLLGS::Handle_qSaveCore(
3907 StringExtractorGDBRemote &packet) {
3908 // Fail if we don't have a current process.
3909 if (!m_current_process ||
3910 (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3911 return SendErrorResponse(Status("Process not running."));
3912
3913 std::string path_hint;
3914
3915 StringRef packet_str{packet.GetStringRef()};
3916 assert(packet_str.startswith("qSaveCore"));
3917 if (packet_str.consume_front("qSaveCore;")) {
3918 for (auto x : llvm::split(packet_str, ';')) {
3919 if (x.consume_front("path-hint:"))
3920 StringExtractor(x).GetHexByteString(path_hint);
3921 else
3922 return SendErrorResponse(Status("Unsupported qSaveCore option"));
3923 }
3924 }
3925
3926 llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint);
3927 if (!ret)
3928 return SendErrorResponse(ret.takeError());
3929
3930 StreamString response;
3931 response.PutCString("core-path:");
3932 response.PutStringAsRawHex8(ret.get());
3933 return SendPacketNoLock(response.GetString());
3934 }
3935
3936 GDBRemoteCommunication::PacketResult
Handle_QNonStop(StringExtractorGDBRemote & packet)3937 GDBRemoteCommunicationServerLLGS::Handle_QNonStop(
3938 StringExtractorGDBRemote &packet) {
3939 Log *log = GetLog(LLDBLog::Process);
3940
3941 StringRef packet_str{packet.GetStringRef()};
3942 assert(packet_str.startswith("QNonStop:"));
3943 packet_str.consume_front("QNonStop:");
3944 if (packet_str == "0") {
3945 if (m_non_stop)
3946 StopSTDIOForwarding();
3947 for (auto &process_it : m_debugged_processes) {
3948 if (process_it.second.process_up->IsRunning()) {
3949 assert(m_non_stop);
3950 Status error = process_it.second.process_up->Interrupt();
3951 if (error.Fail()) {
3952 LLDB_LOG(log,
3953 "while disabling nonstop, failed to halt process {0}: {1}",
3954 process_it.first, error);
3955 return SendErrorResponse(0x41);
3956 }
3957 // we must not send stop reasons after QNonStop
3958 m_disabling_non_stop = true;
3959 }
3960 }
3961 m_stdio_notification_queue.clear();
3962 m_stop_notification_queue.clear();
3963 m_non_stop = false;
3964 // If we are stopping anything, defer sending the OK response until we're
3965 // done.
3966 if (m_disabling_non_stop)
3967 return PacketResult::Success;
3968 } else if (packet_str == "1") {
3969 if (!m_non_stop)
3970 StartSTDIOForwarding();
3971 m_non_stop = true;
3972 } else
3973 return SendErrorResponse(Status("Invalid QNonStop packet"));
3974 return SendOKResponse();
3975 }
3976
3977 GDBRemoteCommunication::PacketResult
HandleNotificationAck(std::deque<std::string> & queue)3978 GDBRemoteCommunicationServerLLGS::HandleNotificationAck(
3979 std::deque<std::string> &queue) {
3980 // Per the protocol, the first message put into the queue is sent
3981 // immediately. However, it remains the queue until the client ACKs it --
3982 // then we pop it and send the next message. The process repeats until
3983 // the last message in the queue is ACK-ed, in which case the packet sends
3984 // an OK response.
3985 if (queue.empty())
3986 return SendErrorResponse(Status("No pending notification to ack"));
3987 queue.pop_front();
3988 if (!queue.empty())
3989 return SendPacketNoLock(queue.front());
3990 return SendOKResponse();
3991 }
3992
3993 GDBRemoteCommunication::PacketResult
Handle_vStdio(StringExtractorGDBRemote & packet)3994 GDBRemoteCommunicationServerLLGS::Handle_vStdio(
3995 StringExtractorGDBRemote &packet) {
3996 return HandleNotificationAck(m_stdio_notification_queue);
3997 }
3998
3999 GDBRemoteCommunication::PacketResult
Handle_vStopped(StringExtractorGDBRemote & packet)4000 GDBRemoteCommunicationServerLLGS::Handle_vStopped(
4001 StringExtractorGDBRemote &packet) {
4002 PacketResult ret = HandleNotificationAck(m_stop_notification_queue);
4003 // If this was the last notification and all the processes exited,
4004 // terminate the server.
4005 if (m_stop_notification_queue.empty() && m_debugged_processes.empty()) {
4006 m_exit_now = true;
4007 m_mainloop.RequestTermination();
4008 }
4009 return ret;
4010 }
4011
4012 GDBRemoteCommunication::PacketResult
Handle_vCtrlC(StringExtractorGDBRemote & packet)4013 GDBRemoteCommunicationServerLLGS::Handle_vCtrlC(
4014 StringExtractorGDBRemote &packet) {
4015 if (!m_non_stop)
4016 return SendErrorResponse(Status("vCtrl is only valid in non-stop mode"));
4017
4018 PacketResult interrupt_res = Handle_interrupt(packet);
4019 // If interrupting the process failed, pass the result through.
4020 if (interrupt_res != PacketResult::Success)
4021 return interrupt_res;
4022 // Otherwise, vCtrlC should issue an OK response (normal interrupts do not).
4023 return SendOKResponse();
4024 }
4025
4026 GDBRemoteCommunication::PacketResult
Handle_T(StringExtractorGDBRemote & packet)4027 GDBRemoteCommunicationServerLLGS::Handle_T(StringExtractorGDBRemote &packet) {
4028 packet.SetFilePos(strlen("T"));
4029 auto pid_tid = packet.GetPidTid(m_current_process ? m_current_process->GetID()
4030 : LLDB_INVALID_PROCESS_ID);
4031 if (!pid_tid)
4032 return SendErrorResponse(llvm::make_error<StringError>(
4033 inconvertibleErrorCode(), "Malformed thread-id"));
4034
4035 lldb::pid_t pid = pid_tid->first;
4036 lldb::tid_t tid = pid_tid->second;
4037
4038 // Technically, this would also be caught by the PID check but let's be more
4039 // explicit about the error.
4040 if (pid == LLDB_INVALID_PROCESS_ID)
4041 return SendErrorResponse(llvm::make_error<StringError>(
4042 inconvertibleErrorCode(), "No current process and no PID provided"));
4043
4044 // Check the process ID and find respective process instance.
4045 auto new_process_it = m_debugged_processes.find(pid);
4046 if (new_process_it == m_debugged_processes.end())
4047 return SendErrorResponse(1);
4048
4049 // Check the thread ID
4050 if (!new_process_it->second.process_up->GetThreadByID(tid))
4051 return SendErrorResponse(2);
4052
4053 return SendOKResponse();
4054 }
4055
MaybeCloseInferiorTerminalConnection()4056 void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
4057 Log *log = GetLog(LLDBLog::Process);
4058
4059 // Tell the stdio connection to shut down.
4060 if (m_stdio_communication.IsConnected()) {
4061 auto connection = m_stdio_communication.GetConnection();
4062 if (connection) {
4063 Status error;
4064 connection->Disconnect(&error);
4065
4066 if (error.Success()) {
4067 LLDB_LOGF(log,
4068 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4069 "terminal stdio - SUCCESS",
4070 __FUNCTION__);
4071 } else {
4072 LLDB_LOGF(log,
4073 "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4074 "terminal stdio - FAIL: %s",
4075 __FUNCTION__, error.AsCString());
4076 }
4077 }
4078 }
4079 }
4080
GetThreadFromSuffix(StringExtractorGDBRemote & packet)4081 NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
4082 StringExtractorGDBRemote &packet) {
4083 // We have no thread if we don't have a process.
4084 if (!m_current_process ||
4085 m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
4086 return nullptr;
4087
4088 // If the client hasn't asked for thread suffix support, there will not be a
4089 // thread suffix. Use the current thread in that case.
4090 if (!m_thread_suffix_supported) {
4091 const lldb::tid_t current_tid = GetCurrentThreadID();
4092 if (current_tid == LLDB_INVALID_THREAD_ID)
4093 return nullptr;
4094 else if (current_tid == 0) {
4095 // Pick a thread.
4096 return m_current_process->GetThreadAtIndex(0);
4097 } else
4098 return m_current_process->GetThreadByID(current_tid);
4099 }
4100
4101 Log *log = GetLog(LLDBLog::Thread);
4102
4103 // Parse out the ';'.
4104 if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
4105 LLDB_LOGF(log,
4106 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4107 "error: expected ';' prior to start of thread suffix: packet "
4108 "contents = '%s'",
4109 __FUNCTION__, packet.GetStringRef().data());
4110 return nullptr;
4111 }
4112
4113 if (!packet.GetBytesLeft())
4114 return nullptr;
4115
4116 // Parse out thread: portion.
4117 if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
4118 LLDB_LOGF(log,
4119 "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4120 "error: expected 'thread:' but not found, packet contents = "
4121 "'%s'",
4122 __FUNCTION__, packet.GetStringRef().data());
4123 return nullptr;
4124 }
4125 packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
4126 const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4127 if (tid != 0)
4128 return m_current_process->GetThreadByID(tid);
4129
4130 return nullptr;
4131 }
4132
GetCurrentThreadID() const4133 lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
4134 if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
4135 // Use whatever the debug process says is the current thread id since the
4136 // protocol either didn't specify or specified we want any/all threads
4137 // marked as the current thread.
4138 if (!m_current_process)
4139 return LLDB_INVALID_THREAD_ID;
4140 return m_current_process->GetCurrentThreadID();
4141 }
4142 // Use the specific current thread id set by the gdb remote protocol.
4143 return m_current_tid;
4144 }
4145
GetNextSavedRegistersID()4146 uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
4147 std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
4148 return m_next_saved_registers_id++;
4149 }
4150
ClearProcessSpecificData()4151 void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
4152 Log *log = GetLog(LLDBLog::Process);
4153
4154 LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
4155 m_xfer_buffer_map.clear();
4156 }
4157
4158 FileSpec
FindModuleFile(const std::string & module_path,const ArchSpec & arch)4159 GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
4160 const ArchSpec &arch) {
4161 if (m_current_process) {
4162 FileSpec file_spec;
4163 if (m_current_process
4164 ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
4165 .Success()) {
4166 if (FileSystem::Instance().Exists(file_spec))
4167 return file_spec;
4168 }
4169 }
4170
4171 return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
4172 }
4173
XMLEncodeAttributeValue(llvm::StringRef value)4174 std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue(
4175 llvm::StringRef value) {
4176 std::string result;
4177 for (const char &c : value) {
4178 switch (c) {
4179 case '\'':
4180 result += "'";
4181 break;
4182 case '"':
4183 result += """;
4184 break;
4185 case '<':
4186 result += "<";
4187 break;
4188 case '>':
4189 result += ">";
4190 break;
4191 default:
4192 result += c;
4193 break;
4194 }
4195 }
4196 return result;
4197 }
4198
HandleFeatures(const llvm::ArrayRef<llvm::StringRef> client_features)4199 std::vector<std::string> GDBRemoteCommunicationServerLLGS::HandleFeatures(
4200 const llvm::ArrayRef<llvm::StringRef> client_features) {
4201 std::vector<std::string> ret =
4202 GDBRemoteCommunicationServerCommon::HandleFeatures(client_features);
4203 ret.insert(ret.end(), {
4204 "QThreadSuffixSupported+",
4205 "QListThreadsInStopReply+",
4206 "qXfer:features:read+",
4207 "QNonStop+",
4208 });
4209
4210 // report server-only features
4211 using Extension = NativeProcessProtocol::Extension;
4212 Extension plugin_features = m_process_factory.GetSupportedExtensions();
4213 if (bool(plugin_features & Extension::pass_signals))
4214 ret.push_back("QPassSignals+");
4215 if (bool(plugin_features & Extension::auxv))
4216 ret.push_back("qXfer:auxv:read+");
4217 if (bool(plugin_features & Extension::libraries_svr4))
4218 ret.push_back("qXfer:libraries-svr4:read+");
4219 if (bool(plugin_features & Extension::siginfo_read))
4220 ret.push_back("qXfer:siginfo:read+");
4221 if (bool(plugin_features & Extension::memory_tagging))
4222 ret.push_back("memory-tagging+");
4223 if (bool(plugin_features & Extension::savecore))
4224 ret.push_back("qSaveCore+");
4225
4226 // check for client features
4227 m_extensions_supported = {};
4228 for (llvm::StringRef x : client_features)
4229 m_extensions_supported |=
4230 llvm::StringSwitch<Extension>(x)
4231 .Case("multiprocess+", Extension::multiprocess)
4232 .Case("fork-events+", Extension::fork)
4233 .Case("vfork-events+", Extension::vfork)
4234 .Default({});
4235
4236 m_extensions_supported &= plugin_features;
4237
4238 // fork & vfork require multiprocess
4239 if (!bool(m_extensions_supported & Extension::multiprocess))
4240 m_extensions_supported &= ~(Extension::fork | Extension::vfork);
4241
4242 // report only if actually supported
4243 if (bool(m_extensions_supported & Extension::multiprocess))
4244 ret.push_back("multiprocess+");
4245 if (bool(m_extensions_supported & Extension::fork))
4246 ret.push_back("fork-events+");
4247 if (bool(m_extensions_supported & Extension::vfork))
4248 ret.push_back("vfork-events+");
4249
4250 for (auto &x : m_debugged_processes)
4251 SetEnabledExtensions(*x.second.process_up);
4252 return ret;
4253 }
4254
SetEnabledExtensions(NativeProcessProtocol & process)4255 void GDBRemoteCommunicationServerLLGS::SetEnabledExtensions(
4256 NativeProcessProtocol &process) {
4257 NativeProcessProtocol::Extension flags = m_extensions_supported;
4258 assert(!bool(flags & ~m_process_factory.GetSupportedExtensions()));
4259 process.SetEnabledExtensions(flags);
4260 }
4261
4262 GDBRemoteCommunication::PacketResult
SendContinueSuccessResponse()4263 GDBRemoteCommunicationServerLLGS::SendContinueSuccessResponse() {
4264 if (m_non_stop)
4265 return SendOKResponse();
4266 StartSTDIOForwarding();
4267 return PacketResult::Success;
4268 }
4269
AppendThreadIDToResponse(Stream & response,lldb::pid_t pid,lldb::tid_t tid)4270 void GDBRemoteCommunicationServerLLGS::AppendThreadIDToResponse(
4271 Stream &response, lldb::pid_t pid, lldb::tid_t tid) {
4272 if (bool(m_extensions_supported &
4273 NativeProcessProtocol::Extension::multiprocess))
4274 response.Format("p{0:x-}.", pid);
4275 response.Format("{0:x-}", tid);
4276 }
4277
4278 std::string
LLGSArgToURL(llvm::StringRef url_arg,bool reverse_connect)4279 lldb_private::process_gdb_remote::LLGSArgToURL(llvm::StringRef url_arg,
4280 bool reverse_connect) {
4281 // Try parsing the argument as URL.
4282 if (std::optional<URI> url = URI::Parse(url_arg)) {
4283 if (reverse_connect)
4284 return url_arg.str();
4285
4286 // Translate the scheme from LLGS notation to ConnectionFileDescriptor.
4287 // If the scheme doesn't match any, pass it through to support using CFD
4288 // schemes directly.
4289 std::string new_url = llvm::StringSwitch<std::string>(url->scheme)
4290 .Case("tcp", "listen")
4291 .Case("unix", "unix-accept")
4292 .Case("unix-abstract", "unix-abstract-accept")
4293 .Default(url->scheme.str());
4294 llvm::append_range(new_url, url_arg.substr(url->scheme.size()));
4295 return new_url;
4296 }
4297
4298 std::string host_port = url_arg.str();
4299 // If host_and_port starts with ':', default the host to be "localhost" and
4300 // expect the remainder to be the port.
4301 if (url_arg.startswith(":"))
4302 host_port.insert(0, "localhost");
4303
4304 // Try parsing the (preprocessed) argument as host:port pair.
4305 if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError()))
4306 return (reverse_connect ? "connect://" : "listen://") + host_port;
4307
4308 // If none of the above applied, interpret the argument as UNIX socket path.
4309 return (reverse_connect ? "unix-connect://" : "unix-accept://") +
4310 url_arg.str();
4311 }
4312