180814287SRaphael Isemann //===-- GDBRemoteCommunicationServerLLGS.cpp ------------------------------===//
2e13c2731STamas Berghammer //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e13c2731STamas Berghammer //
7e13c2731STamas Berghammer //===----------------------------------------------------------------------===//
8e13c2731STamas Berghammer
976e47d48SRaphael Isemann #include <cerrno>
10e13c2731STamas Berghammer
11e13c2731STamas Berghammer #include "lldb/Host/Config.h"
12e13c2731STamas Berghammer
13e13c2731STamas Berghammer
14e13c2731STamas Berghammer #include <chrono>
15b9c1b51eSKate Stone #include <cstring>
16da2e614fSDavid Spickett #include <limits>
17e13c2731STamas Berghammer #include <thread>
18e13c2731STamas Berghammer
19e2f1fe36SPavel Labath #include "GDBRemoteCommunicationServerLLGS.h"
20e13c2731STamas Berghammer #include "lldb/Host/ConnectionFileDescriptor.h"
21e13c2731STamas Berghammer #include "lldb/Host/Debug.h"
22e13c2731STamas Berghammer #include "lldb/Host/File.h"
23eef758e9SPavel Labath #include "lldb/Host/FileAction.h"
24e13c2731STamas Berghammer #include "lldb/Host/FileSystem.h"
25e13c2731STamas Berghammer #include "lldb/Host/Host.h"
26e13c2731STamas Berghammer #include "lldb/Host/HostInfo.h"
27b6dbe9a9SPavel Labath #include "lldb/Host/PosixApi.h"
2858d28b93SMichał Górny #include "lldb/Host/Socket.h"
291eb0d42aSPavel Labath #include "lldb/Host/common/NativeProcessProtocol.h"
301eb0d42aSPavel Labath #include "lldb/Host/common/NativeRegisterContext.h"
311eb0d42aSPavel Labath #include "lldb/Host/common/NativeThreadProtocol.h"
3293749ab3SZachary Turner #include "lldb/Target/MemoryRegionInfo.h"
33145d95c9SPavel Labath #include "lldb/Utility/Args.h"
34666cc0b2SZachary Turner #include "lldb/Utility/DataBuffer.h"
3501c3243fSZachary Turner #include "lldb/Utility/Endian.h"
36e2f1fe36SPavel Labath #include "lldb/Utility/GDBRemote.h"
37abadc221SPavel Labath #include "lldb/Utility/LLDBAssert.h"
38c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
396f9e6901SZachary Turner #include "lldb/Utility/Log.h"
40d821c997SPavel Labath #include "lldb/Utility/RegisterValue.h"
41d821c997SPavel Labath #include "lldb/Utility/State.h"
42bf9a7730SZachary Turner #include "lldb/Utility/StreamString.h"
43e2f1fe36SPavel Labath #include "lldb/Utility/UnimplementedError.h"
4458d28b93SMichał Górny #include "lldb/Utility/UriParser.h"
451eb0d42aSPavel Labath #include "llvm/ADT/Triple.h"
469beb4567SJonas Devlieghere #include "llvm/Support/JSON.h"
471eb0d42aSPavel Labath #include "llvm/Support/ScopedPrinter.h"
48e13c2731STamas Berghammer
49e13c2731STamas Berghammer #include "ProcessGDBRemote.h"
50e13c2731STamas Berghammer #include "ProcessGDBRemoteLog.h"
519af71b38SPavel Labath #include "lldb/Utility/StringExtractorGDBRemote.h"
52e13c2731STamas Berghammer
53e13c2731STamas Berghammer using namespace lldb;
54e13c2731STamas Berghammer using namespace lldb_private;
55db264a6dSTamas Berghammer using namespace lldb_private::process_gdb_remote;
56783bfc8cSTamas Berghammer using namespace llvm;
57e13c2731STamas Berghammer
58e13c2731STamas Berghammer // GDBRemote Errors
59e13c2731STamas Berghammer
60b9c1b51eSKate Stone namespace {
61b9c1b51eSKate Stone enum GDBRemoteServerError {
62e13c2731STamas Berghammer // Set to the first unused error number in literal form below
63e13c2731STamas Berghammer eErrorFirst = 29,
64e13c2731STamas Berghammer eErrorNoProcess = eErrorFirst,
65e13c2731STamas Berghammer eErrorResume,
66e13c2731STamas Berghammer eErrorExitStatus
67e13c2731STamas Berghammer };
68e13c2731STamas Berghammer }
69e13c2731STamas Berghammer
70e13c2731STamas Berghammer // GDBRemoteCommunicationServerLLGS constructor
GDBRemoteCommunicationServerLLGS(MainLoop & mainloop,const NativeProcessProtocol::Factory & process_factory)71b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
7296e600fcSPavel Labath MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
73b9c1b51eSKate Stone : GDBRemoteCommunicationServerCommon("gdb-remote.server",
74b9c1b51eSKate Stone "gdb-remote.server.rx_packet"),
7596e600fcSPavel Labath m_mainloop(mainloop), m_process_factory(process_factory),
76f1812a28SMichał Górny m_current_process(nullptr), m_continue_process(nullptr),
7796e600fcSPavel Labath m_stdio_communication("process.stdio") {
78e13c2731STamas Berghammer RegisterPacketHandlers();
79e13c2731STamas Berghammer }
80e13c2731STamas Berghammer
RegisterPacketHandlers()81b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
82e13c2731STamas Berghammer RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
83e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_C);
84e13c2731STamas Berghammer RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
85e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_c);
86e13c2731STamas Berghammer RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
87e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_D);
88e13c2731STamas Berghammer RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
89e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_H);
90e13c2731STamas Berghammer RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
91e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_I);
92b9c1b51eSKate Stone RegisterMemberFunctionHandler(
93b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_interrupt,
94e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_interrupt);
95b9c1b51eSKate Stone RegisterMemberFunctionHandler(
96b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_m,
973bf11256SPavel Labath &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
98e13c2731STamas Berghammer RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
99e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_M);
1002c4226f8SPavel Labath RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__M,
1012c4226f8SPavel Labath &GDBRemoteCommunicationServerLLGS::Handle__M);
1022c4226f8SPavel Labath RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType__m,
1032c4226f8SPavel Labath &GDBRemoteCommunicationServerLLGS::Handle__m);
104e13c2731STamas Berghammer RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
105e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_p);
106e13c2731STamas Berghammer RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
107e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_P);
108e13c2731STamas Berghammer RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
109e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_qC);
110e827e518SMichał Górny RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_T,
111e827e518SMichał Górny &GDBRemoteCommunicationServerLLGS::Handle_T);
112b9c1b51eSKate Stone RegisterMemberFunctionHandler(
113b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
114e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
115b9c1b51eSKate Stone RegisterMemberFunctionHandler(
116b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
117783bfc8cSTamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
118b9c1b51eSKate Stone RegisterMemberFunctionHandler(
119b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
120e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
121b9c1b51eSKate Stone RegisterMemberFunctionHandler(
1222494243eSPavel Labath StringExtractorGDBRemote::eServerPacketType_QThreadSuffixSupported,
1232494243eSPavel Labath &GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported);
1242494243eSPavel Labath RegisterMemberFunctionHandler(
1252494243eSPavel Labath StringExtractorGDBRemote::eServerPacketType_QListThreadsInStopReply,
1262494243eSPavel Labath &GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply);
1272494243eSPavel Labath RegisterMemberFunctionHandler(
128b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
129e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
130b9c1b51eSKate Stone RegisterMemberFunctionHandler(
131b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
132e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
133b9c1b51eSKate Stone RegisterMemberFunctionHandler(
134b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
135e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
136b9c1b51eSKate Stone RegisterMemberFunctionHandler(
137b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
138e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
139b9c1b51eSKate Stone RegisterMemberFunctionHandler(
140b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
141e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
142b9c1b51eSKate Stone RegisterMemberFunctionHandler(
143b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
144e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
145b9c1b51eSKate Stone RegisterMemberFunctionHandler(
146b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
147e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
148b9c1b51eSKate Stone RegisterMemberFunctionHandler(
149b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
150e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
151b9c1b51eSKate Stone RegisterMemberFunctionHandler(
152b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
153e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
154b9c1b51eSKate Stone RegisterMemberFunctionHandler(
155b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
156e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
157b9c1b51eSKate Stone RegisterMemberFunctionHandler(
158b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
1594a4bb12eSPavel Labath &GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
160b9c1b51eSKate Stone RegisterMemberFunctionHandler(
161b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
162e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
163b9c1b51eSKate Stone RegisterMemberFunctionHandler(
16457e2da4fSAntonio Afonso StringExtractorGDBRemote::eServerPacketType_qXfer,
16557e2da4fSAntonio Afonso &GDBRemoteCommunicationServerLLGS::Handle_qXfer);
166e13c2731STamas Berghammer RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
167e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_s);
168b9c1b51eSKate Stone RegisterMemberFunctionHandler(
169b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_stop_reason,
170e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
171b9c1b51eSKate Stone RegisterMemberFunctionHandler(
172b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_vAttach,
173e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_vAttach);
174b9c1b51eSKate Stone RegisterMemberFunctionHandler(
1752bbf724fSAugusto Noronha StringExtractorGDBRemote::eServerPacketType_vAttachWait,
1762bbf724fSAugusto Noronha &GDBRemoteCommunicationServerLLGS::Handle_vAttachWait);
1772bbf724fSAugusto Noronha RegisterMemberFunctionHandler(
1782afaf072SAugusto Noronha StringExtractorGDBRemote::eServerPacketType_qVAttachOrWaitSupported,
1792afaf072SAugusto Noronha &GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported);
1802afaf072SAugusto Noronha RegisterMemberFunctionHandler(
1812afaf072SAugusto Noronha StringExtractorGDBRemote::eServerPacketType_vAttachOrWait,
1822afaf072SAugusto Noronha &GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait);
1832afaf072SAugusto Noronha RegisterMemberFunctionHandler(
184b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_vCont,
185e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_vCont);
186b9c1b51eSKate Stone RegisterMemberFunctionHandler(
187b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_vCont_actions,
188e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
189b9c1b51eSKate Stone RegisterMemberFunctionHandler(
1906ba3f723SMichał Górny StringExtractorGDBRemote::eServerPacketType_vRun,
1916ba3f723SMichał Górny &GDBRemoteCommunicationServerLLGS::Handle_vRun);
1926ba3f723SMichał Górny RegisterMemberFunctionHandler(
193b9c1b51eSKate Stone StringExtractorGDBRemote::eServerPacketType_x,
1943bf11256SPavel Labath &GDBRemoteCommunicationServerLLGS::Handle_memory_read);
195e13c2731STamas Berghammer RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
196e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_Z);
197e13c2731STamas Berghammer RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
198e13c2731STamas Berghammer &GDBRemoteCommunicationServerLLGS::Handle_z);
1994a705e7eSPavel Labath RegisterMemberFunctionHandler(
2004a705e7eSPavel Labath StringExtractorGDBRemote::eServerPacketType_QPassSignals,
2014a705e7eSPavel Labath &GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
202e13c2731STamas Berghammer
203e714c4f5SRavitheja Addepally RegisterMemberFunctionHandler(
2040b697561SWalter Erquinigo StringExtractorGDBRemote::eServerPacketType_jLLDBTraceSupported,
2050b697561SWalter Erquinigo &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported);
206e714c4f5SRavitheja Addepally RegisterMemberFunctionHandler(
2070b697561SWalter Erquinigo StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStart,
2080b697561SWalter Erquinigo &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart);
209e714c4f5SRavitheja Addepally RegisterMemberFunctionHandler(
2100b697561SWalter Erquinigo StringExtractorGDBRemote::eServerPacketType_jLLDBTraceStop,
2110b697561SWalter Erquinigo &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop);
212e714c4f5SRavitheja Addepally RegisterMemberFunctionHandler(
2130b697561SWalter Erquinigo StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetState,
2140b697561SWalter Erquinigo &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState);
215e714c4f5SRavitheja Addepally RegisterMemberFunctionHandler(
2160b697561SWalter Erquinigo StringExtractorGDBRemote::eServerPacketType_jLLDBTraceGetBinaryData,
2170b697561SWalter Erquinigo &GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData);
218e714c4f5SRavitheja Addepally
219f04b3635SPavel Labath RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g,
220f04b3635SPavel Labath &GDBRemoteCommunicationServerLLGS::Handle_g);
221f04b3635SPavel Labath
222da2e614fSDavid Spickett RegisterMemberFunctionHandler(
223da2e614fSDavid Spickett StringExtractorGDBRemote::eServerPacketType_qMemTags,
224da2e614fSDavid Spickett &GDBRemoteCommunicationServerLLGS::Handle_qMemTags);
225da2e614fSDavid Spickett
2267d27230dSDavid Spickett RegisterMemberFunctionHandler(
2277d27230dSDavid Spickett StringExtractorGDBRemote::eServerPacketType_QMemTags,
2287d27230dSDavid Spickett &GDBRemoteCommunicationServerLLGS::Handle_QMemTags);
2297d27230dSDavid Spickett
230e13c2731STamas Berghammer RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
23197206d57SZachary Turner [this](StringExtractorGDBRemote packet, Status &error,
232b9c1b51eSKate Stone bool &interrupt, bool &quit) {
233e13c2731STamas Berghammer quit = true;
234e13c2731STamas Berghammer return this->Handle_k(packet);
235e13c2731STamas Berghammer });
23637cbd817SMichał Górny
23737cbd817SMichał Górny RegisterMemberFunctionHandler(
238c18784baSMichał Górny StringExtractorGDBRemote::eServerPacketType_vKill,
239c18784baSMichał Górny &GDBRemoteCommunicationServerLLGS::Handle_vKill);
240c18784baSMichał Górny
241c18784baSMichał Górny RegisterMemberFunctionHandler(
24237cbd817SMichał Górny StringExtractorGDBRemote::eServerPacketType_qLLDBSaveCore,
24337cbd817SMichał Górny &GDBRemoteCommunicationServerLLGS::Handle_qSaveCore);
244bc04d240SMichał Górny
245bc04d240SMichał Górny RegisterMemberFunctionHandler(
246bc04d240SMichał Górny StringExtractorGDBRemote::eServerPacketType_QNonStop,
247bc04d240SMichał Górny &GDBRemoteCommunicationServerLLGS::Handle_QNonStop);
248bc04d240SMichał Górny RegisterMemberFunctionHandler(
2491903f358SMichał Górny StringExtractorGDBRemote::eServerPacketType_vStdio,
2501903f358SMichał Górny &GDBRemoteCommunicationServerLLGS::Handle_vStdio);
2511903f358SMichał Górny RegisterMemberFunctionHandler(
252bc04d240SMichał Górny StringExtractorGDBRemote::eServerPacketType_vStopped,
253bc04d240SMichał Górny &GDBRemoteCommunicationServerLLGS::Handle_vStopped);
254bc04d240SMichał Górny RegisterMemberFunctionHandler(
255bc04d240SMichał Górny StringExtractorGDBRemote::eServerPacketType_vCtrlC,
256bc04d240SMichał Górny &GDBRemoteCommunicationServerLLGS::Handle_vCtrlC);
257e13c2731STamas Berghammer }
258e13c2731STamas Berghammer
SetLaunchInfo(const ProcessLaunchInfo & info)25911e5917dSPavel Labath void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) {
26011e5917dSPavel Labath m_process_launch_info = info;
261e13c2731STamas Berghammer }
262e13c2731STamas Berghammer
LaunchProcess()26397206d57SZachary Turner Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
264a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
265e13c2731STamas Berghammer
266e13c2731STamas Berghammer if (!m_process_launch_info.GetArguments().GetArgumentCount())
26797206d57SZachary Turner return Status("%s: no process command line specified to launch",
268b9c1b51eSKate Stone __FUNCTION__);
269e13c2731STamas Berghammer
270b9c1b51eSKate Stone const bool should_forward_stdio =
271b9c1b51eSKate Stone m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
2725ad891f7SPavel Labath m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
2735ad891f7SPavel Labath m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
2745ad891f7SPavel Labath m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
2755ad891f7SPavel Labath m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
2765ad891f7SPavel Labath
2778e55ddefSPavel Labath if (should_forward_stdio) {
278216944eeSAaron Smith // Temporarily relax the following for Windows until we can take advantage
279216944eeSAaron Smith // of the recently added pty support. This doesn't really affect the use of
280216944eeSAaron Smith // lldb-server on Windows.
281216944eeSAaron Smith #if !defined(_WIN32)
2828e55ddefSPavel Labath if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
2838e55ddefSPavel Labath return Status(std::move(Err));
284216944eeSAaron Smith #endif
2858e55ddefSPavel Labath }
2865ad891f7SPavel Labath
287e13c2731STamas Berghammer {
28816ff8604SSaleem Abdulrasool std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
289bbae0c1fSMichał Górny assert(m_debugged_processes.empty() && "lldb-server creating debugged "
290e77fce0aSTodd Fiala "process but one already exists");
29196e600fcSPavel Labath auto process_or =
29296e600fcSPavel Labath m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
2938630d387SPavel Labath if (!process_or)
2948630d387SPavel Labath return Status(process_or.takeError());
295bbae0c1fSMichał Górny m_continue_process = m_current_process = process_or->get();
296355c7916SMichał Górny m_debugged_processes.emplace(
297355c7916SMichał Górny m_current_process->GetID(),
298355c7916SMichał Górny DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});
299e13c2731STamas Berghammer }
300e13c2731STamas Berghammer
30131225768SMichał Górny SetEnabledExtensions(*m_current_process);
30231225768SMichał Górny
30305097246SAdrian Prantl // Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as
30405097246SAdrian Prantl // needed. llgs local-process debugging may specify PTY paths, which will
30505097246SAdrian Prantl // make these file actions non-null process launch -i/e/o will also make
30605097246SAdrian Prantl // these file actions non-null nullptr means that the traffic is expected to
30705097246SAdrian Prantl // flow over gdb-remote protocol
308b9c1b51eSKate Stone if (should_forward_stdio) {
3094a8abd3fSVince Harron // nullptr means it's not redirected to file or pty (in case of LLGS local)
31005097246SAdrian Prantl // at least one of stdio will be transferred pty<->gdb-remote we need to
31152a3ed5bSQuinn Pham // give the pty primary handle to this object to read and/or write
31282abefa4SPavel Labath LLDB_LOG(log,
31382abefa4SPavel Labath "pid = {0}: setting up stdout/stderr redirection via $O "
31482abefa4SPavel Labath "gdb-remote commands",
315bbae0c1fSMichał Górny m_current_process->GetID());
316e13c2731STamas Berghammer
317e13c2731STamas Berghammer // Setup stdout/stderr mapping from inferior to $O
318bbae0c1fSMichał Górny auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
319b9c1b51eSKate Stone if (terminal_fd >= 0) {
32063e5fb76SJonas Devlieghere LLDB_LOGF(log,
32163e5fb76SJonas Devlieghere "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
322b9c1b51eSKate Stone "inferior STDIO fd to %d",
323b9c1b51eSKate Stone __FUNCTION__, terminal_fd);
32496e600fcSPavel Labath Status status = SetSTDIOFileDescriptor(terminal_fd);
32596e600fcSPavel Labath if (status.Fail())
32696e600fcSPavel Labath return status;
327b9c1b51eSKate Stone } else {
32863e5fb76SJonas Devlieghere LLDB_LOGF(log,
32963e5fb76SJonas Devlieghere "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
330b9c1b51eSKate Stone "inferior STDIO since terminal fd reported as %d",
331b9c1b51eSKate Stone __FUNCTION__, terminal_fd);
332e13c2731STamas Berghammer }
333b9c1b51eSKate Stone } else {
33482abefa4SPavel Labath LLDB_LOG(log,
33582abefa4SPavel Labath "pid = {0} skipping stdout/stderr redirection via $O: inferior "
33682abefa4SPavel Labath "will communicate over client-provided file descriptors",
337bbae0c1fSMichał Górny m_current_process->GetID());
338e13c2731STamas Berghammer }
339e13c2731STamas Berghammer
340b9c1b51eSKate Stone printf("Launched '%s' as process %" PRIu64 "...\n",
341b9c1b51eSKate Stone m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
342bbae0c1fSMichał Górny m_current_process->GetID());
343e13c2731STamas Berghammer
34496e600fcSPavel Labath return Status();
345e13c2731STamas Berghammer }
346e13c2731STamas Berghammer
AttachToProcess(lldb::pid_t pid)34797206d57SZachary Turner Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
348a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
34963e5fb76SJonas Devlieghere LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
350b9c1b51eSKate Stone __FUNCTION__, pid);
351e13c2731STamas Berghammer
352b9c1b51eSKate Stone // Before we try to attach, make sure we aren't already monitoring something
353b9c1b51eSKate Stone // else.
354bbae0c1fSMichał Górny if (!m_debugged_processes.empty())
355a70512a9SPavel Labath return Status("cannot attach to process %" PRIu64
356b9c1b51eSKate Stone " when another process with pid %" PRIu64
357b9c1b51eSKate Stone " is being debugged.",
358bbae0c1fSMichał Górny pid, m_current_process->GetID());
359e13c2731STamas Berghammer
360e13c2731STamas Berghammer // Try to attach.
36196e600fcSPavel Labath auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
36296e600fcSPavel Labath if (!process_or) {
36396e600fcSPavel Labath Status status(process_or.takeError());
364a97efde5SDavid Spickett llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}\n", pid,
36596e600fcSPavel Labath status);
36696e600fcSPavel Labath return status;
367e13c2731STamas Berghammer }
368bbae0c1fSMichał Górny m_continue_process = m_current_process = process_or->get();
369355c7916SMichał Górny m_debugged_processes.emplace(
370355c7916SMichał Górny m_current_process->GetID(),
371355c7916SMichał Górny DebuggedProcess{std::move(*process_or), DebuggedProcess::Flag{}});
37231225768SMichał Górny SetEnabledExtensions(*m_current_process);
373e13c2731STamas Berghammer
374e13c2731STamas Berghammer // Setup stdout/stderr mapping from inferior.
375bbae0c1fSMichał Górny auto terminal_fd = m_current_process->GetTerminalFileDescriptor();
376b9c1b51eSKate Stone if (terminal_fd >= 0) {
37763e5fb76SJonas Devlieghere LLDB_LOGF(log,
37863e5fb76SJonas Devlieghere "ProcessGDBRemoteCommunicationServerLLGS::%s setting "
379b9c1b51eSKate Stone "inferior STDIO fd to %d",
380b9c1b51eSKate Stone __FUNCTION__, terminal_fd);
38196e600fcSPavel Labath Status status = SetSTDIOFileDescriptor(terminal_fd);
38296e600fcSPavel Labath if (status.Fail())
38396e600fcSPavel Labath return status;
384b9c1b51eSKate Stone } else {
38563e5fb76SJonas Devlieghere LLDB_LOGF(log,
38663e5fb76SJonas Devlieghere "ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
387b9c1b51eSKate Stone "inferior STDIO since terminal fd reported as %d",
388b9c1b51eSKate Stone __FUNCTION__, terminal_fd);
389e13c2731STamas Berghammer }
390e13c2731STamas Berghammer
391e13c2731STamas Berghammer printf("Attached to process %" PRIu64 "...\n", pid);
39296e600fcSPavel Labath return Status();
393e13c2731STamas Berghammer }
394e13c2731STamas Berghammer
AttachWaitProcess(llvm::StringRef process_name,bool include_existing)3952bbf724fSAugusto Noronha Status GDBRemoteCommunicationServerLLGS::AttachWaitProcess(
3962afaf072SAugusto Noronha llvm::StringRef process_name, bool include_existing) {
397a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
3982bbf724fSAugusto Noronha
3992bbf724fSAugusto Noronha std::chrono::milliseconds polling_interval = std::chrono::milliseconds(1);
4002bbf724fSAugusto Noronha
4012bbf724fSAugusto Noronha // Create the matcher used to search the process list.
4022bbf724fSAugusto Noronha ProcessInstanceInfoList exclusion_list;
4032bbf724fSAugusto Noronha ProcessInstanceInfoMatch match_info;
4042bbf724fSAugusto Noronha match_info.GetProcessInfo().GetExecutableFile().SetFile(
4052afaf072SAugusto Noronha process_name, llvm::sys::path::Style::native);
4062afaf072SAugusto Noronha match_info.SetNameMatchType(NameMatch::Equals);
4072bbf724fSAugusto Noronha
4082afaf072SAugusto Noronha if (include_existing) {
4092afaf072SAugusto Noronha LLDB_LOG(log, "including existing processes in search");
4102afaf072SAugusto Noronha } else {
4112bbf724fSAugusto Noronha // Create the excluded process list before polling begins.
4122bbf724fSAugusto Noronha Host::FindProcesses(match_info, exclusion_list);
4132bbf724fSAugusto Noronha LLDB_LOG(log, "placed '{0}' processes in the exclusion list.",
4142bbf724fSAugusto Noronha exclusion_list.size());
4152afaf072SAugusto Noronha }
4162bbf724fSAugusto Noronha
4172bbf724fSAugusto Noronha LLDB_LOG(log, "waiting for '{0}' to appear", process_name);
4182bbf724fSAugusto Noronha
4192bbf724fSAugusto Noronha auto is_in_exclusion_list =
4202bbf724fSAugusto Noronha [&exclusion_list](const ProcessInstanceInfo &info) {
4212bbf724fSAugusto Noronha for (auto &excluded : exclusion_list) {
4222bbf724fSAugusto Noronha if (excluded.GetProcessID() == info.GetProcessID())
4232bbf724fSAugusto Noronha return true;
4242bbf724fSAugusto Noronha }
4252bbf724fSAugusto Noronha return false;
4262bbf724fSAugusto Noronha };
4272bbf724fSAugusto Noronha
4282bbf724fSAugusto Noronha ProcessInstanceInfoList loop_process_list;
4292bbf724fSAugusto Noronha while (true) {
4302bbf724fSAugusto Noronha loop_process_list.clear();
4312bbf724fSAugusto Noronha if (Host::FindProcesses(match_info, loop_process_list)) {
4322bbf724fSAugusto Noronha // Remove all the elements that are in the exclusion list.
4332bbf724fSAugusto Noronha llvm::erase_if(loop_process_list, is_in_exclusion_list);
4342bbf724fSAugusto Noronha
4352bbf724fSAugusto Noronha // One match! We found the desired process.
4362bbf724fSAugusto Noronha if (loop_process_list.size() == 1) {
4372bbf724fSAugusto Noronha auto matching_process_pid = loop_process_list[0].GetProcessID();
4382bbf724fSAugusto Noronha LLDB_LOG(log, "found pid {0}", matching_process_pid);
4392bbf724fSAugusto Noronha return AttachToProcess(matching_process_pid);
4402bbf724fSAugusto Noronha }
4412bbf724fSAugusto Noronha
4422bbf724fSAugusto Noronha // Multiple matches! Return an error reporting the PIDs we found.
4432bbf724fSAugusto Noronha if (loop_process_list.size() > 1) {
4442bbf724fSAugusto Noronha StreamString error_stream;
4452bbf724fSAugusto Noronha error_stream.Format(
4462bbf724fSAugusto Noronha "Multiple executables with name: '{0}' found. Pids: ",
4472bbf724fSAugusto Noronha process_name);
4482bbf724fSAugusto Noronha for (size_t i = 0; i < loop_process_list.size() - 1; ++i) {
4492bbf724fSAugusto Noronha error_stream.Format("{0}, ", loop_process_list[i].GetProcessID());
4502bbf724fSAugusto Noronha }
4512bbf724fSAugusto Noronha error_stream.Format("{0}.", loop_process_list.back().GetProcessID());
4522bbf724fSAugusto Noronha
4532bbf724fSAugusto Noronha Status error;
4542bbf724fSAugusto Noronha error.SetErrorString(error_stream.GetString());
4552bbf724fSAugusto Noronha return error;
4562bbf724fSAugusto Noronha }
4572bbf724fSAugusto Noronha }
4582bbf724fSAugusto Noronha // No matches, we have not found the process. Sleep until next poll.
4592bbf724fSAugusto Noronha LLDB_LOG(log, "sleep {0} seconds", polling_interval);
4602bbf724fSAugusto Noronha std::this_thread::sleep_for(polling_interval);
4612bbf724fSAugusto Noronha }
4622bbf724fSAugusto Noronha }
4632bbf724fSAugusto Noronha
InitializeDelegate(NativeProcessProtocol * process)464b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
465b9c1b51eSKate Stone NativeProcessProtocol *process) {
466e13c2731STamas Berghammer assert(process && "process cannot be NULL");
467a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
468b9c1b51eSKate Stone if (log) {
46963e5fb76SJonas Devlieghere LLDB_LOGF(log,
47063e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s called with "
471b9c1b51eSKate Stone "NativeProcessProtocol pid %" PRIu64 ", current state: %s",
472b9c1b51eSKate Stone __FUNCTION__, process->GetID(),
473e13c2731STamas Berghammer StateAsCString(process->GetState()));
474e13c2731STamas Berghammer }
475e13c2731STamas Berghammer }
476e13c2731STamas Berghammer
477e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
SendWResponse(NativeProcessProtocol * process)478b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::SendWResponse(
479b9c1b51eSKate Stone NativeProcessProtocol *process) {
480e13c2731STamas Berghammer assert(process && "process cannot be NULL");
481a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
482e13c2731STamas Berghammer
483e13c2731STamas Berghammer // send W notification
4843508fc8cSPavel Labath auto wait_status = process->GetExitStatus();
4853508fc8cSPavel Labath if (!wait_status) {
4863508fc8cSPavel Labath LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
4873508fc8cSPavel Labath process->GetID());
488e13c2731STamas Berghammer
489e13c2731STamas Berghammer StreamGDBRemote response;
490e13c2731STamas Berghammer response.PutChar('E');
491e13c2731STamas Berghammer response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
49226709df8SZachary Turner return SendPacketNoLock(response.GetString());
4933508fc8cSPavel Labath }
4943508fc8cSPavel Labath
4953508fc8cSPavel Labath LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
4963508fc8cSPavel Labath *wait_status);
497e13c2731STamas Berghammer
498c18784baSMichał Górny // If the process was killed through vKill, return "OK".
499355c7916SMichał Górny if (bool(m_debugged_processes.at(process->GetID()).flags &
500355c7916SMichał Górny DebuggedProcess::Flag::vkilled))
501c18784baSMichał Górny return SendOKResponse();
502c18784baSMichał Górny
503e13c2731STamas Berghammer StreamGDBRemote response;
5043508fc8cSPavel Labath response.Format("{0:g}", *wait_status);
505355c7916SMichał Górny if (bool(m_extensions_supported &
506355c7916SMichał Górny NativeProcessProtocol::Extension::multiprocess))
507e4d6ed58SMichał Górny response.Format(";process:{0:x-}", process->GetID());
508bc04d240SMichał Górny if (m_non_stop)
509bc04d240SMichał Górny return SendNotificationPacketNoLock("Stop", m_stop_notification_queue,
510bc04d240SMichał Górny response.GetString());
51126709df8SZachary Turner return SendPacketNoLock(response.GetString());
512e13c2731STamas Berghammer }
513e13c2731STamas Berghammer
AppendHexValue(StreamString & response,const uint8_t * buf,uint32_t buf_size,bool swap)514b9c1b51eSKate Stone static void AppendHexValue(StreamString &response, const uint8_t *buf,
515b9c1b51eSKate Stone uint32_t buf_size, bool swap) {
516e13c2731STamas Berghammer int64_t i;
517b9c1b51eSKate Stone if (swap) {
518e13c2731STamas Berghammer for (i = buf_size - 1; i >= 0; i--)
519e13c2731STamas Berghammer response.PutHex8(buf[i]);
520b9c1b51eSKate Stone } else {
521e13c2731STamas Berghammer for (i = 0; i < buf_size; i++)
522e13c2731STamas Berghammer response.PutHex8(buf[i]);
523e13c2731STamas Berghammer }
524e13c2731STamas Berghammer }
525e13c2731STamas Berghammer
GetEncodingNameOrEmpty(const RegisterInfo & reg_info)526af64b319SMuhammad Omair Javaid static llvm::StringRef GetEncodingNameOrEmpty(const RegisterInfo ®_info) {
527af64b319SMuhammad Omair Javaid switch (reg_info.encoding) {
528af64b319SMuhammad Omair Javaid case eEncodingUint:
529af64b319SMuhammad Omair Javaid return "uint";
530af64b319SMuhammad Omair Javaid case eEncodingSint:
531af64b319SMuhammad Omair Javaid return "sint";
532af64b319SMuhammad Omair Javaid case eEncodingIEEE754:
533af64b319SMuhammad Omair Javaid return "ieee754";
534af64b319SMuhammad Omair Javaid case eEncodingVector:
535af64b319SMuhammad Omair Javaid return "vector";
536af64b319SMuhammad Omair Javaid default:
537af64b319SMuhammad Omair Javaid return "";
538af64b319SMuhammad Omair Javaid }
539af64b319SMuhammad Omair Javaid }
540af64b319SMuhammad Omair Javaid
GetFormatNameOrEmpty(const RegisterInfo & reg_info)541af64b319SMuhammad Omair Javaid static llvm::StringRef GetFormatNameOrEmpty(const RegisterInfo ®_info) {
542af64b319SMuhammad Omair Javaid switch (reg_info.format) {
543af64b319SMuhammad Omair Javaid case eFormatBinary:
544af64b319SMuhammad Omair Javaid return "binary";
545af64b319SMuhammad Omair Javaid case eFormatDecimal:
546af64b319SMuhammad Omair Javaid return "decimal";
547af64b319SMuhammad Omair Javaid case eFormatHex:
548af64b319SMuhammad Omair Javaid return "hex";
549af64b319SMuhammad Omair Javaid case eFormatFloat:
550af64b319SMuhammad Omair Javaid return "float";
551af64b319SMuhammad Omair Javaid case eFormatVectorOfSInt8:
552af64b319SMuhammad Omair Javaid return "vector-sint8";
553af64b319SMuhammad Omair Javaid case eFormatVectorOfUInt8:
554af64b319SMuhammad Omair Javaid return "vector-uint8";
555af64b319SMuhammad Omair Javaid case eFormatVectorOfSInt16:
556af64b319SMuhammad Omair Javaid return "vector-sint16";
557af64b319SMuhammad Omair Javaid case eFormatVectorOfUInt16:
558af64b319SMuhammad Omair Javaid return "vector-uint16";
559af64b319SMuhammad Omair Javaid case eFormatVectorOfSInt32:
560af64b319SMuhammad Omair Javaid return "vector-sint32";
561af64b319SMuhammad Omair Javaid case eFormatVectorOfUInt32:
562af64b319SMuhammad Omair Javaid return "vector-uint32";
563af64b319SMuhammad Omair Javaid case eFormatVectorOfFloat32:
564af64b319SMuhammad Omair Javaid return "vector-float32";
565af64b319SMuhammad Omair Javaid case eFormatVectorOfUInt64:
566af64b319SMuhammad Omair Javaid return "vector-uint64";
567af64b319SMuhammad Omair Javaid case eFormatVectorOfUInt128:
568af64b319SMuhammad Omair Javaid return "vector-uint128";
569af64b319SMuhammad Omair Javaid default:
570af64b319SMuhammad Omair Javaid return "";
571af64b319SMuhammad Omair Javaid };
572af64b319SMuhammad Omair Javaid }
573af64b319SMuhammad Omair Javaid
GetKindGenericOrEmpty(const RegisterInfo & reg_info)574af64b319SMuhammad Omair Javaid static llvm::StringRef GetKindGenericOrEmpty(const RegisterInfo ®_info) {
575af64b319SMuhammad Omair Javaid switch (reg_info.kinds[RegisterKind::eRegisterKindGeneric]) {
576af64b319SMuhammad Omair Javaid case LLDB_REGNUM_GENERIC_PC:
577af64b319SMuhammad Omair Javaid return "pc";
578af64b319SMuhammad Omair Javaid case LLDB_REGNUM_GENERIC_SP:
579af64b319SMuhammad Omair Javaid return "sp";
580af64b319SMuhammad Omair Javaid case LLDB_REGNUM_GENERIC_FP:
581af64b319SMuhammad Omair Javaid return "fp";
582af64b319SMuhammad Omair Javaid case LLDB_REGNUM_GENERIC_RA:
583af64b319SMuhammad Omair Javaid return "ra";
584af64b319SMuhammad Omair Javaid case LLDB_REGNUM_GENERIC_FLAGS:
585af64b319SMuhammad Omair Javaid return "flags";
586af64b319SMuhammad Omair Javaid case LLDB_REGNUM_GENERIC_ARG1:
587af64b319SMuhammad Omair Javaid return "arg1";
588af64b319SMuhammad Omair Javaid case LLDB_REGNUM_GENERIC_ARG2:
589af64b319SMuhammad Omair Javaid return "arg2";
590af64b319SMuhammad Omair Javaid case LLDB_REGNUM_GENERIC_ARG3:
591af64b319SMuhammad Omair Javaid return "arg3";
592af64b319SMuhammad Omair Javaid case LLDB_REGNUM_GENERIC_ARG4:
593af64b319SMuhammad Omair Javaid return "arg4";
594af64b319SMuhammad Omair Javaid case LLDB_REGNUM_GENERIC_ARG5:
595af64b319SMuhammad Omair Javaid return "arg5";
596af64b319SMuhammad Omair Javaid case LLDB_REGNUM_GENERIC_ARG6:
597af64b319SMuhammad Omair Javaid return "arg6";
598af64b319SMuhammad Omair Javaid case LLDB_REGNUM_GENERIC_ARG7:
599af64b319SMuhammad Omair Javaid return "arg7";
600af64b319SMuhammad Omair Javaid case LLDB_REGNUM_GENERIC_ARG8:
601af64b319SMuhammad Omair Javaid return "arg8";
602af64b319SMuhammad Omair Javaid default:
603af64b319SMuhammad Omair Javaid return "";
604af64b319SMuhammad Omair Javaid }
605af64b319SMuhammad Omair Javaid }
606af64b319SMuhammad Omair Javaid
CollectRegNums(const uint32_t * reg_num,StreamString & response,bool usehex)607af64b319SMuhammad Omair Javaid static void CollectRegNums(const uint32_t *reg_num, StreamString &response,
608af64b319SMuhammad Omair Javaid bool usehex) {
609af64b319SMuhammad Omair Javaid for (int i = 0; *reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
610af64b319SMuhammad Omair Javaid if (i > 0)
611af64b319SMuhammad Omair Javaid response.PutChar(',');
612af64b319SMuhammad Omair Javaid if (usehex)
613af64b319SMuhammad Omair Javaid response.Printf("%" PRIx32, *reg_num);
614af64b319SMuhammad Omair Javaid else
615af64b319SMuhammad Omair Javaid response.Printf("%" PRIu32, *reg_num);
616af64b319SMuhammad Omair Javaid }
617af64b319SMuhammad Omair Javaid }
618af64b319SMuhammad Omair Javaid
WriteRegisterValueInHexFixedWidth(StreamString & response,NativeRegisterContext & reg_ctx,const RegisterInfo & reg_info,const RegisterValue * reg_value_p,lldb::ByteOrder byte_order)619b9c1b51eSKate Stone static void WriteRegisterValueInHexFixedWidth(
620d37349f3SPavel Labath StreamString &response, NativeRegisterContext ®_ctx,
621e0a5b575SPavel Labath const RegisterInfo ®_info, const RegisterValue *reg_value_p,
622e0a5b575SPavel Labath lldb::ByteOrder byte_order) {
623e13c2731STamas Berghammer RegisterValue reg_value;
624b9c1b51eSKate Stone if (!reg_value_p) {
625d37349f3SPavel Labath Status error = reg_ctx.ReadRegister(®_info, reg_value);
626e13c2731STamas Berghammer if (error.Success())
627e13c2731STamas Berghammer reg_value_p = ®_value;
628e13c2731STamas Berghammer // else log.
629e13c2731STamas Berghammer }
630e13c2731STamas Berghammer
631b9c1b51eSKate Stone if (reg_value_p) {
632b9c1b51eSKate Stone AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
633e0a5b575SPavel Labath reg_value_p->GetByteSize(),
634e0a5b575SPavel Labath byte_order == lldb::eByteOrderLittle);
635b9c1b51eSKate Stone } else {
636e13c2731STamas Berghammer // Zero-out any unreadable values.
637b9c1b51eSKate Stone if (reg_info.byte_size > 0) {
638e13c2731STamas Berghammer std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
639e13c2731STamas Berghammer AppendHexValue(response, zeros.data(), zeros.size(), false);
640e13c2731STamas Berghammer }
641e13c2731STamas Berghammer }
642e13c2731STamas Berghammer }
643e13c2731STamas Berghammer
644b69c09bfSMuhammad Omair Javaid static llvm::Optional<json::Object>
GetRegistersAsJSON(NativeThreadProtocol & thread)6459beb4567SJonas Devlieghere GetRegistersAsJSON(NativeThreadProtocol &thread) {
646a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Thread);
6474a4bb12eSPavel Labath
648d37349f3SPavel Labath NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
6494a4bb12eSPavel Labath
6509beb4567SJonas Devlieghere json::Object register_object;
651e4fc4ef4SPavel Labath
652e4fc4ef4SPavel Labath #ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
653b69c09bfSMuhammad Omair Javaid const auto expedited_regs =
654b69c09bfSMuhammad Omair Javaid reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);
655e4fc4ef4SPavel Labath #else
656b69c09bfSMuhammad Omair Javaid const auto expedited_regs =
657b69c09bfSMuhammad Omair Javaid reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Minimal);
658e4fc4ef4SPavel Labath #endif
659b69c09bfSMuhammad Omair Javaid if (expedited_regs.empty())
660b69c09bfSMuhammad Omair Javaid return llvm::None;
661e4fc4ef4SPavel Labath
662b69c09bfSMuhammad Omair Javaid for (auto ®_num : expedited_regs) {
663b9c1b51eSKate Stone const RegisterInfo *const reg_info_p =
664d37349f3SPavel Labath reg_ctx.GetRegisterInfoAtIndex(reg_num);
665b9c1b51eSKate Stone if (reg_info_p == nullptr) {
66663e5fb76SJonas Devlieghere LLDB_LOGF(log,
667b9c1b51eSKate Stone "%s failed to get register info for register index %" PRIu32,
668e4fc4ef4SPavel Labath __FUNCTION__, reg_num);
6694a4bb12eSPavel Labath continue;
6704a4bb12eSPavel Labath }
6714a4bb12eSPavel Labath
6724a4bb12eSPavel Labath if (reg_info_p->value_regs != nullptr)
673b9c1b51eSKate Stone continue; // Only expedite registers that are not contained in other
674b9c1b51eSKate Stone // registers.
6754a4bb12eSPavel Labath
6764a4bb12eSPavel Labath RegisterValue reg_value;
677d37349f3SPavel Labath Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
678b9c1b51eSKate Stone if (error.Fail()) {
67963e5fb76SJonas Devlieghere LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
680b9c1b51eSKate Stone __FUNCTION__,
681b9c1b51eSKate Stone reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
682b9c1b51eSKate Stone reg_num, error.AsCString());
6834a4bb12eSPavel Labath continue;
6844a4bb12eSPavel Labath }
6854a4bb12eSPavel Labath
6864a4bb12eSPavel Labath StreamString stream;
687d37349f3SPavel Labath WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
688e0a5b575SPavel Labath ®_value, lldb::eByteOrderBig);
6894a4bb12eSPavel Labath
690ecd849edSPavel Labath register_object.try_emplace(llvm::to_string(reg_num),
691ecd849edSPavel Labath stream.GetString().str());
6924a4bb12eSPavel Labath }
6934a4bb12eSPavel Labath
6949beb4567SJonas Devlieghere return register_object;
6954a4bb12eSPavel Labath }
6964a4bb12eSPavel Labath
GetStopReasonString(StopReason stop_reason)697b9c1b51eSKate Stone static const char *GetStopReasonString(StopReason stop_reason) {
698b9c1b51eSKate Stone switch (stop_reason) {
6994a4bb12eSPavel Labath case eStopReasonTrace:
7004a4bb12eSPavel Labath return "trace";
7014a4bb12eSPavel Labath case eStopReasonBreakpoint:
7024a4bb12eSPavel Labath return "breakpoint";
7034a4bb12eSPavel Labath case eStopReasonWatchpoint:
7044a4bb12eSPavel Labath return "watchpoint";
7054a4bb12eSPavel Labath case eStopReasonSignal:
7064a4bb12eSPavel Labath return "signal";
7074a4bb12eSPavel Labath case eStopReasonException:
7084a4bb12eSPavel Labath return "exception";
7094a4bb12eSPavel Labath case eStopReasonExec:
7104a4bb12eSPavel Labath return "exec";
7110b697561SWalter Erquinigo case eStopReasonProcessorTrace:
7120b697561SWalter Erquinigo return "processor trace";
7136c37984eSMichał Górny case eStopReasonFork:
7146c37984eSMichał Górny return "fork";
7156c37984eSMichał Górny case eStopReasonVFork:
7166c37984eSMichał Górny return "vfork";
7176c37984eSMichał Górny case eStopReasonVForkDone:
7186c37984eSMichał Górny return "vforkdone";
7194a4bb12eSPavel Labath case eStopReasonInstrumentation:
7204a4bb12eSPavel Labath case eStopReasonInvalid:
7214a4bb12eSPavel Labath case eStopReasonPlanComplete:
7224a4bb12eSPavel Labath case eStopReasonThreadExiting:
7234a4bb12eSPavel Labath case eStopReasonNone:
7244a4bb12eSPavel Labath break; // ignored
7254a4bb12eSPavel Labath }
7264a4bb12eSPavel Labath return nullptr;
7274a4bb12eSPavel Labath }
7284a4bb12eSPavel Labath
7295f775d29SJonas Devlieghere static llvm::Expected<json::Array>
GetJSONThreadsInfo(NativeProcessProtocol & process,bool abridged)7309beb4567SJonas Devlieghere GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) {
731a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
73205569f67SPavel Labath
7339beb4567SJonas Devlieghere json::Array threads_array;
73405569f67SPavel Labath
73505569f67SPavel Labath // Ensure we can get info on the given thread.
736e095cddbSMichał Górny for (NativeThreadProtocol &thread : process.Threads()) {
737e095cddbSMichał Górny lldb::tid_t tid = thread.GetID();
73805569f67SPavel Labath // Grab the reason this thread stopped.
73905569f67SPavel Labath struct ThreadStopInfo tid_stop_info;
74005569f67SPavel Labath std::string description;
741e095cddbSMichał Górny if (!thread.GetStopReason(tid_stop_info, description))
7429beb4567SJonas Devlieghere return llvm::make_error<llvm::StringError>(
7439beb4567SJonas Devlieghere "failed to get stop reason", llvm::inconvertibleErrorCode());
74405569f67SPavel Labath
745d6b3de72SMichał Górny const int signum = tid_stop_info.signo;
746b9c1b51eSKate Stone if (log) {
74763e5fb76SJonas Devlieghere LLDB_LOGF(log,
74863e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
749b9c1b51eSKate Stone " tid %" PRIu64
750b9c1b51eSKate Stone " got signal signo = %d, reason = %d, exc_type = %" PRIu64,
751b9c1b51eSKate Stone __FUNCTION__, process.GetID(), tid, signum,
752b9c1b51eSKate Stone tid_stop_info.reason, tid_stop_info.details.exception.type);
75305569f67SPavel Labath }
75405569f67SPavel Labath
7559beb4567SJonas Devlieghere json::Object thread_obj;
75605569f67SPavel Labath
757e0a5b575SPavel Labath if (!abridged) {
758e095cddbSMichał Górny if (llvm::Optional<json::Object> registers = GetRegistersAsJSON(thread))
7599beb4567SJonas Devlieghere thread_obj.try_emplace("registers", std::move(*registers));
760e0a5b575SPavel Labath }
761c4645bb0SPavel Labath
7629beb4567SJonas Devlieghere thread_obj.try_emplace("tid", static_cast<int64_t>(tid));
7639beb4567SJonas Devlieghere
76405569f67SPavel Labath if (signum != 0)
7659beb4567SJonas Devlieghere thread_obj.try_emplace("signal", signum);
76605569f67SPavel Labath
767e095cddbSMichał Górny const std::string thread_name = thread.GetName();
76805569f67SPavel Labath if (!thread_name.empty())
7699beb4567SJonas Devlieghere thread_obj.try_emplace("name", thread_name);
77005569f67SPavel Labath
7719beb4567SJonas Devlieghere const char *stop_reason = GetStopReasonString(tid_stop_info.reason);
7729beb4567SJonas Devlieghere if (stop_reason)
7739beb4567SJonas Devlieghere thread_obj.try_emplace("reason", stop_reason);
77405569f67SPavel Labath
77505569f67SPavel Labath if (!description.empty())
7769beb4567SJonas Devlieghere thread_obj.try_emplace("description", description);
77705569f67SPavel Labath
778b9c1b51eSKate Stone if ((tid_stop_info.reason == eStopReasonException) &&
779b9c1b51eSKate Stone tid_stop_info.details.exception.type) {
7809beb4567SJonas Devlieghere thread_obj.try_emplace(
7819beb4567SJonas Devlieghere "metype", static_cast<int64_t>(tid_stop_info.details.exception.type));
78205569f67SPavel Labath
7839beb4567SJonas Devlieghere json::Array medata_array;
784b9c1b51eSKate Stone for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
785b9c1b51eSKate Stone ++i) {
7869beb4567SJonas Devlieghere medata_array.push_back(
7879beb4567SJonas Devlieghere static_cast<int64_t>(tid_stop_info.details.exception.data[i]));
78805569f67SPavel Labath }
7899beb4567SJonas Devlieghere thread_obj.try_emplace("medata", std::move(medata_array));
79005569f67SPavel Labath }
7919beb4567SJonas Devlieghere threads_array.push_back(std::move(thread_obj));
79205569f67SPavel Labath }
7939beb4567SJonas Devlieghere return threads_array;
79405569f67SPavel Labath }
79505569f67SPavel Labath
796bc04d240SMichał Górny StreamString
PrepareStopReplyPacketForThread(NativeThreadProtocol & thread)797bc04d240SMichał Górny GDBRemoteCommunicationServerLLGS::PrepareStopReplyPacketForThread(
798bc04d240SMichał Górny NativeThreadProtocol &thread) {
799a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
800e13c2731STamas Berghammer
801bc04d240SMichał Górny NativeProcessProtocol &process = thread.GetProcess();
802e13c2731STamas Berghammer
803bc04d240SMichał Górny LLDB_LOG(log, "preparing packet for pid {0} tid {1}", process.GetID(),
804bc04d240SMichał Górny thread.GetID());
805e13c2731STamas Berghammer
806e13c2731STamas Berghammer // Grab the reason this thread stopped.
807bc04d240SMichał Górny StreamString response;
808e13c2731STamas Berghammer struct ThreadStopInfo tid_stop_info;
809e13c2731STamas Berghammer std::string description;
810bc04d240SMichał Górny if (!thread.GetStopReason(tid_stop_info, description))
811bc04d240SMichał Górny return response;
812e13c2731STamas Berghammer
813e13c2731STamas Berghammer // FIXME implement register handling for exec'd inferiors.
81405097246SAdrian Prantl // if (tid_stop_info.reason == eStopReasonExec) {
815e13c2731STamas Berghammer // const bool force = true;
816e13c2731STamas Berghammer // InitializeRegisters(force);
817e13c2731STamas Berghammer // }
818e13c2731STamas Berghammer
819e13c2731STamas Berghammer // Output the T packet with the thread
820e13c2731STamas Berghammer response.PutChar('T');
821d6b3de72SMichał Górny int signum = tid_stop_info.signo;
82282abefa4SPavel Labath LLDB_LOG(
82382abefa4SPavel Labath log,
82482abefa4SPavel Labath "pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
825bc04d240SMichał Górny process.GetID(), thread.GetID(), signum, int(tid_stop_info.reason),
82682abefa4SPavel Labath tid_stop_info.details.exception.type);
827e13c2731STamas Berghammer
828e13c2731STamas Berghammer // Print the signal number.
829e13c2731STamas Berghammer response.PutHex8(signum & 0xff);
830e13c2731STamas Berghammer
831ac570fbbSMichał Górny // Include the (pid and) tid.
832ac570fbbSMichał Górny response.PutCString("thread:");
8334b485fc0SMichał Górny AppendThreadIDToResponse(response, process.GetID(), thread.GetID());
8344b485fc0SMichał Górny response.PutChar(';');
835e13c2731STamas Berghammer
836e13c2731STamas Berghammer // Include the thread name if there is one.
837bc04d240SMichał Górny const std::string thread_name = thread.GetName();
838b9c1b51eSKate Stone if (!thread_name.empty()) {
839e13c2731STamas Berghammer size_t thread_name_len = thread_name.length();
840e13c2731STamas Berghammer
841b9c1b51eSKate Stone if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
842e13c2731STamas Berghammer response.PutCString("name:");
843771ef6d4SMalcolm Parsons response.PutCString(thread_name);
844b9c1b51eSKate Stone } else {
845e13c2731STamas Berghammer // The thread name contains special chars, send as hex bytes.
846e13c2731STamas Berghammer response.PutCString("hexname:");
8477f815a9aSPavel Labath response.PutStringAsRawHex8(thread_name);
848e13c2731STamas Berghammer }
849e13c2731STamas Berghammer response.PutChar(';');
850e13c2731STamas Berghammer }
851e13c2731STamas Berghammer
85205097246SAdrian Prantl // If a 'QListThreadsInStopReply' was sent to enable this feature, we will
85305097246SAdrian Prantl // send all thread IDs back in the "threads" key whose value is a list of hex
85405097246SAdrian Prantl // thread IDs separated by commas:
855e13c2731STamas Berghammer // "threads:10a,10b,10c;"
85605097246SAdrian Prantl // This will save the debugger from having to send a pair of qfThreadInfo and
85705097246SAdrian Prantl // qsThreadInfo packets, but it also might take a lot of room in the stop
85805097246SAdrian Prantl // reply packet, so it must be enabled only on systems where there are no
85905097246SAdrian Prantl // limits on packet lengths.
860b9c1b51eSKate Stone if (m_list_threads_in_stop_reply) {
861e13c2731STamas Berghammer response.PutCString("threads:");
862e13c2731STamas Berghammer
863e095cddbSMichał Górny uint32_t thread_num = 0;
864e095cddbSMichał Górny for (NativeThreadProtocol &listed_thread : process.Threads()) {
865e095cddbSMichał Górny if (thread_num > 0)
866e13c2731STamas Berghammer response.PutChar(',');
867e095cddbSMichał Górny response.Printf("%" PRIx64, listed_thread.GetID());
868e095cddbSMichał Górny ++thread_num;
869e13c2731STamas Berghammer }
870e13c2731STamas Berghammer response.PutChar(';');
87105569f67SPavel Labath
87205097246SAdrian Prantl // Include JSON info that describes the stop reason for any threads that
87305097246SAdrian Prantl // actually have stop reasons. We use the new "jstopinfo" key whose values
87405097246SAdrian Prantl // is hex ascii JSON that contains the thread IDs thread stop info only for
87505097246SAdrian Prantl // threads that have stop reasons. Only send this if we have more than one
87605097246SAdrian Prantl // thread otherwise this packet has all the info it needs.
877e095cddbSMichał Górny if (thread_num > 1) {
87805569f67SPavel Labath const bool threads_with_valid_stop_info_only = true;
8795f775d29SJonas Devlieghere llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo(
880f1812a28SMichał Górny *m_current_process, threads_with_valid_stop_info_only);
8819beb4567SJonas Devlieghere if (threads_info) {
88205569f67SPavel Labath response.PutCString("jstopinfo:");
88305569f67SPavel Labath StreamString unescaped_response;
8845f775d29SJonas Devlieghere unescaped_response.AsRawOstream() << std::move(*threads_info);
8857f815a9aSPavel Labath response.PutStringAsRawHex8(unescaped_response.GetData());
88605569f67SPavel Labath response.PutChar(';');
8879beb4567SJonas Devlieghere } else {
888926d2838SMartin Storsjö LLDB_LOG_ERROR(log, threads_info.takeError(),
889926d2838SMartin Storsjö "failed to prepare a jstopinfo field for pid {1}: {0}",
890af93f123SMichał Górny process.GetID());
8919beb4567SJonas Devlieghere }
89205569f67SPavel Labath }
893e0a5b575SPavel Labath
894e0a5b575SPavel Labath response.PutCString("thread-pcs");
895e0a5b575SPavel Labath char delimiter = ':';
896e095cddbSMichał Górny for (NativeThreadProtocol &thread : process.Threads()) {
897e095cddbSMichał Górny NativeRegisterContext ®_ctx = thread.GetRegisterContext();
898e0a5b575SPavel Labath
899d37349f3SPavel Labath uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
900e0a5b575SPavel Labath eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
901e0a5b575SPavel Labath const RegisterInfo *const reg_info_p =
902d37349f3SPavel Labath reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
903e0a5b575SPavel Labath
904e0a5b575SPavel Labath RegisterValue reg_value;
905d37349f3SPavel Labath Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
906e0a5b575SPavel Labath if (error.Fail()) {
90763e5fb76SJonas Devlieghere LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
908e0a5b575SPavel Labath __FUNCTION__,
90963e5fb76SJonas Devlieghere reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
910e0a5b575SPavel Labath reg_to_read, error.AsCString());
911e0a5b575SPavel Labath continue;
912e0a5b575SPavel Labath }
913e0a5b575SPavel Labath
914e0a5b575SPavel Labath response.PutChar(delimiter);
915e0a5b575SPavel Labath delimiter = ',';
916d37349f3SPavel Labath WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
917e0a5b575SPavel Labath ®_value, endian::InlHostByteOrder());
918e0a5b575SPavel Labath }
919e0a5b575SPavel Labath
920e0a5b575SPavel Labath response.PutChar(';');
921e13c2731STamas Berghammer }
922e13c2731STamas Berghammer
923e13c2731STamas Berghammer //
924e13c2731STamas Berghammer // Expedite registers.
925e13c2731STamas Berghammer //
926e13c2731STamas Berghammer
927e13c2731STamas Berghammer // Grab the register context.
928bc04d240SMichał Górny NativeRegisterContext ®_ctx = thread.GetRegisterContext();
929b69c09bfSMuhammad Omair Javaid const auto expedited_regs =
930b69c09bfSMuhammad Omair Javaid reg_ctx.GetExpeditedRegisters(ExpeditedRegs::Full);
931e13c2731STamas Berghammer
932b69c09bfSMuhammad Omair Javaid for (auto ®_num : expedited_regs) {
933b9c1b51eSKate Stone const RegisterInfo *const reg_info_p =
934b69c09bfSMuhammad Omair Javaid reg_ctx.GetRegisterInfoAtIndex(reg_num);
935e609fe68SMuhammad Omair Javaid // Only expediate registers that are not contained in other registers.
936b69c09bfSMuhammad Omair Javaid if (reg_info_p != nullptr && reg_info_p->value_regs == nullptr) {
937e13c2731STamas Berghammer RegisterValue reg_value;
938d37349f3SPavel Labath Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
939b9c1b51eSKate Stone if (error.Success()) {
940b69c09bfSMuhammad Omair Javaid response.Printf("%.02x:", reg_num);
941d37349f3SPavel Labath WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
942e0a5b575SPavel Labath ®_value, lldb::eByteOrderBig);
943caf31142SChaoren Lin response.PutChar(';');
944b9c1b51eSKate Stone } else {
945bc04d240SMichał Górny LLDB_LOGF(log,
946bc04d240SMichał Górny "GDBRemoteCommunicationServerLLGS::%s failed to read "
947b9c1b51eSKate Stone "register '%s' index %" PRIu32 ": %s",
948d37349f3SPavel Labath __FUNCTION__,
94963e5fb76SJonas Devlieghere reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
950b69c09bfSMuhammad Omair Javaid reg_num, error.AsCString());
951e13c2731STamas Berghammer }
952e13c2731STamas Berghammer }
953e13c2731STamas Berghammer }
954e13c2731STamas Berghammer
9554a4bb12eSPavel Labath const char *reason_str = GetStopReasonString(tid_stop_info.reason);
956b9c1b51eSKate Stone if (reason_str != nullptr) {
957e13c2731STamas Berghammer response.Printf("reason:%s;", reason_str);
958e13c2731STamas Berghammer }
959e13c2731STamas Berghammer
960b9c1b51eSKate Stone if (!description.empty()) {
961e13c2731STamas Berghammer // Description may contains special chars, send as hex bytes.
962e13c2731STamas Berghammer response.PutCString("description:");
9637f815a9aSPavel Labath response.PutStringAsRawHex8(description);
964e13c2731STamas Berghammer response.PutChar(';');
965b9c1b51eSKate Stone } else if ((tid_stop_info.reason == eStopReasonException) &&
966b9c1b51eSKate Stone tid_stop_info.details.exception.type) {
967e13c2731STamas Berghammer response.PutCString("metype:");
968e13c2731STamas Berghammer response.PutHex64(tid_stop_info.details.exception.type);
969e13c2731STamas Berghammer response.PutCString(";mecount:");
970e13c2731STamas Berghammer response.PutHex32(tid_stop_info.details.exception.data_count);
971e13c2731STamas Berghammer response.PutChar(';');
972e13c2731STamas Berghammer
973b9c1b51eSKate Stone for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
974e13c2731STamas Berghammer response.PutCString("medata:");
975e13c2731STamas Berghammer response.PutHex64(tid_stop_info.details.exception.data[i]);
976e13c2731STamas Berghammer response.PutChar(';');
977e13c2731STamas Berghammer }
978e13c2731STamas Berghammer }
979e13c2731STamas Berghammer
9806c37984eSMichał Górny // Include child process PID/TID for forks.
9816c37984eSMichał Górny if (tid_stop_info.reason == eStopReasonFork ||
9826c37984eSMichał Górny tid_stop_info.reason == eStopReasonVFork) {
9836c37984eSMichał Górny assert(bool(m_extensions_supported &
9846c37984eSMichał Górny NativeProcessProtocol::Extension::multiprocess));
9856c37984eSMichał Górny if (tid_stop_info.reason == eStopReasonFork)
9866c37984eSMichał Górny assert(bool(m_extensions_supported &
9876c37984eSMichał Górny NativeProcessProtocol::Extension::fork));
9886c37984eSMichał Górny if (tid_stop_info.reason == eStopReasonVFork)
9896c37984eSMichał Górny assert(bool(m_extensions_supported &
9906c37984eSMichał Górny NativeProcessProtocol::Extension::vfork));
9916c37984eSMichał Górny response.Printf("%s:p%" PRIx64 ".%" PRIx64 ";", reason_str,
9926c37984eSMichał Górny tid_stop_info.details.fork.child_pid,
9936c37984eSMichał Górny tid_stop_info.details.fork.child_tid);
9946c37984eSMichał Górny }
9956c37984eSMichał Górny
996bc04d240SMichał Górny return response;
997bc04d240SMichał Górny }
998bc04d240SMichał Górny
999bc04d240SMichał Górny GDBRemoteCommunication::PacketResult
SendStopReplyPacketForThread(NativeProcessProtocol & process,lldb::tid_t tid,bool force_synchronous)1000bc04d240SMichał Górny GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
1001bc04d240SMichał Górny NativeProcessProtocol &process, lldb::tid_t tid, bool force_synchronous) {
1002bc04d240SMichał Górny // Ensure we can get info on the given thread.
1003bc04d240SMichał Górny NativeThreadProtocol *thread = process.GetThreadByID(tid);
1004bc04d240SMichał Górny if (!thread)
1005bc04d240SMichał Górny return SendErrorResponse(51);
1006bc04d240SMichał Górny
1007bc04d240SMichał Górny StreamString response = PrepareStopReplyPacketForThread(*thread);
1008bc04d240SMichał Górny if (response.Empty())
1009bc04d240SMichał Górny return SendErrorResponse(42);
1010bc04d240SMichał Górny
1011bc04d240SMichał Górny if (m_non_stop && !force_synchronous) {
1012bc04d240SMichał Górny PacketResult ret = SendNotificationPacketNoLock(
1013bc04d240SMichał Górny "Stop", m_stop_notification_queue, response.GetString());
1014bc04d240SMichał Górny // Queue notification events for the remaining threads.
1015bc04d240SMichał Górny EnqueueStopReplyPackets(tid);
1016bc04d240SMichał Górny return ret;
1017bc04d240SMichał Górny }
1018bc04d240SMichał Górny
101926709df8SZachary Turner return SendPacketNoLock(response.GetString());
1020e13c2731STamas Berghammer }
1021e13c2731STamas Berghammer
EnqueueStopReplyPackets(lldb::tid_t thread_to_skip)1022bc04d240SMichał Górny void GDBRemoteCommunicationServerLLGS::EnqueueStopReplyPackets(
1023bc04d240SMichał Górny lldb::tid_t thread_to_skip) {
1024bc04d240SMichał Górny if (!m_non_stop)
1025bc04d240SMichał Górny return;
1026bc04d240SMichał Górny
1027e095cddbSMichał Górny for (NativeThreadProtocol &listed_thread : m_current_process->Threads()) {
1028ab9f1e88SMichał Górny if (listed_thread.GetID() != thread_to_skip) {
1029ab9f1e88SMichał Górny StreamString stop_reply = PrepareStopReplyPacketForThread(listed_thread);
1030ab9f1e88SMichał Górny if (!stop_reply.Empty())
1031ab9f1e88SMichał Górny m_stop_notification_queue.push_back(stop_reply.GetString().str());
1032ab9f1e88SMichał Górny }
1033bc04d240SMichał Górny }
1034bc04d240SMichał Górny }
1035bc04d240SMichał Górny
HandleInferiorState_Exited(NativeProcessProtocol * process)1036b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
1037b9c1b51eSKate Stone NativeProcessProtocol *process) {
1038e13c2731STamas Berghammer assert(process && "process cannot be NULL");
1039e13c2731STamas Berghammer
1040a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
104163e5fb76SJonas Devlieghere LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1042e13c2731STamas Berghammer
1043bc04d240SMichał Górny PacketResult result = SendStopReasonForState(
1044bc04d240SMichał Górny *process, StateType::eStateExited, /*force_synchronous=*/false);
1045b9c1b51eSKate Stone if (result != PacketResult::Success) {
104663e5fb76SJonas Devlieghere LLDB_LOGF(log,
104763e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1048b9c1b51eSKate Stone "notification for PID %" PRIu64 ", state: eStateExited",
1049b9c1b51eSKate Stone __FUNCTION__, process->GetID());
1050e13c2731STamas Berghammer }
1051e13c2731STamas Berghammer
1052e8fe7e93SMichał Górny if (m_current_process == process)
1053e8fe7e93SMichał Górny m_current_process = nullptr;
1054e8fe7e93SMichał Górny if (m_continue_process == process)
1055e8fe7e93SMichał Górny m_continue_process = nullptr;
1056e13c2731STamas Berghammer
1057e8fe7e93SMichał Górny lldb::pid_t pid = process->GetID();
1058e8fe7e93SMichał Górny m_mainloop.AddPendingCallback([this, pid](MainLoopBase &loop) {
1059355c7916SMichał Górny auto find_it = m_debugged_processes.find(pid);
1060355c7916SMichał Górny assert(find_it != m_debugged_processes.end());
1061355c7916SMichał Górny bool vkilled = bool(find_it->second.flags & DebuggedProcess::Flag::vkilled);
1062355c7916SMichał Górny m_debugged_processes.erase(find_it);
1063c18784baSMichał Górny // Terminate the main loop only if vKill has not been used.
1064bc04d240SMichał Górny // When running in non-stop mode, wait for the vStopped to clear
1065bc04d240SMichał Górny // the notification queue.
1066355c7916SMichał Górny if (m_debugged_processes.empty() && !m_non_stop && !vkilled) {
1067e8fe7e93SMichał Górny // Close the pipe to the inferior terminal i/o if we launched it and set
1068e8fe7e93SMichał Górny // one up.
1069e8fe7e93SMichał Górny MaybeCloseInferiorTerminalConnection();
1070e8fe7e93SMichał Górny
1071e13c2731STamas Berghammer // We are ready to exit the debug monitor.
1072e13c2731STamas Berghammer m_exit_now = true;
1073e8fe7e93SMichał Górny loop.RequestTermination();
1074e13c2731STamas Berghammer }
1075e8fe7e93SMichał Górny });
1076bc04d240SMichał Górny }
1077e13c2731STamas Berghammer
HandleInferiorState_Stopped(NativeProcessProtocol * process)1078b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
1079b9c1b51eSKate Stone NativeProcessProtocol *process) {
1080e13c2731STamas Berghammer assert(process && "process cannot be NULL");
1081e13c2731STamas Berghammer
1082a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
108363e5fb76SJonas Devlieghere LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1084e13c2731STamas Berghammer
1085bc04d240SMichał Górny PacketResult result = SendStopReasonForState(
1086bc04d240SMichał Górny *process, StateType::eStateStopped, /*force_synchronous=*/false);
1087b9c1b51eSKate Stone if (result != PacketResult::Success) {
108863e5fb76SJonas Devlieghere LLDB_LOGF(log,
108963e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed to send stop "
1090b9c1b51eSKate Stone "notification for PID %" PRIu64 ", state: eStateExited",
1091b9c1b51eSKate Stone __FUNCTION__, process->GetID());
1092e13c2731STamas Berghammer }
1093e13c2731STamas Berghammer }
1094e13c2731STamas Berghammer
ProcessStateChanged(NativeProcessProtocol * process,lldb::StateType state)1095b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
1096b9c1b51eSKate Stone NativeProcessProtocol *process, lldb::StateType state) {
1097e13c2731STamas Berghammer assert(process && "process cannot be NULL");
1098a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
1099b9c1b51eSKate Stone if (log) {
110063e5fb76SJonas Devlieghere LLDB_LOGF(log,
110163e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s called with "
1102b9c1b51eSKate Stone "NativeProcessProtocol pid %" PRIu64 ", state: %s",
1103b9c1b51eSKate Stone __FUNCTION__, process->GetID(), StateAsCString(state));
1104e13c2731STamas Berghammer }
1105e13c2731STamas Berghammer
1106b9c1b51eSKate Stone switch (state) {
1107abadc221SPavel Labath case StateType::eStateRunning:
1108abadc221SPavel Labath break;
1109abadc221SPavel Labath
1110abadc221SPavel Labath case StateType::eStateStopped:
111105097246SAdrian Prantl // Make sure we get all of the pending stdout/stderr from the inferior and
111205097246SAdrian Prantl // send it to the lldb host before we send the state change notification
1113c7749c3aSPavel Labath SendProcessOutput();
1114b9c1b51eSKate Stone // Then stop the forwarding, so that any late output (see llvm.org/pr25652)
111505097246SAdrian Prantl // does not interfere with our protocol.
111609531edeSMichał Górny if (!m_non_stop)
1117abadc221SPavel Labath StopSTDIOForwarding();
1118abadc221SPavel Labath HandleInferiorState_Stopped(process);
1119e13c2731STamas Berghammer break;
1120e13c2731STamas Berghammer
1121abadc221SPavel Labath case StateType::eStateExited:
1122abadc221SPavel Labath // Same as above
1123abadc221SPavel Labath SendProcessOutput();
112409531edeSMichał Górny if (!m_non_stop)
1125abadc221SPavel Labath StopSTDIOForwarding();
1126abadc221SPavel Labath HandleInferiorState_Exited(process);
1127e13c2731STamas Berghammer break;
1128e13c2731STamas Berghammer
1129e13c2731STamas Berghammer default:
1130b9c1b51eSKate Stone if (log) {
113163e5fb76SJonas Devlieghere LLDB_LOGF(log,
113263e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s didn't handle state "
1133b9c1b51eSKate Stone "change for pid %" PRIu64 ", new state: %s",
1134b9c1b51eSKate Stone __FUNCTION__, process->GetID(), StateAsCString(state));
1135e13c2731STamas Berghammer }
1136e13c2731STamas Berghammer break;
1137e13c2731STamas Berghammer }
1138e13c2731STamas Berghammer }
1139e13c2731STamas Berghammer
DidExec(NativeProcessProtocol * process)1140b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
1141e13c2731STamas Berghammer ClearProcessSpecificData();
1142e13c2731STamas Berghammer }
1143e13c2731STamas Berghammer
NewSubprocess(NativeProcessProtocol * parent_process,std::unique_ptr<NativeProcessProtocol> child_process)1144bbae0c1fSMichał Górny void GDBRemoteCommunicationServerLLGS::NewSubprocess(
1145bbae0c1fSMichał Górny NativeProcessProtocol *parent_process,
1146bbae0c1fSMichał Górny std::unique_ptr<NativeProcessProtocol> child_process) {
1147bbae0c1fSMichał Górny lldb::pid_t child_pid = child_process->GetID();
1148bbae0c1fSMichał Górny assert(child_pid != LLDB_INVALID_PROCESS_ID);
1149bbae0c1fSMichał Górny assert(m_debugged_processes.find(child_pid) == m_debugged_processes.end());
1150355c7916SMichał Górny m_debugged_processes.emplace(
1151355c7916SMichał Górny child_pid,
1152355c7916SMichał Górny DebuggedProcess{std::move(child_process), DebuggedProcess::Flag{}});
1153bbae0c1fSMichał Górny }
1154bbae0c1fSMichał Górny
DataAvailableCallback()1155b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
11560f08db66SPavel Labath Log *log = GetLog(GDBRLog::Comm);
115777dc9569SPavel Labath
115877dc9569SPavel Labath bool interrupt = false;
115977dc9569SPavel Labath bool done = false;
116097206d57SZachary Turner Status error;
1161b9c1b51eSKate Stone while (true) {
11621eff73c3SPavel Labath const PacketResult result = GetPacketAndSendResponse(
11631eff73c3SPavel Labath std::chrono::microseconds(0), error, interrupt, done);
116477dc9569SPavel Labath if (result == PacketResult::ErrorReplyTimeout)
116577dc9569SPavel Labath break; // No more packets in the queue
116677dc9569SPavel Labath
1167b9c1b51eSKate Stone if ((result != PacketResult::Success)) {
116863e5fb76SJonas Devlieghere LLDB_LOGF(log,
116963e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s processing a packet "
1170b9c1b51eSKate Stone "failed: %s",
117177dc9569SPavel Labath __FUNCTION__, error.AsCString());
117277dc9569SPavel Labath m_mainloop.RequestTermination();
117377dc9569SPavel Labath break;
117477dc9569SPavel Labath }
117577dc9569SPavel Labath }
117677dc9569SPavel Labath }
117777dc9569SPavel Labath
InitializeConnection(std::unique_ptr<Connection> connection)117897206d57SZachary Turner Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
1179451741a9SPavel Labath std::unique_ptr<Connection> connection) {
118077dc9569SPavel Labath IOObjectSP read_object_sp = connection->GetReadObject();
1181451741a9SPavel Labath GDBRemoteCommunicationServer::SetConnection(std::move(connection));
118277dc9569SPavel Labath
118397206d57SZachary Turner Status error;
1184b9c1b51eSKate Stone m_network_handle_up = m_mainloop.RegisterReadObject(
1185b9c1b51eSKate Stone read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
1186b9c1b51eSKate Stone error);
118777dc9569SPavel Labath return error;
118877dc9569SPavel Labath }
118977dc9569SPavel Labath
1190e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
SendONotification(const char * buffer,uint32_t len)1191b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
1192b9c1b51eSKate Stone uint32_t len) {
1193b9c1b51eSKate Stone if ((buffer == nullptr) || (len == 0)) {
1194e13c2731STamas Berghammer // Nothing to send.
1195e13c2731STamas Berghammer return PacketResult::Success;
1196e13c2731STamas Berghammer }
1197e13c2731STamas Berghammer
1198e13c2731STamas Berghammer StreamString response;
1199e13c2731STamas Berghammer response.PutChar('O');
1200e13c2731STamas Berghammer response.PutBytesAsRawHex8(buffer, len);
1201e13c2731STamas Berghammer
12021903f358SMichał Górny if (m_non_stop)
12031903f358SMichał Górny return SendNotificationPacketNoLock("Stdio", m_stdio_notification_queue,
12041903f358SMichał Górny response.GetString());
120526709df8SZachary Turner return SendPacketNoLock(response.GetString());
1206e13c2731STamas Berghammer }
1207e13c2731STamas Berghammer
SetSTDIOFileDescriptor(int fd)120897206d57SZachary Turner Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
120997206d57SZachary Turner Status error;
1210e13c2731STamas Berghammer
1211c7749c3aSPavel Labath // Set up the reading/handling of process I/O
1212b9c1b51eSKate Stone std::unique_ptr<ConnectionFileDescriptor> conn_up(
1213b9c1b51eSKate Stone new ConnectionFileDescriptor(fd, true));
1214b9c1b51eSKate Stone if (!conn_up) {
1215e13c2731STamas Berghammer error.SetErrorString("failed to create ConnectionFileDescriptor");
1216e13c2731STamas Berghammer return error;
1217e13c2731STamas Berghammer }
1218e13c2731STamas Berghammer
121900bdca68STamas Berghammer m_stdio_communication.SetCloseOnEOF(false);
1220451741a9SPavel Labath m_stdio_communication.SetConnection(std::move(conn_up));
1221b9c1b51eSKate Stone if (!m_stdio_communication.IsConnected()) {
1222b9c1b51eSKate Stone error.SetErrorString(
1223b9c1b51eSKate Stone "failed to set connection for inferior I/O communication");
1224e13c2731STamas Berghammer return error;
1225e13c2731STamas Berghammer }
1226e13c2731STamas Berghammer
122797206d57SZachary Turner return Status();
1228abadc221SPavel Labath }
1229abadc221SPavel Labath
StartSTDIOForwarding()1230b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
1231abadc221SPavel Labath // Don't forward if not connected (e.g. when attaching).
1232abadc221SPavel Labath if (!m_stdio_communication.IsConnected())
1233abadc221SPavel Labath return;
1234abadc221SPavel Labath
123597206d57SZachary Turner Status error;
1236e8fe7e93SMichał Górny assert(!m_stdio_handle_up);
1237c7749c3aSPavel Labath m_stdio_handle_up = m_mainloop.RegisterReadObject(
1238c7749c3aSPavel Labath m_stdio_communication.GetConnection()->GetReadObject(),
1239c7749c3aSPavel Labath [this](MainLoopBase &) { SendProcessOutput(); }, error);
1240abadc221SPavel Labath
1241b9c1b51eSKate Stone if (!m_stdio_handle_up) {
1242b9c1b51eSKate Stone // Not much we can do about the failure. Log it and continue without
1243b9c1b51eSKate Stone // forwarding.
1244a007a6d8SPavel Labath if (Log *log = GetLog(LLDBLog::Process))
1245e8fe7e93SMichał Górny LLDB_LOG(log, "Failed to set up stdio forwarding: {0}", error);
1246c7749c3aSPavel Labath }
12474a8abd3fSVince Harron }
1248e13c2731STamas Berghammer
StopSTDIOForwarding()1249b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
1250c7749c3aSPavel Labath m_stdio_handle_up.reset();
1251c7749c3aSPavel Labath }
1252c7749c3aSPavel Labath
SendProcessOutput()1253b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
1254c7749c3aSPavel Labath char buffer[1024];
1255c7749c3aSPavel Labath ConnectionStatus status;
125697206d57SZachary Turner Status error;
1257b9c1b51eSKate Stone while (true) {
1258c4063eeeSPavel Labath size_t bytes_read = m_stdio_communication.Read(
1259c4063eeeSPavel Labath buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
1260b9c1b51eSKate Stone switch (status) {
1261c7749c3aSPavel Labath case eConnectionStatusSuccess:
1262c7749c3aSPavel Labath SendONotification(buffer, bytes_read);
1263c7749c3aSPavel Labath break;
1264c7749c3aSPavel Labath case eConnectionStatusLostConnection:
1265c7749c3aSPavel Labath case eConnectionStatusEndOfFile:
1266c7749c3aSPavel Labath case eConnectionStatusError:
1267c7749c3aSPavel Labath case eConnectionStatusNoConnection:
1268a007a6d8SPavel Labath if (Log *log = GetLog(LLDBLog::Process))
126963e5fb76SJonas Devlieghere LLDB_LOGF(log,
127063e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
1271b9c1b51eSKate Stone "forwarding as communication returned status %d (error: "
1272b9c1b51eSKate Stone "%s)",
1273b9c1b51eSKate Stone __FUNCTION__, status, error.AsCString());
1274c7749c3aSPavel Labath m_stdio_handle_up.reset();
1275c7749c3aSPavel Labath return;
1276c7749c3aSPavel Labath
1277c7749c3aSPavel Labath case eConnectionStatusInterrupted:
1278c7749c3aSPavel Labath case eConnectionStatusTimedOut:
1279c7749c3aSPavel Labath return;
1280c7749c3aSPavel Labath }
1281c7749c3aSPavel Labath }
1282e13c2731STamas Berghammer }
1283e13c2731STamas Berghammer
1284e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceSupported(StringExtractorGDBRemote & packet)12850b697561SWalter Erquinigo GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceSupported(
128621555fffSWalter Erquinigo StringExtractorGDBRemote &packet) {
128721555fffSWalter Erquinigo
128821555fffSWalter Erquinigo // Fail if we don't have a current process.
1289f1812a28SMichał Górny if (!m_current_process ||
1290f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
129121555fffSWalter Erquinigo return SendErrorResponse(Status("Process not running."));
129221555fffSWalter Erquinigo
1293f1812a28SMichał Górny return SendJSONResponse(m_current_process->TraceSupported());
129421555fffSWalter Erquinigo }
129521555fffSWalter Erquinigo
129621555fffSWalter Erquinigo GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceStop(StringExtractorGDBRemote & packet)12970b697561SWalter Erquinigo GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStop(
12980b697561SWalter Erquinigo StringExtractorGDBRemote &packet) {
12990b697561SWalter Erquinigo // Fail if we don't have a current process.
1300f1812a28SMichał Górny if (!m_current_process ||
1301f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
13020b697561SWalter Erquinigo return SendErrorResponse(Status("Process not running."));
13030b697561SWalter Erquinigo
13040b697561SWalter Erquinigo packet.ConsumeFront("jLLDBTraceStop:");
13050b697561SWalter Erquinigo Expected<TraceStopRequest> stop_request =
13060b697561SWalter Erquinigo json::parse<TraceStopRequest>(packet.Peek(), "TraceStopRequest");
13070b697561SWalter Erquinigo if (!stop_request)
13080b697561SWalter Erquinigo return SendErrorResponse(stop_request.takeError());
13090b697561SWalter Erquinigo
1310f1812a28SMichał Górny if (Error err = m_current_process->TraceStop(*stop_request))
13110b697561SWalter Erquinigo return SendErrorResponse(std::move(err));
13120b697561SWalter Erquinigo
13130b697561SWalter Erquinigo return SendOKResponse();
13140b697561SWalter Erquinigo }
13150b697561SWalter Erquinigo
13160b697561SWalter Erquinigo GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceStart(StringExtractorGDBRemote & packet)13170b697561SWalter Erquinigo GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceStart(
1318e714c4f5SRavitheja Addepally StringExtractorGDBRemote &packet) {
1319e714c4f5SRavitheja Addepally
1320e714c4f5SRavitheja Addepally // Fail if we don't have a current process.
1321f1812a28SMichał Górny if (!m_current_process ||
1322f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
13230b697561SWalter Erquinigo return SendErrorResponse(Status("Process not running."));
1324e714c4f5SRavitheja Addepally
13250b697561SWalter Erquinigo packet.ConsumeFront("jLLDBTraceStart:");
13260b697561SWalter Erquinigo Expected<TraceStartRequest> request =
13270b697561SWalter Erquinigo json::parse<TraceStartRequest>(packet.Peek(), "TraceStartRequest");
13280b697561SWalter Erquinigo if (!request)
13290b697561SWalter Erquinigo return SendErrorResponse(request.takeError());
1330e714c4f5SRavitheja Addepally
1331f1812a28SMichał Górny if (Error err = m_current_process->TraceStart(packet.Peek(), request->type))
13320b697561SWalter Erquinigo return SendErrorResponse(std::move(err));
1333e714c4f5SRavitheja Addepally
13340b697561SWalter Erquinigo return SendOKResponse();
1335e714c4f5SRavitheja Addepally }
1336e714c4f5SRavitheja Addepally
1337e714c4f5SRavitheja Addepally GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceGetState(StringExtractorGDBRemote & packet)13380b697561SWalter Erquinigo GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetState(
1339e714c4f5SRavitheja Addepally StringExtractorGDBRemote &packet) {
1340e714c4f5SRavitheja Addepally
1341e714c4f5SRavitheja Addepally // Fail if we don't have a current process.
1342f1812a28SMichał Górny if (!m_current_process ||
1343f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
13440b697561SWalter Erquinigo return SendErrorResponse(Status("Process not running."));
1345e714c4f5SRavitheja Addepally
13460b697561SWalter Erquinigo packet.ConsumeFront("jLLDBTraceGetState:");
13470b697561SWalter Erquinigo Expected<TraceGetStateRequest> request =
13480b697561SWalter Erquinigo json::parse<TraceGetStateRequest>(packet.Peek(), "TraceGetStateRequest");
13490b697561SWalter Erquinigo if (!request)
13500b697561SWalter Erquinigo return SendErrorResponse(request.takeError());
1351e714c4f5SRavitheja Addepally
1352f1812a28SMichał Górny return SendJSONResponse(m_current_process->TraceGetState(request->type));
1353e714c4f5SRavitheja Addepally }
1354e714c4f5SRavitheja Addepally
13550b697561SWalter Erquinigo GDBRemoteCommunication::PacketResult
Handle_jLLDBTraceGetBinaryData(StringExtractorGDBRemote & packet)13560b697561SWalter Erquinigo GDBRemoteCommunicationServerLLGS::Handle_jLLDBTraceGetBinaryData(
13570b697561SWalter Erquinigo StringExtractorGDBRemote &packet) {
1358e714c4f5SRavitheja Addepally
13590b697561SWalter Erquinigo // Fail if we don't have a current process.
1360f1812a28SMichał Górny if (!m_current_process ||
1361f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
13620b697561SWalter Erquinigo return SendErrorResponse(Status("Process not running."));
1363e714c4f5SRavitheja Addepally
13640b697561SWalter Erquinigo packet.ConsumeFront("jLLDBTraceGetBinaryData:");
13650b697561SWalter Erquinigo llvm::Expected<TraceGetBinaryDataRequest> request =
13660b697561SWalter Erquinigo llvm::json::parse<TraceGetBinaryDataRequest>(packet.Peek(),
13670b697561SWalter Erquinigo "TraceGetBinaryDataRequest");
13680b697561SWalter Erquinigo if (!request)
13690b697561SWalter Erquinigo return SendErrorResponse(Status(request.takeError()));
1370e714c4f5SRavitheja Addepally
13710b697561SWalter Erquinigo if (Expected<std::vector<uint8_t>> bytes =
1372f1812a28SMichał Górny m_current_process->TraceGetBinaryData(*request)) {
1373e714c4f5SRavitheja Addepally StreamGDBRemote response;
13740b697561SWalter Erquinigo response.PutEscapedBytes(bytes->data(), bytes->size());
13750b697561SWalter Erquinigo return SendPacketNoLock(response.GetString());
13760b697561SWalter Erquinigo } else
13770b697561SWalter Erquinigo return SendErrorResponse(bytes.takeError());
1378e714c4f5SRavitheja Addepally }
1379e714c4f5SRavitheja Addepally
1380e714c4f5SRavitheja Addepally GDBRemoteCommunication::PacketResult
Handle_qProcessInfo(StringExtractorGDBRemote & packet)1381b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
1382b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
1383e13c2731STamas Berghammer // Fail if we don't have a current process.
1384f1812a28SMichał Górny if (!m_current_process ||
1385f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1386e13c2731STamas Berghammer return SendErrorResponse(68);
1387e13c2731STamas Berghammer
1388f1812a28SMichał Górny lldb::pid_t pid = m_current_process->GetID();
1389e13c2731STamas Berghammer
1390e13c2731STamas Berghammer if (pid == LLDB_INVALID_PROCESS_ID)
1391e13c2731STamas Berghammer return SendErrorResponse(1);
1392e13c2731STamas Berghammer
1393e13c2731STamas Berghammer ProcessInstanceInfo proc_info;
1394e13c2731STamas Berghammer if (!Host::GetProcessInfo(pid, proc_info))
1395e13c2731STamas Berghammer return SendErrorResponse(1);
1396e13c2731STamas Berghammer
1397e13c2731STamas Berghammer StreamString response;
1398e13c2731STamas Berghammer CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
139926709df8SZachary Turner return SendPacketNoLock(response.GetString());
1400e13c2731STamas Berghammer }
1401e13c2731STamas Berghammer
1402e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_qC(StringExtractorGDBRemote & packet)1403b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
1404e13c2731STamas Berghammer // Fail if we don't have a current process.
1405f1812a28SMichał Górny if (!m_current_process ||
1406f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1407e13c2731STamas Berghammer return SendErrorResponse(68);
1408e13c2731STamas Berghammer
140905097246SAdrian Prantl // Make sure we set the current thread so g and p packets return the data the
141005097246SAdrian Prantl // gdb will expect.
1411f1812a28SMichał Górny lldb::tid_t tid = m_current_process->GetCurrentThreadID();
1412e13c2731STamas Berghammer SetCurrentThreadID(tid);
1413e13c2731STamas Berghammer
1414f1812a28SMichał Górny NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
1415a5be48b3SPavel Labath if (!thread)
1416e13c2731STamas Berghammer return SendErrorResponse(69);
1417e13c2731STamas Berghammer
1418e13c2731STamas Berghammer StreamString response;
1419630da0e3SMichał Górny response.PutCString("QC");
14204b485fc0SMichał Górny AppendThreadIDToResponse(response, m_current_process->GetID(),
14214b485fc0SMichał Górny thread->GetID());
1422e13c2731STamas Berghammer
142326709df8SZachary Turner return SendPacketNoLock(response.GetString());
1424e13c2731STamas Berghammer }
1425e13c2731STamas Berghammer
1426e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_k(StringExtractorGDBRemote & packet)1427b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
1428a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
1429e13c2731STamas Berghammer
143009531edeSMichał Górny if (!m_non_stop)
1431c7749c3aSPavel Labath StopSTDIOForwarding();
1432e13c2731STamas Berghammer
1433e8fe7e93SMichał Górny if (m_debugged_processes.empty()) {
143482abefa4SPavel Labath LLDB_LOG(log, "No debugged process found.");
1435424b201dSPavel Labath return PacketResult::Success;
1436424b201dSPavel Labath }
1437424b201dSPavel Labath
1438e8fe7e93SMichał Górny for (auto it = m_debugged_processes.begin(); it != m_debugged_processes.end();
1439e8fe7e93SMichał Górny ++it) {
1440e8fe7e93SMichał Górny LLDB_LOG(log, "Killing process {0}", it->first);
1441355c7916SMichał Górny Status error = it->second.process_up->Kill();
144282abefa4SPavel Labath if (error.Fail())
1443e8fe7e93SMichał Górny LLDB_LOG(log, "Failed to kill debugged process {0}: {1}", it->first,
1444e8fe7e93SMichał Górny error);
1445e8fe7e93SMichał Górny }
1446424b201dSPavel Labath
1447bc04d240SMichał Górny // The response to kill packet is undefined per the spec. LLDB
1448bc04d240SMichał Górny // follows the same rules as for continue packets, i.e. no response
1449bc04d240SMichał Górny // in all-stop mode, and "OK" in non-stop mode; in both cases this
1450bc04d240SMichał Górny // is followed by the actual stop reason.
1451bc04d240SMichał Górny return SendContinueSuccessResponse();
1452e13c2731STamas Berghammer }
1453e13c2731STamas Berghammer
1454e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_vKill(StringExtractorGDBRemote & packet)1455c18784baSMichał Górny GDBRemoteCommunicationServerLLGS::Handle_vKill(
1456c18784baSMichał Górny StringExtractorGDBRemote &packet) {
145709531edeSMichał Górny if (!m_non_stop)
1458c18784baSMichał Górny StopSTDIOForwarding();
1459c18784baSMichał Górny
1460c18784baSMichał Górny packet.SetFilePos(6); // vKill;
1461c18784baSMichał Górny uint32_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
1462c18784baSMichał Górny if (pid == LLDB_INVALID_PROCESS_ID)
1463c18784baSMichał Górny return SendIllFormedResponse(packet,
1464c18784baSMichał Górny "vKill failed to parse the process id");
1465c18784baSMichał Górny
1466c18784baSMichał Górny auto it = m_debugged_processes.find(pid);
1467c18784baSMichał Górny if (it == m_debugged_processes.end())
1468c18784baSMichał Górny return SendErrorResponse(42);
1469c18784baSMichał Górny
1470355c7916SMichał Górny Status error = it->second.process_up->Kill();
1471c18784baSMichał Górny if (error.Fail())
1472c18784baSMichał Górny return SendErrorResponse(error.ToError());
1473c18784baSMichał Górny
1474c18784baSMichał Górny // OK response is sent when the process dies.
1475355c7916SMichał Górny it->second.flags |= DebuggedProcess::Flag::vkilled;
1476c18784baSMichał Górny return PacketResult::Success;
1477c18784baSMichał Górny }
1478c18784baSMichał Górny
1479c18784baSMichał Górny GDBRemoteCommunication::PacketResult
Handle_QSetDisableASLR(StringExtractorGDBRemote & packet)1480b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
1481b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
1482e13c2731STamas Berghammer packet.SetFilePos(::strlen("QSetDisableASLR:"));
1483e13c2731STamas Berghammer if (packet.GetU32(0))
1484e13c2731STamas Berghammer m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
1485e13c2731STamas Berghammer else
1486e13c2731STamas Berghammer m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
1487e13c2731STamas Berghammer return SendOKResponse();
1488e13c2731STamas Berghammer }
1489e13c2731STamas Berghammer
1490e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_QSetWorkingDir(StringExtractorGDBRemote & packet)1491b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
1492b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
1493e13c2731STamas Berghammer packet.SetFilePos(::strlen("QSetWorkingDir:"));
1494e13c2731STamas Berghammer std::string path;
1495e13c2731STamas Berghammer packet.GetHexByteString(path);
14968f3be7a3SJonas Devlieghere m_process_launch_info.SetWorkingDirectory(FileSpec(path));
1497e13c2731STamas Berghammer return SendOKResponse();
1498e13c2731STamas Berghammer }
1499e13c2731STamas Berghammer
1500e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_qGetWorkingDir(StringExtractorGDBRemote & packet)1501b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
1502b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
1503d3173f34SChaoren Lin FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
1504b9c1b51eSKate Stone if (working_dir) {
1505e13c2731STamas Berghammer StreamString response;
1506*1b4b12a3SNico Weber response.PutStringAsRawHex8(working_dir.GetCString());
150726709df8SZachary Turner return SendPacketNoLock(response.GetString());
1508e13c2731STamas Berghammer }
1509e13c2731STamas Berghammer
1510e13c2731STamas Berghammer return SendErrorResponse(14);
1511e13c2731STamas Berghammer }
1512e13c2731STamas Berghammer
1513e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_QThreadSuffixSupported(StringExtractorGDBRemote & packet)15142494243eSPavel Labath GDBRemoteCommunicationServerLLGS::Handle_QThreadSuffixSupported(
15152494243eSPavel Labath StringExtractorGDBRemote &packet) {
15162494243eSPavel Labath m_thread_suffix_supported = true;
15172494243eSPavel Labath return SendOKResponse();
15182494243eSPavel Labath }
15192494243eSPavel Labath
15202494243eSPavel Labath GDBRemoteCommunication::PacketResult
Handle_QListThreadsInStopReply(StringExtractorGDBRemote & packet)15212494243eSPavel Labath GDBRemoteCommunicationServerLLGS::Handle_QListThreadsInStopReply(
15222494243eSPavel Labath StringExtractorGDBRemote &packet) {
15232494243eSPavel Labath m_list_threads_in_stop_reply = true;
15242494243eSPavel Labath return SendOKResponse();
15252494243eSPavel Labath }
15262494243eSPavel Labath
15272494243eSPavel Labath GDBRemoteCommunication::PacketResult
ResumeProcess(NativeProcessProtocol & process,const ResumeActionList & actions)1528eb43e43bSMichał Górny GDBRemoteCommunicationServerLLGS::ResumeProcess(
1529eb43e43bSMichał Górny NativeProcessProtocol &process, const ResumeActionList &actions) {
1530eb43e43bSMichał Górny Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
1531eb43e43bSMichał Górny
1532eb43e43bSMichał Górny // In non-stop protocol mode, the process could be running already.
1533eb43e43bSMichał Górny // We do not support resuming threads independently, so just error out.
1534eb43e43bSMichał Górny if (!process.CanResume()) {
1535eb43e43bSMichał Górny LLDB_LOG(log, "process {0} cannot be resumed (state={1})", process.GetID(),
1536eb43e43bSMichał Górny process.GetState());
1537eb43e43bSMichał Górny return SendErrorResponse(0x37);
1538eb43e43bSMichał Górny }
1539eb43e43bSMichał Górny
1540eb43e43bSMichał Górny Status error = process.Resume(actions);
1541eb43e43bSMichał Górny if (error.Fail()) {
1542eb43e43bSMichał Górny LLDB_LOG(log, "process {0} failed to resume: {1}", process.GetID(), error);
1543eb43e43bSMichał Górny return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1544eb43e43bSMichał Górny }
1545eb43e43bSMichał Górny
1546eb43e43bSMichał Górny LLDB_LOG(log, "process {0} resumed", process.GetID());
1547eb43e43bSMichał Górny
1548eb43e43bSMichał Górny return PacketResult::Success;
1549eb43e43bSMichał Górny }
1550eb43e43bSMichał Górny
1551eb43e43bSMichał Górny GDBRemoteCommunication::PacketResult
Handle_C(StringExtractorGDBRemote & packet)1552b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
1553a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
155463e5fb76SJonas Devlieghere LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1555e13c2731STamas Berghammer
1556e13c2731STamas Berghammer // Ensure we have a native process.
1557f1812a28SMichał Górny if (!m_continue_process) {
155863e5fb76SJonas Devlieghere LLDB_LOGF(log,
155963e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1560b9c1b51eSKate Stone "shared pointer",
1561b9c1b51eSKate Stone __FUNCTION__);
1562e13c2731STamas Berghammer return SendErrorResponse(0x36);
1563e13c2731STamas Berghammer }
1564e13c2731STamas Berghammer
1565e13c2731STamas Berghammer // Pull out the signal number.
1566e13c2731STamas Berghammer packet.SetFilePos(::strlen("C"));
1567b9c1b51eSKate Stone if (packet.GetBytesLeft() < 1) {
1568e13c2731STamas Berghammer // Shouldn't be using a C without a signal.
1569e13c2731STamas Berghammer return SendIllFormedResponse(packet, "C packet specified without signal.");
1570e13c2731STamas Berghammer }
1571b9c1b51eSKate Stone const uint32_t signo =
1572b9c1b51eSKate Stone packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1573e13c2731STamas Berghammer if (signo == std::numeric_limits<uint32_t>::max())
1574e13c2731STamas Berghammer return SendIllFormedResponse(packet, "failed to parse signal number");
1575e13c2731STamas Berghammer
1576e13c2731STamas Berghammer // Handle optional continue address.
1577b9c1b51eSKate Stone if (packet.GetBytesLeft() > 0) {
1578e13c2731STamas Berghammer // FIXME add continue at address support for $C{signo}[;{continue-address}].
1579b9739d40SPavel Labath if (*packet.Peek() == ';')
1580d35b42f2SJonas Devlieghere return SendUnimplementedResponse(packet.GetStringRef().data());
1581e13c2731STamas Berghammer else
1582b9c1b51eSKate Stone return SendIllFormedResponse(
1583b9c1b51eSKate Stone packet, "unexpected content after $C{signal-number}");
1584e13c2731STamas Berghammer }
1585e13c2731STamas Berghammer
1586eb43e43bSMichał Górny // In non-stop protocol mode, the process could be running already.
1587eb43e43bSMichał Górny // We do not support resuming threads independently, so just error out.
1588eb43e43bSMichał Górny if (!m_continue_process->CanResume()) {
1589eb43e43bSMichał Górny LLDB_LOG(log, "process cannot be resumed (state={0})",
1590eb43e43bSMichał Górny m_continue_process->GetState());
1591eb43e43bSMichał Górny return SendErrorResponse(0x37);
1592eb43e43bSMichał Górny }
1593eb43e43bSMichał Górny
1594e4d25e9eSMichal Gorny ResumeActionList resume_actions(StateType::eStateRunning,
1595e4d25e9eSMichal Gorny LLDB_INVALID_SIGNAL_NUMBER);
159697206d57SZachary Turner Status error;
1597e13c2731STamas Berghammer
1598b9c1b51eSKate Stone // We have two branches: what to do if a continue thread is specified (in
159905097246SAdrian Prantl // which case we target sending the signal to that thread), or when we don't
160005097246SAdrian Prantl // have a continue thread set (in which case we send a signal to the
160105097246SAdrian Prantl // process).
1602e13c2731STamas Berghammer
1603e13c2731STamas Berghammer // TODO discuss with Greg Clayton, make sure this makes sense.
1604e13c2731STamas Berghammer
1605e13c2731STamas Berghammer lldb::tid_t signal_tid = GetContinueThreadID();
1606b9c1b51eSKate Stone if (signal_tid != LLDB_INVALID_THREAD_ID) {
1607b9c1b51eSKate Stone // The resume action for the continue thread (or all threads if a continue
1608b9c1b51eSKate Stone // thread is not set).
1609b9c1b51eSKate Stone ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
1610b9c1b51eSKate Stone static_cast<int>(signo)};
1611e13c2731STamas Berghammer
1612b9c1b51eSKate Stone // Add the action for the continue thread (or all threads when the continue
1613b9c1b51eSKate Stone // thread isn't present).
1614e13c2731STamas Berghammer resume_actions.Append(action);
1615b9c1b51eSKate Stone } else {
1616b9c1b51eSKate Stone // Send the signal to the process since we weren't targeting a specific
1617b9c1b51eSKate Stone // continue thread with the signal.
1618f1812a28SMichał Górny error = m_continue_process->Signal(signo);
1619b9c1b51eSKate Stone if (error.Fail()) {
162082abefa4SPavel Labath LLDB_LOG(log, "failed to send signal for process {0}: {1}",
1621f1812a28SMichał Górny m_continue_process->GetID(), error);
1622e13c2731STamas Berghammer
1623e13c2731STamas Berghammer return SendErrorResponse(0x52);
1624e13c2731STamas Berghammer }
1625e13c2731STamas Berghammer }
1626e13c2731STamas Berghammer
1627eb43e43bSMichał Górny // NB: this checks CanResume() twice but using a single code path for
1628eb43e43bSMichał Górny // resuming still seems worth it.
1629eb43e43bSMichał Górny PacketResult resume_res = ResumeProcess(*m_continue_process, resume_actions);
1630eb43e43bSMichał Górny if (resume_res != PacketResult::Success)
1631eb43e43bSMichał Górny return resume_res;
1632e13c2731STamas Berghammer
1633bc04d240SMichał Górny // Don't send an "OK" packet, except in non-stop mode;
1634bc04d240SMichał Górny // otherwise, the response is the stopped/exited message.
1635bc04d240SMichał Górny return SendContinueSuccessResponse();
1636e13c2731STamas Berghammer }
1637e13c2731STamas Berghammer
1638e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_c(StringExtractorGDBRemote & packet)1639b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
1640a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
164163e5fb76SJonas Devlieghere LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
1642e13c2731STamas Berghammer
1643e13c2731STamas Berghammer packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
1644e13c2731STamas Berghammer
1645e13c2731STamas Berghammer // For now just support all continue.
1646e13c2731STamas Berghammer const bool has_continue_address = (packet.GetBytesLeft() > 0);
1647b9c1b51eSKate Stone if (has_continue_address) {
164882abefa4SPavel Labath LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
164982abefa4SPavel Labath packet.Peek());
1650d35b42f2SJonas Devlieghere return SendUnimplementedResponse(packet.GetStringRef().data());
1651e13c2731STamas Berghammer }
1652e13c2731STamas Berghammer
1653e13c2731STamas Berghammer // Ensure we have a native process.
1654f1812a28SMichał Górny if (!m_continue_process) {
165563e5fb76SJonas Devlieghere LLDB_LOGF(log,
165663e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s no debugged process "
1657b9c1b51eSKate Stone "shared pointer",
1658b9c1b51eSKate Stone __FUNCTION__);
1659e13c2731STamas Berghammer return SendErrorResponse(0x36);
1660e13c2731STamas Berghammer }
1661e13c2731STamas Berghammer
1662e13c2731STamas Berghammer // Build the ResumeActionList
1663c36b0bf3SMichal Gorny ResumeActionList actions(StateType::eStateRunning,
1664c36b0bf3SMichal Gorny LLDB_INVALID_SIGNAL_NUMBER);
1665e13c2731STamas Berghammer
1666eb43e43bSMichał Górny PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
1667eb43e43bSMichał Górny if (resume_res != PacketResult::Success)
1668eb43e43bSMichał Górny return resume_res;
1669bc04d240SMichał Górny
1670bc04d240SMichał Górny return SendContinueSuccessResponse();
1671e13c2731STamas Berghammer }
1672e13c2731STamas Berghammer
1673e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_vCont_actions(StringExtractorGDBRemote & packet)1674b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
1675b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
1676e13c2731STamas Berghammer StreamString response;
1677b4f2d7cdSMichał Górny response.Printf("vCont;c;C;s;S;t");
1678e13c2731STamas Berghammer
167926709df8SZachary Turner return SendPacketNoLock(response.GetString());
1680e13c2731STamas Berghammer }
1681e13c2731STamas Berghammer
ResumeActionListStopsAllThreads(ResumeActionList & actions)1682eb43e43bSMichał Górny static bool ResumeActionListStopsAllThreads(ResumeActionList &actions) {
1683eb43e43bSMichał Górny // We're doing a stop-all if and only if our only action is a "t" for all
1684eb43e43bSMichał Górny // threads.
1685eb43e43bSMichał Górny if (const ResumeAction *default_action =
1686eb43e43bSMichał Górny actions.GetActionForThread(LLDB_INVALID_THREAD_ID, false)) {
1687eb43e43bSMichał Górny if (default_action->state == eStateSuspended && actions.GetSize() == 1)
1688eb43e43bSMichał Górny return true;
1689eb43e43bSMichał Górny }
1690eb43e43bSMichał Górny
1691eb43e43bSMichał Górny return false;
1692eb43e43bSMichał Górny }
1693eb43e43bSMichał Górny
1694e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_vCont(StringExtractorGDBRemote & packet)1695b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_vCont(
1696b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
1697a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
169863e5fb76SJonas Devlieghere LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
1699b9c1b51eSKate Stone __FUNCTION__);
1700e13c2731STamas Berghammer
1701e13c2731STamas Berghammer packet.SetFilePos(::strlen("vCont"));
1702e13c2731STamas Berghammer
1703b9c1b51eSKate Stone if (packet.GetBytesLeft() == 0) {
170463e5fb76SJonas Devlieghere LLDB_LOGF(log,
170563e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s missing action from "
1706b9c1b51eSKate Stone "vCont package",
1707b9c1b51eSKate Stone __FUNCTION__);
1708e13c2731STamas Berghammer return SendIllFormedResponse(packet, "Missing action from vCont package");
1709e13c2731STamas Berghammer }
1710e13c2731STamas Berghammer
1711a3422793SMichał Górny if (::strcmp(packet.Peek(), ";s") == 0) {
1712e13c2731STamas Berghammer // Move past the ';', then do a simple 's'.
1713e13c2731STamas Berghammer packet.SetFilePos(packet.GetFilePos() + 1);
1714e13c2731STamas Berghammer return Handle_s(packet);
1715e13c2731STamas Berghammer }
1716e13c2731STamas Berghammer
1717a3422793SMichał Górny std::unordered_map<lldb::pid_t, ResumeActionList> thread_actions;
1718e13c2731STamas Berghammer
1719b9c1b51eSKate Stone while (packet.GetBytesLeft() && *packet.Peek() == ';') {
1720e13c2731STamas Berghammer // Skip the semi-colon.
1721e13c2731STamas Berghammer packet.GetChar();
1722e13c2731STamas Berghammer
1723e13c2731STamas Berghammer // Build up the thread action.
1724e13c2731STamas Berghammer ResumeAction thread_action;
1725e13c2731STamas Berghammer thread_action.tid = LLDB_INVALID_THREAD_ID;
1726e13c2731STamas Berghammer thread_action.state = eStateInvalid;
1727c36b0bf3SMichal Gorny thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;
1728e13c2731STamas Berghammer
1729e13c2731STamas Berghammer const char action = packet.GetChar();
1730b9c1b51eSKate Stone switch (action) {
1731e13c2731STamas Berghammer case 'C':
1732e13c2731STamas Berghammer thread_action.signal = packet.GetHexMaxU32(false, 0);
1733e13c2731STamas Berghammer if (thread_action.signal == 0)
1734b9c1b51eSKate Stone return SendIllFormedResponse(
1735b9c1b51eSKate Stone packet, "Could not parse signal in vCont packet C action");
173662e0681aSJason Molenda LLVM_FALLTHROUGH;
1737e13c2731STamas Berghammer
1738e13c2731STamas Berghammer case 'c':
1739e13c2731STamas Berghammer // Continue
1740e13c2731STamas Berghammer thread_action.state = eStateRunning;
1741e13c2731STamas Berghammer break;
1742e13c2731STamas Berghammer
1743e13c2731STamas Berghammer case 'S':
1744e13c2731STamas Berghammer thread_action.signal = packet.GetHexMaxU32(false, 0);
1745e13c2731STamas Berghammer if (thread_action.signal == 0)
1746b9c1b51eSKate Stone return SendIllFormedResponse(
1747b9c1b51eSKate Stone packet, "Could not parse signal in vCont packet S action");
174862e0681aSJason Molenda LLVM_FALLTHROUGH;
1749e13c2731STamas Berghammer
1750e13c2731STamas Berghammer case 's':
1751e13c2731STamas Berghammer // Step
1752e13c2731STamas Berghammer thread_action.state = eStateStepping;
1753e13c2731STamas Berghammer break;
1754e13c2731STamas Berghammer
1755b4f2d7cdSMichał Górny case 't':
1756b4f2d7cdSMichał Górny // Stop
1757b4f2d7cdSMichał Górny thread_action.state = eStateSuspended;
1758b4f2d7cdSMichał Górny break;
1759b4f2d7cdSMichał Górny
1760e13c2731STamas Berghammer default:
1761e13c2731STamas Berghammer return SendIllFormedResponse(packet, "Unsupported vCont action");
1762e13c2731STamas Berghammer break;
1763e13c2731STamas Berghammer }
1764e13c2731STamas Berghammer
1765a3422793SMichał Górny lldb::pid_t pid = StringExtractorGDBRemote::AllProcesses;
1766a3422793SMichał Górny lldb::tid_t tid = StringExtractorGDBRemote::AllThreads;
1767a3422793SMichał Górny
1768e13c2731STamas Berghammer // Parse out optional :{thread-id} value.
1769b9c1b51eSKate Stone if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
1770e13c2731STamas Berghammer // Consume the separator.
1771e13c2731STamas Berghammer packet.GetChar();
1772e13c2731STamas Berghammer
1773a3422793SMichał Górny auto pid_tid = packet.GetPidTid(StringExtractorGDBRemote::AllProcesses);
1774a3422793SMichał Górny if (!pid_tid)
1775a3422793SMichał Górny return SendIllFormedResponse(packet, "Malformed thread-id");
17766c1a8039SMichał Górny
1777a3422793SMichał Górny pid = pid_tid->first;
1778a3422793SMichał Górny tid = pid_tid->second;
1779e13c2731STamas Berghammer }
1780e13c2731STamas Berghammer
1781eb43e43bSMichał Górny if (thread_action.state == eStateSuspended &&
1782eb43e43bSMichał Górny tid != StringExtractorGDBRemote::AllThreads) {
1783eb43e43bSMichał Górny return SendIllFormedResponse(
1784eb43e43bSMichał Górny packet, "'t' action not supported for individual threads");
1785eb43e43bSMichał Górny }
1786eb43e43bSMichał Górny
1787a3422793SMichał Górny if (pid == StringExtractorGDBRemote::AllProcesses) {
1788a3422793SMichał Górny if (m_debugged_processes.size() > 1)
1789a3422793SMichał Górny return SendIllFormedResponse(
1790a3422793SMichał Górny packet, "Resuming multiple processes not supported yet");
1791a3422793SMichał Górny if (!m_continue_process) {
1792a3422793SMichał Górny LLDB_LOG(log, "no debugged process");
1793a3422793SMichał Górny return SendErrorResponse(0x36);
1794a3422793SMichał Górny }
1795a3422793SMichał Górny pid = m_continue_process->GetID();
1796e13c2731STamas Berghammer }
1797e13c2731STamas Berghammer
1798a3422793SMichał Górny if (tid == StringExtractorGDBRemote::AllThreads)
1799a3422793SMichał Górny tid = LLDB_INVALID_THREAD_ID;
1800a3422793SMichał Górny
1801a3422793SMichał Górny thread_action.tid = tid;
1802a3422793SMichał Górny
1803a3422793SMichał Górny thread_actions[pid].Append(thread_action);
1804a3422793SMichał Górny }
1805a3422793SMichał Górny
1806a3422793SMichał Górny assert(thread_actions.size() >= 1);
1807a3422793SMichał Górny if (thread_actions.size() > 1)
1808a3422793SMichał Górny return SendIllFormedResponse(
1809a3422793SMichał Górny packet, "Resuming multiple processes not supported yet");
1810a3422793SMichał Górny
1811a3422793SMichał Górny for (std::pair<lldb::pid_t, ResumeActionList> x : thread_actions) {
1812a3422793SMichał Górny auto process_it = m_debugged_processes.find(x.first);
1813a3422793SMichał Górny if (process_it == m_debugged_processes.end()) {
1814a3422793SMichał Górny LLDB_LOG(log, "vCont failed for process {0}: process not debugged",
1815a3422793SMichał Górny x.first);
1816e13c2731STamas Berghammer return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1817e13c2731STamas Berghammer }
1818e13c2731STamas Berghammer
1819eb43e43bSMichał Górny // There are four possible scenarios here. These are:
1820eb43e43bSMichał Górny // 1. vCont on a stopped process that resumes at least one thread.
1821eb43e43bSMichał Górny // In this case, we call Resume().
1822eb43e43bSMichał Górny // 2. vCont on a stopped process that leaves all threads suspended.
1823eb43e43bSMichał Górny // A no-op.
1824eb43e43bSMichał Górny // 3. vCont on a running process that requests suspending all
1825eb43e43bSMichał Górny // running threads. In this case, we call Interrupt().
1826eb43e43bSMichał Górny // 4. vCont on a running process that requests suspending a subset
1827eb43e43bSMichał Górny // of running threads or resuming a subset of suspended threads.
1828eb43e43bSMichał Górny // Since we do not support full nonstop mode, this is unsupported
1829eb43e43bSMichał Górny // and we return an error.
1830eb43e43bSMichał Górny
1831eb43e43bSMichał Górny assert(process_it->second.process_up);
1832eb43e43bSMichał Górny if (ResumeActionListStopsAllThreads(x.second)) {
1833eb43e43bSMichał Górny if (process_it->second.process_up->IsRunning()) {
1834eb43e43bSMichał Górny assert(m_non_stop);
1835eb43e43bSMichał Górny
1836eb43e43bSMichał Górny Status error = process_it->second.process_up->Interrupt();
1837a3422793SMichał Górny if (error.Fail()) {
1838eb43e43bSMichał Górny LLDB_LOG(log, "vCont failed to halt process {0}: {1}", x.first,
1839eb43e43bSMichał Górny error);
1840a3422793SMichał Górny return SendErrorResponse(GDBRemoteServerError::eErrorResume);
1841a3422793SMichał Górny }
1842a3422793SMichał Górny
1843eb43e43bSMichał Górny LLDB_LOG(log, "halted process {0}", x.first);
1844eb43e43bSMichał Górny
1845eb43e43bSMichał Górny // hack to avoid enabling stdio forwarding after stop
1846eb43e43bSMichał Górny // TODO: remove this when we improve stdio forwarding for nonstop
1847eb43e43bSMichał Górny assert(thread_actions.size() == 1);
1848eb43e43bSMichał Górny return SendOKResponse();
1849eb43e43bSMichał Górny }
1850eb43e43bSMichał Górny } else {
1851eb43e43bSMichał Górny PacketResult resume_res =
1852eb43e43bSMichał Górny ResumeProcess(*process_it->second.process_up, x.second);
1853eb43e43bSMichał Górny if (resume_res != PacketResult::Success)
1854eb43e43bSMichał Górny return resume_res;
1855eb43e43bSMichał Górny }
1856a3422793SMichał Górny }
1857bc04d240SMichał Górny
1858bc04d240SMichał Górny return SendContinueSuccessResponse();
1859e13c2731STamas Berghammer }
1860e13c2731STamas Berghammer
SetCurrentThreadID(lldb::tid_t tid)1861b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
1862a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Thread);
186382abefa4SPavel Labath LLDB_LOG(log, "setting current thread id to {0}", tid);
1864e13c2731STamas Berghammer
1865e13c2731STamas Berghammer m_current_tid = tid;
1866f1812a28SMichał Górny if (m_current_process)
1867f1812a28SMichał Górny m_current_process->SetCurrentThreadID(m_current_tid);
1868e13c2731STamas Berghammer }
1869e13c2731STamas Berghammer
SetContinueThreadID(lldb::tid_t tid)1870b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
1871a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Thread);
187282abefa4SPavel Labath LLDB_LOG(log, "setting continue thread id to {0}", tid);
1873e13c2731STamas Berghammer
1874e13c2731STamas Berghammer m_continue_tid = tid;
1875e13c2731STamas Berghammer }
1876e13c2731STamas Berghammer
1877e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_stop_reason(StringExtractorGDBRemote & packet)1878b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
1879b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
1880e13c2731STamas Berghammer // Handle the $? gdbremote command.
1881e13c2731STamas Berghammer
1882bc04d240SMichał Górny if (m_non_stop) {
1883bc04d240SMichał Górny // Clear the notification queue first, except for pending exit
1884bc04d240SMichał Górny // notifications.
1885bc04d240SMichał Górny llvm::erase_if(m_stop_notification_queue, [](const std::string &x) {
1886bc04d240SMichał Górny return x.front() != 'W' && x.front() != 'X';
1887bc04d240SMichał Górny });
1888bc04d240SMichał Górny
1889e8fe7e93SMichał Górny if (m_current_process) {
1890e8fe7e93SMichał Górny // Queue stop reply packets for all active threads. Start with
1891e8fe7e93SMichał Górny // the current thread (for clients that don't actually support multiple
1892e8fe7e93SMichał Górny // stop reasons).
1893bc04d240SMichał Górny NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
1894ab9f1e88SMichał Górny if (thread) {
1895ab9f1e88SMichał Górny StreamString stop_reply = PrepareStopReplyPacketForThread(*thread);
1896ab9f1e88SMichał Górny if (!stop_reply.Empty())
1897ab9f1e88SMichał Górny m_stop_notification_queue.push_back(stop_reply.GetString().str());
1898ab9f1e88SMichał Górny }
1899e8fe7e93SMichał Górny EnqueueStopReplyPackets(thread ? thread->GetID()
1900e8fe7e93SMichał Górny : LLDB_INVALID_THREAD_ID);
1901e8fe7e93SMichał Górny }
1902bc04d240SMichał Górny
1903bc04d240SMichał Górny // If the notification queue is empty (i.e. everything is running), send OK.
1904bc04d240SMichał Górny if (m_stop_notification_queue.empty())
1905bc04d240SMichał Górny return SendOKResponse();
1906bc04d240SMichał Górny
1907bc04d240SMichał Górny // Send the first item from the new notification queue synchronously.
1908bc04d240SMichał Górny return SendPacketNoLock(m_stop_notification_queue.front());
1909bc04d240SMichał Górny }
1910bc04d240SMichał Górny
1911e8fe7e93SMichał Górny // If no process, indicate error
1912e8fe7e93SMichał Górny if (!m_current_process)
1913e8fe7e93SMichał Górny return SendErrorResponse(02);
1914e8fe7e93SMichał Górny
1915f8c6de8dSMichał Górny return SendStopReasonForState(*m_current_process,
1916bc04d240SMichał Górny m_current_process->GetState(),
1917bc04d240SMichał Górny /*force_synchronous=*/true);
1918e13c2731STamas Berghammer }
1919e13c2731STamas Berghammer
1920e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
SendStopReasonForState(NativeProcessProtocol & process,lldb::StateType process_state,bool force_synchronous)1921b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
1922bc04d240SMichał Górny NativeProcessProtocol &process, lldb::StateType process_state,
1923bc04d240SMichał Górny bool force_synchronous) {
1924a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
1925e13c2731STamas Berghammer
1926c732afa2SMichał Górny if (m_disabling_non_stop) {
1927c732afa2SMichał Górny // Check if we are waiting for any more processes to stop. If we are,
1928c732afa2SMichał Górny // do not send the OK response yet.
1929c732afa2SMichał Górny for (const auto &it : m_debugged_processes) {
1930c732afa2SMichał Górny if (it.second.process_up->IsRunning())
1931c732afa2SMichał Górny return PacketResult::Success;
1932c732afa2SMichał Górny }
1933c732afa2SMichał Górny
1934c732afa2SMichał Górny // If all expected processes were stopped after a QNonStop:0 request,
1935c732afa2SMichał Górny // send the OK response.
1936c732afa2SMichał Górny m_disabling_non_stop = false;
1937c732afa2SMichał Górny return SendOKResponse();
1938c732afa2SMichał Górny }
1939c732afa2SMichał Górny
1940b9c1b51eSKate Stone switch (process_state) {
1941e13c2731STamas Berghammer case eStateAttaching:
1942e13c2731STamas Berghammer case eStateLaunching:
1943e13c2731STamas Berghammer case eStateRunning:
1944e13c2731STamas Berghammer case eStateStepping:
1945e13c2731STamas Berghammer case eStateDetached:
1946e13c2731STamas Berghammer // NOTE: gdb protocol doc looks like it should return $OK
1947e13c2731STamas Berghammer // when everything is running (i.e. no stopped result).
1948e13c2731STamas Berghammer return PacketResult::Success; // Ignore
1949e13c2731STamas Berghammer
1950e13c2731STamas Berghammer case eStateSuspended:
1951e13c2731STamas Berghammer case eStateStopped:
1952b9c1b51eSKate Stone case eStateCrashed: {
1953f8c6de8dSMichał Górny lldb::tid_t tid = process.GetCurrentThreadID();
195405097246SAdrian Prantl // Make sure we set the current thread so g and p packets return the data
195505097246SAdrian Prantl // the gdb will expect.
1956e13c2731STamas Berghammer SetCurrentThreadID(tid);
1957bc04d240SMichał Górny return SendStopReplyPacketForThread(process, tid, force_synchronous);
1958e13c2731STamas Berghammer }
1959e13c2731STamas Berghammer
1960e13c2731STamas Berghammer case eStateInvalid:
1961e13c2731STamas Berghammer case eStateUnloaded:
1962e13c2731STamas Berghammer case eStateExited:
1963f8c6de8dSMichał Górny return SendWResponse(&process);
1964e13c2731STamas Berghammer
1965e13c2731STamas Berghammer default:
196682abefa4SPavel Labath LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
1967f8c6de8dSMichał Górny process.GetID(), process_state);
1968e13c2731STamas Berghammer break;
1969e13c2731STamas Berghammer }
1970e13c2731STamas Berghammer
1971e13c2731STamas Berghammer return SendErrorResponse(0);
1972e13c2731STamas Berghammer }
1973e13c2731STamas Berghammer
1974e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_qRegisterInfo(StringExtractorGDBRemote & packet)1975b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
1976b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
1977e13c2731STamas Berghammer // Fail if we don't have a current process.
1978f1812a28SMichał Górny if (!m_current_process ||
1979f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
1980e13c2731STamas Berghammer return SendErrorResponse(68);
1981e13c2731STamas Berghammer
1982e13c2731STamas Berghammer // Ensure we have a thread.
1983f1812a28SMichał Górny NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
1984a5be48b3SPavel Labath if (!thread)
1985e13c2731STamas Berghammer return SendErrorResponse(69);
1986e13c2731STamas Berghammer
1987e13c2731STamas Berghammer // Get the register context for the first thread.
1988d37349f3SPavel Labath NativeRegisterContext ®_context = thread->GetRegisterContext();
1989e13c2731STamas Berghammer
1990e13c2731STamas Berghammer // Parse out the register number from the request.
1991e13c2731STamas Berghammer packet.SetFilePos(strlen("qRegisterInfo"));
1992b9c1b51eSKate Stone const uint32_t reg_index =
1993b9c1b51eSKate Stone packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
1994e13c2731STamas Berghammer if (reg_index == std::numeric_limits<uint32_t>::max())
1995e13c2731STamas Berghammer return SendErrorResponse(69);
1996e13c2731STamas Berghammer
1997b9c1b51eSKate Stone // Return the end of registers response if we've iterated one past the end of
1998b9c1b51eSKate Stone // the register set.
1999d37349f3SPavel Labath if (reg_index >= reg_context.GetUserRegisterCount())
2000e13c2731STamas Berghammer return SendErrorResponse(69);
2001e13c2731STamas Berghammer
2002d37349f3SPavel Labath const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2003e13c2731STamas Berghammer if (!reg_info)
2004e13c2731STamas Berghammer return SendErrorResponse(69);
2005e13c2731STamas Berghammer
2006e13c2731STamas Berghammer // Build the reginfos response.
2007e13c2731STamas Berghammer StreamGDBRemote response;
2008e13c2731STamas Berghammer
2009e13c2731STamas Berghammer response.PutCString("name:");
2010e13c2731STamas Berghammer response.PutCString(reg_info->name);
2011e13c2731STamas Berghammer response.PutChar(';');
2012e13c2731STamas Berghammer
2013b9c1b51eSKate Stone if (reg_info->alt_name && reg_info->alt_name[0]) {
2014e13c2731STamas Berghammer response.PutCString("alt-name:");
2015e13c2731STamas Berghammer response.PutCString(reg_info->alt_name);
2016e13c2731STamas Berghammer response.PutChar(';');
2017e13c2731STamas Berghammer }
2018e13c2731STamas Berghammer
201978cb4562SMuhammad Omair Javaid response.Printf("bitsize:%" PRIu32 ";", reg_info->byte_size * 8);
202078cb4562SMuhammad Omair Javaid
202178cb4562SMuhammad Omair Javaid if (!reg_context.RegisterOffsetIsDynamic())
202278cb4562SMuhammad Omair Javaid response.Printf("offset:%" PRIu32 ";", reg_info->byte_offset);
2023e13c2731STamas Berghammer
2024af64b319SMuhammad Omair Javaid llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
2025af64b319SMuhammad Omair Javaid if (!encoding.empty())
2026af64b319SMuhammad Omair Javaid response << "encoding:" << encoding << ';';
2027e13c2731STamas Berghammer
2028af64b319SMuhammad Omair Javaid llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
2029af64b319SMuhammad Omair Javaid if (!format.empty())
2030af64b319SMuhammad Omair Javaid response << "format:" << format << ';';
2031e13c2731STamas Berghammer
2032b9c1b51eSKate Stone const char *const register_set_name =
2033d37349f3SPavel Labath reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
2034af64b319SMuhammad Omair Javaid if (register_set_name)
2035af64b319SMuhammad Omair Javaid response << "set:" << register_set_name << ';';
2036e13c2731STamas Berghammer
2037b9c1b51eSKate Stone if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
2038b9c1b51eSKate Stone LLDB_INVALID_REGNUM)
2039b9c1b51eSKate Stone response.Printf("ehframe:%" PRIu32 ";",
2040b9c1b51eSKate Stone reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
2041e13c2731STamas Berghammer
2042e13c2731STamas Berghammer if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
2043b9c1b51eSKate Stone response.Printf("dwarf:%" PRIu32 ";",
2044b9c1b51eSKate Stone reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
2045e13c2731STamas Berghammer
2046af64b319SMuhammad Omair Javaid llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
2047af64b319SMuhammad Omair Javaid if (!kind_generic.empty())
2048af64b319SMuhammad Omair Javaid response << "generic:" << kind_generic << ';';
2049e13c2731STamas Berghammer
2050b9c1b51eSKate Stone if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
2051e13c2731STamas Berghammer response.PutCString("container-regs:");
2052af64b319SMuhammad Omair Javaid CollectRegNums(reg_info->value_regs, response, true);
2053e13c2731STamas Berghammer response.PutChar(';');
2054e13c2731STamas Berghammer }
2055e13c2731STamas Berghammer
2056b9c1b51eSKate Stone if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
2057e13c2731STamas Berghammer response.PutCString("invalidate-regs:");
2058af64b319SMuhammad Omair Javaid CollectRegNums(reg_info->invalidate_regs, response, true);
2059e13c2731STamas Berghammer response.PutChar(';');
2060e13c2731STamas Berghammer }
2061e13c2731STamas Berghammer
206226709df8SZachary Turner return SendPacketNoLock(response.GetString());
2063e13c2731STamas Berghammer }
2064e13c2731STamas Berghammer
AddProcessThreads(StreamGDBRemote & response,NativeProcessProtocol & process,bool & had_any)20651452e2e5SMichał Górny void GDBRemoteCommunicationServerLLGS::AddProcessThreads(
20661452e2e5SMichał Górny StreamGDBRemote &response, NativeProcessProtocol &process, bool &had_any) {
20671452e2e5SMichał Górny Log *log = GetLog(LLDBLog::Thread);
20681452e2e5SMichał Górny
20691452e2e5SMichał Górny lldb::pid_t pid = process.GetID();
20701452e2e5SMichał Górny if (pid == LLDB_INVALID_PROCESS_ID)
20711452e2e5SMichał Górny return;
20721452e2e5SMichał Górny
20731452e2e5SMichał Górny LLDB_LOG(log, "iterating over threads of process {0}", process.GetID());
2074e095cddbSMichał Górny for (NativeThreadProtocol &thread : process.Threads()) {
2075e095cddbSMichał Górny LLDB_LOG(log, "iterated thread tid={0}", thread.GetID());
20761452e2e5SMichał Górny response.PutChar(had_any ? ',' : 'm');
2077e095cddbSMichał Górny AppendThreadIDToResponse(response, pid, thread.GetID());
20781452e2e5SMichał Górny had_any = true;
20791452e2e5SMichał Górny }
20801452e2e5SMichał Górny }
20811452e2e5SMichał Górny
2082e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_qfThreadInfo(StringExtractorGDBRemote & packet)2083b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
2084b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
20851452e2e5SMichał Górny assert(m_debugged_processes.size() == 1 ||
20861452e2e5SMichał Górny bool(m_extensions_supported &
20871452e2e5SMichał Górny NativeProcessProtocol::Extension::multiprocess));
2088e13c2731STamas Berghammer
20891452e2e5SMichał Górny bool had_any = false;
2090e13c2731STamas Berghammer StreamGDBRemote response;
2091e13c2731STamas Berghammer
20921452e2e5SMichał Górny for (auto &pid_ptr : m_debugged_processes)
2093355c7916SMichał Górny AddProcessThreads(response, *pid_ptr.second.process_up, had_any);
2094e13c2731STamas Berghammer
20951452e2e5SMichał Górny if (!had_any)
20961452e2e5SMichał Górny return SendOKResponse();
209726709df8SZachary Turner return SendPacketNoLock(response.GetString());
2098e13c2731STamas Berghammer }
2099e13c2731STamas Berghammer
2100e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_qsThreadInfo(StringExtractorGDBRemote & packet)2101b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
2102b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
2103b9c1b51eSKate Stone // FIXME for now we return the full thread list in the initial packet and
2104b9c1b51eSKate Stone // always do nothing here.
210526709df8SZachary Turner return SendPacketNoLock("l");
2106e13c2731STamas Berghammer }
2107e13c2731STamas Berghammer
2108e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_g(StringExtractorGDBRemote & packet)2109f04b3635SPavel Labath GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) {
2110a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Thread);
2111f04b3635SPavel Labath
2112f04b3635SPavel Labath // Move past packet name.
2113f04b3635SPavel Labath packet.SetFilePos(strlen("g"));
2114f04b3635SPavel Labath
2115f04b3635SPavel Labath // Get the thread to use.
2116f04b3635SPavel Labath NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2117f04b3635SPavel Labath if (!thread) {
2118f04b3635SPavel Labath LLDB_LOG(log, "failed, no thread available");
2119f04b3635SPavel Labath return SendErrorResponse(0x15);
2120f04b3635SPavel Labath }
2121f04b3635SPavel Labath
2122f04b3635SPavel Labath // Get the thread's register context.
2123f04b3635SPavel Labath NativeRegisterContext ®_ctx = thread->GetRegisterContext();
2124f04b3635SPavel Labath
2125f04b3635SPavel Labath std::vector<uint8_t> regs_buffer;
2126f04b3635SPavel Labath for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
2127f04b3635SPavel Labath ++reg_num) {
2128f04b3635SPavel Labath const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
2129f04b3635SPavel Labath
2130f04b3635SPavel Labath if (reg_info == nullptr) {
2131f04b3635SPavel Labath LLDB_LOG(log, "failed to get register info for register index {0}",
2132f04b3635SPavel Labath reg_num);
2133f04b3635SPavel Labath return SendErrorResponse(0x15);
2134f04b3635SPavel Labath }
2135f04b3635SPavel Labath
2136f04b3635SPavel Labath if (reg_info->value_regs != nullptr)
2137f04b3635SPavel Labath continue; // skip registers that are contained in other registers
2138f04b3635SPavel Labath
2139f04b3635SPavel Labath RegisterValue reg_value;
2140f04b3635SPavel Labath Status error = reg_ctx.ReadRegister(reg_info, reg_value);
2141f04b3635SPavel Labath if (error.Fail()) {
2142f04b3635SPavel Labath LLDB_LOG(log, "failed to read register at index {0}", reg_num);
2143f04b3635SPavel Labath return SendErrorResponse(0x15);
2144f04b3635SPavel Labath }
2145f04b3635SPavel Labath
2146f04b3635SPavel Labath if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
2147f04b3635SPavel Labath // Resize the buffer to guarantee it can store the register offsetted
2148f04b3635SPavel Labath // data.
2149f04b3635SPavel Labath regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
2150f04b3635SPavel Labath
2151f04b3635SPavel Labath // Copy the register offsetted data to the buffer.
2152f04b3635SPavel Labath memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
2153f04b3635SPavel Labath reg_info->byte_size);
2154f04b3635SPavel Labath }
2155f04b3635SPavel Labath
2156f04b3635SPavel Labath // Write the response.
2157f04b3635SPavel Labath StreamGDBRemote response;
2158f04b3635SPavel Labath response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
2159f04b3635SPavel Labath
2160f04b3635SPavel Labath return SendPacketNoLock(response.GetString());
2161f04b3635SPavel Labath }
2162f04b3635SPavel Labath
2163f04b3635SPavel Labath GDBRemoteCommunication::PacketResult
Handle_p(StringExtractorGDBRemote & packet)2164b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
2165a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Thread);
2166e13c2731STamas Berghammer
2167e13c2731STamas Berghammer // Parse out the register number from the request.
2168e13c2731STamas Berghammer packet.SetFilePos(strlen("p"));
2169b9c1b51eSKate Stone const uint32_t reg_index =
2170b9c1b51eSKate Stone packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2171b9c1b51eSKate Stone if (reg_index == std::numeric_limits<uint32_t>::max()) {
217263e5fb76SJonas Devlieghere LLDB_LOGF(log,
217363e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2174b9c1b51eSKate Stone "parse register number from request \"%s\"",
2175d35b42f2SJonas Devlieghere __FUNCTION__, packet.GetStringRef().data());
2176e13c2731STamas Berghammer return SendErrorResponse(0x15);
2177e13c2731STamas Berghammer }
2178e13c2731STamas Berghammer
2179e13c2731STamas Berghammer // Get the thread to use.
2180a5be48b3SPavel Labath NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2181a5be48b3SPavel Labath if (!thread) {
2182a5be48b3SPavel Labath LLDB_LOG(log, "failed, no thread available");
2183e13c2731STamas Berghammer return SendErrorResponse(0x15);
2184e13c2731STamas Berghammer }
2185e13c2731STamas Berghammer
2186e13c2731STamas Berghammer // Get the thread's register context.
2187d37349f3SPavel Labath NativeRegisterContext ®_context = thread->GetRegisterContext();
2188e13c2731STamas Berghammer
2189b9c1b51eSKate Stone // Return the end of registers response if we've iterated one past the end of
2190b9c1b51eSKate Stone // the register set.
2191d37349f3SPavel Labath if (reg_index >= reg_context.GetUserRegisterCount()) {
219263e5fb76SJonas Devlieghere LLDB_LOGF(log,
219363e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2194b9c1b51eSKate Stone "register %" PRIu32 " beyond register count %" PRIu32,
219563e5fb76SJonas Devlieghere __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2196e13c2731STamas Berghammer return SendErrorResponse(0x15);
2197e13c2731STamas Berghammer }
2198e13c2731STamas Berghammer
2199d37349f3SPavel Labath const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2200b9c1b51eSKate Stone if (!reg_info) {
220163e5fb76SJonas Devlieghere LLDB_LOGF(log,
220263e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2203b9c1b51eSKate Stone "register %" PRIu32 " returned NULL",
2204b9c1b51eSKate Stone __FUNCTION__, reg_index);
2205e13c2731STamas Berghammer return SendErrorResponse(0x15);
2206e13c2731STamas Berghammer }
2207e13c2731STamas Berghammer
2208e13c2731STamas Berghammer // Build the reginfos response.
2209e13c2731STamas Berghammer StreamGDBRemote response;
2210e13c2731STamas Berghammer
2211e13c2731STamas Berghammer // Retrieve the value
2212e13c2731STamas Berghammer RegisterValue reg_value;
2213d37349f3SPavel Labath Status error = reg_context.ReadRegister(reg_info, reg_value);
2214b9c1b51eSKate Stone if (error.Fail()) {
221563e5fb76SJonas Devlieghere LLDB_LOGF(log,
221663e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed, read of "
2217b9c1b51eSKate Stone "requested register %" PRIu32 " (%s) failed: %s",
2218b9c1b51eSKate Stone __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2219e13c2731STamas Berghammer return SendErrorResponse(0x15);
2220e13c2731STamas Berghammer }
2221e13c2731STamas Berghammer
2222b9c1b51eSKate Stone const uint8_t *const data =
222365fdb342SRaphael Isemann static_cast<const uint8_t *>(reg_value.GetBytes());
2224b9c1b51eSKate Stone if (!data) {
222563e5fb76SJonas Devlieghere LLDB_LOGF(log,
222663e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed to get data "
2227b9c1b51eSKate Stone "bytes from requested register %" PRIu32,
2228b9c1b51eSKate Stone __FUNCTION__, reg_index);
2229e13c2731STamas Berghammer return SendErrorResponse(0x15);
2230e13c2731STamas Berghammer }
2231e13c2731STamas Berghammer
2232e13c2731STamas Berghammer // FIXME flip as needed to get data in big/little endian format for this host.
2233e13c2731STamas Berghammer for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
2234e13c2731STamas Berghammer response.PutHex8(data[i]);
2235e13c2731STamas Berghammer
223626709df8SZachary Turner return SendPacketNoLock(response.GetString());
2237e13c2731STamas Berghammer }
2238e13c2731STamas Berghammer
2239e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_P(StringExtractorGDBRemote & packet)2240b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
2241a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Thread);
2242e13c2731STamas Berghammer
2243e13c2731STamas Berghammer // Ensure there is more content.
2244e13c2731STamas Berghammer if (packet.GetBytesLeft() < 1)
2245e13c2731STamas Berghammer return SendIllFormedResponse(packet, "Empty P packet");
2246e13c2731STamas Berghammer
2247e13c2731STamas Berghammer // Parse out the register number from the request.
2248e13c2731STamas Berghammer packet.SetFilePos(strlen("P"));
2249b9c1b51eSKate Stone const uint32_t reg_index =
2250b9c1b51eSKate Stone packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2251b9c1b51eSKate Stone if (reg_index == std::numeric_limits<uint32_t>::max()) {
225263e5fb76SJonas Devlieghere LLDB_LOGF(log,
225363e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed, could not "
2254b9c1b51eSKate Stone "parse register number from request \"%s\"",
2255d35b42f2SJonas Devlieghere __FUNCTION__, packet.GetStringRef().data());
2256e13c2731STamas Berghammer return SendErrorResponse(0x29);
2257e13c2731STamas Berghammer }
2258e13c2731STamas Berghammer
2259e13c2731STamas Berghammer // Note debugserver would send an E30 here.
2260e13c2731STamas Berghammer if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
2261b9c1b51eSKate Stone return SendIllFormedResponse(
2262b9c1b51eSKate Stone packet, "P packet missing '=' char after register number");
2263e13c2731STamas Berghammer
2264e13c2731STamas Berghammer // Parse out the value.
22659f8b4472SMuhammad Omair Javaid uint8_t reg_bytes[RegisterValue::kMaxRegisterByteSize];
2266d08f09c1SZachary Turner size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
2267e13c2731STamas Berghammer
2268e13c2731STamas Berghammer // Get the thread to use.
2269a5be48b3SPavel Labath NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
2270a5be48b3SPavel Labath if (!thread) {
227163e5fb76SJonas Devlieghere LLDB_LOGF(log,
227263e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed, no thread "
2273b9c1b51eSKate Stone "available (thread index 0)",
2274b9c1b51eSKate Stone __FUNCTION__);
2275e13c2731STamas Berghammer return SendErrorResponse(0x28);
2276e13c2731STamas Berghammer }
2277e13c2731STamas Berghammer
2278e13c2731STamas Berghammer // Get the thread's register context.
2279d37349f3SPavel Labath NativeRegisterContext ®_context = thread->GetRegisterContext();
2280d37349f3SPavel Labath const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
2281b9c1b51eSKate Stone if (!reg_info) {
228263e5fb76SJonas Devlieghere LLDB_LOGF(log,
228363e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2284b9c1b51eSKate Stone "register %" PRIu32 " returned NULL",
2285b9c1b51eSKate Stone __FUNCTION__, reg_index);
2286e13c2731STamas Berghammer return SendErrorResponse(0x48);
2287e13c2731STamas Berghammer }
2288e13c2731STamas Berghammer
2289b9c1b51eSKate Stone // Return the end of registers response if we've iterated one past the end of
2290b9c1b51eSKate Stone // the register set.
2291d37349f3SPavel Labath if (reg_index >= reg_context.GetUserRegisterCount()) {
229263e5fb76SJonas Devlieghere LLDB_LOGF(log,
229363e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed, requested "
2294b9c1b51eSKate Stone "register %" PRIu32 " beyond register count %" PRIu32,
2295d37349f3SPavel Labath __FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
2296e13c2731STamas Berghammer return SendErrorResponse(0x47);
2297e13c2731STamas Berghammer }
2298e13c2731STamas Berghammer
2299202af507SPavel Labath if (reg_size != reg_info->byte_size)
2300e13c2731STamas Berghammer return SendIllFormedResponse(packet, "P packet register size is incorrect");
2301e13c2731STamas Berghammer
2302e13c2731STamas Berghammer // Build the reginfos response.
2303e13c2731STamas Berghammer StreamGDBRemote response;
2304e13c2731STamas Berghammer
2305f1812a28SMichał Górny RegisterValue reg_value(makeArrayRef(reg_bytes, reg_size),
2306f1812a28SMichał Górny m_current_process->GetArchitecture().GetByteOrder());
2307d37349f3SPavel Labath Status error = reg_context.WriteRegister(reg_info, reg_value);
2308b9c1b51eSKate Stone if (error.Fail()) {
230963e5fb76SJonas Devlieghere LLDB_LOGF(log,
231063e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed, write of "
2311b9c1b51eSKate Stone "requested register %" PRIu32 " (%s) failed: %s",
2312b9c1b51eSKate Stone __FUNCTION__, reg_index, reg_info->name, error.AsCString());
2313e13c2731STamas Berghammer return SendErrorResponse(0x32);
2314e13c2731STamas Berghammer }
2315e13c2731STamas Berghammer
2316e13c2731STamas Berghammer return SendOKResponse();
2317e13c2731STamas Berghammer }
2318e13c2731STamas Berghammer
2319e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_H(StringExtractorGDBRemote & packet)2320b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
2321a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Thread);
2322e13c2731STamas Berghammer
2323e13c2731STamas Berghammer // Parse out which variant of $H is requested.
2324e13c2731STamas Berghammer packet.SetFilePos(strlen("H"));
2325b9c1b51eSKate Stone if (packet.GetBytesLeft() < 1) {
232663e5fb76SJonas Devlieghere LLDB_LOGF(log,
232763e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed, H command "
2328b9c1b51eSKate Stone "missing {g,c} variant",
2329b9c1b51eSKate Stone __FUNCTION__);
2330e13c2731STamas Berghammer return SendIllFormedResponse(packet, "H command missing {g,c} variant");
2331e13c2731STamas Berghammer }
2332e13c2731STamas Berghammer
2333e13c2731STamas Berghammer const char h_variant = packet.GetChar();
2334b7c14033SMichał Górny NativeProcessProtocol *default_process;
2335b9c1b51eSKate Stone switch (h_variant) {
2336e13c2731STamas Berghammer case 'g':
2337b7c14033SMichał Górny default_process = m_current_process;
2338e13c2731STamas Berghammer break;
2339e13c2731STamas Berghammer
2340e13c2731STamas Berghammer case 'c':
2341b7c14033SMichał Górny default_process = m_continue_process;
2342e13c2731STamas Berghammer break;
2343e13c2731STamas Berghammer
2344e13c2731STamas Berghammer default:
234563e5fb76SJonas Devlieghere LLDB_LOGF(
234663e5fb76SJonas Devlieghere log,
2347b9c1b51eSKate Stone "GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
2348b9c1b51eSKate Stone __FUNCTION__, h_variant);
2349b9c1b51eSKate Stone return SendIllFormedResponse(packet,
2350b9c1b51eSKate Stone "H variant unsupported, should be c or g");
2351e13c2731STamas Berghammer }
2352e13c2731STamas Berghammer
2353e13c2731STamas Berghammer // Parse out the thread number.
2354b7c14033SMichał Górny auto pid_tid = packet.GetPidTid(default_process ? default_process->GetID()
2355b7c14033SMichał Górny : LLDB_INVALID_PROCESS_ID);
2356b7c14033SMichał Górny if (!pid_tid)
2357b7c14033SMichał Górny return SendErrorResponse(llvm::make_error<StringError>(
2358b7c14033SMichał Górny inconvertibleErrorCode(), "Malformed thread-id"));
2359e13c2731STamas Berghammer
2360b7c14033SMichał Górny lldb::pid_t pid = pid_tid->first;
2361b7c14033SMichał Górny lldb::tid_t tid = pid_tid->second;
2362b7c14033SMichał Górny
2363b7c14033SMichał Górny if (pid == StringExtractorGDBRemote::AllProcesses)
2364b7c14033SMichał Górny return SendUnimplementedResponse("Selecting all processes not supported");
2365b7c14033SMichał Górny if (pid == LLDB_INVALID_PROCESS_ID)
2366b7c14033SMichał Górny return SendErrorResponse(llvm::make_error<StringError>(
2367b7c14033SMichał Górny inconvertibleErrorCode(), "No current process and no PID provided"));
2368b7c14033SMichał Górny
2369b7c14033SMichał Górny // Check the process ID and find respective process instance.
2370b7c14033SMichał Górny auto new_process_it = m_debugged_processes.find(pid);
2371b7c14033SMichał Górny if (new_process_it == m_debugged_processes.end())
2372b7c14033SMichał Górny return SendErrorResponse(llvm::make_error<StringError>(
2373b7c14033SMichał Górny inconvertibleErrorCode(),
2374b7c14033SMichał Górny llvm::formatv("No process with PID {0} debugged", pid)));
2375b7c14033SMichał Górny
2376b9c1b51eSKate Stone // Ensure we have the given thread when not specifying -1 (all threads) or 0
2377b9c1b51eSKate Stone // (any thread).
2378b9c1b51eSKate Stone if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
2379355c7916SMichał Górny NativeThreadProtocol *thread =
2380355c7916SMichał Górny new_process_it->second.process_up->GetThreadByID(tid);
2381a5be48b3SPavel Labath if (!thread) {
238263e5fb76SJonas Devlieghere LLDB_LOGF(log,
238363e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
2384b9c1b51eSKate Stone " not found",
2385b9c1b51eSKate Stone __FUNCTION__, tid);
2386e13c2731STamas Berghammer return SendErrorResponse(0x15);
2387e13c2731STamas Berghammer }
2388e13c2731STamas Berghammer }
2389e13c2731STamas Berghammer
2390b7c14033SMichał Górny // Now switch the given process and thread type.
2391b9c1b51eSKate Stone switch (h_variant) {
2392e13c2731STamas Berghammer case 'g':
2393355c7916SMichał Górny m_current_process = new_process_it->second.process_up.get();
2394e13c2731STamas Berghammer SetCurrentThreadID(tid);
2395e13c2731STamas Berghammer break;
2396e13c2731STamas Berghammer
2397e13c2731STamas Berghammer case 'c':
2398355c7916SMichał Górny m_continue_process = new_process_it->second.process_up.get();
2399e13c2731STamas Berghammer SetContinueThreadID(tid);
2400e13c2731STamas Berghammer break;
2401e13c2731STamas Berghammer
2402e13c2731STamas Berghammer default:
2403e13c2731STamas Berghammer assert(false && "unsupported $H variant - shouldn't get here");
2404b9c1b51eSKate Stone return SendIllFormedResponse(packet,
2405b9c1b51eSKate Stone "H variant unsupported, should be c or g");
2406e13c2731STamas Berghammer }
2407e13c2731STamas Berghammer
2408e13c2731STamas Berghammer return SendOKResponse();
2409e13c2731STamas Berghammer }
2410e13c2731STamas Berghammer
2411e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_I(StringExtractorGDBRemote & packet)2412b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
2413a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Thread);
2414e13c2731STamas Berghammer
2415e13c2731STamas Berghammer // Fail if we don't have a current process.
2416f1812a28SMichał Górny if (!m_current_process ||
2417f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
241863e5fb76SJonas Devlieghere LLDB_LOGF(
241963e5fb76SJonas Devlieghere log,
2420b9c1b51eSKate Stone "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2421b9c1b51eSKate Stone __FUNCTION__);
2422e13c2731STamas Berghammer return SendErrorResponse(0x15);
2423e13c2731STamas Berghammer }
2424e13c2731STamas Berghammer
2425e13c2731STamas Berghammer packet.SetFilePos(::strlen("I"));
2426d08f09c1SZachary Turner uint8_t tmp[4096];
2427b9c1b51eSKate Stone for (;;) {
2428d08f09c1SZachary Turner size_t read = packet.GetHexBytesAvail(tmp);
2429b9c1b51eSKate Stone if (read == 0) {
2430e13c2731STamas Berghammer break;
2431e13c2731STamas Berghammer }
2432e13c2731STamas Berghammer // write directly to stdin *this might block if stdin buffer is full*
2433b9c1b51eSKate Stone // TODO: enqueue this block in circular buffer and send window size to
2434b9c1b51eSKate Stone // remote host
2435e13c2731STamas Berghammer ConnectionStatus status;
243697206d57SZachary Turner Status error;
2437e13c2731STamas Berghammer m_stdio_communication.Write(tmp, read, status, &error);
2438b9c1b51eSKate Stone if (error.Fail()) {
2439e13c2731STamas Berghammer return SendErrorResponse(0x15);
2440e13c2731STamas Berghammer }
2441e13c2731STamas Berghammer }
2442e13c2731STamas Berghammer
2443e13c2731STamas Berghammer return SendOKResponse();
2444e13c2731STamas Berghammer }
2445e13c2731STamas Berghammer
2446e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_interrupt(StringExtractorGDBRemote & packet)2447b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_interrupt(
2448b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
2449a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
2450e13c2731STamas Berghammer
2451e13c2731STamas Berghammer // Fail if we don't have a current process.
2452f1812a28SMichał Górny if (!m_current_process ||
2453f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
245482abefa4SPavel Labath LLDB_LOG(log, "failed, no process available");
2455e13c2731STamas Berghammer return SendErrorResponse(0x15);
2456e13c2731STamas Berghammer }
2457e13c2731STamas Berghammer
2458e13c2731STamas Berghammer // Interrupt the process.
2459f1812a28SMichał Górny Status error = m_current_process->Interrupt();
2460b9c1b51eSKate Stone if (error.Fail()) {
2461f1812a28SMichał Górny LLDB_LOG(log, "failed for process {0}: {1}", m_current_process->GetID(),
246282abefa4SPavel Labath error);
2463e13c2731STamas Berghammer return SendErrorResponse(GDBRemoteServerError::eErrorResume);
2464e13c2731STamas Berghammer }
2465e13c2731STamas Berghammer
2466f1812a28SMichał Górny LLDB_LOG(log, "stopped process {0}", m_current_process->GetID());
2467e13c2731STamas Berghammer
2468e13c2731STamas Berghammer // No response required from stop all.
2469e13c2731STamas Berghammer return PacketResult::Success;
2470e13c2731STamas Berghammer }
2471e13c2731STamas Berghammer
2472e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_memory_read(StringExtractorGDBRemote & packet)2473b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_memory_read(
2474b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
2475a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
2476e13c2731STamas Berghammer
2477f1812a28SMichał Górny if (!m_current_process ||
2478f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
247963e5fb76SJonas Devlieghere LLDB_LOGF(
248063e5fb76SJonas Devlieghere log,
2481b9c1b51eSKate Stone "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2482b9c1b51eSKate Stone __FUNCTION__);
2483e13c2731STamas Berghammer return SendErrorResponse(0x15);
2484e13c2731STamas Berghammer }
2485e13c2731STamas Berghammer
2486e13c2731STamas Berghammer // Parse out the memory address.
2487e13c2731STamas Berghammer packet.SetFilePos(strlen("m"));
2488e13c2731STamas Berghammer if (packet.GetBytesLeft() < 1)
2489e13c2731STamas Berghammer return SendIllFormedResponse(packet, "Too short m packet");
2490e13c2731STamas Berghammer
2491e13c2731STamas Berghammer // Read the address. Punting on validation.
2492b9c1b51eSKate Stone // FIXME replace with Hex U64 read with no default value that fails on failed
2493b9c1b51eSKate Stone // read.
2494e13c2731STamas Berghammer const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2495e13c2731STamas Berghammer
2496e13c2731STamas Berghammer // Validate comma.
2497e13c2731STamas Berghammer if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2498e13c2731STamas Berghammer return SendIllFormedResponse(packet, "Comma sep missing in m packet");
2499e13c2731STamas Berghammer
2500e13c2731STamas Berghammer // Get # bytes to read.
2501e13c2731STamas Berghammer if (packet.GetBytesLeft() < 1)
2502e13c2731STamas Berghammer return SendIllFormedResponse(packet, "Length missing in m packet");
2503e13c2731STamas Berghammer
2504e13c2731STamas Berghammer const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2505b9c1b51eSKate Stone if (byte_count == 0) {
250663e5fb76SJonas Devlieghere LLDB_LOGF(log,
250763e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s nothing to read: "
2508b9c1b51eSKate Stone "zero-length packet",
2509b9c1b51eSKate Stone __FUNCTION__);
25103bf11256SPavel Labath return SendOKResponse();
2511e13c2731STamas Berghammer }
2512e13c2731STamas Berghammer
2513e13c2731STamas Berghammer // Allocate the response buffer.
2514e13c2731STamas Berghammer std::string buf(byte_count, '\0');
2515e13c2731STamas Berghammer if (buf.empty())
2516e13c2731STamas Berghammer return SendErrorResponse(0x78);
2517e13c2731STamas Berghammer
2518e13c2731STamas Berghammer // Retrieve the process memory.
25193eb4b458SChaoren Lin size_t bytes_read = 0;
2520f1812a28SMichał Górny Status error = m_current_process->ReadMemoryWithoutTrap(
2521b9c1b51eSKate Stone read_addr, &buf[0], byte_count, bytes_read);
2522b9c1b51eSKate Stone if (error.Fail()) {
252363e5fb76SJonas Devlieghere LLDB_LOGF(log,
252463e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2525b9c1b51eSKate Stone " mem 0x%" PRIx64 ": failed to read. Error: %s",
2526f1812a28SMichał Górny __FUNCTION__, m_current_process->GetID(), read_addr,
2527b9c1b51eSKate Stone error.AsCString());
2528e13c2731STamas Berghammer return SendErrorResponse(0x08);
2529e13c2731STamas Berghammer }
2530e13c2731STamas Berghammer
2531b9c1b51eSKate Stone if (bytes_read == 0) {
253263e5fb76SJonas Devlieghere LLDB_LOGF(log,
253363e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
2534b9c1b51eSKate Stone " mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
2535f1812a28SMichał Górny __FUNCTION__, m_current_process->GetID(), read_addr, byte_count);
2536e13c2731STamas Berghammer return SendErrorResponse(0x08);
2537e13c2731STamas Berghammer }
2538e13c2731STamas Berghammer
2539e13c2731STamas Berghammer StreamGDBRemote response;
25403bf11256SPavel Labath packet.SetFilePos(0);
25413bf11256SPavel Labath char kind = packet.GetChar('?');
25423bf11256SPavel Labath if (kind == 'x')
25433bf11256SPavel Labath response.PutEscapedBytes(buf.data(), byte_count);
2544b9c1b51eSKate Stone else {
25453bf11256SPavel Labath assert(kind == 'm');
25463eb4b458SChaoren Lin for (size_t i = 0; i < bytes_read; ++i)
2547e13c2731STamas Berghammer response.PutHex8(buf[i]);
25483bf11256SPavel Labath }
2549e13c2731STamas Berghammer
255026709df8SZachary Turner return SendPacketNoLock(response.GetString());
2551e13c2731STamas Berghammer }
2552e13c2731STamas Berghammer
2553e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle__M(StringExtractorGDBRemote & packet)25542c4226f8SPavel Labath GDBRemoteCommunicationServerLLGS::Handle__M(StringExtractorGDBRemote &packet) {
2555a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
25562c4226f8SPavel Labath
2557f1812a28SMichał Górny if (!m_current_process ||
2558f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
25592c4226f8SPavel Labath LLDB_LOGF(
25602c4226f8SPavel Labath log,
25612c4226f8SPavel Labath "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
25622c4226f8SPavel Labath __FUNCTION__);
25632c4226f8SPavel Labath return SendErrorResponse(0x15);
25642c4226f8SPavel Labath }
25652c4226f8SPavel Labath
25662c4226f8SPavel Labath // Parse out the memory address.
25672c4226f8SPavel Labath packet.SetFilePos(strlen("_M"));
25682c4226f8SPavel Labath if (packet.GetBytesLeft() < 1)
25692c4226f8SPavel Labath return SendIllFormedResponse(packet, "Too short _M packet");
25702c4226f8SPavel Labath
25712c4226f8SPavel Labath const lldb::addr_t size = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
25722c4226f8SPavel Labath if (size == LLDB_INVALID_ADDRESS)
25732c4226f8SPavel Labath return SendIllFormedResponse(packet, "Address not valid");
25742c4226f8SPavel Labath if (packet.GetChar() != ',')
25752c4226f8SPavel Labath return SendIllFormedResponse(packet, "Bad packet");
25762c4226f8SPavel Labath Permissions perms = {};
25772c4226f8SPavel Labath while (packet.GetBytesLeft() > 0) {
25782c4226f8SPavel Labath switch (packet.GetChar()) {
25792c4226f8SPavel Labath case 'r':
25802c4226f8SPavel Labath perms |= ePermissionsReadable;
25812c4226f8SPavel Labath break;
25822c4226f8SPavel Labath case 'w':
25832c4226f8SPavel Labath perms |= ePermissionsWritable;
25842c4226f8SPavel Labath break;
25852c4226f8SPavel Labath case 'x':
25862c4226f8SPavel Labath perms |= ePermissionsExecutable;
25872c4226f8SPavel Labath break;
25882c4226f8SPavel Labath default:
25892c4226f8SPavel Labath return SendIllFormedResponse(packet, "Bad permissions");
25902c4226f8SPavel Labath }
25912c4226f8SPavel Labath }
25922c4226f8SPavel Labath
2593f1812a28SMichał Górny llvm::Expected<addr_t> addr = m_current_process->AllocateMemory(size, perms);
25942c4226f8SPavel Labath if (!addr)
25952c4226f8SPavel Labath return SendErrorResponse(addr.takeError());
25962c4226f8SPavel Labath
25972c4226f8SPavel Labath StreamGDBRemote response;
25982c4226f8SPavel Labath response.PutHex64(*addr);
25992c4226f8SPavel Labath return SendPacketNoLock(response.GetString());
26002c4226f8SPavel Labath }
26012c4226f8SPavel Labath
26022c4226f8SPavel Labath GDBRemoteCommunication::PacketResult
Handle__m(StringExtractorGDBRemote & packet)26032c4226f8SPavel Labath GDBRemoteCommunicationServerLLGS::Handle__m(StringExtractorGDBRemote &packet) {
2604a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
26052c4226f8SPavel Labath
2606f1812a28SMichał Górny if (!m_current_process ||
2607f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
26082c4226f8SPavel Labath LLDB_LOGF(
26092c4226f8SPavel Labath log,
26102c4226f8SPavel Labath "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
26112c4226f8SPavel Labath __FUNCTION__);
26122c4226f8SPavel Labath return SendErrorResponse(0x15);
26132c4226f8SPavel Labath }
26142c4226f8SPavel Labath
26152c4226f8SPavel Labath // Parse out the memory address.
26162c4226f8SPavel Labath packet.SetFilePos(strlen("_m"));
26172c4226f8SPavel Labath if (packet.GetBytesLeft() < 1)
26182c4226f8SPavel Labath return SendIllFormedResponse(packet, "Too short m packet");
26192c4226f8SPavel Labath
26202c4226f8SPavel Labath const lldb::addr_t addr = packet.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
26212c4226f8SPavel Labath if (addr == LLDB_INVALID_ADDRESS)
26222c4226f8SPavel Labath return SendIllFormedResponse(packet, "Address not valid");
26232c4226f8SPavel Labath
2624f1812a28SMichał Górny if (llvm::Error Err = m_current_process->DeallocateMemory(addr))
26252c4226f8SPavel Labath return SendErrorResponse(std::move(Err));
26262c4226f8SPavel Labath
26272c4226f8SPavel Labath return SendOKResponse();
26282c4226f8SPavel Labath }
26292c4226f8SPavel Labath
26302c4226f8SPavel Labath GDBRemoteCommunication::PacketResult
Handle_M(StringExtractorGDBRemote & packet)2631b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
2632a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
2633e13c2731STamas Berghammer
2634f1812a28SMichał Górny if (!m_current_process ||
2635f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
263663e5fb76SJonas Devlieghere LLDB_LOGF(
263763e5fb76SJonas Devlieghere log,
2638b9c1b51eSKate Stone "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2639b9c1b51eSKate Stone __FUNCTION__);
2640e13c2731STamas Berghammer return SendErrorResponse(0x15);
2641e13c2731STamas Berghammer }
2642e13c2731STamas Berghammer
2643e13c2731STamas Berghammer // Parse out the memory address.
2644e13c2731STamas Berghammer packet.SetFilePos(strlen("M"));
2645e13c2731STamas Berghammer if (packet.GetBytesLeft() < 1)
2646e13c2731STamas Berghammer return SendIllFormedResponse(packet, "Too short M packet");
2647e13c2731STamas Berghammer
2648e13c2731STamas Berghammer // Read the address. Punting on validation.
2649b9c1b51eSKate Stone // FIXME replace with Hex U64 read with no default value that fails on failed
2650b9c1b51eSKate Stone // read.
2651e13c2731STamas Berghammer const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
2652e13c2731STamas Berghammer
2653e13c2731STamas Berghammer // Validate comma.
2654e13c2731STamas Berghammer if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
2655e13c2731STamas Berghammer return SendIllFormedResponse(packet, "Comma sep missing in M packet");
2656e13c2731STamas Berghammer
2657e13c2731STamas Berghammer // Get # bytes to read.
2658e13c2731STamas Berghammer if (packet.GetBytesLeft() < 1)
2659e13c2731STamas Berghammer return SendIllFormedResponse(packet, "Length missing in M packet");
2660e13c2731STamas Berghammer
2661e13c2731STamas Berghammer const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
2662b9c1b51eSKate Stone if (byte_count == 0) {
266382abefa4SPavel Labath LLDB_LOG(log, "nothing to write: zero-length packet");
2664e13c2731STamas Berghammer return PacketResult::Success;
2665e13c2731STamas Berghammer }
2666e13c2731STamas Berghammer
2667e13c2731STamas Berghammer // Validate colon.
2668e13c2731STamas Berghammer if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
2669b9c1b51eSKate Stone return SendIllFormedResponse(
2670b9c1b51eSKate Stone packet, "Comma sep missing in M packet after byte length");
2671e13c2731STamas Berghammer
2672e13c2731STamas Berghammer // Allocate the conversion buffer.
2673e13c2731STamas Berghammer std::vector<uint8_t> buf(byte_count, 0);
2674e13c2731STamas Berghammer if (buf.empty())
2675e13c2731STamas Berghammer return SendErrorResponse(0x78);
2676e13c2731STamas Berghammer
2677e13c2731STamas Berghammer // Convert the hex memory write contents to bytes.
2678e13c2731STamas Berghammer StreamGDBRemote response;
2679d08f09c1SZachary Turner const uint64_t convert_count = packet.GetHexBytes(buf, 0);
2680b9c1b51eSKate Stone if (convert_count != byte_count) {
268182abefa4SPavel Labath LLDB_LOG(log,
268282abefa4SPavel Labath "pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
268382abefa4SPavel Labath "to convert.",
2684f1812a28SMichał Górny m_current_process->GetID(), write_addr, byte_count, convert_count);
2685b9c1b51eSKate Stone return SendIllFormedResponse(packet, "M content byte length specified did "
2686b9c1b51eSKate Stone "not match hex-encoded content "
2687b9c1b51eSKate Stone "length");
2688e13c2731STamas Berghammer }
2689e13c2731STamas Berghammer
2690e13c2731STamas Berghammer // Write the process memory.
26913eb4b458SChaoren Lin size_t bytes_written = 0;
2692f1812a28SMichał Górny Status error = m_current_process->WriteMemory(write_addr, &buf[0], byte_count,
2693f1812a28SMichał Górny bytes_written);
2694b9c1b51eSKate Stone if (error.Fail()) {
269582abefa4SPavel Labath LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
2696f1812a28SMichał Górny m_current_process->GetID(), write_addr, error);
2697e13c2731STamas Berghammer return SendErrorResponse(0x09);
2698e13c2731STamas Berghammer }
2699e13c2731STamas Berghammer
2700b9c1b51eSKate Stone if (bytes_written == 0) {
270182abefa4SPavel Labath LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
2702f1812a28SMichał Górny m_current_process->GetID(), write_addr, byte_count);
2703e13c2731STamas Berghammer return SendErrorResponse(0x09);
2704e13c2731STamas Berghammer }
2705e13c2731STamas Berghammer
2706e13c2731STamas Berghammer return SendOKResponse();
2707e13c2731STamas Berghammer }
2708e13c2731STamas Berghammer
2709e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_qMemoryRegionInfoSupported(StringExtractorGDBRemote & packet)2710b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
2711b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
2712a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
2713e13c2731STamas Berghammer
2714b9c1b51eSKate Stone // Currently only the NativeProcessProtocol knows if it can handle a
271505097246SAdrian Prantl // qMemoryRegionInfoSupported request, but we're not guaranteed to be
271605097246SAdrian Prantl // attached to a process. For now we'll assume the client only asks this
271705097246SAdrian Prantl // when a process is being debugged.
2718e13c2731STamas Berghammer
2719e13c2731STamas Berghammer // Ensure we have a process running; otherwise, we can't figure this out
2720e13c2731STamas Berghammer // since we won't have a NativeProcessProtocol.
2721f1812a28SMichał Górny if (!m_current_process ||
2722f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
272363e5fb76SJonas Devlieghere LLDB_LOGF(
272463e5fb76SJonas Devlieghere log,
2725b9c1b51eSKate Stone "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2726b9c1b51eSKate Stone __FUNCTION__);
2727e13c2731STamas Berghammer return SendErrorResponse(0x15);
2728e13c2731STamas Berghammer }
2729e13c2731STamas Berghammer
2730e13c2731STamas Berghammer // Test if we can get any region back when asking for the region around NULL.
2731e13c2731STamas Berghammer MemoryRegionInfo region_info;
2732f1812a28SMichał Górny const Status error = m_current_process->GetMemoryRegionInfo(0, region_info);
2733b9c1b51eSKate Stone if (error.Fail()) {
2734b9c1b51eSKate Stone // We don't support memory region info collection for this
2735b9c1b51eSKate Stone // NativeProcessProtocol.
2736e13c2731STamas Berghammer return SendUnimplementedResponse("");
2737e13c2731STamas Berghammer }
2738e13c2731STamas Berghammer
2739e13c2731STamas Berghammer return SendOKResponse();
2740e13c2731STamas Berghammer }
2741e13c2731STamas Berghammer
2742e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_qMemoryRegionInfo(StringExtractorGDBRemote & packet)2743b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
2744b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
2745a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
2746e13c2731STamas Berghammer
2747e13c2731STamas Berghammer // Ensure we have a process.
2748f1812a28SMichał Górny if (!m_current_process ||
2749f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
275063e5fb76SJonas Devlieghere LLDB_LOGF(
275163e5fb76SJonas Devlieghere log,
2752b9c1b51eSKate Stone "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
2753b9c1b51eSKate Stone __FUNCTION__);
2754e13c2731STamas Berghammer return SendErrorResponse(0x15);
2755e13c2731STamas Berghammer }
2756e13c2731STamas Berghammer
2757e13c2731STamas Berghammer // Parse out the memory address.
2758e13c2731STamas Berghammer packet.SetFilePos(strlen("qMemoryRegionInfo:"));
2759e13c2731STamas Berghammer if (packet.GetBytesLeft() < 1)
2760e13c2731STamas Berghammer return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
2761e13c2731STamas Berghammer
2762e13c2731STamas Berghammer // Read the address. Punting on validation.
2763e13c2731STamas Berghammer const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
2764e13c2731STamas Berghammer
2765e13c2731STamas Berghammer StreamGDBRemote response;
2766e13c2731STamas Berghammer
2767e13c2731STamas Berghammer // Get the memory region info for the target address.
2768e13c2731STamas Berghammer MemoryRegionInfo region_info;
276997206d57SZachary Turner const Status error =
2770f1812a28SMichał Górny m_current_process->GetMemoryRegionInfo(read_addr, region_info);
2771b9c1b51eSKate Stone if (error.Fail()) {
2772e13c2731STamas Berghammer // Return the error message.
2773e13c2731STamas Berghammer
2774e13c2731STamas Berghammer response.PutCString("error:");
27757f815a9aSPavel Labath response.PutStringAsRawHex8(error.AsCString());
2776e13c2731STamas Berghammer response.PutChar(';');
2777b9c1b51eSKate Stone } else {
2778e13c2731STamas Berghammer // Range start and size.
2779b9c1b51eSKate Stone response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
2780b9c1b51eSKate Stone region_info.GetRange().GetRangeBase(),
2781b9c1b51eSKate Stone region_info.GetRange().GetByteSize());
2782e13c2731STamas Berghammer
2783e13c2731STamas Berghammer // Permissions.
2784b9c1b51eSKate Stone if (region_info.GetReadable() || region_info.GetWritable() ||
2785b9c1b51eSKate Stone region_info.GetExecutable()) {
2786e13c2731STamas Berghammer // Write permissions info.
2787e13c2731STamas Berghammer response.PutCString("permissions:");
2788e13c2731STamas Berghammer
2789e13c2731STamas Berghammer if (region_info.GetReadable())
2790e13c2731STamas Berghammer response.PutChar('r');
2791e13c2731STamas Berghammer if (region_info.GetWritable())
2792e13c2731STamas Berghammer response.PutChar('w');
2793e13c2731STamas Berghammer if (region_info.GetExecutable())
2794e13c2731STamas Berghammer response.PutChar('x');
2795e13c2731STamas Berghammer
2796e13c2731STamas Berghammer response.PutChar(';');
2797e13c2731STamas Berghammer }
2798d7d69f80STamas Berghammer
279932541685SDavid Spickett // Flags
280032541685SDavid Spickett MemoryRegionInfo::OptionalBool memory_tagged =
280132541685SDavid Spickett region_info.GetMemoryTagged();
280232541685SDavid Spickett if (memory_tagged != MemoryRegionInfo::eDontKnow) {
280332541685SDavid Spickett response.PutCString("flags:");
280432541685SDavid Spickett if (memory_tagged == MemoryRegionInfo::eYes) {
280532541685SDavid Spickett response.PutCString("mt");
280632541685SDavid Spickett }
280732541685SDavid Spickett response.PutChar(';');
280832541685SDavid Spickett }
280932541685SDavid Spickett
2810d7d69f80STamas Berghammer // Name
2811d7d69f80STamas Berghammer ConstString name = region_info.GetName();
2812b9c1b51eSKate Stone if (name) {
2813d7d69f80STamas Berghammer response.PutCString("name:");
2814642bc15dSRaphael Isemann response.PutStringAsRawHex8(name.GetStringRef());
2815d7d69f80STamas Berghammer response.PutChar(';');
2816d7d69f80STamas Berghammer }
2817e13c2731STamas Berghammer }
2818e13c2731STamas Berghammer
281926709df8SZachary Turner return SendPacketNoLock(response.GetString());
2820e13c2731STamas Berghammer }
2821e13c2731STamas Berghammer
2822e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_Z(StringExtractorGDBRemote & packet)2823b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
2824e13c2731STamas Berghammer // Ensure we have a process.
2825f1812a28SMichał Górny if (!m_current_process ||
2826f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2827a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
282882abefa4SPavel Labath LLDB_LOG(log, "failed, no process available");
2829e13c2731STamas Berghammer return SendErrorResponse(0x15);
2830e13c2731STamas Berghammer }
2831e13c2731STamas Berghammer
2832e13c2731STamas Berghammer // Parse out software or hardware breakpoint or watchpoint requested.
2833e13c2731STamas Berghammer packet.SetFilePos(strlen("Z"));
2834e13c2731STamas Berghammer if (packet.GetBytesLeft() < 1)
2835b9c1b51eSKate Stone return SendIllFormedResponse(
2836b9c1b51eSKate Stone packet, "Too short Z packet, missing software/hardware specifier");
2837e13c2731STamas Berghammer
2838e13c2731STamas Berghammer bool want_breakpoint = true;
2839e13c2731STamas Berghammer bool want_hardware = false;
2840cf8eb9daSOmair Javaid uint32_t watch_flags = 0;
2841e13c2731STamas Berghammer
2842e13c2731STamas Berghammer const GDBStoppointType stoppoint_type =
2843e13c2731STamas Berghammer GDBStoppointType(packet.GetS32(eStoppointInvalid));
2844b9c1b51eSKate Stone switch (stoppoint_type) {
2845e13c2731STamas Berghammer case eBreakpointSoftware:
2846b9c1b51eSKate Stone want_hardware = false;
2847b9c1b51eSKate Stone want_breakpoint = true;
2848b9c1b51eSKate Stone break;
2849e13c2731STamas Berghammer case eBreakpointHardware:
2850b9c1b51eSKate Stone want_hardware = true;
2851b9c1b51eSKate Stone want_breakpoint = true;
2852b9c1b51eSKate Stone break;
2853e13c2731STamas Berghammer case eWatchpointWrite:
2854cf8eb9daSOmair Javaid watch_flags = 1;
2855b9c1b51eSKate Stone want_hardware = true;
2856b9c1b51eSKate Stone want_breakpoint = false;
2857b9c1b51eSKate Stone break;
2858e13c2731STamas Berghammer case eWatchpointRead:
2859cf8eb9daSOmair Javaid watch_flags = 2;
2860b9c1b51eSKate Stone want_hardware = true;
2861b9c1b51eSKate Stone want_breakpoint = false;
2862b9c1b51eSKate Stone break;
2863e13c2731STamas Berghammer case eWatchpointReadWrite:
2864cf8eb9daSOmair Javaid watch_flags = 3;
2865b9c1b51eSKate Stone want_hardware = true;
2866b9c1b51eSKate Stone want_breakpoint = false;
2867b9c1b51eSKate Stone break;
2868e13c2731STamas Berghammer case eStoppointInvalid:
2869b9c1b51eSKate Stone return SendIllFormedResponse(
2870b9c1b51eSKate Stone packet, "Z packet had invalid software/hardware specifier");
2871e13c2731STamas Berghammer }
2872e13c2731STamas Berghammer
2873e13c2731STamas Berghammer if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2874b9c1b51eSKate Stone return SendIllFormedResponse(
2875b9c1b51eSKate Stone packet, "Malformed Z packet, expecting comma after stoppoint type");
2876e13c2731STamas Berghammer
2877e13c2731STamas Berghammer // Parse out the stoppoint address.
2878e13c2731STamas Berghammer if (packet.GetBytesLeft() < 1)
2879e13c2731STamas Berghammer return SendIllFormedResponse(packet, "Too short Z packet, missing address");
2880e13c2731STamas Berghammer const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2881e13c2731STamas Berghammer
2882e13c2731STamas Berghammer if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2883b9c1b51eSKate Stone return SendIllFormedResponse(
2884b9c1b51eSKate Stone packet, "Malformed Z packet, expecting comma after address");
2885e13c2731STamas Berghammer
2886e13c2731STamas Berghammer // Parse out the stoppoint size (i.e. size hint for opcode size).
2887b9c1b51eSKate Stone const uint32_t size =
2888b9c1b51eSKate Stone packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
2889e13c2731STamas Berghammer if (size == std::numeric_limits<uint32_t>::max())
2890b9c1b51eSKate Stone return SendIllFormedResponse(
2891b9c1b51eSKate Stone packet, "Malformed Z packet, failed to parse size argument");
2892e13c2731STamas Berghammer
2893b9c1b51eSKate Stone if (want_breakpoint) {
2894e13c2731STamas Berghammer // Try to set the breakpoint.
289597206d57SZachary Turner const Status error =
2896f1812a28SMichał Górny m_current_process->SetBreakpoint(addr, size, want_hardware);
2897e13c2731STamas Berghammer if (error.Success())
2898e13c2731STamas Berghammer return SendOKResponse();
2899a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Breakpoints);
290082abefa4SPavel Labath LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
2901f1812a28SMichał Górny m_current_process->GetID(), error);
2902e13c2731STamas Berghammer return SendErrorResponse(0x09);
2903b9c1b51eSKate Stone } else {
2904e13c2731STamas Berghammer // Try to set the watchpoint.
2905f1812a28SMichał Górny const Status error = m_current_process->SetWatchpoint(
2906e13c2731STamas Berghammer addr, size, watch_flags, want_hardware);
2907e13c2731STamas Berghammer if (error.Success())
2908e13c2731STamas Berghammer return SendOKResponse();
2909a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Watchpoints);
291082abefa4SPavel Labath LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
2911f1812a28SMichał Górny m_current_process->GetID(), error);
2912e13c2731STamas Berghammer return SendErrorResponse(0x09);
2913e13c2731STamas Berghammer }
2914e13c2731STamas Berghammer }
2915e13c2731STamas Berghammer
2916e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_z(StringExtractorGDBRemote & packet)2917b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
2918e13c2731STamas Berghammer // Ensure we have a process.
2919f1812a28SMichał Górny if (!m_current_process ||
2920f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
2921a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
292282abefa4SPavel Labath LLDB_LOG(log, "failed, no process available");
2923e13c2731STamas Berghammer return SendErrorResponse(0x15);
2924e13c2731STamas Berghammer }
2925e13c2731STamas Berghammer
2926e13c2731STamas Berghammer // Parse out software or hardware breakpoint or watchpoint requested.
2927e13c2731STamas Berghammer packet.SetFilePos(strlen("z"));
2928e13c2731STamas Berghammer if (packet.GetBytesLeft() < 1)
2929b9c1b51eSKate Stone return SendIllFormedResponse(
2930b9c1b51eSKate Stone packet, "Too short z packet, missing software/hardware specifier");
2931e13c2731STamas Berghammer
2932e13c2731STamas Berghammer bool want_breakpoint = true;
2933d5ffbad2SOmair Javaid bool want_hardware = false;
2934e13c2731STamas Berghammer
2935e13c2731STamas Berghammer const GDBStoppointType stoppoint_type =
2936e13c2731STamas Berghammer GDBStoppointType(packet.GetS32(eStoppointInvalid));
2937b9c1b51eSKate Stone switch (stoppoint_type) {
2938b9c1b51eSKate Stone case eBreakpointHardware:
2939b9c1b51eSKate Stone want_breakpoint = true;
2940d5ffbad2SOmair Javaid want_hardware = true;
2941b9c1b51eSKate Stone break;
2942b9c1b51eSKate Stone case eBreakpointSoftware:
2943b9c1b51eSKate Stone want_breakpoint = true;
2944b9c1b51eSKate Stone break;
2945b9c1b51eSKate Stone case eWatchpointWrite:
2946b9c1b51eSKate Stone want_breakpoint = false;
2947b9c1b51eSKate Stone break;
2948b9c1b51eSKate Stone case eWatchpointRead:
2949b9c1b51eSKate Stone want_breakpoint = false;
2950b9c1b51eSKate Stone break;
2951b9c1b51eSKate Stone case eWatchpointReadWrite:
2952b9c1b51eSKate Stone want_breakpoint = false;
2953b9c1b51eSKate Stone break;
2954e13c2731STamas Berghammer default:
2955b9c1b51eSKate Stone return SendIllFormedResponse(
2956b9c1b51eSKate Stone packet, "z packet had invalid software/hardware specifier");
2957e13c2731STamas Berghammer }
2958e13c2731STamas Berghammer
2959e13c2731STamas Berghammer if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2960b9c1b51eSKate Stone return SendIllFormedResponse(
2961b9c1b51eSKate Stone packet, "Malformed z packet, expecting comma after stoppoint type");
2962e13c2731STamas Berghammer
2963e13c2731STamas Berghammer // Parse out the stoppoint address.
2964e13c2731STamas Berghammer if (packet.GetBytesLeft() < 1)
2965e13c2731STamas Berghammer return SendIllFormedResponse(packet, "Too short z packet, missing address");
2966e13c2731STamas Berghammer const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
2967e13c2731STamas Berghammer
2968e13c2731STamas Berghammer if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
2969b9c1b51eSKate Stone return SendIllFormedResponse(
2970b9c1b51eSKate Stone packet, "Malformed z packet, expecting comma after address");
2971e13c2731STamas Berghammer
2972e13c2731STamas Berghammer /*
2973e13c2731STamas Berghammer // Parse out the stoppoint size (i.e. size hint for opcode size).
2974b9c1b51eSKate Stone const uint32_t size = packet.GetHexMaxU32 (false,
2975b9c1b51eSKate Stone std::numeric_limits<uint32_t>::max ());
2976e13c2731STamas Berghammer if (size == std::numeric_limits<uint32_t>::max ())
2977b9c1b51eSKate Stone return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
2978b9c1b51eSKate Stone size argument");
2979e13c2731STamas Berghammer */
2980e13c2731STamas Berghammer
2981b9c1b51eSKate Stone if (want_breakpoint) {
2982e13c2731STamas Berghammer // Try to clear the breakpoint.
298397206d57SZachary Turner const Status error =
2984f1812a28SMichał Górny m_current_process->RemoveBreakpoint(addr, want_hardware);
2985e13c2731STamas Berghammer if (error.Success())
2986e13c2731STamas Berghammer return SendOKResponse();
2987a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Breakpoints);
298882abefa4SPavel Labath LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
2989f1812a28SMichał Górny m_current_process->GetID(), error);
2990e13c2731STamas Berghammer return SendErrorResponse(0x09);
2991b9c1b51eSKate Stone } else {
2992e13c2731STamas Berghammer // Try to clear the watchpoint.
2993f1812a28SMichał Górny const Status error = m_current_process->RemoveWatchpoint(addr);
2994e13c2731STamas Berghammer if (error.Success())
2995e13c2731STamas Berghammer return SendOKResponse();
2996a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Watchpoints);
299782abefa4SPavel Labath LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
2998f1812a28SMichał Górny m_current_process->GetID(), error);
2999e13c2731STamas Berghammer return SendErrorResponse(0x09);
3000e13c2731STamas Berghammer }
3001e13c2731STamas Berghammer }
3002e13c2731STamas Berghammer
3003e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_s(StringExtractorGDBRemote & packet)3004b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
3005a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
3006e13c2731STamas Berghammer
3007e13c2731STamas Berghammer // Ensure we have a process.
3008f1812a28SMichał Górny if (!m_continue_process ||
3009f1812a28SMichał Górny (m_continue_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
301063e5fb76SJonas Devlieghere LLDB_LOGF(
301163e5fb76SJonas Devlieghere log,
3012b9c1b51eSKate Stone "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3013b9c1b51eSKate Stone __FUNCTION__);
3014e13c2731STamas Berghammer return SendErrorResponse(0x32);
3015e13c2731STamas Berghammer }
3016e13c2731STamas Berghammer
3017b9c1b51eSKate Stone // We first try to use a continue thread id. If any one or any all set, use
301805097246SAdrian Prantl // the current thread. Bail out if we don't have a thread id.
3019e13c2731STamas Berghammer lldb::tid_t tid = GetContinueThreadID();
3020e13c2731STamas Berghammer if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
3021e13c2731STamas Berghammer tid = GetCurrentThreadID();
3022e13c2731STamas Berghammer if (tid == LLDB_INVALID_THREAD_ID)
3023e13c2731STamas Berghammer return SendErrorResponse(0x33);
3024e13c2731STamas Berghammer
3025e13c2731STamas Berghammer // Double check that we have such a thread.
3026e13c2731STamas Berghammer // TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
3027f1812a28SMichał Górny NativeThreadProtocol *thread = m_continue_process->GetThreadByID(tid);
3028a5be48b3SPavel Labath if (!thread)
3029e13c2731STamas Berghammer return SendErrorResponse(0x33);
3030e13c2731STamas Berghammer
3031e13c2731STamas Berghammer // Create the step action for the given thread.
3032c36b0bf3SMichal Gorny ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER};
3033e13c2731STamas Berghammer
3034e13c2731STamas Berghammer // Setup the actions list.
3035db264a6dSTamas Berghammer ResumeActionList actions;
3036e13c2731STamas Berghammer actions.Append(action);
3037e13c2731STamas Berghammer
3038e13c2731STamas Berghammer // All other threads stop while we're single stepping a thread.
3039e13c2731STamas Berghammer actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
3040eb43e43bSMichał Górny
3041eb43e43bSMichał Górny PacketResult resume_res = ResumeProcess(*m_continue_process, actions);
3042eb43e43bSMichał Górny if (resume_res != PacketResult::Success)
3043eb43e43bSMichał Górny return resume_res;
3044e13c2731STamas Berghammer
3045bc04d240SMichał Górny // No response here, unless in non-stop mode.
3046bc04d240SMichał Górny // Otherwise, the stop or exit will come from the resulting action.
3047bc04d240SMichał Górny return SendContinueSuccessResponse();
3048e13c2731STamas Berghammer }
3049e13c2731STamas Berghammer
305057e2da4fSAntonio Afonso llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
BuildTargetXml()3051af64b319SMuhammad Omair Javaid GDBRemoteCommunicationServerLLGS::BuildTargetXml() {
3052af64b319SMuhammad Omair Javaid // Ensure we have a thread.
3053f1812a28SMichał Górny NativeThreadProtocol *thread = m_current_process->GetThreadAtIndex(0);
3054af64b319SMuhammad Omair Javaid if (!thread)
3055af64b319SMuhammad Omair Javaid return llvm::createStringError(llvm::inconvertibleErrorCode(),
3056af64b319SMuhammad Omair Javaid "No thread available");
3057af64b319SMuhammad Omair Javaid
3058a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
3059af64b319SMuhammad Omair Javaid // Get the register context for the first thread.
3060af64b319SMuhammad Omair Javaid NativeRegisterContext ®_context = thread->GetRegisterContext();
3061af64b319SMuhammad Omair Javaid
3062af64b319SMuhammad Omair Javaid StreamString response;
3063af64b319SMuhammad Omair Javaid
3064af64b319SMuhammad Omair Javaid response.Printf("<?xml version=\"1.0\"?>");
3065af64b319SMuhammad Omair Javaid response.Printf("<target version=\"1.0\">");
3066af64b319SMuhammad Omair Javaid
3067af64b319SMuhammad Omair Javaid response.Printf("<architecture>%s</architecture>",
3068f1812a28SMichał Górny m_current_process->GetArchitecture()
3069af64b319SMuhammad Omair Javaid .GetTriple()
3070af64b319SMuhammad Omair Javaid .getArchName()
3071af64b319SMuhammad Omair Javaid .str()
3072af64b319SMuhammad Omair Javaid .c_str());
3073af64b319SMuhammad Omair Javaid
3074af64b319SMuhammad Omair Javaid response.Printf("<feature>");
3075af64b319SMuhammad Omair Javaid
3076af64b319SMuhammad Omair Javaid const int registers_count = reg_context.GetUserRegisterCount();
3077af64b319SMuhammad Omair Javaid for (int reg_index = 0; reg_index < registers_count; reg_index++) {
3078af64b319SMuhammad Omair Javaid const RegisterInfo *reg_info =
3079af64b319SMuhammad Omair Javaid reg_context.GetRegisterInfoAtIndex(reg_index);
3080af64b319SMuhammad Omair Javaid
3081af64b319SMuhammad Omair Javaid if (!reg_info) {
3082af64b319SMuhammad Omair Javaid LLDB_LOGF(log,
3083af64b319SMuhammad Omair Javaid "%s failed to get register info for register index %" PRIu32,
3084af64b319SMuhammad Omair Javaid "target.xml", reg_index);
3085af64b319SMuhammad Omair Javaid continue;
3086af64b319SMuhammad Omair Javaid }
3087af64b319SMuhammad Omair Javaid
308878cb4562SMuhammad Omair Javaid response.Printf("<reg name=\"%s\" bitsize=\"%" PRIu32 "\" regnum=\"%d\" ",
308978cb4562SMuhammad Omair Javaid reg_info->name, reg_info->byte_size * 8, reg_index);
309078cb4562SMuhammad Omair Javaid
309178cb4562SMuhammad Omair Javaid if (!reg_context.RegisterOffsetIsDynamic())
309278cb4562SMuhammad Omair Javaid response.Printf("offset=\"%" PRIu32 "\" ", reg_info->byte_offset);
3093af64b319SMuhammad Omair Javaid
3094af64b319SMuhammad Omair Javaid if (reg_info->alt_name && reg_info->alt_name[0])
3095af64b319SMuhammad Omair Javaid response.Printf("altname=\"%s\" ", reg_info->alt_name);
3096af64b319SMuhammad Omair Javaid
3097af64b319SMuhammad Omair Javaid llvm::StringRef encoding = GetEncodingNameOrEmpty(*reg_info);
3098af64b319SMuhammad Omair Javaid if (!encoding.empty())
3099af64b319SMuhammad Omair Javaid response << "encoding=\"" << encoding << "\" ";
3100af64b319SMuhammad Omair Javaid
3101af64b319SMuhammad Omair Javaid llvm::StringRef format = GetFormatNameOrEmpty(*reg_info);
3102af64b319SMuhammad Omair Javaid if (!format.empty())
3103af64b319SMuhammad Omair Javaid response << "format=\"" << format << "\" ";
3104af64b319SMuhammad Omair Javaid
3105af64b319SMuhammad Omair Javaid const char *const register_set_name =
3106af64b319SMuhammad Omair Javaid reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
3107af64b319SMuhammad Omair Javaid if (register_set_name)
3108af64b319SMuhammad Omair Javaid response << "group=\"" << register_set_name << "\" ";
3109af64b319SMuhammad Omair Javaid
3110af64b319SMuhammad Omair Javaid if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
3111af64b319SMuhammad Omair Javaid LLDB_INVALID_REGNUM)
3112af64b319SMuhammad Omair Javaid response.Printf("ehframe_regnum=\"%" PRIu32 "\" ",
3113af64b319SMuhammad Omair Javaid reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
3114af64b319SMuhammad Omair Javaid
3115af64b319SMuhammad Omair Javaid if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] !=
3116af64b319SMuhammad Omair Javaid LLDB_INVALID_REGNUM)
3117af64b319SMuhammad Omair Javaid response.Printf("dwarf_regnum=\"%" PRIu32 "\" ",
3118af64b319SMuhammad Omair Javaid reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
3119af64b319SMuhammad Omair Javaid
3120af64b319SMuhammad Omair Javaid llvm::StringRef kind_generic = GetKindGenericOrEmpty(*reg_info);
3121af64b319SMuhammad Omair Javaid if (!kind_generic.empty())
3122af64b319SMuhammad Omair Javaid response << "generic=\"" << kind_generic << "\" ";
3123af64b319SMuhammad Omair Javaid
3124af64b319SMuhammad Omair Javaid if (reg_info->value_regs &&
3125af64b319SMuhammad Omair Javaid reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
3126af64b319SMuhammad Omair Javaid response.PutCString("value_regnums=\"");
3127af64b319SMuhammad Omair Javaid CollectRegNums(reg_info->value_regs, response, false);
3128af64b319SMuhammad Omair Javaid response.Printf("\" ");
3129af64b319SMuhammad Omair Javaid }
3130af64b319SMuhammad Omair Javaid
3131af64b319SMuhammad Omair Javaid if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
3132af64b319SMuhammad Omair Javaid response.PutCString("invalidate_regnums=\"");
3133af64b319SMuhammad Omair Javaid CollectRegNums(reg_info->invalidate_regs, response, false);
3134af64b319SMuhammad Omair Javaid response.Printf("\" ");
3135af64b319SMuhammad Omair Javaid }
3136af64b319SMuhammad Omair Javaid
3137af64b319SMuhammad Omair Javaid response.Printf("/>");
3138af64b319SMuhammad Omair Javaid }
3139af64b319SMuhammad Omair Javaid
3140af64b319SMuhammad Omair Javaid response.Printf("</feature>");
3141af64b319SMuhammad Omair Javaid response.Printf("</target>");
3142af64b319SMuhammad Omair Javaid return MemoryBuffer::getMemBufferCopy(response.GetString(), "target.xml");
3143af64b319SMuhammad Omair Javaid }
3144af64b319SMuhammad Omair Javaid
3145af64b319SMuhammad Omair Javaid llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
ReadXferObject(llvm::StringRef object,llvm::StringRef annex)314657e2da4fSAntonio Afonso GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object,
314757e2da4fSAntonio Afonso llvm::StringRef annex) {
3148e13c2731STamas Berghammer // Make sure we have a valid process.
3149f1812a28SMichał Górny if (!m_current_process ||
3150f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
315157e2da4fSAntonio Afonso return llvm::createStringError(llvm::inconvertibleErrorCode(),
315257e2da4fSAntonio Afonso "No process available");
3153e13c2731STamas Berghammer }
3154e13c2731STamas Berghammer
3155af64b319SMuhammad Omair Javaid if (object == "auxv") {
3156e13c2731STamas Berghammer // Grab the auxv data.
3157f1812a28SMichał Górny auto buffer_or_error = m_current_process->GetAuxvData();
315857e2da4fSAntonio Afonso if (!buffer_or_error)
315957e2da4fSAntonio Afonso return llvm::errorCodeToError(buffer_or_error.getError());
316057e2da4fSAntonio Afonso return std::move(*buffer_or_error);
3161e13c2731STamas Berghammer }
3162e13c2731STamas Berghammer
31631e74e5e9SMichał Górny if (object == "siginfo") {
31641e74e5e9SMichał Górny NativeThreadProtocol *thread = m_current_process->GetCurrentThread();
31651e74e5e9SMichał Górny if (!thread)
31661e74e5e9SMichał Górny return llvm::createStringError(llvm::inconvertibleErrorCode(),
31671e74e5e9SMichał Górny "no current thread");
31681e74e5e9SMichał Górny
31691e74e5e9SMichał Górny auto buffer_or_error = thread->GetSiginfo();
31701e74e5e9SMichał Górny if (!buffer_or_error)
31711e74e5e9SMichał Górny return buffer_or_error.takeError();
31721e74e5e9SMichał Górny return std::move(*buffer_or_error);
31731e74e5e9SMichał Górny }
31741e74e5e9SMichał Górny
317505e32badSAntonio Afonso if (object == "libraries-svr4") {
3176f1812a28SMichał Górny auto library_list = m_current_process->GetLoadedSVR4Libraries();
317705e32badSAntonio Afonso if (!library_list)
317805e32badSAntonio Afonso return library_list.takeError();
317905e32badSAntonio Afonso
318005e32badSAntonio Afonso StreamString response;
318105e32badSAntonio Afonso response.Printf("<library-list-svr4 version=\"1.0\">");
318205e32badSAntonio Afonso for (auto const &library : *library_list) {
318305e32badSAntonio Afonso response.Printf("<library name=\"%s\" ",
318405e32badSAntonio Afonso XMLEncodeAttributeValue(library.name.c_str()).c_str());
318505e32badSAntonio Afonso response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
318605e32badSAntonio Afonso response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
318705e32badSAntonio Afonso response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
318805e32badSAntonio Afonso }
318905e32badSAntonio Afonso response.Printf("</library-list-svr4>");
319005e32badSAntonio Afonso return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
319105e32badSAntonio Afonso }
319205e32badSAntonio Afonso
3193af64b319SMuhammad Omair Javaid if (object == "features" && annex == "target.xml")
3194af64b319SMuhammad Omair Javaid return BuildTargetXml();
3195af64b319SMuhammad Omair Javaid
3196e2f1fe36SPavel Labath return llvm::make_error<UnimplementedError>();
319757e2da4fSAntonio Afonso }
319857e2da4fSAntonio Afonso
319957e2da4fSAntonio Afonso GDBRemoteCommunication::PacketResult
Handle_qXfer(StringExtractorGDBRemote & packet)320057e2da4fSAntonio Afonso GDBRemoteCommunicationServerLLGS::Handle_qXfer(
320157e2da4fSAntonio Afonso StringExtractorGDBRemote &packet) {
320257e2da4fSAntonio Afonso SmallVector<StringRef, 5> fields;
320357e2da4fSAntonio Afonso // The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
320457e2da4fSAntonio Afonso StringRef(packet.GetStringRef()).split(fields, ':', 4);
320557e2da4fSAntonio Afonso if (fields.size() != 5)
320657e2da4fSAntonio Afonso return SendIllFormedResponse(packet, "malformed qXfer packet");
320757e2da4fSAntonio Afonso StringRef &xfer_object = fields[1];
320857e2da4fSAntonio Afonso StringRef &xfer_action = fields[2];
320957e2da4fSAntonio Afonso StringRef &xfer_annex = fields[3];
321057e2da4fSAntonio Afonso StringExtractor offset_data(fields[4]);
321157e2da4fSAntonio Afonso if (xfer_action != "read")
321257e2da4fSAntonio Afonso return SendUnimplementedResponse("qXfer action not supported");
321357e2da4fSAntonio Afonso // Parse offset.
321457e2da4fSAntonio Afonso const uint64_t xfer_offset =
321557e2da4fSAntonio Afonso offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
321657e2da4fSAntonio Afonso if (xfer_offset == std::numeric_limits<uint64_t>::max())
321757e2da4fSAntonio Afonso return SendIllFormedResponse(packet, "qXfer packet missing offset");
321857e2da4fSAntonio Afonso // Parse out comma.
321957e2da4fSAntonio Afonso if (offset_data.GetChar() != ',')
322057e2da4fSAntonio Afonso return SendIllFormedResponse(packet,
322157e2da4fSAntonio Afonso "qXfer packet missing comma after offset");
322257e2da4fSAntonio Afonso // Parse out the length.
322357e2da4fSAntonio Afonso const uint64_t xfer_length =
322457e2da4fSAntonio Afonso offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
322557e2da4fSAntonio Afonso if (xfer_length == std::numeric_limits<uint64_t>::max())
322657e2da4fSAntonio Afonso return SendIllFormedResponse(packet, "qXfer packet missing length");
322757e2da4fSAntonio Afonso
322857e2da4fSAntonio Afonso // Get a previously constructed buffer if it exists or create it now.
322957e2da4fSAntonio Afonso std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
323057e2da4fSAntonio Afonso auto buffer_it = m_xfer_buffer_map.find(buffer_key);
323157e2da4fSAntonio Afonso if (buffer_it == m_xfer_buffer_map.end()) {
323257e2da4fSAntonio Afonso auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
323357e2da4fSAntonio Afonso if (!buffer_up)
323457e2da4fSAntonio Afonso return SendErrorResponse(buffer_up.takeError());
323557e2da4fSAntonio Afonso buffer_it = m_xfer_buffer_map
323657e2da4fSAntonio Afonso .insert(std::make_pair(buffer_key, std::move(*buffer_up)))
323757e2da4fSAntonio Afonso .first;
323857e2da4fSAntonio Afonso }
323957e2da4fSAntonio Afonso
324057e2da4fSAntonio Afonso // Send back the response
3241e13c2731STamas Berghammer StreamGDBRemote response;
3242e13c2731STamas Berghammer bool done_with_buffer = false;
324357e2da4fSAntonio Afonso llvm::StringRef buffer = buffer_it->second->getBuffer();
324457e2da4fSAntonio Afonso if (xfer_offset >= buffer.size()) {
3245e13c2731STamas Berghammer // We have nothing left to send. Mark the buffer as complete.
3246e13c2731STamas Berghammer response.PutChar('l');
3247e13c2731STamas Berghammer done_with_buffer = true;
3248b9c1b51eSKate Stone } else {
3249e13c2731STamas Berghammer // Figure out how many bytes are available starting at the given offset.
325057e2da4fSAntonio Afonso buffer = buffer.drop_front(xfer_offset);
3251b9c1b51eSKate Stone // Mark the response type according to whether we're reading the remainder
325257e2da4fSAntonio Afonso // of the data.
325357e2da4fSAntonio Afonso if (xfer_length >= buffer.size()) {
3254e13c2731STamas Berghammer // There will be nothing left to read after this
3255e13c2731STamas Berghammer response.PutChar('l');
3256e13c2731STamas Berghammer done_with_buffer = true;
3257b9c1b51eSKate Stone } else {
3258e13c2731STamas Berghammer // There will still be bytes to read after this request.
3259e13c2731STamas Berghammer response.PutChar('m');
326057e2da4fSAntonio Afonso buffer = buffer.take_front(xfer_length);
3261e13c2731STamas Berghammer }
3262e13c2731STamas Berghammer // Now write the data in encoded binary form.
3263b7f0f45fSPavel Labath response.PutEscapedBytes(buffer.data(), buffer.size());
3264e13c2731STamas Berghammer }
3265e13c2731STamas Berghammer
3266e13c2731STamas Berghammer if (done_with_buffer)
326757e2da4fSAntonio Afonso m_xfer_buffer_map.erase(buffer_it);
3268e13c2731STamas Berghammer
326926709df8SZachary Turner return SendPacketNoLock(response.GetString());
3270e13c2731STamas Berghammer }
3271e13c2731STamas Berghammer
3272e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_QSaveRegisterState(StringExtractorGDBRemote & packet)3273b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
3274b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
3275a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Thread);
3276e13c2731STamas Berghammer
3277e13c2731STamas Berghammer // Move past packet name.
3278e13c2731STamas Berghammer packet.SetFilePos(strlen("QSaveRegisterState"));
3279e13c2731STamas Berghammer
3280e13c2731STamas Berghammer // Get the thread to use.
3281a5be48b3SPavel Labath NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3282a5be48b3SPavel Labath if (!thread) {
3283e13c2731STamas Berghammer if (m_thread_suffix_supported)
3284b9c1b51eSKate Stone return SendIllFormedResponse(
3285b9c1b51eSKate Stone packet, "No thread specified in QSaveRegisterState packet");
3286e13c2731STamas Berghammer else
3287b9c1b51eSKate Stone return SendIllFormedResponse(packet,
3288b9c1b51eSKate Stone "No thread was is set with the Hg packet");
3289e13c2731STamas Berghammer }
3290e13c2731STamas Berghammer
3291e13c2731STamas Berghammer // Grab the register context for the thread.
3292d37349f3SPavel Labath NativeRegisterContext& reg_context = thread->GetRegisterContext();
3293e13c2731STamas Berghammer
3294e13c2731STamas Berghammer // Save registers to a buffer.
3295c2f64601SJonas Devlieghere WritableDataBufferSP register_data_sp;
3296d37349f3SPavel Labath Status error = reg_context.ReadAllRegisterValues(register_data_sp);
3297b9c1b51eSKate Stone if (error.Fail()) {
329882abefa4SPavel Labath LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
3299f1812a28SMichał Górny m_current_process->GetID(), error);
3300e13c2731STamas Berghammer return SendErrorResponse(0x75);
3301e13c2731STamas Berghammer }
3302e13c2731STamas Berghammer
3303e13c2731STamas Berghammer // Allocate a new save id.
3304e13c2731STamas Berghammer const uint32_t save_id = GetNextSavedRegistersID();
3305b9c1b51eSKate Stone assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
3306b9c1b51eSKate Stone "GetNextRegisterSaveID() returned an existing register save id");
3307e13c2731STamas Berghammer
3308e13c2731STamas Berghammer // Save the register data buffer under the save id.
3309e13c2731STamas Berghammer {
331016ff8604SSaleem Abdulrasool std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3311e13c2731STamas Berghammer m_saved_registers_map[save_id] = register_data_sp;
3312e13c2731STamas Berghammer }
3313e13c2731STamas Berghammer
3314e13c2731STamas Berghammer // Write the response.
3315e13c2731STamas Berghammer StreamGDBRemote response;
3316e13c2731STamas Berghammer response.Printf("%" PRIu32, save_id);
331726709df8SZachary Turner return SendPacketNoLock(response.GetString());
3318e13c2731STamas Berghammer }
3319e13c2731STamas Berghammer
3320e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_QRestoreRegisterState(StringExtractorGDBRemote & packet)3321b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
3322b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
3323a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Thread);
3324e13c2731STamas Berghammer
3325e13c2731STamas Berghammer // Parse out save id.
3326e13c2731STamas Berghammer packet.SetFilePos(strlen("QRestoreRegisterState:"));
3327e13c2731STamas Berghammer if (packet.GetBytesLeft() < 1)
3328b9c1b51eSKate Stone return SendIllFormedResponse(
3329b9c1b51eSKate Stone packet, "QRestoreRegisterState packet missing register save id");
3330e13c2731STamas Berghammer
3331e13c2731STamas Berghammer const uint32_t save_id = packet.GetU32(0);
3332b9c1b51eSKate Stone if (save_id == 0) {
333382abefa4SPavel Labath LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
333482abefa4SPavel Labath "expecting decimal uint32_t");
3335e13c2731STamas Berghammer return SendErrorResponse(0x76);
3336e13c2731STamas Berghammer }
3337e13c2731STamas Berghammer
3338e13c2731STamas Berghammer // Get the thread to use.
3339a5be48b3SPavel Labath NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
3340a5be48b3SPavel Labath if (!thread) {
3341e13c2731STamas Berghammer if (m_thread_suffix_supported)
3342b9c1b51eSKate Stone return SendIllFormedResponse(
3343b9c1b51eSKate Stone packet, "No thread specified in QRestoreRegisterState packet");
3344e13c2731STamas Berghammer else
3345b9c1b51eSKate Stone return SendIllFormedResponse(packet,
3346b9c1b51eSKate Stone "No thread was is set with the Hg packet");
3347e13c2731STamas Berghammer }
3348e13c2731STamas Berghammer
3349e13c2731STamas Berghammer // Grab the register context for the thread.
3350d37349f3SPavel Labath NativeRegisterContext ®_context = thread->GetRegisterContext();
3351e13c2731STamas Berghammer
3352e13c2731STamas Berghammer // Retrieve register state buffer, then remove from the list.
3353e13c2731STamas Berghammer DataBufferSP register_data_sp;
3354e13c2731STamas Berghammer {
335516ff8604SSaleem Abdulrasool std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
3356e13c2731STamas Berghammer
3357e13c2731STamas Berghammer // Find the register set buffer for the given save id.
3358e13c2731STamas Berghammer auto it = m_saved_registers_map.find(save_id);
3359b9c1b51eSKate Stone if (it == m_saved_registers_map.end()) {
336082abefa4SPavel Labath LLDB_LOG(log,
336182abefa4SPavel Labath "pid {0} does not have a register set save buffer for id {1}",
3362f1812a28SMichał Górny m_current_process->GetID(), save_id);
3363e13c2731STamas Berghammer return SendErrorResponse(0x77);
3364e13c2731STamas Berghammer }
3365e13c2731STamas Berghammer register_data_sp = it->second;
3366e13c2731STamas Berghammer
3367e13c2731STamas Berghammer // Remove it from the map.
3368e13c2731STamas Berghammer m_saved_registers_map.erase(it);
3369e13c2731STamas Berghammer }
3370e13c2731STamas Berghammer
3371d37349f3SPavel Labath Status error = reg_context.WriteAllRegisterValues(register_data_sp);
3372b9c1b51eSKate Stone if (error.Fail()) {
337382abefa4SPavel Labath LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
3374f1812a28SMichał Górny m_current_process->GetID(), error);
3375e13c2731STamas Berghammer return SendErrorResponse(0x77);
3376e13c2731STamas Berghammer }
3377e13c2731STamas Berghammer
3378e13c2731STamas Berghammer return SendOKResponse();
3379e13c2731STamas Berghammer }
3380e13c2731STamas Berghammer
3381e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_vAttach(StringExtractorGDBRemote & packet)3382b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_vAttach(
3383b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
3384a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
3385e13c2731STamas Berghammer
3386e13c2731STamas Berghammer // Consume the ';' after vAttach.
3387e13c2731STamas Berghammer packet.SetFilePos(strlen("vAttach"));
3388e13c2731STamas Berghammer if (!packet.GetBytesLeft() || packet.GetChar() != ';')
3389e13c2731STamas Berghammer return SendIllFormedResponse(packet, "vAttach missing expected ';'");
3390e13c2731STamas Berghammer
3391e13c2731STamas Berghammer // Grab the PID to which we will attach (assume hex encoding).
3392e13c2731STamas Berghammer lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3393e13c2731STamas Berghammer if (pid == LLDB_INVALID_PROCESS_ID)
3394b9c1b51eSKate Stone return SendIllFormedResponse(packet,
3395b9c1b51eSKate Stone "vAttach failed to parse the process id");
3396e13c2731STamas Berghammer
3397e13c2731STamas Berghammer // Attempt to attach.
339863e5fb76SJonas Devlieghere LLDB_LOGF(log,
339963e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
3400b9c1b51eSKate Stone "pid %" PRIu64,
3401b9c1b51eSKate Stone __FUNCTION__, pid);
3402e13c2731STamas Berghammer
340397206d57SZachary Turner Status error = AttachToProcess(pid);
3404e13c2731STamas Berghammer
3405b9c1b51eSKate Stone if (error.Fail()) {
340663e5fb76SJonas Devlieghere LLDB_LOGF(log,
340763e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed to attach to "
3408b9c1b51eSKate Stone "pid %" PRIu64 ": %s\n",
3409b9c1b51eSKate Stone __FUNCTION__, pid, error.AsCString());
3410a70512a9SPavel Labath return SendErrorResponse(error);
3411e13c2731STamas Berghammer }
3412e13c2731STamas Berghammer
3413e13c2731STamas Berghammer // Notify we attached by sending a stop packet.
3414f8c6de8dSMichał Górny assert(m_current_process);
3415f8c6de8dSMichał Górny return SendStopReasonForState(*m_current_process,
3416bc04d240SMichał Górny m_current_process->GetState(),
3417bc04d240SMichał Górny /*force_synchronous=*/false);
3418e13c2731STamas Berghammer }
3419e13c2731STamas Berghammer
3420e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_vAttachWait(StringExtractorGDBRemote & packet)34212bbf724fSAugusto Noronha GDBRemoteCommunicationServerLLGS::Handle_vAttachWait(
34222bbf724fSAugusto Noronha StringExtractorGDBRemote &packet) {
3423a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
34242bbf724fSAugusto Noronha
34252bbf724fSAugusto Noronha // Consume the ';' after the identifier.
34262bbf724fSAugusto Noronha packet.SetFilePos(strlen("vAttachWait"));
34272bbf724fSAugusto Noronha
34282bbf724fSAugusto Noronha if (!packet.GetBytesLeft() || packet.GetChar() != ';')
34292bbf724fSAugusto Noronha return SendIllFormedResponse(packet, "vAttachWait missing expected ';'");
34302bbf724fSAugusto Noronha
34312bbf724fSAugusto Noronha // Allocate the buffer for the process name from vAttachWait.
34322bbf724fSAugusto Noronha std::string process_name;
34332bbf724fSAugusto Noronha if (!packet.GetHexByteString(process_name))
34342bbf724fSAugusto Noronha return SendIllFormedResponse(packet,
34352bbf724fSAugusto Noronha "vAttachWait failed to parse process name");
34362bbf724fSAugusto Noronha
34372bbf724fSAugusto Noronha LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
34382bbf724fSAugusto Noronha
34392afaf072SAugusto Noronha Status error = AttachWaitProcess(process_name, false);
34402afaf072SAugusto Noronha if (error.Fail()) {
34412afaf072SAugusto Noronha LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
34422afaf072SAugusto Noronha error);
34432afaf072SAugusto Noronha return SendErrorResponse(error);
34442afaf072SAugusto Noronha }
34452afaf072SAugusto Noronha
34462afaf072SAugusto Noronha // Notify we attached by sending a stop packet.
3447f8c6de8dSMichał Górny assert(m_current_process);
3448f8c6de8dSMichał Górny return SendStopReasonForState(*m_current_process,
3449bc04d240SMichał Górny m_current_process->GetState(),
3450bc04d240SMichał Górny /*force_synchronous=*/false);
34512afaf072SAugusto Noronha }
34522afaf072SAugusto Noronha
34532afaf072SAugusto Noronha GDBRemoteCommunication::PacketResult
Handle_qVAttachOrWaitSupported(StringExtractorGDBRemote & packet)34542afaf072SAugusto Noronha GDBRemoteCommunicationServerLLGS::Handle_qVAttachOrWaitSupported(
34552afaf072SAugusto Noronha StringExtractorGDBRemote &packet) {
34562afaf072SAugusto Noronha return SendOKResponse();
34572afaf072SAugusto Noronha }
34582afaf072SAugusto Noronha
34592afaf072SAugusto Noronha GDBRemoteCommunication::PacketResult
Handle_vAttachOrWait(StringExtractorGDBRemote & packet)34602afaf072SAugusto Noronha GDBRemoteCommunicationServerLLGS::Handle_vAttachOrWait(
34612afaf072SAugusto Noronha StringExtractorGDBRemote &packet) {
3462a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
34632afaf072SAugusto Noronha
34642afaf072SAugusto Noronha // Consume the ';' after the identifier.
34652afaf072SAugusto Noronha packet.SetFilePos(strlen("vAttachOrWait"));
34662afaf072SAugusto Noronha
34672afaf072SAugusto Noronha if (!packet.GetBytesLeft() || packet.GetChar() != ';')
34682afaf072SAugusto Noronha return SendIllFormedResponse(packet, "vAttachOrWait missing expected ';'");
34692afaf072SAugusto Noronha
34702afaf072SAugusto Noronha // Allocate the buffer for the process name from vAttachWait.
34712afaf072SAugusto Noronha std::string process_name;
34722afaf072SAugusto Noronha if (!packet.GetHexByteString(process_name))
34732afaf072SAugusto Noronha return SendIllFormedResponse(packet,
34742afaf072SAugusto Noronha "vAttachOrWait failed to parse process name");
34752afaf072SAugusto Noronha
34762afaf072SAugusto Noronha LLDB_LOG(log, "attempting to attach to process named '{0}'", process_name);
34772afaf072SAugusto Noronha
34782afaf072SAugusto Noronha Status error = AttachWaitProcess(process_name, true);
34792bbf724fSAugusto Noronha if (error.Fail()) {
34802bbf724fSAugusto Noronha LLDB_LOG(log, "failed to attach to process named '{0}': {1}", process_name,
34812bbf724fSAugusto Noronha error);
34822bbf724fSAugusto Noronha return SendErrorResponse(error);
34832bbf724fSAugusto Noronha }
34842bbf724fSAugusto Noronha
34852bbf724fSAugusto Noronha // Notify we attached by sending a stop packet.
3486f8c6de8dSMichał Górny assert(m_current_process);
3487f8c6de8dSMichał Górny return SendStopReasonForState(*m_current_process,
3488bc04d240SMichał Górny m_current_process->GetState(),
3489bc04d240SMichał Górny /*force_synchronous=*/false);
34902bbf724fSAugusto Noronha }
34912bbf724fSAugusto Noronha
34922bbf724fSAugusto Noronha GDBRemoteCommunication::PacketResult
Handle_vRun(StringExtractorGDBRemote & packet)34936ba3f723SMichał Górny GDBRemoteCommunicationServerLLGS::Handle_vRun(
34946ba3f723SMichał Górny StringExtractorGDBRemote &packet) {
3495a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
34966ba3f723SMichał Górny
34976ba3f723SMichał Górny llvm::StringRef s = packet.GetStringRef();
34986ba3f723SMichał Górny if (!s.consume_front("vRun;"))
34996ba3f723SMichał Górny return SendErrorResponse(8);
35006ba3f723SMichał Górny
35016ba3f723SMichał Górny llvm::SmallVector<llvm::StringRef, 16> argv;
35026ba3f723SMichał Górny s.split(argv, ';');
35036ba3f723SMichał Górny
35046ba3f723SMichał Górny for (llvm::StringRef hex_arg : argv) {
35056ba3f723SMichał Górny StringExtractor arg_ext{hex_arg};
35066ba3f723SMichał Górny std::string arg;
35076ba3f723SMichał Górny arg_ext.GetHexByteString(arg);
35086ba3f723SMichał Górny m_process_launch_info.GetArguments().AppendArgument(arg);
35096ba3f723SMichał Górny LLDB_LOGF(log, "LLGSPacketHandler::%s added arg: \"%s\"", __FUNCTION__,
35106ba3f723SMichał Górny arg.c_str());
35116ba3f723SMichał Górny }
35126ba3f723SMichał Górny
35136ba3f723SMichał Górny if (!argv.empty()) {
35146ba3f723SMichał Górny m_process_launch_info.GetExecutableFile().SetFile(
35156ba3f723SMichał Górny m_process_launch_info.GetArguments()[0].ref(), FileSpec::Style::native);
35166ba3f723SMichał Górny m_process_launch_error = LaunchProcess();
3517f8c6de8dSMichał Górny if (m_process_launch_error.Success()) {
3518f8c6de8dSMichał Górny assert(m_current_process);
3519f8c6de8dSMichał Górny return SendStopReasonForState(*m_current_process,
3520bc04d240SMichał Górny m_current_process->GetState(),
3521bc04d240SMichał Górny /*force_synchronous=*/true);
3522f8c6de8dSMichał Górny }
35236ba3f723SMichał Górny LLDB_LOG(log, "failed to launch exe: {0}", m_process_launch_error);
35246ba3f723SMichał Górny }
35256ba3f723SMichał Górny return SendErrorResponse(8);
35266ba3f723SMichał Górny }
35276ba3f723SMichał Górny
35286ba3f723SMichał Górny GDBRemoteCommunication::PacketResult
Handle_D(StringExtractorGDBRemote & packet)3529b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
353013eb5b34SMichał Górny Log *log = GetLog(LLDBLog::Process);
353109531edeSMichał Górny if (!m_non_stop)
3532c7749c3aSPavel Labath StopSTDIOForwarding();
3533c7749c3aSPavel Labath
3534e13c2731STamas Berghammer lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
3535e13c2731STamas Berghammer
3536e13c2731STamas Berghammer // Consume the ';' after D.
3537e13c2731STamas Berghammer packet.SetFilePos(1);
3538b9c1b51eSKate Stone if (packet.GetBytesLeft()) {
3539e13c2731STamas Berghammer if (packet.GetChar() != ';')
3540e13c2731STamas Berghammer return SendIllFormedResponse(packet, "D missing expected ';'");
3541e13c2731STamas Berghammer
3542e13c2731STamas Berghammer // Grab the PID from which we will detach (assume hex encoding).
3543e13c2731STamas Berghammer pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
3544e13c2731STamas Berghammer if (pid == LLDB_INVALID_PROCESS_ID)
3545e13c2731STamas Berghammer return SendIllFormedResponse(packet, "D failed to parse the process id");
3546e13c2731STamas Berghammer }
3547e13c2731STamas Berghammer
3548bbae0c1fSMichał Górny // Detach forked children if their PID was specified *or* no PID was requested
3549bbae0c1fSMichał Górny // (i.e. detach-all packet).
3550bbae0c1fSMichał Górny llvm::Error detach_error = llvm::Error::success();
3551bbae0c1fSMichał Górny bool detached = false;
3552bbae0c1fSMichał Górny for (auto it = m_debugged_processes.begin();
3553bbae0c1fSMichał Górny it != m_debugged_processes.end();) {
3554bbae0c1fSMichał Górny if (pid == LLDB_INVALID_PROCESS_ID || pid == it->first) {
355513eb5b34SMichał Górny LLDB_LOGF(log,
355613eb5b34SMichał Górny "GDBRemoteCommunicationServerLLGS::%s detaching %" PRId64,
355713eb5b34SMichał Górny __FUNCTION__, it->first);
3558355c7916SMichał Górny if (llvm::Error e = it->second.process_up->Detach().ToError())
3559bbae0c1fSMichał Górny detach_error = llvm::joinErrors(std::move(detach_error), std::move(e));
3560bbae0c1fSMichał Górny else {
3561355c7916SMichał Górny if (it->second.process_up.get() == m_current_process)
3562bbae0c1fSMichał Górny m_current_process = nullptr;
3563355c7916SMichał Górny if (it->second.process_up.get() == m_continue_process)
3564bbae0c1fSMichał Górny m_continue_process = nullptr;
3565bbae0c1fSMichał Górny it = m_debugged_processes.erase(it);
3566bbae0c1fSMichał Górny detached = true;
3567bbae0c1fSMichał Górny continue;
3568bbae0c1fSMichał Górny }
3569bbae0c1fSMichał Górny }
3570bbae0c1fSMichał Górny ++it;
3571e13c2731STamas Berghammer }
3572e13c2731STamas Berghammer
3573bbae0c1fSMichał Górny if (detach_error)
3574bbae0c1fSMichał Górny return SendErrorResponse(std::move(detach_error));
3575bbae0c1fSMichał Górny if (!detached)
3576bbae0c1fSMichał Górny return SendErrorResponse(Status("PID %" PRIu64 " not traced", pid));
3577e13c2731STamas Berghammer return SendOKResponse();
3578e13c2731STamas Berghammer }
3579e13c2731STamas Berghammer
3580e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_qThreadStopInfo(StringExtractorGDBRemote & packet)3581b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
3582b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
3583a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Thread);
3584e13c2731STamas Berghammer
3585af93f123SMichał Górny if (!m_current_process ||
3586af93f123SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
3587af93f123SMichał Górny return SendErrorResponse(50);
3588af93f123SMichał Górny
3589e13c2731STamas Berghammer packet.SetFilePos(strlen("qThreadStopInfo"));
359064bb9cf7SMichał Górny const lldb::tid_t tid = packet.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID);
3591b9c1b51eSKate Stone if (tid == LLDB_INVALID_THREAD_ID) {
359263e5fb76SJonas Devlieghere LLDB_LOGF(log,
359363e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s failed, could not "
3594b9c1b51eSKate Stone "parse thread id from request \"%s\"",
3595d35b42f2SJonas Devlieghere __FUNCTION__, packet.GetStringRef().data());
3596e13c2731STamas Berghammer return SendErrorResponse(0x15);
3597e13c2731STamas Berghammer }
3598bc04d240SMichał Górny return SendStopReplyPacketForThread(*m_current_process, tid,
3599bc04d240SMichał Górny /*force_synchronous=*/true);
3600e13c2731STamas Berghammer }
3601e13c2731STamas Berghammer
3602e13c2731STamas Berghammer GDBRemoteCommunication::PacketResult
Handle_jThreadsInfo(StringExtractorGDBRemote &)3603b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
3604b9c1b51eSKate Stone StringExtractorGDBRemote &) {
3605a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process | LLDBLog::Thread);
36064a4bb12eSPavel Labath
36074a4bb12eSPavel Labath // Ensure we have a debugged process.
3608f1812a28SMichał Górny if (!m_current_process ||
3609f1812a28SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
36104a4bb12eSPavel Labath return SendErrorResponse(50);
3611f1812a28SMichał Górny LLDB_LOG(log, "preparing packet for pid {0}", m_current_process->GetID());
36124a4bb12eSPavel Labath
36134a4bb12eSPavel Labath StreamString response;
361405569f67SPavel Labath const bool threads_with_valid_stop_info_only = false;
3615f1812a28SMichał Górny llvm::Expected<json::Value> threads_info =
3616f1812a28SMichał Górny GetJSONThreadsInfo(*m_current_process, threads_with_valid_stop_info_only);
36179beb4567SJonas Devlieghere if (!threads_info) {
3618926d2838SMartin Storsjö LLDB_LOG_ERROR(log, threads_info.takeError(),
3619926d2838SMartin Storsjö "failed to prepare a packet for pid {1}: {0}",
3620f1812a28SMichał Górny m_current_process->GetID());
362105569f67SPavel Labath return SendErrorResponse(52);
362205569f67SPavel Labath }
362305569f67SPavel Labath
36249beb4567SJonas Devlieghere response.AsRawOstream() << *threads_info;
36254a4bb12eSPavel Labath StreamGDBRemote escaped_response;
36264a4bb12eSPavel Labath escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
362726709df8SZachary Turner return SendPacketNoLock(escaped_response.GetString());
36284a4bb12eSPavel Labath }
36294a4bb12eSPavel Labath
36304a4bb12eSPavel Labath GDBRemoteCommunication::PacketResult
Handle_qWatchpointSupportInfo(StringExtractorGDBRemote & packet)3631b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
3632b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
3633e13c2731STamas Berghammer // Fail if we don't have a current process.
3634f1812a28SMichał Górny if (!m_current_process ||
3635f1812a28SMichał Górny m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3636e13c2731STamas Berghammer return SendErrorResponse(68);
3637e13c2731STamas Berghammer
3638e13c2731STamas Berghammer packet.SetFilePos(strlen("qWatchpointSupportInfo"));
3639e13c2731STamas Berghammer if (packet.GetBytesLeft() == 0)
3640e13c2731STamas Berghammer return SendOKResponse();
3641e13c2731STamas Berghammer if (packet.GetChar() != ':')
3642e13c2731STamas Berghammer return SendErrorResponse(67);
3643e13c2731STamas Berghammer
3644f1812a28SMichał Górny auto hw_debug_cap = m_current_process->GetHardwareDebugSupportInfo();
3645d5ffbad2SOmair Javaid
3646e13c2731STamas Berghammer StreamGDBRemote response;
3647d5ffbad2SOmair Javaid if (hw_debug_cap == llvm::None)
3648d5ffbad2SOmair Javaid response.Printf("num:0;");
3649d5ffbad2SOmair Javaid else
3650d5ffbad2SOmair Javaid response.Printf("num:%d;", hw_debug_cap->second);
3651d5ffbad2SOmair Javaid
365226709df8SZachary Turner return SendPacketNoLock(response.GetString());
3653e13c2731STamas Berghammer }
3654e13c2731STamas Berghammer
3655783bfc8cSTamas Berghammer GDBRemoteCommunication::PacketResult
Handle_qFileLoadAddress(StringExtractorGDBRemote & packet)3656b9c1b51eSKate Stone GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
3657b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
3658783bfc8cSTamas Berghammer // Fail if we don't have a current process.
3659f1812a28SMichał Górny if (!m_current_process ||
3660f1812a28SMichał Górny m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
3661783bfc8cSTamas Berghammer return SendErrorResponse(67);
3662783bfc8cSTamas Berghammer
3663783bfc8cSTamas Berghammer packet.SetFilePos(strlen("qFileLoadAddress:"));
3664783bfc8cSTamas Berghammer if (packet.GetBytesLeft() == 0)
3665783bfc8cSTamas Berghammer return SendErrorResponse(68);
3666783bfc8cSTamas Berghammer
3667783bfc8cSTamas Berghammer std::string file_name;
3668783bfc8cSTamas Berghammer packet.GetHexByteString(file_name);
3669783bfc8cSTamas Berghammer
3670783bfc8cSTamas Berghammer lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
367197206d57SZachary Turner Status error =
3672f1812a28SMichał Górny m_current_process->GetFileLoadAddress(file_name, file_load_address);
3673783bfc8cSTamas Berghammer if (error.Fail())
3674783bfc8cSTamas Berghammer return SendErrorResponse(69);
3675783bfc8cSTamas Berghammer
3676783bfc8cSTamas Berghammer if (file_load_address == LLDB_INVALID_ADDRESS)
3677783bfc8cSTamas Berghammer return SendErrorResponse(1); // File not loaded
3678783bfc8cSTamas Berghammer
3679783bfc8cSTamas Berghammer StreamGDBRemote response;
3680783bfc8cSTamas Berghammer response.PutHex64(file_load_address);
368126709df8SZachary Turner return SendPacketNoLock(response.GetString());
3682783bfc8cSTamas Berghammer }
3683783bfc8cSTamas Berghammer
36844a705e7eSPavel Labath GDBRemoteCommunication::PacketResult
Handle_QPassSignals(StringExtractorGDBRemote & packet)36854a705e7eSPavel Labath GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
36864a705e7eSPavel Labath StringExtractorGDBRemote &packet) {
36874a705e7eSPavel Labath std::vector<int> signals;
36884a705e7eSPavel Labath packet.SetFilePos(strlen("QPassSignals:"));
36894a705e7eSPavel Labath
369005097246SAdrian Prantl // Read sequence of hex signal numbers divided by a semicolon and optionally
369105097246SAdrian Prantl // spaces.
36924a705e7eSPavel Labath while (packet.GetBytesLeft() > 0) {
36934a705e7eSPavel Labath int signal = packet.GetS32(-1, 16);
36944a705e7eSPavel Labath if (signal < 0)
36954a705e7eSPavel Labath return SendIllFormedResponse(packet, "Failed to parse signal number.");
36964a705e7eSPavel Labath signals.push_back(signal);
36974a705e7eSPavel Labath
36984a705e7eSPavel Labath packet.SkipSpaces();
36994a705e7eSPavel Labath char separator = packet.GetChar();
37004a705e7eSPavel Labath if (separator == '\0')
37014a705e7eSPavel Labath break; // End of string
37024a705e7eSPavel Labath if (separator != ';')
37034a705e7eSPavel Labath return SendIllFormedResponse(packet, "Invalid separator,"
37044a705e7eSPavel Labath " expected semicolon.");
37054a705e7eSPavel Labath }
37064a705e7eSPavel Labath
37074a705e7eSPavel Labath // Fail if we don't have a current process.
3708f1812a28SMichał Górny if (!m_current_process)
37094a705e7eSPavel Labath return SendErrorResponse(68);
37104a705e7eSPavel Labath
3711f1812a28SMichał Górny Status error = m_current_process->IgnoreSignals(signals);
37124a705e7eSPavel Labath if (error.Fail())
37134a705e7eSPavel Labath return SendErrorResponse(69);
37144a705e7eSPavel Labath
37154a705e7eSPavel Labath return SendOKResponse();
37164a705e7eSPavel Labath }
37174a705e7eSPavel Labath
3718da2e614fSDavid Spickett GDBRemoteCommunication::PacketResult
Handle_qMemTags(StringExtractorGDBRemote & packet)3719da2e614fSDavid Spickett GDBRemoteCommunicationServerLLGS::Handle_qMemTags(
3720da2e614fSDavid Spickett StringExtractorGDBRemote &packet) {
3721a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
3722da2e614fSDavid Spickett
3723da2e614fSDavid Spickett // Ensure we have a process.
3724da2e614fSDavid Spickett if (!m_current_process ||
3725da2e614fSDavid Spickett (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
3726da2e614fSDavid Spickett LLDB_LOGF(
3727da2e614fSDavid Spickett log,
3728da2e614fSDavid Spickett "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
3729da2e614fSDavid Spickett __FUNCTION__);
3730da2e614fSDavid Spickett return SendErrorResponse(1);
3731da2e614fSDavid Spickett }
3732da2e614fSDavid Spickett
3733da2e614fSDavid Spickett // We are expecting
3734da2e614fSDavid Spickett // qMemTags:<hex address>,<hex length>:<hex type>
3735da2e614fSDavid Spickett
3736da2e614fSDavid Spickett // Address
3737da2e614fSDavid Spickett packet.SetFilePos(strlen("qMemTags:"));
3738da2e614fSDavid Spickett const char *current_char = packet.Peek();
3739da2e614fSDavid Spickett if (!current_char || *current_char == ',')
3740da2e614fSDavid Spickett return SendIllFormedResponse(packet, "Missing address in qMemTags packet");
3741da2e614fSDavid Spickett const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3742da2e614fSDavid Spickett
3743da2e614fSDavid Spickett // Length
3744da2e614fSDavid Spickett char previous_char = packet.GetChar();
3745da2e614fSDavid Spickett current_char = packet.Peek();
3746da2e614fSDavid Spickett // If we don't have a separator or the length field is empty
3747da2e614fSDavid Spickett if (previous_char != ',' || (current_char && *current_char == ':'))
3748da2e614fSDavid Spickett return SendIllFormedResponse(packet,
3749da2e614fSDavid Spickett "Invalid addr,length pair in qMemTags packet");
3750da2e614fSDavid Spickett
3751da2e614fSDavid Spickett if (packet.GetBytesLeft() < 1)
3752da2e614fSDavid Spickett return SendIllFormedResponse(
3753da2e614fSDavid Spickett packet, "Too short qMemtags: packet (looking for length)");
3754da2e614fSDavid Spickett const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
3755da2e614fSDavid Spickett
3756da2e614fSDavid Spickett // Type
3757da2e614fSDavid Spickett const char *invalid_type_err = "Invalid type field in qMemTags: packet";
3758da2e614fSDavid Spickett if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
3759da2e614fSDavid Spickett return SendIllFormedResponse(packet, invalid_type_err);
3760da2e614fSDavid Spickett
3761555cd031SDavid Spickett // Type is a signed integer but packed into the packet as its raw bytes.
3762555cd031SDavid Spickett // However, our GetU64 uses strtoull which allows +/-. We do not want this.
3763555cd031SDavid Spickett const char *first_type_char = packet.Peek();
3764555cd031SDavid Spickett if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
3765555cd031SDavid Spickett return SendIllFormedResponse(packet, invalid_type_err);
3766555cd031SDavid Spickett
3767555cd031SDavid Spickett // Extract type as unsigned then cast to signed.
3768555cd031SDavid Spickett // Using a uint64_t here so that we have some value outside of the 32 bit
3769555cd031SDavid Spickett // range to use as the invalid return value.
3770555cd031SDavid Spickett uint64_t raw_type =
3771555cd031SDavid Spickett packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
3772555cd031SDavid Spickett
3773555cd031SDavid Spickett if ( // Make sure the cast below would be valid
3774555cd031SDavid Spickett raw_type > std::numeric_limits<uint32_t>::max() ||
3775da2e614fSDavid Spickett // To catch inputs like "123aardvark" that will parse but clearly aren't
3776da2e614fSDavid Spickett // valid in this case.
3777da2e614fSDavid Spickett packet.GetBytesLeft()) {
3778da2e614fSDavid Spickett return SendIllFormedResponse(packet, invalid_type_err);
3779da2e614fSDavid Spickett }
3780da2e614fSDavid Spickett
3781555cd031SDavid Spickett // First narrow to 32 bits otherwise the copy into type would take
3782555cd031SDavid Spickett // the wrong 4 bytes on big endian.
3783555cd031SDavid Spickett uint32_t raw_type_32 = raw_type;
3784555cd031SDavid Spickett int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
3785555cd031SDavid Spickett
3786da2e614fSDavid Spickett StreamGDBRemote response;
3787da2e614fSDavid Spickett std::vector<uint8_t> tags;
3788da2e614fSDavid Spickett Status error = m_current_process->ReadMemoryTags(type, addr, length, tags);
3789da2e614fSDavid Spickett if (error.Fail())
3790da2e614fSDavid Spickett return SendErrorResponse(1);
3791da2e614fSDavid Spickett
3792da2e614fSDavid Spickett // This m is here in case we want to support multi part replies in the future.
3793da2e614fSDavid Spickett // In the same manner as qfThreadInfo/qsThreadInfo.
3794da2e614fSDavid Spickett response.PutChar('m');
3795da2e614fSDavid Spickett response.PutBytesAsRawHex8(tags.data(), tags.size());
3796da2e614fSDavid Spickett return SendPacketNoLock(response.GetString());
3797da2e614fSDavid Spickett }
3798da2e614fSDavid Spickett
37997d27230dSDavid Spickett GDBRemoteCommunication::PacketResult
Handle_QMemTags(StringExtractorGDBRemote & packet)38007d27230dSDavid Spickett GDBRemoteCommunicationServerLLGS::Handle_QMemTags(
38017d27230dSDavid Spickett StringExtractorGDBRemote &packet) {
3802a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
38037d27230dSDavid Spickett
38047d27230dSDavid Spickett // Ensure we have a process.
38057d27230dSDavid Spickett if (!m_current_process ||
38067d27230dSDavid Spickett (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)) {
38077d27230dSDavid Spickett LLDB_LOGF(
38087d27230dSDavid Spickett log,
38097d27230dSDavid Spickett "GDBRemoteCommunicationServerLLGS::%s failed, no process available",
38107d27230dSDavid Spickett __FUNCTION__);
38117d27230dSDavid Spickett return SendErrorResponse(1);
38127d27230dSDavid Spickett }
38137d27230dSDavid Spickett
38147d27230dSDavid Spickett // We are expecting
38157d27230dSDavid Spickett // QMemTags:<hex address>,<hex length>:<hex type>:<tags as hex bytes>
38167d27230dSDavid Spickett
38177d27230dSDavid Spickett // Address
38187d27230dSDavid Spickett packet.SetFilePos(strlen("QMemTags:"));
38197d27230dSDavid Spickett const char *current_char = packet.Peek();
38207d27230dSDavid Spickett if (!current_char || *current_char == ',')
38217d27230dSDavid Spickett return SendIllFormedResponse(packet, "Missing address in QMemTags packet");
38227d27230dSDavid Spickett const lldb::addr_t addr = packet.GetHexMaxU64(/*little_endian=*/false, 0);
38237d27230dSDavid Spickett
38247d27230dSDavid Spickett // Length
38257d27230dSDavid Spickett char previous_char = packet.GetChar();
38267d27230dSDavid Spickett current_char = packet.Peek();
38277d27230dSDavid Spickett // If we don't have a separator or the length field is empty
38287d27230dSDavid Spickett if (previous_char != ',' || (current_char && *current_char == ':'))
38297d27230dSDavid Spickett return SendIllFormedResponse(packet,
38307d27230dSDavid Spickett "Invalid addr,length pair in QMemTags packet");
38317d27230dSDavid Spickett
38327d27230dSDavid Spickett if (packet.GetBytesLeft() < 1)
38337d27230dSDavid Spickett return SendIllFormedResponse(
38347d27230dSDavid Spickett packet, "Too short QMemtags: packet (looking for length)");
38357d27230dSDavid Spickett const size_t length = packet.GetHexMaxU64(/*little_endian=*/false, 0);
38367d27230dSDavid Spickett
38377d27230dSDavid Spickett // Type
38387d27230dSDavid Spickett const char *invalid_type_err = "Invalid type field in QMemTags: packet";
38397d27230dSDavid Spickett if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
38407d27230dSDavid Spickett return SendIllFormedResponse(packet, invalid_type_err);
38417d27230dSDavid Spickett
38427d27230dSDavid Spickett // Our GetU64 uses strtoull which allows leading +/-, we don't want that.
38437d27230dSDavid Spickett const char *first_type_char = packet.Peek();
38447d27230dSDavid Spickett if (first_type_char && (*first_type_char == '+' || *first_type_char == '-'))
38457d27230dSDavid Spickett return SendIllFormedResponse(packet, invalid_type_err);
38467d27230dSDavid Spickett
38477d27230dSDavid Spickett // The type is a signed integer but is in the packet as its raw bytes.
38487d27230dSDavid Spickett // So parse first as unsigned then cast to signed later.
38497d27230dSDavid Spickett // We extract to 64 bit, even though we only expect 32, so that we've
38507d27230dSDavid Spickett // got some invalid value we can check for.
38517d27230dSDavid Spickett uint64_t raw_type =
38527d27230dSDavid Spickett packet.GetU64(std::numeric_limits<uint64_t>::max(), /*base=*/16);
38537d27230dSDavid Spickett if (raw_type > std::numeric_limits<uint32_t>::max())
38547d27230dSDavid Spickett return SendIllFormedResponse(packet, invalid_type_err);
3855555cd031SDavid Spickett
3856555cd031SDavid Spickett // First narrow to 32 bits. Otherwise the copy below would get the wrong
3857555cd031SDavid Spickett // 4 bytes on big endian.
3858555cd031SDavid Spickett uint32_t raw_type_32 = raw_type;
3859555cd031SDavid Spickett int32_t type = reinterpret_cast<int32_t &>(raw_type_32);
38607d27230dSDavid Spickett
38617d27230dSDavid Spickett // Tag data
38627d27230dSDavid Spickett if (packet.GetBytesLeft() < 1 || packet.GetChar() != ':')
38637d27230dSDavid Spickett return SendIllFormedResponse(packet,
38647d27230dSDavid Spickett "Missing tag data in QMemTags: packet");
38657d27230dSDavid Spickett
38667d27230dSDavid Spickett // Must be 2 chars per byte
38677d27230dSDavid Spickett const char *invalid_data_err = "Invalid tag data in QMemTags: packet";
38687d27230dSDavid Spickett if (packet.GetBytesLeft() % 2)
38697d27230dSDavid Spickett return SendIllFormedResponse(packet, invalid_data_err);
38707d27230dSDavid Spickett
38717d27230dSDavid Spickett // This is bytes here and is unpacked into target specific tags later
38727d27230dSDavid Spickett // We cannot assume that number of bytes == length here because the server
38737d27230dSDavid Spickett // can repeat tags to fill a given range.
38747d27230dSDavid Spickett std::vector<uint8_t> tag_data;
38757d27230dSDavid Spickett // Zero length writes will not have any tag data
38767d27230dSDavid Spickett // (but we pass them on because it will still check that tagging is enabled)
38777d27230dSDavid Spickett if (packet.GetBytesLeft()) {
38787d27230dSDavid Spickett size_t byte_count = packet.GetBytesLeft() / 2;
38797d27230dSDavid Spickett tag_data.resize(byte_count);
38807d27230dSDavid Spickett size_t converted_bytes = packet.GetHexBytes(tag_data, 0);
38817d27230dSDavid Spickett if (converted_bytes != byte_count) {
38827d27230dSDavid Spickett return SendIllFormedResponse(packet, invalid_data_err);
38837d27230dSDavid Spickett }
38847d27230dSDavid Spickett }
38857d27230dSDavid Spickett
38867d27230dSDavid Spickett Status status =
38877d27230dSDavid Spickett m_current_process->WriteMemoryTags(type, addr, length, tag_data);
38887d27230dSDavid Spickett return status.Success() ? SendOKResponse() : SendErrorResponse(1);
38897d27230dSDavid Spickett }
38907d27230dSDavid Spickett
389137cbd817SMichał Górny GDBRemoteCommunication::PacketResult
Handle_qSaveCore(StringExtractorGDBRemote & packet)389237cbd817SMichał Górny GDBRemoteCommunicationServerLLGS::Handle_qSaveCore(
389337cbd817SMichał Górny StringExtractorGDBRemote &packet) {
389437cbd817SMichał Górny // Fail if we don't have a current process.
389537cbd817SMichał Górny if (!m_current_process ||
389637cbd817SMichał Górny (m_current_process->GetID() == LLDB_INVALID_PROCESS_ID))
389737cbd817SMichał Górny return SendErrorResponse(Status("Process not running."));
389837cbd817SMichał Górny
389937cbd817SMichał Górny std::string path_hint;
390037cbd817SMichał Górny
390137cbd817SMichał Górny StringRef packet_str{packet.GetStringRef()};
3902ac312a9dSBenjamin Kramer assert(packet_str.startswith("qSaveCore"));
3903ac312a9dSBenjamin Kramer if (packet_str.consume_front("qSaveCore;")) {
390466e06cc8SMichał Górny for (auto x : llvm::split(packet_str, ';')) {
390537cbd817SMichał Górny if (x.consume_front("path-hint:"))
390637cbd817SMichał Górny StringExtractor(x).GetHexByteString(path_hint);
390737cbd817SMichał Górny else
390837cbd817SMichał Górny return SendErrorResponse(Status("Unsupported qSaveCore option"));
390937cbd817SMichał Górny }
391037cbd817SMichał Górny }
391137cbd817SMichał Górny
391237cbd817SMichał Górny llvm::Expected<std::string> ret = m_current_process->SaveCore(path_hint);
391337cbd817SMichał Górny if (!ret)
3914ac312a9dSBenjamin Kramer return SendErrorResponse(ret.takeError());
391537cbd817SMichał Górny
391637cbd817SMichał Górny StreamString response;
391737cbd817SMichał Górny response.PutCString("core-path:");
391837cbd817SMichał Górny response.PutStringAsRawHex8(ret.get());
391937cbd817SMichał Górny return SendPacketNoLock(response.GetString());
392037cbd817SMichał Górny }
392137cbd817SMichał Górny
3922bc04d240SMichał Górny GDBRemoteCommunication::PacketResult
Handle_QNonStop(StringExtractorGDBRemote & packet)3923bc04d240SMichał Górny GDBRemoteCommunicationServerLLGS::Handle_QNonStop(
3924bc04d240SMichał Górny StringExtractorGDBRemote &packet) {
3925c732afa2SMichał Górny Log *log = GetLog(LLDBLog::Process);
3926c732afa2SMichał Górny
3927bc04d240SMichał Górny StringRef packet_str{packet.GetStringRef()};
3928bc04d240SMichał Górny assert(packet_str.startswith("QNonStop:"));
3929bc04d240SMichał Górny packet_str.consume_front("QNonStop:");
3930bc04d240SMichał Górny if (packet_str == "0") {
393109531edeSMichał Górny if (m_non_stop)
393209531edeSMichał Górny StopSTDIOForwarding();
3933c732afa2SMichał Górny for (auto &process_it : m_debugged_processes) {
3934c732afa2SMichał Górny if (process_it.second.process_up->IsRunning()) {
3935c732afa2SMichał Górny assert(m_non_stop);
3936c732afa2SMichał Górny Status error = process_it.second.process_up->Interrupt();
3937c732afa2SMichał Górny if (error.Fail()) {
3938c732afa2SMichał Górny LLDB_LOG(log,
3939c732afa2SMichał Górny "while disabling nonstop, failed to halt process {0}: {1}",
3940c732afa2SMichał Górny process_it.first, error);
3941c732afa2SMichał Górny return SendErrorResponse(0x41);
3942c732afa2SMichał Górny }
3943c732afa2SMichał Górny // we must not send stop reasons after QNonStop
3944c732afa2SMichał Górny m_disabling_non_stop = true;
3945c732afa2SMichał Górny }
3946c732afa2SMichał Górny }
3947c732afa2SMichał Górny m_stdio_notification_queue.clear();
3948c732afa2SMichał Górny m_stop_notification_queue.clear();
3949bc04d240SMichał Górny m_non_stop = false;
3950c732afa2SMichał Górny // If we are stopping anything, defer sending the OK response until we're
3951c732afa2SMichał Górny // done.
3952c732afa2SMichał Górny if (m_disabling_non_stop)
3953c732afa2SMichał Górny return PacketResult::Success;
3954bc04d240SMichał Górny } else if (packet_str == "1") {
395509531edeSMichał Górny if (!m_non_stop)
395609531edeSMichał Górny StartSTDIOForwarding();
3957bc04d240SMichał Górny m_non_stop = true;
3958bc04d240SMichał Górny } else
3959bc04d240SMichał Górny return SendErrorResponse(Status("Invalid QNonStop packet"));
3960bc04d240SMichał Górny return SendOKResponse();
3961bc04d240SMichał Górny }
3962bc04d240SMichał Górny
3963bc04d240SMichał Górny GDBRemoteCommunication::PacketResult
HandleNotificationAck(std::deque<std::string> & queue)39641903f358SMichał Górny GDBRemoteCommunicationServerLLGS::HandleNotificationAck(
39651903f358SMichał Górny std::deque<std::string> &queue) {
39661903f358SMichał Górny // Per the protocol, the first message put into the queue is sent
39671903f358SMichał Górny // immediately. However, it remains the queue until the client ACKs it --
39681903f358SMichał Górny // then we pop it and send the next message. The process repeats until
39691903f358SMichał Górny // the last message in the queue is ACK-ed, in which case the packet sends
39701903f358SMichał Górny // an OK response.
39711903f358SMichał Górny if (queue.empty())
39721903f358SMichał Górny return SendErrorResponse(Status("No pending notification to ack"));
39731903f358SMichał Górny queue.pop_front();
39741903f358SMichał Górny if (!queue.empty())
39751903f358SMichał Górny return SendPacketNoLock(queue.front());
39761903f358SMichał Górny return SendOKResponse();
39771903f358SMichał Górny }
39781903f358SMichał Górny
39791903f358SMichał Górny GDBRemoteCommunication::PacketResult
Handle_vStdio(StringExtractorGDBRemote & packet)39801903f358SMichał Górny GDBRemoteCommunicationServerLLGS::Handle_vStdio(
39811903f358SMichał Górny StringExtractorGDBRemote &packet) {
39821903f358SMichał Górny return HandleNotificationAck(m_stdio_notification_queue);
39831903f358SMichał Górny }
39841903f358SMichał Górny
39851903f358SMichał Górny GDBRemoteCommunication::PacketResult
Handle_vStopped(StringExtractorGDBRemote & packet)3986bc04d240SMichał Górny GDBRemoteCommunicationServerLLGS::Handle_vStopped(
3987bc04d240SMichał Górny StringExtractorGDBRemote &packet) {
39881903f358SMichał Górny PacketResult ret = HandleNotificationAck(m_stop_notification_queue);
3989261d0033SMichał Górny // If this was the last notification and all the processes exited,
3990261d0033SMichał Górny // terminate the server.
39911903f358SMichał Górny if (m_stop_notification_queue.empty() && m_debugged_processes.empty()) {
3992bc04d240SMichał Górny m_exit_now = true;
3993bc04d240SMichał Górny m_mainloop.RequestTermination();
3994bc04d240SMichał Górny }
39951903f358SMichał Górny return ret;
3996bc04d240SMichał Górny }
3997bc04d240SMichał Górny
3998bc04d240SMichał Górny GDBRemoteCommunication::PacketResult
Handle_vCtrlC(StringExtractorGDBRemote & packet)3999bc04d240SMichał Górny GDBRemoteCommunicationServerLLGS::Handle_vCtrlC(
4000bc04d240SMichał Górny StringExtractorGDBRemote &packet) {
4001bc04d240SMichał Górny if (!m_non_stop)
4002bc04d240SMichał Górny return SendErrorResponse(Status("vCtrl is only valid in non-stop mode"));
4003bc04d240SMichał Górny
4004bc04d240SMichał Górny PacketResult interrupt_res = Handle_interrupt(packet);
4005bc04d240SMichał Górny // If interrupting the process failed, pass the result through.
4006bc04d240SMichał Górny if (interrupt_res != PacketResult::Success)
4007bc04d240SMichał Górny return interrupt_res;
4008bc04d240SMichał Górny // Otherwise, vCtrlC should issue an OK response (normal interrupts do not).
4009bc04d240SMichał Górny return SendOKResponse();
4010bc04d240SMichał Górny }
4011bc04d240SMichał Górny
4012e827e518SMichał Górny GDBRemoteCommunication::PacketResult
Handle_T(StringExtractorGDBRemote & packet)4013e827e518SMichał Górny GDBRemoteCommunicationServerLLGS::Handle_T(StringExtractorGDBRemote &packet) {
4014e827e518SMichał Górny packet.SetFilePos(strlen("T"));
4015e827e518SMichał Górny auto pid_tid = packet.GetPidTid(m_current_process ? m_current_process->GetID()
4016e827e518SMichał Górny : LLDB_INVALID_PROCESS_ID);
4017e827e518SMichał Górny if (!pid_tid)
4018e827e518SMichał Górny return SendErrorResponse(llvm::make_error<StringError>(
4019e827e518SMichał Górny inconvertibleErrorCode(), "Malformed thread-id"));
4020e827e518SMichał Górny
4021e827e518SMichał Górny lldb::pid_t pid = pid_tid->first;
4022e827e518SMichał Górny lldb::tid_t tid = pid_tid->second;
4023e827e518SMichał Górny
4024e827e518SMichał Górny // Technically, this would also be caught by the PID check but let's be more
4025e827e518SMichał Górny // explicit about the error.
4026e827e518SMichał Górny if (pid == LLDB_INVALID_PROCESS_ID)
4027e827e518SMichał Górny return SendErrorResponse(llvm::make_error<StringError>(
4028e827e518SMichał Górny inconvertibleErrorCode(), "No current process and no PID provided"));
4029e827e518SMichał Górny
4030e827e518SMichał Górny // Check the process ID and find respective process instance.
4031e827e518SMichał Górny auto new_process_it = m_debugged_processes.find(pid);
4032e827e518SMichał Górny if (new_process_it == m_debugged_processes.end())
4033e827e518SMichał Górny return SendErrorResponse(1);
4034e827e518SMichał Górny
4035e827e518SMichał Górny // Check the thread ID
4036355c7916SMichał Górny if (!new_process_it->second.process_up->GetThreadByID(tid))
4037e827e518SMichał Górny return SendErrorResponse(2);
4038e827e518SMichał Górny
4039e827e518SMichał Górny return SendOKResponse();
4040e827e518SMichał Górny }
4041e827e518SMichał Górny
MaybeCloseInferiorTerminalConnection()4042b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
4043a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
4044e13c2731STamas Berghammer
4045e13c2731STamas Berghammer // Tell the stdio connection to shut down.
4046b9c1b51eSKate Stone if (m_stdio_communication.IsConnected()) {
4047e13c2731STamas Berghammer auto connection = m_stdio_communication.GetConnection();
4048b9c1b51eSKate Stone if (connection) {
404997206d57SZachary Turner Status error;
4050e13c2731STamas Berghammer connection->Disconnect(&error);
4051e13c2731STamas Berghammer
4052b9c1b51eSKate Stone if (error.Success()) {
405363e5fb76SJonas Devlieghere LLDB_LOGF(log,
405463e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4055b9c1b51eSKate Stone "terminal stdio - SUCCESS",
4056b9c1b51eSKate Stone __FUNCTION__);
4057b9c1b51eSKate Stone } else {
405863e5fb76SJonas Devlieghere LLDB_LOGF(log,
405963e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s disconnect process "
4060b9c1b51eSKate Stone "terminal stdio - FAIL: %s",
4061b9c1b51eSKate Stone __FUNCTION__, error.AsCString());
4062e13c2731STamas Berghammer }
4063e13c2731STamas Berghammer }
4064e13c2731STamas Berghammer }
4065e13c2731STamas Berghammer }
4066e13c2731STamas Berghammer
GetThreadFromSuffix(StringExtractorGDBRemote & packet)4067a5be48b3SPavel Labath NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
4068b9c1b51eSKate Stone StringExtractorGDBRemote &packet) {
4069e13c2731STamas Berghammer // We have no thread if we don't have a process.
4070f1812a28SMichał Górny if (!m_current_process ||
4071f1812a28SMichał Górny m_current_process->GetID() == LLDB_INVALID_PROCESS_ID)
4072a5be48b3SPavel Labath return nullptr;
4073e13c2731STamas Berghammer
4074b9c1b51eSKate Stone // If the client hasn't asked for thread suffix support, there will not be a
407505097246SAdrian Prantl // thread suffix. Use the current thread in that case.
4076b9c1b51eSKate Stone if (!m_thread_suffix_supported) {
4077e13c2731STamas Berghammer const lldb::tid_t current_tid = GetCurrentThreadID();
4078e13c2731STamas Berghammer if (current_tid == LLDB_INVALID_THREAD_ID)
4079a5be48b3SPavel Labath return nullptr;
4080b9c1b51eSKate Stone else if (current_tid == 0) {
4081e13c2731STamas Berghammer // Pick a thread.
4082f1812a28SMichał Górny return m_current_process->GetThreadAtIndex(0);
4083b9c1b51eSKate Stone } else
4084f1812a28SMichał Górny return m_current_process->GetThreadByID(current_tid);
4085e13c2731STamas Berghammer }
4086e13c2731STamas Berghammer
4087a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Thread);
4088e13c2731STamas Berghammer
4089e13c2731STamas Berghammer // Parse out the ';'.
4090b9c1b51eSKate Stone if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
409163e5fb76SJonas Devlieghere LLDB_LOGF(log,
409263e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4093b9c1b51eSKate Stone "error: expected ';' prior to start of thread suffix: packet "
4094b9c1b51eSKate Stone "contents = '%s'",
4095d35b42f2SJonas Devlieghere __FUNCTION__, packet.GetStringRef().data());
4096a5be48b3SPavel Labath return nullptr;
4097e13c2731STamas Berghammer }
4098e13c2731STamas Berghammer
4099e13c2731STamas Berghammer if (!packet.GetBytesLeft())
4100a5be48b3SPavel Labath return nullptr;
4101e13c2731STamas Berghammer
4102e13c2731STamas Berghammer // Parse out thread: portion.
4103b9c1b51eSKate Stone if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
410463e5fb76SJonas Devlieghere LLDB_LOGF(log,
410563e5fb76SJonas Devlieghere "GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
4106b9c1b51eSKate Stone "error: expected 'thread:' but not found, packet contents = "
4107b9c1b51eSKate Stone "'%s'",
4108d35b42f2SJonas Devlieghere __FUNCTION__, packet.GetStringRef().data());
4109a5be48b3SPavel Labath return nullptr;
4110e13c2731STamas Berghammer }
4111e13c2731STamas Berghammer packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
4112e13c2731STamas Berghammer const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
4113e13c2731STamas Berghammer if (tid != 0)
4114f1812a28SMichał Górny return m_current_process->GetThreadByID(tid);
4115e13c2731STamas Berghammer
4116a5be48b3SPavel Labath return nullptr;
4117e13c2731STamas Berghammer }
4118e13c2731STamas Berghammer
GetCurrentThreadID() const4119b9c1b51eSKate Stone lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
4120b9c1b51eSKate Stone if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
412105097246SAdrian Prantl // Use whatever the debug process says is the current thread id since the
412205097246SAdrian Prantl // protocol either didn't specify or specified we want any/all threads
412305097246SAdrian Prantl // marked as the current thread.
4124f1812a28SMichał Górny if (!m_current_process)
4125e13c2731STamas Berghammer return LLDB_INVALID_THREAD_ID;
4126f1812a28SMichał Górny return m_current_process->GetCurrentThreadID();
4127e13c2731STamas Berghammer }
4128e13c2731STamas Berghammer // Use the specific current thread id set by the gdb remote protocol.
4129e13c2731STamas Berghammer return m_current_tid;
4130e13c2731STamas Berghammer }
4131e13c2731STamas Berghammer
GetNextSavedRegistersID()4132b9c1b51eSKate Stone uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
413316ff8604SSaleem Abdulrasool std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
4134e13c2731STamas Berghammer return m_next_saved_registers_id++;
4135e13c2731STamas Berghammer }
4136e13c2731STamas Berghammer
ClearProcessSpecificData()4137b9c1b51eSKate Stone void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
4138a007a6d8SPavel Labath Log *log = GetLog(LLDBLog::Process);
4139e13c2731STamas Berghammer
414057e2da4fSAntonio Afonso LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
414157e2da4fSAntonio Afonso m_xfer_buffer_map.clear();
4142e13c2731STamas Berghammer }
41437cb18bf5STamas Berghammer
41447cb18bf5STamas Berghammer FileSpec
FindModuleFile(const std::string & module_path,const ArchSpec & arch)41457cb18bf5STamas Berghammer GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
4146b9c1b51eSKate Stone const ArchSpec &arch) {
4147f1812a28SMichał Górny if (m_current_process) {
41487cb18bf5STamas Berghammer FileSpec file_spec;
4149f1812a28SMichał Górny if (m_current_process
4150b9c1b51eSKate Stone ->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
4151b9c1b51eSKate Stone .Success()) {
4152dbd7fabaSJonas Devlieghere if (FileSystem::Instance().Exists(file_spec))
41537cb18bf5STamas Berghammer return file_spec;
41547cb18bf5STamas Berghammer }
41557cb18bf5STamas Berghammer }
41567cb18bf5STamas Berghammer
41577cb18bf5STamas Berghammer return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
41587cb18bf5STamas Berghammer }
415905e32badSAntonio Afonso
XMLEncodeAttributeValue(llvm::StringRef value)416005e32badSAntonio Afonso std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue(
416105e32badSAntonio Afonso llvm::StringRef value) {
416205e32badSAntonio Afonso std::string result;
416305e32badSAntonio Afonso for (const char &c : value) {
416405e32badSAntonio Afonso switch (c) {
416505e32badSAntonio Afonso case '\'':
416605e32badSAntonio Afonso result += "'";
416705e32badSAntonio Afonso break;
416805e32badSAntonio Afonso case '"':
416905e32badSAntonio Afonso result += """;
417005e32badSAntonio Afonso break;
417105e32badSAntonio Afonso case '<':
417205e32badSAntonio Afonso result += "<";
417305e32badSAntonio Afonso break;
417405e32badSAntonio Afonso case '>':
417505e32badSAntonio Afonso result += ">";
417605e32badSAntonio Afonso break;
417705e32badSAntonio Afonso default:
417805e32badSAntonio Afonso result += c;
417905e32badSAntonio Afonso break;
418005e32badSAntonio Afonso }
418105e32badSAntonio Afonso }
418205e32badSAntonio Afonso return result;
418305e32badSAntonio Afonso }
41846c1a8039SMichał Górny
HandleFeatures(const llvm::ArrayRef<llvm::StringRef> client_features)4185aab81c2fSMichał Górny std::vector<std::string> GDBRemoteCommunicationServerLLGS::HandleFeatures(
4186aab81c2fSMichał Górny const llvm::ArrayRef<llvm::StringRef> client_features) {
418731225768SMichał Górny std::vector<std::string> ret =
4188aab81c2fSMichał Górny GDBRemoteCommunicationServerCommon::HandleFeatures(client_features);
4189aab81c2fSMichał Górny ret.insert(ret.end(), {
4190ca7824c2SMichał Górny "QThreadSuffixSupported+",
4191ca7824c2SMichał Górny "QListThreadsInStopReply+",
419231225768SMichał Górny "qXfer:features:read+",
4193bc04d240SMichał Górny "QNonStop+",
4194aab81c2fSMichał Górny });
419531225768SMichał Górny
4196ca7824c2SMichał Górny // report server-only features
419731225768SMichał Górny using Extension = NativeProcessProtocol::Extension;
4198ca7824c2SMichał Górny Extension plugin_features = m_process_factory.GetSupportedExtensions();
4199ca7824c2SMichał Górny if (bool(plugin_features & Extension::pass_signals))
4200ca7824c2SMichał Górny ret.push_back("QPassSignals+");
4201ca7824c2SMichał Górny if (bool(plugin_features & Extension::auxv))
4202ca7824c2SMichał Górny ret.push_back("qXfer:auxv:read+");
4203ca7824c2SMichał Górny if (bool(plugin_features & Extension::libraries_svr4))
4204ca7824c2SMichał Górny ret.push_back("qXfer:libraries-svr4:read+");
42051e74e5e9SMichał Górny if (bool(plugin_features & Extension::siginfo_read))
42061e74e5e9SMichał Górny ret.push_back("qXfer:siginfo:read+");
42078d58fbd0SDavid Spickett if (bool(plugin_features & Extension::memory_tagging))
42088d58fbd0SDavid Spickett ret.push_back("memory-tagging+");
420937cbd817SMichał Górny if (bool(plugin_features & Extension::savecore))
421037cbd817SMichał Górny ret.push_back("qSaveCore+");
4211ca7824c2SMichał Górny
4212ca7824c2SMichał Górny // check for client features
421331225768SMichał Górny m_extensions_supported = {};
421431225768SMichał Górny for (llvm::StringRef x : client_features)
421531225768SMichał Górny m_extensions_supported |=
421631225768SMichał Górny llvm::StringSwitch<Extension>(x)
421731225768SMichał Górny .Case("multiprocess+", Extension::multiprocess)
421831225768SMichał Górny .Case("fork-events+", Extension::fork)
421931225768SMichał Górny .Case("vfork-events+", Extension::vfork)
422031225768SMichał Górny .Default({});
4221ca7824c2SMichał Górny
4222ca7824c2SMichał Górny m_extensions_supported &= plugin_features;
422331225768SMichał Górny
422431225768SMichał Górny // fork & vfork require multiprocess
422531225768SMichał Górny if (!bool(m_extensions_supported & Extension::multiprocess))
422631225768SMichał Górny m_extensions_supported &= ~(Extension::fork | Extension::vfork);
422731225768SMichał Górny
422831225768SMichał Górny // report only if actually supported
422931225768SMichał Górny if (bool(m_extensions_supported & Extension::multiprocess))
423031225768SMichał Górny ret.push_back("multiprocess+");
423131225768SMichał Górny if (bool(m_extensions_supported & Extension::fork))
423231225768SMichał Górny ret.push_back("fork-events+");
423331225768SMichał Górny if (bool(m_extensions_supported & Extension::vfork))
423431225768SMichał Górny ret.push_back("vfork-events+");
423531225768SMichał Górny
4236bbae0c1fSMichał Górny for (auto &x : m_debugged_processes)
4237355c7916SMichał Górny SetEnabledExtensions(*x.second.process_up);
4238aab81c2fSMichał Górny return ret;
4239aab81c2fSMichał Górny }
424031225768SMichał Górny
SetEnabledExtensions(NativeProcessProtocol & process)424131225768SMichał Górny void GDBRemoteCommunicationServerLLGS::SetEnabledExtensions(
424231225768SMichał Górny NativeProcessProtocol &process) {
424331225768SMichał Górny NativeProcessProtocol::Extension flags = m_extensions_supported;
424431225768SMichał Górny assert(!bool(flags & ~m_process_factory.GetSupportedExtensions()));
424531225768SMichał Górny process.SetEnabledExtensions(flags);
424631225768SMichał Górny }
424758d28b93SMichał Górny
4248bc04d240SMichał Górny GDBRemoteCommunication::PacketResult
SendContinueSuccessResponse()4249bc04d240SMichał Górny GDBRemoteCommunicationServerLLGS::SendContinueSuccessResponse() {
425009531edeSMichał Górny if (m_non_stop)
425109531edeSMichał Górny return SendOKResponse();
4252e8fe7e93SMichał Górny StartSTDIOForwarding();
425309531edeSMichał Górny return PacketResult::Success;
4254bc04d240SMichał Górny }
4255bc04d240SMichał Górny
AppendThreadIDToResponse(Stream & response,lldb::pid_t pid,lldb::tid_t tid)42564b485fc0SMichał Górny void GDBRemoteCommunicationServerLLGS::AppendThreadIDToResponse(
42574b485fc0SMichał Górny Stream &response, lldb::pid_t pid, lldb::tid_t tid) {
42584b485fc0SMichał Górny if (bool(m_extensions_supported &
42594b485fc0SMichał Górny NativeProcessProtocol::Extension::multiprocess))
42604b485fc0SMichał Górny response.Format("p{0:x-}.", pid);
42614b485fc0SMichał Górny response.Format("{0:x-}", tid);
42624b485fc0SMichał Górny }
42634b485fc0SMichał Górny
426458d28b93SMichał Górny std::string
LLGSArgToURL(llvm::StringRef url_arg,bool reverse_connect)426558d28b93SMichał Górny lldb_private::process_gdb_remote::LLGSArgToURL(llvm::StringRef url_arg,
426658d28b93SMichał Górny bool reverse_connect) {
426758d28b93SMichał Górny // Try parsing the argument as URL.
426858d28b93SMichał Górny if (llvm::Optional<URI> url = URI::Parse(url_arg)) {
426958d28b93SMichał Górny if (reverse_connect)
427058d28b93SMichał Górny return url_arg.str();
427158d28b93SMichał Górny
427258d28b93SMichał Górny // Translate the scheme from LLGS notation to ConnectionFileDescriptor.
427358d28b93SMichał Górny // If the scheme doesn't match any, pass it through to support using CFD
427458d28b93SMichał Górny // schemes directly.
427558d28b93SMichał Górny std::string new_url = llvm::StringSwitch<std::string>(url->scheme)
427658d28b93SMichał Górny .Case("tcp", "listen")
427758d28b93SMichał Górny .Case("unix", "unix-accept")
427858d28b93SMichał Górny .Case("unix-abstract", "unix-abstract-accept")
427958d28b93SMichał Górny .Default(url->scheme.str());
428058d28b93SMichał Górny llvm::append_range(new_url, url_arg.substr(url->scheme.size()));
428158d28b93SMichał Górny return new_url;
428258d28b93SMichał Górny }
428358d28b93SMichał Górny
428458d28b93SMichał Górny std::string host_port = url_arg.str();
428558d28b93SMichał Górny // If host_and_port starts with ':', default the host to be "localhost" and
428658d28b93SMichał Górny // expect the remainder to be the port.
428758d28b93SMichał Górny if (url_arg.startswith(":"))
428858d28b93SMichał Górny host_port.insert(0, "localhost");
428958d28b93SMichał Górny
429058d28b93SMichał Górny // Try parsing the (preprocessed) argument as host:port pair.
4291073c5d0eSMichał Górny if (!llvm::errorToBool(Socket::DecodeHostAndPort(host_port).takeError()))
429258d28b93SMichał Górny return (reverse_connect ? "connect://" : "listen://") + host_port;
429358d28b93SMichał Górny
429458d28b93SMichał Górny // If none of the above applied, interpret the argument as UNIX socket path.
429558d28b93SMichał Górny return (reverse_connect ? "unix-connect://" : "unix-accept://") +
429658d28b93SMichał Górny url_arg.str();
429758d28b93SMichał Górny }
4298