Debian Codegraph @

Source/Core/Common/DirectIOFile.cpp

raw symbols SCIP
1 // Copyright 2025 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "Common/DirectIOFile.h"
5
6 #include <utility>
7
8 #if defined(_WIN32)
9 #include <windows.h>
10
11 #include <cstring>
12
13 #include "Common/Buffer.h"
14 #include "Common/CommonFuncs.h"
15 #include "Common/MathUtil.h"
16 #include "Common/StringUtil.h"
17 #else
18 #include <string>
19
20 #include <fcntl.h>
21 #include <sys/stat.h>
22 #include <unistd.h>
23
24 #ifdef ANDROID
25 #include "jni/AndroidCommon/AndroidCommon.h"
26
27 #include "Common/Lazy.h"
28 #endif
29
30 #include "Common/FileUtil.h"
31 #endif
32
33 #include "Common/Assert.h"
34
35 namespace File
36 {
37 DirectIOFile::DirectIOFile() = default;
38
39 DirectIOFile::~DirectIOFile()
40 {
41 Close();
42 }
43
44 DirectIOFile::DirectIOFile(const DirectIOFile& other)
45 {
46 *this = other.Duplicate();
47 }
48
49 DirectIOFile& DirectIOFile::operator=(const DirectIOFile& other)
50 {
51 return *this = other.Duplicate();
52 }
53
54 DirectIOFile::DirectIOFile(DirectIOFile&& other)
55 {
56 Swap(other);
57 }
58
59 DirectIOFile& DirectIOFile::operator=(DirectIOFile&& other)
60 {
61 Close();
62 Swap(other);
63 return *this;
64 }
65
66 DirectIOFile::DirectIOFile(const std::string& path, AccessMode access_mode, OpenMode open_mode)
67 {
68 Open(path, access_mode, open_mode);
69 }
70
71 bool DirectIOFile::Open(const std::string& path, AccessMode access_mode, OpenMode open_mode)
72 {
73 ASSERT(!IsOpen());
74
75 if (open_mode == OpenMode::Default)
76 open_mode = (access_mode == AccessMode::Write) ? OpenMode::Truncate : OpenMode::Existing;
77
78 // This is not a sensible combination. Fail here to not rely on OS-specific behaviors.
79 if (access_mode == AccessMode::Read && open_mode == OpenMode::Truncate)
80 return false;
81
82 #if defined(_WIN32)
83 DWORD desired_access = GENERIC_READ | GENERIC_WRITE;
84 if (access_mode == AccessMode::Read)
85 desired_access = GENERIC_READ;
86 else if (access_mode == AccessMode::Write)
87 desired_access = GENERIC_WRITE;
88
89 if (access_mode != AccessMode::Read)
90 {
91 // Allow deleting and renaming through our handle.
92 desired_access |= DELETE;
93 }
94
95 // All sharing is allowed to more closely match default behavior on other OSes.
96 constexpr DWORD share_mode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;
97
98 DWORD creation_disposition = OPEN_ALWAYS;
99 if (open_mode == OpenMode::Truncate)
100 creation_disposition = CREATE_ALWAYS;
101 else if (open_mode == OpenMode::Create)
102 creation_disposition = CREATE_NEW;
103 else if (open_mode == OpenMode::Existing)
104 creation_disposition = OPEN_EXISTING;
105
106 m_handle = CreateFile(UTF8ToTStr(path).c_str(), desired_access, share_mode, nullptr,
107 creation_disposition, FILE_ATTRIBUTE_NORMAL, nullptr);
108 if (!IsOpen())
109 WARN_LOG_FMT(COMMON, "CreateFile: {}", Common::GetLastErrorString());
110
111 #else
112 #if defined(ANDROID)
113 if (IsPathAndroidContent(path))
114 {
115 // Android documentation says that "w" may or may not truncate.
116 // In case it does, we'll use "rw" when we don't want truncation.
117 // This wrongly enables read access when we don't need it.
118 if (access_mode == AccessMode::Write && open_mode != OpenMode::Truncate)
119 access_mode = AccessMode::ReadAndWrite;
120
121 std::string open_mode_str = "rw";
122 if (access_mode == AccessMode::Read)
123 open_mode_str = "r";
124 else if (access_mode == AccessMode::Write)
125 open_mode_str = "w";
126
127 if (open_mode == OpenMode::Truncate)
128 open_mode_str += 't';
129
130 if (open_mode == OpenMode::Create)
131 {
132 ASSERT_MSG(COMMON, false, "DirectIOFile doesn't support creating SAF files");
133 return false;
134 }
135
136 m_fd = OpenAndroidContent(path, open_mode_str);
137
138 if (!IsOpen() && (open_mode == OpenMode::Always || open_mode == OpenMode::Truncate))
139 ASSERT_MSG(COMMON, Exists(path), "DirectIOFile doesn't support creating SAF files");
140
141 return IsOpen();
142 }
143 #endif
144 int flags = O_RDWR;
145 if (access_mode == AccessMode::Read)
146 flags = O_RDONLY;
147 else if (access_mode == AccessMode::Write)
148 flags = O_WRONLY;
149
150 if (open_mode == OpenMode::Truncate)
151 flags |= O_CREAT | O_TRUNC;
152 else if (open_mode == OpenMode::Create)
153 flags |= O_CREAT | O_EXCL;
154 else if (open_mode != OpenMode::Existing)
155 flags |= O_CREAT;
156
157 m_fd = open(path.c_str(), flags, 0666);
158
159 #endif
160
161 return IsOpen();
162 }
163
164 bool DirectIOFile::Close()
165 {
166 if (!IsOpen())
167 return false;
168
169 m_current_offset = 0;
170
171 #if defined(_WIN32)
172 return CloseHandle(std::exchange(m_handle, INVALID_HANDLE_VALUE)) != 0;
173 #else
174 return close(std::exchange(m_fd, -1)) == 0;
175 #endif
176 }
177
178 bool DirectIOFile::IsOpen() const
179 {
180 #if defined(_WIN32)
181 return m_handle != INVALID_HANDLE_VALUE;
182 #else
183 return m_fd != -1;
184 #endif
185 }
186
187 #if defined(_WIN32)
188 template <auto* TransferFunc>
189 static bool OverlappedTransfer(HANDLE handle, u64 offset, auto* data_ptr, u64 size)
190 {
191 // ReadFile/WriteFile take a 32bit size so we must loop to handle our 64bit size.
192 while (true)
193 {
194 OVERLAPPED overlapped{};
195 overlapped.Offset = DWORD(offset);
196 overlapped.OffsetHigh = DWORD(offset >> 32);
197
198 DWORD bytes_transferred{};
199 if (TransferFunc(handle, data_ptr, MathUtil::SaturatingCast<DWORD>(size), &bytes_transferred,
200 &overlapped) == 0)
201 {
202 ERROR_LOG_FMT(COMMON, "OverlappedTransfer: {}", Common::GetLastErrorString());
203 return false;
204 }
205
206 size -= bytes_transferred;
207
208 if (size == 0)
209 return true;
210
211 offset += bytes_transferred;
212 data_ptr += bytes_transferred;
213 }
214 }
215 #endif
216
217 bool DirectIOFile::OffsetRead(u64 offset, u8* out_ptr, u64 size)
218 {
219 #if defined(_WIN32)
220 return OverlappedTransfer<ReadFile>(m_handle, offset, out_ptr, size);
221 #else
222 return pread(m_fd, out_ptr, size, off_t(offset)) == ssize_t(size);
223 #endif
224 }
225
226 bool DirectIOFile::OffsetWrite(u64 offset, const u8* in_ptr, u64 size)
227 {
228 #if defined(_WIN32)
229 return OverlappedTransfer<WriteFile>(m_handle, offset, in_ptr, size);
230 #else
231 return pwrite(m_fd, in_ptr, size, off_t(offset)) == ssize_t(size);
232 #endif
233 }
234
235 u64 DirectIOFile::GetSize() const
236 {
237 #if defined(_WIN32)
238 LARGE_INTEGER result{};
239 if (GetFileSizeEx(m_handle, &result) != 0)
240 return result.QuadPart;
241 #else
242 struct stat st{};
243 if (fstat(m_fd, &st) == 0)
244 return st.st_size;
245 #endif
246
247 return 0;
248 }
249
250 bool DirectIOFile::Seek(s64 offset, SeekOrigin origin)
251 {
252 if (!IsOpen())
253 return false;
254
255 u64 reference_pos = 0;
256 switch (origin)
257 {
258 case SeekOrigin::Current:
259 reference_pos = m_current_offset;
260 break;
261 case SeekOrigin::End:
262 reference_pos = GetSize();
263 break;
264 default:
265 break;
266 }
267
268 // Don't let our current offset underflow.
269 if (offset < 0 && u64(-offset) > reference_pos)
270 return false;
271
272 m_current_offset = reference_pos + offset;
273 return true;
274 }
275
276 bool DirectIOFile::Flush()
277 {
278 #if defined(_WIN32)
279 return FlushFileBuffers(m_handle) != 0;
280 #else
281 return fsync(m_fd) == 0;
282 #endif
283 }
284
285 void DirectIOFile::Swap(DirectIOFile& other)
286 {
287 #if defined(_WIN32)
288 std::swap(m_handle, other.m_handle);
289 #else
290 std::swap(m_fd, other.m_fd);
291 #endif
292 std::swap(m_current_offset, other.m_current_offset);
293 }
294
295 DirectIOFile DirectIOFile::Duplicate() const
296 {
297 DirectIOFile result;
298
299 if (!IsOpen())
300 return result;
301
302 #if defined(_WIN32)
303 const auto current_process = GetCurrentProcess();
304 if (DuplicateHandle(current_process, m_handle, current_process, &result.m_handle, 0, FALSE,
305 DUPLICATE_SAME_ACCESS) == 0)
306 {
307 ERROR_LOG_FMT(COMMON, "DuplicateHandle: {}", Common::GetLastErrorString());
308 }
309 #else
310 result.m_fd = dup(m_fd);
311 #endif
312
313 ASSERT(result.IsOpen());
314
315 result.m_current_offset = m_current_offset;
316
317 return result;
318 }
319
320 bool Resize(DirectIOFile& file, u64 size)
321 {
322 #if defined(_WIN32)
323 // This operation is not "atomic", but it's the only thing we're using the file pointer for.
324 // Concurrent `Resize` would need some external synchronization to prevent race regardless.
325 const LARGE_INTEGER distance{.QuadPart = LONGLONG(size)};
326 return (SetFilePointerEx(file.GetHandle(), distance, nullptr, FILE_BEGIN) != 0) &&
327 (SetEndOfFile(file.GetHandle()) != 0);
328 #else
329 return ftruncate(file.GetHandle(), off_t(size)) == 0;
330 #endif
331 }
332
333 bool Rename(DirectIOFile& file, const std::string& source_path [[maybe_unused]],
334 const std::string& destination_path)
335 {
336 #if defined(_WIN32)
337 const auto dest_name = UTF8ToWString(destination_path);
338 const auto dest_name_byte_size = DWORD(dest_name.size() * sizeof(WCHAR));
339 FILE_RENAME_INFO info{
340 .ReplaceIfExists = TRUE,
341 .FileNameLength = dest_name_byte_size, // The size in bytes, not including null termination.
342 };
343 constexpr auto filename_struct_offset = offsetof(FILE_RENAME_INFO, FileName);
344 Common::UniqueBuffer<u8> buffer(filename_struct_offset + dest_name_byte_size + sizeof(WCHAR));
345 std::memcpy(buffer.data(), &info, filename_struct_offset);
346 std::memcpy(buffer.data() + filename_struct_offset, dest_name.c_str(),
347 dest_name_byte_size + sizeof(WCHAR));
348 return SetFileInformationByHandle(file.GetHandle(), FileRenameInfo, buffer.data(),
349 DWORD(buffer.size())) != 0;
350 #else
351 return file.IsOpen() && Rename(source_path, destination_path);
352 #endif
353 }
354
355 bool Delete(DirectIOFile& file, const std::string& filename)
356 {
357 #if defined(_WIN32)
358 FILE_DISPOSITION_INFO info{.DeleteFile = TRUE};
359 return SetFileInformationByHandle(file.GetHandle(), FileDispositionInfo, &info, sizeof(info)) !=
360 0;
361 #else
362 return file.IsOpen() && Delete(filename, IfAbsentBehavior::NoConsoleWarning);
363 #endif
364 }
365
366 } // namespace File