Coverage Report

Created: 2022-01-25 06:29

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- ConnectionFileDescriptorPosix.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
#if defined(__APPLE__)
10
// Enable this special support for Apple builds where we can have unlimited
11
// select bounds. We tried switching to poll() and kqueue and we were panicing
12
// the kernel, so we have to stick with select for now.
13
#define _DARWIN_UNLIMITED_SELECT
14
#endif
15
16
#include "lldb/Host/Config.h"
17
#include "lldb/Host/Socket.h"
18
#include "lldb/Host/SocketAddress.h"
19
#include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
20
#include "lldb/Utility/SelectHelper.h"
21
#include "lldb/Utility/Timeout.h"
22
23
#include <cerrno>
24
#include <cstdlib>
25
#include <cstring>
26
#include <fcntl.h>
27
#include <sys/types.h>
28
29
#if LLDB_ENABLE_POSIX
30
#include <termios.h>
31
#include <unistd.h>
32
#endif
33
34
#include <memory>
35
#include <sstream>
36
37
#include "llvm/Support/Errno.h"
38
#include "llvm/Support/ErrorHandling.h"
39
#if defined(__APPLE__)
40
#include "llvm/ADT/SmallVector.h"
41
#endif
42
#include "lldb/Host/Host.h"
43
#include "lldb/Host/Socket.h"
44
#include "lldb/Host/common/TCPSocket.h"
45
#include "lldb/Host/common/UDPSocket.h"
46
#include "lldb/Utility/Log.h"
47
#include "lldb/Utility/StreamString.h"
48
#include "lldb/Utility/Timer.h"
49
50
using namespace lldb;
51
using namespace lldb_private;
52
53
ConnectionFileDescriptor::ConnectionFileDescriptor(bool child_processes_inherit)
54
    : Connection(), m_pipe(), m_mutex(), m_shutting_down(false),
55
56
122
      m_child_processes_inherit(child_processes_inherit) {
57
122
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION |
58
122
                                                  LIBLLDB_LOG_OBJECT));
59
122
  LLDB_LOGF(log, "%p ConnectionFileDescriptor::ConnectionFileDescriptor ()",
60
122
            static_cast<void *>(this));
61
122
}
62
63
ConnectionFileDescriptor::ConnectionFileDescriptor(int fd, bool owns_fd)
64
    : Connection(), m_pipe(), m_mutex(), m_shutting_down(false),
65
5.24k
      m_child_processes_inherit(false) {
66
5.24k
  m_io_sp =
67
5.24k
      std::make_shared<NativeFile>(fd, File::eOpenOptionReadWrite, owns_fd);
68
69
5.24k
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION |
70
5.24k
                                                  LIBLLDB_LOG_OBJECT));
71
5.24k
  LLDB_LOGF(log,
72
5.24k
            "%p ConnectionFileDescriptor::ConnectionFileDescriptor (fd = "
73
5.24k
            "%i, owns_fd = %i)",
74
5.24k
            static_cast<void *>(this), fd, owns_fd);
75
5.24k
  OpenCommandPipe();
76
5.24k
}
77
78
ConnectionFileDescriptor::ConnectionFileDescriptor(Socket *socket)
79
    : Connection(), m_pipe(), m_mutex(), m_shutting_down(false),
80
31
      m_child_processes_inherit(false) {
81
31
  InitializeSocket(socket);
82
31
}
83
84
5.16k
ConnectionFileDescriptor::~ConnectionFileDescriptor() {
85
5.16k
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION |
86
5.16k
                                                  LIBLLDB_LOG_OBJECT));
87
5.16k
  LLDB_LOGF(log, "%p ConnectionFileDescriptor::~ConnectionFileDescriptor ()",
88
5.16k
            static_cast<void *>(this));
89
5.16k
  Disconnect(nullptr);
90
5.16k
  CloseCommandPipe();
