Compare commits

...

27 Commits

Author SHA1 Message Date
f2753d07ad Android 212 2024-01-26 02:00:26 +00:00
ea0480e651 Merge yuzu-emu#12796 2024-01-26 02:00:26 +00:00
6b17e4b325 Merge yuzu-emu#12769 2024-01-26 02:00:26 +00:00
0e4282bb89 Merge yuzu-emu#12749 2024-01-26 02:00:26 +00:00
e04368ad7c Merge pull request #12759 from liamwhite/mp-misc
core: miscellaneous fixes
2024-01-25 16:21:38 -05:00
3e2d3548f2 Merge pull request #12777 from t895/firmware-warning
android: Add key warning
2024-01-25 16:21:29 -05:00
eb9036d75b Merge pull request #12783 from liamwhite/cmif-generation
service: add template serializer for method calls
2024-01-25 15:40:09 -05:00
01a2d978eb service: add template serializer for method calls 2024-01-25 14:35:51 -05:00
6e67b25af9 Merge pull request #12787 from t895/game-list-refresh
android: Only compare game contents for GameAdapter
2024-01-25 14:19:32 -05:00
e91667ba75 Merge pull request #12786 from t895/driver-overlay
android: Show driver vendor in FPS overlay
2024-01-25 14:19:25 -05:00
d45561ace0 Merge pull request #12499 from Kelebek1/time
Rework time services
2024-01-25 14:19:01 -05:00
0fdd6e8934 android: Fix waiting for driver install on startup 2024-01-25 13:04:04 -05:00
35794f4f18 android: Add current driver vendor to FPS overlay 2024-01-25 13:04:03 -05:00
b8be8dff69 android: Add key check 2024-01-25 12:58:19 -05:00
bc317a9807 android: Add option to make MessageDialogFragments non-dismissible
Additionally fixes an issue where its viewmodel could hold onto a stale positive action
2024-01-25 12:53:49 -05:00
97ca160b08 frontend_common: Consistently use references
Was swapping between references and pointers for no reason. Just unify them here since each of these utility functions will need their parameters to be alive.
2024-01-25 12:53:49 -05:00
1a3fc3724a frontend_common: Remove key rederivation and keep key check 2024-01-25 12:53:48 -05:00
7b01454d5f android: Only compare game contents for GameAdapter 2024-01-25 08:04:59 -05:00
f3749394ac Merge pull request #12781 from goldenx86/dozen
Demote dozen to the bottom of the device list
2024-01-25 03:58:09 -03:00
807f421752 Demote Mesa dozen to the bottom of the device list 2024-01-24 23:36:14 -03:00
e4915fb7d2 Rework time service to fix time passing offline. 2024-01-24 04:26:55 +00:00
a76f6a2775 Merge pull request #12763 from liamwhite/fix-hbl-again
loader: also register fs process for raw exefs partition
2024-01-23 13:31:41 -05:00
ba518f6899 Merge pull request #12768 from german77/wrong_conversion
service: properly convert buffers to strings
2024-01-23 13:31:27 -05:00
fc5d76e6e2 service: properly convert buffers to strings 2024-01-23 10:24:05 -06:00
5f9a45ada9 loader: also register fs process for raw exefs partition 2024-01-23 00:01:38 -05:00
a120f8ff4d nvservices: close map handles on session close 2024-01-22 21:18:52 -05:00
96833cd809 kernel: target invalidate to given process 2024-01-22 21:18:52 -05:00
212 changed files with 10128 additions and 4576 deletions

View File

