mirror of
https://github.com/boykopovar/AnyPS5.git
synced 2026-12-04 00:20:50 +00:00
path_is_directory threw only when std::filesystem::status returned file_type::none. libstdc++ reports EOVERFLOW as file_type::unknown with the error code set, so that failure read as "not a directory" and dirNameSearch could return success with no results. A missing path still returns false; any other status error now throws, as plain_type does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2829 lines
107 KiB
C++
2829 lines
107 KiB
C++
#include "prx/libSceSaveData.native/include/Api.hpp"
|
|
#include "prx/libSceSaveData/include/Api.hpp"
|
|
#include <algorithm>
|
|
#include <atomic>
|
|
#include <cerrno>
|
|
#include <condition_variable>
|
|
#include <cstddef>
|
|
#include <deque>
|
|
#include <fstream>
|
|
#include <map>
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include <vector>
|
|
#include <chrono>
|
|
#include <cstdint>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <limits>
|
|
#include <cstring>
|
|
#include <ctime>
|
|
#include <filesystem>
|
|
#include <span>
|
|
#include <stdexcept>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <system_error>
|
|
#include <utility>
|
|
#ifndef _WIN32
|
|
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
#endif
|
|
#include "SceTypes.hpp"
|
|
#include "prx/libc/include/AppArchive.hpp"
|
|
#include "prx/libc/include/General.hpp"
|
|
#include "prx/libc/include/GuestArena.hpp"
|
|
#include "prx/libc/include/RemoveTree.hpp"
|
|
#include "prx/libkernel/AppMetadata/include/AppMetadata.hpp"
|
|
#include "prx/libkernel/include/Api.hpp"
|
|
#include "SaveData.hpp"
|
|
#include "prx/libSceSaveData.native/include/SaveDataHostSpace.hpp"
|
|
#include "prx/libSceSaveData/SaveDataFile.hpp"
|
|
#ifdef _WIN32
|
|
#ifndef NOMINMAX
|
|
#define NOMINMAX
|
|
#endif
|
|
#ifndef WIN32_LEAN_AND_MEAN
|
|
#define WIN32_LEAN_AND_MEAN
|
|
#endif
|
|
#include <windows.h>
|
|
#endif
|
|
|
|
static constexpr char SAVE_DIR[] = "_sd";
|
|
|
|
static std::atomic<std::int32_t> g_transaction_counter{1};
|
|
static std::atomic<int> g_initializations{0};
|
|
static std::atomic<float> g_convertProgress{0.0f};
|
|
static std::atomic<float> g_backupProgress{0.0f};
|
|
|
|
static std::string save_root() {
|
|
return std::string(SAVE_DIR);
|
|
}
|
|
|
|
// Events the title polls with sceSaveDataGetEventResult; a backup completes at once here.
|
|
static std::mutex g_state_mutex;
|
|
static std::deque<SaveDataEvent> g_events;
|
|
constexpr std::uint32_t SAVE_DATA_EVENT_TYPE_UMOUNT_BACKUP = 1;
|
|
constexpr std::uint32_t SAVE_DATA_EVENT_TYPE_BACKUP = 2;
|
|
constexpr std::uint32_t SAVE_DATA_EVENT_TYPE_CONVERT = 5;
|
|
|
|
namespace {
|
|
|
|
struct EventDelivery {
|
|
SaveDataEvent event;
|
|
SaveDataEventCallback callback;
|
|
void* userdata;
|
|
};
|
|
|
|
struct EventWorker {
|
|
Pthread thread = nullptr;
|
|
bool stopping = false;
|
|
};
|
|
|
|
struct EventCallbacks {
|
|
std::recursive_mutex calling;
|
|
std::mutex mutex;
|
|
std::condition_variable wake;
|
|
SaveDataEventCallback callback = nullptr;
|
|
void* userdata = nullptr;
|
|
std::deque<EventDelivery> pending;
|
|
EventWorker* worker = nullptr;
|
|
Pthread delivering = nullptr;
|
|
};
|
|
|
|
EventCallbacks& Callbacks() {
|
|
static auto* callbacks = new EventCallbacks;
|
|
return *callbacks;
|
|
}
|
|
|
|
void* APS5_VABI DeliverEvents(void* argument) {
|
|
auto& callbacks = Callbacks();
|
|
auto* worker = static_cast<EventWorker*>(argument);
|
|
for (;;) {
|
|
{
|
|
std::unique_lock lock(callbacks.mutex);
|
|
callbacks.wake.wait(lock, [&] { return worker->stopping || !callbacks.pending.empty(); });
|
|
if (worker->stopping) return nullptr;
|
|
}
|
|
std::lock_guard calling(callbacks.calling);
|
|
EventDelivery delivery{};
|
|
{
|
|
std::lock_guard lock(callbacks.mutex);
|
|
if (worker->stopping) return nullptr;
|
|
if (callbacks.pending.empty()) continue;
|
|
delivery = callbacks.pending.front();
|
|
callbacks.pending.pop_front();
|
|
callbacks.delivering = scePthreadSelf();
|
|
}
|
|
delivery.callback(&delivery.event, delivery.userdata);
|
|
std::lock_guard lock(callbacks.mutex);
|
|
callbacks.delivering = nullptr;
|
|
}
|
|
}
|
|
|
|
void StartEventDelivery() {
|
|
auto& callbacks = Callbacks();
|
|
auto worker = std::make_unique<EventWorker>();
|
|
std::lock_guard lock(callbacks.mutex);
|
|
if (callbacks.worker != nullptr) return;
|
|
if (scePthreadCreate(&worker->thread, nullptr, DeliverEvents, worker.get(), "SceSaveDataEventCallback") != 0) {
|
|
throw std::runtime_error("sceSaveDataRegisterEventCallback: scePthreadCreate failed for the event callback thread");
|
|
}
|
|
callbacks.worker = worker.release();
|
|
}
|
|
|
|
EventWorker* DetachEventDelivery() {
|
|
auto& callbacks = Callbacks();
|
|
std::lock_guard lock(callbacks.mutex);
|
|
callbacks.callback = nullptr;
|
|
callbacks.userdata = nullptr;
|
|
callbacks.pending.clear();
|
|
auto* worker = std::exchange(callbacks.worker, nullptr);
|
|
if (worker != nullptr) worker->stopping = true;
|
|
return worker;
|
|
}
|
|
|
|
void JoinEventDelivery(EventWorker* worker) {
|
|
std::unique_ptr<EventWorker> owned(worker);
|
|
Callbacks().wake.notify_all();
|
|
if (scePthreadJoin(owned->thread, nullptr) != 0) throw std::runtime_error("sceSaveDataTerminate: scePthreadJoin failed for the event callback thread");
|
|
}
|
|
|
|
bool InEventCallback() {
|
|
auto& callbacks = Callbacks();
|
|
std::lock_guard lock(callbacks.mutex);
|
|
return callbacks.delivering != nullptr && scePthreadEqual(scePthreadSelf(), callbacks.delivering) != 0;
|
|
}
|
|
|
|
void DeliverEvent(const SaveDataEvent& event) {
|
|
auto& callbacks = Callbacks();
|
|
{
|
|
std::lock_guard lock(callbacks.mutex);
|
|
if (callbacks.callback == nullptr || callbacks.worker == nullptr) return;
|
|
callbacks.pending.push_back({event, callbacks.callback, callbacks.userdata});
|
|
}
|
|
callbacks.wake.notify_all();
|
|
}
|
|
|
|
}
|
|
|
|
static bool dir_name_match(const char* str, const char* pattern) {
|
|
if (pattern == nullptr || pattern[0] == '\0') {
|
|
return true;
|
|
}
|
|
while (*str != '\0' && *pattern != '\0') {
|
|
if (*pattern == '%') {
|
|
for (const char* s = str;; s++) {
|
|
if (dir_name_match(s, pattern + 1)) {
|
|
return true;
|
|
}
|
|
if (*s == '\0') {
|
|
break;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
if (*pattern == '_') {
|
|
str++;
|
|
pattern++;
|
|
continue;
|
|
}
|
|
if (*pattern != *str) {
|
|
return false;
|
|
}
|
|
str++;
|
|
pattern++;
|
|
}
|
|
while (*pattern == '%') {
|
|
pattern++;
|
|
}
|
|
return *str == '\0' && *pattern == '\0';
|
|
}
|
|
|
|
static void flush_path(const std::string& path, bool directory) {
|
|
#ifdef _WIN32
|
|
if (directory) {
|
|
return;
|
|
}
|
|
const HANDLE handle = CreateFileW(std::filesystem::path(path).c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
|
if (handle == INVALID_HANDLE_VALUE) {
|
|
throw std::filesystem::filesystem_error("SaveData: cannot open to flush", path, std::error_code(static_cast<int>(GetLastError()), std::system_category()));
|
|
}
|
|
const bool flushed = FlushFileBuffers(handle) != 0;
|
|
const DWORD error = GetLastError();
|
|
CloseHandle(handle);
|
|
if (!flushed) {
|
|
throw std::filesystem::filesystem_error("SaveData: cannot flush", path, std::error_code(static_cast<int>(error), std::system_category()));
|
|
}
|
|
#else
|
|
const int descriptor = ::open(path.c_str(), O_RDONLY | O_CLOEXEC | (directory ? O_DIRECTORY : 0));
|
|
if (descriptor < 0) {
|
|
throw std::filesystem::filesystem_error("SaveData: cannot open to flush", path, std::error_code(errno, std::generic_category()));
|
|
}
|
|
const int result = ::fsync(descriptor);
|
|
const int error = errno;
|
|
::close(descriptor);
|
|
if (result != 0 && error != EINVAL) {
|
|
throw std::filesystem::filesystem_error("SaveData: cannot flush", path, std::error_code(error, std::generic_category()));
|
|
}
|
|
#endif
|
|
}
|
|
|
|
static void require_no_error(const std::error_code& error, const char* what, const std::filesystem::path& path) {
|
|
if (error) throw std::filesystem::filesystem_error(what, path, error);
|
|
}
|
|
|
|
static void require_no_error(const std::error_code& error, const char* what, const std::filesystem::path& from, const std::filesystem::path& to) {
|
|
if (error) throw std::filesystem::filesystem_error(what, from, to, error);
|
|
}
|
|
|
|
static bool path_exists(const std::filesystem::path& path) {
|
|
std::error_code error;
|
|
const bool exists = std::filesystem::exists(path, error);
|
|
require_no_error(error, "SaveData: cannot read the status of", path);
|
|
return exists;
|
|
}
|
|
|
|
static void make_directories(const std::filesystem::path& path) {
|
|
std::error_code error;
|
|
std::filesystem::create_directories(path, error);
|
|
require_no_error(error, "SaveData: cannot create the directories", path);
|
|
}
|
|
|
|
static void rename_path(const std::filesystem::path& from, const std::filesystem::path& to) {
|
|
std::error_code error;
|
|
std::filesystem::rename(from, to, error);
|
|
require_no_error(error, "SaveData: cannot rename", from, to);
|
|
}
|
|
|
|
static bool path_is_directory(const std::filesystem::path& path) {
|
|
std::error_code error;
|
|
const auto status = std::filesystem::status(path, error);
|
|
if (status.type() == std::filesystem::file_type::not_found) return false;
|
|
if (error) throw std::filesystem::filesystem_error("SaveData: cannot check for a directory", path, error);
|
|
return std::filesystem::is_directory(status);
|
|
}
|
|
|
|
static bool entry_is_directory(const std::filesystem::directory_entry& entry) {
|
|
std::error_code error;
|
|
const bool directory = entry.is_directory(error);
|
|
return error ? path_is_directory(entry.path()) : directory;
|
|
}
|
|
|
|
static std::filesystem::path canonical_location(const std::filesystem::path& path) {
|
|
std::error_code error;
|
|
const auto absolutePath = std::filesystem::absolute(path, error);
|
|
require_no_error(error, "SaveData: cannot make absolute", path);
|
|
const auto canonicalPath = std::filesystem::weakly_canonical(absolutePath, error);
|
|
require_no_error(error, "SaveData: cannot resolve", absolutePath);
|
|
return canonicalPath;
|
|
}
|
|
|
|
template <typename TIterator, typename TVisit>
|
|
static void for_each_entry(const std::filesystem::path& path, TVisit&& visit) {
|
|
std::error_code error;
|
|
TIterator entries(path, error);
|
|
while (!error && entries != TIterator()) {
|
|
visit(*entries);
|
|
entries.increment(error);
|
|
}
|
|
require_no_error(error, "SaveData: cannot list", path);
|
|
}
|
|
|
|
namespace {
|
|
|
|
// Save-data memory: one blob per user and slot, kept next to the save directory (_sd_mem/u<user>/slot<n>.bin),
|
|
// with a small .param sidecar holding the last SaveDataParam the title wrote. Keying by user as well as slot
|
|
// keeps two users' in-memory saves from colliding on the same console.
|
|
constexpr char MEM_DIR[] = "_sd_mem";
|
|
constexpr std::size_t MEM_MAX_SIZE = 32u * 1024u * 1024u;
|
|
std::mutex g_mem_mutex;
|
|
|
|
std::string mem_path(std::int32_t user_id, std::uint32_t slot, const char* ext) {
|
|
char buf[96];
|
|
std::snprintf(buf, sizeof(buf), "%s/u%d/slot%u.%s", MEM_DIR, static_cast<int>(user_id), static_cast<unsigned>(slot), ext);
|
|
return buf;
|
|
}
|
|
|
|
bool file_size_of(const std::string& path, std::size_t* out) {
|
|
std::error_code ec;
|
|
if (!std::filesystem::is_regular_file(path, ec)) {
|
|
return false;
|
|
}
|
|
const auto sz = std::filesystem::file_size(path, ec);
|
|
if (ec) {
|
|
return false;
|
|
}
|
|
*out = static_cast<std::size_t>(sz);
|
|
return true;
|
|
}
|
|
|
|
// Atomic-ish write: write to a temp file then rename over the target, so a kill mid-write never
|
|
// leaves a torn save behind.
|
|
bool write_file_replace(const std::string& path, const std::vector<char>& data) {
|
|
return savedata::replace_file(path, data.data(), data.size());
|
|
}
|
|
|
|
bool read_file_all(const std::filesystem::path& path, std::vector<char>& out) {
|
|
std::error_code ec;
|
|
if (!std::filesystem::is_regular_file(path, ec)) {
|
|
return false;
|
|
}
|
|
std::ifstream f(path, std::ios::binary);
|
|
if (!f) {
|
|
return false;
|
|
}
|
|
f.seekg(0, std::ios::end);
|
|
const auto end = f.tellg();
|
|
if (end < 0 || static_cast<std::uintmax_t>(end) > out.max_size() ||
|
|
static_cast<std::uintmax_t>(end) > static_cast<std::uintmax_t>(std::numeric_limits<std::streamsize>::max())) return false;
|
|
const auto n = static_cast<std::size_t>(end);
|
|
f.seekg(0);
|
|
out.resize(n);
|
|
if (n != 0) {
|
|
f.read(out.data(), static_cast<std::streamsize>(n));
|
|
}
|
|
return static_cast<bool>(f);
|
|
}
|
|
|
|
constexpr char MEM_JOURNAL_MAGIC[] = {'A', 'P', 'S', '5', 'M', 'J', 'N', '1'};
|
|
constexpr char MEM_JOURNAL_PARAM_MAGIC[] = {'A', 'P', 'S', '5', 'M', 'J', 'N', '2'};
|
|
|
|
struct MemoryWrite {
|
|
std::uint64_t offset;
|
|
std::uint64_t size;
|
|
const char* data;
|
|
};
|
|
|
|
struct MemoryJournal {
|
|
std::vector<MemoryWrite> writes;
|
|
std::span<const char> param;
|
|
};
|
|
|
|
std::vector<char> encode_memory_journal(const std::vector<MemoryWrite>& writes, std::span<const char> param) {
|
|
const auto& magic = param.empty() ? MEM_JOURNAL_MAGIC : MEM_JOURNAL_PARAM_MAGIC;
|
|
std::vector<char> bytes(std::begin(magic), std::end(magic));
|
|
if (!param.empty()) {
|
|
bytes.insert(bytes.end(), param.begin(), param.end());
|
|
}
|
|
for (const MemoryWrite& write : writes) {
|
|
const std::size_t at = bytes.size();
|
|
bytes.resize(at + sizeof(write.offset) + sizeof(write.size) + write.size);
|
|
std::memcpy(bytes.data() + at, &write.offset, sizeof(write.offset));
|
|
std::memcpy(bytes.data() + at + sizeof(write.offset), &write.size, sizeof(write.size));
|
|
std::memcpy(bytes.data() + at + sizeof(write.offset) + sizeof(write.size), write.data, write.size);
|
|
}
|
|
return bytes;
|
|
}
|
|
|
|
MemoryJournal decode_memory_journal(const std::string& journal, std::span<const char> bytes, std::size_t memory_size) {
|
|
const auto malformed = [&journal]() { return std::runtime_error("SaveData: memory journal " + journal + " is malformed"); };
|
|
if (bytes.size() < sizeof(MEM_JOURNAL_MAGIC)) {
|
|
throw malformed();
|
|
}
|
|
MemoryJournal result;
|
|
std::size_t at = sizeof(MEM_JOURNAL_MAGIC);
|
|
if (std::memcmp(bytes.data(), MEM_JOURNAL_PARAM_MAGIC, sizeof(MEM_JOURNAL_PARAM_MAGIC)) == 0) {
|
|
if (bytes.size() - at < sizeof(SaveDataParam)) {
|
|
throw malformed();
|
|
}
|
|
result.param = bytes.subspan(at, sizeof(SaveDataParam));
|
|
at += sizeof(SaveDataParam);
|
|
} else if (std::memcmp(bytes.data(), MEM_JOURNAL_MAGIC, sizeof(MEM_JOURNAL_MAGIC)) != 0) {
|
|
throw malformed();
|
|
}
|
|
while (at != bytes.size()) {
|
|
MemoryWrite write{};
|
|
if (bytes.size() - at < sizeof(write.offset) + sizeof(write.size)) {
|
|
throw malformed();
|
|
}
|
|
std::memcpy(&write.offset, bytes.data() + at, sizeof(write.offset));
|
|
std::memcpy(&write.size, bytes.data() + at + sizeof(write.offset), sizeof(write.size));
|
|
at += sizeof(write.offset) + sizeof(write.size);
|
|
if (write.size > bytes.size() - at || write.offset > memory_size || write.size > memory_size - write.offset) {
|
|
throw malformed();
|
|
}
|
|
write.data = bytes.data() + at;
|
|
at += write.size;
|
|
result.writes.push_back(write);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
bool replace_synced_memory_file(const std::filesystem::path& path, std::span<const char> bytes) {
|
|
const bool replaced = savedata::replace_file_with(path, bytes.data(), bytes.size(), [](const auto& temporary, const auto& destination) {
|
|
flush_path(temporary.string(), false);
|
|
return savedata::move_replacing(temporary, destination);
|
|
});
|
|
if (replaced) {
|
|
flush_path(path.parent_path().string(), true);
|
|
}
|
|
return replaced;
|
|
}
|
|
|
|
bool apply_memory_journal(std::fstream& memory, const std::string& path, const std::string& journal, const std::vector<MemoryWrite>& writes, std::span<const char> param) {
|
|
for (const MemoryWrite& write : writes) {
|
|
memory.seekp(static_cast<std::streamoff>(write.offset));
|
|
memory.write(write.data, static_cast<std::streamsize>(write.size));
|
|
}
|
|
memory.close();
|
|
if (!memory) {
|
|
return false;
|
|
}
|
|
flush_path(path, false);
|
|
auto memoryPath = std::filesystem::path(path);
|
|
if (!param.empty() && !replace_synced_memory_file(memoryPath.replace_extension(".param"), param)) {
|
|
return false;
|
|
}
|
|
std::error_code ec;
|
|
if (!std::filesystem::remove(journal, ec)) {
|
|
return false;
|
|
}
|
|
flush_path(memoryPath.parent_path().string(), true);
|
|
return true;
|
|
}
|
|
|
|
void replay_memory_journal(std::int32_t user_id, std::uint32_t slot) {
|
|
const std::string journal = mem_path(user_id, slot, "journal");
|
|
std::error_code ec;
|
|
const bool pending = std::filesystem::exists(journal, ec);
|
|
if (ec) {
|
|
throw std::runtime_error("SaveData: cannot check memory journal " + journal);
|
|
}
|
|
if (!pending) {
|
|
return;
|
|
}
|
|
const std::string path = mem_path(user_id, slot, "bin");
|
|
std::vector<char> bytes;
|
|
std::size_t size = 0;
|
|
if (!read_file_all(journal, bytes) || !file_size_of(path, &size)) {
|
|
throw std::runtime_error("SaveData: cannot replay memory journal " + journal);
|
|
}
|
|
const auto pendingWrites = decode_memory_journal(journal, bytes, size);
|
|
std::fstream memory(path, std::ios::binary | std::ios::in | std::ios::out);
|
|
if (!memory) {
|
|
throw std::runtime_error("SaveData: cannot open " + path + " to replay memory journal " + journal);
|
|
}
|
|
flush_path(journal, false);
|
|
flush_path(std::filesystem::path(journal).parent_path().string(), true);
|
|
if (!apply_memory_journal(memory, path, journal, pendingWrites.writes, pendingWrites.param)) {
|
|
throw std::runtime_error("SaveData: cannot finish memory journal " + journal);
|
|
}
|
|
}
|
|
|
|
std::string param_path(const std::string& real_path) {
|
|
return real_path + ".param";
|
|
}
|
|
|
|
bool read_param_file(const std::string& path, SaveDataParam* param) {
|
|
if (!path_exists(path)) {
|
|
return false;
|
|
}
|
|
std::vector<char> bytes;
|
|
if (!read_file_all(path, bytes)) {
|
|
throw std::runtime_error("SaveData: cannot read param file " + path);
|
|
}
|
|
if (bytes.size() != sizeof(SaveDataParam)) {
|
|
throw std::runtime_error("SaveData: param file " + path + " is " + std::to_string(bytes.size()) + " bytes, expected " + std::to_string(sizeof(SaveDataParam)) + " (outdated format)");
|
|
}
|
|
std::memcpy(param, bytes.data(), sizeof(SaveDataParam));
|
|
return true;
|
|
}
|
|
|
|
SaveDataParam load_param(const std::string& real_path) {
|
|
SaveDataParam param{};
|
|
read_param_file(param_path(real_path), ¶m);
|
|
if (param.mtime == 0) {
|
|
#ifdef _WIN32
|
|
WIN32_FILE_ATTRIBUTE_DATA data{};
|
|
if (GetFileAttributesExW(std::filesystem::path(real_path).c_str(), GetFileExInfoStandard, &data)) {
|
|
const auto ticks = static_cast<std::int64_t>((static_cast<std::uint64_t>(data.ftLastWriteTime.dwHighDateTime) << 32) | data.ftLastWriteTime.dwLowDateTime);
|
|
param.mtime = (ticks - 116444736000000000LL) / 10000000LL;
|
|
}
|
|
#else
|
|
std::error_code ec;
|
|
const auto written = std::filesystem::last_write_time(real_path, ec);
|
|
if (!ec) {
|
|
const auto system = std::chrono::file_clock::to_sys(written);
|
|
param.mtime = std::chrono::duration_cast<std::chrono::seconds>(system.time_since_epoch()).count();
|
|
}
|
|
#endif
|
|
}
|
|
return param;
|
|
}
|
|
|
|
bool store_param(const std::string& real_path, const SaveDataParam& param) {
|
|
std::vector<char> bytes(sizeof(param));
|
|
std::memcpy(bytes.data(), ¶m, sizeof(param));
|
|
return write_file_replace(param_path(real_path), bytes);
|
|
}
|
|
|
|
struct ParamField {
|
|
std::size_t offset;
|
|
std::size_t size;
|
|
bool text;
|
|
};
|
|
|
|
bool param_field(std::uint32_t param_type, ParamField* field) {
|
|
switch (param_type) {
|
|
case SAVE_DATA_PARAM_TYPE_ALL: *field = {0, sizeof(SaveDataParam), false}; return true;
|
|
case SAVE_DATA_PARAM_TYPE_TITLE: *field = {offsetof(SaveDataParam, title), sizeof(SaveDataParam::title), true}; return true;
|
|
case SAVE_DATA_PARAM_TYPE_SUB_TITLE: *field = {offsetof(SaveDataParam, sub_title), sizeof(SaveDataParam::sub_title), true}; return true;
|
|
case SAVE_DATA_PARAM_TYPE_DETAIL: *field = {offsetof(SaveDataParam, detail), sizeof(SaveDataParam::detail), true}; return true;
|
|
case SAVE_DATA_PARAM_TYPE_USER_PARAM: *field = {offsetof(SaveDataParam, user_param), sizeof(SaveDataParam::user_param), false}; return true;
|
|
case SAVE_DATA_PARAM_TYPE_MTIME: *field = {offsetof(SaveDataParam, mtime), sizeof(SaveDataParam::mtime), false}; return true;
|
|
default: return false;
|
|
}
|
|
}
|
|
|
|
int traceLimit() {
|
|
static const int limit = std::getenv("APS5_SAVEDATA_TRACE") != nullptr ? std::numeric_limits<int>::max() : 3;
|
|
return limit;
|
|
}
|
|
#define SAVEDATA_TRACE(...) \
|
|
do { \
|
|
static std::atomic<int> traceCount{0}; \
|
|
if (traceCount.fetch_add(1, std::memory_order_relaxed) < traceLimit()) { \
|
|
std::fprintf(stderr, "[SAVEDATA:native] " __VA_ARGS__); \
|
|
std::fputc('\n', stderr); \
|
|
std::fflush(stderr); \
|
|
} \
|
|
} while (0)
|
|
|
|
template <typename T>
|
|
bool readGuest(const T* source, T& destination) {
|
|
if (source == nullptr) return false;
|
|
const int savedErrno = errno;
|
|
const bool copied = GuestCopyIn_nid_no_patch(&destination, source, sizeof(destination));
|
|
errno = savedErrno;
|
|
return copied;
|
|
}
|
|
|
|
bool writeGuest(void* destination, const void* source, std::size_t bytes) {
|
|
if (destination == nullptr) return false;
|
|
const int savedErrno = errno;
|
|
const bool copied = GuestCopyOut_nid_no_patch(destination, source, bytes);
|
|
errno = savedErrno;
|
|
return copied;
|
|
}
|
|
|
|
} // namespace
|
|
|
|
extern "C" {
|
|
|
|
int APS5_VABI sceSaveDataBackup(const SaveDataBackup* backup) {
|
|
SaveDataBackup localBackup{};
|
|
if (backup == nullptr || !GuestCopyIn_nid_no_patch(&localBackup, backup, sizeof(localBackup))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (localBackup.dir_name == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
SceSaveDataDirName localDirName{};
|
|
if (!GuestCopyIn_nid_no_patch(&localDirName, localBackup.dir_name, sizeof(localDirName))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (std::memchr(localDirName.data, '\0', sizeof(localDirName.data)) == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
SaveDataEvent event{};
|
|
event.type = SAVE_DATA_EVENT_TYPE_BACKUP;
|
|
event.error_code = SAVE_DATA_OK;
|
|
event.user_id = localBackup.user_id;
|
|
if (localBackup.title_id != nullptr) {
|
|
if (!GuestCopyIn_nid_no_patch(&event.title_id, localBackup.title_id, sizeof(event.title_id))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
}
|
|
event.dir_name = localDirName;
|
|
{
|
|
std::lock_guard lock(g_state_mutex);
|
|
g_events.push_back(event);
|
|
}
|
|
g_backupProgress = 1.0f;
|
|
DeliverEvent(event);
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCommit(const SaveDataCommitParam* param) {
|
|
(void)param;
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCreateTransactionResource(uint32_t size) {
|
|
(void)size;
|
|
if (g_initializations == 0) return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
return g_transaction_counter.fetch_add(1);
|
|
}
|
|
|
|
static std::string blocks_path(const std::string& real_path) {
|
|
return real_path + ".blocks";
|
|
}
|
|
|
|
static bool copy_mount_point(const SaveDataMountPoint* mount_point, SaveDataMountPoint* out) {
|
|
if (mount_point == nullptr || out == nullptr) {
|
|
return false;
|
|
}
|
|
if (!readGuest(mount_point, *out)) {
|
|
return false;
|
|
}
|
|
return std::memchr(out->data, '\0', sizeof(out->data)) != nullptr;
|
|
}
|
|
|
|
static bool isMountedDirectory(const std::string& path, std::error_code& error) {
|
|
for (const auto& slot : g_slots) {
|
|
if (!slot.used) continue;
|
|
if (slot.real_path == path) return true;
|
|
const bool exists = std::filesystem::exists(path, error);
|
|
if (error) return false;
|
|
if (!exists) continue;
|
|
const bool mountedExists = std::filesystem::exists(slot.real_path, error);
|
|
if (error) return false;
|
|
if (!mountedExists) continue;
|
|
const bool sameDirectory = std::filesystem::equivalent(slot.real_path, path, error);
|
|
if (error == std::errc::no_such_file_or_directory) error.clear();
|
|
if (error) return false;
|
|
if (sameDirectory) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
static constexpr char BACKUP_DIR[] = "_sd_backup";
|
|
static constexpr char BACKUP_STAGING_DIR[] = "_sd_backup_tmp";
|
|
static constexpr char BACKUP_OLD_DIR[] = "_sd_backup_old";
|
|
static constexpr char RESTORE_STAGING_DIR[] = "_sd_restore_tmp";
|
|
static constexpr char RESTORE_OLD_DIR[] = "_sd_restore_old";
|
|
|
|
static std::atomic<bool (*)(const char*, const char*)> g_file_step_hook{nullptr};
|
|
|
|
void SaveDataSetFileStepHook_nid_no_patch(bool (*hook)(const char* step, const char* path)) {
|
|
g_file_step_hook.store(hook, std::memory_order_release);
|
|
}
|
|
|
|
static void file_step(const char* step, const std::string& path) {
|
|
const auto hook = g_file_step_hook.load(std::memory_order_acquire);
|
|
if (hook != nullptr && !hook(step, path.c_str())) {
|
|
throw std::filesystem::filesystem_error(std::string("SaveData: ") + step + " failed", path, std::make_error_code(std::errc::io_error));
|
|
}
|
|
}
|
|
|
|
static bool is_link(const std::filesystem::path& path, const std::filesystem::file_status& status) {
|
|
#ifdef _WIN32
|
|
const DWORD attributes = GetFileAttributesW(path.c_str());
|
|
if (attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
|
|
return true;
|
|
}
|
|
#endif
|
|
return std::filesystem::is_symlink(status);
|
|
}
|
|
|
|
static std::filesystem::file_type plain_type(const std::string& path) {
|
|
std::error_code error;
|
|
const auto status = std::filesystem::symlink_status(path, error);
|
|
if (status.type() == std::filesystem::file_type::not_found) {
|
|
return std::filesystem::file_type::not_found;
|
|
}
|
|
if (error) {
|
|
throw std::filesystem::filesystem_error("SaveData: cannot read the type of", path, error);
|
|
}
|
|
if (is_link(path, status) || (status.type() != std::filesystem::file_type::regular && status.type() != std::filesystem::file_type::directory)) {
|
|
throw std::filesystem::filesystem_error("SaveData: not a plain file or directory", path, std::make_error_code(std::errc::operation_not_permitted));
|
|
}
|
|
return status.type();
|
|
}
|
|
|
|
static void require_plain_tree(const std::string& path) {
|
|
if (plain_type(path) != std::filesystem::file_type::directory) {
|
|
return;
|
|
}
|
|
for_each_entry<std::filesystem::directory_iterator>(path, [](const std::filesystem::directory_entry& entry) {
|
|
require_plain_tree(entry.path().string());
|
|
});
|
|
}
|
|
|
|
static void require_inside(const std::string& root, const std::string& path) {
|
|
const auto base = canonical_location(root);
|
|
const auto target = canonical_location(path);
|
|
const auto [inBase, inTarget] = std::mismatch(base.begin(), base.end(), target.begin(), target.end());
|
|
if (inBase != base.end() || inTarget == target.end()) {
|
|
throw std::filesystem::filesystem_error("SaveData: a save path leaves its root", path, root, std::make_error_code(std::errc::operation_not_permitted));
|
|
}
|
|
}
|
|
|
|
static void copy_file_step(const char* step, const std::string& from, const std::string& to) {
|
|
if (plain_type(from) != std::filesystem::file_type::regular) {
|
|
throw std::filesystem::filesystem_error("SaveData: not a plain file", from, std::make_error_code(std::errc::operation_not_permitted));
|
|
}
|
|
file_step(step, to);
|
|
std::error_code error;
|
|
std::filesystem::copy_file(from, to, error);
|
|
require_no_error(error, "SaveData: cannot copy", from, to);
|
|
}
|
|
|
|
static void copy_tree(const char* step, const std::string& from, const std::string& to) {
|
|
file_step(step, to);
|
|
std::error_code error;
|
|
std::filesystem::create_directory(to, error);
|
|
require_no_error(error, "SaveData: cannot create the directory", to);
|
|
for_each_entry<std::filesystem::directory_iterator>(from, [&](const std::filesystem::directory_entry& entry) {
|
|
const std::string source = entry.path().string();
|
|
const std::string target = to + "/" + entry.path().filename().string();
|
|
if (plain_type(source) == std::filesystem::file_type::directory) {
|
|
copy_tree(step, source, target);
|
|
} else {
|
|
copy_file_step(step, source, target);
|
|
}
|
|
});
|
|
}
|
|
|
|
static std::map<std::string, std::uintmax_t> tree_sizes(const std::string& root) {
|
|
std::map<std::string, std::uintmax_t> sizes;
|
|
for_each_entry<std::filesystem::recursive_directory_iterator>(root, [&](const std::filesystem::directory_entry& entry) {
|
|
std::uintmax_t size = std::numeric_limits<std::uintmax_t>::max();
|
|
if (!entry_is_directory(entry)) {
|
|
std::error_code error;
|
|
size = entry.file_size(error);
|
|
require_no_error(error, "SaveData: cannot read the size of", entry.path());
|
|
}
|
|
sizes[entry.path().lexically_relative(root).generic_string()] = size;
|
|
});
|
|
return sizes;
|
|
}
|
|
|
|
static void flush_tree(const std::string& root) {
|
|
for_each_entry<std::filesystem::recursive_directory_iterator>(root, [](const std::filesystem::directory_entry& entry) {
|
|
flush_path(entry.path().string(), entry_is_directory(entry));
|
|
});
|
|
flush_path(root, true);
|
|
}
|
|
|
|
struct FileSwap {
|
|
std::vector<std::pair<std::string, std::string>> moved;
|
|
|
|
void move(const char* step, const std::string& from, const std::string& to) {
|
|
file_step(step, to);
|
|
rename_path(from, to);
|
|
moved.emplace_back(from, to);
|
|
flush_path(std::filesystem::path(from).parent_path().string(), true);
|
|
flush_path(std::filesystem::path(to).parent_path().string(), true);
|
|
}
|
|
|
|
void undo(const char* step) {
|
|
while (!moved.empty()) {
|
|
const auto [from, to] = moved.back();
|
|
file_step(step, from);
|
|
rename_path(to, from);
|
|
moved.pop_back();
|
|
flush_path(std::filesystem::path(from).parent_path().string(), true);
|
|
flush_path(std::filesystem::path(to).parent_path().string(), true);
|
|
}
|
|
}
|
|
};
|
|
|
|
static std::string backup_entry(const char* root, const std::string& dirName) {
|
|
return std::string(root) + "/" + dirName;
|
|
}
|
|
|
|
static std::string entry_save(const std::string& entry) {
|
|
return entry + "/save";
|
|
}
|
|
|
|
static void require_plain_paths(const std::string& dirName, std::initializer_list<const char*> roots) {
|
|
for (const char* root : roots) {
|
|
if (plain_type(root) == std::filesystem::file_type::regular) {
|
|
throw std::filesystem::filesystem_error("SaveData: a save root is not a directory", root, std::make_error_code(std::errc::not_a_directory));
|
|
}
|
|
const std::string entry = backup_entry(root, dirName);
|
|
for (const std::string& path : {entry, param_path(entry), blocks_path(entry)}) {
|
|
require_inside(root, path);
|
|
require_plain_tree(path);
|
|
}
|
|
}
|
|
}
|
|
|
|
static bool parse_dir_name(const SceSaveDataDirName* name, std::string* dirName) {
|
|
SceSaveDataDirName localName{};
|
|
if (!readGuest(name, localName)) {
|
|
return false;
|
|
}
|
|
const auto* nameEnd = static_cast<const char*>(std::memchr(localName.data, '\0', sizeof(localName.data)));
|
|
if (nameEnd == nullptr) {
|
|
return false;
|
|
}
|
|
dirName->assign(localName.data, static_cast<std::size_t>(nameEnd - localName.data));
|
|
return !dirName->empty() && *dirName != "." && *dirName != ".." && dirName->find_first_of("/\\:") == std::string::npos;
|
|
}
|
|
|
|
static bool running_title(const SceSaveDataTitleId* titleId) {
|
|
if (titleId == nullptr) return true;
|
|
SceSaveDataTitleId localTitle{};
|
|
if (!readGuest(titleId, localTitle)) return false;
|
|
return std::strncmp(localTitle.data, GetAppTitleId_nid_postfix().value, sizeof(localTitle.data)) == 0;
|
|
}
|
|
|
|
static int read_backup_entry(const std::string& entry, SaveDataParam* param) {
|
|
std::error_code error;
|
|
if (!std::filesystem::exists(entry, error)) {
|
|
return error ? SAVE_DATA_ERROR_INTERNAL : SAVE_DATA_ERROR_NOT_FOUND;
|
|
}
|
|
const std::string backup = entry_save(entry);
|
|
if (!std::filesystem::is_directory(backup, error) || !std::filesystem::is_regular_file(param_path(backup), error) || std::filesystem::file_size(param_path(backup), error) != sizeof(SaveDataParam) || error) {
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
SaveDataParam stored{};
|
|
std::ifstream file(param_path(backup), std::ios::binary);
|
|
if (!file.read(reinterpret_cast<char*>(&stored), sizeof(stored)) || file.peek() != std::ifstream::traits_type::eof()) {
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
const auto blocks = std::filesystem::status(blocks_path(backup), error).type();
|
|
if (blocks != std::filesystem::file_type::not_found && blocks != std::filesystem::file_type::regular) {
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
if (param != nullptr && !writeGuest(param, &stored, sizeof(stored))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
static void move_backup(const char* step, const std::string& from, const std::string& to, bool* moved = nullptr) {
|
|
file_step(step, to);
|
|
std::error_code error;
|
|
std::filesystem::rename(from, to, error);
|
|
if (error) {
|
|
throw std::filesystem::filesystem_error("SaveData: cannot move the backup", from, to, error);
|
|
}
|
|
if (moved != nullptr) *moved = true;
|
|
file_step("backup.flush", to);
|
|
flush_path(std::filesystem::path(to).parent_path().string(), true);
|
|
flush_path(std::filesystem::path(from).parent_path().string(), true);
|
|
}
|
|
|
|
static void remove_backup_copy(const char* step, const std::string& path) {
|
|
if (plain_type(path) == std::filesystem::file_type::not_found) return;
|
|
file_step(step, path);
|
|
RemoveTree(path);
|
|
flush_path(std::filesystem::path(path).parent_path().string(), true);
|
|
}
|
|
|
|
static void recover_backup(const std::string& dirName) {
|
|
require_plain_paths(dirName, {BACKUP_DIR, BACKUP_STAGING_DIR, BACKUP_OLD_DIR});
|
|
const std::string entry = backup_entry(BACKUP_DIR, dirName);
|
|
const std::string staged = backup_entry(BACKUP_STAGING_DIR, dirName);
|
|
const std::string old = backup_entry(BACKUP_OLD_DIR, dirName);
|
|
const auto previous = plain_type(old);
|
|
const auto staging = plain_type(staged);
|
|
if (previous == std::filesystem::file_type::not_found && staging == std::filesystem::file_type::not_found) return;
|
|
for (const auto& path : {staged, old}) {
|
|
if (plain_type(path) == std::filesystem::file_type::regular) {
|
|
throw std::filesystem::filesystem_error("SaveData: a backup recovery copy is not a directory", path, std::make_error_code(std::errc::not_a_directory));
|
|
}
|
|
}
|
|
const auto current = plain_type(entry);
|
|
if (current != std::filesystem::file_type::not_found) {
|
|
if (read_backup_entry(entry, nullptr) != SAVE_DATA_OK) {
|
|
throw std::filesystem::filesystem_error("SaveData: the published backup is incomplete", entry, std::make_error_code(std::errc::io_error));
|
|
}
|
|
flush_path(BACKUP_DIR, true);
|
|
} else if (previous != std::filesystem::file_type::not_found) {
|
|
if (read_backup_entry(old, nullptr) != SAVE_DATA_OK) {
|
|
throw std::filesystem::filesystem_error("SaveData: the previous backup is incomplete", old, std::make_error_code(std::errc::io_error));
|
|
}
|
|
make_directories(BACKUP_DIR);
|
|
flush_path(".", true);
|
|
move_backup("backup.recover", old, entry);
|
|
}
|
|
remove_backup_copy("backup.recover.cleanup", staged);
|
|
remove_backup_copy("backup.recover.cleanup", old);
|
|
}
|
|
|
|
static int read_backup(const std::string& dirName, SaveDataParam* param) {
|
|
try {
|
|
recover_backup(dirName);
|
|
return read_backup_entry(backup_entry(BACKUP_DIR, dirName), param);
|
|
} catch (const std::filesystem::filesystem_error&) {
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
}
|
|
|
|
static void backupSave(const std::string& dirName) {
|
|
const std::string source = save_root() + "/" + dirName;
|
|
const std::string entry = backup_entry(BACKUP_DIR, dirName);
|
|
const std::string staged = backup_entry(BACKUP_STAGING_DIR, dirName);
|
|
const std::string old = backup_entry(BACKUP_OLD_DIR, dirName);
|
|
require_plain_paths(dirName, {SAVE_DIR, BACKUP_DIR, BACKUP_STAGING_DIR, BACKUP_OLD_DIR});
|
|
recover_backup(dirName);
|
|
make_directories(staged);
|
|
flush_path(BACKUP_STAGING_DIR, true);
|
|
flush_path(".", true);
|
|
bool displaced = false;
|
|
bool published = false;
|
|
try {
|
|
copy_tree("backup.copy", source, entry_save(staged));
|
|
file_step("backup.copy", param_path(entry_save(staged)));
|
|
if (!store_param(entry_save(staged), load_param(source))) {
|
|
throw std::filesystem::filesystem_error("SaveData: cannot write the backup's param file", param_path(entry_save(staged)), std::make_error_code(std::errc::io_error));
|
|
}
|
|
if (path_exists(blocks_path(source))) {
|
|
copy_file_step("backup.copy", blocks_path(source), blocks_path(entry_save(staged)));
|
|
}
|
|
flush_tree(staged);
|
|
make_directories(BACKUP_DIR);
|
|
flush_path(".", true);
|
|
if (path_exists(entry)) {
|
|
make_directories(BACKUP_OLD_DIR);
|
|
flush_path(".", true);
|
|
move_backup("backup.aside", entry, old, &displaced);
|
|
}
|
|
move_backup("backup.place", staged, entry, &published);
|
|
} catch (...) {
|
|
if (published) move_backup("backup.rollback", entry, staged);
|
|
if (displaced) move_backup("backup.rollback", old, entry);
|
|
std::error_code ignored;
|
|
RemoveTree(staged, ignored);
|
|
throw;
|
|
}
|
|
try {
|
|
remove_backup_copy("backup.cleanup", old);
|
|
} catch (const std::filesystem::filesystem_error&) {
|
|
}
|
|
}
|
|
|
|
static void restoreSave(const std::string& dirName) {
|
|
const std::string live = save_root() + "/" + dirName;
|
|
const std::string backupEntry = backup_entry(BACKUP_DIR, dirName);
|
|
const std::string backup = entry_save(backupEntry);
|
|
const std::string stagedEntry = backup_entry(RESTORE_STAGING_DIR, dirName);
|
|
const std::string oldEntry = backup_entry(RESTORE_OLD_DIR, dirName);
|
|
const std::string staged = entry_save(stagedEntry);
|
|
const std::string old = entry_save(oldEntry);
|
|
require_plain_paths(dirName, {SAVE_DIR, BACKUP_DIR, RESTORE_STAGING_DIR, RESTORE_OLD_DIR});
|
|
RemoveTree(stagedEntry);
|
|
RemoveTree(oldEntry);
|
|
make_directories(stagedEntry);
|
|
make_directories(oldEntry);
|
|
FileSwap swap;
|
|
try {
|
|
copy_tree("restore.copy", backup, staged);
|
|
copy_file_step("restore.copy", param_path(backup), param_path(staged));
|
|
if (path_exists(blocks_path(backup))) {
|
|
copy_file_step("restore.copy", blocks_path(backup), blocks_path(staged));
|
|
}
|
|
if (tree_sizes(stagedEntry) != tree_sizes(backupEntry)) {
|
|
throw std::filesystem::filesystem_error("SaveData: the staged copy of the backup is incomplete", stagedEntry, std::make_error_code(std::errc::io_error));
|
|
}
|
|
flush_tree(stagedEntry);
|
|
swap.move("restore.aside", live, old);
|
|
for (const auto& [from, to] : {std::pair{param_path(live), param_path(old)}, std::pair{blocks_path(live), blocks_path(old)}}) {
|
|
if (path_exists(from)) {
|
|
swap.move("restore.aside", from, to);
|
|
}
|
|
}
|
|
swap.move("restore.place", staged, live);
|
|
swap.move("restore.place", param_path(staged), param_path(live));
|
|
if (path_exists(blocks_path(staged))) {
|
|
swap.move("restore.place", blocks_path(staged), blocks_path(live));
|
|
}
|
|
} catch (...) {
|
|
swap.undo("restore.rollback");
|
|
std::error_code ignored;
|
|
RemoveTree(stagedEntry, ignored);
|
|
RemoveTree(oldEntry, ignored);
|
|
throw;
|
|
}
|
|
std::error_code ignored;
|
|
RemoveTree(oldEntry, ignored);
|
|
RemoveTree(stagedEntry, ignored);
|
|
}
|
|
|
|
static int deleteSave(const SaveDataDelete* del, std::string* traceDir) {
|
|
SaveDataDelete localDel{};
|
|
if (!readGuest(del, localDel) || localDel.dir_name == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
std::string dirName;
|
|
if (!parse_dir_name(localDel.dir_name, &dirName)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (traceDir != nullptr) *traceDir = dirName;
|
|
const std::string path = save_root() + "/" + dirName;
|
|
std::lock_guard lock(g_slots_mutex);
|
|
std::error_code error;
|
|
if (isMountedDirectory(path, error)) return SAVE_DATA_ERROR_BUSY;
|
|
if (error) return SAVE_DATA_ERROR_INTERNAL;
|
|
try {
|
|
require_plain_paths(dirName, {BACKUP_DIR, BACKUP_STAGING_DIR, BACKUP_OLD_DIR});
|
|
if (path_is_directory(path)) {
|
|
RemoveTree(path);
|
|
}
|
|
std::error_code ec;
|
|
std::filesystem::remove(param_path(path), ec);
|
|
if (ec) return SAVE_DATA_ERROR_INTERNAL;
|
|
std::filesystem::remove(blocks_path(path), ec);
|
|
if (ec) return SAVE_DATA_ERROR_INTERNAL;
|
|
for (const char* root : {BACKUP_STAGING_DIR, BACKUP_OLD_DIR, BACKUP_DIR}) {
|
|
remove_backup_copy("backup.delete", backup_entry(root, dirName));
|
|
}
|
|
} catch (const std::filesystem::filesystem_error&) {
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDelete(const SaveDataDelete* del) {
|
|
std::string dir = "(null)";
|
|
const int rc = deleteSave(del, &dir);
|
|
SAVEDATA_TRACE("delete dir=%s -> 0x%08x", dir.c_str(), static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDeleteTransactionResource(int32_t resource) {
|
|
(void)resource;
|
|
if (g_initializations == 0) return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
static constexpr std::uint64_t SAVE_DATA_BLOCK_BYTES = 65536;
|
|
|
|
enum class FreeSpaceMode : std::uint8_t { Fixed, Host };
|
|
|
|
static FreeSpaceMode free_space_mode() {
|
|
const char* configured = std::getenv("ANYPS5_FREE_SPACE");
|
|
if (configured == nullptr || std::strcmp(configured, "fixed") == 0) return FreeSpaceMode::Fixed;
|
|
if (std::strcmp(configured, "host") == 0) return FreeSpaceMode::Host;
|
|
throw std::runtime_error("ANYPS5_FREE_SPACE must be fixed or host, not \"" + std::string(configured) + "\"");
|
|
}
|
|
|
|
static std::uint64_t default_free_space(const std::string& path) {
|
|
std::error_code error;
|
|
std::filesystem::path probe = std::filesystem::absolute(path, error);
|
|
require_no_error(error, "SaveData: cannot make absolute", path);
|
|
while (!std::filesystem::exists(probe, error) && probe.has_relative_path()) probe = probe.parent_path();
|
|
const auto space = std::filesystem::space(probe, error);
|
|
require_no_error(error, "SaveData: cannot read the free space of", probe);
|
|
return static_cast<std::uint64_t>(space.available);
|
|
}
|
|
|
|
static SaveDataFreeSpaceSource g_free_space_source = default_free_space;
|
|
|
|
extern "C" void SetSaveDataFreeSpaceSourceForTest_nid_no_patch(SaveDataFreeSpaceSource source) {
|
|
g_free_space_source = source != nullptr ? source : default_free_space;
|
|
}
|
|
|
|
static bool host_free_bytes(const std::string& path, std::uint64_t& bytes) {
|
|
try {
|
|
bytes = g_free_space_source(path);
|
|
return true;
|
|
} catch (const std::exception& failure) {
|
|
static std::atomic<bool> reported{false};
|
|
if (!reported.exchange(true, std::memory_order_relaxed)) {
|
|
std::fprintf(stderr, "[SAVEDATA:native] host free space unavailable, saves keep their own size: %s\n", failure.what());
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
|
|
static std::uint64_t save_blocks(const std::string& real_path) {
|
|
std::ifstream file(blocks_path(real_path));
|
|
std::uint64_t blocks = 0;
|
|
if (!(file >> blocks) || blocks == 0) {
|
|
return SAVE_DATA_BLOCKS_MAX;
|
|
}
|
|
return std::min(blocks, SAVE_DATA_BLOCKS_MAX);
|
|
}
|
|
|
|
static bool keep_save_blocks(const std::string& real_path, std::uint64_t blocks) {
|
|
const auto content = std::to_string(std::min(blocks, SAVE_DATA_BLOCKS_MAX)) + '\n';
|
|
return savedata::replace_file(blocks_path(real_path), content.data(), content.size());
|
|
}
|
|
|
|
static std::uint64_t used_blocks(const std::string& real_path) {
|
|
std::uint64_t blocks = 0;
|
|
std::error_code error;
|
|
for (auto it = std::filesystem::recursive_directory_iterator(real_path, error); !error && it != std::filesystem::recursive_directory_iterator(); it.increment(error)) {
|
|
if (!it->is_regular_file(error)) {
|
|
continue;
|
|
}
|
|
const auto bytes = it->file_size(error);
|
|
if (!error) {
|
|
blocks += (bytes + SAVE_DATA_BLOCK_BYTES - 1) / SAVE_DATA_BLOCK_BYTES;
|
|
}
|
|
}
|
|
return blocks;
|
|
}
|
|
|
|
static SaveDataSearchInfo search_info(const std::string& real_path) {
|
|
const auto blocks = save_blocks(real_path);
|
|
auto freeBlocks = blocks - std::min(blocks, used_blocks(real_path));
|
|
if (free_space_mode() == FreeSpaceMode::Host) {
|
|
std::uint64_t available = 0;
|
|
if (host_free_bytes(real_path, available)) freeBlocks = std::min(freeBlocks, available / SAVE_DATA_BLOCK_BYTES);
|
|
}
|
|
return SaveDataSearchInfo{blocks, freeBlocks, {}};
|
|
}
|
|
|
|
struct SearchTrace {
|
|
bool readable = false;
|
|
std::int32_t user_id = -1;
|
|
bool named = false;
|
|
SceSaveDataDirName name{};
|
|
std::uint32_t hit_num = 0;
|
|
std::uint32_t set_num = 0;
|
|
};
|
|
|
|
static int dirNameSearch(const SaveDataDirNameSearchCond* cond, SaveDataDirNameSearchResult* result, SearchTrace* trace) {
|
|
if (cond == nullptr || result == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
SaveDataDirNameSearchCond localCond{};
|
|
if (!GuestCopyIn_nid_no_patch(&localCond, cond, sizeof(localCond))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
SaveDataDirNameSearchResult localResult{};
|
|
if (!GuestCopyIn_nid_no_patch(&localResult, result, sizeof(localResult)) ||
|
|
!GuestWritable_nid_no_patch(result, sizeof(localResult))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (trace != nullptr) {
|
|
trace->readable = true;
|
|
trace->user_id = localCond.user_id;
|
|
}
|
|
localResult.hit_num = 0;
|
|
localResult.set_num = 0;
|
|
if (!GuestCopyOut_nid_no_patch(result, &localResult, sizeof(localResult))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
const std::uint32_t key = localCond.key;
|
|
if ((key > SAVE_DATA_SORT_KEY_MTIME && key != SAVE_DATA_SORT_KEY_FREE_BLOCKS) || localCond.order > SAVE_DATA_SORT_ORDER_DESCENT) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
SceSaveDataDirName localName{};
|
|
if (localCond.dir_name != nullptr) {
|
|
if (!GuestCopyIn_nid_no_patch(&localName, localCond.dir_name, sizeof(localName))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
const auto* nameEnd = static_cast<const char*>(std::memchr(localName.data, '\0', sizeof(localName.data)));
|
|
if (nameEnd == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (trace != nullptr) {
|
|
trace->named = true;
|
|
trace->name = localName;
|
|
}
|
|
}
|
|
if (localCond.title_id != nullptr) {
|
|
SceSaveDataTitleId localTitle{};
|
|
if (!GuestCopyIn_nid_no_patch(&localTitle, localCond.title_id, sizeof(localTitle))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (std::strncmp(localTitle.data, GetAppTitleId_nid_postfix().value, sizeof(localTitle.data)) != 0) {
|
|
return SAVE_DATA_OK;
|
|
}
|
|
}
|
|
const char* pattern = (localCond.dir_name != nullptr) ? localName.data : nullptr;
|
|
const std::string root = save_root();
|
|
if (!path_is_directory(root)) {
|
|
return SAVE_DATA_OK;
|
|
}
|
|
struct Match {
|
|
std::string name;
|
|
std::string path;
|
|
SaveDataParam param;
|
|
SaveDataSearchInfo info;
|
|
};
|
|
const bool sortByParam = key == SAVE_DATA_SORT_KEY_USER_PARAM || key == SAVE_DATA_SORT_KEY_MTIME;
|
|
std::vector<Match> matches;
|
|
for_each_entry<std::filesystem::directory_iterator>(root, [&](const std::filesystem::directory_entry& entry) {
|
|
if (!entry_is_directory(entry)) {
|
|
return;
|
|
}
|
|
const std::string name = entry.path().filename().string();
|
|
if (!dir_name_match(name.c_str(), pattern)) {
|
|
return;
|
|
}
|
|
Match match{name, entry.path().string(), {}, search_info(entry.path().string())};
|
|
if (sortByParam) {
|
|
match.param = load_param(match.path);
|
|
}
|
|
matches.push_back(std::move(match));
|
|
});
|
|
std::sort(matches.begin(), matches.end(), [](const Match& a, const Match& b) { return a.name < b.name; });
|
|
if (key == SAVE_DATA_SORT_KEY_USER_PARAM) {
|
|
std::stable_sort(matches.begin(), matches.end(), [](const Match& a, const Match& b) { return a.param.user_param < b.param.user_param; });
|
|
} else if (key == SAVE_DATA_SORT_KEY_MTIME) {
|
|
std::stable_sort(matches.begin(), matches.end(), [](const Match& a, const Match& b) { return a.param.mtime < b.param.mtime; });
|
|
} else if (key == SAVE_DATA_SORT_KEY_BLOCKS) {
|
|
std::stable_sort(matches.begin(), matches.end(), [](const Match& a, const Match& b) { return a.info.blocks < b.info.blocks; });
|
|
} else if (key == SAVE_DATA_SORT_KEY_FREE_BLOCKS) {
|
|
std::stable_sort(matches.begin(), matches.end(), [](const Match& a, const Match& b) { return a.info.free_blocks < b.info.free_blocks; });
|
|
}
|
|
if (localCond.order == SAVE_DATA_SORT_ORDER_DESCENT) {
|
|
std::reverse(matches.begin(), matches.end());
|
|
}
|
|
const std::uint32_t set = localResult.dir_names == nullptr ? 0 : static_cast<std::uint32_t>(std::min<std::size_t>(localResult.dir_names_num, matches.size()));
|
|
if (set != 0) {
|
|
if (!GuestWritable_nid_no_patch(localResult.dir_names, sizeof(SceSaveDataDirName) * set)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (localResult.params != nullptr && !GuestWritable_nid_no_patch(localResult.params, sizeof(SaveDataParam) * set)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (localResult.infos != nullptr && !GuestWritable_nid_no_patch(localResult.infos, sizeof(SaveDataSearchInfo) * set)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
}
|
|
for (std::uint32_t i = 0; i < set; i++) {
|
|
SceSaveDataDirName entry{};
|
|
std::snprintf(entry.data, sizeof(entry.data), "%s", matches[i].name.c_str());
|
|
if (!GuestCopyOut_nid_no_patch(&localResult.dir_names[i], &entry, sizeof(entry))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (localResult.params != nullptr) {
|
|
const SaveDataParam param = sortByParam ? matches[i].param : load_param(matches[i].path);
|
|
if (!GuestCopyOut_nid_no_patch(&localResult.params[i], ¶m, sizeof(param))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
}
|
|
if (localResult.infos != nullptr && !GuestCopyOut_nid_no_patch(&localResult.infos[i], &matches[i].info, sizeof(matches[i].info))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
}
|
|
localResult.hit_num = static_cast<std::uint32_t>(matches.size());
|
|
localResult.set_num = set;
|
|
if (!GuestCopyOut_nid_no_patch(result, &localResult, sizeof(localResult))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (trace != nullptr) {
|
|
trace->hit_num = localResult.hit_num;
|
|
trace->set_num = localResult.set_num;
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDirNameSearch(const SaveDataDirNameSearchCond* cond, SaveDataDirNameSearchResult* result) {
|
|
SearchTrace trace;
|
|
const int rc = dirNameSearch(cond, result, &trace);
|
|
SAVEDATA_TRACE("dirNameSearch user=%d pattern=%.*s hit=%u set=%u -> 0x%08x", trace.readable ? trace.user_id : -1, static_cast<int>(sizeof(SceSaveDataDirName::data)), trace.named ? trace.name.data : "(all)", trace.hit_num, trace.set_num, static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetEventResult(const void* event_param, SaveDataEvent* event) {
|
|
(void)event_param;
|
|
if (event == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
std::lock_guard lock(g_state_mutex);
|
|
if (g_events.empty()) {
|
|
return SAVE_DATA_ERROR_NOT_FOUND;
|
|
}
|
|
const SaveDataEvent entry = g_events.front();
|
|
if (!GuestCopyOut_nid_no_patch(event, &entry, sizeof(entry))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
g_events.pop_front();
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
static int getMountInfo(const SaveDataMountPoint* mount_point, SaveDataMountInfo* info, std::string* tracePoint) {
|
|
SaveDataMountPoint localPoint{};
|
|
if (!copy_mount_point(mount_point, &localPoint) || info == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (tracePoint != nullptr) *tracePoint = localPoint.data;
|
|
std::lock_guard lock(g_slots_mutex);
|
|
const int slot = find_slot_by_mount_point(localPoint.data);
|
|
if (slot == -1) {
|
|
return SAVE_DATA_ERROR_NOT_MOUNTED;
|
|
}
|
|
SaveDataMountInfo localInfo{};
|
|
const auto search = search_info(g_slots[slot].real_path);
|
|
localInfo.blocks = search.blocks;
|
|
localInfo.free_blocks = search.free_blocks;
|
|
if (!GuestCopyOut_nid_no_patch(info, &localInfo, sizeof(localInfo))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetMountInfo(const SaveDataMountPoint* mount_point, SaveDataMountInfo* info) {
|
|
std::string point = "(null)";
|
|
const int rc = getMountInfo(mount_point, info, &point);
|
|
SAVEDATA_TRACE("getMountInfo point=%s -> 0x%08x", point.c_str(), static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
static int getParam(const SaveDataMountPoint* mount_point, uint32_t param_type, void* param_buf, size_t param_buf_size, size_t* got_size, std::string* tracePoint, size_t* traceGot) {
|
|
SaveDataMountPoint localPoint{};
|
|
if (!copy_mount_point(mount_point, &localPoint) || param_buf == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (tracePoint != nullptr) *tracePoint = localPoint.data;
|
|
std::lock_guard lock(g_slots_mutex);
|
|
const int slot = find_slot_by_mount_point(localPoint.data);
|
|
if (slot == -1) {
|
|
return SAVE_DATA_ERROR_NOT_MOUNTED;
|
|
}
|
|
ParamField field{};
|
|
if (!param_field(param_type, &field) || param_buf_size < field.size) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
const SaveDataParam param = load_param(g_slots[slot].real_path);
|
|
if (got_size != nullptr) {
|
|
std::size_t previousGotSize{};
|
|
if (!GuestCopyIn_nid_no_patch(&previousGotSize, got_size, sizeof(previousGotSize)) ||
|
|
!GuestCopyOut_nid_no_patch(got_size, &previousGotSize, sizeof(previousGotSize))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
}
|
|
if (!GuestCopyOut_nid_no_patch(param_buf, reinterpret_cast<const char*>(¶m) + field.offset, field.size)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (got_size != nullptr) {
|
|
if (!GuestCopyOut_nid_no_patch(got_size, &field.size, sizeof(field.size))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (traceGot != nullptr) *traceGot = field.size;
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetParam(const SaveDataMountPoint* mount_point, uint32_t param_type, void* param_buf, size_t param_buf_size, size_t* got_size) {
|
|
std::string point = "(null)";
|
|
size_t traceGot = 0;
|
|
const int rc = getParam(mount_point, param_type, param_buf, param_buf_size, got_size, &point, &traceGot);
|
|
SAVEDATA_TRACE("getParam point=%s type=%u size=%zu -> 0x%08x got=%zu", point.c_str(), param_type, param_buf_size, static_cast<unsigned>(rc), traceGot);
|
|
return rc;
|
|
}
|
|
|
|
static int getSaveDataMemory2(SaveDataMemoryGet2* get_param, int* traceUser = nullptr, unsigned* traceSlot = nullptr) {
|
|
if (get_param == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
SaveDataMemoryGet2 localParam{};
|
|
const int savedErrno = errno;
|
|
const bool copied = GuestCopyIn_nid_no_patch(&localParam, get_param, sizeof(localParam));
|
|
errno = savedErrno;
|
|
if (!copied) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (traceUser != nullptr) {
|
|
*traceUser = localParam.user_id;
|
|
}
|
|
if (traceSlot != nullptr) {
|
|
*traceSlot = localParam.slot_id;
|
|
}
|
|
std::lock_guard<std::mutex> lk(g_mem_mutex);
|
|
replay_memory_journal(localParam.user_id, localParam.slot_id);
|
|
const std::string path = mem_path(localParam.user_id, localParam.slot_id, "bin");
|
|
std::size_t size = 0;
|
|
if (!file_size_of(path, &size)) {
|
|
return SAVE_DATA_ERROR_MEMORY_NOT_READY;
|
|
}
|
|
SaveDataMemoryData localData{};
|
|
if (localParam.data != nullptr && !GuestCopyIn_nid_no_patch(&localData, localParam.data, sizeof(localData))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (localParam.data != nullptr && localData.buf_size != 0) {
|
|
if (localData.buf == nullptr || localData.offset > size || localData.buf_size > size - localData.offset) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
std::ifstream f(path, std::ios::binary);
|
|
if (!f) {
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
f.seekg(static_cast<std::streamoff>(localData.offset));
|
|
const GuestArena::HostWrite destination(localData.buf, localData.buf_size);
|
|
if (!destination.Open()) {
|
|
throw std::runtime_error("SaveData: the memory buffer is not writable");
|
|
}
|
|
f.read(static_cast<char*>(localData.buf), static_cast<std::streamsize>(localData.buf_size));
|
|
if (!f) {
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
}
|
|
if (localParam.param != nullptr) {
|
|
SaveDataParam param{};
|
|
read_param_file(mem_path(localParam.user_id, localParam.slot_id, "param"), ¶m);
|
|
if (!GuestCopyOut_nid_no_patch(localParam.param, ¶m, sizeof(param))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
}
|
|
if (localParam.icon != nullptr) {
|
|
SaveDataIcon icon{};
|
|
if (!GuestCopyIn_nid_no_patch(&icon, localParam.icon, sizeof(icon))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
icon.data_size = 0;
|
|
if (!GuestCopyOut_nid_no_patch(localParam.icon, &icon, sizeof(icon))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetSaveDataMemory2(SaveDataMemoryGet2* get_param) {
|
|
int traceUser = -1;
|
|
unsigned traceSlot = 0;
|
|
const int rc = getSaveDataMemory2(get_param, &traceUser, &traceSlot);
|
|
SAVEDATA_TRACE("getMemory2 user=%d slot=%u -> 0x%08x", traceUser, traceSlot, static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataInitialize3(const void* init) {
|
|
(void)init;
|
|
std::lock_guard lock(g_slots_mutex);
|
|
++g_initializations;
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataLoadIcon(const SaveDataMountPoint* mount_point, SaveDataIcon* icon) {
|
|
SaveDataMountPoint localPoint{};
|
|
if (!copy_mount_point(mount_point, &localPoint) || icon == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
SaveDataIcon localIcon{};
|
|
if (!GuestCopyIn_nid_no_patch(&localIcon, icon, sizeof(localIcon)) || localIcon.buf == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
std::lock_guard lock(g_slots_mutex);
|
|
const int slot = find_slot_by_mount_point(localPoint.data);
|
|
if (slot == -1) {
|
|
return SAVE_DATA_ERROR_NOT_MOUNTED;
|
|
}
|
|
const auto path = ResolveDiskPath_nid_no_patch((g_slots[slot].mount_point + "/sce_sys/icon0.png").c_str());
|
|
std::error_code error;
|
|
const auto type = std::filesystem::status(path, error).type();
|
|
if (type == std::filesystem::file_type::not_found) return SAVE_DATA_ERROR_NOT_FOUND;
|
|
if (type != std::filesystem::file_type::regular) return SAVE_DATA_ERROR_INTERNAL;
|
|
std::ifstream file(path, std::ios::binary | std::ios::ate);
|
|
if (!file) return SAVE_DATA_ERROR_INTERNAL;
|
|
const std::streamoff size = file.tellg();
|
|
if (size < 0 || static_cast<std::uintmax_t>(size) > std::numeric_limits<std::size_t>::max()) return SAVE_DATA_ERROR_INTERNAL;
|
|
const auto count = std::min(localIcon.buf_size, static_cast<std::size_t>(size));
|
|
if (count > static_cast<std::uintmax_t>(std::numeric_limits<std::streamsize>::max())) return SAVE_DATA_ERROR_INTERNAL;
|
|
std::vector<char> staged(count);
|
|
file.seekg(0);
|
|
if (count != 0) file.read(staged.data(), static_cast<std::streamsize>(count));
|
|
if (!file) return SAVE_DATA_ERROR_INTERNAL;
|
|
void* const dataSizeField = reinterpret_cast<char*>(icon) + offsetof(SaveDataIcon, data_size);
|
|
if (!GuestCopyOut_nid_no_patch(dataSizeField, &localIcon.data_size, sizeof(localIcon.data_size))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (count != 0 && !GuestCopyOut_nid_no_patch(localIcon.buf, staged.data(), count)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
const std::size_t dataSize = static_cast<std::size_t>(size);
|
|
if (!GuestCopyOut_nid_no_patch(dataSizeField, &dataSize, sizeof(dataSize))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
static int mount3(const SaveDataMount3* mount, SaveDataMountResult* mount_result, SaveDataMount3* traceMount = nullptr, std::string* traceDir = nullptr, SaveDataMountResult* traceResult = nullptr) {
|
|
SaveDataMount3 localMount{};
|
|
if (!readGuest(mount, localMount) || mount_result == nullptr || localMount.dir_name == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (traceMount != nullptr) *traceMount = localMount;
|
|
const FreeSpaceMode freeSpace = free_space_mode();
|
|
const bool create = (localMount.mount_mode & SAVE_DATA_MOUNT_MODE_CREATE) != 0;
|
|
const bool create2 = (localMount.mount_mode & SAVE_DATA_MOUNT_MODE_CREATE2) != 0;
|
|
const bool rdonly = (localMount.mount_mode & SAVE_DATA_MOUNT_MODE_RDONLY) != 0;
|
|
const bool rdwr = (localMount.mount_mode & SAVE_DATA_MOUNT_MODE_RDWR) != 0;
|
|
const bool open = !create && !create2 && (rdonly || rdwr);
|
|
if (!create && !create2 && !open) {
|
|
throw std::runtime_error("sceSaveDataMount3: unknown mount_mode");
|
|
}
|
|
std::string dirName;
|
|
if (!parse_dir_name(localMount.dir_name, &dirName)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (traceDir != nullptr) *traceDir = dirName;
|
|
const std::string real_path = save_root() + "/" + dirName;
|
|
std::lock_guard lock(g_slots_mutex);
|
|
std::error_code error;
|
|
if (isMountedDirectory(real_path, error)) return SAVE_DATA_ERROR_BUSY;
|
|
if (error) return SAVE_DATA_ERROR_INTERNAL;
|
|
const bool exists = std::filesystem::is_directory(real_path, error);
|
|
if (error == std::errc::no_such_file_or_directory) error.clear();
|
|
if (error) return SAVE_DATA_ERROR_INTERNAL;
|
|
if (create && exists) {
|
|
return SAVE_DATA_ERROR_EXISTS;
|
|
}
|
|
if (open && !exists) {
|
|
return SAVE_DATA_ERROR_NOT_FOUND;
|
|
}
|
|
int slot = find_free_slot();
|
|
if (slot == -1) {
|
|
return SAVE_DATA_ERROR_MOUNT_FULL;
|
|
}
|
|
if (!exists && (create || create2) && freeSpace == FreeSpaceMode::Host) {
|
|
const std::uint64_t blocks = localMount.blocks == 0 ? SAVE_DATA_BLOCKS_MAX : std::min(localMount.blocks, SAVE_DATA_BLOCKS_MAX);
|
|
const std::uint64_t required = blocks * SAVE_DATA_BLOCK_BYTES;
|
|
std::uint64_t available = 0;
|
|
if (host_free_bytes(real_path, available) && available < required) {
|
|
SaveDataMountResult noSpaceResult{};
|
|
noSpaceResult.required_blocks = (required - available + SAVE_DATA_BLOCK_BYTES - 1) / SAVE_DATA_BLOCK_BYTES;
|
|
if (!writeGuest(mount_result, &noSpaceResult, sizeof(noSpaceResult))) return SAVE_DATA_ERROR_PARAMETER;
|
|
return SAVE_DATA_ERROR_NO_SPACE_FS;
|
|
}
|
|
}
|
|
bool keepSize = localMount.blocks != 0 && (create || (create2 && !exists));
|
|
if (localMount.blocks != 0 && !keepSize) {
|
|
keepSize = !std::filesystem::exists(blocks_path(real_path), error);
|
|
if (error) return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
const auto absolutePath = std::filesystem::absolute(real_path, error).string();
|
|
if (error) return SAVE_DATA_ERROR_INTERNAL;
|
|
const bool created = (create || create2) && std::filesystem::create_directories(real_path, error);
|
|
if (error) return SAVE_DATA_ERROR_INTERNAL;
|
|
if (keepSize && !keep_save_blocks(real_path, localMount.blocks)) {
|
|
if (created) {
|
|
std::error_code ignored;
|
|
std::filesystem::remove(real_path, ignored);
|
|
}
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
// The title gets a short mount point (16 bytes on the PS5) and opens files under it; the
|
|
// path resolver maps it to the save directory, whose name may be far longer.
|
|
const std::string mountPoint = "/savedata" + std::to_string(slot);
|
|
SaveDataMountResult localResult{};
|
|
std::memcpy(localResult.mount_point.data, mountPoint.c_str(), mountPoint.size() + 1);
|
|
localResult.required_blocks = 0;
|
|
localResult.mount_status = (create || (create2 && !exists)) ? 1u : 0u;
|
|
if (!writeGuest(mount_result, &localResult, sizeof(localResult))) {
|
|
if (created) {
|
|
std::error_code ignored;
|
|
RemoveTree(real_path, ignored);
|
|
}
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
AddPathAlias_nid_no_patch(mountPoint.c_str(), absolutePath.c_str());
|
|
g_slots[slot].used = true;
|
|
g_slots[slot].user_id = localMount.user_id;
|
|
g_slots[slot].mount_point = mountPoint;
|
|
g_slots[slot].real_path = real_path;
|
|
if (traceResult != nullptr) *traceResult = localResult;
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataMount3(const SaveDataMount3* mount, SaveDataMountResult* mount_result) {
|
|
SaveDataMount3 traceMount{};
|
|
traceMount.user_id = -1;
|
|
std::string traceDir = "(null)";
|
|
SaveDataMountResult traceResult{};
|
|
const int rc = mount3(mount, mount_result, &traceMount, &traceDir, &traceResult);
|
|
SAVEDATA_TRACE("mount3 user=%d dir=%s mode=0x%x blocks=%llu -> 0x%08x point=%.*s status=%u", traceMount.user_id, traceDir.c_str(), traceMount.mount_mode, static_cast<unsigned long long>(traceMount.blocks), static_cast<unsigned>(rc), static_cast<int>(sizeof(SaveDataMountPoint::data)), rc == SAVE_DATA_OK ? traceResult.mount_point.data : "", rc == SAVE_DATA_OK ? traceResult.mount_status : 0u);
|
|
return rc;
|
|
}
|
|
|
|
static int mount2(const SaveDataMount2* mount, SaveDataMountResult* mount_result, SaveDataMount3* traceMount = nullptr, std::string* traceDir = nullptr, SaveDataMountResult* traceResult = nullptr) {
|
|
SaveDataMount2 localMount{};
|
|
if (!readGuest(mount, localMount) || mount_result == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
if (localMount.user_id == -1 || localMount.user_id == 0) {
|
|
return SAVE_DATA_ERROR_INVALID_LOGIN_USER;
|
|
}
|
|
const bool creates = (localMount.mount_mode & SAVE_DATA_MOUNT_MODE_CREATE) != 0;
|
|
if (localMount.mount_mode == 0 || (creates && localMount.blocks < SAVE_DATA_BLOCKS_MIN2)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (localMount.dir_name != nullptr) {
|
|
SceSaveDataDirName localDirName{};
|
|
if (!readGuest(localMount.dir_name, localDirName)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
const std::string_view name(localDirName.data, sizeof(localDirName.data));
|
|
if (name.substr(0, name.find('\0')).find('_') != std::string_view::npos) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
}
|
|
SaveDataMount3 converted{};
|
|
converted.user_id = localMount.user_id;
|
|
converted.dir_name = localMount.dir_name;
|
|
converted.blocks = localMount.blocks;
|
|
converted.mount_mode = localMount.mount_mode;
|
|
return mount3(&converted, mount_result, traceMount, traceDir, traceResult);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataMount2(const SaveDataMount2* mount, SaveDataMountResult* mount_result) {
|
|
SaveDataMount3 traceMount{};
|
|
traceMount.user_id = -1;
|
|
std::string traceDir = "(null)";
|
|
SaveDataMountResult traceResult{};
|
|
const int rc = mount2(mount, mount_result, &traceMount, &traceDir, &traceResult);
|
|
SAVEDATA_TRACE("mount2 user=%d dir=%s mode=0x%x blocks=%llu -> 0x%08x point=%.*s status=%u", traceMount.user_id, traceDir.c_str(), traceMount.mount_mode, static_cast<unsigned long long>(traceMount.blocks), static_cast<unsigned>(rc), static_cast<int>(sizeof(SaveDataMountPoint::data)), rc == SAVE_DATA_OK ? traceResult.mount_point.data : "", rc == SAVE_DATA_OK ? traceResult.mount_status : 0u);
|
|
return rc;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataPrepare(const SaveDataMountPoint* mount_point, const SaveDataPrepareParam* param) {
|
|
(void)mount_point;
|
|
(void)param;
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSaveIcon(const SaveDataMountPoint* mount_point, const SaveDataIcon* icon) {
|
|
SaveDataMountPoint localPoint{};
|
|
if (!copy_mount_point(mount_point, &localPoint) || icon == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
SaveDataIcon localIcon{};
|
|
if (!GuestCopyIn_nid_no_patch(&localIcon, icon, sizeof(localIcon)) || localIcon.buf == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
std::lock_guard lock(g_slots_mutex);
|
|
const int slot = find_slot_by_mount_point(localPoint.data);
|
|
if (slot == -1) {
|
|
return SAVE_DATA_ERROR_NOT_MOUNTED;
|
|
}
|
|
const std::size_t bytes = std::min(localIcon.buf_size, localIcon.data_size);
|
|
const auto start = reinterpret_cast<std::uintptr_t>(localIcon.buf);
|
|
if (bytes > std::numeric_limits<std::uintptr_t>::max() - start) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
std::vector<char> staged;
|
|
if (bytes != 0) {
|
|
constexpr std::size_t chunkBytes = 65536;
|
|
std::vector<char> chunk(std::min(bytes, chunkBytes));
|
|
for (std::size_t offset = 0; offset < bytes;) {
|
|
const std::size_t part = std::min(bytes - offset, chunk.size());
|
|
if (!GuestCopyIn_nid_no_patch(chunk.data(), static_cast<const char*>(localIcon.buf) + offset, part)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
staged.insert(staged.end(), chunk.begin(), chunk.begin() + static_cast<std::ptrdiff_t>(part));
|
|
offset += part;
|
|
}
|
|
}
|
|
const auto path = ResolveDiskPath_nid_no_patch((g_slots[slot].mount_point + "/sce_sys/icon0.png").c_str());
|
|
return savedata::replace_file(path, staged.data(), bytes) ? SAVE_DATA_OK : SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSaveIconByPath(const SaveDataMountPoint* mount_point, const char* path) {
|
|
SaveDataMountPoint localPoint{};
|
|
std::string guestPath;
|
|
if (!copy_mount_point(mount_point, &localPoint) ||
|
|
CopyGuestPath_nid_no_patch(path, guestPath) != 0 || guestPath.empty()) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
std::lock_guard lock(g_slots_mutex);
|
|
const int slot = find_slot_by_mount_point(localPoint.data);
|
|
if (slot == -1) return SAVE_DATA_ERROR_NOT_MOUNTED;
|
|
|
|
try {
|
|
const auto source = ResolveArchivedPath_nid_no_patch(guestPath.c_str(), false);
|
|
std::vector<char> bytes;
|
|
std::error_code error;
|
|
const auto status = std::filesystem::status(source, error);
|
|
if (status.type() == std::filesystem::file_type::not_found) {
|
|
AppArchiveNode node{};
|
|
if (!AppArchiveLookup_nid_no_patch(source, &node) || node.Directory) return SAVE_DATA_ERROR_NOT_FOUND;
|
|
if (node.Size > bytes.max_size()) return SAVE_DATA_ERROR_INTERNAL;
|
|
bytes.resize(static_cast<std::size_t>(node.Size));
|
|
if (!bytes.empty() && AppArchiveRead_nid_no_patch(node.Handle, 0, bytes.data(), node.Size) != node.Size) {
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
} else {
|
|
if (error) return SAVE_DATA_ERROR_INTERNAL;
|
|
if (!std::filesystem::is_regular_file(status)) return SAVE_DATA_ERROR_NOT_FOUND;
|
|
if (!read_file_all(source, bytes)) return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
const auto destination = ResolveDiskPath_nid_no_patch((g_slots[slot].mount_point + "/sce_sys/icon0.png").c_str());
|
|
return savedata::replace_file(destination, bytes.data(), bytes.size()) ? SAVE_DATA_OK : SAVE_DATA_ERROR_INTERNAL;
|
|
} catch (const std::filesystem::filesystem_error& error) {
|
|
if (error.code() == std::errc::no_such_file_or_directory || error.code() == std::errc::not_a_directory) {
|
|
return SAVE_DATA_ERROR_NOT_FOUND;
|
|
}
|
|
if (error.code() == std::errc::filename_too_long) return SAVE_DATA_ERROR_PARAMETER;
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
}
|
|
|
|
static int setParam(const SaveDataMountPoint* mount_point, uint32_t param_type, const void* param_buf, size_t param_buf_size, std::string* tracePoint) {
|
|
SaveDataMountPoint localPoint{};
|
|
if (!copy_mount_point(mount_point, &localPoint) || param_buf == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (tracePoint != nullptr) *tracePoint = localPoint.data;
|
|
std::lock_guard lock(g_slots_mutex);
|
|
const int slot = find_slot_by_mount_point(localPoint.data);
|
|
if (slot == -1) {
|
|
return SAVE_DATA_ERROR_NOT_MOUNTED;
|
|
}
|
|
ParamField field{};
|
|
if (!param_field(param_type, &field) || param_buf_size == 0 || (!field.text && param_buf_size < field.size)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
SaveDataParam param = load_param(g_slots[slot].real_path);
|
|
char* destination = reinterpret_cast<char*>(¶m) + field.offset;
|
|
if (field.text) {
|
|
const std::size_t length = std::min(param_buf_size, field.size - 1);
|
|
std::vector<char> textBuf(length);
|
|
if (!GuestCopyIn_nid_no_patch(textBuf.data(), param_buf, length)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
const char* end = static_cast<const char*>(std::memchr(textBuf.data(), '\0', length));
|
|
std::memset(destination, 0, field.size);
|
|
std::memcpy(destination, textBuf.data(), end != nullptr ? static_cast<std::size_t>(end - textBuf.data()) : length);
|
|
} else {
|
|
if (!GuestCopyIn_nid_no_patch(destination, param_buf, field.size)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
}
|
|
if (param_type != SAVE_DATA_PARAM_TYPE_MTIME) {
|
|
param.mtime = static_cast<std::int64_t>(std::time(nullptr));
|
|
}
|
|
return store_param(g_slots[slot].real_path, param) ? SAVE_DATA_OK : SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSetParam(const SaveDataMountPoint* mount_point, uint32_t param_type, const void* param_buf, size_t param_buf_size) {
|
|
std::string point = "(null)";
|
|
const int rc = setParam(mount_point, param_type, param_buf, param_buf_size, &point);
|
|
SAVEDATA_TRACE("setParam point=%s type=%u size=%zu -> 0x%08x", point.c_str(), param_type, param_buf_size, static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
struct SetMemoryTrace {
|
|
std::int32_t user_id = -1;
|
|
std::uint32_t slot_id = 0;
|
|
std::uint32_t data_num = 0;
|
|
};
|
|
|
|
static int setSaveDataMemory2(const SaveDataMemorySet2* set_param, SetMemoryTrace* trace) {
|
|
if (set_param == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
SaveDataMemorySet2 localSet{};
|
|
const int savedErrno = errno;
|
|
if (!GuestCopyIn_nid_no_patch(&localSet, set_param, sizeof(localSet))) {
|
|
errno = savedErrno;
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (trace != nullptr) {
|
|
trace->user_id = localSet.user_id;
|
|
trace->slot_id = localSet.slot_id;
|
|
trace->data_num = localSet.data_num;
|
|
}
|
|
if (g_initializations == 0) {
|
|
errno = savedErrno;
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
std::lock_guard<std::mutex> lk(g_mem_mutex);
|
|
replay_memory_journal(localSet.user_id, localSet.slot_id);
|
|
const std::string path = mem_path(localSet.user_id, localSet.slot_id, "bin");
|
|
std::size_t size = 0;
|
|
if (!file_size_of(path, &size)) {
|
|
errno = savedErrno;
|
|
return SAVE_DATA_ERROR_MEMORY_NOT_READY;
|
|
}
|
|
SaveDataParam localParam{};
|
|
if (localSet.param != nullptr) {
|
|
if (!GuestCopyIn_nid_no_patch(&localParam, localSet.param, sizeof(localParam))) {
|
|
errno = savedErrno;
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
}
|
|
const auto paramBytes = localSet.param != nullptr
|
|
? std::span<const char>(reinterpret_cast<const char*>(&localParam), sizeof(localParam))
|
|
: std::span<const char>{};
|
|
const std::uint32_t n = localSet.data != nullptr ? (localSet.data_num != 0 ? localSet.data_num : 1u) : 0u;
|
|
std::vector<MemoryWrite> writes;
|
|
std::deque<std::vector<char>> buffers;
|
|
std::size_t stagedBytes = 0;
|
|
constexpr std::size_t kChunkSize = 64;
|
|
std::array<SaveDataMemoryData, kChunkSize> chunk{};
|
|
try {
|
|
for (std::uint32_t offset = 0; offset < n; offset += kChunkSize) {
|
|
const std::uint32_t count = std::min<std::uint32_t>(kChunkSize, n - offset);
|
|
if (!GuestCopyIn_nid_no_patch(chunk.data(), localSet.data + offset, count * sizeof(SaveDataMemoryData))) {
|
|
errno = savedErrno;
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
for (std::uint32_t i = 0; i < count; i++) {
|
|
const SaveDataMemoryData& d = chunk[i];
|
|
if (d.buf_size == 0) {
|
|
continue;
|
|
}
|
|
if (d.buf == nullptr || d.offset > size || d.buf_size > size - d.offset || stagedBytes > size - d.buf_size) {
|
|
errno = savedErrno;
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
stagedBytes += d.buf_size;
|
|
std::vector<char>& writeBuf = buffers.emplace_back(d.buf_size);
|
|
if (!GuestCopyIn_nid_no_patch(writeBuf.data(), d.buf, d.buf_size)) {
|
|
errno = savedErrno;
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
writes.push_back({d.offset, d.buf_size, writeBuf.data()});
|
|
}
|
|
}
|
|
if (!writes.empty()) {
|
|
std::fstream memory(path, std::ios::binary | std::ios::in | std::ios::out);
|
|
if (!memory) {
|
|
errno = savedErrno;
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
const std::string journal = mem_path(localSet.user_id, localSet.slot_id, "journal");
|
|
const auto bytes = encode_memory_journal(writes, paramBytes);
|
|
if (!replace_synced_memory_file(journal, bytes) || !apply_memory_journal(memory, path, journal, writes, paramBytes)) {
|
|
errno = savedErrno;
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
} else if (!paramBytes.empty() && !replace_synced_memory_file(mem_path(localSet.user_id, localSet.slot_id, "param"), paramBytes)) {
|
|
errno = savedErrno;
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
} catch (const std::filesystem::filesystem_error&) {
|
|
errno = savedErrno;
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
} catch (const std::bad_alloc&) {
|
|
errno = savedErrno;
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
errno = savedErrno;
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSetSaveDataMemory2(const SaveDataMemorySet2* set_param) {
|
|
SetMemoryTrace trace{};
|
|
const int rc = setSaveDataMemory2(set_param, &trace);
|
|
SAVEDATA_TRACE("setMemory2 user=%d slot=%u num=%u -> 0x%08x", trace.user_id, trace.slot_id, trace.data_num, static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
static int setupSaveDataMemory2(const SaveDataMemorySetup2* setup_param, SaveDataMemorySetupResult* result) {
|
|
if (setup_param == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
SaveDataMemorySetup2 localParam{};
|
|
const int savedErrno = errno;
|
|
const bool copied = GuestCopyIn_nid_no_patch(&localParam, setup_param, sizeof(localParam));
|
|
errno = savedErrno;
|
|
if (!copied) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (localParam.memory_size == 0 || localParam.memory_size > MEM_MAX_SIZE) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (result != nullptr && !GuestWritable_nid_no_patch(result, sizeof(*result))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
const bool needParam = (localParam.init_param != nullptr && (localParam.option & 1u) != 0);
|
|
SaveDataParam initParam{};
|
|
if (needParam) {
|
|
const int savedErrnoParam = errno;
|
|
const bool copiedInit = GuestCopyIn_nid_no_patch(&initParam, localParam.init_param, sizeof(initParam));
|
|
errno = savedErrnoParam;
|
|
if (!copiedInit) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
}
|
|
std::lock_guard<std::mutex> lk(g_mem_mutex);
|
|
replay_memory_journal(localParam.user_id, localParam.slot_id);
|
|
const std::string path = mem_path(localParam.user_id, localParam.slot_id, "bin");
|
|
std::size_t existed = 0;
|
|
const bool have = file_size_of(path, &existed);
|
|
if (!have) {
|
|
existed = 0;
|
|
}
|
|
const std::string paramPath = mem_path(localParam.user_id, localParam.slot_id, "param");
|
|
std::size_t paramSize = 0;
|
|
const bool haveParam = file_size_of(paramPath, ¶mSize);
|
|
if (!have || existed < localParam.memory_size || (needParam && !haveParam)) {
|
|
std::error_code ec;
|
|
std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec);
|
|
if (needParam) {
|
|
std::vector<char> pd(sizeof(SaveDataParam));
|
|
std::memcpy(pd.data(), &initParam, sizeof(SaveDataParam));
|
|
if (!write_file_replace(paramPath, pd)) {
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
}
|
|
if (!have || existed < localParam.memory_size) {
|
|
std::vector<char> data;
|
|
if (have && !read_file_all(path, data)) {
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
data.resize(localParam.memory_size, 0);
|
|
if (!write_file_replace(path, data)) {
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
}
|
|
}
|
|
if (result != nullptr) {
|
|
SaveDataMemorySetupResult localResult{};
|
|
localResult.existed_memory_size = have ? existed : 0;
|
|
const int savedErrnoResult = errno;
|
|
const bool copiedResult = GuestCopyOut_nid_no_patch(result, &localResult, sizeof(localResult));
|
|
errno = savedErrnoResult;
|
|
if (!copiedResult) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSetupSaveDataMemory2(const SaveDataMemorySetup2* setup_param, SaveDataMemorySetupResult* result) {
|
|
const int rc = setupSaveDataMemory2(setup_param, result);
|
|
return rc;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSyncSaveDataMemory(const void* sync_param) {
|
|
if (sync_param == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
std::uint32_t syncWords[2]{};
|
|
const int savedErrno = errno;
|
|
const bool copied = GuestCopyIn_nid_no_patch(syncWords, sync_param, sizeof(syncWords));
|
|
errno = savedErrno;
|
|
if (!copied) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
// Every Set already writes straight through to disk; sync only has to confirm the memory exists.
|
|
const auto user_id = static_cast<std::int32_t>(syncWords[0]);
|
|
const std::uint32_t slot_id = syncWords[1];
|
|
std::lock_guard<std::mutex> lk(g_mem_mutex);
|
|
replay_memory_journal(user_id, slot_id);
|
|
std::size_t size = 0;
|
|
if (!file_size_of(mem_path(user_id, slot_id, "bin"), &size)) {
|
|
return SAVE_DATA_ERROR_MEMORY_NOT_READY;
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataTerminate(void) {
|
|
if (InEventCallback()) {
|
|
return SAVE_DATA_ERROR_BUSY;
|
|
}
|
|
EventWorker* stopped = nullptr;
|
|
{
|
|
std::lock_guard lock(g_slots_mutex);
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
if (g_initializations == 1 && any_slot_used()) {
|
|
return SAVE_DATA_ERROR_BUSY;
|
|
}
|
|
--g_initializations;
|
|
if (g_initializations == 0) {
|
|
g_convertProgress = 0.0f;
|
|
g_backupProgress = 0.0f;
|
|
stopped = DetachEventDelivery();
|
|
}
|
|
}
|
|
if (stopped != nullptr) JoinEventDelivery(stopped);
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
static int transferringMount(const SaveDataTransferringMount* mount, SaveDataMountResult* mount_result) {
|
|
(void)mount;
|
|
if (mount_result != nullptr) {
|
|
SaveDataMountResult localResult{};
|
|
const int savedErrno = errno;
|
|
const bool copied = GuestCopyOut_nid_no_patch(mount_result, &localResult, sizeof(localResult));
|
|
errno = savedErrno;
|
|
if (!copied) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
}
|
|
return SAVE_DATA_ERROR_NOT_FOUND;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataTransferringMount(const SaveDataTransferringMount* mount, SaveDataMountResult* mount_result) {
|
|
const int rc = transferringMount(mount, mount_result);
|
|
SAVEDATA_TRACE("transferringMount -> 0x%08x", static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
static int unmountMountPoint(const SaveDataMountPoint* mount_point, std::string* tracePoint, bool backup) {
|
|
SaveDataMountPoint localPoint{};
|
|
if (!copy_mount_point(mount_point, &localPoint)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (tracePoint != nullptr) *tracePoint = localPoint.data;
|
|
SaveDataEvent event{};
|
|
if (backup) {
|
|
event.type = SAVE_DATA_EVENT_TYPE_UMOUNT_BACKUP;
|
|
event.error_code = SAVE_DATA_OK;
|
|
}
|
|
{
|
|
std::lock_guard lock(g_slots_mutex);
|
|
const int slot = find_slot_by_mount_point(localPoint.data);
|
|
if (slot == -1) {
|
|
return SAVE_DATA_ERROR_NOT_MOUNTED;
|
|
}
|
|
const MountSlot mounted = g_slots[slot];
|
|
RemovePathAlias_nid_no_patch(mounted.mount_point.c_str());
|
|
g_slots[slot] = MountSlot{};
|
|
if (backup) {
|
|
const AppTitleId title = GetAppTitleId_nid_postfix();
|
|
const std::string dirName = std::filesystem::path(mounted.real_path).filename().string();
|
|
event.user_id = mounted.user_id;
|
|
std::memcpy(event.title_id.data, title.value, strnlen(title.value, sizeof(event.title_id.data) - 1));
|
|
std::memcpy(event.dir_name.data, dirName.data(), std::min(dirName.size(), sizeof(event.dir_name.data) - 1));
|
|
try {
|
|
backupSave(dirName);
|
|
} catch (const std::exception&) {
|
|
event.error_code = SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
}
|
|
}
|
|
if (backup) {
|
|
{
|
|
std::lock_guard lock(g_state_mutex);
|
|
g_events.push_back(event);
|
|
}
|
|
DeliverEvent(event);
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
static int umount2(uint32_t mode, const SaveDataMountPoint* mount_point, std::string* tracePoint) {
|
|
if ((mode & ~(SAVE_DATA_UMOUNT_MODE_BACKUP | SAVE_DATA_UMOUNT_MODE_BACKUP_FORCE)) != 0) {
|
|
throw std::runtime_error("sceSaveDataUmount2: unknown mode");
|
|
}
|
|
return unmountMountPoint(mount_point, tracePoint, (mode & SAVE_DATA_UMOUNT_MODE_BACKUP) != 0);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataUmount2(uint32_t mode, const SaveDataMountPoint* mount_point) {
|
|
std::string point = "(null)";
|
|
const int rc = umount2(mode, mount_point, &point);
|
|
SAVEDATA_TRACE("umount2 mode=0x%x point=%s -> 0x%08x", mode, point.c_str(), static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataTransferringMountPs4(const SaveDataTransferringMount* mount, SaveDataMountResult* mount_result) {
|
|
const int rc = transferringMount(mount, mount_result);
|
|
SAVEDATA_TRACE("transferringMountPs4 -> 0x%08x", static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
static int dirNameSearchPs4(const SaveDataDirNameSearchCond* cond, SaveDataDirNameSearchResult* result, std::int32_t* traceUser) {
|
|
SaveDataDirNameSearchCond localCond{};
|
|
SaveDataDirNameSearchResult localResult{};
|
|
if (!readGuest(cond, localCond) || !readGuest(result, localResult)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (traceUser != nullptr) *traceUser = localCond.user_id;
|
|
localResult.hit_num = 0;
|
|
localResult.set_num = 0;
|
|
return writeGuest(result, &localResult, sizeof(localResult)) ? SAVE_DATA_OK : SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDirNameSearchPs4(const SaveDataDirNameSearchCond* cond, SaveDataDirNameSearchResult* result) {
|
|
std::int32_t traceUser = -1;
|
|
const int rc = dirNameSearchPs4(cond, result, &traceUser);
|
|
SAVEDATA_TRACE("dirNameSearchPs4 user=%d -> 0x%08x", traceUser, static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
static int convert(const SaveDataConvert* param, std::string* traceDir, int* traceUser) {
|
|
SaveDataConvert localConvert{};
|
|
if (param == nullptr || !GuestCopyIn_nid_no_patch(&localConvert, param, sizeof(localConvert))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (localConvert.dir_name == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
SceSaveDataDirName localDirName{};
|
|
if (!GuestCopyIn_nid_no_patch(&localDirName, localConvert.dir_name, sizeof(localDirName))) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
g_convertProgress = 0.0f;
|
|
std::string dirName;
|
|
if (!parse_dir_name(&localDirName, &dirName)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (traceDir != nullptr) *traceDir = dirName;
|
|
if (traceUser != nullptr) *traceUser = localConvert.user_id;
|
|
if (!path_is_directory(save_root() + "/" + dirName)) {
|
|
return SAVE_DATA_ERROR_NOT_FOUND;
|
|
}
|
|
g_convertProgress = 1.0f;
|
|
SaveDataEvent event{};
|
|
event.type = SAVE_DATA_EVENT_TYPE_CONVERT;
|
|
event.error_code = SAVE_DATA_OK;
|
|
event.user_id = localConvert.user_id;
|
|
event.dir_name = localDirName;
|
|
std::lock_guard lock(g_state_mutex);
|
|
g_events.push_back(event);
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataConvert(const SaveDataConvert* param) {
|
|
std::string dir = "(null)";
|
|
int user = -1;
|
|
const int rc = convert(param, &dir, &user);
|
|
SAVEDATA_TRACE("convert user=%d dir=%s -> 0x%08x", user, dir.c_str(), static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
static int getConvertProgress(float* progress) {
|
|
if (progress == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
const float current = g_convertProgress.load();
|
|
const int savedErrno = errno;
|
|
const bool copied = GuestCopyOut_nid_no_patch(progress, ¤t, sizeof(current));
|
|
errno = savedErrno;
|
|
if (!copied) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetConvertProgress(float* progress) {
|
|
const int rc = getConvertProgress(progress);
|
|
SAVEDATA_TRACE("getConvertProgress -> 0x%08x progress=%.2f", static_cast<unsigned>(rc), rc == SAVE_DATA_OK ? g_convertProgress.load() : 0.0f);
|
|
return rc;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCancel(std::uint32_t cancelArgument) {
|
|
(void)cancelArgument;
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDirNameSearch2(const SaveDataDirNameSearchCond* cond, SaveDataDirNameSearchResult* result) {
|
|
SearchTrace trace;
|
|
const int rc = dirNameSearch(cond, result, &trace);
|
|
SAVEDATA_TRACE("dirNameSearch2 user=%d pattern=%.*s hit=%u set=%u -> 0x%08x", trace.readable ? trace.user_id : -1, static_cast<int>(sizeof(SceSaveDataDirName::data)), trace.named ? trace.name.data : "(all)", trace.hit_num, trace.set_num, static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataPrepareForTransferring(const SaveDataMountPoint* mountPoint, const SaveDataPrepareParam* param) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCheckIpmiIfSize() {
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDebug() {
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDebugCheckBackupData() {
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDebugCleanMount() {
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDebugCompiledSdkVersion() {
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDebugCreateSaveDataRoot() {
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDebugProspero() {
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDebugRemoveSaveDataRoot() {
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDebugTarget() {
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataAbort() {
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataBindPsnAccount(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataBindPsnAccountForSystemBackup(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataChangeDatabase(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataChangeInternal(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
static int checkBackupData(const SaveDataCheckBackupData* check, std::string* traceDir) {
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
SaveDataCheckBackupData localCheck{};
|
|
if (!readGuest(check, localCheck) || localCheck.dir_name == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
std::string dirName;
|
|
if (!parse_dir_name(localCheck.dir_name, &dirName)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (traceDir != nullptr) *traceDir = dirName;
|
|
if (!running_title(localCheck.title_id)) {
|
|
return SAVE_DATA_ERROR_NOT_FOUND;
|
|
}
|
|
std::lock_guard lock(g_slots_mutex);
|
|
std::error_code error;
|
|
if (isMountedDirectory(save_root() + "/" + dirName, error)) {
|
|
return SAVE_DATA_ERROR_BUSY;
|
|
}
|
|
if (error) return SAVE_DATA_ERROR_INTERNAL;
|
|
return read_backup(dirName, localCheck.param);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCheckBackupData(const SaveDataCheckBackupData* check) {
|
|
std::string dir = "(null)";
|
|
const int rc = checkBackupData(check, &dir);
|
|
SAVEDATA_TRACE("checkBackupData dir=%s -> 0x%08x", dir.c_str(), static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCheckBackupDataForCdlg(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCheckBackupDataInternal(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCheckBackupDataLight(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCheckCloudData(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCheckSaveDataBroken(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCheckSaveDataVersion(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCheckSaveDataVersionLatest(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataClearProgress() {
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
g_backupProgress = 0.0f;
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCreateUploadData(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDebugGetThreadId(void) {
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDeleteAllUser(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDeleteBackupData(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDeleteCloudData(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDeleteProspero(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDeleteTitle(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDeleteUser(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDirNameSearchInternal(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataDownload(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
static bool save_tree_bytes(const std::string& path, std::uint64_t& bytes) {
|
|
bytes = 0;
|
|
std::error_code error;
|
|
std::filesystem::recursive_directory_iterator it(path, error);
|
|
const std::filesystem::recursive_directory_iterator end;
|
|
while (!error && it != end) {
|
|
const bool regular = it->is_regular_file(error);
|
|
if (error) return false;
|
|
if (regular) {
|
|
const auto size = it->file_size(error);
|
|
if (error) return false;
|
|
bytes += size;
|
|
}
|
|
it.increment(error);
|
|
}
|
|
return !error;
|
|
}
|
|
|
|
static bool save_root_is_directory(std::error_code& error) {
|
|
const bool exists = std::filesystem::is_directory(save_root(), error);
|
|
if (error == std::errc::no_such_file_or_directory) {
|
|
error.clear();
|
|
}
|
|
return exists;
|
|
}
|
|
|
|
static bool save_directory_paths(std::vector<std::filesystem::path>& paths) {
|
|
paths.clear();
|
|
std::error_code error;
|
|
if (!save_root_is_directory(error)) return !error;
|
|
std::filesystem::directory_iterator it(save_root(), error);
|
|
const std::filesystem::directory_iterator end;
|
|
while (!error && it != end) {
|
|
const bool directory = it->is_directory(error);
|
|
if (error) return false;
|
|
if (directory) paths.push_back(it->path());
|
|
it.increment(error);
|
|
}
|
|
return !error;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetAllSize(std::int32_t reserved, std::uint64_t* size) {
|
|
static_cast<void>(reserved);
|
|
if (g_initializations == 0) return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
if (size == nullptr) return SAVE_DATA_ERROR_PARAMETER;
|
|
std::uint64_t bytes = 0;
|
|
std::vector<std::filesystem::path> paths;
|
|
if (!save_directory_paths(paths)) return SAVE_DATA_ERROR_INTERNAL;
|
|
for (const auto& path : paths) {
|
|
std::uint64_t entryBytes = 0;
|
|
if (!save_tree_bytes(path.string(), entryBytes)) return SAVE_DATA_ERROR_INTERNAL;
|
|
bytes += entryBytes;
|
|
}
|
|
const std::uint64_t kib = (bytes + 1023) / 1024;
|
|
const int savedErrno = errno;
|
|
const bool written = GuestCopyOut_nid_no_patch(size, &kib, sizeof(kib));
|
|
errno = savedErrno;
|
|
return written ? SAVE_DATA_OK : SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetAppLaunchedUser(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetAutoUploadConditions(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetAutoUploadRequestInfo(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetAutoUploadSetting(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetBoundPsnAccountCount(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetClientThreadPriority(void) {
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetCloudQuotaInfo(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetEventInfo() {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetMountedSaveDataCount(std::int32_t reserved, std::uint32_t* count) {
|
|
if (g_initializations == 0) return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
if (count == nullptr) return SAVE_DATA_ERROR_PARAMETER;
|
|
if (reserved != 0) NotImplemented_nid_no_patch(__func__);
|
|
std::uint32_t mounted = 0;
|
|
{
|
|
std::lock_guard lock(g_slots_mutex);
|
|
for (const auto& slot : g_slots) {
|
|
if (slot.used) ++mounted;
|
|
}
|
|
}
|
|
const int savedErrno = errno;
|
|
const bool written = GuestCopyOut_nid_no_patch(count, &mounted, sizeof(mounted));
|
|
errno = savedErrno;
|
|
return written ? SAVE_DATA_OK : SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
|
|
static int getProgress(float* progress) {
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
if (progress == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
const float current = g_backupProgress.load();
|
|
const int savedErrno = errno;
|
|
const bool copied = GuestCopyOut_nid_no_patch(progress, ¤t, sizeof(current));
|
|
errno = savedErrno;
|
|
if (!copied) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetProgress(float* progress) {
|
|
const int rc = getProgress(progress);
|
|
SAVEDATA_TRACE("getProgress -> 0x%08x progress=%.2f", static_cast<unsigned>(rc), rc == SAVE_DATA_OK ? g_backupProgress.load() : 0.0f);
|
|
return rc;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetSaveDataCount(std::int32_t reserved, std::uint32_t* count) {
|
|
static_cast<void>(reserved);
|
|
if (g_initializations == 0) return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
if (count == nullptr) return SAVE_DATA_ERROR_PARAMETER;
|
|
std::uint32_t total = 0;
|
|
std::vector<std::filesystem::path> paths;
|
|
if (!save_directory_paths(paths)) return SAVE_DATA_ERROR_INTERNAL;
|
|
total = static_cast<std::uint32_t>(paths.size());
|
|
const int savedErrno = errno;
|
|
const bool written = GuestCopyOut_nid_no_patch(count, &total, sizeof(total));
|
|
errno = savedErrno;
|
|
return written ? SAVE_DATA_OK : SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetSaveDataRootDir(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetSaveDataRootPath(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetSaveDataRootUsbPath(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetSavePoint(void) {
|
|
return 2;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetUpdatedDataCount(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataInitialize2(const void* init) {
|
|
return sceSaveDataInitialize3(init);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataInitializeForCdlg(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataIsDeletingUsbDb(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataIsMounted() {
|
|
if (g_initializations == 0) return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataManualDelete(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataManualDownload(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataManualUpload(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataMount5() {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataMountInternal(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataMountSys(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataRebuildDatabase(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataRegisterEventCallback(SaveDataEventCallback callback, void* userdata) {
|
|
auto& callbacks = Callbacks();
|
|
std::lock_guard calling(callbacks.calling);
|
|
std::lock_guard slots(g_slots_mutex);
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
if (callback == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
StartEventDelivery();
|
|
std::lock_guard lock(callbacks.mutex);
|
|
callbacks.callback = callback;
|
|
callbacks.userdata = userdata;
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
static int restoreBackupData(const SaveDataRestoreBackupData* restore, std::string* traceDir) {
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
SaveDataRestoreBackupData localRestore{};
|
|
if (!readGuest(restore, localRestore) || localRestore.dir_name == nullptr) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
std::string dirName;
|
|
if (!parse_dir_name(localRestore.dir_name, &dirName)) {
|
|
return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
if (traceDir != nullptr) *traceDir = dirName;
|
|
if (!running_title(localRestore.title_id)) {
|
|
return SAVE_DATA_ERROR_NOT_FOUND;
|
|
}
|
|
const std::string target = save_root() + "/" + dirName;
|
|
std::lock_guard lock(g_slots_mutex);
|
|
std::error_code error;
|
|
if (isMountedDirectory(target, error)) {
|
|
return SAVE_DATA_ERROR_BUSY;
|
|
}
|
|
if (error) return SAVE_DATA_ERROR_INTERNAL;
|
|
const int backup = read_backup(dirName, nullptr);
|
|
if (backup != SAVE_DATA_OK) {
|
|
return backup;
|
|
}
|
|
try {
|
|
if (!path_is_directory(target)) {
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
restoreSave(dirName);
|
|
} catch (const std::filesystem::filesystem_error&) {
|
|
return SAVE_DATA_ERROR_INTERNAL;
|
|
}
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataRestoreBackupData(const SaveDataRestoreBackupData* restore) {
|
|
std::string dir = "(null)";
|
|
const int rc = restoreBackupData(restore, &dir);
|
|
SAVEDATA_TRACE("restoreBackupData dir=%s -> 0x%08x", dir.c_str(), static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataRestoreBackupDataForCdlg(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataRestoreLoadSaveDataMemory(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSetAutoUploadSetting(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSetEventInfo() {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSetSaveDataLibraryUser(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataShutdownStart(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSupportedFakeBrokenStatus(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSyncCloudList(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataUmountSys(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
static int umountWithBackup(const SaveDataMountPoint* mount_point, std::string* tracePoint) {
|
|
if (g_initializations == 0) {
|
|
return SAVE_DATA_ERROR_NOT_INITIALIZED;
|
|
}
|
|
return unmountMountPoint(mount_point, tracePoint, true);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataUmountWithBackup(const SaveDataMountPoint* mount_point) {
|
|
std::string point = "(null)";
|
|
const int rc = umountWithBackup(mount_point, &point);
|
|
SAVEDATA_TRACE("umountWithBackup point=%s -> 0x%08x", point.c_str(), static_cast<unsigned>(rc));
|
|
return rc;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataUnregisterEventCallback(void) {
|
|
auto& callbacks = Callbacks();
|
|
std::lock_guard calling(callbacks.calling);
|
|
std::lock_guard lock(callbacks.mutex);
|
|
callbacks.callback = nullptr;
|
|
callbacks.userdata = nullptr;
|
|
callbacks.pending.clear();
|
|
return SAVE_DATA_OK;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataUpload(void) {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
return 0;
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCheckPremiumMember() {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataCheckSyncStatus() {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetAllSizeProspero() {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetAutoSyncInfo() {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetCloudInfo() {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataNotifySaveDataDownload() {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSetAutoSyncSettings() {
|
|
NotImplemented_nid_no_patch(__func__);
|
|
}
|
|
|
|
}
|
|
|
|
namespace {
|
|
|
|
}
|
|
|
|
extern "C" {
|
|
|
|
int APS5_VABI sceSaveDataInitialize(const void* init) {
|
|
return sceSaveDataInitialize3(init);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataMount(const SaveDataMountPs4* mount, SaveDataMountResult* mount_result) {
|
|
if (mount == nullptr || mount_result == nullptr || mount->dir_name == nullptr) return SAVE_DATA_ERROR_PARAMETER;
|
|
if (mount->title_id != nullptr) NotImplemented_nid_no_patch("sceSaveDataMount of another title's save data");
|
|
SaveDataMount3 converted{};
|
|
converted.user_id = mount->user_id;
|
|
converted.dir_name = mount->dir_name;
|
|
converted.blocks = mount->blocks;
|
|
converted.mount_mode = mount->mount_mode;
|
|
return sceSaveDataMount3(&converted, mount_result);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataUmount(const SaveDataMountPoint* mount_point) {
|
|
return sceSaveDataUmount2(0, mount_point);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSetupSaveDataMemory(std::int32_t user_id, std::size_t memory_size, const SaveDataParam* param) {
|
|
if (param != nullptr) {
|
|
SaveDataParam localParam{};
|
|
const int savedErrno = errno;
|
|
const bool copied = GuestCopyIn_nid_no_patch(&localParam, param, sizeof(localParam));
|
|
errno = savedErrno;
|
|
if (!copied) return SAVE_DATA_ERROR_PARAMETER;
|
|
}
|
|
SaveDataMemorySetup2 setup{};
|
|
setup.user_id = user_id;
|
|
setup.memory_size = memory_size;
|
|
SaveDataMemorySetupResult result{};
|
|
if (const int rc = sceSaveDataSetupSaveDataMemory2(&setup, &result); rc != SAVE_DATA_OK) return rc;
|
|
if (param == nullptr) return SAVE_DATA_OK;
|
|
SaveDataMemorySet2 set{};
|
|
set.user_id = user_id;
|
|
set.param = param;
|
|
return sceSaveDataSetSaveDataMemory2(&set);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataGetSaveDataMemory(std::int32_t user_id, void* buf, std::size_t buf_size, std::int64_t offset) {
|
|
SaveDataMemoryData data{};
|
|
data.buf = buf;
|
|
data.buf_size = buf_size;
|
|
data.offset = static_cast<std::size_t>(offset);
|
|
SaveDataMemoryGet2 get{};
|
|
get.user_id = user_id;
|
|
get.data = &data;
|
|
return sceSaveDataGetSaveDataMemory2(&get);
|
|
}
|
|
|
|
int APS5_VABI sceSaveDataSetSaveDataMemory(std::int32_t user_id, void* buf, std::size_t buf_size, std::int64_t offset) {
|
|
SaveDataMemoryData data{};
|
|
data.buf = buf;
|
|
data.buf_size = buf_size;
|
|
data.offset = static_cast<std::size_t>(offset);
|
|
SaveDataMemorySet2 set{};
|
|
set.user_id = user_id;
|
|
set.data = &data;
|
|
set.data_num = 1;
|
|
return sceSaveDataSetSaveDataMemory2(&set);
|
|
}
|
|
|
|
}
|