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(const char *s,
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), s);
101 
102   if (strstr(s, "file://") != s) {
103     if (error_ptr)
104       error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'",
105                                           s);
106     return eConnectionStatusError;
107   }
108 
109   if (IsConnected()) {
110     ConnectionStatus status = Disconnect(error_ptr);
111     if (status != eConnectionStatusSuccess)
112       return status;
113   }
114 
115   // file://PATH
116   const char *path = s + strlen("file://");
117   // Open the file for overlapped access.  If it does not exist, create it.  We
118   // open it overlapped
119   // so that we can issue asynchronous reads and then use WaitForMultipleObjects
120   // to allow the read
121   // to be interrupted by an event object.
122   std::wstring wpath;
123   if (!llvm::ConvertUTF8toWide(path, wpath)) {
124     if (error_ptr)
125       error_ptr->SetError(1, eErrorTypeGeneric);
126     return eConnectionStatusError;
127   }
128   m_file = ::CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE,
129                          FILE_SHARE_READ, NULL, OPEN_ALWAYS,
130                          FILE_FLAG_OVERLAPPED, NULL);
131   if (m_file == INVALID_HANDLE_VALUE) {
132     if (error_ptr)
133       error_ptr->SetError(::GetLastError(), eErrorTypeWin32);
134     return eConnectionStatusError;
135   }
136 
137   m_owns_file = true;
138   m_uri.assign(s);
139   return eConnectionStatusSuccess;
140 }
141 
142 lldb::ConnectionStatus ConnectionGenericFile::Disconnect(Error *error_ptr) {
143   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
144   if (log)
145     log->Printf("%p ConnectionGenericFile::Disconnect ()",
146                 static_cast<void *>(this));
147 
148   if (!IsConnected())
149     return eConnectionStatusSuccess;
150 
151   // Reset the handle so that after we unblock any pending reads, subsequent
152   // calls to Read() will
153   // see a disconnected state.
154   HANDLE old_file = m_file;
155   m_file = INVALID_HANDLE_VALUE;
156 
157   // Set the disconnect event so that any blocking reads unblock, then cancel
158   // any pending IO operations.
159   ::CancelIoEx(old_file, &m_overlapped);
160 
161   // Close the file handle if we owned it, but don't close the event handles.
162   // We could always
163   // reconnect with the same Connection instance.
164   if (m_owns_file)
165     ::CloseHandle(old_file);
166 
167   ::ZeroMemory(&m_file_position, sizeof(m_file_position));
168   m_owns_file = false;
169   m_uri.clear();
170   return eConnectionStatusSuccess;
171 }
172 
173 size_t ConnectionGenericFile::Read(void *dst, size_t dst_len,
174                                    uint32_t timeout_usec,
175                                    lldb::ConnectionStatus &status,
176                                    Error *error_ptr) {
177   ReturnInfo return_info;
178   BOOL result = 0;
179   DWORD bytes_read = 0;
180 
181   if (error_ptr)
182     error_ptr->Clear();
183 
184   if (!IsConnected()) {
185     return_info.Set(0, eConnectionStatusNoConnection, ERROR_INVALID_HANDLE);
186     goto finish;
187   }
188 
189   m_overlapped.hEvent = m_event_handles[kBytesAvailableEvent];
190 
191   result = ::ReadFile(m_file, dst, dst_len, NULL, &m_overlapped);
192   if (result || ::GetLastError() == ERROR_IO_PENDING) {
193     if (!result) {
194       // The expected return path.  The operation is pending.  Wait for the
195       // operation to complete
196       // or be interrupted.
197       DWORD milliseconds = timeout_usec/1000;
198       DWORD wait_result =
199           ::WaitForMultipleObjects(llvm::array_lengthof(m_event_handles),
200                                    m_event_handles, FALSE, milliseconds);
201       // All of the events are manual reset events, so make sure we reset them
202       // to non-signalled.
203       switch (wait_result) {
204       case WAIT_OBJECT_0 + kBytesAvailableEvent:
205         break;
206       case WAIT_OBJECT_0 + kInterruptEvent:
207         return_info.Set(0, eConnectionStatusInterrupted, 0);
208         goto finish;
209       case WAIT_TIMEOUT:
210         return_info.Set(0, eConnectionStatusTimedOut, 0);
211         goto finish;
212       case WAIT_FAILED:
213         return_info.Set(0, eConnectionStatusError, ::GetLastError());
214         goto finish;
215       }
216     }
217     // The data is ready.  Figure out how much was read and return;
218     if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_read, FALSE)) {
219       DWORD result_error = ::GetLastError();
220       // ERROR_OPERATION_ABORTED occurs when someone calls Disconnect() during a
221       // blocking read.
222       // This triggers a call to CancelIoEx, which causes the operation to
223       // complete and the
224       // result to be ERROR_OPERATION_ABORTED.
225       if (result_error == ERROR_HANDLE_EOF ||
226           result_error == ERROR_OPERATION_ABORTED ||
227           result_error == ERROR_BROKEN_PIPE)
228         return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
229       else
230         return_info.Set(bytes_read, eConnectionStatusError, result_error);
231     } else if (bytes_read == 0)
232       return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
233     else
234       return_info.Set(bytes_read, eConnectionStatusSuccess, 0);
235 
236     goto finish;
237   } else if (::GetLastError() == ERROR_BROKEN_PIPE) {
238     // The write end of a pipe was closed.  This is equivalent to EOF.
239     return_info.Set(0, eConnectionStatusEndOfFile, 0);
240   } else {
241     // An unknown error occurred.  Fail out.
242     return_info.Set(0, eConnectionStatusError, ::GetLastError());
243   }
244   goto finish;
245 
246 finish:
247   status = return_info.GetStatus();
248   if (error_ptr)
249     *error_ptr = return_info.GetError();
250 
251   // kBytesAvailableEvent is a manual reset event.  Make sure it gets reset here
252   // so that any
253   // subsequent operations don't immediately see bytes available.
254   ResetEvent(m_event_handles[kBytesAvailableEvent]);
255 
256   IncrementFilePointer(return_info.GetBytes());
257   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
258   if (log) {
259     log->Printf("%p ConnectionGenericFile::Read()  handle = %p, dst = %p, "
260                 "dst_len = %zu) => %zu, error = %s",
261                 this, m_file, dst, dst_len, return_info.GetBytes(),
262                 return_info.GetError().AsCString());
263   }
264 
265   return return_info.GetBytes();
266 }
267 
268 size_t ConnectionGenericFile::Write(const void *src, size_t src_len,
269                                     lldb::ConnectionStatus &status,
270                                     Error *error_ptr) {
271   ReturnInfo return_info;
272   DWORD bytes_written = 0;
273   BOOL result = 0;
274 
275   if (error_ptr)
276     error_ptr->Clear();
277 
278   if (!IsConnected()) {
279     return_info.Set(0, eConnectionStatusNoConnection, ERROR_INVALID_HANDLE);
280     goto finish;
281   }
282 
283   m_overlapped.hEvent = NULL;
284 
285   // Writes are not interruptible like reads are, so just block until it's done.
286   result = ::WriteFile(m_file, src, src_len, NULL, &m_overlapped);
287   if (!result && ::GetLastError() != ERROR_IO_PENDING) {
288     return_info.Set(0, eConnectionStatusError, ::GetLastError());
289     goto finish;
290   }
291 
292   if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_written, TRUE)) {
293     return_info.Set(bytes_written, eConnectionStatusError, ::GetLastError());
294     goto finish;
295   }
296 
297   return_info.Set(bytes_written, eConnectionStatusSuccess, 0);
298   goto finish;
299 
300 finish:
301   status = return_info.GetStatus();
302   if (error_ptr)
303     *error_ptr = return_info.GetError();
304 
305   IncrementFilePointer(return_info.GetBytes());
306   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
307   if (log) {
308     log->Printf("%p ConnectionGenericFile::Write()  handle = %p, src = %p, "
309                 "src_len = %zu) => %zu, error = %s",
310                 this, m_file, src, src_len, return_info.GetBytes(),
311                 return_info.GetError().AsCString());
312   }
313   return return_info.GetBytes();
314 }
315 
316 std::string ConnectionGenericFile::GetURI() { return m_uri; }
317 
318 bool ConnectionGenericFile::InterruptRead() {
319   return ::SetEvent(m_event_handles[kInterruptEvent]);
320 }
321 
322 void ConnectionGenericFile::IncrementFilePointer(DWORD amount) {
323   LARGE_INTEGER old_pos;
324   old_pos.HighPart = m_overlapped.OffsetHigh;
325   old_pos.LowPart = m_overlapped.Offset;
326   old_pos.QuadPart += amount;
327   m_overlapped.Offset = old_pos.LowPart;
328   m_overlapped.OffsetHigh = old_pos.HighPart;
329 }
330