@ -1,3 +1,14 @@
| Pull Request | Commit | Title | Author | Merged? |
|----|----|----|----|----|
| [12749](https://github.com/yuzu-emu/yuzu-android//pull/12749) | [`e3171486d`](https://github.com/yuzu-emu/yuzu-android//pull/12749/files) | general: workarounds for SMMU syncing issues | [liamwhite](https://github.com/liamwhite/) | Yes |
| [12769](https://github.com/yuzu-emu/yuzu-android//pull/12769) | [`ad4622da2`](https://github.com/yuzu-emu/yuzu-android//pull/12769/files) | core: hid: Reduce controller requests | [german77](https://github.com/german77/) | Yes |
| [12796](https://github.com/yuzu-emu/yuzu-android//pull/12796) | [`677c2c2cd`](https://github.com/yuzu-emu/yuzu-android//pull/12796/files) | android: Controller focus optimizations | [t895](https://github.com/t895/) | Yes |
End of merge log. You can find the original README.md below the break.
-----
<!--
SPDX-FileCopyrightText: 2018 yuzu Emulator Project
SPDX-License-Identifier: GPL-2.0-or-later

View File

@ -178,6 +178,9 @@ if (NOT TARGET stb::headers)
add_library(stb::headers ALIAS stb)
endif()
add_library(tz tz/tz/tz.cpp)
target_include_directories(tz PUBLIC ./tz)
add_library(bc_decoder bc_decoder/bc_decoder.cpp)
target_include_directories(bc_decoder PUBLIC ./bc_decoder)

1636
externals/tz/tz/tz.cpp vendored Normal file

File diff suppressed because it is too large Load Diff

81
externals/tz/tz/tz.h vendored Normal file
View File

@ -0,0 +1,81 @@
// SPDX-FileCopyrightText: 2023 yuzu Emulator Project
// SPDX-FileCopyrightText: 1996 Arthur David Olson
// SPDX-License-Identifier: BSD-2-Clause
#pragma once
#include <cstdint>
#include <limits>
#include <span>
#include <array>
#include <time.h>
namespace Tz {
using u8 = uint8_t;
using s8 = int8_t;
using u16 = uint16_t;
using s16 = int16_t;
using u32 = uint32_t;
using s32 = int32_t;
using u64 = uint64_t;
using s64 = int64_t;
constexpr size_t TZ_MAX_TIMES = 1000;
constexpr size_t TZ_MAX_TYPES = 128;
constexpr size_t TZ_MAX_CHARS = 50;
constexpr size_t MY_TZNAME_MAX = 255;
constexpr size_t TZNAME_MAXIMUM = 255;
constexpr size_t TZ_MAX_LEAPS = 50;
constexpr s64 TIME_T_MAX = std::numeric_limits<s64>::max();
constexpr s64 TIME_T_MIN = std::numeric_limits<s64>::min();
constexpr size_t CHARS_EXTRA = 3;
constexpr size_t MAX_ZONE_CHARS = std::max(TZ_MAX_CHARS + CHARS_EXTRA, sizeof("UTC"));
constexpr size_t MAX_TZNAME_CHARS = 2 * (MY_TZNAME_MAX + 1);
struct ttinfo {
s32 tt_utoff;
bool tt_isdst;
s32 tt_desigidx;
bool tt_ttisstd;
bool tt_ttisut;
};
static_assert(sizeof(ttinfo) == 0x10, "ttinfo has the wrong size!");
struct Rule {
s32 timecnt;
s32 typecnt;
s32 charcnt;
bool goback;
bool goahead;
std::array <u8, 0x2> padding0;
std::array<s64, TZ_MAX_TIMES> ats;
std::array<u8, TZ_MAX_TIMES> types;
std::array<ttinfo, TZ_MAX_TYPES> ttis;
std::array<char, std::max(MAX_ZONE_CHARS, MAX_TZNAME_CHARS)> chars;
s32 defaulttype;
std::array <u8, 0x12C4> padding1;
};
static_assert(sizeof(Rule) == 0x4000, "Rule has the wrong size!");
struct CalendarTimeInternal {
s32 tm_sec;
s32 tm_min;
s32 tm_hour;
s32 tm_mday;
s32 tm_mon;
s32 tm_year;
s32 tm_wday;
s32 tm_yday;
s32 tm_isdst;
std::array<char, 16> tm_zone;
s32 tm_utoff;
s32 time_index;
};
static_assert(sizeof(CalendarTimeInternal) == 0x3C, "CalendarTimeInternal has the wrong size!");
s32 ParseTimeZoneBinary(Rule& out_rule, std::span<const u8> binary);
bool localtime_rz(CalendarTimeInternal* tmp, Rule* sp, time_t* timep);
u32 mktime_tzname(time_t* out_time, Rule* sp, CalendarTimeInternal* tmp);
} // namespace Tz

View File

@ -303,6 +303,11 @@ object NativeLibrary {
*/
external fun getCpuBackend(): String
/**
* Returns the current GPU Driver.
*/
external fun getGpuDriver(): String
external fun applySettings()
external fun logSettings()
@ -614,6 +619,11 @@ object NativeLibrary {
*/
external fun clearFilesystemProvider()
/**
* Checks if all necessary keys are present for decryption
*/
external fun areKeysPresent(): Boolean
/**
* Button type for use in onTouchEvent
*/

View File

@ -193,6 +193,10 @@ class EmulationActivity : AppCompatActivity(), SensorEventListener {
return super.dispatchKeyEvent(event)
}
if (emulationViewModel.drawerOpen.value) {
return super.dispatchKeyEvent(event)
}
return InputHandler.dispatchKeyEvent(event)
}
@ -203,6 +207,10 @@ class EmulationActivity : AppCompatActivity(), SensorEventListener {
return super.dispatchGenericMotionEvent(event)
}
if (emulationViewModel.drawerOpen.value) {
return super.dispatchGenericMotionEvent(event)
}
// Don't attempt to do anything if we are disconnecting a device.
if (event.actionMasked == MotionEvent.ACTION_CANCEL) {
return true

View File

@ -14,15 +14,20 @@ import androidx.recyclerview.widget.RecyclerView
* Generic adapter that implements an [AsyncDifferConfig] and covers some of the basic boilerplate
* code used in every [RecyclerView].
* Type assigned to [Model] must inherit from [Object] in order to be compared properly.
* @param exact Decides whether each item will be compared by reference or by their contents
*/
abstract class AbstractDiffAdapter<Model : Any, Holder : AbstractViewHolder<Model>> :
ListAdapter<Model, Holder>(AsyncDifferConfig.Builder(DiffCallback<Model>()).build()) {
abstract class AbstractDiffAdapter<Model : Any, Holder : AbstractViewHolder<Model>>(
exact: Boolean = true
) : ListAdapter<Model, Holder>(AsyncDifferConfig.Builder(DiffCallback<Model>(exact)).build()) {
override fun onBindViewHolder(holder: Holder, position: Int) =
holder.bind(currentList[position])
private class DiffCallback<Model> : DiffUtil.ItemCallback<Model>() {
private class DiffCallback<Model>(val exact: Boolean) : DiffUtil.ItemCallback<Model>() {
override fun areItemsTheSame(oldItem: Model & Any, newItem: Model & Any): Boolean {
return oldItem === newItem
if (exact) {
return oldItem === newItem
}
return oldItem == newItem
}
@SuppressLint("DiffUtilEquals")

View File

@ -30,7 +30,7 @@ import org.yuzu.yuzu_emu.utils.GameIconUtils
import org.yuzu.yuzu_emu.viewholder.AbstractViewHolder
class GameAdapter(private val activity: AppCompatActivity) :
AbstractDiffAdapter<Game, GameAdapter.GameViewHolder>() {
AbstractDiffAdapter<Game, GameAdapter.GameViewHolder>(exact = false) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GameViewHolder {
CardGameBinding.inflate(LayoutInflater.from(parent.context), parent, false)
.also { return GameViewHolder(it) }

View File

@ -77,7 +77,7 @@ class AboutFragment : Fragment() {
}
binding.textVersionName.text = BuildConfig.VERSION_NAME
binding.textVersionName.setOnClickListener {
binding.buttonVersionName.setOnClickListener {
val clipBoard =
requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText(getString(R.string.build), BuildConfig.GIT_HASH)

View File

@ -141,7 +141,9 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
// So this fragment doesn't restart on configuration changes; i.e. rotation.
retainInstance = true
emulationState = EmulationState(game.path)
emulationState = EmulationState(game.path) {
return@EmulationState driverViewModel.isInteractionAllowed.value
}
}
/**
@ -183,10 +185,13 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
override fun onDrawerOpened(drawerView: View) {
binding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
binding.inGameMenu.requestFocus()
emulationViewModel.setDrawerOpen(true)
}
override fun onDrawerClosed(drawerView: View) {
binding.drawerLayout.setDrawerLockMode(IntSetting.LOCK_DRAWER.getInt())
emulationViewModel.setDrawerOpen(false)
}
override fun onDrawerStateChanged(newState: Int) {
@ -238,6 +243,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
requireContext().theme
)
}
binding.inGameMenu.requestFocus()
true
}
@ -246,6 +252,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
null,
Settings.MenuTag.SECTION_ROOT
)
binding.inGameMenu.requestFocus()
binding.root.findNavController().navigate(action)
true
}
@ -255,6 +262,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
args.game,
Settings.MenuTag.SECTION_ROOT
)
binding.inGameMenu.requestFocus()
binding.root.findNavController().navigate(action)
true
}
@ -286,6 +294,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
)
}
}
binding.inGameMenu.requestFocus()
NativeConfig.saveGlobalConfig()
true
}
@ -294,7 +303,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
emulationState.stop()
emulationViewModel.setIsEmulationStopping(true)
binding.drawerLayout.close()
binding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
binding.inGameMenu.requestFocus()
true
}
@ -311,12 +320,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
if (!NativeLibrary.isRunning()) {
return
}
if (binding.drawerLayout.isOpen) {
binding.drawerLayout.close()
} else {
binding.drawerLayout.open()
}
emulationViewModel.setDrawerOpen(!binding.drawerLayout.isOpen)
}
}
)
@ -370,6 +374,15 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
}
}
}
launch {
repeatOnLifecycle(Lifecycle.State.RESUMED) {
driverViewModel.isInteractionAllowed.collect {
if (it) {
startEmulation()
}
}
}
}
launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
emulationViewModel.emulationStarted.collectLatest {
@ -399,10 +412,13 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
}
}
launch {
repeatOnLifecycle(Lifecycle.State.RESUMED) {
driverViewModel.isInteractionAllowed.collect {
repeatOnLifecycle(Lifecycle.State.CREATED) {
emulationViewModel.drawerOpen.collect {
if (it) {
onEmulationStart()
binding.drawerLayout.open()
binding.inGameMenu.requestFocus()
} else {
binding.drawerLayout.close()
}
}
}
@ -410,7 +426,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
}
}
private fun onEmulationStart() {
private fun startEmulation() {
if (!NativeLibrary.isRunning() && !NativeLibrary.isPaused()) {
if (!DirectoryInitialization.areDirectoriesReady) {
DirectoryInitialization.start()
@ -485,12 +501,15 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
val FRAMETIME = 2
val SPEED = 3
perfStatsUpdater = {
if (emulationViewModel.emulationStarted.value) {
if (emulationViewModel.emulationStarted.value &&
!emulationViewModel.isEmulationStopping.value
) {
val perfStats = NativeLibrary.getPerfStats()
val cpuBackend = NativeLibrary.getCpuBackend()
val gpuDriver = NativeLibrary.getGpuDriver()
if (_binding != null) {
binding.showFpsText.text =
String.format("FPS: %.1f\n%s", perfStats[FPS], cpuBackend)
String.format("FPS: %.1f\n%s/%s", perfStats[FPS], cpuBackend, gpuDriver)
}
perfStatsUpdateHandler.postDelayed(perfStatsUpdater!!, 800)
}
@ -807,7 +826,10 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
}
}
private class EmulationState(private val gamePath: String) {
private class EmulationState(
private val gamePath: String,
private val emulationCanStart: () -> Boolean
) {
private var state: State
private var surface: Surface? = null
@ -901,6 +923,7 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
State.PAUSED -> Log.warning(
"[EmulationFragment] Surface cleared while emulation paused."
)
else -> Log.warning(
"[EmulationFragment] Surface cleared while emulation stopped."
)
@ -910,6 +933,10 @@ class EmulationFragment : Fragment(), SurfaceHolder.Callback {
private fun runWithValidSurface() {
NativeLibrary.surfaceChanged(surface)
if (!emulationCanStart.invoke()) {
return
}
when (state) {
State.STOPPED -> {
val emulationThread = Thread({

View File

@ -26,9 +26,15 @@ class MessageDialogFragment : DialogFragment() {
val descriptionId = requireArguments().getInt(DESCRIPTION_ID)
val descriptionString = requireArguments().getString(DESCRIPTION_STRING)!!
val helpLinkId = requireArguments().getInt(HELP_LINK)
val dismissible = requireArguments().getBoolean(DISMISSIBLE)
val clearPositiveAction = requireArguments().getBoolean(CLEAR_POSITIVE_ACTION)
val builder = MaterialAlertDialogBuilder(requireContext())
if (clearPositiveAction) {
messageDialogViewModel.positiveAction = null
}
if (messageDialogViewModel.positiveAction == null) {
builder.setPositiveButton(R.string.close, null)
} else {
@ -51,6 +57,8 @@ class MessageDialogFragment : DialogFragment() {
}
}
isCancelable = dismissible
return builder.show()
}
@ -67,6 +75,8 @@ class MessageDialogFragment : DialogFragment() {
private const val DESCRIPTION_ID = "DescriptionId"
private const val DESCRIPTION_STRING = "DescriptionString"
private const val HELP_LINK = "Link"
private const val DISMISSIBLE = "Dismissible"
private const val CLEAR_POSITIVE_ACTION = "ClearPositiveAction"
fun newInstance(
activity: FragmentActivity? = null,
@ -75,22 +85,28 @@ class MessageDialogFragment : DialogFragment() {
descriptionId: Int = 0,
descriptionString: String = "",
helpLinkId: Int = 0,
dismissible: Boolean = true,
positiveAction: (() -> Unit)? = null
): MessageDialogFragment {
val dialog = MessageDialogFragment()
val bundle = Bundle()
bundle.apply {
putInt(TITLE_ID, titleId)
putString(TITLE_STRING, titleString)
putInt(DESCRIPTION_ID, descriptionId)
putString(DESCRIPTION_STRING, descriptionString)
putInt(HELP_LINK, helpLinkId)
}
var clearPositiveAction = false
if (activity != null) {
ViewModelProvider(activity)[MessageDialogViewModel::class.java].apply {
clear()
this.positiveAction = positiveAction
}
} else {
clearPositiveAction = true
}
val dialog = MessageDialogFragment()
val bundle = Bundle().apply {
putInt(TITLE_ID, titleId)
putString(TITLE_STRING, titleString)
putInt(DESCRIPTION_ID, descriptionId)
putString(DESCRIPTION_STRING, descriptionString)
putInt(HELP_LINK, helpLinkId)
putBoolean(DISMISSIBLE, dismissible)
putBoolean(CLEAR_POSITIVE_ACTION, clearPositiveAction)
}
dialog.arguments = bundle
return dialog

View File

@ -31,6 +31,7 @@ import androidx.preference.PreferenceManager
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.google.android.material.transition.MaterialFadeThrough
import kotlinx.coroutines.launch
import org.yuzu.yuzu_emu.NativeLibrary
import java.io.File
import org.yuzu.yuzu_emu.R
import org.yuzu.yuzu_emu.YuzuApplication
@ -162,7 +163,7 @@ class SetupFragment : Fragment() {
R.string.install_prod_keys_warning_help,
{
val file = File(DirectoryInitialization.userDirectory + "/keys/prod.keys")
if (file.exists()) {
if (file.exists() && NativeLibrary.areKeysPresent()) {
StepState.COMPLETE
} else {
StepState.INCOMPLETE
@ -347,7 +348,8 @@ class SetupFragment : Fragment() {
val getProdKey =
registerForActivityResult(ActivityResultContracts.OpenDocument()) { result ->
if (result != null) {
if (mainActivity.processKey(result)) {
mainActivity.processKey(result)
if (NativeLibrary.areKeysPresent()) {
keyCallback.onStepCompleted()
}
}

View File

@ -144,6 +144,7 @@ class DriverViewModel : ViewModel() {
val selectedDriverFile = File(StringSetting.DRIVER_PATH.getString())
val selectedDriverMetadata = GpuDriverHelper.customDriverSettingData
if (GpuDriverHelper.installedCustomDriverData == selectedDriverMetadata) {
setDriverReady()
return
}

View File

@ -6,6 +6,7 @@ package org.yuzu.yuzu_emu.model
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
class EmulationViewModel : ViewModel() {
val emulationStarted: StateFlow<Boolean> get() = _emulationStarted
@ -23,6 +24,9 @@ class EmulationViewModel : ViewModel() {
val shaderMessage: StateFlow<String> get() = _shaderMessage
private val _shaderMessage = MutableStateFlow("")
private val _drawerOpen = MutableStateFlow(false)
val drawerOpen = _drawerOpen.asStateFlow()
fun setEmulationStarted(started: Boolean) {
_emulationStarted.value = started
}
@ -49,6 +53,10 @@ class EmulationViewModel : ViewModel() {
setTotalShaders(max)
}
fun setDrawerOpen(value: Boolean) {
_drawerOpen.value = value
}
fun clear() {
setEmulationStarted(false)
setIsEmulationStopping(false)

View File

@ -70,11 +70,19 @@ class Game(
}
override fun equals(other: Any?): Boolean {
if (other !is Game) {
return false
}
if (this === other) return true
if (javaClass != other?.javaClass) return false
return hashCode() == other.hashCode()
other as Game
if (title != other.title) return false
if (path != other.path) return false
if (programId != other.programId) return false
if (developer != other.developer) return false
if (version != other.version) return false
if (isHomebrew != other.isHomebrew) return false
return true
}
override fun hashCode(): Int {

View File

@ -31,6 +31,9 @@ class HomeViewModel : ViewModel() {
private val _reloadPropertiesList = MutableStateFlow(false)
val reloadPropertiesList get() = _reloadPropertiesList.asStateFlow()
private val _checkKeys = MutableStateFlow(false)
val checkKeys = _checkKeys.asStateFlow()
var navigatedToSetup = false
fun setNavigationVisibility(visible: Boolean, animated: Boolean) {
@ -66,4 +69,8 @@ class HomeViewModel : ViewModel() {
fun reloadPropertiesList(reload: Boolean) {
_reloadPropertiesList.value = reload
}
fun setCheckKeys(value: Boolean) {
_checkKeys.value = value
}
}

View File

@ -64,6 +64,9 @@ class MainActivity : AppCompatActivity(), ThemeProvider {
override var themeId: Int = 0
private val CHECKED_DECRYPTION = "CheckedDecryption"
private var checkedDecryption = false
override fun onCreate(savedInstanceState: Bundle?) {
val splashScreen = installSplashScreen()
splashScreen.setKeepOnScreenCondition { !DirectoryInitialization.areDirectoriesReady }
@ -75,6 +78,18 @@ class MainActivity : AppCompatActivity(), ThemeProvider {
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
if (savedInstanceState != null) {
checkedDecryption = savedInstanceState.getBoolean(CHECKED_DECRYPTION)
}
if (!checkedDecryption) {
val firstTimeSetup = PreferenceManager.getDefaultSharedPreferences(applicationContext)
.getBoolean(Settings.PREF_FIRST_APP_LAUNCH, true)
if (!firstTimeSetup) {
checkKeys()
}
checkedDecryption = true
}
WindowCompat.setDecorFitsSystemWindows(window, false)
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
@ -150,6 +165,16 @@ class MainActivity : AppCompatActivity(), ThemeProvider {
}
}
}
launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
homeViewModel.checkKeys.collect {
if (it) {
checkKeys()
homeViewModel.setCheckKeys(false)
}
}
}
}
}
// Dismiss previous notifications (should not happen unless a crash occurred)
@ -158,6 +183,21 @@ class MainActivity : AppCompatActivity(), ThemeProvider {
setInsets()
}
private fun checkKeys() {
if (!NativeLibrary.areKeysPresent()) {
MessageDialogFragment.newInstance(
titleId = R.string.keys_missing,
descriptionId = R.string.keys_missing_description,
helpLinkId = R.string.keys_missing_help
).show(supportFragmentManager, MessageDialogFragment.TAG)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(CHECKED_DECRYPTION, checkedDecryption)
}
fun finishSetup(navController: NavController) {
navController.navigate(R.id.action_firstTimeSetupFragment_to_gamesFragment)
(binding.navigationView as NavigationBarView).setupWithNavController(navController)
@ -349,6 +389,7 @@ class MainActivity : AppCompatActivity(), ThemeProvider {
R.string.install_keys_success,
Toast.LENGTH_SHORT
).show()
homeViewModel.setCheckKeys(true)
gamesViewModel.reloadGames(true)
return true
} else {
@ -399,6 +440,7 @@ class MainActivity : AppCompatActivity(), ThemeProvider {
firmwarePath.deleteRecursively()
cacheFirmwareDir.copyRecursively(firmwarePath, true)
NativeLibrary.initializeSystem(true)
homeViewModel.setCheckKeys(true)
getString(R.string.save_file_imported_success)
}
} catch (e: Exception) {

View File

@ -247,6 +247,7 @@ Core::SystemResultStatus EmulationSession::InitializeEmulation(const std::string
m_system.GetCpuManager().OnGpuReady();
m_system.RegisterExitCallback([&] { HaltEmulation(); });
OnEmulationStarted();
return Core::SystemResultStatus::Success;
}
@ -463,8 +464,8 @@ int Java_org_yuzu_yuzu_1emu_NativeLibrary_installFileToNand(JNIEnv* env, jobject
};
return static_cast<int>(
ContentManager::InstallNSP(&EmulationSession::GetInstance().System(),
EmulationSession::GetInstance().System().GetFilesystem().get(),
ContentManager::InstallNSP(EmulationSession::GetInstance().System(),
*EmulationSession::GetInstance().System().GetFilesystem(),
GetJString(env, j_file), callback));
}
@ -674,6 +675,11 @@ jstring Java_org_yuzu_yuzu_1emu_NativeLibrary_getCpuBackend(JNIEnv* env, jclass
return ToJString(env, "JIT");
}
jstring Java_org_yuzu_yuzu_1emu_NativeLibrary_getGpuDriver(JNIEnv* env, jobject jobj) {
return ToJString(env,
EmulationSession::GetInstance().System().GPU().Renderer().GetDeviceVendor());
}
void Java_org_yuzu_yuzu_1emu_NativeLibrary_applySettings(JNIEnv* env, jobject jobj) {
EmulationSession::GetInstance().System().ApplySettings();
}
@ -819,7 +825,7 @@ void Java_org_yuzu_yuzu_1emu_NativeLibrary_removeUpdate(JNIEnv* env, jobject job
void Java_org_yuzu_yuzu_1emu_NativeLibrary_removeDLC(JNIEnv* env, jobject jobj,
jstring jprogramId) {
auto program_id = 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,
@ -829,8 +835,9 @@ void Java_org_yuzu_yuzu_1emu_NativeLibrary_removeMod(JNIEnv* env, jobject jobj,
program_id, GetJString(env, jname));
}
jobject Java_org_yuzu_yuzu_1emu_NativeLibrary_verifyInstalledContents(JNIEnv* env, jobject jobj,
jobject jcallback) {
jobjectArray Java_org_yuzu_yuzu_1emu_NativeLibrary_verifyInstalledContents(JNIEnv* env,
jobject jobj,
jobject jcallback) {
auto jlambdaClass = env->GetObjectClass(jcallback);
auto jlambdaInvokeMethod = env->GetMethodID(
jlambdaClass, "invoke", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
@ -842,7 +849,7 @@ jobject Java_org_yuzu_yuzu_1emu_NativeLibrary_verifyInstalledContents(JNIEnv* en
auto& session = EmulationSession::GetInstance();
std::vector<std::string> result = ContentManager::VerifyInstalledContents(
&session.System(), session.GetContentProvider(), callback);
session.System(), *session.GetContentProvider(), callback);
jobjectArray jresult =
env->NewObjectArray(result.size(), IDCache::GetStringClass(), ToJString(env, ""));
for (size_t i = 0; i < result.size(); ++i) {
@ -863,7 +870,7 @@ jint Java_org_yuzu_yuzu_1emu_NativeLibrary_verifyGameContents(JNIEnv* env, jobje
};
auto& session = EmulationSession::GetInstance();
return static_cast<jint>(
ContentManager::VerifyGameContents(&session.System(), GetJString(env, jpath), callback));
ContentManager::VerifyGameContents(session.System(), GetJString(env, jpath), callback));
}
jstring Java_org_yuzu_yuzu_1emu_NativeLibrary_getSavePath(JNIEnv* env, jobject jobj,
@ -912,4 +919,10 @@ void Java_org_yuzu_yuzu_1emu_NativeLibrary_clearFilesystemProvider(JNIEnv* env,
EmulationSession::GetInstance().GetContentProvider()->ClearAllEntries();
}
jboolean Java_org_yuzu_yuzu_1emu_NativeLibrary_areKeysPresent(JNIEnv* env, jobject jobj) {
auto& system = EmulationSession::GetInstance().System();
system.GetFileSystemController().CreateFactories(*system.GetFilesystem());
return ContentManager::AreKeysPresent();
}
} // extern "C"

View File

@ -11,12 +11,14 @@
android:id="@+id/appbar_about"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true">
android:fitsSystemWindows="true"
android:touchscreenBlocksFocus="false">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar_about"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:touchscreenBlocksFocus="false"
app:navigationIcon="@drawable/ic_back"
app:title="@string/about" />
@ -28,6 +30,7 @@
android:layout_height="match_parent"
android:fadeScrollbars="false"
android:scrollbars="vertical"
android:defaultFocusHighlightEnabled="false"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<LinearLayout

View File

@ -0,0 +1,155 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/coordinator_about"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/colorSurface">
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:touchscreenBlocksFocus="false">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar_info"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:touchscreenBlocksFocus="false"
app:navigationIcon="@drawable/ic_back" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:id="@+id/scroll_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:defaultFocusHighlightEnabled="false"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<LinearLayout
android:id="@+id/content_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingHorizontal="16dp"
android:baselineAligned="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="3"
android:gravity="top|center_horizontal"
android:paddingHorizontal="16dp">
<com.google.android.material.button.MaterialButton
android:id="@+id/button_copy"
style="@style/Widget.Material3.Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="@string/copy_details" />
<com.google.android.material.button.MaterialButton
android:id="@+id/button_verify_integrity"
style="@style/Widget.Material3.Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/verify_integrity" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="16dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/path_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:importantForAutofill="no"
android:inputType="none"
android:minHeight="48dp"
android:textAlignment="viewStart"
tools:text="1.0.0" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/program_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="16dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/program_id_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:importantForAutofill="no"
android:inputType="none"
android:minHeight="48dp"
android:textAlignment="viewStart"
tools:text="1.0.0" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/developer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="16dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/developer_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:importantForAutofill="no"
android:inputType="none"
android:minHeight="48dp"
android:textAlignment="viewStart"
tools:text="1.0.0" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/version"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="16dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/version_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:editable="false"
android:importantForAutofill="no"
android:inputType="none"
android:minHeight="48dp"
android:textAlignment="viewStart"
tools:text="1.0.0" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View File

@ -14,6 +14,7 @@
android:clipToPadding="false"
android:fadeScrollbars="false"
android:scrollbars="vertical"
android:defaultFocusHighlightEnabled="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/icon_layout"
app:layout_constraintTop_toTopOf="parent">

View File

@ -23,6 +23,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:focusable="false"
android:clickable="false"
android:checked="false" />

View File

@ -6,16 +6,14 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="16dp"
android:layout_marginVertical="12dp"
android:focusable="true">
android:layout_marginVertical="12dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp"
android:layout_gravity="center_vertical"
android:animateLayoutChanges="true">
android:layout_gravity="center_vertical">
<com.google.android.material.textview.MaterialTextView
android:id="@+id/path"

View File

@ -11,12 +11,14 @@
android:id="@+id/appbar_about"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true">
android:fitsSystemWindows="true"
android:touchscreenBlocksFocus="false">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar_about"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:touchscreenBlocksFocus="false"
app:title="@string/about"
app:navigationIcon="@drawable/ic_back" />
@ -28,6 +30,7 @@
android:layout_height="match_parent"
android:scrollbars="vertical"
android:fadeScrollbars="false"
android:defaultFocusHighlightEnabled="false"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<LinearLayout

View File

@ -11,6 +11,7 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:touchscreenBlocksFocus="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
@ -19,6 +20,7 @@
android:id="@+id/toolbar_addons"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:touchscreenBlocksFocus="false"
app:navigationIcon="@drawable/ic_back" />
</com.google.android.material.appbar.AppBarLayout>
@ -28,6 +30,8 @@
android:layout_width="match_parent"
android:layout_height="0dp"
android:clipToPadding="false"
android:defaultFocusHighlightEnabled="false"
android:nextFocusDown="@id/button_install"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"

View File

@ -10,12 +10,14 @@
android:id="@+id/appbar_applets"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true">
android:fitsSystemWindows="true"
android:touchscreenBlocksFocus="false">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar_applets"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:touchscreenBlocksFocus="false"
app:navigationIcon="@drawable/ic_back"
app:title="@string/applets" />

View File

@ -15,12 +15,14 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:touchscreenBlocksFocus="false"
app:liftOnScrollTargetViewId="@id/list_drivers">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar_drivers"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:touchscreenBlocksFocus="false"
app:navigationIcon="@drawable/ic_back"
app:title="@string/gpu_driver_manager" />

View File

@ -11,12 +11,14 @@
android:id="@+id/appbar_ea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true">
android:fitsSystemWindows="true"
android:touchscreenBlocksFocus="false">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar_about"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:touchscreenBlocksFocus="false"
app:navigationIcon="@drawable/ic_back"
app:title="@string/early_access" />
@ -30,6 +32,7 @@
android:paddingBottom="20dp"
android:scrollbars="vertical"
android:fadeScrollbars="false"
android:defaultFocusHighlightEnabled="false"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<LinearLayout

View File

@ -5,6 +5,7 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true"
android:defaultFocusHighlightEnabled="false"
tools:context="org.yuzu.yuzu_emu.fragments.EmulationFragment"
tools:openDrawer="start">
@ -24,7 +25,8 @@
android:layout_height="match_parent"
android:layout_gravity="center"
android:focusable="false"
android:focusableInTouchMode="false" />
android:focusableInTouchMode="false"
android:defaultFocusHighlightEnabled="false" />
<com.google.android.material.card.MaterialCardView
android:id="@+id/loading_indicator"
@ -32,7 +34,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:focusable="false"
android:defaultFocusHighlightEnabled="false"
android:clickable="false">
<androidx.constraintlayout.widget.ConstraintLayout
@ -118,6 +120,7 @@
android:layout_gravity="center"
android:focusable="true"
android:focusableInTouchMode="true"
android:defaultFocusHighlightEnabled="false"
android:visibility="invisible" />
<Button
@ -160,6 +163,7 @@
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:focusedByDefault="true"
app:headerLayout="@layout/header_in_game"
app:menu="@menu/menu_in_game"
tools:visibility="gone" />

View File

@ -15,12 +15,14 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:touchscreenBlocksFocus="false"
app:liftOnScrollTargetViewId="@id/list_folders">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar_folders"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:touchscreenBlocksFocus="false"
app:navigationIcon="@drawable/ic_back"
app:title="@string/game_folders" />
@ -31,6 +33,7 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:defaultFocusHighlightEnabled="false"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View File

@ -11,12 +11,14 @@
android:id="@+id/appbar_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:touchscreenBlocksFocus="false"
android:fitsSystemWindows="true">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar_info"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:touchscreenBlocksFocus="false"
app:navigationIcon="@drawable/ic_back" />
</com.google.android.material.appbar.AppBarLayout>
@ -25,6 +27,7 @@
android:id="@+id/scroll_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:defaultFocusHighlightEnabled="false"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<LinearLayout

View File

@ -12,7 +12,8 @@
android:layout_height="match_parent"
android:scrollbars="vertical"
android:fadeScrollbars="false"
android:clipToPadding="false">
android:clipToPadding="false"
android:defaultFocusHighlightEnabled="false">
<LinearLayout
android:id="@+id/layout_all"
@ -86,7 +87,7 @@
android:id="@+id/list_properties"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="@layout/card_simple_outlined" />
android:defaultFocusHighlightEnabled="false" />
</LinearLayout>

View File

@ -27,6 +27,7 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:defaultFocusHighlightEnabled="false"
tools:listitem="@layout/card_game" />
</RelativeLayout>

View File

@ -7,7 +7,8 @@
android:background="?attr/colorSurface"
android:scrollbars="vertical"
android:fadeScrollbars="false"
android:clipToPadding="false">
android:clipToPadding="false"
android:defaultFocusHighlightEnabled="false">
<androidx.appcompat.widget.LinearLayoutCompat
android:id="@+id/linear_layout_settings"

View File

@ -10,12 +10,14 @@
android:id="@+id/appbar_installables"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true">
android:fitsSystemWindows="true"
android:touchscreenBlocksFocus="false">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar_installables"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:touchscreenBlocksFocus="false"
app:title="@string/manage_yuzu_data"
app:navigationIcon="@drawable/ic_back" />

View File

@ -10,12 +10,14 @@
android:id="@+id/appbar_licenses"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true">
android:fitsSystemWindows="true"
android:touchscreenBlocksFocus="false">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar_licenses"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:touchscreenBlocksFocus="false"
app:title="@string/licenses"
app:navigationIcon="@drawable/ic_back" />

View File

@ -11,6 +11,7 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:touchscreenBlocksFocus="false"
app:elevation="0dp">
<com.google.android.material.appbar.CollapsingToolbarLayout
@ -24,6 +25,7 @@
android:id="@+id/toolbar_settings"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:touchscreenBlocksFocus="false"
app:layout_collapseMode="pin"
app:navigationIcon="@drawable/ic_back" />

View File

@ -6,7 +6,7 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:focusable="true"
android:focusable="false"
android:paddingHorizontal="20dp"
android:paddingVertical="16dp">

View File

@ -12,4 +12,5 @@
android:textAlignment="viewStart"
android:textColor="?attr/colorPrimary"
android:textStyle="bold"
android:focusable="false"
tools:text="CPU Settings" />

View File

@ -144,6 +144,9 @@
<string name="no_save_data_found">No save data found</string>
<string name="verify_installed_content">Verify installed content</string>
<string name="verify_installed_content_description">Checks all installed content for corruption</string>
<string name="keys_missing">Encryption keys are missing</string>
<string name="keys_missing_description">Firmware and retail games cannot be decrypted</string>
<string name="keys_missing_help">https://yuzu-emu.org/help/quickstart/#dumping-decryption-keys</string>
<!-- Applet launcher strings -->
<string name="applets">Applet launcher</string>

View File

@ -106,6 +106,7 @@ add_library(common STATIC
precompiled_headers.h
quaternion.h
range_map.h
range_mutex.h
reader_writer_queue.h
ring_buffer.h
${CMAKE_CURRENT_BINARY_DIR}/scm_rev.cpp

View File

@ -30,27 +30,27 @@ NativeClock::NativeClock() {
}
std::chrono::nanoseconds NativeClock::GetTimeNS() const {
return std::chrono::nanoseconds{MultiplyHigh(GetHostTicksElapsed(), ns_cntfrq_factor)};
return std::chrono::nanoseconds{MultiplyHigh(GetUptime(), ns_cntfrq_factor)};
}
std::chrono::microseconds NativeClock::GetTimeUS() const {
return std::chrono::microseconds{MultiplyHigh(GetHostTicksElapsed(), us_cntfrq_factor)};
return std::chrono::microseconds{MultiplyHigh(GetUptime(), us_cntfrq_factor)};
}
std::chrono::milliseconds NativeClock::GetTimeMS() const {
return std::chrono::milliseconds{MultiplyHigh(GetHostTicksElapsed(), ms_cntfrq_factor)};
return std::chrono::milliseconds{MultiplyHigh(GetUptime(), ms_cntfrq_factor)};
}
u64 NativeClock::GetCNTPCT() const {
return MultiplyHigh(GetHostTicksElapsed(), guest_cntfrq_factor);
s64 NativeClock::GetCNTPCT() const {
return MultiplyHigh(GetUptime(), guest_cntfrq_factor);
}
u64 NativeClock::GetGPUTick() const {
return MultiplyHigh(GetHostTicksElapsed(), gputick_cntfrq_factor);
s64 NativeClock::GetGPUTick() const {
return MultiplyHigh(GetUptime(), gputick_cntfrq_factor);
}
u64 NativeClock::GetHostTicksNow() const {
u64 cntvct_el0 = 0;
s64 NativeClock::GetUptime() const {
s64 cntvct_el0 = 0;
asm volatile("dsb ish\n\t"
"mrs %[cntvct_el0], cntvct_el0\n\t"
"dsb ish\n\t"
@ -58,15 +58,11 @@ u64 NativeClock::GetHostTicksNow() const {
return cntvct_el0;
}
u64 NativeClock::GetHostTicksElapsed() const {
return GetHostTicksNow();
}
bool NativeClock::IsNative() const {
return true;
}
u64 NativeClock::GetHostCNTFRQ() {
s64 NativeClock::GetHostCNTFRQ() {
u64 cntfrq_el0 = 0;
std::string_view board{""};
#ifdef ANDROID

View File

@ -17,17 +17,15 @@ public:
std::chrono::milliseconds GetTimeMS() const override;
u64 GetCNTPCT() const override;
s64 GetCNTPCT() const override;
u64 GetGPUTick() const override;
s64 GetGPUTick() const override;
u64 GetHostTicksNow() const override;
u64 GetHostTicksElapsed() const override;
s64 GetUptime() const override;
bool IsNative() const override;
static u64 GetHostCNTFRQ();
static s64 GetHostCNTFRQ();
public:
using FactorType = unsigned __int128;

View File

@ -18,4 +18,4 @@ struct MemoryInfo {
*/
[[nodiscard]] const MemoryInfo& GetMemInfo();
} // namespace Common
} // namespace Common

93
src/common/range_mutex.h Normal file
View File

@ -0,0 +1,93 @@
// SPDX-FileCopyrightText: 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <condition_variable>
#include <mutex>
#include "common/intrusive_list.h"
namespace Common {
class ScopedRangeLock;
class RangeMutex {
public:
explicit RangeMutex() = default;
~RangeMutex() = default;
private:
friend class ScopedRangeLock;
void Lock(ScopedRangeLock& l);
void Unlock(ScopedRangeLock& l);
bool HasIntersectionLocked(ScopedRangeLock& l);
private:
std::mutex m_mutex;
std::condition_variable m_cv;
using LockList = Common::IntrusiveListBaseTraits<ScopedRangeLock>::ListType;
LockList m_list;
};
class ScopedRangeLock : public Common::IntrusiveListBaseNode<ScopedRangeLock> {
public:
explicit ScopedRangeLock(RangeMutex& mutex, u64 address, u64 size)
: m_mutex(mutex), m_address(address), m_size(size) {
if (m_size > 0) {
m_mutex.Lock(*this);
}
}
~ScopedRangeLock() {
if (m_size > 0) {
m_mutex.Unlock(*this);
}
}
u64 GetAddress() const {
return m_address;
}
u64 GetSize() const {
return m_size;
}
private:
RangeMutex& m_mutex;
const u64 m_address{};
const u64 m_size{};
};
inline void RangeMutex::Lock(ScopedRangeLock& l) {
std::unique_lock lk{m_mutex};
m_cv.wait(lk, [&] { return !HasIntersectionLocked(l); });
m_list.push_back(l);
}
inline void RangeMutex::Unlock(ScopedRangeLock& l) {
{
std::scoped_lock lk{m_mutex};
m_list.erase(m_list.iterator_to(l));
}
m_cv.notify_all();
}
inline bool RangeMutex::HasIntersectionLocked(ScopedRangeLock& l) {
const auto cur_begin = l.GetAddress();
const auto cur_last = l.GetAddress() + l.GetSize() - 1;
for (const auto& other : m_list) {
const auto other_begin = other.GetAddress();
const auto other_last = other.GetAddress() + other.GetSize() - 1;
if (cur_begin <= other_last && other_begin <= cur_last) {
return true;
}
}
return false;
}
} // namespace Common

View File

@ -419,9 +419,16 @@ struct Values {
linkage, false, "custom_rtc_enabled", Category::System, Specialization::Paired, true, true};
SwitchableSetting<s64> custom_rtc{
linkage, 0, "custom_rtc", Category::System, Specialization::Time,
true, true, &custom_rtc_enabled};
// Set on game boot, reset on stop. Seconds difference between current time and `custom_rtc`
s64 custom_rtc_differential;
false, true, &custom_rtc_enabled};
SwitchableSetting<s64, true> custom_rtc_offset{linkage,
0,
std::numeric_limits<int>::min(),
std::numeric_limits<int>::max(),
"custom_rtc_offset",
Category::System,
Specialization::Countable,
true,
true};
SwitchableSetting<bool> rng_seed_enabled{
linkage, false, "rng_seed_enabled", Category::System, Specialization::Paired, true, true};
SwitchableSetting<u32> rng_seed{

View File

@ -88,7 +88,17 @@ std::string FindSystemTimeZone() {
LOG_ERROR(Common, "Time zone {} not handled, defaulting to hour offset.", tz_index);
}
}
return fmt::format("Etc/GMT{:s}{:d}", hours > 0 ? "-" : "+", std::abs(hours));
// For some reason the Etc/GMT times are reversed. GMT+6 contains -21600 as its offset,
// -6 hours instead of +6 hours, so these signs are purposefully reversed to fix it.
std::string postfix{""};
if (hours > 0) {
postfix = fmt::format("-{:d}", std::abs(hours));
} else if (hours < 0) {
postfix = fmt::format("+{:d}", std::abs(hours));
}
return fmt::format("Etc/GMT{:s}", postfix);
}
} // namespace Common::TimeZone

View File

@ -12,9 +12,8 @@
namespace Common {
struct UUID {
std::array<u8, 0x10> uuid{};
std::array<u8, 0x10> uuid;
/// Constructs an invalid UUID.
constexpr UUID() = default;
/// Constructs a UUID from a reference to a 128 bit array.
@ -34,14 +33,6 @@ struct UUID {
*/
explicit UUID(std::string_view uuid_string);
~UUID() = default;
constexpr UUID(const UUID&) noexcept = default;
constexpr UUID(UUID&&) noexcept = default;
constexpr UUID& operator=(const UUID&) noexcept = default;
constexpr UUID& operator=(UUID&&) noexcept = default;
/**
* Returns whether the stored UUID is valid or not.
*
@ -121,6 +112,7 @@ struct UUID {
friend constexpr bool operator==(const UUID& lhs, const UUID& rhs) = default;
};
static_assert(sizeof(UUID) == 0x10, "UUID has incorrect size.");
static_assert(std::is_trivial_v<UUID>);
/// An invalid UUID. This UUID has all its bytes set to 0.
constexpr UUID InvalidUUID = {};

View File

@ -18,42 +18,40 @@ namespace Common {
class StandardWallClock final : public WallClock {
public:
explicit StandardWallClock() : start_time{SteadyClock::Now()} {}
explicit StandardWallClock() {}
std::chrono::nanoseconds GetTimeNS() const override {
return SteadyClock::Now() - start_time;
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now().time_since_epoch());
}
std::chrono::microseconds GetTimeUS() const override {
return static_cast<std::chrono::microseconds>(GetHostTicksElapsed() / NsToUsRatio::den);
return std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::system_clock::now().time_since_epoch());
}
std::chrono::milliseconds GetTimeMS() const override {
return static_cast<std::chrono::milliseconds>(GetHostTicksElapsed() / NsToMsRatio::den);
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch());
}
u64 GetCNTPCT() const override {
return GetHostTicksElapsed() * NsToCNTPCTRatio::num / NsToCNTPCTRatio::den;
s64 GetCNTPCT() const override {
return GetUptime() * NsToCNTPCTRatio::num / NsToCNTPCTRatio::den;
}
u64 GetGPUTick() const override {
return GetHostTicksElapsed() * NsToGPUTickRatio::num / NsToGPUTickRatio::den;
s64 GetGPUTick() const override {
return GetUptime() * NsToGPUTickRatio::num / NsToGPUTickRatio::den;
}
u64 GetHostTicksNow() const override {
return static_cast<u64>(SteadyClock::Now().time_since_epoch().count());
}
u64 GetHostTicksElapsed() const override {
return static_cast<u64>(GetTimeNS().count());
s64 GetUptime() const override {
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
bool IsNative() const override {
return false;
}
private:
SteadyClock::time_point start_time;
};
std::unique_ptr<WallClock> CreateOptimalClock() {

View File

@ -29,16 +29,13 @@ public:
virtual std::chrono::milliseconds GetTimeMS() const = 0;
/// @returns The guest CNTPCT ticks since the construction of this clock.
virtual u64 GetCNTPCT() const = 0;
virtual s64 GetCNTPCT() const = 0;
/// @returns The guest GPU ticks since the construction of this clock.
virtual u64 GetGPUTick() const = 0;
virtual s64 GetGPUTick() const = 0;
/// @returns The raw host timer ticks since an indeterminate epoch.
virtual u64 GetHostTicksNow() const = 0;
/// @returns The raw host timer ticks since the construction of this clock.
virtual u64 GetHostTicksElapsed() const = 0;
virtual s64 GetUptime() const = 0;
/// @returns Whether the clock directly uses the host's hardware clock.
virtual bool IsNative() const = 0;

View File

@ -8,39 +8,35 @@
namespace Common::X64 {
NativeClock::NativeClock(u64 rdtsc_frequency_)
: start_ticks{FencedRDTSC()}, rdtsc_frequency{rdtsc_frequency_},
ns_rdtsc_factor{GetFixedPoint64Factor(NsRatio::den, rdtsc_frequency)},
: rdtsc_frequency{rdtsc_frequency_}, ns_rdtsc_factor{GetFixedPoint64Factor(NsRatio::den,
rdtsc_frequency)},
us_rdtsc_factor{GetFixedPoint64Factor(UsRatio::den, rdtsc_frequency)},
ms_rdtsc_factor{GetFixedPoint64Factor(MsRatio::den, rdtsc_frequency)},
cntpct_rdtsc_factor{GetFixedPoint64Factor(CNTFRQ, rdtsc_frequency)},
gputick_rdtsc_factor{GetFixedPoint64Factor(GPUTickFreq, rdtsc_frequency)} {}
std::chrono::nanoseconds NativeClock::GetTimeNS() const {
return std::chrono::nanoseconds{MultiplyHigh(GetHostTicksElapsed(), ns_rdtsc_factor)};
return std::chrono::nanoseconds{MultiplyHigh(GetUptime(), ns_rdtsc_factor)};
}
std::chrono::microseconds NativeClock::GetTimeUS() const {
return std::chrono::microseconds{MultiplyHigh(GetHostTicksElapsed(), us_rdtsc_factor)};
return std::chrono::microseconds{MultiplyHigh(GetUptime(), us_rdtsc_factor)};
}
std::chrono::milliseconds NativeClock::GetTimeMS() const {
return std::chrono::milliseconds{MultiplyHigh(GetHostTicksElapsed(), ms_rdtsc_factor)};
return std::chrono::milliseconds{MultiplyHigh(GetUptime(), ms_rdtsc_factor)};
}
u64 NativeClock::GetCNTPCT() const {
return MultiplyHigh(GetHostTicksElapsed(), cntpct_rdtsc_factor);
s64 NativeClock::GetCNTPCT() const {
return MultiplyHigh(GetUptime(), cntpct_rdtsc_factor);
}
u64 NativeClock::GetGPUTick() const {
return MultiplyHigh(GetHostTicksElapsed(), gputick_rdtsc_factor);
s64 NativeClock::GetGPUTick() const {
return MultiplyHigh(GetUptime(), gputick_rdtsc_factor);
}
u64 NativeClock::GetHostTicksNow() const {
return FencedRDTSC();
}
u64 NativeClock::GetHostTicksElapsed() const {
return FencedRDTSC() - start_ticks;
s64 NativeClock::GetUptime() const {
return static_cast<s64>(FencedRDTSC());
}
bool NativeClock::IsNative() const {

View File

@ -17,18 +17,15 @@ public:
std::chrono::milliseconds GetTimeMS() const override;
u64 GetCNTPCT() const override;
s64 GetCNTPCT() const override;
u64 GetGPUTick() const override;
s64 GetGPUTick() const override;
u64 GetHostTicksNow() const override;
u64 GetHostTicksElapsed() const override;
s64 GetUptime() const override;
bool IsNative() const override;
private:
u64 start_ticks;
u64 rdtsc_frequency;
u64 ns_rdtsc_factor;

View File

@ -472,6 +472,8 @@ add_library(core STATIC
hle/service/caps/caps_types.h
hle/service/caps/caps_u.cpp
hle/service/caps/caps_u.h
hle/service/cmif_serialization.h
hle/service/cmif_types.h
hle/service/erpt/erpt.cpp
hle/service/erpt/erpt.h
hle/service/es/es.cpp
@ -515,6 +517,24 @@ add_library(core STATIC
hle/service/glue/glue_manager.h
hle/service/glue/notif.cpp
hle/service/glue/notif.h
hle/service/glue/time/alarm_worker.cpp
hle/service/glue/time/alarm_worker.h
hle/service/glue/time/file_timestamp_worker.cpp
hle/service/glue/time/file_timestamp_worker.h
hle/service/glue/time/manager.cpp
hle/service/glue/time/manager.h
hle/service/glue/time/pm_state_change_handler.cpp
hle/service/glue/time/pm_state_change_handler.h
hle/service/glue/time/standard_steady_clock_resource.cpp
hle/service/glue/time/standard_steady_clock_resource.h
hle/service/glue/time/static.cpp
hle/service/glue/time/static.h
hle/service/glue/time/time_zone.cpp
hle/service/glue/time/time_zone.h
hle/service/glue/time/time_zone_binary.cpp
hle/service/glue/time/time_zone_binary.h
hle/service/glue/time/worker.cpp
hle/service/glue/time/worker.h
hle/service/grc/grc.cpp
hle/service/grc/grc.h
hle/service/hid/hid.cpp
@ -693,6 +713,46 @@ add_library(core STATIC
hle/service/prepo/prepo.h
hle/service/psc/psc.cpp
hle/service/psc/psc.h
hle/service/psc/time/alarms.cpp
hle/service/psc/time/alarms.h
hle/service/psc/time/clocks/context_writers.cpp
hle/service/psc/time/clocks/context_writers.h
hle/service/psc/time/clocks/ephemeral_network_system_clock_core.h
hle/service/psc/time/clocks/standard_local_system_clock_core.cpp
hle/service/psc/time/clocks/standard_local_system_clock_core.h
hle/service/psc/time/clocks/standard_network_system_clock_core.cpp
hle/service/psc/time/clocks/standard_network_system_clock_core.h
hle/service/psc/time/clocks/standard_steady_clock_core.cpp
hle/service/psc/time/clocks/standard_steady_clock_core.h
hle/service/psc/time/clocks/standard_user_system_clock_core.cpp
hle/service/psc/time/clocks/standard_user_system_clock_core.h
hle/service/psc/time/clocks/steady_clock_core.h
hle/service/psc/time/clocks/system_clock_core.cpp
hle/service/psc/time/clocks/system_clock_core.h
hle/service/psc/time/clocks/tick_based_steady_clock_core.cpp
hle/service/psc/time/clocks/tick_based_steady_clock_core.h
hle/service/psc/time/common.cpp
hle/service/psc/time/common.h
hle/service/psc/time/errors.h
hle/service/psc/time/shared_memory.cpp
hle/service/psc/time/shared_memory.h
hle/service/psc/time/static.cpp
hle/service/psc/time/static.h
hle/service/psc/time/manager.h
hle/service/psc/time/power_state_service.cpp
hle/service/psc/time/power_state_service.h
hle/service/psc/time/service_manager.cpp
hle/service/psc/time/service_manager.h
hle/service/psc/time/steady_clock.cpp
hle/service/psc/time/steady_clock.h
hle/service/psc/time/system_clock.cpp
hle/service/psc/time/system_clock.h
hle/service/psc/time/time_zone.cpp
hle/service/psc/time/time_zone.h
hle/service/psc/time/time_zone_service.cpp
hle/service/psc/time/time_zone_service.h
hle/service/psc/time/power_state_request_manager.cpp
hle/service/psc/time/power_state_request_manager.h
hle/service/ptm/psm.cpp
hle/service/ptm/psm.h
hle/service/ptm/ptm.cpp
@ -760,40 +820,6 @@ add_library(core STATIC
hle/service/ssl/ssl.cpp
hle/service/ssl/ssl.h
hle/service/ssl/ssl_backend.h
hle/service/time/clock_types.h
hle/service/time/ephemeral_network_system_clock_context_writer.h
hle/service/time/ephemeral_network_system_clock_core.h
hle/service/time/errors.h
hle/service/time/local_system_clock_context_writer.h
hle/service/time/network_system_clock_context_writer.h
hle/service/time/standard_local_system_clock_core.h
hle/service/time/standard_network_system_clock_core.h
hle/service/time/standard_steady_clock_core.cpp
hle/service/time/standard_steady_clock_core.h
hle/service/time/standard_user_system_clock_core.cpp
hle/service/time/standard_user_system_clock_core.h
hle/service/time/steady_clock_core.h
hle/service/time/system_clock_context_update_callback.cpp
hle/service/time/system_clock_context_update_callback.h
hle/service/time/system_clock_core.cpp
hle/service/time/system_clock_core.h
hle/service/time/tick_based_steady_clock_core.cpp
hle/service/time/tick_based_steady_clock_core.h
hle/service/time/time.cpp
hle/service/time/time.h
hle/service/time/time_interface.cpp
hle/service/time/time_interface.h
hle/service/time/time_manager.cpp
hle/service/time/time_manager.h
hle/service/time/time_sharedmemory.cpp
hle/service/time/time_sharedmemory.h
hle/service/time/time_zone_content_manager.cpp
hle/service/time/time_zone_content_manager.h
hle/service/time/time_zone_manager.cpp
hle/service/time/time_zone_manager.h
hle/service/time/time_zone_service.cpp
hle/service/time/time_zone_service.h
hle/service/time/time_zone_types.h
hle/service/usb/usb.cpp
hle/service/usb/usb.h
hle/service/vi/display/vi_display.cpp
@ -874,7 +900,7 @@ endif()
create_target_directory_groups(core)
target_link_libraries(core PUBLIC common PRIVATE audio_core hid_core network video_core nx_tzdb)
target_link_libraries(core PUBLIC common PRIVATE audio_core hid_core network video_core nx_tzdb tz)
target_link_libraries(core PUBLIC Boost::headers PRIVATE fmt::fmt nlohmann_json::nlohmann_json mbedtls RenderDoc::API)
if (MINGW)
target_link_libraries(core PRIVATE ${MSWSOCK_LIBRARY})

View File

@ -40,9 +40,14 @@
#include "core/hle/service/apm/apm_controller.h"
#include "core/hle/service/filesystem/filesystem.h"
#include "core/hle/service/glue/glue_manager.h"
#include "core/hle/service/glue/time/static.h"
#include "core/hle/service/psc/time/static.h"
#include "core/hle/service/psc/time/steady_clock.h"
#include "core/hle/service/psc/time/system_clock.h"
#include "core/hle/service/psc/time/time_zone_service.h"
#include "core/hle/service/service.h"
#include "core/hle/service/set/system_settings_server.h"
#include "core/hle/service/sm/sm.h"
#include "core/hle/service/time/time_manager.h"
#include "core/internal_network/network.h"
#include "core/loader/loader.h"
#include "core/memory.h"
@ -130,8 +135,8 @@ FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs,
struct System::Impl {
explicit Impl(System& system)
: kernel{system}, fs_controller{system}, hid_core{}, room_network{}, cpu_manager{system},
reporter{system}, applet_manager{system}, profile_manager{}, time_manager{system} {}
: kernel{system}, fs_controller{system}, hid_core{}, room_network{},
cpu_manager{system}, reporter{system}, applet_manager{system}, profile_manager{} {}
void Initialize(System& system) {
device_memory = std::make_unique<Core::DeviceMemory>();
@ -143,8 +148,6 @@ struct System::Impl {
core_timing.SetMulticore(is_multicore);
core_timing.Initialize([&system]() { system.RegisterHostThread(); });
RefreshTime();
// Create a default fs if one doesn't already exist.
if (virtual_filesystem == nullptr) {
virtual_filesystem = std::make_shared<FileSys::RealVfsFilesystem>();
@ -182,14 +185,57 @@ struct System::Impl {
Initialize(system);
}
void RefreshTime() {
void RefreshTime(System& system) {
if (!system.IsPoweredOn()) {
return;
}
auto settings_service =
system.ServiceManager().GetService<Service::Set::ISystemSettingsServer>("set:sys",
true);
auto static_service_a =
system.ServiceManager().GetService<Service::Glue::Time::StaticService>("time:a", true);
auto static_service_s =
system.ServiceManager().GetService<Service::PSC::Time::StaticService>("time:s", true);
std::shared_ptr<Service::PSC::Time::SystemClock> user_clock;
static_service_a->GetStandardUserSystemClock(user_clock);
std::shared_ptr<Service::PSC::Time::SystemClock> local_clock;
static_service_a->GetStandardLocalSystemClock(local_clock);
std::shared_ptr<Service::PSC::Time::SystemClock> network_clock;
static_service_s->GetStandardNetworkSystemClock(network_clock);
std::shared_ptr<Service::Glue::Time::TimeZoneService> timezone_service;
static_service_a->GetTimeZoneService(timezone_service);
Service::PSC::Time::LocationName name{};
auto new_name = Settings::GetTimeZoneString(Settings::values.time_zone_index.GetValue());
std::memcpy(name.name.data(), new_name.data(), std::min(name.name.size(), new_name.size()));
timezone_service->SetDeviceLocation(name);
u64 time_offset = 0;
if (Settings::values.custom_rtc_enabled) {
time_offset = Settings::values.custom_rtc_offset.GetValue();
}
const auto posix_time = std::chrono::system_clock::now().time_since_epoch();
const auto current_time =
std::chrono::duration_cast<std::chrono::seconds>(posix_time).count();
Settings::values.custom_rtc_differential =
(Settings::values.custom_rtc_enabled ? Settings::values.custom_rtc.GetValue()
: current_time) -
current_time;
const u64 current_time =
+std::chrono::duration_cast<std::chrono::seconds>(posix_time).count();
const u64 new_time = current_time + time_offset;
Service::PSC::Time::SystemClockContext context{};
settings_service->SetUserSystemClockContext(context);
user_clock->SetCurrentTime(new_time);
local_clock->SetCurrentTime(new_time);
network_clock->GetSystemClockContext(context);
settings_service->SetNetworkSystemClockContext(context);
network_clock->SetCurrentTime(new_time);
}
void Run() {
@ -265,9 +311,6 @@ struct System::Impl {
service_manager = std::make_shared<Service::SM::ServiceManager>(kernel);
services = std::make_unique<Service::Services>(service_manager, system);
// Initialize time manager, which must happen after kernel is created
time_manager.Initialize();
is_powered_on = true;
exit_locked = false;
exit_requested = false;
@ -417,7 +460,6 @@ struct System::Impl {
fs_controller.Reset();
cheat_engine.reset();
telemetry_session.reset();
time_manager.Shutdown();
core_timing.ClearPendingEvents();
app_loader.reset();
audio_core.reset();
@ -533,7 +575,6 @@ struct System::Impl {
/// Service State
Service::Glue::ARPManager arp_manager;
Service::Account::ProfileManager profile_manager;
Service::Time::TimeManager time_manager;
/// Service manager
std::shared_ptr<Service::SM::ServiceManager> service_manager;
@ -911,14 +952,6 @@ const Service::Account::ProfileManager& System::GetProfileManager() const {
return impl->profile_manager;
}
Service::Time::TimeManager& System::GetTimeManager() {
return impl->time_manager;
}
const Service::Time::TimeManager& System::GetTimeManager() const {
return impl->time_manager;
}
void System::SetExitLocked(bool locked) {
impl->exit_locked = locked;
}
@ -1030,13 +1063,9 @@ void System::Exit() {
}
void System::ApplySettings() {
impl->RefreshTime();
impl->RefreshTime(*this);
if (IsPoweredOn()) {
if (Settings::values.custom_rtc_enabled) {
const s64 posix_time{Settings::values.custom_rtc.GetValue()};
GetTimeManager().UpdateLocalSystemClockTime(posix_time);
}
Renderer().RefreshBaseSettings();
}
}

View File

@ -73,10 +73,6 @@ namespace SM {
class ServiceManager;
} // namespace SM
namespace Time {
class TimeManager;
} // namespace Time
} // namespace Service
namespace Tegra {
@ -381,9 +377,6 @@ public:
[[nodiscard]] Service::Account::ProfileManager& GetProfileManager();
[[nodiscard]] const Service::Account::ProfileManager& GetProfileManager() const;
[[nodiscard]] Service::Time::TimeManager& GetTimeManager();
[[nodiscard]] const Service::Time::TimeManager& GetTimeManager() const;
[[nodiscard]] Core::Debugger& GetDebugger();
[[nodiscard]] const Core::Debugger& GetDebugger() const;

View File

@ -157,7 +157,7 @@ void CoreTiming::UnscheduleEvent(const std::shared_ptr<EventType>& event_type,
}
}
for (auto h : to_remove) {
for (auto& h : to_remove) {
event_queue.erase(h);
}

View File

@ -10,6 +10,7 @@
#include <mutex>
#include "common/common_types.h"
#include "common/range_mutex.h"
#include "common/scratch_buffer.h"
#include "common/virtual_buffer.h"
@ -204,7 +205,7 @@ private:
(1ULL << (device_virtual_bits - page_bits)) / subentries;
using CachedPages = std::array<CounterEntry, num_counter_entries>;
std::unique_ptr<CachedPages> cached_pages;
std::mutex counter_guard;
Common::RangeMutex counter_guard;
std::mutex mapping_guard;
};

View File

@ -508,12 +508,7 @@ void DeviceMemoryManager<Traits>::UnregisterProcess(Asid asid) {
template <typename Traits>
void DeviceMemoryManager<Traits>::UpdatePagesCachedCount(DAddr addr, size_t size, s32 delta) {
std::unique_lock<std::mutex> lk(counter_guard, std::defer_lock);
const auto Lock = [&] {
if (!lk) {
lk.lock();
}
};
Common::ScopedRangeLock lk(counter_guard, addr, size);
u64 uncache_begin = 0;
u64 cache_begin = 0;
u64 uncache_bytes = 0;
@ -548,7 +543,6 @@ void DeviceMemoryManager<Traits>::UpdatePagesCachedCount(DAddr addr, size_t size
}
uncache_bytes += Memory::YUZU_PAGESIZE;
} else if (uncache_bytes > 0) {
Lock();
MarkRegionCaching(memory_device_inter, uncache_begin << Memory::YUZU_PAGEBITS,
uncache_bytes, false);
uncache_bytes = 0;
@ -559,7 +553,6 @@ void DeviceMemoryManager<Traits>::UpdatePagesCachedCount(DAddr addr, size_t size
}
cache_bytes += Memory::YUZU_PAGESIZE;
} else if (cache_bytes > 0) {
Lock();
MarkRegionCaching(memory_device_inter, cache_begin << Memory::YUZU_PAGEBITS, cache_bytes,
true);
cache_bytes = 0;
@ -567,12 +560,10 @@ void DeviceMemoryManager<Traits>::UpdatePagesCachedCount(DAddr addr, size_t size
vpage++;
}
if (uncache_bytes > 0) {
Lock();
MarkRegionCaching(memory_device_inter, uncache_begin << Memory::YUZU_PAGEBITS, uncache_bytes,
false);
}
if (cache_bytes > 0) {
Lock();
MarkRegionCaching(memory_device_inter, cache_begin << Memory::YUZU_PAGEBITS, cache_bytes,
true);
}

View File

@ -67,25 +67,29 @@ constexpr std::array<SystemArchiveDescriptor, SYSTEM_ARCHIVE_COUNT> SYSTEM_ARCHI
}};
VirtualFile SynthesizeSystemArchive(const u64 title_id) {
if (title_id < SYSTEM_ARCHIVES.front().title_id || title_id > SYSTEM_ARCHIVES.back().title_id)
if (title_id < SYSTEM_ARCHIVES.front().title_id || title_id > SYSTEM_ARCHIVES.back().title_id) {
return nullptr;
}
const auto& desc = SYSTEM_ARCHIVES[title_id - SYSTEM_ARCHIVE_BASE_TITLE_ID];
LOG_INFO(Service_FS, "Synthesizing system archive '{}' (0x{:016X}).", desc.name, desc.title_id);
if (desc.supplier == nullptr)
if (desc.supplier == nullptr) {
return nullptr;
}
const auto dir = desc.supplier();
if (dir == nullptr)
if (dir == nullptr) {
return nullptr;
}
const auto romfs = CreateRomFS(dir);
if (romfs == nullptr)
if (romfs == nullptr) {
return nullptr;
}
LOG_INFO(Service_FS, " - System archive generation successful!");
return romfs;

View File

@ -6,7 +6,6 @@
#include "common/swap.h"
#include "core/file_sys/system_archive/time_zone_binary.h"
#include "core/file_sys/vfs_vector.h"
#include "core/hle/service/time/time_zone_types.h"
#include "nx_tzdb.h"

View File

@ -69,9 +69,14 @@ public:
};
template <typename AddressType>
void InvalidateInstructionCache(KernelCore& kernel, AddressType addr, u64 size) {
void InvalidateInstructionCache(KernelCore& kernel, KPageTableBase* table, AddressType addr,
u64 size) {
// TODO: lock the process list
for (auto& process : kernel.GetProcessList()) {
if (std::addressof(process->GetPageTable().GetBasePageTable()) != table) {
continue;
}
for (size_t i = 0; i < Core::Hardware::NUM_CPU_CORES; i++) {
auto* interface = process->GetArmInterface(i);
if (interface) {
@ -1302,7 +1307,7 @@ Result KPageTableBase::UnmapCodeMemory(KProcessAddress dst_address, KProcessAddr
bool reprotected_pages = false;
SCOPE_EXIT({
if (reprotected_pages && any_code_pages) {
InvalidateInstructionCache(m_kernel, dst_address, size);
InvalidateInstructionCache(m_kernel, this, dst_address, size);
}
});
@ -2036,7 +2041,7 @@ Result KPageTableBase::SetProcessMemoryPermission(KProcessAddress addr, size_t s
for (const auto& block : pg) {
StoreDataCache(GetHeapVirtualPointer(m_kernel, block.GetAddress()), block.GetSize());
}
InvalidateInstructionCache(m_kernel, addr, size);
InvalidateInstructionCache(m_kernel, this, addr, size);
}
R_SUCCEED();
@ -3277,7 +3282,7 @@ Result KPageTableBase::WriteDebugMemory(KProcessAddress dst_address, KProcessAdd
R_TRY(PerformCopy());
// Invalidate the instruction cache, as this svc allows modifying executable pages.
InvalidateInstructionCache(m_kernel, dst_address, size);
InvalidateInstructionCache(m_kernel, this, dst_address, size);
R_SUCCEED();
}

View File

@ -10,8 +10,10 @@
#include "core/core.h"
#include "core/hle/service/caps/caps_manager.h"
#include "core/hle/service/caps/caps_result.h"
#include "core/hle/service/time/time_manager.h"
#include "core/hle/service/time/time_zone_content_manager.h"
#include "core/hle/service/glue/time/static.h"
#include "core/hle/service/psc/time/system_clock.h"
#include "core/hle/service/service.h"
#include "core/hle/service/sm/sm.h"
namespace Service::Capture {
@ -239,10 +241,15 @@ Result AlbumManager::SaveScreenShot(ApplicationAlbumEntry& out_entry,
const ApplicationData& app_data, std::span<const u8> image_data,
u64 aruid) {
const u64 title_id = system.GetApplicationProcessProgramID();
const auto& user_clock = system.GetTimeManager().GetStandardUserSystemClockCore();
auto static_service =
system.ServiceManager().GetService<Service::Glue::Time::StaticService>("time:u", true);
std::shared_ptr<Service::PSC::Time::SystemClock> user_clock{};
static_service->GetStandardUserSystemClock(user_clock);
s64 posix_time{};
Result result = user_clock.GetCurrentTime(system, posix_time);
auto result = user_clock->GetCurrentTime(posix_time);
if (result.IsError()) {
return result;
@ -257,10 +264,14 @@ Result AlbumManager::SaveEditedScreenShot(ApplicationAlbumEntry& out_entry,
const ScreenShotAttribute& attribute,
const AlbumFileId& file_id,
std::span<const u8> image_data) {
const auto& user_clock = system.GetTimeManager().GetStandardUserSystemClockCore();
auto static_service =
system.ServiceManager().GetService<Service::Glue::Time::StaticService>("time:u", true);
std::shared_ptr<Service::PSC::Time::SystemClock> user_clock{};
static_service->GetStandardUserSystemClock(user_clock);
s64 posix_time{};
Result result = user_clock.GetCurrentTime(system, posix_time);
auto result = user_clock->GetCurrentTime(posix_time);
if (result.IsError()) {
return result;
@ -455,19 +466,23 @@ Result AlbumManager::SaveImage(ApplicationAlbumEntry& out_entry, std::span<const
}
AlbumFileDateTime AlbumManager::ConvertToAlbumDateTime(u64 posix_time) const {
Time::TimeZone::CalendarInfo calendar_date{};
const auto& time_zone_manager =
system.GetTimeManager().GetTimeZoneContentManager().GetTimeZoneManager();
auto static_service =
system.ServiceManager().GetService<Service::Glue::Time::StaticService>("time:u", true);
time_zone_manager.ToCalendarTimeWithMyRules(posix_time, calendar_date);
std::shared_ptr<Service::Glue::Time::TimeZoneService> timezone_service{};
static_service->GetTimeZoneService(timezone_service);
Service::PSC::Time::CalendarTime calendar_time{};
Service::PSC::Time::CalendarAdditionalInfo additional_info{};
timezone_service->ToCalendarTimeWithMyRule(calendar_time, additional_info, posix_time);
return {
.year = calendar_date.time.year,
.month = calendar_date.time.month,
.day = calendar_date.time.day,
.hour = calendar_date.time.hour,
.minute = calendar_date.time.minute,
.second = calendar_date.time.second,
.year = calendar_time.year,
.month = calendar_time.month,
.day = calendar_time.day,
.hour = calendar_time.hour,
.minute = calendar_time.minute,
.second = calendar_time.second,
.unique_id = 0,
};
}

View File

@ -0,0 +1,337 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include "common/div_ceil.h"
#include "core/hle/service/cmif_types.h"
#include "core/hle/service/ipc_helpers.h"
#include "core/hle/service/service.h"
namespace Service {
// clang-format off
struct RequestLayout {
u32 copy_handle_count;
u32 move_handle_count;
u32 cmif_raw_data_size;
u32 domain_interface_count;
};
template <ArgumentType Type1, ArgumentType Type2, typename MethodArguments, size_t PrevAlign = 1, size_t DataOffset = 0, size_t ArgIndex = 0>
constexpr u32 GetArgumentRawDataSize() {
if constexpr (ArgIndex >= std::tuple_size_v<MethodArguments>) {
return static_cast<u32>(DataOffset);
} else {
using ArgType = std::tuple_element_t<ArgIndex, MethodArguments>;
if constexpr (ArgumentTraits<ArgType>::Type == Type1 || ArgumentTraits<ArgType>::Type == Type2) {
constexpr size_t ArgAlign = alignof(ArgType);
constexpr size_t ArgSize = sizeof(ArgType);
static_assert(PrevAlign <= ArgAlign, "Input argument is not ordered by alignment");
constexpr size_t ArgOffset = Common::AlignUp(DataOffset, ArgAlign);
constexpr size_t ArgEnd = ArgOffset + ArgSize;
return GetArgumentRawDataSize<Type1, Type2, MethodArguments, ArgAlign, ArgEnd, ArgIndex + 1>();
} else {
return GetArgumentRawDataSize<Type1, Type2, MethodArguments, PrevAlign, DataOffset, ArgIndex + 1>();
}
}
}
template <ArgumentType DataType, typename MethodArguments, size_t ArgCount = 0, size_t ArgIndex = 0>
constexpr u32 GetArgumentTypeCount() {
if constexpr (ArgIndex >= std::tuple_size_v<MethodArguments>) {
return static_cast<u32>(ArgCount);
} else {
using ArgType = std::tuple_element_t<ArgIndex, MethodArguments>;
if constexpr (ArgumentTraits<ArgType>::Type == DataType) {
return GetArgumentTypeCount<DataType, MethodArguments, ArgCount + 1, ArgIndex + 1>();
} else {
return GetArgumentTypeCount<DataType, MethodArguments, ArgCount, ArgIndex + 1>();
}
}
}
template <typename MethodArguments>
constexpr RequestLayout GetNonDomainReplyInLayout() {
return RequestLayout{
.copy_handle_count = GetArgumentTypeCount<ArgumentType::InCopyHandle, MethodArguments>(),
.move_handle_count = 0,
.cmif_raw_data_size = GetArgumentRawDataSize<ArgumentType::InData, ArgumentType::InProcessId, MethodArguments>(),
.domain_interface_count = 0,
};
}
template <typename MethodArguments>
constexpr RequestLayout GetDomainReplyInLayout() {
return RequestLayout{
.copy_handle_count = GetArgumentTypeCount<ArgumentType::InCopyHandle, MethodArguments>(),
.move_handle_count = 0,
.cmif_raw_data_size = GetArgumentRawDataSize<ArgumentType::InData, ArgumentType::InProcessId, MethodArguments>(),
.domain_interface_count = GetArgumentTypeCount<ArgumentType::InInterface, MethodArguments>(),
};
}
template <typename MethodArguments>
constexpr RequestLayout GetNonDomainReplyOutLayout() {
return RequestLayout{
.copy_handle_count = GetArgumentTypeCount<ArgumentType::OutCopyHandle, MethodArguments>(),
.move_handle_count = GetArgumentTypeCount<ArgumentType::OutMoveHandle, MethodArguments>() + GetArgumentTypeCount<ArgumentType::OutInterface, MethodArguments>(),
.cmif_raw_data_size = GetArgumentRawDataSize<ArgumentType::OutData, ArgumentType::OutData, MethodArguments>(),
.domain_interface_count = 0,
};
}
template <typename MethodArguments>
constexpr RequestLayout GetDomainReplyOutLayout() {
return RequestLayout{
.copy_handle_count = GetArgumentTypeCount<ArgumentType::OutCopyHandle, MethodArguments>(),
.move_handle_count = GetArgumentTypeCount<ArgumentType::OutMoveHandle, MethodArguments>(),
.cmif_raw_data_size = GetArgumentRawDataSize<ArgumentType::OutData, ArgumentType::OutData, MethodArguments>(),
.domain_interface_count = GetArgumentTypeCount<ArgumentType::OutInterface, MethodArguments>(),
};
}
template <bool Domain, typename MethodArguments>
constexpr RequestLayout GetReplyInLayout() {
return Domain ? GetDomainReplyInLayout<MethodArguments>() : GetNonDomainReplyInLayout<MethodArguments>();
}
template <bool Domain, typename MethodArguments>
constexpr RequestLayout GetReplyOutLayout() {
return Domain ? GetDomainReplyOutLayout<MethodArguments>() : GetNonDomainReplyOutLayout<MethodArguments>();
}
using OutTemporaryBuffers = std::array<Common::ScratchBuffer<u8>, 3>;
template <bool Domain, typename MethodArguments, typename CallArguments, size_t PrevAlign = 1, size_t DataOffset = 0, size_t HandleIndex = 0, size_t InBufferIndex = 0, size_t OutBufferIndex = 0, bool RawDataFinished = false, size_t ArgIndex = 0>
void ReadInArgument(CallArguments& args, const u8* raw_data, HLERequestContext& ctx, OutTemporaryBuffers& temp) {
if constexpr (ArgIndex >= std::tuple_size_v<CallArguments>) {
return;
} else {
using ArgType = std::tuple_element_t<ArgIndex, MethodArguments>;
if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::InData || ArgumentTraits<ArgType>::Type == ArgumentType::InProcessId) {
constexpr size_t ArgAlign = alignof(ArgType);
constexpr size_t ArgSize = sizeof(ArgType);
static_assert(PrevAlign <= ArgAlign, "Input argument is not ordered by alignment");
static_assert(!RawDataFinished, "All input interface arguments must appear after raw data");
constexpr size_t ArgOffset = Common::AlignUp(DataOffset, ArgAlign);
constexpr size_t ArgEnd = ArgOffset + ArgSize;
if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::InProcessId) {
// TODO: abort parsing if PID is not provided?
// TODO: validate against raw data value?
std::get<ArgIndex>(args).pid = ctx.GetPID();
} else {
std::memcpy(&std::get<ArgIndex>(args), raw_data + ArgOffset, ArgSize);
}
return ReadInArgument<Domain, MethodArguments, CallArguments, ArgAlign, ArgEnd, HandleIndex, InBufferIndex, OutBufferIndex, false, ArgIndex + 1>(args, raw_data, ctx, temp);
} else if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::InInterface) {
constexpr size_t ArgAlign = alignof(u32);
constexpr size_t ArgSize = sizeof(u32);
constexpr size_t ArgOffset = Common::AlignUp(DataOffset, ArgAlign);
constexpr size_t ArgEnd = ArgOffset + ArgSize;
static_assert(Domain);
ASSERT(ctx.GetDomainMessageHeader().input_object_count > 0);
u32 value{};
std::memcpy(&value, raw_data + ArgOffset, ArgSize);
std::get<ArgIndex>(args) = ctx.GetDomainHandler<ArgType::Type>(value - 1);
return ReadInArgument<Domain, MethodArguments, CallArguments, ArgAlign, ArgEnd, HandleIndex, InBufferIndex, OutBufferIndex, true, ArgIndex + 1>(args, raw_data, ctx, temp);
} else if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::InCopyHandle) {
std::get<ArgIndex>(args) = std::move(ctx.GetObjectFromHandle<typename ArgType::Type>(ctx.GetCopyHandle(HandleIndex)));
return ReadInArgument<Domain, MethodArguments, CallArguments, PrevAlign, DataOffset, HandleIndex + 1, InBufferIndex, OutBufferIndex, RawDataFinished, ArgIndex + 1>(args, raw_data, ctx, temp);
} else if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::InLargeData) {
constexpr size_t BufferSize = sizeof(ArgType);
// Clear the existing data.
std::memset(&std::get<ArgIndex>(args), 0, BufferSize);
std::span<const u8> buffer{};
ASSERT(ctx.CanReadBuffer(InBufferIndex));
if constexpr (ArgType::Attr & BufferAttr_HipcAutoSelect) {
buffer = ctx.ReadBuffer(InBufferIndex);
} else if constexpr (ArgType::Attr & BufferAttr_HipcMapAlias) {
buffer = ctx.ReadBufferA(InBufferIndex);
} else /* if (ArgType::Attr & BufferAttr_HipcPointer) */ {
buffer = ctx.ReadBufferX(InBufferIndex);
}
std::memcpy(&std::get<ArgIndex>(args), buffer.data(), std::min(BufferSize, buffer.size()));
return ReadInArgument<Domain, MethodArguments, CallArguments, PrevAlign, DataOffset, HandleIndex, InBufferIndex + 1, OutBufferIndex, RawDataFinished, ArgIndex + 1>(args, raw_data, ctx, temp);
} else if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::InBuffer) {
using ElementType = typename ArgType::Type;
std::span<const u8> buffer{};
if (ctx.CanReadBuffer(InBufferIndex)) {
if constexpr (ArgType::Attr & BufferAttr_HipcAutoSelect) {
buffer = ctx.ReadBuffer(InBufferIndex);
} else if constexpr (ArgType::Attr & BufferAttr_HipcMapAlias) {
buffer = ctx.ReadBufferA(InBufferIndex);
} else /* if (ArgType::Attr & BufferAttr_HipcPointer) */ {
buffer = ctx.ReadBufferX(InBufferIndex);
}
}
ElementType* ptr = (ElementType*) buffer.data();
size_t size = buffer.size() / sizeof(ElementType);
std::get<ArgIndex>(args) = std::span(ptr, size);
return ReadInArgument<Domain, MethodArguments, CallArguments, PrevAlign, DataOffset, HandleIndex, InBufferIndex + 1, OutBufferIndex, RawDataFinished, ArgIndex + 1>(args, raw_data, ctx, temp);
} else if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::OutLargeData) {
constexpr size_t BufferSize = sizeof(ArgType);
// Clear the existing data.
std::memset(&std::get<ArgIndex>(args), 0, BufferSize);
return ReadInArgument<Domain, MethodArguments, CallArguments, PrevAlign, DataOffset, HandleIndex, InBufferIndex, OutBufferIndex + 1, RawDataFinished, ArgIndex + 1>(args, raw_data, ctx, temp);
} else if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::OutBuffer) {
using ElementType = typename ArgType::Type;
// Set up scratch buffer.
auto& buffer = temp[OutBufferIndex];
if (ctx.CanWriteBuffer(OutBufferIndex)) {
buffer.resize_destructive(ctx.GetWriteBufferSize(OutBufferIndex));
} else {
buffer.resize_destructive(0);
}
ElementType* ptr = (ElementType*) buffer.data();
size_t size = buffer.size() / sizeof(ElementType);
std::get<ArgIndex>(args) = std::span(ptr, size);
return ReadInArgument<Domain, MethodArguments, CallArguments, PrevAlign, DataOffset, HandleIndex, InBufferIndex, OutBufferIndex + 1, RawDataFinished, ArgIndex + 1>(args, raw_data, ctx, temp);
} else {
return ReadInArgument<Domain, MethodArguments, CallArguments, PrevAlign, DataOffset, HandleIndex, InBufferIndex, OutBufferIndex, RawDataFinished, ArgIndex + 1>(args, raw_data, ctx, temp);
}
}
}
template <bool Domain, typename MethodArguments, typename CallArguments, size_t PrevAlign = 1, size_t DataOffset = 0, size_t OutBufferIndex = 0, bool RawDataFinished = false, size_t ArgIndex = 0>
void WriteOutArgument(CallArguments& args, u8* raw_data, HLERequestContext& ctx, OutTemporaryBuffers& temp) {
if constexpr (ArgIndex >= std::tuple_size_v<CallArguments>) {
return;
} else {
using ArgType = std::tuple_element_t<ArgIndex, MethodArguments>;
if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::OutData) {
constexpr size_t ArgAlign = alignof(ArgType);
constexpr size_t ArgSize = sizeof(ArgType);
static_assert(PrevAlign <= ArgAlign, "Output argument is not ordered by alignment");
static_assert(!RawDataFinished, "All output interface arguments must appear after raw data");
constexpr size_t ArgOffset = Common::AlignUp(DataOffset, ArgAlign);
constexpr size_t ArgEnd = ArgOffset + ArgSize;
std::memcpy(raw_data + ArgOffset, &std::get<ArgIndex>(args), ArgSize);
return WriteOutArgument<Domain, MethodArguments, CallArguments, ArgAlign, ArgEnd, OutBufferIndex, false, ArgIndex + 1>(args, raw_data, ctx, temp);
} else if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::OutInterface) {
if constexpr (Domain) {
ctx.AddDomainObject(std::get<ArgIndex>(args));
} else {
ctx.AddMoveInterface(std::get<ArgIndex>(args));
}
return WriteOutArgument<Domain, MethodArguments, CallArguments, PrevAlign, DataOffset, OutBufferIndex, true, ArgIndex + 1>(args, raw_data, ctx, temp);
} else if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::OutCopyHandle) {
ctx.AddCopyObject(std::get<ArgIndex>(args).GetPointerUnsafe());
return WriteOutArgument<Domain, MethodArguments, CallArguments, PrevAlign, DataOffset, OutBufferIndex, RawDataFinished, ArgIndex + 1>(args, raw_data, ctx, temp);
} else if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::OutMoveHandle) {
ctx.AddMoveObject(std::get<ArgIndex>(args).GetPointerUnsafe());
return WriteOutArgument<Domain, MethodArguments, CallArguments, PrevAlign, DataOffset, OutBufferIndex, RawDataFinished, ArgIndex + 1>(args, raw_data, ctx, temp);
} else if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::OutLargeData) {
constexpr size_t BufferSize = sizeof(ArgType);
ASSERT(ctx.CanWriteBuffer(OutBufferIndex));
if constexpr (ArgType::Attr & BufferAttr_HipcAutoSelect) {
ctx.WriteBuffer(std::get<ArgIndex>(args), OutBufferIndex);
} else if constexpr (ArgType::Attr & BufferAttr_HipcMapAlias) {
ctx.WriteBufferB(&std::get<ArgIndex>(args), BufferSize, OutBufferIndex);
} else /* if (ArgType::Attr & BufferAttr_HipcPointer) */ {
ctx.WriteBufferC(&std::get<ArgIndex>(args), BufferSize, OutBufferIndex);
}
return WriteOutArgument<Domain, MethodArguments, CallArguments, PrevAlign, DataOffset, OutBufferIndex + 1, RawDataFinished, ArgIndex + 1>(args, raw_data, ctx, temp);
} else if constexpr (ArgumentTraits<ArgType>::Type == ArgumentType::OutBuffer) {
auto& buffer = temp[OutBufferIndex];
const size_t size = buffer.size();
if (ctx.CanWriteBuffer(OutBufferIndex)) {
if constexpr (ArgType::Attr & BufferAttr_HipcAutoSelect) {
ctx.WriteBuffer(buffer.data(), size, OutBufferIndex);
} else if constexpr (ArgType::Attr & BufferAttr_HipcMapAlias) {
ctx.WriteBufferB(buffer.data(), size, OutBufferIndex);
} else /* if (ArgType::Attr & BufferAttr_HipcPointer) */ {
ctx.WriteBufferC(buffer.data(), size, OutBufferIndex);
}
}
return WriteOutArgument<Domain, MethodArguments, CallArguments, PrevAlign, DataOffset, OutBufferIndex + 1, RawDataFinished, ArgIndex + 1>( args, raw_data, ctx, temp);
} else {
return WriteOutArgument<Domain, MethodArguments, CallArguments, PrevAlign, DataOffset, OutBufferIndex, RawDataFinished, ArgIndex + 1>(args, raw_data, ctx, temp);
}
}
}
template <bool Domain, typename T, typename... A>
void CmifReplyWrapImpl(HLERequestContext& ctx, T& t, Result (T::*f)(A...)) {
// Verify domain state.
if constexpr (Domain) {
ASSERT_MSG(ctx.GetManager()->IsDomain(), "Domain reply used on non-domain session");
} else {
ASSERT_MSG(!ctx.GetManager()->IsDomain(), "Non-domain reply used on domain session");
}
using MethodArguments = std::tuple<std::remove_reference_t<A>...>;
OutTemporaryBuffers buffers{};
auto call_arguments = std::tuple<typename RemoveOut<A>::Type...>();
// Read inputs.
const size_t offset_plus_command_id = ctx.GetDataPayloadOffset() + 2;
ReadInArgument<Domain, MethodArguments>(call_arguments, reinterpret_cast<u8*>(ctx.CommandBuffer() + offset_plus_command_id), ctx, buffers);
// Call.
const auto Callable = [&]<typename... CallArgs>(CallArgs&... args) {
return (t.*f)(args...);
};
const Result res = std::apply(Callable, call_arguments);
// Write result.
constexpr RequestLayout layout = GetReplyOutLayout<Domain, MethodArguments>();
IPC::ResponseBuilder rb{ctx, 2 + Common::DivCeil(layout.cmif_raw_data_size, sizeof(u32)), layout.copy_handle_count, layout.move_handle_count + layout.domain_interface_count};
rb.Push(res);
// Write out arguments.
WriteOutArgument<Domain, MethodArguments>(call_arguments, reinterpret_cast<u8*>(ctx.CommandBuffer() + rb.GetCurrentOffset()), ctx, buffers);
}
// clang-format on
template <typename Self>
template <bool Domain, auto F>
inline void ServiceFramework<Self>::CmifReplyWrap(HLERequestContext& ctx) {
return CmifReplyWrapImpl<Domain>(ctx, *static_cast<Self*>(this), F);
}
} // namespace Service

