#ifndef CORE_LIBS_PRX_LIBC_INCLUDE_FILESTREAM_HPP #define CORE_LIBS_PRX_LIBC_INCLUDE_FILESTREAM_HPP #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _WIN32 #include #include #include "prx/libc/include/FileLock.hpp" extern "C" void* HostStandardHandle_nid_no_patch(int descriptor); extern "C" void KeepStandardHandle_nid_no_patch(int descriptor, void* handle); extern "C" void PrepareStandardStreams_nid_no_patch(); struct UcrtStreamState { char* pointer; char* base; int count; long flags; long descriptor; int characterBuffer; int bufferSize; }; extern "C" void LibcRegisterDirectoryStreams_nid_no_patch(int (*open)(const wchar_t* path), void (*forget)(int descriptor), void (*duplicate)(int from, int to)); extern "C" void ForgetDirectoryStream_nid_no_patch(int descriptor); extern "C" void DuplicateDirectoryStream_nid_no_patch(int from, int to); #else #include #include #endif #if defined(__GLIBC__) #include extern "C" int _IO_switch_to_get_mode(std::FILE* stream); #endif extern "C" int DuplicateHostDescriptor_nid_no_patch(int descriptor); extern "C" void LibcRegisterClosedDescriptors_nid_no_patch(void* (*begin)(int descriptor), void (*end)(void* closing)); extern "C" void* BeginClosingDescriptor_nid_no_patch(int descriptor); extern "C" void EndClosingDescriptor_nid_no_patch(void* closing); class ClosingDescriptor { public: ClosingDescriptor([[maybe_unused]] std::FILE* stream, int descriptor) #ifdef _WIN32 : _stream(stream), _closing(BeginClosingDescriptor_nid_no_patch(descriptor)) {} #else : _closing(BeginClosingDescriptor_nid_no_patch(descriptor)) {} #endif ~ClosingDescriptor() { EndClosingDescriptor_nid_no_patch(_closing); } ClosingDescriptor(const ClosingDescriptor&) = delete; ClosingDescriptor& operator=(const ClosingDescriptor&) = delete; private: #ifdef _WIN32 struct LockedStream { explicit LockedStream(std::FILE* value) : stream(value) { ::_lock_file(stream); } ~LockedStream() { ::_unlock_file(stream); } LockedStream(const LockedStream&) = delete; LockedStream& operator=(const LockedStream&) = delete; std::FILE* stream; } _stream; #endif void* _closing; }; struct GuestFilePrefix { unsigned char* position = nullptr; std::int32_t readRemaining = 0; std::int32_t writeRemaining = 0; std::int16_t flags = 0; std::int16_t descriptor = -1; unsigned char* buffer = nullptr; std::int32_t bufferSize = 0; std::int32_t bufferPadding = 0; std::int32_t lineBufferSize = 0; }; static_assert(offsetof(GuestFilePrefix, flags) == 16); static_assert(offsetof(GuestFilePrefix, descriptor) == 18); static_assert(offsetof(GuestFilePrefix, buffer) == 24); static_assert(offsetof(GuestFilePrefix, lineBufferSize) == 40); static constexpr const char* FOPEN_EXT_VERT = ".vert"; static constexpr const char* FOPEN_MSG_NULL_ARG = "null argument"; static constexpr const char* FOPEN_MSG_NOT_FOUND = "file not found"; static constexpr const char* FOPEN_MSG_OPEN_FAILED = "open failed"; extern "C" int KeepHostStandardError_nid_no_patch(); extern "C" int KeepHostStandardOutput_nid_no_patch(); class FileStream { // Only the macro-accessed FreeBSD prefix is exposed. The remaining guest // FILE area is reserved; host state lives beyond it and is never a guest FILE*. GuestFilePrefix _guest{}; std::byte _reserved[256 - sizeof(GuestFilePrefix)]{}; std::FILE* _handle; bool _dynamic; bool guestError = false; bool randomDevice = false; bool directory = false; std::atomic _orientation{0}; char16_t lowSurrogate = 0; unsigned pushedBack = 0; std::string bytesPushedBack; bool pushbackLive = false; signed char seekableCache = -1; #ifdef _WIN32 char* pushbackBuffer = nullptr; void ReleasePushbackBuffer(std::FILE* native) { if (!pushbackBuffer) return; if (native) { auto* state = reinterpret_cast(native); if (state->base == pushbackBuffer) { state->base = reinterpret_cast(&state->characterBuffer); state->pointer = state->base; state->count = 0; } } std::free(std::exchange(pushbackBuffer, nullptr)); } void MakePushbackRoomUnlocked() { constexpr long UcrtCrtBuffer = 0x0040; constexpr long UcrtNoBuffer = 0x0400; auto* state = reinterpret_cast(GetHandle()); if (state->base == nullptr || state->pointer != state->base || state->count <= 0) return; const long flags = std::atomic_ref(state->flags).load(); const bool ownedHere = state->base == pushbackBuffer; if (!ownedHere && (flags & (UcrtCrtBuffer | UcrtNoBuffer)) == 0) return; const std::size_t count = static_cast(state->count); const std::size_t size = std::max({count * 2, count + 16, static_cast(state->bufferSize > 0 ? state->bufferSize : 0)}); auto* const grown = static_cast(std::malloc(size)); if (!grown) return; std::memcpy(grown + size - count, state->pointer, count); if (ownedHere || (flags & UcrtCrtBuffer) == 0) std::free(std::exchange(pushbackBuffer, grown)); else std::free(state->base); state->base = grown; state->pointer = grown + size - count; } #endif public: std::string& PushedBackBytes() { return bytesPushedBack; } bool PushbackLive() const { return pushbackLive; } void ClearPushback() { bytesPushedBack.clear(); pushbackLive = false; } bool IsRegularFile() { if (seekableCache < 0) { #ifdef _WIN32 struct _stat64 status{}; seekableCache = ::_fstat64(::_fileno(GetHandle()), &status) == 0 && (status.st_mode & _S_IFMT) == _S_IFREG ? 1 : 0; #else struct stat status{}; seekableCache = ::fstat(::fileno(GetHandle()), &status) == 0 && S_ISREG(status.st_mode) ? 1 : 0; #endif } return seekableCache == 1; } std::int64_t TellSeekable() { if (!IsRegularFile()) return -1; #ifdef _WIN32 return ::_ftelli64(GetHandle()); #else return ::ftello(GetHandle()); #endif } void NotePushedBackByte(char byte, bool wasLive) { if (!wasLive) bytesPushedBack.clear(); bytesPushedBack.push_back(byte); pushbackLive = true; } explicit FileStream(std::FILE* handle, bool dynamic = false) : _handle(handle), _dynamic(dynamic) { if (!_handle) throw std::runtime_error("FileStream: null handle"); #ifdef _WIN32 PrepareStandardStreams_nid_no_patch(); #endif _guest.flags = handle == stdin ? 4 : handle == stdout || handle == stderr ? 8 : 0x10; #ifdef _WIN32 const int descriptor = _fileno(handle); #else const int descriptor = ::fileno(handle); #endif _guest.descriptor = descriptor >= 0 && descriptor <= 32767 ? static_cast(descriptor) : -1; } #ifdef _WIN32 ~FileStream() { ReleasePushbackBuffer(_handle); } #endif FileStream(const FileStream&) = delete; FileStream& operator=(const FileStream&) = delete; std::FILE* GetHandle() const { if (!_handle) throw std::runtime_error("FileStream: closed stream"); return _handle; } bool IsOpen() const { return _handle != nullptr; } int Orientation(int mode) { if (mode == 0) return _orientation.load(std::memory_order_relaxed); int expected = 0; _orientation.compare_exchange_strong(expected, mode > 0 ? 1 : -1, std::memory_order_relaxed); return _orientation.load(std::memory_order_relaxed); } bool IsDynamic() const { return _dynamic; } GuestFilePrefix& GuestState() { return _guest; } bool IsHostStandard() const { #ifdef _WIN32 return _handle == __acrt_iob_func(0) || _handle == __acrt_iob_func(1) || _handle == __acrt_iob_func(2); #else return _handle == stdin || _handle == stdout || _handle == stderr; #endif } void Detach() { #ifdef _WIN32 if (_handle) { ::_lock_file(_handle); ReleasePushbackBuffer(_handle); ::_unlock_file(_handle); } #endif _orientation.store(0, std::memory_order_relaxed); _handle = nullptr; _guest.flags = 0; _guest.descriptor = -1; lowSurrogate = 0; pushedBack = 0; seekableCache = -1; } void RestoreHostStandard(std::FILE* stream, int kept) { const int error = errno; #ifdef _WIN32 const bool restored = _handle || (::_wfreopen(L"NUL", stream == stdin ? L"r" : L"w", stream) && ::_dup2(kept, ::_fileno(stream)) == 0); ::_unlock_file(stream); ::_close(kept); #else const bool restored = _handle || (std::freopen("/dev/null", stream == stdin ? "r" : "w", stream) && ::dup2(kept, ::fileno(stream)) >= 0); ::funlockfile(stream); ::close(kept); #endif if (!restored) throw std::runtime_error("FileStream: cannot restore the host standard stream"); errno = error; } void MarkRandomDevice() { randomDevice = true; _guest.descriptor = -1; lowSurrogate = 0; pushedBack = 0; seekableCache = -1; } bool IsRandomDevice() const { return randomDevice; } void MarkDirectory() { directory = true; } bool IsDirectory() const { return directory; } bool Adopt(std::FILE* handle) { #ifdef _WIN32 ReleasePushbackBuffer(nullptr); #endif _handle = handle; _guest = {}; guestError = false; randomDevice = false; lowSurrogate = 0; pushedBack = 0; seekableCache = -1; if (!_handle) return false; _guest.flags = 0x10; #ifdef _WIN32 const int descriptor = _fileno(_handle); #else const int descriptor = ::fileno(_handle); #endif _guest.descriptor = descriptor >= 0 && descriptor <= 32767 ? static_cast(descriptor) : -1; return true; } bool Reopen(const std::filesystem::path& filename, const char* mode, [[maybe_unused]] std::FILE* (*open)(const std::filesystem::path&, const std::string&) = nullptr, [[maybe_unused]] bool directoryStream = false) { if (!_handle) { if (!open || filename.empty()) { errno = ENOENT; return false; } if (!Adopt(open(filename, mode))) return false; _orientation.store(0, std::memory_order_relaxed); return true; } auto* previous = GetHandle(); #ifdef _WIN32 ::_lock_file(previous); ReleasePushbackBuffer(previous); ::_unlock_file(previous); #endif _guest = {}; guestError = false; randomDevice = false; _orientation.store(0, std::memory_order_relaxed); lowSurrogate = 0; pushedBack = 0; seekableCache = -1; #ifdef _WIN32 std::wstring wideMode; for (const char character : std::string_view(mode)) wideMode.push_back(static_cast(character)); const int replaced = previous ? _fileno(previous) : -1; if (std::exchange(directory, false)) ForgetDirectoryStream_nid_no_patch(replaced); auto* const standard = HostStandardHandle_nid_no_patch(replaced); GuestFileLockForget_nid_no_patch(replaced); if (IsHostStandard() && replaced == 1) KeepHostStandardOutput_nid_no_patch(); if (IsHostStandard() && replaced == 2) KeepHostStandardError_nid_no_patch(); std::optional closing(std::in_place, previous, replaced); if (open && !filename.empty()) { if (!IsHostStandard()) { _handle = nullptr; std::fclose(previous); closing.reset(); _handle = open(filename, mode); } else { std::wstring resetMode; for (const char character : std::string_view(mode)) if (character != 'x') resetMode.push_back(static_cast(character)); const int kept = DuplicateHostDescriptor_nid_no_patch(replaced); if (kept >= 0) ::_lock_file(previous); _handle = nullptr; try { std::FILE* const replacement = open(filename, mode); if (replacement) { if (::_wfreopen(L"NUL", resetMode.c_str(), previous) == previous) { const int source = ::_fileno(replacement); const int moved = ::_dup2(source, replaced); const int error = errno; if (moved == 0 && directoryStream) DuplicateDirectoryStream_nid_no_patch(source, replaced); std::fclose(replacement); if (moved == 0 && directoryStream) ForgetDirectoryStream_nid_no_patch(source); if (moved == 0) _handle = previous; else errno = error; } else { const int error = errno; std::fclose(replacement); errno = error; } } } catch (...) { if (kept >= 0) RestoreHostStandard(previous, kept); KeepStandardHandle_nid_no_patch(replaced, standard); throw; } if (kept >= 0) RestoreHostStandard(previous, kept); } } else { const int kept = IsHostStandard() ? DuplicateHostDescriptor_nid_no_patch(replaced) : -1; if (kept >= 0) ::_lock_file(previous); _handle = ::_wfreopen(filename.c_str(), wideMode.c_str(), previous); if (kept >= 0) RestoreHostStandard(previous, kept); } KeepStandardHandle_nid_no_patch(replaced, standard); #else const int error = errno; try { #ifndef __EMSCRIPTEN__ if (::fileno(previous) == 1) KeepHostStandardOutput_nid_no_patch(); #endif if (::fileno(previous) == 2) KeepHostStandardError_nid_no_patch(); } catch (const std::system_error&) { errno = error; } const ClosingDescriptor closing(previous, ::fileno(previous)); const int kept = IsHostStandard() ? DuplicateHostDescriptor_nid_no_patch(::fileno(previous)) : -1; errno = error; if (kept >= 0) ::flockfile(previous); _handle = std::freopen(filename.c_str(), mode, previous); if (kept >= 0) RestoreHostStandard(previous, kept); #endif return Adopt(_handle); } void PublishStatus(bool endOfFile, bool error) { __atomic_store_n(&_guest.readRemaining, 0, __ATOMIC_RELAXED); __atomic_store_n(&_guest.writeRemaining, 0, __ATOMIC_RELAXED); auto old = __atomic_load_n(&_guest.flags, __ATOMIC_RELAXED); std::int16_t next; do next = static_cast((old & ~0x60) | (endOfFile ? 0x20 : 0) | (error ? 0x40 : 0)); while (!__atomic_compare_exchange_n(&_guest.flags, &old, next, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED)); } void DropFailedUnbufferedWrite() { #ifdef __APPLE__ if (_handle && (GetHandle()->_flags & __SNBF) != 0) ::fpurge(GetHandle()); #endif } void SyncStatus() { pushbackLive = false; if (!_handle) return; PublishStatus(std::feof(GetHandle()) != 0, std::ferror(GetHandle()) != 0 || guestError); } void SyncUnlockedStatus() { pushbackLive = false; if (!_handle) return; #ifdef _WIN32 const bool endOfFile = std::feof(GetHandle()) != 0; const bool error = std::ferror(GetHandle()) != 0; #elif defined(__APPLE__) const bool endOfFile = feof_unlocked(GetHandle()) != 0; const bool error = ferror_unlocked(GetHandle()) != 0; #else const bool endOfFile = feof_unlocked(GetHandle()) != 0; const bool error = ferror_unlocked(GetHandle()) != 0; #endif PublishStatus(endOfFile, error || guestError); } bool SwitchToReading() { #ifdef _WIN32 ::_lock_file(GetHandle()); const bool switched = SwitchToReadingUnlocked(); ::_unlock_file(GetHandle()); return switched; #else ::flockfile(GetHandle()); const bool switched = SwitchToReadingUnlocked(); ::funlockfile(GetHandle()); return switched; #endif } bool OpenForReading() { #ifdef _WIN32 constexpr long UcrtReading = 0x0001; constexpr long UcrtUpdate = 0x0004; std::atomic_ref state(reinterpret_cast(GetHandle())->flags); return (state.load() & (UcrtReading | UcrtUpdate)) != 0; #elif defined(__GLIBC__) return ::__freadable(GetHandle()) != 0; #else return true; #endif } bool SwitchToReadingUnlocked() { #ifdef _WIN32 constexpr long UcrtReading = 0x0001; constexpr long UcrtWriting = 0x0002; constexpr long UcrtUpdate = 0x0004; auto* native = GetHandle(); std::atomic_ref state(reinterpret_cast(native)->flags); if ((state.load() & (UcrtReading | UcrtUpdate)) == 0) { errno = 9; guestError = true; SyncUnlockedStatus(); return false; } if ((state.load() & (UcrtReading | UcrtUpdate)) != UcrtUpdate) return true; const bool switched = (state.load() & UcrtWriting) == 0 || ::_fflush_nolock(native) == 0; if (switched) { state.fetch_and(~UcrtWriting); state.fetch_or(UcrtReading); } SyncUnlockedStatus(); return switched; #elif defined(__GLIBC__) auto* native = GetHandle(); if (!::__freadable(native)) { errno = 9; guestError = true; SyncUnlockedStatus(); return false; } if (!::__fwriting(native)) return true; const bool switched = ::_IO_switch_to_get_mode(native) == 0; SyncUnlockedStatus(); return switched; #else return true; #endif } bool SwitchToWriting() { #ifdef _WIN32 ::_lock_file(GetHandle()); const bool switched = SwitchToWritingUnlocked(); ::_unlock_file(GetHandle()); return switched; #else return true; #endif } bool SwitchToWritingUnlocked() { #ifdef _WIN32 constexpr long UcrtReading = 0x0001; constexpr long UcrtWriting = 0x0002; constexpr long UcrtUpdate = 0x0004; constexpr long UcrtEndOfFile = 0x0008; if (randomDevice) return true; auto* native = reinterpret_cast(GetHandle()); std::atomic_ref state(native->flags); if ((state.load() & (UcrtWriting | UcrtUpdate)) == 0) { errno = 9; guestError = true; SyncUnlockedStatus(); return false; } if ((state.load() & (UcrtReading | UcrtUpdate)) != (UcrtReading | UcrtUpdate)) return true; native->count = 0; native->pointer = native->base; state.fetch_and(~(UcrtReading | UcrtEndOfFile)); SyncUnlockedStatus(); return true; #else return true; #endif } int PushBack(int value) { #ifdef _WIN32 auto* native = GetHandle(); ::_lock_file(native); if (value != EOF) MakePushbackRoomUnlocked(); const int result = ::_ungetc_nolock(value, native); ::_unlock_file(native); return result; #else return std::ungetc(value, GetHandle()); #endif } void KeepDirectoryReadError(bool failed) { if (failed && directory && (__atomic_load_n(&_guest.flags, __ATOMIC_RELAXED) & 0x40) != 0) errno = 21; } void SetError() { guestError = true; SyncStatus(); } void ClearError() { if (!_handle) return; std::clearerr(GetHandle()); guestError = false; SyncStatus(); } char16_t TakeLowSurrogate() { if (pushedBack != 0) return 0; return std::exchange(lowSurrogate, char16_t{0}); } void SetLowSurrogate(char16_t unit) { lowSurrogate = unit; pushedBack = 0; seekableCache = -1; } void NotePushback() { if (lowSurrogate != 0) ++pushedBack; } void NoteWideRead() { if (pushedBack != 0) --pushedBack; } int Close() { GetHandle(); #ifdef _WIN32 GuestFileLockForget_nid_no_patch(::_fileno(_handle)); if (std::exchange(directory, false)) ForgetDirectoryStream_nid_no_patch(::_fileno(_handle)); const ClosingDescriptor closing(_handle, ::_fileno(_handle)); #else const ClosingDescriptor closing(_handle, ::fileno(_handle)); #endif #ifdef _WIN32 ::_lock_file(_handle); ReleasePushbackBuffer(_handle); ::_unlock_file(_handle); #endif const int result = std::fclose(_handle); _handle = nullptr; _guest.flags = 0; _guest.descriptor = -1; _orientation.store(0, std::memory_order_relaxed); lowSurrogate = 0; pushedBack = 0; seekableCache = -1; return result; } }; static_assert(std::is_standard_layout_v); inline std::FILE* GetStreamHandle(FileStream* stream) { if (!stream) throw std::runtime_error("FileStream: null stream"); return stream->GetHandle(); } inline std::FILE* GetNativeStream(FileStream* stream) { auto* handle = GetStreamHandle(stream); if (stream->IsRandomDevice()) throw std::runtime_error("FileStream: this function is not implemented on a /dev/random or /dev/urandom stream"); return handle; } extern "C" { extern FileStream* __stdinp_nid_postfix; extern FileStream _Stdout_nid_postfix; extern FileStream _Stderr_nid_postfix; } #endif