91
5.16k
}
92
93
5.42k
void ConnectionFileDescriptor::OpenCommandPipe() {
94
5.42k
  CloseCommandPipe();
95
96
5.42k
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
97
  // Make the command file descriptor here:
98
5.42k
  Status result = m_pipe.CreateNew(m_child_processes_inherit);
99
5.42k
  if (!result.Success()) {
100
0
    LLDB_LOGF(log,
101
0
              "%p ConnectionFileDescriptor::OpenCommandPipe () - could not "
102
0
              "make pipe: %s",
103
0
              static_cast<void *>(this), result.AsCString());
104
5.42k
  } else {
105
5.42k
    LLDB_LOGF(log,
106
5.42k
              "%p ConnectionFileDescriptor::OpenCommandPipe() - success "
107
5.42k
              "readfd=%d writefd=%d",
108
5.42k
              static_cast<void *>(this), m_pipe.GetReadFileDescriptor(),
109
5.42k
              m_pipe.GetWriteFileDescriptor());
110
5.42k
  }
111
5.42k
}
112
113
10.5k
void ConnectionFileDescriptor::CloseCommandPipe() {
114
10.5k
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
115
10.5k
  LLDB_LOGF(log, "%p ConnectionFileDescriptor::CloseCommandPipe()",
116
10.5k
            static_cast<void *>(this));
117
118
10.5k
  m_pipe.Close();
119
10.5k
}
120
121
2.50M
bool ConnectionFileDescriptor::IsConnected() const {
122
2.50M
  return m_io_sp && 
m_io_sp->IsValid()2.50M
;
123
2.50M
}
124
125
ConnectionStatus ConnectionFileDescriptor::Connect(llvm::StringRef path,
126
188
                                                   Status *error_ptr) {
127
188
  return Connect(path, nullptr, error_ptr);
128
188
}
129
130
ConnectionStatus
131
ConnectionFileDescriptor::Connect(llvm::StringRef path,
132
                                  socket_id_callback_type socket_id_callback,
133
188
                                  Status *error_ptr) {
134
188
  std::lock_guard<std::recursive_mutex> guard(m_mutex);
135
188
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
136
188
  LLDB_LOGF(log, "%p ConnectionFileDescriptor::Connect (url = '%s')",
137
188
            static_cast<void *>(this), path.str().c_str());
138
139
188
  OpenCommandPipe();
140
141
188
  if (path.empty()) {
142
0
    if (error_ptr)
143
0
      error_ptr->SetErrorString("invalid connect arguments");
144
0
    return eConnectionStatusError;
145
0
  }
146
147
188
  llvm::StringRef scheme;
148
188
  std::tie(scheme, path) = path.split("://");
149
150
188
  if (!path.empty()) {
151
188
    auto method =
152
188
        llvm::StringSwitch<ConnectionStatus (ConnectionFileDescriptor::*)(
153
188
            llvm::StringRef, socket_id_callback_type, Status *)>(scheme)
154
188
            .Case("listen", &ConnectionFileDescriptor::AcceptTCP)
155
188
            .Cases("accept", "unix-accept",
156
188
                   &ConnectionFileDescriptor::AcceptNamedSocket)
157
188
            .Case("unix-abstract-accept",
158
188
                  &ConnectionFileDescriptor::AcceptAbstractSocket)
159
188
            .Cases("connect", "tcp-connect",
160
188
                   &ConnectionFileDescriptor::ConnectTCP)
161
188
            .Case("udp", &ConnectionFileDescriptor::ConnectUDP)
162
188
            .Case("unix-connect", &ConnectionFileDescriptor::ConnectNamedSocket)
163
188
            .Case("unix-abstract-connect",
164
188
                  &ConnectionFileDescriptor::ConnectAbstractSocket)
165
188
#if LLDB_ENABLE_POSIX
166
188
            .Case("fd", &ConnectionFileDescriptor::ConnectFD)
167
188
            .Case("file", &ConnectionFileDescriptor::ConnectFile)
168
188
            .Case("serial", &ConnectionFileDescriptor::ConnectSerialPort)
169
188
#endif
170
188
            .Default(nullptr);
171
172
188
    if (method) {
173
188
      if (error_ptr)
174
188
        *error_ptr = Status();
175
188
      return (this->*method)(path, socket_id_callback, error_ptr);
176
188
    }
177
188
  }
178
179
0
  if (error_ptr)
180
0
    error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'",
181
0
                                        path.str().c_str());
182
0
  return eConnectionStatusError;