View File

@ -0,0 +1,234 @@
// SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <memory>
#include "common/common_funcs.h"
#include "common/common_types.h"
#include "core/hle/service/hle_ipc.h"
namespace Service {
// clang-format off
template <typename T>
class Out {
public:
/* implicit */ Out(T& t) : raw(&t) {}
~Out() = default;
T* Get() const {
return raw;
}
T& operator*() {
return *raw;
}
private:
T* raw;
};
template <typename T>
using SharedPointer = std::shared_ptr<T>;
struct ClientProcessId {
explicit operator bool() const {
return pid != 0;
}
const u64& operator*() const {
return pid;
}
u64 pid;
};
using ClientAppletResourceUserId = ClientProcessId;
template <typename T>
class InCopyHandle : public Kernel::KScopedAutoObject<T> {
public:
using Type = T;
template <typename... Args>
/* implicit */ InCopyHandle(Args&&... args) : Kernel::KScopedAutoObject<T>(std::forward<Args...>(args)...) {}
~InCopyHandle() = default;
InCopyHandle& operator=(InCopyHandle&& rhs) {
Kernel::KScopedAutoObject<T>::operator=(std::move(rhs));
return *this;
}
};
template <typename T>
class OutCopyHandle : public Kernel::KScopedAutoObject<T> {
public:
using Type = T;
template <typename... Args>
/* implicit */ OutCopyHandle(Args&&... args) : Kernel::KScopedAutoObject<T>(std::forward<Args...>(args)...) {}
~OutCopyHandle() = default;
OutCopyHandle& operator=(OutCopyHandle&& rhs) {
Kernel::KScopedAutoObject<T>::operator=(std::move(rhs));
return *this;
}
};
template <typename T>
class OutMoveHandle : public Kernel::KScopedAutoObject<T> {
public:
using Type = T;
template <typename... Args>
/* implicit */ OutMoveHandle(Args&&... args) : Kernel::KScopedAutoObject<T>(std::forward<Args...>(args)...) {}
~OutMoveHandle() = default;
OutMoveHandle& operator=(OutMoveHandle&& rhs) {
Kernel::KScopedAutoObject<T>::operator=(std::move(rhs));
return *this;
}
};
enum BufferAttr : int {
BufferAttr_In = (1U << 0),
BufferAttr_Out = (1U << 1),
BufferAttr_HipcMapAlias = (1U << 2),
BufferAttr_HipcPointer = (1U << 3),
BufferAttr_FixedSize = (1U << 4),
BufferAttr_HipcAutoSelect = (1U << 5),
BufferAttr_HipcMapTransferAllowsNonSecure = (1U << 6),
BufferAttr_HipcMapTransferAllowsNonDevice = (1U << 7),
};
template <typename T, int A>
struct Buffer : public std::span<T> {
static_assert(std::is_trivial_v<T>, "Buffer type must be trivial");
static_assert((A & BufferAttr_FixedSize) == 0, "Buffer attr must not contain FixedSize");
static_assert(((A & BufferAttr_In) == 0) ^ ((A & BufferAttr_Out) == 0), "Buffer attr must be In or Out");
static constexpr BufferAttr Attr = static_cast<BufferAttr>(A);
using Type = T;
Buffer& operator=(const std::span<T>& rhs) {
std::span<T>::operator=(rhs);
return *this;
}
T& operator*() const {
return *this->data();
}
explicit operator bool() const {
return this->size() > 0;
}
};
template <BufferAttr A>
using InBuffer = Buffer<const u8, BufferAttr_In | A>;
template <typename T, BufferAttr A>
using InArray = Buffer<T, BufferAttr_In | A>;
template <BufferAttr A>
using OutBuffer = Buffer<u8, BufferAttr_Out | A>;
template <typename T, BufferAttr A>
using OutArray = Buffer<T, BufferAttr_Out | A>;
template <typename T, int A>
struct LargeData : public T {
static_assert(std::is_trivial_v<T>, "LargeData type must be trivial");
static_assert((A & BufferAttr_FixedSize) != 0, "LargeData attr must contain FixedSize");
static_assert(((A & BufferAttr_In) == 0) ^ ((A & BufferAttr_Out) == 0), "LargeData attr must be In or Out");
static constexpr BufferAttr Attr = static_cast<BufferAttr>(A);
using Type = T;
};
template <typename T, BufferAttr A>
using InLargeData = LargeData<T, BufferAttr_FixedSize | BufferAttr_In | A>;
template <typename T, BufferAttr A>
using OutLargeData = LargeData<T, BufferAttr_FixedSize | BufferAttr_Out | A>;
template <typename T>
struct RemoveOut {
using Type = std::remove_reference_t<T>;
};
template <typename T>
struct RemoveOut<Out<T>> {
using Type = T;
};
enum class ArgumentType {
InProcessId,
InData,
InInterface,
InCopyHandle,
OutData,
OutInterface,
OutCopyHandle,
OutMoveHandle,
InBuffer,
InLargeData,
OutBuffer,
OutLargeData,
};
template <typename T>
struct ArgumentTraits;
template <>
struct ArgumentTraits<ClientProcessId> {
static constexpr ArgumentType Type = ArgumentType::InProcessId;
};
template <typename T>
struct ArgumentTraits<SharedPointer<T>> {
static constexpr ArgumentType Type = ArgumentType::InInterface;
};
template <typename T>
struct ArgumentTraits<InCopyHandle<T>> {
static constexpr ArgumentType Type = ArgumentType::InCopyHandle;
};
template <typename T>
struct ArgumentTraits<Out<SharedPointer<T>>> {
static constexpr ArgumentType Type = ArgumentType::OutInterface;
};
template <typename T>
struct ArgumentTraits<Out<T>> {
static constexpr ArgumentType Type = ArgumentType::OutData;
};
template <typename T>
struct ArgumentTraits<OutCopyHandle<T>> {
static constexpr ArgumentType Type = ArgumentType::OutCopyHandle;
};
template <typename T>
struct ArgumentTraits<OutMoveHandle<T>> {
static constexpr ArgumentType Type = ArgumentType::OutMoveHandle;
};
template <typename T, int A>
struct ArgumentTraits<Buffer<T, A>> {
static constexpr ArgumentType Type = (A & BufferAttr_In) == 0 ? ArgumentType::OutBuffer : ArgumentType::InBuffer;
};
template <typename T, int A>
struct ArgumentTraits<LargeData<T, A>> {
static constexpr ArgumentType Type = (A & BufferAttr_In) == 0 ? ArgumentType::OutLargeData : ArgumentType::InLargeData;
};
template <typename T>
struct ArgumentTraits {
static constexpr ArgumentType Type = ArgumentType::InData;
};
// clang-format on
} // namespace Service

