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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
|
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/debug/wasm/gdb-server/transport.h"
#include <fcntl.h>
#ifndef SD_BOTH
#define SD_BOTH 2
#endif
namespace v8 {
namespace internal {
namespace wasm {
namespace gdb_server {
SocketBinding::SocketBinding(SocketHandle socket_handle)
: socket_handle_(socket_handle) {}
// static
SocketBinding SocketBinding::Bind(uint16_t tcp_port) {
SocketHandle socket_handle = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socket_handle == InvalidSocket) {
TRACE_GDB_REMOTE("Failed to create socket.\n");
return SocketBinding(InvalidSocket);
}
struct sockaddr_in sockaddr;
// Clearing sockaddr_in first appears to be necessary on Mac OS X.
memset(&sockaddr, 0, sizeof(sockaddr));
socklen_t addrlen = static_cast<socklen_t>(sizeof(sockaddr));
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
sockaddr.sin_port = htons(tcp_port);
#if _WIN32
// On Windows, SO_REUSEADDR has a different meaning than on POSIX systems.
// SO_REUSEADDR allows hijacking of an open socket by another process.
// The SO_EXCLUSIVEADDRUSE flag prevents this behavior.
// See:
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621(v=vs.85).aspx
//
// Additionally, unlike POSIX, TCP server sockets can be bound to
// ports in the TIME_WAIT state, without setting SO_REUSEADDR.
int exclusive_address = 1;
if (setsockopt(socket_handle, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
reinterpret_cast<char*>(&exclusive_address),
sizeof(exclusive_address))) {
TRACE_GDB_REMOTE("Failed to set SO_EXCLUSIVEADDRUSE option.\n");
}
#else
// On POSIX, this is necessary to ensure that the TCP port is released
// promptly when sel_ldr exits. Without this, the TCP port might
// only be released after a timeout, and later processes can fail
// to bind it.
int reuse_address = 1;
if (setsockopt(socket_handle, SOL_SOCKET, SO_REUSEADDR,
reinterpret_cast<char*>(&reuse_address),
sizeof(reuse_address))) {
TRACE_GDB_REMOTE("Failed to set SO_REUSEADDR option.\n");
}
#endif
if (bind(socket_handle, reinterpret_cast<struct sockaddr*>(&sockaddr),
addrlen)) {
TRACE_GDB_REMOTE("Failed to bind server.\n");
return SocketBinding(InvalidSocket);
}
if (listen(socket_handle, 1)) {
TRACE_GDB_REMOTE("Failed to listen.\n");
return SocketBinding(InvalidSocket);
}
return SocketBinding(socket_handle);
}
std::unique_ptr<Transport> SocketBinding::CreateTransport() {
return std::make_unique<Transport>(socket_handle_);
}
uint16_t SocketBinding::GetBoundPort() {
struct sockaddr_in saddr;
struct sockaddr* psaddr = reinterpret_cast<struct sockaddr*>(&saddr);
// Clearing sockaddr_in first appears to be necessary on Mac OS X.
memset(&saddr, 0, sizeof(saddr));
socklen_t addrlen = static_cast<socklen_t>(sizeof(saddr));
if (::getsockname(socket_handle_, psaddr, &addrlen)) {
TRACE_GDB_REMOTE("Failed to retrieve bound address.\n");
return 0;
}
return ntohs(saddr.sin_port);
}
// Do not delay sending small packets. This significantly speeds up
// remote debugging. Debug stub uses buffering to send outgoing packets
// so they are not split into more TCP packets than necessary.
void DisableNagleAlgorithm(SocketHandle socket) {
int nodelay = 1;
if (::setsockopt(socket, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<char*>(&nodelay), sizeof(nodelay))) {
TRACE_GDB_REMOTE("Failed to set TCP_NODELAY option.\n");
}
}
TransportBase::TransportBase(SocketHandle s)
: buf_(new char[kBufSize]),
pos_(0),
size_(0),
handle_bind_(s),
handle_accept_(InvalidSocket) {}
TransportBase::~TransportBase() {
if (handle_accept_ != InvalidSocket) {
CloseSocket(handle_accept_);
}
}
void TransportBase::CopyFromBuffer(char** dst, int32_t* len) {
int32_t copy_bytes = std::min(*len, size_ - pos_);
memcpy(*dst, buf_.get() + pos_, copy_bytes);
pos_ += copy_bytes;
*len -= copy_bytes;
*dst += copy_bytes;
}
bool TransportBase::Read(char* dst, int32_t len) {
if (pos_ < size_) {
CopyFromBuffer(&dst, &len);
}
while (len > 0) {
pos_ = 0;
size_ = 0;
if (!ReadSomeData()) {
return false;
}
CopyFromBuffer(&dst, &len);
}
return true;
}
bool TransportBase::Write(const char* src, int32_t len) {
while (len > 0) {
ssize_t result = ::send(handle_accept_, src, len, 0);
if (result > 0) {
src += result;
len -= result;
continue;
}
if (result == 0) {
return false;
}
if (SocketGetLastError() != kErrInterrupt) {
return false;
}
}
return true;
}
// Return true if there is data to read.
bool TransportBase::IsDataAvailable() const {
if (pos_ < size_) {
return true;
}
fd_set fds;
FD_ZERO(&fds);
FD_SET(handle_accept_, &fds);
// We want a "non-blocking" check
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
// Check if this file handle can select on read
int cnt = select(static_cast<int>(handle_accept_) + 1, &fds, 0, 0, &timeout);
// If we are ready, or if there is an error. We return true
// on error, to let the next IO request fail.
if (cnt != 0) return true;
return false;
}
void TransportBase::Close() {
::shutdown(handle_bind_, SD_BOTH);
CloseSocket(handle_bind_);
Disconnect();
}
void TransportBase::Disconnect() {
if (handle_accept_ != InvalidSocket) {
// Shutdown the connection in both directions. This should
// always succeed, and nothing we can do if this fails.
::shutdown(handle_accept_, SD_BOTH);
CloseSocket(handle_accept_);
handle_accept_ = InvalidSocket;
}
}
#if _WIN32
Transport::Transport(SocketHandle s) : TransportBase(s) {
socket_event_ = WSA_INVALID_EVENT;
faulted_thread_event_ = ::CreateEvent(NULL, TRUE, FALSE, NULL);
if (faulted_thread_event_ == NULL) {
TRACE_GDB_REMOTE(
"Transport::Transport: Failed to create event object for faulted"
"thread\n");
}
}
Transport::~Transport() {
if (!CloseHandle(faulted_thread_event_)) {
TRACE_GDB_REMOTE("Transport::~Transport: Failed to close event\n");
}
if (socket_event_) {
if (!::WSACloseEvent(socket_event_)) {
TRACE_GDB_REMOTE("Transport::~Transport: Failed to close socket event\n");
}
}
}
bool Transport::AcceptConnection() {
CHECK(handle_accept_ == InvalidSocket);
handle_accept_ = ::accept(handle_bind_, NULL, 0);
if (handle_accept_ != InvalidSocket) {
DisableNagleAlgorithm(handle_accept_);
// Create socket event
socket_event_ = ::WSACreateEvent();
if (socket_event_ == WSA_INVALID_EVENT) {
TRACE_GDB_REMOTE(
"Transport::AcceptConnection: Failed to create socket event\n");
}
// Listen for close events in order to handle them correctly.
// Additionally listen for read readiness as WSAEventSelect sets the socket
// to non-blocking mode.
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms738547(v=vs.85).aspx
if (::WSAEventSelect(handle_accept_, socket_event_, FD_CLOSE | FD_READ) ==
SOCKET_ERROR) {
TRACE_GDB_REMOTE(
"Transport::AcceptConnection: Failed to bind event to socket\n");
}
return true;
}
return false;
}
bool Transport::ReadSomeData() {
while (true) {
ssize_t result =
::recv(handle_accept_, buf_.get() + size_, kBufSize - size_, 0);
if (result > 0) {
size_ += result;
return true;
}
if (result == 0) {
return false; // The connection was gracefully closed.
}
// WSAEventSelect sets socket to non-blocking mode. This is essential
// for socket event notification to work, there is no workaround.
// See remarks section at the page
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms741576(v=vs.85).aspx
if (SocketGetLastError() == WSAEWOULDBLOCK) {
if (::WaitForSingleObject(socket_event_, INFINITE) == WAIT_FAILED) {
TRACE_GDB_REMOTE(
"Transport::ReadSomeData: Failed to wait on socket event\n");
}
if (!::ResetEvent(socket_event_)) {
TRACE_GDB_REMOTE(
"Transport::ReadSomeData: Failed to reset socket event\n");
}
continue;
}
if (SocketGetLastError() != kErrInterrupt) {
return false;
}
}
}
void Transport::WaitForDebugStubEvent() {
// Don't wait if we already have data to read.
bool wait = !(pos_ < size_);
HANDLE handles[2];
handles[0] = faulted_thread_event_;
handles[1] = socket_event_;
int count = size_ < kBufSize ? 2 : 1;
int result =
WaitForMultipleObjects(count, handles, FALSE, wait ? INFINITE : 0);
if (result == WAIT_OBJECT_0 + 1) {
if (!ResetEvent(socket_event_)) {
TRACE_GDB_REMOTE(
"Transport::WaitForDebugStubEvent: Failed to reset socket event\n");
}
return;
} else if (result == WAIT_OBJECT_0) {
if (!ResetEvent(faulted_thread_event_)) {
TRACE_GDB_REMOTE(
"Transport::WaitForDebugStubEvent: Failed to reset event\n");
}
return;
} else if (result == WAIT_TIMEOUT) {
return;
}
TRACE_GDB_REMOTE(
"Transport::WaitForDebugStubEvent: Wait for events failed\n");
}
bool Transport::SignalThreadEvent() {
if (!SetEvent(faulted_thread_event_)) {
return false;
}
return true;
}
void Transport::Disconnect() {
TransportBase::Disconnect();
if (socket_event_ != WSA_INVALID_EVENT && !::WSACloseEvent(socket_event_)) {
TRACE_GDB_REMOTE("Transport::~Transport: Failed to close socket event\n");
}
socket_event_ = WSA_INVALID_EVENT;
SignalThreadEvent();
}
#else // _WIN32
Transport::Transport(SocketHandle s) : TransportBase(s) {
int fds[2];
#if defined(__linux__)
int ret = pipe2(fds, O_CLOEXEC);
#else
int ret = pipe(fds);
#endif
if (ret < 0) {
TRACE_GDB_REMOTE(
"Transport::Transport: Failed to allocate pipe for faulted thread\n");
}
faulted_thread_fd_read_ = fds[0];
faulted_thread_fd_write_ = fds[1];
}
Transport::~Transport() {
if (close(faulted_thread_fd_read_) != 0) {
TRACE_GDB_REMOTE("Transport::~Transport: Failed to close event\n");
}
if (close(faulted_thread_fd_write_) != 0) {
TRACE_GDB_REMOTE("Transport::~Transport: Failed to close event\n");
}
}
bool Transport::AcceptConnection() {
CHECK(handle_accept_ == InvalidSocket);
handle_accept_ = ::accept(handle_bind_, NULL, 0);
if (handle_accept_ != InvalidSocket) {
DisableNagleAlgorithm(handle_accept_);
return true;
}
return false;
}
bool Transport::ReadSomeData() {
while (true) {
ssize_t result =
::recv(handle_accept_, buf_.get() + size_, kBufSize - size_, 0);
if (result > 0) {
size_ += result;
return true;
}
if (result == 0) {
return false; // The connection was gracefully closed.
}
if (SocketGetLastError() != kErrInterrupt) {
return false;
}
}
}
void Transport::WaitForDebugStubEvent() {
// Don't wait if we already have data to read.
bool wait = !(pos_ < size_);
fd_set fds;
FD_ZERO(&fds);
FD_SET(faulted_thread_fd_read_, &fds);
int max_fd = faulted_thread_fd_read_;
if (size_ < kBufSize) {
FD_SET(handle_accept_, &fds);
max_fd = std::max(max_fd, handle_accept_);
}
int ret;
// We don't need sleep-polling on Linux now, so we set either zero or infinite
// timeout.
if (wait) {
ret = select(max_fd + 1, &fds, NULL, NULL, NULL);
} else {
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
ret = select(max_fd + 1, &fds, NULL, NULL, &timeout);
}
if (ret < 0) {
TRACE_GDB_REMOTE(
"Transport::WaitForDebugStubEvent: Failed to wait for "
"debug stub event\n");
}
if (ret > 0) {
if (FD_ISSET(faulted_thread_fd_read_, &fds)) {
char buf[16];
if (read(faulted_thread_fd_read_, &buf, sizeof(buf)) < 0) {
TRACE_GDB_REMOTE(
"Transport::WaitForDebugStubEvent: Failed to read from "
"debug stub event pipe fd\n");
}
}
if (FD_ISSET(handle_accept_, &fds)) ReadSomeData();
}
}
bool Transport::SignalThreadEvent() {
// Notify the debug stub by marking the thread as faulted.
char buf = 0;
if (write(faulted_thread_fd_write_, &buf, sizeof(buf)) != sizeof(buf)) {
TRACE_GDB_REMOTE("SignalThreadEvent: Can't send debug stub event\n");
return false;
}
return true;
}
#endif // _WIN32
} // namespace gdb_server
} // namespace wasm
} // namespace internal
} // namespace v8
#undef SD_BOTH
|