#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/libc/include/FileStream.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 "prx/libkernel/Semaphore/include/Ksem.hpp" #include "SceTypes.hpp" #include #include #include #include #include #include #include #ifdef _WIN32 #include #include #include #include #include "prx/libc/include/WindowsDescriptor.hpp" #include "prx/libc/include/WindowsVerbatimPath.hpp" #include "prx/libkernel/File/include/WindowsSymbolicLink.hpp" #include "prx/libkernel/File/include/WindowsPermissions.hpp" #include "prx/libc/include/CreationMask.hpp" static HANDLE OpenNativeHandle(const std::filesystem::path& p, int nativeFlags, DWORD desired, SECURITY_ATTRIBUTES& security, DWORD attributes, bool& created) { constexpr DWORD share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE; const DWORD existing = (nativeFlags & _O_TRUNC) ? TRUNCATE_EXISTING : OPEN_EXISTING; for (int attempt = 0; attempt < 8; ++attempt) { if (nativeFlags & _O_CREAT) { const auto handle = CreateFileW(p.c_str(), desired, share, &security, CREATE_NEW, attributes, nullptr); if (handle != INVALID_HANDLE_VALUE) { created = true; return handle; } if (GetLastError() != ERROR_FILE_EXISTS || (nativeFlags & _O_EXCL)) return INVALID_HANDLE_VALUE; } const auto handle = CreateFileW(p.c_str(), desired, share, &security, existing, FILE_ATTRIBUTE_NORMAL, nullptr); if (handle != INVALID_HANDLE_VALUE || !(nativeFlags & _O_CREAT) || GetLastError() != ERROR_FILE_NOT_FOUND) return handle; } return INVALID_HANDLE_VALUE; } static void DeleteCreatedFile(HANDLE handle) { const HANDLE deleter = File::WindowsPermissions::Reopen(handle, DELETE | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES); if (deleter == INVALID_HANDLE_VALUE) return; FILE_BASIC_INFO basic{}; if (GetFileInformationByHandleEx(deleter, FileBasicInfo, &basic, sizeof(basic)) && (basic.FileAttributes & FILE_ATTRIBUTE_READONLY) != 0) { basic.FileAttributes &= ~static_cast(FILE_ATTRIBUTE_READONLY); if (basic.FileAttributes == 0) basic.FileAttributes = FILE_ATTRIBUTE_NORMAL; SetFileInformationByHandle(deleter, FileBasicInfo, &basic, sizeof(basic)); } FILE_DISPOSITION_INFO disposition{TRUE}; SetFileInformationByHandle(deleter, FileDispositionInfo, &disposition, sizeof(disposition)); CloseHandle(deleter); } 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; const auto requested = static_cast((mode & ~File::GetCreationMask_nid_no_patch()) & 06777); const DWORD attributes = (requested & _S_IWRITE) ? FILE_ATTRIBUTE_NORMAL : FILE_ATTRIBUTE_READONLY; SECURITY_ATTRIBUTES security{sizeof(SECURITY_ATTRIBUTES), nullptr, (nativeFlags & _O_NOINHERIT) == 0}; bool created = false; const auto handle = OpenNativeHandle(p, nativeFlags, desired, security, attributes, created); if (handle == INVALID_HANDLE_VALUE) { errno = WindowsOpenError_nid_no_patch(GetLastError()); return -1; } if (created) { if (const DWORD error = File::WindowsPermissions::Store(handle, requested); error != ERROR_SUCCESS) { DeleteCreatedFile(handle); CloseHandle(handle); errno = WindowsOpenError_nid_no_patch(error); return -1; } } const int descriptor = ::_open_osfhandle(reinterpret_cast(handle), nativeFlags & (_O_APPEND | _O_RDONLY | _O_BINARY | _O_NOINHERIT)); 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; const auto handle = WindowsDescriptorHandle_nid_no_patch(fd); if (handle == INVALID_HANDLE_VALUE) { errno = EBADF; return -1; } if (GetFileType(handle) == FILE_TYPE_PIPE) { errno = ESPIPE; return -1; } return ::_lseeki64(fd, offset, whence); } static bool NativeTransfersInParts(HANDLE handle, std::size_t n, const char* function) { if (File::TransferPartBytes(n, 0) == n) return false; if (::GetFileType(handle) == FILE_TYPE_DISK) return true; if (n > static_cast(std::numeric_limits::max())) { throw std::runtime_error(std::string(function) + ": nbytes exceeds platform limit"); } return false; } static std::int64_t NativeRead(int fd, void* buf, std::size_t n) { if (File::IsDirectoryDescriptor(fd)) { errno = EISDIR; return -1; } const auto positioned = File::LockPositionedTransfer(fd); const auto handle = WindowsDescriptorHandle_nid_no_patch(fd); if (handle == INVALID_HANDLE_VALUE) { errno = EBADF; return -1; } const bool parts = NativeTransfersInParts(handle, n, "sceKernelRead"); std::size_t done = 0; do { const auto part = parts ? File::TransferPartBytes(n, done) : n; const int result = ::_read(fd, static_cast(buf) + done, static_cast(part)); if (result < 0) { if (done != 0) break; if (_doserrno == ERROR_NO_DATA) errno = EAGAIN; return -1; } done += static_cast(result); if (static_cast(result) < part) break; } while (done < n); return static_cast(done); } static std::int64_t NativeWrite(int fd, const void* buf, std::size_t n) { const auto positioned = File::LockPositionedTransfer(fd); if (File::HasFixedSizeWrites(fd)) { const auto position = ::_lseeki64(fd, 0, SEEK_CUR); if (position < 0 || !File::LimitSharedMemoryWrite_nid_no_patch(fd, n, position)) return -1; if (n == 0) return 0; } const auto shared = File::WriteSharedMemory_nid_no_patch(fd, buf, n); if (shared != -2) return shared; if (File::Appends(fd)) { const auto appended = File::WriteAtEnd(fd, buf, n); if (appended != -2) return appended; } const auto handle = WindowsDescriptorHandle_nid_no_patch(fd); if (handle == INVALID_HANDLE_VALUE) { errno = EBADF; return -1; } const bool parts = NativeTransfersInParts(handle, n, "sceKernelWrite"); std::size_t done = 0; do { const auto part = parts ? File::TransferPartBytes(n, done) : n; const int result = ::_write(fd, static_cast(buf) + done, static_cast(part)); if (result < 0) { if (done != 0) break; if (errno == ENOSPC && _doserrno == 0 && ::GetFileType(handle) == FILE_TYPE_PIPE) errno = EAGAIN; if ((_doserrno == ERROR_NO_DATA || _doserrno == ERROR_BROKEN_PIPE) && ::GetFileType(handle) == FILE_TYPE_PIPE) errno = EPIPE; return -1; } done += static_cast(result); if (static_cast(result) < part) break; } while (done < n); return static_cast(done); } 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) { return NativeVerbatimPath_nid_no_patch(path, error); } 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; if (sceFlags & SCE_KERNEL_O_CLOEXEC) f |= _O_NOINHERIT; f |= _O_BINARY; return f; } #else #include #include #ifdef __APPLE__ #include #endif static int NativeOpen(const std::filesystem::path& p, int nativeFlags, std::uint16_t mode) { return ::open(p.c_str(), nativeFlags, static_cast(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 appending = File::LockAppendingTransfer(fd); #endif return ::lseek(fd, static_cast(offset), whence); } static std::int64_t NativeRead(int fd, void* buf, std::size_t n) { #ifdef __APPLE__ const auto appending = File::LockAppendingTransfer(fd); #endif const iovec whole{buf, n}; const auto parts = File::TransferInParts(fd, &whole, 1, nullptr, false); return parts == -2 ? ::read(fd, buf, n) : parts; } 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 appending = File::LockAppendingTransfer(fd); #endif const iovec whole{const_cast(buf), n}; const auto parts = File::TransferInParts(fd, &whole, 1, nullptr, true); return parts == -2 ? ::write(fd, buf, n) : parts; } 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; if (sceFlags & SCE_KERNEL_O_CLOEXEC) f |= O_CLOEXEC; 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(0x80020000u | static_cast(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(0x80020000u | static_cast(guest)); } static int TrailingSlashCreationError(const std::filesystem::path& native, int flags) { if ((flags & SCE_KERNEL_O_CREAT) == 0 || native.has_filename() || !native.has_relative_path()) return 0; std::error_code error; const auto status = std::filesystem::status(native, error); if (error) return FilesystemError(error); return status.type() == std::filesystem::file_type::not_found ? 2 : 0; } #ifdef _WIN32 static int CreationThroughSeparatorError(const std::filesystem::path& native, int flags) { if ((flags & SCE_KERNEL_O_CREAT) == 0 || native.has_filename() || !native.has_relative_path()) return 0; auto target = native; while (!target.has_filename() && target.has_relative_path()) target = target.parent_path(); std::error_code error; const auto status = std::filesystem::status(target, error); if (status.type() == std::filesystem::file_type::not_found) return 2; if (error) return FilesystemError(error); return std::filesystem::is_directory(status) ? 0 : 20; } #endif static int OpenNative(const std::filesystem::path& native, int flags, std::uint16_t mode) { if ((flags & SCE_KERNEL_O_DIRECTORY) != 0) flags &= ~SCE_KERNEL_O_CREAT; 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 std::error_code pathError; const auto metadataOpenPath = NativeMetadataPath(native, pathError); const auto& openNative = pathError ? native : metadataOpenPath; if ((flags & (SCE_KERNEL_O_DIRECTORY | SCE_KERNEL_O_CREAT)) == SCE_KERNEL_O_DIRECTORY) { std::error_code error; const auto status = std::filesystem::status(openNative, 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) && openNative.has_filename()) { const DWORD attributes = GetFileAttributesW(openNative.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; #ifdef _WIN32 if (std::filesystem::is_symlink(openNative, error)) return SceErrorFromErrno(GuestEmlink); const DWORD attributes = GetFileAttributesW(openNative.c_str()); if (attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) { std::string junctionTarget; if (File::WindowsSymbolicLink::ReadJunction(openNative, junctionTarget, "open")) return SceErrorFromErrno(GuestEmlink); } #else if (std::filesystem::is_symlink(native, error)) return SceErrorFromErrno(GuestEmlink); #endif } #ifdef _WIN32 const int separatorError = CreationThroughSeparatorError(native, flags); if (separatorError != 0 && separatorError != 2) return SceKernelError(separatorError); int fd = -1; if (separatorError == 2) errno = ENOENT; else fd = NativeOpen(openNative, MapFlags(flags), mode); #else int fd = NativeOpen(native, MapFlags(flags), mode); #endif #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; std::error_code directoryPathError; const auto directoryOpenPath = NativeMetadataPath(directory, directoryPathError); if (std::filesystem::is_directory(directoryPathError ? directory : directoryOpenPath, 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 if (fd < 0 && (errno == EISDIR || errno == EINVAL)) { const int openError = errno; const int lookupError = TrailingSlashCreationError(native, flags); errno = lookupError == 2 ? ENOENT : openError; if (lookupError != 0 && lookupError != 2) return SceKernelError(lookupError); } #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; } void File::ForgetClosedDescriptor(int descriptor) { File::ForgetRandomDevice(descriptor); File::ForgetDescriptor(descriptor); ForgetJitSharedMemory(descriptor); #ifdef _WIN32 File::ForgetFileLock(descriptor); #endif File::ForgetDirectoryDescriptor(descriptor); } namespace { void* BeginClosingStreamDescriptor(int descriptor) { EqueueDescriptorClosed(descriptor); #ifdef _WIN32 auto positioned = std::make_unique(File::LockPositionedTransfer(descriptor)); File::ForgetClosedDescriptor(descriptor); return positioned.release(); #else File::ForgetClosedDescriptor(descriptor); return nullptr; #endif } void EndClosingStreamDescriptor(void* closing) { delete static_cast(closing); } struct ClosedDescriptorRegistration { ClosedDescriptorRegistration() { LibcRegisterClosedDescriptors_nid_no_patch(&BeginClosingStreamDescriptor, &EndClosingStreamDescriptor); } ~ClosedDescriptorRegistration() { LibcRegisterClosedDescriptors_nid_no_patch(nullptr, nullptr); } ClosedDescriptorRegistration(const ClosedDescriptorRegistration&) = delete; ClosedDescriptorRegistration& operator=(const ClosedDescriptorRegistration&) = delete; }; const ClosedDescriptorRegistration g_closedDescriptorRegistration; } extern "C" { int APS5_VABI sceKernelOpen(const char* path, int flags, std::uint16_t mode) { const int savedErrno = *__error_nid_postfix(); if (File::InvalidOpenFlags(flags)) return File::KernelFileResult(savedErrno, SCE_KERNEL_ERROR_EINVAL); std::string copy; if (const int error = CopyGuestPath_nid_no_patch(path, copy)) return File::KernelFileResult(savedErrno, SceKernelError(error)); path = copy.c_str(); if (copy.empty()) return File::KernelFileResult(savedErrno, SCE_KERNEL_ERROR_ENOENT); APS5_LOG_OUT("path=%s flags=0x%X nativeFlags=0x%X mode=0%o", path, flags, MapFlags(flags), mode); if (std::string_view(path) == "/dev/null") { const int fd = File::OpenNullDevice(flags); if (fd < 0) return SceErrorFromErrno(errno); File::RememberDescriptor(fd, flags); return fd; } 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 File::KernelFileResult(savedErrno, SceErrorFromErrno(errno)); File::RememberDescriptor(fd, flags); return File::KernelFileResult(savedErrno, 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 : "", error, static_cast(result)); return File::KernelFileResult(savedErrno, 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 : "", reinterpret_cast(resolved.c_str()), static_cast(result)); } return File::KernelFileResult(savedErrno, 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(base)) / std::filesystem::path(reinterpret_cast(path)), flags, mode); } int APS5_VABI sceKernelClose(int d) { return File::RunKernelFileCall([&]() -> int { 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::ForgetClosedDescriptor(d); if (NativeClose(d) != 0) { if (errno == EBADF) return SCE_KERNEL_ERROR_EBADF; throw std::runtime_error(std::string("sceKernelClose") + ": close failed, fd=" + std::to_string(d) + ", errno=" + std::to_string(errno)); } return 0; }); } static std::int64_t KernelRead(int d, void* buf, std::size_t nbytes) { if (File::IsDirectoryDescriptor(d)) return SceErrorFromErrno(EISDIR); if (IsKqueueDescriptor_nid_no_patch(d) || IsKsemDescriptor(d)) return nbytes == 0 ? 0 : SCE_KERNEL_ERROR_EOPNOTSUPP; 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 KernelRead(d, &empty, 0); } const GuestArena::HostWrite destination(buf, nbytes); if (!destination.Open()) errno = EFAULT; else if (File::ReadRandomDevice(d, buf, nbytes)) return static_cast(nbytes); else if (const auto archived = File::ReadArchivedFile(d, buf, nbytes, nullptr)) return *archived < 0 ? SceIoErrorFromErrno(static_cast(-*archived)) : *archived; auto n = destination.Open() ? NativeRead(d, buf, nbytes) : -1; if (n < 0) return SceIoErrorFromErrno(errno); return static_cast(n); } std::int64_t APS5_VABI sceKernelRead(int d, void* buf, std::size_t nbytes) { return File::RunKernelFileCall([&] { return KernelRead(d, buf, nbytes); }); } static std::int64_t KernelWrite(int d, const void* buf, std::size_t nbytes) { if (File::IsVirtualDirectoryDescriptor(d)) return SceErrorFromErrno(EISDIR); if (IsKqueueDescriptor_nid_no_patch(d) || IsKsemDescriptor(d)) return SCE_KERNEL_ERROR_EOPNOTSUPP; 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 KernelWrite(d, &empty, 0); } const File::WriteSync sync(d); GuestArena::GuestArenaPrepareHostRead_nid_no_patch(buf, nbytes); auto n = NativeWrite(d, buf, nbytes); if (n < 0) return SceIoErrorFromErrno(errno); return static_cast(n); } std::int64_t APS5_VABI sceKernelWrite(int d, const void* buf, std::size_t nbytes) { return File::RunKernelFileCall([&] { return KernelWrite(d, buf, nbytes); }); } 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::max() - offset; } std::int64_t APS5_VABI sceKernelLseek(int d, std::int64_t offset, int whence) { return File::RunKernelFileCall([&]() -> std::int64_t { if (GuestSockets::IsOpen(d) || IsKqueueDescriptor_nid_no_patch(d) || IsKsemDescriptor(d)) return SCE_KERNEL_ERROR_ESPIPE; if (whence < 0 || whence > 2) { throw std::invalid_argument(std::string("sceKernelLseek") + ": 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 || !GuestCopyOut_nid_no_patch(sb, &archived, sizeof(archived))) return SceErrorFromErrno(GuestEfault); 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) { return File::RunKernelFileCall([&] { std::string copy; if (const int error = CopyGuestPath_nid_no_patch(path, copy)) return SceKernelError(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(base)) / std::filesystem::path(reinterpret_cast(path)); if (follow) return StatNative(native, std::string_view(path).back() == '/', sb); FileStat result{}; if (!File::FillLinkStat(native, &result)) return SceErrorFromErrno(errno); if (!GuestCopyOut_nid_no_patch(sb, &result, sizeof(result))) return SceErrorFromErrno(GuestEfault); return 0; } static int KernelUnlink(const char* path) { std::string copy; if (const int error = CopyGuestPath_nid_no_patch(path, copy)) return SceKernelError(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); #ifdef _WIN32 std::error_code unlinkPathError; const auto metadataUnlinkPath = NativeMetadataPath(native, unlinkPathError); const auto& unlinkNative = unlinkPathError ? native : metadataUnlinkPath; #else const auto& unlinkNative = native; #endif constexpr int GuestEperm = 1; std::error_code error; bool directory = std::filesystem::is_directory(std::filesystem::symlink_status(unlinkNative, error)); #ifdef _WIN32 constexpr DWORD DirectoryLink = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT; const DWORD linkAttributes = GetFileAttributesW(unlinkNative.c_str()); if (linkAttributes != INVALID_FILE_ATTRIBUTES && (linkAttributes & DirectoryLink) == DirectoryLink) directory = true; #endif #ifdef _WIN32 if (unlinkNative.has_filename() && unlinkNative.filename().native().find_first_of(L"*?<>\"") == std::wstring::npos) { WIN32_FIND_DATAW found{}; if (const HANDLE find = FindFirstFileW(unlinkNative.c_str(), &found); find != INVALID_HANDLE_VALUE) { FindClose(find); constexpr DWORD DirectoryLink = FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY; if ((found.dwFileAttributes & DirectoryLink) == DirectoryLink && found.dwReserved0 == IO_REPARSE_TAG_SYMLINK) { if (!RemoveDirectoryW(unlinkNative.c_str())) return SceErrorFromErrno(GetLastError() == ERROR_ACCESS_DENIED ? 13 : 5); RecordWrittenPath_nid_no_patch(native); return 0; } } } #endif if (directory) { #ifdef _WIN32 const DWORD attributes = GetFileAttributesW(unlinkNative.c_str()); if (attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) { std::string junctionTarget; if (File::WindowsSymbolicLink::ReadJunction(unlinkNative, junctionTarget, "unlink")) { if (RemoveDirectoryW(unlinkNative.c_str()) == 0) return SceErrorFromErrno(GuestEperm); RecordWrittenPath_nid_no_patch(native); return 0; } } #endif return SceErrorFromErrno(GuestEperm); } if (NativeUnlink(unlinkNative) != 0) { #ifdef _WIN32 if (NativeSymbolicLinkLoop(unlinkNative.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 sceKernelUnlink(const char* path) { return File::RunKernelFileCall([&] { return KernelUnlink(path); }); } 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(__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(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(argument)); else if (type == File::FcntlArgument::Pointer) result = fcntl_nid_postfix(d, command, reinterpret_cast(argument)); else result = fcntl_nid_postfix(d, command); } else { result = File::Fcntl(d, command, argument); } return result < 0 ? SceKernelError(*__error_nid_postfix()) : result; } }