View File

@ -8,6 +8,9 @@
#include "core/hle/service/glue/ectx.h"
#include "core/hle/service/glue/glue.h"
#include "core/hle/service/glue/notif.h"
#include "core/hle/service/glue/time/manager.h"
#include "core/hle/service/glue/time/static.h"
#include "core/hle/service/psc/time/common.h"
#include "core/hle/service/server_manager.h"
namespace Service::Glue {
@ -31,6 +34,22 @@ void LoopProcess(Core::System& system) {
// Notification Services for application
server_manager->RegisterNamedService("notif:a", std::make_shared<NOTIF_A>(system));
// Time
auto time = std::make_shared<Time::TimeManager>(system);
server_manager->RegisterNamedService(
"time:u",
std::make_shared<Time::StaticService>(
system, Service::PSC::Time::StaticServiceSetupInfo{0, 0, 0, 0, 0, 0}, time, "time:u"));
server_manager->RegisterNamedService(
"time:a",
std::make_shared<Time::StaticService>(
system, Service::PSC::Time::StaticServiceSetupInfo{1, 1, 0, 1, 0, 0}, time, "time:a"));
server_manager->RegisterNamedService(
"time:r",
std::make_shared<Time::StaticService>(
system, Service::PSC::Time::StaticServiceSetupInfo{0, 0, 0, 0, 1, 0}, time, "time:r"));
ServerManager::RunServer(std::move(server_manager));
}

View File

@ -0,0 +1,82 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/core.h"
#include "core/core_timing.h"
#include "core/hle/kernel/svc.h"
#include "core/hle/service/glue/time/alarm_worker.h"
#include "core/hle/service/psc/time/service_manager.h"
#include "core/hle/service/sm/sm.h"
namespace Service::Glue::Time {
AlarmWorker::AlarmWorker(Core::System& system, StandardSteadyClockResource& steady_clock_resource)
: m_system{system}, m_ctx{system, "Glue:AlarmWorker"}, m_steady_clock_resource{
steady_clock_resource} {}
AlarmWorker::~AlarmWorker() {
m_system.CoreTiming().UnscheduleEvent(m_timer_timing_event);
m_ctx.CloseEvent(m_timer_event);
}
void AlarmWorker::Initialize(std::shared_ptr<Service::PSC::Time::ServiceManager> time_m) {
m_time_m = std::move(time_m);
m_timer_event = m_ctx.CreateEvent("Glue:AlarmWorker:TimerEvent");
m_timer_timing_event = Core::Timing::CreateEvent(
"Glue:AlarmWorker::AlarmTimer",
[this](s64 time,
std::chrono::nanoseconds ns_late) -> std::optional<std::chrono::nanoseconds> {
m_timer_event->Signal();
return std::nullopt;
});
AttachToClosestAlarmEvent();
}
bool AlarmWorker::GetClosestAlarmInfo(Service::PSC::Time::AlarmInfo& out_alarm_info,
s64& out_time) {
bool is_valid{};
Service::PSC::Time::AlarmInfo alarm_info{};
s64 closest_time{};
auto res = m_time_m->GetClosestAlarmInfo(is_valid, alarm_info, closest_time);
ASSERT(res == ResultSuccess);
if (is_valid) {
out_alarm_info = alarm_info;
out_time = closest_time;
}
return is_valid;
}
void AlarmWorker::OnPowerStateChanged() {
Service::PSC::Time::AlarmInfo closest_alarm_info{};
s64 closest_time{};
if (!GetClosestAlarmInfo(closest_alarm_info, closest_time)) {
m_system.CoreTiming().UnscheduleEvent(m_timer_timing_event);
m_timer_event->Clear();
return;
}
if (closest_alarm_info.alert_time <= closest_time) {
m_time_m->CheckAndSignalAlarms();
} else {
auto next_time{closest_alarm_info.alert_time - closest_time};
m_system.CoreTiming().UnscheduleEvent(m_timer_timing_event);
m_timer_event->Clear();
m_system.CoreTiming().ScheduleEvent(std::chrono::nanoseconds(next_time),
m_timer_timing_event);
}
}
Result AlarmWorker::AttachToClosestAlarmEvent() {
m_time_m->GetClosestAlarmUpdatedEvent(&m_event);
R_SUCCEED();
}
} // namespace Service::Glue::Time

View File

@ -0,0 +1,53 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include "common/common_types.h"
#include "core/hle/kernel/k_event.h"
#include "core/hle/service/kernel_helpers.h"
#include "core/hle/service/psc/time/common.h"
namespace Core {
class System;
}
namespace Service::PSC::Time {
class ServiceManager;
}
namespace Service::Glue::Time {
class StandardSteadyClockResource;
class AlarmWorker {
public:
explicit AlarmWorker(Core::System& system, StandardSteadyClockResource& steady_clock_resource);
~AlarmWorker();
void Initialize(std::shared_ptr<Service::PSC::Time::ServiceManager> time_m);
Kernel::KEvent& GetEvent() {
return *m_event;
}
Kernel::KEvent& GetTimerEvent() {
return *m_timer_event;
}
void OnPowerStateChanged();
private:
bool GetClosestAlarmInfo(Service::PSC::Time::AlarmInfo& out_alarm_info, s64& out_time);
Result AttachToClosestAlarmEvent();
Core::System& m_system;
KernelHelpers::ServiceContext m_ctx;
std::shared_ptr<Service::PSC::Time::ServiceManager> m_time_m;
Kernel::KEvent* m_event{};
Kernel::KEvent* m_timer_event{};
std::shared_ptr<Core::Timing::EventType> m_timer_timing_event;
StandardSteadyClockResource& m_steady_clock_resource;
};
} // namespace Service::Glue::Time

View File

@ -0,0 +1,23 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/hle/service/glue/time/file_timestamp_worker.h"
#include "core/hle/service/psc/time/common.h"
#include "core/hle/service/psc/time/system_clock.h"
#include "core/hle/service/psc/time/time_zone_service.h"
namespace Service::Glue::Time {
void FileTimestampWorker::SetFilesystemPosixTime() {
s64 time{};
Service::PSC::Time::CalendarTime calendar_time{};
Service::PSC::Time::CalendarAdditionalInfo additional_info{};
if (m_initialized && m_system_clock->GetCurrentTime(time) == ResultSuccess &&
m_time_zone->ToCalendarTimeWithMyRule(calendar_time, additional_info, time) ==
ResultSuccess) {
// TODO IFileSystemProxy::SetCurrentPosixTime
}
}
} // namespace Service::Glue::Time

View File

@ -0,0 +1,28 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <memory>
#include "common/common_types.h"
namespace Service::PSC::Time {
class SystemClock;
class TimeZoneService;
} // namespace Service::PSC::Time
namespace Service::Glue::Time {
class FileTimestampWorker {
public:
FileTimestampWorker() = default;
void SetFilesystemPosixTime();
std::shared_ptr<Service::PSC::Time::SystemClock> m_system_clock{};
std::shared_ptr<Service::PSC::Time::TimeZoneService> m_time_zone{};
bool m_initialized{};
};
} // namespace Service::Glue::Time

View File

@ -0,0 +1,277 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <chrono>
#include "core/core.h"
#include "core/core_timing.h"
#include "common/settings.h"
#include "common/time_zone.h"
#include "core/file_sys/vfs.h"
#include "core/hle/kernel/svc.h"
#include "core/hle/service/glue/time/manager.h"
#include "core/hle/service/glue/time/time_zone_binary.h"
#include "core/hle/service/psc/time/service_manager.h"
#include "core/hle/service/psc/time/static.h"
#include "core/hle/service/psc/time/system_clock.h"
#include "core/hle/service/psc/time/time_zone_service.h"
#include "core/hle/service/set/system_settings_server.h"
#include "core/hle/service/sm/sm.h"
namespace Service::Glue::Time {
namespace {
template <typename T>
T GetSettingsItemValue(std::shared_ptr<Service::Set::ISystemSettingsServer>& set_sys,
const char* category, const char* name) {
std::vector<u8> interval_buf;
auto res = set_sys->GetSettingsItemValue(interval_buf, category, name);
ASSERT(res == ResultSuccess);
T v{};
std::memcpy(&v, interval_buf.data(), sizeof(T));
return v;
}
s64 CalendarTimeToEpoch(Service::PSC::Time::CalendarTime calendar) {
constexpr auto is_leap = [](s32 year) -> bool {
return (((year) % 4) == 0 && (((year) % 100) != 0 || ((year) % 400) == 0));
};
constexpr std::array<s32, 12> MonthStartDayOfYear{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334,
};
s16 month_s16{calendar.month};
s8 month{static_cast<s8>(((month_s16 * 43) & ~std::numeric_limits<s16>::max()) +
((month_s16 * 43) >> 9))};
s8 month_index{static_cast<s8>(calendar.month - 12 * month)};
if (month_index == 0) {
month_index = 12;
}
s32 year{(month + calendar.year) - !month_index};
s32 v8{year >= 0 ? year : year + 3};
s64 days_since_epoch = calendar.day + MonthStartDayOfYear[month_index - 1];
days_since_epoch += (year * 365) + (v8 / 4) - (year / 100) + (year / 400) - 365;
if (month_index <= 2 && is_leap(year)) {
days_since_epoch--;
}
auto epoch_s{((24ll * days_since_epoch + calendar.hour) * 60ll + calendar.minute) * 60ll +
calendar.second};
return epoch_s - 62135683200ll;
}
s64 GetEpochTimeFromInitialYear(std::shared_ptr<Service::Set::ISystemSettingsServer>& set_sys) {
Service::PSC::Time::CalendarTime calendar{
.year = GetSettingsItemValue<s16>(set_sys, "time", "standard_user_clock_initial_year"),
.month = 1,
.day = 1,
.hour = 0,
.minute = 0,
.second = 0,
};
return CalendarTimeToEpoch(calendar);
}
Service::PSC::Time::LocationName GetTimeZoneString(Service::PSC::Time::LocationName& in_name) {
auto configured_zone = Settings::GetTimeZoneString(Settings::values.time_zone_index.GetValue());
Service::PSC::Time::LocationName configured_name{};
std::memcpy(configured_name.name.data(), configured_zone.data(),
std::min(configured_name.name.size(), configured_zone.size()));
if (!IsTimeZoneBinaryValid(configured_name)) {
configured_zone = Common::TimeZone::FindSystemTimeZone();
configured_name = {};
std::memcpy(configured_name.name.data(), configured_zone.data(),
std::min(configured_name.name.size(), configured_zone.size()));
}
ASSERT_MSG(IsTimeZoneBinaryValid(configured_name), "Invalid time zone {}!",
configured_name.name.data());
return configured_name;
}
} // namespace
TimeManager::TimeManager(Core::System& system)
: m_steady_clock_resource{system}, m_worker{system, m_steady_clock_resource,
m_file_timestamp_worker} {
m_time_m =
system.ServiceManager().GetService<Service::PSC::Time::ServiceManager>("time:m", true);
auto res = m_time_m->GetStaticServiceAsServiceManager(m_time_sm);
ASSERT(res == ResultSuccess);
m_set_sys =
system.ServiceManager().GetService<Service::Set::ISystemSettingsServer>("set:sys", true);
res = MountTimeZoneBinary(system);
ASSERT(res == ResultSuccess);
m_worker.Initialize(m_time_sm, m_set_sys);
res = m_time_sm->GetStandardUserSystemClock(m_file_timestamp_worker.m_system_clock);
ASSERT(res == ResultSuccess);
res = m_time_sm->GetTimeZoneService(m_file_timestamp_worker.m_time_zone);
ASSERT(res == ResultSuccess);
res = SetupStandardSteadyClockCore();
ASSERT(res == ResultSuccess);
Service::PSC::Time::SystemClockContext user_clock_context{};
res = m_set_sys->GetUserSystemClockContext(user_clock_context);
ASSERT(res == ResultSuccess);
// TODO the local clock should initialise with this epoch time, and be updated somewhere else on
// first boot to update it, but I haven't been able to find that point (likely via ntc's auto
// correct as it's defaulted to be enabled). So to get a time that isn't stuck in the past for
// first boot, grab the current real seconds.
auto epoch_time{GetEpochTimeFromInitialYear(m_set_sys)};
if (user_clock_context == Service::PSC::Time::SystemClockContext{}) {
m_steady_clock_resource.GetRtcTimeInSeconds(epoch_time);
}
res = m_time_m->SetupStandardLocalSystemClockCore(user_clock_context, epoch_time);
ASSERT(res == ResultSuccess);
Service::PSC::Time::SystemClockContext network_clock_context{};
res = m_set_sys->GetNetworkSystemClockContext(network_clock_context);
ASSERT(res == ResultSuccess);
auto network_accuracy_m{GetSettingsItemValue<s32>(
m_set_sys, "time", "standard_network_clock_sufficient_accuracy_minutes")};
auto one_minute_ns{
std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::minutes(1)).count()};
s64 network_accuracy_ns{network_accuracy_m * one_minute_ns};
res = m_time_m->SetupStandardNetworkSystemClockCore(network_clock_context, network_accuracy_ns);
ASSERT(res == ResultSuccess);
bool is_automatic_correction_enabled{};
res = m_set_sys->IsUserSystemClockAutomaticCorrectionEnabled(is_automatic_correction_enabled);
ASSERT(res == ResultSuccess);
Service::PSC::Time::SteadyClockTimePoint automatic_correction_time_point{};
res = m_set_sys->GetUserSystemClockAutomaticCorrectionUpdatedTime(
automatic_correction_time_point);
ASSERT(res == ResultSuccess);
res = m_time_m->SetupStandardUserSystemClockCore(automatic_correction_time_point,
is_automatic_correction_enabled);
ASSERT(res == ResultSuccess);
res = m_time_m->SetupEphemeralNetworkSystemClockCore();
ASSERT(res == ResultSuccess);
res = SetupTimeZoneServiceCore();
ASSERT(res == ResultSuccess);
s64 rtc_time_s{};
res = m_steady_clock_resource.GetRtcTimeInSeconds(rtc_time_s);
ASSERT(res == ResultSuccess);
// TODO system report "launch"
// "rtc_reset" = m_steady_clock_resource.m_rtc_reset
// "rtc_value" = rtc_time_s
m_worker.StartThread();
m_file_timestamp_worker.m_initialized = true;
s64 system_clock_time{};
if (m_file_timestamp_worker.m_system_clock->GetCurrentTime(system_clock_time) ==
ResultSuccess) {
Service::PSC::Time::CalendarTime calendar_time{};
Service::PSC::Time::CalendarAdditionalInfo calendar_additional{};
if (m_file_timestamp_worker.m_time_zone->ToCalendarTimeWithMyRule(
calendar_time, calendar_additional, system_clock_time) == ResultSuccess) {
// TODO IFileSystemProxy::SetCurrentPosixTime(system_clock_time,
// calendar_additional.ut_offset)
}
}
}
Result TimeManager::SetupStandardSteadyClockCore() {
Common::UUID external_clock_source_id{};
auto res = m_set_sys->GetExternalSteadyClockSourceId(external_clock_source_id);
ASSERT(res == ResultSuccess);
s64 external_steady_clock_internal_offset_s{};
res = m_set_sys->GetExternalSteadyClockInternalOffset(external_steady_clock_internal_offset_s);
ASSERT(res == ResultSuccess);
auto one_second_ns{
std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::seconds(1)).count()};
s64 external_steady_clock_internal_offset_ns{external_steady_clock_internal_offset_s *
one_second_ns};
s32 standard_steady_clock_test_offset_m{
GetSettingsItemValue<s32>(m_set_sys, "time", "standard_steady_clock_test_offset_minutes")};
auto one_minute_ns{
std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::minutes(1)).count()};
s64 standard_steady_clock_test_offset_ns{standard_steady_clock_test_offset_m * one_minute_ns};
auto reset_detected = m_steady_clock_resource.GetResetDetected();
if (reset_detected) {
external_clock_source_id = {};
}
Common::UUID clock_source_id{};
m_steady_clock_resource.Initialize(&clock_source_id, &external_clock_source_id);
if (clock_source_id != external_clock_source_id) {
m_set_sys->SetExternalSteadyClockSourceId(clock_source_id);
}
res = m_time_m->SetupStandardSteadyClockCore(clock_source_id, m_steady_clock_resource.GetTime(),
external_steady_clock_internal_offset_ns,
standard_steady_clock_test_offset_ns,
reset_detected);
ASSERT(res == ResultSuccess);
R_SUCCEED();
}
Result TimeManager::SetupTimeZoneServiceCore() {
Service::PSC::Time::LocationName name{};
auto res = m_set_sys->GetDeviceTimeZoneLocationName(name);
ASSERT(res == ResultSuccess);
auto configured_zone = GetTimeZoneString(name);
if (configured_zone.name != name.name) {
m_set_sys->SetDeviceTimeZoneLocationName(configured_zone);
name = configured_zone;
std::shared_ptr<Service::PSC::Time::SystemClock> local_clock;
m_time_sm->GetStandardLocalSystemClock(local_clock);
Service::PSC::Time::SystemClockContext context{};
local_clock->GetSystemClockContext(context);
m_set_sys->SetDeviceTimeZoneLocationUpdatedTime(context.steady_time_point);
}
Service::PSC::Time::SteadyClockTimePoint time_point{};
res = m_set_sys->GetDeviceTimeZoneLocationUpdatedTime(time_point);
ASSERT(res == ResultSuccess);
auto location_count = GetTimeZoneCount();
Service::PSC::Time::RuleVersion rule_version{};
GetTimeZoneVersion(rule_version);
std::span<const u8> rule_buffer{};
size_t rule_size{};
res = GetTimeZoneRule(rule_buffer, rule_size, name);
ASSERT(res == ResultSuccess);
res = m_time_m->SetupTimeZoneServiceCore(name, time_point, rule_version, location_count,
rule_buffer);
ASSERT(res == ResultSuccess);
R_SUCCEED();
}
} // namespace Service::Glue::Time

