1 | //===-- LockFileWindows.cpp -----------------------------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | #include "lldb/Host/windows/LockFileWindows.h" |
10 | |
11 | #include <io.h> |
12 | |
13 | using namespace lldb; |
14 | using namespace lldb_private; |
15 | |
16 | static Status fileLock(HANDLE file_handle, DWORD flags, const uint64_t start, |
17 | const uint64_t len) { |
18 | if (start != 0) |
19 | return Status::FromErrorString( |
20 | str: "Non-zero start lock regions are not supported" ); |
21 | |
22 | OVERLAPPED overlapped = {}; |
23 | |
24 | if (!::LockFileEx(file_handle, flags, 0, len, 0, &overlapped) && |
25 | ::GetLastError() != ERROR_IO_PENDING) |
26 | return Status(::GetLastError(), eErrorTypeWin32); |
27 | |
28 | DWORD bytes; |
29 | if (!::GetOverlappedResult(file_handle, &overlapped, &bytes, TRUE)) |
30 | return Status(::GetLastError(), eErrorTypeWin32); |
31 | |
32 | return Status(); |
33 | } |
34 | |
35 | LockFileWindows::LockFileWindows(int fd) |
36 | : LockFileBase(fd), m_file(reinterpret_cast<HANDLE>(_get_osfhandle(fd))) {} |
37 | |
38 | LockFileWindows::~LockFileWindows() { Unlock(); } |
39 | |
40 | bool LockFileWindows::IsValidFile() const { |
41 | return LockFileBase::IsValidFile() && m_file != INVALID_HANDLE_VALUE; |
42 | } |
43 | |
44 | Status LockFileWindows::DoWriteLock(const uint64_t start, const uint64_t len) { |
45 | return fileLock(m_file, LOCKFILE_EXCLUSIVE_LOCK, start, len); |
46 | } |
47 | |
48 | Status LockFileWindows::DoTryWriteLock(const uint64_t start, |
49 | const uint64_t len) { |
50 | return fileLock(m_file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, |
51 | start, len); |
52 | } |
53 | |
54 | Status LockFileWindows::DoReadLock(const uint64_t start, const uint64_t len) { |
55 | return fileLock(m_file, 0, start, len); |
56 | } |
57 | |
58 | Status LockFileWindows::DoTryReadLock(const uint64_t start, |
59 | const uint64_t len) { |
60 | return fileLock(m_file, LOCKFILE_FAIL_IMMEDIATELY, start, len); |
61 | } |
62 | |
63 | Status LockFileWindows::DoUnlock() { |
64 | OVERLAPPED overlapped = {}; |
65 | |
66 | if (!::UnlockFileEx(m_file, 0, m_len, 0, &overlapped) && |
67 | ::GetLastError() != ERROR_IO_PENDING) |
68 | return Status(::GetLastError(), eErrorTypeWin32); |
69 | |
70 | DWORD bytes; |
71 | if (!::GetOverlappedResult(m_file, &overlapped, &bytes, TRUE)) |
72 | return Status(::GetLastError(), eErrorTypeWin32); |
73 | |
74 | return Status(); |
75 | } |
76 | |