Repository navigation
Expand file tree
/
Copy pathOpen.cpp
More file actions
578 lines (556 loc) · 26 KB
/
Copy pathOpen.cpp
File metadata and controls
578 lines (556 loc) · 26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
#include "prx/libkernel/include/Api.hpp"
#include "prx/libc/include/Api.hpp"
#include "prx/libkernel/File/include/FileFlags.hpp"
#include "prx/libkernel/File/include/NativeStat.hpp"
#include "prx/libc/include/General.hpp"
#include "prx/libc/include/FilesystemError.hpp"
#include "prx/libc/include/RenameDot.hpp"
#include "prx/libc/include/GuestArena.hpp"
#include "prx/libc/include/AppArchive.hpp"
#include "prx/libkernel/DirectMemory/DirectMemory.hpp"
#include "prx/libkernel/File/include/File.hpp"
#include "prx/libkernel/File/include/SharedMemory.hpp"
#include "prx/libkernel/File/include/DirectoryDescriptor.hpp"
#include "prx/libkernel/File/include/DescriptorControl.hpp"
#include "prx/libkernel/File/include/FileLock.hpp"
#include "prx/libkernel/Socket/include/SocketRuntime.hpp"
#include "prx/libkernel/Socket/include/SocketPoll.hpp"
#include "prx/libkernel/File/include/RandomDevice.hpp"
#include "prx/libkernel/File/include/HostStreams.hpp"
#include "prx/libkernel/File/include/ArchivedFile.hpp"
#include "prx/libkernel/KernelErrors.hpp"
#include "prx/libkernel/Equeue/Equeue.hpp"
#include "SceTypes.hpp"
#include <cerrno>
#include <cstdarg>
#include <limits>
#include <stdexcept>
#include <string>
#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#include <sys/stat.h>
#include <windows.h>
#include "prx/libc/include/WindowsDescriptor.hpp"
#include "prx/libkernel/File/include/WindowsSymbolicLink.hpp"
static int NativeOpen(const std::filesystem::path& p, int nativeFlags, std::uint16_t mode) {
const int access = nativeFlags & (_O_RDONLY | _O_WRONLY | _O_RDWR);
const DWORD desired = access == _O_RDONLY ? GENERIC_READ : access == _O_WRONLY ? GENERIC_WRITE : GENERIC_READ | GENERIC_WRITE;
DWORD disposition = OPEN_EXISTING;
if (nativeFlags & _O_CREAT) disposition = (nativeFlags & _O_EXCL) ? CREATE_NEW : (nativeFlags & _O_TRUNC) ? CREATE_ALWAYS : OPEN_ALWAYS;
else if (nativeFlags & _O_TRUNC) disposition = TRUNCATE_EXISTING;
const DWORD attributes = (nativeFlags & _O_CREAT) && !(mode & _S_IWRITE) ? FILE_ATTRIBUTE_READONLY : FILE_ATTRIBUTE_NORMAL;
SECURITY_ATTRIBUTES security{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
const auto handle = CreateFileW(p.c_str(), desired, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &security, disposition, attributes, nullptr);
if (handle == INVALID_HANDLE_VALUE) {
errno = WindowsOpenError_nid_no_patch(GetLastError());
return -1;
}
const int descriptor = ::_open_osfhandle(reinterpret_cast<std::intptr_t>(handle), nativeFlags & (_O_APPEND | _O_RDONLY | _O_BINARY));
if (descriptor < 0) CloseHandle(handle);
return descriptor;
}
static std::int64_t NativeLseek(int fd, std::int64_t offset, int whence) {
const auto positioned = File::LockPositionedTransfer(fd);
const auto result = File::SeekSharedMemory_nid_no_patch(fd, offset, whence);
if (result != -2) return result;
if (GetFileType(WindowsDescriptorHandle_nid_no_patch(fd)) == FILE_TYPE_PIPE) {
errno = ESPIPE;
return -1;
}
return ::_lseeki64(fd, offset, whence);
}
static int NativeRead(int fd, void* buf, std::size_t n) {
if (n > static_cast<std::size_t>(std::numeric_limits<unsigned int>::max())) {
throw std::runtime_error("sceKernelRead: nbytes exceeds platform limit");
}
if (File::IsDirectoryDescriptor(fd)) {
errno = EISDIR;
return -1;
}
const auto positioned = File::LockPositionedTransfer(fd);
const int result = ::_read(fd, buf, static_cast<unsigned int>(n));
if (result < 0 && _doserrno == ERROR_NO_DATA) errno = EAGAIN;
return result;
}
static int NativeWrite(int fd, const void* buf, std::size_t n) {
if (n > static_cast<std::size_t>(std::numeric_limits<unsigned int>::max())) {
throw std::runtime_error("sceKernelWrite: nbytes exceeds platform limit");
}
const auto positioned = File::LockPositionedTransfer(fd);
const auto shared = File::WriteSharedMemory_nid_no_patch(fd, buf, n);
if (shared != -2) return static_cast<int>(shared);
if (File::Appends(fd)) {
const auto appended = File::WriteAtEnd(fd, buf, n);
if (appended != -2) return static_cast<int>(appended);
}
const int result = ::_write(fd, buf, static_cast<unsigned int>(n));
if (result < 0 && errno == ENOSPC && _doserrno == 0 && ::GetFileType(reinterpret_cast<HANDLE>(::_get_osfhandle(fd))) == FILE_TYPE_PIPE) errno = EAGAIN;
if (result < 0 && (_doserrno == ERROR_NO_DATA || _doserrno == ERROR_BROKEN_PIPE) && ::GetFileType(reinterpret_cast<HANDLE>(::_get_osfhandle(fd))) == FILE_TYPE_PIPE) errno = EPIPE;
return result;
}
extern "C" _invalid_parameter_handler _set_thread_local_invalid_parameter_handler(_invalid_parameter_handler);
static void IgnoreInvalidParameter(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, std::uintptr_t) {}
static int NativeClose(int fd) {
const int shared = File::CloseSharedMemoryDescriptor_nid_no_patch(fd);
if (shared != -2) return shared;
const auto previous = _set_thread_local_invalid_parameter_handler(IgnoreInvalidParameter);
const int result = ::_close(fd);
_set_thread_local_invalid_parameter_handler(previous);
return result;
}
static int NativeUnlink(const std::filesystem::path& p) {
const auto path = p.wstring();
struct _stat64 status{};
const bool unlocked = ::_wstat64(path.c_str(), &status) == 0 && (status.st_mode & _S_IFMT) == _S_IFREG &&
!(status.st_mode & _S_IWRITE) && ::_wchmod(path.c_str(), _S_IREAD | _S_IWRITE) == 0;
if (::_wunlink(path.c_str()) == 0) return 0;
const int error = errno;
if (unlocked) ::_wchmod(path.c_str(), _S_IREAD);
errno = error;
return -1;
}
static std::filesystem::path NativeMetadataPath(const std::filesystem::path& path, std::error_code& error) {
const auto& input = path.native();
if (input.starts_with(L"\\\\?\\") || input.starts_with(L"\\\\.\\")) return path;
auto absolute = std::filesystem::absolute(path, error);
if (error) return {};
absolute = absolute.lexically_normal().make_preferred();
const auto& native = absolute.native();
if (native.size() < MAX_PATH || native.starts_with(L"\\\\?\\") || native.starts_with(L"\\\\.\\")) return absolute;
return native.starts_with(L"\\\\") ? std::filesystem::path(L"\\\\?\\UNC\\" + native.substr(2))
: std::filesystem::path(L"\\\\?\\" + native);
}
static bool NativeSymbolicLinkLoop(const std::filesystem::path& path) {
return File::WindowsSymbolicLinkLoop(path);
}
static int MapFlags(int sceFlags) {
int f = 0;
const int acc = sceFlags & SCE_KERNEL_O_ACCMODE;
if (acc == SCE_KERNEL_O_RDONLY) f |= _O_RDONLY;
else if (acc == SCE_KERNEL_O_WRONLY) f |= _O_WRONLY;
else if (acc == SCE_KERNEL_O_RDWR) f |= _O_RDWR;
else throw std::invalid_argument("sceKernelOpen: invalid access mode");
if (sceFlags & SCE_KERNEL_O_APPEND) f |= _O_APPEND;
if (sceFlags & SCE_KERNEL_O_CREAT) f |= _O_CREAT;
if (sceFlags & SCE_KERNEL_O_TRUNC) f |= _O_TRUNC;
if (sceFlags & SCE_KERNEL_O_EXCL) f |= _O_EXCL;
f |= _O_BINARY;
return f;
}
#else
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#ifdef __APPLE__
#include <sys/stat.h>
#endif
static int NativeOpen(const std::filesystem::path& p, int nativeFlags, std::uint16_t mode) {
return ::open(p.c_str(), nativeFlags, static_cast<mode_t>(mode));
}
static std::int64_t NativeLseek(int fd, std::int64_t offset, int whence) {
const auto result = File::SeekSharedMemory_nid_no_patch(fd, offset, whence);
if (result != -2) return result;
#ifdef __APPLE__
const auto appendOffset = File::LockAppendOffset(fd);
#endif
return ::lseek(fd, static_cast<off_t>(offset), whence);
}
static std::int64_t NativeRead(int fd, void* buf, std::size_t n) {
#ifdef __APPLE__
const auto appendOffset = File::LockAppendOffset(fd);
#endif
return ::read(fd, buf, n);
}
static std::int64_t NativeWrite(int fd, const void* buf, std::size_t n) {
const auto result = File::WriteSharedMemory_nid_no_patch(fd, buf, n);
if (result != -2) return result;
#ifdef __APPLE__
const auto appendOffset = File::LockAppendOffset(fd);
#endif
return ::write(fd, buf, n);
}
static int NativeClose(int fd) { return ::close(fd); }
static int NativeUnlink(const std::filesystem::path& p) {
return ::unlink(p.c_str());
}
static int MapFlags(int sceFlags) {
int f = 0;
const int acc = sceFlags & SCE_KERNEL_O_ACCMODE;
if (acc == SCE_KERNEL_O_RDONLY) f |= O_RDONLY;
else if (acc == SCE_KERNEL_O_WRONLY) f |= O_WRONLY;
else if (acc == SCE_KERNEL_O_RDWR) f |= O_RDWR;
else throw std::invalid_argument("sceKernelOpen: invalid access mode");
if (sceFlags & SCE_KERNEL_O_APPEND) f |= O_APPEND;
if (sceFlags & SCE_KERNEL_O_CREAT) f |= O_CREAT;
if (sceFlags & SCE_KERNEL_O_TRUNC) f |= O_TRUNC;
if (sceFlags & SCE_KERNEL_O_EXCL) f |= O_EXCL;
if (sceFlags & SCE_KERNEL_O_SYNC) f |= O_SYNC;
if (sceFlags & SCE_KERNEL_O_DIRECTORY) f |= O_DIRECTORY;
return f;
}
#endif
static int SceErrorFromErrno(int error) {
const int guest = error > 0 && error <= 34 ? error : FilesystemError(std::error_code(error, std::generic_category()));
return static_cast<int>(0x80020000u | static_cast<unsigned>(guest));
}
static int SceStatErrorFromErrno(int error) {
#ifdef ELOOP
if (error == ELOOP) return SCE_KERNEL_ERROR_ELOOP;
#endif
return SceErrorFromErrno(error);
}
static int SceIoErrorFromErrno(int error) {
int guest = SceErrorFromErrno(error) & 0xffff;
if (error == EAGAIN) guest = 35;
#ifdef EDEADLK
else if (error == EDEADLK) guest = 11;
#endif
#ifdef EDQUOT
else if (error == EDQUOT) guest = 69;
#endif
#ifdef EOVERFLOW
else if (error == EOVERFLOW) guest = 84;
#endif
return static_cast<int>(0x80020000u | static_cast<unsigned>(guest));
}
static int OpenNative(const std::filesystem::path& native, int flags, std::uint16_t mode) {
if (AppArchiveHasDirectory_nid_no_patch(native)) {
std::error_code error;
const auto status = std::filesystem::status(native, error);
const bool hostDirectory = !error && std::filesystem::is_directory(status);
if (hostDirectory || AppArchiveOnly_nid_no_patch(native)) {
if ((flags & SCE_KERNEL_O_ACCMODE) != SCE_KERNEL_O_RDONLY ||
(flags & (SCE_KERNEL_O_CREAT | SCE_KERNEL_O_TRUNC)) != 0) return SceErrorFromErrno(EISDIR);
const int fd = File::OpenDirectoryDescriptor(native);
if (fd < 0) return SceErrorFromErrno(errno);
File::RememberDescriptor(fd, flags);
return fd;
}
}
if (const auto archived = File::OpenArchivedFile(native, flags)) {
if (*archived < 0) return SceErrorFromErrno(-*archived);
File::RememberDescriptor(*archived, flags);
return *archived;
}
#ifdef _WIN32
if ((flags & (SCE_KERNEL_O_DIRECTORY | SCE_KERNEL_O_CREAT)) == SCE_KERNEL_O_DIRECTORY) {
std::error_code error;
const auto status = std::filesystem::status(native, error);
if (std::filesystem::exists(status) && !std::filesystem::is_directory(status)) return SceErrorFromErrno(ENOTDIR);
}
if ((flags & (SCE_KERNEL_O_CREAT | SCE_KERNEL_O_EXCL)) == (SCE_KERNEL_O_CREAT | SCE_KERNEL_O_EXCL) && native.has_filename()) {
const DWORD attributes = GetFileAttributesW(native.c_str());
if (attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) return SceErrorFromErrno(EEXIST);
}
#endif
if ((flags & SCE_KERNEL_O_NOFOLLOW) != 0 && (flags & (SCE_KERNEL_O_CREAT | SCE_KERNEL_O_EXCL)) != (SCE_KERNEL_O_CREAT | SCE_KERNEL_O_EXCL)) {
constexpr int GuestEmlink = 31;
std::error_code error;
if (std::filesystem::is_symlink(native, error)) return SceErrorFromErrno(GuestEmlink);
#ifdef _WIN32
const DWORD attributes = GetFileAttributesW(native.c_str());
if (attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
std::string junctionTarget;
if (File::WindowsSymbolicLink::ReadJunction(native, junctionTarget, "open")) return SceErrorFromErrno(GuestEmlink);
}
#endif
}
int fd = NativeOpen(native, MapFlags(flags), mode);
#ifdef __APPLE__
if (fd >= 0 && (flags & (SCE_KERNEL_O_CREAT | SCE_KERNEL_O_EXCL)) == SCE_KERNEL_O_CREAT) {
struct stat opened{};
if (::fstat(fd, &opened) == 0 && S_ISDIR(opened.st_mode)) {
::close(fd);
fd = -1;
errno = EISDIR;
}
}
#endif
#ifdef _WIN32
if (fd < 0 && (errno != ENOENT || !native.has_filename())) {
const int openError = errno;
auto directory = native;
while (!directory.has_filename() && directory.has_relative_path()) directory = directory.parent_path();
std::error_code error;
if (std::filesystem::is_directory(directory, error)) {
if ((flags & (SCE_KERNEL_O_CREAT | SCE_KERNEL_O_EXCL)) == (SCE_KERNEL_O_CREAT | SCE_KERNEL_O_EXCL)) errno = EEXIST;
else if ((flags & SCE_KERNEL_O_ACCMODE) != SCE_KERNEL_O_RDONLY || (flags & (SCE_KERNEL_O_CREAT | SCE_KERNEL_O_TRUNC))) errno = EISDIR;
else fd = File::OpenDirectoryDescriptor(directory);
} else {
errno = openError;
}
}
#endif
#ifdef __APPLE__
// macOS opens an existing directory under O_CREAT without O_EXCL; FreeBSD and Linux refuse it with EISDIR.
if (fd >= 0 && (flags & SCE_KERNEL_O_CREAT)) {
struct stat info{};
if (::fstat(fd, &info) == 0 && S_ISDIR(info.st_mode)) {
NativeClose(fd);
fd = -1;
errno = EISDIR;
}
}
#endif
#ifdef _WIN32
if (fd < 0 && (errno == ENOENT || errno == ENOTDIR)) {
std::error_code metadataError;
const auto metadataPath = NativeMetadataPath(native, metadataError);
if (!metadataError && NativeSymbolicLinkLoop(metadataPath)) return SCE_KERNEL_ERROR_ELOOP;
}
#endif
if (fd < 0) {
return SceErrorFromErrno(errno == ENOENT ? NotFoundError_nid_no_patch(native) : errno);
}
if ((flags & SCE_KERNEL_O_ACCMODE) != SCE_KERNEL_O_RDONLY || (flags & (SCE_KERNEL_O_CREAT | SCE_KERNEL_O_TRUNC)))
RecordWrittenPath_nid_no_patch(native);
File::RememberDescriptor(fd, flags);
return fd;
}
extern "C" {
int APS5_VABI sceKernelOpen(const char* path, int flags, std::uint16_t mode) {
if (File::InvalidOpenFlags(flags)) return SCE_KERNEL_ERROR_EINVAL;
std::string copy;
if (const int error = CopyGuestPath_nid_no_patch(path, copy)) return SceKernelError(error);
path = copy.c_str();
if (copy.empty()) return SCE_KERNEL_ERROR_ENOENT;
APS5_LOG_OUT("path=%s flags=0x%X nativeFlags=0x%X mode=0%o", path, flags, MapFlags(flags), mode);
if (path != nullptr && File::IsRandomDevicePath(path)) {
if ((flags & SCE_KERNEL_O_ACCMODE) != SCE_KERNEL_O_RDONLY) throw std::runtime_error(std::string(__func__) + ": writing to " + path + " is not implemented");
const int fd = File::OpenRandomDevice();
if (fd < 0) return SceErrorFromErrno(errno);
File::RememberDescriptor(fd, flags);
return fd;
}
std::filesystem::path native;
const bool module = (flags & (SCE_KERNEL_O_ACCMODE | SCE_KERNEL_O_CREAT)) == SCE_KERNEL_O_RDONLY;
if (const int error = ResolvePathError_nid_no_patch(path, native, module, true)) {
const int result = SceKernelError(error);
APS5_LOG_ERR("open failed path=%s resolveError=%d result=0x%08X", path != nullptr ? path : "<null>", error, static_cast<unsigned>(result));
return result;
}
const int result = OpenNative(native, flags, mode);
if (result < 0) {
const auto resolved = native.u8string();
APS5_LOG_ERR("open failed path=%s resolvedPath=%s result=0x%08X", path != nullptr ? path : "<null>", reinterpret_cast<const char*>(resolved.c_str()), static_cast<unsigned>(result));
}
return result;
}
int OpenInDirectory_nid_no_patch(int directory, const char* path, int flags, std::uint16_t mode) {
if (File::InvalidOpenFlags(flags)) return SCE_KERNEL_ERROR_EINVAL;
int error = 0;
const char* base = GetDirectoryDescriptorPath_nid_no_patch(directory, &error);
if (base == nullptr) return SceErrorFromErrno(error);
return OpenNative(std::filesystem::path(reinterpret_cast<const char8_t*>(base)) / std::filesystem::path(reinterpret_cast<const char8_t*>(path)), flags, mode);
}
int APS5_VABI sceKernelClose(int d) {
if (File::IsHostStream(d)) return SCE_KERNEL_ERROR_EPERM;
int socketError = 0;
if (KernelCloseSocket_nid_no_patch(d, &socketError)) return socketError == 0 ? 0 : SceKernelError(socketError);
if (GuestSockets::IsOpen(d)) return GuestSockets::Close(d) == 0 ? 0 : SceKernelError(*__error_nid_postfix());
EqueueDescriptorClosed(d);
#ifdef _WIN32
const auto positioned = File::LockPositionedTransfer(d);
#endif
File::ForgetRandomDevice(d);
File::ForgetDescriptor(d);
ForgetJitSharedMemory(d);
#ifdef _WIN32
File::ForgetFileLock(d);
#endif
File::ForgetDirectoryDescriptor(d);
if (NativeClose(d) != 0) {
if (errno == EBADF) return SCE_KERNEL_ERROR_EBADF;
throw std::runtime_error(std::string(__func__) + ": close failed, fd=" + std::to_string(d) + ", errno=" + std::to_string(errno));
}
return 0;
}
#ifndef _WIN32
extern "C" void LogRepeatFilterWrite_nid_no_patch(int standard, int descriptor, const void* data, std::size_t size);
#endif
std::int64_t APS5_VABI sceKernelRead(int d, void* buf, std::size_t nbytes) {
if (File::IsDirectoryDescriptor(d)) return SceErrorFromErrno(EISDIR);
if (GuestSockets::IsOpen(d)) {
const auto n = GuestSockets::Read(d, buf, nbytes);
return n < 0 ? SceKernelError(*__error_nid_postfix()) : n;
}
if (buf == nullptr) {
if (nbytes != 0) return SceIoErrorFromErrno(DescriptorIsOpen_nid_no_patch(d) ? EFAULT : EBADF);
char empty = 0;
return sceKernelRead(d, &empty, 0);
}
const GuestArena::HostWrite destination(buf, nbytes);
if (!destination.Open()) errno = EFAULT;
else if (File::ReadRandomDevice(d, buf, nbytes)) return static_cast<std::int64_t>(nbytes);
else if (const auto archived = File::ReadArchivedFile(d, buf, nbytes, nullptr)) return *archived;
auto n = destination.Open() ? NativeRead(d, buf, nbytes) : -1;
if (n < 0) return SceIoErrorFromErrno(errno);
return static_cast<std::int64_t>(n);
}
std::int64_t APS5_VABI sceKernelWrite(int d, const void* buf, std::size_t nbytes) {
if (File::IsVirtualDirectoryDescriptor(d)) return SceErrorFromErrno(EISDIR);
if (GuestSockets::IsOpen(d)) {
const auto n = GuestSockets::Write(d, buf, nbytes);
return n < 0 ? SceKernelError(*__error_nid_postfix()) : n;
}
if (buf == nullptr) {
if (nbytes != 0) return SceIoErrorFromErrno(DescriptorIsOpen_nid_no_patch(d) ? EFAULT : EBADF);
const char empty = 0;
return sceKernelWrite(d, &empty, 0);
}
const File::WriteSync sync(d);
GuestArena::GuestArenaPrepareHostRead_nid_no_patch(buf, nbytes);
#ifndef _WIN32
// Descriptors 1 and 2 are the game log until the title points them elsewhere.
if ((d == 1 && File::HostStandardOutput() < 0) || (d == 2 && File::HostStandardError() < 0)) {
LogRepeatFilterWrite_nid_no_patch(d, d, buf, nbytes);
return static_cast<std::int64_t>(nbytes);
}
#endif
auto n = NativeWrite(d, buf, nbytes);
if (n < 0) return SceIoErrorFromErrno(errno);
return static_cast<std::int64_t>(n);
}
static bool SeekOverflows(int d, std::int64_t offset, int whence) {
const std::int64_t current = NativeLseek(d, 0, 1);
if (current < 0) return false;
std::int64_t base = current;
if (whence == 2) {
base = NativeLseek(d, 0, 2);
NativeLseek(d, current, 0);
if (base < 0) return false;
}
return base > std::numeric_limits<std::int64_t>::max() - offset;
}
std::int64_t APS5_VABI sceKernelLseek(int d, std::int64_t offset, int whence) {
if (GuestSockets::IsOpen(d)) return SCE_KERNEL_ERROR_ESPIPE;
if (whence < 0 || whence > 2) {
throw std::invalid_argument(std::string(__func__) + ": invalid whence=" + std::to_string(whence));
}
if (const auto archived = File::SeekArchivedFile(d, offset, whence)) return *archived < 0 ? SceIoErrorFromErrno(-*archived) : *archived;
if (const auto directory = File::SeekDirectoryDescriptor(d, offset, whence)) {
if (*directory < 0) return SceIoErrorFromErrno(errno);
return *directory;
}
std::int64_t result = NativeLseek(d, offset, whence);
if (result < 0) {
const int error = errno;
if (error == EINVAL && offset > 0 && (whence == 1 || whence == 2) && SeekOverflows(d, offset, whence)) return SceIoErrorFromErrno(EOVERFLOW);
return SceIoErrorFromErrno(error);
}
return result;
}
constexpr int GuestEfault = 14;
static int StatNative(const std::filesystem::path& native, bool directory, FileStat* sb) {
std::error_code error;
constexpr int GuestEnotdir = 20;
FileStat archived{};
if (File::FillArchivedStat(native, &archived)) {
if (directory && (archived.st_mode & 0170000) != 0040000) return SceErrorFromErrno(GuestEnotdir);
if (sb == nullptr) return SceErrorFromErrno(GuestEfault);
*sb = archived;
return 0;
}
auto metadataPath = native;
#ifdef _WIN32
metadataPath = NativeMetadataPath(native, error);
if (error) return SceErrorFromErrno(FilesystemError(error));
#endif
const auto status = std::filesystem::status(metadataPath, error);
if (error == std::errc::not_a_directory) return SceErrorFromErrno(GuestEnotdir);
if (error == std::errc::filename_too_long || error == std::errc::too_many_symbolic_link_levels) return SceKernelError(FilesystemError(error));
if (!std::filesystem::exists(status)) {
#ifdef _WIN32
if (NativeSymbolicLinkLoop(metadataPath)) return SCE_KERNEL_ERROR_ELOOP;
#endif
return SceErrorFromErrno(NotFoundError_nid_no_patch(native));
}
if (directory && !std::filesystem::is_directory(status)) return SceErrorFromErrno(GuestEnotdir);
if (sb == nullptr) return SceErrorFromErrno(GuestEfault);
FileStat result{};
if (!File::TryFillFileStat(metadataPath, &result)) return SceStatErrorFromErrno(errno);
if (!GuestCopyOut_nid_no_patch(sb, &result, sizeof(result))) return SceErrorFromErrno(GuestEfault);
return 0;
}
int APS5_VABI sceKernelStat(const char* path, FileStat* sb) {
std::string copy;
if (const int error = CopyGuestPath_nid_no_patch(path, copy)) return SceErrorFromErrno(error);
path = copy.c_str();
if (copy.empty()) return SceErrorFromErrno(2);
std::filesystem::path native;
if (const int error = ResolvePathError_nid_no_patch(path, native, true, true)) return SceKernelError(error);
return StatNative(native, std::string_view(path).back() == '/', sb);
}
int StatInDirectory_nid_no_patch(int directory, const char* path, FileStat* sb, bool follow) {
int error = 0;
const char* base = GetDirectoryDescriptorPath_nid_no_patch(directory, &error);
if (base == nullptr) return SceErrorFromErrno(error);
const auto native = std::filesystem::path(reinterpret_cast<const char8_t*>(base)) / std::filesystem::path(reinterpret_cast<const char8_t*>(path));
if (follow) return StatNative(native, std::string_view(path).back() == '/', sb);
if (sb == nullptr) return SceErrorFromErrno(GuestEfault);
if (!File::FillLinkStat(native, sb)) return SceErrorFromErrno(errno);
return 0;
}
int APS5_VABI sceKernelUnlink(const char* path) {
std::string copy;
if (const int error = CopyGuestPath_nid_no_patch(path, copy)) return SceErrorFromErrno(error);
path = copy.c_str();
if (copy.empty()) return SceErrorFromErrno(2);
if (const int dot = RenameDotError_nid_no_patch(path)) return SceKernelError(dot);
std::filesystem::path native;
if (const int error = ResolvePathError_nid_no_patch(path, native)) return SceKernelError(error);
constexpr int GuestEperm = 1;
std::error_code error;
if (std::filesystem::is_directory(std::filesystem::symlink_status(native, error))) {
#ifdef _WIN32
const DWORD attributes = GetFileAttributesW(native.c_str());
if (attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
std::string junctionTarget;
if (File::WindowsSymbolicLink::ReadJunction(native, junctionTarget, "unlink")) {
if (RemoveDirectoryW(native.c_str()) == 0) return SceErrorFromErrno(GuestEperm);
RecordWrittenPath_nid_no_patch(native);
return 0;
}
}
#endif
return SceErrorFromErrno(GuestEperm);
}
if (NativeUnlink(native) != 0) {
#ifdef _WIN32
if (NativeSymbolicLinkLoop(native.parent_path())) return SCE_KERNEL_ERROR_ELOOP;
#endif
return SceErrorFromErrno(errno == ENOENT ? NotFoundError_nid_no_patch(native) : errno);
}
RecordWrittenPath_nid_no_patch(native);
return 0;
}
int APS5_VABI sceKernelFcntl(int d, int command, ...) {
const auto type = File::FcntlArgumentOf(command);
std::intptr_t argument = 0;
if (type != File::FcntlArgument::None) {
#ifdef _WIN32
__builtin_sysv_va_list arguments;
__builtin_sysv_va_start(arguments, command);
argument = type == File::FcntlArgument::Int ? __builtin_va_arg(arguments, int)
: reinterpret_cast<std::intptr_t>(__builtin_va_arg(arguments, void*));
__builtin_sysv_va_end(arguments);
#else
std::va_list arguments;
va_start(arguments, command);
argument = type == File::FcntlArgument::Int ? va_arg(arguments, int)
: reinterpret_cast<std::intptr_t>(va_arg(arguments, void*));
va_end(arguments);
#endif
}
int result;
if (GuestSockets::IsOpen(d)) {
if (type == File::FcntlArgument::Int) result = fcntl_nid_postfix(d, command, static_cast<int>(argument));
else if (type == File::FcntlArgument::Pointer) result = fcntl_nid_postfix(d, command, reinterpret_cast<void*>(argument));
else result = fcntl_nid_postfix(d, command);
} else {
result = File::Fcntl(d, command, argument);
}
return result < 0 ? SceKernelError(*__error_nid_postfix()) : result;
}
}