1 //===-- PipePosix.cpp -------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Host/posix/PipePosix.h"
11 #include "lldb/Host/FileSystem.h"
12 #include "lldb/Host/HostInfo.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/Support/FileSystem.h"
15 
16 #if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8))
17 #ifndef _GLIBCXX_USE_NANOSLEEP
18 #define _GLIBCXX_USE_NANOSLEEP
19 #endif
20 #endif
21 
22 #include <functional>
23 #include <thread>
24 
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <unistd.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 
32 using namespace lldb;
33 using namespace lldb_private;
34 
35 int PipePosix::kInvalidDescriptor = -1;
36 
37 enum PIPES { READ, WRITE }; // Constants 0 and 1 for READ and WRITE
38 
39 // pipe2 is supported by a limited set of platforms
40 // TODO: Add more platforms that support pipe2.
41 #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD__ >= 10) || defined(__NetBSD__)
42 #define PIPE2_SUPPORTED 1
43 #else
44 #define PIPE2_SUPPORTED 0
45 #endif
46 
47 namespace
48 {
49 
50 constexpr auto OPEN_WRITER_SLEEP_TIMEOUT_MSECS = 100;
51 
52 #if defined(FD_CLOEXEC) && !PIPE2_SUPPORTED
53 bool SetCloexecFlag(int fd)
54 {
55     int flags = ::fcntl(fd, F_GETFD);
56     if (flags == -1)
57         return false;
58     return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
59 }
60 #endif
61 
62 std::chrono::time_point<std::chrono::steady_clock>
63 Now()
64 {
65     return std::chrono::steady_clock::now();
66 }
67 
68 Error
69 SelectIO(int handle, bool is_read, const std::function<Error(bool&)> &io_handler, const std::chrono::microseconds &timeout)
70 {
71     Error error;
72     fd_set fds;
73     bool done = false;
74 
75     using namespace std::chrono;
76 
77     const auto finish_time = Now() + timeout;
78 
79     while (!done)
80     {
81         struct timeval tv = {0, 0};
82         if (timeout != microseconds::zero())
83         {
84             const auto remaining_dur = duration_cast<microseconds>(finish_time - Now());
85             if (remaining_dur.count() <= 0)
86             {
87                 error.SetErrorString("timeout exceeded");
88                 break;
89             }
90             const auto dur_secs = duration_cast<seconds>(remaining_dur);
91             const auto dur_usecs = remaining_dur % seconds(1);
92 
93             tv.tv_sec = dur_secs.count();
94             tv.tv_usec = dur_usecs.count();
95         }
96         else
97             tv.tv_sec = 1;
98 
99         FD_ZERO(&fds);
100         FD_SET(handle, &fds);
101 
102         const auto retval = ::select(handle + 1,
103                                      (is_read) ? &fds : nullptr,
104                                      (is_read) ? nullptr : &fds,
105                                      nullptr, &tv);
106         if (retval == -1)
107         {
108             if (errno == EINTR)
109                 continue;
110             error.SetErrorToErrno();
111             break;
112         }
113         if (retval == 0)
114         {
115             error.SetErrorString("timeout exceeded");
116             break;
117         }
118         if (!FD_ISSET(handle, &fds))
119         {
120             error.SetErrorString("invalid state");
121             break;
122         }
123 
124         error = io_handler(done);
125         if (error.Fail())
126         {
127           if (error.GetError() == EINTR)
128               continue;
129             break;
130         }
131     }
132     return error;
133 }
134 
135 }
136 
137 PipePosix::PipePosix()
138     : m_fds{
139         PipePosix::kInvalidDescriptor,
140         PipePosix::kInvalidDescriptor
141     } {}
142 
143 PipePosix::PipePosix(int read_fd, int write_fd)
144     : m_fds{read_fd, write_fd} {}
145 
146 PipePosix::PipePosix(PipePosix &&pipe_posix)
147     : PipeBase{std::move(pipe_posix)},
148       m_fds{
149         pipe_posix.ReleaseReadFileDescriptor(),
150         pipe_posix.ReleaseWriteFileDescriptor()
151       } {}
152 
153 PipePosix &PipePosix::operator=(PipePosix &&pipe_posix)
154 {
155     PipeBase::operator=(std::move(pipe_posix));
156     m_fds[READ] = pipe_posix.ReleaseReadFileDescriptor();
157     m_fds[WRITE] = pipe_posix.ReleaseWriteFileDescriptor();
158     return *this;
159 }
160 
161 PipePosix::~PipePosix()
162 {
163     Close();
164 }
165 
166 Error
167 PipePosix::CreateNew(bool child_processes_inherit)
168 {
169     if (CanRead() || CanWrite())
170         return Error(EINVAL, eErrorTypePOSIX);
171 
172     Error error;
173 #if PIPE2_SUPPORTED
174     if (::pipe2(m_fds, (child_processes_inherit) ? 0 : O_CLOEXEC) == 0)
175         return error;
176 #else
177     if (::pipe(m_fds) == 0)
178     {
179 #ifdef FD_CLOEXEC
180         if (!child_processes_inherit)
181         {
182             if (!SetCloexecFlag(m_fds[0]) || !SetCloexecFlag(m_fds[1]))
183             {
184                 error.SetErrorToErrno();
185                 Close();
186                 return error;
187             }
188         }
189 #endif
190         return error;
191     }
192 #endif
193 
194     error.SetErrorToErrno();
195     m_fds[READ] = PipePosix::kInvalidDescriptor;
196     m_fds[WRITE] = PipePosix::kInvalidDescriptor;
197     return error;
198 }
199 
200 Error
201 PipePosix::CreateNew(llvm::StringRef name, bool child_process_inherit)
202 {
203     if (CanRead() || CanWrite())
204         return Error("Pipe is already opened");
205 
206     Error error;
207     if (::mkfifo(name.data(), 0660) != 0)
208         error.SetErrorToErrno();
209 
210     return error;
211 }
212 
213 Error
214 PipePosix::CreateWithUniqueName(llvm::StringRef prefix, bool child_process_inherit, llvm::SmallVectorImpl<char>& name)
215 {
216     llvm::SmallString<PATH_MAX> named_pipe_path;
217     llvm::SmallString<PATH_MAX> pipe_spec((prefix + ".%%%%%%").str());
218     FileSpec tmpdir_file_spec;
219     tmpdir_file_spec.Clear();
220     if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
221     {
222         tmpdir_file_spec.AppendPathComponent(pipe_spec.c_str());
223     }
224     else
225     {
226         tmpdir_file_spec.AppendPathComponent("/tmp");
227         tmpdir_file_spec.AppendPathComponent(pipe_spec.c_str());
228     }
229 
230     // It's possible that another process creates the target path after we've
231     // verified it's available but before we create it, in which case we
232     // should try again.
233     Error error;
234     do {
235         llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath().c_str(), named_pipe_path);
236         error = CreateNew(named_pipe_path, child_process_inherit);
237     } while (error.GetError() == EEXIST);
238 
239     if (error.Success())
240         name = named_pipe_path;
241     return error;
242 }
243 
244 Error
245 PipePosix::OpenAsReader(llvm::StringRef name, bool child_process_inherit)
246 {
247     if (CanRead() || CanWrite())
248         return Error("Pipe is already opened");
249 
250     int flags = O_RDONLY | O_NONBLOCK;
251     if (!child_process_inherit)
252         flags |= O_CLOEXEC;
253 
254     Error error;
255     int fd = ::open(name.data(), flags);
256     if (fd != -1)
257         m_fds[READ] = fd;
258     else
259         error.SetErrorToErrno();
260 
261     return error;
262 }
263 
264 Error
265 PipePosix::OpenAsWriterWithTimeout(llvm::StringRef name, bool child_process_inherit, const std::chrono::microseconds &timeout)
266 {
267     if (CanRead() || CanWrite())
268         return Error("Pipe is already opened");
269 
270     int flags = O_WRONLY | O_NONBLOCK;
271     if (!child_process_inherit)
272         flags |= O_CLOEXEC;
273 
274     using namespace std::chrono;
275     const auto finish_time = Now() + timeout;
276 
277     while (!CanWrite())
278     {
279         if (timeout != microseconds::zero())
280         {
281             const auto dur = duration_cast<microseconds>(finish_time - Now()).count();
282             if (dur <= 0)
283                 return Error("timeout exceeded - reader hasn't opened so far");
284         }
285 
286         errno = 0;
287         int fd = ::open(name.data(), flags);
288         if (fd == -1)
289         {
290             const auto errno_copy = errno;
291             // We may get ENXIO if a reader side of the pipe hasn't opened yet.
292             if (errno_copy != ENXIO)
293                 return Error(errno_copy, eErrorTypePOSIX);
294 
295             std::this_thread::sleep_for(milliseconds(OPEN_WRITER_SLEEP_TIMEOUT_MSECS));
296         }
297         else
298         {
299             m_fds[WRITE] = fd;
300         }
301     }
302 
303     return Error();
304 }
305 
306 int
307 PipePosix::GetReadFileDescriptor() const
308 {
309     return m_fds[READ];
310 }
311 
312 int
313 PipePosix::GetWriteFileDescriptor() const
314 {
315     return m_fds[WRITE];
316 }
317 
318 int
319 PipePosix::ReleaseReadFileDescriptor()
320 {
321     const int fd = m_fds[READ];
322     m_fds[READ] = PipePosix::kInvalidDescriptor;
323     return fd;
324 }
325 
326 int
327 PipePosix::ReleaseWriteFileDescriptor()
328 {
329     const int fd = m_fds[WRITE];
330     m_fds[WRITE] = PipePosix::kInvalidDescriptor;
331     return fd;
332 }
333 
334 void
335 PipePosix::Close()
336 {
337     CloseReadFileDescriptor();
338     CloseWriteFileDescriptor();
339 }
340 
341 Error
342 PipePosix::Delete(llvm::StringRef name)
343 {
344     return FileSystem::Unlink(FileSpec{name.data(), true});
345 }
346 
347 bool
348 PipePosix::CanRead() const
349 {
350     return m_fds[READ] != PipePosix::kInvalidDescriptor;
351 }
352 
353 bool
354 PipePosix::CanWrite() const
355 {
356     return m_fds[WRITE] != PipePosix::kInvalidDescriptor;
357 }
358 
359 void
360 PipePosix::CloseReadFileDescriptor()
361 {
362     if (CanRead())
363     {
364         close(m_fds[READ]);
365         m_fds[READ] = PipePosix::kInvalidDescriptor;
366     }
367 }
368 
369 void
370 PipePosix::CloseWriteFileDescriptor()
371 {
372     if (CanWrite())
373     {
374         close(m_fds[WRITE]);
375         m_fds[WRITE] = PipePosix::kInvalidDescriptor;
376     }
377 }
378 
379 Error
380 PipePosix::ReadWithTimeout(void *buf, size_t size, const std::chrono::microseconds &timeout, size_t &bytes_read)
381 {
382     bytes_read = 0;
383     if (!CanRead())
384         return Error(EINVAL, eErrorTypePOSIX);
385 
386     auto handle = GetReadFileDescriptor();
387     return SelectIO(handle,
388                     true,
389                     [=, &bytes_read](bool &done)
390                     {
391                       Error error;
392                       auto result = ::read(handle,
393                                            reinterpret_cast<char*>(buf) + bytes_read,
394                                            size - bytes_read);
395                       if (result != -1)
396                       {
397                           bytes_read += result;
398                           if (bytes_read == size || result == 0)
399                               done = true;
400                       }
401                       else
402                           error.SetErrorToErrno();
403 
404                       return error;
405                   },
406                   timeout);
407 }
408 
409 Error
410 PipePosix::Write(const void *buf, size_t size, size_t &bytes_written)
411 {
412     bytes_written = 0;
413     if (!CanWrite())
414         return Error(EINVAL, eErrorTypePOSIX);
415 
416     auto handle = GetWriteFileDescriptor();
417     return SelectIO(handle,
418                     false,
419                     [=, &bytes_written](bool &done)
420                     {
421                         Error error;
422                         auto result = ::write(handle,
423                                               reinterpret_cast<const char*>(buf) + bytes_written,
424                                               size - bytes_written);
425                         if (result != -1)
426                         {
427                             bytes_written += result;
428                             if (bytes_written == size)
429                                 done = true;
430                         }
431                         else
432                             error.SetErrorToErrno();
433 
434                         return error;
435                     },
436                     std::chrono::microseconds::zero());
437 }
438