summaryrefslogtreecommitdiffstats
path: root/lldb/unittests/tools/lldb-server/tests/TestClient.cpp
blob: f309e62dbd5c03e9c297a511754101e597255bd6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
//===-- TestClient.cpp ------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "TestClient.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Host/common/TCPSocket.h"
#include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
#include "lldb/Interpreter/Args.h"
#include "lldb/Target/ProcessLaunchInfo.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Path.h"
#include "llvm/Testing/Support/Error.h"
#include "gtest/gtest.h"
#include <cstdlib>
#include <future>
#include <sstream>
#include <string>

using namespace lldb;
using namespace lldb_private;
using namespace llvm;

namespace llgs_tests {

TestClient::TestClient(std::unique_ptr<Connection> Conn) {
  SetConnection(Conn.release());

  SendAck(); // Send this as a handshake.
}

TestClient::~TestClient() {
  if (!IsConnected())
    return;

  std::string response;
  // Debugserver (non-conformingly?) sends a reply to the k packet instead of
  // simply closing the connection.
  PacketResult result =
      IsDebugServer() ? PacketResult::Success : PacketResult::ErrorDisconnected;
  EXPECT_THAT_ERROR(SendMessage("k", response, result), Succeeded());
}

Expected<std::unique_ptr<TestClient>> TestClient::launch(StringRef Log) {
  return launch(Log, {});
}

Expected<std::unique_ptr<TestClient>> TestClient::launch(StringRef Log, ArrayRef<StringRef> InferiorArgs) {
  return launchCustom(Log, {}, InferiorArgs);
}

Expected<std::unique_ptr<TestClient>> TestClient::launchCustom(StringRef Log, ArrayRef<StringRef> ServerArgs, ArrayRef<StringRef> InferiorArgs) {
  const ArchSpec &arch_spec = HostInfo::GetArchitecture();
  Args args;
  args.AppendArgument(LLDB_SERVER);
  if (IsLldbServer())
    args.AppendArgument("gdbserver");
  args.AppendArgument("--reverse-connect");

  if (!Log.empty()) {
    args.AppendArgument(("--log-file=" + Log).str());
    if (IsLldbServer())
      args.AppendArgument("--log-channels=gdb-remote packets");
    else
      args.AppendArgument("--log-flags=0x800000");
  }

  Status status;
  TCPSocket listen_socket(true, false);
  status = listen_socket.Listen("127.0.0.1:0", 5);
  if (status.Fail())
    return status.ToError();

  args.AppendArgument(
      ("localhost:" + Twine(listen_socket.GetLocalPortNumber())).str());

  for (StringRef arg : ServerArgs)
    args.AppendArgument(arg);

  if (!InferiorArgs.empty()) {
    args.AppendArgument("--");
    for (StringRef arg : InferiorArgs)
      args.AppendArgument(arg);
  }

  ProcessLaunchInfo Info;
  Info.SetArchitecture(arch_spec);
  Info.SetArguments(args, true);
  Info.GetEnvironment() = Host::GetEnvironment();

  status = Host::LaunchProcess(Info);
  if (status.Fail())
    return status.ToError();

  Socket *accept_socket;
  listen_socket.Accept(accept_socket);
  auto Conn = llvm::make_unique<ConnectionFileDescriptor>(accept_socket);
  auto Client = std::unique_ptr<TestClient>(new TestClient(std::move(Conn)));

  if (!InferiorArgs.empty()) {
    if (Error E = Client->QueryProcessInfo())
      return std::move(E);
  }

  return std::move(Client);
}

Error TestClient::SetInferior(llvm::ArrayRef<std::string> inferior_args) {
  if (SendEnvironment(Host::GetEnvironment()) != 0) {
    return make_error<StringError>("Failed to set launch environment",
                                   inconvertibleErrorCode());
  }
  std::stringstream command;
  command << "A";
  for (size_t i = 0; i < inferior_args.size(); i++) {
    if (i > 0)
      command << ',';
    std::string hex_encoded = toHex(inferior_args[i]);
    command << hex_encoded.size() << ',' << i << ',' << hex_encoded;
  }

  if (Error E = SendMessage(command.str()))
    return E;
  if (Error E = SendMessage("qLaunchSuccess"))
    return E;
  if (Error E = QueryProcessInfo())
    return E;
  return Error::success();
}

Error TestClient::ListThreadsInStopReply() {
  return SendMessage("QListThreadsInStopReply");
}

Error TestClient::SetBreakpoint(unsigned long address) {
  return SendMessage(formatv("Z0,{0:x-},1", address).str());
}

Error TestClient::ContinueAll() { return Continue("vCont;c"); }

Error TestClient::ContinueThread(unsigned long thread_id) {
  return Continue(formatv("vCont;c:{0:x-}", thread_id).str());
}

const ProcessInfo &TestClient::GetProcessInfo() { return *m_process_info; }

Optional<JThreadsInfo> TestClient::GetJThreadsInfo() {
  std::string response;
  if (SendMessage("jThreadsInfo", response))
    return llvm::None;
  auto creation = JThreadsInfo::Create(response, m_process_info->GetEndian());
  if (auto create_error = creation.takeError()) {
    GTEST_LOG_(ERROR) << toString(std::move(create_error));
    return llvm::None;
  }

  return std::move(*creation);
}

const StopReply &TestClient::GetLatestStopReply() {
  assert(m_stop_reply);
  return *m_stop_reply;
}

Error TestClient::SendMessage(StringRef message) {
  std::string dummy_string;
  return SendMessage(message, dummy_string);
}

Error TestClient::SendMessage(StringRef message, std::string &response_string) {
  if (Error E = SendMessage(message, response_string, PacketResult::Success))
    return E;
  if (response_string[0] == 'E') {
    return make_error<StringError>(
        formatv("Error `{0}` while sending message: {1}", response_string,
                message)
            .str(),
        inconvertibleErrorCode());
  }
  return Error::success();
}

Error TestClient::SendMessage(StringRef message, std::string &response_string,
                              PacketResult expected_result) {
  StringExtractorGDBRemote response;
  GTEST_LOG_(INFO) << "Send Packet: " << message.str();
  PacketResult result = SendPacketAndWaitForResponse(message, response, false);
  response.GetEscapedBinaryData(response_string);
  GTEST_LOG_(INFO) << "Read Packet: " << response_string;
  if (result != expected_result)
    return make_error<StringError>(
        formatv("Error sending message `{0}`: {1}", message, result).str(),
        inconvertibleErrorCode());

  return Error::success();
}

unsigned int TestClient::GetPcRegisterId() {
  if (m_pc_register != UINT_MAX)
    return m_pc_register;

  for (unsigned int register_id = 0;; register_id++) {
    std::string message = formatv("qRegisterInfo{0:x-}", register_id).str();
    std::string response;
    if (SendMessage(message, response)) {
      GTEST_LOG_(ERROR) << "Unable to query register ID for PC register.";
      return UINT_MAX;
    }

    auto elements_or_error = SplitUniquePairList("GetPcRegisterId", response);
    if (auto split_error = elements_or_error.takeError()) {
      GTEST_LOG_(ERROR) << "GetPcRegisterId: Error splitting response: "
                        << response;
      return UINT_MAX;
    }

    auto elements = *elements_or_error;
    if (elements["alt-name"] == "pc" || elements["generic"] == "pc") {
      m_pc_register = register_id;
      break;
    }
  }

  return m_pc_register;
}

llvm::Error TestClient::QueryProcessInfo() {
  std::string response;
  if (Error E = SendMessage("qProcessInfo", response))
    return E;
  auto create_or_error = ProcessInfo::Create(response);
  if (!create_or_error)
    return create_or_error.takeError();
  m_process_info = *create_or_error;
  return Error::success();
}

Error TestClient::Continue(StringRef message) {
  assert(m_process_info.hasValue());

  std::string response;
  if (Error E = SendMessage(message, response))
    return E;
  auto creation = StopReply::create(response, m_process_info->GetEndian());
  if (Error E = creation.takeError())
    return E;

  m_stop_reply = std::move(*creation);
  if (!isa<StopReplyStop>(m_stop_reply)) {
    StringExtractorGDBRemote R;
    PacketResult result = ReadPacket(R, GetPacketTimeout(), false);
    if (result != PacketResult::ErrorDisconnected) {
      return make_error<StringError>(
          formatv("Expected connection close after receiving {0}. Got {1}/{2} "
                  "instead.",
                  response, result, R.GetStringRef())
              .str(),
          inconvertibleErrorCode());
    }
  }
  return Error::success();
}

} // namespace llgs_tests
OpenPOWER on IntegriCloud