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