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