From 88e5bdeebed5b4923b2887c0e50490dc380add20 Mon Sep 17 00:00:00 2001 From: erick-dsnk Date: Fri, 9 Oct 2026 14:18:16 +0200 Subject: [PATCH] feat(contentexport): export images into a persistent content catalog --- core/libs/SceTypes.hpp | 13 + .../prx/libSceContentExport/CMakeLists.txt | 8 +- .../libSceContentExport/ContentCatalog.hpp | 291 ++++++++++++++ core/libs/prx/libSceContentExport/Export.cpp | 360 ++++++++++++++++-- core/libs/tests/GuestContentExport.cpp | 353 +++++++++++++++-- docs/dev/TechnicalDebt.md | 2 + 6 files changed, 972 insertions(+), 55 deletions(-) create mode 100644 core/libs/prx/libSceContentExport/ContentCatalog.hpp diff --git a/core/libs/SceTypes.hpp b/core/libs/SceTypes.hpp index 887b13d57aef..051b6d44e17c 100644 --- a/core/libs/SceTypes.hpp +++ b/core/libs/SceTypes.hpp @@ -1533,6 +1533,19 @@ struct ContentExportInitParam2 { std::int64_t reserved1; }; +struct ContentExportParam { + char title[257]; + char reserved[257]; + char content_type[65]; +}; + +using ContentExportMalloc = void* (APS5_VABI*)(std::size_t size, void* userData); +using ContentExportFree = void (APS5_VABI*)(void* pointer, void* userData); +using ContentExportDataProvideFunction = int (APS5_VABI*)(void** data, std::size_t* size, void* userData); + +static_assert(sizeof(ContentExportParam) == 579); +static_assert(offsetof(ContentExportParam, content_type) == 514); + struct ContentSearchInitParam { std::size_t memory_size; }; struct PngEncCreateParam { diff --git a/core/libs/prx/libSceContentExport/CMakeLists.txt b/core/libs/prx/libSceContentExport/CMakeLists.txt index 7c401ea5fabf..4443872051af 100644 --- a/core/libs/prx/libSceContentExport/CMakeLists.txt +++ b/core/libs/prx/libSceContentExport/CMakeLists.txt @@ -1,13 +1,19 @@ add_library(libSceContentExport SHARED EXCLUDE_FROM_ALL Export.cpp) target_include_directories(libSceContentExport PRIVATE ${LIBS_INCLUDE_DIR}) +target_link_libraries(libSceContentExport PRIVATE decoder_png decoder_jpeg) +target_include_directories(libSceContentExport SYSTEM PRIVATE ${PROJECT_SOURCE_DIR}/3rdparty/stb) configure_windows_unwind(libSceContentExport) if(BUILD_TESTING) add_test_executable(guest_content_export_tests ${LIBS_INCLUDE_DIR}/tests/GuestContentExport.cpp) target_include_directories(guest_content_export_tests PRIVATE ${LIBS_INCLUDE_DIR}) - target_link_libraries(guest_content_export_tests PRIVATE libSceContentExport libc) + target_link_libraries(guest_content_export_tests PRIVATE libSceContentExport decoder_jpeg libc) configure_windows_unwind(guest_content_export_tests) add_test(NAME guest_content_export COMMAND guest_content_export_tests) + file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/guest_content_export) + set_tests_properties(guest_content_export PROPERTIES + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/guest_content_export + TIMEOUT 30) if(WIN32) set_tests_properties(guest_content_export PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") diff --git a/core/libs/prx/libSceContentExport/ContentCatalog.hpp b/core/libs/prx/libSceContentExport/ContentCatalog.hpp new file mode 100644 index 000000000000..30b25472bca7 --- /dev/null +++ b/core/libs/prx/libSceContentExport/ContentCatalog.hpp @@ -0,0 +1,291 @@ +#pragma once + +#include "prx/libc/include/General.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#include +#include +#include +#endif + +namespace ContentCatalog_nid_no_patch { + +struct Entry { + std::int64_t id = 0; + std::int64_t generation = 0; + std::string title; + std::string mimeType; + std::string path; + std::string iconPath; + std::uint64_t createdTime = 0; + std::int64_t size = 0; + std::int32_t contentType = 0; + std::int32_t generatorType = 2; + std::int32_t status = 1; + std::int32_t uploadStatus = 0; + std::array accounts{}; + std::uint32_t width = 0; + std::uint32_t height = 0; + double duration = 0; + bool hasDimensions = false; + bool hasDuration = false; +}; + +struct Snapshot { + std::vector entries; + std::int64_t updateId = 0; +}; + +inline std::filesystem::path Root_nid_no_patch() { + return ResolvePath_nid_no_patch("/data/anyps5-content"); +} + +inline std::uint64_t CurrentTick_nid_no_patch() { + const auto micros = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + return 62135596800000000ull + static_cast(micros); +} + +class Lock_nid_no_patch { +public: + explicit Lock_nid_no_patch(const std::filesystem::path& root) { + std::filesystem::create_directories(root); + const auto file = root / ".catalog.lock"; +#ifdef _WIN32 + handle = CreateFileW(file.c_str(), GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (handle == INVALID_HANDLE_VALUE) throw std::runtime_error("content catalog: lock open failed"); + OVERLAPPED position{}; + if (!LockFileEx(handle, LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &position)) { + CloseHandle(handle); + handle = INVALID_HANDLE_VALUE; + throw std::runtime_error("content catalog: lock failed"); + } +#else + descriptor = ::open(file.c_str(), O_CREAT | O_RDWR | O_CLOEXEC, 0600); + if (descriptor < 0) throw std::runtime_error("content catalog: lock open failed"); + int result; + do { result = ::flock(descriptor, LOCK_EX); } while (result < 0 && errno == EINTR); + if (result < 0) { + ::close(descriptor); + descriptor = -1; + throw std::runtime_error("content catalog: lock failed"); + } +#endif + } + + ~Lock_nid_no_patch() { +#ifdef _WIN32 + if (handle != INVALID_HANDLE_VALUE) CloseHandle(handle); +#else + if (descriptor >= 0) ::close(descriptor); +#endif + } + + Lock_nid_no_patch(const Lock_nid_no_patch&) = delete; + Lock_nid_no_patch& operator=(const Lock_nid_no_patch&) = delete; +private: +#ifdef _WIN32 + HANDLE handle = INVALID_HANDLE_VALUE; +#else + int descriptor = -1; +#endif +}; + +template +inline void WriteScalar_nid_no_patch(std::ostream& stream, const TValue& value) { + stream.write(reinterpret_cast(&value), sizeof(value)); + if (!stream) throw std::runtime_error("content catalog: metadata write failed"); +} + +template +inline void ReadScalar_nid_no_patch(std::istream& stream, TValue& value) { + stream.read(reinterpret_cast(&value), sizeof(value)); + if (!stream) throw std::runtime_error("content catalog: truncated metadata"); +} + +inline void WriteString_nid_no_patch(std::ostream& stream, const std::string& value) { + const auto size = static_cast(value.size()); + WriteScalar_nid_no_patch(stream, size); + stream.write(value.data(), size); + if (!stream) throw std::runtime_error("content catalog: metadata write failed"); +} + +inline void ReadString_nid_no_patch(std::istream& stream, std::string& value, std::uint32_t limit) { + std::uint32_t size = 0; + ReadScalar_nid_no_patch(stream, size); + if (size > limit) throw std::runtime_error("content catalog: invalid metadata string size"); + value.resize(size); + stream.read(value.data(), size); + if (!stream || value.find('\0') != std::string::npos) + throw std::runtime_error("content catalog: invalid metadata string"); +} + +inline void WriteEntry_nid_no_patch(const std::filesystem::path& directory, const Entry& entry) { + std::ofstream stream(directory / "entry.bin", std::ios::binary | std::ios::trunc); + WriteScalar_nid_no_patch(stream, std::uint64_t{0x31544E43535041}); + WriteScalar_nid_no_patch(stream, entry.id); + WriteScalar_nid_no_patch(stream, entry.generation); + WriteScalar_nid_no_patch(stream, entry.createdTime); + WriteScalar_nid_no_patch(stream, entry.size); + WriteScalar_nid_no_patch(stream, entry.contentType); + WriteScalar_nid_no_patch(stream, entry.width); + WriteScalar_nid_no_patch(stream, entry.height); + WriteScalar_nid_no_patch(stream, entry.duration); + WriteScalar_nid_no_patch(stream, std::uint8_t{entry.hasDimensions}); + WriteScalar_nid_no_patch(stream, std::uint8_t{entry.hasDuration}); + for (const auto account : entry.accounts) WriteScalar_nid_no_patch(stream, account); + WriteString_nid_no_patch(stream, entry.title); + WriteString_nid_no_patch(stream, entry.mimeType); + WriteString_nid_no_patch(stream, entry.path); + WriteString_nid_no_patch(stream, entry.iconPath); + stream.close(); + if (!stream) throw std::runtime_error("content catalog: metadata close failed"); +} + +inline Entry ReadEntry_nid_no_patch(const std::filesystem::path& directory, std::int64_t id) { + std::ifstream stream(directory / "entry.bin", std::ios::binary); + std::uint64_t magic = 0; + ReadScalar_nid_no_patch(stream, magic); + if (magic != 0x31544E43535041) throw std::runtime_error("content catalog: unknown metadata version"); + Entry entry; + ReadScalar_nid_no_patch(stream, entry.id); + ReadScalar_nid_no_patch(stream, entry.generation); + ReadScalar_nid_no_patch(stream, entry.createdTime); + ReadScalar_nid_no_patch(stream, entry.size); + ReadScalar_nid_no_patch(stream, entry.contentType); + ReadScalar_nid_no_patch(stream, entry.width); + ReadScalar_nid_no_patch(stream, entry.height); + ReadScalar_nid_no_patch(stream, entry.duration); + std::uint8_t dimensions = 0; + std::uint8_t duration = 0; + ReadScalar_nid_no_patch(stream, dimensions); + ReadScalar_nid_no_patch(stream, duration); + if (entry.id != id || entry.generation <= 0 || entry.size < 0 || dimensions > 1 || duration > 1) + throw std::runtime_error("content catalog: invalid metadata"); + entry.hasDimensions = dimensions != 0; + entry.hasDuration = duration != 0; + for (auto& account : entry.accounts) ReadScalar_nid_no_patch(stream, account); + ReadString_nid_no_patch(stream, entry.title, 256); + ReadString_nid_no_patch(stream, entry.mimeType, 64); + ReadString_nid_no_patch(stream, entry.path, 1024); + ReadString_nid_no_patch(stream, entry.iconPath, 1024); + if (stream.peek() != std::char_traits::eof()) + throw std::runtime_error("content catalog: trailing metadata"); + const auto content = ResolvePath_nid_no_patch(entry.path.c_str()); + if (content.parent_path() != directory || content.filename().string().find("content.") != 0) + throw std::runtime_error("content catalog: invalid content path"); + std::error_code error; + const auto size = std::filesystem::file_size(content, error); + if (error || size != static_cast(entry.size)) entry.status = 0; + if (!entry.iconPath.empty()) { + const auto icon = ResolvePath_nid_no_patch(entry.iconPath.c_str()); + if (icon.parent_path() != directory || icon.filename().string().find("thumbnail.") != 0) + throw std::runtime_error("content catalog: invalid icon path"); + if (!std::filesystem::is_regular_file(icon, error) || error) entry.status = 0; + } + return entry; +} + +inline Snapshot ReadUnlocked_nid_no_patch(const std::filesystem::path& root) { + Snapshot snapshot; + std::error_code error; + if (!std::filesystem::exists(root, error)) { + if (error) throw std::filesystem::filesystem_error("content catalog", root, error); + return snapshot; + } + for (const auto& item : std::filesystem::directory_iterator(root)) { + const auto name = item.path().filename().string(); + std::int64_t id = 0; + const auto parsed = std::from_chars(name.data(), name.data() + name.size(), id); + if (parsed.ec != std::errc{} || parsed.ptr != name.data() + name.size() || id <= 0) continue; + if (!item.is_directory()) throw std::runtime_error("content catalog: invalid entry directory"); + snapshot.entries.push_back(ReadEntry_nid_no_patch(item.path(), id)); + snapshot.updateId = std::max(snapshot.updateId, snapshot.entries.back().generation); + } + std::ranges::sort(snapshot.entries, {}, &Entry::id); + return snapshot; +} + +inline Snapshot Read_nid_no_patch() { + const auto root = Root_nid_no_patch(); + Lock_nid_no_patch lock(root); + return ReadUnlocked_nid_no_patch(root); +} + +class Transaction_nid_no_patch { +public: + Transaction_nid_no_patch() { + const auto root = Root_nid_no_patch(); + Lock_nid_no_patch lock(root); + const auto snapshot = ReadUnlocked_nid_no_patch(root); + const auto previous = snapshot.entries.empty() ? std::int64_t{0} : snapshot.entries.back().id; + if (previous == std::numeric_limits::max()) + throw std::overflow_error("content catalog: content ids exhausted"); + id = std::max(static_cast(CurrentTick_nid_no_patch()), previous + 1); + for (;;) { + directory = root / (".pending-" + std::to_string(id)); + finalDirectory = root / std::to_string(id); + if (!std::filesystem::exists(finalDirectory) && std::filesystem::create_directory(directory)) break; + if (id == std::numeric_limits::max()) + throw std::overflow_error("content catalog: content ids exhausted"); + ++id; + } + } + + ~Transaction_nid_no_patch() { + if (!committed) { + std::error_code error; + std::filesystem::remove_all(directory, error); + } + } + + Transaction_nid_no_patch(const Transaction_nid_no_patch&) = delete; + Transaction_nid_no_patch& operator=(const Transaction_nid_no_patch&) = delete; + + std::int64_t Id_nid_no_patch() const { return id; } + const std::filesystem::path& Directory_nid_no_patch() const { return directory; } + + std::string GuestPath_nid_no_patch(const std::string& file) const { + return "/data/anyps5-content/" + std::to_string(id) + "/" + file; + } + + void Commit_nid_no_patch(Entry entry) { + const auto root = Root_nid_no_patch(); + Lock_nid_no_patch lock(root); + const auto snapshot = ReadUnlocked_nid_no_patch(root); + if (snapshot.updateId == std::numeric_limits::max()) + throw std::overflow_error("content catalog: generations exhausted"); + entry.generation = snapshot.updateId + 1; + WriteEntry_nid_no_patch(directory, entry); + std::filesystem::rename(directory, finalDirectory); + committed = true; + } + +private: + std::int64_t id = 0; + std::filesystem::path directory; + std::filesystem::path finalDirectory; + bool committed = false; +}; + +} diff --git a/core/libs/prx/libSceContentExport/Export.cpp b/core/libs/prx/libSceContentExport/Export.cpp index 1a7fde306887..448251406467 100644 --- a/core/libs/prx/libSceContentExport/Export.cpp +++ b/core/libs/prx/libSceContentExport/Export.cpp @@ -1,54 +1,358 @@ -#include -#include #include "SceTypes.hpp" +#include "Decoder/Png.hpp" +#include "Decoder/Jpeg.hpp" +#include "ContentCatalog.hpp" +#include "prx/libSceUserService/UserService.hpp" #include "prx/libc/include/General.hpp" -#include +#include +#include +#include +#include +#include +#include +#include #include #include +#include +#include + +#define STB_IMAGE_STATIC +#define STB_IMAGE_IMPLEMENTATION +#define STBI_ONLY_GIF +#define STBI_NO_STDIO +#include "stb_image.h" namespace { -std::atomic g_initialized{false}; + +constexpr int Busy = static_cast(0x809D3003); +constexpr int NoInit = static_cast(0x809D3004); +constexpr int NoMemory = static_cast(0x809D3006); +constexpr int FileNotFound = static_cast(0x809D3011); +constexpr int UnsupportedFormat = static_cast(0x809D3012); +constexpr int InvalidParam = static_cast(0x809D3016); +constexpr int ExecutionMax = static_cast(0x809D3018); +constexpr int UnsupportedThumbnail = static_cast(0x809D3019); +constexpr int DataProvideError = static_cast(0x809D301B); + +struct Session { bool busy = false; }; +struct State { + std::mutex mutex; + bool initialized = false; + ContentExportInitParam2 allocator{}; + std::unordered_map> sessions; + int nextId = 1; +}; + +State& State_nid_no_patch() { + static State state; + return state; +} + +class Operation_nid_no_patch { +public: + explicit Operation_nid_no_patch(int id) { + auto& state = State_nid_no_patch(); + std::lock_guard lock(state.mutex); + if (!state.initialized) { result = NoInit; return; } + const auto found = state.sessions.find(id); + if (found == state.sessions.end()) throw std::invalid_argument("content export: invalid session"); + if (found->second->busy) { result = Busy; return; } + session = found->second; + allocator = state.allocator; + session->busy = true; + } + ~Operation_nid_no_patch() { + if (session) { + auto& state = State_nid_no_patch(); + std::lock_guard lock(state.mutex); + session->busy = false; + } + } + Operation_nid_no_patch(const Operation_nid_no_patch&) = delete; + Operation_nid_no_patch& operator=(const Operation_nid_no_patch&) = delete; + int Result_nid_no_patch() const { return result; } + const ContentExportInitParam2& Allocator_nid_no_patch() const { return allocator; } +private: + std::shared_ptr session; + ContentExportInitParam2 allocator{}; + int result = 0; +}; + +class Buffer_nid_no_patch { +public: + explicit Buffer_nid_no_patch(const ContentExportInitParam2& param) : allocator(param) { + size = allocator.buffer_size == 0 ? 64 * 1024 : allocator.buffer_size; + if (size > static_cast(std::numeric_limits::max())) + throw std::overflow_error("content export: allocator buffer too large"); + pointer = reinterpret_cast(allocator.malloc_func)(size, allocator.user_data); + } + ~Buffer_nid_no_patch() { + if (pointer) reinterpret_cast(allocator.free_func)(pointer, allocator.user_data); + } + Buffer_nid_no_patch(const Buffer_nid_no_patch&) = delete; + Buffer_nid_no_patch& operator=(const Buffer_nid_no_patch&) = delete; + void* Data_nid_no_patch() const { return pointer; } + std::size_t Size_nid_no_patch() const { return size; } +private: + ContentExportInitParam2 allocator; + void* pointer = nullptr; + std::size_t size = 0; +}; + +struct MediaFormat { + const char* mimeType; + const char* extension; + std::int32_t type; +}; +constexpr std::array Formats{ + MediaFormat{"image/jpeg", "jpg", 1}, + MediaFormat{"image/png", "png", 1}, + MediaFormat{"image/gif", "gif", 1}, +}; + +template +bool Terminated_nid_no_patch(const char (&value)[TSize]) { + return std::memchr(value, 0, TSize) != nullptr; +} + +const MediaFormat* Format_nid_no_patch(const ContentExportParam& param) { + if (std::ranges::any_of(param.reserved, [](char value) { return value != 0; })) + NotImplemented_nid_no_patch("content export: nonzero reserved/comment field"); + if (std::string_view(param.content_type).starts_with("video/")) + NotImplemented_nid_no_patch("content export: video import semantics"); + const auto found = std::ranges::find_if(Formats, [&](const auto& format) { + return std::strcmp(param.content_type, format.mimeType) == 0; + }); + return found == Formats.end() ? nullptr : &*found; +} + +int CopyFile_nid_no_patch(const char* source, const std::filesystem::path& destination, + const ContentExportInitParam2& allocator) { + const auto native = ResolvePath_nid_no_patch(source); + std::error_code error; + if (!std::filesystem::exists(native, error)) { + if (error) throw std::filesystem::filesystem_error("content export", native, error); + return FileNotFound; + } + if (!std::filesystem::is_regular_file(native)) return UnsupportedFormat; + std::ifstream input(native, std::ios::binary); + if (!input) throw std::runtime_error("content export: source open failed"); + Buffer_nid_no_patch buffer(allocator); + if (!buffer.Data_nid_no_patch()) return NoMemory; + std::ofstream output(destination, std::ios::binary | std::ios::trunc); + if (!output) throw std::runtime_error("content export: destination open failed"); + for (;;) { + input.read(static_cast(buffer.Data_nid_no_patch()), static_cast(buffer.Size_nid_no_patch())); + const auto size = input.gcount(); + if (size) output.write(static_cast(buffer.Data_nid_no_patch()), size); + if (!output) throw std::runtime_error("content export: file write failed"); + if (input.eof()) break; + if (!input) throw std::runtime_error("content export: file read failed"); + } + output.close(); + if (!output) throw std::runtime_error("content export: file close failed"); + return 0; +} + +int CopyData_nid_no_patch(const std::filesystem::path& destination, std::size_t expected, + ContentExportDataProvideFunction callback, void* userData, + const ContentExportInitParam2& allocator) { + Buffer_nid_no_patch buffer(allocator); + if (!buffer.Data_nid_no_patch()) return NoMemory; + std::ofstream output(destination, std::ios::binary | std::ios::trunc); + if (!output) throw std::runtime_error("content export: destination open failed"); + std::size_t written = 0; + for (;;) { + void* data = nullptr; + std::size_t size = 0; + const auto result = callback(&data, &size, userData); + if ((result != 0 && result != 1) || size > expected - written || (size != 0 && !data) + || (result == 0 && size == 0)) return DataProvideError; + const auto* bytes = static_cast(data); + for (std::size_t offset = 0; offset < size;) { + const auto count = std::min(buffer.Size_nid_no_patch(), size - offset); + std::memcpy(buffer.Data_nid_no_patch(), bytes + offset, count); + output.write(static_cast(buffer.Data_nid_no_patch()), static_cast(count)); + if (!output) throw std::runtime_error("content export: data write failed"); + offset += count; + } + written += size; + if (result == 1) { + if (written != expected) return DataProvideError; + break; + } + } + output.close(); + if (!output) throw std::runtime_error("content export: data close failed"); + return 0; +} + +bool ReadMedia_nid_no_patch(const std::filesystem::path& path, const MediaFormat& format, + ContentCatalog_nid_no_patch::Entry& entry) { + std::ifstream stream(path, std::ios::binary); + if (!stream) throw std::runtime_error("content export: media open failed"); + const std::vector bytes{std::istreambuf_iterator(stream), std::istreambuf_iterator()}; + if (stream.bad()) throw std::runtime_error("content export: media read failed"); + if (std::string_view(format.mimeType) == "image/png") { + const auto image = Decoder::Png::Decode(bytes); + if (!image) return false; + entry.width = image->width; + entry.height = image->height; + } else if (std::string_view(format.mimeType) == "image/jpeg") { + const auto image = Decoder::Jpeg::Decode(bytes); + if (!image) return false; + entry.width = image->width; + entry.height = image->height; + } else { + if (bytes.size() > static_cast(std::numeric_limits::max())) + NotImplemented_nid_no_patch("content export: GIF beyond decoder size limit"); + int width = 0; + int height = 0; + int channels = 0; + const auto pixels = stbi_load_from_memory(bytes.data(), static_cast(bytes.size()), &width, &height, &channels, 4); + if (!pixels) return false; + stbi_image_free(pixels); + entry.width = static_cast(width); + entry.height = static_cast(height); + } + entry.hasDimensions = true; + return entry.width > 0 && entry.height > 0; +} + +template +int Export_nid_no_patch(const Operation_nid_no_patch& operation, const ContentExportParam& param, + const MediaFormat& format, char* path, std::size_t capacity, + const char* thumbnail, TCopy copy) { + ContentCatalog_nid_no_patch::Transaction_nid_no_patch transaction; + const auto filename = std::string("content.") + format.extension; + const auto guest = transaction.GuestPath_nid_no_patch(filename); + if (capacity <= guest.size()) return InvalidParam; + const auto native = transaction.Directory_nid_no_patch() / filename; + if (const auto result = copy(native); result != 0) return result; + ContentCatalog_nid_no_patch::Entry entry; + if (!ReadMedia_nid_no_patch(native, format, entry)) return UnsupportedFormat; + const auto size = std::filesystem::file_size(native); + if (size > static_cast(std::numeric_limits::max())) + throw std::overflow_error("content export: content too large"); + entry.id = transaction.Id_nid_no_patch(); + entry.title = param.title; + entry.mimeType = format.mimeType; + entry.path = guest; + entry.createdTime = ContentCatalog_nid_no_patch::CurrentTick_nid_no_patch(); + entry.size = static_cast(size); + entry.contentType = format.type; + entry.accounts.fill(USER_SERVICE_USER_ID_INVALID); + entry.accounts[0] = USER_SERVICE_INITIAL_USER_ID; + if (thumbnail) { + const auto thumbnailNative = transaction.Directory_nid_no_patch() / "thumbnail"; + if (const auto result = CopyFile_nid_no_patch(thumbnail, thumbnailNative, operation.Allocator_nid_no_patch()); result != 0) + return result; + bool recognized = false; + for (const auto& thumbnailFormat : Formats) { + if (thumbnailFormat.type != 1) continue; + ContentCatalog_nid_no_patch::Entry ignored; + if (!ReadMedia_nid_no_patch(thumbnailNative, thumbnailFormat, ignored)) continue; + const auto name = std::string("thumbnail.") + thumbnailFormat.extension; + std::filesystem::rename(thumbnailNative, transaction.Directory_nid_no_patch() / name); + entry.iconPath = transaction.GuestPath_nid_no_patch(name); + recognized = true; + break; + } + if (!recognized) return UnsupportedThumbnail; + } + transaction.Commit_nid_no_patch(entry); + std::memcpy(path, guest.c_str(), guest.size() + 1); + return 0; +} + +bool Parameters_nid_no_patch(const ContentExportParam* param, char* path, std::size_t capacity) { + return param && path && capacity != 0 && Terminated_nid_no_patch(param->title) + && Terminated_nid_no_patch(param->content_type); +} + } extern "C" { -int APS5_VABI sceContentExportInit2(const ContentExportInitParam2* init_param) { - if (init_param == nullptr) APS5_INVALID_ARG_EX; - if (init_param->malloc_func == nullptr || init_param->free_func == nullptr) throw std::invalid_argument(std::string(__func__) + ": missing allocator functions"); - if (init_param->reserved0 != 0 || init_param->reserved1 != 0) throw std::invalid_argument(std::string(__func__) + ": reserved fields are not zero"); - bool expected = false; - if (!g_initialized.compare_exchange_strong(expected, true)) throw std::logic_error(std::string(__func__) + ": already initialized"); +int APS5_VABI sceContentExportInit2(const ContentExportInitParam2* initParam) { + if (!initParam) APS5_INVALID_ARG_EX; + if (!initParam->malloc_func || !initParam->free_func) throw std::invalid_argument(std::string(__func__) + ": missing allocator functions"); + if (initParam->reserved0 != 0 || initParam->reserved1 != 0) throw std::invalid_argument(std::string(__func__) + ": reserved fields are not zero"); + if (initParam->buffer_size != 0 && initParam->buffer_size < 0x100) return InvalidParam; + auto& state = State_nid_no_patch(); + std::lock_guard lock(state.mutex); + if (state.initialized) throw std::logic_error(std::string(__func__) + ": already initialized"); + state.allocator = *initParam; + state.initialized = true; return 0; } -int APS5_VABI sceContentExportFinish(void) { - NotImplemented_nid_no_patch(__func__); - return 0; +int APS5_VABI sceContentExportStart() { + auto& state = State_nid_no_patch(); + std::lock_guard lock(state.mutex); + if (!state.initialized) return NoInit; + if (state.sessions.size() >= 10) return ExecutionMax; + if (state.nextId == std::numeric_limits::max()) throw std::overflow_error("content export: session ids exhausted"); + const int id = state.nextId++; + state.sessions.emplace(id, std::make_shared()); + return id; } -int APS5_VABI sceContentExportFromData(void) { - NotImplemented_nid_no_patch(__func__); - return 0; +int APS5_VABI sceContentExportFinish(int expId) { + auto& state = State_nid_no_patch(); + std::lock_guard lock(state.mutex); + if (!state.initialized) return NoInit; + const auto found = state.sessions.find(expId); + if (found == state.sessions.end()) throw std::invalid_argument(std::string(__func__) + ": invalid session"); + if (found->second->busy) return Busy; + state.sessions.erase(found); + return 0; } -int APS5_VABI sceContentExportFromFile(void) { - NotImplemented_nid_no_patch(__func__); - return 0; +int APS5_VABI sceContentExportFromData(int expId, const ContentExportParam* param, + std::size_t contentLength, ContentExportDataProvideFunction func, void* userData, char* path, std::size_t pathBufferLength) { + Operation_nid_no_patch operation(expId); + if (operation.Result_nid_no_patch()) return operation.Result_nid_no_patch(); + if (!Parameters_nid_no_patch(param, path, pathBufferLength) || !func + || contentLength > static_cast(std::numeric_limits::max())) return InvalidParam; + const auto* format = Format_nid_no_patch(*param); + if (!format) return UnsupportedFormat; + return Export_nid_no_patch(operation, *param, *format, path, pathBufferLength, nullptr, + [&](const auto& native) { + return CopyData_nid_no_patch(native, contentLength, func, userData, operation.Allocator_nid_no_patch()); + }); } -int APS5_VABI sceContentExportFromFileWithThumbnail(void) { - NotImplemented_nid_no_patch(__func__); - return 0; +int APS5_VABI sceContentExportFromFile(int expId, const ContentExportParam* param, + const char* srcPath, char* path, std::size_t pathBufferLength) { + Operation_nid_no_patch operation(expId); + if (operation.Result_nid_no_patch()) return operation.Result_nid_no_patch(); + if (!Parameters_nid_no_patch(param, path, pathBufferLength) || !srcPath || !*srcPath) return InvalidParam; + const auto* format = Format_nid_no_patch(*param); + if (!format) return UnsupportedFormat; + return Export_nid_no_patch(operation, *param, *format, path, pathBufferLength, nullptr, + [&](const auto& native) { return CopyFile_nid_no_patch(srcPath, native, operation.Allocator_nid_no_patch()); }); } -int APS5_VABI sceContentExportStart(void) { - NotImplemented_nid_no_patch(__func__); - return 0; +int APS5_VABI sceContentExportFromFileWithThumbnail(int expId, const ContentExportParam* param, + const char* srcPath, const char* thumbnailPath, char* path, std::size_t pathBufferLength) { + Operation_nid_no_patch operation(expId); + if (operation.Result_nid_no_patch()) return operation.Result_nid_no_patch(); + if (!Parameters_nid_no_patch(param, path, pathBufferLength) || !srcPath || !*srcPath + || !thumbnailPath || !*thumbnailPath) return InvalidParam; + const auto* format = Format_nid_no_patch(*param); + if (!format) return UnsupportedFormat; + return Export_nid_no_patch(operation, *param, *format, path, pathBufferLength, thumbnailPath, + [&](const auto& native) { return CopyFile_nid_no_patch(srcPath, native, operation.Allocator_nid_no_patch()); }); } -int APS5_VABI sceContentExportTerm(void) { - bool expected = true; - if (!g_initialized.compare_exchange_strong(expected, false)) throw std::logic_error(std::string(__func__) + ": not initialized"); +int APS5_VABI sceContentExportTerm() { + auto& state = State_nid_no_patch(); + std::lock_guard lock(state.mutex); + if (!state.initialized) throw std::logic_error(std::string(__func__) + ": not initialized"); + if (!state.sessions.empty()) return Busy; + state.allocator = {}; + state.initialized = false; return 0; } diff --git a/core/libs/tests/GuestContentExport.cpp b/core/libs/tests/GuestContentExport.cpp index 12038531a8b5..f6bd9f368ddf 100644 --- a/core/libs/tests/GuestContentExport.cpp +++ b/core/libs/tests/GuestContentExport.cpp @@ -1,42 +1,343 @@ #include "SceTypes.hpp" +#include "Decoder/Jpeg.hpp" +#include "prx/libSceContentExport/ContentCatalog.hpp" +#include "prx/libSceUserService/UserService.hpp" +#include +#include #include +#include +#include +#include +#include #include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif -extern "C" int APS5_VABI sceContentExportInit2(const ContentExportInitParam2* init_param); -extern "C" int APS5_VABI sceContentExportTerm(void); +extern "C" { +int APS5_VABI sceContentExportInit2(const ContentExportInitParam2*); +int APS5_VABI sceContentExportTerm(); +int APS5_VABI sceContentExportStart(); +int APS5_VABI sceContentExportFinish(int); +int APS5_VABI sceContentExportFromFile(int, const ContentExportParam*, const char*, char*, std::size_t); +int APS5_VABI sceContentExportFromFileWithThumbnail(int, const ContentExportParam*, const char*, const char*, char*, std::size_t); +int APS5_VABI sceContentExportFromData(int, const ContentExportParam*, std::size_t, ContentExportDataProvideFunction, void*, char*, std::size_t); +} namespace { -void Require(bool value) { if (!value) std::abort(); } +constexpr int Busy = static_cast(0x809D3003); +constexpr int NoInit = static_cast(0x809D3004); +constexpr int NoMemory = static_cast(0x809D3006); +constexpr int FileNotFound = static_cast(0x809D3011); +constexpr int UnsupportedFormat = static_cast(0x809D3012); +constexpr int InvalidParam = static_cast(0x809D3016); +constexpr int ExecutionMax = static_cast(0x809D3018); +constexpr int UnsupportedThumbnail = static_cast(0x809D3019); +constexpr int DataProvideError = static_cast(0x809D301B); + +constexpr std::array Png{ + 0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0x00,0x00,0x00,0x0D,0x49,0x48,0x44,0x52, + 0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x01,0x10,0x00,0x00,0x00,0x00,0x81,0xD9,0xFC, + 0x15,0x00,0x00,0x00,0x0D,0x49,0x44,0x41,0x54,0x78,0x9C,0x63,0x10,0x32,0x59,0x7D, + 0x16,0x00,0x03,0x0C,0x01,0xBF,0x6E,0xB9,0xC6,0x5D,0x00,0x00,0x00,0x00,0x49,0x45, + 0x4E,0x44,0xAE,0x42,0x60,0x82 +}; + +void Require(bool value, const char* message) { + if (!value) { std::cerr << message << '\n'; std::abort(); } +} -template +template bool Throws(TAction action) { - try { - action(); - } catch (const std::logic_error&) { - return true; - } + try { action(); } catch (const std::exception&) { return true; } return false; } -int allocator = 0; +struct Allocator { + std::atomic allocations{0}; + std::atomic releases{0}; + std::atomic fail{false}; +}; + +void* APS5_VABI Allocate(std::size_t size, void* userData) { + auto& allocator = *static_cast(userData); + if (allocator.fail) return nullptr; + ++allocator.allocations; + return std::malloc(size); +} + +void APS5_VABI Release(void* pointer, void* userData) { + ++static_cast(userData)->releases; + std::free(pointer); +} + +void Write(const std::filesystem::path& path, const void* data, std::size_t size) { + std::ofstream stream(path, std::ios::binary | std::ios::trunc); + stream.write(static_cast(data), static_cast(size)); + stream.close(); + Require(static_cast(stream), "fixture write failed"); +} + +std::vector Read(const char* guest) { + std::ifstream stream(ResolvePath_nid_no_patch(guest), std::ios::binary); + Require(static_cast(stream), "exported path cannot be read"); + return {std::istreambuf_iterator(stream), std::istreambuf_iterator()}; +} + +ContentExportParam MakeParam(const char* title = "export title", const char* mime = "image/png") { + ContentExportParam param{}; + std::strcpy(param.title, title); + std::strcpy(param.content_type, mime); + return param; +} + +struct Chunks { + std::size_t position = 0; + int failure = 0; + bool reenter = false; + int session = 0; + bool separateDone = false; +}; + +int APS5_VABI Provide(void** data, std::size_t* size, void* userData) { + auto& chunks = *static_cast(userData); + if (chunks.reenter) { + chunks.reenter = false; + Require(sceContentExportFinish(chunks.session) == Busy, "finish must refuse active callback"); + const auto param = MakeParam(); + std::array path{}; + Require(sceContentExportFromFile(chunks.session, ¶m, "/source.png", path.data(), path.size()) == Busy, + "same session must refuse reentrant export"); + Require(sceContentExportTerm() == Busy, "term must refuse open sessions"); + } + if (chunks.failure == 1) return -1; + if (chunks.failure == 2) { *size = Png.size() + 1; *data = const_cast(Png.data()); return 1; } + if (chunks.failure == 3) return 0; + if (chunks.failure == 4) { *size = 1; return 1; } + if (chunks.failure == 5) { *data = const_cast(Png.data()); *size = 1; return 1; } + *size = std::min(13, Png.size() - chunks.position); + *data = *size ? const_cast(Png.data()) + chunks.position : nullptr; + chunks.position += *size; + return chunks.position == Png.size() && (!chunks.separateDone || *size == 0) ? 1 : 0; +} + +void CheckCatalogTransactions() { + namespace Catalog = ContentCatalog_nid_no_patch; + const auto before = Catalog::Read_nid_no_patch(); + Catalog::Transaction_nid_no_patch first; + Catalog::Transaction_nid_no_patch second; + const auto entry = [](const auto& transaction) { + Catalog::Entry item; + item.id = transaction.Id_nid_no_patch(); + item.title = "transaction"; + item.mimeType = "image/png"; + item.path = transaction.GuestPath_nid_no_patch("content.png"); + item.size = Png.size(); + item.contentType = 1; + Write(transaction.Directory_nid_no_patch() / "content.png", Png.data(), Png.size()); + return item; + }; + second.Commit_nid_no_patch(entry(second)); + const auto middle = Catalog::Read_nid_no_patch(); + Require(middle.entries.size() == before.entries.size() + 1, "pending export became visible"); + first.Commit_nid_no_patch(entry(first)); + const auto after = Catalog::Read_nid_no_patch(); + Require(after.entries.size() == before.entries.size() + 2, "transaction publication lost entry"); + Require(after.updateId > middle.updateId, "out of order publication did not advance update id"); + for (const auto& directory : std::filesystem::directory_iterator(Catalog::Root_nid_no_patch())) + Require(directory.path().filename().string().find(".pending-") != 0, "failed export left pending files"); +} +void CheckCatalogChild() { + namespace Catalog = ContentCatalog_nid_no_patch; + const auto before = Catalog::Read_nid_no_patch(); + Require(!before.entries.empty(), "child process cannot read persistent catalog"); + const auto& first = before.entries.front(); + Require(Read(first.path.c_str()) == std::vector(Png.begin(), Png.end()), + "child process read different content bytes"); + Catalog::Transaction_nid_no_patch transaction; + Catalog::Entry item; + item.id = transaction.Id_nid_no_patch(); + item.title = "separate process"; + item.mimeType = "image/png"; + item.path = transaction.GuestPath_nid_no_patch("content.png"); + item.size = Png.size(); + item.contentType = 1; + Write(transaction.Directory_nid_no_patch() / "content.png", Png.data(), Png.size()); + transaction.Commit_nid_no_patch(item); + const auto after = Catalog::Read_nid_no_patch(); + Require(after.updateId > before.updateId && after.entries.size() == before.entries.size() + 1, + "child process publication lost generation"); } -int main() { - ContentExportInitParam2 param{&allocator, &allocator, nullptr, 0x10000, 0, 0}; - Require(Throws([] { sceContentExportInit2(nullptr); })); - Require(Throws([] { sceContentExportTerm(); })); - ContentExportInitParam2 missing = param; - missing.free_func = nullptr; - Require(Throws([&] { sceContentExportInit2(&missing); })); - ContentExportInitParam2 reserved = param; - reserved.reserved1 = 1; - Require(Throws([&] { sceContentExportInit2(&reserved); })); - Require(sceContentExportInit2(¶m) == 0); - Require(Throws([&] { sceContentExportInit2(¶m); })); - Require(sceContentExportTerm() == 0); - Require(Throws([] { sceContentExportTerm(); })); - Require(sceContentExportInit2(¶m) == 0); - Require(sceContentExportTerm() == 0); +void CheckCatalogProcess(const std::filesystem::path& executable) { + const auto before = ContentCatalog_nid_no_patch::Read_nid_no_patch(); +#ifdef _WIN32 + const auto root = std::filesystem::current_path().wstring(); + const auto program = executable.wstring(); + const auto status = _wspawnl(_P_WAIT, program.c_str(), program.c_str(), L"--catalog-child", root.c_str(), static_cast(nullptr)); + Require(status == 0, "catalog child process failed"); +#else + const auto root = std::filesystem::current_path().string(); + const auto process = fork(); + Require(process >= 0, "catalog child fork failed"); + if (process == 0) { + execl(executable.c_str(), executable.c_str(), "--catalog-child", root.c_str(), static_cast(nullptr)); + _exit(127); + } + int status = 0; + Require(waitpid(process, &status, 0) == process && WIFEXITED(status) && WEXITSTATUS(status) == 0, + "catalog child process failed"); +#endif + const auto after = ContentCatalog_nid_no_patch::Read_nid_no_patch(); + Require(after.entries.size() == before.entries.size() + 1 && after.updateId > before.updateId, + "parent process missed child publication"); +} + +} + +int main(int argc, char** argv) { + if (argc == 3 && std::strcmp(argv[1], "--catalog-child") == 0) { + std::filesystem::current_path(argv[2]); + CheckCatalogChild(); + return 0; + } + const auto executable = std::filesystem::absolute(argv[0]); + const auto previous = std::filesystem::current_path(); + const auto root = previous / ("export-" + std::to_string(ContentCatalog_nid_no_patch::CurrentTick_nid_no_patch())); + std::filesystem::create_directories(root); + std::filesystem::current_path(root); + Write("source.png", Png.data(), Png.size()); + Write("thumbnail.png", Png.data(), Png.size()); + Write("invalid", "invalid media", 13); + Allocator allocator; + ContentExportInitParam2 init{ + reinterpret_cast(&Allocate), reinterpret_cast(&Release), &allocator, 256, 0, 0}; + Require(sceContentExportStart() == NoInit, "start before init"); + Require(sceContentExportFinish(1) == NoInit, "finish before init"); + Require(Throws([] { sceContentExportInit2(nullptr); }), "null init accepted"); + Require(Throws([] { sceContentExportTerm(); }), "term before init"); + auto invalidInit = init; + invalidInit.free_func = nullptr; + Require(Throws([&] { sceContentExportInit2(&invalidInit); }), "missing allocator accepted"); + invalidInit = init; + invalidInit.reserved1 = 1; + Require(Throws([&] { sceContentExportInit2(&invalidInit); }), "nonzero init reserved accepted"); + invalidInit = init; + invalidInit.buffer_size = 255; + Require(sceContentExportInit2(&invalidInit) == InvalidParam, "undersized buffer accepted"); + Require(sceContentExportInit2(&init) == 0, "init failed"); + Require(Throws([&] { sceContentExportInit2(&init); }), "double init accepted"); + std::array sessions; + for (auto& session : sessions) { session = sceContentExportStart(); Require(session > 0, "session creation failed"); } + Require(sceContentExportStart() == ExecutionMax, "session limit ignored"); + Require(sceContentExportTerm() == Busy, "term discarded sessions"); + for (const auto session : sessions) Require(sceContentExportFinish(session) == 0, "session finish failed"); + Require(Throws([&] { sceContentExportFinish(sessions[0]); }), "finished session accepted"); + const auto session = sceContentExportStart(); + auto param = MakeParam(); + std::array path{}; + Require(sceContentExportFromFile(session, ¶m, "/source.png", path.data(), path.size()) == 0, "file export failed"); + Require(Read(path.data()) == std::vector(Png.begin(), Png.end()), "file bytes changed"); + const auto filePath = std::string(path.data()); + auto snapshot = ContentCatalog_nid_no_patch::Read_nid_no_patch(); + Require(snapshot.entries.size() == 1 && snapshot.entries[0].title == param.title, "file metadata missing"); + Require(snapshot.entries[0].width == 2 && snapshot.entries[0].height == 1, "image dimensions wrong"); + Require(snapshot.entries[0].accounts[0] == USER_SERVICE_INITIAL_USER_ID, "owner missing"); + Require(sceContentExportFromFileWithThumbnail(session, ¶m, "/source.png", "/thumbnail.png", path.data(), path.size()) == 0, + "thumbnail export failed"); + snapshot = ContentCatalog_nid_no_patch::Read_nid_no_patch(); + Require(snapshot.entries.size() == 2 && !snapshot.entries.back().iconPath.empty(), "thumbnail path missing"); + Require(Read(snapshot.entries.back().iconPath.c_str()) == std::vector(Png.begin(), Png.end()), "thumbnail bytes changed"); + for (const bool separateDone : {false, true}) { + Chunks chunks{0, 0, true, session, separateDone}; + Require(sceContentExportFromData(session, ¶m, Png.size(), Provide, &chunks, path.data(), path.size()) == 0, "callback export failed"); + Require(Read(path.data()) == std::vector(Png.begin(), Png.end()), "callback bytes changed"); + } + const auto beforeFailure = ContentCatalog_nid_no_patch::Read_nid_no_patch(); + std::memset(path.data(), 'x', path.size()); + const auto untouched = path; + Require(sceContentExportFromFile(session, nullptr, "/source.png", path.data(), path.size()) == InvalidParam, "null parameter accepted"); + Require(sceContentExportFromFile(session, ¶m, "/source.png", path.data(), 2) == InvalidParam, "short output accepted"); + Require(sceContentExportFromFile(session, ¶m, "/missing", path.data(), path.size()) == FileNotFound, "missing file accepted"); + Require(sceContentExportFromFile(session, ¶m, "/invalid", path.data(), path.size()) == UnsupportedFormat, "invalid media accepted"); + Require(sceContentExportFromFileWithThumbnail(session, ¶m, "/source.png", "/invalid", path.data(), path.size()) == UnsupportedThumbnail, + "invalid thumbnail accepted"); + auto unsupported = MakeParam("unsupported", "application/octet-stream"); + Require(sceContentExportFromFile(session, &unsupported, "/source.png", path.data(), path.size()) == UnsupportedFormat, "unknown format accepted"); + unsupported = param; + unsupported.reserved[0] = 1; + Require(Throws([&] { sceContentExportFromFile(session, &unsupported, "/source.png", path.data(), path.size()); }), "unknown field accepted"); + unsupported = param; + std::memset(unsupported.title, 't', sizeof(unsupported.title)); + Require(sceContentExportFromFile(session, &unsupported, "/source.png", path.data(), path.size()) == InvalidParam, "unterminated title accepted"); + for (int failure = 1; failure <= 5; ++failure) { + Chunks chunks{0, failure}; + Require(sceContentExportFromData(session, ¶m, Png.size(), Provide, &chunks, path.data(), path.size()) == DataProvideError, + "bad callback accepted"); + } + allocator.fail = true; + Require(sceContentExportFromFile(session, ¶m, "/source.png", path.data(), path.size()) == NoMemory, "allocator failure ignored"); + allocator.fail = false; + Require(path == untouched, "failed operation modified output"); + const auto afterFailure = ContentCatalog_nid_no_patch::Read_nid_no_patch(); + Require(afterFailure.entries.size() == beforeFailure.entries.size() && afterFailure.updateId == beforeFailure.updateId, "failed operation published content"); + const std::array pixels{255,0,0,0,255,0,0,0,255,255,255,255}; + const auto jpeg = Decoder::Jpeg::Encode(pixels, 2, 2, 3, 90); + Write("source.jpg", jpeg.data(), jpeg.size()); + auto jpegParam = MakeParam("jpeg", "image/jpeg"); + Require(sceContentExportFromFile(session, &jpegParam, "/source.jpg", path.data(), path.size()) == 0, "JPEG export failed"); + Require(Read(path.data()) == jpeg, "JPEG bytes changed"); + constexpr std::array gif{ + 'G','I','F','8','9','a',1,0,1,0,0x80,0,0,0,0,0,255,255,255, + 0x2c,0,0,0,0,1,0,1,0,0,2,2,0x44,0x01,0,0x3b}; + Write("source.gif", gif.data(), gif.size()); + auto gifParam = MakeParam("gif", "image/gif"); + Require(sceContentExportFromFile(session, &gifParam, "/source.gif", path.data(), path.size()) == 0, "GIF export failed"); + Require(Read(path.data()) == std::vector(gif.begin(), gif.end()), "GIF bytes changed"); + auto videoParam = MakeParam("video", "video/mp4"); + Require(Throws([&] { sceContentExportFromFile(session, &videoParam, "/source.png", path.data(), path.size()); }), "unsupported video succeeded"); + Require(sceContentExportFromFile(session, &jpegParam, "/source.png", path.data(), path.size()) == UnsupportedFormat, "mismatched MIME accepted"); + std::array parallel{session, sceContentExportStart()}; + std::array threads; + std::atomic reading{true}; + std::thread reader([&] { + std::int64_t generation = 0; + while (reading) { + const auto snapshot = ContentCatalog_nid_no_patch::Read_nid_no_patch(); + Require(snapshot.updateId >= generation, "snapshot generation went backwards"); + generation = snapshot.updateId; + for (const auto& item : snapshot.entries) { + Require(item.status == 1 && std::filesystem::exists(ResolvePath_nid_no_patch(item.path.c_str())), + "snapshot exposed incomplete publication"); + } + } + }); + for (std::size_t index = 0; index < threads.size(); ++index) { + threads[index] = std::thread([&, index] { + std::array output{}; + Require(sceContentExportFromFile(parallel[index], ¶m, "/source.png", output.data(), output.size()) == 0, "parallel export failed"); + }); + } + for (auto& thread : threads) thread.join(); + reading = false; + reader.join(); + for (const auto id : parallel) Require(sceContentExportFinish(id) == 0, "parallel session finish failed"); + CheckCatalogTransactions(); + CheckCatalogProcess(executable); + Require(allocator.allocations == allocator.releases, "allocator ownership leaked"); + const auto persisted = ContentCatalog_nid_no_patch::Read_nid_no_patch(); + Require(sceContentExportTerm() == 0, "term failed"); + Require(sceContentExportInit2(&init) == 0, "reinit failed"); + const auto reopened = ContentCatalog_nid_no_patch::Read_nid_no_patch(); + Require(reopened.entries.size() == persisted.entries.size() && reopened.updateId == persisted.updateId, "catalog did not persist"); + Require(Read(filePath.c_str()) == std::vector(Png.begin(), Png.end()), "persisted file changed"); + Require(sceContentExportTerm() == 0, "final term failed"); + std::filesystem::current_path(previous); + std::filesystem::remove_all(root); } diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index 8f2178189d5b..10734881ca95 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -38,6 +38,8 @@ Throughout the project, every function at every stage either **does exactly what ### Unknown function info +- [libSceContentExport](../../core/libs/prx/libSceContentExport/Export.cpp) - session, file, thumbnail and callback signatures follow [Orbital](https://github.com/AlexAltea/orbital/blob/cc408367da6a6ebbf5ac1ac559fefeadc73b2831/tools/ida/db_types.json) and [SharpProspero](https://github.com/SvenGDK/SharpProspero/blob/5dfdb4b0b166e83dc9ae275001afb695f12c7174/src/SharpProspero/Interop/Content/ContentExport.cs); the 579-byte parameter also follows [shadPS4](https://github.com/shadps4-emu/shadPS4/blob/0fe263a4760dfbfa973366890061749b4af0de97/src/core/libraries/content_export/content_export.h). These contracts are unverified on PS5 hardware or a title reaching the calls. JPEG, PNG and GIF exports copy media into a persistent host catalog under the launch root's `/data/anyps5-content`, using the host's initial user and RTC ticks. The existing PNG and JPEG decoders and stb GIF decoder validate image data and dimensions; only the first GIF frame is decoded. Automatic thumbnails, console path naming, gallery notifications and sharing are not implemented. The middle 257 parameter bytes are reserved in SharpProspero and called a comment in shadPS4; nonzero bytes throw. Video imports throw. Unknown session and filesystem errors throw rather than inventing console error codes. Callback completion follows SharpProspero's 0 (more) and 1 (done); zero progress and inconsistent byte totals report the data-provider error. The ten-session limit follows SharpProspero's execution limit; its application to allocated sessions is unverified. + - [sceNpEntitlementAccessGetEntitlementKey](../../core/libs/prx/libSceNpEntitlementAccess/Export.cpp) - the three-argument signature, 16-byte key and errors `0x817D0002`/`0x817D0007` follow [KytyPS5](https://github.com/KytyPS5/KytyPS5/blob/main/src/libs/libNet.cpp); PPSA01521 passes a service label, entitlement label and output pointer. Only the no-key path is implemented: local entitlement labels carry no keys, and the output is untouched on failure. Console error precedence and key provisioning are unverified - [sceNpEntitlementAccess{Request,Poll}{Unified,Service}EntitlementInfoList](../../core/libs/prx/libSceNpEntitlementAccess/Export.cpp) - signatures unknown; no reference implements them, so they are declared without parameters. Like the consume requests in the same library, they report the signed-out NP state with `SCE_NP_ERROR_SIGNED_OUT` (`0x80550006`) and write nothing. PPSA15657 calls the unified request during start-up and continues past the error. Whether the console fails at the request or at the poll when signed out is unverified - [sceRudpGetStatus](../../core/libs/prx/libSceRudp/Export.cpp) - PPSA01521 passes an output pointer and byte count `0xF8`; the status layout, size rules and error behavior are unknown. The export throws without writing output, including after initialization. [shadPS4](https://github.com/shadps4-emu/shadPS4/blob/main/src/core/libraries/rudp/rudp.cpp) declares it without arguments and returns success without writing status