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 Status PipeWindows::CreateNew(bool child_process_inherit) {
43   // Even for anonymous pipes, we open a named pipe.  This is because you
44   // cannot get overlapped i/o on Windows without using a named pipe.  So we
45   // synthesize a unique name.
46   uint32_t serial = g_pipe_serial.fetch_add(1);
47   std::string pipe_name;
48   llvm::raw_string_ostream pipe_name_stream(pipe_name);
49   pipe_name_stream << "lldb.pipe." << ::GetCurrentProcessId() << "." << serial;
50   pipe_name_stream.flush();
51 
52   return CreateNew(pipe_name.c_str(), child_process_inherit);
53 }
54 
55 Status PipeWindows::CreateNew(llvm::StringRef name,
56                               bool child_process_inherit) {
57   if (name.empty())
58     return Status(ERROR_INVALID_PARAMETER, eErrorTypeWin32);
59 
60   if (CanRead() || CanWrite())
61     return Status(ERROR_ALREADY_EXISTS, eErrorTypeWin32);
62 
63   std::string pipe_path = "\\\\.\\Pipe\\";
64   pipe_path.append(name);
65 
66   // Always open for overlapped i/o.  We implement blocking manually in Read
67   // and Write.
68   DWORD read_mode = FILE_FLAG_OVERLAPPED;
69   m_read = ::CreateNamedPipeA(
70       pipe_path.c_str(), PIPE_ACCESS_INBOUND | read_mode,
71       PIPE_TYPE_BYTE | PIPE_WAIT, 1, 1024, 1024, 120 * 1000, NULL);
72   if (INVALID_HANDLE_VALUE == m_read)
73     return Status(::GetLastError(), eErrorTypeWin32);
74   m_read_fd = _open_osfhandle((intptr_t)m_read, _O_RDONLY);
75   ZeroMemory(&m_read_overlapped, sizeof(m_read_overlapped));
76   m_read_overlapped.hEvent = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
77 
78   // Open the write end of the pipe.
79   Status result = OpenNamedPipe(name, child_process_inherit, false);
80   if (!result.Success()) {
81     CloseReadFileDescriptor();
82     return result;
83   }
84 
85   return result;
86 }
87 
88 Status PipeWindows::CreateWithUniqueName(llvm::StringRef prefix,
89                                          bool child_process_inherit,
90                                          llvm::SmallVectorImpl<char> &name) {
91   llvm::SmallString<128> pipe_name;
92   Status error;
93   ::UUID unique_id;
94   RPC_CSTR unique_string;
95   RPC_STATUS status = ::UuidCreate(&unique_id);
96   if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
97     status = ::UuidToStringA(&unique_id, &unique_string);
98   if (status == RPC_S_OK) {
99     pipe_name = prefix;
100     pipe_name += "-";
101     pipe_name += reinterpret_cast<char *>(unique_string);
102     ::RpcStringFreeA(&unique_string);
103     error = CreateNew(pipe_name, child_process_inherit);
104   } else {
105     error.SetError(status, eErrorTypeWin32);
106   }
107   if (error.Success())
108     name = pipe_name;
109   return error;
110 }
111 
112 Status PipeWindows::OpenAsReader(llvm::StringRef name,
113                                  bool child_process_inherit) {
114   if (CanRead() || CanWrite())
115     return Status(ERROR_ALREADY_EXISTS, eErrorTypeWin32);
116 
117   return OpenNamedPipe(name, child_process_inherit, true);
118 }
119 
120 Status
121 PipeWindows::OpenAsWriterWithTimeout(llvm::StringRef name,
122                                      bool child_process_inherit,
123                                      const std::chrono::microseconds &timeout) {
124   if (CanRead() || CanWrite())
125     return Status(ERROR_ALREADY_EXISTS, eErrorTypeWin32);
126 
127   return OpenNamedPipe(name, child_process_inherit, false);
128 }
129 
130 Status PipeWindows::OpenNamedPipe(llvm::StringRef name,
131                                   bool child_process_inherit, bool is_read) {
132   if (name.empty())
133     return Status(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 Status(::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 Status(::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 Status();
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 Status PipeWindows::Delete(llvm::StringRef name) { return Status(); }
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 Status PipeWindows::ReadWithTimeout(void *buf, size_t size,
233                                     const std::chrono::microseconds &duration,
234                                     size_t &bytes_read) {
235   if (!CanRead())
236     return Status(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 Status(::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. Between the time we returned from WaitForSingleObject
252     // and the time we call CancelIoEx, the operation may complete.  If that
253     // hapens, CancelIoEx will fail and return ERROR_NOT_FOUND. If that
254     // happens, the original operation should be considered to have been
255     // successful.
256     bool failed = true;
257     DWORD failure_error = ::GetLastError();
258     if (wait_result == WAIT_TIMEOUT) {
259       BOOL cancel_result = CancelIoEx(m_read, &m_read_overlapped);
260       if (!cancel_result && GetLastError() == ERROR_NOT_FOUND)
261         failed = false;
262     }
263     if (failed)
264       return Status(failure_error, eErrorTypeWin32);
265   }
266 
267   // Now we call GetOverlappedResult setting bWait to false, since we've
268   // already waited as long as we're willing to.
269   if (!GetOverlappedResult(m_read, &m_read_overlapped, &sys_bytes_read, FALSE))
270     return Status(::GetLastError(), eErrorTypeWin32);
271 
272   bytes_read = sys_bytes_read;
273   return Status();
274 }
275 
276 Status PipeWindows::Write(const void *buf, size_t num_bytes,
277                           size_t &bytes_written) {
278   if (!CanWrite())
279     return Status(ERROR_INVALID_HANDLE, eErrorTypeWin32);
280 
281   DWORD sys_bytes_written = 0;
282   BOOL write_result = ::WriteFile(m_write, buf, num_bytes, &sys_bytes_written,
283                                   &m_write_overlapped);
284   if (!write_result && GetLastError() != ERROR_IO_PENDING)
285     return Status(::GetLastError(), eErrorTypeWin32);
286 
287   BOOL result = GetOverlappedResult(m_write, &m_write_overlapped,
288                                     &sys_bytes_written, TRUE);
289   if (!result)
290     return Status(::GetLastError(), eErrorTypeWin32);
291   return Status();
292 }
293