Compare commits

...

88 Commits
0.8.4 ... 0.8.5

Author SHA1 Message Date
Michael Scire
b42d16cf1c Atmosphere: Bump version to 0.8.5 2019-03-07 10:27:22 -08:00
Michael Scire
bcdf32b214 0.8.5: amend changelog 2019-03-07 10:26:53 -08:00
Michael Scire
9c3728c8f2 Add 0.8.5 changelog ahead of release, fix keypress docs. 2019-03-07 04:13:32 -08:00
Michael Scire
23fff1e8fd Add cheats.md 2019-03-07 03:51:18 -08:00
Michael Scire
a553fbcdd1 docs: add dmnt.md 2019-03-07 02:51:26 -08:00
Michael Scire
e62606d276 fatal: only set display magnification on 3.0.0+ 2019-03-06 14:39:48 -08:00
Michael Scire
e25d83f701 fss: seems ext_csd is not initialized by then 2019-03-06 08:34:33 -08:00
Michael Scire
ed37c149d1 fss: how many commits does it take to fix one line of code? 2019-03-06 05:56:58 -08:00
Michael Scire
7c8d126f23 fusee-secondary: fix previous generalization 2019-03-06 05:55:35 -08:00
Michael Scire
c9b88f0404 fusee: dynamically read NAND num_sectors (thanks @shchmue!) 2019-03-06 05:40:32 -08:00
Michael Scire
e24d7a1fd2 default-settings: Language. 2019-03-06 00:21:29 -08:00
Michael Scire
d756f2fc0d dmnt-cheat: make cheats default toggle configurable 2019-03-06 00:20:17 -08:00
Michael Scire
4d0ab41e6e dmnt-cheat: Fix debug event management 2019-03-05 23:58:36 -08:00
Michael Scire
512dbc3a24 dmnt: prevent lag on game thread-spawning 2019-03-05 18:57:50 -08:00
Michael Scire
a3d44e37b5 dmnt-cheat: *properly* update frozen address values on write 2019-03-05 11:56:17 -08:00
Michael Scire
18e4d80073 dmnt-cheat: update frozen address values on write 2019-03-05 11:44:24 -08:00
Michael Scire
e5bedd52ac fusee-secondary: add content type to content headers 2019-03-05 10:53:17 -08:00
Michael Scire
a38927ec04 fatal: remove debugging log that slipped through 2019-03-05 07:52:42 -08:00
Michael Scire
fbddf090a4 dmnt: only initialize HID once 2019-03-05 07:50:50 -08:00
Michael Scire
b4b1208222 stratosphere: fix svcExitThread usage 2019-03-05 07:50:27 -08:00
Michael Scire
4e95397ed5 dmnt-cheat: const correctness 2019-03-05 01:40:49 -08:00
Michael Scire
853a57e4d4 dmnt-cheat: Support nested conditionals in VM 2019-03-05 01:39:20 -08:00
Michael Scire
8c86074da2 dmnt-cheat: Add opcode to store register to memory 2019-03-05 01:20:18 -08:00
Michael Scire
88a6ef4cd7 ams: default USB 3.0 off (some users see issues) 2019-03-05 00:56:17 -08:00
Michael Scire
7d2dd628ba dmnt-cheat: multi-nybble opcodes, update libstrat 2019-03-05 00:53:45 -08:00
Michael Scire
7e93ca0977 dmnt: give hid access 2019-03-04 22:40:58 -08:00
Michael Scire
eddbd7c072 dmnt-cheat: output value on EnableFrozenAddress 2019-03-04 22:17:18 -08:00
Michael Scire
e734a5412a dmnt-cheat: Implement frozen addresses 2019-03-04 22:13:43 -08:00
Michael Scire
7ddb0da5f6 dmnt-cheat: Implement cheat management service commands 2019-03-04 21:11:12 -08:00
Michael Scire
862aa73783 Add maximum instruction opcode bounds check (thanks hthh) 2019-03-04 20:24:49 -08:00
Michael Scire
34af93b72f dmnt-cheat: implement cheat loading from SD 2019-03-04 20:13:52 -08:00
Michael Scire
5ef3ca9364 fs.mitm: make prodinfo backups actually work 2019-03-04 19:05:52 -08:00
Michael Scire
37d3577028 dmnt: allow disabling cheats via title-specific button combo 2019-03-04 06:55:37 -08:00
Michael Scire
ef68881e5c dmnt-cheat: Implement memory service cmds 2019-03-04 05:56:44 -08:00
Michael Scire
e8a5aa81f4 dmnt-cheat: fix decode error, add debug logging 2019-03-04 01:41:01 -08:00
Michael Scire
f2f25dd5ed atmosphere: launch tma (fixes home button) 2019-03-03 23:53:53 -08:00
Michael Scire
8d140d835a dmnt-cheat: fix compat 2019-03-03 23:42:52 -08:00
Michael Scire
afae7eaa11 dmnt-cheat: finish vm instruction decoder 2019-03-03 09:09:21 -08:00
Michael Scire
af70a4a3a3 dmnt-cheat: skeleton decode, fix missing libnx call 2019-03-03 06:44:21 -08:00
Michael Scire
bc6ad53018 dmnt-cheat: Implement remaining VM opcodes 2019-03-03 06:29:48 -08:00
Michael Scire
a3fc2c95b8 dmnt-cheat: Add new, better math instruction to vm 2019-02-27 19:30:29 -08:00
Michael Scire
68af2c1c2a dmnt-cheat: Implement static math opcode. 2019-02-27 18:46:53 -08:00
Michael Scire
2552c0327c dmnt-cheat: Begin implementing Cheat VM. 2019-02-27 18:33:07 -08:00
Michael Scire
f5ac895062 dmnt-cheat: revise cheatentry definition 2019-02-27 04:47:43 -08:00
Michael Scire
e4cc39c29b dmnt-cheat: Implement all meta commands. 2019-02-27 04:37:02 -08:00
Michael Scire
c80eb26135 dmnt-cheat: continue fleshing out cheat manager code 2019-02-27 04:27:49 -08:00
Michael Scire
964a698875 dmnt-cheat: flesh out new process logic 2019-02-27 04:09:14 -08:00
Michael Scire
b57ec74ca3 pm: remove duplicate definitions 2019-02-27 03:33:42 -08:00
Michael Scire
66d5c9fe26 dmnt-cheat: Skeleton cheat manager 2019-02-27 03:30:08 -08:00
Michael Scire
434f600f95 dmnt: Skeleton cheat service API. 2019-02-27 02:51:05 -08:00
Michael Scire
89503049b3 dmnt: pull in from ams.tma branch 2019-02-27 01:44:47 -08:00
Michael Scire
aaabb4bfc4 atmosphere: add define for supported hos version 2019-02-24 20:28:06 -08:00
Michael Scire
be772b40e1 fusee-secondary: add content metadata 2019-02-24 20:22:57 -08:00
Dylan Nguyen
3149b8a6fe Update readme.md reswitched website (#339)
Should be reswitched.team, 

the other one (reswitched.tech) is not availble
2019-02-24 12:51:45 -08:00
Michael Scire
c8e0028874 Make default override key !L 2019-02-23 22:14:38 -08:00
Michael Scire
a8d929a343 fs.mitm: fix inverted conditional 2019-02-23 22:11:57 -08:00
thedax
618de9546a Makefile tweaks. (#376)
-Have fusee-secondary clean sept-secondary as required.
-Use $(TARGET) variable for sept-secondary, and clean the encrypted output as required.
2019-02-23 17:16:37 -08:00
Michael Scire
2673118478 update loader doc 2019-02-23 07:43:12 -08:00
Michael Scire
6cc69fb3fc fs.mitm: Add title-specific override key support. 2019-02-23 07:39:40 -08:00
Michael Scire
eefee8c7a8 loader: add support for title-specific override keys 2019-02-23 07:18:24 -08:00
Pedro Diaz
dcf44e406e Fix sept-secondary build when using prebuild sept-secondary.enc (#371) 2019-02-22 18:57:27 -08:00
thedax
1970a52fc9 Allow the user to build with a prebuilt sept-secondary blob via a SEPT_ENC_PATH variable. (#365) 2019-02-21 18:26:41 -08:00
Michael Scire
aca8f53050 Merge branch 'master' into debugger_dev 2018-12-07 14:55:28 -08:00
Michael Scire
cdb7ce3dec ams: turn on debugmode by default. 2018-12-07 03:32:24 -08:00
Michael Scire
49d1e65496 tma: Fix nn.tma.PmModuleThread priority 2018-12-07 03:26:06 -08:00
Michael Scire
29153af2bc tma.tio: Improve read/write bounding. 2018-12-06 23:25:16 -08:00
Michael Scire
f79f4d175b tma: add more dmnt wrapper commands 2018-12-06 20:21:15 -08:00
Michael Scire
600ad660a6 tma: First pass at tio file read/write 2018-12-06 15:32:27 -08:00
Michael Scire
efcce68a56 tma: Correct JSON to work as non-kip 2018-12-06 13:55:02 -08:00
Michael Scire
6b04c937e6 dmnt: Add remaining TargetIO_File* funcs 2018-12-06 13:39:27 -08:00
Michael Scire
46c50f2cbe dmnt: Add TargetIO_Open/Close/Read/Write funcs. 2018-12-06 13:16:33 -08:00
Michael Scire
eb6ab2ba62 dmnt: Implement three more easy commands 2018-12-05 23:57:35 -08:00
Michael Scire
8a92a63a64 pm: Don't launch titles twice due to boot2.flag 2018-12-05 23:44:11 -08:00
Michael Scire
907f6fa72d stratosphere: make tma non-kip, add to build system 2018-12-05 23:36:12 -08:00
Michael Scire
94e527e763 dmnt: Skeleton real process implementation. 2018-12-05 23:35:09 -08:00
Michael Scire
588315f877 dmnt: Create Makefile/Process folder. 2018-12-05 21:08:04 -08:00
Michael Scire
d1985fe77e tma: better GetSettingsTask output 2018-12-05 13:21:21 -08:00
Michael Scire
61ad4e0991 tma: Implement example set:sys getter service 2018-12-05 13:18:31 -08:00
Michael Scire
24be9ffc57 tma: Add working AtmosphereTestService (echoes As) 2018-12-05 08:33:56 -08:00
Michael Scire
d875d84d2d tma: Fix sleep/wake semantics, now tested on hardware. 2018-12-05 07:11:06 -08:00
Michael Scire
9fe8b22269 Merge branch 'master' into debugger_dev 2018-12-05 05:44:58 -08:00
Michael Scire
37e5a8544b tma: Add target initialization/power management logic 2018-12-05 05:31:45 -08:00
Michael Scire
bf7dc84893 tma: first pass at TmaServiceManager 2018-12-05 04:16:48 -08:00
Michael Scire
bb48e33074 tma: Skeleton Service/Task/TaskList classes. 2018-12-05 02:11:20 -08:00
Michael Scire
2572ae8378 tma: impl helper services, cleanup hostside packets 2018-11-30 18:18:04 -08:00
Michael Scire
46001263f8 tma: impl helper services, cleanup hostside packets 2018-11-30 18:18:04 -08:00
Michael Scire
ec8523af7c tma: Implement USB packet rw. 2018-11-30 18:18:03 -08:00
Michael Scire
2708de3876 debug-kit: Implement tma.stub 2018-11-30 18:18:03 -08:00
51 changed files with 5051 additions and 192 deletions

View File

@@ -1,6 +1,7 @@
TOPTARGETS := all clean dist
AMSBRANCH := $(shell git symbolic-ref --short HEAD)
AMSREV := $(AMSBRANCH)-$(shell git rev-parse --short HEAD)
AMSHASH := $(shell git rev-parse --short HEAD)
AMSREV := $(AMSBRANCH)-$(AMSHASH)
ifneq (, $(strip $(shell git status --porcelain 2>/dev/null)))
AMSREV := $(AMSREV)-dirty
@@ -53,6 +54,7 @@ dist: all
mkdir -p atmosphere-$(AMSVER)/atmosphere/titles/0100000000000034
mkdir -p atmosphere-$(AMSVER)/atmosphere/titles/0100000000000032
cp fusee/fusee-primary/fusee-primary.bin atmosphere-$(AMSVER)/atmosphere/reboot_payload.bin
mkdir -p atmosphere-$(AMSVER)/atmosphere/titles/010000000000000D
cp fusee/fusee-secondary/fusee-secondary.bin atmosphere-$(AMSVER)/atmosphere/fusee-secondary.bin
cp fusee/fusee-secondary/fusee-secondary.bin atmosphere-$(AMSVER)/sept/payload.bin
cp sept/sept-primary/sept-primary.bin atmosphere-$(AMSVER)/sept/sept-primary.bin
@@ -68,6 +70,7 @@ dist: all
cp troposphere/reboot_to_payload/reboot_to_payload.nro atmosphere-$(AMSVER)/switch/reboot_to_payload.nro
mkdir -p atmosphere-$(AMSVER)/atmosphere/titles/0100000000000032/flags
touch atmosphere-$(AMSVER)/atmosphere/titles/0100000000000032/flags/boot2.flag
cp stratosphere/dmnt/dmnt.nsp atmosphere-$(AMSVER)/atmosphere/titles/010000000000000D/exefs.nsp
cd atmosphere-$(AMSVER); zip -r ../atmosphere-$(AMSVER).zip ./*; cd ../;
rm -r atmosphere-$(AMSVER)
mkdir out

View File

@@ -27,7 +27,7 @@ In no particular order, we credit the following for their invaluable contributio
* __switchbrew__ for the [libnx](https://github.com/switchbrew/libnx) project and the extensive [documentation, research and tool development](http://switchbrew.org) pertaining to the Nintendo Switch.
* __devkitPro__ for the [devkitA64](https://devkitpro.org/) toolchain and libnx support.
* __ReSwitched Team__ for additional [documentation, research and tool development](https://reswitched.tech/) pertaining to the Nintendo Switch.
* __ReSwitched Team__ for additional [documentation, research and tool development](https://reswitched.team/) pertaining to the Nintendo Switch.
* __ChaN__ for the [FatFs](http://elm-chan.org/fsw/ff/00index_e.html) module.
* __Marcus Geelnard__ for the [bcl-1.2.0](https://sourceforge.net/projects/bcl/files/bcl/bcl-1.2.0) library.
* __naehrwert__ and __st4rk__ for the original [hekate](https://github.com/nwert/hekate) project and its hwinit code base.

View File

@@ -1,4 +1,8 @@
[config]
hbl_tid=010000000000100D
hbl_path=atmosphere/hbl.nsp
override_key=!R
[hbl_config]
title_id=010000000000100D
path=atmosphere/hbl.nsp
override_key=!R
[default_config]
override_key=!L
cheat_enable_key=!L

View File

@@ -3,9 +3,12 @@
upload_enabled = u8!0x0
; Enable USB 3.0 superspeed for homebrew
[usb]
usb30_force_enabled = u8!0x1
usb30_force_enabled = u8!0x0
; Atmosphere custom settings
[atmosphere]
; Make the power menu's "reboot" button reboot to payload.
; Set to "normal" for normal reboot, "rcm" for rcm reboot.
power_menu_reboot_function = str!payload
power_menu_reboot_function = str!payload
; Controls whether dmnt cheats should be toggled on or off by
; default. 1 = toggled on by default, 0 = toggled off by default.
dmnt_cheats_enabled_by_default = u8!0x1

View File

@@ -19,6 +19,10 @@
#define ATMOSPHERE_RELEASE_VERSION_MAJOR 0
#define ATMOSPHERE_RELEASE_VERSION_MINOR 8
#define ATMOSPHERE_RELEASE_VERSION_MICRO 4
#define ATMOSPHERE_RELEASE_VERSION_MICRO 5
#define ATMOSPHERE_SUPPORTED_HOS_VERSION_MAJOR 7
#define ATMOSPHERE_SUPPORTED_HOS_VERSION_MINOR 0
#define ATMOSPHERE_SUPPORTED_HOS_VERSION_MICRO 1
#endif

View File

@@ -1,4 +1,25 @@
# Changelog
## 0.8.5
+ Support was added for overriding content on a per-title basis, separate from HBL override.
+ This allows for using mods on the same title that one uses to launch HBL.
+ By default, `!L` is used for title content override (this is configurable by editing `default_config!override_key` in `loader.ini`)
+ This key combination can be set on a per-title basis by creating a `atmosphere/titles/<title id>/config.ini`, and editing `override_config!override_key`.
+ Content headers were added for the embedded files inside of fusee-secondary.
+ This will allow non-fusee bootloaders (like `hekate`) to extract the components bundled inside release binaries.
+ This should greatly simplify the update process in the future, for users who do not launch Atmosphère using fusee.
+ Support for cheat codes was added.
+ These are handled by a new `dmnt` sysmodule, which will also reimplement Nintendo's Debug Monitor in the future.
+ Cheat codes can be enabled/disabled at application launch via a per-title key combination.
+ For details, please see the [cheat loading documentation](https://github.com/Atmosphere-NX/Atmosphere/blob/master/docs/cheats.md#cheat-loating-process).
+ Cheat codes are fully backwards compatible with the pre-existing format, although a number of bugs have been fixed and some new features have been added.
+ For details, please see [the compatibility documentation](https://github.com/Atmosphere-NX/Atmosphere/blob/master/docs/cheats.md#cheat-code-compatibility).
+ An HIPC service API was added (`dmnt:cht`), that will allow user homebrew to interface with and control Atmosphère's cheat manager.
+ Please see [the relevant documentation](https://github.com/Atmosphere-NX/Atmosphere/blob/master/docs/modules/dmnt.md).
+ Full client code can be found in [libstratosphere](https://github.com/Atmosphere-NX/libstratosphere/blob/master/include/stratosphere/services/dmntcht.h).
+ Users interested in interfacing should see [EdiZon](https://github.com/WerWolv/EdiZon), which should have support for interfacing with Atmosphère's API shortly after 0.8.5 releases.
+ A bug was fixed that would cause Atmosphère's fatal screen to not show on 1.0.0-2.3.0.
+ A bug was fixed that caused Atmosphère's automatic ProdInfo backups to be corrupt.
+ General system stability improvements to enhance the user's experience.
## 0.8.4
+ Support for 7.0.0/7.0.1 was added.
+ This is facilitated through a new payload, `sept`, which can be signed, encrypted, and then loaded by Nintendo's TSEC firmware.

316
docs/cheats.md Normal file
View File

@@ -0,0 +1,316 @@
# Cheats
Atmosphère supports Action-Replay style cheat codes, with cheats loaded off of the SD card.
## Cheat Loading Process
By default, Atmosphère will do the following when deciding whether to attach to a new application process:
+ Retrieve information about the new application process from `pm` and `loader`.
+ Check whether a user-defined key combination is held, and stop if not.
+ This defaults to "L is not held", and can be configured the same way as `fs.mitm` override keys.
+ The ini key to configure this is `cheat_enable_key`.
+ Check whether the process is a real application, and stop if not.
+ This guards against applying cheat codes to the homebrew loader.
+ Attempt to load cheats from `atmosphere/titles/<title_id>/cheats/<build_id>.txt`, where `build_id` is the hexadecimal representation of the first 8 bytes of the application's main executable's build id.
+ If no cheats are found, then the cheat manager will stop.
+ Open a kernel debug session for the new application process.
+ Signal to a system event that a new cheat process has been attached to.
This behavior ensures that cheat codes are only loaded when the user would want them to.
In cases where dmnt has not activated the cheat manager, but the user wants to make it do so anyway, the cheat manager's service API provides a `ForceOpenCheatProcess` command that homebrew can use. This command will cause the cheat manager to try to force itself to attach to the process.
By default, all cheat codes listed in the loaded .txt file will be toggled on. This is configurable by the user, and the default can be set to toggled off by editing the `atmosphere!dmnt_cheats_enabled_by_default` entry to 0 instead of 1.
Users may use homebrew programs to toggle cheats on and off at runtime via the cheat manager's service API.
## Cheat Code Compatibility
Atmosphère manages cheat code through the execution of a small, custom virtual machine. Care has been taken to ensure that Atmosphère's cheat code format is fully backwards compatible with the pre-existing cheat code format, though new features have been added and bugs in the pre-existing cheat code applier have been fixed. Here is a short summary of the changes from the pre-existing format:
+ A number of bugs were fixed in the processing of conditional instructions.
+ The pre-existing implementation was fundamentally broken, and checked for the wrong value when detecting the end of a conditional block.
+ The pre-existing implementation also did not properly decode instructions, and instead linearly scanned for the terminator value. This caused problems if an instruction happened to encode a terminator inside its immediate values.
+ The pre-existing implementation did not bounds check, and thus certain conditional cheat codes could cause it to read out-of-bounds memory, and potentially crash due to a data abort.
+ Support was added for nesting conditional blocks.
+ An instruction was added to perform much more complex arbitrary arithmetic on two registers.
+ An instruction was added to allow writing the contents of register to a memory address specified by another register.
+ The pre-existing implementation did not correctly synchronize with the application process, and thus would cause heavy lag under certain circumstances (especially around loading screens). This has been fixed in Atmosphère's implementation.
## Cheat Code Format
The following provides documentation of the instruction format for the virtual machine used to manage cheat codes.
Typically, instruction type is encoded in the upper nybble of the first instruction u32.
### Code Type 0: Store Static Value to Memory
Code type 0 allows writing a static value to a memory address.
#### Encoding
`0TMR00AA AAAAAAAA VVVVVVVV (VVVVVVVV)`
+ T: width of memory write (1, 2, 4, or 8 bytes)
+ M: memory region to write to (0 = Main NSO, 1 = Heap)
+ R: Register to use as an offset from memory region base.
+ A: Immediate offset to use from memory region base.
+ V: Value to write.
---
### Code Type 1: Begin Conditional Block
Code type 1 performs a comparison of the contents of memory to a static value.
If the condition is not met, all instructions until the appropriate conditional block terminator are skipped.
#### Encoding
`1TMC00AA AAAAAAAA VVVVVVVV (VVVVVVVV)`
+ T: width of memory write (1, 2, 4, or 8 bytes)
+ M: memory region to write to (0 = Main NSO, 1 = Heap)
+ C: Condition to use, see below.
+ A: Immediate offset to use from memory region base.
+ V: Value to compare to.
#### Conditions
+ 1: >
+ 2: >=
+ 3: <
+ 4: <=
+ 5: ==
+ 6: !=
---
### Code Type 2: End Conditional Block
Code type 2 marks the end of a conditional block (started by Code Type 1 or Code Type 8).
#### Encoding
`20000000`
---
### Code Type 3: Start/End Loop
Code type 3 allows for iterating in a loop a fixed number of times.
#### Start Loop Encoding
`300R0000 VVVVVVVV`
+ R: Register to use as loop counter.
+ V: Number of iterations to loop.
#### End Loop Encoding
`310R0000`
+ R: Register to use as loop counter.
---
### Code Type 4: Load Register with Static Value
Code type 4 allows setting a register to a constant value.
#### Encoding
`400R0000 VVVVVVVV VVVVVVVV`
+ R: Register to use.
+ V: Value to load.
---
### Code Type 5: Load Register with Memory Value
Code type 5 allows loading a value from memory into a register, either using a fixed address or by dereferencing the destination register.
#### Load From Fixed Address Encoding
`5TMR00AA AAAAAAAA`
+ T: width of memory read (1, 2, 4, or 8 bytes)
+ M: memory region to write to (0 = Main NSO, 1 = Heap)
+ R: Register to load value into.
+ A: Immediate offset to use from memory region base.
#### Load from Register Address Encoding
`5TMR10AA AAAAAAAA`
+ T: width of memory read (1, 2, 4, or 8 bytes)
+ M: memory region to write to (0 = Main NSO, 1 = Heap)
+ R: Register to load value into.
+ A: Immediate offset to use from register R.
---
### Code Type 6: Store Static Value to Register Memory Address
Code type 6 allows writing a fixed value to a memory address specified by a register.
#### Encoding
`6T0RIor0 VVVVVVVV VVVVVVVV`
+ T: width of memory write (1, 2, 4, or 8 bytes)
+ R: Register used as base memory address.
+ I: Increment register flag (0 = do not increment R, 1 = increment R by T).
+ o: Offset register enable flag (0 = do not add r to address, 1 = add r to address).
+ r: Register used as offset when o is 1.
+ V: Value to write to memory.
---
### Code Type 7: Legacy Arithmetic
Code type 7 allows performing arithmetic on registers.
However, it has been deprecated by Code type 9, and is only kept for backwards compatibility.
#### Encoding
`7T0RC000 VVVVVVVV`
+ T: width of arithmetic operation (1, 2, 4, or 8 bytes)
+ R: Register to apply arithmetic to.
+ C: Arithmetic operation to apply, see below.
+ V: Value to use for arithmetic operation.
#### Arithmetic Types
+ 0: Addition
+ 1: Subtraction
+ 2: Multiplication
+ 3: Left Shift
+ 4: Right Shift
---
### Code Type 8: Begin Keypress Conditional Block
Code type 8 enters or skips a conditional block based on whether a key combination is pressed.
#### Encoding
`8kkkkkkk`
+ k: Keypad mask to check against, see below.
Note that for multiple button combinations, the bitmasks should be ORd together.
#### Keypad Values
Note: This is the direct output of `hidKeysDown()`.
+ 0000001: A
+ 0000002: B
+ 0000004: X
+ 0000008: Y
+ 0000010: Left Stick Pressed
+ 0000020: Right Stick Pressed
+ 0000040: L
+ 0000080: R
+ 0000100: ZL
+ 0000200: ZR
+ 0000400: Plus
+ 0000800: Minus
+ 0001000: Left
+ 0002000: Up
+ 0004000: Right
+ 0008000: Down
+ 0010000: Left Stick Left
+ 0020000: Left Stick Up
+ 0040000: Left Stick Right
+ 0080000: Left Stick Down
+ 0100000: Right Stick Left
+ 0200000: Right Stick Up
+ 0400000: Right Stick Right
+ 0800000: Right Stick Down
+ 1000000: SL
+ 2000000: SR
---
### Code Type 9: Perform Arithmetic
Code type 9 allows performing arithmetic on registers.
#### Register Arithmetic Encoding
`9TCRS0s0`
+ T: width of arithmetic operation (1, 2, 4, or 8 bytes)
+ C: Arithmetic operation to apply, see below.
+ R: Register to store result in.
+ S: Register to use as left-hand operand.
+ s: Register to use as right-hand operand.
#### Immediate Value Arithmetic Encoding
`9TCRS100 VVVVVVVV (VVVVVVVV)`
+ T: width of arithmetic operation (1, 2, 4, or 8 bytes)
+ C: Arithmetic operation to apply, see below.
+ R: Register to store result in.
+ S: Register to use as left-hand operand.
+ V: Value to use as right-hand operand.
#### Arithmetic Types
+ 0: Addition
+ 1: Subtraction
+ 2: Multiplication
+ 3: Left Shift
+ 4: Right Shift
+ 5: Logical And
+ 6: Logical Or
+ 7: Logical Not (discards right-hand operand)
+ 8: Logical Xor
+ 9: None/Move (discards right-hand operand)
---
### Code Type 10: Store Register to Memory Address
Code type 10 allows writing a register to memory.
#### Encoding
`ATSRIOra (aaaaaaaa)`
+ T: width of memory write (1, 2, 4, or 8 bytes)
+ S: Register to write to memory.
+ R: Register to use as base address.
+ I: Increment register flag (0 = do not increment R, 1 = increment R by T).
+ O: Offset type, see below.
+ r: Register used as offset when O is 1.
+ a: Value used as offset when O is 2.
#### Offset Types
+ 0: No Offset
+ 1: Use Offset Register
+ 2: Use Fixed Offset
---
### Code Type 11: Reserved
Code Type 11 is currently reserved for future use.
---
### Code Type 12-15: Extended-Width Instruction
Code Types 12-15 signal to the VM to treat the upper two nybbles of the first dword as instruction type, instead of just the upper nybble.
This reserves an additional 64 opcodes for future use.
---

38
docs/modules/dmnt.md Normal file
View File

@@ -0,0 +1,38 @@
# dmnt
dmnt is a reimplementation of Nintendo's debug monitor. It provides Atmosphère a rich set of debugging functionality, so that users can easily analyze the behaviors of programs. In addition, Atmosphère implements an extension in dmnt to provide cheat code functionality.
## Atmosphère Cheat Extension
In addition to the functionality provided by Nintendo's debug monitor, Atmosphère's dmnt has an extension for providing cheat code functionality. A HIPC Service API is provided for interacting with the cheat code manager, through the service `dmnt:cht`.
Those looking for more information on the cheat code functionality may wish to read `cheats.md`.
The SwIPC definition for `dmnt:cht` follows.
```
interface DmntCheatService is dmnt:cht {
[65000] HasCheatProcess() -> bool;
[65001] GetCheatProcessEvent() -> KObject;
[65002] GetCheatProcessMetadata() -> CheatProcessMetadata;
[65003] ForceOpenCheatProcess();
[65100] GetCheatProcessMappingCount() -> u64;
[65101] GetCheatProcessMappings(u64 offset) -> buffer<MemoryInfo, 6>, u64 count;
[65102] ReadCheatProcessMemory(u64 address, u64 size) -> buffer<u8, 6> data;
[65103] WriteCheatProcessMemory(u64 address, u64 size, buffer<u8, 5> data);
[65104] QueryCheatProcessMemory(u64 address) -> MemoryInfo;
[65200] GetCheatCount() -> u64;
[65201] GetCheats(u64 offset) -> buffer<CheatEntry, 6>, u64 count;
[65202] GetCheatById(u32 cheat_id) -> buffer<CheatEntry, 6> cheat;
[65203] ToggleCheat(u32 cheat_id);
[65204] AddCheat(buffer<CheatDefinition, 5> cheat, bool enabled) -> u32 cheat_id;
[65203] RemoveCheat(u32 cheat_id);
[65300] GetFrozenAddressCount() -> u64;
[65301] GetFrozenAddresses(u64 offset) -> buffer<FrozenAddressEntry, 6>, u64 count;
[65302] GetFrozenAddress(u64 address) -> FrozenAddressEntry;
[65303] EnableFrozenAddress(u64 address, u64 width) -> u64 value;
[65304] DisableFrozenAddress(u64 address);
}
```

View File

@@ -55,7 +55,7 @@ When authoring patches, [hactool](https://github.com/SciresM/hactool) can be use
Atmosphère can use the loader module in order to turn any game on your Switch's home menu into a launchpoint for the Homebrew Menu, rather than launching it through the album applet. This allows one to launch the Homebrew Menu with access to the ~3.2GB of RAM that the Switch reserves for games and applications, as opposed to the 442MB of RAM we are limited to when launching the Homebrew Menu from the album. This also means that it is no longer necessary to install homebrew as `.nsp` files on your Switch so long as you are using this method, as the only reason to do so is to allow the homebrew to access all of the Switch's available memory.
In order to setup this method you will need the latest release of [hbmenu](https://github.com/switchbrew/nx-hbmenu/releases), and the latest release of [hbloader](https://github.com/switchbrew/nx-hbloader/releases). Place `hbmenu.nro` on the root of your Switch's SD Card, and place `hbl.nsp` in the atmosphere folder. From there, simply configure `loader.ini` in the atmosphere folder by replacing the Title ID in the ini (hbl_tid) (it is the Title ID for the album by default) with the Title ID of whatever game you wish to use to launch the Homebrew Menu. A list of Title IDs for Switch Games can be found [here](https://switchbrew.org/wiki/Title_list/Games). Afterwards you may reinsert your SD Card into your Switch and boot into Atmosphère as you normally would. You should now be able to boot into the Homebrew Menu by launching your designated game of choice.
In order to setup this method you will need the latest release of [hbmenu](https://github.com/switchbrew/nx-hbmenu/releases), and the latest release of [hbloader](https://github.com/switchbrew/nx-hbloader/releases). Place `hbmenu.nro` on the root of your Switch's SD Card, and place `hbl.nsp` in the atmosphere folder. From there, simply configure `loader.ini` in the atmosphere folder by replacing the Title ID in the ini (title_id in the [hbl_config] section) (it is the Title ID for the album by default) with the Title ID of whatever game you wish to use to launch the Homebrew Menu. A list of Title IDs for Switch Games can be found [here](https://switchbrew.org/wiki/Title_list/Games). Afterwards you may reinsert your SD Card into your Switch and boot into Atmosphère as you normally would. You should now be able to boot into the Homebrew Menu by launching your designated game of choice.
### Button Overrides

View File

@@ -14,7 +14,7 @@ The SwIPC definition for this command follows.
```
interface nn::pm::detail::IDebugMonitorInterface is pm:dmnt {
...
[65000] AtmosphereGetProcessHandle(u64 pid) -> handle<copy, process> process_handle;
[65000] AtmosphereGetProcessInfo(u64 pid) -> handle<copy, process> process_handle, u64 title_id, u64 storage_id;
}
```

View File

@@ -13,7 +13,8 @@ AMS := $(TOPDIR)/../../
include $(DEVKITARM)/base_rules
AMSBRANCH := $(shell git symbolic-ref --short HEAD)
AMSREV := $(AMSBRANCH)-$(shell git rev-parse --short HEAD)
AMSHASH := $(shell git rev-parse --short HEAD)
AMSREV := $(AMSBRANCH)-$(AMSHASH)
ifneq (, $(strip $(shell git status --porcelain 2>/dev/null)))
AMSREV := $(AMSREV)-dirty
@@ -43,7 +44,7 @@ INCLUDES := include ../../common/include
# options for code generation
#---------------------------------------------------------------------------------
ARCH := -march=armv4t -mtune=arm7tdmi -marm
DEFINES := -D__BPMP__ -DFUSEE_STAGE2_SRC -DATMOSPHERE_GIT_BRANCH=\"$(AMSBRANCH)\" -DATMOSPHERE_GIT_REV=\"$(AMSREV)\"
DEFINES := -D__BPMP__ -DFUSEE_STAGE2_SRC -DATMOSPHERE_GIT_BRANCH=\"$(AMSBRANCH)\" -DATMOSPHERE_GIT_REV=\"$(AMSREV)\" -DATMOSPHERE_GIT_HASH=$(AMSHASH)
CFLAGS := \
-g \
@@ -61,7 +62,7 @@ CFLAGS += $(INCLUDE)
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions -std=gnu++11
ASFLAGS := -g $(ARCH)
ASFLAGS := -g $(ARCH) $(INCLUDE) $(DEFINES)
LDFLAGS = -specs=$(TOPDIR)/linker.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS :=
@@ -159,6 +160,7 @@ clean:
@$(MAKE) -C $(AMS)/exosphere clean
@$(MAKE) -C $(AMS)/thermosphere clean
@$(MAKE) -C $(AMS)/stratosphere clean
@$(MAKE) -C $(AMS)/sept clean
@rm -fr $(BUILD) $(TARGET).bin $(TARGET).elf
#---------------------------------------------------------------------------------

View File

@@ -157,6 +157,9 @@ SECTIONS
CONSTRUCTORS
. = ALIGN(32);
} >main
__data_end__ = ABSOLUTE(.);
PROVIDE (__total_size__ = (__data_end__ - __start__));
.bss (NOLOAD) :
{
@@ -211,4 +214,36 @@ SECTIONS
.debug_str 0 : { *(.debug_str) }
.debug_loc 0 : { *(.debug_loc) }
.debug_macinfo 0 : { *(.debug_macinfo) }
/* =======================
==== Embedded Data ====
======================= */
PROVIDE(__ams_mitm_kip_start__ = ams_mitm_kip - __start__);
PROVIDE(__ams_mitm_kip_size__ = ams_mitm_kip_end - ams_mitm_kip);
PROVIDE(__boot_100_kip_start__ = boot_100_kip - __start__);
PROVIDE(__boot_100_kip_size__ = boot_100_kip_end - boot_100_kip);
PROVIDE(__boot_200_kip_start__ = boot_200_kip - __start__);
PROVIDE(__boot_200_kip_size__ = boot_200_kip_end - boot_200_kip);
PROVIDE(__exosphere_bin_start__ = exosphere_bin - __start__);
PROVIDE(__exosphere_bin_size__ = exosphere_bin_end - exosphere_bin);
PROVIDE(__fusee_primary_bin_start__ = fusee_primary_bin - __start__);
PROVIDE(__fusee_primary_bin_size__ = fusee_primary_bin_end - fusee_primary_bin);
PROVIDE(__loader_kip_start__ = loader_kip - __start__);
PROVIDE(__loader_kip_size__ = loader_kip_end - loader_kip);
PROVIDE(__lp0fw_bin_start__ = lp0fw_bin - __start__);
PROVIDE(__lp0fw_bin_size__ = lp0fw_bin_end - lp0fw_bin);
PROVIDE(__pm_kip_start__ = pm_kip - __start__);
PROVIDE(__pm_kip_size__ = pm_kip_end - pm_kip);
PROVIDE(__rebootstub_bin_start__ = rebootstub_bin - __start__);
PROVIDE(__rebootstub_bin_size__ = rebootstub_bin_end - rebootstub_bin);
PROVIDE(__sept_primary_bin_start__ = sept_primary_bin - __start__);
PROVIDE(__sept_primary_bin_size__ = sept_primary_bin_end - sept_primary_bin);
PROVIDE(__sept_secondary_enc_start__ = sept_secondary_enc - __start__);
PROVIDE(__sept_secondary_enc_size__ = sept_secondary_enc_end - sept_secondary_enc);
PROVIDE(__sm_kip_start__ = sm_kip - __start__);
PROVIDE(__sm_kip_size__ = sm_kip_end - sm_kip);
PROVIDE(__splash_screen_bmp_start__ = splash_screen_bmp - __start__);
PROVIDE(__splash_screen_bmp_size__ = splash_screen_bmp_end - splash_screen_bmp);
PROVIDE(__thermosphere_bin_start__ = thermosphere_bin - __start__);
PROVIDE(__thermosphere_bin_size__ = thermosphere_bin_end - thermosphere_bin);
}

View File

@@ -316,7 +316,7 @@ int nxfs_mount_all(void) {
model = g_mmc_devpart_template;
model.device_struct = &g_emmc_user_mmcpart;
model.start_sector = 0;
model.num_sectors = (32ull << 30) / model.sector_size;
model.num_sectors = (256ull << 30) / model.sector_size;
rc = rawdev_mount_device("rawnand", &model, false);

View File

@@ -13,6 +13,7 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <atmosphere/version.h>
.macro CLEAR_GPR_REG_ITER
mov r\@, #0
@@ -20,21 +21,27 @@
.section .text.start, "ax", %progbits
.arm
.align 5
.global _start
.type _start, %function
_start:
b _crt0
.word (_metadata - _start)
_crt0:
/* Switch to system mode, mask all interrupts, clear all flags */
msr cpsr_cxsf, #0xDF
/* Relocate ourselves if necessary */
ldr r2, =__start__
ldr r2, =_start
adr r3, _start
cmp r2, r3
bne _relocation_loop_end
beq _relocation_loop_end
ldr r4, =__bss_start__
sub r4, r4, r2 /* size >= 32, obviously, and we've declared 32-byte-alignment */
sub r4, r4, r2 /* size >= 32, obviously, and weve declared 32-byte-alignment */
_relocation_loop:
ldmia r3!, {r5-r12}
stmia r2!, {r5-r12}
@@ -60,6 +67,138 @@ _start:
ldr r0, [r0]
ldr r1, [r1]
b main
/* Fusee-secondary header. */
.align 5
_metadata:
.ascii "FSS0"
.word __total_size__
.word (_crt0 - _start)
.word (_content_headers - _start)
.word (_content_headers_end - _content_headers) / 0x20 /* Number of content headers */
.word ((ATMOSPHERE_SUPPORTED_HOS_VERSION_MAJOR << 24) | (ATMOSPHERE_SUPPORTED_HOS_VERSION_MINOR << 16) | (ATMOSPHERE_SUPPORTED_HOS_VERSION_MICRO << 8) | (0x0))
.word ((ATMOSPHERE_RELEASE_VERSION_MAJOR << 24) | (ATMOSPHERE_RELEASE_VERSION_MINOR << 16) | (ATMOSPHERE_RELEASE_VERSION_MICRO << 8) | (0x0))
#define TO_WORD(x) TO_WORD_(x)
#define TO_WORD_(x) 0x##x
#define AMS_GIT_REV_WORD TO_WORD(ATMOSPHERE_GIT_HASH)
.word AMS_GIT_REV_WORD
#undef TO_WORD_
#undef TO_WORD
#define CONTENT_TYPE_FSP 0
#define CONTENT_TYPE_EXO 1
#define CONTENT_TYPE_WBT 2
#define CONTENT_TYPE_RBT 3
#define CONTENT_TYPE_SP1 4
#define CONTENT_TYPE_SP2 5
#define CONTENT_TYPE_KIP 6
#define CONTENT_TYPE_BMP 7
_content_headers:
/* ams_mitm content header */
.word __ams_mitm_kip_start__
.word __ams_mitm_kip_size__
.word CONTENT_TYPE_KIP
.word 0xCCCCCCCC
.asciz "ams_mitm"
.align 5
/* boot_100 content header */
.word __boot_100_kip_start__
.word __boot_100_kip_size__
.word CONTENT_TYPE_KIP
.word 0xCCCCCCCC
.asciz "boot_100"
.align 5
/* boot_200 content header */
.word __boot_200_kip_start__
.word __boot_200_kip_size__
.word CONTENT_TYPE_KIP
.word 0xCCCCCCCC
.asciz "boot_200"
.align 5
/* exosphere content header */
.word __exosphere_bin_start__
.word __exosphere_bin_size__
.word CONTENT_TYPE_EXO
.word 0xCCCCCCCC
.asciz "exosphere"
.align 5
/* fusee_primary content header */
.word __fusee_primary_bin_start__
.word __fusee_primary_bin_size__
.word CONTENT_TYPE_FSP
.word 0xCCCCCCCC
.asciz "fusee_primary"
.align 5
/* loader content header */
.word __loader_kip_start__
.word __loader_kip_size__
.word CONTENT_TYPE_KIP
.word 0xCCCCCCCC
.asciz "loader"
.align 5
/* lp0fw content header */
.word __lp0fw_bin_start__
.word __lp0fw_bin_size__
.word CONTENT_TYPE_WBT
.word 0xCCCCCCCC
.asciz "lp0fw"
.align 5
/* pm content header */
.word __pm_kip_start__
.word __pm_kip_size__
.word CONTENT_TYPE_KIP
.word 0xCCCCCCCC
.asciz "pm"
.align 5
/* rebootstub content header */
.word __rebootstub_bin_start__
.word __rebootstub_bin_size__
.word CONTENT_TYPE_RBT
.word 0xCCCCCCCC
.asciz "rebootstub"
.align 5
/* sept_primary content header */
.word __sept_primary_bin_start__
.word __sept_primary_bin_size__
.word CONTENT_TYPE_SP1
.word 0xCCCCCCCC
.asciz "sept_primary"
.align 5
/* sept_secondary content header */
.word __sept_secondary_enc_start__
.word __sept_secondary_enc_size__
.word CONTENT_TYPE_SP2
.word 0xCCCCCCCC
.asciz "sept_secondary"
.align 5
/* sm content header */
.word __sm_kip_start__
.word __sm_kip_size__
.word CONTENT_TYPE_KIP
.word 0xCCCCCCCC
.asciz "sm"
.align 5
/* splash_screen content header */
.word __splash_screen_bmp_start__
.word __splash_screen_bmp_size__
.word CONTENT_TYPE_BMP
.word 0xCCCCCCCC
.asciz "splash_screen"
.align 5
_content_headers_end:
/* No need to include this in normal programs: */
.section .chainloader.text.start, "ax", %progbits

View File

@@ -120,14 +120,19 @@ check_rebootstub:
@$(MAKE) -C $(AMS)/exosphere/rebootstub all
$(BUILD):
ifeq ($(strip $(SEPT_ENC_PATH)),)
@[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
else
@touch $(TOPDIR)/$(TARGET).bin
@cp $(SEPT_ENC_PATH) $(TOPDIR)/$(TARGET).enc
endif
#---------------------------------------------------------------------------------
clean:
@echo clean ...
@$(MAKE) -C $(AMS)/exosphere/rebootstub clean
@rm -fr $(BUILD) $(TARGET).bin $(TARGET).elf
@rm -fr $(BUILD) $(TARGET).bin $(TARGET).enc $(TARGET).elf
#---------------------------------------------------------------------------------

View File

@@ -1,4 +1,4 @@
MODULES := loader pm sm boot ams_mitm eclct.stub creport fatal
MODULES := loader pm sm boot ams_mitm eclct.stub creport fatal dmnt
SUBFOLDERS := libstratosphere $(MODULES)

View File

@@ -35,10 +35,26 @@ static std::vector<u64> g_disable_mitm_flagged_tids;
static std::atomic_bool g_has_initialized = false;
static std::atomic_bool g_has_hid_session = false;
static u64 g_override_key_combination = KEY_R;
static u64 g_override_hbl_tid = 0x010000000000100DULL;
static bool g_override_any_app = false;
static bool g_override_by_default = true;
/* Content override support variables/types */
static OverrideKey g_default_override_key = {
.key_combination = KEY_R,
.override_by_default = true
};
struct HblOverrideConfig {
OverrideKey override_key;
u64 title_id;
bool override_any_app;
};
static HblOverrideConfig g_hbl_override_config = {
.override_key = {
.key_combination = KEY_L,
.override_by_default = true
},
.title_id = 0x010000000000100D,
.override_any_app = false
};
/* Static buffer for loader.ini contents at runtime. */
static char g_config_ini_data[0x800];
@@ -121,7 +137,7 @@ void Utils::InitializeThreadFunc(void *args) {
if (!has_auto_backup) {
fsFileSetSize(&g_cal0_file, ProdinfoSize);
fsFileWrite(&g_cal0_file, 0, g_cal0_backup, ProdinfoSize);
fsFileWrite(&g_cal0_file, 0, g_cal0_storage_backup, ProdinfoSize);
fsFileFlush(&g_cal0_file);
}
@@ -207,8 +223,6 @@ void Utils::InitializeThreadFunc(void *args) {
hidExit();
}
svcExitThread();
}
bool Utils::IsSdInitialized() {
@@ -368,7 +382,7 @@ Result Utils::SaveSdFileForAtmosphere(u64 title_id, const char *fn, void *data,
}
bool Utils::IsHblTid(u64 tid) {
return (g_override_any_app && IsApplicationTid(tid)) || (!g_override_any_app && tid == g_override_hbl_tid);
return (g_hbl_override_config.override_any_app && IsApplicationTid(tid)) || (!g_hbl_override_config.override_any_app && tid == g_hbl_override_config.title_id);
}
bool Utils::HasTitleFlag(u64 tid, const char *flag) {
@@ -446,6 +460,13 @@ Result Utils::GetKeysDown(u64 *keys) {
return 0x0;
}
static bool HasOverrideKey(OverrideKey *cfg) {
u64 kDown = 0;
bool keys_triggered = (R_SUCCEEDED(Utils::GetKeysDown(&kDown)) && ((kDown & cfg->key_combination) != 0));
return Utils::IsSdInitialized() && (cfg->override_by_default ^ keys_triggered);
}
bool Utils::HasOverrideButton(u64 tid) {
if ((!IsApplicationTid(tid)) || (!IsSdInitialized())) {
/* Disable button override disable for non-applications. */
@@ -455,71 +476,88 @@ bool Utils::HasOverrideButton(u64 tid) {
/* Unconditionally refresh loader.ini contents. */
RefreshConfiguration();
u64 kDown = 0;
bool keys_triggered = (R_SUCCEEDED(GetKeysDown(&kDown)) && ((kDown & g_override_key_combination) != 0));
return IsSdInitialized() && (g_override_by_default ^ keys_triggered);
if (IsHblTid(tid) && HasOverrideKey(&g_hbl_override_config.override_key)) {
return true;
}
OverrideKey title_cfg = GetTitleOverrideKey(tid);
return HasOverrideKey(&title_cfg);
}
static int FsMitMIniHandler(void *user, const char *section, const char *name, const char *value) {
static OverrideKey ParseOverrideKey(const char *value) {
OverrideKey cfg;
/* Parse on by default. */
if (value[0] == '!') {
cfg.override_by_default = true;
value++;
} else {
cfg.override_by_default = false;
}
/* Parse key combination. */
if (strcasecmp(value, "A") == 0) {
cfg.key_combination = KEY_A;
} else if (strcasecmp(value, "B") == 0) {
cfg.key_combination = KEY_B;
} else if (strcasecmp(value, "X") == 0) {
cfg.key_combination = KEY_X;
} else if (strcasecmp(value, "Y") == 0) {
cfg.key_combination = KEY_Y;
} else if (strcasecmp(value, "LS") == 0) {
cfg.key_combination = KEY_LSTICK;
} else if (strcasecmp(value, "RS") == 0) {
cfg.key_combination = KEY_RSTICK;
} else if (strcasecmp(value, "L") == 0) {
cfg.key_combination = KEY_L;
} else if (strcasecmp(value, "R") == 0) {
cfg.key_combination = KEY_R;
} else if (strcasecmp(value, "ZL") == 0) {
cfg.key_combination = KEY_ZL;
} else if (strcasecmp(value, "ZR") == 0) {
cfg.key_combination = KEY_ZR;
} else if (strcasecmp(value, "PLUS") == 0) {
cfg.key_combination = KEY_PLUS;
} else if (strcasecmp(value, "MINUS") == 0) {
cfg.key_combination = KEY_MINUS;
} else if (strcasecmp(value, "DLEFT") == 0) {
cfg.key_combination = KEY_DLEFT;
} else if (strcasecmp(value, "DUP") == 0) {
cfg.key_combination = KEY_DUP;
} else if (strcasecmp(value, "DRIGHT") == 0) {
cfg.key_combination = KEY_DRIGHT;
} else if (strcasecmp(value, "DDOWN") == 0) {
cfg.key_combination = KEY_DDOWN;
} else if (strcasecmp(value, "SL") == 0) {
cfg.key_combination = KEY_SL;
} else if (strcasecmp(value, "SR") == 0) {
cfg.key_combination = KEY_SR;
} else {
cfg.key_combination = 0;
}
return cfg;
}
static int FsMitmIniHandler(void *user, const char *section, const char *name, const char *value) {
/* Taken and modified, with love, from Rajkosto's implementation. */
if (strcasecmp(section, "config") == 0) {
if (strcasecmp(name, "hbl_tid") == 0) {
if (strcasecmp(section, "hbl_config") == 0) {
if (strcasecmp(name, "title_id") == 0) {
if (strcasecmp(value, "app") == 0) {
g_override_any_app = true;
g_hbl_override_config.override_any_app = true;
}
else {
u64 override_tid = strtoul(value, NULL, 16);
if (override_tid != 0) {
g_override_hbl_tid = override_tid;
g_hbl_override_config.title_id = override_tid;
}
}
} else if (strcasecmp(name, "override_key") == 0) {
if (value[0] == '!') {
g_override_by_default = true;
value++;
} else {
g_override_by_default = false;
}
if (strcasecmp(value, "A") == 0) {
g_override_key_combination = KEY_A;
} else if (strcasecmp(value, "B") == 0) {
g_override_key_combination = KEY_B;
} else if (strcasecmp(value, "X") == 0) {
g_override_key_combination = KEY_X;
} else if (strcasecmp(value, "Y") == 0) {
g_override_key_combination = KEY_Y;
} else if (strcasecmp(value, "LS") == 0) {
g_override_key_combination = KEY_LSTICK;
} else if (strcasecmp(value, "RS") == 0) {
g_override_key_combination = KEY_RSTICK;
} else if (strcasecmp(value, "L") == 0) {
g_override_key_combination = KEY_L;
} else if (strcasecmp(value, "R") == 0) {
g_override_key_combination = KEY_R;
} else if (strcasecmp(value, "ZL") == 0) {
g_override_key_combination = KEY_ZL;
} else if (strcasecmp(value, "ZR") == 0) {
g_override_key_combination = KEY_ZR;
} else if (strcasecmp(value, "PLUS") == 0) {
g_override_key_combination = KEY_PLUS;
} else if (strcasecmp(value, "MINUS") == 0) {
g_override_key_combination = KEY_MINUS;
} else if (strcasecmp(value, "DLEFT") == 0) {
g_override_key_combination = KEY_DLEFT;
} else if (strcasecmp(value, "DUP") == 0) {
g_override_key_combination = KEY_DUP;
} else if (strcasecmp(value, "DRIGHT") == 0) {
g_override_key_combination = KEY_DRIGHT;
} else if (strcasecmp(value, "DDOWN") == 0) {
g_override_key_combination = KEY_DDOWN;
} else if (strcasecmp(value, "SL") == 0) {
g_override_key_combination = KEY_SL;
} else if (strcasecmp(value, "SR") == 0) {
g_override_key_combination = KEY_SR;
} else {
g_override_key_combination = 0;
}
g_hbl_override_config.override_key = ParseOverrideKey(value);
}
} else if (strcasecmp(section, "default_config") == 0) {
if (strcasecmp(name, "override_key") == 0) {
g_default_override_key = ParseOverrideKey(value);
}
} else {
return 0;
@@ -527,6 +565,46 @@ static int FsMitMIniHandler(void *user, const char *section, const char *name, c
return 1;
}
static int FsMitmTitleSpecificIniHandler(void *user, const char *section, const char *name, const char *value) {
/* We'll output an override key when relevant. */
OverrideKey *user_cfg = reinterpret_cast<OverrideKey *>(user);
if (strcasecmp(section, "override_config") == 0) {
if (strcasecmp(name, "override_key") == 0) {
*user_cfg = ParseOverrideKey(value);
}
} else {
return 0;
}
return 1;
}
OverrideKey Utils::GetTitleOverrideKey(u64 tid) {
OverrideKey cfg = g_default_override_key;
char path[FS_MAX_PATH+1] = {0};
snprintf(path, FS_MAX_PATH, "/atmosphere/titles/%016lx/config.ini", tid);
FsFile cfg_file;
if (R_SUCCEEDED(fsFsOpenFile(&g_sd_filesystem, path, FS_OPEN_READ, &cfg_file))) {
ON_SCOPE_EXIT { fsFileClose(&cfg_file); };
size_t config_file_size = 0x20000;
fsFileGetSize(&cfg_file, &config_file_size);
char *config_buf = reinterpret_cast<char *>(calloc(1, config_file_size + 1));
if (config_buf != NULL) {
ON_SCOPE_EXIT { free(config_buf); };
/* Read title ini contents. */
fsFileRead(&cfg_file, 0, config_buf, config_file_size, &config_file_size);
/* Parse title ini. */
ini_parse_string(config_buf, FsMitmTitleSpecificIniHandler, &cfg);
}
}
return cfg;
}
void Utils::RefreshConfiguration() {
FsFile config_file;
@@ -547,7 +625,7 @@ void Utils::RefreshConfiguration() {
fsFileRead(&config_file, 0, g_config_ini_data, size, &r_s);
fsFileClose(&config_file);
ini_parse_string(g_config_ini_data, FsMitMIniHandler, NULL);
ini_parse_string(g_config_ini_data, FsMitmIniHandler, NULL);
}
Result Utils::GetSettingsItemValueSize(const char *name, const char *key, u64 *out_size) {

View File

@@ -37,6 +37,11 @@ enum BisStorageId : u32 {
BisStorageId_SystemProperPartition = 33,
};
struct OverrideKey {
u64 key_combination;
bool override_by_default;
};
class Utils {
public:
static bool IsSdInitialized();
@@ -72,6 +77,8 @@ class Utils {
static bool IsHidAvailable();
static Result GetKeysDown(u64 *keys);
static OverrideKey GetTitleOverrideKey(u64 tid);
static bool HasOverrideButton(u64 tid);
/* Settings! */

166
stratosphere/dmnt/Makefile Normal file
View File

@@ -0,0 +1,166 @@
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>/devkitpro")
endif
TOPDIR ?= $(CURDIR)
include $(DEVKITPRO)/libnx/switch_rules
AMSBRANCH := $(shell git symbolic-ref --short HEAD)
AMSREV := $(AMSBRANCH)-$(shell git rev-parse --short HEAD)
ifneq (, $(strip $(shell git status --porcelain 2>/dev/null)))
AMSREV := $(AMSREV)-dirty
endif
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
# EXEFS_SRC is the optional input directory containing data copied into exefs, if anything this normally should only contain "main.npdm".
#---------------------------------------------------------------------------------
TARGET := $(notdir $(CURDIR))
BUILD := build
SOURCES := source
DATA := data
INCLUDES := include ../../common/include
EXEFS_SRC := exefs_src
DEFINES := -DDISABLE_IPC -DATMOSPHERE_GIT_BRANCH=\"$(AMSBRANCH)\" -DATMOSPHERE_GIT_REV=\"$(AMSREV)\"
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH := -march=armv8-a -mtune=cortex-a57 -mtp=soft -fPIE
CFLAGS := -g -Wall -O2 -ffunction-sections \
$(ARCH) $(DEFINES)
CFLAGS += $(INCLUDE) -D__SWITCH__
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions -std=gnu++17
ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS := -lstratosphere -lnx
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(PORTLIBS) $(LIBNX) $(CURDIR)/../libstratosphere
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export OUTPUT := $(CURDIR)/$(TARGET)
export TOPDIR := $(CURDIR)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
export OFILES := $(addsuffix .o,$(BINFILES)) \
$(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
export BUILD_EXEFS_SRC := $(TOPDIR)/$(EXEFS_SRC)
ifeq ($(strip $(CONFIG_JSON)),)
jsons := $(wildcard *.json)
ifneq (,$(findstring $(TARGET).json,$(jsons)))
export APP_JSON := $(TOPDIR)/$(TARGET).json
else
ifneq (,$(findstring config.json,$(jsons)))
export APP_JSON := $(TOPDIR)/config.json
endif
endif
else
export APP_JSON := $(TOPDIR)/$(CONFIG_JSON)
endif
.PHONY: $(BUILD) clean all
#---------------------------------------------------------------------------------
all: $(BUILD)
$(BUILD):
@[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@echo clean ...
@rm -fr $(BUILD) $(TARGET).nsp $(TARGET).npdm $(TARGET).nso $(TARGET).elf
#---------------------------------------------------------------------------------
else
.PHONY: all
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
all : $(OUTPUT).nsp
ifeq ($(strip $(APP_JSON)),)
$(OUTPUT).nsp : $(OUTPUT).nso
else
$(OUTPUT).nsp : $(OUTPUT).nso $(OUTPUT).npdm
endif
$(OUTPUT).nso : $(OUTPUT).elf
$(OUTPUT).elf : $(OFILES)
#---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#---------------------------------------------------------------------------------
%.bin.o : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------

121
stratosphere/dmnt/dmnt.json Normal file
View File

@@ -0,0 +1,121 @@
{
"name": "dmnt",
"title_id": "0x010000000000000d",
"title_id_range_min": "0x010000000000000d",
"title_id_range_max": "0x010000000000000d",
"main_thread_stack_size": "0x00004000",
"main_thread_priority": 39,
"default_cpu_id": 3,
"process_category": 0,
"is_retail": true,
"pool_partition": 2,
"is_64_bit": true,
"address_space_type": 1,
"filesystem_access": {
"permissions": "0xFFFFFFFFFFFFFFFF"
},
"service_access": [
"pm:dmnt",
"ldr:dmnt",
"ro:dmnt",
"ns:dev",
"spl:",
"lr",
"htc",
"bsd:s",
"sfdnsres",
"bsdcfg",
"set",
"set:sys",
"fsp-srv",
"fatal:u",
"hid"
],
"service_host": [
"dmnt:-",
"dmnt:cht"
],
"kernel_capabilities": [{
"type": "kernel_flags",
"value": {
"highest_thread_priority": 63,
"lowest_thread_priority": 24,
"lowest_cpu_id": 0,
"highest_cpu_id": 3
}
}, {
"type": "syscalls",
"value": {
"svcSetHeapSize": "0x01",
"svcSetMemoryPermission": "0x02",
"svcSetMemoryAttribute": "0x03",
"svcMapMemory": "0x04",
"svcUnmapMemory": "0x05",
"svcQueryMemory": "0x06",
"svcExitProcess": "0x07",
"svcCreateThread": "0x08",
"svcStartThread": "0x09",
"svcExitThread": "0x0a",
"svcSleepThread": "0x0b",
"svcGetThreadPriority": "0x0c",
"svcSetThreadPriority": "0x0d",
"svcGetThreadCoreMask": "0x0e",
"svcSetThreadCoreMask": "0x0f",
"svcGetCurrentProcessorNumber": "0x10",
"svcSignalEvent": "0x11",
"svcClearEvent": "0x12",
"svcMapSharedMemory": "0x13",
"svcUnmapSharedMemory": "0x14",
"svcCreateTransferMemory": "0x15",
"svcCloseHandle": "0x16",
"svcResetSignal": "0x17",
"svcWaitSynchronization": "0x18",
"svcCancelSynchronization": "0x19",
"svcArbitrateLock": "0x1a",
"svcArbitrateUnlock": "0x1b",
"svcWaitProcessWideKeyAtomic": "0x1c",
"svcSignalProcessWideKey": "0x1d",
"svcGetSystemTick": "0x1e",
"svcConnectToNamedPort": "0x1f",
"svcSendSyncRequestLight": "0x20",
"svcSendSyncRequest": "0x21",
"svcSendSyncRequestWithUserBuffer": "0x22",
"svcSendAsyncRequestWithUserBuffer": "0x23",
"svcGetProcessId": "0x24",
"svcGetThreadId": "0x25",
"svcBreak": "0x26",
"svcOutputDebugString": "0x27",
"svcReturnFromException": "0x28",
"svcGetInfo": "0x29",
"svcWaitForAddress": "0x34",
"svcSignalToAddress": "0x35",
"svcCreateSession": "0x40",
"svcAcceptSession": "0x41",
"svcReplyAndReceiveLight": "0x42",
"svcReplyAndReceive": "0x43",
"svcReplyAndReceiveWithUserBuffer": "0x44",
"svcCreateEvent": "0x45",
"svcDebugActiveProcess": "0x60",
"svcBreakDebugProcess": "0x61",
"svcTerminateDebugProcess": "0x62",
"svcGetDebugEvent": "0x63",
"svcContinueDebugEvent": "0x64",
"svcGetProcessList": "0x65",
"svcGetThreadList": "0x66",
"svcGetDebugThreadContext": "0x67",
"svcSetDebugThreadContext": "0x68",
"svcQueryDebugProcessMemory": "0x69",
"svcReadDebugProcessMemory": "0x6a",
"svcWriteDebugProcessMemory": "0x6b",
"svcSetHardwareBreakPoint": "0x6c",
"svcGetDebugThreadParam": "0x6d",
"svcCallSecureMonitor": "0x7f"
}
}, {
"type": "min_kernel_version",
"value": "0x0030"
}, {
"type": "handle_table_size",
"value": 0
}]
}

View File

@@ -0,0 +1,971 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <map>
#include <switch.h>
#include "dmnt_cheat_manager.hpp"
#include "dmnt_cheat_vm.hpp"
#include "dmnt_config.hpp"
#include "pm_shim.h"
static HosMutex g_cheat_lock;
static HosThread g_detect_thread, g_vm_thread, g_debug_events_thread;
static IEvent *g_cheat_process_event;
static DmntCheatVm *g_cheat_vm;
static CheatProcessMetadata g_cheat_process_metadata = {0};
static Handle g_cheat_process_debug_hnd = 0;
/* Should we enable cheats by default? */
static bool g_enable_cheats_by_default = true;
/* For debug event thread management. */
static HosMutex g_debug_event_thread_lock;
static bool g_has_debug_events_thread = false;
/* To save some copying. */
static bool g_needs_reload_vm_program = false;
/* Global cheat entry storage. */
static CheatEntry g_cheat_entries[DmntCheatManager::MaxCheatCount];
/* Global frozen address storage. */
static std::map<u64, FrozenAddressValue> g_frozen_addresses_map;
void DmntCheatManager::StartDebugEventsThread() {
std::scoped_lock<HosMutex> lk(g_debug_event_thread_lock);
/* Spawn the debug events thread. */
if (!g_has_debug_events_thread) {
Result rc;
if (R_FAILED((rc = g_debug_events_thread.Initialize(&DmntCheatManager::DebugEventsThread, nullptr, 0x4000, 48)))) {
return fatalSimple(rc);
}
if (R_FAILED((rc = g_debug_events_thread.Start()))) {
return fatalSimple(rc);
}
g_has_debug_events_thread = true;
}
}
void DmntCheatManager::WaitDebugEventsThread() {
std::scoped_lock<HosMutex> lk(g_debug_event_thread_lock);
/* Wait for the thread to exit. */
if (g_has_debug_events_thread) {
g_debug_events_thread.CancelSynchronization();
g_debug_events_thread.Join();
g_has_debug_events_thread = false;
}
}
void DmntCheatManager::CloseActiveCheatProcess() {
if (g_cheat_process_debug_hnd != 0) {
/* Close process resources. */
svcCloseHandle(g_cheat_process_debug_hnd);
g_cheat_process_debug_hnd = 0;
g_cheat_process_metadata = (CheatProcessMetadata){0};
/* Clear cheat list. */
ResetAllCheatEntries();
/* Clear frozen addresses. */
ResetFrozenAddresses();
/* Signal to our fans. */
g_cheat_process_event->Signal();
}
}
bool DmntCheatManager::HasActiveCheatProcess() {
u64 tmp;
bool has_cheat_process = g_cheat_process_debug_hnd != 0;
if (has_cheat_process) {
has_cheat_process &= R_SUCCEEDED(svcGetProcessId(&tmp, g_cheat_process_debug_hnd));
}
if (has_cheat_process) {
has_cheat_process &= R_SUCCEEDED(pmdmntGetApplicationPid(&tmp));
}
if (has_cheat_process) {
has_cheat_process &= tmp == g_cheat_process_metadata.process_id;
}
if (!has_cheat_process) {
CloseActiveCheatProcess();
}
return has_cheat_process;
}
void DmntCheatManager::ContinueCheatProcess() {
if (HasActiveCheatProcess()) {
/* Loop getting debug events. */
u64 debug_event_buf[0x50];
while (R_SUCCEEDED(svcGetDebugEvent((u8 *)debug_event_buf, g_cheat_process_debug_hnd))) {
/* ... */
}
/* Continue the process. */
if (kernelAbove300()) {
svcContinueDebugEvent(g_cheat_process_debug_hnd, 5, nullptr, 0);
} else {
svcLegacyContinueDebugEvent(g_cheat_process_debug_hnd, 5, 0);
}
}
}
Result DmntCheatManager::ReadCheatProcessMemoryForVm(u64 proc_addr, void *out_data, size_t size) {
if (HasActiveCheatProcess()) {
return svcReadDebugProcessMemory(out_data, g_cheat_process_debug_hnd, proc_addr, size);
}
return ResultDmntCheatNotAttached;
}
Result DmntCheatManager::WriteCheatProcessMemoryForVm(u64 proc_addr, const void *data, size_t size) {
if (HasActiveCheatProcess()) {
Result rc = svcWriteDebugProcessMemory(g_cheat_process_debug_hnd, data, proc_addr, size);
/* We might have a frozen address. Update it if we do! */
if (R_SUCCEEDED(rc)) {
for (auto & [address, value] : g_frozen_addresses_map) {
/* Map is in order, so break here. */
if (address >= proc_addr + size) {
break;
}
/* Check if we need to write. */
if (proc_addr <= address) {
const size_t offset = (address - proc_addr);
const size_t size_to_copy = size - offset;
memcpy(&value.value, (void *)((uintptr_t)data + offset), size_to_copy < sizeof(value.value) ? size_to_copy : sizeof(value.value));
}
}
}
return rc;
}
return ResultDmntCheatNotAttached;
}
Result DmntCheatManager::GetCheatProcessMappingCount(u64 *out_count) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (!HasActiveCheatProcess()) {
return ResultDmntCheatNotAttached;
}
MemoryInfo mem_info;
u64 address = 0;
*out_count = 0;
do {
mem_info.perm = 0;
u32 tmp;
if (R_FAILED(svcQueryDebugProcessMemory(&mem_info, &tmp, g_cheat_process_debug_hnd, address))) {
break;
}
if (mem_info.perm != 0) {
*out_count += 1;
}
address = mem_info.addr + mem_info.size;
} while (address != 0);
return 0;
}
Result DmntCheatManager::GetCheatProcessMappings(MemoryInfo *mappings, size_t max_count, u64 *out_count, u64 offset) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (!HasActiveCheatProcess()) {
return ResultDmntCheatNotAttached;
}
MemoryInfo mem_info;
u64 address = 0;
u64 count = 0;
*out_count = 0;
do {
mem_info.perm = 0;
u32 tmp;
if (R_FAILED(svcQueryDebugProcessMemory(&mem_info, &tmp, g_cheat_process_debug_hnd, address))) {
break;
}
if (mem_info.perm != 0) {
count++;
if (count > offset) {
mappings[(*out_count)++] = mem_info;
}
}
address = mem_info.addr + mem_info.size;
} while (address != 0 && *out_count < max_count);
return 0;
}
Result DmntCheatManager::ReadCheatProcessMemory(u64 proc_addr, void *out_data, size_t size) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
return ReadCheatProcessMemoryForVm(proc_addr, out_data, size);
}
Result DmntCheatManager::WriteCheatProcessMemory(u64 proc_addr, const void *data, size_t size) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
return WriteCheatProcessMemoryForVm(proc_addr, data, size);
}
Result DmntCheatManager::QueryCheatProcessMemory(MemoryInfo *mapping, u64 address) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (HasActiveCheatProcess()) {
u32 tmp;
return svcQueryDebugProcessMemory(mapping, &tmp, g_cheat_process_debug_hnd, address);
}
return ResultDmntCheatNotAttached;
}
void DmntCheatManager::ResetFrozenAddresses() {
/* Just clear the map. */
g_frozen_addresses_map.clear();
}
void DmntCheatManager::ResetCheatEntry(size_t i) {
if (i < DmntCheatManager::MaxCheatCount) {
g_cheat_entries[i].enabled = false;
g_cheat_entries[i].cheat_id = i;
g_cheat_entries[i].definition = {0};
/* Trigger a VM reload. */
g_needs_reload_vm_program = true;
}
}
void DmntCheatManager::ResetAllCheatEntries() {
for (size_t i = 0; i < DmntCheatManager::MaxCheatCount; i++) {
ResetCheatEntry(i);
}
}
CheatEntry *DmntCheatManager::GetFreeCheatEntry() {
/* Check all non-master cheats for availability. */
for (size_t i = 1; i < DmntCheatManager::MaxCheatCount; i++) {
if (g_cheat_entries[i].definition.num_opcodes == 0) {
return &g_cheat_entries[i];
}
}
return nullptr;
}
CheatEntry *DmntCheatManager::GetCheatEntryById(size_t i) {
if (i < DmntCheatManager::MaxCheatCount) {
return &g_cheat_entries[i];
}
return nullptr;
}
bool DmntCheatManager::ParseCheats(const char *s, size_t len) {
size_t i = 0;
CheatEntry *cur_entry = NULL;
/* Trigger a VM reload. */
g_needs_reload_vm_program = true;
while (i < len) {
if (isspace(s[i])) {
/* Just ignore space. */
i++;
} else if (s[i] == '[') {
/* Parse a readable cheat name. */
cur_entry = GetFreeCheatEntry();
if (cur_entry == NULL) {
return false;
}
/* Extract name bounds. */
size_t j = i + 1;
while (s[j] != ']') {
j++;
if (j >= len || (j - i - 1) >= sizeof(cur_entry->definition.readable_name)) {
return false;
}
}
/* s[i+1:j] is cheat name. */
const size_t cheat_name_len = (j - i - 1);
memcpy(cur_entry->definition.readable_name, &s[i+1], cheat_name_len);
cur_entry->definition.readable_name[cheat_name_len] = 0;
/* Skip onwards. */
i = j + 1;
} else if (s[i] == '{') {
/* We're parsing a master cheat. */
cur_entry = &g_cheat_entries[0];
/* There can only be one master cheat. */
if (cur_entry->definition.num_opcodes > 0) {
return false;
}
/* Extract name bounds */
size_t j = i + 1;
while (s[j] != '}') {
j++;
if (j >= len || (j - i - 1) >= sizeof(cur_entry->definition.readable_name)) {
return false;
}
}
/* s[i+1:j] is cheat name. */
const size_t cheat_name_len = (j - i - 1);
memcpy(cur_entry->definition.readable_name, &s[i+1], cheat_name_len);
cur_entry->definition.readable_name[cheat_name_len] = 0;
/* Skip onwards. */
i = j + 1;
} else if (isxdigit(s[i])) {
/* Make sure that we have a cheat open. */
if (cur_entry == NULL) {
return false;
}
/* Bounds check the opcode count. */
if (cur_entry->definition.num_opcodes >= sizeof(cur_entry->definition.opcodes)/sizeof(cur_entry->definition.opcodes[0])) {
return false;
}
/* We're parsing an instruction, so validate it's 8 hex digits. */
for (size_t j = 1; j < 8; j++) {
/* Validate 8 hex chars. */
if (i + j >= len || !isxdigit(s[i+j])) {
return false;
}
}
/* Parse the new opcode. */
char hex_str[9] = {0};
memcpy(hex_str, &s[i], 8);
cur_entry->definition.opcodes[cur_entry->definition.num_opcodes++] = strtoul(hex_str, NULL, 16);
/* Skip onwards. */
i += 8;
} else {
/* Unexpected character encountered. */
return false;
}
}
/* Master cheat can't be disabled. */
if (g_cheat_entries[0].definition.num_opcodes > 0) {
g_cheat_entries[0].enabled = true;
}
/* Enable all entries we parsed. */
for (size_t i = 1; i < DmntCheatManager::MaxCheatCount; i++) {
if (g_cheat_entries[i].definition.num_opcodes > 0) {
g_cheat_entries[i].enabled = g_enable_cheats_by_default;
}
}
return true;
}
bool DmntCheatManager::LoadCheats(u64 title_id, const u8 *build_id) {
/* Reset existing entries. */
ResetAllCheatEntries();
FILE *f_cht = NULL;
/* Open the file for title/build_id. */
{
char path[FS_MAX_PATH+1] = {0};
snprintf(path, FS_MAX_PATH, "sdmc:/atmosphere/titles/%016lx/cheats/%02x%02x%02x%02x%02x%02x%02x%02x.txt", title_id,
build_id[0], build_id[1], build_id[2], build_id[3], build_id[4], build_id[5], build_id[6], build_id[7]);
f_cht = fopen(path, "rb");
}
/* Check for NULL */
if (f_cht == NULL) {
return false;
}
ON_SCOPE_EXIT { fclose(f_cht); };
/* Get file size. */
fseek(f_cht, 0L, SEEK_END);
const size_t cht_sz = ftell(f_cht);
fseek(f_cht, 0L, SEEK_SET);
/* Allocate cheat txt buffer. */
char *cht_txt = (char *)malloc(cht_sz + 1);
if (cht_txt == NULL) {
return false;
}
ON_SCOPE_EXIT { free(cht_txt); };
/* Read cheats into buffer. */
if (fread(cht_txt, 1, cht_sz, f_cht) != cht_sz) {
return false;
}
cht_txt[cht_sz] = 0;
/* Parse cheat buffer. */
return ParseCheats(cht_txt, strlen(cht_txt));
}
Result DmntCheatManager::GetCheatCount(u64 *out_count) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (!HasActiveCheatProcess()) {
return ResultDmntCheatNotAttached;
}
*out_count = 0;
for (size_t i = 0; i < DmntCheatManager::MaxCheatCount; i++) {
if (g_cheat_entries[i].definition.num_opcodes > 0) {
*out_count += 1;
}
}
return 0;
}
Result DmntCheatManager::GetCheats(CheatEntry *cheats, size_t max_count, u64 *out_count, u64 offset) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (!HasActiveCheatProcess()) {
return ResultDmntCheatNotAttached;
}
u64 count = 0;
*out_count = 0;
for (size_t i = 0; i < DmntCheatManager::MaxCheatCount && (*out_count) < max_count; i++) {
if (g_cheat_entries[i].definition.num_opcodes > 0) {
count++;
if (count > offset) {
cheats[(*out_count)++] = g_cheat_entries[i];
}
}
}
return 0;
}
Result DmntCheatManager::GetCheatById(CheatEntry *out_cheat, u32 cheat_id) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (!HasActiveCheatProcess()) {
return ResultDmntCheatNotAttached;
}
const CheatEntry *entry = GetCheatEntryById(cheat_id);
if (entry == nullptr || entry->definition.num_opcodes == 0) {
return ResultDmntCheatUnknownChtId;
}
*out_cheat = *entry;
return 0;
}
Result DmntCheatManager::ToggleCheat(u32 cheat_id) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (!HasActiveCheatProcess()) {
return ResultDmntCheatNotAttached;
}
CheatEntry *entry = GetCheatEntryById(cheat_id);
if (entry == nullptr || entry->definition.num_opcodes == 0) {
return ResultDmntCheatUnknownChtId;
}
if (cheat_id == 0) {
return ResultDmntCheatCannotDisableMasterCheat;
}
entry->enabled = !entry->enabled;
/* Trigger a VM reload. */
g_needs_reload_vm_program = true;
return 0;
}
Result DmntCheatManager::AddCheat(u32 *out_id, CheatDefinition *def, bool enabled) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (!HasActiveCheatProcess()) {
return ResultDmntCheatNotAttached;
}
if (def->num_opcodes == 0 || def->num_opcodes > sizeof(def->opcodes)/sizeof(def->opcodes[0])) {
return ResultDmntCheatInvalidCheat;
}
CheatEntry *new_entry = GetFreeCheatEntry();
if (new_entry == nullptr) {
return ResultDmntCheatOutOfCheats;
}
new_entry->enabled = enabled;
new_entry->definition = *def;
/* Trigger a VM reload. */
g_needs_reload_vm_program = true;
return 0;
}
Result DmntCheatManager::RemoveCheat(u32 cheat_id) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (!HasActiveCheatProcess()) {
return ResultDmntCheatNotAttached;
}
if (cheat_id >= DmntCheatManager::MaxCheatCount) {
return ResultDmntCheatUnknownChtId;
}
ResetCheatEntry(cheat_id);
/* Trigger a VM reload. */
g_needs_reload_vm_program = true;
return 0;
}
Result DmntCheatManager::GetFrozenAddressCount(u64 *out_count) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (!HasActiveCheatProcess()) {
return ResultDmntCheatNotAttached;
}
*out_count = g_frozen_addresses_map.size();
return 0;
}
Result DmntCheatManager::GetFrozenAddresses(FrozenAddressEntry *frz_addrs, size_t max_count, u64 *out_count, u64 offset) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (!HasActiveCheatProcess()) {
return ResultDmntCheatNotAttached;
}
u64 count = 0;
*out_count = 0;
for (auto const& [address, value] : g_frozen_addresses_map) {
if ((*out_count) >= max_count) {
break;
}
count++;
if (count > offset) {
const u64 cur_ind = (*out_count)++;
frz_addrs[cur_ind].address = address;
frz_addrs[cur_ind].value = value;
}
}
return 0;
}
Result DmntCheatManager::GetFrozenAddress(FrozenAddressEntry *frz_addr, u64 address) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (!HasActiveCheatProcess()) {
return ResultDmntCheatNotAttached;
}
const auto it = g_frozen_addresses_map.find(address);
if (it == g_frozen_addresses_map.end()) {
return ResultDmntCheatAddressNotFrozen;
}
frz_addr->address = it->first;
frz_addr->value = it->second;
return 0;
}
Result DmntCheatManager::EnableFrozenAddress(u64 *out_value, u64 address, u64 width) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (!HasActiveCheatProcess()) {
return ResultDmntCheatNotAttached;
}
if (g_frozen_addresses_map.size() >= DmntCheatManager::MaxFrozenAddressCount) {
return ResultDmntCheatTooManyFrozenAddresses;
}
const auto it = g_frozen_addresses_map.find(address);
if (it != g_frozen_addresses_map.end()) {
return ResultDmntCheatAddressAlreadyFrozen;
}
Result rc;
FrozenAddressValue value = {0};
value.width = width;
if (R_FAILED((rc = ReadCheatProcessMemoryForVm(address, &value.value, width)))) {
return rc;
}
g_frozen_addresses_map[address] = value;
*out_value = value.value;
return 0;
}
Result DmntCheatManager::DisableFrozenAddress(u64 address) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (!HasActiveCheatProcess()) {
return ResultDmntCheatNotAttached;
}
const auto it = g_frozen_addresses_map.find(address);
if (it == g_frozen_addresses_map.end()) {
return ResultDmntCheatAddressNotFrozen;
}
g_frozen_addresses_map.erase(address);
return 0;
}
Handle DmntCheatManager::PrepareDebugNextApplication() {
Result rc;
Handle event_h;
if (R_FAILED((rc = pmdmntEnableDebugForApplication(&event_h)))) {
fatalSimple(rc);
}
return event_h;
}
static void PopulateMemoryExtents(MemoryRegionExtents *extents, Handle p_h, u64 id_base, u64 id_size) {
Result rc;
/* Get base extent. */
if (R_FAILED((rc = svcGetInfo(&extents->base, id_base, p_h, 0)))) {
fatalSimple(rc);
}
/* Get size extent. */
if (R_FAILED((rc = svcGetInfo(&extents->size, id_size, p_h, 0)))) {
fatalSimple(rc);
}
}
static void StartDebugProcess(u64 pid) {
Result rc = pmdmntStartProcess(pid);
if (R_FAILED(rc)) {
fatalSimple(rc);
}
}
Result DmntCheatManager::ForceOpenCheatProcess() {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
Result rc;
if (HasActiveCheatProcess()) {
return 0;
}
/* Close the current application, if it's open. */
CloseActiveCheatProcess();
/* Wait to not have debug events thread. */
WaitDebugEventsThread();
/* Get the current application process ID. */
if (R_FAILED((rc = pmdmntGetApplicationPid(&g_cheat_process_metadata.process_id)))) {
return rc;
}
ON_SCOPE_EXIT { if (R_FAILED(rc)) { g_cheat_process_metadata.process_id = 0; } };
/* Get process handle, use it to learn memory extents. */
{
Handle proc_h = 0;
ON_SCOPE_EXIT { if (proc_h != 0) { svcCloseHandle(proc_h); } };
if (R_FAILED((rc = pmdmntAtmosphereGetProcessInfo(&proc_h, &g_cheat_process_metadata.title_id, nullptr, g_cheat_process_metadata.process_id)))) {
return rc;
}
/* Get memory extents. */
PopulateMemoryExtents(&g_cheat_process_metadata.heap_extents, proc_h, 4, 5);
PopulateMemoryExtents(&g_cheat_process_metadata.alias_extents, proc_h, 2, 3);
if (kernelAbove200()) {
PopulateMemoryExtents(&g_cheat_process_metadata.address_space_extents, proc_h, 12, 13);
} else {
g_cheat_process_metadata.address_space_extents.base = 0x08000000UL;
g_cheat_process_metadata.address_space_extents.size = 0x78000000UL;
}
}
/* Get module information from Loader. */
{
LoaderModuleInfo proc_modules[2];
u32 num_modules;
if (R_FAILED((rc = ldrDmntGetModuleInfos(g_cheat_process_metadata.process_id, proc_modules, sizeof(proc_modules), &num_modules)))) {
return rc;
}
/* All applications must have two modules. */
/* However, this is a force-open, so we will accept one module. */
/* Poor HBL, I guess... */
LoaderModuleInfo *proc_module;
if (num_modules == 2) {
proc_module = &proc_modules[1];
} else if (num_modules == 1) {
proc_module = &proc_modules[0];
} else {
rc = ResultDmntCheatNotAttached;
return rc;
}
g_cheat_process_metadata.main_nso_extents.base = proc_module->base_address;
g_cheat_process_metadata.main_nso_extents.size = proc_module->size;
memcpy(g_cheat_process_metadata.main_nso_build_id, proc_module->build_id, sizeof(g_cheat_process_metadata.main_nso_build_id));
}
/* Read cheats off the SD. */
/* This is allowed to fail. We may not have any cheats. */
LoadCheats(g_cheat_process_metadata.title_id, g_cheat_process_metadata.main_nso_build_id);
/* Open a debug handle. */
if (R_FAILED((rc = svcDebugActiveProcess(&g_cheat_process_debug_hnd, g_cheat_process_metadata.process_id)))) {
return rc;
}
/* Start debug events thread. */
StartDebugEventsThread();
/* Signal to our fans. */
g_cheat_process_event->Signal();
return rc;
}
void DmntCheatManager::OnNewApplicationLaunch() {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
Result rc;
/* Close the current application, if it's open. */
CloseActiveCheatProcess();
/* Wait to not have debug events thread. */
WaitDebugEventsThread();
/* Get the new application's process ID. */
if (R_FAILED((rc = pmdmntGetApplicationPid(&g_cheat_process_metadata.process_id)))) {
fatalSimple(rc);
}
/* Get process handle, use it to learn memory extents. */
{
Handle proc_h = 0;
ON_SCOPE_EXIT { if (proc_h != 0) { svcCloseHandle(proc_h); } };
if (R_FAILED((rc = pmdmntAtmosphereGetProcessInfo(&proc_h, &g_cheat_process_metadata.title_id, nullptr, g_cheat_process_metadata.process_id)))) {
fatalSimple(rc);
}
/* Get memory extents. */
PopulateMemoryExtents(&g_cheat_process_metadata.heap_extents, proc_h, 4, 5);
PopulateMemoryExtents(&g_cheat_process_metadata.alias_extents, proc_h, 2, 3);
if (kernelAbove200()) {
PopulateMemoryExtents(&g_cheat_process_metadata.address_space_extents, proc_h, 12, 13);
} else {
g_cheat_process_metadata.address_space_extents.base = 0x08000000UL;
g_cheat_process_metadata.address_space_extents.size = 0x78000000UL;
}
}
/* Check if we should skip based on keys down. */
if (!DmntConfigManager::HasCheatEnableButton(g_cheat_process_metadata.title_id)) {
StartDebugProcess(g_cheat_process_metadata.process_id);
g_cheat_process_metadata.process_id = 0;
return;
}
/* Get module information from Loader. */
{
LoaderModuleInfo proc_modules[2];
u32 num_modules;
if (R_FAILED((rc = ldrDmntGetModuleInfos(g_cheat_process_metadata.process_id, proc_modules, sizeof(proc_modules), &num_modules)))) {
fatalSimple(rc);
}
/* All applications must have two modules. */
/* If we only have one, we must be e.g. mitming HBL. */
/* We don't want to fuck with HBL. */
if (num_modules != 2) {
StartDebugProcess(g_cheat_process_metadata.process_id);
g_cheat_process_metadata.process_id = 0;
return;
}
g_cheat_process_metadata.main_nso_extents.base = proc_modules[1].base_address;
g_cheat_process_metadata.main_nso_extents.size = proc_modules[1].size;
memcpy(g_cheat_process_metadata.main_nso_build_id, proc_modules[1].build_id, sizeof(g_cheat_process_metadata.main_nso_build_id));
}
/* Read cheats off the SD. */
if (!LoadCheats(g_cheat_process_metadata.title_id, g_cheat_process_metadata.main_nso_build_id)) {
/* If we don't have cheats, or cheats are malformed, don't attach. */
StartDebugProcess(g_cheat_process_metadata.process_id);
g_cheat_process_metadata.process_id = 0;
return;
}
/* Open a debug handle. */
if (R_FAILED((rc = svcDebugActiveProcess(&g_cheat_process_debug_hnd, g_cheat_process_metadata.process_id)))) {
fatalSimple(rc);
}
/* Start the process. */
StartDebugProcess(g_cheat_process_metadata.process_id);
/* Start debug events thread. */
StartDebugEventsThread();
/* Signal to our fans. */
g_cheat_process_event->Signal();
}
void DmntCheatManager::DetectThread(void *arg) {
auto waiter = new WaitableManager(1);
waiter->AddWaitable(LoadReadOnlySystemEvent(PrepareDebugNextApplication(), [](u64 timeout) {
/* Process stuff for new application. */
DmntCheatManager::OnNewApplicationLaunch();
/* Setup detection for the next application, and close the duplicate handle. */
svcCloseHandle(PrepareDebugNextApplication());
return 0x0;
}, true));
waiter->Process();
delete waiter;
}
void DmntCheatManager::VmThread(void *arg) {
while (true) {
/* Execute Cheat VM. */
{
/* Acquire lock. */
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (HasActiveCheatProcess()) {
/* Execute VM. */
if (!g_needs_reload_vm_program || (g_cheat_vm->LoadProgram(g_cheat_entries, DmntCheatManager::MaxCheatCount))) {
/* Program: reloaded. */
g_needs_reload_vm_program = false;
/* Execute program if it's present. */
if (g_cheat_vm->GetProgramSize() != 0) {
g_cheat_vm->Execute(&g_cheat_process_metadata);
}
}
/* Apply frozen addresses. */
for (auto const& [address, value] : g_frozen_addresses_map) {
WriteCheatProcessMemoryForVm(address, &value.value, value.width);
}
}
}
constexpr u64 ONE_SECOND = 1000000000ul;
constexpr u64 NUM_TIMES = 12;
constexpr u64 DELAY = ONE_SECOND / NUM_TIMES;
svcSleepThread(DELAY);
}
}
void DmntCheatManager::DebugEventsThread(void *arg) {
while (R_SUCCEEDED(svcWaitSynchronizationSingle(g_cheat_process_debug_hnd, U64_MAX))) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
/* Handle any pending debug events. */
if (HasActiveCheatProcess()) {
ContinueCheatProcess();
}
}
}
bool DmntCheatManager::GetHasActiveCheatProcess() {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
return HasActiveCheatProcess();
}
Handle DmntCheatManager::GetCheatProcessEventHandle() {
return g_cheat_process_event->GetHandle();
}
Result DmntCheatManager::GetCheatProcessMetadata(CheatProcessMetadata *out) {
std::scoped_lock<HosMutex> lk(g_cheat_lock);
if (HasActiveCheatProcess()) {
*out = g_cheat_process_metadata;
return 0;
}
return ResultDmntCheatNotAttached;
}
void DmntCheatManager::InitializeCheatManager() {
/* Create cheat process detection event. */
g_cheat_process_event = CreateWriteOnlySystemEvent();
/* Create cheat vm. */
g_cheat_vm = new DmntCheatVm();
/* Learn whether we should enable cheats by default. */
{
u8 en;
if (R_SUCCEEDED(setsysGetSettingsItemValue("atmosphere", "dmnt_cheats_enabled_by_default", &en, sizeof(en)))) {
g_enable_cheats_by_default = (en != 0);
}
}
/* Spawn application detection thread, spawn cheat vm thread. */
if (R_FAILED(g_detect_thread.Initialize(&DmntCheatManager::DetectThread, nullptr, 0x4000, 39))) {
std::abort();
}
if (R_FAILED(g_vm_thread.Initialize(&DmntCheatManager::VmThread, nullptr, 0x4000, 48))) {
std::abort();
}
/* Start threads. */
if (R_FAILED(g_detect_thread.Start()) || R_FAILED(g_vm_thread.Start())) {
std::abort();
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <switch.h>
#include <stratosphere.hpp>
#include "dmnt_cheat_types.hpp"
class DmntCheatManager {
public:
static constexpr size_t MaxCheatCount = 0x80;
static constexpr size_t MaxFrozenAddressCount = 0x80;
private:
static Handle PrepareDebugNextApplication();
static void OnNewApplicationLaunch();
static void DetectThread(void *arg);
static void VmThread(void *arg);
static void DebugEventsThread(void *arg);
static void StartDebugEventsThread();
static void WaitDebugEventsThread();
static bool HasActiveCheatProcess();
static void CloseActiveCheatProcess();
static void ContinueCheatProcess();
static void ResetCheatEntry(size_t i);
static void ResetAllCheatEntries();
static CheatEntry *GetFreeCheatEntry();
static CheatEntry *GetCheatEntryById(size_t i);
static bool ParseCheats(const char *cht_txt, size_t len);
static bool LoadCheats(u64 title_id, const u8 *build_id);
static void ResetFrozenAddresses();
public:
static bool GetHasActiveCheatProcess();
static Handle GetCheatProcessEventHandle();
static Result GetCheatProcessMetadata(CheatProcessMetadata *out);
static Result ForceOpenCheatProcess();
static Result ReadCheatProcessMemoryForVm(u64 proc_addr, void *out_data, size_t size);
static Result WriteCheatProcessMemoryForVm(u64 proc_addr, const void *data, size_t size);
static Result GetCheatProcessMappingCount(u64 *out_count);
static Result GetCheatProcessMappings(MemoryInfo *mappings, size_t max_count, u64 *out_count, u64 offset);
static Result ReadCheatProcessMemory(u64 proc_addr, void *out_data, size_t size);
static Result WriteCheatProcessMemory(u64 proc_addr, const void *data, size_t size);
static Result QueryCheatProcessMemory(MemoryInfo *mapping, u64 address);
static Result GetCheatCount(u64 *out_count);
static Result GetCheats(CheatEntry *cheats, size_t max_count, u64 *out_count, u64 offset);
static Result GetCheatById(CheatEntry *out_cheat, u32 cheat_id);
static Result ToggleCheat(u32 cheat_id);
static Result AddCheat(u32 *out_id, CheatDefinition *def, bool enabled);
static Result RemoveCheat(u32 cheat_id);
static Result GetFrozenAddressCount(u64 *out_count);
static Result GetFrozenAddresses(FrozenAddressEntry *frz_addrs, size_t max_count, u64 *out_count, u64 offset);
static Result GetFrozenAddress(FrozenAddressEntry *frz_addr, u64 address);
static Result EnableFrozenAddress(u64 *out_value, u64 address, u64 width);
static Result DisableFrozenAddress(u64 address);
static void InitializeCheatManager();
};

View File

@@ -0,0 +1,177 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <switch.h>
#include "dmnt_cheat_service.hpp"
#include "dmnt_cheat_manager.hpp"
/* ========================================================================================= */
/* ==================================== Meta Commands ==================================== */
/* ========================================================================================= */
void DmntCheatService::HasCheatProcess(Out<bool> out) {
out.SetValue(DmntCheatManager::GetHasActiveCheatProcess());
}
void DmntCheatService::GetCheatProcessEvent(Out<CopiedHandle> out_event) {
out_event.SetValue(DmntCheatManager::GetCheatProcessEventHandle());
}
Result DmntCheatService::GetCheatProcessMetadata(Out<CheatProcessMetadata> out_metadata) {
return DmntCheatManager::GetCheatProcessMetadata(out_metadata.GetPointer());
}
Result DmntCheatService::ForceOpenCheatProcess() {
Result rc = DmntCheatManager::ForceOpenCheatProcess();
if (R_FAILED(rc)) {
rc = ResultDmntCheatNotAttached;
}
return rc;
}
/* ========================================================================================= */
/* =================================== Memory Commands =================================== */
/* ========================================================================================= */
Result DmntCheatService::GetCheatProcessMappingCount(Out<u64> out_count) {
return DmntCheatManager::GetCheatProcessMappingCount(out_count.GetPointer());
}
Result DmntCheatService::GetCheatProcessMappings(OutBuffer<MemoryInfo> mappings, Out<u64> out_count, u64 offset) {
if (mappings.buffer == nullptr) {
return ResultDmntCheatNullBuffer;
}
return DmntCheatManager::GetCheatProcessMappings(mappings.buffer, mappings.num_elements, out_count.GetPointer(), offset);
}
Result DmntCheatService::ReadCheatProcessMemory(OutBuffer<u8> buffer, u64 address, u64 out_size) {
if (buffer.buffer == nullptr) {
return ResultDmntCheatNullBuffer;
}
u64 sz = out_size;
if (buffer.num_elements < sz) {
sz = buffer.num_elements;
}
return DmntCheatManager::ReadCheatProcessMemory(address, buffer.buffer, sz);
}
Result DmntCheatService::WriteCheatProcessMemory(InBuffer<u8> buffer, u64 address, u64 in_size) {
if (buffer.buffer == nullptr) {
return ResultDmntCheatNullBuffer;
}
u64 sz = in_size;
if (buffer.num_elements < sz) {
sz = buffer.num_elements;
}
return DmntCheatManager::WriteCheatProcessMemory(address, buffer.buffer, sz);
}
Result DmntCheatService::QueryCheatProcessMemory(Out<MemoryInfo> mapping, u64 address) {
return DmntCheatManager::QueryCheatProcessMemory(mapping.GetPointer(), address);
}
/* ========================================================================================= */
/* =================================== Cheat Commands ==================================== */
/* ========================================================================================= */
Result DmntCheatService::GetCheatCount(Out<u64> out_count) {
return DmntCheatManager::GetCheatCount(out_count.GetPointer());
}
Result DmntCheatService::GetCheats(OutBuffer<CheatEntry> cheats, Out<u64> out_count, u64 offset) {
if (cheats.buffer == nullptr) {
return ResultDmntCheatNullBuffer;
}
return DmntCheatManager::GetCheats(cheats.buffer, cheats.num_elements, out_count.GetPointer(), offset);
}
Result DmntCheatService::GetCheatById(OutBuffer<CheatEntry> cheat, u32 cheat_id) {
if (cheat.buffer == nullptr) {
return ResultDmntCheatNullBuffer;
}
if (cheat.num_elements < 1) {
return ResultDmntCheatInvalidBuffer;
}
return DmntCheatManager::GetCheatById(cheat.buffer, cheat_id);
}
Result DmntCheatService::ToggleCheat(u32 cheat_id) {
return DmntCheatManager::ToggleCheat(cheat_id);
}
Result DmntCheatService::AddCheat(InBuffer<CheatDefinition> cheat, Out<u32> out_cheat_id, bool enabled) {
if (cheat.buffer == nullptr) {
return ResultDmntCheatNullBuffer;
}
if (cheat.num_elements < 1) {
return ResultDmntCheatInvalidBuffer;
}
return DmntCheatManager::AddCheat(out_cheat_id.GetPointer(), cheat.buffer, enabled);
}
Result DmntCheatService::RemoveCheat(u32 cheat_id) {
return DmntCheatManager::RemoveCheat(cheat_id);
}
/* ========================================================================================= */
/* =================================== Address Commands ================================== */
/* ========================================================================================= */
Result DmntCheatService::GetFrozenAddressCount(Out<u64> out_count) {
return DmntCheatManager::GetFrozenAddressCount(out_count.GetPointer());
}
Result DmntCheatService::GetFrozenAddresses(OutBuffer<FrozenAddressEntry> frz_addrs, Out<u64> out_count, u64 offset) {
if (frz_addrs.buffer == nullptr) {
return ResultDmntCheatNullBuffer;
}
return DmntCheatManager::GetFrozenAddresses(frz_addrs.buffer, frz_addrs.num_elements, out_count.GetPointer(), offset);
}
Result DmntCheatService::GetFrozenAddress(Out<FrozenAddressEntry> entry, u64 address) {
return DmntCheatManager::GetFrozenAddress(entry.GetPointer(), address);
}
Result DmntCheatService::EnableFrozenAddress(Out<u64> out_value, u64 address, u64 width) {
switch (width) {
case 1:
case 2:
case 4:
case 8:
break;
default:
return ResultDmntCheatInvalidFreezeWidth;
}
return DmntCheatManager::EnableFrozenAddress(out_value.GetPointer(), address, width);
}
Result DmntCheatService::DisableFrozenAddress(u64 address) {
return DmntCheatManager::DisableFrozenAddress(address);
}

View File

@@ -0,0 +1,105 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <switch.h>
#include <stratosphere.hpp>
#include "dmnt_cheat_types.hpp"
enum DmntCheatCmd {
/* Meta */
DmntCheat_Cmd_HasCheatProcess = 65000,
DmntCheat_Cmd_GetCheatProcessEvent = 65001,
DmntCheat_Cmd_GetCheatProcessMetadata = 65002,
DmntCheat_Cmd_ForceOpenCheatProcess = 65003,
/* Interact with Memory */
DmntCheat_Cmd_GetCheatProcessMappingCount = 65100,
DmntCheat_Cmd_GetCheatProcessMappings = 65101,
DmntCheat_Cmd_ReadCheatProcessMemory = 65102,
DmntCheat_Cmd_WriteCheatProcessMemory = 65103,
DmntCheat_Cmd_QueryCheatProcessMemory = 65104,
/* Interact with Cheats */
DmntCheat_Cmd_GetCheatCount = 65200,
DmntCheat_Cmd_GetCheats = 65201,
DmntCheat_Cmd_GetCheatById = 65202,
DmntCheat_Cmd_ToggleCheat = 65203,
DmntCheat_Cmd_AddCheat = 65204,
DmntCheat_Cmd_RemoveCheat = 65205,
/* Interact with Frozen Addresses */
DmntCheat_Cmd_GetFrozenAddressCount = 65300,
DmntCheat_Cmd_GetFrozenAddresses = 65301,
DmntCheat_Cmd_GetFrozenAddress = 65302,
DmntCheat_Cmd_EnableFrozenAddress = 65303,
DmntCheat_Cmd_DisableFrozenAddress = 65304,
};
class DmntCheatService final : public IServiceObject {
private:
void HasCheatProcess(Out<bool> out);
void GetCheatProcessEvent(Out<CopiedHandle> out_event);
Result GetCheatProcessMetadata(Out<CheatProcessMetadata> out_metadata);
Result ForceOpenCheatProcess();
Result GetCheatProcessMappingCount(Out<u64> out_count);
Result GetCheatProcessMappings(OutBuffer<MemoryInfo> mappings, Out<u64> out_count, u64 offset);
Result ReadCheatProcessMemory(OutBuffer<u8> buffer, u64 address, u64 out_size);
Result WriteCheatProcessMemory(InBuffer<u8> buffer, u64 address, u64 in_size);
Result QueryCheatProcessMemory(Out<MemoryInfo> mapping, u64 address);
Result GetCheatCount(Out<u64> out_count);
Result GetCheats(OutBuffer<CheatEntry> cheats, Out<u64> out_count, u64 offset);
Result GetCheatById(OutBuffer<CheatEntry> cheat, u32 cheat_id);
Result ToggleCheat(u32 cheat_id);
Result AddCheat(InBuffer<CheatDefinition> cheat, Out<u32> out_cheat_id, bool enabled);
Result RemoveCheat(u32 cheat_id);
Result GetFrozenAddressCount(Out<u64> out_count);
Result GetFrozenAddresses(OutBuffer<FrozenAddressEntry> addresses, Out<u64> out_count, u64 offset);
Result GetFrozenAddress(Out<FrozenAddressEntry> entry, u64 address);
Result EnableFrozenAddress(Out<u64> out_value, u64 address, u64 width);
Result DisableFrozenAddress(u64 address);
public:
DEFINE_SERVICE_DISPATCH_TABLE {
MakeServiceCommandMeta<DmntCheat_Cmd_HasCheatProcess, &DmntCheatService::HasCheatProcess>(),
MakeServiceCommandMeta<DmntCheat_Cmd_GetCheatProcessEvent, &DmntCheatService::GetCheatProcessEvent>(),
MakeServiceCommandMeta<DmntCheat_Cmd_GetCheatProcessMetadata, &DmntCheatService::GetCheatProcessMetadata>(),
MakeServiceCommandMeta<DmntCheat_Cmd_ForceOpenCheatProcess, &DmntCheatService::ForceOpenCheatProcess>(),
MakeServiceCommandMeta<DmntCheat_Cmd_GetCheatProcessMappingCount, &DmntCheatService::GetCheatProcessMappingCount>(),
MakeServiceCommandMeta<DmntCheat_Cmd_GetCheatProcessMappings, &DmntCheatService::GetCheatProcessMappings>(),
MakeServiceCommandMeta<DmntCheat_Cmd_ReadCheatProcessMemory, &DmntCheatService::ReadCheatProcessMemory>(),
MakeServiceCommandMeta<DmntCheat_Cmd_WriteCheatProcessMemory, &DmntCheatService::WriteCheatProcessMemory>(),
MakeServiceCommandMeta<DmntCheat_Cmd_QueryCheatProcessMemory, &DmntCheatService::QueryCheatProcessMemory>(),
MakeServiceCommandMeta<DmntCheat_Cmd_GetCheatCount, &DmntCheatService::GetCheatCount>(),
MakeServiceCommandMeta<DmntCheat_Cmd_GetCheats, &DmntCheatService::GetCheats>(),
MakeServiceCommandMeta<DmntCheat_Cmd_GetCheatById, &DmntCheatService::GetCheatById>(),
MakeServiceCommandMeta<DmntCheat_Cmd_ToggleCheat, &DmntCheatService::ToggleCheat>(),
MakeServiceCommandMeta<DmntCheat_Cmd_AddCheat, &DmntCheatService::AddCheat>(),
MakeServiceCommandMeta<DmntCheat_Cmd_RemoveCheat, &DmntCheatService::RemoveCheat>(),
MakeServiceCommandMeta<DmntCheat_Cmd_GetFrozenAddressCount, &DmntCheatService::GetFrozenAddressCount>(),
MakeServiceCommandMeta<DmntCheat_Cmd_GetFrozenAddresses, &DmntCheatService::GetFrozenAddresses>(),
MakeServiceCommandMeta<DmntCheat_Cmd_GetFrozenAddress, &DmntCheatService::GetFrozenAddress>(),
MakeServiceCommandMeta<DmntCheat_Cmd_EnableFrozenAddress, &DmntCheatService::EnableFrozenAddress>(),
MakeServiceCommandMeta<DmntCheat_Cmd_DisableFrozenAddress, &DmntCheatService::DisableFrozenAddress>(),
};
};

View File

@@ -0,0 +1,58 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <switch.h>
#include <stratosphere.hpp>
#include "dmnt_results.hpp"
struct MemoryRegionExtents {
u64 base;
u64 size;
};
struct CheatProcessMetadata {
u64 process_id;
u64 title_id;
MemoryRegionExtents main_nso_extents;
MemoryRegionExtents heap_extents;
MemoryRegionExtents alias_extents;
MemoryRegionExtents address_space_extents;
u8 main_nso_build_id[0x20];
};
struct CheatDefinition {
char readable_name[0x40];
uint32_t num_opcodes;
uint32_t opcodes[0x100];
};
struct CheatEntry {
bool enabled;
uint32_t cheat_id;
CheatDefinition definition;
};
struct FrozenAddressValue {
u64 value;
u8 width;
};
struct FrozenAddressEntry {
u64 address;
FrozenAddressValue value;
};

View File

@@ -0,0 +1,762 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <switch.h>
#include "dmnt_cheat_types.hpp"
#include "dmnt_cheat_vm.hpp"
#include "dmnt_cheat_manager.hpp"
#include "dmnt_hid.hpp"
void DmntCheatVm::OpenDebugLogFile() {
#ifdef DMNT_CHEAT_VM_DEBUG_LOG
CloseDebugLogFile();
this->debug_log_file = fopen("cheat_vm_log.txt", "wb");
#endif
}
void DmntCheatVm::CloseDebugLogFile() {
#ifdef DMNT_CHEAT_VM_DEBUG_LOG
if (this->debug_log_file != NULL) {
fclose(this->debug_log_file);
this->debug_log_file = NULL;
}
#endif
}
void DmntCheatVm::LogToDebugFile(const char *format, ...) {
#ifdef DMNT_CHEAT_VM_DEBUG_LOG
if (this->debug_log_file != NULL) {
va_list arglist;
va_start(arglist, format);
vfprintf(this->debug_log_file, format, arglist);
va_end(arglist);
}
#endif
}
void DmntCheatVm::LogOpcode(const CheatVmOpcode *opcode) {
#ifndef DMNT_CHEAT_VM_DEBUG_LOG
return;
#endif
switch (opcode->opcode) {
case CheatVmOpcodeType_StoreStatic:
this->LogToDebugFile("Opcode: Store Static\n");
this->LogToDebugFile("Bit Width: %x\n", opcode->store_static.bit_width);
this->LogToDebugFile("Mem Type: %x\n", opcode->store_static.mem_type);
this->LogToDebugFile("Reg Idx: %x\n", opcode->store_static.offset_register);
this->LogToDebugFile("Rel Addr: %lx\n", opcode->store_static.rel_address);
this->LogToDebugFile("Value: %lx\n", opcode->store_static.value.bit64);
break;
case CheatVmOpcodeType_BeginConditionalBlock:
this->LogToDebugFile("Opcode: Begin Conditional\n");
this->LogToDebugFile("Bit Width: %x\n", opcode->begin_cond.bit_width);
this->LogToDebugFile("Mem Type: %x\n", opcode->begin_cond.mem_type);
this->LogToDebugFile("Cond Type: %x\n", opcode->begin_cond.cond_type);
this->LogToDebugFile("Rel Addr: %lx\n", opcode->begin_cond.rel_address);
this->LogToDebugFile("Value: %lx\n", opcode->begin_cond.value.bit64);
break;
case CheatVmOpcodeType_EndConditionalBlock:
this->LogToDebugFile("Opcode: End Conditional\n");
break;
case CheatVmOpcodeType_ControlLoop:
if (opcode->ctrl_loop.start_loop) {
this->LogToDebugFile("Opcode: Start Loop\n");
this->LogToDebugFile("Reg Idx: %x\n", opcode->ctrl_loop.reg_index);
this->LogToDebugFile("Num Iters: %x\n", opcode->ctrl_loop.num_iters);
} else {
this->LogToDebugFile("Opcode: End Loop\n");
this->LogToDebugFile("Reg Idx: %x\n", opcode->ctrl_loop.reg_index);
}
break;
case CheatVmOpcodeType_LoadRegisterStatic:
this->LogToDebugFile("Opcode: Load Register Static\n");
this->LogToDebugFile("Reg Idx: %x\n", opcode->ldr_static.reg_index);
this->LogToDebugFile("Value: %lx\n", opcode->ldr_static.value);
break;
case CheatVmOpcodeType_LoadRegisterMemory:
this->LogToDebugFile("Opcode: Load Register Memory\n");
this->LogToDebugFile("Bit Width: %x\n", opcode->ldr_memory.bit_width);
this->LogToDebugFile("Reg Idx: %x\n", opcode->ldr_memory.reg_index);
this->LogToDebugFile("Mem Type: %x\n", opcode->ldr_memory.mem_type);
this->LogToDebugFile("From Reg: %d\n", opcode->ldr_memory.load_from_reg);
this->LogToDebugFile("Rel Addr: %lx\n", opcode->ldr_memory.rel_address);
break;
case CheatVmOpcodeType_StoreStaticToAddress:
this->LogToDebugFile("Opcode: Store Static to Address\n");
this->LogToDebugFile("Bit Width: %x\n", opcode->str_static.bit_width);
this->LogToDebugFile("Reg Idx: %x\n", opcode->str_static.reg_index);
if (opcode->str_static.add_offset_reg) {
this->LogToDebugFile("O Reg Idx: %x\n", opcode->str_static.offset_reg_index);
}
this->LogToDebugFile("Incr Reg: %d\n", opcode->str_static.increment_reg);
this->LogToDebugFile("Value: %lx\n", opcode->str_static.value);
break;
case CheatVmOpcodeType_PerformArithmeticStatic:
this->LogToDebugFile("Opcode: Perform Static Arithmetic\n");
this->LogToDebugFile("Bit Width: %x\n", opcode->perform_math_static.bit_width);
this->LogToDebugFile("Reg Idx: %x\n", opcode->perform_math_static.reg_index);
this->LogToDebugFile("Math Type: %x\n", opcode->perform_math_static.math_type);
this->LogToDebugFile("Value: %lx\n", opcode->perform_math_static.value);
break;
case CheatVmOpcodeType_BeginKeypressConditionalBlock:
this->LogToDebugFile("Opcode: Begin Keypress Conditional\n");
this->LogToDebugFile("Key Mask: %x\n", opcode->begin_keypress_cond.key_mask);
break;
case CheatVmOpcodeType_PerformArithmeticRegister:
this->LogToDebugFile("Opcode: Perform Register Arithmetic\n");
this->LogToDebugFile("Bit Width: %x\n", opcode->perform_math_reg.bit_width);
this->LogToDebugFile("Dst Idx: %x\n", opcode->perform_math_reg.dst_reg_index);
this->LogToDebugFile("Src1 Idx: %x\n", opcode->perform_math_reg.src_reg_1_index);
if (opcode->perform_math_reg.has_immediate) {
this->LogToDebugFile("Value: %lx\n", opcode->perform_math_reg.value.bit64);
} else {
this->LogToDebugFile("Src2 Idx: %x\n", opcode->perform_math_reg.src_reg_2_index);
}
break;
case CheatVmOpcodeType_StoreRegisterToAddress:
this->LogToDebugFile("Opcode: Store Register to Address\n");
this->LogToDebugFile("Bit Width: %x\n", opcode->str_register.bit_width);
this->LogToDebugFile("S Reg Idx: %x\n", opcode->str_register.str_reg_index);
this->LogToDebugFile("A Reg Idx: %x\n", opcode->str_register.addr_reg_index);
this->LogToDebugFile("Incr Reg: %d\n", opcode->str_register.increment_reg);
switch (opcode->str_register.ofs_type) {
case StoreRegisterOffsetType_None:
break;
case StoreRegisterOffsetType_Reg:
this->LogToDebugFile("O Reg Idx: %x\n", opcode->str_register.ofs_reg_index);
break;
case StoreRegisterOffsetType_Imm:
this->LogToDebugFile("Rel Addr: %lx\n", opcode->str_register.rel_address);
break;
}
break;
default:
this->LogToDebugFile("Unknown opcode: %x\n", opcode->opcode);
break;
}
}
bool DmntCheatVm::DecodeNextOpcode(CheatVmOpcode *out) {
/* If we've ever seen a decode failure, return false. */
bool valid = this->decode_success;
CheatVmOpcode opcode = {};
ON_SCOPE_EXIT {
this->decode_success &= valid;
if (valid) {
*out = opcode;
}
};
/* Helper function for getting instruction dwords. */
auto GetNextDword = [&]() {
if (this->instruction_ptr >= this->num_opcodes) {
valid = false;
return static_cast<u32>(0);
}
return this->program[this->instruction_ptr++];
};
/* Helper function for parsing a VmInt. */
auto GetNextVmInt = [&](const u32 bit_width) {
VmInt val = {0};
const u32 first_dword = GetNextDword();
switch (bit_width) {
case 1:
val.bit8 = (u8)first_dword;
break;
case 2:
val.bit16 = (u16)first_dword;
break;
case 4:
val.bit32 = first_dword;
break;
case 8:
val.bit64 = (((u64)first_dword) << 32ul) | ((u64)GetNextDword());
break;
}
return val;
};
/* Read opcode. */
const u32 first_dword = GetNextDword();
if (!valid) {
return valid;
}
opcode.opcode = (CheatVmOpcodeType)(((first_dword >> 28) & 0xF));
if (opcode.opcode >= CheatVmOpcodeType_ExtendedWidth) {
opcode.opcode = (CheatVmOpcodeType)((((u32)opcode.opcode) << 4) | ((first_dword >> 24) & 0xF));
}
/* detect condition start. */
switch (opcode.opcode) {
case CheatVmOpcodeType_BeginConditionalBlock:
case CheatVmOpcodeType_BeginKeypressConditionalBlock:
opcode.begin_conditional_block = true;
break;
default:
opcode.begin_conditional_block = false;
break;
}
switch (opcode.opcode) {
case CheatVmOpcodeType_StoreStatic:
{
/* 0TMR00AA AAAAAAAA YYYYYYYY (YYYYYYYY) */
/* Read additional words. */
const u32 second_dword = GetNextDword();
opcode.store_static.bit_width = (first_dword >> 24) & 0xF;
opcode.store_static.mem_type = (MemoryAccessType)((first_dword >> 20) & 0xF);
opcode.store_static.offset_register = ((first_dword >> 16) & 0xF);
opcode.store_static.rel_address = ((u64)(first_dword & 0xFF) << 32ul) | ((u64)second_dword);
opcode.store_static.value = GetNextVmInt(opcode.store_static.bit_width);
}
break;
case CheatVmOpcodeType_BeginConditionalBlock:
{
/* 1TMC00AA AAAAAAAA YYYYYYYY (YYYYYYYY) */
/* Read additional words. */
const u32 second_dword = GetNextDword();
opcode.begin_cond.bit_width = (first_dword >> 24) & 0xF;
opcode.begin_cond.mem_type = (MemoryAccessType)((first_dword >> 20) & 0xF);
opcode.begin_cond.cond_type = (ConditionalComparisonType)((first_dword >> 16) & 0xF);
opcode.begin_cond.rel_address = ((u64)(first_dword & 0xFF) << 32ul) | ((u64)second_dword);
opcode.begin_cond.value = GetNextVmInt(opcode.store_static.bit_width);
}
break;
case CheatVmOpcodeType_EndConditionalBlock:
{
/* 20000000 */
/* There's actually nothing left to process here! */
}
break;
case CheatVmOpcodeType_ControlLoop:
{
/* 300R0000 VVVVVVVV */
/* 310R0000 */
/* Parse register, whether loop start or loop end. */
opcode.ctrl_loop.start_loop = ((first_dword >> 24) & 0xF) == 0;
opcode.ctrl_loop.reg_index = ((first_dword >> 20) & 0xF);
/* Read number of iters if loop start. */
if (opcode.ctrl_loop.start_loop) {
opcode.ctrl_loop.num_iters = GetNextDword();
}
}
break;
case CheatVmOpcodeType_LoadRegisterStatic:
{
/* 400R0000 VVVVVVVV VVVVVVVV */
/* Read additional words. */
opcode.ldr_static.reg_index = ((first_dword >> 20) & 0xF);
opcode.ldr_static.value = (((u64)GetNextDword()) << 32ul) | ((u64)GetNextDword());
}
break;
case CheatVmOpcodeType_LoadRegisterMemory:
{
/* 5TMRI0AA AAAAAAAA */
/* Read additional words. */
const u32 second_dword = GetNextDword();
opcode.ldr_memory.bit_width = (first_dword >> 24) & 0xF;
opcode.ldr_memory.mem_type = (MemoryAccessType)((first_dword >> 20) & 0xF);
opcode.ldr_memory.reg_index = ((first_dword >> 16) & 0xF);
opcode.ldr_memory.load_from_reg = ((first_dword >> 12) & 0xF) != 0;
opcode.ldr_memory.rel_address = ((u64)(first_dword & 0xFF) << 32ul) | ((u64)second_dword);
}
break;
case CheatVmOpcodeType_StoreStaticToAddress:
{
/* 6T0RIor0 VVVVVVVV VVVVVVVV */
/* Read additional words. */
opcode.str_static.bit_width = (first_dword >> 24) & 0xF;
opcode.str_static.reg_index = ((first_dword >> 16) & 0xF);
opcode.str_static.increment_reg = ((first_dword >> 12) & 0xF) != 0;
opcode.str_static.add_offset_reg = ((first_dword >> 8) & 0xF) != 0;
opcode.str_static.offset_reg_index = ((first_dword >> 4) & 0xF);
opcode.str_static.value = (((u64)GetNextDword()) << 32ul) | ((u64)GetNextDword());
}
break;
case CheatVmOpcodeType_PerformArithmeticStatic:
{
/* 7T0RC000 VVVVVVVV */
/* Read additional words. */
opcode.perform_math_static.bit_width = (first_dword >> 24) & 0xF;
opcode.perform_math_static.reg_index = ((first_dword >> 16) & 0xF);
opcode.perform_math_static.math_type = (RegisterArithmeticType)((first_dword >> 12) & 0xF);
opcode.perform_math_static.value = GetNextDword();
}
break;
case CheatVmOpcodeType_BeginKeypressConditionalBlock:
{
/* 8kkkkkkk */
/* Just parse the mask. */
opcode.begin_keypress_cond.key_mask = first_dword & 0x0FFFFFFF;
}
break;
case CheatVmOpcodeType_PerformArithmeticRegister:
{
/* 9TCRSIs0 (VVVVVVVV (VVVVVVVV)) */
opcode.perform_math_reg.bit_width = (first_dword >> 24) & 0xF;
opcode.perform_math_reg.math_type = (RegisterArithmeticType)((first_dword >> 20) & 0xF);
opcode.perform_math_reg.dst_reg_index = ((first_dword >> 16) & 0xF);
opcode.perform_math_reg.src_reg_1_index = ((first_dword >> 12) & 0xF);
opcode.perform_math_reg.has_immediate = ((first_dword >> 8) & 0xF) != 0;
if (opcode.perform_math_reg.has_immediate) {
opcode.perform_math_reg.src_reg_2_index = 0;
opcode.perform_math_reg.value = GetNextVmInt(opcode.perform_math_reg.bit_width);
} else {
opcode.perform_math_reg.src_reg_2_index = ((first_dword >> 4) & 0xF);
}
}
break;
case CheatVmOpcodeType_StoreRegisterToAddress:
{
/* ATSRIOra (aaaaaaaa) */
/* A = opcode 10 */
/* T = bit width */
/* S = src register index */
/* R = address register index */
/* I = 1 if increment address register, 0 if not increment address register */
/* O = offset type, 0 = None, 1 = Register, 2 = Immediate */
/* r = offset register (for offset type 1) */
/* a = relative address (for offset type 2) */
opcode.str_register.bit_width = (first_dword >> 24) & 0xF;
opcode.str_register.str_reg_index = ((first_dword >> 20) & 0xF);
opcode.str_register.addr_reg_index = ((first_dword >> 16) & 0xF);
opcode.str_register.increment_reg = ((first_dword >> 12) & 0xF) != 0;
opcode.str_register.ofs_type = (StoreRegisterOffsetType)(((first_dword >> 8) & 0xF));
opcode.str_register.ofs_reg_index = ((first_dword >> 4) & 0xF);
switch (opcode.str_register.ofs_type) {
case StoreRegisterOffsetType_None:
case StoreRegisterOffsetType_Reg:
/* Nothing more to do */
break;
case StoreRegisterOffsetType_Imm:
opcode.str_register.rel_address = (((u64)(first_dword & 0xF) << 32ul) | ((u64)GetNextDword()));
break;
default:
opcode.str_register.ofs_type = StoreRegisterOffsetType_None;
break;
}
}
break;
case CheatVmOpcodeType_ExtendedWidth:
default:
/* Unrecognized instruction cannot be decoded. */
valid = false;
break;
}
/* End decoding. */
return valid;
}
void DmntCheatVm::SkipConditionalBlock() {
if (this->condition_depth > 0) {
/* We want to continue until we're out of the current block. */
const size_t desired_depth = this->condition_depth - 1;
CheatVmOpcode skip_opcode;
while (this->DecodeNextOpcode(&skip_opcode) && this->condition_depth > desired_depth) {
/* Decode instructions until we see end of the current conditional block. */
/* NOTE: This is broken in gateway's implementation. */
/* Gateway currently checks for "0x2" instead of "0x20000000" */
/* In addition, they do a linear scan instead of correctly decoding opcodes. */
/* This causes issues if "0x2" appears as an immediate in the conditional block... */
/* We also support nesting of conditional blocks, and Gateway does not. */
if (skip_opcode.begin_conditional_block) {
this->condition_depth++;
} else if (skip_opcode.opcode == CheatVmOpcodeType_EndConditionalBlock) {
this->condition_depth--;
}
}
} else {
/* Skipping, but this->condition_depth = 0. */
/* This is an error condition. */
/* However, I don't actually believe it is possible for this to happen. */
/* I guess we'll throw a fatal error here, so as to encourage me to fix the VM */
/* in the event that someone triggers it? I don't know how you'd do that. */
fatalSimple(ResultDmntCheatVmInvalidCondDepth);
}
}
u64 DmntCheatVm::GetVmInt(VmInt value, u32 bit_width) {
switch (bit_width) {
case 1:
return value.bit8;
case 2:
return value.bit16;
case 4:
return value.bit32;
case 8:
return value.bit64;
default:
/* Invalid bit width -> return 0. */
return 0;
}
}
u64 DmntCheatVm::GetCheatProcessAddress(const CheatProcessMetadata* metadata, MemoryAccessType mem_type, u64 rel_address) {
switch (mem_type) {
case MemoryAccessType_MainNso:
default:
return metadata->main_nso_extents.base + rel_address;
case MemoryAccessType_Heap:
return metadata->heap_extents.base + rel_address;
}
}
void DmntCheatVm::ResetState() {
for (size_t i = 0; i < DmntCheatVm::NumRegisters; i++) {
this->registers[i] = 0;
this->loop_tops[i] = 0;
}
this->instruction_ptr = 0;
this->condition_depth = 0;
this->decode_success = true;
}
bool DmntCheatVm::LoadProgram(const CheatEntry *cheats, size_t num_cheats) {
/* Reset opcode count. */
this->num_opcodes = 0;
for (size_t i = 0; i < num_cheats; i++) {
if (cheats[i].enabled) {
/* Bounds check. */
if (cheats[i].definition.num_opcodes + this->num_opcodes > MaximumProgramOpcodeCount) {
this->num_opcodes = 0;
return false;
}
for (size_t n = 0; n < cheats[i].definition.num_opcodes; n++) {
this->program[this->num_opcodes++] = cheats[i].definition.opcodes[n];
}
}
}
return true;
}
void DmntCheatVm::Execute(const CheatProcessMetadata *metadata) {
CheatVmOpcode cur_opcode;
u64 kDown = 0;
/* Get Keys down. */
HidManagement::GetKeysDown(&kDown);
this->OpenDebugLogFile();
ON_SCOPE_EXIT { this->CloseDebugLogFile(); };
this->LogToDebugFile("Started VM execution.\n");
this->LogToDebugFile("Main NSO: %012lx\n", metadata->main_nso_extents.base);
this->LogToDebugFile("Heap: %012lx\n", metadata->main_nso_extents.base);
this->LogToDebugFile("Keys Down: %08x\n", (u32)(kDown & 0x0FFFFFFF));
/* Clear VM state. */
this->ResetState();
/* Loop until program finishes. */
while (this->DecodeNextOpcode(&cur_opcode)) {
this->LogToDebugFile("Instruction Ptr: %04x\n", (u32)this->instruction_ptr);
for (size_t i = 0; i < NumRegisters; i++) {
this->LogToDebugFile("Registers[%02x]: %016lx\n", i, this->registers[i]);
}
this->LogOpcode(&cur_opcode);
/* Increment conditional depth, if relevant. */
if (cur_opcode.begin_conditional_block) {
this->condition_depth++;
}
switch (cur_opcode.opcode) {
case CheatVmOpcodeType_StoreStatic:
{
/* Calculate address, write value to memory. */
u64 dst_address = GetCheatProcessAddress(metadata, cur_opcode.store_static.mem_type, cur_opcode.store_static.rel_address + this->registers[cur_opcode.store_static.offset_register]);
u64 dst_value = GetVmInt(cur_opcode.store_static.value, cur_opcode.store_static.bit_width);
switch (cur_opcode.store_static.bit_width) {
case 1:
case 2:
case 4:
case 8:
DmntCheatManager::WriteCheatProcessMemoryForVm(dst_address, &dst_value, cur_opcode.store_static.bit_width);
break;
}
}
break;
case CheatVmOpcodeType_BeginConditionalBlock:
{
/* Read value from memory. */
u64 src_address = GetCheatProcessAddress(metadata, cur_opcode.begin_cond.mem_type, cur_opcode.begin_cond.rel_address);
u64 src_value = 0;
switch (cur_opcode.store_static.bit_width) {
case 1:
case 2:
case 4:
case 8:
DmntCheatManager::ReadCheatProcessMemoryForVm(src_address, &src_value, cur_opcode.begin_cond.bit_width);
break;
}
/* Check against condition. */
u64 cond_value = GetVmInt(cur_opcode.begin_cond.value, cur_opcode.begin_cond.bit_width);
bool cond_met = false;
switch (cur_opcode.begin_cond.cond_type) {
case ConditionalComparisonType_GT:
cond_met = src_value > cond_value;
break;
case ConditionalComparisonType_GE:
cond_met = src_value >= cond_value;
break;
case ConditionalComparisonType_LT:
cond_met = src_value < cond_value;
break;
case ConditionalComparisonType_LE:
cond_met = src_value <= cond_value;
break;
case ConditionalComparisonType_EQ:
cond_met = src_value == cond_value;
break;
case ConditionalComparisonType_NE:
cond_met = src_value != cond_value;
break;
}
/* Skip conditional block if condition not met. */
if (!cond_met) {
this->SkipConditionalBlock();
}
}
break;
case CheatVmOpcodeType_EndConditionalBlock:
/* Decrement the condition depth. */
/* We will assume, graciously, that mismatched conditional block ends are a nop. */
if (this->condition_depth > 0) {
this->condition_depth--;
}
break;
case CheatVmOpcodeType_ControlLoop:
if (cur_opcode.ctrl_loop.start_loop) {
/* Start a loop. */
this->registers[cur_opcode.ctrl_loop.reg_index] = cur_opcode.ctrl_loop.num_iters;
this->loop_tops[cur_opcode.ctrl_loop.reg_index] = this->instruction_ptr;
} else {
/* End a loop. */
this->registers[cur_opcode.ctrl_loop.reg_index]--;
if (this->registers[cur_opcode.ctrl_loop.reg_index] != 0) {
this->instruction_ptr = this->loop_tops[cur_opcode.ctrl_loop.reg_index];
}
}
break;
case CheatVmOpcodeType_LoadRegisterStatic:
/* Set a register to a static value. */
this->registers[cur_opcode.ldr_static.reg_index] = cur_opcode.ldr_static.value;
break;
case CheatVmOpcodeType_LoadRegisterMemory:
{
/* Choose source address. */
u64 src_address;
if (cur_opcode.ldr_memory.load_from_reg) {
src_address = this->registers[cur_opcode.ldr_memory.reg_index] + cur_opcode.ldr_memory.rel_address;
} else {
src_address = GetCheatProcessAddress(metadata, cur_opcode.ldr_memory.mem_type, cur_opcode.ldr_memory.rel_address);
}
/* Read into register. Gateway only reads on valid bitwidth. */
switch (cur_opcode.ldr_memory.bit_width) {
case 1:
case 2:
case 4:
case 8:
DmntCheatManager::ReadCheatProcessMemoryForVm(src_address, &this->registers[cur_opcode.ldr_memory.reg_index], cur_opcode.ldr_memory.bit_width);
break;
}
}
break;
case CheatVmOpcodeType_StoreStaticToAddress:
{
/* Calculate address. */
u64 dst_address = this->registers[cur_opcode.str_static.reg_index];
u64 dst_value = cur_opcode.str_static.value;
if (cur_opcode.str_static.add_offset_reg) {
dst_address += this->registers[cur_opcode.str_static.offset_reg_index];
}
/* Write value to memory. Gateway only writes on valid bitwidth. */
switch (cur_opcode.str_static.bit_width) {
case 1:
case 2:
case 4:
case 8:
DmntCheatManager::WriteCheatProcessMemoryForVm(dst_address, &dst_value, cur_opcode.str_static.bit_width);
break;
}
/* Increment register if relevant. */
if (cur_opcode.str_static.increment_reg) {
this->registers[cur_opcode.str_static.reg_index] += cur_opcode.str_static.bit_width;
}
}
break;
case CheatVmOpcodeType_PerformArithmeticStatic:
{
/* Do requested math. */
switch (cur_opcode.perform_math_static.math_type) {
case RegisterArithmeticType_Addition:
this->registers[cur_opcode.perform_math_static.reg_index] += (u64)cur_opcode.perform_math_static.value;
break;
case RegisterArithmeticType_Subtraction:
this->registers[cur_opcode.perform_math_static.reg_index] -= (u64)cur_opcode.perform_math_static.value;
break;
case RegisterArithmeticType_Multiplication:
this->registers[cur_opcode.perform_math_static.reg_index] *= (u64)cur_opcode.perform_math_static.value;
break;
case RegisterArithmeticType_LeftShift:
this->registers[cur_opcode.perform_math_static.reg_index] <<= (u64)cur_opcode.perform_math_static.value;
break;
case RegisterArithmeticType_RightShift:
this->registers[cur_opcode.perform_math_static.reg_index] >>= (u64)cur_opcode.perform_math_static.value;
break;
default:
/* Do not handle extensions here. */
break;
}
/* Apply bit width. */
switch (cur_opcode.perform_math_static.bit_width) {
case 1:
this->registers[cur_opcode.perform_math_static.reg_index] = static_cast<u8>(this->registers[cur_opcode.perform_math_static.reg_index]);
break;
case 2:
this->registers[cur_opcode.perform_math_static.reg_index] = static_cast<u16>(this->registers[cur_opcode.perform_math_static.reg_index]);
break;
case 4:
this->registers[cur_opcode.perform_math_static.reg_index] = static_cast<u32>(this->registers[cur_opcode.perform_math_static.reg_index]);
break;
case 8:
this->registers[cur_opcode.perform_math_static.reg_index] = static_cast<u64>(this->registers[cur_opcode.perform_math_static.reg_index]);
break;
}
}
break;
case CheatVmOpcodeType_BeginKeypressConditionalBlock:
/* Check for keypress. */
if ((cur_opcode.begin_keypress_cond.key_mask & kDown) != cur_opcode.begin_keypress_cond.key_mask) {
/* Keys not pressed. Skip conditional block. */
this->SkipConditionalBlock();
}
break;
case CheatVmOpcodeType_PerformArithmeticRegister:
{
const u64 operand_1_value = this->registers[cur_opcode.perform_math_reg.src_reg_1_index];
const u64 operand_2_value = cur_opcode.perform_math_reg.has_immediate ?
GetVmInt(cur_opcode.perform_math_reg.value, cur_opcode.perform_math_reg.bit_width) :
this->registers[cur_opcode.perform_math_reg.src_reg_2_index];
u64 res_val = 0;
/* Do requested math. */
switch (cur_opcode.perform_math_reg.math_type) {
case RegisterArithmeticType_Addition:
res_val = operand_1_value + operand_2_value;
break;
case RegisterArithmeticType_Subtraction:
res_val = operand_1_value - operand_2_value;
break;
case RegisterArithmeticType_Multiplication:
res_val = operand_1_value * operand_2_value;
break;
case RegisterArithmeticType_LeftShift:
res_val = operand_1_value << operand_2_value;
break;
case RegisterArithmeticType_RightShift:
res_val = operand_1_value >> operand_2_value;
break;
case RegisterArithmeticType_LogicalAnd:
res_val = operand_1_value & operand_2_value;
break;
case RegisterArithmeticType_LogicalOr:
res_val = operand_1_value | operand_2_value;
break;
case RegisterArithmeticType_LogicalNot:
res_val = ~operand_1_value;
break;
case RegisterArithmeticType_LogicalXor:
res_val = operand_1_value ^ operand_2_value;
break;
case RegisterArithmeticType_None:
res_val = operand_1_value;
break;
}
/* Apply bit width. */
switch (cur_opcode.perform_math_reg.bit_width) {
case 1:
res_val = static_cast<u8>(res_val);
break;
case 2:
res_val = static_cast<u16>(res_val);
break;
case 4:
res_val = static_cast<u32>(res_val);
break;
case 8:
res_val = static_cast<u64>(res_val);
break;
}
/* Save to register. */
this->registers[cur_opcode.perform_math_reg.dst_reg_index] = res_val;
}
break;
case CheatVmOpcodeType_StoreRegisterToAddress:
{
/* Calculate address. */
u64 dst_value = this->registers[cur_opcode.str_register.str_reg_index];
u64 dst_address = this->registers[cur_opcode.str_register.addr_reg_index];
switch (cur_opcode.str_register.ofs_type) {
case StoreRegisterOffsetType_None:
/* Nothing more to do */
break;
case StoreRegisterOffsetType_Reg:
dst_address += this->registers[cur_opcode.str_register.ofs_reg_index];
break;
case StoreRegisterOffsetType_Imm:
dst_address += cur_opcode.str_register.rel_address;
break;
}
/* Write value to memory. Write only on valid bitwidth. */
switch (cur_opcode.str_register.bit_width) {
case 1:
case 2:
case 4:
case 8:
DmntCheatManager::WriteCheatProcessMemoryForVm(dst_address, &dst_value, cur_opcode.str_register.bit_width);
break;
}
/* Increment register if relevant. */
if (cur_opcode.str_register.increment_reg) {
this->registers[cur_opcode.str_register.addr_reg_index] += cur_opcode.str_register.bit_width;
}
}
break;
default:
/* By default, we do a no-op. */
break;
}
}
}

View File

@@ -0,0 +1,221 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <switch.h>
#include <stdarg.h>
#include <stratosphere.hpp>
#include "dmnt_cheat_types.hpp"
enum CheatVmOpcodeType : u32 {
CheatVmOpcodeType_StoreStatic = 0,
CheatVmOpcodeType_BeginConditionalBlock = 1,
CheatVmOpcodeType_EndConditionalBlock = 2,
CheatVmOpcodeType_ControlLoop = 3,
CheatVmOpcodeType_LoadRegisterStatic = 4,
CheatVmOpcodeType_LoadRegisterMemory = 5,
CheatVmOpcodeType_StoreStaticToAddress = 6,
CheatVmOpcodeType_PerformArithmeticStatic = 7,
CheatVmOpcodeType_BeginKeypressConditionalBlock = 8,
/* These are not implemented by Gateway's VM. */
CheatVmOpcodeType_PerformArithmeticRegister = 9,
CheatVmOpcodeType_StoreRegisterToAddress = 10,
/* This is a meta entry, and not a real opcode. */
/* This is to facilitate multi-nybble instruction decoding in the future. */
CheatVmOpcodeType_ExtendedWidth = 12,
};
enum MemoryAccessType : u32 {
MemoryAccessType_MainNso = 0,
MemoryAccessType_Heap = 1,
};
enum ConditionalComparisonType : u32 {
ConditionalComparisonType_GT = 1,
ConditionalComparisonType_GE = 2,
ConditionalComparisonType_LT = 3,
ConditionalComparisonType_LE = 4,
ConditionalComparisonType_EQ = 5,
ConditionalComparisonType_NE = 6,
};
enum RegisterArithmeticType : u32 {
RegisterArithmeticType_Addition = 0,
RegisterArithmeticType_Subtraction = 1,
RegisterArithmeticType_Multiplication = 2,
RegisterArithmeticType_LeftShift = 3,
RegisterArithmeticType_RightShift = 4,
/* These are not supported by Gateway's VM. */
RegisterArithmeticType_LogicalAnd = 5,
RegisterArithmeticType_LogicalOr = 6,
RegisterArithmeticType_LogicalNot = 7,
RegisterArithmeticType_LogicalXor = 8,
RegisterArithmeticType_None = 9,
};
enum StoreRegisterOffsetType : u32 {
StoreRegisterOffsetType_None = 0,
StoreRegisterOffsetType_Reg = 1,
StoreRegisterOffsetType_Imm = 2,
};
union VmInt {
u8 bit8;
u16 bit16;
u32 bit32;
u64 bit64;
};
struct StoreStaticOpcode {
u32 bit_width;
MemoryAccessType mem_type;
u32 offset_register;
u64 rel_address;
VmInt value;
};
struct BeginConditionalOpcode {
u32 bit_width;
MemoryAccessType mem_type;
ConditionalComparisonType cond_type;
u64 rel_address;
VmInt value;
};
struct EndConditionalOpcode {};
struct ControlLoopOpcode {
bool start_loop;
u32 reg_index;
u32 num_iters;
};
struct LoadRegisterStaticOpcode {
u32 reg_index;
u64 value;
};
struct LoadRegisterMemoryOpcode {
u32 bit_width;
MemoryAccessType mem_type;
u32 reg_index;
bool load_from_reg;
u64 rel_address;
};
struct StoreStaticToAddressOpcode {
u32 bit_width;
u32 reg_index;
bool increment_reg;
bool add_offset_reg;
u32 offset_reg_index;
u64 value;
};
struct PerformArithmeticStaticOpcode {
u32 bit_width;
u32 reg_index;
RegisterArithmeticType math_type;
u32 value;
};
struct BeginKeypressConditionalOpcode {
u32 key_mask;
};
struct PerformArithmeticRegisterOpcode {
u32 bit_width;
RegisterArithmeticType math_type;
u32 dst_reg_index;
u32 src_reg_1_index;
u32 src_reg_2_index;
bool has_immediate;
VmInt value;
};
struct StoreRegisterToAddressOpcode {
u32 bit_width;
u32 str_reg_index;
u32 addr_reg_index;
bool increment_reg;
StoreRegisterOffsetType ofs_type;
u32 ofs_reg_index;
u64 rel_address;
};
struct CheatVmOpcode {
CheatVmOpcodeType opcode;
bool begin_conditional_block;
union {
StoreStaticOpcode store_static;
BeginConditionalOpcode begin_cond;
EndConditionalOpcode end_cond;
ControlLoopOpcode ctrl_loop;
LoadRegisterStaticOpcode ldr_static;
LoadRegisterMemoryOpcode ldr_memory;
StoreStaticToAddressOpcode str_static;
PerformArithmeticStaticOpcode perform_math_static;
BeginKeypressConditionalOpcode begin_keypress_cond;
PerformArithmeticRegisterOpcode perform_math_reg;
StoreRegisterToAddressOpcode str_register;
};
};
class DmntCheatVm {
public:
constexpr static size_t MaximumProgramOpcodeCount = 0x400;
constexpr static size_t NumRegisters = 0x10;
private:
size_t num_opcodes = 0;
size_t instruction_ptr = 0;
size_t condition_depth = 0;
bool decode_success = false;
u32 program[MaximumProgramOpcodeCount] = {0};
u64 registers[NumRegisters] = {0};
size_t loop_tops[NumRegisters] = {0};
private:
bool DecodeNextOpcode(CheatVmOpcode *out);
void SkipConditionalBlock();
void ResetState();
/* For debugging. These will be IFDEF'd out normally. */
void OpenDebugLogFile();
void CloseDebugLogFile();
void LogToDebugFile(const char *format, ...);
void LogOpcode(const CheatVmOpcode *opcode);
static u64 GetVmInt(VmInt value, u32 bit_width);
static u64 GetCheatProcessAddress(const CheatProcessMetadata* metadata, MemoryAccessType mem_type, u64 rel_address);
public:
DmntCheatVm() { }
size_t GetProgramSize() {
return this->num_opcodes;
}
bool LoadProgram(const CheatEntry *cheats, size_t num_cheats);
void Execute(const CheatProcessMetadata *metadata);
#ifdef DMNT_CHEAT_VM_DEBUG_LOG
private:
FILE *debug_log_file = NULL;
#endif
};

View File

@@ -0,0 +1,157 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <switch.h>
#include <string.h>
#include <stratosphere.hpp>
#include "dmnt_hid.hpp"
#include "dmnt_config.hpp"
#include "ini.h"
/* Support variables. */
static OverrideKey g_default_cheat_enable_key = {
.key_combination = KEY_L,
.override_by_default = true
};
/* Static buffer for loader.ini contents at runtime. */
static char g_config_ini_data[0x800];
static OverrideKey ParseOverrideKey(const char *value) {
OverrideKey cfg;
/* Parse on by default. */
if (value[0] == '!') {
cfg.override_by_default = true;
value++;
} else {
cfg.override_by_default = false;
}
/* Parse key combination. */
if (strcasecmp(value, "A") == 0) {
cfg.key_combination = KEY_A;
} else if (strcasecmp(value, "B") == 0) {
cfg.key_combination = KEY_B;
} else if (strcasecmp(value, "X") == 0) {
cfg.key_combination = KEY_X;
} else if (strcasecmp(value, "Y") == 0) {
cfg.key_combination = KEY_Y;
} else if (strcasecmp(value, "LS") == 0) {
cfg.key_combination = KEY_LSTICK;
} else if (strcasecmp(value, "RS") == 0) {
cfg.key_combination = KEY_RSTICK;
} else if (strcasecmp(value, "L") == 0) {
cfg.key_combination = KEY_L;
} else if (strcasecmp(value, "R") == 0) {
cfg.key_combination = KEY_R;
} else if (strcasecmp(value, "ZL") == 0) {
cfg.key_combination = KEY_ZL;
} else if (strcasecmp(value, "ZR") == 0) {
cfg.key_combination = KEY_ZR;
} else if (strcasecmp(value, "PLUS") == 0) {
cfg.key_combination = KEY_PLUS;
} else if (strcasecmp(value, "MINUS") == 0) {
cfg.key_combination = KEY_MINUS;
} else if (strcasecmp(value, "DLEFT") == 0) {
cfg.key_combination = KEY_DLEFT;
} else if (strcasecmp(value, "DUP") == 0) {
cfg.key_combination = KEY_DUP;
} else if (strcasecmp(value, "DRIGHT") == 0) {
cfg.key_combination = KEY_DRIGHT;
} else if (strcasecmp(value, "DDOWN") == 0) {
cfg.key_combination = KEY_DDOWN;
} else if (strcasecmp(value, "SL") == 0) {
cfg.key_combination = KEY_SL;
} else if (strcasecmp(value, "SR") == 0) {
cfg.key_combination = KEY_SR;
} else {
cfg.key_combination = 0;
}
return cfg;
}
static int DmntIniHandler(void *user, const char *section, const char *name, const char *value) {
/* Taken and modified, with love, from Rajkosto's implementation. */
if (strcasecmp(section, "default_config") == 0) {
if (strcasecmp(name, "cheat_enable_key") == 0) {
g_default_cheat_enable_key = ParseOverrideKey(value);
}
} else {
return 0;
}
return 1;
}
static int DmntTitleSpecificIniHandler(void *user, const char *section, const char *name, const char *value) {
/* We'll output an override key when relevant. */
OverrideKey *user_cfg = reinterpret_cast<OverrideKey *>(user);
if (strcasecmp(section, "override_config") == 0) {
if (strcasecmp(name, "cheat_enable_key") == 0) {
*user_cfg = ParseOverrideKey(value);
}
} else {
return 0;
}
return 1;
}
void DmntConfigManager::RefreshConfiguration() {
FILE *config = fopen("sdmc:/atmosphere/loader.ini", "r");
if (config == NULL) {
return;
}
memset(g_config_ini_data, 0, sizeof(g_config_ini_data));
fread(g_config_ini_data, 1, sizeof(g_config_ini_data) - 1, config);
fclose(config);
ini_parse_string(g_config_ini_data, DmntIniHandler, NULL);
}
OverrideKey DmntConfigManager::GetTitleCheatEnableKey(u64 tid) {
OverrideKey cfg = g_default_cheat_enable_key;
char path[FS_MAX_PATH+1] = {0};
snprintf(path, FS_MAX_PATH, "sdmc:/atmosphere/titles/%016lx/config.ini", tid);
FILE *config = fopen(path, "r");
if (config != NULL) {
ON_SCOPE_EXIT { fclose(config); };
/* Parse current title ini. */
ini_parse_file(config, DmntTitleSpecificIniHandler, &cfg);
}
return cfg;
}
static bool HasOverrideKey(OverrideKey *cfg) {
u64 kDown = 0;
bool keys_triggered = (R_SUCCEEDED(HidManagement::GetKeysDown(&kDown)) && ((kDown & cfg->key_combination) != 0));
return (cfg->override_by_default ^ keys_triggered);
}
bool DmntConfigManager::HasCheatEnableButton(u64 tid) {
/* Unconditionally refresh loader.ini contents. */
RefreshConfiguration();
OverrideKey title_cfg = GetTitleCheatEnableKey(tid);
return HasOverrideKey(&title_cfg);
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <switch.h>
struct OverrideKey {
u64 key_combination;
bool override_by_default;
};
class DmntConfigManager {
public:
static void RefreshConfiguration();
static OverrideKey GetTitleCheatEnableKey(u64 tid);
static bool HasCheatEnableButton(u64 tid);
};

View File

@@ -0,0 +1,32 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <switch.h>
#include <string.h>
#include <stratosphere.hpp>
#include "dmnt_hid.hpp"
static HosMutex g_hid_keys_down_lock;
Result HidManagement::GetKeysDown(u64 *keys) {
std::scoped_lock<HosMutex> lk(g_hid_keys_down_lock);
hidScanInput();
*keys = hidKeysDown(CONTROLLER_P1_AUTO);
return 0x0;
}

View File

@@ -0,0 +1,23 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <switch.h>
class HidManagement {
public:
static Result GetKeysDown(u64 *keys);
};

View File

@@ -0,0 +1,168 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <malloc.h>
#include <switch.h>
#include <atmosphere.h>
#include <stratosphere.hpp>
#include "dmnt_service.hpp"
#include "dmnt_cheat_service.hpp"
#include "dmnt_cheat_manager.hpp"
#include "dmnt_config.hpp"
extern "C" {
extern u32 __start__;
u32 __nx_applet_type = AppletType_None;
#define INNER_HEAP_SIZE 0x80000
size_t nx_inner_heap_size = INNER_HEAP_SIZE;
char nx_inner_heap[INNER_HEAP_SIZE];
void __libnx_initheap(void);
void __appInit(void);
void __appExit(void);
}
void __libnx_initheap(void) {
void* addr = nx_inner_heap;
size_t size = nx_inner_heap_size;
/* Newlib */
extern char* fake_heap_start;
extern char* fake_heap_end;
fake_heap_start = (char*)addr;
fake_heap_end = (char*)addr + size;
}
void __appInit(void) {
Result rc;
SetFirmwareVersionForLibnx();
rc = smInitialize();
if (R_FAILED(rc)) {
fatalSimple(MAKERESULT(Module_Libnx, LibnxError_InitFail_SM));
}
rc = pmdmntInitialize();
if (R_FAILED(rc)) {
fatalSimple(rc);
}
rc = ldrDmntInitialize();
if (R_FAILED(rc)) {
fatalSimple(rc);
}
/*
if (kernelAbove300()) {
rc = roDmntInitialize();
if (R_FAILED(rc)) {
fatalSimple(rc);
}
}
*/
rc = nsdevInitialize();
if (R_FAILED(rc)) {
fatalSimple(rc);
}
rc = lrInitialize();
if (R_FAILED(rc)) {
fatalSimple(rc);
}
rc = setInitialize();
if (R_FAILED(rc)) {
fatalSimple(rc);
}
rc = setsysInitialize();
if (R_FAILED(rc)) {
fatalSimple(rc);
}
rc = hidInitialize();
if (R_FAILED(rc)) {
fatalSimple(rc);
}
rc = fsInitialize();
if (R_FAILED(rc)) {
fatalSimple(rc);
}
rc = fsdevMountSdmc();
if (R_FAILED(rc)) {
fatalSimple(rc);
}
CheckAtmosphereVersion(CURRENT_ATMOSPHERE_VERSION);
}
void __appExit(void) {
/* Cleanup services. */
fsdevUnmountAll();
fsExit();
hidExit();
setsysExit();
setExit();
lrExit();
nsdevExit();
/* if (kernelAbove300()) { roDmntExit(); } */
ldrDmntExit();
pmdmntExit();
smExit();
}
int main(int argc, char **argv)
{
consoleDebugInit(debugDevice_SVC);
/* Initialize configuration manager. */
DmntConfigManager::RefreshConfiguration();
/* Start cheat manager. */
DmntCheatManager::InitializeCheatManager();
/* Nintendo uses four threads. Add a fifth for our cheat service. */
auto server_manager = new WaitableManager(5);
/* Create services. */
/* TODO: Implement rest of dmnt:- in ams.tma development branch. */
/* server_manager->AddWaitable(new ServiceServer<DebugMonitorService>("dmnt:-", 4)); */
server_manager->AddWaitable(new ServiceServer<DmntCheatService>("dmnt:cht", 1));
/* Loop forever, servicing our services. */
server_manager->Process();
delete server_manager;
return 0;
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <switch.h>
#include <stratosphere.hpp>
static constexpr u32 Module_Dmnt = 13;
static constexpr Result ResultDmntUnknown = MAKERESULT(Module_Dmnt, 1);
static constexpr Result ResultDmntDebuggingDisabled = MAKERESULT(Module_Dmnt, 2);
static constexpr Result ResultDmntCheatNotAttached = MAKERESULT(Module_Dmnt, 6500);
static constexpr Result ResultDmntCheatNullBuffer = MAKERESULT(Module_Dmnt, 6501);
static constexpr Result ResultDmntCheatInvalidBuffer = MAKERESULT(Module_Dmnt, 6502);
static constexpr Result ResultDmntCheatUnknownChtId = MAKERESULT(Module_Dmnt, 6503);
static constexpr Result ResultDmntCheatOutOfCheats = MAKERESULT(Module_Dmnt, 6504);
static constexpr Result ResultDmntCheatInvalidCheat = MAKERESULT(Module_Dmnt, 6505);
static constexpr Result ResultDmntCheatCannotDisableMasterCheat = MAKERESULT(Module_Dmnt, 6505);
static constexpr Result ResultDmntCheatInvalidFreezeWidth = MAKERESULT(Module_Dmnt, 6600);
static constexpr Result ResultDmntCheatAddressAlreadyFrozen = MAKERESULT(Module_Dmnt, 6601);
static constexpr Result ResultDmntCheatAddressNotFrozen = MAKERESULT(Module_Dmnt, 6602);
static constexpr Result ResultDmntCheatTooManyFrozenAddresses = MAKERESULT(Module_Dmnt, 6603);
static constexpr Result ResultDmntCheatVmInvalidCondDepth = MAKERESULT(Module_Dmnt, 6700);

View File

@@ -0,0 +1,150 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <switch.h>
#include <stratosphere.hpp>
enum DmntCmd {
DebugMonitor_Cmd_BreakDebugProcess = 0,
DebugMonitor_Cmd_TerminateDebugProcess = 1,
DebugMonitor_Cmd_CloseHandle = 2,
DebugMonitor_Cmd_LoadImage = 3,
DebugMonitor_Cmd_GetProcessId = 4,
DebugMonitor_Cmd_GetProcessHandle = 5,
DebugMonitor_Cmd_WaitSynchronization = 6,
DebugMonitor_Cmd_GetDebugEvent = 7,
DebugMonitor_Cmd_GetProcessModuleInfo = 8,
DebugMonitor_Cmd_GetProcessList = 9,
DebugMonitor_Cmd_GetThreadList = 10,
DebugMonitor_Cmd_GetDebugThreadContext = 11,
DebugMonitor_Cmd_ContinueDebugEvent = 12,
DebugMonitor_Cmd_ReadDebugProcessMemory = 13,
DebugMonitor_Cmd_WriteDebugProcessMemory = 14,
DebugMonitor_Cmd_SetDebugThreadContext = 15,
DebugMonitor_Cmd_GetDebugThreadParam = 16,
DebugMonitor_Cmd_InitializeThreadInfo = 17,
DebugMonitor_Cmd_SetHardwareBreakPoint = 18,
DebugMonitor_Cmd_QueryDebugProcessMemory = 19,
DebugMonitor_Cmd_GetProcessMemoryDetails = 20,
DebugMonitor_Cmd_AttachByProgramId = 21,
DebugMonitor_Cmd_AttachOnLaunch = 22,
DebugMonitor_Cmd_GetDebugMonitorProcessId = 23,
DebugMonitor_Cmd_GetJitDebugProcessList = 25,
DebugMonitor_Cmd_CreateCoreDump = 26,
DebugMonitor_Cmd_GetAllDebugThreadInfo = 27,
DebugMonitor_Cmd_TargetIO_FileOpen = 29,
DebugMonitor_Cmd_TargetIO_FileClose = 30,
DebugMonitor_Cmd_TargetIO_FileRead = 31,
DebugMonitor_Cmd_TargetIO_FileWrite = 32,
DebugMonitor_Cmd_TargetIO_FileSetAttributes = 33,
DebugMonitor_Cmd_TargetIO_FileGetInformation = 34,
DebugMonitor_Cmd_TargetIO_FileSetTime = 35,
DebugMonitor_Cmd_TargetIO_FileSetSize = 36,
DebugMonitor_Cmd_TargetIO_FileDelete = 37,
DebugMonitor_Cmd_TargetIO_FileMove = 38,
DebugMonitor_Cmd_TargetIO_DirectoryCreate = 39,
DebugMonitor_Cmd_TargetIO_DirectoryDelete = 40,
DebugMonitor_Cmd_TargetIO_DirectoryRename = 41,
DebugMonitor_Cmd_TargetIO_DirectoryGetCount = 42,
DebugMonitor_Cmd_TargetIO_DirectoryOpen = 43,
DebugMonitor_Cmd_TargetIO_DirectoryGetNext = 44,
DebugMonitor_Cmd_TargetIO_DirectoryClose = 45,
DebugMonitor_Cmd_TargetIO_GetFreeSpace = 46,
DebugMonitor_Cmd_TargetIO_GetVolumeInformation = 47,
DebugMonitor_Cmd_InitiateCoreDump = 48,
DebugMonitor_Cmd_ContinueCoreDump = 49,
DebugMonitor_Cmd_AddTTYToCoreDump = 50,
DebugMonitor_Cmd_AddImageToCoreDump = 51,
DebugMonitor_Cmd_CloseCoreDump = 52,
DebugMonitor_Cmd_CancelAttach = 53,
};
class DebugMonitorService final : public IServiceObject {
private:
Result BreakDebugProcess(Handle debug_hnd);
Result TerminateDebugProcess(Handle debug_hnd);
Result CloseHandle(Handle debug_hnd);
Result GetProcessId(Out<u64> out_pid, Handle hnd);
Result GetProcessHandle(Out<Handle> out_hnd, u64 pid);
Result WaitSynchronization(Handle hnd, u64 ns);
Result TargetIO_FileOpen(OutBuffer<u64> out_hnd, InBuffer<char> path, int open_mode, u32 create_mode);
Result TargetIO_FileClose(InBuffer<u64> hnd);
Result TargetIO_FileRead(InBuffer<u64> hnd, OutBuffer<u8, BufferType_Type1> out_data, Out<u32> out_read, u64 offset);
Result TargetIO_FileWrite(InBuffer<u64> hnd, InBuffer<u8, BufferType_Type1> data, Out<u32> out_written, u64 offset);
Result TargetIO_FileSetAttributes(InBuffer<char> path, InBuffer<u8> attributes);
Result TargetIO_FileGetInformation(InBuffer<char> path, OutBuffer<u64> out_info, Out<int> is_directory);
Result TargetIO_FileSetTime(InBuffer<char> path, u64 create, u64 access, u64 modify);
Result TargetIO_FileSetSize(InBuffer<char> path, u64 size);
Result TargetIO_FileDelete(InBuffer<char> path);
Result TargetIO_FileMove(InBuffer<char> path0, InBuffer<char> path1);
public:
DEFINE_SERVICE_DISPATCH_TABLE {
MakeServiceCommandMeta<DebugMonitor_Cmd_BreakDebugProcess, &DebugMonitorService::BreakDebugProcess>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_TerminateDebugProcess, &DebugMonitorService::TerminateDebugProcess>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_CloseHandle, &DebugMonitorService::CloseHandle>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_LoadImage, &DebugMonitorService::LoadImage>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_GetProcessId, &DebugMonitorService::GetProcessId>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_GetProcessHandle, &DebugMonitorService::GetProcessHandle>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_WaitSynchronization, &DebugMonitorService::WaitSynchronization>(),
//MakeServiceCommandMeta<DebugMonitor_Cmd_GetDebugEvent, &DebugMonitorService::GetDebugEvent>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_GetProcessModuleInfo, &DebugMonitorService::GetProcessModuleInfo>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_GetProcessList, &DebugMonitorService::GetProcessList>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_GetThreadList, &DebugMonitorService::GetThreadList>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_GetDebugThreadContext, &DebugMonitorService::GetDebugThreadContext>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_ContinueDebugEvent, &DebugMonitorService::ContinueDebugEvent>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_ReadDebugProcessMemory, &DebugMonitorService::ReadDebugProcessMemory>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_WriteDebugProcessMemory, &DebugMonitorService::WriteDebugProcessMemory>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_SetDebugThreadContext, &DebugMonitorService::SetDebugThreadContext>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_GetDebugThreadParam, &DebugMonitorService::GetDebugThreadParam>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_InitializeThreadInfo, &DebugMonitorService::InitializeThreadInfo>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_SetHardwareBreakPoint, &DebugMonitorService::SetHardwareBreakPoint>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_QueryDebugProcessMemory, &DebugMonitorService::QueryDebugProcessMemory>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_GetProcessMemoryDetails, &DebugMonitorService::GetProcessMemoryDetails>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_AttachByProgramId, &DebugMonitorService::AttachByProgramId>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_AttachOnLaunch, &DebugMonitorService::AttachOnLaunch>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_GetDebugMonitorProcessId, &DebugMonitorService::GetDebugMonitorProcessId>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_GetJitDebugProcessList, &DebugMonitorService::GetJitDebugProcessList>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_CreateCoreDump, &DebugMonitorService::CreateCoreDump>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_GetAllDebugThreadInfo, &DebugMonitorService::GetAllDebugThreadInfo>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_FileOpen, &DebugMonitorService::TargetIO_FileOpen>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_FileClose, &DebugMonitorService::TargetIO_FileClose>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_FileRead, &DebugMonitorService::TargetIO_FileRead>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_FileWrite, &DebugMonitorService::TargetIO_FileWrite>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_FileSetAttributes, &DebugMonitorService::TargetIO_FileSetAttributes>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_FileGetInformation, &DebugMonitorService::TargetIO_FileGetInformation>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_FileSetTime, &DebugMonitorService::TargetIO_FileSetTime>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_FileSetSize, &DebugMonitorService::TargetIO_FileSetSize>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_FileDelete, &DebugMonitorService::TargetIO_FileDelete>(),
MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_FileMove, &DebugMonitorService::TargetIO_FileMove>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_DirectoryCreate, &DebugMonitorService::TargetIO_DirectoryCreate>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_DirectoryDelete, &DebugMonitorService::TargetIO_DirectoryDelete>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_DirectoryRename, &DebugMonitorService::TargetIO_DirectoryRename>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_DirectoryGetCount, &DebugMonitorService::TargetIO_DirectoryGetCount>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_DirectoryOpen, &DebugMonitorService::TargetIO_DirectoryOpen>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_DirectoryGetNext, &DebugMonitorService::TargetIO_DirectoryGetNext>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_DirectoryClose, &DebugMonitorService::TargetIO_DirectoryClose>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_GetFreeSpace, &DebugMonitorService::TargetIO_GetFreeSpace>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_TargetIO_GetVolumeInformation, &DebugMonitorService::TargetIO_GetVolumeInformation>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_InitiateCoreDump, &DebugMonitorService::InitiateCoreDump>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_ContinueCoreDump, &DebugMonitorService::ContinueCoreDump>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_AddTTYToCoreDump, &DebugMonitorService::AddTTYToCoreDump>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_AddImageToCoreDump, &DebugMonitorService::AddImageToCoreDump>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_CloseCoreDump, &DebugMonitorService::CloseCoreDump>(),
// MakeServiceCommandMeta<DebugMonitor_Cmd_CancelAttach, &DebugMonitorService::CancelAttach>(),
};
};

View File

@@ -0,0 +1,52 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <switch.h>
#include "dmnt_service.hpp"
Result DebugMonitorService::BreakDebugProcess(Handle debug_hnd) {
/* Nintendo discards the output of this command, but we will return it. */
return svcBreakDebugProcess(debug_hnd);
}
Result DebugMonitorService::TerminateDebugProcess(Handle debug_hnd) {
/* Nintendo discards the output of this command, but we will return it. */
return svcTerminateDebugProcess(debug_hnd);
}
Result DebugMonitorService::CloseHandle(Handle debug_hnd) {
/* Nintendo discards the output of this command, but we will return it. */
/* This command is, entertainingly, also pretty unsafe in general... */
return svcCloseHandle(debug_hnd);
}
Result DebugMonitorService::GetProcessId(Out<u64> out_pid, Handle hnd) {
/* Nintendo discards the output of this command, but we will return it. */
return svcGetProcessId(out_pid.GetPointer(), hnd);
}
Result DebugMonitorService::GetProcessHandle(Out<Handle> out_hnd, u64 pid) {
Result rc = svcDebugActiveProcess(out_hnd.GetPointer(), pid);
if (rc == 0xF401) {
rc = 0x4B7;
}
return rc;
}
Result DebugMonitorService::WaitSynchronization(Handle hnd, u64 ns) {
/* Nintendo discards the output of this command, but we will return it. */
return svcWaitSynchronizationSingle(hnd, ns);
}

View File

@@ -0,0 +1,299 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unordered_map>
#include <switch.h>
#include "dmnt_service.hpp"
enum TIOCreateOption : u32 {
TIOCreateOption_CreateNew = 1,
TIOCreateOption_CreateAlways = 2,
TIOCreateOption_OpenExisting = 3,
TIOCreateOption_OpenAlways = 4,
TIOCreateOption_ResetSize = 5,
};
/* Nintendo uses actual pointers as file handles. We'll add a layer of indirection... */
static bool g_sd_initialized = false;
static HosMutex g_sd_lock;
static FsFileSystem g_sd_fs;
static HosMutex g_file_handle_lock;
static u64 g_cur_fd = 0;
static std::unordered_map<u64, FsFile> g_file_handles;
static Result EnsureSdInitialized() {
std::scoped_lock<HosMutex> lk(g_sd_lock);
if (g_sd_initialized) {
return 0;
}
Result rc = fsMountSdcard(&g_sd_fs);
if (R_SUCCEEDED(rc)) {
g_sd_initialized = true;
}
return rc;
}
static u64 GetFileHandle(FsFile f) {
std::scoped_lock<HosMutex> lk(g_file_handle_lock);
u64 fd = g_cur_fd++;
g_file_handles[fd] = f;
return fd;
}
static Result GetFileByHandle(FsFile *out, u64 handle) {
std::scoped_lock<HosMutex> lk(g_file_handle_lock);
if (g_file_handles.find(handle) != g_file_handles.end()) {
*out = g_file_handles[handle];
return 0;
}
return 0x2EE202;
}
static Result CloseFileByHandle(u64 handle) {
std::scoped_lock<HosMutex> lk(g_file_handle_lock);
if (g_file_handles.find(handle) != g_file_handles.end()) {
fsFileClose(&g_file_handles[handle]);
g_file_handles.erase(handle);
return 0;
}
return 0x2EE202;
}
static void FixPath(char *dst, size_t dst_size, InBuffer<char> &path) {
dst[dst_size - 1] = 0;
strncpy(dst, "/", dst_size - 1);
const char *src = path.buffer;
size_t src_idx = 0;
size_t dst_idx = 1;
while (src_idx < path.num_elements && (src[src_idx] == '/' || src[src_idx] == '\\')) {
src_idx++;
}
while (src_idx < path.num_elements && dst_idx < dst_size - 1 && src[src_idx] != 0) {
if (src[src_idx] == '\\') {
dst[dst_idx] = '/';
} else {
dst[dst_idx] = src[src_idx];
}
src_idx++;
dst_idx++;
}
if (dst_idx < dst_size) {
dst[dst_idx] = 0;
}
}
Result DebugMonitorService::TargetIO_FileOpen(OutBuffer<u64> out_hnd, InBuffer<char> path, int open_mode, u32 create_mode) {
if (out_hnd.num_elements != 1) {
return 0xF601;
}
Result rc = EnsureSdInitialized();
if (R_FAILED(rc)) {
return rc;
}
char fs_path[FS_MAX_PATH];
FixPath(fs_path, sizeof(fs_path), path);
if (create_mode == TIOCreateOption_CreateAlways) {
fsFsDeleteFile(&g_sd_fs, fs_path);
rc = fsFsCreateFile(&g_sd_fs, fs_path, 0, 0);
} else if (create_mode == TIOCreateOption_CreateNew) {
rc = fsFsCreateFile(&g_sd_fs, fs_path, 0, 0);
}
if (R_FAILED(rc)) {
return rc;
}
FsFile f;
rc = fsFsOpenFile(&g_sd_fs, fs_path, open_mode, &f);
if (R_FAILED(rc)) {
if (create_mode == TIOCreateOption_OpenAlways) {
fsFsCreateFile(&g_sd_fs, fs_path, 0, 0);
rc = fsFsOpenFile(&g_sd_fs, fs_path, open_mode, &f);
}
}
if (R_SUCCEEDED(rc)) {
if (create_mode == TIOCreateOption_ResetSize) {
rc = fsFileSetSize(&f, 0);
}
if (R_SUCCEEDED(rc)) {
out_hnd[0] = GetFileHandle(f);
} else {
fsFileClose(&f);
}
}
return rc;
}
Result DebugMonitorService::TargetIO_FileClose(InBuffer<u64> hnd) {
if (hnd.num_elements != 1) {
return 0xF601;
}
return CloseFileByHandle(hnd[0]);
}
Result DebugMonitorService::TargetIO_FileRead(InBuffer<u64> hnd, OutBuffer<u8, BufferType_Type1> out_data, Out<u32> out_read, u64 offset) {
if (hnd.num_elements != 1) {
return 0xF601;
}
FsFile f;
Result rc = GetFileByHandle(&f, hnd[0]);
if (R_FAILED(rc)) {
return rc;
}
size_t read = 0;
rc = fsFileRead(&f, offset, out_data.buffer, out_data.num_elements, &read);
out_read.SetValue(static_cast<u32>(read));
return rc;
}
Result DebugMonitorService::TargetIO_FileWrite(InBuffer<u64> hnd, InBuffer<u8, BufferType_Type1> data, Out<u32> out_written, u64 offset) {
if (hnd.num_elements != 1) {
return 0xF601;
}
FsFile f;
Result rc = GetFileByHandle(&f, hnd[0]);
if (R_FAILED(rc)) {
return rc;
}
rc = fsFileWrite(&f, offset, data.buffer, data.num_elements);
if (R_SUCCEEDED(rc)) {
out_written.SetValue(data.num_elements);
}
return rc;
}
Result DebugMonitorService::TargetIO_FileSetAttributes(InBuffer<char> path, InBuffer<u8> attributes) {
/* I don't really know why this command exists, Horizon doesn't allow you to set any attributes. */
/* N just returns 0x0 unconditionally here. */
return 0x0;
}
Result DebugMonitorService::TargetIO_FileGetInformation(InBuffer<char> path, OutBuffer<u64> out_info, Out<int> is_directory) {
if (out_info.num_elements != 4) {
return 0xF601;
}
Result rc = EnsureSdInitialized();
if (R_FAILED(rc)) {
return rc;
}
char fs_path[FS_MAX_PATH];
FixPath(fs_path, sizeof(fs_path), path);
for (size_t i = 0; i < out_info.num_elements; i++) {
out_info[i] = 0;
}
is_directory.SetValue(0);
FsFile f;
rc = fsFsOpenFile(&g_sd_fs, fs_path, FS_OPEN_READ, &f);
if (R_SUCCEEDED(rc)) {
ON_SCOPE_EXIT { fsFileClose(&f); };
/* N doesn't check this return code. */
fsFileGetSize(&f, &out_info[0]);
/* TODO: N does not call fsFsGetFileTimestampRaw here, but we possibly could. */
} else {
FsDir dir;
rc = fsFsOpenDirectory(&g_sd_fs, fs_path, FS_DIROPEN_FILE | FS_DIROPEN_DIRECTORY, &dir);
if (R_SUCCEEDED(rc)) {
fsDirClose(&dir);
is_directory.SetValue(1);
}
}
return rc;
}
Result DebugMonitorService::TargetIO_FileSetTime(InBuffer<char> path, u64 create, u64 access, u64 modify) {
/* This is another function that doesn't really need to exist, because Horizon doesn't let you set anything. */
return 0x0;
}
Result DebugMonitorService::TargetIO_FileSetSize(InBuffer<char> input, u64 size) {
/* Why does this function take in a path and not a file handle? */
/* We will try to be better than N, here. N only treats input as a path. */
if (input.num_elements == sizeof(u64)) {
FsFile f;
if (R_SUCCEEDED(GetFileByHandle(&f, reinterpret_cast<u64 *>(input.buffer)[0]))) {
return fsFileSetSize(&f, size);
}
}
Result rc = EnsureSdInitialized();
if (R_FAILED(rc)) {
return rc;
}
char fs_path[FS_MAX_PATH];
FixPath(fs_path, sizeof(fs_path), input);
FsFile f;
rc = fsFsOpenFile(&g_sd_fs, fs_path, FS_OPEN_WRITE, &f);
if (R_SUCCEEDED(rc)) {
rc = fsFileSetSize(&f, size);
fsFileClose(&f);
}
return rc;
}
Result DebugMonitorService::TargetIO_FileDelete(InBuffer<char> path) {
Result rc = EnsureSdInitialized();
if (R_FAILED(rc)) {
return rc;
}
char fs_path[FS_MAX_PATH];
FixPath(fs_path, sizeof(fs_path), path);
return fsFsDeleteFile(&g_sd_fs, fs_path);
}
Result DebugMonitorService::TargetIO_FileMove(InBuffer<char> path0, InBuffer<char> path1) {
Result rc = EnsureSdInitialized();
if (R_FAILED(rc)) {
return rc;
}
char fs_path0[FS_MAX_PATH];
char fs_path1[FS_MAX_PATH];
FixPath(fs_path0, sizeof(fs_path0), path0);
FixPath(fs_path1, sizeof(fs_path1), path1);
return fsFsRenameFile(&g_sd_fs, fs_path0, fs_path1);
}

View File

@@ -0,0 +1,269 @@
/* inih -- simple .INI file parser
inih is released under the New BSD license (see LICENSE.txt). Go to the project
home page for more info:
https://github.com/benhoyt/inih
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "ini.h"
#if !INI_USE_STACK
#include <stdlib.h>
#endif
#define MAX_SECTION 50
#define MAX_NAME 50
/* Used by ini_parse_string() to keep track of string parsing state. */
typedef struct {
const char* ptr;
size_t num_left;
} ini_parse_string_ctx;
/* Strip whitespace chars off end of given string, in place. Return s. */
static char* rstrip(char* s)
{
char* p = s + strlen(s);
while (p > s && isspace((unsigned char)(*--p)))
*p = '\0';
return s;
}
/* Return pointer to first non-whitespace char in given string. */
static char* lskip(const char* s)
{
while (*s && isspace((unsigned char)(*s)))
s++;
return (char*)s;
}
/* Return pointer to first char (of chars) or inline comment in given string,
or pointer to null at end of string if neither found. Inline comment must
be prefixed by a whitespace character to register as a comment. */
static char* find_chars_or_comment(const char* s, const char* chars)
{
#if INI_ALLOW_INLINE_COMMENTS
int was_space = 0;
while (*s && (!chars || !strchr(chars, *s)) &&
!(was_space && strchr(INI_INLINE_COMMENT_PREFIXES, *s))) {
was_space = isspace((unsigned char)(*s));
s++;
}
#else
while (*s && (!chars || !strchr(chars, *s))) {
s++;
}
#endif
return (char*)s;
}
/* Version of strncpy that ensures dest (size bytes) is null-terminated. */
static char* strncpy0(char* dest, const char* src, size_t size)
{
strncpy(dest, src, size - 1);
dest[size - 1] = '\0';
return dest;
}
/* See documentation in header file. */
int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler,
void* user)
{
/* Uses a fair bit of stack (use heap instead if you need to) */
#if INI_USE_STACK
char line[INI_MAX_LINE];
int max_line = INI_MAX_LINE;
#else
char* line;
int max_line = INI_INITIAL_ALLOC;
#endif
#if INI_ALLOW_REALLOC
char* new_line;
int offset;
#endif
char section[MAX_SECTION] = "";
char prev_name[MAX_NAME] = "";
char* start;
char* end;
char* name;
char* value;
int lineno = 0;
int error = 0;
#if !INI_USE_STACK
line = (char*)malloc(INI_INITIAL_ALLOC);
if (!line) {
return -2;
}
#endif
#if INI_HANDLER_LINENO
#define HANDLER(u, s, n, v) handler(u, s, n, v, lineno)
#else
#define HANDLER(u, s, n, v) handler(u, s, n, v)
#endif
/* Scan through stream line by line */
while (reader(line, max_line, stream) != NULL) {
#if INI_ALLOW_REALLOC
offset = strlen(line);
while (offset == max_line - 1 && line[offset - 1] != '\n') {
max_line *= 2;
if (max_line > INI_MAX_LINE)
max_line = INI_MAX_LINE;
new_line = realloc(line, max_line);
if (!new_line) {
free(line);
return -2;
}
line = new_line;
if (reader(line + offset, max_line - offset, stream) == NULL)
break;
if (max_line >= INI_MAX_LINE)
break;
offset += strlen(line + offset);
}
#endif
lineno++;
start = line;
#if INI_ALLOW_BOM
if (lineno == 1 && (unsigned char)start[0] == 0xEF &&
(unsigned char)start[1] == 0xBB &&
(unsigned char)start[2] == 0xBF) {
start += 3;
}
#endif
start = lskip(rstrip(start));
if (strchr(INI_START_COMMENT_PREFIXES, *start)) {
/* Start-of-line comment */
}
#if INI_ALLOW_MULTILINE
else if (*prev_name && *start && start > line) {
/* Non-blank line with leading whitespace, treat as continuation
of previous name's value (as per Python configparser). */
if (!HANDLER(user, section, prev_name, start) && !error)
error = lineno;
}
#endif
else if (*start == '[') {
/* A "[section]" line */
end = find_chars_or_comment(start + 1, "]");
if (*end == ']') {
*end = '\0';
strncpy0(section, start + 1, sizeof(section));
*prev_name = '\0';
}
else if (!error) {
/* No ']' found on section line */
error = lineno;
}
}
else if (*start) {
/* Not a comment, must be a name[=:]value pair */
end = find_chars_or_comment(start, "=:");
if (*end == '=' || *end == ':') {
*end = '\0';
name = rstrip(start);
value = end + 1;
#if INI_ALLOW_INLINE_COMMENTS
end = find_chars_or_comment(value, NULL);
if (*end)
*end = '\0';
#endif
value = lskip(value);
rstrip(value);
/* Valid name[=:]value pair found, call handler */
strncpy0(prev_name, name, sizeof(prev_name));
if (!HANDLER(user, section, name, value) && !error)
error = lineno;
}
else if (!error) {
/* No '=' or ':' found on name[=:]value line */
error = lineno;
}
}
#if INI_STOP_ON_FIRST_ERROR
if (error)
break;
#endif
}
#if !INI_USE_STACK
free(line);
#endif
return error;
}
/* See documentation in header file. */
int ini_parse_file(FILE* file, ini_handler handler, void* user)
{
return ini_parse_stream((ini_reader)fgets, file, handler, user);
}
/* See documentation in header file. */
int ini_parse(const char* filename, ini_handler handler, void* user)
{
FILE* file;
int error;
file = fopen(filename, "r");
if (!file)
return -1;
error = ini_parse_file(file, handler, user);
fclose(file);
return error;
}
/* An ini_reader function to read the next line from a string buffer. This
is the fgets() equivalent used by ini_parse_string(). */
static char* ini_reader_string(char* str, int num, void* stream) {
ini_parse_string_ctx* ctx = (ini_parse_string_ctx*)stream;
const char* ctx_ptr = ctx->ptr;
size_t ctx_num_left = ctx->num_left;
char* strp = str;
char c;
if (ctx_num_left == 0 || num < 2)
return NULL;
while (num > 1 && ctx_num_left != 0) {
c = *ctx_ptr++;
ctx_num_left--;
*strp++ = c;
if (c == '\n')
break;
num--;
}
*strp = '\0';
ctx->ptr = ctx_ptr;
ctx->num_left = ctx_num_left;
return str;
}
/* See documentation in header file. */
int ini_parse_string(const char* string, ini_handler handler, void* user) {
ini_parse_string_ctx ctx;
ctx.ptr = string;
ctx.num_left = strlen(string);
return ini_parse_stream((ini_reader)ini_reader_string, &ctx, handler,
user);
}

View File

@@ -0,0 +1,130 @@
/* inih -- simple .INI file parser
inih is released under the New BSD license (see LICENSE.txt). Go to the project
home page for more info:
https://github.com/benhoyt/inih
*/
#ifndef __INI_H__
#define __INI_H__
/* Make this header file easier to include in C++ code */
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
/* Nonzero if ini_handler callback should accept lineno parameter. */
#ifndef INI_HANDLER_LINENO
#define INI_HANDLER_LINENO 0
#endif
/* Typedef for prototype of handler function. */
#if INI_HANDLER_LINENO
typedef int (*ini_handler)(void* user, const char* section,
const char* name, const char* value,
int lineno);
#else
typedef int (*ini_handler)(void* user, const char* section,
const char* name, const char* value);
#endif
/* Typedef for prototype of fgets-style reader function. */
typedef char* (*ini_reader)(char* str, int num, void* stream);
/* Parse given INI-style file. May have [section]s, name=value pairs
(whitespace stripped), and comments starting with ';' (semicolon). Section
is "" if name=value pair parsed before any section heading. name:value
pairs are also supported as a concession to Python's configparser.
For each name=value pair parsed, call handler function with given user
pointer as well as section, name, and value (data only valid for duration
of handler call). Handler should return nonzero on success, zero on error.
Returns 0 on success, line number of first error on parse error (doesn't
stop on first error), -1 on file open error, or -2 on memory allocation
error (only when INI_USE_STACK is zero).
*/
int ini_parse(const char* filename, ini_handler handler, void* user);
/* Same as ini_parse(), but takes a FILE* instead of filename. This doesn't
close the file when it's finished -- the caller must do that. */
int ini_parse_file(FILE* file, ini_handler handler, void* user);
/* Same as ini_parse(), but takes an ini_reader function pointer instead of
filename. Used for implementing custom or string-based I/O (see also
ini_parse_string). */
int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler,
void* user);
/* Same as ini_parse(), but takes a zero-terminated string with the INI data
instead of a file. Useful for parsing INI data from a network socket or
already in memory. */
int ini_parse_string(const char* string, ini_handler handler, void* user);
/* Nonzero to allow multi-line value parsing, in the style of Python's
configparser. If allowed, ini_parse() will call the handler with the same
name for each subsequent line parsed. */
#ifndef INI_ALLOW_MULTILINE
#define INI_ALLOW_MULTILINE 1
#endif
/* Nonzero to allow a UTF-8 BOM sequence (0xEF 0xBB 0xBF) at the start of
the file. See http://code.google.com/p/inih/issues/detail?id=21 */
#ifndef INI_ALLOW_BOM
#define INI_ALLOW_BOM 1
#endif
/* Chars that begin a start-of-line comment. Per Python configparser, allow
both ; and # comments at the start of a line by default. */
#ifndef INI_START_COMMENT_PREFIXES
#define INI_START_COMMENT_PREFIXES ";#"
#endif
/* Nonzero to allow inline comments (with valid inline comment characters
specified by INI_INLINE_COMMENT_PREFIXES). Set to 0 to turn off and match
Python 3.2+ configparser behaviour. */
#ifndef INI_ALLOW_INLINE_COMMENTS
#define INI_ALLOW_INLINE_COMMENTS 1
#endif
#ifndef INI_INLINE_COMMENT_PREFIXES
#define INI_INLINE_COMMENT_PREFIXES ";"
#endif
/* Nonzero to use stack for line buffer, zero to use heap (malloc/free). */
#ifndef INI_USE_STACK
#define INI_USE_STACK 1
#endif
/* Maximum line length for any line in INI file (stack or heap). Note that
this must be 3 more than the longest line (due to '\r', '\n', and '\0'). */
#ifndef INI_MAX_LINE
#define INI_MAX_LINE 200
#endif
/* Nonzero to allow heap line buffer to grow via realloc(), zero for a
fixed-size buffer of INI_MAX_LINE bytes. Only applies if INI_USE_STACK is
zero. */
#ifndef INI_ALLOW_REALLOC
#define INI_ALLOW_REALLOC 0
#endif
/* Initial size in bytes for heap line buffer. Only applies if INI_USE_STACK
is zero. */
#ifndef INI_INITIAL_ALLOC
#define INI_INITIAL_ALLOC 200
#endif
/* Stop parsing on first error (default is to keep parsing). */
#ifndef INI_STOP_ON_FIRST_ERROR
#define INI_STOP_ON_FIRST_ERROR 0
#endif
#ifdef __cplusplus
}
#endif
#endif /* __INI_H__ */

View File

@@ -0,0 +1,66 @@
/*
* Copyright (c) 2018 Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <switch.h>
#include "pm_shim.h"
/* Atmosphere extension commands. */
Result pmdmntAtmosphereGetProcessInfo(Handle* out, u64 *tid_out, FsStorageId *sid_out, u64 pid) {
IpcCommand c;
ipcInitialize(&c);
Service *s = pmdmntGetServiceSession();
struct {
u64 magic;
u64 cmd_id;
u64 pid;
} *raw;
raw = serviceIpcPrepareHeader(s, &c, sizeof(*raw));
raw->magic = SFCI_MAGIC;
raw->cmd_id = 65000;
raw->pid = pid;
Result rc = serviceIpcDispatch(s);
if (R_SUCCEEDED(rc)) {
IpcParsedCommand r;
struct {
u64 magic;
u64 result;
u64 title_id;
FsStorageId storage_id;
} *resp;
serviceIpcParse(s, &r, sizeof(*resp));
resp = r.Raw;
rc = resp->result;
if (R_SUCCEEDED(rc)) {
if (out) {
*out = r.Handles[0];
} else {
svcCloseHandle(r.Handles[0]);
}
if (tid_out) *tid_out = resp->title_id;
if (sid_out) *sid_out = resp->storage_id;
}
}
return rc;
}

View File

@@ -0,0 +1,19 @@
/**
* @file pm_shim.h
* @brief Process Management (pm) IPC wrapper.
* @author SciresM
* @copyright libnx Authors
*/
#pragma once
#include <switch.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Atmosphere extension commands. */
Result pmdmntAtmosphereGetProcessInfo(Handle* out, u64 *tid_out, FsStorageId *sid_out, u64 pid);
#ifdef __cplusplus
}
#endif

View File

@@ -39,7 +39,6 @@ static void RunTaskThreadFunc(void *arg) {
}
/* Finish. */
svcExitThread();
}
static void RunTask(IFatalTask *task, u32 stack_size = 0x4000) {

View File

@@ -117,8 +117,12 @@ Result ShowFatalTask::PrepareScreenForDrawing() {
if (R_FAILED((rc = viGetDisplayLogicalResolution(&this->display, &display_width, &display_height)))) {
return rc;
}
if (R_FAILED((rc = viSetDisplayMagnification(&this->display, 0, 0, display_width, display_height)))) {
return rc;
/* viSetDisplayMagnification was added in 3.0.0. */
if (GetRuntimeFirmwareVersion() >= FirmwareVersion_300) {
if (R_FAILED((rc = viSetDisplayMagnification(&this->display, 0, 0, display_width, display_height)))) {
return rc;
}
}
/* Create layer to draw to. */

View File

@@ -38,10 +38,26 @@ static bool g_has_initialized_fs_dev = false;
/* Default to Key R, hold disables override, HBL at atmosphere/hbl.nsp. */
static bool g_mounted_hbl_nsp = false;
static char g_hbl_sd_path[FS_MAX_PATH+1] = "@Sdcard:/atmosphere/hbl.nsp\x00";
static u64 g_override_key_combination = KEY_R;
static bool g_override_by_default = true;
static u64 g_override_hbl_tid = 0x010000000000100D;
static bool g_override_any_app = false;
static OverrideKey g_default_override_key = {
.key_combination = KEY_L,
.override_by_default = true
};
struct HblOverrideConfig {
OverrideKey override_key;
u64 title_id;
bool override_any_app;
};
static HblOverrideConfig g_hbl_override_config = {
.override_key = {
.key_combination = KEY_R,
.override_by_default = true
},
.title_id = 0x010000000000100D,
.override_any_app = false
};
/* Static buffer for loader.ini contents at runtime. */
static char g_config_ini_data[0x800];
@@ -62,7 +78,7 @@ Result ContentManagement::MountCode(u64 tid, FsStorageId sid) {
RefreshConfigurationData();
}
if (ShouldOverrideContents(tid) && R_SUCCEEDED(MountCodeNspOnSd(tid))) {
if (ShouldOverrideContentsWithSD(tid) && R_SUCCEEDED(MountCodeNspOnSd(tid))) {
return 0x0;
}
@@ -204,72 +220,86 @@ void ContentManagement::SetCreatedTitle(u64 tid) {
}
}
static OverrideKey ParseOverrideKey(const char *value) {
OverrideKey cfg;
/* Parse on by default. */
if (value[0] == '!') {
cfg.override_by_default = true;
value++;
} else {
cfg.override_by_default = false;
}
/* Parse key combination. */
if (strcasecmp(value, "A") == 0) {
cfg.key_combination = KEY_A;
} else if (strcasecmp(value, "B") == 0) {
cfg.key_combination = KEY_B;
} else if (strcasecmp(value, "X") == 0) {
cfg.key_combination = KEY_X;
} else if (strcasecmp(value, "Y") == 0) {
cfg.key_combination = KEY_Y;
} else if (strcasecmp(value, "LS") == 0) {
cfg.key_combination = KEY_LSTICK;
} else if (strcasecmp(value, "RS") == 0) {
cfg.key_combination = KEY_RSTICK;
} else if (strcasecmp(value, "L") == 0) {
cfg.key_combination = KEY_L;
} else if (strcasecmp(value, "R") == 0) {
cfg.key_combination = KEY_R;
} else if (strcasecmp(value, "ZL") == 0) {
cfg.key_combination = KEY_ZL;
} else if (strcasecmp(value, "ZR") == 0) {
cfg.key_combination = KEY_ZR;
} else if (strcasecmp(value, "PLUS") == 0) {
cfg.key_combination = KEY_PLUS;
} else if (strcasecmp(value, "MINUS") == 0) {
cfg.key_combination = KEY_MINUS;
} else if (strcasecmp(value, "DLEFT") == 0) {
cfg.key_combination = KEY_DLEFT;
} else if (strcasecmp(value, "DUP") == 0) {
cfg.key_combination = KEY_DUP;
} else if (strcasecmp(value, "DRIGHT") == 0) {
cfg.key_combination = KEY_DRIGHT;
} else if (strcasecmp(value, "DDOWN") == 0) {
cfg.key_combination = KEY_DDOWN;
} else if (strcasecmp(value, "SL") == 0) {
cfg.key_combination = KEY_SL;
} else if (strcasecmp(value, "SR") == 0) {
cfg.key_combination = KEY_SR;
} else {
cfg.key_combination = 0;
}
return cfg;
}
static int LoaderIniHandler(void *user, const char *section, const char *name, const char *value) {
/* Taken and modified, with love, from Rajkosto's implementation. */
if (strcasecmp(section, "config") == 0) {
if (strcasecmp(name, "hbl_tid") == 0) {
if (strcasecmp(section, "hbl_config") == 0) {
if (strcasecmp(name, "title_id") == 0) {
if (strcasecmp(value, "app") == 0) {
g_override_any_app = true;
g_hbl_override_config.override_any_app = true;
}
else {
u64 override_tid = strtoul(value, NULL, 16);
if (override_tid != 0) {
g_override_hbl_tid = override_tid;
g_hbl_override_config.title_id = override_tid;
}
}
} else if (strcasecmp(name, "hbl_path") == 0) {
} else if (strcasecmp(name, "path") == 0) {
while (*value == '/' || *value == '\\') {
value++;
}
snprintf(g_hbl_sd_path, FS_MAX_PATH, "@Sdcard:/%s", value);
g_hbl_sd_path[FS_MAX_PATH] = 0;
} else if (strcasecmp(name, "override_key") == 0) {
if (value[0] == '!') {
g_override_by_default = true;
value++;
} else {
g_override_by_default = false;
}
if (strcasecmp(value, "A") == 0) {
g_override_key_combination = KEY_A;
} else if (strcasecmp(value, "B") == 0) {
g_override_key_combination = KEY_B;
} else if (strcasecmp(value, "X") == 0) {
g_override_key_combination = KEY_X;
} else if (strcasecmp(value, "Y") == 0) {
g_override_key_combination = KEY_Y;
} else if (strcasecmp(value, "LS") == 0) {
g_override_key_combination = KEY_LSTICK;
} else if (strcasecmp(value, "RS") == 0) {
g_override_key_combination = KEY_RSTICK;
} else if (strcasecmp(value, "L") == 0) {
g_override_key_combination = KEY_L;
} else if (strcasecmp(value, "R") == 0) {
g_override_key_combination = KEY_R;
} else if (strcasecmp(value, "ZL") == 0) {
g_override_key_combination = KEY_ZL;
} else if (strcasecmp(value, "ZR") == 0) {
g_override_key_combination = KEY_ZR;
} else if (strcasecmp(value, "PLUS") == 0) {
g_override_key_combination = KEY_PLUS;
} else if (strcasecmp(value, "MINUS") == 0) {
g_override_key_combination = KEY_MINUS;
} else if (strcasecmp(value, "DLEFT") == 0) {
g_override_key_combination = KEY_DLEFT;
} else if (strcasecmp(value, "DUP") == 0) {
g_override_key_combination = KEY_DUP;
} else if (strcasecmp(value, "DRIGHT") == 0) {
g_override_key_combination = KEY_DRIGHT;
} else if (strcasecmp(value, "DDOWN") == 0) {
g_override_key_combination = KEY_DDOWN;
} else if (strcasecmp(value, "SL") == 0) {
g_override_key_combination = KEY_SL;
} else if (strcasecmp(value, "SR") == 0) {
g_override_key_combination = KEY_SR;
} else {
g_override_key_combination = 0;
}
g_hbl_override_config.override_key = ParseOverrideKey(value);
}
} else if (strcasecmp(section, "default_config") == 0) {
if (strcasecmp(name, "override_key") == 0) {
g_default_override_key = ParseOverrideKey(value);
}
} else {
return 0;
@@ -277,7 +307,21 @@ static int LoaderIniHandler(void *user, const char *section, const char *name, c
return 1;
}
void ContentManagement::RefreshConfigurationData() {
static int LoaderTitleSpecificIniHandler(void *user, const char *section, const char *name, const char *value) {
/* We'll output an override key when relevant. */
OverrideKey *user_cfg = reinterpret_cast<OverrideKey *>(user);
if (strcasecmp(section, "override_config") == 0) {
if (strcasecmp(name, "override_key") == 0) {
*user_cfg = ParseOverrideKey(value);
}
} else {
return 0;
}
return 1;
}
void ContentManagement::RefreshConfigurationData() {
FILE *config = fopen("sdmc:/atmosphere/loader.ini", "r");
if (config == NULL) {
return;
@@ -309,18 +353,56 @@ void ContentManagement::TryMountSdCard() {
}
}
bool ContentManagement::ShouldReplaceWithHBL(u64 tid) {
return g_mounted_hbl_nsp && ((g_override_any_app && IsApplicationTid(tid)) || (!g_override_any_app && tid == g_override_hbl_tid));
static bool IsHBLTitleId(u64 tid) {
return ((g_hbl_override_config.override_any_app && IsApplicationTid(tid)) || (!g_hbl_override_config.override_any_app && tid == g_hbl_override_config.title_id));
}
bool ContentManagement::ShouldOverrideContents(u64 tid) {
if (tid >= 0x0100000000001000 && HasCreatedTitle(0x0100000000001000)) {
u64 kDown = 0;
bool keys_triggered = (R_SUCCEEDED(HidManagement::GetKeysDown(&kDown)) && ((kDown & g_override_key_combination) != 0));
return g_has_initialized_fs_dev && (g_override_by_default ^ keys_triggered);
OverrideKey ContentManagement::GetTitleOverrideKey(u64 tid) {
OverrideKey cfg = g_default_override_key;
char path[FS_MAX_PATH+1] = {0};
snprintf(path, FS_MAX_PATH, "sdmc:/atmosphere/titles/%016lx/config.ini", tid);
FILE *config = fopen(path, "r");
if (config != NULL) {
ON_SCOPE_EXIT { fclose(config); };
/* Parse current title ini. */
ini_parse_file(config, LoaderTitleSpecificIniHandler, &cfg);
}
return cfg;
}
static bool ShouldOverrideContents(OverrideKey *cfg) {
u64 kDown = 0;
bool keys_triggered = (R_SUCCEEDED(HidManagement::GetKeysDown(&kDown)) && ((kDown & cfg->key_combination) != 0));
return g_has_initialized_fs_dev && (cfg->override_by_default ^ keys_triggered);
}
bool ContentManagement::ShouldOverrideContentsWithHBL(u64 tid) {
if (g_mounted_hbl_nsp && tid >= 0x0100000000001000 && HasCreatedTitle(0x0100000000001000)) {
/* Return whether we should override contents with HBL. */
return IsHBLTitleId(tid) && ShouldOverrideContents(&g_hbl_override_config.override_key);
} else {
/* Always redirect before qlaunch. */
return g_has_initialized_fs_dev;
/* Don't override if we failed to mount HBL or haven't launched qlaunch. */
return false;
}
}
bool ContentManagement::ShouldOverrideContentsWithSD(u64 tid) {
if (g_has_initialized_fs_dev) {
if (tid >= 0x0100000000001000 && HasCreatedTitle(0x0100000000001000)) {
/* Check whether we should override with non-HBL. */
OverrideKey title_cfg = GetTitleOverrideKey(tid);
return ShouldOverrideContents(&title_cfg);
} else {
/* Always redirect before qlaunch. */
return true;
}
} else {
/* Never redirect before we can do so. */
return false;
}
}

View File

@@ -19,6 +19,11 @@
#include "ldr_registration.hpp"
struct OverrideKey {
u64 key_combination;
bool override_by_default;
};
class ContentManagement {
public:
static Result MountCode(u64 tid, FsStorageId sid);
@@ -37,8 +42,9 @@ class ContentManagement {
static void RefreshConfigurationData();
static void TryMountSdCard();
static bool ShouldReplaceWithHBL(u64 tid);
static bool ShouldOverrideContents(u64 tid);
static OverrideKey GetTitleOverrideKey(u64 tid);
static bool ShouldOverrideContentsWithSD(u64 tid);
static bool ShouldOverrideContentsWithHBL(u64 tid);
/* SetExternalContentSource extension */
class ExternalContentSource {

View File

@@ -63,16 +63,21 @@ FILE *NpdmUtils::OpenNpdm(u64 title_id) {
if ((ecs = ContentManagement::GetExternalContentSource(title_id)) != nullptr) {
return OpenNpdmFromECS(ecs);
}
if (ContentManagement::ShouldOverrideContents(title_id)) {
if (ContentManagement::ShouldReplaceWithHBL(title_id)) {
return OpenNpdmFromHBL();
}
/* First, check HBL. */
if (ContentManagement::ShouldOverrideContentsWithHBL(title_id)) {
return OpenNpdmFromHBL();
}
/* Next, check other override. */
if (ContentManagement::ShouldOverrideContentsWithSD(title_id)) {
FILE *f_out = OpenNpdmFromSdCard(title_id);
if (f_out != NULL) {
return f_out;
}
}
/* Last resort: real exefs. */
return OpenNpdmFromExeFS();
}
@@ -193,8 +198,7 @@ Result NpdmUtils::LoadNpdm(u64 tid, NpdmInfo *out) {
info->acid->title_id_range_max = tid;
info->aci0->title_id = tid;
if (ContentManagement::ShouldOverrideContents(tid) && ContentManagement::ShouldReplaceWithHBL(tid)
&& R_SUCCEEDED(LoadNpdmInternal(OpenNpdmFromExeFS(), &g_original_npdm_cache))) {
if (ContentManagement::ShouldOverrideContentsWithHBL(tid) && R_SUCCEEDED(LoadNpdmInternal(OpenNpdmFromExeFS(), &g_original_npdm_cache))) {
NpdmInfo *original_info = &g_original_npdm_cache.info;
/* Fix pool partition. */
if (kernelAbove500()) {

View File

@@ -71,11 +71,14 @@ FILE *NsoUtils::OpenNso(unsigned int index, u64 title_id) {
if ((ecs = ContentManagement::GetExternalContentSource(title_id)) != nullptr) {
return OpenNsoFromECS(index, ecs);
}
/* First, check HBL. */
if (ContentManagement::ShouldOverrideContentsWithHBL(title_id)) {
return OpenNsoFromHBL(index);
}
if (ContentManagement::ShouldOverrideContents(title_id)) {
if (ContentManagement::ShouldReplaceWithHBL(title_id)) {
return OpenNsoFromHBL(index);
}
/* Next, check secondary override. */
if (ContentManagement::ShouldOverrideContentsWithSD(title_id)) {
FILE *f_out = OpenNsoFromSdCard(index, title_id);
if (f_out != NULL) {
return f_out;
@@ -83,6 +86,8 @@ FILE *NsoUtils::OpenNso(unsigned int index, u64 title_id) {
return NULL;
}
}
/* Finally, default to exefs. */
return OpenNsoFromExeFS(index);
}

View File

@@ -27,19 +27,7 @@
#include "pm_registration.hpp"
#include "pm_boot_mode.hpp"
static std::vector<Boot2KnownTitleId> g_boot2_titles;
static void ClearLaunchedTitles() {
g_boot2_titles.clear();
}
static void SetLaunchedTitle(Boot2KnownTitleId title_id) {
g_boot2_titles.push_back(title_id);
}
static bool HasLaunchedTitle(Boot2KnownTitleId title_id) {
return std::find(g_boot2_titles.begin(), g_boot2_titles.end(), title_id) != g_boot2_titles.end();
}
static std::vector<Boot2KnownTitleId> g_launched_titles;
static bool IsHexadecimal(const char *str) {
while (*str) {
@@ -52,8 +40,20 @@ static bool IsHexadecimal(const char *str) {
return true;
}
static bool HasLaunchedTitle(Boot2KnownTitleId title_id) {
return std::find(g_launched_titles.begin(), g_launched_titles.end(), title_id) != g_launched_titles.end();
}
static void SetLaunchedTitle(Boot2KnownTitleId title_id) {
g_launched_titles.push_back(title_id);
}
static void ClearLaunchedTitles() {
g_launched_titles.clear();
}
static void LaunchTitle(Boot2KnownTitleId title_id, FsStorageId storage_id, u32 launch_flags, u64 *pid) {
u64 local_pid;
u64 local_pid = 0;
/* Don't launch a title twice during boot2. */
if (HasLaunchedTitle(title_id)) {
@@ -64,15 +64,15 @@ static void LaunchTitle(Boot2KnownTitleId title_id, FsStorageId storage_id, u32
switch (rc) {
case 0xCE01:
/* Out of resource! */
/* TODO: Panic(). */
std::abort();
break;
case 0xDE01:
/* Out of memory! */
/* TODO: Panic(). */
std::abort();
break;
case 0xD001:
/* Limit Reached! */
/* TODO: Panic(). */
std::abort();
break;
default:
/* We don't care about other issues. */
@@ -235,8 +235,12 @@ void EmbeddedBoot2::Main() {
/* Launch usb. */
LaunchTitle(Boot2KnownTitleId::usb, FsStorageId_NandSystem, 0, NULL);
/* Launch tma. */
LaunchTitle(Boot2KnownTitleId::tma, FsStorageId_NandSystem, 0, NULL);
/* Launch Atmosphere dmnt, using FsStorageId_None to force SD card boot. */
LaunchTitle(Boot2KnownTitleId::dmnt, FsStorageId_None, 0, NULL);
/* Launch default programs. */
for (auto &launch_program : g_additional_launch_programs) {
@@ -251,7 +255,10 @@ void EmbeddedBoot2::Main() {
if (titles_dir != NULL) {
while ((ent = readdir(titles_dir)) != NULL) {
if (strlen(ent->d_name) == 0x10 && IsHexadecimal(ent->d_name)) {
u64 title_id = strtoul(ent->d_name, NULL, 16);
Boot2KnownTitleId title_id = (Boot2KnownTitleId)strtoul(ent->d_name, NULL, 16);
if (HasLaunchedTitle(title_id)) {
continue;
}
char title_path[FS_MAX_PATH] = {0};
strcpy(title_path, "sdmc:/atmosphere/titles/");
strcat(title_path, ent->d_name);
@@ -259,7 +266,7 @@ void EmbeddedBoot2::Main() {
FILE *f_flag = fopen(title_path, "rb");
if (f_flag != NULL) {
fclose(f_flag);
LaunchTitle((Boot2KnownTitleId)title_id, FsStorageId_None, 0, NULL);
LaunchTitle(title_id, FsStorageId_None, 0, NULL);
} else {
/* TODO: Deprecate this in the future. */
memset(title_path, 0, FS_MAX_PATH);
@@ -269,13 +276,16 @@ void EmbeddedBoot2::Main() {
f_flag = fopen(title_path, "rb");
if (f_flag != NULL) {
fclose(f_flag);
LaunchTitle((Boot2KnownTitleId)title_id, FsStorageId_None, 0, NULL);
LaunchTitle(title_id, FsStorageId_None, 0, NULL);
}
}
}
}
closedir(titles_dir);
}
/* Free the memory used to track what boot2 launches. */
ClearLaunchedTitles();
/* We no longer need the SD card. */
fsdevUnmountAll();

View File

@@ -76,10 +76,11 @@ Result DebugMonitorService::DisableDebug(u32 which) {
return Registration::DisableDebug(which);
}
Result DebugMonitorService::AtmosphereGetProcessHandle(Out<CopiedHandle> proc_hand, u64 pid) {
Result DebugMonitorService::AtmosphereGetProcessInfo(Out<CopiedHandle> proc_hand, Out<Registration::TidSid> tid_sid, u64 pid) {
auto proc = Registration::GetProcess(pid);
if(proc != nullptr) {
if (proc != nullptr) {
proc_hand.SetValue(proc->handle);
tid_sid.SetValue(proc->tid_sid);
return 0;
}
return 0x20F;

View File

@@ -38,7 +38,7 @@ enum DmntCmd {
Dmnt_Cmd_6X_DisableDebug = 6,
Dmnt_Cmd_AtmosphereGetProcessHandle = 65000,
Dmnt_Cmd_AtmosphereGetProcessInfo = 65000,
Dmnt_Cmd_AtmosphereGetCurrentLimitInfo = 65001,
};
@@ -55,7 +55,7 @@ class DebugMonitorService final : public IServiceObject {
Result DisableDebug(u32 which);
/* Atmosphere commands. */
Result AtmosphereGetProcessHandle(Out<CopiedHandle> proc_hand, u64 pid);
Result AtmosphereGetProcessInfo(Out<CopiedHandle> proc_hand, Out<Registration::TidSid> tid_sid, u64 pid);
Result AtmosphereGetCurrentLimitInfo(Out<u64> cur_val, Out<u64> lim_val, u32 category, u32 resource);
public:
DEFINE_SERVICE_DISPATCH_TABLE {
@@ -80,7 +80,7 @@ class DebugMonitorService final : public IServiceObject {
MakeServiceCommandMeta<Dmnt_Cmd_6X_DisableDebug, &DebugMonitorService::DisableDebug, FirmwareVersion_600>(),
/* Atmosphere extensions. */
MakeServiceCommandMeta<Dmnt_Cmd_AtmosphereGetProcessHandle, &DebugMonitorService::AtmosphereGetProcessHandle>(),
MakeServiceCommandMeta<Dmnt_Cmd_AtmosphereGetProcessInfo, &DebugMonitorService::AtmosphereGetProcessInfo>(),
MakeServiceCommandMeta<Dmnt_Cmd_AtmosphereGetCurrentLimitInfo, &DebugMonitorService::AtmosphereGetCurrentLimitInfo>(),
};
};

View File

@@ -28,5 +28,4 @@ void ProcessTracking::MainLoop(void *arg) {
process_waiter->Process();
delete process_waiter;
svcExitThread();
}