View File

@ -0,0 +1,42 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <functional>
#include <string>
#include "common/common_types.h"
#include "core/file_sys/vfs_types.h"
#include "core/hle/service/glue/time/file_timestamp_worker.h"
#include "core/hle/service/glue/time/standard_steady_clock_resource.h"
#include "core/hle/service/glue/time/worker.h"
#include "core/hle/service/service.h"
namespace Core {
class System;
}
namespace Service::PSC::Time {
class ServiceManager;
class StaticService;
} // namespace Service::PSC::Time
namespace Service::Glue::Time {
class TimeManager {
public:
explicit TimeManager(Core::System& system);
std::shared_ptr<Service::Set::ISystemSettingsServer> m_set_sys;
std::shared_ptr<Service::PSC::Time::ServiceManager> m_time_m{};
std::shared_ptr<Service::PSC::Time::StaticService> m_time_sm{};
StandardSteadyClockResource m_steady_clock_resource;
FileTimestampWorker m_file_timestamp_worker;
TimeWorker m_worker;
private:
Result SetupStandardSteadyClockCore();
Result SetupTimeZoneServiceCore();
};
} // namespace Service::Glue::Time

View File

@ -0,0 +1,13 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/hle/service/glue/time/pm_state_change_handler.h"
namespace Service::Glue::Time {
PmStateChangeHandler::PmStateChangeHandler(AlarmWorker& alarm_worker)
: m_alarm_worker{alarm_worker} {
// TODO Initialize IPmModule, dependent on Rtc and Fs
}
} // namespace Service::Glue::Time

View File

@ -0,0 +1,18 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include "common/common_types.h"
namespace Service::Glue::Time {
class AlarmWorker;
class PmStateChangeHandler {
public:
explicit PmStateChangeHandler(AlarmWorker& alarm_worker);
AlarmWorker& m_alarm_worker;
s32 m_priority{};
};
} // namespace Service::Glue::Time

View File

@ -0,0 +1,123 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <chrono>
#include "common/settings.h"
#include "core/core.h"
#include "core/core_timing.h"
#include "core/hle/kernel/svc.h"
#include "core/hle/service/glue/time/standard_steady_clock_resource.h"
#include "core/hle/service/psc/time/errors.h"
namespace Service::Glue::Time {
namespace {
[[maybe_unused]] constexpr u32 Max77620PmicSession = 0x3A000001;
[[maybe_unused]] constexpr u32 Max77620RtcSession = 0x3B000001;
Result GetTimeInSeconds(Core::System& system, s64& out_time_s) {
out_time_s = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
if (Settings::values.custom_rtc_enabled) {
out_time_s += Settings::values.custom_rtc_offset.GetValue();
}
R_SUCCEED();
}
} // namespace
StandardSteadyClockResource::StandardSteadyClockResource(Core::System& system) : m_system{system} {}
void StandardSteadyClockResource::Initialize(Common::UUID* out_source_id,
Common::UUID* external_source_id) {
constexpr size_t NUM_TRIES{20};
size_t i{0};
Result res{ResultSuccess};
for (; i < NUM_TRIES; i++) {
res = SetCurrentTime();
if (res == ResultSuccess) {
break;
}
Kernel::Svc::SleepThread(m_system, std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::milliseconds(1))
.count());
}
if (i < NUM_TRIES) {
m_set_time_result = ResultSuccess;
if (*external_source_id != Service::PSC::Time::ClockSourceId{}) {
m_clock_source_id = *external_source_id;
} else {
m_clock_source_id = Common::UUID::MakeRandom();
}
} else {
m_set_time_result = res;
auto ticks{m_system.CoreTiming().GetClockTicks()};
m_time = -Service::PSC::Time::ConvertToTimeSpan(ticks).count();
m_clock_source_id = Common::UUID::MakeRandom();
}
if (out_source_id) {
*out_source_id = m_clock_source_id;
}
}
bool StandardSteadyClockResource::GetResetDetected() {
// TODO:
// call Rtc::GetRtcResetDetected(Max77620RtcSession)
// if detected:
// SetSys::SetExternalSteadyClockSourceId(invalid_id)
// Rtc::ClearRtcResetDetected(Max77620RtcSession)
// set m_rtc_reset to result
// Instead, only set reset to true if we're booting for the first time.
m_rtc_reset = false;
return m_rtc_reset;
}
Result StandardSteadyClockResource::SetCurrentTime() {
auto start_tick{m_system.CoreTiming().GetClockTicks()};
s64 rtc_time_s{};
// TODO R_TRY(Rtc::GetTimeInSeconds(rtc_time_s, Max77620RtcSession))
R_TRY(GetTimeInSeconds(m_system, rtc_time_s));
auto end_tick{m_system.CoreTiming().GetClockTicks()};
auto diff{Service::PSC::Time::ConvertToTimeSpan(end_tick - start_tick)};
// Why is this here?
R_UNLESS(diff < std::chrono::milliseconds(101), Service::PSC::Time::ResultRtcTimeout);
auto one_second_ns{
std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::seconds(1)).count()};
s64 boot_time{rtc_time_s * one_second_ns -
Service::PSC::Time::ConvertToTimeSpan(end_tick).count()};
std::scoped_lock l{m_mutex};
m_time = boot_time;
R_SUCCEED();
}
Result StandardSteadyClockResource::GetRtcTimeInSeconds(s64& out_time) {
// TODO
// R_TRY(Rtc::GetTimeInSeconds(time_s, Max77620RtcSession)
R_RETURN(GetTimeInSeconds(m_system, out_time));
}
void StandardSteadyClockResource::UpdateTime() {
constexpr size_t NUM_TRIES{3};
size_t i{0};
Result res{ResultSuccess};
for (; i < NUM_TRIES; i++) {
res = SetCurrentTime();
if (res == ResultSuccess) {
break;
}
Kernel::Svc::SleepThread(m_system, std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::milliseconds(1))
.count());
}
}
} // namespace Service::Glue::Time

View File

@ -0,0 +1,41 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <mutex>
#include "common/common_types.h"
#include "core/hle/result.h"
#include "core/hle/service/psc/time/common.h"
namespace Core {
class System;
}
namespace Service::Glue::Time {
class StandardSteadyClockResource {
public:
StandardSteadyClockResource(Core::System& system);
void Initialize(Common::UUID* out_source_id, Common::UUID* external_source_id);
s64 GetTime() const {
return m_time;
}
bool GetResetDetected();
Result SetCurrentTime();
Result GetRtcTimeInSeconds(s64& out_time);
void UpdateTime();
private:
Core::System& m_system;
std::mutex m_mutex;
Service::PSC::Time::ClockSourceId m_clock_source_id{};
s64 m_time{};
Result m_set_time_result;
bool m_rtc_reset;
};
} // namespace Service::Glue::Time

View File

@ -0,0 +1,448 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <chrono>
#include "core/core.h"
#include "core/hle/kernel/k_shared_memory.h"
#include "core/hle/kernel/svc.h"
#include "core/hle/service/glue/time/file_timestamp_worker.h"
#include "core/hle/service/glue/time/static.h"
#include "core/hle/service/psc/time/errors.h"
#include "core/hle/service/psc/time/service_manager.h"
#include "core/hle/service/psc/time/static.h"
#include "core/hle/service/psc/time/steady_clock.h"
#include "core/hle/service/psc/time/system_clock.h"
#include "core/hle/service/psc/time/time_zone_service.h"
#include "core/hle/service/set/system_settings_server.h"
#include "core/hle/service/sm/sm.h"
namespace Service::Glue::Time {
namespace {
template <typename T>
T GetSettingsItemValue(std::shared_ptr<Service::Set::ISystemSettingsServer>& set_sys,
const char* category, const char* name) {
std::vector<u8> interval_buf;
auto res = set_sys->GetSettingsItemValue(interval_buf, category, name);
ASSERT(res == ResultSuccess);
T v{};
std::memcpy(&v, interval_buf.data(), sizeof(T));
return v;
}
} // namespace
StaticService::StaticService(Core::System& system_,
Service::PSC::Time::StaticServiceSetupInfo setup_info,
std::shared_ptr<TimeManager> time, const char* name)
: ServiceFramework{system_, name}, m_system{system_}, m_time_m{time->m_time_m},
m_setup_info{setup_info}, m_time_sm{time->m_time_sm},
m_file_timestamp_worker{time->m_file_timestamp_worker}, m_standard_steady_clock_resource{
time->m_steady_clock_resource} {
// clang-format off
static const FunctionInfo functions[] = {
{0, &StaticService::Handle_GetStandardUserSystemClock, "GetStandardUserSystemClock"},
{1, &StaticService::Handle_GetStandardNetworkSystemClock, "GetStandardNetworkSystemClock"},
{2, &StaticService::Handle_GetStandardSteadyClock, "GetStandardSteadyClock"},
{3, &StaticService::Handle_GetTimeZoneService, "GetTimeZoneService"},
{4, &StaticService::Handle_GetStandardLocalSystemClock, "GetStandardLocalSystemClock"},
{5, &StaticService::Handle_GetEphemeralNetworkSystemClock, "GetEphemeralNetworkSystemClock"},
{20, &StaticService::Handle_GetSharedMemoryNativeHandle, "GetSharedMemoryNativeHandle"},
{50, &StaticService::Handle_SetStandardSteadyClockInternalOffset, "SetStandardSteadyClockInternalOffset"},
{51, &StaticService::Handle_GetStandardSteadyClockRtcValue, "GetStandardSteadyClockRtcValue"},
{100, &StaticService::Handle_IsStandardUserSystemClockAutomaticCorrectionEnabled, "IsStandardUserSystemClockAutomaticCorrectionEnabled"},
{101, &StaticService::Handle_SetStandardUserSystemClockAutomaticCorrectionEnabled, "SetStandardUserSystemClockAutomaticCorrectionEnabled"},
{102, &StaticService::Handle_GetStandardUserSystemClockInitialYear, "GetStandardUserSystemClockInitialYear"},
{200, &StaticService::Handle_IsStandardNetworkSystemClockAccuracySufficient, "IsStandardNetworkSystemClockAccuracySufficient"},
{201, &StaticService::Handle_GetStandardUserSystemClockAutomaticCorrectionUpdatedTime, "GetStandardUserSystemClockAutomaticCorrectionUpdatedTime"},
{300, &StaticService::Handle_CalculateMonotonicSystemClockBaseTimePoint, "CalculateMonotonicSystemClockBaseTimePoint"},
{400, &StaticService::Handle_GetClockSnapshot, "GetClockSnapshot"},
{401, &StaticService::Handle_GetClockSnapshotFromSystemClockContext, "GetClockSnapshotFromSystemClockContext"},
{500, &StaticService::Handle_CalculateStandardUserSystemClockDifferenceByUser, "CalculateStandardUserSystemClockDifferenceByUser"},
{501, &StaticService::Handle_CalculateSpanBetween, "CalculateSpanBetween"},
};
// clang-format on
RegisterHandlers(functions);
m_set_sys =
m_system.ServiceManager().GetService<Service::Set::ISystemSettingsServer>("set:sys", true);
if (m_setup_info.can_write_local_clock && m_setup_info.can_write_user_clock &&
!m_setup_info.can_write_network_clock && m_setup_info.can_write_timezone_device_location &&
!m_setup_info.can_write_steady_clock && !m_setup_info.can_write_uninitialized_clock) {
m_time_m->GetStaticServiceAsAdmin(m_wrapped_service);
} else if (!m_setup_info.can_write_local_clock && !m_setup_info.can_write_user_clock &&
!m_setup_info.can_write_network_clock &&
!m_setup_info.can_write_timezone_device_location &&
!m_setup_info.can_write_steady_clock &&
!m_setup_info.can_write_uninitialized_clock) {
m_time_m->GetStaticServiceAsUser(m_wrapped_service);
} else if (!m_setup_info.can_write_local_clock && !m_setup_info.can_write_user_clock &&
!m_setup_info.can_write_network_clock &&
!m_setup_info.can_write_timezone_device_location &&
m_setup_info.can_write_steady_clock && !m_setup_info.can_write_uninitialized_clock) {
m_time_m->GetStaticServiceAsRepair(m_wrapped_service);
} else {
UNREACHABLE();
}
auto res = m_wrapped_service->GetTimeZoneService(m_time_zone);
ASSERT(res == ResultSuccess);
}
void StaticService::Handle_GetStandardUserSystemClock(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
std::shared_ptr<Service::PSC::Time::SystemClock> service{};
auto res = GetStandardUserSystemClock(service);
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(res);
rb.PushIpcInterface<Service::PSC::Time::SystemClock>(std::move(service));
}
void StaticService::Handle_GetStandardNetworkSystemClock(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
std::shared_ptr<Service::PSC::Time::SystemClock> service{};
auto res = GetStandardNetworkSystemClock(service);
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(res);
rb.PushIpcInterface<Service::PSC::Time::SystemClock>(std::move(service));
}
void StaticService::Handle_GetStandardSteadyClock(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
std::shared_ptr<Service::PSC::Time::SteadyClock> service{};
auto res = GetStandardSteadyClock(service);
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(res);
rb.PushIpcInterface(std::move(service));
}
void StaticService::Handle_GetTimeZoneService(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
std::shared_ptr<TimeZoneService> service{};
auto res = GetTimeZoneService(service);
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(res);
rb.PushIpcInterface(std::move(service));
}
void StaticService::Handle_GetStandardLocalSystemClock(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
std::shared_ptr<Service::PSC::Time::SystemClock> service{};
auto res = GetStandardLocalSystemClock(service);
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(res);
rb.PushIpcInterface<Service::PSC::Time::SystemClock>(std::move(service));
}
void StaticService::Handle_GetEphemeralNetworkSystemClock(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
std::shared_ptr<Service::PSC::Time::SystemClock> service{};
auto res = GetEphemeralNetworkSystemClock(service);
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(res);
rb.PushIpcInterface<Service::PSC::Time::SystemClock>(std::move(service));
}
void StaticService::Handle_GetSharedMemoryNativeHandle(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
Kernel::KSharedMemory* shared_memory{};
auto res = GetSharedMemoryNativeHandle(&shared_memory);
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(res);
rb.PushCopyObjects(shared_memory);
}
void StaticService::Handle_SetStandardSteadyClockInternalOffset(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::RequestParser rp{ctx};
auto offset_ns{rp.Pop<s64>()};
auto res = SetStandardSteadyClockInternalOffset(offset_ns);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(res);
}
void StaticService::Handle_GetStandardSteadyClockRtcValue(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
s64 rtc_value{};
auto res = GetStandardSteadyClockRtcValue(rtc_value);
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(res);
rb.Push(rtc_value);
}
void StaticService::Handle_IsStandardUserSystemClockAutomaticCorrectionEnabled(
HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
bool is_enabled{};
auto res = IsStandardUserSystemClockAutomaticCorrectionEnabled(is_enabled);
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(res);
rb.Push<bool>(is_enabled);
}
void StaticService::Handle_SetStandardUserSystemClockAutomaticCorrectionEnabled(
HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::RequestParser rp{ctx};
auto automatic_correction{rp.Pop<bool>()};
auto res = SetStandardUserSystemClockAutomaticCorrectionEnabled(automatic_correction);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(res);
}
void StaticService::Handle_GetStandardUserSystemClockInitialYear(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
s32 initial_year{};
auto res = GetStandardUserSystemClockInitialYear(initial_year);
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(res);
rb.Push(initial_year);
}
void StaticService::Handle_IsStandardNetworkSystemClockAccuracySufficient(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
bool is_sufficient{};
auto res = IsStandardNetworkSystemClockAccuracySufficient(is_sufficient);
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(res);
rb.Push<bool>(is_sufficient);
}
void StaticService::Handle_GetStandardUserSystemClockAutomaticCorrectionUpdatedTime(
HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
Service::PSC::Time::SteadyClockTimePoint time_point{};
auto res = GetStandardUserSystemClockAutomaticCorrectionUpdatedTime(time_point);
IPC::ResponseBuilder rb{ctx,
2 + sizeof(Service::PSC::Time::SteadyClockTimePoint) / sizeof(u32)};
rb.Push(res);
rb.PushRaw<Service::PSC::Time::SteadyClockTimePoint>(time_point);
}
void StaticService::Handle_CalculateMonotonicSystemClockBaseTimePoint(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::RequestParser rp{ctx};
auto context{rp.PopRaw<Service::PSC::Time::SystemClockContext>()};
s64 time{};
auto res = CalculateMonotonicSystemClockBaseTimePoint(time, context);
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(res);
rb.Push<s64>(time);
}
void StaticService::Handle_GetClockSnapshot(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::RequestParser rp{ctx};
auto type{rp.PopEnum<Service::PSC::Time::TimeType>()};
Service::PSC::Time::ClockSnapshot snapshot{};
auto res = GetClockSnapshot(snapshot, type);
ctx.WriteBuffer(snapshot);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(res);
}
void StaticService::Handle_GetClockSnapshotFromSystemClockContext(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::RequestParser rp{ctx};
auto clock_type{rp.PopEnum<Service::PSC::Time::TimeType>()};
[[maybe_unused]] auto alignment{rp.Pop<u32>()};
auto user_context{rp.PopRaw<Service::PSC::Time::SystemClockContext>()};
auto network_context{rp.PopRaw<Service::PSC::Time::SystemClockContext>()};
Service::PSC::Time::ClockSnapshot snapshot{};
auto res =
GetClockSnapshotFromSystemClockContext(snapshot, user_context, network_context, clock_type);
ctx.WriteBuffer(snapshot);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(res);
}
void StaticService::Handle_CalculateStandardUserSystemClockDifferenceByUser(
HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
Service::PSC::Time::ClockSnapshot a{};
Service::PSC::Time::ClockSnapshot b{};
auto a_buffer{ctx.ReadBuffer(0)};
auto b_buffer{ctx.ReadBuffer(1)};
std::memcpy(&a, a_buffer.data(), sizeof(Service::PSC::Time::ClockSnapshot));
std::memcpy(&b, b_buffer.data(), sizeof(Service::PSC::Time::ClockSnapshot));
s64 difference{};
auto res = CalculateStandardUserSystemClockDifferenceByUser(difference, a, b);
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(res);
rb.Push(difference);
}
void StaticService::Handle_CalculateSpanBetween(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
Service::PSC::Time::ClockSnapshot a{};
Service::PSC::Time::ClockSnapshot b{};
auto a_buffer{ctx.ReadBuffer(0)};
auto b_buffer{ctx.ReadBuffer(1)};
std::memcpy(&a, a_buffer.data(), sizeof(Service::PSC::Time::ClockSnapshot));
std::memcpy(&b, b_buffer.data(), sizeof(Service::PSC::Time::ClockSnapshot));
s64 time{};
auto res = CalculateSpanBetween(time, a, b);
IPC::ResponseBuilder rb{ctx, 4};
rb.Push(res);
rb.Push(time);
}
// =============================== Implementations ===========================
Result StaticService::GetStandardUserSystemClock(
std::shared_ptr<Service::PSC::Time::SystemClock>& out_service) {
R_RETURN(m_wrapped_service->GetStandardUserSystemClock(out_service));
}
Result StaticService::GetStandardNetworkSystemClock(
std::shared_ptr<Service::PSC::Time::SystemClock>& out_service) {
R_RETURN(m_wrapped_service->GetStandardNetworkSystemClock(out_service));
}
Result StaticService::GetStandardSteadyClock(
std::shared_ptr<Service::PSC::Time::SteadyClock>& out_service) {
R_RETURN(m_wrapped_service->GetStandardSteadyClock(out_service));
}
Result StaticService::GetTimeZoneService(std::shared_ptr<TimeZoneService>& out_service) {
out_service = std::make_shared<TimeZoneService>(m_system, m_file_timestamp_worker,
m_setup_info.can_write_timezone_device_location,
m_time_zone);
R_SUCCEED();
}
Result StaticService::GetStandardLocalSystemClock(
std::shared_ptr<Service::PSC::Time::SystemClock>& out_service) {
R_RETURN(m_wrapped_service->GetStandardLocalSystemClock(out_service));
}
Result StaticService::GetEphemeralNetworkSystemClock(
std::shared_ptr<Service::PSC::Time::SystemClock>& out_service) {
R_RETURN(m_wrapped_service->GetEphemeralNetworkSystemClock(out_service));
}
Result StaticService::GetSharedMemoryNativeHandle(Kernel::KSharedMemory** out_shared_memory) {
R_RETURN(m_wrapped_service->GetSharedMemoryNativeHandle(out_shared_memory));
}
Result StaticService::SetStandardSteadyClockInternalOffset(s64 offset_ns) {
R_UNLESS(m_setup_info.can_write_steady_clock, Service::PSC::Time::ResultPermissionDenied);
R_RETURN(m_set_sys->SetExternalSteadyClockInternalOffset(
offset_ns /
std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::seconds(1)).count()));
}
Result StaticService::GetStandardSteadyClockRtcValue(s64& out_rtc_value) {
R_RETURN(m_standard_steady_clock_resource.GetRtcTimeInSeconds(out_rtc_value));
}
Result StaticService::IsStandardUserSystemClockAutomaticCorrectionEnabled(
bool& out_automatic_correction) {
R_RETURN(m_wrapped_service->IsStandardUserSystemClockAutomaticCorrectionEnabled(
out_automatic_correction));
}
Result StaticService::SetStandardUserSystemClockAutomaticCorrectionEnabled(
bool automatic_correction) {
R_RETURN(m_wrapped_service->SetStandardUserSystemClockAutomaticCorrectionEnabled(
automatic_correction));
}
Result StaticService::GetStandardUserSystemClockInitialYear(s32& out_year) {
out_year = GetSettingsItemValue<s32>(m_set_sys, "time", "standard_user_clock_initial_year");
R_SUCCEED();
}
Result StaticService::IsStandardNetworkSystemClockAccuracySufficient(bool& out_is_sufficient) {
R_RETURN(m_wrapped_service->IsStandardNetworkSystemClockAccuracySufficient(out_is_sufficient));
}
Result StaticService::GetStandardUserSystemClockAutomaticCorrectionUpdatedTime(
Service::PSC::Time::SteadyClockTimePoint& out_time_point) {
R_RETURN(m_wrapped_service->GetStandardUserSystemClockAutomaticCorrectionUpdatedTime(
out_time_point));
}
Result StaticService::CalculateMonotonicSystemClockBaseTimePoint(
s64& out_time, Service::PSC::Time::SystemClockContext& context) {
R_RETURN(m_wrapped_service->CalculateMonotonicSystemClockBaseTimePoint(out_time, context));
}
Result StaticService::GetClockSnapshot(Service::PSC::Time::ClockSnapshot& out_snapshot,
Service::PSC::Time::TimeType type) {
R_RETURN(m_wrapped_service->GetClockSnapshot(out_snapshot, type));
}
Result StaticService::GetClockSnapshotFromSystemClockContext(
Service::PSC::Time::ClockSnapshot& out_snapshot,
Service::PSC::Time::SystemClockContext& user_context,
Service::PSC::Time::SystemClockContext& network_context, Service::PSC::Time::TimeType type) {
R_RETURN(m_wrapped_service->GetClockSnapshotFromSystemClockContext(out_snapshot, user_context,
network_context, type));
}
Result StaticService::CalculateStandardUserSystemClockDifferenceByUser(
s64& out_time, Service::PSC::Time::ClockSnapshot& a, Service::PSC::Time::ClockSnapshot& b) {
R_RETURN(m_wrapped_service->CalculateStandardUserSystemClockDifferenceByUser(out_time, a, b));
}
Result StaticService::CalculateSpanBetween(s64& out_time, Service::PSC::Time::ClockSnapshot& a,
Service::PSC::Time::ClockSnapshot& b) {
R_RETURN(m_wrapped_service->CalculateSpanBetween(out_time, a, b));
}
} // namespace Service::Glue::Time

View File

