1 //===-- ConnectionGenericFileWindows.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/ConnectionGenericFileWindows.h"
11 #include "lldb/Utility/Log.h"
12 #include "lldb/Utility/Status.h"
13 #include "lldb/Utility/Timeout.h"
14 
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/Support/ConvertUTF.h"
18 
19 using namespace lldb;
20 using namespace lldb_private;
21 
22 namespace {
23 // This is a simple helper class to package up the information needed to return
24 // from a Read/Write
25 // operation function.  Since there is a lot of code to be run before exit
26 // regardless of whether the
27 // operation succeeded or failed, combined with many possible return paths, this
28 // is the cleanest
29 // way to represent it.
30 class ReturnInfo {
31 public:
32   void Set(size_t bytes, ConnectionStatus status, DWORD error_code) {
33     m_error.SetError(error_code, eErrorTypeWin32);
34     m_bytes = bytes;
35     m_status = status;
36   }
37 
38   void Set(size_t bytes, ConnectionStatus status, llvm::StringRef error_msg) {
39     m_error.SetErrorString(error_msg.data());
40     m_bytes = bytes;
41     m_status = status;
42   }
43 
44   size_t GetBytes() const { return m_bytes; }
45   ConnectionStatus GetStatus() const { return m_status; }
46   const Status &GetError() const { return m_error; }
47 
48 private:
49   Status m_error;
50   size_t m_bytes;
51   ConnectionStatus m_status;
52 };
53 }
54 
55 ConnectionGenericFile::ConnectionGenericFile()
56     : m_file(INVALID_HANDLE_VALUE), m_owns_file(false) {
57   ::ZeroMemory(&m_overlapped, sizeof(m_overlapped));
58   ::ZeroMemory(&m_file_position, sizeof(m_file_position));
59   InitializeEventHandles();
60 }
61 
62 ConnectionGenericFile::ConnectionGenericFile(lldb::file_t file, bool owns_file)
63     : m_file(file), m_owns_file(owns_file) {
64   ::ZeroMemory(&m_overlapped, sizeof(m_overlapped));
65   ::ZeroMemory(&m_file_position, sizeof(m_file_position));
66   InitializeEventHandles();
67 }
68 
69 ConnectionGenericFile::~ConnectionGenericFile() {
70   if (m_owns_file && IsConnected())
71     ::CloseHandle(m_file);
72 
73   ::CloseHandle(m_event_handles[kBytesAvailableEvent]);
74   ::CloseHandle(m_event_handles[kInterruptEvent]);
75 }
76 
77 void ConnectionGenericFile::InitializeEventHandles() {
78   m_event_handles[kInterruptEvent] = CreateEvent(NULL, FALSE, FALSE, NULL);
79 
80   // Note, we should use a manual reset event for the hEvent argument of the
81   // OVERLAPPED.  This
82   // is because both WaitForMultipleObjects and GetOverlappedResult (if you set
83   // the bWait
84   // argument to TRUE) will wait for the event to be signalled.  If we use an
85   // auto-reset event,
86   // WaitForMultipleObjects will reset the event, return successfully, and then
87   // GetOverlappedResult will block since the event is no longer signalled.
88   m_event_handles[kBytesAvailableEvent] =
89       ::CreateEvent(NULL, TRUE, FALSE, NULL);
90 }
91 
92 bool ConnectionGenericFile::IsConnected() const {
93   return m_file && (m_file != INVALID_HANDLE_VALUE);
94 }
95 
96 lldb::ConnectionStatus ConnectionGenericFile::Connect(llvm::StringRef path,
97                                                       Status *error_ptr) {
98   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
99   if (log)
100     log->Printf("%p ConnectionGenericFile::Connect (url = '%s')",
101                 static_cast<void *>(this), path.str().c_str());
102 
103   if (!path.consume_front("file://")) {
104     if (error_ptr)
105       error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'",
106                                           path.str().c_str());
107     return eConnectionStatusError;
108   }
109 
110   if (IsConnected()) {
111     ConnectionStatus status = Disconnect(error_ptr);
112     if (status != eConnectionStatusSuccess)
113       return status;
114   }
115 
116   // Open the file for overlapped access.  If it does not exist, create it.  We
117   // open it overlapped so that we can issue asynchronous reads and then use
118   // WaitForMultipleObjects to allow the read to be interrupted by an event
119   // object.
120   std::wstring wpath;
121   if (!llvm::ConvertUTF8toWide(path, wpath)) {
122     if (error_ptr)
123       error_ptr->SetError(1, eErrorTypeGeneric);
124     return eConnectionStatusError;
125   }
126   m_file = ::CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE,
127                          FILE_SHARE_READ, NULL, OPEN_ALWAYS,
128                          FILE_FLAG_OVERLAPPED, NULL);
129   if (m_file == INVALID_HANDLE_VALUE) {
130     if (error_ptr)
131       error_ptr->SetError(::GetLastError(), eErrorTypeWin32);
132     return eConnectionStatusError;
133   }
134 
135   m_owns_file = true;
136   m_uri.assign(path);
137   return eConnectionStatusSuccess;
138 }
139 
140 lldb::ConnectionStatus ConnectionGenericFile::Disconnect(Status *error_ptr) {
141   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
142   if (log)
143     log->Printf("%p ConnectionGenericFile::Disconnect ()",
144                 static_cast<void *>(this));
145 
146   if (!IsConnected())
147     return eConnectionStatusSuccess;
148 
149   // Reset the handle so that after we unblock any pending reads, subsequent
150   // calls to Read() will
151   // see a disconnected state.
152   HANDLE old_file = m_file;
153   m_file = INVALID_HANDLE_VALUE;
154 
155   // Set the disconnect event so that any blocking reads unblock, then cancel
156   // any pending IO operations.
157   ::CancelIoEx(old_file, &m_overlapped);
158 
159   // Close the file handle if we owned it, but don't close the event handles.
160   // We could always
161   // reconnect with the same Connection instance.
162   if (m_owns_file)
163     ::CloseHandle(old_file);
164 
165   ::ZeroMemory(&m_file_position, sizeof(m_file_position));
166   m_owns_file = false;
167   m_uri.clear();
168   return eConnectionStatusSuccess;
169 }
170 
171 size_t ConnectionGenericFile::Read(void *dst, size_t dst_len,
172                                    const Timeout<std::micro> &timeout,
173                                    lldb::ConnectionStatus &status,
174                                    Status *error_ptr) {
175   ReturnInfo return_info;
176   BOOL result = 0;
177   DWORD bytes_read = 0;
178 
179   if (error_ptr)
180     error_ptr->Clear();
181 
182   if (!IsConnected()) {
183     return_info.Set(0, eConnectionStatusNoConnection, ERROR_INVALID_HANDLE);
184     goto finish;
185   }
186 
187   m_overlapped.hEvent = m_event_handles[kBytesAvailableEvent];
188 
189   result = ::ReadFile(m_file, dst, dst_len, NULL, &m_overlapped);
190   if (result || ::GetLastError() == ERROR_IO_PENDING) {
191     if (!result) {
192       // The expected return path.  The operation is pending.  Wait for the
193       // operation to complete
194       // or be interrupted.
195       DWORD milliseconds =
196           timeout
197               ? std::chrono::duration_cast<std::chrono::milliseconds>(*timeout)
198                     .count()
199               : INFINITE;
200       DWORD wait_result =
201           ::WaitForMultipleObjects(llvm::array_lengthof(m_event_handles),
202                                    m_event_handles, FALSE, milliseconds);
203       // All of the events are manual reset events, so make sure we reset them
204       // to non-signalled.
205       switch (wait_result) {
206       case WAIT_OBJECT_0 + kBytesAvailableEvent:
207         break;
208       case WAIT_OBJECT_0 + kInterruptEvent:
209         return_info.Set(0, eConnectionStatusInterrupted, 0);
210         goto finish;
211       case WAIT_TIMEOUT:
212         return_info.Set(0, eConnectionStatusTimedOut, 0);
213         goto finish;
214       case WAIT_FAILED:
215         return_info.Set(0, eConnectionStatusError, ::GetLastError());
216         goto finish;
217       }
218     }
219     // The data is ready.  Figure out how much was read and return;
220     if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_read, FALSE)) {
221       DWORD result_error = ::GetLastError();
222       // ERROR_OPERATION_ABORTED occurs when someone calls Disconnect() during a
223       // blocking read.
224       // This triggers a call to CancelIoEx, which causes the operation to
225       // complete and the
226       // result to be ERROR_OPERATION_ABORTED.
227       if (result_error == ERROR_HANDLE_EOF ||
228           result_error == ERROR_OPERATION_ABORTED ||
229           result_error == ERROR_BROKEN_PIPE)
230         return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
231       else
232         return_info.Set(bytes_read, eConnectionStatusError, result_error);
233     } else if (bytes_read == 0)
234       return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
235     else
236       return_info.Set(bytes_read, eConnectionStatusSuccess, 0);
237 
238     goto finish;
239   } else if (::GetLastError() == ERROR_BROKEN_PIPE) {
240     // The write end of a pipe was closed.  This is equivalent to EOF.
241     return_info.Set(0, eConnectionStatusEndOfFile, 0);
242   } else {
243     // An unknown error occurred.  Fail out.
244     return_info.Set(0, eConnectionStatusError, ::GetLastError());
245   }
246   goto finish;
247 
248 finish:
249   status = return_info.GetStatus();
250   if (error_ptr)
251     *error_ptr = return_info.GetError();
252 
253   // kBytesAvailableEvent is a manual reset event.  Make sure it gets reset here
254   // so that any
255   // subsequent operations don't immediately see bytes available.
256   ResetEvent(m_event_handles[kBytesAvailableEvent]);
257 
258   IncrementFilePointer(return_info.GetBytes());
259   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
260   if (log) {
261     log->Printf("%p ConnectionGenericFile::Read()  handle = %p, dst = %p, "
262                 "dst_len = %zu) => %zu, error = %s",
263                 this, m_file, dst, dst_len, return_info.GetBytes(),
264                 return_info.GetError().AsCString());
265   }
266 
267   return return_info.GetBytes();
268 }
269 
270 size_t ConnectionGenericFile::Write(const void *src, size_t src_len,
271                                     lldb::ConnectionStatus &status,
272                                     Status *error_ptr) {
273   ReturnInfo return_info;
274   DWORD bytes_written = 0;
275   BOOL result = 0;
276 
277   if (error_ptr)
278     error_ptr->Clear();
279 
280   if (!IsConnected()) {
281     return_info.Set(0, eConnectionStatusNoConnection, ERROR_INVALID_HANDLE);
282     goto finish;
283   }
284 
285   m_overlapped.hEvent = NULL;
286 
287   // Writes are not interruptible like reads are, so just block until it's done.
288   result = ::WriteFile(m_file, src, src_len, NULL, &m_overlapped);
289   if (!result && ::GetLastError() != ERROR_IO_PENDING) {
290     return_info.Set(0, eConnectionStatusError, ::GetLastError());
291     goto finish;
292   }
293 
294   if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_written, TRUE)) {
295     return_info.Set(bytes_written, eConnectionStatusError, ::GetLastError());
296     goto finish;
297   }
298 
299   return_info.Set(bytes_written, eConnectionStatusSuccess, 0);
300   goto finish;
301 
302 finish:
303   status = return_info.GetStatus();
304   if (error_ptr)
305     *error_ptr = return_info.GetError();
306 
307   IncrementFilePointer(return_info.GetBytes());
308   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
309   if (log) {
310     log->Printf("%p ConnectionGenericFile::Write()  handle = %p, src = %p, "
311                 "src_len = %zu) => %zu, error = %s",
312                 this, m_file, src, src_len, return_info.GetBytes(),
313                 return_info.GetError().AsCString());
314   }
315   return return_info.GetBytes();
316 }
317 
318 std::string ConnectionGenericFile::GetURI() { return m_uri; }
319 
320 bool ConnectionGenericFile::InterruptRead() {
321   return ::SetEvent(m_event_handles[kInterruptEvent]);
322 }
323 
324 void ConnectionGenericFile::IncrementFilePointer(DWORD amount) {
325   LARGE_INTEGER old_pos;
326   old_pos.HighPart = m_overlapped.OffsetHigh;
327   old_pos.LowPart = m_overlapped.Offset;
328   old_pos.QuadPart += amount;
329   m_overlapped.Offset = old_pos.LowPart;
330   m_overlapped.OffsetHigh = old_pos.HighPart;
331 }
332