183
188
}
184
185
19.2k
bool ConnectionFileDescriptor::InterruptRead() {
186
19.2k
  size_t bytes_written = 0;
187
19.2k
  Status result = m_pipe.Write("i", 1, bytes_written);
188
19.2k
  return result.Success();
189
19.2k
}
190
191
33.6k
ConnectionStatus ConnectionFileDescriptor::Disconnect(Status *error_ptr) {
192
33.6k
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
193
33.6k
  LLDB_LOGF(log, "%p ConnectionFileDescriptor::Disconnect ()",
194
33.6k
            static_cast<void *>(this));
195
196
33.6k
  ConnectionStatus status = eConnectionStatusSuccess;
197
198
33.6k
  if (!IsConnected()) {
199
28.2k
    LLDB_LOGF(
200
28.2k
        log, "%p ConnectionFileDescriptor::Disconnect(): Nothing to disconnect",
201
28.2k
        static_cast<void *>(this));
202
28.2k
    return eConnectionStatusSuccess;
203
28.2k
  }
204
205
5.39k
  if (m_io_sp->GetFdType() == IOObject::eFDTypeSocket)
206
149
    static_cast<Socket &>(*m_io_sp).PreDisconnect();
207
208
  // Try to get the ConnectionFileDescriptor's mutex.  If we fail, that is
209
  // quite likely because somebody is doing a blocking read on our file
210
  // descriptor.  If that's the case, then send the "q" char to the command
211
  // file channel so the read will wake up and the connection will then know to
212
  // shut down.
213
5.39k
  std::unique_lock<std::recursive_mutex> locker(m_mutex, std::defer_lock);
214
5.39k
  if (!locker.try_lock()) {
215
0
    if (m_pipe.CanWrite()) {
216
0
      size_t bytes_written = 0;
217
0
      Status result = m_pipe.Write("q", 1, bytes_written);
218
0
      LLDB_LOGF(log,
219
0
                "%p ConnectionFileDescriptor::Disconnect(): Couldn't get "
220
0
                "the lock, sent 'q' to %d, error = '%s'.",
221
0
                static_cast<void *>(this), m_pipe.GetWriteFileDescriptor(),
222
0
                result.AsCString());
223
0
    } else if (log) {
224
0
      LLDB_LOGF(log,
225
0
                "%p ConnectionFileDescriptor::Disconnect(): Couldn't get the "
226
0
                "lock, but no command pipe is available.",
227
0
                static_cast<void *>(this));
228
0
    }
229
0
    locker.lock();
230
0
  }
231
232
  // Prevents reads and writes during shutdown.
233
5.39k
  m_shutting_down = true;
234
235
5.39k
  Status error = m_io_sp->Close();
236
5.39k
  if (error.Fail())
237
0
    status = eConnectionStatusError;
238
5.39k
  if (error_ptr)
239
0
    *error_ptr = error;
240
241
  // Close any pipes we were using for async interrupts
242
5.39k
  m_pipe.Close();
243
244
5.39k
  m_uri.clear();
245
5.39k
  m_shutting_down = false;
246
5.39k
  return status;
247
33.6k
}
248
249
size_t ConnectionFileDescriptor::Read(void *dst, size_t dst_len,
250
                                      const Timeout<std::micro> &timeout,
251
                                      ConnectionStatus &status,
252
857k
                                      Status *error_ptr) {
253
857k
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
254
255
857k
  std::unique_lock<std::recursive_mutex> locker(m_mutex, std::defer_lock);
256
857k
  if (!locker.try_lock()) {
257
0
    LLDB_LOGF(log,
258
0
              "%p ConnectionFileDescriptor::Read () failed to get the "
259
0
              "connection lock.",
260
0
              static_cast<void *>(this));
261
0
    if (error_ptr)
262
0
      error_ptr->SetErrorString("failed to get the connection lock for read.");
263
264
0
    status = eConnectionStatusTimedOut;
265
0
    return 0;
266
0
  }
267
268
857k
  if (m_shutting_down) {
269
0
    if (error_ptr)
270
0
      error_ptr->SetErrorString("shutting down");
271
0
    status = eConnectionStatusError;
272
0
    return 0;
273
0
  }
274
275
857k
  status = BytesAvailable(timeout, error_ptr);
276
857k
  if (status != eConnectionStatusSuccess)
277
278k
    return 0;
278
279
578k
  Status error;
280
578k
  size_t bytes_read = dst_len;
281
578k
  error = m_io_sp->Read(dst, bytes_read);
282
283
578k
  if (log) {
284
0
    LLDB_LOGF(log,
285
0
              "%p ConnectionFileDescriptor::Read()  fd = %" PRIu64
286
0
              ", dst = %p, dst_len = %" PRIu64 ") => %" PRIu64 ", error = %s",
287
0
              static_cast<void *>(this),
288
0
              static_cast<uint64_t>(m_io_sp->GetWaitableHandle()),
289
0
              static_cast<void *>(dst), static_cast<uint64_t>(dst_len),
290
0
              static_cast<uint64_t>(bytes_read), error.AsCString());
291
0
  }
292
293
578k
  if (bytes_read == 0) {
294
2.64k
    error.Clear(); // End-of-file.  Do not automatically close; pass along for
295
                   // the end-of-file handlers.
296
2.64k
    status = eConnectionStatusEndOfFile;
297
2.64k
  }
298
299
578k
  if (error_ptr)
300
577k
    *error_ptr = error;
301
302
578k
  if (error.Fail()) {
303
0
    uint32_t error_value = error.GetError();
304
0
    switch (error_value) {
305
0
    case EAGAIN: // The file was marked for non-blocking I/O, and no data were
306
                 // ready to be read.
307
0
      if (m_io_sp->GetFdType() == IOObject::eFDTypeSocket)
308
0
        status = eConnectionStatusTimedOut;
309
0
      else
310
0
        status = eConnectionStatusSuccess;
311
0
      return 0;
312
313
0
    case EFAULT:  // Buf points outside the allocated address space.
314
0
    case EINTR:   // A read from a slow device was interrupted before any data
315
                  // arrived by the delivery of a signal.
316
0
    case EINVAL:  // The pointer associated with fildes was negative.
317
0
    case EIO:     // An I/O error occurred while reading from the file system.
318
                  // The process group is orphaned.
319
                  // The file is a regular file, nbyte is greater than 0, the
320
                  // starting position is before the end-of-file, and the
321
                  // starting position is greater than or equal to the offset
322
                  // maximum established for the open file descriptor
323
                  // associated with fildes.
324
0
    case EISDIR:  // An attempt is made to read a directory.
325
0
    case ENOBUFS: // An attempt to allocate a memory buffer fails.
326
0
    case ENOMEM:  // Insufficient memory is available.
327
0
      status = eConnectionStatusError;
328
0
      break; // Break to close....
329
330
0
    case ENOENT:     // no such file or directory
331
0
    case EBADF:      // fildes is not a valid file or socket descriptor open for
332
                     // reading.
333
0
    case ENXIO:      // An action is requested of a device that does not exist..
334
                     // A requested action cannot be performed by the device.
335
0
    case ECONNRESET: // The connection is closed by the peer during a read
336
                     // attempt on a socket.
337
0
    case ENOTCONN:   // A read is attempted on an unconnected socket.
338
0
      status = eConnectionStatusLostConnection;
339
0
      break; // Break to close....
340
341
0
    case ETIMEDOUT: // A transmission timeout occurs during a read attempt on a
342
                    // socket.
343
0
      status = eConnectionStatusTimedOut;
344
0
      return 0;
345
346
0
    default:
347
0
      LLDB_LOG(log, "this = {0}, unexpected error: {1}", this,
348
0
               llvm::sys::StrError(error_value));
349
0
      status = eConnectionStatusError;
350
0
      break; // Break to close....
351
0
    }
352
353
0
    return 0;
354
0
  }
355
578k
  return bytes_read;
356
578k
}
357
358
size_t ConnectionFileDescriptor::Write(const void *src, size_t src_len,
359
                                       ConnectionStatus &status,
360
419k
                                       Status *error_ptr) {
361
419k
  Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
362
419k
  LLDB_LOGF(log,
363
419k
            "%p ConnectionFileDescriptor::Write (src = %p, src_len = %" PRIu64
364
419k
            ")",
365
419k
            static_cast<void *>(this), static_cast<const void *>(src),
366
419k
            static_cast<uint64_t>(src_len));
367
368
419k
  if (!IsConnected()) {
369
0
    if (error_ptr)
370
0
      error_ptr->SetErrorString("not connected");
371
0
    status = eConnectionStatusNoConnection;
372
0
    return 0;
373
0
  }
374
375
419k
  if (m_shutting_down) {
376
0
    if (error_ptr)
377
0
      error_ptr->SetErrorString("shutting down");
378
0
    status = eConnectionStatusError;
379
0
    return 0;
380
0
  }
381
382
419k
  Status error;
383
384
419k
  size_t bytes_sent = src_len;
385
419k
  error = m_io_sp->Write(src, bytes_sent);
386
387
419k
  if (log) {
388
0
    LLDB_LOGF(log,
389
0
              "%p ConnectionFileDescriptor::Write(fd = %" PRIu64
390
0
              ", src = %p, src_len = %" PRIu64 ") => %" PRIu64 " (error = %s)",
391
0
              static_cast<void *>(this),
392
0
              static_cast<uint64_t>(m_io_sp->GetWaitableHandle()),
393
0
              static_cast<const void *>(src), static_cast<uint64_t>(src_len),
394
0
              static_cast<uint64_t>(bytes_sent), error.AsCString());
395
0
  }
396
397
419k
  if (error_ptr)
398
148
    *error_ptr = error;
399
400
419k
  if (error.Fail()) {
401
132
    switch (error.GetError()) {
402
132
    case EAGAIN:
403
132
    case EINTR:
404
132
      status = eConnectionStatusSuccess;
405
132
      return 0;
406
407
0
    case ECONNRESET: // The connection is closed by the peer during a read
408
                     // attempt on a socket.
409
0
    case ENOTCONN:   // A read is attempted on an unconnected socket.
410
0
      status = eConnectionStatusLostConnection;
411
0
      break; // Break to close....
412
413
0
    default:
414
0
      status = eConnectionStatusError;
415
0
      break; // Break to close....
416
132
    }
417
418
0
    return 0;
419
132
  }
420
421
419k
  status = eConnectionStatusSuccess;
422
419k
  return bytes_sent;
423
419k
}
424
425
2
std::string ConnectionFileDescriptor::GetURI() { return m_uri; }
426
427
// This ConnectionFileDescriptor::BytesAvailable() uses select() via
428
// SelectHelper
429
//
430
// PROS:
431
//  - select is consistent across most unix platforms
432
//  - The Apple specific version allows for unlimited fds in the fd_sets by
433
//    setting the _DARWIN_UNLIMITED_SELECT define prior to including the
434
//    required header files.
435
// CONS:
436
//  - on non-Apple platforms, only supports file descriptors up to FD_SETSIZE.
437
//     This implementation  will assert if it runs into that hard limit to let
438
//     users know that another ConnectionFileDescriptor::BytesAvailable() should
439
//     be used or a new version of ConnectionFileDescriptor::BytesAvailable()
440
//     should be written for the system that is running into the limitations.
441
442
ConnectionStatus
443
ConnectionFileDescriptor::BytesAvailable(const Timeout<std::micro> &timeout,
444
857k
                                         Status *error_ptr) {
445
  // Don't need to take the mutex here separately since we are only called from
446
  // Read.  If we ever get used more generally we will need to lock here as
447
  // well.
448
449
857k
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_CONNECTION));
450
857k
  LLDB_LOG(log, "this = {0}, timeout = {1}", this, timeout);
