Debian Codegraph @

llvm-project/lldb/unittests/tools/lldb-server/tests/TestClient.cpp

raw
1 //===-- TestClient.cpp ----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "TestClient.h"
10 #include "TestingSupport/Host/SocketTestUtilities.h"
11 #include "lldb/Host/HostInfo.h"
12 #include "lldb/Host/common/TCPSocket.h"
13 #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
14 #include "lldb/Utility/Args.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/Support/Path.h"
17 #include "llvm/Testing/Support/Error.h"
18 #include "gtest/gtest.h"
19 #include <cstdlib>
20 #include <future>
21 #include <sstream>
22 #include <string>
23
24 using namespace lldb;
25 using namespace lldb_private;
26 using namespace llvm;
27 using namespace llgs_tests;
28
29 #ifdef SendMessage
30 #undef SendMessage
31 #endif
32
33 TestClient::TestClient(std::unique_ptr<Connection> Conn) {
34 SetConnection(std::move(Conn));
35 SetPacketTimeout(std::chrono::seconds(10));
36 }
37
38 TestClient::~TestClient() {
39 if (!IsConnected())
40 return;
41
42 EXPECT_THAT_ERROR(SendMessage("k"), Succeeded());
43 }
44
45 Error TestClient::initializeConnection() {
46 if (SendAck() == 0)
47 return make_error<StringError>("Sending initial ACK failed.",
48 inconvertibleErrorCode());
49
50 if (Error E = SendMessage("QStartNoAckMode"))
51 return E;
52
53 m_send_acks = false;
54 return Error::success();
55 }
56
57 Expected<std::unique_ptr<TestClient>> TestClient::launch(StringRef Log) {
58 return launch(Log, {});
59 }
60
61 Expected<std::unique_ptr<TestClient>> TestClient::launch(StringRef Log, ArrayRef<StringRef> InferiorArgs) {
62 return launchCustom(Log, {}, InferiorArgs);
63 }
64
65 Expected<std::unique_ptr<TestClient>> TestClient::launchCustom(StringRef Log, ArrayRef<StringRef> ServerArgs, ArrayRef<StringRef> InferiorArgs) {
66 const ArchSpec &arch_spec = HostInfo::GetArchitecture();
67 Args args;
68 args.AppendArgument(LLDB_SERVER);
69 if (IsLldbServer())
70 args.AppendArgument("gdbserver");
71 args.AppendArgument("--reverse-connect");
72
73 if (!Log.empty()) {
74 args.AppendArgument(("--log-file=" + Log).str());
75 if (IsLldbServer())
76 args.AppendArgument("--log-channels=gdb-remote packets");
77 else
78 args.AppendArgument("--log-flags=0x800000");
79 }
80
81 auto LocalhostIPOrErr = GetLocalhostIP();
82 if (!LocalhostIPOrErr)
83 return LocalhostIPOrErr.takeError();
84 const std::string &LocalhostIP = *LocalhostIPOrErr;
85
86 Status status;
87 TCPSocket listen_socket(true, false);
88 status = listen_socket.Listen(LocalhostIP + ":0", 5);
89 if (status.Fail())
90 return status.ToError();
91
92 args.AppendArgument(
93 formatv("{0}:{1}", LocalhostIP, listen_socket.GetLocalPortNumber())
94 .str());
95
96 for (StringRef arg : ServerArgs)
97 args.AppendArgument(arg);
98
99 if (!InferiorArgs.empty()) {
100 args.AppendArgument("--");
101 for (StringRef arg : InferiorArgs)
102 args.AppendArgument(arg);
103 }
104
105 ProcessLaunchInfo Info;
106 Info.SetArchitecture(arch_spec);
107 Info.SetArguments(args, true);
108 Info.GetEnvironment() = Host::GetEnvironment();
109 // TODO: Use this callback to detect botched launches. If lldb-server does not
110 // start, we can print a nice error message here instead of hanging in
111 // Accept().
112 Info.SetMonitorProcessCallback(&ProcessLaunchInfo::NoOpMonitorCallback);
113
114 status = Host::LaunchProcess(Info);
115 if (status.Fail())
116 return status.ToError();
117
118 Socket *accept_socket;
119 listen_socket.Accept(accept_socket);
120 auto Conn = std::make_unique<ConnectionFileDescriptor>(accept_socket);
121 auto Client = std::unique_ptr<TestClient>(new TestClient(std::move(Conn)));
122
123 if (Error E = Client->initializeConnection())
124 return std::move(E);
125
126 if (!InferiorArgs.empty()) {
127 if (Error E = Client->queryProcess())
128 return std::move(E);
129 }
130
131 return std::move(Client);
132 }
133
134 Error TestClient::SetInferior(llvm::ArrayRef<std::string> inferior_args) {
135 if (SendEnvironment(Host::GetEnvironment()) != 0) {
136 return make_error<StringError>("Failed to set launch environment",
137 inconvertibleErrorCode());
138 }
139 std::stringstream command;
140 command << "A";
141 for (size_t i = 0; i < inferior_args.size(); i++) {
142 if (i > 0)
143 command << ',';
144 std::string hex_encoded = toHex(inferior_args[i]);
145 command << hex_encoded.size() << ',' << i << ',' << hex_encoded;
146 }
147
148 if (Error E = SendMessage(command.str()))
149 return E;
150 if (Error E = SendMessage("qLaunchSuccess"))
151 return E;
152 if (Error E = queryProcess())
153 return E;
154 return Error::success();
155 }
156
157 Error TestClient::ListThreadsInStopReply() {
158 return SendMessage("QListThreadsInStopReply");
159 }
160
161 Error TestClient::SetBreakpoint(unsigned long address) {
162 return SendMessage(formatv("Z0,{0:x-},1", address).str());
163 }
164
165 Error TestClient::ContinueAll() { return Continue("vCont;c"); }
166
167 Error TestClient::ContinueThread(unsigned long thread_id) {
168 return Continue(formatv("vCont;c:{0:x-}", thread_id).str());
169 }
170
171 const llgs_tests::ProcessInfo &TestClient::GetProcessInfo() {
172 return *m_process_info;
173 }
174
175 Expected<JThreadsInfo> TestClient::GetJThreadsInfo() {
176 return SendMessage<JThreadsInfo>("jThreadsInfo", m_register_infos);
177 }
178
179 const StopReply &TestClient::GetLatestStopReply() {
180 assert(m_stop_reply);
181 return *m_stop_reply;
182 }
183
184 Error TestClient::SendMessage(StringRef message) {
185 std::string dummy_string;
186 return SendMessage(message, dummy_string);
187 }
188
189 Error TestClient::SendMessage(StringRef message, std::string &response_string) {
190 if (Error E = SendMessage(message, response_string, PacketResult::Success))
191 return E;
192 StringExtractorGDBRemote Extractor(response_string);
193 if (Extractor.IsErrorResponse())
194 return Extractor.GetStatus().ToError();
195 return Error::success();
196 }
197
198 Error TestClient::SendMessage(StringRef message, std::string &response_string,
199 PacketResult expected_result) {
200 StringExtractorGDBRemote response;
201 GTEST_LOG_(INFO) << "Send Packet: " << message.str();
202 PacketResult result = SendPacketAndWaitForResponse(message, response);
203 response.GetEscapedBinaryData(response_string);
204 GTEST_LOG_(INFO) << "Read Packet: " << response_string;
205 if (result != expected_result)
206 return make_error<StringError>(
207 formatv("Error sending message `{0}`: {1}", message, result).str(),
208 inconvertibleErrorCode());
209
210 return Error::success();
211 }
212
213 unsigned int TestClient::GetPcRegisterId() {
214 assert(m_pc_register != LLDB_INVALID_REGNUM);
215 return m_pc_register;
216 }
217
218 Error TestClient::qProcessInfo() {
219 m_process_info = std::nullopt;
220 auto InfoOr = SendMessage<ProcessInfo>("qProcessInfo");
221 if (!InfoOr)
222 return InfoOr.takeError();
223 m_process_info = std::move(*InfoOr);
224 return Error::success();
225 }
226
227 Error TestClient::qRegisterInfos() {
228 uint32_t reg_offset = 0;
229 for (unsigned int Reg = 0;; ++Reg) {
230 std::string Message = formatv("qRegisterInfo{0:x-}", Reg).str();
231 Expected<RegisterInfo> InfoOr = SendMessage<RegisterInfoParser>(Message);
232 if (!InfoOr) {
233 consumeError(InfoOr.takeError());
234 break;
235 }
236 m_register_infos.emplace_back(std::move(*InfoOr));
237
238 if (m_register_infos[Reg].byte_offset == LLDB_INVALID_INDEX32)
239 m_register_infos[Reg].byte_offset = reg_offset;
240
241 reg_offset =
242 m_register_infos[Reg].byte_offset + m_register_infos[Reg].byte_size;
243 if (m_register_infos[Reg].kinds[eRegisterKindGeneric] ==
244 LLDB_REGNUM_GENERIC_PC)
245 m_pc_register = Reg;
246 }
247 if (m_pc_register == LLDB_INVALID_REGNUM)
248 return make_parsing_error("qRegisterInfo: generic");
249 return Error::success();
250 }
251
252 Error TestClient::queryProcess() {
253 if (Error E = qProcessInfo())
254 return E;
255 if (Error E = qRegisterInfos())
256 return E;
257 return Error::success();
258 }
259
260 Error TestClient::Continue(StringRef message) {
261 assert(m_process_info);
262
263 auto StopReplyOr = SendMessage<StopReply>(
264 message, m_process_info->GetEndian(), m_register_infos);
265 if (!StopReplyOr)
266 return StopReplyOr.takeError();
267
268 m_stop_reply = std::move(*StopReplyOr);
269 if (!isa<StopReplyStop>(m_stop_reply)) {
270 StringExtractorGDBRemote R;
271 PacketResult result = ReadPacket(R, GetPacketTimeout(), false);
272 if (result != PacketResult::ErrorDisconnected) {
273 return make_error<StringError>(
274 formatv("Expected connection close after sending {0}. Got {1}/{2} "
275 "instead.",
276 message, result, R.GetStringRef())
277 .str(),
278 inconvertibleErrorCode());
279 }
280 }
281 return Error::success();
282 }