@ -0,0 +1,110 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include "common/common_types.h"
#include "core/hle/service/glue/time/manager.h"
#include "core/hle/service/glue/time/time_zone.h"
#include "core/hle/service/psc/time/common.h"
namespace Core {
class System;
}
namespace Service::Set {
class ISystemSettingsServer;
}
namespace Service::PSC::Time {
class StaticService;
class SystemClock;
class SteadyClock;
class TimeZoneService;
class ServiceManager;
} // namespace Service::PSC::Time
namespace Service::Glue::Time {
class FileTimestampWorker;
class StandardSteadyClockResource;
class StaticService final : public ServiceFramework<StaticService> {
public:
explicit StaticService(Core::System& system,
Service::PSC::Time::StaticServiceSetupInfo setup_info,
std::shared_ptr<TimeManager> time, const char* name);
~StaticService() override = default;
Result GetStandardUserSystemClock(
std::shared_ptr<Service::PSC::Time::SystemClock>& out_service);
Result GetStandardNetworkSystemClock(
std::shared_ptr<Service::PSC::Time::SystemClock>& out_service);
Result GetStandardSteadyClock(std::shared_ptr<Service::PSC::Time::SteadyClock>& out_service);
Result GetTimeZoneService(std::shared_ptr<TimeZoneService>& out_service);
Result GetStandardLocalSystemClock(
std::shared_ptr<Service::PSC::Time::SystemClock>& out_service);
Result GetEphemeralNetworkSystemClock(
std::shared_ptr<Service::PSC::Time::SystemClock>& out_service);
Result GetSharedMemoryNativeHandle(Kernel::KSharedMemory** out_shared_memory);
Result SetStandardSteadyClockInternalOffset(s64 offset);
Result GetStandardSteadyClockRtcValue(s64& out_rtc_value);
Result IsStandardUserSystemClockAutomaticCorrectionEnabled(bool& out_automatic_correction);
Result SetStandardUserSystemClockAutomaticCorrectionEnabled(bool automatic_correction);
Result GetStandardUserSystemClockInitialYear(s32& out_year);
Result IsStandardNetworkSystemClockAccuracySufficient(bool& out_is_sufficient);
Result GetStandardUserSystemClockAutomaticCorrectionUpdatedTime(
Service::PSC::Time::SteadyClockTimePoint& out_time_point);
Result CalculateMonotonicSystemClockBaseTimePoint(
s64& out_time, Service::PSC::Time::SystemClockContext& context);
Result GetClockSnapshot(Service::PSC::Time::ClockSnapshot& out_snapshot,
Service::PSC::Time::TimeType type);
Result GetClockSnapshotFromSystemClockContext(
Service::PSC::Time::ClockSnapshot& out_snapshot,
Service::PSC::Time::SystemClockContext& user_context,
Service::PSC::Time::SystemClockContext& network_context, Service::PSC::Time::TimeType type);
Result CalculateStandardUserSystemClockDifferenceByUser(s64& out_time,
Service::PSC::Time::ClockSnapshot& a,
Service::PSC::Time::ClockSnapshot& b);
Result CalculateSpanBetween(s64& out_time, Service::PSC::Time::ClockSnapshot& a,
Service::PSC::Time::ClockSnapshot& b);
private:
Result GetClockSnapshotImpl(Service::PSC::Time::ClockSnapshot& out_snapshot,
Service::PSC::Time::SystemClockContext& user_context,
Service::PSC::Time::SystemClockContext& network_context,
Service::PSC::Time::TimeType type);
void Handle_GetStandardUserSystemClock(HLERequestContext& ctx);
void Handle_GetStandardNetworkSystemClock(HLERequestContext& ctx);
void Handle_GetStandardSteadyClock(HLERequestContext& ctx);
void Handle_GetTimeZoneService(HLERequestContext& ctx);
void Handle_GetStandardLocalSystemClock(HLERequestContext& ctx);
void Handle_GetEphemeralNetworkSystemClock(HLERequestContext& ctx);
void Handle_GetSharedMemoryNativeHandle(HLERequestContext& ctx);
void Handle_SetStandardSteadyClockInternalOffset(HLERequestContext& ctx);
void Handle_GetStandardSteadyClockRtcValue(HLERequestContext& ctx);
void Handle_IsStandardUserSystemClockAutomaticCorrectionEnabled(HLERequestContext& ctx);
void Handle_SetStandardUserSystemClockAutomaticCorrectionEnabled(HLERequestContext& ctx);
void Handle_GetStandardUserSystemClockInitialYear(HLERequestContext& ctx);
void Handle_IsStandardNetworkSystemClockAccuracySufficient(HLERequestContext& ctx);
void Handle_GetStandardUserSystemClockAutomaticCorrectionUpdatedTime(HLERequestContext& ctx);
void Handle_CalculateMonotonicSystemClockBaseTimePoint(HLERequestContext& ctx);
void Handle_GetClockSnapshot(HLERequestContext& ctx);
void Handle_GetClockSnapshotFromSystemClockContext(HLERequestContext& ctx);
void Handle_CalculateStandardUserSystemClockDifferenceByUser(HLERequestContext& ctx);
void Handle_CalculateSpanBetween(HLERequestContext& ctx);
Core::System& m_system;
std::shared_ptr<Service::Set::ISystemSettingsServer> m_set_sys;
std::shared_ptr<Service::PSC::Time::ServiceManager> m_time_m;
std::shared_ptr<Service::PSC::Time::StaticService> m_wrapped_service;
Service::PSC::Time::StaticServiceSetupInfo m_setup_info;
std::shared_ptr<Service::PSC::Time::StaticService> m_time_sm;
std::shared_ptr<Service::PSC::Time::TimeZoneService> m_time_zone;
FileTimestampWorker& m_file_timestamp_worker;
StandardSteadyClockResource& m_standard_steady_clock_resource;
};
} // namespace Service::Glue::Time

View File

@ -0,0 +1,377 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <chrono>
#include "core/core.h"
#include "core/hle/kernel/svc.h"
#include "core/hle/service/glue/time/file_timestamp_worker.h"
#include "core/hle/service/glue/time/time_zone.h"
#include "core/hle/service/glue/time/time_zone_binary.h"
#include "core/hle/service/psc/time/time_zone_service.h"
#include "core/hle/service/set/system_settings_server.h"
#include "core/hle/service/sm/sm.h"
namespace Service::Glue::Time {
namespace {
static std::mutex g_list_mutex;
static Common::IntrusiveListBaseTraits<Service::PSC::Time::OperationEvent>::ListType g_list_nodes{};
} // namespace
TimeZoneService::TimeZoneService(
Core::System& system_, FileTimestampWorker& file_timestamp_worker,
bool can_write_timezone_device_location,
std::shared_ptr<Service::PSC::Time::TimeZoneService> time_zone_service)
: ServiceFramework{system_, "ITimeZoneService"}, m_system{system},
m_can_write_timezone_device_location{can_write_timezone_device_location},
m_file_timestamp_worker{file_timestamp_worker},
m_wrapped_service{std::move(time_zone_service)}, m_operation_event{m_system} {
// clang-format off
static const FunctionInfo functions[] = {
{0, &TimeZoneService::Handle_GetDeviceLocationName, "GetDeviceLocationName"},
{1, &TimeZoneService::Handle_SetDeviceLocationName, "SetDeviceLocationName"},
{2, &TimeZoneService::Handle_GetTotalLocationNameCount, "GetTotalLocationNameCount"},
{3, &TimeZoneService::Handle_LoadLocationNameList, "LoadLocationNameList"},
{4, &TimeZoneService::Handle_LoadTimeZoneRule, "LoadTimeZoneRule"},
{5, &TimeZoneService::Handle_GetTimeZoneRuleVersion, "GetTimeZoneRuleVersion"},
{6, &TimeZoneService::Handle_GetDeviceLocationNameAndUpdatedTime, "GetDeviceLocationNameAndUpdatedTime"},
{7, &TimeZoneService::Handle_SetDeviceLocationNameWithTimeZoneRule, "SetDeviceLocationNameWithTimeZoneRule"},
{8, &TimeZoneService::Handle_ParseTimeZoneBinary, "ParseTimeZoneBinary"},
{20, &TimeZoneService::Handle_GetDeviceLocationNameOperationEventReadableHandle, "GetDeviceLocationNameOperationEventReadableHandle"},
{100, &TimeZoneService::Handle_ToCalendarTime, "ToCalendarTime"},
{101, &TimeZoneService::Handle_ToCalendarTimeWithMyRule, "ToCalendarTimeWithMyRule"},
{201, &TimeZoneService::Handle_ToPosixTime, "ToPosixTime"},
{202, &TimeZoneService::Handle_ToPosixTimeWithMyRule, "ToPosixTimeWithMyRule"},
};
// clang-format on
RegisterHandlers(functions);
g_list_nodes.clear();
m_set_sys =
m_system.ServiceManager().GetService<Service::Set::ISystemSettingsServer>("set:sys", true);
}
TimeZoneService::~TimeZoneService() = default;
void TimeZoneService::Handle_GetDeviceLocationName(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
Service::PSC::Time::LocationName name{};
auto res = GetDeviceLocationName(name);
IPC::ResponseBuilder rb{ctx, 2 + sizeof(Service::PSC::Time::LocationName) / sizeof(u32)};
rb.Push(res);
rb.PushRaw<Service::PSC::Time::LocationName>(name);
}
void TimeZoneService::Handle_SetDeviceLocationName(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::RequestParser rp{ctx};
auto name{rp.PopRaw<Service::PSC::Time::LocationName>()};
auto res = SetDeviceLocation(name);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(res);
}
void TimeZoneService::Handle_GetTotalLocationNameCount(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
u32 count{};
auto res = GetTotalLocationNameCount(count);
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(res);
rb.Push(count);
}
void TimeZoneService::Handle_LoadLocationNameList(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::RequestParser rp{ctx};
auto index{rp.Pop<u32>()};
auto max_names{ctx.GetWriteBufferSize() / sizeof(Service::PSC::Time::LocationName)};
std::vector<Service::PSC::Time::LocationName> names{};
u32 count{};
auto res = LoadLocationNameList(count, names, max_names, index);
ctx.WriteBuffer(names);
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(res);
rb.Push(count);
}
void TimeZoneService::Handle_LoadTimeZoneRule(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::RequestParser rp{ctx};
auto name{rp.PopRaw<Service::PSC::Time::LocationName>()};
Tz::Rule rule{};
auto res = LoadTimeZoneRule(rule, name);
ctx.WriteBuffer(rule);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(res);
}
void TimeZoneService::Handle_GetTimeZoneRuleVersion(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
Service::PSC::Time::RuleVersion rule_version{};
auto res = GetTimeZoneRuleVersion(rule_version);
IPC::ResponseBuilder rb{ctx, 2 + sizeof(Service::PSC::Time::RuleVersion) / sizeof(u32)};
rb.Push(res);
rb.PushRaw<Service::PSC::Time::RuleVersion>(rule_version);
}
void TimeZoneService::Handle_GetDeviceLocationNameAndUpdatedTime(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
Service::PSC::Time::LocationName name{};
Service::PSC::Time::SteadyClockTimePoint time_point{};
auto res = GetDeviceLocationNameAndUpdatedTime(time_point, name);
IPC::ResponseBuilder rb{ctx,
2 + (sizeof(Service::PSC::Time::LocationName) / sizeof(u32)) +
(sizeof(Service::PSC::Time::SteadyClockTimePoint) / sizeof(u32))};
rb.Push(res);
rb.PushRaw<Service::PSC::Time::LocationName>(name);
rb.PushRaw<Service::PSC::Time::SteadyClockTimePoint>(time_point);
}
void TimeZoneService::Handle_SetDeviceLocationNameWithTimeZoneRule(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
auto res = SetDeviceLocationNameWithTimeZoneRule();
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(res);
}
void TimeZoneService::Handle_ParseTimeZoneBinary(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(Service::PSC::Time::ResultNotImplemented);
}
void TimeZoneService::Handle_GetDeviceLocationNameOperationEventReadableHandle(
HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
Kernel::KEvent* event{};
auto res = GetDeviceLocationNameOperationEventReadableHandle(&event);
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(res);
rb.PushCopyObjects(event->GetReadableEvent());
}
void TimeZoneService::Handle_ToCalendarTime(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::RequestParser rp{ctx};
auto time{rp.Pop<s64>()};
auto rule_buffer{ctx.ReadBuffer()};
Tz::Rule rule{};
std::memcpy(&rule, rule_buffer.data(), sizeof(Tz::Rule));
Service::PSC::Time::CalendarTime calendar_time{};
Service::PSC::Time::CalendarAdditionalInfo additional_info{};
auto res = ToCalendarTime(calendar_time, additional_info, time, rule);
IPC::ResponseBuilder rb{ctx,
2 + (sizeof(Service::PSC::Time::CalendarTime) / sizeof(u32)) +
(sizeof(Service::PSC::Time::CalendarAdditionalInfo) / sizeof(u32))};
rb.Push(res);
rb.PushRaw<Service::PSC::Time::CalendarTime>(calendar_time);
rb.PushRaw<Service::PSC::Time::CalendarAdditionalInfo>(additional_info);
}
void TimeZoneService::Handle_ToCalendarTimeWithMyRule(HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
auto time{rp.Pop<s64>()};
LOG_DEBUG(Service_Time, "called. time={}", time);
Service::PSC::Time::CalendarTime calendar_time{};
Service::PSC::Time::CalendarAdditionalInfo additional_info{};
auto res = ToCalendarTimeWithMyRule(calendar_time, additional_info, time);
IPC::ResponseBuilder rb{ctx,
2 + (sizeof(Service::PSC::Time::CalendarTime) / sizeof(u32)) +
(sizeof(Service::PSC::Time::CalendarAdditionalInfo) / sizeof(u32))};
rb.Push(res);
rb.PushRaw<Service::PSC::Time::CalendarTime>(calendar_time);
rb.PushRaw<Service::PSC::Time::CalendarAdditionalInfo>(additional_info);
}
void TimeZoneService::Handle_ToPosixTime(HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
auto calendar{rp.PopRaw<Service::PSC::Time::CalendarTime>()};
LOG_DEBUG(Service_Time, "called. calendar year {} month {} day {} hour {} minute {} second {}",
calendar.year, calendar.month, calendar.day, calendar.hour, calendar.minute,
calendar.second);
auto binary{ctx.ReadBuffer()};
Tz::Rule rule{};
std::memcpy(&rule, binary.data(), sizeof(Tz::Rule));
u32 count{};
std::array<s64, 2> times{};
u32 times_count{static_cast<u32>(ctx.GetWriteBufferSize() / sizeof(s64))};
auto res = ToPosixTime(count, times, times_count, calendar, rule);
ctx.WriteBuffer(times);
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(res);
rb.Push(count);
}
void TimeZoneService::Handle_ToPosixTimeWithMyRule(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::RequestParser rp{ctx};
auto calendar{rp.PopRaw<Service::PSC::Time::CalendarTime>()};
u32 count{};
std::array<s64, 2> times{};
u32 times_count{static_cast<u32>(ctx.GetWriteBufferSize() / sizeof(s64))};
auto res = ToPosixTimeWithMyRule(count, times, times_count, calendar);
ctx.WriteBuffer(times);
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(res);
rb.Push(count);
}
// =============================== Implementations ===========================
Result TimeZoneService::GetDeviceLocationName(Service::PSC::Time::LocationName& out_location_name) {
R_RETURN(m_wrapped_service->GetDeviceLocationName(out_location_name));
}
Result TimeZoneService::SetDeviceLocation(Service::PSC::Time::LocationName& location_name) {
R_UNLESS(m_can_write_timezone_device_location, Service::PSC::Time::ResultPermissionDenied);
R_UNLESS(IsTimeZoneBinaryValid(location_name), Service::PSC::Time::ResultTimeZoneNotFound);
std::scoped_lock l{m_mutex};
std::span<const u8> binary{};
size_t binary_size{};
R_TRY(GetTimeZoneRule(binary, binary_size, location_name))
R_TRY(m_wrapped_service->SetDeviceLocationNameWithTimeZoneRule(location_name, binary));
m_file_timestamp_worker.SetFilesystemPosixTime();
Service::PSC::Time::SteadyClockTimePoint time_point{};
Service::PSC::Time::LocationName name{};
R_TRY(m_wrapped_service->GetDeviceLocationNameAndUpdatedTime(time_point, name));
m_set_sys->SetDeviceTimeZoneLocationName(name);
m_set_sys->SetDeviceTimeZoneLocationUpdatedTime(time_point);
std::scoped_lock m{g_list_mutex};
for (auto& operation_event : g_list_nodes) {
operation_event.m_event->Signal();
}
R_SUCCEED();
}
Result TimeZoneService::GetTotalLocationNameCount(u32& out_count) {
R_RETURN(m_wrapped_service->GetTotalLocationNameCount(out_count));
}
Result TimeZoneService::LoadLocationNameList(
u32& out_count, std::vector<Service::PSC::Time::LocationName>& out_names, size_t max_names,
u32 index) {
std::scoped_lock l{m_mutex};
R_RETURN(GetTimeZoneLocationList(out_count, out_names, max_names, index));
}
Result TimeZoneService::LoadTimeZoneRule(Tz::Rule& out_rule,
Service::PSC::Time::LocationName& name) {
std::scoped_lock l{m_mutex};
std::span<const u8> binary{};
size_t binary_size{};
R_TRY(GetTimeZoneRule(binary, binary_size, name))
R_RETURN(m_wrapped_service->ParseTimeZoneBinary(out_rule, binary));
}
Result TimeZoneService::GetTimeZoneRuleVersion(Service::PSC::Time::RuleVersion& out_rule_version) {
R_RETURN(m_wrapped_service->GetTimeZoneRuleVersion(out_rule_version));
}
Result TimeZoneService::GetDeviceLocationNameAndUpdatedTime(
Service::PSC::Time::SteadyClockTimePoint& out_time_point,
Service::PSC::Time::LocationName& location_name) {
R_RETURN(m_wrapped_service->GetDeviceLocationNameAndUpdatedTime(out_time_point, location_name));
}
Result TimeZoneService::SetDeviceLocationNameWithTimeZoneRule() {
R_UNLESS(m_can_write_timezone_device_location, Service::PSC::Time::ResultPermissionDenied);
R_RETURN(Service::PSC::Time::ResultNotImplemented);
}
Result TimeZoneService::GetDeviceLocationNameOperationEventReadableHandle(
Kernel::KEvent** out_event) {
if (!operation_event_initialized) {
operation_event_initialized = false;
m_operation_event.m_ctx.CloseEvent(m_operation_event.m_event);
m_operation_event.m_event =
m_operation_event.m_ctx.CreateEvent("Psc:TimeZoneService:OperationEvent");
operation_event_initialized = true;
std::scoped_lock l{m_mutex};
g_list_nodes.push_back(m_operation_event);
}
*out_event = m_operation_event.m_event;
R_SUCCEED();
}
Result TimeZoneService::ToCalendarTime(
Service::PSC::Time::CalendarTime& out_calendar_time,
Service::PSC::Time::CalendarAdditionalInfo& out_additional_info, s64 time, Tz::Rule& rule) {
R_RETURN(m_wrapped_service->ToCalendarTime(out_calendar_time, out_additional_info, time, rule));
}
Result TimeZoneService::ToCalendarTimeWithMyRule(
Service::PSC::Time::CalendarTime& out_calendar_time,
Service::PSC::Time::CalendarAdditionalInfo& out_additional_info, s64 time) {
R_RETURN(
m_wrapped_service->ToCalendarTimeWithMyRule(out_calendar_time, out_additional_info, time));
}
Result TimeZoneService::ToPosixTime(u32& out_count, std::span<s64, 2> out_times,
u32 out_times_count,
Service::PSC::Time::CalendarTime& calendar_time,
Tz::Rule& rule) {
R_RETURN(
m_wrapped_service->ToPosixTime(out_count, out_times, out_times_count, calendar_time, rule));
}
Result TimeZoneService::ToPosixTimeWithMyRule(u32& out_count, std::span<s64, 2> out_times,
u32 out_times_count,
Service::PSC::Time::CalendarTime& calendar_time) {
R_RETURN(m_wrapped_service->ToPosixTimeWithMyRule(out_count, out_times, out_times_count,
calendar_time));
}
} // namespace Service::Glue::Time

View File

@ -0,0 +1,95 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <memory>
#include <mutex>
#include <span>
#include <vector>
#include "core/hle/service/ipc_helpers.h"
#include "core/hle/service/psc/time/common.h"
#include "core/hle/service/server_manager.h"
#include "core/hle/service/service.h"
namespace Core {
class System;
}
namespace Tz {
struct Rule;
}
namespace Service::Set {
class ISystemSettingsServer;
}
namespace Service::PSC::Time {
class TimeZoneService;
}
namespace Service::Glue::Time {
class FileTimestampWorker;
class TimeZoneService final : public ServiceFramework<TimeZoneService> {
public:
explicit TimeZoneService(
Core::System& system, FileTimestampWorker& file_timestamp_worker,
bool can_write_timezone_device_location,
std::shared_ptr<Service::PSC::Time::TimeZoneService> time_zone_service);
~TimeZoneService() override;
Result GetDeviceLocationName(Service::PSC::Time::LocationName& out_location_name);
Result SetDeviceLocation(Service::PSC::Time::LocationName& location_name);
Result GetTotalLocationNameCount(u32& out_count);
Result LoadLocationNameList(u32& out_count,
std::vector<Service::PSC::Time::LocationName>& out_names,
size_t max_names, u32 index);
Result LoadTimeZoneRule(Tz::Rule& out_rule, Service::PSC::Time::LocationName& name);
Result GetTimeZoneRuleVersion(Service::PSC::Time::RuleVersion& out_rule_version);
Result GetDeviceLocationNameAndUpdatedTime(
Service::PSC::Time::SteadyClockTimePoint& out_time_point,
Service::PSC::Time::LocationName& location_name);
Result SetDeviceLocationNameWithTimeZoneRule();
Result GetDeviceLocationNameOperationEventReadableHandle(Kernel::KEvent** out_event);
Result ToCalendarTime(Service::PSC::Time::CalendarTime& out_calendar_time,
Service::PSC::Time::CalendarAdditionalInfo& out_additional_info, s64 time,
Tz::Rule& rule);
Result ToCalendarTimeWithMyRule(Service::PSC::Time::CalendarTime& out_calendar_time,
Service::PSC::Time::CalendarAdditionalInfo& out_additional_info,
s64 time);
Result ToPosixTime(u32& out_count, std::span<s64, 2> out_times, u32 out_times_count,
Service::PSC::Time::CalendarTime& calendar_time, Tz::Rule& rule);
Result ToPosixTimeWithMyRule(u32& out_count, std::span<s64, 2> out_times, u32 out_times_count,
Service::PSC::Time::CalendarTime& calendar_time);
private:
void Handle_GetDeviceLocationName(HLERequestContext& ctx);
void Handle_SetDeviceLocationName(HLERequestContext& ctx);
void Handle_GetTotalLocationNameCount(HLERequestContext& ctx);
void Handle_LoadLocationNameList(HLERequestContext& ctx);
void Handle_LoadTimeZoneRule(HLERequestContext& ctx);
void Handle_GetTimeZoneRuleVersion(HLERequestContext& ctx);
void Handle_GetDeviceLocationNameAndUpdatedTime(HLERequestContext& ctx);
void Handle_SetDeviceLocationNameWithTimeZoneRule(HLERequestContext& ctx);
void Handle_ParseTimeZoneBinary(HLERequestContext& ctx);
void Handle_GetDeviceLocationNameOperationEventReadableHandle(HLERequestContext& ctx);
void Handle_ToCalendarTime(HLERequestContext& ctx);
void Handle_ToCalendarTimeWithMyRule(HLERequestContext& ctx);
void Handle_ToPosixTime(HLERequestContext& ctx);
void Handle_ToPosixTimeWithMyRule(HLERequestContext& ctx);
Core::System& m_system;
std::shared_ptr<Service::Set::ISystemSettingsServer> m_set_sys;
bool m_can_write_timezone_device_location;
FileTimestampWorker& m_file_timestamp_worker;
std::shared_ptr<Service::PSC::Time::TimeZoneService> m_wrapped_service;
std::mutex m_mutex;
bool operation_event_initialized{};
Service::PSC::Time::OperationEvent m_operation_event;
};
} // namespace Service::Glue::Time

View File

@ -0,0 +1,221 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/core.h"
#include "core/file_sys/content_archive.h"
#include "core/file_sys/nca_metadata.h"
#include "core/file_sys/registered_cache.h"
#include "core/file_sys/romfs.h"
#include "core/file_sys/system_archive/system_archive.h"
#include "core/file_sys/vfs.h"
#include "core/hle/service/filesystem/filesystem.h"
#include "core/hle/service/glue/time/time_zone_binary.h"
namespace Service::Glue::Time {
namespace {
constexpr u64 TimeZoneBinaryId = 0x10000000000080E;
static FileSys::VirtualDir g_time_zone_binary_romfs{};
static Result g_time_zone_binary_mount_result{ResultUnknown};
static std::vector<u8> g_time_zone_scratch_space(0x2800, 0);
Result TimeZoneReadBinary(size_t& out_read_size, std::span<u8> out_buffer, size_t out_buffer_size,
std::string_view path) {
R_UNLESS(g_time_zone_binary_mount_result == ResultSuccess, g_time_zone_binary_mount_result);
auto vfs_file{g_time_zone_binary_romfs->GetFileRelative(path)};
R_UNLESS(vfs_file, ResultUnknown);
auto file_size{vfs_file->GetSize()};
R_UNLESS(file_size > 0, ResultUnknown);
R_UNLESS(file_size <= out_buffer_size, Service::PSC::Time::ResultFailed);
out_read_size = vfs_file->Read(out_buffer.data(), file_size);
R_UNLESS(out_read_size > 0, ResultUnknown);
R_SUCCEED();
}
} // namespace
void ResetTimeZoneBinary() {
g_time_zone_binary_romfs = {};
g_time_zone_binary_mount_result = ResultUnknown;
g_time_zone_scratch_space.clear();
g_time_zone_scratch_space.resize(0x2800, 0);
}
Result MountTimeZoneBinary(Core::System& system) {
ResetTimeZoneBinary();
auto& fsc{system.GetFileSystemController()};
std::unique_ptr<FileSys::NCA> nca{};
auto* bis_system = fsc.GetSystemNANDContents();
R_UNLESS(bis_system, ResultUnknown);
nca = bis_system->GetEntry(TimeZoneBinaryId, FileSys::ContentRecordType::Data);
if (nca) {
g_time_zone_binary_romfs = FileSys::ExtractRomFS(nca->GetRomFS());
}
if (g_time_zone_binary_romfs) {
// Validate that the romfs is readable, using invalid firmware keys can cause this to get
// set but the files to be garbage. In that case, we want to hit the next path and
// synthesise them instead.
Service::PSC::Time::LocationName name{"Etc/GMT"};
if (!IsTimeZoneBinaryValid(name)) {
ResetTimeZoneBinary();
}
}
if (!g_time_zone_binary_romfs) {
g_time_zone_binary_romfs = FileSys::ExtractRomFS(
FileSys::SystemArchive::SynthesizeSystemArchive(TimeZoneBinaryId));
}
R_UNLESS(g_time_zone_binary_romfs, ResultUnknown);
g_time_zone_binary_mount_result = ResultSuccess;
R_SUCCEED();
}
void GetTimeZoneBinaryListPath(std::string& out_path) {
if (g_time_zone_binary_mount_result != ResultSuccess) {
return;
}
// out_path = fmt::format("{}:/binaryList.txt", "TimeZoneBinary");
out_path = "/binaryList.txt";
}
void GetTimeZoneBinaryVersionPath(std::string& out_path) {
if (g_time_zone_binary_mount_result != ResultSuccess) {
return;
}
// out_path = fmt::format("{}:/version.txt", "TimeZoneBinary");
out_path = "/version.txt";
}
void GetTimeZoneZonePath(std::string& out_path, Service::PSC::Time::LocationName& name) {
if (g_time_zone_binary_mount_result != ResultSuccess) {
return;
}
// out_path = fmt::format("{}:/zoneinfo/{}", "TimeZoneBinary", name);
out_path = fmt::format("/zoneinfo/{}", name.name.data());
}
bool IsTimeZoneBinaryValid(Service::PSC::Time::LocationName& name) {
std::string path{};
GetTimeZoneZonePath(path, name);
auto vfs_file{g_time_zone_binary_romfs->GetFileRelative(path)};
if (!vfs_file) {
LOG_INFO(Service_Time, "Could not find timezone file {}", path);
return false;
}
return vfs_file->GetSize() != 0;
}
u32 GetTimeZoneCount() {
std::string path{};
GetTimeZoneBinaryListPath(path);
size_t bytes_read{};
if (TimeZoneReadBinary(bytes_read, g_time_zone_scratch_space, 0x2800, path) != ResultSuccess) {
return 0;
}
if (bytes_read == 0) {
return 0;
}
auto chars = std::span(reinterpret_cast<char*>(g_time_zone_scratch_space.data()), bytes_read);
u32 count{};
for (auto chr : chars) {
if (chr == '\n') {
count++;
}
}
return count;
}
Result GetTimeZoneVersion(Service::PSC::Time::RuleVersion& out_rule_version) {
std::string path{};
GetTimeZoneBinaryVersionPath(path);
auto rule_version_buffer{std::span(reinterpret_cast<u8*>(&out_rule_version),
sizeof(Service::PSC::Time::RuleVersion))};
size_t bytes_read{};
R_TRY(TimeZoneReadBinary(bytes_read, rule_version_buffer, rule_version_buffer.size_bytes(),
path));
rule_version_buffer[bytes_read] = 0;
R_SUCCEED();
}
Result GetTimeZoneRule(std::span<const u8>& out_rule, size_t& out_rule_size,
Service::PSC::Time::LocationName& name) {
std::string path{};
GetTimeZoneZonePath(path, name);
size_t bytes_read{};
R_TRY(TimeZoneReadBinary(bytes_read, g_time_zone_scratch_space,
g_time_zone_scratch_space.size(), path));
out_rule = std::span(g_time_zone_scratch_space.data(), bytes_read);
out_rule_size = bytes_read;
R_SUCCEED();
}
Result GetTimeZoneLocationList(u32& out_count,
std::vector<Service::PSC::Time::LocationName>& out_names,
size_t max_names, u32 index) {
std::string path{};
GetTimeZoneBinaryListPath(path);
size_t bytes_read{};
R_TRY(TimeZoneReadBinary(bytes_read, g_time_zone_scratch_space,
g_time_zone_scratch_space.size(), path));
out_count = 0;
R_SUCCEED_IF(bytes_read == 0);
Service::PSC::Time::LocationName current_name{};
size_t current_name_len{};
std::span<const u8> chars{g_time_zone_scratch_space};
u32 name_count{};
for (auto chr : chars) {
if (chr == '\r') {
continue;
}
if (chr == '\n') {
if (name_count >= index) {
out_names.push_back(current_name);
out_count++;
if (out_count >= max_names) {
break;
}
}
name_count++;
current_name_len = 0;
current_name = {};
continue;
}
if (chr == '\0') {
break;
}
R_UNLESS(current_name_len <= current_name.name.size() - 2,
Service::PSC::Time::ResultFailed);
current_name.name[current_name_len++] = chr;
}
R_SUCCEED();
}
} // namespace Service::Glue::Time

