1 //===-- ConnectionGenericFileWindows.cpp ------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Host/windows/ConnectionGenericFileWindows.h"
11 #include "lldb/Core/Error.h"
12 #include "lldb/Core/Log.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/Support/ConvertUTF.h"
19 using namespace lldb_private;
22 // This is a simple helper class to package up the information needed to return
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
28 // way to represent it.
31 void Set(size_t bytes, ConnectionStatus status, DWORD error_code) {
32 m_error.SetError(error_code, eErrorTypeWin32);
37 void Set(size_t bytes, ConnectionStatus status, llvm::StringRef error_msg) {
38 m_error.SetErrorString(error_msg.data());
43 size_t GetBytes() const { return m_bytes; }
44 ConnectionStatus GetStatus() const { return m_status; }
45 const Error &GetError() const { return m_error; }
50 ConnectionStatus m_status;
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();
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();
68 ConnectionGenericFile::~ConnectionGenericFile() {
69 if (m_owns_file && IsConnected())
70 ::CloseHandle(m_file);
72 ::CloseHandle(m_event_handles[kBytesAvailableEvent]);
73 ::CloseHandle(m_event_handles[kInterruptEvent]);
76 void ConnectionGenericFile::InitializeEventHandles() {
77 m_event_handles[kInterruptEvent] = CreateEvent(NULL, FALSE, FALSE, NULL);
79 // Note, we should use a manual reset event for the hEvent argument of the
81 // is because both WaitForMultipleObjects and GetOverlappedResult (if you set
83 // argument to TRUE) will wait for the event to be signalled. If we use an
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);
91 bool ConnectionGenericFile::IsConnected() const {
92 return m_file && (m_file != INVALID_HANDLE_VALUE);
95 lldb::ConnectionStatus ConnectionGenericFile::Connect(llvm::StringRef path,
97 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
99 log->Printf("%p ConnectionGenericFile::Connect (url = '%s')",
100 static_cast<void *>(this), path.str().c_str());
102 if (!path.consume_front("file://")) {
104 error_ptr->SetErrorStringWithFormat("unsupported connection URL: '%s'",
106 return eConnectionStatusError;
110 ConnectionStatus status = Disconnect(error_ptr);
111 if (status != eConnectionStatusSuccess)
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
120 if (!llvm::ConvertUTF8toWide(path, wpath)) {
122 error_ptr->SetError(1, eErrorTypeGeneric);
123 return eConnectionStatusError;
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) {
130 error_ptr->SetError(::GetLastError(), eErrorTypeWin32);
131 return eConnectionStatusError;
136 return eConnectionStatusSuccess;
139 lldb::ConnectionStatus ConnectionGenericFile::Disconnect(Error *error_ptr) {
140 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
142 log->Printf("%p ConnectionGenericFile::Disconnect ()",
143 static_cast<void *>(this));
146 return eConnectionStatusSuccess;
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;
154 // Set the disconnect event so that any blocking reads unblock, then cancel
155 // any pending IO operations.
156 ::CancelIoEx(old_file, &m_overlapped);
158 // Close the file handle if we owned it, but don't close the event handles.
160 // reconnect with the same Connection instance.
162 ::CloseHandle(old_file);
164 ::ZeroMemory(&m_file_position, sizeof(m_file_position));
167 return eConnectionStatusSuccess;
170 size_t ConnectionGenericFile::Read(void *dst, size_t dst_len,
171 const Timeout<std::micro> &timeout,
172 lldb::ConnectionStatus &status,
174 ReturnInfo return_info;
176 DWORD bytes_read = 0;
181 if (!IsConnected()) {
182 return_info.Set(0, eConnectionStatusNoConnection, ERROR_INVALID_HANDLE);
186 m_overlapped.hEvent = m_event_handles[kBytesAvailableEvent];
188 result = ::ReadFile(m_file, dst, dst_len, NULL, &m_overlapped);
189 if (result || ::GetLastError() == ERROR_IO_PENDING) {
191 // The expected return path. The operation is pending. Wait for the
192 // operation to complete
193 // or be interrupted.
196 ? std::chrono::duration_cast<std::chrono::milliseconds>(*timeout)
200 ::WaitForMultipleObjects(llvm::array_lengthof(m_event_handles),
201 m_event_handles, FALSE, milliseconds);
202 // All of the events are manual reset events, so make sure we reset them
204 switch (wait_result) {
205 case WAIT_OBJECT_0 + kBytesAvailableEvent:
207 case WAIT_OBJECT_0 + kInterruptEvent:
208 return_info.Set(0, eConnectionStatusInterrupted, 0);
211 return_info.Set(0, eConnectionStatusTimedOut, 0);
214 return_info.Set(0, eConnectionStatusError, ::GetLastError());
218 // The data is ready. Figure out how much was read and return;
219 if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_read, FALSE)) {
220 DWORD result_error = ::GetLastError();
221 // ERROR_OPERATION_ABORTED occurs when someone calls Disconnect() during a
223 // This triggers a call to CancelIoEx, which causes the operation to
225 // result to be ERROR_OPERATION_ABORTED.
226 if (result_error == ERROR_HANDLE_EOF ||
227 result_error == ERROR_OPERATION_ABORTED ||
228 result_error == ERROR_BROKEN_PIPE)
229 return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
231 return_info.Set(bytes_read, eConnectionStatusError, result_error);
232 } else if (bytes_read == 0)
233 return_info.Set(bytes_read, eConnectionStatusEndOfFile, 0);
235 return_info.Set(bytes_read, eConnectionStatusSuccess, 0);
238 } else if (::GetLastError() == ERROR_BROKEN_PIPE) {
239 // The write end of a pipe was closed. This is equivalent to EOF.
240 return_info.Set(0, eConnectionStatusEndOfFile, 0);
242 // An unknown error occurred. Fail out.
243 return_info.Set(0, eConnectionStatusError, ::GetLastError());
248 status = return_info.GetStatus();
250 *error_ptr = return_info.GetError();
252 // kBytesAvailableEvent is a manual reset event. Make sure it gets reset here
254 // subsequent operations don't immediately see bytes available.
255 ResetEvent(m_event_handles[kBytesAvailableEvent]);
257 IncrementFilePointer(return_info.GetBytes());
258 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
260 log->Printf("%p ConnectionGenericFile::Read() handle = %p, dst = %p, "
261 "dst_len = %zu) => %zu, error = %s",
262 this, m_file, dst, dst_len, return_info.GetBytes(),
263 return_info.GetError().AsCString());
266 return return_info.GetBytes();
269 size_t ConnectionGenericFile::Write(const void *src, size_t src_len,
270 lldb::ConnectionStatus &status,
272 ReturnInfo return_info;
273 DWORD bytes_written = 0;
279 if (!IsConnected()) {
280 return_info.Set(0, eConnectionStatusNoConnection, ERROR_INVALID_HANDLE);
284 m_overlapped.hEvent = NULL;
286 // Writes are not interruptible like reads are, so just block until it's done.
287 result = ::WriteFile(m_file, src, src_len, NULL, &m_overlapped);
288 if (!result && ::GetLastError() != ERROR_IO_PENDING) {
289 return_info.Set(0, eConnectionStatusError, ::GetLastError());
293 if (!::GetOverlappedResult(m_file, &m_overlapped, &bytes_written, TRUE)) {
294 return_info.Set(bytes_written, eConnectionStatusError, ::GetLastError());
298 return_info.Set(bytes_written, eConnectionStatusSuccess, 0);
302 status = return_info.GetStatus();
304 *error_ptr = return_info.GetError();
306 IncrementFilePointer(return_info.GetBytes());
307 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION));
309 log->Printf("%p ConnectionGenericFile::Write() handle = %p, src = %p, "
310 "src_len = %zu) => %zu, error = %s",
311 this, m_file, src, src_len, return_info.GetBytes(),
312 return_info.GetError().AsCString());
314 return return_info.GetBytes();
317 std::string ConnectionGenericFile::GetURI() { return m_uri; }
319 bool ConnectionGenericFile::InterruptRead() {
320 return ::SetEvent(m_event_handles[kInterruptEvent]);
323 void ConnectionGenericFile::IncrementFilePointer(DWORD amount) {
324 LARGE_INTEGER old_pos;
325 old_pos.HighPart = m_overlapped.OffsetHigh;
326 old_pos.LowPart = m_overlapped.Offset;
327 old_pos.QuadPart += amount;
328 m_overlapped.Offset = old_pos.LowPart;
329 m_overlapped.OffsetHigh = old_pos.HighPart;