aboutsummaryrefslogtreecommitdiff
path: root/source/Host/posix/PipePosix.cpp
blob: 0ed319facf93facb5e0fc96492992d797d3ac506 (plain) (blame)
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
//===-- PipePosix.cpp -------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Host/posix/PipePosix.h"
#include "lldb/Host/FileSystem.h"
#include "lldb/Host/HostInfo.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/FileSystem.h"

#include <functional>
#include <thread>

#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

using namespace lldb;
using namespace lldb_private;

int PipePosix::kInvalidDescriptor = -1;

enum PIPES { READ, WRITE }; // Constants 0 and 1 for READ and WRITE

// pipe2 is supported by Linux, FreeBSD v10 and higher.
// TODO: Add more platforms that support pipe2.
#if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD__ >= 10)
#define PIPE2_SUPPORTED 1
#else
#define PIPE2_SUPPORTED 0
#endif

namespace
{

constexpr auto OPEN_WRITER_SLEEP_TIMEOUT_MSECS = 100;

#if defined(FD_CLOEXEC) && !PIPE2_SUPPORTED
bool SetCloexecFlag(int fd)
{
    int flags = ::fcntl(fd, F_GETFD);
    if (flags == -1)
        return false;
    return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
}
#endif

std::chrono::time_point<std::chrono::steady_clock>
Now()
{
    return std::chrono::steady_clock::now();
}

Error
SelectIO(int handle, bool is_read, const std::function<Error(bool&)> &io_handler, const std::chrono::microseconds &timeout)
{
    Error error;
    fd_set fds;
    bool done = false;

    using namespace std::chrono;

    const auto finish_time = Now() + timeout;

    while (!done)
    {
        struct timeval tv = {0, 0};
        if (timeout != microseconds::zero())
        {
            const auto remaining_dur = duration_cast<microseconds>(finish_time - Now());
            if (remaining_dur.count() <= 0)
            {
                error.SetErrorString("timeout exceeded");
                break;
            }
            const auto dur_secs = duration_cast<seconds>(remaining_dur);
            const auto dur_usecs = remaining_dur % seconds(1);

            tv.tv_sec = dur_secs.count();
            tv.tv_usec = dur_usecs.count();
        }
        else
            tv.tv_sec = 1;

        FD_ZERO(&fds);
        FD_SET(handle, &fds);

        const auto retval = ::select(handle + 1,
                                     (is_read) ? &fds : nullptr,
                                     (is_read) ? nullptr : &fds,
                                     nullptr, &tv);
        if (retval == -1)
        {
            if (errno == EINTR)
                continue;
            error.SetErrorToErrno();
            break;
        }
        if (retval == 0)
        {
            error.SetErrorString("timeout exceeded");
            break;
        }
        if (!FD_ISSET(handle, &fds))
        {
            error.SetErrorString("invalid state");
            break;
        }

        error = io_handler(done);
        if (error.Fail())
        {
          if (error.GetError() == EINTR)
              continue;
            break;
        }
    }
    return error;
}

}

PipePosix::PipePosix()
    : m_fds{
        PipePosix::kInvalidDescriptor,
        PipePosix::kInvalidDescriptor
    } {}

PipePosix::PipePosix(int read_fd, int write_fd)
    : m_fds{read_fd, write_fd} {}

PipePosix::PipePosix(PipePosix &&pipe_posix)
    : PipeBase{std::move(pipe_posix)},
      m_fds{
        pipe_posix.ReleaseReadFileDescriptor(),
        pipe_posix.ReleaseWriteFileDescriptor()
      } {}

PipePosix &PipePosix::operator=(PipePosix &&pipe_posix)
{
    PipeBase::operator=(std::move(pipe_posix));
    m_fds[READ] = pipe_posix.ReleaseReadFileDescriptor();
    m_fds[WRITE] = pipe_posix.ReleaseWriteFileDescriptor();
    return *this;
}

PipePosix::~PipePosix()
{
    Close();
}

Error
PipePosix::CreateNew(bool child_processes_inherit)
{
    if (CanRead() || CanWrite())
        return Error(EINVAL, eErrorTypePOSIX);

    Error error;
#if PIPE2_SUPPORTED
    if (::pipe2(m_fds, (child_processes_inherit) ? 0 : O_CLOEXEC) == 0)
        return error;
#else
    if (::pipe(m_fds) == 0)
    {
#ifdef FD_CLOEXEC
        if (!child_processes_inherit)
        {
            if (!SetCloexecFlag(m_fds[0]) || !SetCloexecFlag(m_fds[1]))
            {
                error.SetErrorToErrno();
                Close();
                return error;
            }
        }
#endif
        return error;
    }
#endif

    error.SetErrorToErrno();
    m_fds[READ] = PipePosix::kInvalidDescriptor;
    m_fds[WRITE] = PipePosix::kInvalidDescriptor;
    return error;
}

Error
PipePosix::CreateNew(llvm::StringRef name, bool child_process_inherit)
{
    if (CanRead() || CanWrite())
        return Error("Pipe is already opened");

    Error error;
    if (::mkfifo(name.data(), 0660) != 0)
        error.SetErrorToErrno();

    return error;
}