451
452
  // Make a copy of the file descriptors to make sure we don't have another
453
  // thread change these values out from under us and cause problems in the
454
  // loop below where like in FS_SET()
455
857k
  const IOObject::WaitableHandle handle = m_io_sp->GetWaitableHandle();
456
857k
  const int pipe_fd = m_pipe.GetReadFileDescriptor();
457
458
857k
  if (handle != IOObject::kInvalidHandleValue) {
459
857k
    SelectHelper select_helper;
460
857k
    if (timeout)
461
856k
      select_helper.SetTimeout(*timeout);
462
463
857k
    select_helper.FDSetRead(handle);
464
#if defined(_WIN32)
465
    // select() won't accept pipes on Windows.  The entire Windows codepath
466
    // needs to be converted over to using WaitForMultipleObjects and event
467
    // HANDLEs, but for now at least this will allow ::select() to not return
468
    // an error.
469
    const bool have_pipe_fd = false;
470
#else
471
857k
    const bool have_pipe_fd = pipe_fd >= 0;
472
857k
#endif
473
857k
    if (have_pipe_fd)
474
856k
      select_helper.FDSetRead(pipe_fd);
475
476
857k
    while (
handle == m_io_sp->GetWaitableHandle()857k
) {
477
478
857k
      Status error = select_helper.Select();
479
480
857k
      if (error_ptr)
481
856k
        *error_ptr = error;
482
483
857k
      if (error.Fail()) {
484
259k
        switch (error.GetError()) {
485
0
        case EBADF: // One of the descriptor sets specified an invalid
486
                    // descriptor.
487
0
          return eConnectionStatusLostConnection;
488
489
0
        case EINVAL: // The specified time limit is invalid. One of its
490
                     // components is negative or too large.
491
0
        default:     // Other unknown error
492
0
          return eConnectionStatusError;
493
494
259k
        case ETIMEDOUT:
495
259k
          return eConnectionStatusTimedOut;
496
497
0
        case EAGAIN: // The kernel was (perhaps temporarily) unable to
498
                     // allocate the requested number of file descriptors, or
499
                     // we have non-blocking IO
500
0
        case EINTR:  // A signal was delivered before the time limit
501
          // expired and before any of the selected events occurred.
502
0
          break; // Lets keep reading to until we timeout
503
259k
        }
504
597k
      } else {
505
597k
        if (select_helper.FDIsSetRead(handle))
506
578k
          return eConnectionStatusSuccess;
507
508
19.2k
        if (select_helper.FDIsSetRead(pipe_fd)) {
509
          // There is an interrupt or exit command in the command pipe Read the
510
          // data from that pipe:
511
19.2k
          char c;
512
513
19.2k
          ssize_t bytes_read =
514
19.2k
              llvm::sys::RetryAfterSignal(-1, ::read, pipe_fd, &c, 1);
515
19.2k
          assert(bytes_read == 1);
516
0
          (void)bytes_read;
517
19.2k
          switch (c) {
518
0
          case 'q':
519
0
            LLDB_LOGF(log,
520
0
                      "%p ConnectionFileDescriptor::BytesAvailable() "
521
0
                      "got data: %c from the command channel.",
522
0
                      static_cast<void *>(this), c);
523
0
            return eConnectionStatusEndOfFile;
524
19.2k
          case 'i':
525
            // Interrupt the current read
526
19.2k
            return eConnectionStatusInterrupted;
527
19.2k
          }
528
19.2k
        }
529
19.2k
      }
530
857k
    }
531
857k
  }
