summaryrefslogtreecommitdiffstats
path: root/Source/cmDebuggerPipeConnection.cxx
blob: 1b543460d33dd4c23f0c0dbd804e5f86e784fd71 (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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
#include "cmDebuggerPipeConnection.h"

#include <algorithm>
#include <cassert>
#include <cstring>
#include <stdexcept>
#include <utility>

namespace cmDebugger {

struct write_req_t
{
  uv_write_t req;
  uv_buf_t buf;
};

cmDebuggerPipeBase::cmDebuggerPipeBase(std::string name)
  : PipeName(std::move(name))
{
  Loop.init();
  LoopExit.init(
    *Loop, [](uv_async_t* handle) { uv_stop((uv_loop_t*)handle->data); },
    Loop);
  WriteEvent.init(
    *Loop,
    [](uv_async_t* handle) {
      auto* conn = static_cast<cmDebuggerPipeBase*>(handle->data);
      conn->WriteInternal();
    },
    this);
  PipeClose.init(
    *Loop,
    [](uv_async_t* handle) {
      auto* conn = static_cast<cmDebuggerPipeBase*>(handle->data);
      if (conn->Pipe.get()) {
        conn->Pipe->data = nullptr;
        conn->Pipe.reset();
      }
    },
    this);
}

void cmDebuggerPipeBase::WaitForConnection()
{
  std::unique_lock<std::mutex> lock(Mutex);
  Connected.wait(lock, [this] { return isOpen() || FailedToOpen; });
  if (FailedToOpen) {
    throw std::runtime_error("Failed to open debugger connection.");
  }
}

void cmDebuggerPipeBase::close()
{
  std::unique_lock<std::mutex> lock(Mutex);

  CloseConnection();
  PipeClose.send();
  lock.unlock();
  ReadReady.notify_all();
}

size_t cmDebuggerPipeBase::read(void* buffer, size_t n)
{
  std::unique_lock<std::mutex> lock(Mutex);
  ReadReady.wait(lock, [this] { return !isOpen() || !ReadBuffer.empty(); });

  if (!isOpen() && ReadBuffer.empty()) {
    return 0;
  }

  auto size = std::min(n, ReadBuffer.size());
  memcpy(buffer, ReadBuffer.data(), size);
  ReadBuffer.erase(0, size);
  return size;
}

bool cmDebuggerPipeBase::write(const void* buffer, size_t n)
{
  std::unique_lock<std::mutex> lock(Mutex);
  WriteBuffer.append(static_cast<const char*>(buffer), n);
  lock.unlock();
  WriteEvent.send();

  lock.lock();
  WriteComplete.wait(lock, [this] { return WriteBuffer.empty(); });
  return true;
}

void cmDebuggerPipeBase::StopLoop()
{
  LoopExit.send();

  if (LoopThread.joinable()) {
    LoopThread.join();
  }
}

void cmDebuggerPipeBase::BufferData(const std::string& data)
{
  std::unique_lock<std::mutex> lock(Mutex);
  ReadBuffer += data;
  lock.unlock();
  ReadReady.notify_all();
}

void cmDebuggerPipeBase::WriteInternal()
{
  std::unique_lock<std::mutex> lock(Mutex);
  auto n = WriteBuffer.length();
  assert(this->Pipe.get());
  write_req_t* req = new write_req_t;
  req->req.data = &WriteComplete;
  char* rawBuffer = new char[n];
  req->buf = uv_buf_init(rawBuffer, static_cast<unsigned int>(n));
  memcpy(req->buf.base, WriteBuffer.data(), n);
  WriteBuffer.clear();
  lock.unlock();

  uv_write(
    reinterpret_cast<uv_write_t*>(req), this->Pipe, &req->buf, 1,
    [](uv_write_t* cb_req, int status) {
      (void)status; // We need to free memory even if the write failed.
      write_req_t* wr = reinterpret_cast<write_req_t*>(cb_req);
      reinterpret_cast<std::condition_variable*>(wr->req.data)->notify_all();
      delete[] (wr->buf.base);
      delete wr;
    });

#ifdef __clang_analyzer__
  // Tell clang-analyzer that 'rawBuffer' does not leak.
  // We pass ownership to the closure.
  delete[] rawBuffer;
#endif
}

cmDebuggerPipeConnection::cmDebuggerPipeConnection(std::string name)
  : cmDebuggerPipeBase(std::move(name))
{
  ServerPipeClose.init(
    *Loop,
    [](uv_async_t* handle) {
      auto* conn = static_cast<cmDebuggerPipeConnection*>(handle->data);
      if (conn->ServerPipe.get()) {
        conn->ServerPipe->data = nullptr;
        conn->ServerPipe.reset();
      }
    },
    this);
}

cmDebuggerPipeConnection::~cmDebuggerPipeConnection()
{
  StopLoop();
}

bool cmDebuggerPipeConnection::StartListening(std::string& errorMessage)
{
  this->ServerPipe.init(*Loop, 0,
                        static_cast<cmDebuggerPipeConnection*>(this));

  int r;
  if ((r = uv_pipe_bind(this->ServerPipe, this->PipeName.c_str())) != 0) {
    errorMessage =
      "Internal Error with " + this->PipeName + ": " + uv_err_name(r);
    return false;
  }

  r = uv_listen(this->ServerPipe, 1, [](uv_stream_t* stream, int status) {
    if (status >= 0) {
      auto* conn = static_cast<cmDebuggerPipeConnection*>(stream->data);
      if (conn) {
        conn->Connect(stream);
      }
    }
  });

  if (r != 0) {
    errorMessage =
      "Internal Error listening on " + this->PipeName + ": " + uv_err_name(r);
    return false;
  }

  // Start the libuv event loop thread so that a client can connect.
  LoopThread = std::thread([this] { uv_run(Loop, UV_RUN_DEFAULT); });

  StartedListening.set_value();

  return true;
}

std::shared_ptr<dap::Reader> cmDebuggerPipeConnection::GetReader()
{
  return std::static_pointer_cast<dap::Reader>(shared_from_this());
}

std::shared_ptr<dap::Writer> cmDebuggerPipeConnection::GetWriter()
{
  return std::static_pointer_cast<dap::Writer>(shared_from_this());
}

bool cmDebuggerPipeConnection::isOpen()
{
  return this->Pipe.get() != nullptr;
}

void cmDebuggerPipeConnection::CloseConnection()
{
  ServerPipeClose.send();
}

void cmDebuggerPipeConnection::Connect(uv_stream_t* server)
{
  if (this->Pipe.get()) {
    // Accept and close all pipes but the first:
    cm::uv_pipe_ptr rejectPipe;

    rejectPipe.init(*Loop, 0);
    uv_accept(server, rejectPipe);

    return;
  }

  cm::uv_pipe_ptr ClientPipe;
  ClientPipe.init(*Loop, 0, static_cast<cmDebuggerPipeConnection*>(this));

  if (uv_accept(server, ClientPipe) != 0) {
    return;
  }

  StartReading<cmDebuggerPipeConnection>(ClientPipe);

  std::unique_lock<std::mutex> lock(Mutex);
  Pipe = std::move(ClientPipe);
  lock.unlock();
  Connected.notify_all();
}

cmDebuggerPipeClient::~cmDebuggerPipeClient()
{
  StopLoop();
}

void cmDebuggerPipeClient::Start()
{
  this->Pipe.init(*Loop, 0, static_cast<cmDebuggerPipeClient*>(this));

  uv_connect_t* connect = new uv_connect_t;
  connect->data = this;
  uv_pipe_connect(
    connect, Pipe, PipeName.c_str(), [](uv_connect_t* cb_connect, int status) {
      auto* conn = static_cast<cmDebuggerPipeClient*>(cb_connect->data);
      if (status >= 0) {
        conn->Connect();
      } else {
        conn->FailConnection();
      }
      delete cb_connect;
    });

  // Start the libuv event loop so that the pipe can connect.
  LoopThread = std::thread([this] { uv_run(Loop, UV_RUN_DEFAULT); });
}

bool cmDebuggerPipeClient::isOpen()
{
  return IsConnected;
}

void cmDebuggerPipeClient::CloseConnection()
{
  IsConnected = false;
}

void cmDebuggerPipeClient::Connect()
{
  StartReading<cmDebuggerPipeClient>(Pipe);
  std::unique_lock<std::mutex> lock(Mutex);
  IsConnected = true;
  lock.unlock();
  Connected.notify_all();
}

void cmDebuggerPipeClient::FailConnection()
{
  std::unique_lock<std::mutex> lock(Mutex);
  FailedToOpen = true;
  lock.unlock();
  Connected.notify_all();
}

} // namespace cmDebugger