Compare commits

..

1 Commits

Author SHA1 Message Date
xbzk aa0878b636 [core, *] support bundled application program IDs 2026-08-29 12:39:26 -03:00
183 changed files with 1220 additions and 1165 deletions
@@ -0,0 +1,26 @@
From b3622608433c183ba868a1dc8dd9cf285eb3b916 Mon Sep 17 00:00:00 2001
From: Dario Petrillo <dario.pk1@gmail.com>
Date: Thu, 27 Nov 2025 23:12:38 +0100
Subject: [PATCH] avoid extra memset when clearing an empty table
---
include/ankerl/unordered_dense.h | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/include/ankerl/unordered_dense.h b/include/ankerl/unordered_dense.h
index 0835342..4938212 100644
--- a/include/ankerl/unordered_dense.h
+++ b/include/ankerl/unordered_dense.h
@@ -1490,8 +1490,10 @@ class table : public std::conditional_t<is_map_v<T>, base_table_type_map<T>, bas
// modifiers //////////////////////////////////////////////////////////////
void clear() {
- m_values.clear();
- clear_buckets();
+ if (!empty()) {
+ m_values.clear();
+ clear_buckets();
+ }
}
auto insert(value_type const& value) -> std::pair<iterator, bool> {
+1
View File
@@ -540,6 +540,7 @@ add_subdirectory(externals)
# pass targets from externals # pass targets from externals
# TODO(crueter): CPMUtil Propagate func? # TODO(crueter): CPMUtil Propagate func?
find_package(enet) find_package(enet)
find_package(unordered_dense REQUIRED)
if (ARCHITECTURE_x86 OR ARCHITECTURE_x86_64) if (ARCHITECTURE_x86 OR ARCHITECTURE_x86_64)
find_package(xbyak) find_package(xbyak)
+13 -2
View File
@@ -301,6 +301,17 @@
"repo": "eden-emu/tzdb_to_nx", "repo": "eden-emu/tzdb_to_nx",
"version": "230326" "version": "230326"
}, },
"unordered-dense": {
"bundled": true,
"find_args": "CONFIG",
"hash": "d2106f6640f6bfb81755e4b8bfb64982e46ec4a507cacdb38f940123212ccf35a20b43c70c6f01d7bfb8c246d1a16f7845d8052971949cea9def1475e3fa02c8",
"package": "unordered_dense",
"patches": [
"0001-avoid-memset-when-clearing-an-empty-table.patch"
],
"repo": "martinus/unordered_dense",
"version": "7b55cab841"
},
"vulkan-headers": { "vulkan-headers": {
"hash": "d2846ea228415772645eea4b52a9efd33e6a563043dd3de059e798be6391a8f0ca089f455ae420ff22574939ed0f48ed7c6ff3d5a9987d5231dbf3b3f89b484b", "hash": "d2846ea228415772645eea4b52a9efd33e6a563043dd3de059e798be6391a8f0ca089f455ae420ff22574939ed0f48ed7c6ff3d5a9987d5231dbf3b3f89b484b",
"min_version": "1.4.317", "min_version": "1.4.317",
@@ -329,10 +340,10 @@
"version": "vulkan-sdk-%NUMERIC_VERSION%" "version": "vulkan-sdk-%NUMERIC_VERSION%"
}, },
"xbyak": { "xbyak": {
"hash": "e0aa0a603dd3ac1a39d82213df1e73c042831aec2d6b2fe382c899651eaae4ed7e8aeb6be9c41ea0097087c9d091961ab18f313cd6a9e10d621715ffd49bfe36", "hash": "b6475276b2faaeb315734ea8f4f8bd87ededcee768961b39679bee547e7f3e98884d8b7851e176d861dab30a80a76e6ea302f8c111483607dde969b4797ea95a",
"package": "xbyak", "package": "xbyak",
"repo": "herumi/xbyak", "repo": "herumi/xbyak",
"version": "v7.40.1" "version": "v7.35.2"
}, },
"zlib": { "zlib": {
"hash": "16fea4df307a68cf0035858abe2fd550250618a97590e202037acd18a666f57afc10f8836cbbd472d54a0e76539d0e558cb26f059d53de52ff90634bbf4f47d4", "hash": "16fea4df307a68cf0035858abe2fd550250618a97590e202037acd18a666f57afc10f8836cbbd472d54a0e76539d0e558cb26f059d53de52ff90634bbf4f47d4",
-2
View File
@@ -509,8 +509,6 @@ QWidget#contentRichDialog QLabel#label_title_rich {
} }
QWidget#contentDialog QLabel#label_dialog { QWidget#contentDialog QLabel#label_dialog {
background: #2E2E2E;
padding: 20px 65px; padding: 20px 65px;
} }
+5 -4
View File
@@ -80,6 +80,7 @@ Certain other dependencies will be fetched by CPM regardless. System packages *c
* [httplib](https://github.com/yhirose/cpp-httplib) - if `ENABLE_UPDATE_CHECKER` or `ENABLE_WEB_SERVICE` are on * [httplib](https://github.com/yhirose/cpp-httplib) - if `ENABLE_UPDATE_CHECKER` or `ENABLE_WEB_SERVICE` are on
* This package is known to be broken on the AUR. * This package is known to be broken on the AUR.
* [cpp-jwt](https://github.com/arun11299/cpp-jwt) 1.4+ - if `ENABLE_WEB_SERVICE` is on * [cpp-jwt](https://github.com/arun11299/cpp-jwt) 1.4+ - if `ENABLE_WEB_SERVICE` is on
* [unordered-dense](https://github.com/martinus/unordered_dense)
On amd64: On amd64:
@@ -118,7 +119,7 @@ Now, install all deps:
sudo emerge -a \ sudo emerge -a \
app-arch/lz4 app-arch/zstd app-arch/unzip \ app-arch/lz4 app-arch/zstd app-arch/unzip \
dev-libs/libfmt dev-libs/libusb dev-libs/mcl dev-libs/sirit \ dev-libs/libfmt dev-libs/libusb dev-libs/mcl dev-libs/sirit \
dev-libs/boost dev-libs/openssl dev-libs/discord-rpc \ dev-libs/unordered_dense dev-libs/boost dev-libs/openssl dev-libs/discord-rpc \
dev-util/spirv-tools dev-util/spirv-headers dev-util/vulkan-headers \ dev-util/spirv-tools dev-util/spirv-headers dev-util/vulkan-headers \
dev-util/vulkan-utility-libraries dev-util/glslang \ dev-util/vulkan-utility-libraries dev-util/glslang \
media-gfx/renderdoc media-libs/libva media-libs/opus media-video/ffmpeg \ media-gfx/renderdoc media-libs/libva media-libs/opus media-video/ffmpeg \
@@ -259,7 +260,7 @@ brew install molten-vk
<details> <details>
<summary>FreeBSD</summary> <summary>FreeBSD</summary>
As root run: `pkg install devel/cmake sdl3 devel/boost-libs devel/catch2 devel/libfmt devel/nlohmann-json devel/ninja devel/nasm devel/autoconf devel/pkgconf devel/qt6-base devel/qt6-charts devel/simpleini net/enet multimedia/ffnvcodec-headers multimedia/ffmpeg audio/opus archivers/liblz4 lang/gcc12 graphics/glslang graphics/vulkan-utility-libraries graphics/spirv-tools www/cpp-httplib vulkan-headers quazip-qt6` As root run: `pkg install devel/cmake sdl3 devel/boost-libs devel/catch2 devel/libfmt devel/nlohmann-json devel/ninja devel/nasm devel/autoconf devel/pkgconf devel/qt6-base devel/qt6-charts devel/simpleini net/enet multimedia/ffnvcodec-headers multimedia/ffmpeg audio/opus archivers/liblz4 lang/gcc12 graphics/glslang graphics/vulkan-utility-libraries graphics/spirv-tools www/cpp-httplib devel/unordered-dense vulkan-headers quazip-qt6`
If using FreeBSD 12 or prior, use `devel/pkg-config` instead. If using FreeBSD 12 or prior, use `devel/pkg-config` instead.
@@ -293,7 +294,7 @@ pkg_add cmake nasm git boost unzip--iconv autoconf-2.72p0 bash ffmpeg glslang gm
<summary>DragonFlyBSD</summary> <summary>DragonFlyBSD</summary>
```sh ```sh
pkg install gcc14 git cmake unzip nasm autoconf bash pkgconf ffmpeg glslang gmake jq nlohmann-json enet spirv-tools sdl3 vulkan-utility-libraries vulkan-headers catch2 libfmt openssl liblz4 boost-libs cpp-httplib qt6-base qt6-charts quazip-qt6 libva-vdpau-driver libva-utils libva-intel-driver pkg install gcc14 git cmake unzip nasm autoconf bash pkgconf ffmpeg glslang gmake jq nlohmann-json enet spirv-tools sdl3 vulkan-utility-libraries vulkan-headers catch2 libfmt openssl liblz4 boost-libs cpp-httplib qt6-base qt6-charts quazip-qt6 unordered-dense libva-vdpau-driver libva-utils libva-intel-driver
``` ```
[Caveats](./Caveats.md#dragonflybsd). [Caveats](./Caveats.md#dragonflybsd).
@@ -327,7 +328,7 @@ sudo pkgin install git cmake autoconf build-essential libusb-1 nasm gcc13
```sh ```sh
BASE="git make autoconf libtool automake-wrapper jq patch" BASE="git make autoconf libtool automake-wrapper jq patch"
MINGW="qt6-base qt6-charts qt6-tools qt6-translations qt6-svg cmake toolchain clang python-pip openssl vulkan-memory-allocator vulkan-devel glslang boost fmt lz4 nlohmann-json zlib zstd enet opus libusb openssl SDL3" MINGW="qt6-base qt6-charts qt6-tools qt6-translations qt6-svg cmake toolchain clang python-pip openssl vulkan-memory-allocator vulkan-devel glslang boost fmt lz4 nlohmann-json zlib zstd enet opus libusb unordered_dense openssl SDL3"
# Either x86_64 or clang-aarch64 (Windows on ARM) # Either x86_64 or clang-aarch64 (Windows on ARM)
packages="$BASE" packages="$BASE"
for pkg in $MINGW; do for pkg in $MINGW; do
+11 -27
View File
@@ -43,7 +43,6 @@ This guide will walk you through adding a new boolean toggle setting to Eden's c
Firstly add your desired toggle: Firstly add your desired toggle:
Example: `src/common/setting.h` Example: `src/common/setting.h`
```cpp ```cpp
SwitchableSetting<bool> your_setting_name{linkage, false, "your_setting_name", Category::RendererExtensions}; SwitchableSetting<bool> your_setting_name{linkage, false, "your_setting_name", Category::RendererExtensions};
``` ```
@@ -68,7 +67,6 @@ Common Categories:
Add the toggle to the Qt UI, where you wish for it to appear and place it there. Add the toggle to the Qt UI, where you wish for it to appear and place it there.
Example: `src/qt_common/config/shared_translation.cpp` Example: `src/qt_common/config/shared_translation.cpp`
```cpp ```cpp
INSERT(Settings, INSERT(Settings,
your_setting_name, your_setting_name,
@@ -93,7 +91,6 @@ INSERT(Settings,
Add where it should be in the settings. Add where it should be in the settings.
Example: `src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/BooleanSetting.kt` Example: `src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/BooleanSetting.kt`
```kts ```kts
RENDERER_YOUR_SETTING_NAME("your_setting_name"), RENDERER_YOUR_SETTING_NAME("your_setting_name"),
``` ```
@@ -109,7 +106,6 @@ RENDERER_YOUR_SETTING_NAME("your_setting_name"),
Add the toggle to the Kotlin (Android) UI Add the toggle to the Kotlin (Android) UI
Example: `src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SettingsItem.kt` Example: `src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/model/view/SettingsItem.kt`
```kts ```kts
put( put(
SwitchSetting( SwitchSetting(
@@ -127,7 +123,6 @@ put(
Add your setting within the right category. Add your setting within the right category.
Example: `src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt` Example: `src/android/app/src/main/java/org/yuzu/yuzu_emu/features/settings/ui/SettingsFragmentPresenter.kt`
```kts ```kts
add(BooleanSetting.RENDERER_YOUR_SETTING_NAME.key) add(BooleanSetting.RENDERER_YOUR_SETTING_NAME.key)
``` ```
@@ -142,7 +137,6 @@ add(BooleanSetting.RENDERER_YOUR_SETTING_NAME.key)
Add your setting and description in the appropriate place. Add your setting and description in the appropriate place.
Example: `src/android/app/src/main/res/values/strings.xml` Example: `src/android/app/src/main/res/values/strings.xml`
```xml ```xml
<string name="your_setting_name">Your Setting Display Name</string> <string name="your_setting_name">Your Setting Display Name</string>
<string name="your_setting_name_description">Detailed description of what this setting does. Explain any caveats, requirements, or warnings here.</string> <string name="your_setting_name_description">Detailed description of what this setting does. Explain any caveats, requirements, or warnings here.</string>
@@ -156,7 +150,6 @@ Now the UI part is done find a place in the code for the toggle,
And use it to your heart's desire! And use it to your heart's desire!
Example: Example:
```cpp ```cpp
const bool your_value = Settings::values.your_setting_name.GetValue(); const bool your_value = Settings::values.your_setting_name.GetValue();
@@ -203,31 +196,25 @@ Common advantages recap:
#### Accessing Debug Knobs (dev side) #### Accessing Debug Knobs (dev side)
Use the `Settings::GetDebugKnobAt(u8 i)` function to check if a specific bit is set: Use the `Settings::getDebugKnobAt(u8 i)` function to check if a specific bit is set:
```cpp ```cpp
//cpp side //cpp side
#include "common/settings.h" #include "common/settings.h"
//To use it as a general purpose uint var:
unsigned int debug_knobs = Settings::values.debug_knobs.GetValue();
// Check if bit 0 is set // Check if bit 0 is set
bool feature_enabled = Settings::GetDebugKnobAt(0); bool feature_enabled = Settings::getDebugKnobAt(0);
// Check if bit 15 is set // Check if bit 15 is set
bool another_feature = Settings::GetDebugKnobAt(15); bool another_feature = Settings::getDebugKnobAt(15);
``` ```
```kts ```kts
//kotlin side //kotlin side
import org.yuzu.yuzu_emu.features.settings.model.Settings import org.yuzu.yuzu_emu.features.settings.model.Settings
//To use it as a general purpose uint var
val debug_knobs: Int = UShortSetting.DEBUG_KNOBS.getInt()
// Check if bit x is set // Check if bit x is set
bool feature_enabled = Settings.GetDebugKnobAt(x); //x as integer from 0 to 15 bool feature_enabled = Settings.getDebugKnobAt(x); //x as integer from 0 to 15
``` ```
The function returns `true` if the specified bit (0-15) is set in the `debug_knobs` value, `false` otherwise. The function returns `true` if the specified bit (0-15) is set in the `debug_knobs` value, `false` otherwise.
@@ -260,7 +247,6 @@ There are two main confusions when talking about knobs:
Sometimes when an user reports: knobs 1 and 2 gets better performance, dev may get confuse whether he means the knobs 1 and 2 literally, or the 1st and 2nd knobs (knobs 0 and 1). Sometimes when an user reports: knobs 1 and 2 gets better performance, dev may get confuse whether he means the knobs 1 and 2 literally, or the 1st and 2nd knobs (knobs 0 and 1).
Debug knobs are **zero-based**, which means: Debug knobs are **zero-based**, which means:
* The first knob is the knob(0) (or knob0 henceforth), and the last one is the 15 (knob15, likewise) * The first knob is the knob(0) (or knob0 henceforth), and the last one is the 15 (knob15, likewise)
* You can talk: "knob0 is enabled/disabled", "In this video i was using only knobs 0 and 2", etc. * You can talk: "knob0 is enabled/disabled", "In this video i was using only knobs 0 and 2", etc.
@@ -273,7 +259,6 @@ Whenever you're instructing tests or reporting results, be precise about whether
ALWAYS use the word in PLURAL (knobs), without mentioning which one, to refer to the setting, aka multiple knobs at once: ALWAYS use the word in PLURAL (knobs), without mentioning which one, to refer to the setting, aka multiple knobs at once:
Examples: Examples:
- **knobs=0**: no knobs enabled - **knobs=0**: no knobs enabled
- **knobs=1**: knob0 enabled, others disabled - **knobs=1**: knob0 enabled, others disabled
- **knobs=2**: knob1 enabled, others disabled - **knobs=2**: knob1 enabled, others disabled
@@ -285,7 +270,6 @@ Examples:
Use the word in SINGULAR (knob), or in plural but referring which ones, when meaning multiple knobs at once: Use the word in SINGULAR (knob), or in plural but referring which ones, when meaning multiple knobs at once:
Examples: Examples:
- **knob0**: knob 0 enabled, others disabled - **knob0**: knob 0 enabled, others disabled
- **knob1**: knob 1 enabled, others disabled - **knob1**: knob 1 enabled, others disabled
- **knobs 0 and 1**: knobs 0 and 1 enabled, others disabled - **knobs 0 and 1**: knobs 0 and 1 enabled, others disabled
@@ -298,12 +282,12 @@ Examples:
```cpp ```cpp
void SomeFunction() { void SomeFunction() {
if (Settings::GetDebugKnobAt(0)) { if (Settings::getDebugKnobAt(0)) {
LOG_DEBUG(Common, "Debug feature 0 is enabled"); LOG_DEBUG(Common, "Debug feature 0 is enabled");
// Additional debug code here // Additional debug code here
} }
if (Settings::GetDebugKnobAt(1)) { if (Settings::getDebugKnobAt(1)) {
LOG_DEBUG(Common, "Debug feature 1 is enabled"); LOG_DEBUG(Common, "Debug feature 1 is enabled");
// Different debug behavior // Different debug behavior
} }
@@ -315,7 +299,7 @@ void SomeFunction() {
```cpp ```cpp
bool UseOptimizedPath() { bool UseOptimizedPath() {
// Skip optimization if debug bit 2 is set for testing // Skip optimization if debug bit 2 is set for testing
return !Settings::GetDebugKnobAt(2); return !Settings::getDebugKnobAt(2);
} }
``` ```
@@ -324,13 +308,13 @@ bool UseOptimizedPath() {
```cpp ```cpp
void ExperimentalFeature() { void ExperimentalFeature() {
static constexpr u8 EXPERIMENTAL_FEATURE_BIT = 3; static constexpr u8 EXPERIMENTAL_FEATURE_BIT = 3;
if (!Settings::GetDebugKnobAt(EXPERIMENTAL_FEATURE_BIT)) { if (!Settings::getDebugKnobAt(EXPERIMENTAL_FEATURE_BIT)) {
// Fallback to stable implementation // Fallback to stable implementation
StableImplementation(); StableImplementation();
return; return;
} }
// Experimental implementation // Experimental implementation
ExperimentalImplementation(); ExperimentalImplementation();
} }
+25
View File
@@ -308,6 +308,31 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
``` ```
### unordered_dense
```
MIT License
Copyright (c) 2022 Martin Leitner-Ankerl
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
### xbyak ### xbyak
+3
View File
@@ -58,6 +58,9 @@ if (WIN32 AND NOT TARGET LLVM::Demangle)
add_library(LLVM::Demangle ALIAS demangle) add_library(LLVM::Demangle ALIAS demangle)
endif() endif()
# unordered_dense
AddJsonPackage(unordered-dense)
# httplib # httplib
if (IOS) if (IOS)
set(HTTPLIB_USE_BROTLI_IF_AVAILABLE OFF) set(HTTPLIB_USE_BROTLI_IF_AVAILABLE OFF)
@@ -220,7 +220,7 @@ object NativeLibrary {
external fun refreshThreadPolicies() external fun refreshThreadPolicies()
external fun GetDebugKnobAt(index: Int): Boolean external fun getDebugKnobAt(index: Int): Boolean
/** /**
* Set the current speed limit to the configured turbo speed. * Set the current speed limit to the configured turbo speed.
@@ -35,8 +35,8 @@ object Settings {
fun getPlayerString(player: Int): String = fun getPlayerString(player: Int): String =
YuzuApplication.appContext.getString(R.string.preferences_player, player) YuzuApplication.appContext.getString(R.string.preferences_player, player)
fun GetDebugKnobAt(index: Int): Boolean { fun getDebugKnobAt(index: Int): Boolean {
return org.yuzu.yuzu_emu.NativeLibrary.GetDebugKnobAt(index) return org.yuzu.yuzu_emu.NativeLibrary.getDebugKnobAt(index)
} }
const val PREF_FIRST_APP_LAUNCH = "FirstApplicationLaunch" const val PREF_FIRST_APP_LAUNCH = "FirstApplicationLaunch"
@@ -11,7 +11,8 @@ import org.yuzu.yuzu_emu.utils.NativeConfig
enum class ShortSetting(override val key: String) : AbstractShortSetting { enum class ShortSetting(override val key: String) : AbstractShortSetting {
RENDERER_SPEED_LIMIT("speed_limit"), RENDERER_SPEED_LIMIT("speed_limit"),
RENDERER_TURBO_SPEED_LIMIT("turbo_speed_limit"), RENDERER_TURBO_SPEED_LIMIT("turbo_speed_limit"),
RENDERER_SLOW_SPEED_LIMIT("slow_speed_limit") RENDERER_SLOW_SPEED_LIMIT("slow_speed_limit"),
DEBUG_KNOBS("debug_knobs")
; ;
override fun getShort(needsGlobal: Boolean): Short = NativeConfig.getShort(key, needsGlobal) override fun getShort(needsGlobal: Boolean): Short = NativeConfig.getShort(key, needsGlobal)
@@ -28,4 +29,4 @@ enum class ShortSetting(override val key: String) : AbstractShortSetting {
override fun getValueAsString(needsGlobal: Boolean): String = getShort(needsGlobal).toString() override fun getValueAsString(needsGlobal: Boolean): String = getShort(needsGlobal).toString()
override fun reset() = NativeConfig.setShort(key, defaultValue) override fun reset() = NativeConfig.setShort(key, defaultValue)
} }
@@ -1,27 +0,0 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
package org.yuzu.yuzu_emu.features.settings.model
import org.yuzu.yuzu_emu.utils.NativeConfig
enum class UShortSetting(override val key: String) : AbstractIntSetting {
DEBUG_KNOBS("debug_knobs")
;
override fun getInt(needsGlobal: Boolean): Int =
NativeConfig.getUnsignedShort(key, needsGlobal)
override fun setInt(value: Int) {
if (NativeConfig.isPerGameConfigLoaded()) {
global = false
}
NativeConfig.setUnsignedShort(key, value)
}
override val defaultValue: Int by lazy { NativeConfig.getDefaultToString(key).toInt() }
override fun getValueAsString(needsGlobal: Boolean): String = getInt(needsGlobal).toString()
override fun reset() = NativeConfig.setUnsignedShort(key, defaultValue)
}
@@ -20,7 +20,6 @@ import org.yuzu.yuzu_emu.features.settings.model.IntSetting
import org.yuzu.yuzu_emu.features.settings.model.LongSetting import org.yuzu.yuzu_emu.features.settings.model.LongSetting
import org.yuzu.yuzu_emu.features.settings.model.ShortSetting import org.yuzu.yuzu_emu.features.settings.model.ShortSetting
import org.yuzu.yuzu_emu.features.settings.model.StringSetting import org.yuzu.yuzu_emu.features.settings.model.StringSetting
import org.yuzu.yuzu_emu.features.settings.model.UShortSetting
import org.yuzu.yuzu_emu.network.NetDataValidators import org.yuzu.yuzu_emu.network.NetDataValidators
import org.yuzu.yuzu_emu.utils.LosslessScalingHelper import org.yuzu.yuzu_emu.utils.LosslessScalingHelper
import org.yuzu.yuzu_emu.utils.NativeConfig import org.yuzu.yuzu_emu.utils.NativeConfig
@@ -1035,7 +1034,7 @@ abstract class SettingsItem(
) )
put( put(
SpinBoxSetting( SpinBoxSetting(
UShortSetting.DEBUG_KNOBS, ShortSetting.DEBUG_KNOBS,
titleId = R.string.debug_knobs, titleId = R.string.debug_knobs,
descriptionId = R.string.debug_knobs_description, descriptionId = R.string.debug_knobs_description,
valueHint = R.string.debug_knobs_hint, valueHint = R.string.debug_knobs_hint,
@@ -25,7 +25,6 @@ import org.yuzu.yuzu_emu.features.settings.model.Settings
import org.yuzu.yuzu_emu.features.settings.model.Settings.MenuTag import org.yuzu.yuzu_emu.features.settings.model.Settings.MenuTag
import org.yuzu.yuzu_emu.features.settings.model.ShortSetting import org.yuzu.yuzu_emu.features.settings.model.ShortSetting
import org.yuzu.yuzu_emu.features.settings.model.StringSetting import org.yuzu.yuzu_emu.features.settings.model.StringSetting
import org.yuzu.yuzu_emu.features.settings.model.UShortSetting
import org.yuzu.yuzu_emu.features.settings.model.view.* import org.yuzu.yuzu_emu.features.settings.model.view.*
import org.yuzu.yuzu_emu.utils.InputHandler import org.yuzu.yuzu_emu.utils.InputHandler
import org.yuzu.yuzu_emu.utils.LosslessScalingHelper import org.yuzu.yuzu_emu.utils.LosslessScalingHelper
@@ -1327,7 +1326,7 @@ class SettingsFragmentPresenter(
add(HeaderSetting(R.string.general)) add(HeaderSetting(R.string.general))
add(UShortSetting.DEBUG_KNOBS.key) add(ShortSetting.DEBUG_KNOBS.key)
add(StringSetting.PROGRAM_ARGS.key) add(StringSetting.PROGRAM_ARGS.key)
if (!NativeConfig.isPerGameConfigLoaded()) { if (!NativeConfig.isPerGameConfigLoaded()) {
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2023 yuzu Emulator Project // SPDX-FileCopyrightText: 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
@@ -24,6 +27,6 @@ object SettingsFile {
fun loadCustomConfig(game: Game) { fun loadCustomConfig(game: Game) {
val fileName = FileUtil.getFilename(Uri.parse(game.path)) val fileName = FileUtil.getFilename(Uri.parse(game.path))
NativeConfig.initializePerGameConfig(game.programId, fileName) NativeConfig.initializePerGameConfig(game.applicationId, fileName)
} }
} }
@@ -189,7 +189,7 @@ class AddonsFragment : Fragment() {
fragmentManager = parentFragmentManager, fragmentManager = parentFragmentManager,
addonViewModel = addonViewModel, addonViewModel = addonViewModel,
documents = documents, documents = documents,
programId = args.game.programId programId = args.game.applicationId
) )
} }
@@ -347,7 +347,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
} }
try { try {
if (GpuDriverHelper.isAdrenoGpu()) { if (GpuDriverHelper.isAdrenoGpu()) {
val programIdHex = game!!.programIdHex val programIdHex = game!!.applicationIdHex
if (NativeFreedrenoConfig.loadPerGameConfigWithGlobalFallback(programIdHex)) { if (NativeFreedrenoConfig.loadPerGameConfigWithGlobalFallback(programIdHex)) {
Log.info("[EmulationFragment] Loaded per-game Freedreno config for $programIdHex") Log.info("[EmulationFragment] Loaded per-game Freedreno config for $programIdHex")
} else { } else {
@@ -59,7 +59,7 @@ class FreedrenoSettingsFragment : Fragment() {
NativeFreedrenoConfig.initializeFreedrenoConfig() NativeFreedrenoConfig.initializeFreedrenoConfig()
if (isPerGameConfig) { if (isPerGameConfig) {
NativeFreedrenoConfig.loadPerGameConfig(game!!.programIdHex) NativeFreedrenoConfig.loadPerGameConfig(game!!.applicationIdHex)
} else { } else {
NativeFreedrenoConfig.reloadFreedrenoConfig() NativeFreedrenoConfig.reloadFreedrenoConfig()
} }
@@ -157,7 +157,7 @@ class FreedrenoSettingsFragment : Fragment() {
binding.buttonSave.setOnClickListener { binding.buttonSave.setOnClickListener {
if (isPerGameConfig) { if (isPerGameConfig) {
NativeFreedrenoConfig.savePerGameConfig(game!!.programIdHex) NativeFreedrenoConfig.savePerGameConfig(game!!.applicationIdHex)
showSnackbar(getString(R.string.freedreno_per_game_saved)) showSnackbar(getString(R.string.freedreno_per_game_saved))
} else { } else {
NativeFreedrenoConfig.saveFreedrenoConfig() NativeFreedrenoConfig.saveFreedrenoConfig()
@@ -455,7 +455,7 @@ class GamePropertiesFragment : Fragment() {
val shaderCacheDir = File( val shaderCacheDir = File(
DirectoryInitialization.userDirectory + DirectoryInitialization.userDirectory +
"/cache/shader/" + args.game.settingsName.lowercase() "/cache/shader/" + args.game.shaderCacheName.lowercase()
) )
if (shaderCacheDir.exists()) { if (shaderCacheDir.exists()) {
add( add(
@@ -600,7 +600,7 @@ class GamePropertiesFragment : Fragment() {
val files = cacheSaveDir.listFiles() val files = cacheSaveDir.listFiles()
var savesFolderFile: File? = null var savesFolderFile: File? = null
if (files != null) { if (files != null) {
val savesFolderName = args.game.programIdHex val savesFolderName = args.game.applicationIdHex
for (file in files) { for (file in files) {
if (file.isDirectory && file.name == savesFolderName) { if (file.isDirectory && file.name == savesFolderName) {
savesFolderFile = file savesFolderFile = file
@@ -232,7 +232,7 @@ class InstallableFragment : Fragment() {
fragmentManager = parentFragmentManager, fragmentManager = parentFragmentManager,
addonViewModel = addonViewModel, addonViewModel = addonViewModel,
documents = documents, documents = documents,
programId = addonViewModel.game?.programId programId = addonViewModel.game?.applicationId
) )
} }
@@ -142,10 +142,11 @@ class AddonViewModel : ViewModel() {
} }
fun onDeleteAddon(patch: Patch) { fun onDeleteAddon(patch: Patch) {
val currentGame = game ?: return
when (PatchType.from(patch.type)) { when (PatchType.from(patch.type)) {
PatchType.Update -> NativeLibrary.removeUpdate(patch.programId) PatchType.Update -> NativeLibrary.removeUpdate(currentGame.programId)
PatchType.DLC -> NativeLibrary.removeDLC(patch.programId) PatchType.DLC -> NativeLibrary.removeDLC(currentGame.applicationId)
PatchType.Mod -> NativeLibrary.removeMod(patch.programId, patch.name) PatchType.Mod -> NativeLibrary.removeMod(currentGame.programId, patch.name)
} }
refreshAddons(force = true) refreshAddons(force = true)
} }
@@ -165,7 +166,7 @@ class AddonViewModel : ViewModel() {
} }
NativeConfig.setDisabledAddons( NativeConfig.setDisabledAddons(
currentGame.programId, currentGame.applicationId,
currentList.mapNotNull { currentList.mapNotNull {
if (it.enabled) { if (it.enabled) {
null null
@@ -199,6 +200,6 @@ class AddonViewModel : ViewModel() {
} }
private fun gameKey(game: Game): String { private fun gameKey(game: Game): String {
return "${game.programId}|${game.path}" return "${game.applicationId}|${game.path}"
} }
} }
@@ -150,7 +150,7 @@ class DriverViewModel : ViewModel() {
?: return@withContext ?: return@withContext
val shaderDir = File( val shaderDir = File(
externalFilesDir.absolutePath + externalFilesDir.absolutePath +
"/shader/" + game.settingsName.lowercase() "/shader/" + game.shaderCacheName.lowercase()
) )
if (shaderDir.exists()) { if (shaderDir.exists()) {
shaderDir.deleteRecursively() shaderDir.deleteRecursively()
@@ -1,4 +1,4 @@
// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project // SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2023 yuzu Emulator Project // SPDX-FileCopyrightText: 2023 yuzu Emulator Project
@@ -35,19 +35,26 @@ class Game(
val keyAddedToLibraryTime get() = "${path}_AddedToLibraryTime" val keyAddedToLibraryTime get() = "${path}_AddedToLibraryTime"
val keyLastPlayedTime get() = "${path}_LastPlayed" val keyLastPlayedTime get() = "${path}_LastPlayed"
private val programIdLong: Long
get() = programId.toLongOrNull() ?: 0L
private val applicationIdLong: Long
get() = programIdLong and -8192L
val applicationId: String
get() = applicationIdLong.toString()
val settingsName: String val settingsName: String
get() { get() {
val programIdLong = programId.toLong() return if (applicationIdLong == 0L) {
return if (programIdLong == 0L) {
FileUtil.getFilename(Uri.parse(path)) FileUtil.getFilename(Uri.parse(path))
} else { } else {
"0" + programIdLong.toString(16).uppercase() "0" + applicationIdLong.toString(16).uppercase()
} }
} }
val programIdHex: String val programIdHex: String
get() { get() {
val programIdLong = programId.toLong()
return if (programIdLong == 0L) { return if (programIdLong == 0L) {
"0" "0"
} else { } else {
@@ -55,16 +62,32 @@ class Game(
} }
} }
val shaderCacheName: String
get() = if (programIdLong == 0L) {
FileUtil.getFilename(Uri.parse(path))
} else {
"0" + programIdLong.toString(16).uppercase()
}
val applicationIdHex: String
get() {
return if (applicationIdLong == 0L) {
"0"
} else {
"0" + applicationIdLong.toString(16).uppercase()
}
}
val saveZipName: String val saveZipName: String
get() = "$title ${YuzuApplication.appContext.getString(R.string.save_data).lowercase()} - ${ get() = "$title ${YuzuApplication.appContext.getString(R.string.save_data).lowercase()} - ${
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
}.zip" }.zip"
val saveDir: String val saveDir: String
get() = NativeConfig.getSaveDir() + NativeLibrary.getSavePath(programId) get() = NativeConfig.getSaveDir() + NativeLibrary.getSavePath(applicationId)
val addonDir: String val addonDir: String
get() = DirectoryInitialization.userDirectory + "/load/" + programIdHex + "/" get() = DirectoryInitialization.userDirectory + "/load/" + applicationIdHex + "/"
val launchIntent: Intent val launchIntent: Intent
get() = Intent(YuzuApplication.appContext, EmulationActivity::class.java).apply { get() = Intent(YuzuApplication.appContext, EmulationActivity::class.java).apply {
@@ -47,6 +47,7 @@ import info.debatty.java.stringsimilarity.Jaccard
import info.debatty.java.stringsimilarity.JaroWinkler import info.debatty.java.stringsimilarity.JaroWinkler
import java.util.Locale import java.util.Locale
import androidx.core.content.edit import androidx.core.content.edit
import androidx.core.view.doOnNextLayout
class GamesFragment : Fragment() { class GamesFragment : Fragment() {
private var _binding: FragmentGamesBinding? = null private var _binding: FragmentGamesBinding? = null
@@ -58,6 +59,7 @@ class GamesFragment : Fragment() {
private var originalHeaderLeftMargin: Int? = null private var originalHeaderLeftMargin: Int? = null
private var lastViewType: Int = GameAdapter.VIEW_TYPE_GRID private var lastViewType: Int = GameAdapter.VIEW_TYPE_GRID
private var fallbackBottomInset: Int = 0
private var pendingPostReloadListSettle = false private var pendingPostReloadListSettle = false
private var pendingPostReloadListSettleGeneration = 0 private var pendingPostReloadListSettleGeneration = 0
private var gameListSubmitGeneration = 0 private var gameListSubmitGeneration = 0
@@ -225,7 +227,12 @@ class GamesFragment : Fragment() {
} }
else -> throw IllegalArgumentException("Invalid view type: $savedViewType") else -> throw IllegalArgumentException("Invalid view type: $savedViewType")
} }
if (savedViewType != GameAdapter.VIEW_TYPE_CAROUSEL) { if (savedViewType == GameAdapter.VIEW_TYPE_CAROUSEL) {
(binding.gridGames as? View)?.let { it -> ViewCompat.requestApplyInsets(it)}
doOnNextLayout { //Carousel: important to avoid overlap issues
(this as? CarouselRecyclerView)?.notifyLaidOut(fallbackBottomInset)
}
} else {
(this as? CarouselRecyclerView)?.setupCarousel(false) (this as? CarouselRecyclerView)?.setupCarousel(false)
} }
adapter = gameAdapter adapter = gameAdapter
@@ -583,6 +590,11 @@ class GamesFragment : Fragment() {
qlaunchButton.layoutParams = mlpQLaunch qlaunchButton.layoutParams = mlpQLaunch
} }
val navInsets = windowInsets.getInsets(WindowInsetsCompat.Type.navigationBars())
val gestureInsets = windowInsets.getInsets(WindowInsetsCompat.Type.systemGestures())
val bottomInset = maxOf(navInsets.bottom, gestureInsets.bottom, cutoutInsets.bottom)
fallbackBottomInset = bottomInset
(binding.gridGames as? CarouselRecyclerView)?.notifyInsetsReady(bottomInset)
windowInsets windowInsets
} }
} }
@@ -1,4 +1,4 @@
// SPDX-FileCopyrightText: Copyright 2025 Eden Emulator Project // SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2023 yuzu Emulator Project // SPDX-FileCopyrightText: 2023 yuzu Emulator Project
@@ -65,7 +65,7 @@ object CustomSettingsHandler {
// Initialize per-game config // Initialize per-game config
try { try {
val fileName = FileUtil.getFilename(Uri.parse(game.path)) val fileName = FileUtil.getFilename(Uri.parse(game.path))
NativeConfig.initializePerGameConfig(game.programId, fileName) NativeConfig.initializePerGameConfig(game.applicationId, fileName)
Log.info("[CustomSettingsHandler] Successfully applied custom settings") Log.info("[CustomSettingsHandler] Successfully applied custom settings")
return game return game
} catch (e: Exception) { } catch (e: Exception) {
@@ -333,20 +333,20 @@ object CustomSettingsHandler {
*/ */
fun findGameByTitleId(titleId: String, context: Context): Game? { fun findGameByTitleId(titleId: String, context: Context): Game? {
Log.info("[CustomSettingsHandler] Searching for game with title ID: $titleId") Log.info("[CustomSettingsHandler] Searching for game with title ID: $titleId")
// Convert hex title ID to decimal for comparison with programId // Convert the program ID to the application ID used by per-game settings.
val programIdDecimal = try { val applicationIdLong = try {
titleId.toLong(16).toString() titleId.toLong(16) and -8192L
} catch (e: NumberFormatException) { } catch (e: NumberFormatException) {
Log.error("[CustomSettingsHandler] Invalid title ID format: $titleId") Log.error("[CustomSettingsHandler] Invalid title ID format: $titleId")
return null return null
} }
val applicationIdDecimal = applicationIdLong.toString()
// Expected hex format with "0" prefix // Expected hex format with "0" prefix
val expectedHex = "0${titleId.uppercase()}" val expectedHex = "0${applicationIdLong.toString(16).uppercase()}"
// First check cached games for fast lookup // First check cached games for fast lookup
GameHelper.cachedGameList.find { game -> GameHelper.cachedGameList.find { game ->
game.programId == programIdDecimal || game.applicationId == applicationIdDecimal || game.applicationIdHex.equals(expectedHex, ignoreCase = true)
game.programIdHex.equals(expectedHex, ignoreCase = true)
}?.let { foundGame -> }?.let { foundGame ->
Log.info("[CustomSettingsHandler] Found game in cache: ${foundGame.title}") Log.info("[CustomSettingsHandler] Found game in cache: ${foundGame.title}")
return foundGame return foundGame
@@ -355,8 +355,7 @@ object CustomSettingsHandler {
Log.info("[CustomSettingsHandler] Game not in cache, scanning full library...") Log.info("[CustomSettingsHandler] Game not in cache, scanning full library...")
val allGames = GameHelper.getGames() val allGames = GameHelper.getGames()
val foundGame = allGames.find { game -> val foundGame = allGames.find { game ->
game.programId == programIdDecimal || game.applicationId == applicationIdDecimal || game.applicationIdHex.equals(expectedHex, ignoreCase = true)
game.programIdHex.equals(expectedHex, ignoreCase = true)
} }
if (foundGame != null) { if (foundGame != null) {
Log.info("[CustomSettingsHandler] Found game: ${foundGame.title} at ${foundGame.path}") Log.info("[CustomSettingsHandler] Found game: ${foundGame.title} at ${foundGame.path}")
@@ -170,12 +170,12 @@ object GameHelper {
val game = getGame(it.uri, true, false) val game = getGame(it.uri, true, false)
if (game != null) { if (game != null) {
games.add(game) games.add(game)
if (game.programId != "0") { if (game.applicationId != "0") {
gamesByProgramId[game.programId] = game gamesByProgramId[game.applicationId] = game
} }
} else if (mountedContainer) { } else if (mountedContainer) {
GameMetadata.getProgramId(filePath).toLongOrNull()?.let { programId -> GameMetadata.getProgramId(filePath).toLongOrNull()?.let { programId ->
gamesByProgramId[(programId and 0x800L.inv()).toString()] gamesByProgramId[(programId and -8192L).toString()]
}?.let { existingGame -> }?.let { existingGame ->
NativeLibrary.getPatchesForFile(existingGame.path, existingGame.programId) NativeLibrary.getPatchesForFile(existingGame.path, existingGame.programId)
existingGame.version = GameMetadata.getVersion( existingGame.version = GameMetadata.getVersion(
@@ -80,12 +80,6 @@ object NativeConfig {
@Synchronized @Synchronized
external fun setShort(key: String, value: Short) external fun setShort(key: String, value: Short)
@Synchronized
external fun getUnsignedShort(key: String, needsGlobal: Boolean): Int
@Synchronized
external fun setUnsignedShort(key: String, value: Int)
@Synchronized @Synchronized
external fun getInt(key: String, needsGlobal: Boolean): Int external fun getInt(key: String, needsGlobal: Boolean): Int
@@ -12,16 +12,13 @@ import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import kotlin.math.abs import kotlin.math.abs
import kotlin.math.cos import kotlin.math.cos
import kotlin.math.pow
import kotlin.math.sin import kotlin.math.sin
import org.yuzu.yuzu_emu.R import org.yuzu.yuzu_emu.R
import org.yuzu.yuzu_emu.adapters.GameAdapter import org.yuzu.yuzu_emu.adapters.GameAdapter
import androidx.core.view.doOnNextLayout import androidx.core.view.doOnNextLayout
import androidx.core.view.ViewCompat
import org.yuzu.yuzu_emu.YuzuApplication import org.yuzu.yuzu_emu.YuzuApplication
import androidx.preference.PreferenceManager import androidx.preference.PreferenceManager
import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsCompat
import org.yuzu.yuzu_emu.utils.FullscreenHelper
/** /**
* CarouselRecyclerView encapsulates all carousel content for the games UI. * CarouselRecyclerView encapsulates all carousel content for the games UI.
* It manages overlapping cards, center snapping, custom drawing order, * It manages overlapping cards, center snapping, custom drawing order,
@@ -35,9 +32,7 @@ class CarouselRecyclerView @JvmOverloads constructor(
private var overlapFactor: Float = 0f private var overlapFactor: Float = 0f
private var overlapPx: Int = 0 private var overlapPx: Int = 0
private var bottomInset: Int = 0 private var bottomInset: Int = -1
private var latestWindowInsets: WindowInsetsCompat? = null
private var cardGeometryInitialized: Boolean = false
private var overlapDecoration: OverlappingDecoration? = null private var overlapDecoration: OverlappingDecoration? = null
private var pagerSnapHelper: PagerSnapHelper? = null private var pagerSnapHelper: PagerSnapHelper? = null
private var scalingScrollListener: OnScrollListener? = null private var scalingScrollListener: OnScrollListener? = null
@@ -96,38 +91,6 @@ class CarouselRecyclerView @JvmOverloads constructor(
init { init {
setChildrenDrawingOrderEnabled(true) setChildrenDrawingOrderEnabled(true)
ViewCompat.setOnApplyWindowInsetsListener(this) { _, insets ->
latestWindowInsets = insets
updateCardGeometry()
applyCarouselPadding()
insets
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
ViewCompat.requestApplyInsets(this)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
if (w != oldw || h != oldh) {
updateCardGeometry()
applyCarouselPadding()
}
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
if (isCarouselMode) updateChildScalesAndAlpha()
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
ViewCompat.requestApplyInsets(this)
post { updateCardGeometry() }
}
} }
override fun setAdapter(adapter: Adapter<*>?) { override fun setAdapter(adapter: Adapter<*>?) {
@@ -140,8 +103,6 @@ class CarouselRecyclerView @JvmOverloads constructor(
super.setAdapter(adapter) super.setAdapter(adapter)
(adapter as? GameAdapter)?.registerAdapterDataObserver(carouselAdapterObserver) (adapter as? GameAdapter)?.registerAdapterDataObserver(carouselAdapterObserver)
updateCardGeometry()
applyCarouselPadding()
} }
private fun calculateCenter(width: Int, paddingStart: Int, paddingEnd: Int): Int { private fun calculateCenter(width: Int, paddingStart: Int, paddingEnd: Int): Int {
@@ -292,71 +253,40 @@ class CarouselRecyclerView @JvmOverloads constructor(
} }
} }
private fun resolveBottomInset(windowInsets: WindowInsetsCompat): Int { fun notifyInsetsReady(newBottomInset: Int) {
val navigationBottom = if (FullscreenHelper.isFullscreenEnabled(context)) { if (bottomInset != newBottomInset) {
0 bottomInset = newBottomInset
} else { }
windowInsets.getInsetsIgnoringVisibility(WindowInsetsCompat.Type.navigationBars()).bottom
if (isCarouselMode) {
setupCarousel(true)
} else {
setupCarousel(false)
} }
val gestureInsets = windowInsets.getInsetsIgnoringVisibility(
WindowInsetsCompat.Type.systemGestures()
)
val cutoutInsets = windowInsets.getInsetsIgnoringVisibility(
WindowInsetsCompat.Type.displayCutout()
)
return maxOf(navigationBottom, gestureInsets.bottom, cutoutInsets.bottom)
} }
private fun updateCardGeometry() { fun notifyLaidOut(fallBackBottomInset: Int) {
if (!isCarouselMode || height <= 0) return if (bottomInset < 0) bottomInset = fallBackBottomInset
var gameAdapter = adapter as? GameAdapter ?: return
var newCardSize = cardSize(bottomInset)
if (gameAdapter.cardSize != newCardSize) {
gameAdapter.setCardSize(newCardSize)
}
val gameAdapter = adapter as? GameAdapter ?: return if (isCarouselMode) {
val windowInsets = latestWindowInsets ?: ViewCompat.getRootWindowInsets(this) ?: return setupCarousel(true)
}
}
if (cardGeometryInitialized && !hasWindowFocus()) return fun cardSize(bottomInset: Int): Int {
val newBottomInset = resolveBottomInset(windowInsets).coerceIn(0, height)
val internalFactor = resources.getFraction(R.fraction.carousel_card_size_factor, 1, 1) val internalFactor = resources.getFraction(R.fraction.carousel_card_size_factor, 1, 1)
val userFactor = preferences.getFloat(CAROUSEL_CARD_SIZE_FACTOR, internalFactor).coerceIn( val userFactor = preferences.getFloat(CAROUSEL_CARD_SIZE_FACTOR, internalFactor).coerceIn(
0f, 0f,
1f 1f
) )
val screenWidth = resources.displayMetrics.widthPixels.toFloat() val scaledHeight = height * userFactor
val screenHeight = resources.displayMetrics.heightPixels.toFloat() val availableHeight = height - bottomInset
val aspectFactor = ((screenWidth / screenHeight) / (20f / 9f)) return minOf(scaledHeight.toInt(), availableHeight.toInt())
.pow(0.75f)
.coerceIn(0.5f, 1f)
val newCardSize = minOf(
(height * userFactor).toInt(),
height - newBottomInset,
(height * aspectFactor).toInt()
)
if (newCardSize <= 0) return
val insetChanged = bottomInset != newBottomInset
val cardSizeChanged = gameAdapter.cardSize != newCardSize
bottomInset = newBottomInset
cardGeometryInitialized = true
if (cardSizeChanged) gameAdapter.setCardSize(newCardSize)
if (insetChanged || cardSizeChanged) setupCarousel(true)
}
private fun applyCarouselPadding() {
if (!isCarouselMode) return
val gameAdapter = adapter as? GameAdapter ?: return
val cardSize = gameAdapter.cardSize
if (cardSize <= 0 || bottomInset < 0) return
val topPadding = ((height - bottomInset - cardSize) / 2).coerceAtLeast(0)
val sidePadding = (width - cardSize) / 2
if (paddingLeft != sidePadding || paddingTop != topPadding ||
paddingRight != sidePadding || paddingBottom != 0
) {
setPadding(sidePadding, topPadding, sidePadding, 0)
}
clipToPadding = false
} }
fun setupCarousel(enabled: Boolean) { fun setupCarousel(enabled: Boolean) {
@@ -385,6 +315,9 @@ class CarouselRecyclerView @JvmOverloads constructor(
internalFlingMultiplier internalFlingMultiplier
).coerceIn(1f, 5f) ).coerceIn(1f, 5f)
// Detach SnapHelper during setup
pagerSnapHelper?.attachToRecyclerView(null)
// Add overlap decoration if not present // Add overlap decoration if not present
if (overlapDecoration == null) { if (overlapDecoration == null) {
overlapDecoration = OverlappingDecoration(overlapPx) overlapDecoration = OverlappingDecoration(overlapPx)
@@ -402,7 +335,12 @@ class CarouselRecyclerView @JvmOverloads constructor(
addOnScrollListener(scalingScrollListener!!) addOnScrollListener(scalingScrollListener!!)
} }
applyCarouselPadding() if (cardSize > 0) {
val topPadding = ((height - bottomInset - cardSize) / 2).coerceAtLeast(0) // Center vertically
val sidePadding = (width - cardSize) / 2 // Center first/last card
setPadding(sidePadding, topPadding, sidePadding, 0)
clipToPadding = false
}
if (pagerSnapHelper == null) { if (pagerSnapHelper == null) {
pagerSnapHelper = CenterPagerSnapHelper() pagerSnapHelper = CenterPagerSnapHelper()
@@ -424,7 +362,6 @@ class CarouselRecyclerView @JvmOverloads constructor(
} }
savedItemAnimator = null savedItemAnimator = null
} }
cardGeometryInitialized = false
useCustomDrawingOrder = false useCustomDrawingOrder = false
// Reset padding and fling // Reset padding and fling
setPadding(0, 0, 0, 0) setPadding(0, 0, 0, 0)
@@ -20,7 +20,7 @@ struct RomMetadata {
std::vector<u8> icon; std::vector<u8> icon;
bool isHomebrew; bool isHomebrew;
}; };
static boost::unordered::unordered_flat_map<std::string, RomMetadata> m_rom_metadata_cache; static ankerl::unordered_dense::map<std::string, RomMetadata> m_rom_metadata_cache;
static RomMetadata CacheRomMetadata(const std::string& path) { static RomMetadata CacheRomMetadata(const std::string& path) {
auto& instance = EmulationSession::GetInstance(); auto& instance = EmulationSession::GetInstance();
+10 -9
View File
@@ -788,7 +788,7 @@ int Java_org_yuzu_yuzu_1emu_NativeLibrary_installFileToNand(JNIEnv* env, jobject
jboolean Java_org_yuzu_yuzu_1emu_NativeLibrary_doesUpdateMatchProgram(JNIEnv* env, jobject jobj, jboolean Java_org_yuzu_yuzu_1emu_NativeLibrary_doesUpdateMatchProgram(JNIEnv* env, jobject jobj,
jstring jprogramId, jstring jprogramId,
jstring jupdatePath) { jstring jupdatePath) {
u64 program_id = EmulationSession::GetProgramId(env, jprogramId); const u64 program_id = FileSys::GetBaseTitleID(EmulationSession::GetProgramId(env, jprogramId));
std::string updatePath = Common::Android::GetJString(env, jupdatePath); std::string updatePath = Common::Android::GetJString(env, jupdatePath);
std::shared_ptr<FileSys::NSP> nsp = std::make_shared<FileSys::NSP>( std::shared_ptr<FileSys::NSP> nsp = std::make_shared<FileSys::NSP>(
EmulationSession::GetInstance().System().GetFilesystem()->OpenFile( EmulationSession::GetInstance().System().GetFilesystem()->OpenFile(
@@ -796,7 +796,7 @@ jboolean Java_org_yuzu_yuzu_1emu_NativeLibrary_doesUpdateMatchProgram(JNIEnv* en
for (const auto& item : nsp->GetNCAs()) { for (const auto& item : nsp->GetNCAs()) {
for (const auto& nca_details : item.second) { for (const auto& nca_details : item.second) {
if (nca_details.second->GetName().ends_with(".cnmt.nca")) { if (nca_details.second->GetName().ends_with(".cnmt.nca")) {
auto update_id = nca_details.second->GetTitleId() & ~0xFFFULL; const auto update_id = FileSys::GetBaseTitleID(nca_details.second->GetTitleId());
if (update_id == program_id) { if (update_id == program_id) {
return true; return true;
} }
@@ -1300,8 +1300,8 @@ void Java_org_yuzu_yuzu_1emu_NativeLibrary_refreshThreadPolicies(JNIEnv* env, jo
Common::RefreshThreadPolicies(); Common::RefreshThreadPolicies();
} }
jboolean Java_org_yuzu_yuzu_1emu_NativeLibrary_GetDebugKnobAt(JNIEnv* env, jobject jobj, jint index) { jboolean Java_org_yuzu_yuzu_1emu_NativeLibrary_getDebugKnobAt(JNIEnv* env, jobject jobj, jint index) {
return static_cast<jboolean>(Settings::GetDebugKnobAt(static_cast<u8>(index))); return static_cast<jboolean>(Settings::getDebugKnobAt(static_cast<u8>(index)));
} }
void Java_org_yuzu_yuzu_1emu_NativeLibrary_setTurboSpeedLimit(JNIEnv *env, jobject jobj, jboolean enabled) { void Java_org_yuzu_yuzu_1emu_NativeLibrary_setTurboSpeedLimit(JNIEnv *env, jobject jobj, jboolean enabled) {
@@ -1491,7 +1491,7 @@ jstring Java_org_yuzu_yuzu_1emu_NativeLibrary_firmwareVersion(JNIEnv* env, jclas
} }
jboolean Java_org_yuzu_yuzu_1emu_NativeLibrary_gameRequiresFirmware(JNIEnv* env, jclass clazz, jstring jprogramId) { jboolean Java_org_yuzu_yuzu_1emu_NativeLibrary_gameRequiresFirmware(JNIEnv* env, jclass clazz, jstring jprogramId) {
auto program_id = EmulationSession::GetProgramId(env, jprogramId); const auto program_id = FileSys::GetBaseTitleID(EmulationSession::GetProgramId(env, jprogramId));
return FirmwareManager::GameRequiresFirmware(program_id); return FirmwareManager::GameRequiresFirmware(program_id);
} }
@@ -1575,20 +1575,21 @@ jobjectArray Java_org_yuzu_yuzu_1emu_NativeLibrary_getPatchesForFile(JNIEnv* env
void Java_org_yuzu_yuzu_1emu_NativeLibrary_removeUpdate(JNIEnv* env, jobject jobj, void Java_org_yuzu_yuzu_1emu_NativeLibrary_removeUpdate(JNIEnv* env, jobject jobj,
jstring jprogramId) { jstring jprogramId) {
auto program_id = EmulationSession::GetProgramId(env, jprogramId); const auto program_id = EmulationSession::GetProgramId(env, jprogramId);
ContentManager::RemoveUpdate(EmulationSession::GetInstance().System().GetFileSystemController(), ContentManager::RemoveUpdate(EmulationSession::GetInstance().System().GetFileSystemController(),
program_id); program_id);
} }
void Java_org_yuzu_yuzu_1emu_NativeLibrary_removeDLC(JNIEnv* env, jobject jobj, void Java_org_yuzu_yuzu_1emu_NativeLibrary_removeDLC(JNIEnv* env, jobject jobj,
jstring jprogramId) { jstring jprogramId) {
auto program_id = EmulationSession::GetProgramId(env, jprogramId); const auto program_id = FileSys::GetBaseTitleID(
EmulationSession::GetProgramId(env, jprogramId));
ContentManager::RemoveAllDLC(EmulationSession::GetInstance().System(), program_id); ContentManager::RemoveAllDLC(EmulationSession::GetInstance().System(), program_id);
} }
void Java_org_yuzu_yuzu_1emu_NativeLibrary_removeMod(JNIEnv* env, jobject jobj, jstring jprogramId, void Java_org_yuzu_yuzu_1emu_NativeLibrary_removeMod(JNIEnv* env, jobject jobj, jstring jprogramId,
jstring jname) { jstring jname) {
auto program_id = EmulationSession::GetProgramId(env, jprogramId); const auto program_id = EmulationSession::GetProgramId(env, jprogramId);
ContentManager::RemoveMod(EmulationSession::GetInstance().System().GetFileSystemController(), ContentManager::RemoveMod(EmulationSession::GetInstance().System().GetFileSystemController(),
program_id, Common::Android::GetJString(env, jname)); program_id, Common::Android::GetJString(env, jname));
} }
@@ -1635,7 +1636,7 @@ jint Java_org_yuzu_yuzu_1emu_NativeLibrary_verifyGameContents(JNIEnv* env, jobje
jstring Java_org_yuzu_yuzu_1emu_NativeLibrary_getSavePath(JNIEnv* env, jobject jobj, jstring Java_org_yuzu_yuzu_1emu_NativeLibrary_getSavePath(JNIEnv* env, jobject jobj,
jstring jprogramId) { jstring jprogramId) {
auto program_id = EmulationSession::GetProgramId(env, jprogramId); const auto program_id = FileSys::GetBaseTitleID(EmulationSession::GetProgramId(env, jprogramId));
if (program_id == 0) { if (program_id == 0) {
return Common::Android::ToJString(env, ""); return Common::Android::ToJString(env, "");
} }
+4 -22
View File
@@ -12,6 +12,7 @@
#include "common/fs/path_util.h" #include "common/fs/path_util.h"
#include "common/logging.h" #include "common/logging.h"
#include "common/settings.h" #include "common/settings.h"
#include "core/file_sys/common_funcs.h"
#include "frontend_common/config.h" #include "frontend_common/config.h"
#include "frontend_common/settings_generator.h" #include "frontend_common/settings_generator.h"
#include "native.h" #include "native.h"
@@ -56,7 +57,7 @@ void Java_org_yuzu_yuzu_1emu_utils_NativeConfig_saveGlobalConfig(JNIEnv* env, jo
void Java_org_yuzu_yuzu_1emu_utils_NativeConfig_initializePerGameConfig(JNIEnv* env, jobject obj, void Java_org_yuzu_yuzu_1emu_utils_NativeConfig_initializePerGameConfig(JNIEnv* env, jobject obj,
jstring jprogramId, jstring jprogramId,
jstring jfileName) { jstring jfileName) {
auto program_id = EmulationSession::GetProgramId(env, jprogramId); const auto program_id = FileSys::GetBaseTitleID(EmulationSession::GetProgramId(env, jprogramId));
auto file_name = Common::Android::GetJString(env, jfileName); auto file_name = Common::Android::GetJString(env, jfileName);
const auto config_file_name = program_id == 0 ? file_name : fmt::format("{:016X}", program_id); const auto config_file_name = program_id == 0 ? file_name : fmt::format("{:016X}", program_id);
per_game_config = per_game_config =
@@ -130,25 +131,6 @@ void Java_org_yuzu_yuzu_1emu_utils_NativeConfig_setShort(JNIEnv* env, jobject ob
setting->SetValue(value); setting->SetValue(value);
} }
jint Java_org_yuzu_yuzu_1emu_utils_NativeConfig_getUnsignedShort(JNIEnv* env, jobject obj,
jstring jkey,
jboolean needGlobal) {
auto setting = getSetting<u16>(env, jkey);
if (setting == nullptr) {
return -1;
}
return static_cast<jint>(setting->GetValue(static_cast<bool>(needGlobal)));
}
void Java_org_yuzu_yuzu_1emu_utils_NativeConfig_setUnsignedShort(JNIEnv* env, jobject obj,
jstring jkey, jint value) {
auto setting = getSetting<u16>(env, jkey);
if (setting == nullptr) {
return;
}
setting->SetValue(static_cast<u16>(value));
}
jint Java_org_yuzu_yuzu_1emu_utils_NativeConfig_getInt(JNIEnv* env, jobject obj, jstring jkey, jint Java_org_yuzu_yuzu_1emu_utils_NativeConfig_getInt(JNIEnv* env, jobject obj, jstring jkey,
jboolean needGlobal) { jboolean needGlobal) {
auto setting = getSetting<int>(env, jkey); auto setting = getSetting<int>(env, jkey);
@@ -341,7 +323,7 @@ void Java_org_yuzu_yuzu_1emu_utils_NativeConfig_addGameDir(JNIEnv* env, jobject
jobjectArray Java_org_yuzu_yuzu_1emu_utils_NativeConfig_getDisabledAddons(JNIEnv* env, jobject obj, jobjectArray Java_org_yuzu_yuzu_1emu_utils_NativeConfig_getDisabledAddons(JNIEnv* env, jobject obj,
jstring jprogramId) { jstring jprogramId) {
auto program_id = EmulationSession::GetProgramId(env, jprogramId); const auto program_id = FileSys::GetBaseTitleID(EmulationSession::GetProgramId(env, jprogramId));
auto& disabledAddons = Settings::values.disabled_addons[program_id]; auto& disabledAddons = Settings::values.disabled_addons[program_id];
jobjectArray jdisabledAddonsArray = jobjectArray jdisabledAddonsArray =
env->NewObjectArray(disabledAddons.size(), Common::Android::GetStringClass(), env->NewObjectArray(disabledAddons.size(), Common::Android::GetStringClass(),
@@ -356,7 +338,7 @@ jobjectArray Java_org_yuzu_yuzu_1emu_utils_NativeConfig_getDisabledAddons(JNIEnv
void Java_org_yuzu_yuzu_1emu_utils_NativeConfig_setDisabledAddons(JNIEnv* env, jobject obj, void Java_org_yuzu_yuzu_1emu_utils_NativeConfig_setDisabledAddons(JNIEnv* env, jobject obj,
jstring jprogramId, jstring jprogramId,
jobjectArray jdisabledAddons) { jobjectArray jdisabledAddons) {
auto program_id = EmulationSession::GetProgramId(env, jprogramId); const auto program_id = FileSys::GetBaseTitleID(EmulationSession::GetProgramId(env, jprogramId));
Settings::values.disabled_addons[program_id].clear(); Settings::values.disabled_addons[program_id].clear();
std::vector<std::string> disabled_addons; std::vector<std::string> disabled_addons;
const int size = env->GetArrayLength(jdisabledAddons); const int size = env->GetArrayLength(jdisabledAddons);
@@ -21,7 +21,7 @@
#include "input_common/drivers/virtual_gamepad.h" #include "input_common/drivers/virtual_gamepad.h"
#include "native.h" #include "native.h"
boost::unordered::unordered_flat_map<std::string, std::unique_ptr<AndroidConfig>> map_profiles; ankerl::unordered_dense::map<std::string, std::unique_ptr<AndroidConfig>> map_profiles;
bool IsHandheldOnly() { bool IsHandheldOnly() {
const auto npad_style_set = const auto npad_style_set =
+1 -1
View File
@@ -241,7 +241,7 @@ if (lz4_ADDED)
target_include_directories(common PRIVATE ${lz4_SOURCE_DIR}/lib) target_include_directories(common PRIVATE ${lz4_SOURCE_DIR}/lib)
endif() endif()
target_link_libraries(common PUBLIC fmt::fmt stb::headers Threads::Threads) target_link_libraries(common PUBLIC fmt::fmt stb::headers Threads::Threads unordered_dense::unordered_dense)
target_link_libraries(common PRIVATE lz4::lz4 zstd::zstd) target_link_libraries(common PRIVATE lz4::lz4 zstd::zstd)
# Please refer to src/common/demangle.cpp # Please refer to src/common/demangle.cpp
+3 -4
View File
@@ -7,8 +7,7 @@
#include <algorithm> #include <algorithm>
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "common/assert.h" #include "common/assert.h"
#include "common/fs/fs.h" #include "common/fs/fs.h"
@@ -197,8 +196,8 @@ private:
SetLegacyPathImpl(legacy_path, new_path); SetLegacyPathImpl(legacy_path, new_path);
} }
boost::unordered::unordered_flat_map<EdenPath, fs::path> eden_paths; ankerl::unordered_dense::map<EdenPath, fs::path> eden_paths;
boost::unordered::unordered_flat_map<EmuPath, fs::path> legacy_paths; ankerl::unordered_dense::map<EmuPath, fs::path> legacy_paths;
}; };
bool ValidatePath(const fs::path& path) { bool ValidatePath(const fs::path& path) {
+2 -3
View File
@@ -7,8 +7,7 @@
#ifdef _WIN32 #ifdef _WIN32
#include <iterator> #include <iterator>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <boost/icl/separate_interval_set.hpp> #include <boost/icl/separate_interval_set.hpp>
#include <windows.h> #include <windows.h>
#include "common/dynamic_library.h" #include "common/dynamic_library.h"
@@ -392,7 +391,7 @@ private:
std::mutex placeholder_mutex; ///< Mutex for placeholders std::mutex placeholder_mutex; ///< Mutex for placeholders
boost::icl::separate_interval_set<size_t> placeholders; ///< Mapped placeholders boost::icl::separate_interval_set<size_t> placeholders; ///< Mapped placeholders
boost::unordered::unordered_flat_map<size_t, size_t> placeholder_host_pointers; ///< Placeholder backing offset ankerl::unordered_dense::map<size_t, size_t> placeholder_host_pointers; ///< Placeholder backing offset
}; };
#elif defined(__OPENORBIS__) || defined(__managarm__) #elif defined(__OPENORBIS__) || defined(__managarm__)
+2 -3
View File
@@ -9,8 +9,7 @@
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <string> #include <string>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include "common/logging.h" #include "common/logging.h"
@@ -413,7 +412,7 @@ public:
namespace Impl { namespace Impl {
template <typename InputDeviceType> template <typename InputDeviceType>
using FactoryListType = boost::unordered::unordered_flat_map<std::string, std::shared_ptr<Factory<InputDeviceType>>>; using FactoryListType = ankerl::unordered_dense::map<std::string, std::shared_ptr<Factory<InputDeviceType>>>;
template <typename InputDeviceType> template <typename InputDeviceType>
struct FactoryList { struct FactoryList {
+15 -27
View File
@@ -329,7 +329,7 @@ struct LogcatBackend : public Backend {
} }
}(); }();
auto const df = GetDirectFormatArgs(entry); auto const df = GetDirectFormatArgs(entry);
__android_log_print(android_log_priority, "YuzuNative", "%s %s:%u:%s: %s", df.class_name, entry.filename, entry.line_num, entry.function, entry.message); __android_log_print(android_log_priority, "YuzuNative", CCB_PRINTF_FMT, df.time_seconds, df.time_fractional, df.class_name, df.level_name, entry.filename, entry.line_num, entry.function, entry.message);
} }
void Flush() noexcept override {} void Flush() noexcept override {}
}; };
@@ -428,33 +428,21 @@ void FmtLogMessageImpl(Class log_class, Level log_level, const char* filename, u
auto const flush = ::Settings::values.log_flush_line.GetValue(); auto const flush = ::Settings::values.log_flush_line.GetValue();
char buffer[BUFSIZ]; char buffer[BUFSIZ];
auto result = fmt::vformat_to_n(buffer, sizeof(buffer) - 1, format, args); auto result = fmt::vformat_to_n(buffer, sizeof(buffer) - 1, format, args);
Entry e{ buffer[(std::min)(result.size, sizeof(buffer) - 1)] = '\0';
.message = nullptr, logging_instance->ForEachBackend([=](Backend& backend) {
.message_len = 0, backend.Write(Entry{
.timestamp = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - logging_instance->time_origin), .message = buffer,
.log_class = log_class, .message_len = (std::min)(result.size, sizeof(buffer) - 1),
.log_level = log_level, .timestamp = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - logging_instance->time_origin),
.filename = TrimSourcePath(filename), .log_class = log_class,
.function = function, .log_level = log_level,
.line_num = line_num, .filename = TrimSourcePath(filename),
}; .function = function,
if (result.size <= sizeof(buffer) - 1) { .line_num = line_num,
buffer[(std::min)(result.size, sizeof(buffer) - 1)] = '\0';
e.message = buffer;
e.message_len = (std::min)(result.size, sizeof(buffer) - 1);
logging_instance->ForEachBackend([=](Backend& backend) {
backend.Write(e);
if (flush) backend.Flush();
}); });
} else { if (flush)
std::string s = fmt::vformat(format, args); backend.Flush();
e.message = s.c_str(); });
e.message_len = s.size();
logging_instance->ForEachBackend([=](Backend& backend) {
backend.Write(e);
if (flush) backend.Flush();
});
}
} }
} }
} // namespace Common::Log } // namespace Common::Log
+4 -4
View File
@@ -11,14 +11,14 @@
namespace Common::Net { namespace Common::Net {
struct Asset { typedef struct {
std::string name; std::string name;
std::string url; std::string url;
std::string path; std::string path;
std::string filename; std::string filename;
}; } Asset;
struct Release { typedef struct Release {
std::string title; std::string title;
std::string body; std::string body;
std::string tag; std::string tag;
@@ -39,7 +39,7 @@ struct Release {
static std::optional<Release> FromJson(const std::string_view& json, const std::string &host, const std::string& repo); static std::optional<Release> FromJson(const std::string_view& json, const std::string &host, const std::string& repo);
static std::vector<Release> ListFromJson(const nlohmann::json &json, const std::string &host, const std::string &repo); static std::vector<Release> ListFromJson(const nlohmann::json &json, const std::string &host, const std::string &repo);
static std::vector<Release> ListFromJson(const std::string_view &json, const std::string &host, const std::string &repo); static std::vector<Release> ListFromJson(const std::string_view &json, const std::string &host, const std::string &repo);
}; } Release;
// Make a request via httplib, and return the response body if applicable. // Make a request via httplib, and return the response body if applicable.
std::optional<std::string> MakeRequest(const std::string &url, const std::string &path); std::optional<std::string> MakeRequest(const std::string &url, const std::string &path);
+2 -3
View File
@@ -8,15 +8,14 @@
#include <initializer_list> #include <initializer_list>
#include <string> #include <string>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
namespace Common { namespace Common {
/// A string-based key-value container supporting serializing to and deserializing from a string /// A string-based key-value container supporting serializing to and deserializing from a string
class ParamPackage { class ParamPackage {
public: public:
using DataType = boost::unordered::unordered_flat_map<std::string, std::string>; using DataType = ankerl::unordered_dense::map<std::string, std::string>;
ParamPackage() = default; ParamPackage() = default;
explicit ParamPackage(const std::string& serialized); explicit ParamPackage(const std::string& serialized);
+3 -3
View File
@@ -126,9 +126,9 @@ void LogSettings() {
setting->UsingGlobal() ? '-' : 'C', TranslateCategory(category), setting->UsingGlobal() ? '-' : 'C', TranslateCategory(category),
setting->GetLabel()); setting->GetLabel());
if (is_default) if (is_default)
settings_list.push_back(fmt::format("{}: {}", name, setting->Canonicalize())); settings_list.push_back(fmt::format("{}: {}\n", name, setting->Canonicalize()));
else else
settings_list.push_front(fmt::format("{}: {}", name, setting->Canonicalize())); settings_list.push_front(fmt::format("{}: {}\n", name, setting->Canonicalize()));
} }
} }
} }
@@ -146,7 +146,7 @@ void LogSettings() {
#undef LOG_PATH #undef LOG_PATH
} }
bool GetDebugKnobAt(u8 i) { bool getDebugKnobAt(u8 i) {
return (values.debug_knobs.GetValue() & (1 << (i & 0xF))) != 0; return (values.debug_knobs.GetValue() & (1 << (i & 0xF))) != 0;
} }
+2 -2
View File
@@ -904,7 +904,7 @@ struct Values {
0, 0,
65535, 65535,
"debug_knobs", "debug_knobs",
Category::System, Category::Debugging,
Specialization::Countable, Specialization::Countable,
true, true,
true}; true};
@@ -947,7 +947,7 @@ constexpr u32 MAX_FRAME_GEN_MULTIPLIER = 4;
[[nodiscard]] size_t FrameGenMaxGenerations(); [[nodiscard]] size_t FrameGenMaxGenerations();
bool GetDebugKnobAt(u8 i); bool getDebugKnobAt(u8 i);
void UpdateGPUAccuracy(); void UpdateGPUAccuracy();
bool IsGPULevelHigh(); bool IsGPULevelHigh();
+3 -4
View File
@@ -22,11 +22,10 @@
#endif #endif
// You must ensure this matches with src/common/x64/xbyak.h on root dir // You must ensure this matches with src/common/x64/xbyak.h on root dir
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <boost/unordered_map.hpp> #include <boost/unordered_map.hpp>
#define XBYAK_STD_UNORDERED_SET boost::unordered::unordered_flat_set #define XBYAK_STD_UNORDERED_SET ankerl::unordered_dense::set
#define XBYAK_STD_UNORDERED_MAP boost::unordered::unordered_flat_map #define XBYAK_STD_UNORDERED_MAP ankerl::unordered_dense::map
#define XBYAK_STD_UNORDERED_MULTIMAP boost::unordered_multimap #define XBYAK_STD_UNORDERED_MULTIMAP boost::unordered_multimap
#include <xbyak/xbyak.h> #include <xbyak/xbyak.h>
#include <xbyak/xbyak_util.h> #include <xbyak/xbyak_util.h>
+1 -2
View File
@@ -8,8 +8,7 @@
#include <atomic> #include <atomic>
#include <memory> #include <memory>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <dynarmic/interface/A64/a64.h> #include <dynarmic/interface/A64/a64.h>
#include <dynarmic/interface/code_page.h> #include <dynarmic/interface/code_page.h>
+2 -2
View File
@@ -4,7 +4,7 @@
#pragma once #pragma once
#include <span> #include <span>
#include <boost/container/flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <vector> #include <vector>
#include <oaknut/code_block.hpp> #include <oaknut/code_block.hpp>
#include <oaknut/oaknut.hpp> #include <oaknut/oaknut.hpp>
@@ -46,7 +46,7 @@ enum class PatchMode : u32 {
using ModuleTextAddress = u64; using ModuleTextAddress = u64;
using PatchTextAddress = u64; using PatchTextAddress = u64;
using EntryTrampolines = boost::container::flat_map<ModuleTextAddress, PatchTextAddress>; using EntryTrampolines = ankerl::unordered_dense::map<ModuleTextAddress, PatchTextAddress>;
class Patcher { class Patcher {
public: public:
+2 -1
View File
@@ -17,6 +17,7 @@
#include "common/string_util.h" #include "common/string_util.h"
#include "core/arm/exclusive_monitor.h" #include "core/arm/exclusive_monitor.h"
#include "core/core.h" #include "core/core.h"
#include "core/file_sys/common_funcs.h"
#include "launch_timestamp_cache.h" #include "launch_timestamp_cache.h"
#include "core/core_timing.h" #include "core/core_timing.h"
@@ -396,7 +397,7 @@ struct System::Impl {
LOG_ERROR(Core, "Failed to find program id for ROM"); LOG_ERROR(Core, "Failed to find program id for ROM");
} }
GameSettings::LoadOverrides(program_id, gpu_core->Renderer()); GameSettings::LoadOverrides(FileSys::GetBaseTitleID(program_id), gpu_core->Renderer());
if (auto room_member = Network::GetRoomMember().lock()) { if (auto room_member = Network::GetRoomMember().lock()) {
Network::GameInfo game_info; Network::GameInfo game_info;
game_info.name = name; game_info.name = name;
+233 -161
View File
@@ -3,13 +3,10 @@
#include <algorithm> #include <algorithm>
#include <cstring> #include <cstring>
#include <map>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <utility> #include <utility>
#include <span>
#include <cctype>
#include <boost/unordered/unordered_flat_map.hpp>
#include <boost/unordered/unordered_flat_set.hpp>
#include "common/hex_util.h" #include "common/hex_util.h"
#include "common/logging.h" #include "common/logging.h"
@@ -25,30 +22,61 @@ enum class IPSFileType {
Error, Error,
}; };
static IPSFileType IdentifyMagic(std::span<const u8> magic) { constexpr std::array<std::pair<const char*, const char*>, 11> ESCAPE_CHARACTER_MAP{{
if (magic.size() >= 5) { {"\\a", "\a"},
if (std::memcmp(magic.data(), "PATCH", 5) == 0) {"\\b", "\b"},
return IPSFileType::IPS; {"\\f", "\f"},
if (std::memcmp(magic.data(), "IPS32", 5) == 0) {"\\n", "\n"},
return IPSFileType::IPS32; {"\\r", "\r"},
{"\\t", "\t"},
{"\\v", "\v"},
{"\\\\", "\\"},
{"\\\'", "\'"},
{"\\\"", "\""},
{"\\\?", "\?"},
}};
static IPSFileType IdentifyMagic(const std::vector<u8>& magic) {
if (magic.size() != 5) {
return IPSFileType::Error;
} }
static constexpr std::array<u8, 5> patch_magic{{'P', 'A', 'T', 'C', 'H'}};
if (std::equal(magic.begin(), magic.end(), patch_magic.begin())) {
return IPSFileType::IPS;
}
static constexpr std::array<u8, 5> ips32_magic{{'I', 'P', 'S', '3', '2'}};
if (std::equal(magic.begin(), magic.end(), ips32_magic.begin())) {
return IPSFileType::IPS32;
}
return IPSFileType::Error; return IPSFileType::Error;
} }
static bool IsEOF(IPSFileType type, std::span<const u8> magic) { static bool IsEOF(IPSFileType type, const std::vector<u8>& data) {
return (type == IPSFileType::IPS && magic.size() > 3 && std::memcmp(magic.data(), "EOF", 3) == 0) static constexpr std::array<u8, 3> eof{{'E', 'O', 'F'}};
|| (type == IPSFileType::IPS32 && magic.size() > 4 && std::memcmp(magic.data(), "EEOF", 4) == 0); if (type == IPSFileType::IPS && std::equal(data.begin(), data.end(), eof.begin())) {
return true;
}
static constexpr std::array<u8, 4> eeof{{'E', 'E', 'O', 'F'}};
return type == IPSFileType::IPS32 && std::equal(data.begin(), data.end(), eeof.begin());
} }
VirtualFile PatchIPS(const VirtualFile& in, const VirtualFile& ips) { VirtualFile PatchIPS(const VirtualFile& in, const VirtualFile& ips) {
if (in == nullptr || ips == nullptr) if (in == nullptr || ips == nullptr)
return nullptr; return nullptr;
auto in_data = in->ReadAllBytes(); const auto type = IdentifyMagic(ips->ReadBytes(0x5));
auto const type = IdentifyMagic(in_data);
if (type == IPSFileType::Error) if (type == IPSFileType::Error)
return nullptr; return nullptr;
auto in_data = in->ReadAllBytes();
if (in_data.size() == 0) {
return nullptr;
}
std::vector<u8> temp(type == IPSFileType::IPS ? 3 : 4); std::vector<u8> temp(type == IPSFileType::IPS ? 3 : 4);
u64 offset = 5; // After header u64 offset = 5; // After header
while (ips->Read(temp.data(), temp.size(), offset) == temp.size()) { while (ips->Read(temp.data(), temp.size(), offset) == temp.size()) {
@@ -57,9 +85,12 @@ VirtualFile PatchIPS(const VirtualFile& in, const VirtualFile& ips) {
break; break;
} }
u32 real_offset = (type == IPSFileType::IPS32) u32 real_offset{};
? ((temp[0] << 24) | (temp[1] << 16) | (temp[2] << 8) | temp[3]) if (type == IPSFileType::IPS32)
: ((temp[0] << 16) | (temp[1] << 8) | temp[2]); real_offset = (temp[0] << 24) | (temp[1] << 16) | (temp[2] << 8) | temp[3];
else
real_offset = (temp[0] << 16) | (temp[1] << 8) | temp[2];
if (real_offset > in_data.size()) { if (real_offset > in_data.size()) {
return nullptr; return nullptr;
} }
@@ -82,35 +113,34 @@ VirtualFile PatchIPS(const VirtualFile& in, const VirtualFile& ips) {
return nullptr; return nullptr;
if (real_offset + rle_size > in_data.size()) if (real_offset + rle_size > in_data.size())
rle_size = u16(in_data.size() - real_offset); rle_size = static_cast<u16>(in_data.size() - real_offset);
std::memset(in_data.data() + real_offset, *data, rle_size); std::memset(in_data.data() + real_offset, *data, rle_size);
} else { // Standard Patch } else { // Standard Patch
auto read = data_size; auto read = data_size;
if (real_offset + read > in_data.size()) if (real_offset + read > in_data.size())
read = u16(in_data.size() - real_offset); read = static_cast<u16>(in_data.size() - real_offset);
if (ips->Read(in_data.data() + real_offset, read, offset) != data_size) if (ips->Read(in_data.data() + real_offset, read, offset) != data_size)
return nullptr; return nullptr;
offset += data_size; offset += data_size;
} }
} }
if (IsEOF(type, temp)) {
return std::make_shared<VectorVfsFile>(std::move(in_data), in->GetName(), in->GetContainingDirectory()); if (!IsEOF(type, temp)) {
return nullptr;
} }
return nullptr;
return std::make_shared<VectorVfsFile>(std::move(in_data), in->GetName(),
in->GetContainingDirectory());
} }
struct IPSwitchRecord {
std::array<uint8_t, 256 - sizeof(size_t)> data;
size_t count;
};
struct IPSwitchCompiler::IPSwitchPatch { struct IPSwitchCompiler::IPSwitchPatch {
boost::unordered::unordered_flat_map<u32, IPSwitchRecord> records; std::string name;
bool enabled; bool enabled;
std::map<u32, std::vector<u8>> records;
}; };
IPSwitchCompiler::IPSwitchCompiler(VirtualFile patch_text_) : patch_text(std::move(patch_text_)) { IPSwitchCompiler::IPSwitchCompiler(VirtualFile patch_text_) : patch_text(std::move(patch_text_)) {
Parse(patch_text->ReadAllBytes()); Parse();
} }
IPSwitchCompiler::~IPSwitchCompiler() = default; IPSwitchCompiler::~IPSwitchCompiler() = default;
@@ -119,159 +149,201 @@ std::array<u8, 32> IPSwitchCompiler::GetBuildID() const {
return nso_build_id; return nso_build_id;
} }
static IPSwitchRecord EscapeStringSequences(std::string_view sv) { bool IPSwitchCompiler::IsValid() const {
IPSwitchRecord r{}; return valid;
for (auto it = sv.cbegin(); it != sv.cend(); ) { }
if (*it == '\\' && it + 1 < sv.cend()) {
switch (it[1]) { static bool StartsWith(std::string_view base, std::string_view check) {
case 'n': r.data[r.count] = '\n'; break; return base.size() >= check.size() && base.substr(0, check.size()) == check;
case 't': r.data[r.count] = '\t'; break; }
case 'b': r.data[r.count] = '\b'; break;
case 'r': r.data[r.count] = '\r'; break; static std::string EscapeStringSequences(std::string in) {
case 'e': r.data[r.count] = '\e'; break; for (const auto& seq : ESCAPE_CHARACTER_MAP) {
case 'v': r.data[r.count] = '\v'; break; for (auto index = in.find(seq.first); index != std::string::npos;
case '?': r.data[r.count] = '\?'; break; index = in.find(seq.first, index)) {
default: r.data[r.count] = it[1]; break; in.replace(index, std::strlen(seq.first), seq.second);
} index += std::strlen(seq.second);
++r.count;
it += 2;
} else {
++r.count;
++it;
} }
} }
return r;
return in;
} }
[[nodiscard]] static inline std::array<u8, 32> ReadNSOBuildId(std::string_view const s) { void IPSwitchCompiler::ParseFlag(const std::string& line) {
std::array<u8, 32> r{}; if (StartsWith(line, "@flag offset_shift ")) {
for (std::size_t i = 0; i < s.size(); ++i) // Offset Shift Flag
r[i / 2] |= u8(u8(Common::ToHexNibble(s[i])) << u8((i % 2) * 4)); offset_shift = std::strtoll(line.substr(19).c_str(), nullptr, 0);
return r; } else if (StartsWith(line, "@little-endian")) {
// Set values to read as little endian
is_little_endian = true;
} else if (StartsWith(line, "@big-endian")) {
// Set values to read as big endian
is_little_endian = false;
} else if (StartsWith(line, "@flag print_values")) {
// Force printing of applied values
print_values = true;
}
} }
void IPSwitchCompiler::Parse(std::span<u8 const> bytes) { void IPSwitchCompiler::Parse() {
LOG_INFO(Loader, "IPSwitchCompiler: '{}'", patch_text->GetName()); const auto bytes = patch_text->ReadAllBytes();
bool is_little_endian = false; std::stringstream s;
s64 offset_shift = 0; s.write(reinterpret_cast<const char*>(bytes.data()), bytes.size());
//bool print_values = false;
auto const parse_line = [&](std::string_view const line) { std::vector<std::string> lines;
// Keep in mind lines have trimmed spaces (at the end & start)! std::string stream_line;
LOG_INFO(Loader, "<{}>", line); while (std::getline(s, stream_line)) {
if (line.starts_with("@stop")) { // Remove a trailing \r
return false; // Force stop if (!stream_line.empty() && stream_line.back() == '\r')
} else if (line.starts_with("@nsobid-")) { // NSO Build ID Specifier stream_line.pop_back();
nso_build_id = ReadNSOBuildId(line.substr(8)); lines.push_back(std::move(stream_line));
} else if (line.starts_with("@enabled")) { }
patches.push_back({{}, true}); //enabled patch
} else if (line.starts_with("@disabled")) {
patches.push_back({{}, false}); //disabled patch
} else if (line.starts_with("@flag offset_shift ")) {
offset_shift = std::strtoll(line.data() + 19, nullptr, 0); // Offset Shift Flag
} else if (line.starts_with("@little-endian")) {
is_little_endian = true; // Set values to read as little endian
} else if (line.starts_with("@big-endian")) {
is_little_endian = false; // Set values to read as big endian
} else if (line.starts_with("@flag print_values")) {
//print_values = true; // Force printing of applied values
} else if (line.starts_with("@")) {
LOG_WARNING(Loader, "Unknown flag {}", line);
} else {
size_t offset = size_t(std::strtoul(line.data(), nullptr, 16));
offset += size_t(offset_shift);
if (auto const first_quote = line.find_first_of("\"\'"); first_quote != std::string::npos) {
// string replacement
char quote = line[first_quote];
auto const start = line.cbegin() + first_quote + 1;
auto end = start;
for (; end < line.cend() && *end != quote; )
end += (*end == '\\') ? 2 : 1;
if (start <= line.cend() && end <= line.cend()) {
LOG_INFO(Loader, "[S] value @ {:#08X} ", offset);
patches.back().records.insert_or_assign(u32(offset), EscapeStringSequences({start, end}));
} else {
LOG_WARNING(Loader, "invalid string");
}
} else if (auto const first_space = line.find_last_of(" /\t\r\n"); first_space != std::string::npos) {
IPSwitchRecord r{}; // hex replacement
auto const start = line.cbegin() + first_space + 1;
auto const end = line.cend();
if (start <= line.cend() && end <= line.cend()) {
auto const hs = Common::HexStringToVector({start, end}, is_little_endian);
std::memcpy(r.data.data(), hs.data(), hs.size());
r.count = hs.size();
LOG_INFO(Loader, "[H] value @ {:#08X}", offset);
patches.back().records.insert_or_assign(u32(offset), std::move(r));
} else {
LOG_WARNING(Loader, "invalid line");
}
} else {
LOG_WARNING(Loader, "unhandled line!");
}
}
return true; //continue
};
for (auto it = bytes.begin(); it < bytes.end(); ) { for (std::size_t i = 0; i < lines.size(); ++i) {
auto const start = it; auto line = lines[i];
auto end = start;
for (; end < bytes.end() && *end != '\n' && *end != '\r'; ++end) // Remove midline comments
; std::size_t comment_index = std::string::npos;
it = end + 1; //prepare for next line bool within_string = false;
std::string_view const sline{ for (std::size_t k = 0; k < line.size(); ++k) {
reinterpret_cast<const char*>(bytes.data() + std::distance(bytes.begin(), start)), if (line[k] == '\"' && (k > 0 && line[k - 1] != '\\')) {
size_t(std::distance(start, end)) within_string = !within_string;
}; } else if (line[k] == '\\' && (k < line.size() - 1 && line[k + 1] == '\\')) {
if (sline.size() > 0) { comment_index = k;
auto p = sline.cbegin();
// skip space off line
for (; p < sline.cend() && std::isspace(*p); ++p)
;
// now make a nominal preprocessed line: remove comments
char quote = '\0';
auto const sline_start = p;
for (; p < sline.cend(); ) {
if ((!quote && p + 1 < sline.cend() && p[0] == '/' && p[1] == '/')
|| (!quote && p[0] == '#')) {
break;
} else if (p[0] == '\"' || p[0] == '\'') {
quote = (p[0] == quote) ? '\0' : p[0];
++p;
} else if (p + 1 < sline.cend() && p[0] == '\\') {
p += 2;
} else {
++p;
}
}
// now we have the preprocessed string ;)
std::string_view pp_str(sline_start, p);
if (pp_str.size() > 0 && !parse_line(pp_str)) {
break; break;
} }
} }
if (!StartsWith(line, "//") && comment_index != std::string::npos) {
last_comment = line.substr(comment_index + 2);
line = line.substr(0, comment_index);
}
if (StartsWith(line, "@stop")) {
// Force stop
break;
} else if (StartsWith(line, "@nsobid-")) {
// NSO Build ID Specifier
const auto raw_build_id = fmt::format("{:0<64}", line.substr(8));
nso_build_id = Common::HexStringToArray<0x20>(raw_build_id);
} else if (StartsWith(line, "#")) {
// Mandatory Comment
LOG_INFO(Loader, "[IPSwitchCompiler ('{}')] Forced output comment: {}",
patch_text->GetName(), line.substr(1));
} else if (StartsWith(line, "//")) {
// Normal Comment
last_comment = line.substr(2);
if (last_comment.find_first_not_of(' ') == std::string::npos)
continue;
if (last_comment.find_first_not_of(' ') != 0)
last_comment = last_comment.substr(last_comment.find_first_not_of(' '));
} else if (StartsWith(line, "@enabled") || StartsWith(line, "@disabled")) {
// Start of patch
const auto enabled = StartsWith(line, "@enabled");
if (i == 0)
return;
LOG_INFO(Loader, "[IPSwitchCompiler ('{}')] Parsing patch '{}' ({})",
patch_text->GetName(), last_comment, line.substr(1));
IPSwitchPatch patch{last_comment, enabled, {}};
// Read rest of patch
while (true) {
if (i + 1 >= lines.size()) {
break;
}
const auto& patch_line = lines[++i];
// Patch line may contain comments
if (StartsWith(patch_line, "//") || StartsWith(patch_line, "#")) {
continue;
}
// Start of new patch
if (StartsWith(patch_line, "@enabled") || StartsWith(patch_line, "@disabled")) {
--i;
break;
}
// Check for a flag
if (StartsWith(patch_line, "@")) {
ParseFlag(patch_line);
continue;
}
// 11 - 8 hex digit offset + space + minimum two digit overwrite val
if (patch_line.length() < 11)
break;
auto offset = std::strtoul(patch_line.substr(0, 8).c_str(), nullptr, 16);
offset += static_cast<unsigned long>(offset_shift);
std::vector<u8> replace;
// 9 - first char of replacement val
if (patch_line[9] == '\"') {
// string replacement
auto end_index = patch_line.find('\"', 10);
if (end_index == std::string::npos || end_index < 10)
return;
while (patch_line[end_index - 1] == '\\') {
end_index = patch_line.find('\"', end_index + 1);
if (end_index == std::string::npos || end_index < 10)
return;
}
auto value = patch_line.substr(10, end_index - 10);
value = EscapeStringSequences(value);
replace.reserve(value.size());
std::copy(value.begin(), value.end(), std::back_inserter(replace));
} else {
// hex replacement
const auto value =
patch_line.substr(9, patch_line.find_first_of(" /\r\n", 9) - 9);
replace = Common::HexStringToVector(value, is_little_endian);
}
if (print_values) {
LOG_INFO(Loader,
"[IPSwitchCompiler ('{}')] - Patching value at offset {:#08x} "
"with byte string '{}'",
patch_text->GetName(), offset, Common::HexToString(replace));
}
patch.records.insert_or_assign(static_cast<u32>(offset), std::move(replace));
}
patches.push_back(std::move(patch));
} else if (StartsWith(line, "@")) {
ParseFlag(line);
}
} }
valid = true;
} }
VirtualFile IPSwitchCompiler::Apply(const VirtualFile& in) const { VirtualFile IPSwitchCompiler::Apply(const VirtualFile& in) const {
if (in == nullptr) if (in == nullptr || !valid)
return nullptr; return nullptr;
auto in_data = in->ReadAllBytes(); auto in_data = in->ReadAllBytes();
for (const auto& patch : patches) { for (const auto& patch : patches) {
if (patch.enabled) { if (!patch.enabled)
for (const auto& record : patch.records) { continue;
if (record.first < in_data.size()) {
auto replace_size = record.second.count; for (const auto& record : patch.records) {
if (record.first + replace_size > in_data.size()) if (record.first >= in_data.size())
replace_size = in_data.size() - record.first; continue;
std::memcpy(in_data.data() + record.first, record.second.data.data(), replace_size); auto replace_size = record.second.size();
} if (record.first + replace_size > in_data.size())
} replace_size = in_data.size() - record.first;
for (std::size_t i = 0; i < replace_size; ++i)
in_data[i + record.first] = record.second[i];
} }
} }
return std::make_shared<VectorVfsFile>(std::move(in_data), in->GetName(), in->GetContainingDirectory());
return std::make_shared<VectorVfsFile>(std::move(in_data), in->GetName(),
in->GetContainingDirectory());
} }
} // namespace FileSys } // namespace FileSys
+9 -5
View File
@@ -1,14 +1,11 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
#pragma once #pragma once
#include <array> #include <array>
#include <memory>
#include <vector> #include <vector>
#include <span>
#include "common/common_types.h" #include "common/common_types.h"
#include "core/file_sys/vfs/vfs.h" #include "core/file_sys/vfs/vfs.h"
@@ -23,17 +20,24 @@ public:
~IPSwitchCompiler(); ~IPSwitchCompiler();
std::array<u8, 0x20> GetBuildID() const; std::array<u8, 0x20> GetBuildID() const;
bool IsValid() const;
VirtualFile Apply(const VirtualFile& in) const; VirtualFile Apply(const VirtualFile& in) const;
private: private:
struct IPSwitchPatch; struct IPSwitchPatch;
void ParseFlag(const std::string& flag); void ParseFlag(const std::string& flag);
void Parse(std::span<u8 const> bytes); void Parse();
bool valid = false;
VirtualFile patch_text; VirtualFile patch_text;
std::vector<IPSwitchPatch> patches; std::vector<IPSwitchPatch> patches;
std::array<u8, 0x20> nso_build_id{}; std::array<u8, 0x20> nso_build_id{};
bool is_little_endian = false;
s64 offset_shift = 0;
bool print_values = false;
std::string last_comment = "";
}; };
} // namespace FileSys } // namespace FileSys
+141 -64
View File
@@ -161,7 +161,7 @@ std::string GetUpdateVersionStringFromSlot(const ContentProvider* provider, u64
PatchManager::PatchManager(u64 title_id_, PatchManager::PatchManager(u64 title_id_,
const Service::FileSystem::FileSystemController& fs_controller_, const Service::FileSystem::FileSystemController& fs_controller_,
const ContentProvider& content_provider_) const ContentProvider& content_provider_)
: title_id{title_id_}, fs_controller{fs_controller_}, content_provider{content_provider_} {} : title_id{title_id_}, application_id{GetBaseTitleID(title_id_)}, fs_controller{fs_controller_}, content_provider{content_provider_} {}
PatchManager::~PatchManager() = default; PatchManager::~PatchManager() = default;
@@ -169,13 +169,41 @@ u64 PatchManager::GetTitleID() const {
return title_id; return title_id;
} }
u64 PatchManager::GetUpdateTitleIDForContent() const {
const auto program_update_id = GetUpdateTitleID(title_id);
if (program_update_id == GetUpdateTitleID(application_id) || content_provider.HasEntry(program_update_id, ContentRecordType::Program)) {
return program_update_id;
}
return GetUpdateTitleID(application_id);
}
std::vector<VirtualDir> PatchManager::GetModificationLoadRoots() const {
std::vector<VirtualDir> roots;
roots.push_back(fs_controller.GetModificationLoadRoot(title_id));
if (application_id != title_id) {
roots.push_back(fs_controller.GetModificationLoadRoot(application_id));
}
std::erase(roots, nullptr);
return roots;
}
std::vector<VirtualDir> PatchManager::GetSDMCModificationLoadRoots() const {
std::vector<VirtualDir> roots;
roots.push_back(fs_controller.GetSDMCModificationLoadRoot(title_id));
if (application_id != title_id) {
roots.push_back(fs_controller.GetSDMCModificationLoadRoot(application_id));
}
std::erase(roots, nullptr);
return roots;
}
VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const { VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const {
LOG_INFO(Loader, "Patching ExeFS for title_id={:016X}", title_id); LOG_INFO(Loader, "Patching ExeFS for title_id={:016X}", title_id);
if (exefs == nullptr) if (exefs == nullptr)
return exefs; return exefs;
const auto& disabled = Settings::values.disabled_addons[title_id]; const auto& disabled = Settings::values.disabled_addons[application_id];
bool update_disabled = true; bool update_disabled = true;
std::optional<u32> enabled_version; std::optional<u32> enabled_version;
@@ -183,7 +211,7 @@ VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const {
bool checked_manual = false; bool checked_manual = false;
const auto* content_union = static_cast<const ContentProviderUnion*>(&content_provider); const auto* content_union = static_cast<const ContentProviderUnion*>(&content_provider);
const auto update_tid = GetUpdateTitleID(title_id); const auto update_tid = GetUpdateTitleIDForContent();
if (content_union) { if (content_union) {
// First, check ExternalContentProvider // First, check ExternalContentProvider
@@ -303,17 +331,21 @@ VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const {
} }
// LayeredExeFS // LayeredExeFS
const auto load_dir = fs_controller.GetModificationLoadRoot(title_id); const auto load_dirs = GetModificationLoadRoots();
const auto sdmc_load_dir = fs_controller.GetSDMCModificationLoadRoot(title_id); const auto sdmc_load_dirs = GetSDMCModificationLoadRoots();
std::vector<VirtualDir> patch_dirs = {sdmc_load_dir}; std::vector<VirtualDir> patch_dirs;
if (load_dir != nullptr) { for (const auto& sdmc_load_dir : sdmc_load_dirs) {
patch_dirs.push_back(sdmc_load_dir);
}
for (const auto& load_dir : load_dirs) {
const auto load_patch_dirs = load_dir->GetSubdirectories(); const auto load_patch_dirs = load_dir->GetSubdirectories();
patch_dirs.insert(patch_dirs.end(), load_patch_dirs.begin(), load_patch_dirs.end()); patch_dirs.insert(patch_dirs.end(), load_patch_dirs.begin(), load_patch_dirs.end());
} }
std::sort(patch_dirs.begin(), patch_dirs.end(), std::stable_sort(patch_dirs.begin(), patch_dirs.end(), [](const VirtualDir& l, const VirtualDir& r) {
[](const VirtualDir& l, const VirtualDir& r) { return l->GetName() < r->GetName(); }); return l->GetName() < r->GetName();
});
std::vector<VirtualDir> layers; std::vector<VirtualDir> layers;
layers.reserve(patch_dirs.size() + 1); layers.reserve(patch_dirs.size() + 1);
@@ -345,8 +377,9 @@ VirtualDir PatchManager::PatchExeFS(VirtualDir exefs) const {
return exefs; return exefs;
} }
std::vector<VirtualFile> PatchManager::CollectPatches(const std::vector<VirtualDir>& patch_dirs, const std::string& build_id) const { std::vector<VirtualFile> PatchManager::CollectPatches(const std::vector<VirtualDir>& patch_dirs,
const auto& disabled = Settings::values.disabled_addons[title_id]; const std::string& build_id) const {
const auto& disabled = Settings::values.disabled_addons[application_id];
const auto nso_build_id = fmt::format("{:0<64}", build_id); const auto nso_build_id = fmt::format("{:0<64}", build_id);
std::vector<VirtualFile> out; std::vector<VirtualFile> out;
@@ -360,11 +393,16 @@ std::vector<VirtualFile> PatchManager::CollectPatches(const std::vector<VirtualD
for (const auto& file : exefs_dir->GetFiles()) { for (const auto& file : exefs_dir->GetFiles()) {
if (file->GetExtension() == "ips") { if (file->GetExtension() == "ips") {
auto name = file->GetName(); auto name = file->GetName();
const auto this_build_id = fmt::format("{:0<64}", name.substr(0, name.find('.')));
const auto this_build_id =
fmt::format("{:0<64}", name.substr(0, name.find('.')));
if (nso_build_id == this_build_id) if (nso_build_id == this_build_id)
out.push_back(file); out.push_back(file);
} else if (file->GetExtension() == "pchtxt") { } else if (file->GetExtension() == "pchtxt") {
IPSwitchCompiler compiler{file}; IPSwitchCompiler compiler{file};
if (!compiler.IsValid())
continue;
const auto this_build_id = Common::HexToString(compiler.GetBuildID()); const auto this_build_id = Common::HexToString(compiler.GetBuildID());
if (nso_build_id == this_build_id) if (nso_build_id == this_build_id)
out.push_back(file); out.push_back(file);
@@ -372,6 +410,7 @@ std::vector<VirtualFile> PatchManager::CollectPatches(const std::vector<VirtualD
} }
} }
} }
return out; return out;
} }
@@ -405,15 +444,20 @@ std::vector<u8> PatchManager::PatchNSO(const std::vector<u8>& nso, const std::st
LOG_INFO(Loader, "Patching NSO for name={}, build_id={}", name, build_id); LOG_INFO(Loader, "Patching NSO for name={}, build_id={}", name, build_id);
const auto load_dir = fs_controller.GetModificationLoadRoot(title_id); const auto load_dirs = GetModificationLoadRoots();
if (load_dir == nullptr) { if (load_dirs.empty()) {
LOG_ERROR(Loader, "Cannot load mods for invalid title_id={:016X}", title_id); LOG_ERROR(Loader, "Cannot load mods for invalid title_id={:016X}", title_id);
return nso; return nso;
} }
auto patch_dirs = load_dir->GetSubdirectories(); std::vector<VirtualDir> patch_dirs;
std::sort(patch_dirs.begin(), patch_dirs.end(), for (const auto& load_dir : load_dirs) {
[](const VirtualDir& l, const VirtualDir& r) { return l->GetName() < r->GetName(); }); const auto load_patch_dirs = load_dir->GetSubdirectories();
patch_dirs.insert(patch_dirs.end(), load_patch_dirs.begin(), load_patch_dirs.end());
}
std::stable_sort(patch_dirs.begin(), patch_dirs.end(), [](const VirtualDir& l, const VirtualDir& r) {
return l->GetName() < r->GetName();
});
const auto patches = CollectPatches(patch_dirs, build_id); const auto patches = CollectPatches(patch_dirs, build_id);
auto out = nso; auto out = nso;
@@ -448,29 +492,39 @@ bool PatchManager::HasNSOPatch(const BuildID& build_id_, std::string_view name)
LOG_INFO(Loader, "Querying NSO patch existence for build_id={}, name={}", build_id, name); LOG_INFO(Loader, "Querying NSO patch existence for build_id={}, name={}", build_id, name);
const auto load_dir = fs_controller.GetModificationLoadRoot(title_id); const auto load_dirs = GetModificationLoadRoots();
if (load_dir == nullptr) { if (load_dirs.empty()) {
LOG_ERROR(Loader, "Cannot load mods for invalid title_id={:016X}", title_id); LOG_ERROR(Loader, "Cannot load mods for invalid title_id={:016X}", title_id);
return false; return false;
} }
auto patch_dirs = load_dir->GetSubdirectories(); std::vector<VirtualDir> patch_dirs;
std::sort(patch_dirs.begin(), patch_dirs.end(), for (const auto& load_dir : load_dirs) {
[](const VirtualDir& l, const VirtualDir& r) { return l->GetName() < r->GetName(); }); const auto load_patch_dirs = load_dir->GetSubdirectories();
patch_dirs.insert(patch_dirs.end(), load_patch_dirs.begin(), load_patch_dirs.end());
}
std::stable_sort(patch_dirs.begin(), patch_dirs.end(), [](const VirtualDir& l, const VirtualDir& r) {
return l->GetName() < r->GetName();
});
return !CollectPatches(patch_dirs, build_id).empty(); return !CollectPatches(patch_dirs, build_id).empty();
} }
std::vector<Core::Memory::CheatEntry> PatchManager::CreateCheatList(const BuildID& build_id_) const { std::vector<Core::Memory::CheatEntry> PatchManager::CreateCheatList(const BuildID& build_id_) const {
const auto load_dir = fs_controller.GetModificationLoadRoot(title_id); const auto load_dirs = GetModificationLoadRoots();
if (load_dir == nullptr) { if (load_dirs.empty()) {
LOG_ERROR(Loader, "Cannot load mods for invalid title_id={:016X}", title_id); LOG_ERROR(Loader, "Cannot load mods for invalid title_id={:016X}", title_id);
return {}; return {};
} }
const auto& disabled = Settings::values.disabled_addons[title_id]; const auto& disabled = Settings::values.disabled_addons[application_id];
auto patch_dirs = load_dir->GetSubdirectories(); std::vector<VirtualDir> patch_dirs;
std::sort(patch_dirs.begin(), patch_dirs.end(), [](auto const& l, auto const& r) { return l->GetName() < r->GetName(); }); for (const auto& load_dir : load_dirs) {
const auto load_patch_dirs = load_dir->GetSubdirectories();
patch_dirs.insert(patch_dirs.end(), load_patch_dirs.begin(), load_patch_dirs.end());
}
std::stable_sort(patch_dirs.begin(), patch_dirs.end(),
[](auto const& l, auto const& r) { return l->GetName() < r->GetName(); });
// <mod dir> / <folder> / cheats / <build id>.txt // <mod dir> / <folder> / cheats / <build id>.txt
std::vector<Core::Memory::CheatEntry> out; std::vector<Core::Memory::CheatEntry> out;
@@ -486,39 +540,52 @@ std::vector<Core::Memory::CheatEntry> PatchManager::CreateCheatList(const BuildI
} }
// Uncareless user-friendly loading of patches (must start with 'cheat_') // Uncareless user-friendly loading of patches (must start with 'cheat_')
// <mod dir> / <cheat file>.txt // <mod dir> / <cheat file>.txt
for (auto const& f : load_dir->GetFiles()) { for (const auto& load_dir : load_dirs) {
auto const name = f->GetName(); for (auto const& f : load_dir->GetFiles()) {
if (name.starts_with("cheat_") && std::find(disabled.cbegin(), disabled.cend(), name) == disabled.cend()) { auto const name = f->GetName();
std::vector<u8> data(f->GetSize()); if (name.starts_with("cheat_") && std::find(disabled.cbegin(), disabled.cend(), name) == disabled.cend()) {
if (f->Read(data.data(), data.size()) == data.size()) { std::vector<u8> data(f->GetSize());
const Core::Memory::TextCheatParser parser; if (f->Read(data.data(), data.size()) == data.size()) {
auto const res = parser.Parse(std::string_view(reinterpret_cast<const char*>(data.data()), data.size())); const Core::Memory::TextCheatParser parser;
std::copy(res.begin(), res.end(), std::back_inserter(out)); auto const res = parser.Parse(std::string_view(reinterpret_cast<const char*>(data.data()), data.size()));
} else { std::copy(res.begin(), res.end(), std::back_inserter(out));
LOG_INFO(Common_Filesystem, "Failed to read cheats file for title_id={:016X}", title_id); } else {
LOG_INFO(Common_Filesystem, "Failed to read cheats file for title_id={:016X}", title_id);
}
} }
} }
} }
return out; return out;
} }
static void ApplyLayeredFS(VirtualFile& romfs, u64 title_id, ContentRecordType type, static void ApplyLayeredFS(VirtualFile& romfs, u64 title_id, u64 application_id, ContentRecordType type,
const Service::FileSystem::FileSystemController& fs_controller) { const Service::FileSystem::FileSystemController& fs_controller) {
const auto load_dir = fs_controller.GetModificationLoadRoot(title_id); std::vector<VirtualDir> load_dirs{fs_controller.GetModificationLoadRoot(title_id)};
const auto sdmc_load_dir = fs_controller.GetSDMCModificationLoadRoot(title_id); std::vector<VirtualDir> sdmc_load_dirs{fs_controller.GetSDMCModificationLoadRoot(title_id)};
if (application_id != title_id) {
load_dirs.push_back(fs_controller.GetModificationLoadRoot(application_id));
sdmc_load_dirs.push_back(fs_controller.GetSDMCModificationLoadRoot(application_id));
}
std::erase(load_dirs, nullptr);
std::erase(sdmc_load_dirs, nullptr);
if ((type != ContentRecordType::Program && type != ContentRecordType::Data && if ((type != ContentRecordType::Program && type != ContentRecordType::Data &&
type != ContentRecordType::HtmlDocument) || type != ContentRecordType::HtmlDocument) ||
(load_dir == nullptr && sdmc_load_dir == nullptr)) { (load_dirs.empty() && sdmc_load_dirs.empty())) {
return; return;
} }
const auto& disabled = Settings::values.disabled_addons[title_id]; const auto& disabled = Settings::values.disabled_addons[application_id];
std::vector<VirtualDir> patch_dirs = load_dir->GetSubdirectories(); std::vector<VirtualDir> patch_dirs;
if (std::find(disabled.cbegin(), disabled.cend(), "SDMC") == disabled.cend()) { for (const auto& load_dir : load_dirs) {
patch_dirs.push_back(sdmc_load_dir); const auto load_patch_dirs = load_dir->GetSubdirectories();
patch_dirs.insert(patch_dirs.end(), load_patch_dirs.begin(), load_patch_dirs.end());
} }
std::sort(patch_dirs.begin(), patch_dirs.end(), if (std::find(disabled.cbegin(), disabled.cend(), "SDMC") == disabled.cend()) {
[](const VirtualDir& l, const VirtualDir& r) { return l->GetName() < r->GetName(); }); patch_dirs.insert(patch_dirs.end(), sdmc_load_dirs.begin(), sdmc_load_dirs.end());
}
std::stable_sort(patch_dirs.begin(), patch_dirs.end(), [](const VirtualDir& l, const VirtualDir& r) {
return l->GetName() < r->GetName();
});
std::vector<VirtualDir> layers; std::vector<VirtualDir> layers;
std::vector<VirtualDir> layers_ext; std::vector<VirtualDir> layers_ext;
@@ -590,8 +657,8 @@ VirtualFile PatchManager::PatchRomFS(const NCA* base_nca, VirtualFile base_romfs
auto romfs = base_romfs; auto romfs = base_romfs;
// Game Updates // Game Updates
const auto update_tid = GetUpdateTitleID(title_id); const auto update_tid = GetUpdateTitleIDForContent();
const auto& disabled = Settings::values.disabled_addons[title_id]; const auto& disabled = Settings::values.disabled_addons[application_id];
bool update_disabled = true; bool update_disabled = true;
std::optional<u32> enabled_version; std::optional<u32> enabled_version;
@@ -698,7 +765,7 @@ VirtualFile PatchManager::PatchRomFS(const NCA* base_nca, VirtualFile base_romfs
// LayeredFS // LayeredFS
if (apply_layeredfs) { if (apply_layeredfs) {
ApplyLayeredFS(romfs, title_id, type, fs_controller); ApplyLayeredFS(romfs, title_id, application_id, type, fs_controller);
} }
return romfs; return romfs;
@@ -710,10 +777,10 @@ std::vector<Patch> PatchManager::GetPatches(VirtualFile update_raw) const {
} }
std::vector<Patch> out; std::vector<Patch> out;
const auto& disabled = Settings::values.disabled_addons[title_id]; const auto& disabled = Settings::values.disabled_addons[application_id];
// Game Updates // Game Updates
const auto update_tid = GetUpdateTitleID(title_id); const auto update_tid = GetUpdateTitleIDForContent();
std::vector<Patch> external_update_patches; std::vector<Patch> external_update_patches;
@@ -862,7 +929,7 @@ std::vector<Patch> PatchManager::GetPatches(VirtualFile update_raw) const {
.version = "", .version = "",
.type = PatchType::Update, .type = PatchType::Update,
.program_id = title_id, .program_id = title_id,
.title_id = title_id, .title_id = update_tid,
.source = PatchSource::Unknown, .source = PatchSource::Unknown,
.numeric_version = 0}; .numeric_version = 0};
@@ -888,8 +955,7 @@ std::vector<Patch> PatchManager::GetPatches(VirtualFile update_raw) const {
} }
// General Mods (LayeredFS and IPS) // General Mods (LayeredFS and IPS)
const auto mod_dir = fs_controller.GetModificationLoadRoot(title_id); for (const auto& mod_dir : GetModificationLoadRoots()) {
if (mod_dir != nullptr) {
for (auto const& f : mod_dir->GetFiles()) for (auto const& f : mod_dir->GetFiles())
if (auto const name = f->GetName(); name.starts_with("cheat_")) { if (auto const name = f->GetName(); name.starts_with("cheat_")) {
auto const mod_disabled = std::find(disabled.begin(), disabled.end(), name) != disabled.end(); auto const mod_disabled = std::find(disabled.begin(), disabled.end(), name) != disabled.end();
@@ -956,8 +1022,7 @@ std::vector<Patch> PatchManager::GetPatches(VirtualFile update_raw) const {
} }
// SDMC mod directory (RomFS LayeredFS) // SDMC mod directory (RomFS LayeredFS)
const auto sdmc_mod_dir = fs_controller.GetSDMCModificationLoadRoot(title_id); for (const auto& sdmc_mod_dir : GetSDMCModificationLoadRoots()) {
if (sdmc_mod_dir != nullptr) {
std::string types; std::string types;
if (IsDirValidAndNonEmpty(FindSubdirectoryCaseless(sdmc_mod_dir, "exefs"))) if (IsDirValidAndNonEmpty(FindSubdirectoryCaseless(sdmc_mod_dir, "exefs")))
AppendCommaIfNotEmpty(types, "LayeredExeFS"); AppendCommaIfNotEmpty(types, "LayeredExeFS");
@@ -992,10 +1057,10 @@ std::vector<Patch> PatchManager::GetPatches(VirtualFile update_raw) const {
dlc_match.reserve(dlc_entries_with_origin.size()); dlc_match.reserve(dlc_entries_with_origin.size());
for (const auto& [slot, entry] : dlc_entries_with_origin) { for (const auto& [slot, entry] : dlc_entries_with_origin) {
const auto base_tid = GetBaseTitleID(entry.title_id); const auto base_tid = GetBaseTitleID(entry.title_id);
const bool matches_base = base_tid == title_id; const bool matches_base = base_tid == application_id;
if (!matches_base) { if (!matches_base) {
LOG_DEBUG(Loader, "DLC {:016X} base {:016X} doesn't match title {:016X}", LOG_DEBUG(Loader, "DLC {:016X} base {:016X} doesn't match title {:016X}",
entry.title_id, base_tid, title_id); entry.title_id, base_tid, application_id);
continue; continue;
} }
@@ -1070,16 +1135,22 @@ std::vector<Patch> PatchManager::GetPatches(VirtualFile update_raw) const {
} }
std::optional<u32> PatchManager::GetGameVersion() const { std::optional<u32> PatchManager::GetGameVersion() const {
const auto update_tid = GetUpdateTitleID(title_id); const auto update_tid = GetUpdateTitleIDForContent();
if (content_provider.HasEntry(update_tid, ContentRecordType::Program)) { if (content_provider.HasEntry(update_tid, ContentRecordType::Program)) {
return content_provider.GetEntryVersion(update_tid); return content_provider.GetEntryVersion(update_tid);
} }
return content_provider.GetEntryVersion(title_id); if (const auto version = content_provider.GetEntryVersion(title_id); version.has_value()) {
return version;
}
return content_provider.GetEntryVersion(application_id);
} }
PatchManager::Metadata PatchManager::GetControlMetadata() const { PatchManager::Metadata PatchManager::GetControlMetadata() const {
const auto base_control_nca = content_provider.GetEntry(title_id, ContentRecordType::Control); auto base_control_nca = content_provider.GetEntry(title_id, ContentRecordType::Control);
if (base_control_nca == nullptr && application_id != title_id) {
base_control_nca = content_provider.GetEntry(application_id, ContentRecordType::Control);
}
if (base_control_nca == nullptr) { if (base_control_nca == nullptr) {
return {}; return {};
} }
@@ -1155,8 +1226,14 @@ PatchManager::Metadata PatchManager::ParseControlNCA(const NCA& nca) const {
auto metadata = pm.GetControlMetadata(); auto metadata = pm.GetControlMetadata();
if (metadata.first != nullptr) if (metadata.first != nullptr)
return metadata; return metadata;
const FileSys::PatchManager pm_update{FileSys::GetUpdateTitleID(application_id), system.GetFileSystemController(), system.GetContentProvider()}; const auto update_id = FileSys::GetUpdateTitleID(application_id);
return pm_update.GetControlMetadata(); const auto application_update_id = FileSys::GetUpdateTitleID(GetBaseTitleID(application_id));
const FileSys::PatchManager pm_update{update_id, system.GetFileSystemController(), system.GetContentProvider()};
metadata = pm_update.GetControlMetadata();
if (metadata.first != nullptr || update_id == application_update_id)
return metadata;
const FileSys::PatchManager pm_application_update{application_update_id, system.GetFileSystemController(), system.GetContentProvider()};
return pm_application_update.GetControlMetadata();
} }
} // namespace FileSys } // namespace FileSys
+5
View File
@@ -10,6 +10,7 @@
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <string> #include <string>
#include <vector>
#include "common/common_types.h" #include "common/common_types.h"
#include "core/file_sys/nca_metadata.h" #include "core/file_sys/nca_metadata.h"
#include "core/file_sys/vfs/vfs_types.h" #include "core/file_sys/vfs/vfs_types.h"
@@ -109,10 +110,14 @@ public:
[[nodiscard]] static PatchManager::Metadata GetMetadataFromBaseOrUpdate(Core::System& system, u64 application_id) noexcept; [[nodiscard]] static PatchManager::Metadata GetMetadataFromBaseOrUpdate(Core::System& system, u64 application_id) noexcept;
private: private:
[[nodiscard]] u64 GetUpdateTitleIDForContent() const;
[[nodiscard]] std::vector<VirtualDir> GetModificationLoadRoots() const;
[[nodiscard]] std::vector<VirtualDir> GetSDMCModificationLoadRoots() const;
[[nodiscard]] std::vector<VirtualFile> CollectPatches(const std::vector<VirtualDir>& patch_dirs, [[nodiscard]] std::vector<VirtualFile> CollectPatches(const std::vector<VirtualDir>& patch_dirs,
const std::string& build_id) const; const std::string& build_id) const;
u64 title_id; u64 title_id;
u64 application_id;
const Service::FileSystem::FileSystemController& fs_controller; const Service::FileSystem::FileSystemController& fs_controller;
const ContentProvider& content_provider; const ContentProvider& content_provider;
}; };
+1 -1
View File
@@ -566,7 +566,7 @@ VirtualFile RegisteredCache::GetFileAtID(NcaID id) const {
return file; return file;
} }
static std::optional<NcaID> CheckMapForContentRecord(const boost::unordered::unordered_flat_map<u64, CNMT>& map, u64 title_id, ContentRecordType type) { static std::optional<NcaID> CheckMapForContentRecord(const ankerl::unordered_dense::map<u64, CNMT>& map, u64 title_id, ContentRecordType type) {
auto cmnt_iter = map.find(title_id); auto cmnt_iter = map.find(title_id);
u8 id_offset = 0; u8 id_offset = 0;
+6 -5
View File
@@ -12,6 +12,7 @@
#include <optional> #include <optional>
#include <string> #include <string>
#include <vector> #include <vector>
#include <ankerl/unordered_dense.h>
#include <boost/container/flat_map.hpp> #include <boost/container/flat_map.hpp>
#include "common/common_types.h" #include "common/common_types.h"
#include "core/crypto/key_manager.h" #include "core/crypto/key_manager.h"
@@ -208,11 +209,11 @@ private:
ContentProviderParsingFunction parser; ContentProviderParsingFunction parser;
// maps tid -> NcaID of meta // maps tid -> NcaID of meta
boost::container::flat_map<u64, NcaID> meta_id; ankerl::unordered_dense::map<u64, NcaID> meta_id;
// maps tid -> meta // maps tid -> meta
boost::container::flat_map<u64, CNMT> meta; ankerl::unordered_dense::map<u64, CNMT> meta;
// maps tid -> meta for CNMT in yuzu_meta // maps tid -> meta for CNMT in yuzu_meta
boost::container::flat_map<u64, CNMT> yuzu_meta; ankerl::unordered_dense::map<u64, CNMT> yuzu_meta;
}; };
enum class ContentProviderUnionSlot { enum class ContentProviderUnionSlot {
@@ -312,8 +313,8 @@ private:
void ProcessXCI(const VirtualFile& file); void ProcessXCI(const VirtualFile& file);
std::vector<VirtualDir> load_dirs; std::vector<VirtualDir> load_dirs;
boost::container::flat_map<std::tuple<u64, ContentRecordType, TitleType>, VirtualFile> entries; ankerl::unordered_dense::map<std::tuple<u64, ContentRecordType, TitleType>, VirtualFile> entries;
boost::container::flat_map<u64, u32> versions; ankerl::unordered_dense::map<u64, u32> versions;
std::vector<ExternalUpdateEntry> multi_version_entries; std::vector<ExternalUpdateEntry> multi_version_entries;
}; };
+6 -3
View File
@@ -4,7 +4,9 @@
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
#include <boost/container/flat_set.hpp> #include <algorithm>
#include <set>
#include <ankerl/unordered_dense.h>
#include <utility> #include <utility>
#include "core/file_sys/vfs/vfs_layered.h" #include "core/file_sys/vfs/vfs_layered.h"
@@ -61,7 +63,7 @@ std::string LayeredVfsDirectory::GetFullPath() const {
std::vector<VirtualFile> LayeredVfsDirectory::GetFiles() const { std::vector<VirtualFile> LayeredVfsDirectory::GetFiles() const {
std::vector<VirtualFile> out; std::vector<VirtualFile> out;
boost::container::flat_set<std::string> out_names; ankerl::unordered_dense::set<std::string> out_names;
for (const auto& layer : dirs) { for (const auto& layer : dirs) {
for (auto& file : layer->GetFiles()) { for (auto& file : layer->GetFiles()) {
@@ -77,7 +79,8 @@ std::vector<VirtualFile> LayeredVfsDirectory::GetFiles() const {
std::vector<VirtualDir> LayeredVfsDirectory::GetSubdirectories() const { std::vector<VirtualDir> LayeredVfsDirectory::GetSubdirectories() const {
std::vector<VirtualDir> out; std::vector<VirtualDir> out;
boost::container::flat_set<std::string> out_names; ankerl::unordered_dense::set<std::string> out_names;
for (const auto& layer : dirs) { for (const auto& layer : dirs) {
for (const auto& sd : layer->GetSubdirectories()) { for (const auto& sd : layer->GetSubdirectories()) {
out_names.emplace(sd->GetName()); out_names.emplace(sd->GetName());
+2 -2
View File
@@ -78,7 +78,7 @@ private:
std::array<DebugWatchpoint, Core::Hardware::NUM_WATCHPOINTS> m_watchpoints{}; std::array<DebugWatchpoint, Core::Hardware::NUM_WATCHPOINTS> m_watchpoints{};
std::map<KProcessAddress, u64> m_debug_page_refcounts{}; std::map<KProcessAddress, u64> m_debug_page_refcounts{};
#ifdef HAS_NCE #ifdef HAS_NCE
boost::unordered::unordered_flat_map<u64, u64> m_post_handlers{}; ankerl::unordered_dense::map<u64, u64> m_post_handlers{};
#endif #endif
std::unique_ptr<Core::ExclusiveMonitor> m_exclusive_monitor; std::unique_ptr<Core::ExclusiveMonitor> m_exclusive_monitor;
Core::Memory::Memory m_memory; Core::Memory::Memory m_memory;
@@ -494,7 +494,7 @@ public:
static void Switch(KernelCore& kernel, KProcess* cur_process, KProcess* next_process); static void Switch(KernelCore& kernel, KProcess* cur_process, KProcess* next_process);
#ifdef HAS_NCE #ifdef HAS_NCE
boost::unordered::unordered_flat_map<u64, u64>& GetPostHandlers() noexcept { ankerl::unordered_dense::map<u64, u64>& GetPostHandlers() noexcept {
return m_post_handlers; return m_post_handlers;
} }
#endif #endif
+2 -2
View File
@@ -1216,7 +1216,7 @@ Result KServerSession::ReceiveRequest(KernelCore& kernel, uintptr_t server_messa
} }
Result KServerSession::SendReply(KernelCore& kernel, uintptr_t server_message, uintptr_t server_buffer_size, Result KServerSession::SendReply(KernelCore& kernel, uintptr_t server_message, uintptr_t server_buffer_size,
KPhysicalAddress server_message_paddr, bool is_hle, bool session_closed) { KPhysicalAddress server_message_paddr, bool is_hle) {
// Lock the session. // Lock the session.
KScopedLightLock lk{m_lock}; KScopedLightLock lk{m_lock};
@@ -1248,7 +1248,7 @@ Result KServerSession::SendReply(KernelCore& kernel, uintptr_t server_message, u
KEvent* event = request->GetEvent(); KEvent* event = request->GetEvent();
// Check whether we're closed. // Check whether we're closed.
const bool closed = (client_thread == nullptr || m_parent->IsClientClosed() || session_closed); const bool closed = (client_thread == nullptr || m_parent->IsClientClosed());
Result result = ResultSuccess; Result result = ResultSuccess;
if (!closed) { if (!closed) {
+3 -3
View File
@@ -54,14 +54,14 @@ public:
Result OnRequest(KernelCore& kernel, KSessionRequest* request); Result OnRequest(KernelCore& kernel, KSessionRequest* request);
Result SendReply(KernelCore& kernel, uintptr_t server_message, uintptr_t server_buffer_size, Result SendReply(KernelCore& kernel, uintptr_t server_message, uintptr_t server_buffer_size,
KPhysicalAddress server_message_paddr, bool is_hle = false, bool session_closed = false); KPhysicalAddress server_message_paddr, bool is_hle = false);
Result ReceiveRequest(KernelCore& kernel, uintptr_t server_message, uintptr_t server_buffer_size, Result ReceiveRequest(KernelCore& kernel, uintptr_t server_message, uintptr_t server_buffer_size,
KPhysicalAddress server_message_paddr, KPhysicalAddress server_message_paddr,
std::shared_ptr<Service::HLERequestContext>* out_context = nullptr, std::shared_ptr<Service::HLERequestContext>* out_context = nullptr,
std::weak_ptr<Service::SessionRequestManager> manager = {}); std::weak_ptr<Service::SessionRequestManager> manager = {});
Result SendReplyHLE(KernelCore& kernel, bool session_closed = false) { Result SendReplyHLE(KernelCore& kernel) {
R_RETURN(this->SendReply(kernel, 0, 0, 0, true, session_closed)); R_RETURN(this->SendReply(kernel, 0, 0, 0, true));
} }
Result ReceiveRequestHLE(KernelCore& kernel, std::shared_ptr<Service::HLERequestContext>* out_context, Result ReceiveRequestHLE(KernelCore& kernel, std::shared_ptr<Service::HLERequestContext>* out_context,
+3 -4
View File
@@ -10,8 +10,7 @@
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <thread> #include <thread>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <utility> #include <utility>
#include "common/assert.h" #include "common/assert.h"
@@ -793,8 +792,8 @@ struct KernelCore::Impl {
std::optional<KObjectNameGlobalData> object_name_global_data; std::optional<KObjectNameGlobalData> object_name_global_data;
boost::unordered::unordered_flat_set<KAutoObject*> registered_objects; ankerl::unordered_dense::set<KAutoObject*> registered_objects;
boost::unordered::unordered_flat_set<KAutoObject*> registered_in_use_objects; ankerl::unordered_dense::set<KAutoObject*> registered_in_use_objects;
std::mutex server_lock; std::mutex server_lock;
std::vector<std::unique_ptr<Service::ServerManager>> server_managers; std::vector<std::unique_ptr<Service::ServerManager>> server_managers;
+1 -2
View File
@@ -11,8 +11,7 @@
#include <list> #include <list>
#include <memory> #include <memory>
#include <string> #include <string>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <vector> #include <vector>
#include "common/polyfill_thread.h" #include "common/polyfill_thread.h"
+47 -3
View File
@@ -17,12 +17,56 @@
namespace Kernel::Svc { namespace Kernel::Svc {
constexpr auto MAX_MSG_TIME = std::chrono::milliseconds(250);
const auto MAX_MSG_SIZE = 0x1000;
/// Used to output a message on a debug hardware unit - does nothing on a retail unit /// Used to output a message on a debug hardware unit - does nothing on a retail unit
Result OutputDebugString(Core::System& system, u64 address, u64 len) { Result OutputDebugString(Core::System& system, u64 address, u64 len) {
static struct DebugFlusher {
std::string msg_buffer;
std::mutex msg_mutex;
std::condition_variable msg_cv;
std::chrono::steady_clock::time_point last_msg_time;
std::optional<std::jthread> thread;
} flusher_data;
R_SUCCEED_IF(len == 0); R_SUCCEED_IF(len == 0);
std::string msg_buffer(len, 0); // Only start the thread the very first time this function is called
GetCurrentMemory(system.Kernel()).ReadBlock(address, msg_buffer.data(), len); if (!flusher_data.thread) {
LOG_INFO(Debug_Emulated, "{}", msg_buffer); flusher_data.thread.emplace([](std::stop_token stop_token) {
while (!stop_token.stop_requested()) {
std::unique_lock lock(flusher_data.msg_mutex);
flusher_data.msg_cv.wait(lock, [&stop_token] {
return !flusher_data.msg_buffer.empty() || stop_token.stop_requested();
});
if (stop_token.stop_requested() && flusher_data.msg_buffer.empty())
break;
auto timeout = flusher_data.last_msg_time + MAX_MSG_TIME;
bool woke_early = flusher_data.msg_cv.wait_until(lock, timeout, [&stop_token] {
return flusher_data.msg_buffer.size() >= MAX_MSG_SIZE || stop_token.stop_requested();
});
if (!woke_early || flusher_data.msg_buffer.size() >= MAX_MSG_SIZE || stop_token.stop_requested()) {
if (!flusher_data.msg_buffer.empty()) {
// Remove trailing newline as LOG_INFO adds that anyways
if (flusher_data.msg_buffer.back() == '\n')
flusher_data.msg_buffer.pop_back();
LOG_INFO(Debug_Emulated, "\n{}", flusher_data.msg_buffer);
flusher_data.msg_buffer.clear();
}
if (stop_token.stop_requested()) break;
}
}
flusher_data.msg_cv.notify_all();
});
}
{
std::lock_guard lock(flusher_data.msg_mutex);
const auto old_size = flusher_data.msg_buffer.size();
flusher_data.msg_buffer.resize(old_size + len);
GetCurrentMemory(system.Kernel()).ReadBlock(address, flusher_data.msg_buffer.data() + old_size, len);
flusher_data.last_msg_time = std::chrono::steady_clock::now();
}
flusher_data.msg_cv.notify_one();
R_SUCCEED(); R_SUCCEED();
} }
@@ -7,8 +7,7 @@
#pragma once #pragma once
#include <array> #include <array>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <vector> #include <vector>
#include "common/common_funcs.h" #include "common/common_funcs.h"
@@ -177,6 +176,6 @@ struct WebCommonReturnValue {
}; };
static_assert(sizeof(WebCommonReturnValue) == 0x1010, "WebCommonReturnValue has incorrect size."); static_assert(sizeof(WebCommonReturnValue) == 0x1010, "WebCommonReturnValue has incorrect size.");
using WebArgInputTLVMap = boost::unordered::unordered_flat_map<WebArgInputTLVType, std::vector<u8>>; using WebArgInputTLVMap = ankerl::unordered_dense::map<WebArgInputTLVType, std::vector<u8>>;
} // namespace Service::AM::Frontend } // namespace Service::AM::Frontend
+11 -2
View File
@@ -6,6 +6,7 @@
#include <optional> #include <optional>
#include "core/core.h" #include "core/core.h"
#include "core/file_sys/common_funcs.h"
#include "core/file_sys/content_archive.h" #include "core/file_sys/content_archive.h"
#include "core/file_sys/nca_metadata.h" #include "core/file_sys/nca_metadata.h"
#include "core/file_sys/patch_manager.h" #include "core/file_sys/patch_manager.h"
@@ -104,8 +105,16 @@ std::unique_ptr<Process> CreateApplicationProcess(std::vector<u8>& out_control,
// TODO(DarkLordZach): When FSController/Game Card Support is added, if // TODO(DarkLordZach): When FSController/Game Card Support is added, if
// current_process_game_card use correct StorageId // current_process_game_card use correct StorageId
launch.base_game_storage_id = GetStorageIdForFrontendSlot(storage.GetSlotForEntry(launch.title_id, FileSys::ContentRecordType::Program)); auto base_slot = storage.GetSlotForEntry(launch.title_id, FileSys::ContentRecordType::Program);
launch.update_storage_id = GetStorageIdForFrontendSlot(storage.GetSlotForEntry(FileSys::GetUpdateTitleID(launch.title_id), FileSys::ContentRecordType::Program)); if (!base_slot) {
base_slot = storage.GetSlotForEntry(FileSys::GetBaseTitleID(launch.title_id), FileSys::ContentRecordType::Program);
}
launch.base_game_storage_id = GetStorageIdForFrontendSlot(base_slot);
auto update_slot = storage.GetSlotForEntry(FileSys::GetUpdateTitleID(launch.title_id), FileSys::ContentRecordType::Program);
if (!update_slot) {
update_slot = storage.GetSlotForEntry(FileSys::GetUpdateTitleID(FileSys::GetBaseTitleID(launch.title_id)), FileSys::ContentRecordType::Program);
}
launch.update_storage_id = GetStorageIdForFrontendSlot(update_slot);
system.GetARPManager().Register(launch.title_id, launch, out_control); system.GetARPManager().Register(launch.title_id, launch, out_control);
return process; return process;
@@ -158,7 +158,7 @@ Result IApplicationFunctions::EnsureSaveData(Out<u64> out_size, Common::UUID use
LOG_INFO(Service_AM, "called, uid={}", user_id.FormattedString()); LOG_INFO(Service_AM, "called, uid={}", user_id.FormattedString());
FileSys::SaveDataAttribute attribute{}; FileSys::SaveDataAttribute attribute{};
attribute.program_id = m_applet->program_id; attribute.program_id = FileSys::GetBaseTitleID(m_applet->program_id);
attribute.user_id = user_id.AsU128(); attribute.user_id = user_id.AsU128();
attribute.type = FileSys::SaveDataType::Account; attribute.type = FileSys::SaveDataType::Account;
@@ -238,7 +238,7 @@ Result IApplicationFunctions::ExtendSaveData(Out<u64> out_required_size, FileSys
static_cast<u8>(type), user_id.FormattedString(), normal_size, journal_size); static_cast<u8>(type), user_id.FormattedString(), normal_size, journal_size);
system.GetFileSystemController().OpenSaveDataController()->WriteSaveDataSize( system.GetFileSystemController().OpenSaveDataController()->WriteSaveDataSize(
type, m_applet->program_id, user_id.AsU128(), {normal_size, journal_size}); type, FileSys::GetBaseTitleID(m_applet->program_id), user_id.AsU128(), {normal_size, journal_size});
// The following value is used to indicate the amount of space remaining on failure // The following value is used to indicate the amount of space remaining on failure
// due to running out of space. Since we always succeed, this should be 0. // due to running out of space. Since we always succeed, this should be 0.
@@ -252,7 +252,7 @@ Result IApplicationFunctions::GetSaveDataSize(Out<u64> out_normal_size, Out<u64>
LOG_DEBUG(Service_AM, "called with type={} user_id={}", type, user_id.FormattedString()); LOG_DEBUG(Service_AM, "called with type={} user_id={}", type, user_id.FormattedString());
const auto size = system.GetFileSystemController().OpenSaveDataController()->ReadSaveDataSize( const auto size = system.GetFileSystemController().OpenSaveDataController()->ReadSaveDataSize(
type, m_applet->program_id, user_id.AsU128()); type, FileSys::GetBaseTitleID(m_applet->program_id), user_id.AsU128());
*out_normal_size = size.normal; *out_normal_size = size.normal;
*out_journal_size = size.journal; *out_journal_size = size.journal;
@@ -40,8 +40,8 @@ std::vector<u8> default_logo_small;
std::vector<u8> default_logo_large; std::vector<u8> default_logo_large;
bool default_logos_loaded = false; bool default_logos_loaded = false;
boost::unordered::unordered_flat_map<std::string, std::vector<u8>> news_images_small; ankerl::unordered_dense::map<std::string, std::vector<u8>> news_images_small;
boost::unordered::unordered_flat_map<std::string, std::vector<u8>> news_images_large; ankerl::unordered_dense::map<std::string, std::vector<u8>> news_images_large;
std::mutex images_mutex; std::mutex images_mutex;
@@ -12,8 +12,7 @@
#include <optional> #include <optional>
#include <span> #include <span>
#include <string> #include <string>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <vector> #include <vector>
#include "common/common_types.h" #include "common/common_types.h"
@@ -94,7 +93,7 @@ private:
static s64 Now(); static s64 Now();
mutable std::mutex mtx; mutable std::mutex mtx;
boost::unordered::unordered_flat_map<std::string, StoredNews> items; ankerl::unordered_dense::map<std::string, StoredNews> items;
size_t open_counter{}; size_t open_counter{};
}; };
+2 -3
View File
@@ -6,8 +6,7 @@
#pragma once #pragma once
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "common/fs/fs.h" #include "common/fs/fs.h"
#include "core/hle/result.h" #include "core/hle/result.h"
@@ -89,7 +88,7 @@ private:
AlbumFileDateTime ConvertToAlbumDateTime(u64 posix_time) const; AlbumFileDateTime ConvertToAlbumDateTime(u64 posix_time) const;
bool is_mounted{}; bool is_mounted{};
boost::unordered::unordered_flat_map<AlbumFileId, std::filesystem::path> album_files; ankerl::unordered_dense::map<AlbumFileId, std::filesystem::path> album_files;
Core::System& system; Core::System& system;
}; };
@@ -14,6 +14,7 @@
#include "core/core.h" #include "core/core.h"
#include "core/file_sys/bis_factory.h" #include "core/file_sys/bis_factory.h"
#include "core/file_sys/card_image.h" #include "core/file_sys/card_image.h"
#include "core/file_sys/common_funcs.h"
#include "core/file_sys/control_metadata.h" #include "core/file_sys/control_metadata.h"
#include "core/file_sys/errors.h" #include "core/file_sys/errors.h"
#include "core/file_sys/patch_manager.h" #include "core/file_sys/patch_manager.h"
@@ -227,13 +228,12 @@ Result VfsDirectoryServiceWrapper::RenameDirectory(const std::string& src_path_,
std::string src_path(Common::FS::SanitizePath(src_path_)); std::string src_path(Common::FS::SanitizePath(src_path_));
std::string dest_path(Common::FS::SanitizePath(dest_path_)); std::string dest_path(Common::FS::SanitizePath(dest_path_));
auto src = GetDirectoryRelativeWrapped(backing, src_path); auto src = GetDirectoryRelativeWrapped(backing, src_path);
if (src == nullptr)
return FileSys::ResultPathNotFound;
if (Common::FS::GetParentPath(src_path) == Common::FS::GetParentPath(dest_path)) { if (Common::FS::GetParentPath(src_path) == Common::FS::GetParentPath(dest_path)) {
std::string full_src_path = backing->GetFullPath() + "/" + src_path; // Use more-optimized vfs implementation rename.
std::string full_dest_path = backing->GetFullPath() + "/" + dest_path; if (src == nullptr)
if (!Common::FS::RenameDir(full_src_path, full_dest_path)) { return FileSys::ResultPathNotFound;
if (!src->Rename(Common::FS::GetFilename(dest_path))) {
// TODO(DarkLordZach): Find a better error code for this
return ResultUnknown; return ResultUnknown;
} }
return ResultSuccess; return ResultSuccess;
@@ -340,7 +340,7 @@ Result FileSystemController::RegisterProcess(
registrations.emplace(process_id, Registration{ registrations.emplace(process_id, Registration{
.program_id = program_id, .program_id = program_id,
.romfs_factory = std::move(romfs_factory), .romfs_factory = std::move(romfs_factory),
.save_data_factory = CreateSaveDataFactory(program_id), .save_data_factory = CreateSaveDataFactory(FileSys::GetBaseTitleID(program_id)),
}); });
LOG_DEBUG(Service_FS, "Registered for process {}", process_id); LOG_DEBUG(Service_FS, "Registered for process {}", process_id);
@@ -24,7 +24,7 @@ IFileSystem::IFileSystem(Core::System& system_, FileSys::VirtualDir dir_, SizeGe
{3, D<&IFileSystem::DeleteDirectory>, "DeleteDirectory"}, {3, D<&IFileSystem::DeleteDirectory>, "DeleteDirectory"},
{4, D<&IFileSystem::DeleteDirectoryRecursively>, "DeleteDirectoryRecursively"}, {4, D<&IFileSystem::DeleteDirectoryRecursively>, "DeleteDirectoryRecursively"},
{5, D<&IFileSystem::RenameFile>, "RenameFile"}, {5, D<&IFileSystem::RenameFile>, "RenameFile"},
{6, D<&IFileSystem::RenameDirectory>, "RenameDirectory"}, {6, nullptr, "RenameDirectory"},
{7, D<&IFileSystem::GetEntryType>, "GetEntryType"}, {7, D<&IFileSystem::GetEntryType>, "GetEntryType"},
{8, D<&IFileSystem::OpenFile>, "OpenFile"}, {8, D<&IFileSystem::OpenFile>, "OpenFile"},
{9, D<&IFileSystem::OpenDirectory>, "OpenDirectory"}, {9, D<&IFileSystem::OpenDirectory>, "OpenDirectory"},
@@ -88,14 +88,6 @@ Result IFileSystem::RenameFile(
R_RETURN(backend->RenameFile(FileSys::Path(old_path->str), FileSys::Path(new_path->str))); R_RETURN(backend->RenameFile(FileSys::Path(old_path->str), FileSys::Path(new_path->str)));
} }
Result IFileSystem::RenameDirectory(
const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> old_path,
const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> new_path) {
LOG_DEBUG(Service_FS, "called. directory '{}' to directory '{}'", old_path->str, new_path->str);
R_RETURN(backend->RenameDirectory(FileSys::Path(old_path->str), FileSys::Path(new_path->str)));
}
Result IFileSystem::OpenFile(OutInterface<IFile> out_interface, Result IFileSystem::OpenFile(OutInterface<IFile> out_interface,
const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path, const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path,
u32 mode) { u32 mode) {
@@ -1,6 +1,3 @@
// SPDX-FileCopyrightText: Copyright 2026 Eden Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project // SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later // SPDX-License-Identifier: GPL-2.0-or-later
@@ -39,8 +36,6 @@ public:
const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path); const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path);
Result RenameFile(const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> old_path, Result RenameFile(const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> old_path,
const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> new_path); const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> new_path);
Result RenameDirectory(const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> old_path,
const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> new_path);
Result OpenFile(OutInterface<IFile> out_interface, Result OpenFile(OutInterface<IFile> out_interface,
const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path, u32 mode); const InLargeData<FileSys::Sf::Path, BufferAttr_HipcPointer> path, u32 mode);
Result OpenDirectory(OutInterface<IDirectory> out_interface, Result OpenDirectory(OutInterface<IDirectory> out_interface,
@@ -18,6 +18,7 @@
#include "common/settings.h" #include "common/settings.h"
#include "common/string_util.h" #include "common/string_util.h"
#include "core/core.h" #include "core/core.h"
#include "core/file_sys/common_funcs.h"
#include "core/file_sys/content_archive.h" #include "core/file_sys/content_archive.h"
#include "core/file_sys/errors.h" #include "core/file_sys/errors.h"
#include "core/file_sys/fs_directory.h" #include "core/file_sys/fs_directory.h"
@@ -313,7 +314,7 @@ Result FSP_SRV::OpenSaveDataFileSystemBySystemSaveDataId(OutInterface<IFileSyste
FileSys::ResultInvalidArgument); FileSys::ResultInvalidArgument);
if (attribute.program_id == 0) { if (attribute.program_id == 0) {
attribute.program_id = program_id; attribute.program_id = FileSys::GetBaseTitleID(program_id);
} }
FileSys::VirtualDir dir{}; FileSys::VirtualDir dir{};
+2 -3
View File
@@ -15,8 +15,7 @@
#include <random> #include <random>
#include <span> #include <span>
#include <thread> #include <thread>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "common/logging.h" #include "common/logging.h"
#include "common/socket_types.h" #include "common/socket_types.h"
@@ -120,7 +119,7 @@ protected:
std::array<LanStation, StationCountMax> stations; std::array<LanStation, StationCountMax> stations;
std::array<NodeLatestUpdate, NodeCountMax> node_changes{}; std::array<NodeLatestUpdate, NodeCountMax> node_changes{};
std::array<u8, NodeCountMax> node_last_states{}; std::array<u8, NodeCountMax> node_last_states{};
boost::unordered::unordered_flat_map<MacAddress, NetworkInfo, MACAddressHash> scan_results{}; ankerl::unordered_dense::map<MacAddress, NetworkInfo, MACAddressHash> scan_results{};
NodeInfo node_info{}; NodeInfo node_info{};
NetworkInfo network_info{}; NetworkInfo network_info{};
State state{State::None}; State state{State::None};
+2 -3
View File
@@ -7,8 +7,7 @@
#include <string> #include <string>
#include <optional> #include <optional>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <boost/container_hash/hash.hpp> #include <boost/container_hash/hash.hpp>
#include "common/logging.h" #include "common/logging.h"
#include "core/core.h" #include "core/core.h"
@@ -332,7 +331,7 @@ private:
}; };
static_assert(sizeof(LogPacketHeader) == 0x18, "LogPacketHeader is an invalid size"); static_assert(sizeof(LogPacketHeader) == 0x18, "LogPacketHeader is an invalid size");
boost::unordered::unordered_flat_map<LogPacketHeaderEntry, std::vector<u8>> entries{}; ankerl::unordered_dense::map<LogPacketHeaderEntry, std::vector<u8>> entries{};
LogDestination destination{LogDestination::All}; LogDestination destination{LogDestination::All};
}; };
+1 -2
View File
@@ -23,8 +23,7 @@
#include <mutex> #include <mutex>
#include <optional> #include <optional>
#include <thread> #include <thread>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <common/settings.h> #include <common/settings.h>
#ifdef _WIN32 #ifdef _WIN32
+1 -2
View File
@@ -9,8 +9,7 @@
#include <deque> #include <deque>
#include <memory> #include <memory>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "core/device_memory_manager.h" #include "core/device_memory_manager.h"
#include "core/hle/service/nvdrv/nvdata.h" #include "core/hle/service/nvdrv/nvdata.h"
+2 -3
View File
@@ -12,8 +12,7 @@
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <optional> #include <optional>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <assert.h> #include <assert.h>
#include "common/bit_field.h" #include "common/bit_field.h"
@@ -162,7 +161,7 @@ private:
std::list<std::shared_ptr<Handle>> unmap_queue{}; std::list<std::shared_ptr<Handle>> unmap_queue{};
std::mutex unmap_queue_lock{}; //!< Protects access to `unmap_queue` std::mutex unmap_queue_lock{}; //!< Protects access to `unmap_queue`
boost::unordered::unordered_flat_map<Handle::Id, std::shared_ptr<Handle>> ankerl::unordered_dense::map<Handle::Id, std::shared_ptr<Handle>>
handles{}; //!< Main owning map of handles handles{}; //!< Main owning map of handles
std::mutex handles_lock; //!< Protects access to `handles` std::mutex handles_lock; //!< Protects access to `handles`
@@ -13,8 +13,7 @@
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <optional> #include <optional>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <vector> #include <vector>
#include "common/address_space.h" #include "common/address_space.h"
@@ -114,7 +113,7 @@ private:
}; };
static_assert(sizeof(IoctlRemapEntry) == 20, "IoctlRemapEntry is incorrect size"); static_assert(sizeof(IoctlRemapEntry) == 20, "IoctlRemapEntry is incorrect size");
boost::unordered::unordered_flat_set<s64_le> map_buffer_offsets{}; ankerl::unordered_dense::set<s64_le> map_buffer_offsets{};
struct IoctlMapBufferEx { struct IoctlMapBufferEx {
MappingFlags flags{}; // bit0: fixed_offset, bit2: cacheable MappingFlags flags{}; // bit0: fixed_offset, bit2: cacheable
@@ -217,7 +217,7 @@ private:
NvCore::SyncpointManager& syncpoint_manager; NvCore::SyncpointManager& syncpoint_manager;
NvCore::NvMap& nvmap; NvCore::NvMap& nvmap;
std::shared_ptr<Tegra::Control::ChannelState> channel_state; std::shared_ptr<Tegra::Control::ChannelState> channel_state;
boost::unordered::unordered_flat_map<DeviceFD, NvCore::SessionId> sessions; ankerl::unordered_dense::map<DeviceFD, NvCore::SessionId> sessions;
u32 channel_syncpoint; u32 channel_syncpoint;
std::mutex channel_mutex; std::mutex channel_mutex;
@@ -7,8 +7,7 @@
#pragma once #pragma once
#include <deque> #include <deque>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <vector> #include <vector>
#include "common/common_types.h" #include "common/common_types.h"
@@ -139,7 +138,7 @@ protected:
NvCore::NvMap& nvmap; NvCore::NvMap& nvmap;
NvCore::ChannelType channel_type; NvCore::ChannelType channel_type;
std::array<u32, MaxSyncPoints> device_syncpoints{}; std::array<u32, MaxSyncPoints> device_syncpoints{};
boost::unordered::unordered_flat_map<DeviceFD, NvCore::SessionId> sessions; ankerl::unordered_dense::map<DeviceFD, NvCore::SessionId> sessions;
}; };
}; // namespace Devices }; // namespace Devices
} // namespace Service::Nvidia } // namespace Service::Nvidia
+2 -3
View File
@@ -7,8 +7,7 @@
#pragma once #pragma once
#include <memory> #include <memory>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <vector> #include <vector>
#include "common/common_funcs.h" #include "common/common_funcs.h"
#include "common/common_types.h" #include "common/common_types.h"
@@ -119,7 +118,7 @@ private:
NvCore::Container& container; NvCore::Container& container;
NvCore::NvMap& file; NvCore::NvMap& file;
boost::unordered::unordered_flat_map<DeviceFD, NvCore::SessionId> sessions; ankerl::unordered_dense::map<DeviceFD, NvCore::SessionId> sessions;
}; };
} // namespace Service::Nvidia::Devices } // namespace Service::Nvidia::Devices
+3 -4
View File
@@ -12,8 +12,7 @@
#include <memory> #include <memory>
#include <span> #include <span>
#include <string> #include <string>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "common/common_types.h" #include "common/common_types.h"
#include "core/hle/service/kernel_helpers.h" #include "core/hle/service/kernel_helpers.h"
@@ -104,7 +103,7 @@ private:
/// Id to use for the next open file descriptor. /// Id to use for the next open file descriptor.
DeviceFD next_fd = 1; DeviceFD next_fd = 1;
using FilesContainerType = boost::unordered::unordered_flat_map<DeviceFD, std::shared_ptr<Devices::nvdevice>>; using FilesContainerType = ankerl::unordered_dense::map<DeviceFD, std::shared_ptr<Devices::nvdevice>>;
/// Mapping of file descriptors to the devices they reference. /// Mapping of file descriptors to the devices they reference.
FilesContainerType open_files; FilesContainerType open_files;
@@ -112,7 +111,7 @@ private:
EventInterface events_interface; EventInterface events_interface;
boost::unordered::unordered_flat_map<std::string, std::function<FilesContainerType::iterator(DeviceFD)>> builders; ankerl::unordered_dense::map<std::string, std::function<FilesContainerType::iterator(DeviceFD)>> builders;
}; };
void LoopProcess(Core::System& system); void LoopProcess(Core::System& system);
@@ -8,8 +8,7 @@
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "common/common_types.h" #include "common/common_types.h"
#include "core/hle/service/nvnflinger/binder.h" #include "core/hle/service/nvnflinger/binder.h"
@@ -40,8 +39,8 @@ private:
mutable std::mutex lock; mutable std::mutex lock;
s32 last_id = 0; s32 last_id = 0;
boost::unordered::unordered_flat_map<s32, std::shared_ptr<android::IBinder>> binders; ankerl::unordered_dense::map<s32, std::shared_ptr<android::IBinder>> binders;
boost::unordered::unordered_flat_map<s32, RefCounts> refcounts; ankerl::unordered_dense::map<s32, RefCounts> refcounts;
}; };
} // namespace Service::Nvnflinger } // namespace Service::Nvnflinger
@@ -6,8 +6,7 @@
#pragma once #pragma once
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "common/uuid.h" #include "common/uuid.h"
#include "core/hle/service/cmif_types.h" #include "core/hle/service/cmif_types.h"
@@ -57,10 +56,10 @@ private:
} }
}; };
boost::unordered::unordered_flat_map<AppKey, bool, AppKeyHash> app_auto_transfer_{}; ankerl::unordered_dense::map<AppKey, bool, AppKeyHash> app_auto_transfer_{};
boost::unordered::unordered_flat_map<Common::UUID, bool> global_auto_upload_{}; ankerl::unordered_dense::map<Common::UUID, bool> global_auto_upload_{};
boost::unordered::unordered_flat_map<Common::UUID, bool> global_auto_download_{}; ankerl::unordered_dense::map<Common::UUID, bool> global_auto_download_{};
boost::unordered::unordered_flat_map<AppKey, u8, AppKeyHash> autonomy_task_status_{}; ankerl::unordered_dense::map<AppKey, u8, AppKeyHash> autonomy_task_status_{};
}; };
} // namespace Service::OLSC } // namespace Service::OLSC
+1 -1
View File
@@ -393,7 +393,7 @@ Result ServerManager::CompleteSyncRequest(Session* session) {
} }
// Send the reply. // Send the reply.
res = server_session->SendReplyHLE(m_system.Kernel(), service_res == IPC::ResultSessionClosed); res = server_session->SendReplyHLE(m_system.Kernel());
// If the session has been closed, we're done. // If the session has been closed, we're done.
if (res == Kernel::ResultSessionClosed || service_res == IPC::ResultSessionClosed) { if (res == Kernel::ResultSessionClosed || service_res == IPC::ResultSessionClosed) {
+3 -4
View File
@@ -8,8 +8,7 @@
#include <cstddef> #include <cstddef>
#include <mutex> #include <mutex>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "common/common_types.h" #include "common/common_types.h"
#include "core/hle/service/hle_ipc.h" #include "core/hle/service/hle_ipc.h"
@@ -100,8 +99,8 @@ private:
void ReportUnimplementedFunction(HLERequestContext& ctx, const FunctionInfoBase* info); void ReportUnimplementedFunction(HLERequestContext& ctx, const FunctionInfoBase* info);
protected: protected:
boost::unordered::unordered_flat_map<u32, FunctionInfoBase> handlers; ankerl::unordered_dense::map<u32, FunctionInfoBase> handlers;
boost::unordered::unordered_flat_map<u32, FunctionInfoBase> handlers_tipc; ankerl::unordered_dense::map<u32, FunctionInfoBase> handlers_tipc;
/// Used to gain exclusive access to the service members, e.g. from CoreTiming thread. /// Used to gain exclusive access to the service members, e.g. from CoreTiming thread.
std::mutex lock_service; std::mutex lock_service;
/// System context that the service operates under. /// System context that the service operates under.
+3 -4
View File
@@ -10,8 +10,7 @@
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <string> #include <string>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <concepts> #include <concepts>
#include "core/hle/kernel/k_port.h" #include "core/hle/kernel/k_port.h"
@@ -101,8 +100,8 @@ private:
/// Map of registered services, retrieved using GetServicePort. /// Map of registered services, retrieved using GetServicePort.
mutable std::mutex lock; mutable std::mutex lock;
boost::unordered::unordered_flat_map<std::string, SessionRequestHandlerFactory> registered_services; ankerl::unordered_dense::map<std::string, SessionRequestHandlerFactory> registered_services;
boost::unordered::unordered_flat_map<std::string, Kernel::KClientPort*> service_ports; ankerl::unordered_dense::map<std::string, Kernel::KClientPort*> service_ports;
/// Kernel context /// Kernel context
Kernel::KernelCore& kernel; Kernel::KernelCore& kernel;
+2 -3
View File
@@ -7,8 +7,7 @@
#pragma once #pragma once
#include <memory> #include <memory>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "common/common_types.h" #include "common/common_types.h"
#include "common/polyfill_thread.h" #include "common/polyfill_thread.h"
@@ -50,7 +49,7 @@ private:
private: private:
Core::System& m_system; Core::System& m_system;
Container& m_container; Container& m_container;
boost::unordered::unordered_flat_map<u64, VsyncManager> m_vsync_managers; ankerl::unordered_dense::map<u64, VsyncManager> m_vsync_managers;
std::shared_ptr<Core::Timing::EventType> m_event; std::shared_ptr<Core::Timing::EventType> m_event;
Common::Event m_signal; Common::Event m_signal;
std::jthread m_thread; std::jthread m_thread;
+6 -3
View File
@@ -8,7 +8,7 @@
#include <mutex> #include <mutex>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <boost/container/flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <fmt/format.h> #include <fmt/format.h>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
@@ -21,9 +21,12 @@
namespace Core::LaunchTimestampCache { namespace Core::LaunchTimestampCache {
namespace { namespace {
using CacheMap = ankerl::unordered_dense::map<u64, s64>;
using CountMap = ankerl::unordered_dense::map<u64, u64>;
std::mutex g_mutex; std::mutex g_mutex;
boost::container::flat_map<u64, s64> g_cache; CacheMap g_cache;
boost::container::flat_map<u64, u64> g_counts; CountMap g_counts;
bool g_loaded = false; bool g_loaded = false;
std::filesystem::path GetCachePath() { std::filesystem::path GetCachePath() {
+9
View File
@@ -70,6 +70,15 @@ std::optional<IndexedProgram> ResolveIndexedProgram(Core::System& system, u64 pr
return IndexedProgram{std::move(update), target_id, true}; return IndexedProgram{std::move(update), target_id, true};
} }
const auto application_update_id =
FileSys::GetUpdateTitleID(FileSys::GetBaseTitleID(target_id));
if (application_update_id != update_id) {
if (auto update = provider.GetEntryRaw(application_update_id, FileSys::ContentRecordType::Program)) {
LOG_INFO(Loader, "Program index {} has no base program, loading it from application update {:016X}", program_index, application_update_id);
return IndexedProgram{std::move(update), target_id, true};
}
}
LOG_WARNING(Loader, "No program NCA for {:016X} (index {}), falling back to the container", LOG_WARNING(Loader, "No program NCA for {:016X} (index {}), falling back to the container",
target_id, program_index); target_id, program_index);
return std::nullopt; return std::nullopt;
+8 -2
View File
@@ -11,6 +11,7 @@
#include "common/hex_util.h" #include "common/hex_util.h"
#include "common/scope_exit.h" #include "common/scope_exit.h"
#include "core/core.h" #include "core/core.h"
#include "core/file_sys/common_funcs.h"
#include "core/file_sys/content_archive.h" #include "core/file_sys/content_archive.h"
#include "core/file_sys/control_metadata.h" #include "core/file_sys/control_metadata.h"
#include "core/file_sys/nca_metadata.h" #include "core/file_sys/nca_metadata.h"
@@ -76,8 +77,13 @@ AppLoader_NCA::LoadResult AppLoader_NCA::Load(Kernel::KProcess& process, Core::S
LOG_INFO(Loader, "No ExeFS found in NCA, looking for ExeFS from update"); LOG_INFO(Loader, "No ExeFS found in NCA, looking for ExeFS from update");
const auto& installed = system.GetContentProvider(); const auto& installed = system.GetContentProvider();
const auto update_nca = installed.GetEntry(FileSys::GetUpdateTitleID(nca->GetTitleId()), const auto program_update_id = FileSys::GetUpdateTitleID(nca->GetTitleId());
FileSys::ContentRecordType::Program); auto update_nca = installed.GetEntry(program_update_id, FileSys::ContentRecordType::Program);
if (update_nca == nullptr) {
update_nca = installed.GetEntry(
FileSys::GetUpdateTitleID(FileSys::GetBaseTitleID(nca->GetTitleId())),
FileSys::ContentRecordType::Program);
}
if (update_nca) { if (update_nca) {
exefs = update_nca->GetExeFS(); exefs = update_nca->GetExeFS();
+7 -2
View File
@@ -186,8 +186,13 @@ ResultStatus AppLoader_NSP::ReadUpdateRaw(FileSys::VirtualFile& out_file) {
return ResultStatus::ErrorNoPackedUpdate; return ResultStatus::ErrorNoPackedUpdate;
} }
const auto read = nsp->GetNCAFile(FileSys::GetUpdateTitleID(nsp->GetProgramTitleID()), const auto program_update_id = FileSys::GetUpdateTitleID(nsp->GetProgramTitleID());
FileSys::ContentRecordType::Program); auto read = nsp->GetNCAFile(program_update_id, FileSys::ContentRecordType::Program);
if (read == nullptr) {
read = nsp->GetNCAFile(
FileSys::GetUpdateTitleID(FileSys::GetBaseTitleID(nsp->GetProgramTitleID())),
FileSys::ContentRecordType::Program);
}
if (read == nullptr) { if (read == nullptr) {
return ResultStatus::ErrorNoPackedUpdate; return ResultStatus::ErrorNoPackedUpdate;
+8 -2
View File
@@ -9,6 +9,7 @@
#include "common/common_types.h" #include "common/common_types.h"
#include "core/core.h" #include "core/core.h"
#include "core/file_sys/card_image.h" #include "core/file_sys/card_image.h"
#include "core/file_sys/common_funcs.h"
#include "core/file_sys/content_archive.h" #include "core/file_sys/content_archive.h"
#include "core/file_sys/control_metadata.h" #include "core/file_sys/control_metadata.h"
#include "core/file_sys/patch_manager.h" #include "core/file_sys/patch_manager.h"
@@ -137,8 +138,13 @@ ResultStatus AppLoader_XCI::ReadUpdateRaw(FileSys::VirtualFile& out_file) {
return ResultStatus::ErrorXCIMissingProgramNCA; return ResultStatus::ErrorXCIMissingProgramNCA;
} }
const auto read = xci->GetSecurePartitionNSP()->GetNCAFile( const auto program_update_id = FileSys::GetUpdateTitleID(program_id);
FileSys::GetUpdateTitleID(program_id), FileSys::ContentRecordType::Program); auto read = xci->GetSecurePartitionNSP()->GetNCAFile(program_update_id, FileSys::ContentRecordType::Program);
if (read == nullptr) {
read = xci->GetSecurePartitionNSP()->GetNCAFile(
FileSys::GetUpdateTitleID(FileSys::GetBaseTitleID(program_id)),
FileSys::ContentRecordType::Program);
}
if (read == nullptr) { if (read == nullptr) {
return ResultStatus::ErrorNoPackedUpdate; return ResultStatus::ErrorNoPackedUpdate;
} }
+2
View File
@@ -120,6 +120,8 @@ if (NOT Boost_FOUND)
endif() endif()
find_package(fmt 8 CONFIG) find_package(fmt 8 CONFIG)
find_package(unordered_dense REQUIRED)
if ("arm64" IN_LIST ARCHITECTURE OR DYNARMIC_TESTS) if ("arm64" IN_LIST ARCHITECTURE OR DYNARMIC_TESTS)
find_package(oaknut 2.0.1 CONFIG) find_package(oaknut 2.0.1 CONFIG)
endif() endif()
@@ -8,6 +8,8 @@ if (NOT @BUILD_SHARED_LIBS@)
find_dependency(Boost 1.57) find_dependency(Boost 1.57)
find_dependency(fmt 9) find_dependency(fmt 9)
find_dependency(mcl 0.1.12 EXACT) find_dependency(mcl 0.1.12 EXACT)
find_dependency(unordered_dense)
if ("arm64" IN_LIST ARCHITECTURE) if ("arm64" IN_LIST ARCHITECTURE)
find_dependency(oaknut 2.0.1) find_dependency(oaknut 2.0.1)
endif() endif()
+2
View File
@@ -386,6 +386,8 @@ set_target_properties(dynarmic PROPERTIES
) )
target_compile_options(dynarmic PRIVATE ${DYNARMIC_CXX_FLAGS}) target_compile_options(dynarmic PRIVATE ${DYNARMIC_CXX_FLAGS})
target_link_libraries(dynarmic PRIVATE unordered_dense::unordered_dense)
target_link_libraries(dynarmic PUBLIC fmt::fmt common) target_link_libraries(dynarmic PUBLIC fmt::fmt common)
if (BOOST_NO_HEADERS) if (BOOST_NO_HEADERS)
@@ -75,7 +75,7 @@ CodePtr AddressSpace::GetOrEmit(IR::LocationDescriptor descriptor) {
return block_info.entry_point; return block_info.entry_point;
} }
void AddressSpace::InvalidateBasicBlocks(const boost::unordered::unordered_flat_set<IR::LocationDescriptor>& descriptors) { void AddressSpace::InvalidateBasicBlocks(const ankerl::unordered_dense::set<IR::LocationDescriptor>& descriptors) {
UnprotectCodeMemory(); UnprotectCodeMemory();
for (const auto& descriptor : descriptors) { for (const auto& descriptor : descriptors) {
@@ -14,8 +14,7 @@
#include "common/common_types.h" #include "common/common_types.h"
#include <oaknut/code_block.hpp> #include <oaknut/code_block.hpp>
#include <oaknut/oaknut.hpp> #include <oaknut/oaknut.hpp>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "dynarmic/backend/arm64/emit_arm64.h" #include "dynarmic/backend/arm64/emit_arm64.h"
#include "dynarmic/backend/arm64/fastmem.h" #include "dynarmic/backend/arm64/fastmem.h"
@@ -42,7 +41,7 @@ public:
CodePtr GetOrEmit(IR::LocationDescriptor descriptor); CodePtr GetOrEmit(IR::LocationDescriptor descriptor);
void InvalidateBasicBlocks(const boost::unordered::unordered_flat_set<IR::LocationDescriptor>& descriptors); void InvalidateBasicBlocks(const ankerl::unordered_dense::set<IR::LocationDescriptor>& descriptors);
void ClearCache(); void ClearCache();
protected: protected:
@@ -77,9 +76,9 @@ protected:
// A IR::LocationDescriptor will have one current CodePtr. // A IR::LocationDescriptor will have one current CodePtr.
// However, there can be multiple other CodePtrs which are older, previously invalidated blocks. // However, there can be multiple other CodePtrs which are older, previously invalidated blocks.
std::map<CodePtr, IR::LocationDescriptor> reverse_block_entries; std::map<CodePtr, IR::LocationDescriptor> reverse_block_entries;
boost::unordered::unordered_flat_map<IR::LocationDescriptor, CodePtr> block_entries; ankerl::unordered_dense::map<IR::LocationDescriptor, CodePtr> block_entries;
boost::unordered::unordered_flat_map<CodePtr, EmittedBlockInfo> block_infos; ankerl::unordered_dense::map<CodePtr, EmittedBlockInfo> block_infos;
boost::unordered::unordered_flat_map<IR::LocationDescriptor, boost::unordered::unordered_flat_set<CodePtr>> block_references; ankerl::unordered_dense::map<IR::LocationDescriptor, ankerl::unordered_dense::set<CodePtr>> block_references;
ExceptionHandler exception_handler; ExceptionHandler exception_handler;
FastmemManager fastmem_manager; FastmemManager fastmem_manager;
@@ -14,8 +14,7 @@
#include <vector> #include <vector>
#include "common/common_types.h" #include "common/common_types.h"
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "dynarmic/backend/arm64/fastmem.h" #include "dynarmic/backend/arm64/fastmem.h"
#include "dynarmic/interface/A32/coprocessor.h" #include "dynarmic/interface/A32/coprocessor.h"
@@ -106,8 +105,8 @@ struct EmittedBlockInfo {
CodePtr entry_point; CodePtr entry_point;
std::size_t size; std::size_t size;
std::vector<Relocation> relocations; std::vector<Relocation> relocations;
boost::unordered::unordered_flat_map<IR::LocationDescriptor, std::vector<BlockRelocation>> block_relocations; ankerl::unordered_dense::map<IR::LocationDescriptor, std::vector<BlockRelocation>> block_relocations;
boost::unordered::unordered_flat_map<std::ptrdiff_t, FastmemPatchInfo> fastmem_patch_info; ankerl::unordered_dense::map<std::ptrdiff_t, FastmemPatchInfo> fastmem_patch_info;
}; };
struct EmitConfig { struct EmitConfig {
@@ -10,8 +10,7 @@
#include <cstddef> #include <cstddef>
#include <tuple> #include <tuple>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "dynarmic/mcl/bit.hpp" #include "dynarmic/mcl/bit.hpp"
#include "common/common_types.h" #include "common/common_types.h"
@@ -60,7 +59,7 @@ public:
private: private:
ExceptionHandler& exception_handler; ExceptionHandler& exception_handler;
boost::unordered::unordered_flat_set<DoNotFastmemMarker, DoNotFastmemMarkerHash> do_not_fastmem; ankerl::unordered_dense::set<DoNotFastmemMarker, DoNotFastmemMarkerHash> do_not_fastmem;
}; };
} // namespace Dynarmic::Backend::Arm64 } // namespace Dynarmic::Backend::Arm64
@@ -18,8 +18,7 @@
#include "common/common_types.h" #include "common/common_types.h"
#include "dynarmic/mcl/is_instance_of_template.hpp" #include "dynarmic/mcl/is_instance_of_template.hpp"
#include <oaknut/oaknut.hpp> #include <oaknut/oaknut.hpp>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "dynarmic/backend/arm64/stack_layout.h" #include "dynarmic/backend/arm64/stack_layout.h"
#include "dynarmic/ir/cond.h" #include "dynarmic/ir/cond.h"
@@ -337,7 +336,7 @@ private:
std::array<HostLocInfo, SpillCount> spills; std::array<HostLocInfo, SpillCount> spills;
mutable std::size_t alloc_candidate_index = 0; mutable std::size_t alloc_candidate_index = 0;
boost::unordered::unordered_flat_set<const IR::Inst*> defined_insts; ankerl::unordered_dense::set<const IR::Inst*> defined_insts;
}; };
template<typename T> template<typename T>
@@ -11,14 +11,13 @@
#include <boost/icl/interval_map.hpp> #include <boost/icl/interval_map.hpp>
#include <boost/icl/interval_set.hpp> #include <boost/icl/interval_set.hpp>
#include "common/common_types.h" #include "common/common_types.h"
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
namespace Dynarmic::Backend { namespace Dynarmic::Backend {
template<typename P> template<typename P>
void BlockRangeInformation<P>::AddRange(boost::icl::discrete_interval<P> range, IR::LocationDescriptor location) { void BlockRangeInformation<P>::AddRange(boost::icl::discrete_interval<P> range, IR::LocationDescriptor location) {
block_ranges.add(std::make_pair(range, boost::unordered::unordered_flat_set<IR::LocationDescriptor>{location})); block_ranges.add(std::make_pair(range, ankerl::unordered_dense::set<IR::LocationDescriptor>{location}));
} }
template<typename P> template<typename P>
@@ -27,8 +26,8 @@ void BlockRangeInformation<P>::ClearCache() {
} }
template<typename P> template<typename P>
boost::unordered::unordered_flat_set<IR::LocationDescriptor> BlockRangeInformation<P>::InvalidateRanges(const boost::icl::interval_set<P>& ranges) { ankerl::unordered_dense::set<IR::LocationDescriptor> BlockRangeInformation<P>::InvalidateRanges(const boost::icl::interval_set<P>& ranges) {
boost::unordered::unordered_flat_set<IR::LocationDescriptor> erase_locations; ankerl::unordered_dense::set<IR::LocationDescriptor> erase_locations;
for (auto invalidate_interval : ranges) { for (auto invalidate_interval : ranges) {
auto pair = block_ranges.equal_range(invalidate_interval); auto pair = block_ranges.equal_range(invalidate_interval);
for (auto it = pair.first; it != pair.second; ++it) for (auto it = pair.first; it != pair.second; ++it)
@@ -12,8 +12,7 @@
#include <boost/icl/interval_map.hpp> #include <boost/icl/interval_map.hpp>
#include <boost/icl/interval_set.hpp> #include <boost/icl/interval_set.hpp>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include "dynarmic/ir/location_descriptor.h" #include "dynarmic/ir/location_descriptor.h"
@@ -24,8 +23,8 @@ class BlockRangeInformation {
public: public:
void AddRange(boost::icl::discrete_interval<P> range, IR::LocationDescriptor location); void AddRange(boost::icl::discrete_interval<P> range, IR::LocationDescriptor location);
void ClearCache(); void ClearCache();
boost::unordered::unordered_flat_set<IR::LocationDescriptor> InvalidateRanges(const boost::icl::interval_set<P>& ranges); ankerl::unordered_dense::set<IR::LocationDescriptor> InvalidateRanges(const boost::icl::interval_set<P>& ranges);
boost::icl::interval_map<P, boost::unordered::unordered_flat_set<IR::LocationDescriptor>> block_ranges; boost::icl::interval_map<P, ankerl::unordered_dense::set<IR::LocationDescriptor>> block_ranges;
}; };
} // namespace Dynarmic::Backend } // namespace Dynarmic::Backend
@@ -17,8 +17,7 @@
#include <optional> #include <optional>
#include <shared_mutex> #include <shared_mutex>
#include <boost/unordered/unordered_flat_map.hpp> #include <ankerl/unordered_dense.h>
#include <boost/unordered/unordered_flat_set.hpp>
#include <fmt/format.h> #include <fmt/format.h>
#include <sys/mman.h> #include <sys/mman.h>
@@ -56,7 +55,7 @@ class SigHandler {
}); });
} }
boost::unordered::unordered_flat_map<u64, CodeBlockInfo> code_block_infos; ankerl::unordered_dense::map<u64, CodeBlockInfo> code_block_infos;
std::shared_mutex code_block_infos_mutex; std::shared_mutex code_block_infos_mutex;
struct sigaction old_sa_segv; struct sigaction old_sa_segv;
struct sigaction old_sa_bus; struct sigaction old_sa_bus;

Some files were not shown because too many files have changed in this diff Show More