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