Coverage Report

Created: 2023-09-30 09:22

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