View File

@ -0,0 +1,32 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <span>
#include <string>
#include <string_view>
#include "core/hle/service/psc/time/common.h"
namespace Core {
class System;
}
namespace Service::Glue::Time {
void ResetTimeZoneBinary();
Result MountTimeZoneBinary(Core::System& system);
void GetTimeZoneBinaryListPath(std::string& out_path);
void GetTimeZoneBinaryVersionPath(std::string& out_path);
void GetTimeZoneZonePath(std::string& out_path, Service::PSC::Time::LocationName& name);
bool IsTimeZoneBinaryValid(Service::PSC::Time::LocationName& name);
u32 GetTimeZoneCount();
Result GetTimeZoneVersion(Service::PSC::Time::RuleVersion& out_rule_version);
Result GetTimeZoneRule(std::span<const u8>& out_rule, size_t& out_rule_size,
Service::PSC::Time::LocationName& name);
Result GetTimeZoneLocationList(u32& out_count,
std::vector<Service::PSC::Time::LocationName>& out_names,
size_t max_names, u32 index);
} // namespace Service::Glue::Time

View File

@ -0,0 +1,338 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "common/scope_exit.h"
#include "core/core.h"
#include "core/core_timing.h"
#include "core/hle/service/glue/time/file_timestamp_worker.h"
#include "core/hle/service/glue/time/standard_steady_clock_resource.h"
#include "core/hle/service/glue/time/worker.h"
#include "core/hle/service/psc/time/common.h"
#include "core/hle/service/psc/time/service_manager.h"
#include "core/hle/service/psc/time/static.h"
#include "core/hle/service/psc/time/system_clock.h"
#include "core/hle/service/set/system_settings_server.h"
#include "core/hle/service/sm/sm.h"
namespace Service::Glue::Time {
namespace {
bool g_ig_report_network_clock_context_set{};
Service::PSC::Time::SystemClockContext g_report_network_clock_context{};
bool g_ig_report_ephemeral_clock_context_set{};
Service::PSC::Time::SystemClockContext g_report_ephemeral_clock_context{};
template <typename T>
T GetSettingsItemValue(std::shared_ptr<Service::Set::ISystemSettingsServer>& set_sys,
const char* category, const char* name) {
std::vector<u8> interval_buf;
auto res = set_sys->GetSettingsItemValue(interval_buf, category, name);
ASSERT(res == ResultSuccess);
T v{};
std::memcpy(&v, interval_buf.data(), sizeof(T));
return v;
}
} // namespace
TimeWorker::TimeWorker(Core::System& system, StandardSteadyClockResource& steady_clock_resource,
FileTimestampWorker& file_timestamp_worker)
: m_system{system}, m_ctx{m_system, "Glue:58"}, m_event{m_ctx.CreateEvent("Glue:58:Event")},
m_steady_clock_resource{steady_clock_resource},
m_file_timestamp_worker{file_timestamp_worker}, m_timer_steady_clock{m_ctx.CreateEvent(
"Glue:58:SteadyClockTimerEvent")},
m_timer_file_system{m_ctx.CreateEvent("Glue:58:FileTimeTimerEvent")},
m_alarm_worker{m_system, m_steady_clock_resource}, m_pm_state_change_handler{m_alarm_worker} {
g_ig_report_network_clock_context_set = false;
g_report_network_clock_context = {};
g_ig_report_ephemeral_clock_context_set = false;
g_report_ephemeral_clock_context = {};
m_timer_steady_clock_timing_event = Core::Timing::CreateEvent(
"Time::SteadyClockEvent",
[this](s64 time,
std::chrono::nanoseconds ns_late) -> std::optional<std::chrono::nanoseconds> {
m_timer_steady_clock->Signal();
return std::nullopt;
});
m_timer_file_system_timing_event = Core::Timing::CreateEvent(
"Time::SteadyClockEvent",
[this](s64 time,
std::chrono::nanoseconds ns_late) -> std::optional<std::chrono::nanoseconds> {
m_timer_file_system->Signal();
return std::nullopt;
});
}
TimeWorker::~TimeWorker() {
m_local_clock_event->Signal();
m_network_clock_event->Signal();
m_ephemeral_clock_event->Signal();
std::this_thread::sleep_for(std::chrono::milliseconds(16));
m_thread.request_stop();
m_event->Signal();
m_thread.join();
m_ctx.CloseEvent(m_event);
m_system.CoreTiming().UnscheduleEvent(m_timer_steady_clock_timing_event);
m_ctx.CloseEvent(m_timer_steady_clock);
m_system.CoreTiming().UnscheduleEvent(m_timer_file_system_timing_event);
m_ctx.CloseEvent(m_timer_file_system);
}
void TimeWorker::Initialize(std::shared_ptr<Service::PSC::Time::StaticService> time_sm,
std::shared_ptr<Service::Set::ISystemSettingsServer> set_sys) {
m_set_sys = std::move(set_sys);
m_time_m =
m_system.ServiceManager().GetService<Service::PSC::Time::ServiceManager>("time:m", true);
m_time_sm = std::move(time_sm);
m_alarm_worker.Initialize(m_time_m);
auto steady_clock_interval_m = GetSettingsItemValue<s32>(
m_set_sys, "time", "standard_steady_clock_rtc_update_interval_minutes");
auto one_minute_ns{
std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::minutes(1)).count()};
s64 steady_clock_interval_ns{steady_clock_interval_m * one_minute_ns};
m_system.CoreTiming().ScheduleLoopingEvent(std::chrono::nanoseconds(0),
std::chrono::nanoseconds(steady_clock_interval_ns),
m_timer_steady_clock_timing_event);
auto fs_notify_time_s =
GetSettingsItemValue<s32>(m_set_sys, "time", "notify_time_to_fs_interval_seconds");
auto one_second_ns{
std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::seconds(1)).count()};
s64 fs_notify_time_ns{fs_notify_time_s * one_second_ns};
m_system.CoreTiming().ScheduleLoopingEvent(std::chrono::nanoseconds(0),
std::chrono::nanoseconds(fs_notify_time_ns),
m_timer_file_system_timing_event);
auto res = m_time_sm->GetStandardLocalSystemClock(m_local_clock);
ASSERT(res == ResultSuccess);
res = m_time_m->GetStandardLocalClockOperationEvent(&m_local_clock_event);
ASSERT(res == ResultSuccess);
res = m_time_sm->GetStandardNetworkSystemClock(m_network_clock);
ASSERT(res == ResultSuccess);
res = m_time_m->GetStandardNetworkClockOperationEventForServiceManager(&m_network_clock_event);
ASSERT(res == ResultSuccess);
res = m_time_sm->GetEphemeralNetworkSystemClock(m_ephemeral_clock);
ASSERT(res == ResultSuccess);
res =
m_time_m->GetEphemeralNetworkClockOperationEventForServiceManager(&m_ephemeral_clock_event);
ASSERT(res == ResultSuccess);
res = m_time_m->GetStandardUserSystemClockAutomaticCorrectionUpdatedEvent(
&m_standard_user_auto_correct_clock_event);
ASSERT(res == ResultSuccess);
}
void TimeWorker::StartThread() {
m_thread = std::jthread(std::bind_front(&TimeWorker::ThreadFunc, this));
}
void TimeWorker::ThreadFunc(std::stop_token stop_token) {
Common::SetCurrentThreadName("TimeWorker");
Common::SetCurrentThreadPriority(Common::ThreadPriority::Low);
enum class EventType {
Exit = 0,
IpmModuleService_GetEvent = 1,
PowerStateChange = 2,
SignalAlarms = 3,
UpdateLocalSystemClock = 4,
UpdateNetworkSystemClock = 5,
UpdateEphemeralSystemClock = 6,
UpdateSteadyClock = 7,
UpdateFileTimestamp = 8,
AutoCorrect = 9,
Max = 10,
};
s32 num_objs{};
std::array<Kernel::KSynchronizationObject*, static_cast<u32>(EventType::Max)> wait_objs{};
std::array<EventType, static_cast<u32>(EventType::Max)> wait_indices{};
const auto AddWaiter{
[&](Kernel::KSynchronizationObject* synchronization_object, EventType type) {
// Open a new reference to the object.
synchronization_object->Open();
// Insert into the list.
wait_indices[num_objs] = type;
wait_objs[num_objs++] = synchronization_object;
}};
while (!stop_token.stop_requested()) {
SCOPE_EXIT({
for (s32 i = 0; i < num_objs; i++) {
wait_objs[i]->Close();
}
});
num_objs = {};
wait_objs = {};
if (m_pm_state_change_handler.m_priority != 0) {
AddWaiter(&m_event->GetReadableEvent(), EventType::Exit);
// TODO
// AddWaiter(gIPmModuleService::GetEvent(), 1);
AddWaiter(&m_alarm_worker.GetEvent().GetReadableEvent(), EventType::PowerStateChange);
} else {
AddWaiter(&m_event->GetReadableEvent(), EventType::Exit);
// TODO
// AddWaiter(gIPmModuleService::GetEvent(), 1);
AddWaiter(&m_alarm_worker.GetEvent().GetReadableEvent(), EventType::PowerStateChange);
AddWaiter(&m_alarm_worker.GetTimerEvent().GetReadableEvent(), EventType::SignalAlarms);
AddWaiter(&m_local_clock_event->GetReadableEvent(), EventType::UpdateLocalSystemClock);
AddWaiter(&m_network_clock_event->GetReadableEvent(),
EventType::UpdateNetworkSystemClock);
AddWaiter(&m_ephemeral_clock_event->GetReadableEvent(),
EventType::UpdateEphemeralSystemClock);
AddWaiter(&m_timer_steady_clock->GetReadableEvent(), EventType::UpdateSteadyClock);
AddWaiter(&m_timer_file_system->GetReadableEvent(), EventType::UpdateFileTimestamp);
AddWaiter(&m_standard_user_auto_correct_clock_event->GetReadableEvent(),
EventType::AutoCorrect);
}
s32 out_index{-1};
Kernel::KSynchronizationObject::Wait(m_system.Kernel(), &out_index, wait_objs.data(),
num_objs, -1);
ASSERT(out_index >= 0 && out_index < num_objs);
if (stop_token.stop_requested()) {
return;
}
switch (wait_indices[out_index]) {
case EventType::Exit:
return;
case EventType::IpmModuleService_GetEvent:
// TODO
// IPmModuleService::GetEvent()
// clear the event
// Handle power state change event
break;
case EventType::PowerStateChange:
m_alarm_worker.GetEvent().Clear();
if (m_pm_state_change_handler.m_priority <= 1) {
m_alarm_worker.OnPowerStateChanged();
}
break;
case EventType::SignalAlarms:
m_alarm_worker.GetTimerEvent().Clear();
m_time_m->CheckAndSignalAlarms();
break;
case EventType::UpdateLocalSystemClock: {
m_local_clock_event->Clear();
Service::PSC::Time::SystemClockContext context{};
auto res = m_local_clock->GetSystemClockContext(context);
ASSERT(res == ResultSuccess);
m_set_sys->SetUserSystemClockContext(context);
m_file_timestamp_worker.SetFilesystemPosixTime();
} break;
case EventType::UpdateNetworkSystemClock: {
m_network_clock_event->Clear();
Service::PSC::Time::SystemClockContext context{};
auto res = m_network_clock->GetSystemClockContext(context);
ASSERT(res == ResultSuccess);
m_set_sys->SetNetworkSystemClockContext(context);
s64 time{};
if (m_network_clock->GetCurrentTime(time) != ResultSuccess) {
break;
}
[[maybe_unused]] auto offset_before{
g_ig_report_network_clock_context_set ? g_report_network_clock_context.offset : 0};
// TODO system report "standard_netclock_operation"
// "clock_time" = time
// "context_offset_before" = offset_before
// "context_offset_after" = context.offset
g_report_network_clock_context = context;
if (!g_ig_report_network_clock_context_set) {
g_ig_report_network_clock_context_set = true;
}
m_file_timestamp_worker.SetFilesystemPosixTime();
} break;
case EventType::UpdateEphemeralSystemClock: {
m_ephemeral_clock_event->Clear();
Service::PSC::Time::SystemClockContext context{};
auto res = m_ephemeral_clock->GetSystemClockContext(context);
if (res != ResultSuccess) {
break;
}
s64 time{};
res = m_ephemeral_clock->GetCurrentTime(time);
if (res != ResultSuccess) {
break;
}
[[maybe_unused]] auto offset_before{g_ig_report_ephemeral_clock_context_set
? g_report_ephemeral_clock_context.offset
: 0};
// TODO system report "ephemeral_netclock_operation"
// "clock_time" = time
// "context_offset_before" = offset_before
// "context_offset_after" = context.offset
g_report_ephemeral_clock_context = context;
if (!g_ig_report_ephemeral_clock_context_set) {
g_ig_report_ephemeral_clock_context_set = true;
}
} break;
case EventType::UpdateSteadyClock:
m_timer_steady_clock->Clear();
m_steady_clock_resource.UpdateTime();
m_time_m->SetStandardSteadyClockBaseTime(m_steady_clock_resource.GetTime());
break;
case EventType::UpdateFileTimestamp:
m_timer_file_system->Clear();
m_file_timestamp_worker.SetFilesystemPosixTime();
break;
case EventType::AutoCorrect: {
m_standard_user_auto_correct_clock_event->Clear();
bool automatic_correction{};
auto res = m_time_sm->IsStandardUserSystemClockAutomaticCorrectionEnabled(
automatic_correction);
ASSERT(res == ResultSuccess);
Service::PSC::Time::SteadyClockTimePoint time_point{};
res = m_time_sm->GetStandardUserSystemClockAutomaticCorrectionUpdatedTime(time_point);
ASSERT(res == ResultSuccess);
m_set_sys->SetUserSystemClockAutomaticCorrectionEnabled(automatic_correction);
m_set_sys->SetUserSystemClockAutomaticCorrectionUpdatedTime(time_point);
} break;
default:
UNREACHABLE();
break;
}
}
}
} // namespace Service::Glue::Time

View File

@ -0,0 +1,64 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include "common/common_types.h"
#include "core/hle/kernel/k_event.h"
#include "core/hle/service/glue/time/alarm_worker.h"
#include "core/hle/service/glue/time/pm_state_change_handler.h"
#include "core/hle/service/kernel_helpers.h"
namespace Service::Set {
class ISystemSettingsServer;
}
namespace Service::PSC::Time {
class StaticService;
class SystemClock;
} // namespace Service::PSC::Time
namespace Service::Glue::Time {
class FileTimestampWorker;
class StandardSteadyClockResource;
class TimeWorker {
public:
explicit TimeWorker(Core::System& system, StandardSteadyClockResource& steady_clock_resource,
FileTimestampWorker& file_timestamp_worker);
~TimeWorker();
void Initialize(std::shared_ptr<Service::PSC::Time::StaticService> time_sm,
std::shared_ptr<Service::Set::ISystemSettingsServer> set_sys);
void StartThread();
private:
void ThreadFunc(std::stop_token stop_token);
Core::System& m_system;
KernelHelpers::ServiceContext m_ctx;
std::shared_ptr<Service::Set::ISystemSettingsServer> m_set_sys;
std::jthread m_thread;
Kernel::KEvent* m_event{};
std::shared_ptr<Service::PSC::Time::ServiceManager> m_time_m;
std::shared_ptr<Service::PSC::Time::StaticService> m_time_sm;
std::shared_ptr<Service::PSC::Time::SystemClock> m_network_clock;
std::shared_ptr<Service::PSC::Time::SystemClock> m_local_clock;
std::shared_ptr<Service::PSC::Time::SystemClock> m_ephemeral_clock;
StandardSteadyClockResource& m_steady_clock_resource;
FileTimestampWorker& m_file_timestamp_worker;
Kernel::KEvent* m_local_clock_event{};
Kernel::KEvent* m_network_clock_event{};
Kernel::KEvent* m_ephemeral_clock_event{};
Kernel::KEvent* m_standard_user_auto_correct_clock_event{};
Kernel::KEvent* m_timer_steady_clock{};
std::shared_ptr<Core::Timing::EventType> m_timer_steady_clock_timing_event;
Kernel::KEvent* m_timer_file_system{};
std::shared_ptr<Core::Timing::EventType> m_timer_file_system_timing_event;
AlarmWorker m_alarm_worker;
PmStateChangeHandler m_pm_state_change_handler;
};
} // namespace Service::Glue::Time

View File

