1 //===-- PipeWindows.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/windows/PipeWindows.h"
11 
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/Support/Process.h"
14 #include "llvm/Support/raw_ostream.h"
15 
16 #include <fcntl.h>
17 #include <io.h>
18 #include <rpc.h>
19 
20 #include <atomic>
21 #include <string>
22 
23 using namespace lldb;
24 using namespace lldb_private;
25 
26 namespace {
27 std::atomic<uint32_t> g_pipe_serial(0);
28 }
29 
30 PipeWindows::PipeWindows() {
31   m_read = INVALID_HANDLE_VALUE;
32   m_write = INVALID_HANDLE_VALUE;
33 
34   m_read_fd = -1;
35   m_write_fd = -1;
36   ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
37   ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
38 }
39 
40 PipeWindows::~PipeWindows() { Close(); }
41 
42 Error PipeWindows::CreateNew(bool child_process_inherit) {
43   // Even for anonymous pipes, we open a named pipe.  This is because you cannot
44   // get
45   // overlapped i/o on Windows without using a named pipe.  So we synthesize a
46   // unique
47   // name.
48   uint32_t serial = g_pipe_serial.fetch_add(1);
49   std::string pipe_name;
50   llvm::raw_string_ostream pipe_name_stream(pipe_name);
51   pipe_name_stream << "lldb.pipe." << ::GetCurrentProcessId() << "." << serial;
52   pipe_name_stream.flush();
53 
54   return CreateNew(pipe_name.c_str(), child_process_inherit);
55 }
56 
57 Error PipeWindows::CreateNew(llvm::StringRef name, bool child_process_inherit) {
58   if (name.empty())
59     return Error(ERROR_INVALID_PARAMETER, eErrorTypeWin32);
60 
61   if (CanRead() || CanWrite())
62     return Error(ERROR_ALREADY_EXISTS, eErrorTypeWin32);
63 
64   std::string pipe_path = "\\\\.\\Pipe\\";
65   pipe_path.append(name);
66 
67   // Always open for overlapped i/o.  We implement blocking manually in Read and
68   // Write.
69   DWORD read_mode = FILE_FLAG_OVERLAPPED;
70   m_read = ::CreateNamedPipeA(
71       pipe_path.c_str(), PIPE_ACCESS_INBOUND | read_mode,
72       PIPE_TYPE_BYTE | PIPE_WAIT, 1, 1024, 1024, 120 * 1000, NULL);
73   if (INVALID_HANDLE_VALUE == m_read)
74     return Error(::GetLastError(), eErrorTypeWin32);
75   m_read_fd = _open_osfhandle((intptr_t)m_read, _O_RDONLY);
76   ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
77   m_read_overlapped.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
78 
79   // Open the write end of the pipe.
80   Error result = OpenNamedPipe(name, child_process_inherit, false);
81   if (!result.Success()) {
82     CloseReadFileDescriptor();
83     return result;
84   }
85 
86   return result;
87 }
88 
89 Error PipeWindows::CreateWithUniqueName(llvm::StringRef prefix,
90                                         bool child_process_inherit,
91                                         llvm::SmallVectorImpl<char> &name) {
92   llvm::SmallString<128> pipe_name;
93   Error error;
94   ::UUID unique_id;
95   RPC_CSTR unique_string;
96   RPC_STATUS status = ::UuidCreate(&unique_id);
97   if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
98     status = ::UuidToStringA(&unique_id, &unique_string);
99   if (status == RPC_S_OK) {
100     pipe_name = prefix;
101     pipe_name += "-";
102     pipe_name += reinterpret_cast<char *>(unique_string);
103     ::RpcStringFreeA(&unique_string);
104     error = CreateNew(pipe_name, child_process_inherit);
105   } else {
106     error.SetError(status, eErrorTypeWin32);
107   }
108   if (error.Success())
109     name = pipe_name;
110   return error;
111 }
112 
113 Error PipeWindows::OpenAsReader(llvm::StringRef name,
114                                 bool child_process_inherit) {
115   if (CanRead() || CanWrite())
116     return Error(ERROR_ALREADY_EXISTS, eErrorTypeWin32);
117 
118   return OpenNamedPipe(name, child_process_inherit, true);
119 }
120 
121 Error PipeWindows::OpenAsWriterWithTimeout(
122     llvm::StringRef name, bool child_process_inherit,
123     const std::chrono::microseconds &timeout) {
124   if (CanRead() || CanWrite())
125     return Error(ERROR_ALREADY_EXISTS, eErrorTypeWin32);
126 
127   return OpenNamedPipe(name, child_process_inherit, false);
128 }
129 
130 Error PipeWindows::OpenNamedPipe(llvm::StringRef name,
131                                  bool child_process_inherit, bool is_read) {
132   if (name.empty())
133     return Error(ERROR_INVALID_PARAMETER, eErrorTypeWin32);
134 
135   assert(is_read ? !CanRead() : !CanWrite());
136 
137   SECURITY_ATTRIBUTES attributes = {};
138   attributes.bInheritHandle = child_process_inherit;
139 
140   std::string pipe_path = "\\\\.\\Pipe\\";
141   pipe_path.append(name);
142 
143   if (is_read) {
144     m_read = ::CreateFileA(pipe_path.c_str(), GENERIC_READ, 0, &attributes,
145                            OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
146     if (INVALID_HANDLE_VALUE == m_read)
147       return Error(::GetLastError(), eErrorTypeWin32);
148 
149     m_read_fd = _open_osfhandle((intptr_t)m_read, _O_RDONLY);
150 
151     ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
152     m_read_overlapped.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
153   } else {
154     m_write = ::CreateFileA(pipe_path.c_str(), GENERIC_WRITE, 0, &attributes,
155                             OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
156     if (INVALID_HANDLE_VALUE == m_write)
157       return Error(::GetLastError(), eErrorTypeWin32);
158 
159     m_write_fd = _open_osfhandle((intptr_t)m_write, _O_WRONLY);
160 
161     ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
162   }
163 
164   return Error();
165 }
166 
167 int PipeWindows::GetReadFileDescriptor() const { return m_read_fd; }
168 
169 int PipeWindows::GetWriteFileDescriptor() const { return m_write_fd; }
170 
171 int PipeWindows::ReleaseReadFileDescriptor() {
172   if (!CanRead())
173     return -1;
174   int result = m_read_fd;
175   m_read_fd = -1;
176   if (m_read_overlapped.hEvent)
177     ::CloseHandle(m_read_overlapped.hEvent);
178   m_read = INVALID_HANDLE_VALUE;
179   ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
180   return result;
181 }
182 
183 int PipeWindows::ReleaseWriteFileDescriptor() {
184   if (!CanWrite())
185     return -1;
186   int result = m_write_fd;
187   m_write_fd = -1;
188   m_write = INVALID_HANDLE_VALUE;
189   ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
190   return result;
191 }
192 
193 void PipeWindows::CloseReadFileDescriptor() {
194   if (!CanRead())
195     return;
196 
197   if (m_read_overlapped.hEvent)
198     ::CloseHandle(m_read_overlapped.hEvent);
199   _close(m_read_fd);
200   m_read = INVALID_HANDLE_VALUE;
201   m_read_fd = -1;
202   ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
203 }
204 
205 void PipeWindows::CloseWriteFileDescriptor() {
206   if (!CanWrite())
207     return;
208 
209   _close(m_write_fd);
210   m_write = INVALID_HANDLE_VALUE;
211   m_write_fd = -1;
212   ZeroMemory(&m_write_overlapped, sizeof(m_write_overlapped));
213 }
214 
215 void PipeWindows::Close() {
216   CloseReadFileDescriptor();
217   CloseWriteFileDescriptor();
218 }
219 
220 Error PipeWindows::Delete(llvm::StringRef name) { return Error(); }
221 
222 bool PipeWindows::CanRead() const { return (m_read != INVALID_HANDLE_VALUE); }
223 
224 bool PipeWindows::CanWrite() const { return (m_write != INVALID_HANDLE_VALUE); }
225 
226 HANDLE
227 PipeWindows::GetReadNativeHandle() { return m_read; }
228 
229 HANDLE
230 PipeWindows::GetWriteNativeHandle() { return m_write; }
231 
232 Error PipeWindows::ReadWithTimeout(void *buf, size_t size,
233                                    const std::chrono::microseconds &duration,
234                                    size_t &bytes_read) {
235   if (!CanRead())
236     return Error(ERROR_INVALID_HANDLE, eErrorTypeWin32);
237 
238   bytes_read = 0;
239   DWORD sys_bytes_read = size;
240   BOOL result = ::ReadFile(m_read, buf, sys_bytes_read, &sys_bytes_read,
241                            &m_read_overlapped);
242   if (!result && GetLastError() != ERROR_IO_PENDING)
243     return Error(::GetLastError(), eErrorTypeWin32);
244 
245   DWORD timeout = (duration == std::chrono::microseconds::zero())
246                       ? INFINITE
247                       : duration.count() * 1000;
248   DWORD wait_result = ::WaitForSingleObject(m_read_overlapped.hEvent, timeout);
249   if (wait_result != WAIT_OBJECT_0) {
250     // The operation probably failed.  However, if it timed out, we need to
251     // cancel the I/O.
252     // Between the time we returned from WaitForSingleObject and the time we
253     // call CancelIoEx,
254     // the operation may complete.  If that hapens, CancelIoEx will fail and
255     // return ERROR_NOT_FOUND.
256     // If that happens, the original operation should be considered to have been
257     // successful.
258     bool failed = true;
259     DWORD failure_error = ::GetLastError();
260     if (wait_result == WAIT_TIMEOUT) {
261       BOOL cancel_result = CancelIoEx(m_read, &m_read_overlapped);
262       if (!cancel_result && GetLastError() == ERROR_NOT_FOUND)
263         failed = false;
264     }
265     if (failed)
266       return Error(failure_error, eErrorTypeWin32);
267   }
268 
269   // Now we call GetOverlappedResult setting bWait to false, since we've already
270   // waited
271   // as long as we're willing to.
272   if (!GetOverlappedResult(m_read, &m_read_overlapped, &sys_bytes_read, FALSE))
273     return Error(::GetLastError(), eErrorTypeWin32);
274 
275   bytes_read = sys_bytes_read;
276   return Error();
277 }
278 
279 Error PipeWindows::Write(const void *buf, size_t num_bytes,
280                          size_t &bytes_written) {
281   if (!CanWrite())
282     return Error(ERROR_INVALID_HANDLE, eErrorTypeWin32);
283 
284   DWORD sys_bytes_written = 0;
285   BOOL write_result = ::WriteFile(m_write, buf, num_bytes, &sys_bytes_written,
286                                   &m_write_overlapped);
287   if (!write_result && GetLastError() != ERROR_IO_PENDING)
288     return Error(::GetLastError(), eErrorTypeWin32);
289 
290   BOOL result = GetOverlappedResult(m_write, &m_write_overlapped,
291                                     &sys_bytes_written, TRUE);
292   if (!result)
293     return Error(::GetLastError(), eErrorTypeWin32);
294   return Error();
295 }
296