532
533
18.4E
  if (error_ptr)
534
0
    error_ptr->SetErrorString("not connected");
535
18.4E
  return eConnectionStatusLostConnection;
536
857k
}
537
538
lldb::ConnectionStatus ConnectionFileDescriptor::AcceptSocket(
539
    Socket::SocketProtocol socket_protocol, llvm::StringRef socket_name,
540
    llvm::function_ref<void(Socket &)> post_listen_callback,
541
0
    Status *error_ptr) {
542
0
  Status error;
543
0
  std::unique_ptr<Socket> listening_socket =
544
0
      Socket::Create(socket_protocol, m_child_processes_inherit, error);
545
0
  Socket *accepted_socket;
546
547
0
  if (!error.Fail())
548
0
    error = listening_socket->Listen(socket_name, 5);
549
550
0
  if (!error.Fail()) {
551
0
    post_listen_callback(*listening_socket);
552
0
    error = listening_socket->Accept(accepted_socket);
553
0
  }
554
555
0
  if (!error.Fail()) {
556
0
    m_io_sp.reset(accepted_socket);
557
0
    m_uri.assign(socket_name.str());
558
0
    return eConnectionStatusSuccess;
559
0
  }
560
561
0
  if (error_ptr)
562
0
    *error_ptr = error;
563
0
  return eConnectionStatusError;
564
0
}
565
566
lldb::ConnectionStatus
567
ConnectionFileDescriptor::ConnectSocket(Socket::SocketProtocol socket_protocol,
568
                                        llvm::StringRef socket_name,
569
184
                                        Status *error_ptr) {
570
184
  Status error;
571
184
  std::unique_ptr<Socket> socket =
572
184
      Socket::Create(socket_protocol, m_child_processes_inherit, error);
573
574
184
  if (!error.Fail())
575
184
    error = socket->Connect(socket_name);
576
577
184
  if (!error.Fail()) {
578
118
    m_io_sp = std::move(socket);
579
118
    m_uri.assign(socket_name.str());
580
118
    return eConnectionStatusSuccess;
581
118
  }
582
583
66
  if (error_ptr)
584
66
    *error_ptr = error;
585
66
  return eConnectionStatusError;
586
184
}
587
588
ConnectionStatus ConnectionFileDescriptor::AcceptNamedSocket(
589
    llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,
590
0
    Status *error_ptr) {
591
0
  return AcceptSocket(
592
0
      Socket::ProtocolUnixDomain, socket_name,
593
0
      [socket_id_callback, socket_name](Socket &listening_socket) {
594
0
        socket_id_callback(socket_name);
595
0
      },
596
0
      error_ptr);
597
0
}
598
599
ConnectionStatus ConnectionFileDescriptor::ConnectNamedSocket(
600
    llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,
601
72
    Status *error_ptr) {
602
72
  return ConnectSocket(Socket::ProtocolUnixDomain, socket_name, error_ptr);
603
72
}
604
605
ConnectionStatus ConnectionFileDescriptor::AcceptAbstractSocket(
606
    llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,
607
0
    Status *error_ptr) {
608
0
  return AcceptSocket(
609
0
      Socket::ProtocolUnixAbstract, socket_name,
610
0
      [socket_id_callback, socket_name](Socket &listening_socket) {
611
0
        socket_id_callback(socket_name);
612
0
      },
613
0
      error_ptr);
614
0
}
615
616
lldb::ConnectionStatus ConnectionFileDescriptor::ConnectAbstractSocket(
617
    llvm::StringRef socket_name, socket_id_callback_type socket_id_callback,
618
0
    Status *error_ptr) {
619
0
  return ConnectSocket(Socket::ProtocolUnixAbstract, socket_name, error_ptr);
620
0
}
621
622
ConnectionStatus
623
ConnectionFileDescriptor::AcceptTCP(llvm::StringRef socket_name,
624
                                    socket_id_callback_type socket_id_callback,
625
0
                                    Status *error_ptr) {
626
0
  ConnectionStatus ret = AcceptSocket(
627
0
      Socket::ProtocolTcp, socket_name,
628
0
      [socket_id_callback](Socket &listening_socket) {
629
0
        uint16_t port =
630
0
            static_cast<TCPSocket &>(listening_socket).GetLocalPortNumber();
631
0
        socket_id_callback(std::to_string(port));
632
0
      },
633
0
      error_ptr);
634
0
  if (ret == eConnectionStatusSuccess)
635
0
    m_uri.assign(
636
0
        static_cast<TCPSocket *>(m_io_sp.get())->GetRemoteConnectionURI());
637
0
  return ret;
638
0
}
639
640
ConnectionStatus
641
ConnectionFileDescriptor::ConnectTCP(llvm::StringRef socket_name,
642
                                     socket_id_callback_type socket_id_callback,
643
112
                                     Status *error_ptr) {
644
112
  return ConnectSocket(Socket::ProtocolTcp, socket_name, error_ptr);
645
112
}
646
647
ConnectionStatus
648
ConnectionFileDescriptor::ConnectUDP(llvm::StringRef s,
649
                                     socket_id_callback_type socket_id_callback,
650
0
                                     Status *error_ptr) {
651
0
  if (error_ptr)
652
0
    *error_ptr = Status();
653
0
  llvm::Expected<std::unique_ptr<UDPSocket>> socket =
654
0
      Socket::UdpConnect(s, m_child_processes_inherit);
655
0
  if (!socket) {
656
0
    if (error_ptr)
657
0
      *error_ptr = socket.takeError();
658
0
    else
659
0
      LLDB_LOG_ERROR(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION),
660
0
                     socket.takeError(), "tcp connect failed: {0}");
661
0
    return eConnectionStatusError;
662
0
  }
