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