From 8899219333e960bbf96fc681d87774c4fa75ab5e Mon Sep 17 00:00:00 2001 From: shen Date: Sat, 12 Sep 2026 14:08:33 +0800 Subject: [PATCH] feat: implement M5 reliable saves and recovery --- README.md | 4 +- app/build.gradle.kts | 4 +- app/src/main/cpp/CMakeLists.txt | 5 + app/src/main/cpp/core_session.cpp | 372 ++++++++++++++++-- app/src/main/cpp/core_session.h | 2 + app/src/main/cpp/jni_bridge.cpp | 7 + app/src/main/cpp/safe_commit.cpp | 144 +++++++ app/src/main/cpp/safe_commit.h | 31 ++ app/src/main/cpp/save_package.cpp | 131 ++++++ app/src/main/cpp/save_package.h | 29 ++ app/src/main/cpp/save_policy.cpp | 48 +++ app/src/main/cpp/save_policy.h | 26 ++ app/src/main/cpp/save_state.cpp | 140 +++++++ app/src/main/cpp/save_state.h | 41 ++ app/src/main/cpp/sha256.cpp | 85 ++++ app/src/main/cpp/sha256.h | 12 + app/src/main/cpp/tests/native_smoke_test.cpp | 93 +++++ app/src/main/cpp/video_buffer.cpp | 5 + app/src/main/cpp/video_buffer.h | 1 + .../main/java/org/neslite/app/MainActivity.kt | 168 +++++++- .../main/java/org/neslite/app/NativeBridge.kt | 2 + .../java/org/neslite/app/BuildIdentityTest.kt | 4 +- docs/architecture.md | 13 +- docs/identity.md | 2 +- docs/reports/m5-save-recovery.md | 29 ++ docs/save-format.md | 38 ++ 26 files changed, 1389 insertions(+), 47 deletions(-) create mode 100644 app/src/main/cpp/safe_commit.cpp create mode 100644 app/src/main/cpp/safe_commit.h create mode 100644 app/src/main/cpp/save_package.cpp create mode 100644 app/src/main/cpp/save_package.h create mode 100644 app/src/main/cpp/save_policy.cpp create mode 100644 app/src/main/cpp/save_policy.h create mode 100644 app/src/main/cpp/save_state.cpp create mode 100644 app/src/main/cpp/save_state.h create mode 100644 app/src/main/cpp/sha256.cpp create mode 100644 app/src/main/cpp/sha256.h create mode 100644 docs/reports/m5-save-recovery.md create mode 100644 docs/save-format.md diff --git a/README.md b/README.md index 9c17bfd..3213b7c 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # NESLite NESLite 是一个面向 Android 的轻量 NES/FC 模拟器前端。它使用固定版本的 -FCEUmm libretro 内核。当前仓库已完成 M4 的隔离实现和本地验证,包括通用手柄映射、自定义绑定、 -输入来源合成、死区、连发、暂停菜单和档案持久化;由于前序真机门槛尚未通过,M2~M4 的实机 +FCEUmm libretro 内核。当前仓库已完成 M5 的隔离实现和本地验证,包括通用手柄映射、可靠提交、 +十个手动槽、三个自动恢复点、异常恢复和不含 ROM 的存档包;由于前序真机门槛尚未通过,M2~M5 的实机 验收仍待补齐。 ## 快速构建 diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 504c2d7..3980577 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -21,8 +21,8 @@ android { applicationId = "org.neslite.app" minSdk = 28 targetSdk = 36 - versionCode = 4004 - versionName = "0.4.4" + versionCode = 5004 + versionName = "0.5.4" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" ndk { diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index dd7eb5a..1024659 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -12,6 +12,11 @@ set(NESLITE_COMMON_SOURCES linear_resampler.cpp timing_metrics.cpp video_buffer.cpp + sha256.cpp + safe_commit.cpp + save_state.cpp + save_policy.cpp + save_package.cpp ) function(neslite_enable_strict_warnings target) diff --git a/app/src/main/cpp/core_session.cpp b/app/src/main/cpp/core_session.cpp index 71dc0ff..5163553 100644 --- a/app/src/main/cpp/core_session.cpp +++ b/app/src/main/cpp/core_session.cpp @@ -23,6 +23,11 @@ #include "libretro.h" #include "audio_engine.h" #include "linear_resampler.h" +#include "safe_commit.h" +#include "save_package.h" +#include "save_policy.h" +#include "save_state.h" +#include "sha256.h" #include "session_rules.h" #include "timing_metrics.h" @@ -32,6 +37,29 @@ namespace { constexpr std::size_t kMaxCommands = 32; constexpr std::size_t kMaxRomBytes = 64U * 1024U * 1024U; constexpr std::size_t kAudioCapacityFrames = 4096; +constexpr std::string_view kCoreName = "FCEUmm"; +constexpr std::string_view kCoreCommit = "236ccdfc911e84c60fea6b9d0699c2d440a8de14"; +constexpr double kBatteryIntervalSeconds = 10.0; +constexpr double kAutoIntervalSeconds = 60.0; + +std::int64_t wall_now_ms() { + return std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); +} + +bool read_bounded_file(const std::filesystem::path& path, std::size_t maximum, + std::vector* output) { + if (output == nullptr) return false; + std::ifstream input(path, std::ios::binary); + if (!input) return false; + input.seekg(0, std::ios::end); + const auto length = input.tellg(); + if (length <= 0 || length > static_cast(maximum)) return false; + input.seekg(0, std::ios::beg); + output->resize(static_cast(length)); + input.read(reinterpret_cast(output->data()), length); + return input.good(); +} std::int64_t monotonic_now_ns() { return std::chrono::duration_cast( @@ -97,6 +125,13 @@ struct Host { std::atomic audio_target_frames{800}; double turbo_simulated_seconds = 0.0; std::uint16_t previous_turbo_mask = 0; + SafeCommitter committer; + SaveSchedule save_schedule{kBatteryIntervalSeconds, kAutoIntervalSeconds}; + std::uint64_t save_generation = 0; + std::size_t auto_generation = 0; + std::string committed_battery_hash; + std::atomic recovery_candidates{0}; + std::atomic abnormal_session{false}; Host() : worker([this] { run(); }) {} ~Host() { @@ -148,50 +183,270 @@ struct Host { return input.good(); } + std::string configuration_identity() const { + std::ostringstream identity; + for (const auto& [key, value] : variables) identity << key << '=' << value << '\n'; + return identity.str(); + } + + CommitResult commit_bytes(const std::filesystem::path& path, std::vector bytes) { + CommitResult result = CommitResult::IoError; + const std::uint64_t generation = ++save_generation; + std::thread file_thread([this, path, bytes = std::move(bytes), generation, &result] { + result = committer.commit(rom_hash, path, bytes, generation); + }); + file_thread.join(); + return result; + } + + std::vector battery_snapshot() const { + void* memory = retro_get_memory_data(RETRO_MEMORY_SAVE_RAM); + const std::size_t size = retro_get_memory_size(RETRO_MEMORY_SAVE_RAM); + if (memory == nullptr || size == 0 || rom_hash.empty()) return {}; + const auto* begin = static_cast(memory); + return {begin, begin + size}; + } + void load_battery() { void* memory = retro_get_memory_data(RETRO_MEMORY_SAVE_RAM); const std::size_t size = retro_get_memory_size(RETRO_MEMORY_SAVE_RAM); if (memory == nullptr || size == 0 || rom_hash.empty()) return; const auto path = std::filesystem::path(save_dir) / rom_hash / "battery" / "battery.sav"; - std::ifstream input(path, std::ios::binary); - if (!input) return; - input.read(static_cast(memory), static_cast(size)); + std::vector bytes; + if ((!read_bounded_file(path, size, &bytes) || bytes.size() != size) && + (!read_bounded_file(path.string() + ".bak", size, &bytes) || bytes.size() != size)) { + bytes.clear(); + } + if (!bytes.empty()) std::copy(bytes.begin(), bytes.end(), static_cast(memory)); + committed_battery_hash = sha256_hex(battery_snapshot()); } bool save_battery() { - void* memory = retro_get_memory_data(RETRO_MEMORY_SAVE_RAM); - const std::size_t size = retro_get_memory_size(RETRO_MEMORY_SAVE_RAM); - if (memory == nullptr || size == 0 || rom_hash.empty()) return false; - // Snapshot libretro-owned memory on the core thread; only the copy crosses to file I/O. - std::vector snapshot(size); - std::copy_n(static_cast(memory), size, snapshot.data()); + auto snapshot = battery_snapshot(); + if (snapshot.empty()) return false; + const std::string checksum = sha256_hex(snapshot); const auto final_path = std::filesystem::path(save_dir) / rom_hash / "battery" / "battery.sav"; - bool success = false; - std::thread file_thread([snapshot = std::move(snapshot), final_path, &success] { - std::error_code error_code; - std::filesystem::create_directories(final_path.parent_path(), error_code); - if (error_code) return; - const auto temp_path = final_path.string() + ".tmp"; - { - std::ofstream output(temp_path, std::ios::binary | std::ios::trunc); - output.write(reinterpret_cast(snapshot.data()), - static_cast(snapshot.size())); - if (!output.good()) { - output.close(); - std::filesystem::remove(temp_path, error_code); - return; + std::error_code exists_error; + if (checksum == committed_battery_hash && std::filesystem::is_regular_file(final_path, exists_error)) return false; + const bool success = commit_bytes(final_path, std::move(snapshot)) == CommitResult::Committed; + if (success) committed_battery_hash = checksum; + return success; + } + + SaveStateMetadata state_metadata(const VideoFrame& frame) const { + return SaveStateMetadata{ + .rom_hash = rom_hash, + .core_name = std::string(kCoreName), + .core_commit = std::string(kCoreCommit), + .configuration = configuration_identity(), + .created_epoch_ms = wall_now_ms(), + .thumbnail_width = frame.width, + .thumbnail_height = frame.height, + .thumbnail_pitch = frame.pitch, + .thumbnail_pixel_format = static_cast(frame.pixel_format), + }; + } + + std::vector serialized_state() const { + const std::size_t size = retro_serialize_size(); + if (size == 0 || size > kMaxStateBytes) return {}; + std::vector bytes(size); + if (!retro_serialize(bytes.data(), bytes.size())) return {}; + return bytes; + } + + bool save_state_to(const std::filesystem::path& path) { + const auto state_bytes = serialized_state(); + if (state_bytes.empty()) return false; + VideoFrame frame; + const bool has_frame = video.latest(&frame) && frame.bytes.size() <= kMaxThumbnailBytes; + const auto metadata = state_metadata(has_frame ? frame : VideoFrame{}); + std::span thumbnail; + if (has_frame) { + thumbnail = {reinterpret_cast(frame.bytes.data()), frame.bytes.size()}; + } + auto envelope = encode_save_state(metadata, state_bytes, thumbnail); + return !envelope.empty() && commit_bytes(path, std::move(envelope)) == CommitResult::Committed; + } + + bool save_manual_slot(unsigned slot) { + if (slot >= 10U) return false; + return save_state_to(std::filesystem::path(save_dir) / rom_hash / "states" / + ("slot-" + std::to_string(slot) + ".nls")); + } + + bool save_auto_point() { + const std::size_t slot = auto_slot_for_generation(auto_generation); + const bool saved = save_state_to(std::filesystem::path(save_dir) / rom_hash / "auto" / + ("auto-" + std::to_string(slot) + ".nls")); + if (saved) ++auto_generation; + return saved; + } + + bool read_valid_state(const std::filesystem::path& path, DecodedSaveState* decoded, + std::string* reason) const { + std::vector bytes; + if (!read_bounded_file(path, kMaxStateBytes + kMaxThumbnailBytes + 65536U, &bytes)) { + if (reason != nullptr) *reason = "missing"; + return false; + } + return decode_save_state(bytes, decoded, reason) && + save_state_compatible(decoded->metadata, rom_hash, std::string(kCoreName), + std::string(kCoreCommit), configuration_identity(), reason); + } + + unsigned count_recovery_candidates() const { + unsigned count = 0; + for (unsigned slot = 0; slot < 3U; ++slot) { + DecodedSaveState decoded; + std::string reason; + if (read_valid_state(std::filesystem::path(save_dir) / rom_hash / "auto" / + ("auto-" + std::to_string(slot) + ".nls"), &decoded, &reason)) ++count; + } + return count; + } + + bool write_session_marker(bool active) { + const std::string marker = std::string(active ? "active\n" : "closed\n") + + std::to_string(wall_now_ms()) + "\n"; + return commit_bytes(std::filesystem::path(save_dir) / rom_hash / "session.marker", + std::vector(marker.begin(), marker.end())) == CommitResult::Committed; + } + + bool previous_session_abnormal() const { + std::vector marker; + const auto path = std::filesystem::path(save_dir) / rom_hash / "session.marker"; + return read_bounded_file(path, 256U, &marker) && marker.size() >= 7U && + std::equal(marker.begin(), marker.begin() + 7, "active\n"); + } + + bool load_state_from(const std::filesystem::path& path) { + DecodedSaveState decoded; + std::string reason; + if (!read_valid_state(path, &decoded, &reason)) { + error = "State rejected: " + reason; + return false; + } + const auto before_state = serialized_state(); + const auto before_battery = battery_snapshot(); + if (before_state.empty() || before_battery.empty()) { + error = "Cannot protect current progress"; + return false; + } + VideoFrame empty_frame; + auto backup_envelope = encode_save_state(state_metadata(empty_frame), before_state, {}); + const auto root = std::filesystem::path(save_dir) / rom_hash / "recovery"; + if (commit_bytes(root / "before-load.nls", std::move(backup_envelope)) != CommitResult::Committed || + commit_bytes(root / "before-load.sav", before_battery) != CommitResult::Committed) { + error = "Cannot commit pre-load backup"; + return false; + } + audio.stop(); + audio_buffer.clear(); + resampler.reset(); + video.clear(); + if (!retro_unserialize(decoded.state.data(), decoded.state.size())) { + if (!retro_unserialize(before_state.data(), before_state.size())) { + retro_unload_game(); + loaded = false; + retro_game_info game{}; + game.path = rom_path.c_str(); + game.data = rom.data(); + game.size = rom.size(); + if (!retro_load_game(&game)) { + error = "State load and rollback failed; core is not runnable"; + set_state(SessionState::Error); + return false; + } + loaded = true; + void* memory = retro_get_memory_data(RETRO_MEMORY_SAVE_RAM); + const std::size_t memory_size = retro_get_memory_size(RETRO_MEMORY_SAVE_RAM); + if (memory == nullptr || memory_size != before_battery.size()) { + error = "Safe reload could not restore battery memory"; + set_state(SessionState::Error); + return false; + } + std::copy(before_battery.begin(), before_battery.end(), static_cast(memory)); + } + error = "State load failed; previous progress restored"; + timing.reset(monotonic_now_ns()); + set_state(SessionState::Paused); + return false; + } + timing.reset(monotonic_now_ns()); + set_state(SessionState::Paused); + error.clear(); + return true; + } + + bool export_package(const std::filesystem::path& destination) { + (void)save_battery(); + std::vector entries; + const auto root = std::filesystem::path(save_dir) / rom_hash; + const std::array candidates = { + "battery/battery.sav", "states/slot-0.nls", "states/slot-1.nls", "states/slot-2.nls", + "states/slot-3.nls", "states/slot-4.nls", "states/slot-5.nls", "states/slot-6.nls", + "states/slot-7.nls", "states/slot-8.nls", "states/slot-9.nls", "auto/auto-0.nls", + "auto/auto-1.nls", "auto/auto-2.nls", + }; + for (const auto& relative : candidates) { + std::vector bytes; + if (read_bounded_file(root / relative, kMaxPackageItemBytes, &bytes)) { + entries.push_back({relative, std::move(bytes)}); + } + } + auto package = encode_save_package(rom_hash, entries); + return !package.empty() && commit_bytes(destination, std::move(package)) == CommitResult::Committed; + } + + bool import_package(const std::filesystem::path& source) { + std::vector bytes; + if (!read_bounded_file(source, kMaxPackageTotalBytes + 4096U, &bytes)) { + error = "Import package cannot be read or is too large"; + return false; + } + DecodedSavePackage package; + std::string reason; + if (!decode_save_package(bytes, &package, &reason) || package.rom_hash != rom_hash) { + error = "Import package rejected: " + (reason.empty() ? std::string("rom_hash") : reason); + return false; + } + const std::size_t battery_size = retro_get_memory_size(RETRO_MEMORY_SAVE_RAM); + for (const auto& entry : package.entries) { + if (entry.path == "battery/battery.sav") { + if (entry.bytes.size() != battery_size) { + error = "Import package rejected: battery_size"; + return false; + } + } else { + DecodedSaveState decoded; + if (!decode_save_state(entry.bytes, &decoded, &reason) || + !save_state_compatible(decoded.metadata, rom_hash, std::string(kCoreName), + std::string(kCoreCommit), configuration_identity(), &reason)) { + error = "Import package rejected: " + reason; + return false; } } - std::filesystem::rename(temp_path, final_path, error_code); - if (error_code) { - std::filesystem::remove(final_path, error_code); - error_code.clear(); - std::filesystem::rename(temp_path, final_path, error_code); + } + const auto root = std::filesystem::path(save_dir) / rom_hash; + for (const auto& entry : package.entries) { + if (commit_bytes(root / entry.path, entry.bytes) != CommitResult::Committed) { + error = "Import package commit failed"; + return false; } - success = !error_code; - }); - file_thread.join(); - return success; + } + const auto battery = std::find_if(package.entries.begin(), package.entries.end(), + [](const SavePackageEntry& entry) { + return entry.path == "battery/battery.sav"; + }); + if (battery != package.entries.end()) { + void* memory = retro_get_memory_data(RETRO_MEMORY_SAVE_RAM); + std::copy(battery->bytes.begin(), battery->bytes.end(), static_cast(memory)); + committed_battery_hash = sha256_hex(battery->bytes); + } + recovery_candidates.store(count_recovery_candidates()); + error.clear(); + return true; } bool unload() { @@ -204,6 +459,8 @@ struct Host { bool battery_saved = false; if (loaded) { battery_saved = save_battery(); + (void)save_auto_point(); + (void)write_session_marker(false); retro_unload_game(); loaded = false; } @@ -217,6 +474,10 @@ struct Host { effective_joypad.store(0, std::memory_order_relaxed); turbo_simulated_seconds = 0.0; previous_turbo_mask = 0; + save_schedule.reset(); + committed_battery_hash.clear(); + recovery_candidates.store(0); + abnormal_session.store(false); return battery_saved; } @@ -283,6 +544,11 @@ struct Host { std::lround(static_cast(output_rate) / av.timing.fps), 128L, static_cast(kAudioCapacityFrames / 2U)))); load_battery(); + abnormal_session.store(previous_session_abnormal()); + recovery_candidates.store(abnormal_session.load() ? count_recovery_candidates() : 0U); + (void)write_session_marker(true); + save_schedule.reset(); + auto_generation = 0; const auto load_finished = monotonic_now_ns(); timing.reset(load_finished); timing.record_load(load_finished - load_started); @@ -370,8 +636,29 @@ struct Host { audio.stop(); timing.transition(TimingMode::Paused, monotonic_now_ns()); const bool battery_saved = save_battery(); + const bool auto_saved = save_auto_point(); set_state(SessionState::Paused); - complete(active_id, battery_saved ? "paused_saved" : "paused"); + complete(active_id, battery_saved || auto_saved ? "paused_saved" : "paused"); + } else if (command.name.starts_with("state_save:") && loaded && state == SessionState::Paused) { + const unsigned slot = static_cast(command.name.back() - '0'); + const bool saved = command.name.size() == 12U && save_manual_slot(slot); + complete(active_id, saved ? "state_saved" : "state_save_failed"); + } else if (command.name.starts_with("state_load:") && loaded && state == SessionState::Paused) { + const unsigned slot = static_cast(command.name.back() - '0'); + const bool loaded_state = command.name.size() == 12U && load_state_from( + std::filesystem::path(save_dir) / rom_hash / "states" / + ("slot-" + std::to_string(slot) + ".nls")); + complete(active_id, loaded_state ? "state_loaded" : "state_load_failed"); + } else if (command.name.starts_with("auto_load:") && loaded && state == SessionState::Paused) { + const unsigned slot = static_cast(command.name.back() - '0'); + const bool loaded_state = command.name.size() == 11U && slot < 3U && load_state_from( + std::filesystem::path(save_dir) / rom_hash / "auto" / + ("auto-" + std::to_string(slot) + ".nls")); + complete(active_id, loaded_state ? "auto_loaded" : "auto_load_failed"); + } else if (command.name == "package_export" && loaded && state == SessionState::Paused) { + complete(active_id, export_package(command.rom_path) ? "package_exported" : "package_export_failed"); + } else if (command.name == "package_import" && loaded && state == SessionState::Paused) { + complete(active_id, import_package(command.rom_path) ? "package_imported" : "package_import_failed"); } else if (command.name == "reset" && loaded && command_allowed(state.load(), command.name)) { audio_buffer.clear(); resampler.reset(); @@ -437,6 +724,9 @@ struct Host { previous_turbo_mask = requested_turbo; const auto work_started = clock::now(); retro_run(); + save_schedule.advance(1.0 / fps); + if (save_schedule.take_battery_due()) (void)save_battery(); + if (save_schedule.take_auto_due()) (void)save_auto_point(); if (requested_turbo != 0) turbo_simulated_seconds += 1.0 / fps; timing.record_frame(1.0 / fps, std::chrono::duration_cast( clock::now() - work_started).count()); @@ -592,14 +882,26 @@ std::uint64_t load_rom(const std::string& rom_path, } bool session_command(std::uint64_t session_id, const std::string& command) { + bool slot_command = false; + if ((command.starts_with("state_save:") || command.starts_with("state_load:")) && + command.size() == 12U) slot_command = command.back() >= '0' && command.back() <= '9'; + if (command.starts_with("auto_load:") && command.size() == 11U) { + slot_command = command.back() >= '0' && command.back() <= '2'; + } const bool known = command == "run" || command == "pause" || command == "reset" || command == "stop" || command == "mute:on" || command == "mute:off" || command == "audio_rebuild" || command == "fast:on" || command == "fast:off" || - command.starts_with("volume:"); + command.starts_with("volume:") || slot_command; if (!known) return false; return Host::instance().enqueue(Command{session_id, command, {}, {}, {}, {}}); } +bool save_package_command(std::uint64_t session_id, const std::string& command, + const std::string& path) { + if ((command != "package_export" && command != "package_import") || path.empty()) return false; + return Host::instance().enqueue(Command{session_id, command, path, {}, {}, {}}); +} + void set_joypad_mask(std::uint16_t mask) { Host::instance().joypad.store(mask, std::memory_order_relaxed); } @@ -621,6 +923,8 @@ std::string session_status_json() { << ",\"completion\":\"" << json_escape(host.completion) << "\",\"error\":\"" << json_escape(host.error) << "\",\"fastForward\":" << (host.fast_forward.load() ? "true" : "false") + << ",\"abnormalSession\":" << (host.abnormal_session.load() ? "true" : "false") + << ",\"recoveryCandidates\":" << host.recovery_candidates.load() << ",\"input\":{\"baseMask\":" << host.joypad.load(std::memory_order_relaxed) << ",\"turboMask\":" << host.turbo.load(std::memory_order_relaxed) << ",\"effectiveMask\":" << host.effective_joypad.load(std::memory_order_relaxed) << "}" diff --git a/app/src/main/cpp/core_session.h b/app/src/main/cpp/core_session.h index 270cedb..dfedd26 100644 --- a/app/src/main/cpp/core_session.h +++ b/app/src/main/cpp/core_session.h @@ -14,6 +14,8 @@ std::uint64_t load_rom(const std::string& rom_path, const std::string& save_dir, const std::string& rom_hash); bool session_command(std::uint64_t session_id, const std::string& command); +bool save_package_command(std::uint64_t session_id, const std::string& command, + const std::string& path); void set_joypad_mask(std::uint16_t mask); void set_turbo_mask(std::uint16_t mask); std::string session_status_json(); diff --git a/app/src/main/cpp/jni_bridge.cpp b/app/src/main/cpp/jni_bridge.cpp index 2c3daba..f3032be 100644 --- a/app/src/main/cpp/jni_bridge.cpp +++ b/app/src/main/cpp/jni_bridge.cpp @@ -55,6 +55,13 @@ Java_org_neslite_app_NativeBridge_command(JNIEnv* env, jclass, jlong session_id, return neslite::session_command(static_cast(session_id), from_jstring(env, command)); } +extern "C" JNIEXPORT jboolean JNICALL +Java_org_neslite_app_NativeBridge_savePackageCommand(JNIEnv* env, jclass, jlong session_id, + jstring command, jstring path) { + return neslite::save_package_command(static_cast(session_id), + from_jstring(env, command), from_jstring(env, path)); +} + extern "C" JNIEXPORT void JNICALL Java_org_neslite_app_NativeBridge_setJoypadMask(JNIEnv*, jclass, jint mask) { neslite::set_joypad_mask(static_cast(mask)); diff --git a/app/src/main/cpp/safe_commit.cpp b/app/src/main/cpp/safe_commit.cpp new file mode 100644 index 0000000..434c5b0 --- /dev/null +++ b/app/src/main/cpp/safe_commit.cpp @@ -0,0 +1,144 @@ +#include "safe_commit.h" + +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#else +#include +#include +#endif + +namespace neslite { +namespace { + +bool sync_file(std::FILE* file) { + if (std::fflush(file) != 0) return false; +#ifdef _WIN32 + return _commit(_fileno(file)) == 0; +#else + return fsync(fileno(file)) == 0; +#endif +} + +bool write_synced(const std::filesystem::path& path, std::span bytes) { +#ifdef _WIN32 + std::FILE* file = nullptr; + if (_wfopen_s(&file, path.c_str(), L"wb") != 0) file = nullptr; +#else + std::FILE* file = std::fopen(path.c_str(), "wb"); +#endif + if (file == nullptr) return false; + const bool written = bytes.empty() || std::fwrite(bytes.data(), 1U, bytes.size(), file) == bytes.size(); + const bool synced = written && sync_file(file); + const bool closed = std::fclose(file) == 0; + return synced && closed; +} + +bool read_exact(const std::filesystem::path& path, std::vector* output) { + if (output == nullptr) return false; + std::ifstream input(path, std::ios::binary); + if (!input) return false; + input.seekg(0, std::ios::end); + const auto length = input.tellg(); + if (length < 0) return false; + input.seekg(0, std::ios::beg); + output->resize(static_cast(length)); + if (!output->empty()) input.read(reinterpret_cast(output->data()), length); + return input.good() || input.eof(); +} + +bool verify_file(const std::filesystem::path& path, std::span expected) { + std::vector actual; + return read_exact(path, &actual) && actual.size() == expected.size() && + std::equal(actual.begin(), actual.end(), expected.begin(), expected.end()); +} + +bool atomic_replace(const std::filesystem::path& source, const std::filesystem::path& destination) { +#ifdef _WIN32 + return MoveFileExW(source.c_str(), destination.c_str(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0; +#else + return std::rename(source.c_str(), destination.c_str()) == 0; +#endif +} + +void sync_directory(const std::filesystem::path& path) { +#ifndef _WIN32 + const int descriptor = open(path.c_str(), O_RDONLY | O_DIRECTORY); + if (descriptor >= 0) { + (void)fsync(descriptor); + (void)close(descriptor); + } +#else + (void)path; +#endif +} + +} // namespace + +CommitResult SafeCommitter::commit(const std::string& rom_key, + const std::filesystem::path& destination, + std::span bytes, + std::uint64_t generation, + CommitOptions options) { + std::lock_guard lock(mutex_); + const std::string serial_key = rom_key + "\n" + destination.string(); + auto& newest = newest_generation_[serial_key]; + if (generation <= newest) return CommitResult::Superseded; + newest = generation; + + std::error_code error; + std::filesystem::create_directories(destination.parent_path(), error); + if (error) return CommitResult::IoError; + const auto temporary = std::filesystem::path(destination.string() + ".tmp." + std::to_string(generation)); + const auto backup = std::filesystem::path(destination.string() + ".bak"); + const auto backup_next = std::filesystem::path(destination.string() + ".bak.tmp." + std::to_string(generation)); + std::filesystem::remove(temporary, error); + error.clear(); + std::filesystem::remove(backup_next, error); + + if (!write_synced(temporary, bytes)) { + std::filesystem::remove(temporary, error); + return CommitResult::IoError; + } + if (!verify_file(temporary, bytes)) { + std::filesystem::remove(temporary, error); + return CommitResult::VerificationFailed; + } + if (std::filesystem::is_regular_file(destination, error)) { + std::vector previous; + if (!read_exact(destination, &previous) || !write_synced(backup_next, previous) || + !verify_file(backup_next, previous) || !atomic_replace(backup_next, backup)) { + std::filesystem::remove(temporary, error); + std::filesystem::remove(backup_next, error); + return CommitResult::IoError; + } + } + if (options.fail_before_replace) { + std::filesystem::remove(temporary, error); + return CommitResult::InjectedFailure; + } + if (!atomic_replace(temporary, destination)) { + std::filesystem::remove(temporary, error); + return CommitResult::IoError; + } + sync_directory(destination.parent_path()); + return verify_file(destination, bytes) ? CommitResult::Committed : CommitResult::VerificationFailed; +} + +const char* commit_result_name(CommitResult result) { + switch (result) { + case CommitResult::Committed: return "committed"; + case CommitResult::Superseded: return "superseded"; + case CommitResult::IoError: return "io_error"; + case CommitResult::VerificationFailed: return "verification_failed"; + case CommitResult::InjectedFailure: return "injected_failure"; + } + return "unknown"; +} + +} // namespace neslite diff --git a/app/src/main/cpp/safe_commit.h b/app/src/main/cpp/safe_commit.h new file mode 100644 index 0000000..8d70f26 --- /dev/null +++ b/app/src/main/cpp/safe_commit.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace neslite { + +enum class CommitResult { Committed, Superseded, IoError, VerificationFailed, InjectedFailure }; + +struct CommitOptions { + bool fail_before_replace = false; +}; + +class SafeCommitter { + public: + CommitResult commit(const std::string& rom_key, const std::filesystem::path& destination, + std::span bytes, std::uint64_t generation, + CommitOptions options = {}); + + private: + std::mutex mutex_; + std::unordered_map newest_generation_; +}; + +const char* commit_result_name(CommitResult result); + +} // namespace neslite diff --git a/app/src/main/cpp/save_package.cpp b/app/src/main/cpp/save_package.cpp new file mode 100644 index 0000000..872eeea --- /dev/null +++ b/app/src/main/cpp/save_package.cpp @@ -0,0 +1,131 @@ +#include "save_package.h" + +#include +#include +#include + +#include "sha256.h" + +namespace neslite { +namespace { + +constexpr std::array kMagic = {'N', 'E', 'S', 'L', 'P', 'K', '0', '1'}; +constexpr std::uint32_t kFormatVersion = 1; +constexpr std::size_t kMaxEntries = 16; + +void append_u32(std::vector* output, std::uint32_t value) { + for (unsigned shift = 0; shift < 32U; shift += 8U) output->push_back(static_cast(value >> shift)); +} + +void append_u64(std::vector* output, std::uint64_t value) { + for (unsigned shift = 0; shift < 64U; shift += 8U) output->push_back(static_cast(value >> shift)); +} + +bool read_u32(std::span input, std::size_t* cursor, std::uint32_t* value) { + if (*cursor > input.size() || input.size() - *cursor < 4U) return false; + *value = 0; + for (unsigned shift = 0; shift < 32U; shift += 8U) *value |= static_cast(input[(*cursor)++]) << shift; + return true; +} + +bool read_u64(std::span input, std::size_t* cursor, std::uint64_t* value) { + if (*cursor > input.size() || input.size() - *cursor < 8U) return false; + *value = 0; + for (unsigned shift = 0; shift < 64U; shift += 8U) *value |= static_cast(input[(*cursor)++]) << shift; + return true; +} + +bool fail(std::string* error, const char* message) { + if (error != nullptr) *error = message; + return false; +} + +} // namespace + +bool package_path_allowed(const std::string& path) { + if (path == "battery/battery.sav") return true; + if (path.size() == 17U && path.starts_with("states/slot-") && path[12] >= '0' && + path[12] <= '9' && path.substr(13) == ".nls") return true; + if (path.size() == 15U && path.starts_with("auto/auto-") && path[10] >= '0' && + path[10] <= '2' && path.substr(11) == ".nls") return true; + return false; +} + +std::vector encode_save_package(const std::string& rom_hash, + const std::vector& entries) { + if (rom_hash.size() != 64U || entries.empty() || entries.size() > kMaxEntries) return {}; + std::size_t total = 0; + for (const auto& entry : entries) { + if (!package_path_allowed(entry.path) || entry.bytes.empty() || + entry.bytes.size() > kMaxPackageItemBytes || total > kMaxPackageTotalBytes - entry.bytes.size()) return {}; + total += entry.bytes.size(); + } + std::vector output; + output.insert(output.end(), kMagic.begin(), kMagic.end()); + append_u32(&output, kFormatVersion); + append_u32(&output, static_cast(rom_hash.size())); + append_u32(&output, static_cast(entries.size())); + output.insert(output.end(), rom_hash.begin(), rom_hash.end()); + for (const auto& entry : entries) { + append_u32(&output, static_cast(entry.path.size())); + append_u64(&output, entry.bytes.size()); + const std::string checksum = sha256_hex(entry.bytes); + output.insert(output.end(), checksum.begin(), checksum.end()); + output.insert(output.end(), entry.path.begin(), entry.path.end()); + output.insert(output.end(), entry.bytes.begin(), entry.bytes.end()); + } + return output; +} + +bool decode_save_package(std::span bytes, DecodedSavePackage* package, + std::string* error) { + if (package == nullptr || bytes.size() < 20U || bytes.size() > kMaxPackageTotalBytes + 4096U) { + return fail(error, "package_size"); + } + if (!std::equal(kMagic.begin(), kMagic.end(), bytes.begin())) return fail(error, "magic"); + std::size_t cursor = kMagic.size(); + std::uint32_t version = 0; + std::uint32_t hash_length = 0; + std::uint32_t count = 0; + if (!read_u32(bytes, &cursor, &version) || !read_u32(bytes, &cursor, &hash_length) || + !read_u32(bytes, &cursor, &count)) return fail(error, "truncated"); + if (version != kFormatVersion) return fail(error, "format_version"); + if (hash_length != 64U || count == 0U || count > kMaxEntries || bytes.size() - cursor < hash_length) { + return fail(error, "metadata"); + } + DecodedSavePackage next; + next.rom_hash.assign(reinterpret_cast(bytes.data() + cursor), hash_length); + cursor += hash_length; + std::size_t total = 0; + for (std::uint32_t index = 0; index < count; ++index) { + std::uint32_t path_length = 0; + std::uint64_t data_length = 0; + if (!read_u32(bytes, &cursor, &path_length) || !read_u64(bytes, &cursor, &data_length) || + path_length == 0U || path_length > 128U || data_length == 0U || + data_length > kMaxPackageItemBytes || bytes.size() - cursor < 64U) return fail(error, "entry_header"); + const std::string checksum(reinterpret_cast(bytes.data() + cursor), 64U); + cursor += 64U; + if (bytes.size() - cursor < path_length) return fail(error, "truncated"); + SavePackageEntry entry; + entry.path.assign(reinterpret_cast(bytes.data() + cursor), path_length); + cursor += path_length; + if (!package_path_allowed(entry.path)) return fail(error, "entry_path"); + if (data_length > std::numeric_limits::max() || bytes.size() - cursor < data_length || + total > kMaxPackageTotalBytes - static_cast(data_length)) return fail(error, "entry_size"); + total += static_cast(data_length); + entry.bytes.assign(bytes.begin() + static_cast(cursor), + bytes.begin() + static_cast(cursor + data_length)); + cursor += static_cast(data_length); + if (sha256_hex(entry.bytes) != checksum) return fail(error, "entry_checksum"); + if (std::any_of(next.entries.begin(), next.entries.end(), [&](const SavePackageEntry& existing) { + return existing.path == entry.path; + })) return fail(error, "duplicate_path"); + next.entries.push_back(std::move(entry)); + } + if (cursor != bytes.size()) return fail(error, "trailing_bytes"); + *package = std::move(next); + if (error != nullptr) error->clear(); + return true; +} + +} // namespace neslite diff --git a/app/src/main/cpp/save_package.h b/app/src/main/cpp/save_package.h new file mode 100644 index 0000000..2d4ab6b --- /dev/null +++ b/app/src/main/cpp/save_package.h @@ -0,0 +1,29 @@ +#pragma once + +#include +#include +#include +#include + +namespace neslite { + +constexpr std::size_t kMaxPackageItemBytes = 64U * 1024U * 1024U; +constexpr std::size_t kMaxPackageTotalBytes = 128U * 1024U * 1024U; + +struct SavePackageEntry { + std::string path; + std::vector bytes; +}; + +struct DecodedSavePackage { + std::string rom_hash; + std::vector entries; +}; + +bool package_path_allowed(const std::string& path); +std::vector encode_save_package(const std::string& rom_hash, + const std::vector& entries); +bool decode_save_package(std::span bytes, DecodedSavePackage* package, + std::string* error); + +} // namespace neslite diff --git a/app/src/main/cpp/save_policy.cpp b/app/src/main/cpp/save_policy.cpp new file mode 100644 index 0000000..dea1154 --- /dev/null +++ b/app/src/main/cpp/save_policy.cpp @@ -0,0 +1,48 @@ +#include "save_policy.h" + +#include + +namespace neslite { + +SaveSchedule::SaveSchedule(double battery_interval_seconds, double auto_interval_seconds) + : battery_interval_(std::max(0.001, battery_interval_seconds)), + auto_interval_(std::max(0.001, auto_interval_seconds)) {} + +void SaveSchedule::reset() { + battery_elapsed_ = 0.0; + auto_elapsed_ = 0.0; + battery_due_ = false; + auto_due_ = false; +} + +void SaveSchedule::advance(double simulated_seconds) { + if (simulated_seconds <= 0.0) return; + battery_elapsed_ += simulated_seconds; + auto_elapsed_ += simulated_seconds; + if (battery_elapsed_ >= battery_interval_) { + battery_due_ = true; + battery_elapsed_ = 0.0; + } + if (auto_elapsed_ >= auto_interval_) { + auto_due_ = true; + auto_elapsed_ = 0.0; + } +} + +bool SaveSchedule::take_battery_due() { + const bool result = battery_due_; + battery_due_ = false; + return result; +} + +bool SaveSchedule::take_auto_due() { + const bool result = auto_due_; + auto_due_ = false; + return result; +} + +std::size_t auto_slot_for_generation(std::size_t generation) { + return generation % 3U; +} + +} // namespace neslite diff --git a/app/src/main/cpp/save_policy.h b/app/src/main/cpp/save_policy.h new file mode 100644 index 0000000..300694b --- /dev/null +++ b/app/src/main/cpp/save_policy.h @@ -0,0 +1,26 @@ +#pragma once + +#include + +namespace neslite { + +class SaveSchedule { + public: + SaveSchedule(double battery_interval_seconds, double auto_interval_seconds); + void reset(); + void advance(double simulated_seconds); + bool take_battery_due(); + bool take_auto_due(); + + private: + double battery_interval_; + double auto_interval_; + double battery_elapsed_ = 0.0; + double auto_elapsed_ = 0.0; + bool battery_due_ = false; + bool auto_due_ = false; +}; + +std::size_t auto_slot_for_generation(std::size_t generation); + +} // namespace neslite diff --git a/app/src/main/cpp/save_state.cpp b/app/src/main/cpp/save_state.cpp new file mode 100644 index 0000000..8ae05f0 --- /dev/null +++ b/app/src/main/cpp/save_state.cpp @@ -0,0 +1,140 @@ +#include "save_state.h" + +#include +#include + +#include "sha256.h" + +namespace neslite { +namespace { + +constexpr std::array kMagic = {'N', 'E', 'S', 'L', 'S', 'T', '0', '1'}; +constexpr std::size_t kFixedHeaderBytes = 8U + 4U * 9U + 8U * 3U + 64U; +constexpr std::uint32_t kMaxTextBytes = 16U * 1024U; + +void append_u32(std::vector* output, std::uint32_t value) { + for (unsigned shift = 0; shift < 32U; shift += 8U) output->push_back(static_cast(value >> shift)); +} + +void append_u64(std::vector* output, std::uint64_t value) { + for (unsigned shift = 0; shift < 64U; shift += 8U) output->push_back(static_cast(value >> shift)); +} + +bool read_u32(std::span input, std::size_t* cursor, std::uint32_t* value) { + if (*cursor > input.size() || input.size() - *cursor < 4U) return false; + *value = 0; + for (unsigned shift = 0; shift < 32U; shift += 8U) *value |= static_cast(input[(*cursor)++]) << shift; + return true; +} + +bool read_u64(std::span input, std::size_t* cursor, std::uint64_t* value) { + if (*cursor > input.size() || input.size() - *cursor < 8U) return false; + *value = 0; + for (unsigned shift = 0; shift < 64U; shift += 8U) *value |= static_cast(input[(*cursor)++]) << shift; + return true; +} + +void append_text(std::vector* output, const std::string& value) { + output->insert(output->end(), value.begin(), value.end()); +} + +bool read_text(std::span input, std::size_t* cursor, std::uint32_t length, + std::string* value) { + if (length > kMaxTextBytes || *cursor > input.size() || input.size() - *cursor < length) return false; + value->assign(reinterpret_cast(input.data() + *cursor), length); + *cursor += length; + return true; +} + +bool fail(std::string* error, const char* message) { + if (error != nullptr) *error = message; + return false; +} + +} // namespace + +std::vector encode_save_state(const SaveStateMetadata& metadata, + std::span state, + std::span thumbnail) { + if (state.empty() || state.size() > kMaxStateBytes || thumbnail.size() > kMaxThumbnailBytes || + metadata.rom_hash.size() > kMaxTextBytes || metadata.core_name.size() > kMaxTextBytes || + metadata.core_commit.size() > kMaxTextBytes || metadata.configuration.size() > kMaxTextBytes) return {}; + std::vector output; + output.reserve(kFixedHeaderBytes + metadata.rom_hash.size() + metadata.core_name.size() + + metadata.core_commit.size() + metadata.configuration.size() + state.size() + thumbnail.size()); + output.insert(output.end(), kMagic.begin(), kMagic.end()); + append_u32(&output, kSaveStateFormatVersion); + append_u32(&output, static_cast(metadata.rom_hash.size())); + append_u32(&output, static_cast(metadata.core_name.size())); + append_u32(&output, static_cast(metadata.core_commit.size())); + append_u32(&output, static_cast(metadata.configuration.size())); + append_u32(&output, metadata.thumbnail_width); + append_u32(&output, metadata.thumbnail_height); + append_u32(&output, metadata.thumbnail_pitch); + append_u32(&output, metadata.thumbnail_pixel_format); + append_u64(&output, static_cast(metadata.created_epoch_ms)); + append_u64(&output, state.size()); + append_u64(&output, thumbnail.size()); + append_text(&output, sha256_hex(state)); + append_text(&output, metadata.rom_hash); + append_text(&output, metadata.core_name); + append_text(&output, metadata.core_commit); + append_text(&output, metadata.configuration); + output.insert(output.end(), state.begin(), state.end()); + output.insert(output.end(), thumbnail.begin(), thumbnail.end()); + return output; +} + +bool decode_save_state(std::span encoded, DecodedSaveState* decoded, + std::string* error) { + if (decoded == nullptr || encoded.size() < kFixedHeaderBytes) return fail(error, "truncated"); + if (!std::equal(kMagic.begin(), kMagic.end(), encoded.begin())) return fail(error, "magic"); + std::size_t cursor = kMagic.size(); + std::array fields{}; + for (auto& field : fields) if (!read_u32(encoded, &cursor, &field)) return fail(error, "truncated"); + if (fields[0] != kSaveStateFormatVersion) return fail(error, "format_version"); + std::uint64_t created = 0; + std::uint64_t state_size = 0; + std::uint64_t thumbnail_size = 0; + if (!read_u64(encoded, &cursor, &created) || !read_u64(encoded, &cursor, &state_size) || + !read_u64(encoded, &cursor, &thumbnail_size)) return fail(error, "truncated"); + if (state_size == 0 || state_size > kMaxStateBytes || thumbnail_size > kMaxThumbnailBytes) { + return fail(error, "size_limit"); + } + std::string checksum; + if (!read_text(encoded, &cursor, 64U, &checksum)) return fail(error, "truncated"); + DecodedSaveState next; + if (!read_text(encoded, &cursor, fields[1], &next.metadata.rom_hash) || + !read_text(encoded, &cursor, fields[2], &next.metadata.core_name) || + !read_text(encoded, &cursor, fields[3], &next.metadata.core_commit) || + !read_text(encoded, &cursor, fields[4], &next.metadata.configuration)) return fail(error, "metadata_length"); + if (state_size > std::numeric_limits::max() || + thumbnail_size > std::numeric_limits::max() || cursor > encoded.size() || + encoded.size() - cursor != state_size + thumbnail_size) return fail(error, "payload_length"); + next.metadata.created_epoch_ms = static_cast(created); + next.metadata.thumbnail_width = fields[5]; + next.metadata.thumbnail_height = fields[6]; + next.metadata.thumbnail_pitch = fields[7]; + next.metadata.thumbnail_pixel_format = fields[8]; + next.state.assign(encoded.begin() + static_cast(cursor), + encoded.begin() + static_cast(cursor + state_size)); + cursor += static_cast(state_size); + next.thumbnail.assign(encoded.begin() + static_cast(cursor), encoded.end()); + if (sha256_hex(next.state) != checksum) return fail(error, "checksum"); + *decoded = std::move(next); + if (error != nullptr) error->clear(); + return true; +} + +bool save_state_compatible(const SaveStateMetadata& metadata, const std::string& rom_hash, + const std::string& core_name, const std::string& core_commit, + const std::string& configuration, std::string* error) { + if (metadata.rom_hash != rom_hash) return fail(error, "rom_hash"); + if (metadata.core_name != core_name) return fail(error, "core_name"); + if (metadata.core_commit != core_commit) return fail(error, "core_commit"); + if (metadata.configuration != configuration) return fail(error, "configuration"); + if (error != nullptr) error->clear(); + return true; +} + +} // namespace neslite diff --git a/app/src/main/cpp/save_state.h b/app/src/main/cpp/save_state.h new file mode 100644 index 0000000..991229a --- /dev/null +++ b/app/src/main/cpp/save_state.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include +#include + +namespace neslite { + +constexpr std::uint32_t kSaveStateFormatVersion = 1; +constexpr std::size_t kMaxStateBytes = 64U * 1024U * 1024U; +constexpr std::size_t kMaxThumbnailBytes = 2U * 1024U * 1024U; + +struct SaveStateMetadata { + std::string rom_hash; + std::string core_name; + std::string core_commit; + std::string configuration; + std::int64_t created_epoch_ms = 0; + std::uint32_t thumbnail_width = 0; + std::uint32_t thumbnail_height = 0; + std::uint32_t thumbnail_pitch = 0; + std::uint32_t thumbnail_pixel_format = 0; +}; + +struct DecodedSaveState { + SaveStateMetadata metadata; + std::vector state; + std::vector thumbnail; +}; + +std::vector encode_save_state(const SaveStateMetadata& metadata, + std::span state, + std::span thumbnail); +bool decode_save_state(std::span encoded, DecodedSaveState* decoded, + std::string* error); +bool save_state_compatible(const SaveStateMetadata& metadata, const std::string& rom_hash, + const std::string& core_name, const std::string& core_commit, + const std::string& configuration, std::string* error); + +} // namespace neslite diff --git a/app/src/main/cpp/sha256.cpp b/app/src/main/cpp/sha256.cpp new file mode 100644 index 0000000..a621671 --- /dev/null +++ b/app/src/main/cpp/sha256.cpp @@ -0,0 +1,85 @@ +#include "sha256.h" + +#include +#include +#include +#include + +namespace neslite { +namespace { + +constexpr std::array kRound = { + 0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U, 0x3956c25bU, 0x59f111f1U, + 0x923f82a4U, 0xab1c5ed5U, 0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U, + 0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U, 0xe49b69c1U, 0xefbe4786U, + 0x0fc19dc6U, 0x240ca1ccU, 0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU, + 0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U, 0xc6e00bf3U, 0xd5a79147U, + 0x06ca6351U, 0x14292967U, 0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U, + 0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U, 0xa2bfe8a1U, 0xa81a664bU, + 0xc24b8b70U, 0xc76c51a3U, 0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U, + 0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U, 0x391c0cb3U, 0x4ed8aa4aU, + 0x5b9cca4fU, 0x682e6ff3U, 0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U, + 0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U, +}; + +constexpr std::uint32_t rotate_right(std::uint32_t value, unsigned bits) { + return (value >> bits) | (value << (32U - bits)); +} + +} // namespace + +std::string sha256_hex(std::span bytes) { + std::vector padded(bytes.begin(), bytes.end()); + const std::uint64_t bit_length = static_cast(padded.size()) * 8U; + padded.push_back(0x80U); + while ((padded.size() % 64U) != 56U) padded.push_back(0U); + for (int shift = 56; shift >= 0; shift -= 8) { + padded.push_back(static_cast((bit_length >> shift) & 0xffU)); + } + + std::array hash = { + 0x6a09e667U, 0xbb67ae85U, 0x3c6ef372U, 0xa54ff53aU, + 0x510e527fU, 0x9b05688cU, 0x1f83d9abU, 0x5be0cd19U, + }; + for (std::size_t offset = 0; offset < padded.size(); offset += 64U) { + std::array words{}; + for (std::size_t index = 0; index < 16U; ++index) { + const std::size_t base = offset + index * 4U; + words[index] = (static_cast(padded[base]) << 24U) | + (static_cast(padded[base + 1U]) << 16U) | + (static_cast(padded[base + 2U]) << 8U) | padded[base + 3U]; + } + for (std::size_t index = 16; index < words.size(); ++index) { + const std::uint32_t s0 = rotate_right(words[index - 15U], 7U) ^ + rotate_right(words[index - 15U], 18U) ^ (words[index - 15U] >> 3U); + const std::uint32_t s1 = rotate_right(words[index - 2U], 17U) ^ + rotate_right(words[index - 2U], 19U) ^ (words[index - 2U] >> 10U); + words[index] = words[index - 16U] + s0 + words[index - 7U] + s1; + } + std::uint32_t a = hash[0]; + std::uint32_t b = hash[1]; + std::uint32_t c = hash[2]; + std::uint32_t d = hash[3]; + std::uint32_t e = hash[4]; + std::uint32_t f = hash[5]; + std::uint32_t g = hash[6]; + std::uint32_t h = hash[7]; + for (std::size_t index = 0; index < words.size(); ++index) { + const std::uint32_t choice = (e & f) ^ (~e & g); + const std::uint32_t majority = (a & b) ^ (a & c) ^ (b & c); + const std::uint32_t sigma0 = rotate_right(a, 2U) ^ rotate_right(a, 13U) ^ rotate_right(a, 22U); + const std::uint32_t sigma1 = rotate_right(e, 6U) ^ rotate_right(e, 11U) ^ rotate_right(e, 25U); + const std::uint32_t temporary1 = h + sigma1 + choice + kRound[index] + words[index]; + const std::uint32_t temporary2 = sigma0 + majority; + h = g; g = f; f = e; e = d + temporary1; d = c; c = b; b = a; a = temporary1 + temporary2; + } + hash[0] += a; hash[1] += b; hash[2] += c; hash[3] += d; + hash[4] += e; hash[5] += f; hash[6] += g; hash[7] += h; + } + std::ostringstream result; + result << std::hex << std::setfill('0'); + for (const auto word : hash) result << std::setw(8) << word; + return result.str(); +} + +} // namespace neslite diff --git a/app/src/main/cpp/sha256.h b/app/src/main/cpp/sha256.h new file mode 100644 index 0000000..cf784b9 --- /dev/null +++ b/app/src/main/cpp/sha256.h @@ -0,0 +1,12 @@ +#pragma once + +#include +#include +#include +#include + +namespace neslite { + +std::string sha256_hex(std::span bytes); + +} // namespace neslite diff --git a/app/src/main/cpp/tests/native_smoke_test.cpp b/app/src/main/cpp/tests/native_smoke_test.cpp index 12e77f9..0918769 100644 --- a/app/src/main/cpp/tests/native_smoke_test.cpp +++ b/app/src/main/cpp/tests/native_smoke_test.cpp @@ -4,8 +4,16 @@ #include "session_rules.h" #include "timing_metrics.h" #include "video_buffer.h" +#include "safe_commit.h" +#include "save_package.h" +#include "save_policy.h" +#include "save_state.h" +#include "sha256.h" #include +#include +#include +#include int main() { using neslite::SessionState; @@ -99,5 +107,90 @@ int main() { previous_pal = gate; } if (ntsc_pulses != 15 || pal_pulses != 15 || neslite::turbo_gate(-1.0)) return 40; + + const std::vector abc = {'a', 'b', 'c'}; + if (neslite::sha256_hex(abc) != "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad") return 41; + + const auto test_root = std::filesystem::current_path() / "neslite-save-tests"; + std::error_code file_error; + std::filesystem::remove_all(test_root, file_error); + std::filesystem::create_directories(test_root, file_error); + if (file_error) return 42; + neslite::SafeCommitter committer; + const auto destination = test_root / "rom" / "battery.sav"; + const std::vector first = {1, 2, 3}; + const std::vector second = {4, 5, 6, 7}; + const std::vector older = {9}; + if (committer.commit("rom", destination, first, 1) != neslite::CommitResult::Committed) return 43; + if (committer.commit("rom", destination, second, 2, {.fail_before_replace = true}) != + neslite::CommitResult::InjectedFailure) return 44; + std::ifstream preserved(destination, std::ios::binary); + const std::vector preserved_bytes((std::istreambuf_iterator(preserved)), {}); + if (preserved_bytes != first) return 45; + preserved.close(); + if (committer.commit("rom", destination, second, 3) != neslite::CommitResult::Committed) return 46; + if (committer.commit("rom", destination, older, 2) != neslite::CommitResult::Superseded) return 47; + std::ifstream current(destination, std::ios::binary); + const std::vector current_bytes((std::istreambuf_iterator(current)), {}); + if (current_bytes != second) return 48; + current.close(); + std::ifstream backup(destination.string() + ".bak", std::ios::binary); + const std::vector backup_bytes((std::istreambuf_iterator(backup)), {}); + if (backup_bytes != first) return 49; + backup.close(); + + neslite::SaveStateMetadata metadata{ + .rom_hash = std::string(64, 'a'), + .core_name = "FCEUmm", + .core_commit = "236ccdf", + .configuration = "region=auto", + .created_epoch_ms = 123456, + .thumbnail_width = 2, + .thumbnail_height = 1, + .thumbnail_pitch = 4, + .thumbnail_pixel_format = 2, + }; + const std::vector state = {10, 20, 30, 40}; + const std::vector thumbnail = {1, 2, 3, 4}; + const auto envelope = neslite::encode_save_state(metadata, state, thumbnail); + neslite::DecodedSaveState decoded; + std::string decode_error; + if (!neslite::decode_save_state(envelope, &decoded, &decode_error) || decoded.state != state || + decoded.thumbnail != thumbnail || decoded.metadata.created_epoch_ms != 123456) return 50; + auto truncated = envelope; + truncated.pop_back(); + if (neslite::decode_save_state(truncated, &decoded, &decode_error) || decode_error != "payload_length") return 51; + auto corrupted = envelope; + corrupted[corrupted.size() - thumbnail.size() - 1U] ^= 0xffU; + if (neslite::decode_save_state(corrupted, &decoded, &decode_error) || decode_error != "checksum") return 52; + if (!neslite::save_state_compatible(metadata, metadata.rom_hash, "FCEUmm", "236ccdf", "region=auto", &decode_error)) return 53; + if (neslite::save_state_compatible(metadata, std::string(64, 'b'), "FCEUmm", "236ccdf", "region=auto", &decode_error) || + decode_error != "rom_hash") return 54; + if (neslite::save_state_compatible(metadata, metadata.rom_hash, "FCEUmm", "other", "region=auto", &decode_error) || + decode_error != "core_commit") return 55; + + neslite::SaveSchedule schedule(10.0, 60.0); + schedule.advance(9.9); + if (schedule.take_battery_due() || schedule.take_auto_due()) return 56; + schedule.advance(0.1); + if (!schedule.take_battery_due() || schedule.take_battery_due()) return 57; + schedule.advance(50.0); + if (!schedule.take_battery_due() || !schedule.take_auto_due()) return 58; + if (neslite::auto_slot_for_generation(0) != 0 || neslite::auto_slot_for_generation(3) != 0 || + neslite::auto_slot_for_generation(4) != 1) return 59; + + const std::vector entries = { + {"battery/battery.sav", first}, {"states/slot-0.nls", envelope}, + }; + const auto package_bytes = neslite::encode_save_package(metadata.rom_hash, entries); + neslite::DecodedSavePackage decoded_package; + if (!neslite::decode_save_package(package_bytes, &decoded_package, &decode_error) || + decoded_package.entries.size() != 2U || decoded_package.entries[1].bytes != envelope) return 60; + if (neslite::package_path_allowed("../rom.nes") || neslite::package_path_allowed("states/slot-10.nls")) return 61; + auto bad_package = package_bytes; + bad_package.back() ^= 0xffU; + if (neslite::decode_save_package(bad_package, &decoded_package, &decode_error) || + decode_error != "entry_checksum") return 62; + std::filesystem::remove_all(test_root, file_error); return 0; } diff --git a/app/src/main/cpp/video_buffer.cpp b/app/src/main/cpp/video_buffer.cpp index 7736462..835679a 100644 --- a/app/src/main/cpp/video_buffer.cpp +++ b/app/src/main/cpp/video_buffer.cpp @@ -33,4 +33,9 @@ bool VideoBuffer::latest(VideoFrame* frame) const { return true; } +void VideoBuffer::clear() { + std::lock_guard lock(mutex_); + frame_ = {}; +} + } // namespace neslite diff --git a/app/src/main/cpp/video_buffer.h b/app/src/main/cpp/video_buffer.h index 0cc3844..dd6c458 100644 --- a/app/src/main/cpp/video_buffer.h +++ b/app/src/main/cpp/video_buffer.h @@ -21,6 +21,7 @@ class VideoBuffer { bool submit(const void* data, unsigned width, unsigned height, std::size_t source_pitch, unsigned bytes_per_pixel, int pixel_format); bool latest(VideoFrame* frame) const; + void clear(); private: mutable std::mutex mutex_; diff --git a/app/src/main/java/org/neslite/app/MainActivity.kt b/app/src/main/java/org/neslite/app/MainActivity.kt index 3baa591..17daae6 100644 --- a/app/src/main/java/org/neslite/app/MainActivity.kt +++ b/app/src/main/java/org/neslite/app/MainActivity.kt @@ -58,6 +58,7 @@ import org.neslite.app.input.InputSourceKind import org.neslite.app.input.ProfileOrigin import org.neslite.app.input.RoutedInputState import java.io.File +import java.io.FileOutputStream import java.text.SimpleDateFormat import java.util.Date import java.util.Locale @@ -102,6 +103,10 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { private var pendingBindingAction: GameAction? = null private var controllerSettingsMessage = "选择动作后按一个手柄键或推动一个轴。" private var settingsReturnToPause = false + private var lastCompletionId = 0L + private var recoveryPromptedSession = 0L + private var pendingSaveExportUri: Uri? = null + private var pendingSaveExportFile: File? = null private val audioFocusListener = AudioManager.OnAudioFocusChangeListener { focusChange -> if (focusChange != AudioManager.AUDIOFOCUS_GAIN) { @@ -124,6 +129,24 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { if (uri != null) importRom(uri) } + private val createSavePackage = registerForActivityResult( + ActivityResultContracts.CreateDocument("application/vnd.neslite.save"), + ) { uri -> + if (uri == null) { + emulatorStatus.text = "已取消导出存档包" + } else { + beginSavePackageExport(uri) + } + } + + private val openSavePackage = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri == null) { + emulatorStatus.text = "已取消导入存档包" + } else { + beginSavePackageImport(uri) + } + } + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) inputManager = getSystemService(Context.INPUT_SERVICE) as InputManager @@ -343,7 +366,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { setPadding(32, 32, 32, 48) addView(title(getString(R.string.diagnostics_title))) addView(body(getString(R.string.diagnostics_instructions))) - addView(section("M4 游戏库、完整手柄操作与音画")) + addView(section("M5 游戏库、可靠存档与音画")) addView( Button(context).apply { text = "从文件导入 iNES / NES 2.0 ROM" @@ -479,6 +502,44 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { text = "重置游戏" setOnClickListener { sendControlCommand("reset") } }) + addView(section("手动即时存档(10 槽)")) + repeat(10) { slot -> + addView( + LinearLayout(context).apply { + orientation = LinearLayout.HORIZONTAL + addView(Button(context).apply { + text = "保存 ${slot + 1}" + setOnClickListener { sendControlCommand("state_save:$slot") } + }) + addView(Button(context).apply { + text = "读取 ${slot + 1}" + setOnClickListener { sendControlCommand("state_load:$slot") } + }) + }, + ) + } + addView(section("自动恢复点(最近 3 份)")) + addView( + LinearLayout(context).apply { + orientation = LinearLayout.HORIZONTAL + repeat(3) { slot -> + addView(Button(context).apply { + text = "恢复 ${slot + 1}" + setOnClickListener { sendControlCommand("auto_load:$slot") } + }) + } + }, + ) + addView(Button(context).apply { + text = "导出存档包(不含 ROM)" + setOnClickListener { createSavePackage.launch("neslite-save-${System.currentTimeMillis()}.nsp") } + }) + addView(Button(context).apply { + text = "导入存档包" + setOnClickListener { + openSavePackage.launch(arrayOf("application/vnd.neslite.save", "application/octet-stream", "*/*")) + } + }) addView(Button(context).apply { text = "手柄设置" setOnClickListener { showControllerSettings(returnToPause = true) } @@ -917,6 +978,83 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { emulatorStatus.text = if (activeSessionId == 0L) "命令队列已满" else "正在加载会话 $activeSessionId" } + private fun beginSavePackageExport(uri: Uri) { + if (activeSessionId == 0L || lastSessionState != "Paused") { + emulatorStatus.text = "请先加载游戏并暂停,再导出存档包" + return + } + val temporary = File(cacheDir, "save-export-$activeSessionId.nsp") + temporary.delete() + File(temporary.absolutePath + ".bak").delete() + pendingSaveExportUri = uri + pendingSaveExportFile = temporary + if (!NativeBridge.savePackageCommand(activeSessionId, "package_export", temporary.absolutePath)) { + pendingSaveExportUri = null + pendingSaveExportFile = null + emulatorStatus.text = "存档导出命令队列已满" + } else { + emulatorStatus.text = "正在准备不含 ROM 的存档包" + } + } + + private fun finishSavePackageExport() { + val uri = pendingSaveExportUri ?: return + val source = pendingSaveExportFile ?: return + pendingSaveExportUri = null + pendingSaveExportFile = null + libraryExecutor.execute { + val result = runCatching { + require(source.isFile && source.length() in 1..MAX_SAVE_PACKAGE_BYTES) + contentResolver.openOutputStream(uri, "w")!!.use { output -> + source.inputStream().use { input -> input.copyTo(output) } + output.flush() + } + } + source.delete() + File(source.absolutePath + ".bak").delete() + runOnUiThread { + emulatorStatus.text = if (result.isSuccess) "存档包导出成功(不含 ROM)" else + "存档包导出失败:${result.exceptionOrNull()?.message ?: "无法写入目标"}" + } + } + } + + private fun beginSavePackageImport(uri: Uri) { + if (activeSessionId == 0L || lastSessionState != "Paused") { + emulatorStatus.text = "请先加载对应游戏并暂停,再导入存档包" + return + } + val target = File(cacheDir, "save-import-$activeSessionId.nsp") + target.delete() + libraryExecutor.execute { + val result = runCatching { + contentResolver.openInputStream(uri)!!.use { input -> + FileOutputStream(target).use { output -> + val buffer = ByteArray(DEFAULT_BUFFER_SIZE) + var total = 0L + while (true) { + val read = input.read(buffer) + if (read < 0) break + total += read + require(total <= MAX_SAVE_PACKAGE_BYTES) { "存档包超过 128 MiB" } + output.write(buffer, 0, read) + } + output.fd.sync() + } + } + require(target.length() > 0L) { "存档包为空" } + require(NativeBridge.savePackageCommand(activeSessionId, "package_import", target.absolutePath)) { + "存档导入命令队列已满" + } + } + if (result.isFailure) target.delete() + runOnUiThread { + emulatorStatus.text = if (result.isSuccess) "正在校验并导入存档包" else + "存档包导入失败:${result.exceptionOrNull()?.message ?: "无法读取来源"}" + } + } + } + private fun pollSessionStatus() { if (::emulatorStatus.isInitialized && activeSessionId != 0L) { val raw = NativeBridge.sessionStatus() @@ -924,8 +1062,33 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { val nextState = status.optString("state") if (lastSessionState == "Running" && nextState != "Running") clearControllerState() lastSessionState = nextState - emulatorStatus.text = "状态:$nextState · ${status.optString("completion")}" + + val completionId = status.optLong("completionId") + val completion = status.optString("completion") + emulatorStatus.text = "状态:$nextState · $completion" + if (status.optBoolean("fastForward")) " · 2×" else "" + if (completionId != lastCompletionId) { + lastCompletionId = completionId + if (completion.endsWith(":package_exported")) finishSavePackageExport() + if (completion.endsWith(":package_export_failed")) { + pendingSaveExportUri = null + pendingSaveExportFile?.delete() + pendingSaveExportFile = null + } + if (completion.endsWith(":package_imported") || completion.endsWith(":package_import_failed")) { + File(cacheDir, "save-import-$activeSessionId.nsp").delete() + } + } + val candidateCount = status.optInt("recoveryCandidates") + if (status.optBoolean("abnormalSession") && candidateCount > 0 && + recoveryPromptedSession != activeSessionId && nextState == "Paused") { + recoveryPromptedSession = activeSessionId + showPauseMenu() + AlertDialog.Builder(this) + .setTitle("发现异常结束的会话") + .setMessage("已找到 $candidateCount 个校验有效的自动恢复点。不会自动运行游戏,请在暂停菜单中选择恢复点。") + .setPositiveButton("查看恢复点", null) + .show() + } val audio = status.optJSONObject("audio") ?: JSONObject() val timing = status.optJSONObject("timing") ?: JSONObject() audioStatus.text = "音频:${audio.optString("mode")},核心/设备 ${audio.optInt("coreRate")}/${audio.optInt("deviceRate")} Hz\n" + @@ -1126,5 +1289,6 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener { companion object { private const val EVENT_LINES = 30 private const val STATE_SESSION_ID = "active_session_id" + private const val MAX_SAVE_PACKAGE_BYTES = 128L * 1024L * 1024L } } diff --git a/app/src/main/java/org/neslite/app/NativeBridge.kt b/app/src/main/java/org/neslite/app/NativeBridge.kt index 7320867..d591d7c 100644 --- a/app/src/main/java/org/neslite/app/NativeBridge.kt +++ b/app/src/main/java/org/neslite/app/NativeBridge.kt @@ -16,6 +16,8 @@ object NativeBridge { external fun command(sessionId: Long, command: String): Boolean + external fun savePackageCommand(sessionId: Long, command: String, path: String): Boolean + external fun setJoypadMask(mask: Int) external fun setTurboMask(mask: Int) diff --git a/app/src/test/java/org/neslite/app/BuildIdentityTest.kt b/app/src/test/java/org/neslite/app/BuildIdentityTest.kt index 932a08c..15e6a87 100644 --- a/app/src/test/java/org/neslite/app/BuildIdentityTest.kt +++ b/app/src/test/java/org/neslite/app/BuildIdentityTest.kt @@ -7,7 +7,7 @@ class BuildIdentityTest { @Test fun debugBuildUsesTheDocumentedIdentity() { assertEquals("org.neslite.app.debug", BuildConfig.APPLICATION_ID) - assertEquals("0.4.4-debug", BuildConfig.VERSION_NAME) - assertEquals(4004, BuildConfig.VERSION_CODE) + assertEquals("0.5.4-debug", BuildConfig.VERSION_NAME) + assertEquals(5004, BuildConfig.VERSION_CODE) } } diff --git a/docs/architecture.md b/docs/architecture.md index 8bb627f..1bcab92 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,4 +1,4 @@ -# NESLite 架构(M4 基线) +# NESLite 架构(M5 基线) ## 边界与线程 @@ -82,6 +82,11 @@ M4 输入层按物理来源维护状态,来源键包含本次设备 ID、按 非运行态不消费方向导航,手柄 B 可从设置返回、从暂停菜单继续。失焦、暂停、断柄和退出同步清除 来源、轴滞回、基础掩码及连发掩码。 -电池存档按 ROM 哈希隔离为 `files/saves//battery/battery.sav`。暂停和正常退出时在内核线程 -取得保存内存并以临时文件替换提交,状态通知用 `paused_saved`/`stopped_saved` 报告成功。更完整的 -备份、故障注入和恢复保证属于 M5,不在此处提前声明。 +存档按 ROM 哈希隔离。核心线程在帧边界取得不可变电池/核心状态/缩略图快照,统一提交器在文件线程 +以同目录临时文件、刷新、回读校验、有效备份和原子替换提交,并用单调版本阻止旧任务倒灌。变化电池 +每 10 个模拟秒请求,自动恢复点每 60 秒及暂停/退出请求,手动十槽和自动三槽共用带哈希、固定内核 +提交、配置、时间、长度和 SHA-256 的 v1 封装,详见 `docs/save-format.md`。 + +读档只在暂停态核心线程进行并先持久保护当前状态和电池,失败回滚,双重失败安全重载或进入 Error。 +活动会话标记只提示校验有效的异常恢复候选,不自动运行。SAF 存档包只允许电池、手动槽和自动槽, +不含 ROM;原生层在写入前完成路径、单项/总大小、格式、哈希、内核提交、配置和每项校验。 diff --git a/docs/identity.md b/docs/identity.md index 2cf0a52..fee040f 100644 --- a/docs/identity.md +++ b/docs/identity.md @@ -6,7 +6,7 @@ | --- | --- | | 显示名称 | `NESLite` | | 正式 application ID/namespace | `org.neslite.app` | -| 当前开发版本 | `0.4.4`,`versionCode = 4004` | +| 当前开发版本 | `0.5.4`,`versionCode = 5004` | | 调试 application ID | `org.neslite.app.debug` | | 发布 ABI | `arm64-v8a` | | min/target SDK | 28/36 | diff --git a/docs/reports/m5-save-recovery.md b/docs/reports/m5-save-recovery.md new file mode 100644 index 0000000..c9c0347 --- /dev/null +++ b/docs/reports/m5-save-recovery.md @@ -0,0 +1,29 @@ +# M5 可靠存档与恢复记录 + +日期:2026-09-12 +构建目标:`org.neslite.app.debug`,`0.5.4-debug`,versionCode 5004,arm64-v8a + +## 已实现 + +- 同目录临时文件、持久化刷新、回读校验、有效 `.bak`、原子替换、单调版本拒绝旧任务;核心线程只 + 取得不可变快照,文件操作在独立线程完成并按 ROM/目标串行。 +- 电池内存按 SHA-256 检测变化,初始周期 10 个模拟秒;自动即时恢复点周期 60 个模拟秒且最多三份; + 暂停和退出补充请求,失败不推进自动槽轮换。 +- 十个手动槽和三个自动槽使用带 ROM、内核、固定提交、配置、时间、长度、状态 SHA-256 及同帧 + 缩略图的 v1 封装。暂停菜单可保存、读取和选择恢复点。 +- 活动/正常结束标记可发现上次异常会话,只提示有效候选且不自动运行。读档前持久保护当前状态和 + 电池;拒绝不匹配文件,反序列化失败回滚,双重失败安全重载或进入不可运行 Error。 +- Android SAF 导入/导出白名单存档包,默认不含 ROM;限制路径、重复项、格式、单项 64 MiB 和总计 + 128 MiB,所有项先校验后通过同一提交器写入。 + +## 自动验证 + +Windows 原生测试覆盖 SHA-256 标准向量、安全提交首次成功、替换前故障保持旧文件、有效备份、乱序 +旧版本拒绝;状态封装往返、截断、载荷校验错、ROM/内核提交不匹配;可控时钟的 10 秒/60 秒触发 +和三槽轮换;存档包往返、路径穿越拒绝及校验错。 + +## 待真机验收 + +用户当前不连接手机,且 G1~G4 尚未通过。首次/覆盖槽位、SAF 成功与取消、异常进程终止、内核 +反序列化失败/双重失败、实机帧时间,以及 H-SAVE 的十槽共 100 次循环和全手柄路径均未执行。 +因此 `todo.md` 的 M5 实现项和 G5 不勾选,10 秒/60 秒仍是初始值而非实测冻结值。 diff --git a/docs/save-format.md b/docs/save-format.md new file mode 100644 index 0000000..984dadc --- /dev/null +++ b/docs/save-format.md @@ -0,0 +1,38 @@ +# NESLite 存档格式 v1 + +M5 固定两种二进制格式:即时存档 `.nls`(魔数 `NESLST01`)和独立存档包 `.nsp`(魔数 +`NESLPK01`)。所有多字节整数均为无符号小端;时间为 Unix epoch 毫秒。格式解析先检查固定头、版本、 +长度上限和精确总长,再分配载荷。 + +## 即时存档 `.nls` + +固定头依次包含格式版本、ROM 哈希/内核名/内核提交/配置文本的长度,缩略图宽、高、行距和 +像素格式,创建时间、状态长度、缩略图长度,以及 64 字节小写十六进制状态 SHA-256。随后依次保存 +四段 UTF-8 元数据、核心状态和与该状态在同一帧边界取得的原始缩略图。 + +- 状态最大 64 MiB,缩略图最大 2 MiB,单段文本最大 16 KiB。 +- 读档必须匹配完整 ROM SHA-256、`FCEUmm`、固定内核提交和当前核心配置;不同内核提交默认拒绝, + 原文件不改名、不删除。 +- 手动槽为 `states/slot-0.nls` 至 `slot-9.nls`;自动恢复点为 `auto/auto-0.nls` 至 + `auto-2.nls`,仅在新文件提交成功后推进轮换。 + +## 独立存档包 `.nsp` + +包头保存格式版本、64 字节 ROM SHA-256 和条目数。每项保存相对路径长度、数据长度、64 字节数据 +SHA-256、路径和数据。只允许 `battery/battery.sav`、十个手动槽和三个自动槽;拒绝绝对路径、父目录、 +重复路径及任何未列入白名单的名称。单项上限 64 MiB,总数据上限 128 MiB,最多 16 项。包不包含 ROM、 +会话标记或读档前保护副本。 + +## 提交、备份与恢复 + +所有文件使用同一安全提交器:不可变快照在文件线程写入目标同目录的带版本临时文件,刷新到存储后 +逐字节回读校验;已有目标先以同样流程生成 `.bak`,再原子替换正式文件并同步目录。提交器按 ROM/ +目标串行,并拒绝不大于已接收版本的旧任务。替换前失败会清除临时文件,正式文件和有效备份不变。 + +读档只允许在暂停态的核心线程执行。反序列化前把当前核心状态和电池内存提交到 `recovery/`;失败先 +恢复内存快照,回滚也失败则重新载入当前 ROM 并恢复保护的电池内存,无法确定核心状态时进入 Error, +不可继续运行。成功或回滚后均清空旧音视频并重建时钟基线。 + +电池内容变化后每 10 个模拟秒请求提交;自动恢复点每 60 个模拟秒请求,暂停和正常退出额外请求。 +无变化的电池不重复写入,只有正式文件提交成功才报告保存成功。`session.marker` 区分活动/正常关闭; +再次启动发现活动标记时仅列出校验有效的恢复候选,不自动运行。