@ -501,6 +501,22 @@ bool HLERequestContext::CanWriteBuffer(std::size_t buffer_index) const {
}
}
void HLERequestContext::AddMoveInterface(SessionRequestHandlerPtr s) {
ASSERT(Kernel::GetCurrentProcess(kernel).GetResourceLimit()->Reserve(
Kernel::LimitableResource::SessionCountMax, 1));
auto* session = Kernel::KSession::Create(kernel);
session->Initialize(nullptr, 0);
Kernel::KSession::Register(kernel, session);
auto& server = manager.lock()->GetServerManager();
auto next_manager = std::make_shared<Service::SessionRequestManager>(kernel, server);
next_manager->SetSessionHandler(std::move(s));
server.RegisterSession(&session->GetServerSession(), next_manager);
AddMoveObject(&session->GetClientSession());
}
std::string HLERequestContext::Description() const {
if (!command_header) {
return "No command header available";

View File

@ -339,6 +339,8 @@ public:
outgoing_move_objects.emplace_back(object);
}
void AddMoveInterface(SessionRequestHandlerPtr s);
void AddCopyObject(Kernel::KAutoObject* object) {
outgoing_copy_objects.emplace_back(object);
}

View File

@ -6,12 +6,12 @@
#include "core/core.h"
#include "core/hle/kernel/k_transfer_memory.h"
#include "core/hle/result.h"
#include "core/hle/service/cmif_serialization.h"
#include "core/hle/service/ipc_helpers.h"
#include "core/hle/service/jit/jit.h"
#include "core/hle/service/jit/jit_code_memory.h"
#include "core/hle/service/jit/jit_context.h"
#include "core/hle/service/server_manager.h"
#include "core/hle/service/service.h"
#include "core/memory.h"
namespace Service::JIT {
@ -21,6 +21,9 @@ struct CodeRange {
u64 size;
};
using Struct32 = std::array<u64, 4>;
static_assert(sizeof(Struct32) == 32, "Struct32 has wrong size");
class IJitEnvironment final : public ServiceFramework<IJitEnvironment> {
public:
explicit IJitEnvironment(Core::System& system_,
@ -29,12 +32,13 @@ public:
: ServiceFramework{system_, "IJitEnvironment"}, process{std::move(process_)},
user_rx{std::move(user_rx_)}, user_ro{std::move(user_ro_)},
context{system_.ApplicationMemory()} {
// clang-format off
static const FunctionInfo functions[] = {
{0, &IJitEnvironment::GenerateCode, "GenerateCode"},
{1, &IJitEnvironment::Control, "Control"},
{1000, &IJitEnvironment::LoadPlugin, "LoadPlugin"},
{1001, &IJitEnvironment::GetCodeAddress, "GetCodeAddress"},
{0, C<&IJitEnvironment::GenerateCode>, "GenerateCode"},
{1, C<&IJitEnvironment::Control>, "Control"},
{1000, C<&IJitEnvironment::LoadPlugin>, "LoadPlugin"},
{1001, C<&IJitEnvironment::GetCodeAddress>, "GetCodeAddress"},
};
// clang-format on
@ -50,28 +54,10 @@ public:
configuration.sys_ro_memory = configuration.user_ro_memory;
}
void GenerateCode(HLERequestContext& ctx) {
LOG_DEBUG(Service_JIT, "called");
struct InputParameters {
u32 data_size;
u64 command;
std::array<CodeRange, 2> ranges;
Struct32 data;
};
struct OutputParameters {
s32 return_value;
std::array<CodeRange, 2> ranges;
};
IPC::RequestParser rp{ctx};
const auto parameters{rp.PopRaw<InputParameters>()};
// Optional input/output buffers
const auto input_buffer{ctx.CanReadBuffer() ? ctx.ReadBuffer() : std::span<const u8>()};
std::vector<u8> output_buffer(ctx.CanWriteBuffer() ? ctx.GetWriteBufferSize() : 0);
Result GenerateCode(Out<s32> out_return_value, Out<CodeRange> out_range0,
Out<CodeRange> out_range1, OutBuffer<BufferAttr_HipcMapAlias> out_buffer,
u32 data_size, u64 command, CodeRange range0, CodeRange range1,
Struct32 data, InBuffer<BufferAttr_HipcMapAlias> buffer) {
// Function call prototype:
// void GenerateCode(s32* ret, CodeRange* c0_out, CodeRange* c1_out, JITConfiguration* cfg,
// u64 cmd, u8* input_buf, size_t input_size, CodeRange* c0_in,
@ -83,66 +69,36 @@ public:
// other arguments are used to transfer state between the game and the plugin.
const VAddr ret_ptr{context.AddHeap(0u)};
const VAddr c0_in_ptr{context.AddHeap(parameters.ranges[0])};
const VAddr c1_in_ptr{context.AddHeap(parameters.ranges[1])};
const VAddr c0_out_ptr{context.AddHeap(ClearSize(parameters.ranges[0]))};
const VAddr c1_out_ptr{context.AddHeap(ClearSize(parameters.ranges[1]))};
const VAddr c0_in_ptr{context.AddHeap(range0)};
const VAddr c1_in_ptr{context.AddHeap(range1)};
const VAddr c0_out_ptr{context.AddHeap(ClearSize(range0))};
const VAddr c1_out_ptr{context.AddHeap(ClearSize(range1))};
const VAddr input_ptr{context.AddHeap(input_buffer.data(), input_buffer.size())};
const VAddr output_ptr{context.AddHeap(output_buffer.data(), output_buffer.size())};
const VAddr data_ptr{context.AddHeap(parameters.data)};
const VAddr input_ptr{context.AddHeap(buffer.data(), buffer.size())};
const VAddr output_ptr{context.AddHeap(out_buffer.data(), out_buffer.size())};
const VAddr data_ptr{context.AddHeap(data)};
const VAddr configuration_ptr{context.AddHeap(configuration)};
// The callback does not directly return a value, it only writes to the output pointer
context.CallFunction(callbacks.GenerateCode, ret_ptr, c0_out_ptr, c1_out_ptr,
configuration_ptr, parameters.command, input_ptr, input_buffer.size(),
c0_in_ptr, c1_in_ptr, data_ptr, parameters.data_size, output_ptr,
output_buffer.size());
configuration_ptr, command, input_ptr, buffer.size(), c0_in_ptr,
c1_in_ptr, data_ptr, data_size, output_ptr, out_buffer.size());
const s32 return_value{context.GetHeap<s32>(ret_ptr)};
*out_return_value = context.GetHeap<s32>(ret_ptr);
*out_range0 = context.GetHeap<CodeRange>(c0_out_ptr);
*out_range1 = context.GetHeap<CodeRange>(c1_out_ptr);
context.GetHeap(output_ptr, out_buffer.data(), out_buffer.size());
if (return_value == 0) {
// The callback has written to the output executable code range,
// requiring an instruction cache invalidation
Core::InvalidateInstructionCacheRange(process.GetPointerUnsafe(),
configuration.user_rx_memory.offset,
configuration.user_rx_memory.size);
// Write back to the IPC output buffer, if provided
if (ctx.CanWriteBuffer()) {
context.GetHeap(output_ptr, output_buffer.data(), output_buffer.size());
ctx.WriteBuffer(output_buffer.data(), output_buffer.size());
}
const OutputParameters out{
.return_value = return_value,
.ranges =
{
context.GetHeap<CodeRange>(c0_out_ptr),
context.GetHeap<CodeRange>(c1_out_ptr),
},
};
IPC::ResponseBuilder rb{ctx, 8};
rb.Push(ResultSuccess);
rb.PushRaw(out);
} else {
if (*out_return_value != 0) {
LOG_WARNING(Service_JIT, "plugin GenerateCode callback failed");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
R_THROW(ResultUnknown);
}
};
void Control(HLERequestContext& ctx) {
LOG_DEBUG(Service_JIT, "called");
IPC::RequestParser rp{ctx};
const auto command{rp.PopRaw<u64>()};
// Optional input/output buffers
const auto input_buffer{ctx.CanReadBuffer() ? ctx.ReadBuffer() : std::span<const u8>()};
std::vector<u8> output_buffer(ctx.CanWriteBuffer() ? ctx.GetWriteBufferSize() : 0);
R_SUCCEED();
}
Result Control(Out<s32> out_return_value, InBuffer<BufferAttr_HipcMapAlias> in_data,
OutBuffer<BufferAttr_HipcMapAlias> out_data, u64 command) {
// Function call prototype:
// u64 Control(s32* ret, JITConfiguration* cfg, u64 cmd, u8* input_buf, size_t input_size,
// u8* output_buf, size_t output_size);
@ -152,53 +108,30 @@ public:
const VAddr ret_ptr{context.AddHeap(0u)};
const VAddr configuration_ptr{context.AddHeap(configuration)};
const VAddr input_ptr{context.AddHeap(input_buffer.data(), input_buffer.size())};
const VAddr output_ptr{context.AddHeap(output_buffer.data(), output_buffer.size())};
const VAddr input_ptr{context.AddHeap(in_data.data(), in_data.size())};
const VAddr output_ptr{context.AddHeap(out_data.data(), out_data.size())};
const u64 wrapper_value{context.CallFunction(callbacks.Control, ret_ptr, configuration_ptr,
command, input_ptr, input_buffer.size(),
output_ptr, output_buffer.size())};
command, input_ptr, in_data.size(), output_ptr,
out_data.size())};
const s32 return_value{context.GetHeap<s32>(ret_ptr)};
*out_return_value = context.GetHeap<s32>(ret_ptr);
context.GetHeap(output_ptr, out_data.data(), out_data.size());
if (wrapper_value == 0 && return_value == 0) {
// Write back to the IPC output buffer, if provided
if (ctx.CanWriteBuffer()) {
context.GetHeap(output_ptr, output_buffer.data(), output_buffer.size());
ctx.WriteBuffer(output_buffer.data(), output_buffer.size());
}
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(ResultSuccess);
rb.Push(return_value);
} else {
LOG_WARNING(Service_JIT, "plugin Control callback failed");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
if (wrapper_value == 0 && *out_return_value == 0) {
R_SUCCEED();
}
LOG_WARNING(Service_JIT, "plugin Control callback failed");
R_THROW(ResultUnknown);
}
void LoadPlugin(HLERequestContext& ctx) {
LOG_DEBUG(Service_JIT, "called");
IPC::RequestParser rp{ctx};
const auto tmem_size{rp.PopRaw<u64>()};
const auto tmem_handle{ctx.GetCopyHandle(0)};
const auto nro_plugin{ctx.ReadBuffer(1)};
if (tmem_size == 0) {
LOG_ERROR(Service_JIT, "attempted to load plugin with empty transfer memory");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
return;
}
auto tmem{ctx.GetObjectFromHandle<Kernel::KTransferMemory>(tmem_handle)};
Result LoadPlugin(u64 tmem_size, InCopyHandle<Kernel::KTransferMemory>& tmem,
InBuffer<BufferAttr_HipcMapAlias> nrr,
InBuffer<BufferAttr_HipcMapAlias> nro) {
if (tmem.IsNull()) {
LOG_ERROR(Service_JIT, "attempted to load plugin with invalid transfer memory handle");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
return;
LOG_ERROR(Service_JIT, "Invalid transfer memory handle!");
R_THROW(ResultUnknown);
}
// Set up the configuration with the required TransferMemory address
@ -206,7 +139,7 @@ public:
configuration.transfer_memory.size = tmem_size;
// Gather up all the callbacks from the loaded plugin
auto symbols{Core::Symbols::GetSymbols(nro_plugin, true)};
auto symbols{Core::Symbols::GetSymbols(nro, true)};
const auto GetSymbol{[&](const std::string& name) { return symbols[name].first; }};
callbacks.rtld_fini = GetSymbol("_fini");
@ -223,16 +156,12 @@ public:
if (callbacks.GetVersion == 0 || callbacks.Configure == 0 || callbacks.GenerateCode == 0 ||
callbacks.OnPrepared == 0) {
LOG_ERROR(Service_JIT, "plugin does not implement all necessary functionality");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
return;
R_THROW(ResultUnknown);
}
if (!context.LoadNRO(nro_plugin)) {
if (!context.LoadNRO(nro)) {
LOG_ERROR(Service_JIT, "failed to load plugin");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
return;
R_THROW(ResultUnknown);
}
context.MapProcessMemory(configuration.sys_ro_memory.offset,
@ -252,9 +181,7 @@ public:
const auto version{context.CallFunction(callbacks.GetVersion)};
if (version != 1) {
LOG_ERROR(Service_JIT, "unknown plugin version {}", version);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
return;
R_THROW(ResultUnknown);
}
// Function prototype:
@ -280,22 +207,19 @@ public:
const auto configuration_ptr{context.AddHeap(configuration)};
context.CallFunction(callbacks.OnPrepared, configuration_ptr);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
R_SUCCEED();
}
void GetCodeAddress(HLERequestContext& ctx) {
Result GetCodeAddress(Out<u64> rx_offset, Out<u64> ro_offset) {
LOG_DEBUG(Service_JIT, "called");
IPC::ResponseBuilder rb{ctx, 6};
rb.Push(ResultSuccess);
rb.Push(configuration.user_rx_memory.offset);
rb.Push(configuration.user_ro_memory.offset);
*rx_offset = configuration.user_rx_memory.offset;
*ro_offset = configuration.user_ro_memory.offset;
R_SUCCEED();
}
private:
using Struct32 = std::array<u8, 32>;
struct GuestCallbacks {
VAddr rtld_fini;
VAddr rtld_init;
@ -335,7 +259,7 @@ public:
explicit JITU(Core::System& system_) : ServiceFramework{system_, "jit:u"} {
// clang-format off
static const FunctionInfo functions[] = {
{0, &JITU::CreateJitEnvironment, "CreateJitEnvironment"},
{0, C<&JITU::CreateJitEnvironment>, "CreateJitEnvironment"},
};
// clang-format on
@ -343,76 +267,33 @@ public:
}
private:
void CreateJitEnvironment(HLERequestContext& ctx) {
LOG_DEBUG(Service_JIT, "called");
struct Parameters {
u64 rx_size;
u64 ro_size;
};
IPC::RequestParser rp{ctx};
const auto parameters{rp.PopRaw<Parameters>()};
const auto process_handle{ctx.GetCopyHandle(0)};
const auto rx_mem_handle{ctx.GetCopyHandle(1)};
const auto ro_mem_handle{ctx.GetCopyHandle(2)};
if (parameters.rx_size == 0 || parameters.ro_size == 0) {
LOG_ERROR(Service_JIT, "attempted to init with empty code regions");
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
return;
}
auto process{ctx.GetObjectFromHandle<Kernel::KProcess>(process_handle)};
Result CreateJitEnvironment(Out<SharedPointer<IJitEnvironment>> out_jit_environment,
u64 rx_size, u64 ro_size, InCopyHandle<Kernel::KProcess>& process,
InCopyHandle<Kernel::KCodeMemory>& rx_mem,
InCopyHandle<Kernel::KCodeMemory>& ro_mem) {
if (process.IsNull()) {
LOG_ERROR(Service_JIT, "process is null for handle=0x{:08X}", process_handle);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
return;
LOG_ERROR(Service_JIT, "process is null");
R_THROW(ResultUnknown);
}
auto rx_mem{ctx.GetObjectFromHandle<Kernel::KCodeMemory>(rx_mem_handle)};
if (rx_mem.IsNull()) {
LOG_ERROR(Service_JIT, "rx_mem is null for handle=0x{:08X}", rx_mem_handle);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
return;
LOG_ERROR(Service_JIT, "rx_mem is null");
R_THROW(ResultUnknown);
}
auto ro_mem{ctx.GetObjectFromHandle<Kernel::KCodeMemory>(ro_mem_handle)};
if (ro_mem.IsNull()) {
LOG_ERROR(Service_JIT, "ro_mem is null for handle=0x{:08X}", ro_mem_handle);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultUnknown);
return;
if (rx_mem.IsNull()) {
LOG_ERROR(Service_JIT, "ro_mem is null");
R_THROW(ResultUnknown);
}
CodeMemory rx, ro;
Result res;
res = rx.Initialize(*process, *rx_mem, parameters.rx_size,
Kernel::Svc::MemoryPermission::ReadExecute, generate_random);
if (R_FAILED(res)) {
LOG_ERROR(Service_JIT, "rx_mem could not be mapped for handle=0x{:08X}", rx_mem_handle);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(res);
return;
}
R_TRY(rx.Initialize(*process, *rx_mem, rx_size, Kernel::Svc::MemoryPermission::ReadExecute,
generate_random));
R_TRY(ro.Initialize(*process, *ro_mem, ro_size, Kernel::Svc::MemoryPermission::Read,
generate_random));
res = ro.Initialize(*process, *ro_mem, parameters.ro_size,
Kernel::Svc::MemoryPermission::Read, generate_random);
if (R_FAILED(res)) {
LOG_ERROR(Service_JIT, "ro_mem could not be mapped for handle=0x{:08X}", ro_mem_handle);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(res);
return;
}
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(ResultSuccess);
rb.PushIpcInterface<IJitEnvironment>(system, std::move(process), std::move(rx),
std::move(ro));
*out_jit_environment = std::make_shared<IJitEnvironment>(system, std::move(process),
std::move(rx), std::move(ro));
R_SUCCEED();
}
private:

View File

@ -65,6 +65,9 @@ Kernel::KEvent* ServiceContext::CreateEvent(std::string&& name) {
}
void ServiceContext::CloseEvent(Kernel::KEvent* event) {
if (!event) {
return;
}
event->GetReadableEvent().Close();
event->Close();
}

View File

@ -1,6 +1,8 @@
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/hle/service/glue/time/static.h"
#include "core/hle/service/psc/time/steady_clock.h"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4701) // Potentially uninitialized local variable 'result' used
@ -29,7 +31,8 @@
#include "core/hle/service/nfc/common/device.h"
#include "core/hle/service/nfc/mifare_result.h"
#include "core/hle/service/nfc/nfc_result.h"
#include "core/hle/service/time/time_manager.h"
#include "core/hle/service/service.h"
#include "core/hle/service/sm/sm.h"
#include "hid_core/frontend/emulated_controller.h"
#include "hid_core/hid_core.h"
#include "hid_core/hid_types.h"
@ -393,8 +396,7 @@ Result NfcDevice::WriteMifare(std::span<const MifareWriteBlockParameter> paramet
return result;
}
Result NfcDevice::SendCommandByPassThrough(const Time::Clock::TimeSpanType& timeout,
std::span<const u8> command_data,
Result NfcDevice::SendCommandByPassThrough(const s64& timeout, std::span<const u8> command_data,
std::span<u8> out_data) {
// Not implemented
return ResultSuccess;
@ -1399,27 +1401,41 @@ void NfcDevice::SetAmiiboName(NFP::AmiiboSettings& settings,
}
NFP::AmiiboDate NfcDevice::GetAmiiboDate(s64 posix_time) const {
const auto& time_zone_manager =
system.GetTimeManager().GetTimeZoneContentManager().GetTimeZoneManager();
Time::TimeZone::CalendarInfo calendar_info{};
auto static_service =
system.ServiceManager().GetService<Service::Glue::Time::StaticService>("time:u", true);
std::shared_ptr<Service::Glue::Time::TimeZoneService> timezone_service{};
static_service->GetTimeZoneService(timezone_service);
Service::PSC::Time::CalendarTime calendar_time{};
Service::PSC::Time::CalendarAdditionalInfo additional_info{};
NFP::AmiiboDate amiibo_date{};
amiibo_date.SetYear(2000);
amiibo_date.SetMonth(1);
amiibo_date.SetDay(1);
if (time_zone_manager.ToCalendarTime({}, posix_time, calendar_info) == ResultSuccess) {
amiibo_date.SetYear(calendar_info.time.year);
amiibo_date.SetMonth(calendar_info.time.month);
amiibo_date.SetDay(calendar_info.time.day);
if (timezone_service->ToCalendarTimeWithMyRule(calendar_time, additional_info, posix_time) ==
ResultSuccess) {
amiibo_date.SetYear(calendar_time.year);
amiibo_date.SetMonth(calendar_time.month);
amiibo_date.SetDay(calendar_time.day);
}
return amiibo_date;
}
u64 NfcDevice::GetCurrentPosixTime() const {
auto& standard_steady_clock{system.GetTimeManager().GetStandardSteadyClockCore()};
return standard_steady_clock.GetCurrentTimePoint(system).time_point;
s64 NfcDevice::GetCurrentPosixTime() const {
auto static_service =
system.ServiceManager().GetService<Service::Glue::Time::StaticService>("time:u", true);
std::shared_ptr<Service::PSC::Time::SteadyClock> steady_clock{};
static_service->GetStandardSteadyClock(steady_clock);
Service::PSC::Time::SteadyClockTimePoint time_point{};
R_ASSERT(steady_clock->GetCurrentTimePoint(time_point));
return time_point.time_point;
}
u64 NfcDevice::RemoveVersionByte(u64 application_id) const {

View File

@ -11,7 +11,6 @@
#include "core/hle/service/nfc/nfc_types.h"
#include "core/hle/service/nfp/nfp_types.h"
#include "core/hle/service/service.h"
#include "core/hle/service/time/clock_types.h"
namespace Kernel {
class KEvent;
@ -49,8 +48,8 @@ public:
Result WriteMifare(std::span<const MifareWriteBlockParameter> parameters);
Result SendCommandByPassThrough(const Time::Clock::TimeSpanType& timeout,
std::span<const u8> command_data, std::span<u8> out_data);
Result SendCommandByPassThrough(const s64& timeout, std::span<const u8> command_data,
std::span<u8> out_data);
Result Mount(NFP::ModelType model_type, NFP::MountTarget mount_target);
Result Unmount();
@ -108,7 +107,7 @@ private:
NFP::AmiiboName GetAmiiboName(const NFP::AmiiboSettings& settings) const;
void SetAmiiboName(NFP::AmiiboSettings& settings, const NFP::AmiiboName& amiibo_name) const;
NFP::AmiiboDate GetAmiiboDate(s64 posix_time) const;
u64 GetCurrentPosixTime() const;
s64 GetCurrentPosixTime() const;
u64 RemoveVersionByte(u64 application_id) const;
void UpdateSettingsCrc();
void UpdateRegisterInfoCrc();

View File

@ -6,12 +6,14 @@
#include "common/logging/log.h"
#include "core/core.h"
#include "core/hle/kernel/k_event.h"
#include "core/hle/service/glue/time/static.h"
#include "core/hle/service/ipc_helpers.h"
#include "core/hle/service/nfc/common/device.h"
#include "core/hle/service/nfc/common/device_manager.h"
#include "core/hle/service/nfc/nfc_result.h"
#include "core/hle/service/time/clock_types.h"
#include "core/hle/service/time/time_manager.h"
#include "core/hle/service/psc/time/steady_clock.h"
#include "core/hle/service/service.h"
#include "core/hle/service/sm/sm.h"
#include "hid_core/hid_types.h"
#include "hid_core/hid_util.h"
@ -82,11 +84,19 @@ Result DeviceManager::ListDevices(std::vector<u64>& nfp_devices, std::size_t max
continue;
}
if (skip_fatal_errors) {
constexpr u64 MinimumRecoveryTime = 60;
auto& standard_steady_clock{system.GetTimeManager().GetStandardSteadyClockCore()};
const u64 elapsed_time = standard_steady_clock.GetCurrentTimePoint(system).time_point -
time_since_last_error;
constexpr s64 MinimumRecoveryTime = 60;
auto static_service =
system.ServiceManager().GetService<Service::Glue::Time::StaticService>("time:u",
true);
std::shared_ptr<Service::PSC::Time::SteadyClock> steady_clock{};
static_service->GetStandardSteadyClock(steady_clock);
Service::PSC::Time::SteadyClockTimePoint time_point{};
R_ASSERT(steady_clock->GetCurrentTimePoint(time_point));
const s64 elapsed_time = time_point.time_point - time_since_last_error;
if (time_since_last_error != 0 && elapsed_time < MinimumRecoveryTime) {
continue;
}
@ -250,8 +260,7 @@ Result DeviceManager::WriteMifare(u64 device_handle,
return result;
}
Result DeviceManager::SendCommandByPassThrough(u64 device_handle,
const Time::Clock::TimeSpanType& timeout,
Result DeviceManager::SendCommandByPassThrough(u64 device_handle, const s64& timeout,
std::span<const u8> command_data,
std::span<u8> out_data) {
std::scoped_lock lock{mutex};
@ -741,8 +750,16 @@ Result DeviceManager::VerifyDeviceResult(std::shared_ptr<NfcDevice> device,
if (operation_result == ResultUnknown112 || operation_result == ResultUnknown114 ||
operation_result == ResultUnknown115) {
auto& standard_steady_clock{system.GetTimeManager().GetStandardSteadyClockCore()};
time_since_last_error = standard_steady_clock.GetCurrentTimePoint(system).time_point;
auto static_service =
system.ServiceManager().GetService<Service::Glue::Time::StaticService>("time:u", true);
std::shared_ptr<Service::PSC::Time::SteadyClock> steady_clock{};
static_service->GetStandardSteadyClock(steady_clock);
Service::PSC::Time::SteadyClockTimePoint time_point{};
R_ASSERT(steady_clock->GetCurrentTimePoint(time_point));
time_since_last_error = time_point.time_point;
}
return operation_result;

View File

@ -13,7 +13,6 @@
#include "core/hle/service/nfc/nfc_types.h"
#include "core/hle/service/nfp/nfp_types.h"
#include "core/hle/service/service.h"
#include "core/hle/service/time/clock_types.h"
#include "hid_core/hid_types.h"
namespace Service::NFC {
@ -42,7 +41,7 @@ public:
std::span<MifareReadBlockData> read_data);
Result WriteMifare(u64 device_handle,
std::span<const MifareWriteBlockParameter> write_parameters);
Result SendCommandByPassThrough(u64 device_handle, const Time::Clock::TimeSpanType& timeout,
Result SendCommandByPassThrough(u64 device_handle, const s64& timeout,
std::span<const u8> command_data, std::span<u8> out_data);
// Nfp device manager
@ -92,7 +91,7 @@ private:
const std::optional<std::shared_ptr<NfcDevice>> GetNfcDevice(u64 handle) const;
bool is_initialized = false;
u64 time_since_last_error = 0;
s64 time_since_last_error = 0;
mutable std::mutex mutex;
std::array<std::shared_ptr<NfcDevice>, 10> devices{};

View File

@ -13,7 +13,6 @@
#include "core/hle/service/nfc/nfc_result.h"
#include "core/hle/service/nfc/nfc_types.h"
#include "core/hle/service/nfp/nfp_result.h"
#include "core/hle/service/time/clock_types.h"
#include "hid_core/hid_types.h"
namespace Service::NFC {
@ -261,10 +260,10 @@ void NfcInterface::WriteMifare(HLERequestContext& ctx) {
void NfcInterface::SendCommandByPassThrough(HLERequestContext& ctx) {
IPC::RequestParser rp{ctx};
const auto device_handle{rp.Pop<u64>()};
const auto timeout{rp.PopRaw<Time::Clock::TimeSpanType>()};
const auto timeout{rp.PopRaw<s64>()};
const auto command_data{ctx.ReadBuffer()};
LOG_INFO(Service_NFC, "(STUBBED) called, device_handle={}, timeout={}, data_size={}",
device_handle, timeout.ToSeconds(), command_data.size());
device_handle, timeout, command_data.size());
std::vector<u8> out_data(1);
auto result =

View File

@ -415,4 +415,4 @@ std::optional<Set::LanguageCode> ConvertToLanguageCode(const ApplicationLanguage
return std::nullopt;
}
}
} // namespace Service::NS
} // namespace Service::NS

View File

@ -5,10 +5,7 @@
#include <optional>
#include "common/common_types.h"
namespace Service::Set {
enum class LanguageCode : u64;
}
#include "core/hle/service/set/system_settings_server.h"
namespace Service::NS {
/// This is nn::ns::detail::ApplicationLanguage

View File

@ -112,6 +112,7 @@ SessionId Container::OpenSession(Kernel::KProcess* process) {
void Container::CloseSession(SessionId session_id) {
std::scoped_lock lk(impl->session_guard);
impl->file.UnmapAllHandles(session_id);
auto& session = impl->sessions[session_id.id];
auto& smmu = impl->host1x.MemoryManager();
if (session.has_preallocated_area) {

View File

@ -326,4 +326,17 @@ std::optional<NvMap::FreeInfo> NvMap::FreeHandle(Handle::Id handle, bool interna
return freeInfo;
}
void NvMap::UnmapAllHandles(NvCore::SessionId session_id) {
auto handles_copy = [&] {
std::scoped_lock lk{handles_lock};
return handles;
}();
for (auto& [id, handle] : handles_copy) {
if (handle->session_id.id == session_id.id) {
FreeHandle(id, false);
}
}
}
} // namespace Service::Nvidia::NvCore

View File

@ -152,6 +152,8 @@ public:
*/
std::optional<FreeInfo> FreeHandle(Handle::Id handle, bool internal_session);
void UnmapAllHandles(NvCore::SessionId session_id);
private:
std::list<std::shared_ptr<Handle>> unmap_queue{};
std::mutex unmap_queue_lock{}; //!< Protects access to `unmap_queue`

View File

@ -4,6 +4,7 @@
#include "common/logging/log.h"
#include "common/scope_exit.h"
#include "common/string_util.h"
#include "core/core.h"
#include "core/hle/kernel/k_event.h"
#include "core/hle/kernel/k_process.h"
@ -29,7 +30,7 @@ void NVDRV::Open(HLERequestContext& ctx) {
}
const auto& buffer = ctx.ReadBuffer();
const std::string device_name(buffer.begin(), buffer.end());
const std::string device_name(Common::StringFromBuffer(buffer));
if (device_name == "/dev/nvhost-prof-gpu") {
rb.Push<DeviceFD>(0);

View File

@ -4,9 +4,13 @@
#include <memory>
#include "common/logging/log.h"
#include "core/core.h"
#include "core/hle/service/ipc_helpers.h"
#include "core/hle/service/psc/psc.h"
#include "core/hle/service/server_manager.h"
#include "core/hle/service/psc/time/manager.h"
#include "core/hle/service/psc/time/power_state_service.h"
#include "core/hle/service/psc/time/service_manager.h"
#include "core/hle/service/psc/time/static.h"
#include "core/hle/service/service.h"
namespace Service::PSC {
@ -76,6 +80,17 @@ void LoopProcess(Core::System& system) {
server_manager->RegisterNamedService("psc:c", std::make_shared<IPmControl>(system));
server_manager->RegisterNamedService("psc:m", std::make_shared<IPmService>(system));
auto time = std::make_shared<Time::TimeManager>(system);
server_manager->RegisterNamedService(
"time:m", std::make_shared<Time::ServiceManager>(system, time, server_manager.get()));
server_manager->RegisterNamedService(
"time:su", std::make_shared<Time::StaticService>(
system, Time::StaticServiceSetupInfo{0, 0, 0, 0, 0, 1}, time, "time:su"));
server_manager->RegisterNamedService("time:al",
std::make_shared<Time::IAlarmService>(system, time));
ServerManager::RunServer(std::move(server_manager));
}

View File

@ -0,0 +1,209 @@
// SPDX-FileCopyrightText: Copyright 2023 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "core/core.h"
#include "core/hle/service/psc/time/alarms.h"
#include "core/hle/service/psc/time/manager.h"
namespace Service::PSC::Time {
Alarm::Alarm(Core::System& system, KernelHelpers::ServiceContext& ctx, AlarmType type)
: m_ctx{ctx}, m_event{ctx.CreateEvent("Psc:Alarm:Event")} {
m_event->Clear();
switch (type) {
case WakeupAlarm:
m_priority = 1;
break;
case BackgroundTaskAlarm:
m_priority = 0;
break;
default:
UNREACHABLE();
return;
}
}
Alarm::~Alarm() {
m_ctx.CloseEvent(m_event);
}
Alarms::Alarms(Core::System& system, StandardSteadyClockCore& steady_clock,
PowerStateRequestManager& power_state_request_manager)
: m_system{system}, m_ctx{system, "Psc:Alarms"}, m_steady_clock{steady_clock},
m_power_state_request_manager{power_state_request_manager}, m_event{m_ctx.CreateEvent(
"Psc:Alarms:Event")} {}
Alarms::~Alarms() {
m_ctx.CloseEvent(m_event);
}
Result Alarms::Enable(Alarm& alarm, s64 time) {
R_UNLESS(m_steady_clock.IsInitialized(), ResultClockUninitialized);
std::scoped_lock l{m_mutex};
R_UNLESS(alarm.IsLinked(), ResultAlarmNotRegistered);
auto time_ns{time + m_steady_clock.GetRawTime()};
auto one_second_ns{
std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::seconds(1)).count()};
time_ns = Common::AlignUp(time_ns, one_second_ns);
alarm.SetAlertTime(time_ns);
Insert(alarm);
R_RETURN(UpdateClosestAndSignal());
}
void Alarms::Disable(Alarm& alarm) {
std::scoped_lock l{m_mutex};
if (!alarm.IsLinked()) {
return;
}
Erase(alarm);
UpdateClosestAndSignal();
}
void Alarms::CheckAndSignal() {
std::scoped_lock l{m_mutex};
if (m_alarms.empty()) {
return;
}
bool alarm_signalled{false};
for (auto& alarm : m_alarms) {
if (m_steady_clock.GetRawTime() >= alarm.GetAlertTime()) {
alarm.Signal();
alarm.Lock();
Erase(alarm);
m_power_state_request_manager.UpdatePendingPowerStateRequestPriority(
alarm.GetPriority());
alarm_signalled = true;
}
}
if (!alarm_signalled) {
return;
}
m_power_state_request_manager.SignalPowerStateRequestAvailability();
UpdateClosestAndSignal();
}
bool Alarms::GetClosestAlarm(Alarm** out_alarm) {
std::scoped_lock l{m_mutex};
auto alarm = m_alarms.empty() ? nullptr : std::addressof(m_alarms.front());
*out_alarm = alarm;
return alarm != nullptr;
}
void Alarms::Insert(Alarm& alarm) {
// Alarms are sorted by alert time, then priority
auto it{m_alarms.begin()};
while (it != m_alarms.end()) {
if (alarm.GetAlertTime() < it->GetAlertTime() ||
(alarm.GetAlertTime() == it->GetAlertTime() &&
alarm.GetPriority() < it->GetPriority())) {
m_alarms.insert(it, alarm);
return;
}
it++;
}
m_alarms.push_back(alarm);
}
void Alarms::Erase(Alarm& alarm) {
m_alarms.erase(m_alarms.iterator_to(alarm));
}
Result Alarms::UpdateClosestAndSignal() {
m_closest_alarm = m_alarms.empty() ? nullptr : std::addressof(m_alarms.front());
R_SUCCEED_IF(m_closest_alarm == nullptr);
m_event->Signal();
R_SUCCEED();
}
IAlarmService::IAlarmService(Core::System& system_, std::shared_ptr<TimeManager> manager)
: ServiceFramework{system_, "time:al"}, m_system{system}, m_alarms{manager->m_alarms} {
// clang-format off
static const FunctionInfo functions[] = {
{0, &IAlarmService::CreateWakeupAlarm, "CreateWakeupAlarm"},
{1, &IAlarmService::CreateBackgroundTaskAlarm, "CreateBackgroundTaskAlarm"},
};
// clang-format on
RegisterHandlers(functions);
}
void IAlarmService::CreateWakeupAlarm(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(ResultSuccess);
rb.PushIpcInterface<ISteadyClockAlarm>(system, m_alarms, AlarmType::WakeupAlarm);
}
void IAlarmService::CreateBackgroundTaskAlarm(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::ResponseBuilder rb{ctx, 2, 0, 1};
rb.Push(ResultSuccess);
rb.PushIpcInterface<ISteadyClockAlarm>(system, m_alarms, AlarmType::BackgroundTaskAlarm);
}
ISteadyClockAlarm::ISteadyClockAlarm(Core::System& system_, Alarms& alarms, AlarmType type)
: ServiceFramework{system_, "ISteadyClockAlarm"}, m_ctx{system, "Psc:ISteadyClockAlarm"},
m_alarms{alarms}, m_alarm{system, m_ctx, type} {
// clang-format off
static const FunctionInfo functions[] = {
{0, &ISteadyClockAlarm::GetAlarmEvent, "GetAlarmEvent"},
{1, &ISteadyClockAlarm::Enable, "Enable"},
{2, &ISteadyClockAlarm::Disable, "Disable"},
{3, &ISteadyClockAlarm::IsEnabled, "IsEnabled"},
{10, nullptr, "CreateWakeLock"},
{11, nullptr, "DestroyWakeLock"},
};
// clang-format on
RegisterHandlers(functions);
}
void ISteadyClockAlarm::GetAlarmEvent(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::ResponseBuilder rb{ctx, 2, 1};
rb.Push(ResultSuccess);
rb.PushCopyObjects(m_alarm.GetEventHandle());
}
void ISteadyClockAlarm::Enable(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::RequestParser rp{ctx};
auto time{rp.Pop<s64>()};
auto res = m_alarms.Enable(m_alarm, time);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(res);
}
void ISteadyClockAlarm::Disable(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
m_alarms.Disable(m_alarm);
IPC::ResponseBuilder rb{ctx, 2};
rb.Push(ResultSuccess);
}
void ISteadyClockAlarm::IsEnabled(HLERequestContext& ctx) {
LOG_DEBUG(Service_Time, "called.");
IPC::ResponseBuilder rb{ctx, 3};
rb.Push(ResultSuccess);
rb.Push<bool>(m_alarm.IsLinked());
}
} // namespace Service::PSC::Time

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