Error
PipePosix::CreateWithUniqueName(llvm::StringRef prefix, bool child_process_inherit, llvm::SmallVectorImpl<char>& name)
{
    llvm::SmallString<PATH_MAX> named_pipe_path;
    llvm::SmallString<PATH_MAX> pipe_spec((prefix + ".%%%%%%").str());
    FileSpec tmpdir_file_spec;
    tmpdir_file_spec.Clear();
    if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
    {
        tmpdir_file_spec.AppendPathComponent(pipe_spec.c_str());
    }
    else
    {
        tmpdir_file_spec.AppendPathComponent("/tmp");
        tmpdir_file_spec.AppendPathComponent(pipe_spec.c_str());
    }

    // It's possible that another process creates the target path after we've
    // verified it's available but before we create it, in which case we
    // should try again.
    Error error;
    do {
        llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath().c_str(), named_pipe_path);
        error = CreateNew(named_pipe_path, child_process_inherit);
    } while (error.GetError() == EEXIST);

    if (error.Success())
        name = named_pipe_path;
    return error;
}

Error
PipePosix::OpenAsReader(llvm::StringRef name, bool child_process_inherit)
{
    if (CanRead() || CanWrite())
        return Error("Pipe is already opened");

    int flags = O_RDONLY | O_NONBLOCK;
    if (!child_process_inherit)
        flags |= O_CLOEXEC;

    Error error;
    int fd = ::open(name.data(), flags);
    if (fd != -1)
        m_fds[READ] = fd;
    else
        error.SetErrorToErrno();

    return error;
}

Error
PipePosix::OpenAsWriterWithTimeout(llvm::StringRef name, bool child_process_inherit, const std::chrono::microseconds &timeout)
{
    if (CanRead() || CanWrite())
        return Error("Pipe is already opened");

    int flags = O_WRONLY | O_NONBLOCK;
    if (!child_process_inherit)
        flags |= O_CLOEXEC;

    using namespace std::chrono;
    const auto finish_time = Now() + timeout;

    while (!CanWrite())
    {
        if (timeout != microseconds::zero())
        {
            const auto dur = duration_cast<microseconds>(finish_time - Now()).count();
            if (dur <= 0)
                return Error("timeout exceeded - reader hasn't opened so far");
        }

        errno = 0;
        int fd = ::open(name.data(), flags);
        if (fd == -1)
        {
            const auto errno_copy = errno;
            // We may get ENXIO if a reader side of the pipe hasn't opened yet.
            if (errno_copy != ENXIO)
                return Error(errno_copy, eErrorTypePOSIX);

            std::this_thread::sleep_for(milliseconds(OPEN_WRITER_SLEEP_TIMEOUT_MSECS));
        }
        else
        {
            m_fds[WRITE] = fd;
        }
    }

    return Error();
}

int
PipePosix::GetReadFileDescriptor() const
{
    return m_fds[READ];
}

int
PipePosix::GetWriteFileDescriptor() const
{
    return m_fds[WRITE];
}

int
PipePosix::ReleaseReadFileDescriptor()
{
    const int fd = m_fds[READ];
    m_fds[READ] = PipePosix::kInvalidDescriptor;
    return fd;
}

int
PipePosix::ReleaseWriteFileDescriptor()
{
    const int fd = m_fds[WRITE];
    m_fds[WRITE] = PipePosix::kInvalidDescriptor;
    return fd;
}

void
PipePosix::Close()
{
    CloseReadFileDescriptor();
    CloseWriteFileDescriptor();
}

Error
PipePosix::Delete(llvm::StringRef name)
{
    return FileSystem::Unlink(FileSpec{name.data(), true});
}

bool
PipePosix::CanRead() const
{
    return m_fds[READ] != PipePosix::kInvalidDescriptor;
}

bool
PipePosix::CanWrite() const
{
    return m_fds[WRITE] != PipePosix::kInvalidDescriptor;
}

void
PipePosix::CloseReadFileDescriptor()
{
    if (CanRead())
    {
        close(m_fds[READ]);
        m_fds[READ] = PipePosix::kInvalidDescriptor;
    }
}

void
PipePosix::CloseWriteFileDescriptor()
{
    if (CanWrite())
    {
        close(m_fds[WRITE]);
        m_fds[WRITE] = PipePosix::kInvalidDescriptor;
    }
}

Error
PipePosix::ReadWithTimeout(void *buf, size_t size, const std::chrono::microseconds &timeout, size_t &bytes_read)
{
    bytes_read = 0;
    if (!CanRead())
        return Error(EINVAL, eErrorTypePOSIX);

    auto handle = GetReadFileDescriptor();
    return SelectIO(handle,
                    true,
                    [=, &bytes_read](bool &done)
                    {
                      Error error;
                      auto result = ::read(handle,
                                           reinterpret_cast<char*>(buf) + bytes_read,
                                           size - bytes_read);
                      if (result != -1)
                      {
                          bytes_read += result;
                          if (bytes_read == size || result == 0)
                              done = true;
                      }
                      else
                          error.SetErrorToErrno();

                      return error;
                  },
                  timeout);
}

Error
PipePosix::Write(const void *buf, size_t size, size_t &bytes_written)
{
    bytes_written = 0;
    if (!CanWrite())
        return Error(EINVAL, eErrorTypePOSIX);

    auto handle = GetWriteFileDescriptor();
    return SelectIO(handle,
                    false,
                    [=, &bytes_written](bool &done)
                    {
                        Error error;
                        auto result = ::write(handle,
                                              reinterpret_cast<const char*>(buf) + bytes_written,
                                              size - bytes_written);
                        if (result != -1)
                        {
                            bytes_written += result;
                            if (bytes_written == size)
                                done = true;
                        }
                        else
                            error.SetErrorToErrno();

                        return error;
                    },
                    std::chrono::microseconds::zero());
}