663
0
  m_io_sp = std::move(*socket);
664
0
  m_uri.assign(std::string(s));
665
0
  return eConnectionStatusSuccess;
666
0
}
667
668
ConnectionStatus
669
ConnectionFileDescriptor::ConnectFD(llvm::StringRef s,
670
                                    socket_id_callback_type socket_id_callback,
671
0
                                    Status *error_ptr) {
672
0
#if LLDB_ENABLE_POSIX
673
  // Just passing a native file descriptor within this current process that
674
  // is already opened (possibly from a service or other source).
675
0
  int fd = -1;
676
677
0
  if (!s.getAsInteger(0, fd)) {
678
    // We have what looks to be a valid file descriptor, but we should make
679
    // sure it is. We currently are doing this by trying to get the flags
680
    // from the file descriptor and making sure it isn't a bad fd.
681
0
    errno = 0;
682
0
    int flags = ::fcntl(fd, F_GETFL, 0);
683
0
    if (flags == -1 || errno == EBADF) {
684
0
      if (error_ptr)
685
0
        error_ptr->SetErrorStringWithFormat("stale file descriptor: %s",
686
0
                                            s.str().c_str());
687
0
      m_io_sp.reset();
688
0
      return eConnectionStatusError;
689
0
    } else {
690
      // Don't take ownership of a file descriptor that gets passed to us
691
      // since someone else opened the file descriptor and handed it to us.
692
      // TODO: Since are using a URL to open connection we should
693
      // eventually parse options using the web standard where we have
694
      // "fd://123?opt1=value;opt2=value" and we can have an option be
695
      // "owns=1" or "owns=0" or something like this to allow us to specify
696
      // this. For now, we assume we must assume we don't own it.
697
698
0
      std::unique_ptr<TCPSocket> tcp_socket;
699
0
      tcp_socket = std::make_unique<TCPSocket>(fd, false, false);
700
      // Try and get a socket option from this file descriptor to see if
701
      // this is a socket and set m_is_socket accordingly.
702
0
      int resuse;
703
0
      bool is_socket =
704
0
          !!tcp_socket->GetOption(SOL_SOCKET, SO_REUSEADDR, resuse);
705
0
      if (is_socket)
706
0
        m_io_sp = std::move(tcp_socket);
707
0
      else
708
0
        m_io_sp =
709
0
            std::make_shared<NativeFile>(fd, File::eOpenOptionReadWrite, false);
710
0
      m_uri = s.str();
711
0
      return eConnectionStatusSuccess;
712
0
    }
713
0
  }
714
715
0
  if (error_ptr)
716
0
    error_ptr->SetErrorStringWithFormat("invalid file descriptor: \"%s\"",
717
0
                                        s.str().c_str());
718
0
  m_io_sp.reset();
719
0
  return eConnectionStatusError;
720
0
#endif // LLDB_ENABLE_POSIX
721
0
  llvm_unreachable("this function should be only called w/ LLDB_ENABLE_POSIX");
722
0
}
723
724
ConnectionStatus ConnectionFileDescriptor::ConnectFile(
725
    llvm::StringRef s, socket_id_callback_type socket_id_callback,
726
1
    Status *error_ptr) {
727
1
#if LLDB_ENABLE_POSIX
728
1
  std::string addr_str = s.str();
729
  // file:///PATH
730
1
  int fd = llvm::sys::RetryAfterSignal(-1, ::open, addr_str.c_str(), O_RDWR);
731
1
  if (fd == -1) {
732
0
    if (error_ptr)
733
0
      error_ptr->SetErrorToErrno();
734
0
    return eConnectionStatusError;
735
0
  }
736
737
1
  if (::isatty(fd)) {
738
    // Set up serial terminal emulation
739
1
    struct termios options;
740
1
    ::tcgetattr(fd, &options);
741
742
    // Set port speed to maximum
743
1
    ::cfsetospeed(&options, B115200);
744
1
    ::cfsetispeed(&options, B115200);
745
746
    // Raw input, disable echo and signals
747
1
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
748
749
    // Make sure only one character is needed to return from a read
750
1
    options.c_cc[VMIN] = 1;
751
1
    options.c_cc[VTIME] = 0;
752
753
1
    llvm::sys::RetryAfterSignal(-1, ::tcsetattr, fd, TCSANOW, &options);
754
1
  }
755
756
1
  m_io_sp = std::make_shared<NativeFile>(fd, File::eOpenOptionReadWrite, true);
757
1
  return eConnectionStatusSuccess;
758
0
#endif // LLDB_ENABLE_POSIX
759
0
  llvm_unreachable("this function should be only called w/ LLDB_ENABLE_POSIX");
760
0
}
761
762
ConnectionStatus ConnectionFileDescriptor::ConnectSerialPort(
763
    llvm::StringRef s, socket_id_callback_type socket_id_callback,
764
3
    Status *error_ptr) {
765
3
#if LLDB_ENABLE_POSIX
766
3
  llvm::StringRef path, qs;
767
  // serial:///PATH?k1=v1&k2=v2...
768
3
  std::tie(path, qs) = s.split('?');
769
770
3
  llvm::Expected<SerialPort::Options> serial_options =
771
3
      SerialPort::OptionsFromURL(qs);
772
3
  if (!serial_options) {
773
0
    if (error_ptr)
774
0
      *error_ptr = serial_options.takeError();
775
0
    else
776
0
      llvm::consumeError(serial_options.takeError());
777
0
    return eConnectionStatusError;
778
0
  }
779
780
3
  int fd = llvm::sys::RetryAfterSignal(-1, ::open, path.str().c_str(), O_RDWR);
781
3
  if (fd == -1) {
782
0
    if (error_ptr)
783
0
      error_ptr->SetErrorToErrno();
784
0
    return eConnectionStatusError;
785
0
  }
786
787
3
  llvm::Expected<std::unique_ptr<SerialPort>> serial_sp = SerialPort::Create(
788
3
      fd, File::eOpenOptionReadWrite, serial_options.get(), true);
789
3
  if (!serial_sp) {
790
0
    if (error_ptr)
791
0
      *error_ptr = serial_sp.takeError();
792
0
    else
793
0
      llvm::consumeError(serial_sp.takeError());
794
0
    return eConnectionStatusError;
795
0
  }
796
3
  m_io_sp = std::move(serial_sp.get());
797
798
3
  return eConnectionStatusSuccess;
799
0
#endif // LLDB_ENABLE_POSIX
800
0
  llvm_unreachable("this function should be only called w/ LLDB_ENABLE_POSIX");
801
0
}
802
803
0
bool ConnectionFileDescriptor::GetChildProcessesInherit() const {
804
0
  return m_child_processes_inherit;
805
0
}
806
807
void ConnectionFileDescriptor::SetChildProcessesInherit(
808
0
    bool child_processes_inherit) {
809
0
  m_child_processes_inherit = child_processes_inherit;
810
0
}
811
812
31
void ConnectionFileDescriptor::InitializeSocket(Socket *socket) {
813
31
  m_io_sp.reset(socket);
814
31
  m_uri = socket->GetRemoteConnectionURI();
815
31
}