Compare commits

..

No commits in common. "master" and "v12.0.1" have entirely different histories.

141 changed files with 4009 additions and 7925 deletions

View File

@ -25,7 +25,7 @@ about: Use this to report bugs you encounter with Luma3DS. Make sure you upload
**SysNAND version (+emu/redNAND version if applicable):** **SysNAND version (+emu/redNAND version if applicable):**
[e.g. 11.17.0-50U SysNAND, 11.17.0-50E EmuNAND] [e.g. 11.13.0-45U SysNAND, 11.13.0-45E EmuNAND]
<!--You can check which version you're on in System Settings. It will be on the bottom right of the top screen.--> <!--You can check which version you're on in System Settings. It will be on the bottom right of the top screen.-->
**Entrypoint (How/what you're using to boot Luma3DS):** **Entrypoint (How/what you're using to boot Luma3DS):**
@ -34,7 +34,7 @@ about: Use this to report bugs you encounter with Luma3DS. Make sure you upload
**Luma3DS version:** **Luma3DS version:**
[e.g. v13.2.1 stable or if using non-releases specify the commit like this https://github.com/LumaTeam/Luma3DS/commit/988ec17ebfce513fc4589f7b12e0d6e3894ae542] [e.g. v10.2 stable or if using non-releases specify the commit like this https://github.com/LumaTeam/Luma3DS/commit/0543c208fd154e6326ea5da8cbf66ffcbdef010c]
**Luma3DS configuration/options:** **Luma3DS configuration/options:**
@ -52,26 +52,31 @@ PIN lock: ( )
New 3DS CPU: ( ) New 3DS CPU: ( )
<!--This option is only available on New 3DS (XL)/New 2DS XL.--> <!--This option is only available on New 3DS (XL)/New 2DS XL.-->
Hbmenu autoboot: ( )
-- --
Autoboot EmuNAND: ( ) Autoboot EmuNAND: ( )
<!--This option is only available if there's at least one EmuNAND.--> <!--This option is only available if there's at least one EmuNAND.-->
Use EmuNAND FIRM if booting with R: ( )
<!--This option is only available if there's at least one EmuNAND.-->
Enable loading external FIRMs and modules: ( ) Enable loading external FIRMs and modules: ( )
<!--Firmware (.bin) files are not required by Luma, or NTR CFW anymore. <!--Firmware (.bin) files are not required by Luma, or NTR CFW anymore.
-- If you're having issues with this option enabled try deleting them from the luma folder on the root of the SD card or /rw/luma on CTRNAND and disabling this option.--> -- If you're having issues with this option enabled try deleting them from the luma folder on the root of the SD card or /rw/luma on CTRNAND and disabling this option.-->
Enable game patching: ( ) Enable game patching: ( )
Redirect app. syscore threads to core2: ( )
<!--This option is only available on New 3DS (XL)/New 2DS XL.-->
Show NAND or user string in System Settings: ( ) Show NAND or user string in System Settings: ( )
Show GBA boot screen in patched AGB_FIRM: ( ) Show GBA boot screen in patched AGB_FIRM: ( )
Set developer UNITINFO: ( )
Disable Arm11 exception handlers: ( )
Enable Rosalina on SAFE_FIRM: ( )
<!--This option is only available on New 3DS (XL)/New 2DS XL.-->
-- --
@ -89,8 +94,7 @@ Show GBA boot screen in patched AGB_FIRM: ( )
2. 2.
**Dump file (if applicable):** **Dump file:**
<!--If the issue leads to a crash you must ensure the "Disable Arm11 exception handlers" <!--If the issue leads to a crash you must uncheck the "Disable Arm11 exception handlers" option.
-- option is not disabled in config.ini.
-- The error message will tell you where the dump is. -- The error message will tell you where the dump is.
-- Zip the dmp file and drag & drop it below.--> -- Zip the dmp file and drag & drop it below.-->

1
.gitignore vendored
View File

@ -21,4 +21,3 @@ exceptions/arm11/build
.settings .settings
Luma3DS*.zip Luma3DS*.zip
hbmenu.zip

View File

@ -31,17 +31,16 @@ clean:
@rm -rf *.firm *.zip *.3dsx @rm -rf *.firm *.zip *.3dsx
# boot.3dsx comes from https://github.com/fincs/new-hbmenu/releases # boot.3dsx comes from https://github.com/fincs/new-hbmenu/releases
$(NAME)$(REVISION).zip: hbmenu.zip boot.firm $(NAME)$(REVISION).zip: boot.firm boot.3dsx
@cp $< $@ @zip -r $@ $^ -x "*.DS_Store*" "*__MACOSX*"
@zip $@ boot.firm -x "*.DS_Store*" "*__MACOSX*"
boot.firm: $(SUBFOLDERS) boot.firm: $(SUBFOLDERS)
@firmtool build $@ -D sysmodules/sysmodules.bin arm11/arm11.elf arm9/arm9.elf k11_extension/k11_extension.elf \ @firmtool build $@ -D sysmodules/sysmodules.bin arm11/arm11.elf arm9/arm9.elf k11_extension/k11_extension.elf \
-A 0x18180000 -C XDMA XDMA NDMA XDMA -A 0x18180000 -C XDMA XDMA NDMA XDMA
@echo built... $(notdir $@) @echo built... $(notdir $@)
hbmenu.zip: boot.3dsx:
@curl -sSfL $(shell curl -s https://api.github.com/repos/devkitPro/3ds-hbmenu/releases/latest | grep 'browser_' | cut -d\" -f4) -o $@ @curl -sSfLO "https://github.com/fincs/new-hbmenu/releases/latest/download/$@"
@echo downloaded... $(notdir $@) @echo downloaded... $(notdir $@)
$(SUBFOLDERS): $(SUBFOLDERS):

126
README.md
View File

@ -1,112 +1,36 @@
# Luma3DS # Luma3DS
*Noob-proof (N)3DS "Custom Firmware"*
![GitHub Downloads (all assets, all releases)](https://img.shields.io/github/downloads/LumaTeam/Luma3DS/total) ### What it is
![License](https://img.shields.io/badge/License-GPLv3-blue.svg) **Luma3DS** is a program to patch the system software of (New) Nintendo (2)3DS handheld consoles "on the fly", adding features such as per-game language settings, debugging capabilities for developers, and removing restrictions enforced by Nintendo such as the region lock.
*Nintendo 3DS "Custom Firmware"* It also allows you to run unauthorized ("homebrew") content by removing signature checks.
To use it, you will need a console capable of running homebrew software on the Arm9 processor.
![Boot menu screenshot](img/boot_menu_v1321.png) Since v8.0, Luma3DS has its own in-game menu, triggerable by <kbd>L+Down+Select</kbd> (see the [release notes](https://github.com/LumaTeam/Luma3DS/releases/tag/v8.0)).
![Rosalina menu screenshot](img/rosalina_menu_v1321.png)
## Description #
**Luma3DS** patches and reimplements significant parts of the system software running on all models of the Nintendo 3DS family of consoles. It aims to greatly improve the user experience and support the 3DS far beyond its end-of-life. Features include: ### Compiling
* Prerequisites
1. git
2. [makerom](https://github.com/jakcron/Project_CTR) in PATH
3. [firmtool](https://github.com/TuxSH/firmtool)
4. Up-to-date devkitARM+libctru
1. Clone the repository with `git clone https://github.com/LumaTeam/Luma3DS.git`
2. Run `make`.
* **First-class support for homebrew applications** The produced `boot.firm` is meant to be copied to the root of your SD card for usage with Boot9Strap.
* **Rosalina**, an overlay menu (triggered by <kbd>L+Down+Select</kbd> by default), allowing things like:
* Taking screenshots while in game
* Blue light filters and other screen filters
* Input redirection to play with external devices, such as controllers
* Using cheat codes
* Setting time and date accurately from the network (NTP)
* ... and much more!
* **Many game modding features**, such as, but not limited to:
* Game plugins (in 3GX format)
* Per-game language overrides ("locale emulation")
* Asset content path redirection ("LayeredFS")
* **Support for user-provided patches and/or full "system modules" replacements**, an essential feature for Nintendo Network replacements (amongst other projects)
* A **fully-fledged GDB stub**, allowing homebrew developers and reverse-engineers alike to work much more efficiently
* Ability to chainload other firmware files, including other versions of itself
* ... and much more!
## Installation and upgrade #
Luma3DS requires [boot9strap](https://github.com/SciresM/boot9strap) to run. ### Setup / Usage / Features
See https://github.com/LumaTeam/Luma3DS/wiki
Once boot9strap has been installed, simply download the [latest release archive](https://github.com/LumaTeam/Luma3DS/releases/latest) and extract the archive onto the root of your SD card to "install" or to upgrade Luma3DS alongside the [homebrew menu and certs bundle](https://github.com/devkitPro/3ds-hbmenu) shipped with it. Replace existing files and merge existing folders if necessary. #
### Credits
See https://github.com/LumaTeam/Luma3DS/wiki/Credits
## Basic usage #
**The main Luma3DS configuration menu** can be accessed by pressing <kbd>Select</kbd> at boot. The configuration file is stored in `/luma/config.ini` on the SD card (or `/rw/luma/config.ini` on the CTRNAND partition if Luma3DS has been launched from the CTRNAND partition, which happens when SD card is missing). ### Licensing
**The chainloader menu** is accessed by pressing <kbd>Start</kbd> at boot, or from the configuration menu. Payloads are expected to be located in `/luma/payloads` with the `.firm` extension; if there is only one such payload, the aforementionned selection menu will be skipped. Hotkeys can be assigned to payload, for example `x_test.firm` will be chainloaded when <kbd>X</kbd> is pressed at boot.
**The overlay menu, Rosalina**, has a default button combination: <kbd>L+Down+Select</kbd>. For greater flexbility, most Rosalina menu settings aren't saved automatically, hence the "Save settings" option.
**GDB ports**, when enabled, are `4000-4002` for the normal ports. Use of `attach` in "extended-remote" mode, alongside `info os processes` is supported and encouraged (for reverse-engineering, also check out `monitor getmemregions`). The port for the break-on-start feature is `4003` without "extended-remote". Both devkitARM-patched GDB and IDA Pro (without "stepping support" enabled) are actively supported.
We have a wiki, however it is currently very outdated.
## Components
Luma3DS consists of multiple components. While the code style within each component is mostly consistent, these components have been written over many years and may not reflect how maintainers would write new code in new components/projects:
* **arm9**, **arm11**: baremetal main settings menu, chainloader and firmware loader. Aside from showing settings and chainloading to other homebrew firmware files on demand, it is responsible for patching the official firmware to modify `Process9` code and to inject all other custom components. This was the first component ever written for this project, in 2015
* **k11_extension**: code extending the Arm11 `NATIVE_FIRM` kernel (`Kernel11`). It is injected by the above mentioned baremetal loader into the kernel by hooking its startup code, then hooks itself into the rest of the kernel. Its features include hooking system calls (SVCs), introducing new SVCs and hooking into interprocess communications, to bypass limitations in Nintendo's system design. This is the component that allows Rosalina to pause other processes on overlay menu entry, for example. This was written at a time when we didn't fully reverse-engineer the kernel, and originally released in 2017 alongside Rosalina. Further hooks for "game plugin" support have been merged in 2023
* **sysmodules**: reimplementation of "system modules" (processes) of the 3DS's OS (except for Rosalina being custom), currently only initial processes loaded directly in-memory by the kernel ("kernel initial process", or KIP in short)
* **loader**: process that loads non-KIP processes from storage. Because this is the perfect place to patch/replace executable code, this is where all process patches are done, enabling in particular "game modding" features. This is also the sysmodule handling 3DSX homebrew loading. Introduced in 2016
* _**rosalina**_: the most important component of Luma3DS and custom KIP: overlay menu, GDB server, `err:f` (fatal error screen) reimplementation, and much more. Introduced in mid-2017, and has continuously undergone changes and received many external contributions ever since
* **pxi**: Arm11<>Arm9 communication KIP, reimplemented just for the sake of it. Introduced late 2017
* **sm**: service manager KIP, reimplemented to remove service access control restrictions. Introduced late 2017
* **pm**: process manager KIP reponsible of starting/terminating processes and instructing `loader` to load them. The reimplemention allows for break-on-start GDB feature in Rosalina, as well as lifting FS access control restrictions the proper way. Introduced in 2019
## Maintainers
* **[@TuxSH](https://github.com/TuxSH)**: lead developer, created and maintains most features of the project. Joined in 2016
* **[@AuroraWright](https://github.com/AuroraWright)**: author of the project, implemented the core features (most of the baremetal boot settings menu and firmware loading code) with successful design decisions that made the project popular. Created the project in 2015, currently inactive
* **[@PabloMK7](https://github.com/PabloMK7)**: maintainer of the plugin loader feature merged for the v13.0 release. Joined in 2023
## Roadmap
There are still a lot more features and consolidation planned for Luma3DS! Here is a list of what is currently in store:
* Full reimplementation of `TwlBg` and `AgbBg`. This will allow much better, and more configurable, upscaling for top screen in DS and GBA games (except on Old 2DS). This is currently being developed privately in C++23 (no ETA). While this is quite a difficult endeavor as this requires rewriting the entire driver stack in semi-bare-metal (limited kernel with no IPC), this is the most critical feature for Luma3DS to have and will make driver sysmodule reimpelementation trivial
* Reimplementation of `Process9` for `TWL_FIRM` and `AGB_FIRM` to allow for more features in DS and GBA compatibility mode (ones that require file access)
* Eventually, a full `Kernel11` reimplementation
## Known issues
* **Cheat engine crashes with some applications, in particular Pokémon games**: there is a race condition in Nintendo's `Kernel11` pertaining to attaching a new `KDebugThread` to a `KThread` on thread creation, and another thread null-dereferencing `thread->debugThread`. This causes the cheat engine to crashes games that create and destroy many threads all the time (like Pokémon).
* For these games, having a **dedicated "game plugin"** is the only alternative until `Kernel11` is reimplemented.
* **Applications reacting to Rosalina menu button combo**: Rosalina merely polls button input at an interval to know when to show the menu. This means that the Rosalina menu combo can sometimes be processed by the game/process that is going to be paused.
* You can **change the menu combo** in the "Miscellaneous options" submenu (then save it with "Save settings" in the main menu) to work around this.
## Building from source
To build Luma3DS, the following is needed:
* git
* [makerom](https://github.com/jakcron/Project_CTR) in `$PATH`
* [firmtool](https://github.com/TuxSH/firmtool) installed
* up-to-date devkitARM and libctru:
* install `dkp-pacman` (or, for distributions that already provide pacman, add repositories): https://devkitpro.org/wiki/devkitPro_pacman
* install packages from `3ds-dev` metapackage: `sudo dkp-pacman -S 3ds-dev --needed`
* while libctru and Luma3DS releases are kept in sync, you may have to build libctru from source for non-release Luma3DS commits
While Luma3DS releases are bundled with `3ds-hbmenu`, Luma3DS actually compiles into one single file: `boot.firm`. Just copy it over to the root of your SD card ([ftpd](https://github.com/mtheall/ftpd) is the easiest way to do so), and you're done.
## Licensing
This software is licensed under the terms of the GPLv3. You can find a copy of the license in the LICENSE.txt file. This software is licensed under the terms of the GPLv3. You can find a copy of the license in the LICENSE.txt file.
Files in the GDB stub are instead triple-licensed as MIT or "GPLv2 or any later version", in which case it's specified in the file header. PM, SM, PXI reimplementations are also licensed under MIT. Files in the GDB stub are instead triple-licensed as MIT or "GPLv2 or any later version", in which case it's specified in the file header.
## Credits
Luma3DS would not be what it is without the contributions and constructive feedback of many. We would like to thanks in particular:
* **[@devkitPro](https://github.com/devkitPro)** (especially **[@fincs](https://github.com/fincs)**, **[@WinterMute](https://github.com/WinterMute)** and **[@mtheall](https://github.com/mtheall)**) for providing quality and easy-to-use toolchains with bleeding-edge GCC, and for their continued technical advice
* **[@Nanquitas](https://github.com/Nanquitas)** for the initial version of the game plugin loader code as well as very useful contributions to the GDB stub
* **[@piepie62](https://github.com/piepie62)** for the current implementation of the Rosalina cheat engine, **Duckbill** for its original implementation
* **[@panicbit](https://github.com/panicbit)** for the original implementation of screen filters in Rosalina
* **[@jasondellaluce](https://github.com/jasondellaluce)** for LayeredFS
* **[@LiquidFenrir](https://github.com/LiquidFenrir)** for the memory viewer inside Rosalina's "Process List"
* **ChaN** for [FatFs](http://elm-chan.org/fsw/ff/00index_e.html)
* Everyone who has contributed to the Luma3DS repository
* Everyone who has assisted with troubleshooting end-users
* Everyone who has provided constructive feedback to Luma3DS

View File

@ -84,8 +84,7 @@ static void initScreens(u32 brightnessLevel, struct fb *fbs)
*(vu32 *)0x10400490 = 0x000002D0; *(vu32 *)0x10400490 = 0x000002D0;
*(vu32 *)0x1040049C = 0x00000000; *(vu32 *)0x1040049C = 0x00000000;
// Color LUT //Disco register
*(vu32 *)0x10400480 = 0;
for(u32 i = 0; i < 256; i++) for(u32 i = 0; i < 256; i++)
*(vu32 *)0x10400484 = 0x10101 * i; *(vu32 *)0x10400484 = 0x10101 * i;
@ -120,8 +119,7 @@ static void initScreens(u32 brightnessLevel, struct fb *fbs)
*(vu32 *)0x10400590 = 0x000002D0; *(vu32 *)0x10400590 = 0x000002D0;
*(vu32 *)0x1040059C = 0x00000000; *(vu32 *)0x1040059C = 0x00000000;
// Color LUT //Disco register
*(vu32 *)0x10400580 = 0;
for(u32 i = 0; i < 256; i++) for(u32 i = 0; i < 256; i++)
*(vu32 *)0x10400584 = 0x10101 * i; *(vu32 *)0x10400584 = 0x10101 * i;
@ -195,28 +193,6 @@ static void deinitScreens(void)
*(vu32 *)0x10202014 = 0; *(vu32 *)0x10202014 = 0;
} }
static void zerofillN3dsAblRegisters(void)
{
// It should be fine to write to these regs even on O3DS as they
// are RAZ/WI
// TODO: read from calibration, but null values should do just
// fine. From testing, LUT explicitly ignores null values, and
// it is probably the case of reg @ 0x54 as well.
*(vu32 *)0x10202250 = 0; // unknown 24-bit value, seen: 0
*(vu32 *)0x10202254 = 0; // unknown 24-bit value, seen: nonzero
*(vu32 *)0x10202A50 = 0; // unknown 24-bit value, seen: 0
*(vu32 *)0x10202A54 = 0; // unknown 24-bit value, seen: nonzero
for (u32 i = 0; i < 64; i++) {
// Blend colors (w/ color multiplication) for each group
// of 4 relative-luminance Rs
*(vu32 *)(0x10202300 + 4*i) = 0;
*(vu32 *)(0x10202B00 + 4*i) = 0;
}
}
void main(void) void main(void)
{ {
operation = ARM11_READY; operation = ARM11_READY;
@ -245,9 +221,6 @@ void main(void)
case DEINIT_SCREENS: case DEINIT_SCREENS:
deinitScreens(); deinitScreens();
break; break;
case ZEROFILL_N3DS_ABL_REGISTERS:
zerofillN3dsAblRegisters();
break;
case PREPARE_ARM11_FOR_FIRMLAUNCH: case PREPARE_ARM11_FOR_FIRMLAUNCH:
memcpy((void *)0x1FFFFC00, (void *)prepareForFirmlaunch, prepareForFirmlaunchSize); memcpy((void *)0x1FFFFC00, (void *)prepareForFirmlaunch, prepareForFirmlaunchSize);
*(vu32 *)0x1FFFFFFC = 0; *(vu32 *)0x1FFFFFFC = 0;

View File

@ -60,7 +60,6 @@ typedef enum
SWAP_FRAMEBUFFERS, SWAP_FRAMEBUFFERS,
UPDATE_BRIGHTNESS, UPDATE_BRIGHTNESS,
DEINIT_SCREENS, DEINIT_SCREENS,
ZEROFILL_N3DS_ABL_REGISTERS,
PREPARE_ARM11_FOR_FIRMLAUNCH, PREPARE_ARM11_FOR_FIRMLAUNCH,
ARM11_READY, ARM11_READY,
} Arm11Operation; } Arm11Operation;

Binary file not shown.

View File

@ -46,7 +46,6 @@ SECTIONS
chainloader.o(.text*) chainloader.o(.text*)
i2c.o(.text*) i2c.o(.text*)
arm9_exception_handlers.o(.text*) arm9_exception_handlers.o(.text*)
KEEP (*(.emunand_patch))
*(.arm9_exception_handlers.rodata*) *(.arm9_exception_handlers.rodata*)
chainloader.o(.rodata*) chainloader.o(.rodata*)

View File

@ -102,20 +102,6 @@ typedef struct
u8 romFsHash[0x20]; //RomFS superblock SHA-256 hash u8 romFsHash[0x20]; //RomFS superblock SHA-256 hash
} Ncch; } Ncch;
typedef struct ExeFsFileHeader
{
char name[8];
u32 offset;
u32 size;
} ExeFsFileHeader;
typedef struct ExeFsHeader
{
ExeFsFileHeader fileHeaders[10];
u8 _reserved_0xa0[0xC0 - 0xA0];
u8 fileHashes[10][32];
} ExeFsHeader;
typedef struct typedef struct
{ {
Ncch ncch; Ncch ncch;

View File

@ -39,7 +39,6 @@
#include "pin.h" #include "pin.h"
#include "i2c.h" #include "i2c.h"
#include "ini.h" #include "ini.h"
#include "firm.h"
#include "config_template_ini.h" // note that it has an extra NUL byte inserted #include "config_template_ini.h" // note that it has an extra NUL byte inserted
@ -60,6 +59,7 @@ static_assert(sizeof(CfgDataMcu) > 0, "wrong data size");
static const char *singleOptionIniNamesBoot[] = { static const char *singleOptionIniNamesBoot[] = {
"autoboot_emunand", "autoboot_emunand",
"use_emunand_firm_if_r_pressed",
"enable_external_firm_and_modules", "enable_external_firm_and_modules",
"enable_game_patching", "enable_game_patching",
"app_syscore_threads_on_core_2", "app_syscore_threads_on_core_2",
@ -69,7 +69,6 @@ static const char *singleOptionIniNamesBoot[] = {
static const char *singleOptionIniNamesMisc[] = { static const char *singleOptionIniNamesMisc[] = {
"use_dev_unitinfo", "use_dev_unitinfo",
"enable_dsi_external_filter",
"disable_arm11_exception_handlers", "disable_arm11_exception_handlers",
"enable_safe_firm_rosalina", "enable_safe_firm_rosalina",
}; };
@ -462,11 +461,6 @@ static int configIniHandler(void* user, const char* section, const char* name, c
CHECK_PARSE_OPTION(parseKeyComboOption(&opt, value)); CHECK_PARSE_OPTION(parseKeyComboOption(&opt, value));
cfg->rosalinaMenuCombo = opt; cfg->rosalinaMenuCombo = opt;
return 1; return 1;
} else if (strcmp(name, "plugin_loader_enabled") == 0) {
bool opt;
CHECK_PARSE_OPTION(parseBoolOption(&opt, value));
cfg->pluginLoaderFlags = opt ? cfg->pluginLoaderFlags | 1 : cfg->pluginLoaderFlags & ~1;
return 1;
} else if (strcmp(name, "ntp_tz_offset_min") == 0) { } else if (strcmp(name, "ntp_tz_offset_min") == 0) {
s64 opt; s64 opt;
CHECK_PARSE_OPTION(parseDecIntOption(&opt, value, -779, 899)); CHECK_PARSE_OPTION(parseDecIntOption(&opt, value, -779, 899));
@ -483,7 +477,7 @@ static int configIniHandler(void* user, const char* section, const char* name, c
return 1; return 1;
} else if (strcmp(name, "screen_filters_top_gamma") == 0) { } else if (strcmp(name, "screen_filters_top_gamma") == 0) {
s64 opt; s64 opt;
CHECK_PARSE_OPTION(parseDecFloatOption(&opt, value, 0, 8 * FLOAT_CONV_MULT)); CHECK_PARSE_OPTION(parseDecFloatOption(&opt, value, 0, 1411 * FLOAT_CONV_MULT));
cfg->topScreenFilter.gammaEnc = opt; cfg->topScreenFilter.gammaEnc = opt;
return 1; return 1;
} else if (strcmp(name, "screen_filters_top_contrast") == 0) { } else if (strcmp(name, "screen_filters_top_contrast") == 0) {
@ -501,11 +495,6 @@ static int configIniHandler(void* user, const char* section, const char* name, c
CHECK_PARSE_OPTION(parseBoolOption(&opt, value)); CHECK_PARSE_OPTION(parseBoolOption(&opt, value));
cfg->topScreenFilter.invert = opt; cfg->topScreenFilter.invert = opt;
return 1; return 1;
} else if (strcmp(name, "screen_filters_top_color_curve_adj") == 0) {
s64 opt;
CHECK_PARSE_OPTION(parseDecIntOption(&opt, value, 0, 2));
cfg->topScreenFilter.colorCurveCorrection = (u8)opt;
return 1;
} else if (strcmp(name, "screen_filters_bot_cct") == 0) { } else if (strcmp(name, "screen_filters_bot_cct") == 0) {
s64 opt; s64 opt;
CHECK_PARSE_OPTION(parseDecIntOption(&opt, value, 1000, 25100)); CHECK_PARSE_OPTION(parseDecIntOption(&opt, value, 1000, 25100));
@ -513,7 +502,7 @@ static int configIniHandler(void* user, const char* section, const char* name, c
return 1; return 1;
} else if (strcmp(name, "screen_filters_bot_gamma") == 0) { } else if (strcmp(name, "screen_filters_bot_gamma") == 0) {
s64 opt; s64 opt;
CHECK_PARSE_OPTION(parseDecFloatOption(&opt, value, 0, 8 * FLOAT_CONV_MULT)); CHECK_PARSE_OPTION(parseDecFloatOption(&opt, value, 0, 1411 * FLOAT_CONV_MULT));
cfg->bottomScreenFilter.gammaEnc = opt; cfg->bottomScreenFilter.gammaEnc = opt;
return 1; return 1;
} else if (strcmp(name, "screen_filters_bot_contrast") == 0) { } else if (strcmp(name, "screen_filters_bot_contrast") == 0) {
@ -531,11 +520,6 @@ static int configIniHandler(void* user, const char* section, const char* name, c
CHECK_PARSE_OPTION(parseBoolOption(&opt, value)); CHECK_PARSE_OPTION(parseBoolOption(&opt, value));
cfg->bottomScreenFilter.invert = opt; cfg->bottomScreenFilter.invert = opt;
return 1; return 1;
} else if (strcmp(name, "screen_filters_bot_color_curve_adj") == 0) {
s64 opt;
CHECK_PARSE_OPTION(parseDecIntOption(&opt, value, 0, 2));
cfg->bottomScreenFilter.colorCurveCorrection = (u8)opt;
return 1;
} else { } else {
CHECK_PARSE_OPTION(-1); CHECK_PARSE_OPTION(-1);
} }
@ -576,11 +560,6 @@ static int configIniHandler(void* user, const char* section, const char* name, c
} else { } else {
CHECK_PARSE_OPTION(-1); CHECK_PARSE_OPTION(-1);
} }
} else if (strcmp(name, "volume_slider_override") == 0) {
s64 opt;
CHECK_PARSE_OPTION(parseDecIntOption(&opt, value, -1, 100));
cfg->volumeSliderOverride = (s8)opt;
return 1;
} else { } else {
CHECK_PARSE_OPTION(-1); CHECK_PARSE_OPTION(-1);
} }
@ -663,20 +642,20 @@ static size_t saveLumaIniConfigToStr(char *out)
lumaVerStr, lumaRevSuffixStr, lumaVerStr, lumaRevSuffixStr,
(int)CONFIG_VERSIONMAJOR, (int)CONFIG_VERSIONMINOR, (int)CONFIG_VERSIONMAJOR, (int)CONFIG_VERSIONMINOR,
(int)CONFIG(AUTOBOOTEMU), (int)CONFIG(LOADEXTFIRMSANDMODULES), (int)CONFIG(AUTOBOOTEMU), (int)CONFIG(USEEMUFIRM),
(int)CONFIG(PATCHGAMES), (int)CONFIG(REDIRECTAPPTHREADS), (int)CONFIG(LOADEXTFIRMSANDMODULES), (int)CONFIG(PATCHGAMES),
(int)CONFIG(PATCHVERSTRING), (int)CONFIG(SHOWGBABOOT), (int)CONFIG(REDIRECTAPPTHREADS), (int)CONFIG(PATCHVERSTRING),
(int)CONFIG(SHOWGBABOOT),
1 + (int)MULTICONFIG(DEFAULTEMU), 4 - (int)MULTICONFIG(BRIGHTNESS), 1 + (int)MULTICONFIG(DEFAULTEMU), 4 - (int)MULTICONFIG(BRIGHTNESS),
splashPosStr, (unsigned int)cfg->splashDurationMsec, splashPosStr, (unsigned int)cfg->splashDurationMsec,
pinNumDigits, n3dsCpuStr, pinNumDigits, n3dsCpuStr,
autobootModeStr, autobootModeStr,
cfg->hbldr3dsxTitleId, rosalinaMenuComboStr, (int)(cfg->pluginLoaderFlags & 1), cfg->hbldr3dsxTitleId, rosalinaMenuComboStr,
(int)cfg->ntpTzOffetMinutes, (int)cfg->ntpTzOffetMinutes,
(int)cfg->topScreenFilter.cct, (int)cfg->bottomScreenFilter.cct, (int)cfg->topScreenFilter.cct, (int)cfg->bottomScreenFilter.cct,
(int)cfg->topScreenFilter.colorCurveCorrection, (int)cfg->bottomScreenFilter.colorCurveCorrection,
topScreenFilterGammaStr, bottomScreenFilterGammaStr, topScreenFilterGammaStr, bottomScreenFilterGammaStr,
topScreenFilterContrastStr, bottomScreenFilterContrastStr, topScreenFilterContrastStr, bottomScreenFilterContrastStr,
topScreenFilterBrightnessStr, bottomScreenFilterBrightnessStr, topScreenFilterBrightnessStr, bottomScreenFilterBrightnessStr,
@ -685,16 +664,15 @@ static size_t saveLumaIniConfigToStr(char *out)
cfg->autobootTwlTitleId, (int)cfg->autobootCtrAppmemtype, cfg->autobootTwlTitleId, (int)cfg->autobootCtrAppmemtype,
forceAudioOutputStr, forceAudioOutputStr,
cfg->volumeSliderOverride,
(int)CONFIG(PATCHUNITINFO), (int)CONFIG(ENABLEDSIEXTFILTER), (int)CONFIG(PATCHUNITINFO), (int)CONFIG(DISABLEARM11EXCHANDLERS),
(int)CONFIG(DISABLEARM11EXCHANDLERS), (int)CONFIG(ENABLESAFEFIRMROSALINA) (int)CONFIG(ENABLESAFEFIRMROSALINA)
); );
return n < 0 ? 0 : (size_t)n; return n < 0 ? 0 : (size_t)n;
} }
static char tmpIniBuffer[0x2000 + 0x400]; // eyeballed. TODO use #embed static char tmpIniBuffer[0x2000];
static bool readLumaIniConfig(void) static bool readLumaIniConfig(void)
{ {
@ -709,13 +687,6 @@ static bool readLumaIniConfig(void)
static bool writeLumaIniConfig(void) static bool writeLumaIniConfig(void)
{ {
size_t n = saveLumaIniConfigToStr(tmpIniBuffer); size_t n = saveLumaIniConfigToStr(tmpIniBuffer);
// FIXME: this is UB we should port snprintf sometime (as well as fix other tech debt)
if (n + 1 >= sizeof(tmpIniBuffer)) {
error("Configuration data buffer overflow, please report this issue");
__builtin_unreachable();
}
return n != 0 && fileWrite(tmpIniBuffer, "config.ini", n); return n != 0 && fileWrite(tmpIniBuffer, "config.ini", n);
} }
@ -797,7 +768,6 @@ bool readConfig(void)
configData.formatVersionMinor = CONFIG_VERSIONMINOR; configData.formatVersionMinor = CONFIG_VERSIONMINOR;
configData.config |= 1u << PATCHVERSTRING; configData.config |= 1u << PATCHVERSTRING;
configData.splashDurationMsec = 3000; configData.splashDurationMsec = 3000;
configData.volumeSliderOverride = -1;
configData.hbldr3dsxTitleId = HBLDR_DEFAULT_3DSX_TID; configData.hbldr3dsxTitleId = HBLDR_DEFAULT_3DSX_TID;
configData.rosalinaMenuCombo = 1u << 9 | 1u << 7 | 1u << 2; // L+Start+Select configData.rosalinaMenuCombo = 1u << 9 | 1u << 7 | 1u << 2; // L+Start+Select
configData.topScreenFilter.cct = 6500; // default temp, no-op configData.topScreenFilter.cct = 6500; // default temp, no-op
@ -850,21 +820,17 @@ void configMenu(bool oldPinStatus, u32 oldPinMode)
}; };
static const char *singleOptionsText[] = { "( ) Autoboot EmuNAND", static const char *singleOptionsText[] = { "( ) Autoboot EmuNAND",
"( ) Use EmuNAND FIRM if booting with R",
"( ) Enable loading external FIRMs and modules", "( ) Enable loading external FIRMs and modules",
"( ) Enable game patching", "( ) Enable game patching",
"( ) Redirect app. syscore threads to core2", "( ) Redirect app. syscore threads to core2",
"( ) Show NAND or user string in System Settings", "( ) Show NAND or user string in System Settings",
"( ) Show GBA boot screen in patched AGB_FIRM", "( ) Show GBA boot screen in patched AGB_FIRM",
// Should always be the last 2 entries
"\nBoot chainloader",
"Save and exit"
}; };
static const char *optionsDescription[] = { "Select the default EmuNAND.\n\n" static const char *optionsDescription[] = { "Select the default EmuNAND.\n\n"
"It will be booted when no directional\n" "It will be booted when no\n"
"pad buttons are pressed (Up/Right/Down\n" "directional pad buttons are pressed.",
"/Left equal EmuNANDs 1/2/3/4).",
"Select the screen brightness.", "Select the screen brightness.",
@ -910,6 +876,17 @@ void configMenu(bool oldPinStatus, u32 oldPinMode)
"(Up/Right/Down/Left equal EmuNANDs\n" "(Up/Right/Down/Left equal EmuNANDs\n"
"1/2/3/4).", "1/2/3/4).",
"If enabled, when holding R on boot\n"
"SysNAND will be booted with an\n"
"EmuNAND FIRM.\n\n"
"Otherwise, an EmuNAND will be booted\n"
"with the SysNAND FIRM.\n\n"
"To use a different EmuNAND from the\n"
"default, hold a directional pad button\n"
"(Up/Right/Down/Left equal EmuNANDs\n"
"1/2/3/4), also add A if you have\n"
"a matching payload.",
"Enable loading external FIRMs and\n" "Enable loading external FIRMs and\n"
"system modules.\n\n" "system modules.\n\n"
"This isn't needed in most cases.\n\n" "This isn't needed in most cases.\n\n"
@ -933,32 +910,27 @@ void configMenu(bool oldPinStatus, u32 oldPinMode)
"by about 10%. Can break some games\n" "by about 10%. Can break some games\n"
"and other applications.\n", "and other applications.\n",
"Enable showing the current NAND:\n\n" "Enable showing the current NAND/FIRM:\n\n"
"\t* Sys = SysNAND\n" "\t* Sys = SysNAND\n"
"\t* Emu = EmuNAND 1\n" "\t* Emu = EmuNAND 1\n"
"\t* EmuX = EmuNAND X\n\n" "\t* EmuX = EmuNAND X\n"
"\t* SysE = SysNAND with EmuNAND 1 FIRM\n"
"\t* SyEX = SysNAND with EmuNAND X FIRM\n"
"\t* EmuS = EmuNAND 1 with SysNAND FIRM\n"
"\t* EmXS = EmuNAND X with SysNAND FIRM\n\n"
"or a user-defined custom string in\n" "or a user-defined custom string in\n"
"System Settings.\n\n" "System Settings.\n\n"
"Refer to the wiki for instructions.", "Refer to the wiki for instructions.",
"Enable showing the GBA boot screen\n" "Enable showing the GBA boot screen\n"
"when booting GBA games.", "when booting GBA games.",
// Should always be the last 2 entries
"Boot to the Luma3DS chainloader menu.",
"Save the changes and exit. To discard\n"
"any changes press the POWER button.\n"
"Use START as a shortcut to this entry."
}; };
FirmwareSource nandType = FIRMWARE_SYSNAND; FirmwareSource nandType = FIRMWARE_SYSNAND;
if(isSdMode) if(isSdMode)
{ {
// Check if there is at least one emuNAND
u32 emuIndex = 0;
nandType = FIRMWARE_EMUNAND; nandType = FIRMWARE_EMUNAND;
locateEmuNand(&nandType, &emuIndex, false); locateEmuNand(&nandType);
} }
struct multiOption { struct multiOption {
@ -981,14 +953,13 @@ void configMenu(bool oldPinStatus, u32 oldPinMode)
bool enabled; bool enabled;
bool visible; bool visible;
} singleOptions[] = { } singleOptions[] = {
{ .visible = nandType == FIRMWARE_EMUNAND },
{ .visible = nandType == FIRMWARE_EMUNAND }, { .visible = nandType == FIRMWARE_EMUNAND },
{ .visible = true }, { .visible = true },
{ .visible = true }, { .visible = true },
{ .visible = ISN3DS }, { .visible = ISN3DS },
{ .visible = true }, { .visible = true },
{ .visible = true }, { .visible = true },
{ .visible = true },
{ .visible = true },
}; };
//Calculate the amount of the various kinds of options and pre-select the first single one //Calculate the amount of the various kinds of options and pre-select the first single one
@ -1021,7 +992,7 @@ void configMenu(bool oldPinStatus, u32 oldPinMode)
"FIRM1" }; "FIRM1" };
drawString(true, 10, 10, COLOR_TITLE, CONFIG_TITLE); drawString(true, 10, 10, COLOR_TITLE, CONFIG_TITLE);
drawString(true, 10, 10 + SPACING_Y, COLOR_TITLE, "Use the DPAD and A to change settings"); drawString(true, 10, 10 + SPACING_Y, COLOR_TITLE, "Press A to select, START to save");
drawFormattedString(false, 10, SCREEN_HEIGHT - 2 * SPACING_Y, COLOR_YELLOW, "Booted from %s via %s", isSdMode ? "SD" : "CTRNAND", bootTypes[(u32)bootType]); drawFormattedString(false, 10, SCREEN_HEIGHT - 2 * SPACING_Y, COLOR_YELLOW, "Booted from %s via %s", isSdMode ? "SD" : "CTRNAND", bootTypes[(u32)bootType]);
//Character to display a selected option //Character to display a selected option
@ -1048,7 +1019,7 @@ void configMenu(bool oldPinStatus, u32 oldPinMode)
singleOptions[i].posY = endPos + SPACING_Y; singleOptions[i].posY = endPos + SPACING_Y;
endPos = drawString(true, 10, singleOptions[i].posY, color, singleOptionsText[i]); endPos = drawString(true, 10, singleOptions[i].posY, color, singleOptionsText[i]);
if(singleOptions[i].enabled && singleOptionsText[i][0] == '(') drawCharacter(true, 10 + SPACING_X, singleOptions[i].posY, color, selected); if(singleOptions[i].enabled) drawCharacter(true, 10 + SPACING_X, singleOptions[i].posY, color, selected);
if(color == COLOR_RED) if(color == COLOR_RED)
{ {
@ -1060,25 +1031,17 @@ void configMenu(bool oldPinStatus, u32 oldPinMode)
drawString(false, 10, 10, COLOR_WHITE, optionsDescription[selectedOption]); drawString(false, 10, 10, COLOR_WHITE, optionsDescription[selectedOption]);
bool startPressed = false;
//Boring configuration menu //Boring configuration menu
while(true) while(true)
{ {
u32 pressed = 0; u32 pressed;
if (!startPressed)
do do
{ {
pressed = waitInput(true) & MENU_BUTTONS; pressed = waitInput(true) & MENU_BUTTONS;
} }
while(!pressed); while(!pressed);
// Force the selection of "save and exit" and trigger it. if(pressed & BUTTON_START) break;
if(pressed & BUTTON_START)
{
startPressed = true;
// This moves the cursor to the last entry
pressed = BUTTON_RIGHT;
}
if(pressed & DPAD_BUTTONS) if(pressed & DPAD_BUTTONS)
{ {
@ -1125,7 +1088,7 @@ void configMenu(bool oldPinStatus, u32 oldPinMode)
} }
} }
if(selectedOption == oldSelectedOption && !startPressed) continue; if(selectedOption == oldSelectedOption) continue;
//The user moved to a different option, print the old option in white and the new one in red. Only print 'x's if necessary //The user moved to a different option, print the old option in white and the new one in red. Only print 'x's if necessary
if(oldSelectedOption < multiOptionsAmount) if(oldSelectedOption < multiOptionsAmount)
@ -1146,7 +1109,7 @@ void configMenu(bool oldPinStatus, u32 oldPinMode)
drawString(false, 10, 10, COLOR_BLACK, optionsDescription[oldSelectedOption]); drawString(false, 10, 10, COLOR_BLACK, optionsDescription[oldSelectedOption]);
drawString(false, 10, 10, COLOR_WHITE, optionsDescription[selectedOption]); drawString(false, 10, 10, COLOR_WHITE, optionsDescription[selectedOption]);
} }
else if (pressed & BUTTON_A || startPressed) else if (pressed & BUTTON_A)
{ {
//The selected option's status changed, print the 'x's accordingly //The selected option's status changed, print the 'x's accordingly
if(isMultiOption) if(isMultiOption)
@ -1159,29 +1122,15 @@ void configMenu(bool oldPinStatus, u32 oldPinMode)
} }
else else
{ {
// Save and exit was selected. bool oldEnabled = singleOptions[singleSelected].enabled;
if (singleSelected == singleOptionsAmount - 1) singleOptions[singleSelected].enabled = !oldEnabled;
{ if(oldEnabled) drawCharacter(true, 10 + SPACING_X, singleOptions[singleSelected].posY, COLOR_BLACK, selected);
drawString(true, 10, singleOptions[singleSelected].posY, COLOR_GREEN, singleOptionsText[singleSelected]);
startPressed = false;
break;
}
else if (singleSelected == singleOptionsAmount - 2) {
loadHomebrewFirm(0);
break;
}
else
{
bool oldEnabled = singleOptions[singleSelected].enabled;
singleOptions[singleSelected].enabled = !oldEnabled;
if(oldEnabled) drawCharacter(true, 10 + SPACING_X, singleOptions[singleSelected].posY, COLOR_BLACK, selected);
}
} }
} }
//In any case, if the current option is enabled (or a multiple choice option is selected) we must display a red 'x' //In any case, if the current option is enabled (or a multiple choice option is selected) we must display a red 'x'
if(isMultiOption) drawCharacter(true, 10 + multiOptions[selectedOption].posXs[multiOptions[selectedOption].enabled] * SPACING_X, multiOptions[selectedOption].posY, COLOR_RED, selected); if(isMultiOption) drawCharacter(true, 10 + multiOptions[selectedOption].posXs[multiOptions[selectedOption].enabled] * SPACING_X, multiOptions[selectedOption].posY, COLOR_RED, selected);
else if(singleOptions[singleSelected].enabled && singleOptionsText[singleSelected][0] == '(') drawCharacter(true, 10 + SPACING_X, singleOptions[singleSelected].posY, COLOR_RED, selected); else if(singleOptions[singleSelected].enabled) drawCharacter(true, 10 + SPACING_X, singleOptions[singleSelected].posY, COLOR_RED, selected);
} }
//Parse and write the new configuration //Parse and write the new configuration

View File

@ -36,12 +36,12 @@
#define CONFIG_FILE "config.ini" #define CONFIG_FILE "config.ini"
#define CONFIG_VERSIONMAJOR 3 #define CONFIG_VERSIONMAJOR 3
#define CONFIG_VERSIONMINOR 13 #define CONFIG_VERSIONMINOR 7
#define BOOTCFG_NAND BOOTCONFIG(0, 1) #define BOOTCFG_NAND BOOTCONFIG(0, 7)
#define BOOTCFG_EMUINDEX BOOTCONFIG(1, 3) #define BOOTCFG_FIRM BOOTCONFIG(3, 7)
#define BOOTCFG_NOFORCEFLAG BOOTCONFIG(3, 1) #define BOOTCFG_NOFORCEFLAG BOOTCONFIG(6, 1)
#define BOOTCFG_NTRCARDBOOT BOOTCONFIG(4, 1) #define BOOTCFG_NTRCARDBOOT BOOTCONFIG(7, 1)
enum multiOptions enum multiOptions
{ {
@ -57,13 +57,13 @@ enum multiOptions
enum singleOptions enum singleOptions
{ {
AUTOBOOTEMU = 0, AUTOBOOTEMU = 0,
USEEMUFIRM,
LOADEXTFIRMSANDMODULES, LOADEXTFIRMSANDMODULES,
PATCHGAMES, PATCHGAMES,
REDIRECTAPPTHREADS, REDIRECTAPPTHREADS,
PATCHVERSTRING, PATCHVERSTRING,
SHOWGBABOOT, SHOWGBABOOT,
PATCHUNITINFO, PATCHUNITINFO,
ENABLEDSIEXTFILTER,
DISABLEARM11EXCHANDLERS, DISABLEARM11EXCHANDLERS,
ENABLESAFEFIRMROSALINA, ENABLESAFEFIRMROSALINA,

View File

@ -322,7 +322,7 @@ __attribute__((aligned(4))) static u8 nandCtr[AES_BLOCK_SIZE];
static u8 nandSlot; static u8 nandSlot;
static u32 fatStart = 0; static u32 fatStart = 0;
FirmwareSource ctrNandLocation = FIRMWARE_SYSNAND; FirmwareSource firmSource = FIRMWARE_SYSNAND;
__attribute__((aligned(4))) static const u8 key1s[2][AES_BLOCK_SIZE] = { __attribute__((aligned(4))) static const u8 key1s[2][AES_BLOCK_SIZE] = {
{0x07, 0x29, 0x44, 0x38, 0xF8, 0xC9, 0x75, 0x93, 0xAA, 0x0E, 0x4A, 0xB4, 0xAE, 0x84, 0xC1, 0xD8}, {0x07, 0x29, 0x44, 0x38, 0xF8, 0xC9, 0x75, 0x93, 0xAA, 0x0E, 0x4A, 0xB4, 0xAE, 0x84, 0xC1, 0xD8},
@ -348,7 +348,7 @@ int ctrNandInit(void)
u8 __attribute__((aligned(4))) temp[0x200]; u8 __attribute__((aligned(4))) temp[0x200];
//Read NCSD header //Read NCSD header
result = ctrNandLocation == FIRMWARE_SYSNAND ? sdmmc_nand_readsectors(0, 1, temp) : sdmmc_sdcard_readsectors(emuOffset + emuHeader, 1, temp); result = firmSource == FIRMWARE_SYSNAND ? sdmmc_nand_readsectors(0, 1, temp) : sdmmc_sdcard_readsectors(emuOffset + emuHeader, 1, temp);
if(!result) if(!result)
{ {
@ -375,7 +375,7 @@ int ctrNandRead(u32 sector, u32 sectorCount, u8 *outbuf)
//Read //Read
int result; int result;
if(ctrNandLocation == FIRMWARE_SYSNAND) if(firmSource == FIRMWARE_SYSNAND)
result = sdmmc_nand_readsectors(sector + fatStart, sectorCount, outbuf); result = sdmmc_nand_readsectors(sector + fatStart, sectorCount, outbuf);
else else
{ {

View File

@ -110,7 +110,7 @@
#define SHA_224_HASH_SIZE (224 / 8) #define SHA_224_HASH_SIZE (224 / 8)
#define SHA_1_HASH_SIZE (160 / 8) #define SHA_1_HASH_SIZE (160 / 8)
extern FirmwareSource ctrNandLocation; extern FirmwareSource firmSource;
void sha(void *res, const void *src, u32 size, u32 mode); void sha(void *res, const void *src, u32 size, u32 mode);

View File

@ -29,8 +29,6 @@
#include "memory.h" #include "memory.h"
#include "config.h" #include "config.h"
#include "fs.h" #include "fs.h"
#include "i2c.h"
#include "screen.h"
u8 *loadDeliverArg(void) u8 *loadDeliverArg(void)
{ {
@ -72,7 +70,7 @@ u8 *loadDeliverArg(void)
bool hasMagic = memcmp(tlnc, "TLNC", 4) == 0; bool hasMagic = memcmp(tlnc, "TLNC", 4) == 0;
u8 crcLen = tlnc[5]; u8 crcLen = tlnc[5];
u16 crc = *(u16 *)(tlnc + 6); u16 crc = *(u16 *)(tlnc + 6);
if (!hasMagic || (8 + crcLen) > 0x100 || crc != crc16(tlnc + 8, crcLen, 0xFFFF)) if (!hasMagic || crcLen <= 248 || crc != crc16(tlnc + 8, crcLen, 0xFFFF))
memset(tlnc, 0, 0x100); memset(tlnc, 0, 0x100);
memset(deliverArg + 0x400, 0, 0xC00); memset(deliverArg + 0x400, 0, 0xC00);
@ -142,8 +140,6 @@ static bool configureHomebrewAutobootCtr(u8 *deliverArg)
return false; return false;
u8 memtype = configData.autobootCtrAppmemtype; u8 memtype = configData.autobootCtrAppmemtype;
// autobootCtrAppmemtype already checked, but it doesn't hurt to check again
memtype = memtype >= 5 ? 0 : memtype;
deliverArg[0x400] = ISN3DS ? appmemtypesN3ds[memtype] : appmemtypesO3ds[memtype]; deliverArg[0x400] = ISN3DS ? appmemtypesN3ds[memtype] : appmemtypesO3ds[memtype];
// Determine whether to load from the SD card or from NAND. We don't support gamecards for this // Determine whether to load from the SD card or from NAND. We don't support gamecards for this
@ -155,26 +151,6 @@ static bool configureHomebrewAutobootCtr(u8 *deliverArg)
// Tell NS to run the title, and that it's not a title jump from legacy mode // Tell NS to run the title, and that it's not a title jump from legacy mode
*(u32 *)(deliverArg + 0x460) = (0 << 1) | (1 << 0); *(u32 *)(deliverArg + 0x460) = (0 << 1) | (1 << 0);
// Whenever power button is held long enough ("force shutdown"), mcu sysmodule
// stores a flag in free reg 0. It will clear it next boot.
// During that next boot, if that flag was set and if CFG_BOOTENV.bit0 is set
// (warmboot/firm chainload, i.e. not coldbooting), then main() will simulate
// a "power button held" interrupt (after upgrading mcu fw if necessary -- it
// will reboot console after if it has upgraded mcu fw, I guess that's one of
// the reasons the flag is there). This obviously cause other processes to initiate
// a shutdown, and it also sets that flag again.
// In the case of autoboot, ns will panic when this happens. This caused
// hb autoboot to keep failing over and over again.
// Select free reg 0, read it, select it again, write it (clearing force shutdown flag)
I2C_writeReg(I2C_DEV_MCU, 0x60, 0);
u8 flags = I2C_readReg(I2C_DEV_MCU, 0x61);
flags &= ~4;
I2C_writeReg(I2C_DEV_MCU, 0x60, 0);
I2C_writeReg(I2C_DEV_MCU, 0x61, flags);
CFG_BOOTENV = 1; CFG_BOOTENV = 1;
return true; return true;
@ -201,29 +177,6 @@ static bool configureHomebrewAutobootTwl(u8 *deliverArg)
*(u16 *)(tlnc + 6) = crc16(tlnc + 8, 0x18, 0xFFFF); *(u16 *)(tlnc + 6) = crc16(tlnc + 8, 0x18, 0xFFFF);
// Even though (when running TWL/AGB FIRM) the SoC is in O3DS mode, and the GPU also is,
// as well as most other components behaving as such (external RAM, L2C not usable, etc.),
// this is NOT the case for the LCD and adaptive backlight logic which retains FULL N3DS
// functionality, including a feature where the window is blended with a given color depending
// on the overall relative luminance of that window.
// However, Nintendo's own code mistakenly assumes the opposite, and clearly so ("if GPU in N3DS mode"
// checks, not passing N3DS extra adaptive backlight (ABL) to TWL/AGB_FIRM). This has implications:
// - Powersaving (ABL) settings in TWL/AGB_FIRM is inconsistent with *both* O3DS (because the new RGB blend LUT
// has been set to its current value by NATIVE_FIRM) and N3DS (because "pwn_cnt" and "inertia" are missing
// their N3DS-only bits)
// - "rave party" when booting into TWL/AGB_FIRM or O3DS NATIVE_FIRM without these regs (well, the LUT) initialized.
// Easiest way to do so is by leveraging the "DSi autooboot" feature Luma provides. It is worth noting at least
// the LUT survives hardware reboots (if Nintendo were using DSi software that was using TLNC-based reboots,
// they wouldn't have noticed).
// As such, zerofill these registers (from testing, hardware explicitly discards null values, so this
// should be fine). For now, only touch the Luma-initiated autoboot path
if (ISN3DS)
zerofillN3dsAblRegisters();
CFG_BOOTENV = 3; CFG_BOOTENV = 3;
return true; return true;

View File

@ -39,7 +39,6 @@
#define COLOR_TITLE 0xFF9900 #define COLOR_TITLE 0xFF9900
#define COLOR_WHITE 0xFFFFFF #define COLOR_WHITE 0xFFFFFF
#define COLOR_RED 0x0000FF #define COLOR_RED 0x0000FF
#define COLOR_GREEN 0x00FF00
#define COLOR_BLACK 0x000000 #define COLOR_BLACK 0x000000
#define COLOR_YELLOW 0x00FFFF #define COLOR_YELLOW 0x00FFFF

View File

@ -38,7 +38,7 @@
u32 emuOffset, u32 emuOffset,
emuHeader; emuHeader;
void locateEmuNand(FirmwareSource *nandType, u32 *emunandIndex, bool configureCtrNandParams) void locateEmuNand(FirmwareSource *nandType)
{ {
static u8 __attribute__((aligned(4))) temp[0x200]; static u8 __attribute__((aligned(4))) temp[0x200];
static u32 nandSize = 0, static u32 nandSize = 0,
@ -51,10 +51,7 @@ void locateEmuNand(FirmwareSource *nandType, u32 *emunandIndex, bool configureCt
fatStart = *(u32 *)(temp + 0x1C6); //First sector of the FAT partition fatStart = *(u32 *)(temp + 0x1C6); //First sector of the FAT partition
} }
/*if (*nandType == FIRMWARE_SYSNAND) for(u32 i = 0; i < 3; i++)
return;*/
for(u32 i = 0; i < 3; i++) // Test the different kinds of multi-EmuNAND there are, unless we are looking for the first one
{ {
static const u32 roundedMinsizes[] = {0x1D8000, 0x26E000}; static const u32 roundedMinsizes[] = {0x1D8000, 0x26E000};
@ -68,64 +65,56 @@ void locateEmuNand(FirmwareSource *nandType, u32 *emunandIndex, bool configureCt
nandOffset = roundedMinsizes[ISN3DS ? 1 : 0]; //"Minsize" layout nandOffset = roundedMinsizes[ISN3DS ? 1 : 0]; //"Minsize" layout
break; break;
case 0: case 0:
nandOffset = nandSize > 0x200000 ? 0x400000 : 0x200000; //"Legacy" layout nandOffset = *nandType == FIRMWARE_EMUNAND ? 0 : (nandSize > 0x200000 ? 0x400000 : 0x200000); //"Legacy" layout
break; break;
} }
nandOffset *= *emunandIndex; // always 0 for 1st EmuNAND if(*nandType != FIRMWARE_EMUNAND) nandOffset *= ((u32)*nandType - 1);
if(fatStart >= nandOffset + roundedMinsizes[ISN3DS ? 1 : 0]) if(fatStart >= nandOffset + roundedMinsizes[ISN3DS ? 1 : 0])
{ {
//Check for RedNAND //Check for RedNAND
if(!sdmmc_sdcard_readsectors(nandOffset + 1, 1, temp) && memcmp(temp + 0x100, "NCSD", 4) == 0) if(!sdmmc_sdcard_readsectors(nandOffset + 1, 1, temp) && memcmp(temp + 0x100, "NCSD", 4) == 0)
{ {
if (configureCtrNandParams) emuOffset = nandOffset + 1;
{ emuHeader = 0;
emuOffset = nandOffset + 1;
emuHeader = 0;
}
return; return;
} }
//Check for Gateway EmuNAND //Check for Gateway EmuNAND
else if(i != 2 && !sdmmc_sdcard_readsectors(nandOffset + nandSize, 1, temp) && memcmp(temp + 0x100, "NCSD", 4) == 0) else if(i != 2 && !sdmmc_sdcard_readsectors(nandOffset + nandSize, 1, temp) && memcmp(temp + 0x100, "NCSD", 4) == 0)
{ {
if (configureCtrNandParams) emuOffset = nandOffset;
{ emuHeader = nandSize;
emuOffset = nandOffset;
emuHeader = nandSize;
}
return; return;
} }
} }
if(*emunandIndex == 0) break; // See above comments if(*nandType == FIRMWARE_EMUNAND) break;
} }
//Fallback to the first EmuNAND if there's no second/third/fourth one, or to SysNAND if there isn't any //Fallback to the first EmuNAND if there's no second/third/fourth one, or to SysNAND if there isn't any
if(*emunandIndex != 0) if(*nandType != FIRMWARE_EMUNAND)
{ {
*emunandIndex = 0; *nandType = FIRMWARE_EMUNAND;
locateEmuNand(nandType, emunandIndex, configureCtrNandParams); locateEmuNand(nandType);
} }
else *nandType = FIRMWARE_SYSNAND; else *nandType = FIRMWARE_SYSNAND;
} }
static inline u32 getProtoSdmmc(u32 *sdmmc, u32 firmVersion) static inline bool getFreeK9Space(u8 *pos, u32 size, u8 **freeK9Space)
{ {
switch(firmVersion) static const u8 pattern[] = {0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00};
{
case 243: // SDK 0.9.x (0.9.7?)
*sdmmc = (0x080AAA28 + 0x4e0);
break;
case 238: // SDK 0.10
*sdmmc = (0x080BEA70 + 0x690);
break;
default:
return 1;
}
return 0; //Looking for the last free space before Process9
*freeK9Space = memsearch(pos, pattern, size, sizeof(pattern));
if(*freeK9Space == NULL || (u32)(pos + size - *freeK9Space) < 0x455 + emunandPatchSize ||
*(u32 *)(*freeK9Space + 0x455 + emunandPatchSize - 4) != 0xFFFFFFFF) return false;
*freeK9Space += 0x455;
return true;
} }
static inline u32 getOldSdmmc(u32 *sdmmc, u32 firmVersion) static inline u32 getOldSdmmc(u32 *sdmmc, u32 firmVersion)
@ -160,7 +149,7 @@ static inline u32 getSdmmc(u8 *pos, u32 size, u32 *sdmmc)
return 0; return 0;
} }
static inline u32 patchNandRw(u8 *pos, u32 size, u32 hookAddr) static inline u32 patchNandRw(u8 *pos, u32 size, u32 branchOffset)
{ {
//Look for read/write code //Look for read/write code
static const u8 pattern[] = {0x1E, 0x00, 0xC8, 0x05}; static const u8 pattern[] = {0x1E, 0x00, 0xC8, 0x05};
@ -178,118 +167,32 @@ static inline u32 patchNandRw(u8 *pos, u32 size, u32 hookAddr)
writeOffset -= 3; writeOffset -= 3;
*readOffset = *writeOffset = 0x4C00; *readOffset = *writeOffset = 0x4C00;
readOffset[1] = writeOffset[1] = 0x47A0; readOffset[1] = writeOffset[1] = 0x47A0;
((u32 *)writeOffset)[1] = ((u32 *)readOffset)[1] = hookAddr; ((u32 *)writeOffset)[1] = ((u32 *)readOffset)[1] = branchOffset;
return 0; return 0;
} }
static inline u32 patchProtoNandRw(u8 *pos, u32 size, u32 hookAddr, u32 hookCidAddr) static inline u32 patchMpu(u8 *pos, u32 size)
{ {
//Look for read/write code //Look for MPU pattern
static const u8 pattern[] = { static const u8 pattern[] = {0x03, 0x00, 0x24, 0x00};
0x03, 0x00, 0x51, 0xE3, // cmp r1, #3
0x02, 0xC0, 0xA0, 0xE1, // mov r12, r2
0x04, 0x00, 0x80, 0xE2, // add r0, r0, #4
};
u32 *writeOffset = (u32 *)memsearch(pos, pattern, size, sizeof(pattern)); u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
if(writeOffset == NULL) return 1; if(off == NULL) return 1;
u32 *readOffset = (u32 *)memsearch((u8 *)(writeOffset + 3), pattern, 0x400, sizeof(pattern)); off[1] = 0x0036;
off[0xC] = off[0x12] = 0x0603;
if(readOffset == NULL) return 1;
// Find the sdmmc mount/init(?) function
static const u8 mount_pattern[] = {
0x20, 0x00, 0x84, 0xE2, // add r0, r4, 0x20
0x01, 0x20, 0xA0, 0xE3, // mov r2, #1
0x00, 0x10, 0xA0, 0xE3, // mov r1, #0
};
u32* mountOffset = (u32*) memsearch(pos, mount_pattern, size, sizeof(mount_pattern));
if (mountOffset == NULL) return 1;
// Find the sdmmc read cid function.
static const u8 readcid_pattern[] = {
0x31, 0xFF, 0x2F, 0xE1, // blx r1
0x20, 0x60, 0x9F, 0xE5, // ldr r6, [pc, #0x20] // =failing_result
0x00, 0x00, 0x50, 0xE3, // cmp r0, #0
};
u32* readCidOffset = (u32*) memsearch(pos, readcid_pattern, size, sizeof(readcid_pattern));
if (readCidOffset == NULL) return 1;
readCidOffset -= 5;
mountOffset[1] = 0xe3a02000; // mov r2, #0 // sd-card
readOffset[0] = writeOffset[0] = 0xe52de004; // push {lr}
readOffset[1] = writeOffset[1] = 0xe59fc000; // ldr r12, [pc, #0]
readOffset[2] = writeOffset[2] = 0xe12fff3c; // blx r12
readOffset[3] = writeOffset[3] = hookAddr;
readCidOffset[0] = 0xe59fc000; // ldr r12, [pc, #0]
readCidOffset[1] = 0xe12fff3c; // blx r12
readCidOffset[2] = hookCidAddr;
// Read the emmc cid into the place hook will copy it from
sdmmc_get_cid(1, emunandPatchNandCid);
return 0; return 0;
} }
static inline u32 patchProtoNandRw238(u8 *pos, u32 size, u32 hookAddr, u32 hookCidAddr) u32 patchEmuNand(u8 *arm9Section, u32 kernel9Size, u8 *process9Offset, u32 process9Size, u8 *kernel9Address, u32 firmVersion)
{ {
//Look for read/write code u8 *freeK9Space;
static const u8 pattern[] = {
0x03, 0x00, 0x50, 0xE3, // cmp r0, #3
0x00, 0x00, 0xA0, 0x13, // movne r0, #0
0x01, 0x00, 0xA0, 0x03, // moveq r0, #1
};
u32 *writeOffset = (u32 *)memsearch(pos, pattern, size, sizeof(pattern)); if(!getFreeK9Space(arm9Section, kernel9Size, &freeK9Space)) return 1;
if(writeOffset == NULL) return 1;
u32 *readOffset = (u32 *)memsearch((u8 *)(writeOffset + 3), pattern, 0x400, sizeof(pattern));
if(readOffset == NULL) return 1;
// Find the mmc static ctor...
static const u8 mount_pattern[] = {
0x08, // last byte of some ptr to something in P9
0x01, 0x01, 0x00, 0x00, // emmc controller id
};
u8* mountOffset = (u8*) memsearch(pos, mount_pattern, size, sizeof(mount_pattern));
if (mountOffset == NULL) return 1;
mountOffset++;
// Find the sdmmc read cid function.
static const u8 readcid_pattern[] = {
0x31, 0xFF, 0x2F, 0xE1, // blx r1
0x20, 0x60, 0x9F, 0xE5, // ldr r6, [pc, #0x20] // =failing_result
0x00, 0x00, 0x50, 0xE3, // cmp r0, #0
};
u32* readCidOffset = (u32*) memsearch(pos, readcid_pattern, size, sizeof(readcid_pattern));
if (readCidOffset == NULL) return 1;
readCidOffset -= 5;
*(u32*)mountOffset = 0x300; // sd card
readOffset[0] = writeOffset[0] = 0xe59fc000; // ldr r12, [pc, #0]
readOffset[1] = writeOffset[1] = 0xe12fff3c; // blx r12
readOffset[2] = writeOffset[2] = hookAddr;
readCidOffset[0] = 0xe59fc000; // ldr r12, [pc, #0]
readCidOffset[1] = 0xe12fff3c; // blx r12
readCidOffset[2] = hookCidAddr;
// Read the emmc cid into the place hook will copy it from
sdmmc_get_cid(1, emunandPatchNandCid);
return 0;
}
u32 patchEmuNand(u8 *process9Offset, u32 process9Size, u32 firmVersion)
{
u32 ret = 0; u32 ret = 0;
//Add the data of the found EmuNAND //Add the data of the found EmuNAND
@ -301,38 +204,15 @@ u32 patchEmuNand(u8 *process9Offset, u32 process9Size, u32 firmVersion)
ret += !ISN3DS && firmVersion < 0x25 ? getOldSdmmc(&sdmmc, firmVersion) : getSdmmc(process9Offset, process9Size, &sdmmc); ret += !ISN3DS && firmVersion < 0x25 ? getOldSdmmc(&sdmmc, firmVersion) : getSdmmc(process9Offset, process9Size, &sdmmc);
if(!ret) emunandPatchSdmmcStructPtr = sdmmc; if(!ret) emunandPatchSdmmcStructPtr = sdmmc;
//Copy EmuNAND code
memcpy(freeK9Space, emunandPatch, emunandPatchSize);
//Add EmuNAND hooks //Add EmuNAND hooks
ret += patchNandRw(process9Offset, process9Size, (u32)emunandPatch); u32 branchOffset = (u32)(freeK9Space - arm9Section + kernel9Address);
ret += patchNandRw(process9Offset, process9Size, branchOffset);
return ret;
} //Set MPU
ret += patchMpu(arm9Section, kernel9Size);
u32 patchProtoEmuNand(u8 *process9Offset, u32 process9Size)
{
extern u32 firmProtoVersion;
u32 ret = 0;
// Add the data of the found EmuNAND
emunandPatchNandOffset = emuOffset;
emunandPatchNcsdHeaderOffset = emuHeader;
// Find and add the SDMMC struct
u32 sdmmc;
ret += getProtoSdmmc(&sdmmc, firmProtoVersion);
if(!ret) emunandPatchSdmmcStructPtr = sdmmc;
// Add EmuNAND hooks
switch (firmProtoVersion) {
case 243: // SDK 0.9.x (0.9.7?)
ret += patchProtoNandRw(process9Offset, process9Size, (u32)emunandProtoPatch, (u32)emunandProtoCidPatch);
break;
case 238: // SDK 0.10.x
ret += patchProtoNandRw238(process9Offset, process9Size, (u32)emunandProtoPatch238, (u32)emunandProtoCidPatch);
break;
default:
ret++;
break;
}
return ret; return ret;
} }

View File

@ -37,6 +37,5 @@
extern u32 emuOffset, extern u32 emuOffset,
emuHeader; emuHeader;
void locateEmuNand(FirmwareSource *nandType, u32 *emunandIndex, bool configureCtrNandParams); void locateEmuNand(FirmwareSource *nandType);
u32 patchEmuNand(u8 *process9Offset, u32 process9Size, u32 firmVersion); u32 patchEmuNand(u8 *arm9Section, u32 kernel9Size, u8 *process9Offset, u32 process9Size, u8 *kernel9Address, u32 firmVersion);
u32 patchProtoEmuNand(u8 *process9Offset, u32 process9Size);

View File

@ -1,194 +0,0 @@
.section .emunand_patch, "aw", %progbits
.arm
.align 4
@ Code originally by Normmatt
.global emunandPatch
emunandPatch:
@ Original code that still needs to be executed
mov r4, r0
mov r5, r1
mov r7, r2
mov r6, r3
@ End
@ If we're already trying to access the SD, return
ldr r2, [r0, #4]
ldr r1, emunandPatchSdmmcStructPtr
cmp r2, r1
beq out
str r1, [r0, #4] @ Set object to be SD
ldr r2, [r0, #8] @ Get sector to read
cmp r2, #0 @ For GW compatibility, see if we're trying to read the ncsd header (sector 0)
ldr r3, emunandPatchNandOffset
add r2, r3 @ Add the offset to the NAND in the SD
ldreq r3, emunandPatchNcsdHeaderOffset
addeq r2, r3 @ If we're reading the ncsd header, add the offset of that sector
str r2, [r0, #8] @ Store sector to read
out:
@ Restore registers.
mov r1, r5
mov r2, r7
mov r3, r6
@ Return 4 bytes behind where we got called,
@ due to the offset of this function being stored there
mov r0, lr
add r0, #4
bx r0
.pool
_emunandPatchEnd:
.global emunandProtoPatch
emunandProtoPatch:
@ Save registers
push {r0-r3}
@ If we're already trying to access the SD, return
ldr r2, [r0, #4]
ldr r1, emunandPatchSdmmcStructPtr
cmp r2, r1
beq _out
ldrb r2, [r1, #0xc] @ Get sdmc->m_isInitialised
cmp r2, #0 @ Is initialised?
beq _pastSdmc @ if not, use "NAND" object, patched elsewhere to access SD
str r1, [r0, #4] @ Set object to be SD
_pastSdmc:
ldr r2, [r0, #8] @ Get sector to read
cmp r2, #0 @ For GW compatibility, see if we're trying to read the ncsd header (sector 0)
ldr r3, emunandPatchNandOffset
add r2, r3 @ Add the offset to the NAND in the SD
ldreq r3, emunandPatchNcsdHeaderOffset
addeq r2, r3 @ If we're reading the ncsd header, add the offset of that sector
str r2, [r0, #8] @ Store sector to read
_out:
@ Restore registers
pop {r0-r3}
@ Execute original code that got patched.
cmp r1, #3
mov r12, r2
add r0, r0, #4
movne r1, #0
moveq r1, #1
@ r2 about to be overwritten, so it's free to use here.
@ Save off our return address and restore lr.
mov r2, lr
pop {lr}
@ r2+0 is return address (patched movne r1, #0)
@ r2+4 is moveq r1, #1
@ r2+8 is the following instruction (mov r2, r3)
add r2, #8
bx r2
.global emunandProtoCidPatch
emunandProtoCidPatch:
@ If we're already trying to access the SD, return
ldr r4, emunandPatchSdmmcStructPtr
cmp r0, r4
beq _cid_return
@ Trying to access nand, so copy the NAND cid into r1
adr r4, emunandPatchNandCid
ldr r2, [r4, #0]
ldr r3, [r4, #4]
ldr r5, [r4, #8]
ldr r6, [r4, #0xc]
str r2, [r1, #0]
str r3, [r1, #4]
str r5, [r1, #8]
str r6, [r1, #0xc]
@ And return from whence we came
mov r0, #0
pop {r4-r6, pc}
_cid_return:
@ Execute original code that got patched.
mov r4, r0
ldr r0, [r0]
mov r5, r1
@ lr+0 is return address (patched mov r5, r1)
@ lr+4 is following instruction (ldr r1, [r0,#8])
add lr, #4
bx lr
.global emunandProtoPatch238
emunandProtoPatch238:
@ Save registers
push {r0-r3}
@ If we're already trying to access the SD, return
ldr r2, [r4, #4]
ldr r1, emunandPatchSdmmcStructPtr
cmp r2, r1
beq _out238
ldr r2, [r1, #0x24] @ Get sdmc->m_someObjInitedLater
cmp r2, #0 @ Is initialised?
beq _pastSdmc238 @ if not, use "NAND" object, patched elsewhere to access SD
str r1, [r4, #4] @ Set object to be SD
_pastSdmc238:
ldr r2, [r4, #8] @ Get sector to read
cmp r2, #0 @ For GW compatibility, see if we're trying to read the ncsd header (sector 0)
ldr r3, emunandPatchNandOffset
add r2, r3 @ Add the offset to the NAND in the SD
ldreq r3, emunandPatchNcsdHeaderOffset
addeq r2, r3 @ If we're reading the ncsd header, add the offset of that sector
str r2, [r4, #8] @ Store sector to read
_out238:
@ Restore registers
pop {r0-r3}
@ Execute original code that got patched.
cmp r0, #3
movne r0, #0
moveq r0, #1
@ r1 about to be overwritten, so it's free to use here.
@ Save off our return address.
mov r1, lr
@ r1+0 is return address (patched moveq r1, #1)
@ r1+4 is tst r0, #0xff or sub sp, sp, #0xc
add r1, #4
bx r1
.pool
.global emunandPatchSdmmcStructPtr
.global emunandPatchNandOffset
.global emunandPatchNcsdHeaderOffset
.global emunandPatchNandCid
_emunandPatchBssStart:
emunandPatchSdmmcStructPtr: .word 0 @ Pointer to sdmmc struct
emunandPatchNandOffset: .word 0 @ For rednand this should be 1
emunandPatchNcsdHeaderOffset: .word 0 @ Depends on nand manufacturer + emunand type (GW/RED)
emunandPatchNandCid: @ Store emmc cid here, to override "sdmc's" when trying to read emmc's
.word 0,0,0,0
_emunandPatchBssEnd:
.pool
.balign 4
.global emunandPatchSize
emunandPatchSize:
.word _emunandPatchEnd - emunandPatch
.global emunandPatchBssSize
emunandPatchBssSize:
.word _emunandPatchBssEnd - _emunandPatchBssStart

View File

@ -39,28 +39,12 @@ DSTATUS disk_initialize (
BYTE pdrv /* Physical drive nmuber to identify the drive */ BYTE pdrv /* Physical drive nmuber to identify the drive */
) )
{ {
static u32 sdmmcInitResult = 4; static u32 sdmmcInitResult = 4;
DSTATUS res = 0;
if(sdmmcInitResult == 4) if(sdmmcInitResult == 4) sdmmcInitResult = sdmmc_sdcard_init();
sdmmcInitResult = sdmmc_sdcard_init();
// Check physical drive initialized status return ((pdrv == SDCARD && !(sdmmcInitResult & 2)) ||
switch (pdrv) (pdrv == CTRNAND && !(sdmmcInitResult & 1) && !ctrNandInit())) ? 0 : STA_NOINIT;
{
case SDCARD:
res = (sdmmcInitResult & 2) == 0 ? 0 : STA_NOINIT;
break;
case CTRNAND:
// Always update CTRNAND parameters when remounting
res = (sdmmcInitResult & 1) == 0 && ctrNandInit() == 0 ? 0 : STA_NOINIT;
break;
default:
res = STA_NODISK;
break;
}
return res;
} }
@ -76,22 +60,8 @@ DRESULT disk_read (
UINT count /* Number of sectors to read */ UINT count /* Number of sectors to read */
) )
{ {
DRESULT res = RES_OK; return ((pdrv == SDCARD && !sdmmc_sdcard_readsectors(sector, count, buff)) ||
(pdrv == CTRNAND && !ctrNandRead(sector, count, buff))) ? RES_OK : RES_PARERR;
switch (pdrv)
{
case SDCARD:
res = sdmmc_sdcard_readsectors(sector, count, buff) == 0 ? RES_OK : RES_PARERR;
break;
case CTRNAND:
res = ctrNandRead(sector, count, buff) == 0 ? RES_OK : RES_PARERR;
break;
default:
res = RES_NOTRDY;
break;
}
return res;
} }
@ -109,27 +79,8 @@ DRESULT disk_write (
UINT count /* Number of sectors to write */ UINT count /* Number of sectors to write */
) )
{ {
DRESULT res = RES_OK; return ((pdrv == SDCARD && (*(vu16 *)(SDMMC_BASE + REG_SDSTATUS0) & TMIO_STAT0_WRPROTECT) != 0 && !sdmmc_sdcard_writesectors(sector, count, buff)) ||
(pdrv == CTRNAND && !ctrNandWrite(sector, count, buff))) ? RES_OK : RES_PARERR;
switch (pdrv)
{
case SDCARD:
{
if ((*(vu16 *)(SDMMC_BASE + REG_SDSTATUS0) & TMIO_STAT0_WRPROTECT) == 0) // why == 0?
res = RES_WRPRT;
else
res = sdmmc_sdcard_writesectors(sector, count, buff) == 0 ? RES_OK : RES_PARERR;
break;
}
case CTRNAND:
res = ctrNandWrite(sector, count, buff) == 0 ? RES_OK : RES_PARERR;
break;
default:
res = RES_NOTRDY;
break;
}
return res;
} }
#endif #endif

View File

@ -39,7 +39,6 @@
#include "chainloader.h" #include "chainloader.h"
static Firm *firm = (Firm *)0x20001000; static Firm *firm = (Firm *)0x20001000;
u32 firmProtoVersion = 0;
static __attribute__((noinline)) bool overlaps(u32 as, u32 ae, u32 bs, u32 be) static __attribute__((noinline)) bool overlaps(u32 as, u32 ae, u32 bs, u32 be)
{ {
@ -152,24 +151,10 @@ static inline u32 loadFirmFromStorage(FirmwareType firmType)
u32 loadNintendoFirm(FirmwareType *firmType, FirmwareSource nandType, bool loadFromStorage, bool isSafeMode) u32 loadNintendoFirm(FirmwareType *firmType, FirmwareSource nandType, bool loadFromStorage, bool isSafeMode)
{ {
u32 firmVersion = 0xFFFFFFFF, u32 firmVersion,
firmSize; firmSize;
bool ctrNandError = true; bool ctrNandError = isSdMode && !mountFs(false, false);
bool loadedFromStorage = false;
bool storageLoadError = false;
// Try loading FIRM from sdmc first if specified.
if (loadFromStorage) {
firmSize = loadFirmFromStorage(*firmType);
if (firmSize != 0) loadedFromStorage = true;
else storageLoadError = true;
}
// Remount ctrnand and load FIRM from it if loading from sdmc failed.
if (!loadedFromStorage) {
ctrNandError = isSdMode && !remountCtrNandPartition(false);
}
if(!ctrNandError) if(!ctrNandError)
{ {
@ -184,8 +169,10 @@ u32 loadNintendoFirm(FirmwareType *firmType, FirmwareSource nandType, bool loadF
if(!firmSize || !checkFirm(firmSize)) ctrNandError = true; if(!firmSize || !checkFirm(firmSize)) ctrNandError = true;
} }
} }
// If CTRNAND load failed, and it wasn't tried yet, load FIRM from sdmc.
if (ctrNandError && !storageLoadError) bool loadedFromStorage = false;
if(loadFromStorage || ctrNandError)
{ {
u32 result = loadFirmFromStorage(*firmType); u32 result = loadFirmFromStorage(*firmType);
@ -194,69 +181,11 @@ u32 loadNintendoFirm(FirmwareType *firmType, FirmwareSource nandType, bool loadF
loadedFromStorage = true; loadedFromStorage = true;
firmSize = result; firmSize = result;
} }
else storageLoadError = true; else if(ctrNandError) error("Unable to mount CTRNAND or load the CTRNAND FIRM.\nPlease use an external one.");
} }
// If all attempts failed, panic.
if(ctrNandError && storageLoadError) error("Unable to mount CTRNAND or load the CTRNAND FIRM.\nPlease use an external one.");
//Check that the FIRM is right for the console from the Arm9 section address //Check that the FIRM is right for the console from the Arm9 section address
bool isO3dsFirm = firm->section[3].offset == 0 && firm->section[2].address == (u8 *)0x8006800; if((firm->section[3].offset != 0 ? firm->section[3].address : firm->section[2].address) != (ISN3DS ? (u8 *)0x8006000 : (u8 *)0x8006800))
if(loadedFromStorage || ISDEVUNIT)
{
firmVersion = 0xFFFFFFFF;
if(isO3dsFirm && (*firmType == NATIVE_FIRM || *firmType == NATIVE_FIRM1X2X))
{
__attribute__((aligned(4))) static const u8 hashes[5][0x20] = {
{0xD7, 0x43, 0x0F, 0x27, 0x8D, 0xC9, 0x3F, 0x4C, 0x96, 0xB5, 0xA8, 0x91, 0x48, 0xDB, 0x08, 0x8A,
0x7E, 0x46, 0xB3, 0x95, 0x65, 0xA2, 0x05, 0xF1, 0xF2, 0x41, 0x21, 0xF1, 0x0C, 0x59, 0x6A, 0x9D},
{0x93, 0xDF, 0x49, 0xA1, 0x24, 0x86, 0xBB, 0x6F, 0xAF, 0x49, 0x99, 0x2D, 0xD0, 0x8D, 0xB1, 0x88,
0x8A, 0x00, 0xB6, 0xDD, 0x36, 0x89, 0xC0, 0xE2, 0xC9, 0xA9, 0x99, 0x62, 0x57, 0x5E, 0x6C, 0x23},
{0x39, 0x75, 0xB5, 0x28, 0x24, 0x5E, 0x8B, 0x56, 0xBC, 0x83, 0x79, 0x41, 0x09, 0x2C, 0x42, 0xE6,
0x26, 0xB6, 0x80, 0x59, 0xA5, 0x56, 0xF9, 0xF9, 0x6E, 0xF3, 0x63, 0x05, 0x58, 0xDF, 0x35, 0xEF},
{0x81, 0x9E, 0x71, 0x58, 0xE5, 0x44, 0x73, 0xF7, 0x48, 0x78, 0x7C, 0xEF, 0x5E, 0x30, 0xE2, 0x28,
0x78, 0x0B, 0x21, 0x23, 0x94, 0x63, 0xE8, 0x4E, 0x06, 0xBB, 0xD6, 0x8D, 0xA0, 0x99, 0xAE, 0x98},
{0x1D, 0xD5, 0xB0, 0xC2, 0xD9, 0x4A, 0x4A, 0xF3, 0x23, 0xDD, 0x2F, 0x65, 0x21, 0x95, 0x9B, 0x7E,
0xF2, 0x71, 0x7E, 0xB6, 0x7A, 0x3A, 0x74, 0x78, 0x0D, 0xE3, 0xB5, 0x0C, 0x2B, 0x7F, 0x85, 0x37},
};
u32 i;
for(i = 0; i < sizeof(hashes)/sizeof(hashes[0]); i++)
{
if(memcmp(firm->section[1].hash, hashes[i], 0x20) == 0) break;
}
switch(i)
{
// Beta
case 0:
firmVersion = 0x0;
firmProtoVersion = 243;
*firmType = NATIVE_PROTOTYPE;
break;
case 1:
firmVersion = 0x0;
firmProtoVersion = 238;
*firmType = NATIVE_PROTOTYPE;
break;
// Release
case 2:
firmVersion = 0x18;
break;
case 3:
firmVersion = 0x1D;
break;
case 4:
firmVersion = 0x1F;
break;
default:
break;
}
}
}
if(*firmType != NATIVE_PROTOTYPE && (firm->section[3].offset != 0 ? firm->section[3].address : firm->section[2].address) != (ISN3DS ? (u8 *)0x8006000 : (u8 *)0x8006800))
error("The %s FIRM is not for this console.", loadedFromStorage ? "external" : "CTRNAND"); error("The %s FIRM is not for this console.", loadedFromStorage ? "external" : "CTRNAND");
if(!ISN3DS && *firmType == NATIVE_FIRM && firm->section[0].address == (u8 *)0x1FF80000) if(!ISN3DS && *firmType == NATIVE_FIRM && firm->section[0].address == (u8 *)0x1FF80000)
@ -270,6 +199,39 @@ u32 loadNintendoFirm(FirmwareType *firmType, FirmwareSource nandType, bool loadF
*firmType = NATIVE_FIRM1X2X; *firmType = NATIVE_FIRM1X2X;
} }
if(loadedFromStorage || ISDEVUNIT)
{
firmVersion = 0xFFFFFFFF;
if(!ISN3DS && *firmType == NATIVE_FIRM)
{
__attribute__((aligned(4))) static const u8 hashes[3][0x20] = {
{0x39, 0x75, 0xB5, 0x28, 0x24, 0x5E, 0x8B, 0x56, 0xBC, 0x83, 0x79, 0x41, 0x09, 0x2C, 0x42, 0xE6,
0x26, 0xB6, 0x80, 0x59, 0xA5, 0x56, 0xF9, 0xF9, 0x6E, 0xF3, 0x63, 0x05, 0x58, 0xDF, 0x35, 0xEF},
{0x81, 0x9E, 0x71, 0x58, 0xE5, 0x44, 0x73, 0xF7, 0x48, 0x78, 0x7C, 0xEF, 0x5E, 0x30, 0xE2, 0x28,
0x78, 0x0B, 0x21, 0x23, 0x94, 0x63, 0xE8, 0x4E, 0x06, 0xBB, 0xD6, 0x8D, 0xA0, 0x99, 0xAE, 0x98},
{0x1D, 0xD5, 0xB0, 0xC2, 0xD9, 0x4A, 0x4A, 0xF3, 0x23, 0xDD, 0x2F, 0x65, 0x21, 0x95, 0x9B, 0x7E,
0xF2, 0x71, 0x7E, 0xB6, 0x7A, 0x3A, 0x74, 0x78, 0x0D, 0xE3, 0xB5, 0x0C, 0x2B, 0x7F, 0x85, 0x37}
};
u32 i;
for(i = 0; i < 3; i++) if(memcmp(firm->section[1].hash, hashes[i], 0x20) == 0) break;
switch(i)
{
case 0:
firmVersion = 0x18;
break;
case 1:
firmVersion = 0x1D;
break;
case 2:
firmVersion = 0x1F;
break;
}
}
}
return firmVersion; return firmVersion;
} }
@ -300,148 +262,11 @@ void loadHomebrewFirm(u32 pressed)
launchFirm(wantsScreenInit ? 2 : 1, argv); launchFirm(wantsScreenInit ? 2 : 1, argv);
} }
static int lzss_decompress(u8 *end) static inline void mergeSection0(FirmwareType firmType, u32 firmVersion, bool loadFromStorage)
{
unsigned int v1; // r1@2
u8 *v2; // r2@2
u8 *v3; // r3@2
u8 *v4; // r1@2
char v5; // r5@4
char v6; // t1@4
signed int v7; // r6@4
int v9; // t1@7
u8 *v11; // r3@8
int v12; // r12@8
int v13; // t1@8
int v14; // t1@8
unsigned int v15; // r7@8
int v16; // r12@8
int ret;
ret = 0;
if ( end )
{
v1 = *((u32 *)end - 2);
v2 = &end[*((u32 *)end - 1)];
v3 = &end[-(v1 >> 24)];
v4 = &end[-(v1 & 0xFFFFFF)];
while ( v3 > v4 )
{
v6 = *(v3-- - 1);
v5 = v6;
v7 = 8;
while ( 1 )
{
if ( (v7-- < 1) )
break;
if ( v5 & 0x80 )
{
v13 = *(v3 - 1);
v11 = v3 - 1;
v12 = v13;
v14 = *(v11 - 1);
v3 = v11 - 1;
v15 = ((v14 | (v12 << 8)) & 0xFFFF0FFF) + 2;
v16 = v12 + 32;
do
{
ret = v2[v15];
*(v2-- - 1) = ret;
v16 -= 16;
}
while ( !(v16 < 0) );
}
else
{
v9 = *(v3-- - 1);
ret = v9;
*(v2-- - 1) = v9;
}
v5 *= 2;
if ( v3 <= v4 )
return ret;
}
}
}
return ret;
}
typedef struct CopyKipResult {
u32 cxiSize;
u8 *codeDstAddr;
u32 codeSize;
} CopyKipResult;
// Copy a KIP, decompressing it in place if necessary (TwlBg)
static CopyKipResult copyKip(u8 *dst, const u8 *src, u32 maxSize, bool decompress)
{
const char *extModuleSizeError = "The external FIRM modules are too large.";
CopyKipResult res = { 0 };
Cxi *dstCxi = (Cxi *)dst;
const Cxi *srcCxi = (const Cxi *)src;
u32 mediaUnitShift = 9 + srcCxi->ncch.flags[6];
u32 totalSizeCompressed = srcCxi->ncch.contentSize << mediaUnitShift;
if (totalSizeCompressed > maxSize)
error(extModuleSizeError);
// First, copy the compressed KIP to the destination
memcpy(dst, src, totalSizeCompressed);
ExHeader *exh = &dstCxi->exHeader;
bool isCompressed = (exh->systemControlInfo.flag & 1) != 0;
ExeFsHeader *exefs = (ExeFsHeader *)(dst + (dstCxi->ncch.exeFsOffset << mediaUnitShift));
ExeFsFileHeader *fh = &exefs->fileHeaders[0];
u8 *codeAddr = (u8 *)exefs + sizeof(ExeFsHeader) + fh->offset;
if (memcmp(fh->name, ".code\0\0\0", 8) != 0 || fh->offset != 0 || exefs->fileHeaders[1].size != 0)
error("One of the external FIRM modules have invalid layout.");
// If it's already decompressed or we don't need to, there is not much left to do
if (!decompress || !isCompressed)
{
res.cxiSize = totalSizeCompressed;
res.codeDstAddr = codeAddr;
res.codeSize = fh->size;
}
else
{
u32 codeSize = exh->systemControlInfo.textCodeSet.size;
codeSize += exh->systemControlInfo.roCodeSet.size;
codeSize += exh->systemControlInfo.dataCodeSet.size;
u32 codeSizePadded = ((codeSize + (1 << mediaUnitShift) - 1) >> mediaUnitShift) << mediaUnitShift;
u32 newTotalSize = (codeAddr + codeSizePadded) - dst;
if (newTotalSize > maxSize)
error(extModuleSizeError);
// Decompress in place
lzss_decompress(codeAddr + fh->size);
// Fill padding just in case
memset(codeAddr + codeSize, 0, codeSizePadded - codeSize);
// Fix fields
fh->size = codeSize;
dstCxi->ncch.exeFsSize = codeSizePadded >> mediaUnitShift;
exh->systemControlInfo.flag &= ~1;
dstCxi->ncch.contentSize = newTotalSize >> mediaUnitShift;
res.cxiSize = newTotalSize;
res.codeDstAddr = codeAddr;
res.codeSize = codeSize;
}
return res;
}
static void mergeSection0(FirmwareType firmType, u32 firmVersion, bool loadFromStorage)
{ {
u32 srcModuleSize, u32 srcModuleSize,
nbModules = 0; nbModules = 0;
bool isLgyFirm = firmType == TWL_FIRM || firmType == AGB_FIRM;
struct struct
{ {
char name[8]; char name[8];
@ -458,7 +283,7 @@ static void mergeSection0(FirmwareType firmType, u32 firmVersion, bool loadFromS
} }
// SAFE_FIRM only for N3DS and only if ENABLESAFEFIRMROSALINA is on // SAFE_FIRM only for N3DS and only if ENABLESAFEFIRMROSALINA is on
if((firmType == NATIVE_FIRM || firmType == SAFE_FIRM) && (ISN3DS || firmVersion >= 0x25)) if((firmType == NATIVE_FIRM || firmType == SAFE_FIRM) && (ISN3DS || firmVersion >= 0x1D))
{ {
//2) Merge that info with our own modules' //2) Merge that info with our own modules'
for(u8 *src = (u8 *)0x18180000; memcmp(((Cxi *)src)->ncch.magic, "NCCH", 4) == 0; src += srcModuleSize) for(u8 *src = (u8 *)0x18180000; memcmp(((Cxi *)src)->ncch.magic, "NCCH", 4) == 0; src += srcModuleSize)
@ -484,9 +309,8 @@ static void mergeSection0(FirmwareType firmType, u32 firmVersion, bool loadFromS
u8 *dst = firm->section[0].address; u8 *dst = firm->section[0].address;
const char *extModuleSizeError = "The external FIRM modules are too large."; const char *extModuleSizeError = "The external FIRM modules are too large.";
// SAFE_FIRM only for N3DS and only if ENABLESAFEFIRMROSALINA is on // SAFE_FIRM only for N3DS and only if ENABLESAFEFIRMROSALINA is on
u32 maxModuleSize = !isLgyFirm ? 0x80000 : 0x600000; u32 maxModuleSize = (firmType == NATIVE_FIRM || firmType == SAFE_FIRM) ? 0x80000 : 0x600000;
u32 dstModuleSize = 0; for(u32 i = 0, dstModuleSize; i < nbModules; i++, dst += dstModuleSize, maxModuleSize -= dstModuleSize)
for(u32 i = 0; i < nbModules; i++)
{ {
if(loadFromStorage) if(loadFromStorage)
{ {
@ -507,40 +331,22 @@ static void mergeSection0(FirmwareType firmType, u32 firmVersion, bool loadFromS
memcmp(moduleList[i].name, ((Cxi *)dst)->exHeader.systemControlInfo.appTitle, sizeof(((Cxi *)dst)->exHeader.systemControlInfo.appTitle)) != 0) memcmp(moduleList[i].name, ((Cxi *)dst)->exHeader.systemControlInfo.appTitle, sizeof(((Cxi *)dst)->exHeader.systemControlInfo.appTitle)) != 0)
error("An external FIRM module is invalid or corrupted."); error("An external FIRM module is invalid or corrupted.");
dst += dstModuleSize;
maxModuleSize -= dstModuleSize;
continue; continue;
} }
} }
// If not successfully loaded from storage, then... dstModuleSize = moduleList[i].size;
// Decompress stock TwlBg so that we can patch it if(dstModuleSize > maxModuleSize) error(extModuleSizeError);
bool isStockTwlBg = firmType == TWL_FIRM && strcmp(moduleList[i].name, "TwlBg") == 0;
CopyKipResult copyRes = copyKip(dst, moduleList[i].src, maxModuleSize, isStockTwlBg); memcpy(dst, moduleList[i].src, dstModuleSize);
if (isStockTwlBg)
patchTwlBg(copyRes.codeDstAddr, copyRes.codeSize);
dst += copyRes.cxiSize;
maxModuleSize -= copyRes.cxiSize;
} }
//4) Patch kernel to take module size into account //4) Patch NATIVE_FIRM/SAFE_FIRM (N3DS) if necessary
u32 newKipSectionSize = dst - firm->section[0].address; if(nbModules == 6)
u32 oldKipSectionSize = firm->section[0].size;
u8 *kernel11Addr = (u8 *)firm + firm->section[1].offset;
u32 kernel11Size = firm->section[1].size;
if (isLgyFirm)
{ {
if (patchK11ModuleLoadingLgy(newKipSectionSize, kernel11Addr, kernel11Size) != 0) if(patchK11ModuleLoading(firm->section[0].size, dst - firm->section[0].address, (u8 *)firm + firm->section[1].offset, firm->section[1].size) != 0)
error("Failed to load sysmodules"); error("Failed to inject custom sysmodule");
}
else
{
if (patchK11ModuleLoading(oldKipSectionSize, newKipSectionSize, nbModules, kernel11Addr, kernel11Size) != 0)
error("Failed to load sysmodules");
} }
} }
@ -564,8 +370,8 @@ u32 patchNativeFirm(u32 firmVersion, FirmwareSource nandType, bool loadFromStora
ret = 0; ret = 0;
#ifndef BUILD_FOR_EXPLOIT_DEV #ifndef BUILD_FOR_EXPLOIT_DEV
//Skip on FIRMs < 5.0 //Skip on FIRMs < 4.0
if(ISN3DS || firmVersion >= 0x25) if(ISN3DS || firmVersion >= 0x1D)
{ {
//Find the Kernel11 SVC table and handler, exceptions page and free space locations //Find the Kernel11 SVC table and handler, exceptions page and free space locations
u8 *arm11Section1 = (u8 *)firm + firm->section[1].offset; u8 *arm11Section1 = (u8 *)firm + firm->section[1].offset;
@ -586,7 +392,7 @@ u32 patchNativeFirm(u32 firmVersion, FirmwareSource nandType, bool loadFromStora
ret += patchSignatureChecks(process9Offset, process9Size); ret += patchSignatureChecks(process9Offset, process9Size);
//Apply EmuNAND patches //Apply EmuNAND patches
if(nandType != FIRMWARE_SYSNAND) ret += patchEmuNand(process9Offset, process9Size, firmVersion); if(nandType != FIRMWARE_SYSNAND) ret += patchEmuNand(arm9Section, kernel9Size, process9Offset, process9Size, firm->section[2].address, firmVersion);
//Apply FIRM0/1 writes patches on SysNAND to protect A9LH //Apply FIRM0/1 writes patches on SysNAND to protect A9LH
else if(isFirmProtEnabled) ret += patchFirmWrites(process9Offset, process9Size); else if(isFirmProtEnabled) ret += patchFirmWrites(process9Offset, process9Size);
@ -631,11 +437,6 @@ u32 patchNativeFirm(u32 firmVersion, FirmwareSource nandType, bool loadFromStora
u32 patchTwlFirm(u32 firmVersion, bool loadFromStorage, bool doUnitinfoPatch) u32 patchTwlFirm(u32 firmVersion, bool loadFromStorage, bool doUnitinfoPatch)
{ {
u8 *section1 = (u8 *)firm + firm->section[1].offset;
u32 section1Size = firm->section[1].size;
u8 *section2 = (u8 *)firm + firm->section[2].offset;
u32 section2Size = firm->section[2].size;
u8 *arm9Section = (u8 *)firm + firm->section[3].offset; u8 *arm9Section = (u8 *)firm + firm->section[3].offset;
// Below 3.0, do not actually do anything. // Below 3.0, do not actually do anything.
@ -668,11 +469,11 @@ u32 patchTwlFirm(u32 firmVersion, bool loadFromStorage, bool doUnitinfoPatch)
//Apply UNITINFO patch //Apply UNITINFO patch
if(doUnitinfoPatch) ret += patchUnitInfoValueSet(arm9Section, kernel9Size); if(doUnitinfoPatch) ret += patchUnitInfoValueSet(arm9Section, kernel9Size);
ret += patchLgyK11(section1, section1Size, section2, section2Size); if(loadFromStorage)
{
// Also patch TwlBg here mergeSection0(TWL_FIRM, 0, true);
mergeSection0(TWL_FIRM, 0, loadFromStorage); firm->section[0].size = 0;
firm->section[0].size = 0; }
return ret; return ret;
} }
@ -681,11 +482,6 @@ u32 patchAgbFirm(bool loadFromStorage, bool doUnitinfoPatch)
{ {
u8 *arm9Section = (u8 *)firm + firm->section[3].offset; u8 *arm9Section = (u8 *)firm + firm->section[3].offset;
u8 *section1 = (u8 *)firm + firm->section[1].offset;
u32 section1Size = firm->section[1].size;
u8 *section2 = (u8 *)firm + firm->section[2].offset;
u32 section2Size = firm->section[2].size;
//On N3DS, decrypt Arm9Bin and patch Arm9 entrypoint to skip kernel9loader //On N3DS, decrypt Arm9Bin and patch Arm9 entrypoint to skip kernel9loader
if(ISN3DS) if(ISN3DS)
{ {
@ -703,7 +499,6 @@ u32 patchAgbFirm(bool loadFromStorage, bool doUnitinfoPatch)
ret += patchLgySignatureChecks(process9Offset, process9Size); ret += patchLgySignatureChecks(process9Offset, process9Size);
if(CONFIG(SHOWGBABOOT)) ret += patchAgbBootSplash(process9Offset, process9Size); if(CONFIG(SHOWGBABOOT)) ret += patchAgbBootSplash(process9Offset, process9Size);
ret += patchLgyK11(section1, section1Size, section2, section2Size);
//Apply UNITINFO patch //Apply UNITINFO patch
if(doUnitinfoPatch) ret += patchUnitInfoValueSet(arm9Section, kernel9Size); if(doUnitinfoPatch) ret += patchUnitInfoValueSet(arm9Section, kernel9Size);
@ -773,29 +568,6 @@ u32 patch1x2xNativeAndSafeFirm(void)
return ret; return ret;
} }
u32 patchPrototypeNative(FirmwareSource nandType)
{
u8 *arm9Section = (u8 *)firm + firm->section[2].offset;
//Find the Process9 .code location, size and memory address
u32 process9Size,
process9MemAddr;
u8 *process9Offset = getProcess9Info(arm9Section, firm->section[2].size, &process9Size, &process9MemAddr);
u32 kernel9Size = (u32)(process9Offset - arm9Section) - sizeof(Cxi) - 0x200,
ret = 0;
ret += patchProtoNandSignatureCheck(process9Offset, process9Size);
//Arm9 exception handlers
ret += patchArm9ExceptionHandlersInstall(arm9Section, kernel9Size);
//Apply EmuNAND patches
if(nandType != FIRMWARE_SYSNAND) ret += patchProtoEmuNand(process9Offset, process9Size);
return ret;
}
void launchFirm(int argc, char **argv) void launchFirm(int argc, char **argv)
{ {
prepareArm11ForFirmlaunch(); prepareArm11ForFirmlaunch();

View File

@ -35,5 +35,4 @@ u32 patchNativeFirm(u32 firmVersion, FirmwareSource nandType, bool loadFromStora
u32 patchTwlFirm(u32 firmVersion, bool loadFromStorage, bool doUnitinfoPatch); u32 patchTwlFirm(u32 firmVersion, bool loadFromStorage, bool doUnitinfoPatch);
u32 patchAgbFirm(bool loadFromStorage, bool doUnitinfoPatch); u32 patchAgbFirm(bool loadFromStorage, bool doUnitinfoPatch);
u32 patch1x2xNativeAndSafeFirm(void); u32 patch1x2xNativeAndSafeFirm(void);
u32 patchPrototypeNative(FirmwareSource nandType);
void launchFirm(int argc, char **argv); void launchFirm(int argc, char **argv);

View File

@ -52,50 +52,27 @@ static bool switchToMainDir(bool isSd)
case FR_OK: case FR_OK:
return true; return true;
case FR_NO_PATH: case FR_NO_PATH:
{ return f_mkdir(mainDir) == FR_OK && switchToMainDir(isSd);
if (f_mkdir(mainDir) != FR_OK)
{
error("Failed to create luma directory.");
return false;
}
return switchToMainDir(isSd);
}
default: default:
return false; return false;
} }
} }
bool mountSdCardPartition(bool switchMainDir) bool mountFs(bool isSd, bool switchToCtrNand)
{ {
static bool sdInitialized = false; static bool sdInitialized = false, nandInitialized = false;
if (!sdInitialized) if (isSd)
sdInitialized = f_mount(&sdFs, "sdmc:", 1) == FR_OK;
if (sdInitialized && switchMainDir)
return f_chdrive("sdmc:") == FR_OK && switchToMainDir(true);
return sdInitialized;
}
bool remountCtrNandPartition(bool switchMainDir)
{
static bool nandInitialized = false;
int res = FR_OK;
if (!nandInitialized)
{ {
res = f_mount(&nandFs, "nand:", 1); if (!sdInitialized)
nandInitialized = res == FR_OK; sdInitialized = f_mount(&sdFs, "sdmc:", 1) == FR_OK;
return sdInitialized && switchToMainDir(true);
}
else
{
if (!nandInitialized)
nandInitialized = f_mount(&nandFs, "nand:", 1) == FR_OK;
return nandInitialized && (!switchToCtrNand || (f_chdrive("nand:") == FR_OK && switchToMainDir(false)));
} }
if (nandInitialized && switchMainDir)
return f_chdrive("nand:") == FR_OK && switchToMainDir(false);
return nandInitialized;
}
void unmountPartitions(void)
{
f_unmount("nand:");
f_unmount("sdmc:");
} }
u32 fileRead(void *dest, const char *path, u32 maxSize) u32 fileRead(void *dest, const char *path, u32 maxSize)
@ -137,7 +114,6 @@ bool fileWrite(const void *buffer, const char *path, u32 size)
return result == FR_OK && (u32)written == size; return result == FR_OK && (u32)written == size;
} }
case FR_NO_PATH: case FR_NO_PATH:
// Only create the last dir in the hierarchy
for(u32 i = 1; path[i] != 0; i++) for(u32 i = 1; path[i] != 0; i++)
if(path[i] == '/') if(path[i] == '/')
{ {
@ -179,7 +155,6 @@ bool fileCopy(const char *pathSrc, const char *pathDst, bool replace, void *tmpB
} }
else if (res == FR_NO_PATH) else if (res == FR_NO_PATH)
{ {
// Only create the last dir in the hierarchy
const char *c; const char *c;
for (c = pathDst + strlen(pathDst); *c != '/' && c >= pathDst; --c); for (c = pathDst + strlen(pathDst); *c != '/' && c >= pathDst; --c);
if (c >= pathDst && c - pathDst <= FF_MAX_LFN && *c != '\0') if (c >= pathDst && c - pathDst <= FF_MAX_LFN && *c != '\0')
@ -232,12 +207,6 @@ bool fileCopy(const char *pathSrc, const char *pathDst, bool replace, void *tmpB
return true; return true;
} }
bool createDir(const char *path)
{
FRESULT res = f_mkdir(path);
return res == FR_OK || res == FR_EXIST;
}
bool findPayload(char *path, u32 pressed) bool findPayload(char *path, u32 pressed)
{ {
const char *pattern; const char *pattern;
@ -443,38 +412,22 @@ static bool backupEssentialFiles(void)
{ {
size_t sz = sizeof(fileCopyBuffer); size_t sz = sizeof(fileCopyBuffer);
u32 deviceID = *(vu32*)0x01FFB804; bool ok = !(isSdMode && !mountFs(false, false));
char pathStart[0x20];
sprintf(pathStart, "backups/%08lX/", deviceID);
char fullPath[0x80];
// Since the other funcs in this file don't create directories recursively (only the last one), ok = ok && fileCopy("nand:/ro/sys/HWCAL0.dat", "backups/HWCAL0.dat", false, fileCopyBuffer, sz);
// and nor does f_mkdir, create the directories anyway and ignore the result ok = ok && fileCopy("nand:/ro/sys/HWCAL1.dat", "backups/HWCAL1.dat", false, fileCopyBuffer, sz);
f_mkdir("backups");
f_mkdir(pathStart);
bool ok = true; ok = ok && fileCopy("nand:/rw/sys/LocalFriendCodeSeed_A", "backups/LocalFriendCodeSeed_A", false, fileCopyBuffer, sz); // often doesn't exist
sprintf(fullPath, "%sHWCAL0.dat", pathStart); ok = ok && fileCopy("nand:/rw/sys/LocalFriendCodeSeed_B", "backups/LocalFriendCodeSeed_B", false, fileCopyBuffer, sz);
ok = ok && fileCopy("nand:/ro/sys/HWCAL0.dat", fullPath, false, fileCopyBuffer, sz);
sprintf(fullPath, "%sHWCAL1.dat", pathStart);
ok = ok && fileCopy("nand:/ro/sys/HWCAL1.dat", fullPath, false, fileCopyBuffer, sz);
sprintf(fullPath, "%sLocalFriendCodeSeed_A", pathStart); ok = ok && fileCopy("nand:/rw/sys/SecureInfo_A", "backups/SecureInfo_A", false, fileCopyBuffer, sz);
ok = ok && fileCopy("nand:/rw/sys/LocalFriendCodeSeed_A", fullPath, false, fileCopyBuffer, sz); // often doesn't exist ok = ok && fileCopy("nand:/rw/sys/SecureInfo_B", "backups/SecureInfo_B", false, fileCopyBuffer, sz); // often doesn't exist
sprintf(fullPath, "%sLocalFriendCodeSeed_B", pathStart);
ok = ok && fileCopy("nand:/rw/sys/LocalFriendCodeSeed_B", fullPath, false, fileCopyBuffer, sz);
sprintf(fullPath, "%sSecureInfo_A", pathStart);
ok = ok && fileCopy("nand:/rw/sys/SecureInfo_A", fullPath, false, fileCopyBuffer, sz);
sprintf(fullPath, "%sSecureInfo_B", pathStart);
ok = ok && fileCopy("nand:/rw/sys/SecureInfo_B", fullPath, false, fileCopyBuffer, sz); // often doesn't exist
if (!ok) return false; if (!ok) return false;
alignedseqmemcpy(fileCopyBuffer, (const void *)0x10012000, 0x100); alignedseqmemcpy(fileCopyBuffer, (const void *)0x10012000, 0x100);
sprintf(fullPath, "%sotp.bin", pathStart); if (getFileSize("backups/otp.bin") != 0x100)
if (getFileSize(fullPath) != 0x100) ok = ok && fileWrite(fileCopyBuffer, "backups/otp.bin", 0x100);
ok = ok && fileWrite(fileCopyBuffer, fullPath, 0x100);
if (!ok) return false; if (!ok) return false;
@ -482,38 +435,33 @@ static bool backupEssentialFiles(void)
u8 c = mcuConsoleInfo[0]; u8 c = mcuConsoleInfo[0];
if (c == 2 || c == 4 || (ISN3DS && c == 5) || c == 6) if (c == 2 || c == 4 || (ISN3DS && c == 5) || c == 6)
{ {
sprintf(fullPath, "%sHWCAL_01_EEPROM.dat", pathStart);
I2C_readRegBuf(I2C_DEV_EEPROM, 0, fileCopyBuffer, 0x1000); // Up to two instances of hwcal, with the second one @0x800 I2C_readRegBuf(I2C_DEV_EEPROM, 0, fileCopyBuffer, 0x1000); // Up to two instances of hwcal, with the second one @0x800
if (getFileSize(fullPath) != 0x1000) if (getFileSize("backups/HWCAL_01_EEPROM.dat") != 0x1000)
ok = ok && fileWrite(fileCopyBuffer, fullPath, 0x1000); ok = ok && fileWrite(fileCopyBuffer, "backups/HWCAL_01_EEPROM.dat", 0x1000);
} }
// B9S bootrom backups // B9S bootrom backups
u32 hash[32/4]; u32 hash[32/4];
sha(hash, (const void *)0x08080000, 0x10000, SHA_256_MODE); sha(hash, (const void *)0x08080000, 0x10000, SHA_256_MODE);
sprintf(fullPath, "%sboot9.bin", pathStart); if (memcmp(hash, boot9Sha256, 32) == 0 && getFileSize("backups/boot9.bin") != 0x10000)
if (memcmp(hash, boot9Sha256, 32) == 0 && getFileSize(fullPath) != 0x10000) ok = ok && fileWrite((const void *)0x08080000, "backups/boot9.bin", 0x10000);
ok = ok && fileWrite((const void *)0x08080000, fullPath, 0x10000);
sha(hash, (const void *)0x08090000, 0x10000, SHA_256_MODE); sha(hash, (const void *)0x08090000, 0x10000, SHA_256_MODE);
sprintf(fullPath, "%sboot11.bin", pathStart); if (memcmp(hash, boot11Sha256, 32) == 0 && getFileSize("backups/boot11.bin") != 0x10000)
if (memcmp(hash, boot11Sha256, 32) == 0 && getFileSize(fullPath) != 0x10000) ok = ok && fileWrite((const void *)0x08090000, "backups/boot11.bin", 0x10000);
ok = ok && fileWrite((const void *)0x08090000, fullPath, 0x10000);
return ok; return ok;
} }
bool doLumaUpgradeProcess(void) bool doLumaUpgradeProcess(void)
{ {
bool ok = true, ok2 = true;
// Ensure CTRNAND is mounted // Ensure CTRNAND is mounted
remountCtrNandPartition(false); bool ok = mountFs(false, false), ok2 = true;
if (!ok)
return false;
// Try to boot.firm to CTRNAND, when applicable // Try to boot.firm to CTRNAND, when applicable
#ifndef BUILD_FOR_EXPLOIT_DEV
if (isSdMode && memcmp(launchedPathForFatfs, "sdmc:", 5) == 0) if (isSdMode && memcmp(launchedPathForFatfs, "sdmc:", 5) == 0)
ok = fileCopy(launchedPathForFatfs, "nand:/boot.firm", true, fileCopyBuffer, sizeof(fileCopyBuffer)); ok = fileCopy(launchedPathForFatfs, "nand:/boot.firm", true, fileCopyBuffer, sizeof(fileCopyBuffer));
#endif
// Try to backup essential files // Try to backup essential files
ok2 = backupEssentialFiles(); ok2 = backupEssentialFiles();
@ -522,8 +470,5 @@ bool doLumaUpgradeProcess(void)
fileDelete("sdmc:/luma/config.bin"); fileDelete("sdmc:/luma/config.bin");
fileDelete("nand:/rw/luma/config.bin"); fileDelete("nand:/rw/luma/config.bin");
createDir("sdmc:/luma/payloads");
createDir("nand:/rw/luma/payloads");
return ok && ok2; return ok && ok2;
} }

View File

@ -30,16 +30,12 @@
#define PATTERN(a) a "_*.firm" #define PATTERN(a) a "_*.firm"
bool mountSdCardPartition(bool switchMainDir); bool mountFs(bool isSd, bool switchToCtrNand);
bool remountCtrNandPartition(bool switchMainDir);
void unmountPartitions(void);
u32 fileRead(void *dest, const char *path, u32 maxSize); u32 fileRead(void *dest, const char *path, u32 maxSize);
u32 getFileSize(const char *path); u32 getFileSize(const char *path);
bool fileWrite(const void *buffer, const char *path, u32 size); bool fileWrite(const void *buffer, const char *path, u32 size);
bool fileDelete(const char *path); bool fileDelete(const char *path);
bool fileCopy(const char *pathSrc, const char *pathDst, bool replace, void *tmpBuffer, size_t bufferSize); bool fileCopy(const char *pathSrc, const char *pathDst, bool replace, void *tmpBuffer, size_t bufferSize);
bool createDir(const char *path);
bool findPayload(char *path, u32 pressed); bool findPayload(char *path, u32 pressed);
bool payloadMenu(char *path, bool *hasDisplayedMenu); bool payloadMenu(char *path, bool *hasDisplayedMenu);
u32 firmRead(void *dest, u32 firmType); u32 firmRead(void *dest, u32 firmType);

View File

@ -40,8 +40,6 @@ typedef enum
I2C_DEV_CAMERA = 1, // Unconfirmed I2C_DEV_CAMERA = 1, // Unconfirmed
I2C_DEV_CAMERA2 = 2, // Unconfirmed I2C_DEV_CAMERA2 = 2, // Unconfirmed
I2C_DEV_MCU = 3, I2C_DEV_MCU = 3,
I2C_DEV_LCD_TOP = 5,
I2C_DEV_LCD_BOT = 6,
I2C_DEV_GYRO = 10, I2C_DEV_GYRO = 10,
I2C_DEV_DEBUG_PAD = 12, I2C_DEV_DEBUG_PAD = 12,
I2C_DEV_IR = 13, I2C_DEV_IR = 13,

View File

@ -28,11 +28,9 @@
#include "types.h" #include "types.h"
extern const u8 emunandPatch[], emunandProtoPatch[], emunandProtoCidPatch[]; extern const u8 emunandPatch[];
extern const u8 emunandProtoPatch238[]; extern const u32 emunandPatchSize;
extern const u32 emunandPatchSize, emunandPatchBssSize;
extern u32 emunandPatchSdmmcStructPtr, emunandPatchNandOffset, emunandPatchNcsdHeaderOffset; extern u32 emunandPatchSdmmcStructPtr, emunandPatchNandOffset, emunandPatchNcsdHeaderOffset;
extern u32 emunandPatchNandCid[4];
extern const u8 rebootPatch[]; extern const u8 rebootPatch[];
extern const u32 rebootPatchSize; extern const u32 rebootPatchSize;

View File

@ -1,3 +1,67 @@
.section .large_patch.emunand, "aw", %progbits
.arm
.align 4
@ Code originally by Normmatt
.global emunandPatch
emunandPatch:
@ Original code that still needs to be executed
mov r4, r0
mov r5, r1
mov r7, r2
mov r6, r3
@ End
@ If we're already trying to access the SD, return
ldr r2, [r0, #4]
ldr r1, emunandPatchSdmmcStructPtr
cmp r2, r1
beq out
str r1, [r0, #4] @ Set object to be SD
ldr r2, [r0, #8] @ Get sector to read
cmp r2, #0 @ For GW compatibility, see if we're trying to read the ncsd header (sector 0)
ldr r3, emunandPatchNandOffset
add r2, r3 @ Add the offset to the NAND in the SD
ldreq r3, emunandPatchNcsdHeaderOffset
addeq r2, r3 @ If we're reading the ncsd header, add the offset of that sector
str r2, [r0, #8] @ Store sector to read
out:
@ Restore registers.
mov r1, r5
mov r2, r7
mov r3, r6
@ Return 4 bytes behind where we got called,
@ due to the offset of this function being stored there
mov r0, lr
add r0, #4
bx r0
.pool
.global emunandPatchSdmmcStructPtr
.global emunandPatchNandOffset
.global emunandPatchNcsdHeaderOffset
emunandPatchSdmmcStructPtr: .word 0 @ Pointer to sdmmc struct
emunandPatchNandOffset: .word 0 @ For rednand this should be 1
emunandPatchNcsdHeaderOffset: .word 0 @ Depends on nand manufacturer + emunand type (GW/RED)
.pool
.balign 4
_emunandPatchEnd:
.global emunandPatchSize
emunandPatchSize:
.word _emunandPatchEnd - emunandPatch
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ Code originally from delebile and mid-kid @ Code originally from delebile and mid-kid

View File

@ -45,6 +45,7 @@ extern u8 __itcm_start__[], __itcm_lma__[], __itcm_bss_start__[], __itcm_end__[]
extern CfgData configData; extern CfgData configData;
extern ConfigurationStatus needConfig; extern ConfigurationStatus needConfig;
extern FirmwareSource firmSource;
bool isSdMode; bool isSdMode;
char launchedPathForFatfs[256]; char launchedPathForFatfs[256];
@ -56,16 +57,14 @@ u8 mcuConsoleInfo[9];
void main(int argc, char **argv, u32 magicWord) void main(int argc, char **argv, u32 magicWord)
{ {
bool isFirmProtEnabled = true, bool isFirmProtEnabled,
isSafeMode = false, isSafeMode = false,
needToInitSd = false, needToInitSd = false,
isNoForceFlagSet = false, isNoForceFlagSet = false,
isInvalidLoader = false, isInvalidLoader = false,
isNtrBoot = false; isNtrBoot;
FirmwareType firmType = NATIVE_FIRM; FirmwareType firmType;
FirmwareSource nandType = FIRMWARE_SYSNAND; FirmwareSource nandType;
u32 emunandIndex = 0;
const vu8 *bootMediaStatus = (const vu8 *)0x1FFFE00C; const vu8 *bootMediaStatus = (const vu8 *)0x1FFFE00C;
const vu32 *bootPartitionsStatus = (const vu32 *)0x1FFFE010; const vu32 *bootPartitionsStatus = (const vu32 *)0x1FFFE010;
u32 firmlaunchTidLow = 0; u32 firmlaunchTidLow = 0;
@ -146,18 +145,18 @@ void main(int argc, char **argv, u32 magicWord)
if(memcmp(launchedPath, u"sdmc", 8) == 0) if(memcmp(launchedPath, u"sdmc", 8) == 0)
{ {
if(!mountSdCardPartition(true)) error("Failed to mount SD."); if(!mountFs(true, false)) error("Failed to mount SD.");
isSdMode = true; isSdMode = true;
} }
else if(memcmp(launchedPath, u"nand", 8) == 0) else if(memcmp(launchedPath, u"nand", 8) == 0)
{ {
if(!remountCtrNandPartition(true)) error("Failed to mount CTRNAND."); if(!mountFs(false, true)) error("Failed to mount CTRNAND.");
isSdMode = false; isSdMode = false;
} }
else if(bootType == NTR || memcmp(launchedPath, u"firm", 8) == 0) else if(bootType == NTR || memcmp(launchedPath, u"firm", 8) == 0)
{ {
if(mountSdCardPartition(true)) isSdMode = true; if(mountFs(true, false)) isSdMode = true;
else if(remountCtrNandPartition(true)) isSdMode = false; else if(mountFs(false, true)) isSdMode = false;
else error("Failed to mount SD and CTRNAND."); else error("Failed to mount SD and CTRNAND.");
if(bootType == NTR) if(bootType == NTR)
@ -203,7 +202,7 @@ void main(int argc, char **argv, u32 magicWord)
} }
nandType = (FirmwareSource)BOOTCFG_NAND; nandType = (FirmwareSource)BOOTCFG_NAND;
emunandIndex = BOOTCFG_EMUINDEX; firmSource = (FirmwareSource)BOOTCFG_FIRM;
isFirmProtEnabled = !BOOTCFG_NTRCARDBOOT; isFirmProtEnabled = !BOOTCFG_NTRCARDBOOT;
goto boot; goto boot;
@ -228,12 +227,13 @@ void main(int argc, char **argv, u32 magicWord)
if(bootenv == 7) if(bootenv == 7)
{ {
nandType = FIRMWARE_SYSNAND; nandType = FIRMWARE_SYSNAND;
firmSource = (BOOTCFG_NAND != 0) == (BOOTCFG_FIRM != 0) ? FIRMWARE_SYSNAND : (FirmwareSource)BOOTCFG_FIRM;
// Prevent multiple boot options-forcing // Prevent multiple boot options-forcing
// This bit is a bit weird. Basically, as you return to Home Menu by pressing either // This bit is a bit weird. Basically, as you return to Home Menu by pressing either
// the HOME or POWER button, nandType will be overridden to "SysNAND" (needed). But, // the HOME or POWER button, nandType will be overridden to "SysNAND" (needed). But,
// if you reboot again (e.g. via Rosalina menu), it'll use your default settings. // if you reboot again (e.g. via Rosalina menu), it'll use your default settings.
if(nandType != BOOTCFG_NAND) isNoForceFlagSet = true; if(nandType != BOOTCFG_NAND || firmSource != BOOTCFG_FIRM) isNoForceFlagSet = true;
goto boot; goto boot;
} }
@ -247,7 +247,7 @@ void main(int argc, char **argv, u32 magicWord)
if(validTlnc || !(pressed || BOOTCFG_NOFORCEFLAG)) if(validTlnc || !(pressed || BOOTCFG_NOFORCEFLAG))
{ {
nandType = (FirmwareSource)BOOTCFG_NAND; nandType = (FirmwareSource)BOOTCFG_NAND;
emunandIndex = BOOTCFG_EMUINDEX; firmSource = (FirmwareSource)BOOTCFG_FIRM;
goto boot; goto boot;
} }
@ -280,6 +280,7 @@ void main(int argc, char **argv, u32 magicWord)
if(!CFG_BOOTENV && pressed == SAFE_MODE) if(!CFG_BOOTENV && pressed == SAFE_MODE)
{ {
nandType = FIRMWARE_SYSNAND; nandType = FIRMWARE_SYSNAND;
firmSource = FIRMWARE_SYSNAND;
isSafeMode = true; isSafeMode = true;
needToInitSd = true; needToInitSd = true;
@ -307,6 +308,7 @@ void main(int argc, char **argv, u32 magicWord)
if(!CFG_BOOTENV && pressed == SAFE_MODE) if(!CFG_BOOTENV && pressed == SAFE_MODE)
{ {
nandType = FIRMWARE_SYSNAND; nandType = FIRMWARE_SYSNAND;
firmSource = FIRMWARE_SYSNAND;
isSafeMode = true; isSafeMode = true;
needToInitSd = true; needToInitSd = true;
@ -320,29 +322,51 @@ void main(int argc, char **argv, u32 magicWord)
//If booting from CTRNAND, always use SysNAND //If booting from CTRNAND, always use SysNAND
if(!isSdMode) nandType = FIRMWARE_SYSNAND; if(!isSdMode) nandType = FIRMWARE_SYSNAND;
else nandType = (autoBootEmu == ((pressed & BUTTON_L1) == BUTTON_L1)) ? FIRMWARE_SYSNAND : FIRMWARE_EMUNAND;
//If R is pressed, boot the non-updated NAND with the FIRM of the opposite one
else if(pressed & BUTTON_R1)
{
if(CONFIG(USEEMUFIRM))
{
nandType = FIRMWARE_SYSNAND;
firmSource = FIRMWARE_EMUNAND;
}
else
{
nandType = FIRMWARE_EMUNAND;
firmSource = FIRMWARE_SYSNAND;
}
}
/* Else, boot the NAND the user set to autoboot or the opposite one, depending on L,
with their own FIRM */
else firmSource = nandType = (autoBootEmu == ((pressed & BUTTON_L1) == BUTTON_L1)) ? FIRMWARE_SYSNAND : FIRMWARE_EMUNAND;
//If we're booting EmuNAND or using EmuNAND FIRM, determine which one from the directional pad buttons, or otherwise from the config //If we're booting EmuNAND or using EmuNAND FIRM, determine which one from the directional pad buttons, or otherwise from the config
if(nandType == FIRMWARE_EMUNAND) if(nandType == FIRMWARE_EMUNAND || firmSource == FIRMWARE_EMUNAND)
{ {
FirmwareSource tempNand;
switch(pressed & DPAD_BUTTONS) switch(pressed & DPAD_BUTTONS)
{ {
case BUTTON_UP: case BUTTON_UP:
emunandIndex = 0; tempNand = FIRMWARE_EMUNAND;
break; break;
case BUTTON_RIGHT: case BUTTON_RIGHT:
emunandIndex = 1; tempNand = FIRMWARE_EMUNAND2;
break; break;
case BUTTON_DOWN: case BUTTON_DOWN:
emunandIndex = 2; tempNand = FIRMWARE_EMUNAND3;
break; break;
case BUTTON_LEFT: case BUTTON_LEFT:
emunandIndex = 3; tempNand = FIRMWARE_EMUNAND4;
break; break;
default: default:
emunandIndex = MULTICONFIG(DEFAULTEMU); tempNand = (FirmwareSource)(1 + MULTICONFIG(DEFAULTEMU));
break; break;
} }
if(nandType == FIRMWARE_EMUNAND) nandType = tempNand;
else firmSource = tempNand;
} }
boot: boot:
@ -350,21 +374,24 @@ boot:
//If we need to boot EmuNAND, make sure it exists //If we need to boot EmuNAND, make sure it exists
if(nandType != FIRMWARE_SYSNAND) if(nandType != FIRMWARE_SYSNAND)
{ {
locateEmuNand(&nandType, &emunandIndex, true); locateEmuNand(&nandType);
if(nandType == FIRMWARE_EMUNAND && (*(vu16 *)(SDMMC_BASE + REG_SDSTATUS0) & TMIO_STAT0_WRPROTECT) == 0) //Make sure the SD card isn't write protected if(nandType == FIRMWARE_SYSNAND) firmSource = FIRMWARE_SYSNAND;
else if((*(vu16 *)(SDMMC_BASE + REG_SDSTATUS0) & TMIO_STAT0_WRPROTECT) == 0) //Make sure the SD card isn't write protected
error("The SD card is locked, EmuNAND can not be used.\nPlease turn the write protection switch off."); error("The SD card is locked, EmuNAND can not be used.\nPlease turn the write protection switch off.");
} }
ctrNandLocation = nandType; // for CTRNAND partition //Same if we're using EmuNAND as the FIRM source
else if(firmSource != FIRMWARE_SYSNAND)
locateEmuNand(&firmSource);
if(bootType != FIRMLAUNCH) if(bootType != FIRMLAUNCH)
{ {
configData.bootConfig = ((bootType == NTR ? 1 : 0) << 4) | ((u32)isNoForceFlagSet << 3) | ((u32)emunandIndex << 1) | (u32)nandType; configData.bootConfig = ((bootType == NTR ? 1 : 0) << 7) | ((u32)isNoForceFlagSet << 6) | ((u32)firmSource << 3) | (u32)nandType;
writeConfig(false); writeConfig(false);
} }
bool loadFromStorage = CONFIG(LOADEXTFIRMSANDMODULES); bool loadFromStorage = CONFIG(LOADEXTFIRMSANDMODULES);
u32 firmVersion = loadNintendoFirm(&firmType, nandType, loadFromStorage, isSafeMode); u32 firmVersion = loadNintendoFirm(&firmType, firmSource, loadFromStorage, isSafeMode);
bool doUnitinfoPatch = CONFIG(PATCHUNITINFO); bool doUnitinfoPatch = CONFIG(PATCHUNITINFO);
u32 res = 0; u32 res = 0;
@ -386,14 +413,10 @@ boot:
case NATIVE_FIRM1X2X: case NATIVE_FIRM1X2X:
res = patch1x2xNativeAndSafeFirm(); res = patch1x2xNativeAndSafeFirm();
break; break;
case NATIVE_PROTOTYPE:
res = patchPrototypeNative(nandType);
break;
} }
if(res != 0) error("Failed to apply %u FIRM patch(es).", res); if(res != 0) error("Failed to apply %u FIRM patch(es).", res);
unmountPartitions();
if(bootType != FIRMLAUNCH) deinitScreens(); if(bootType != FIRMLAUNCH) deinitScreens();
launchFirm(0, NULL); launchFirm(0, NULL);
} }

View File

@ -44,9 +44,6 @@
#define K11EXT_VA 0x70000000 #define K11EXT_VA 0x70000000
extern u16 launchedPath[];
extern u32 firmProtoVersion;
u8 *getProcess9Info(u8 *pos, u32 size, u32 *process9Size, u32 *process9MemAddr) u8 *getProcess9Info(u8 *pos, u32 size, u32 *process9Size, u32 *process9MemAddr)
{ {
u8 *temp = memsearch(pos, "NCCH", size, 4); u8 *temp = memsearch(pos, "NCCH", size, 4);
@ -55,20 +52,10 @@ u8 *getProcess9Info(u8 *pos, u32 size, u32 *process9Size, u32 *process9MemAddr)
Cxi *off = (Cxi *)(temp - 0x100); Cxi *off = (Cxi *)(temp - 0x100);
*process9Size = (off->ncch.exeFsSize - 1) * 0x200;
*process9MemAddr = off->exHeader.systemControlInfo.textCodeSet.address; *process9MemAddr = off->exHeader.systemControlInfo.textCodeSet.address;
// Prototype FW has a different NCCH format return (u8 *)off + (off->ncch.exeFsOffset + 1) * 0x200;
if (firmProtoVersion && firmProtoVersion <= 243)
{
*process9Size = off->ncch.exeFsSize;
return (u8 *)off + off->ncch.exeFsOffset;
}
else
{
*process9Size = (off->ncch.exeFsSize - 1) * 0x200;
return (u8 *)off + (off->ncch.exeFsOffset + 1) * 0x200;
}
} }
u32 *getKernel11Info(u8 *pos, u32 size, u32 *baseK11VA, u8 **freeK11Space, u32 **arm11SvcHandler, u32 **arm11ExceptionsPage) u32 *getKernel11Info(u8 *pos, u32 size, u32 *baseK11VA, u8 **freeK11Space, u32 **arm11SvcHandler, u32 **arm11ExceptionsPage)
@ -143,10 +130,8 @@ u32 installK11Extension(u8 *pos, u32 size, bool needToInitSd, u32 baseK11VA, u32
u16 configFormatVersionMajor, configFormatVersionMinor; u16 configFormatVersionMajor, configFormatVersionMinor;
u32 config, multiConfig, bootConfig; u32 config, multiConfig, bootConfig;
u32 splashDurationMsec; u32 splashDurationMsec;
s8 volumeSliderOverride;
u64 hbldr3dsxTitleId; u64 hbldr3dsxTitleId;
u32 rosalinaMenuCombo; u32 rosalinaMenuCombo;
u32 pluginLoaderFlags;
s16 ntpTzOffetMinutes; s16 ntpTzOffetMinutes;
ScreenFiltersCfgData topScreenFilter; ScreenFiltersCfgData topScreenFilter;
@ -154,8 +139,6 @@ u32 installK11Extension(u8 *pos, u32 size, bool needToInitSd, u32 baseK11VA, u32
u64 autobootTwlTitleId; u64 autobootTwlTitleId;
u8 autobootCtrAppmemtype; u8 autobootCtrAppmemtype;
u16 launchedPath[80+1];
} info; } info;
}; };
@ -227,10 +210,8 @@ u32 installK11Extension(u8 *pos, u32 size, bool needToInitSd, u32 baseK11VA, u32
info->multiConfig = configData.multiConfig; info->multiConfig = configData.multiConfig;
info->bootConfig = configData.bootConfig; info->bootConfig = configData.bootConfig;
info->splashDurationMsec = configData.splashDurationMsec; info->splashDurationMsec = configData.splashDurationMsec;
info->volumeSliderOverride = configData.volumeSliderOverride;
info->hbldr3dsxTitleId = configData.hbldr3dsxTitleId; info->hbldr3dsxTitleId = configData.hbldr3dsxTitleId;
info->rosalinaMenuCombo = configData.rosalinaMenuCombo; info->rosalinaMenuCombo = configData.rosalinaMenuCombo;
info->pluginLoaderFlags = configData.pluginLoaderFlags;
info->ntpTzOffetMinutes = configData.ntpTzOffetMinutes; info->ntpTzOffetMinutes = configData.ntpTzOffetMinutes;
info->topScreenFilter = configData.topScreenFilter; info->topScreenFilter = configData.topScreenFilter;
info->bottomScreenFilter = configData.bottomScreenFilter; info->bottomScreenFilter = configData.bottomScreenFilter;
@ -245,8 +226,6 @@ u32 installK11Extension(u8 *pos, u32 size, bool needToInitSd, u32 baseK11VA, u32
if(needToInitSd) info->flags |= 1 << 5; if(needToInitSd) info->flags |= 1 << 5;
if(isSdMode) info->flags |= 1 << 6; if(isSdMode) info->flags |= 1 << 6;
memcpy(info->launchedPath, launchedPath, sizeof(info->launchedPath));
return 0; return 0;
} }
@ -478,7 +457,7 @@ u32 patchCheckForDevCommonKey(u8 *pos, u32 size)
return 0; return 0;
} }
u32 patchK11ModuleLoading(u32 oldKipSectionSize, u32 newKipSectionSize, u32 numKips, u8 *pos, u32 size) u32 patchK11ModuleLoading(u32 section0size, u32 modulesSize, u8 *pos, u32 size)
{ {
static const u8 moduleLoadingPattern[] = {0xE2, 0x05, 0x00, 0x57}, static const u8 moduleLoadingPattern[] = {0xE2, 0x05, 0x00, 0x57},
modulePidPattern[] = {0x06, 0xA0, 0xE1, 0xF2}; //GetSystemInfo modulePidPattern[] = {0x06, 0xA0, 0xE1, 0xF2}; //GetSystemInfo
@ -487,44 +466,20 @@ u32 patchK11ModuleLoading(u32 oldKipSectionSize, u32 newKipSectionSize, u32 numK
if(off == NULL) return 1; if(off == NULL) return 1;
off[1] = (u8)numKips; off[1]++;
u32 *off32; u32 *off32;
for(off32 = (u32 *)(off - 3); *off32 != 0xE59F0000; off32++); for(off32 = (u32 *)(off - 3); *off32 != 0xE59F0000; off32++);
off32 += 2; off32 += 2;
off32[1] = off32[0] + newKipSectionSize; off32[1] = off32[0] + modulesSize;
for(; *off32 != oldKipSectionSize; off32++); for(; *off32 != section0size; off32++);
*off32 = ((newKipSectionSize + 0x1FF) >> 9) << 9; *off32 = ((modulesSize + 0x1FF) >> 9) << 9;
off = memsearch(pos, modulePidPattern, size, 4); off = memsearch(pos, modulePidPattern, size, 4);
if(off == NULL) return 1; if(off == NULL) return 1;
off[0xB] = (u8)numKips; off[0xB] = 6;
return 0;
}
u32 patchK11ModuleLoadingLgy(u32 newKipSectionSize, u8 *pos, u32 size)
{
// Patch the function where TwlBg/AgbBg is copied from 18000000 (VRAM) to 21000000 (FCRAM).
// This is where we can also automatically obtain the section size
u16 *off = (u16 *)pos;
for (; (u8 *)off < pos + size && (off[0] != 0x06C9 || off[1] != 0x0600); off++);
if ((u8 *)off >= pos + size)
return 3;
off += 7;
u32 oldKipSectionSize = *(u32 *)off;
*(u32 *)off = newKipSectionSize;
off += 2;
u32 *off2 = (u32 *)off;
for (; (u8 *)off2 < pos + size && *off2 != oldKipSectionSize; off2++);
if ((u8 *)off2 >= pos + size)
return 4;
*off2 = newKipSectionSize;
return 0; return 0;
} }
@ -779,120 +734,3 @@ u32 patchAgbBootSplash(u8 *pos, u32 size)
return 0; return 0;
} }
void patchTwlBg(u8 *pos, u32 size)
{
// You can use the following Python code to convert something like below
// into twl_upscaling_filter.bin:
// import struct; open("twl_upscaling_filter.bin", "wb+").write(struct.pack("<30H", [array contents]))
static const u16 nintendoFilterTwl[] = {
0x0000, 0x004E, 0x011D, 0x01E3, 0x01C1,
0x0000, 0xFCA5, 0xF8D0, 0xF69D, 0xF873,
0x0000, 0x0D47, 0x1E35, 0x2F08, 0x3B6F,
0x4000, 0x3B6F, 0x2F08, 0x1E35, 0x0D47,
0x0000, 0xF873, 0xF69D, 0xF8D0, 0xFCA5,
0x0000, 0x01C1, 0x01E3, 0x011D, 0x004E,
};
// "error" func doesn't seem to work here
if (CONFIG(ENABLEDSIEXTFILTER))
{
u16 filter[5*6] = { 0 };
u32 rd = fileRead(filter, "twl_upscaling_filter.bin", sizeof(filter));
if (rd == sizeof(filter))
{
// else error("Failed to apply enable_dsi_external_filter:\n\ntwl_upscaling_filter.bin is missing or invalid.");
u8 *off = memsearch(pos, nintendoFilterTwl, size, sizeof(nintendoFilterTwl));
if (off != NULL)
memcpy(off, filter, sizeof(filter));
// else error("Failed to apply enable_dsi_external_filter.");
}
}
}
u32 patchLgyK11(u8 *section1, u32 section1Size, u8 *section2, u32 section2Size)
{
u32 *off;
// Fix a bug where Legacy K11 maps user TLS with "user no access" permissions
// Map it as RWX (just like the rest of other user-accessible pages) instead
for (off = (u32 *)section1; (u8 *)off <= section1 + section1Size && *off != 0xE0100000; off++);
if ((u8 *)off >= section1 + section1Size)
return 1;
++off;
*off &= ~0x231; // clear APX mask and XN
*off |= 0x030; // re-set APX (to user/kernel RW)
// Patch two pointer-to-bool to point to a non-zero byte, enabling user exception handling.
// It is impossible to enable it by normal means, otherwise
for (off = (u32 *)section2; (u8 *)off <= section2 + section2Size && *off != 0x100021F; off++);
if ((u8 *)off >= section2 + section2Size)
return 1;
off[1] = 0xFFFF0F00;
off[2] = 0xFFFF0F04;
// Dispatch-to-user code checks for memory block type and permissions (etc.), but
// LGY K11 doesn't do any memory management, so these checks will always fail.
// Patch with b +0x38 to skip all those checks
u16 *off2;
for (off2 = (u16 *)section2; (u8 *)off2 <= section2 + section2Size && (off2[0] != 0xDB1F || off2[1] != 0x4915); off2++);
if ((u8 *)off2 >= section2 + section2Size)
return 1;
*off2 = 0xE01A;
// Patch kernelpanic to skip devunit check, so that it sets the LCD fill regs
// which are useful to detect such panics
u16 *off3;
for (off3 = (u16 *)section1; (u8 *)off3 <= section1 + section1Size && (off3[0] != 0x481D || off3[1] != 0xB570); off3++);
if ((u8 *)off3 >= section1 + section1Size)
return 1;
off3[2] = 0x2001; // movs r0, #1
// Patch kernel to avoid allocating the two "configuration memory" pages, freeing
// 0x2000 bytes of kernel "heap" (which is 0xD000 AXIWRAM bytes on LGY K11 instead
// of the entire FCRAM on NFIRM). This is indeed a bug because if prevents two of the
// 12 KThread objects from being created
u16 *off4;
for (off4 = (u16 *)section1; (u8 *)off4 <= section1 + section1Size && (off4[0] != 0xB570 || off4[1] != 0x2200); off4++);
if ((u8 *)off4 >= section1 + section1Size)
return 1;
*off4 = 0x4770; // bx lr
return 0;
}
u32 patchProtoNandSignatureCheck(u8 *pos, u32 size) {
if (firmProtoVersion == 243) {
static const u8 pattern[] = {0x08, 0x31, 0x9F, 0xE5};
// Signature check function returns 0 if failed and 1 if succeeded.
// Proc9 breaks if the returned value is 0, change it to break if
// the returned value is 2 (never).
u8 *off = memsearch(pos, pattern, size, sizeof(pattern));
if (!off)
return 1;
off[0x20] = 2;
}
else if (firmProtoVersion == 238) { // SDK 0.10
// Same patch as for v243 ported to the different ncsd_read() function
static const u8 pattern[] = {
0x00, 0x11, 0x9f, 0xe5,
0x00, 0x51, 0x9f, 0xe5,
};
u8 *off = memsearch(pos, pattern, size, sizeof(pattern));
if (!off)
return 1;
off[0x20] = 2;
}
else return 1;
return 0;
}

View File

@ -31,7 +31,6 @@
* FIRM partition writes patches by delebile * FIRM partition writes patches by delebile
* Idea for svcBreak patches from yellows8 and others on #3dsdev * Idea for svcBreak patches from yellows8 and others on #3dsdev
* TWL_FIRM patches by Steveice10 and others * TWL_FIRM patches by Steveice10 and others
* Signature patches for prototype FW by PabloMK7
*/ */
#pragma once #pragma once
@ -51,8 +50,7 @@ u32 patchTitleInstallMinVersionChecks(u8 *pos, u32 size, u32 firmVersion);
u32 patchZeroKeyNcchEncryptionCheck(u8 *pos, u32 size); u32 patchZeroKeyNcchEncryptionCheck(u8 *pos, u32 size);
u32 patchNandNcchEncryptionCheck(u8 *pos, u32 size); u32 patchNandNcchEncryptionCheck(u8 *pos, u32 size);
u32 patchCheckForDevCommonKey(u8 *pos, u32 size); u32 patchCheckForDevCommonKey(u8 *pos, u32 size);
u32 patchK11ModuleLoading(u32 oldKipSectionSize, u32 newKipSectionSize, u32 numKips, u8 *pos, u32 size); u32 patchK11ModuleLoading(u32 section0size, u32 modulesSize, u8 *startPos, u32 size);
u32 patchK11ModuleLoadingLgy(u32 newKipSectionSize, u8 *pos, u32 size);
u32 patchArm9ExceptionHandlersInstall(u8 *pos, u32 size); u32 patchArm9ExceptionHandlersInstall(u8 *pos, u32 size);
u32 patchSvcBreak9(u8 *pos, u32 size, u32 kernel9Address); u32 patchSvcBreak9(u8 *pos, u32 size, u32 kernel9Address);
u32 patchKernel9Panic(u8 *pos, u32 size); u32 patchKernel9Panic(u8 *pos, u32 size);
@ -67,6 +65,3 @@ u32 patchTwlFlashcartChecks(u8 *pos, u32 size, u32 firmVersion);
u32 patchOldTwlFlashcartChecks(u8 *pos, u32 size); u32 patchOldTwlFlashcartChecks(u8 *pos, u32 size);
u32 patchTwlShaHashChecks(u8 *pos, u32 size); u32 patchTwlShaHashChecks(u8 *pos, u32 size);
u32 patchAgbBootSplash(u8 *pos, u32 size); u32 patchAgbBootSplash(u8 *pos, u32 size);
void patchTwlBg(u8 *pos, u32 size); // silently fails
u32 patchLgyK11(u8 *section1, u32 section1Size, u8 *section2, u32 section2Size);
u32 patchProtoNandSignatureCheck(u8 *pos, u32 size);

View File

@ -70,14 +70,6 @@ void prepareArm11ForFirmlaunch(void)
void deinitScreens(void) void deinitScreens(void)
{ {
if(ARESCREENSINITIALIZED) invokeArm11Function(DEINIT_SCREENS); if(ARESCREENSINITIALIZED) invokeArm11Function(DEINIT_SCREENS);
// Backlight voltage off
I2C_writeReg(I2C_DEV_MCU, 0x22, 0x14);
wait(50);
// LCD panel voltage off
I2C_writeReg(I2C_DEV_MCU, 0x22, 0x01);
wait(50);
} }
void updateBrightness(u32 brightnessIndex) void updateBrightness(u32 brightnessIndex)
@ -110,31 +102,8 @@ void initScreens(void)
memcpy((void *)(ARM11_PARAMETERS_ADDRESS + 4), fbs, sizeof(fbs)); memcpy((void *)(ARM11_PARAMETERS_ADDRESS + 4), fbs, sizeof(fbs));
invokeArm11Function(INIT_SCREENS); invokeArm11Function(INIT_SCREENS);
// Fragile code, needs proper fix/total rewrite of the baremetal components anyway //Turn on backlight
// Assume controller revision is not 0x00 for either screen (this revision is extremely I2C_writeReg(I2C_DEV_MCU, 0x22, 0x2A);
// old and shouldn't be seen in retail units nor normal devunits)
// Controller reset off
I2C_writeReg(I2C_DEV_LCD_TOP, 0xFE, 0xAA);
I2C_writeReg(I2C_DEV_LCD_BOT, 0xFE, 0xAA);
wait(5);
// Controller power on
I2C_writeReg(I2C_DEV_LCD_TOP, 0x01, 0x10);
I2C_writeReg(I2C_DEV_LCD_BOT, 0x01, 0x10);
wait(5);
// Clear error flag
I2C_writeReg(I2C_DEV_LCD_TOP, 0x60, 0x00);
I2C_writeReg(I2C_DEV_LCD_BOT, 0x60, 0x00);
wait(5);
// LCD panel (bias ?) voltage on
I2C_writeReg(I2C_DEV_MCU, 0x22, 0x02);
wait(50);
// Backlight voltage on
I2C_writeReg(I2C_DEV_MCU, 0x22, 0x28);
wait(5); wait(5);
} }
else updateBrightness(MULTICONFIG(BRIGHTNESS)); else updateBrightness(MULTICONFIG(BRIGHTNESS));
@ -149,8 +118,3 @@ void initScreens(void)
clearScreens(false); clearScreens(false);
swapFramebuffers(false); swapFramebuffers(false);
} }
void zerofillN3dsAblRegisters(void)
{
invokeArm11Function(ZEROFILL_N3DS_ABL_REGISTERS);
}

View File

@ -59,7 +59,6 @@ typedef enum
SWAP_FRAMEBUFFERS, SWAP_FRAMEBUFFERS,
UPDATE_BRIGHTNESS, UPDATE_BRIGHTNESS,
DEINIT_SCREENS, DEINIT_SCREENS,
ZEROFILL_N3DS_ABL_REGISTERS,
PREPARE_ARM11_FOR_FIRMLAUNCH, PREPARE_ARM11_FOR_FIRMLAUNCH,
ARM11_READY, ARM11_READY,
} Arm11Operation; } Arm11Operation;
@ -74,4 +73,3 @@ void swapFramebuffers(bool isAlternate);
void updateBrightness(u32 brightnessIndex); void updateBrightness(u32 brightnessIndex);
void clearScreens(bool isAlternate); void clearScreens(bool isAlternate);
void initScreens(void); void initScreens(void);
void zerofillN3dsAblRegisters(void);

View File

@ -64,7 +64,6 @@ typedef volatile s64 vs64;
typedef struct ScreenFiltersCfgData { typedef struct ScreenFiltersCfgData {
u16 cct; u16 cct;
bool invert; bool invert;
u8 colorCurveCorrection;
s64 gammaEnc; s64 gammaEnc;
s64 contrastEnc; s64 contrastEnc;
s64 brightnessEnc; s64 brightnessEnc;
@ -75,11 +74,9 @@ typedef struct CfgData {
u32 config, multiConfig, bootConfig; u32 config, multiConfig, bootConfig;
u32 splashDurationMsec; u32 splashDurationMsec;
s8 volumeSliderOverride;
u64 hbldr3dsxTitleId; u64 hbldr3dsxTitleId;
u32 rosalinaMenuCombo; u32 rosalinaMenuCombo;
u32 pluginLoaderFlags;
s16 ntpTzOffetMinutes; s16 ntpTzOffetMinutes;
ScreenFiltersCfgData topScreenFilter; ScreenFiltersCfgData topScreenFilter;
@ -125,6 +122,9 @@ typedef enum FirmwareSource
{ {
FIRMWARE_SYSNAND = 0, FIRMWARE_SYSNAND = 0,
FIRMWARE_EMUNAND, FIRMWARE_EMUNAND,
FIRMWARE_EMUNAND2,
FIRMWARE_EMUNAND3,
FIRMWARE_EMUNAND4
} FirmwareSource; } FirmwareSource;
typedef enum FirmwareType typedef enum FirmwareType
@ -134,8 +134,7 @@ typedef enum FirmwareType
AGB_FIRM, AGB_FIRM,
SAFE_FIRM, SAFE_FIRM,
SYSUPDATER_FIRM, SYSUPDATER_FIRM,
NATIVE_FIRM1X2X, NATIVE_FIRM1X2X
NATIVE_PROTOTYPE,
} FirmwareType; } FirmwareType;
typedef enum bootType typedef enum bootType

View File

@ -113,11 +113,8 @@ u32 waitInput(bool isMenu)
return key; return key;
} }
__attribute__((noreturn)) void mcuPowerOff(void) void mcuPowerOff(void)
{ {
// Unmount partitions
unmountPartitions();
if(!needToSetupScreens) clearScreens(false); if(!needToSetupScreens) clearScreens(false);
//Shutdown LCD //Shutdown LCD
@ -158,44 +155,23 @@ void error(const char *fmt, ...)
mcuPowerOff(); mcuPowerOff();
} }
// CRC-16/MODBUS
u16 crc16(const void *data, size_t size, u16 initialValue) u16 crc16(const void *data, size_t size, u16 initialValue)
{ {
static const u16 lut[256] = { static u16 lut[256] = {0};
0x0000,0xC0C1,0xC181,0x0140,0xC301,0x03C0,0x0280,0xC241, static bool lutInitialized = false;
0xC601,0x06C0,0x0780,0xC741,0x0500,0xC5C1,0xC481,0x0440,
0xCC01,0x0CC0,0x0D80,0xCD41,0x0F00,0xCFC1,0xCE81,0x0E40, if (!lutInitialized)
0x0A00,0xCAC1,0xCB81,0x0B40,0xC901,0x09C0,0x0880,0xC841, {
0xD801,0x18C0,0x1980,0xD941,0x1B00,0xDBC1,0xDA81,0x1A40, static const u16 poly = 0xA001;
0x1E00,0xDEC1,0xDF81,0x1F40,0xDD01,0x1DC0,0x1C80,0xDC41, for (u32 i = 0; i < 256; i++)
0x1400,0xD4C1,0xD581,0x1540,0xD701,0x17C0,0x1680,0xD641, {
0xD201,0x12C0,0x1380,0xD341,0x1100,0xD1C1,0xD081,0x1040, u16 r = i;
0xF001,0x30C0,0x3180,0xF141,0x3300,0xF3C1,0xF281,0x3240, for (u32 j = 0; j < 8; j++)
0x3600,0xF6C1,0xF781,0x3740,0xF501,0x35C0,0x3480,0xF441, r = (r >> 1) ^ ((r & 1) != 0 ? poly : 0);
0x3C00,0xFCC1,0xFD81,0x3D40,0xFF01,0x3FC0,0x3E80,0xFE41, lut[i] = r;
0xFA01,0x3AC0,0x3B80,0xFB41,0x3900,0xF9C1,0xF881,0x3840, }
0x2800,0xE8C1,0xE981,0x2940,0xEB01,0x2BC0,0x2A80,0xEA41, lutInitialized = true;
0xEE01,0x2EC0,0x2F80,0xEF41,0x2D00,0xEDC1,0xEC81,0x2C40, }
0xE401,0x24C0,0x2580,0xE541,0x2700,0xE7C1,0xE681,0x2640,
0x2200,0xE2C1,0xE381,0x2340,0xE101,0x21C0,0x2080,0xE041,
0xA001,0x60C0,0x6180,0xA141,0x6300,0xA3C1,0xA281,0x6240,
0x6600,0xA6C1,0xA781,0x6740,0xA501,0x65C0,0x6480,0xA441,
0x6C00,0xACC1,0xAD81,0x6D40,0xAF01,0x6FC0,0x6E80,0xAE41,
0xAA01,0x6AC0,0x6B80,0xAB41,0x6900,0xA9C1,0xA881,0x6840,
0x7800,0xB8C1,0xB981,0x7940,0xBB01,0x7BC0,0x7A80,0xBA41,
0xBE01,0x7EC0,0x7F80,0xBF41,0x7D00,0xBDC1,0xBC81,0x7C40,
0xB401,0x74C0,0x7580,0xB541,0x7700,0xB7C1,0xB681,0x7640,
0x7200,0xB2C1,0xB381,0x7340,0xB101,0x71C0,0x7080,0xB041,
0x5000,0x90C1,0x9181,0x5140,0x9301,0x53C0,0x5280,0x9241,
0x9601,0x56C0,0x5780,0x9741,0x5500,0x95C1,0x9481,0x5440,
0x9C01,0x5CC0,0x5D80,0x9D41,0x5F00,0x9FC1,0x9E81,0x5E40,
0x5A00,0x9AC1,0x9B81,0x5B40,0x9901,0x59C0,0x5880,0x9841,
0x8801,0x48C0,0x4980,0x8941,0x4B00,0x8BC1,0x8A81,0x4A40,
0x4E00,0x8EC1,0x8F81,0x4F40,0x8D01,0x4DC0,0x4C80,0x8C41,
0x4400,0x84C1,0x8581,0x4540,0x8701,0x47C0,0x4680,0x8641,
0x8201,0x42C0,0x4380,0x8341,0x4100,0x81C1,0x8081,0x4040,
};
u16 r = initialValue; u16 r = initialValue;
const u8 *data8 = (const u8 *)data; const u8 *data8 = (const u8 *)data;
@ -207,40 +183,21 @@ u16 crc16(const void *data, size_t size, u16 initialValue)
u32 crc32(const void *data, size_t size, u32 initialValue) u32 crc32(const void *data, size_t size, u32 initialValue)
{ {
static const u32 lut[256] = { static u32 lut[256] = {0};
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3, static bool lutInitialized = false;
0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7, if (!lutInitialized)
0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5, {
0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B, static const u32 poly = 0xEDB88320;
0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59, for (u32 i = 0; i < 256; i++)
0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F, {
0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D, u32 r = i;
0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433, for (u32 j = 0; j < 8; j++)
0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01, r = (r >> 1) ^ ((r & 1) != 0 ? poly : 0);
0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457, lut[i] = r;
0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65, }
0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB, lutInitialized = true;
0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9, }
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,
0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,
0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,
0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,
0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,
0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,
0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,
0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,
0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,
0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
};
u32 r = initialValue; u32 r = initialValue;
const u8 *data8 = (const u8 *)data; const u8 *data8 = (const u8 *)data;

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

View File

@ -9,10 +9,10 @@
#define MULTICONFIG(a) ((cfwInfo.multiConfig >> (2 * (a))) & 3) #define MULTICONFIG(a) ((cfwInfo.multiConfig >> (2 * (a))) & 3)
#define BOOTCONFIG(a, b) ((cfwInfo.bootConfig >> (a)) & (b)) #define BOOTCONFIG(a, b) ((cfwInfo.bootConfig >> (a)) & (b))
#define BOOTCFG_NAND BOOTCONFIG(0, 1) #define BOOTCFG_NAND BOOTCONFIG(0, 7)
#define BOOTCFG_EMUINDEX BOOTCONFIG(1, 3) #define BOOTCFG_FIRM BOOTCONFIG(3, 7)
#define BOOTCFG_NOFORCEFLAG BOOTCONFIG(3, 1) #define BOOTCFG_NOFORCEFLAG BOOTCONFIG(6, 1)
#define BOOTCFG_NTRCARDBOOT BOOTCONFIG(4, 1) #define BOOTCFG_NTRCARDBOOT BOOTCONFIG(7, 1)
enum multiOptions enum multiOptions
{ {
@ -28,13 +28,13 @@ enum multiOptions
enum singleOptions enum singleOptions
{ {
AUTOBOOTEMU = 0, AUTOBOOTEMU = 0,
USEEMUFIRM,
LOADEXTFIRMSANDMODULES, LOADEXTFIRMSANDMODULES,
PATCHGAMES, PATCHGAMES,
REDIRECTAPPTHREADS, REDIRECTAPPTHREADS,
PATCHVERSTRING, PATCHVERSTRING,
SHOWGBABOOT, SHOWGBABOOT,
PATCHUNITINFO, PATCHUNITINFO,
ENABLEDSIEXTFILTER,
DISABLEARM11EXCHANDLERS, DISABLEARM11EXCHANDLERS,
ENABLESAFEFIRMROSALINA, ENABLESAFEFIRMROSALINA,
}; };

View File

@ -31,7 +31,6 @@
extern KRecursiveLock *criticalSectionLock; extern KRecursiveLock *criticalSectionLock;
extern KObjectList *threadList; extern KObjectList *threadList;
extern KObjectList *resourceLimitList;
extern KObjectMutex *synchronizationMutex; extern KObjectMutex *synchronizationMutex;
extern void (*KRecursiveLock__Lock)(KRecursiveLock *this); extern void (*KRecursiveLock__Lock)(KRecursiveLock *this);
@ -45,27 +44,18 @@ extern KAutoObject * (*KProcessHandleTable__ToKAutoObject)(KProcessHandleTable *
extern void (*KSynchronizationObject__Signal)(KSynchronizationObject *this, bool isPulse); extern void (*KSynchronizationObject__Signal)(KSynchronizationObject *this, bool isPulse);
extern Result (*WaitSynchronization1)(void *this_unused, KThread *thread, KSynchronizationObject *syncObject, s64 timeout); extern Result (*WaitSynchronization1)(void *this_unused, KThread *thread, KSynchronizationObject *syncObject, s64 timeout);
extern Result (*KProcessHandleTable__CreateHandle)(KProcessHandleTable *this, Handle *out, KAutoObject *obj, u8 token); extern Result (*KProcessHandleTable__CreateHandle)(KProcessHandleTable *this, Handle *out, KAutoObject *obj, u8 token);
extern Result (*KProcessHwInfo__QueryMemory)(KProcessHwInfo *this, MemoryInfo *memoryInfo, PageInfo *pageInfo, void *address);
extern Result (*KProcessHwInfo__MapProcessMemory)(KProcessHwInfo *this, KProcessHwInfo *other, void *dst, void *src, u32 nbPages); extern Result (*KProcessHwInfo__MapProcessMemory)(KProcessHwInfo *this, KProcessHwInfo *other, void *dst, void *src, u32 nbPages);
extern Result (*KProcessHwInfo__UnmapProcessMemory)(KProcessHwInfo *this, void *addr, u32 nbPages); extern Result (*KProcessHwInfo__UnmapProcessMemory)(KProcessHwInfo *this, void *addr, u32 nbPages);
extern Result (*KProcessHwInfo__CheckVaState)(KProcessHwInfo *hwInfo, u32 va, u32 size, u32 state, u32 perm);
extern Result (*KProcessHwInfo__GetListOfKBlockInfoForVA)(KProcessHwInfo *hwInfo, KLinkedList *list, u32 va, u32 sizeInPage);
extern Result (*KProcessHwInfo__MapListOfKBlockInfo)(KProcessHwInfo *this, u32 va, KLinkedList *list, u32 state, u32 perm, u32 sbz);
extern Result (*KEvent__Clear)(KEvent *this); extern Result (*KEvent__Clear)(KEvent *this);
extern Result (*KEvent__Signal)(KEvent *this);
extern void (*KObjectMutex__WaitAndAcquire)(KObjectMutex *this); extern void (*KObjectMutex__WaitAndAcquire)(KObjectMutex *this);
extern void (*KObjectMutex__ErrorOccured)(void); extern void (*KObjectMutex__ErrorOccured)(void);
extern void (*KScheduler__AdjustThread)(KScheduler *this, KThread *thread, u32 oldSchedulingMask); extern void (*KScheduler__AdjustThread)(KScheduler *this, KThread *thread, u32 oldSchedulingMask);
extern void (*KScheduler__AttemptSwitchingThreadContext)(KScheduler *this); extern void (*KScheduler__AttemptSwitchingThreadContext)(KScheduler *this);
extern void (*KLinkedList_KBlockInfo__Clear)(KLinkedList *list);
extern Result (*ControlMemory)(u32 *addrOut, u32 addr0, u32 addr1, u32 size, MemOp op, MemPerm perm, bool isLoader); extern Result (*ControlMemory)(u32 *addrOut, u32 addr0, u32 addr1, u32 size, MemOp op, MemPerm perm, bool isLoader);
extern Result (*doControlMemory)(KProcessHwInfo *this, u32 addr, u32 requestedNbPages, u32 pa, u32 state, u32 perm, u32 a7, u32 region);
extern Result (*CreateThread)(Handle *outThreadHandle, u32 ep, u32 arg, u32 stackTop, s32 priority, s32 processorId); extern Result (*CreateThread)(Handle *outThreadHandle, u32 ep, u32 arg, u32 stackTop, s32 priority, s32 processorId);
extern void (*SleepThread)(s64 ns); extern void (*SleepThread)(s64 ns);
extern Result (*CreateEvent)(Handle *out, ResetType resetType);
extern Result (*CloseHandle)(Handle handle); extern Result (*CloseHandle)(Handle handle);
extern Result (*GetHandleInfo)(s64 *out, Handle handle, u32 type); extern Result (*GetHandleInfo)(s64 *out, Handle handle, u32 type);
extern Result (*GetSystemInfo)(s64 *out, s32 type, s32 param); extern Result (*GetSystemInfo)(s64 *out, s32 type, s32 param);
@ -76,7 +66,6 @@ extern Result (*SendSyncRequest)(Handle handle);
extern Result (*OpenProcess)(Handle *out, u32 processId); extern Result (*OpenProcess)(Handle *out, u32 processId);
extern Result (*GetProcessId)(u32 *out, Handle process); extern Result (*GetProcessId)(u32 *out, Handle process);
extern Result (*DebugActiveProcess)(Handle *out, u32 processId); extern Result (*DebugActiveProcess)(Handle *out, u32 processId);
extern Result (*SignalEvent)(Handle event);
extern Result (*UnmapProcessMemory)(Handle processHandle, void *dst, u32 size); extern Result (*UnmapProcessMemory)(Handle processHandle, void *dst, u32 size);
extern Result (*KernelSetState)(u32 type, u32 varg1, u32 varg2, u32 varg3); extern Result (*KernelSetState)(u32 type, u32 varg1, u32 varg2, u32 varg3);
@ -109,7 +98,6 @@ extern bool *isDevUnit;
extern vu8 *configPage; extern vu8 *configPage;
extern u32 kernelVersion; extern u32 kernelVersion;
extern FcramLayout fcramLayout; extern FcramLayout fcramLayout;
extern FcramDescriptor *fcramDescriptor;
extern KCoreContext *coreCtxs; extern KCoreContext *coreCtxs;
@ -123,15 +111,13 @@ extern Result (*InterruptManager__MapInterrupt)(InterruptManager *manager, KBase
extern InterruptManager *interruptManager; extern InterruptManager *interruptManager;
extern KBaseInterruptEvent *customInterruptEvent; extern KBaseInterruptEvent *customInterruptEvent;
extern void (*initFPU)(void); extern void (*initFPU)(void);
extern void (*mcuReboot)(void); extern void (*mcuReboot)(void);
extern void (*coreBarrier)(void); extern void (*coreBarrier)(void);
extern void* (*kAlloc)(FcramDescriptor *fcramDesc, u32 nbPages, u32 alignment, u32 region);
typedef struct ScreenFiltersCfgData { typedef struct ScreenFiltersCfgData {
u16 cct; u16 cct;
bool invert; bool invert;
u8 colorCurveCorrection;
s64 gammaEnc; s64 gammaEnc;
s64 contrastEnc; s64 contrastEnc;
s64 brightnessEnc; s64 brightnessEnc;
@ -151,10 +137,8 @@ typedef struct CfwInfo
u16 configFormatVersionMajor, configFormatVersionMinor; u16 configFormatVersionMajor, configFormatVersionMinor;
u32 config, multiConfig, bootConfig; u32 config, multiConfig, bootConfig;
u32 splashDurationMsec; u32 splashDurationMsec;
s8 volumeSliderOverride;
u64 hbldr3dsxTitleId; u64 hbldr3dsxTitleId;
u32 rosalinaMenuCombo; u32 rosalinaMenuCombo;
u32 pluginLoaderFlags;
s16 ntpTzOffetMinutes; s16 ntpTzOffetMinutes;
ScreenFiltersCfgData topScreenFilter; ScreenFiltersCfgData topScreenFilter;
@ -162,31 +146,11 @@ typedef struct CfwInfo
u64 autobootTwlTitleId; u64 autobootTwlTitleId;
u8 autobootCtrAppmemtype; u8 autobootCtrAppmemtype;
u16 launchedPath[80+1];
} CfwInfo; } CfwInfo;
extern CfwInfo cfwInfo; extern CfwInfo cfwInfo;
extern u32 kextBasePa; extern u32 kextBasePa;
extern u32 stolenSystemMemRegionSize; extern u32 stolenSystemMemRegionSize;
extern bool disableThreadRedirection;
extern vu32 rosalinaState; extern vu32 rosalinaState;
extern bool hasStartedRosalinaNetworkFuncsOnce; extern bool hasStartedRosalinaNetworkFuncsOnce;
extern KEvent* signalPluginEvent;
typedef enum
{
PLG_CFG_NONE = 0,
PLG_CFG_RUNNING = 1,
PLG_CFG_INHOME = 2,
PLG_CFG_EXITING = 3,
PLG_CFG_HOME_EVENT = 1 << 16,
PLG_CFG_EXIT_EVENT = 2 << 16
} PLG_CFG_STATUS;
void PLG_SignalEvent(u32 event);
void PLG__WakeAppThread(void);
u32 PLG_GetStatus(void);
KLinkedList* KLinkedList__Initialize(KLinkedList *list);

View File

@ -53,7 +53,7 @@ struct KMutexLinkedList;
struct KPreemptionTimer; struct KPreemptionTimer;
/* 12 */ /* 12 */
typedef struct CTR_ALIGN(4) KAutoObject typedef struct ALIGN(4) KAutoObject
{ {
struct Vtable__KAutoObject *vtable; struct Vtable__KAutoObject *vtable;
u32 refCount; u32 refCount;
@ -96,7 +96,7 @@ typedef struct KMutexLinkedListNode
} KMutexLinkedListNode; } KMutexLinkedListNode;
/* 1 */ /* 1 */
typedef struct CTR_ALIGN(4) KMutex typedef struct ALIGN(4) KMutex
{ {
KSynchronizationObject syncObject; KSynchronizationObject syncObject;
KMutexLinkedListNode mutexListNode; KMutexLinkedListNode mutexListNode;
@ -106,14 +106,6 @@ typedef struct CTR_ALIGN(4) KMutex
union KProcess *owner; union KProcess *owner;
} KMutex; } KMutex;
typedef struct KAddressArbiter
{
KAutoObject autoObject;
struct KThread *first;
struct KThread *last;
union KProcess *owner;
} KAddressArbiter;
/* 92 */ /* 92 */
typedef struct KMutexLinkedList typedef struct KMutexLinkedList
{ {
@ -121,30 +113,6 @@ typedef struct KMutexLinkedList
KMutex *last; KMutex *last;
} KMutexLinkedList; } KMutexLinkedList;
enum
{
TOKEN_KAUTOOBJECT = 0,
TOKEN_KSYNCHRONIZATIONOBJECT = 1,
TOKEN_KEVENT = 0x1F,
TOKEN_KSEMAPHORE = 0x2F,
TOKEN_KTIMER = 0x35,
TOKEN_KMUTEX = 0x39,
TOKEN_KDEBUG = 0x4D,
TOKEN_KSERVERPORT = 0x55,
TOKEN_KDMAOBJECT = 0x59,
TOKEN_KCLIENTPORT = 0x65,
TOKEN_KCODESET = 0x68,
TOKEN_KSESSION = 0x70,
TOKEN_KTHREAD = 0x8D,
TOKEN_KSERVERSESSION = 0x95,
TOKEN_KADDRESSARBITER = 0x98,
TOKEN_KCLIENTSESSION = 0xA5,
TOKEN_KPORT = 0xA8,
TOKEN_KSHAREDMEMORY = 0xB0,
TOKEN_KPROCESS = 0xC5,
TOKEN_KRESOURCELIMIT = 0xC8
};
/* 45 */ /* 45 */
typedef struct KClassToken typedef struct KClassToken
{ {
@ -153,7 +121,7 @@ typedef struct KClassToken
} KClassToken; } KClassToken;
/* 44 */ /* 44 */
typedef struct CTR_ALIGN(4) Vtable__KAutoObject typedef struct ALIGN(4) Vtable__KAutoObject
{ {
void *field_0; void *field_0;
void *field_4; void *field_4;
@ -174,7 +142,7 @@ typedef struct KBaseInterruptEvent
} KBaseInterruptEvent; } KBaseInterruptEvent;
/* 55 */ /* 55 */
typedef struct CTR_ALIGN(4) Vtable__KBaseInterruptEvent typedef struct ALIGN(4) Vtable__KBaseInterruptEvent
{ {
struct KSchedulableInterruptEvent *(*handleInterruptEvent)(KBaseInterruptEvent *, u32); struct KSchedulableInterruptEvent *(*handleInterruptEvent)(KBaseInterruptEvent *, u32);
} Vtable__KBaseInterruptEvent; } Vtable__KBaseInterruptEvent;
@ -210,7 +178,7 @@ typedef struct KThreadLinkedListNode
/* 93 */ /* 93 */
typedef struct CTR_ALIGN(4) KPreemptionTimer typedef struct ALIGN(4) KPreemptionTimer
{ {
u32 nLimitedTicks; u32 nLimitedTicks;
u32 timer; u32 timer;
@ -219,7 +187,7 @@ typedef struct CTR_ALIGN(4) KPreemptionTimer
} KPreemptionTimer; } KPreemptionTimer;
/* 15 */ /* 15 */
typedef struct CTR_PACKED CTR_ALIGN(4) KThread typedef struct PACKED ALIGN(4) KThread
{ {
KSynchronizationObject syncObject; KSynchronizationObject syncObject;
KTimeableInterruptEvent timeableInterruptEvent; KTimeableInterruptEvent timeableInterruptEvent;
@ -277,7 +245,7 @@ typedef enum ProcessStatus
} ProcessStatus; } ProcessStatus;
/* 3 */ /* 3 */
typedef struct CTR_ALIGN(4) HandleDescriptor typedef struct ALIGN(4) HandleDescriptor
{ {
u32 info; u32 info;
KAutoObject *pointer; KAutoObject *pointer;
@ -297,7 +265,7 @@ typedef struct KProcessHandleTable
} KProcessHandleTable; } KProcessHandleTable;
/* 4 */ /* 4 */
typedef struct CTR_ALIGN(4) KDebugThread typedef struct ALIGN(4) KDebugThread
{ {
KThread *linkedThread; KThread *linkedThread;
bool usedSvcBreak; bool usedSvcBreak;
@ -355,7 +323,7 @@ typedef enum {
} ExceptionEventType; } ExceptionEventType;
/* 6 */ /* 6 */
typedef struct CTR_ALIGN(4) KDebug typedef struct ALIGN(4) KDebug
{ {
KSynchronizationObject syncObject; KSynchronizationObject syncObject;
KSendableInterruptEvent sendableInterruptEvent; KSendableInterruptEvent sendableInterruptEvent;
@ -422,7 +390,7 @@ typedef struct KCodeSetMemDescriptor
} KCodeSetMemDescriptor; } KCodeSetMemDescriptor;
/* 5 */ /* 5 */
typedef struct CTR_PACKED CTR_ALIGN(4) KCodeSet typedef struct PACKED ALIGN(4) KCodeSet
{ {
KAutoObject autoObject; KAutoObject autoObject;
KCodeSetMemDescriptor textSection; KCodeSetMemDescriptor textSection;
@ -497,7 +465,7 @@ typedef struct KUserBindableInterruptEvent
} KUserBindableInterruptEvent; } KUserBindableInterruptEvent;
/* 14 */ /* 14 */
typedef struct CTR_ALIGN(4) KEvent typedef struct ALIGN(4) KEvent
{ {
KSynchronizationObject syncObject; KSynchronizationObject syncObject;
KUserBindableInterruptEvent userBindableInterruptEvent; KUserBindableInterruptEvent userBindableInterruptEvent;
@ -521,9 +489,6 @@ typedef enum MemOp
MEMOP_REGION_SYSTEM = 0x200, MEMOP_REGION_SYSTEM = 0x200,
MEMOP_REGION_BASE = 0x300, MEMOP_REGION_BASE = 0x300,
MEMOP_LINEAR = 0x10000, MEMOP_LINEAR = 0x10000,
MEMOP_OP_MASK = 0xFF,
MEMOP_REGION_MASK = 0xF00,
} MemOp; } MemOp;
/* 17 */ /* 17 */
@ -576,20 +541,6 @@ typedef struct KBlockInfo
u32 pageCount; u32 pageCount;
} KBlockInfo; } KBlockInfo;
typedef struct KSharedMemory
{
KAutoObject autoObject;
KLinkedList ownedKBlockInfo;
union KProcess *owner;
u32 ownerPermissions;
u32 otherPermissions;
u8 isBlockInfoGenerated;
s8 allBlockInfoGenerated;
u8 unknown_1;
u8 unknown_2;
u32 address;
} KSharedMemory;
/* 25 */ /* 25 */
typedef struct KMemoryBlock typedef struct KMemoryBlock
{ {
@ -601,7 +552,7 @@ typedef struct KMemoryBlock
} KMemoryBlock; } KMemoryBlock;
/* 28 */ /* 28 */
typedef struct CTR_ALIGN(4) KScheduler typedef struct ALIGN(4) KScheduler
{ {
KSchedulableInterruptEvent interruptEvent; KSchedulableInterruptEvent interruptEvent;
u32 threadSwitchAttempts; u32 threadSwitchAttempts;
@ -619,7 +570,7 @@ typedef struct CTR_ALIGN(4) KScheduler
} KScheduler; } KScheduler;
/* 46 */ /* 46 */
typedef struct CTR_PACKED CodeSetInfo typedef struct PACKED CodeSetInfo
{ {
char name[8]; char name[8];
u16 unknown_1; u16 unknown_1;
@ -639,7 +590,7 @@ typedef struct CTR_PACKED CodeSetInfo
} CodeSetInfo; } CodeSetInfo;
/* 53 */ /* 53 */
typedef struct CTR_ALIGN(4) InterruptData typedef struct ALIGN(4) InterruptData
{ {
KBaseInterruptEvent *interruptEvent; KBaseInterruptEvent *interruptEvent;
bool disableUponReceipt; bool disableUponReceipt;
@ -740,7 +691,7 @@ typedef enum ResetType
} ResetType; } ResetType;
/* 81 */ /* 81 */
typedef struct CTR_PACKED CTR_ALIGN(4) KTimer typedef struct PACKED ALIGN(4) KTimer
{ {
KSynchronizationObject syncObject; KSynchronizationObject syncObject;
KTimeableInterruptEvent timeableInterruptEvent; KTimeableInterruptEvent timeableInterruptEvent;
@ -768,7 +719,7 @@ typedef KSchedulableInterruptEvent KThreadTerminationInterruptEvent;
typedef KSchedulableInterruptEvent KThreadExitInterruptEvent; typedef KSchedulableInterruptEvent KThreadExitInterruptEvent;
/* 89 */ /* 89 */
typedef struct CTR_ALIGN(4) KInterruptEventMailbox typedef struct ALIGN(4) KInterruptEventMailbox
{ {
u32 mailboxID; u32 mailboxID;
KSendableInterruptEvent *first; KSendableInterruptEvent *first;
@ -795,7 +746,7 @@ typedef enum LimitableResource
} LimitableResource; } LimitableResource;
/* 99 */ /* 99 */
typedef struct CTR_ALIGN(4) CpuRegisters typedef struct ALIGN(4) CpuRegisters
{ {
u32 r[13]; u32 r[13];
u32 sp; u32 sp;
@ -809,7 +760,7 @@ typedef struct FpuRegisters
{ {
union union
{ {
struct CTR_PACKED { double d[16]; }; struct PACKED { double d[16]; };
float s[32]; float s[32];
}; };
u32 fpscr; u32 fpscr;
@ -974,7 +925,7 @@ typedef struct KEventInfo
}; };
} KEventInfo; } KEventInfo;
typedef struct CTR_ALIGN(0x1000) KCoreObjectContext typedef struct ALIGN(0x1000) KCoreObjectContext
{ {
KThread *volatile currentThread; KThread *volatile currentThread;
union KProcess *volatile currentProcess; union KProcess *volatile currentProcess;
@ -1004,7 +955,7 @@ extern KCoreContext *coreCtxs;
#define DEFINE_CONSOLE_SPECIFIC_STRUCTS(console, nbCores) #define DEFINE_CONSOLE_SPECIFIC_STRUCTS(console, nbCores)
/* 60 */ /* 60 */
typedef struct CTR_ALIGN(4) KProcessHwInfoN3DS typedef struct ALIGN(4) KProcessHwInfoN3DS
{ {
KObjectMutex mutex; KObjectMutex mutex;
u32 processTLBEntriesNeedToBeFlushedOnCore[4]; u32 processTLBEntriesNeedToBeFlushedOnCore[4];
@ -1023,7 +974,7 @@ typedef struct CTR_ALIGN(4) KProcessHwInfoN3DS
u32 *mmuTableVA; u32 *mmuTableVA;
} KProcessHwInfoN3DS; } KProcessHwInfoN3DS;
typedef struct CTR_ALIGN(4) KProcessHwInfoO3DS8x typedef struct ALIGN(4) KProcessHwInfoO3DS8x
{ {
KObjectMutex mutex; KObjectMutex mutex;
u32 processTLBEntriesNeedToBeFlushedOnCore[2]; u32 processTLBEntriesNeedToBeFlushedOnCore[2];
@ -1042,7 +993,7 @@ typedef struct CTR_ALIGN(4) KProcessHwInfoO3DS8x
u32 *mmuTableVA; u32 *mmuTableVA;
} KProcessHwInfoO3DS8x; } KProcessHwInfoO3DS8x;
typedef struct CTR_ALIGN(4) KProcessHwInfoO3DSPre8x typedef struct ALIGN(4) KProcessHwInfoO3DSPre8x
{ {
KObjectMutex mutex; KObjectMutex mutex;
u32 processTLBEntriesNeedToBeFlushedOnCore[2]; u32 processTLBEntriesNeedToBeFlushedOnCore[2];
@ -1087,24 +1038,10 @@ typedef struct KProcess##sys\
KThread *mainThread;\ KThread *mainThread;\
u32 interruptEnabledFlags[4];\ u32 interruptEnabledFlags[4];\
KProcessHandleTable handleTable;\ KProcessHandleTable handleTable;\
/* Custom fields for plugin system */ \ u8 gap234[52];\
/* { */ \
u32 customFlags; /* see KProcess_CustomFlags enum below */ \
Handle onMemoryLayoutChangeEvent;\
/* } */ \
u8 gap234[44];\
u64 unused;\ u64 unused;\
} KProcess##sys; } KProcess##sys;
enum KProcess_CustomFlags
{
ForceRWXPages = 1 << 0,
SignalOnMemLayoutChanges = 1 << 1,
SignalOnExit = 1 << 2,
MemLayoutChanged = 1 << 16
};
INSTANCIATE_KPROCESS(N3DS); INSTANCIATE_KPROCESS(N3DS);
INSTANCIATE_KPROCESS(O3DS8x); INSTANCIATE_KPROCESS(O3DS8x);
INSTANCIATE_KPROCESS(O3DSPre8x); INSTANCIATE_KPROCESS(O3DSPre8x);
@ -1198,28 +1135,6 @@ typedef struct FcramLayout
u32 baseSize; u32 baseSize;
} FcramLayout; } FcramLayout;
typedef struct RegionDescriptor
{
void *firstMemoryBlock;
void *lastMemoryBlock;
void *regionStart;
u32 regionSizeInBytes;
} RegionDescriptor;
typedef struct FcramDescriptor
{
RegionDescriptor appRegion;
RegionDescriptor sysRegion;
RegionDescriptor baseRegion;
RegionDescriptor * regionDescsPtr;
u32 fcramStart;
u32 fcramSizeInPages;
u32 baseMemoryStart;
u32 kernelUsageInBytes;
u32 unknown;
KObjectMutex mutex;
} FcramDescriptor;
extern bool isN3DS; extern bool isN3DS;
extern void *officialSVCs[0x7E]; extern void *officialSVCs[0x7E];

View File

@ -1,129 +0,0 @@
#pragma once
#include "types.h"
#include "kernel.h"
typedef struct
{
u32 bits1_0 : 2; ///< 0b00
} Desc_TranslationFault;
typedef struct
{
u32 bits1_0 : 2; ///< 0b01
u32 sbz : 3;
u32 domain : 4;
u32 p : 1;
u32 addr : 21;
} Desc_CoarsePageTable;
typedef struct
{
u32 bits1_0 : 2; ///< 0b10
u32 b : 1;
u32 c : 1;
u32 xn : 1;
u32 domain : 4;
u32 p : 1;
u32 ap : 2;
u32 tex : 3;
u32 apx : 1;
u32 s : 1;
u32 ng : 1;
u32 bit18 : 1; ///< 0
u32 sbz : 1;
u32 addr : 12;
} Desc_Section;
typedef struct
{
u32 bits1_0 : 2; ///< 0b10
u32 b : 1;
u32 c : 1;
u32 xn : 1;
u32 domain : 4;
u32 p : 1;
u32 ap : 2;
u32 tex : 3;
u32 sbz : 3;
u32 bit18 : 1; ///< 1
u32 sbz2 : 5;
u32 addr : 8;
} Desc_Supersection;
typedef struct
{
u32 bits1_0 : 2; ///< 0b11
} Desc_Reserved;
typedef struct
{
u32 bits1_0 : 2; ///< 0b01
u32 b : 1;
u32 c : 1;
u32 ap : 2;
u32 sbz : 3;
u32 apx : 1;
u32 s : 1;
u32 ng : 1;
u32 tex : 3;
u32 xn : 1;
u32 addr : 16;
} Desc_LargePage;
typedef struct
{
u32 xn : 1;
u32 bit1 : 1; ///< 1
u32 b : 1;
u32 c : 1;
u32 ap : 2;
u32 tex : 3;
u32 apx : 1;
u32 s : 1;
u32 ng : 1;
u32 addr : 20;
} Desc_SmallPage;
typedef union
{
u32 raw;
Desc_TranslationFault translationFault;
Desc_CoarsePageTable coarsePageTable;
Desc_Section section;
Desc_Supersection supersection;
Desc_Reserved reserved;
} L1Descriptor;
typedef union
{
u32 raw;
Desc_TranslationFault translationFault;
Desc_LargePage largePage;
Desc_SmallPage smallPage;
} L2Descriptor;
typedef enum
{
Descriptor_TranslationFault,
Descriptor_CoarsePageTable,
Descriptor_Section,
Descriptor_Supersection,
Descriptor_Reserved,
Descriptor_LargePage,
Descriptor_SmallPage
} DescType;
void L1MMUTable__RWXForAll(u32 *table);
void L2MMUTable__RWXForAll(u32 *table);
u32 L1MMUTable__GetPAFromVA(u32 *table, u32 va);
u32 L2MMUTable__GetPAFromVA(u32 *table, u32 va);
u32 L1MMUTable__GetAddressUserPerm(u32 *table, u32 va);
u32 L2MMUTable__GetAddressUserPerm(u32 *table, u32 va);
void KProcessHwInfo__SetMMUTableToRWX(KProcessHwInfo *hwInfo);
u32 KProcessHwInfo__GetPAFromVA(KProcessHwInfo *hwInfo, u32 va);
u32 KProcessHwInfo__GetAddressUserPerm(KProcessHwInfo *hwInfo, u32 va);

View File

@ -1,34 +0,0 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2018 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that 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/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#pragma once
#include "utils.h"
#include "kernel.h"
#include "svc.h"
Result ControlMemoryUnsafe(u32 *out, u32 addr0, u32 size, MemOp op, MemPerm perm);
Result ControlMemoryUnsafeWrapper(u32 *out, u32 addr0, u32 size, MemOp op, MemPerm perm);

View File

@ -1,21 +0,0 @@
#pragma once
#include "utils.h"
#include "kernel.h"
#include "svc.h"
/// Operations for svcControlProcess
typedef enum ProcessOp
{
PROCESSOP_GET_ALL_HANDLES, ///< List all handles of the process, varg3 can be either 0 to fetch all handles, or token of the type to fetch
///< svcControlProcess(handle, PROCESSOP_GET_ALL_HANDLES, (u32)&outBuf, 0)
PROCESSOP_SET_MMU_TO_RWX, ///< Set the whole memory of the process with rwx access
///< svcControlProcess(handle, PROCESSOP_SET_MMU_TO_RWX, 0, 0)
PROCESSOP_GET_ON_MEMORY_CHANGE_EVENT,
PROCESSOP_SIGNAL_ON_EXIT,
PROCESSOP_GET_PA_FROM_VA, ///< Get the physical address of the va within the process
///< svcControlProcess(handle, PROCESSOP_GET_PA_FROM_VA, (u32)&outPa, va)
PROCESSOP_SCHEDULE_THREADS,
} ProcessOp;
Result ControlProcess(Handle process, ProcessOp op, u32 varg2, u32 varg3);

View File

@ -1,6 +0,0 @@
#include "utils.h"
#include "kernel.h"
#include "svc.h"
void ExitProcessHook(void);
void ExitProcessHookWrapper(void);

View File

@ -30,7 +30,7 @@
#include "kernel.h" #include "kernel.h"
#include "svc.h" #include "svc.h"
extern u8 svcSignalingEnabled; extern bool svcSignalingEnabled;
bool shouldSignalSyscallDebugEvent(KProcess *process, u8 svcId); bool shouldSignalSyscallDebugEvent(KProcess *process, u8 svcId);
Result KernelSetStateHook(u32 type, u32 varg1, u32 varg2, u32 varg3); Result KernelSetStateHook(u32 type, u32 varg1, u32 varg2, u32 varg3);

View File

@ -30,11 +30,4 @@
#include "kernel.h" #include "kernel.h"
#include "svc.h" #include "svc.h"
/// Flags for svcMapProcessMemoryEx Result MapProcessMemoryEx(Handle processHandle, void *dst, void *src, u32 size);
typedef enum MapExFlags
{
MAPEXFLAGS_PRIVATE = BIT(0), ///< Maps the memory as PRIVATE (0xBB05) instead of SHARED (0x5806)
} MapExFlags;
Result MapProcessMemoryEx(Handle dstProcessHandle, u32 vaDst, Handle srcProcessHandle, u32 vaSrc, u32 size, MapExFlags flags);
Result MapProcessMemoryExWrapper(Handle dstProcessHandle, u32 vaDst, Handle srcProcessHandle, u32 vaSrc, u32 size, MapExFlags flags);

View File

@ -69,11 +69,11 @@ typedef s32 Result; ///< Function result.
#define BIT(n) (1U<<(n)) #define BIT(n) (1U<<(n))
/// Aligns a struct (and other types?) to m, making sure that the size of the struct is a multiple of m. /// Aligns a struct (and other types?) to m, making sure that the size of the struct is a multiple of m.
#define CTR_ALIGN(m) __attribute__((aligned(m))) #define ALIGN(m) __attribute__((aligned(m)))
/// Packs a struct (and other types?) so it won't include padding bytes. /// Packs a struct (and other types?) so it won't include padding bytes.
#define CTR_PACKED __attribute__((packed)) #define PACKED __attribute__((packed))
#define CTR_USED __attribute__((used)) #define USED __attribute__((used))
#define CTR_UNUSED __attribute__((unused)) #define UNUSED __attribute__((unused))
/// Packs a system version from its components. /// Packs a system version from its components.
#define SYSTEM_VERSION(major, minor, revision) \ #define SYSTEM_VERSION(major, minor, revision) \
(((major)<<24)|((minor)<<16)|((revision)<<8)) (((major)<<24)|((minor)<<16)|((revision)<<8))

View File

@ -31,7 +31,7 @@
KRecursiveLock dbgParamsLock = { NULL }; KRecursiveLock dbgParamsLock = { NULL };
u32 dbgParamWatchpointId, dbgParamDVA, dbgParamWCR, dbgParamContextId; u32 dbgParamWatchpointId, dbgParamDVA, dbgParamWCR, dbgParamContextId;
KSchedulableInterruptEvent *enableMonitorModeDebugging(KBaseInterruptEvent *this CTR_UNUSED, u32 interruptID CTR_UNUSED) KSchedulableInterruptEvent *enableMonitorModeDebugging(KBaseInterruptEvent *this UNUSED, u32 interruptID UNUSED)
{ {
coreBarrier(); coreBarrier();
@ -76,7 +76,7 @@ static void disableWatchpoint1(void)
__asm__ __volatile__("mcr p14, 0, %[val], c0, c5, 5" :: [val] "r" (control)); __asm__ __volatile__("mcr p14, 0, %[val], c0, c5, 5" :: [val] "r" (control));
} }
KSchedulableInterruptEvent *disableWatchpoint(KBaseInterruptEvent *this CTR_UNUSED, u32 interruptID CTR_UNUSED) KSchedulableInterruptEvent *disableWatchpoint(KBaseInterruptEvent *this UNUSED, u32 interruptID UNUSED)
{ {
coreBarrier(); coreBarrier();
@ -131,7 +131,7 @@ static void setWatchpoint1WithContextId(u32 DVA, u32 WCR, u32 contextId)
__asm__ __volatile__("mcr p15, 0, %[val], c7, c10, 5" :: [val] "r" (0) : "memory"); // DMB __asm__ __volatile__("mcr p15, 0, %[val], c7, c10, 5" :: [val] "r" (0) : "memory"); // DMB
} }
KSchedulableInterruptEvent *setWatchpointWithContextId(KBaseInterruptEvent *this CTR_UNUSED, u32 interruptID CTR_UNUSED) KSchedulableInterruptEvent *setWatchpointWithContextId(KBaseInterruptEvent *this UNUSED, u32 interruptID UNUSED)
{ {
coreBarrier(); coreBarrier();

View File

@ -28,43 +28,10 @@
#include "fatalExceptionHandlers.h" #include "fatalExceptionHandlers.h"
#include "utils.h" #include "utils.h"
#include "kernel.h" #include "kernel.h"
#include "memory.h"
#include "mmu.h"
#include "globals.h" #include "globals.h"
#define REG_DUMP_SIZE 4 * 23 #define REG_DUMP_SIZE 4 * 23
#define CODE_DUMP_SIZE 96 #define CODE_DUMP_SIZE 48
// Return true if parameters are invalid
static bool checkExceptionHandlerValidity(KProcess *process, vu32 *threadLocalStorage)
{
if (process == NULL)
return true;
u32 stackBottom = threadLocalStorage[0x11];
u32 exceptionBuf = threadLocalStorage[0x12];
MemoryInfo memInfo;
PageInfo pageInfo;
KProcessHwInfo *hwInfo = hwInfoOfProcess(process);
u32 perm = KProcessHwInfo__GetAddressUserPerm(hwInfo, threadLocalStorage[0x10]);
if (stackBottom != 1)
{
if (KProcessHwInfo__QueryMemory(hwInfo, &memInfo, &pageInfo, (void *)stackBottom)
|| (memInfo.permissions & MEMPERM_RW) != MEMPERM_RW)
return true;
}
if (exceptionBuf > 1)
{
if (KProcessHwInfo__QueryMemory(hwInfo, &memInfo, &pageInfo, (void *)exceptionBuf)
|| (memInfo.permissions & MEMPERM_RW) != MEMPERM_RW)
return true;
}
return (perm & MEMPERM_RX) != MEMPERM_RX;
}
bool isExceptionFatal(u32 spsr, u32 *regs, u32 index) bool isExceptionFatal(u32 spsr, u32 *regs, u32 index)
{ {
@ -76,7 +43,7 @@ bool isExceptionFatal(u32 spsr, u32 *regs, u32 index)
KProcess *currentProcess = currentCoreContext->objectContext.currentProcess; KProcess *currentProcess = currentCoreContext->objectContext.currentProcess;
if(thread != NULL && thread->threadLocalStorage != NULL && *((vu32 *)thread->threadLocalStorage + 0x10) != 0) if(thread != NULL && thread->threadLocalStorage != NULL && *((vu32 *)thread->threadLocalStorage + 0x10) != 0)
return checkExceptionHandlerValidity(currentProcess, (vu32 *)thread->threadLocalStorage); return false;
if(currentProcess != NULL) if(currentProcess != NULL)
{ {
@ -85,7 +52,7 @@ bool isExceptionFatal(u32 spsr, u32 *regs, u32 index)
thread = KPROCESS_GET_RVALUE(currentProcess, mainThread); thread = KPROCESS_GET_RVALUE(currentProcess, mainThread);
if(thread != NULL && thread->threadLocalStorage != NULL && *((vu32 *)thread->threadLocalStorage + 0x10) != 0) if(thread != NULL && thread->threadLocalStorage != NULL && *((vu32 *)thread->threadLocalStorage + 0x10) != 0)
return checkExceptionHandlerValidity(currentProcess, thread->threadLocalStorage); return false;
if(index == 3 && strcmp(codeSetOfProcess(currentProcess)->processName, "menu") == 0 && // workaround a Home Menu bug leading to a dabort if(index == 3 && strcmp(codeSetOfProcess(currentProcess)->processName, "menu") == 0 && // workaround a Home Menu bug leading to a dabort
regs[0] == 0x3FFF && regs[2] == 0 && regs[5] == 2 && regs[7] == 1) regs[0] == 0x3FFF && regs[2] == 0 && regs[5] == 2 && regs[7] == 1)
@ -103,7 +70,6 @@ bool isDataAbortExceptionRangeControlled(u32 spsr, u32 addr)
((u32)safecpy <= addr && addr < (u32)safecpy + safecpy_sz) ((u32)safecpy <= addr && addr < (u32)safecpy + safecpy_sz)
); );
} }
void fatalExceptionHandlersMain(u32 *registerDump, u32 type, u32 cpuId) void fatalExceptionHandlersMain(u32 *registerDump, u32 type, u32 cpuId)
{ {
ExceptionDumpHeader dumpHeader; ExceptionDumpHeader dumpHeader;

View File

@ -25,8 +25,6 @@
*/ */
#include "globals.h" #include "globals.h"
#include "utils.h"
#include "ipc.h"
KRecursiveLock *criticalSectionLock; KRecursiveLock *criticalSectionLock;
KObjectList *threadList; KObjectList *threadList;
@ -42,29 +40,18 @@ KAutoObject * (*KProcessHandleTable__ToKAutoObject)(KProcessHandleTable *this, H
void (*KSynchronizationObject__Signal)(KSynchronizationObject *this, bool isPulse); void (*KSynchronizationObject__Signal)(KSynchronizationObject *this, bool isPulse);
Result (*WaitSynchronization1)(void *this_unused, KThread *thread, KSynchronizationObject *syncObject, s64 timeout); Result (*WaitSynchronization1)(void *this_unused, KThread *thread, KSynchronizationObject *syncObject, s64 timeout);
Result (*KProcessHandleTable__CreateHandle)(KProcessHandleTable *this, Handle *out, KAutoObject *obj, u8 token); Result (*KProcessHandleTable__CreateHandle)(KProcessHandleTable *this, Handle *out, KAutoObject *obj, u8 token);
Result (*KProcessHwInfo__QueryMemory)(KProcessHwInfo *this, MemoryInfo *memoryInfo, PageInfo *pageInfo, void *address);
Result (*KProcessHwInfo__MapProcessMemory)(KProcessHwInfo *this, KProcessHwInfo *other, void *dst, void *src, u32 nbPages); Result (*KProcessHwInfo__MapProcessMemory)(KProcessHwInfo *this, KProcessHwInfo *other, void *dst, void *src, u32 nbPages);
Result (*KProcessHwInfo__UnmapProcessMemory)(KProcessHwInfo *this, void *addr, u32 nbPages); Result (*KProcessHwInfo__UnmapProcessMemory)(KProcessHwInfo *this, void *addr, u32 nbPages);
Result (*KProcessHwInfo__CheckVaState)(KProcessHwInfo *hwInfo, u32 va, u32 size, u32 state, u32 perm);
Result (*KProcessHwInfo__GetListOfKBlockInfoForVA)(KProcessHwInfo *hwInfo, KLinkedList *list, u32 va, u32 sizeInPage);
Result (*KProcessHwInfo__MapListOfKBlockInfo)(KProcessHwInfo *this, u32 va, KLinkedList *list, u32 state, u32 perm, u32 sbz);
Result (*KEvent__Clear)(KEvent *this); Result (*KEvent__Clear)(KEvent *this);
Result (*KEvent__Signal)(KEvent *this);
void (*KObjectMutex__WaitAndAcquire)(KObjectMutex *this); void (*KObjectMutex__WaitAndAcquire)(KObjectMutex *this);
void (*KObjectMutex__ErrorOccured)(void); void (*KObjectMutex__ErrorOccured)(void);
void (*KScheduler__AdjustThread)(KScheduler *this, KThread *thread, u32 oldSchedulingMask); void (*KScheduler__AdjustThread)(KScheduler *this, KThread *thread, u32 oldSchedulingMask);
void (*KScheduler__AttemptSwitchingThreadContext)(KScheduler *this); void (*KScheduler__AttemptSwitchingThreadContext)(KScheduler *this);
void (*KLinkedList_KBlockInfo__Clear)(KLinkedList *list);
Result (*ControlMemory)(u32 *addrOut, u32 addr0, u32 addr1, u32 size, MemOp op, MemPerm perm, bool isLoader); Result (*ControlMemory)(u32 *addrOut, u32 addr0, u32 addr1, u32 size, MemOp op, MemPerm perm, bool isLoader);
Result (*doControlMemory)(KProcessHwInfo *this, u32 addr, u32 requestedNbPages, u32 pa, u32 state, u32 perm, u32 a7, u32 region);
Result (*CreateThread)(Handle *outThreadHandle, u32 ep, u32 arg, u32 stackTop, s32 priority, s32 processorId); Result (*CreateThread)(Handle *outThreadHandle, u32 ep, u32 arg, u32 stackTop, s32 priority, s32 processorId);
void (*SleepThread)(s64 ns); void (*SleepThread)(s64 ns);
Result (*CreateEvent)(Handle *out, ResetType resetType);
Result (*CloseHandle)(Handle handle); Result (*CloseHandle)(Handle handle);
Result (*GetHandleInfo)(s64 *out, Handle handle, u32 type); Result (*GetHandleInfo)(s64 *out, Handle handle, u32 type);
Result (*GetSystemInfo)(s64 *out, s32 type, s32 param); Result (*GetSystemInfo)(s64 *out, s32 type, s32 param);
@ -75,7 +62,6 @@ Result (*SendSyncRequest)(Handle handle);
Result (*OpenProcess)(Handle *out, u32 processId); Result (*OpenProcess)(Handle *out, u32 processId);
Result (*GetProcessId)(u32 *out, Handle process); Result (*GetProcessId)(u32 *out, Handle process);
Result (*DebugActiveProcess)(Handle *out, u32 processId); Result (*DebugActiveProcess)(Handle *out, u32 processId);
Result (*SignalEvent)(Handle event);
Result (*UnmapProcessMemory)(Handle processHandle, void *dst, u32 size); Result (*UnmapProcessMemory)(Handle processHandle, void *dst, u32 size);
Result (*KernelSetState)(u32 type, u32 varg1, u32 varg2, u32 varg3); Result (*KernelSetState)(u32 type, u32 varg1, u32 varg2, u32 varg3);
@ -108,7 +94,6 @@ bool *isDevUnit;
vu8 *configPage; vu8 *configPage;
u32 kernelVersion; u32 kernelVersion;
FcramLayout fcramLayout; FcramLayout fcramLayout;
FcramDescriptor *fcramDescriptor;
KCoreContext *coreCtxs; KCoreContext *coreCtxs;
void *originalHandlers[8] = {NULL}; void *originalHandlers[8] = {NULL};
@ -119,67 +104,15 @@ Result (*InterruptManager__MapInterrupt)(InterruptManager *manager, KBaseInterru
u32 coreID, u32 priority, bool disableUponReceipt, bool levelHighActive); u32 coreID, u32 priority, bool disableUponReceipt, bool levelHighActive);
InterruptManager *interruptManager; InterruptManager *interruptManager;
void (*initFPU)(void); void (*initFPU)(void);
void (*mcuReboot)(void); void (*mcuReboot)(void);
void (*coreBarrier)(void); void (*coreBarrier)(void);
void* (*kAlloc)(FcramDescriptor *fcramDesc, u32 nbPages, u32 alignment, u32 region);
CfwInfo cfwInfo; CfwInfo cfwInfo;
u32 kextBasePa; u32 kextBasePa;
u32 stolenSystemMemRegionSize; u32 stolenSystemMemRegionSize;
bool disableThreadRedirection = false;
vu32 rosalinaState; vu32 rosalinaState;
bool hasStartedRosalinaNetworkFuncsOnce; bool hasStartedRosalinaNetworkFuncsOnce;
KEvent* signalPluginEvent = NULL;
u32 pidOffsetKProcess, hwInfoOffsetKProcess, codeSetOffsetKProcess, handleTableOffsetKProcess, debugOffsetKProcess, flagsKProcess; u32 pidOffsetKProcess, hwInfoOffsetKProcess, codeSetOffsetKProcess, handleTableOffsetKProcess, debugOffsetKProcess, flagsKProcess;
KLinkedList* KLinkedList__Initialize(KLinkedList *list)
{
list->size = 0;
list->nodes.first = list->nodes.last = (KLinkedListNode *)&list->nodes;
return list;
}
void PLG_SignalEvent(u32 event)
{
KThread *currentThread = currentCoreContext->objectContext.currentThread;
// Set configuration memory field with event
*(vu32 *)PA_FROM_VA_PTR((u32 *)0x1FF800F0) |= event;
// Send notification 0x1001
{
u32 *cmdbuf = (u32 *)((u8 *)currentCoreContext->objectContext.currentThread->threadLocalStorage + 0x80);
u32 backup[3] = { cmdbuf[0], cmdbuf[1], cmdbuf[2] };
Handle srvHandle;
SessionInfo *info = SessionInfo_FindFirst("srv:");
Result res = createHandleForThisProcess(&srvHandle, &info->session->clientSession.syncObject.autoObject);
if (res >= 0)
{
cmdbuf[0] = 0x000C0080;
cmdbuf[1] = 0x1001;
cmdbuf[2] = 0;
SendSyncRequest(srvHandle);
CloseHandle(srvHandle);
}
cmdbuf[0] = backup[0]; cmdbuf[1] = backup[1]; cmdbuf[2] = backup[2];
}
// Wait for notification 0x1002
WaitSynchronization1(NULL, currentThread, (KSynchronizationObject *)signalPluginEvent, U64_MAX);
}
void PLG__WakeAppThread(void)
{
KEvent__Signal(signalPluginEvent);
}
u32 PLG_GetStatus(void)
{
return (*(vu32 *)PA_FROM_VA_PTR((u32 *)0x1FF800F0)) & 0xFFFF;
}

View File

@ -46,7 +46,7 @@ struct KExtParameters
CfwInfo cfwInfo; CfwInfo cfwInfo;
} kExtParameters = { .basePA = 0x12345678 }; // place this in .data } kExtParameters = { .basePA = 0x12345678 }; // place this in .data
static CTR_ALIGN(1024) u32 g_L2Table[256] = {0}; static ALIGN(1024) u32 g_L2Table[256] = {0};
void relocateAndSetupMMU(u32 coreId, u32 *L1Table) void relocateAndSetupMMU(u32 coreId, u32 *L1Table)
{ {
@ -130,67 +130,11 @@ void configHook(vu8 *cfgPage)
flagsKProcess = KPROCESS_OFFSETOF(kernelFlags); flagsKProcess = KPROCESS_OFFSETOF(kernelFlags);
} }
void KProcessHwInfo__MapL1Section_Hook(void);
void KProcessHwInfo__MapL2Section_Hook(void);
static void installMmuHooks(void)
{
// Older versions of k11 had different VA memory mappings
u32 k11TextStartVa = (u32)originalHandlers[2] & ~0xFFFF;
u32 *off;
for (off = (u32 *)k11TextStartVa; off[0] != 0xE3A05801 || off[1] != 0xE2010EE3; off++);
for (; (off[0] >> 16) != 0xE92D; off--);
u32 *mapL2Section = PA_FROM_VA_PTR(off); // fragile, might break due to cache
for (off = (u32 *)k11TextStartVa; off[0] != 0x13A0A401 || off[1] != 0x03A0A601; off++);
for (; (off[0] >> 16) != 0xE92D; off--);
u32 *mapL1Section = PA_FROM_VA_PTR(off);
mapL1Section[1] = 0xE28FE004; // add lr, pc, #4
mapL1Section[2] = 0xE51FF004; // ldr pc, [pc, #-4]
mapL1Section[3] = (u32)KProcessHwInfo__MapL1Section_Hook;
mapL2Section[1] = 0xE28FE004; // add lr, pc, #4
mapL2Section[2] = 0xE51FF004; // ldr pc, [pc, #-4]
mapL2Section[3] = (u32)KProcessHwInfo__MapL2Section_Hook;
}
static void findUsefulSymbols(void) static void findUsefulSymbols(void)
{ {
u32 *off; u32 *off;
// Older versions of k11 had different VA memory mappings for(off = (u32 *)0xFFFF0000; *off != 0xE1A0D002; off++);
u32 k11TextStartVa = (u32)originalHandlers[2] & ~0xFFFF;
// Get fcramDescriptor
for (off = (u32 *)k11TextStartVa; ; ++off)
{
if ( (off[0] >> 16) == 0xE59F
&& (off[1] >> 16) == 0xE3A0
&& (off[2] >> 16) == 0xE3A0
&& (off[3] >> 16) == 0xE1A0
&& (off[4] >> 16) == 0xEB00)
{
fcramDescriptor = (FcramDescriptor *)off[2 + (off[0] & 0xFFFF) / 4];
break;
}
}
// Get kAlloc
for (; *off != 0xE1A00005 || *(off + 1) != 0xE320F000; ++off);
off = decodeArmBranch(off + 2);
for (; (*off >> 16) != 0xEB00; ++off);
kAlloc = (void* (*)(FcramDescriptor *, u32, u32, u32))decodeArmBranch(off);
// Patch ERRF__DumpException
for(off = (u32 *)0xFFFF0000; *off != 0xE1A04005; ++off);
++off;
*(u32 *)PA_FROM_VA_PTR(off) = makeArmBranch(off, off + 51, false);
for(; *off != 0xE2100102; ++off);
KProcessHwInfo__QueryMemory = (Result (*)(KProcessHwInfo *, MemoryInfo *, PageInfo *, void *))decodeArmBranch(off - 1);
for(; *off != 0xE1A0D002; off++);
off += 3; off += 3;
initFPU = (void (*) (void))off; initFPU = (void (*) (void))off;
@ -227,8 +171,6 @@ static void findUsefulSymbols(void)
KEvent__Clear = (Result (*)(KEvent *))decodeArmBranch(off + 1); KEvent__Clear = (Result (*)(KEvent *))decodeArmBranch(off + 1);
for(off = (u32 *)KEvent__Clear; *off != 0xE8BD8070; off++); for(off = (u32 *)KEvent__Clear; *off != 0xE8BD8070; off++);
synchronizationMutex = *(KObjectMutex **)(off + 1); synchronizationMutex = *(KObjectMutex **)(off + 1);
for(off = (u32 *)officialSVCs[0x18]; *off != 0xE1A04005; ++off);
KEvent__Signal = (Result (*)(KEvent *))decodeArmBranch(off + 1);
for(off = (u32 *)officialSVCs[0x24]; *off != 0xE59F004C; off++); for(off = (u32 *)officialSVCs[0x24]; *off != 0xE59F004C; off++);
WaitSynchronization1 = (Result (*)(void *, KThread *, KSynchronizationObject *, s64))decodeArmBranch(off + 6); WaitSynchronization1 = (Result (*)(void *, KThread *, KSynchronizationObject *, s64))decodeArmBranch(off + 6);
@ -255,21 +197,6 @@ static void findUsefulSymbols(void)
for(off = (u32 *)officialSVCs[0x72]; *off != 0xE2041102; off++); for(off = (u32 *)officialSVCs[0x72]; *off != 0xE2041102; off++);
KProcessHwInfo__UnmapProcessMemory = (Result (*)(KProcessHwInfo *, void *, u32))decodeArmBranch(off - 1); KProcessHwInfo__UnmapProcessMemory = (Result (*)(KProcessHwInfo *, void *, u32))decodeArmBranch(off - 1);
for (off = (u32 *)officialSVCs[0x70]; *off != 0xE8881200 && *off != 0xE8891900; ++off);
for (off = (u32 *)decodeArmBranch(off + 1); *off != 0xE2101102; ++off);
KProcessHwInfo__CheckVaState = (Result (*)(KProcessHwInfo *, u32, u32, u32, u32))decodeArmBranch(off - 1);
for (; *off != 0xE28D1008; ++off);
KProcessHwInfo__GetListOfKBlockInfoForVA = (Result (*)(KProcessHwInfo*, KLinkedList*, u32, u32))decodeArmBranch(off + 1);
for (; *off != 0xE2000102; ++off);
KProcessHwInfo__MapListOfKBlockInfo = (Result (*)(KProcessHwInfo*, u32, KLinkedList*, u32, u32, u32))decodeArmBranch(off - 1);
for (; *off != 0xE8BD8FF0; ++off);
KLinkedList_KBlockInfo__Clear = (void (*)(KLinkedList *))decodeArmBranch(off - 6);
for(off = (u32 *)KProcessHwInfo__MapListOfKBlockInfo; *off != 0xE1A0000B; ++off);
doControlMemory = (Result (*)(KProcessHwInfo*, u32, u32, u32, u32, u32, u32, u32))decodeArmBranch(off + 1);
for(off = (u32 *)officialSVCs[0x7C]; *off != 0x03530000; off++); for(off = (u32 *)officialSVCs[0x7C]; *off != 0x03530000; off++);
KObjectMutex__WaitAndAcquire = (void (*)(KObjectMutex *))decodeArmBranch(++off); KObjectMutex__WaitAndAcquire = (void (*)(KObjectMutex *))decodeArmBranch(++off);
for(; *off != 0xE320F000; off++); for(; *off != 0xE320F000; off++);
@ -316,7 +243,6 @@ static void findUsefulSymbols(void)
decodeArmBranch((u32 *)officialSVCs[0x01] + 5); decodeArmBranch((u32 *)officialSVCs[0x01] + 5);
CreateThread = (Result (*)(Handle *, u32, u32, u32, s32, s32))decodeArmBranch((u32 *)officialSVCs[0x08] + 5); CreateThread = (Result (*)(Handle *, u32, u32, u32, s32, s32))decodeArmBranch((u32 *)officialSVCs[0x08] + 5);
SleepThread = (void (*)(s64))officialSVCs[0x0A]; SleepThread = (void (*)(s64))officialSVCs[0x0A];
CreateEvent = (Result (*)(Handle *, ResetType))decodeArmBranch((u32 *)officialSVCs[0x17] + 3);
CloseHandle = (Result (*)(Handle))officialSVCs[0x23]; CloseHandle = (Result (*)(Handle))officialSVCs[0x23];
GetHandleInfo = (Result (*)(s64 *, Handle, u32))decodeArmBranch((u32 *)officialSVCs[0x29] + 3); GetHandleInfo = (Result (*)(s64 *, Handle, u32))decodeArmBranch((u32 *)officialSVCs[0x29] + 3);
GetSystemInfo = (Result (*)(s64 *, s32, s32))decodeArmBranch((u32 *)officialSVCs[0x2A] + 3); GetSystemInfo = (Result (*)(s64 *, s32, s32))decodeArmBranch((u32 *)officialSVCs[0x2A] + 3);
@ -327,8 +253,6 @@ static void findUsefulSymbols(void)
OpenProcess = (Result (*)(Handle *, u32))decodeArmBranch((u32 *)officialSVCs[0x33] + 3); OpenProcess = (Result (*)(Handle *, u32))decodeArmBranch((u32 *)officialSVCs[0x33] + 3);
GetProcessId = (Result (*)(u32 *, Handle))decodeArmBranch((u32 *)officialSVCs[0x35] + 3); GetProcessId = (Result (*)(u32 *, Handle))decodeArmBranch((u32 *)officialSVCs[0x35] + 3);
DebugActiveProcess = (Result (*)(Handle *, u32))decodeArmBranch((u32 *)officialSVCs[0x60] + 3); DebugActiveProcess = (Result (*)(Handle *, u32))decodeArmBranch((u32 *)officialSVCs[0x60] + 3);
SignalEvent = (Result (*)(Handle event))officialSVCs[0x18];
UnmapProcessMemory = (Result (*)(Handle, void *, u32))officialSVCs[0x72]; UnmapProcessMemory = (Result (*)(Handle, void *, u32))officialSVCs[0x72];
KernelSetState = (Result (*)(u32, u32, u32, u32))((u32 *)officialSVCs[0x7C] + 1); KernelSetState = (Result (*)(u32, u32, u32, u32))((u32 *)officialSVCs[0x7C] + 1);
@ -360,8 +284,6 @@ static void findUsefulSymbols(void)
invalidateInstructionCacheRange = (void (*)(void *, u32))off2; invalidateInstructionCacheRange = (void (*)(void *, u32))off2;
} }
} }
installMmuHooks();
} }
void main(FcramLayout *layout, KCoreContext *ctxs) void main(FcramLayout *layout, KCoreContext *ctxs)

View File

@ -1,319 +0,0 @@
#include "mmu.h"
#include "globals.h"
#include "utils.h"
extern u8 svcSignalingEnabled;
DescType L1Descriptor__GetType(u32 descriptor)
{
L1Descriptor pdesc = {descriptor};
if (pdesc.reserved.bits1_0 == 0b00)
return Descriptor_TranslationFault;
if (pdesc.reserved.bits1_0 == 0b01)
return Descriptor_CoarsePageTable;
if (pdesc.reserved.bits1_0 == 0b10)
return pdesc.section.bit18 == 0 ? Descriptor_Section : Descriptor_Supersection;
return Descriptor_Reserved;
}
DescType L2Descriptor__GetType(u32 descriptor)
{
L2Descriptor pdesc = {descriptor};
if (pdesc.translationFault.bits1_0 == 0b01)
return Descriptor_LargePage;
if (pdesc.smallPage.bit1 == 1)
return Descriptor_SmallPage;
return Descriptor_TranslationFault;
}
void L1MMUTable__RWXForAll(u32 *table)
{
u32 *tableEnd = table + 1024;
for (; table != tableEnd; ++table)
{
L1Descriptor descriptor = {*table};
switch (L1Descriptor__GetType(descriptor.raw))
{
case Descriptor_CoarsePageTable:
{
u32 *l2table = (u32 *)((descriptor.coarsePageTable.addr << 10) - 0x40000000);
L2MMUTable__RWXForAll(l2table);
break;
}
case Descriptor_Section:
{
descriptor.section.xn = 0;
descriptor.section.apx = 0;
descriptor.section.ap = 3;
*table = descriptor.raw;
break;
}
case Descriptor_Supersection:
{
descriptor.supersection.xn = 0;
descriptor.supersection.ap = 3;
*table = descriptor.raw;
break;
}
default:
break;
}
}
}
void L2MMUTable__RWXForAll(u32 *table)
{
u32 *tableEnd = table + 256;
for (; table != tableEnd; ++table)
{
L2Descriptor descriptor = {*table};
switch (L2Descriptor__GetType(descriptor.raw))
{
case Descriptor_LargePage:
{
descriptor.largePage.xn = 0;
descriptor.largePage.apx = 0;
descriptor.largePage.ap = 3;
*table = descriptor.raw;
break;
}
case Descriptor_SmallPage:
{
descriptor.smallPage.xn = 0;
descriptor.smallPage.apx = 0;
descriptor.smallPage.ap = 3;
*table = descriptor.raw;
break;
}
default:
break;
}
}
}
u32 L1MMUTable__GetPAFromVA(u32 *table, u32 va)
{
u32 pa = 0;
L1Descriptor descriptor = {table[va >> 20]};
switch (L1Descriptor__GetType(descriptor.raw))
{
case Descriptor_CoarsePageTable:
{
u32 *l2table = (u32 *)((descriptor.coarsePageTable.addr << 10) - 0x40000000);
pa = L2MMUTable__GetPAFromVA(l2table, va);
break;
}
case Descriptor_Section:
{
pa = descriptor.section.addr << 20;
pa |= (va << 12) >> 12;
break;
}
case Descriptor_Supersection:
{
pa = descriptor.supersection.addr << 24;
pa |= (va << 8) >> 8;
break;
}
default:
// VA not found
break;
}
return pa;
}
u32 L2MMUTable__GetPAFromVA(u32 *table, u32 va)
{
u32 pa = 0;
L2Descriptor descriptor = {table[(va << 12) >> 24]};
switch(L2Descriptor__GetType(descriptor.raw))
{
case Descriptor_LargePage:
{
pa = descriptor.largePage.addr << 16;
pa |= va & 0xFFFF;
break;
}
case Descriptor_SmallPage:
{
pa = descriptor.smallPage.addr << 12;
pa |= va & 0xFFF;
break;
}
default:
break;
}
return pa;
}
u32 L1MMUTable__GetAddressUserPerm(u32 *table, u32 va)
{
u32 perm = 0;
L1Descriptor descriptor = {table[va >> 20]};
switch (L1Descriptor__GetType(descriptor.raw))
{
case Descriptor_CoarsePageTable:
{
u32 *l2table = (u32 *)((descriptor.coarsePageTable.addr << 10) - 0x40000000);
perm = L2MMUTable__GetAddressUserPerm(l2table, va);
break;
}
case Descriptor_Section:
{
perm = descriptor.section.ap >> 1;
if (perm)
{
perm |= (!descriptor.section.apx && (descriptor.section.ap & 1)) << 1;
perm |= (!descriptor.section.xn) << 2;
}
break;
}
case Descriptor_Supersection:
{
perm = descriptor.supersection.ap >> 1;
if (perm)
{
perm |= (descriptor.supersection.ap & 1) << 1;
perm |= (!descriptor.supersection.xn) << 2;
}
break;
}
default:
// VA not found
break;
}
return perm;
}
u32 L2MMUTable__GetAddressUserPerm(u32 *table, u32 va)
{
u32 perm = 0;
L2Descriptor descriptor = {table[(va << 12) >> 24]};
switch(L2Descriptor__GetType(descriptor.raw))
{
case Descriptor_LargePage:
{
perm = descriptor.largePage.ap >> 1;
if (perm)
{
perm |= (!descriptor.largePage.apx && (descriptor.largePage.ap & 1)) << 1;
perm |= (!descriptor.largePage.xn) << 2;
}
break;
}
case Descriptor_SmallPage:
{
perm = descriptor.smallPage.ap >> 1;
if (perm)
{
perm |= (!descriptor.smallPage.apx && (descriptor.smallPage.ap & 1)) << 1;
perm |= (!descriptor.smallPage.xn) << 2;
}
break;
}
default:
break;
}
return perm;
}
void KProcessHwInfo__SetMMUTableToRWX(KProcessHwInfo *hwInfo)
{
KObjectMutex *mutex = KPROCESSHWINFO_GET_PTR(hwInfo, mutex);
u32 *table = KPROCESSHWINFO_GET_RVALUE(hwInfo, mmuTableVA);
KObjectMutex__Acquire(mutex);
L1MMUTable__RWXForAll(table);
KObjectMutex__Release(mutex);
}
u32 KProcessHwInfo__GetPAFromVA(KProcessHwInfo *hwInfo, u32 va)
{
KObjectMutex *mutex = KPROCESSHWINFO_GET_PTR(hwInfo, mutex);
u32 *table = KPROCESSHWINFO_GET_RVALUE(hwInfo, mmuTableVA);
KObjectMutex__Acquire(mutex);
u32 pa = L1MMUTable__GetPAFromVA(table, va);
KObjectMutex__Release(mutex);
return pa;
}
u32 KProcessHwInfo__GetAddressUserPerm(KProcessHwInfo *hwInfo, u32 va)
{
KObjectMutex *mutex = KPROCESSHWINFO_GET_PTR(hwInfo, mutex);
u32 *table = KPROCESSHWINFO_GET_RVALUE(hwInfo, mmuTableVA);
KObjectMutex__Acquire(mutex);
u32 perm = L1MMUTable__GetAddressUserPerm(table, va);
KObjectMutex__Release(mutex);
return perm;
}
static union
{
u32 raw;
struct
{
u32 xn : 1;
u32 unkn : 1;
u32 cb : 2;
u32 ap : 2;
u32 tex : 3;
u32 apx : 1;
u32 s : 1;
u32 ng : 1;
};
} g_rwxState;
// This function patch the permissions when memory is mapped in the mmu table (rwx)
KProcessHwInfo *PatchDescriptorAccessControl(KProcessHwInfo *hwInfo, u32 **outState)
{
KProcess *process = (KProcess *)((u32)hwInfo - 0x1C);
u32 state = **outState;
u32 flags = KPROCESS_GET_RVALUE(process, customFlags);
if (flags & SignalOnMemLayoutChanges) {
svcSignalingEnabled |= 2;
*KPROCESS_GET_PTR(process, customFlags) |= MemLayoutChanged;
}
if (!(flags & ForceRWXPages))
return hwInfo;
g_rwxState.raw = state;
g_rwxState.xn = 0;
g_rwxState.ap = 3;
g_rwxState.apx = 0;
*outState = &g_rwxState.raw;
return hwInfo;
}

View File

@ -44,11 +44,8 @@
#include "svc/MapProcessMemoryEx.h" #include "svc/MapProcessMemoryEx.h"
#include "svc/UnmapProcessMemoryEx.h" #include "svc/UnmapProcessMemoryEx.h"
#include "svc/ControlService.h" #include "svc/ControlService.h"
#include "svc/ControlProcess.h"
#include "svc/ExitProcess.h"
#include "svc/CopyHandle.h" #include "svc/CopyHandle.h"
#include "svc/TranslateHandle.h" #include "svc/TranslateHandle.h"
#include "svc/ControlMemoryUnsafe.h"
void *officialSVCs[0x7E] = {NULL}; void *officialSVCs[0x7E] = {NULL};
void *alteredSvcTable[0x100] = {NULL}; void *alteredSvcTable[0x100] = {NULL};
@ -66,7 +63,6 @@ void buildAlteredSvcTable(void)
memcpy(alteredSvcTable, officialSVCs, 4 * 0x7E); memcpy(alteredSvcTable, officialSVCs, 4 * 0x7E);
alteredSvcTable[0x01] = ControlMemoryHookWrapper; alteredSvcTable[0x01] = ControlMemoryHookWrapper;
alteredSvcTable[0x03] = ExitProcessHookWrapper;
if (isN3DS) if (isN3DS)
alteredSvcTable[0x08] = CreateThreadHookWrapper; alteredSvcTable[0x08] = CreateThreadHookWrapper;
@ -94,15 +90,13 @@ void buildAlteredSvcTable(void)
alteredSvcTable[0x93] = invalidateInstructionCacheRange; alteredSvcTable[0x93] = invalidateInstructionCacheRange;
alteredSvcTable[0x94] = invalidateEntireInstructionCache; alteredSvcTable[0x94] = invalidateEntireInstructionCache;
alteredSvcTable[0xA0] = MapProcessMemoryExWrapper; alteredSvcTable[0xA0] = MapProcessMemoryEx;
alteredSvcTable[0xA1] = UnmapProcessMemoryEx; alteredSvcTable[0xA1] = UnmapProcessMemoryEx;
alteredSvcTable[0xA2] = ControlMemoryEx; alteredSvcTable[0xA2] = ControlMemoryEx;
alteredSvcTable[0xA3] = ControlMemoryUnsafeWrapper;
alteredSvcTable[0xB0] = ControlService; alteredSvcTable[0xB0] = ControlService;
alteredSvcTable[0xB1] = CopyHandleWrapper; alteredSvcTable[0xB1] = CopyHandleWrapper;
alteredSvcTable[0xB2] = TranslateHandleWrapper; alteredSvcTable[0xB2] = TranslateHandleWrapper;
alteredSvcTable[0xB3] = ControlProcess;
} }
void signalSvcEntry(u32 svcId) void signalSvcEntry(u32 svcId)
@ -117,18 +111,10 @@ void signalSvcEntry(u32 svcId)
void signalSvcReturn(u32 svcId) void signalSvcReturn(u32 svcId)
{ {
KProcess *currentProcess = currentCoreContext->objectContext.currentProcess; KProcess *currentProcess = currentCoreContext->objectContext.currentProcess;
u32 flags = KPROCESS_GET_RVALUE(currentProcess, customFlags);
// Since DBGEVENT_SYSCALL_RETURN is non blocking, we'll cheat using EXCEVENT_UNDEFINED_SYSCALL (debug->svcId is fortunately an u16!) // Since DBGEVENT_SYSCALL_RETURN is non blocking, we'll cheat using EXCEVENT_UNDEFINED_SYSCALL (debug->svcId is fortunately an u16!)
if((svcSignalingEnabled & 1) != 0 && (currentProcess) != NULL && svcId != 0xFF && shouldSignalSyscallDebugEvent(currentProcess, svcId)) if(debugOfProcess(currentProcess) != NULL && svcId != 0xFF && shouldSignalSyscallDebugEvent(currentProcess, svcId))
SignalDebugEvent(DBGEVENT_OUTPUT_STRING, 0xFFFFFFFF, svcId); SignalDebugEvent(DBGEVENT_OUTPUT_STRING, 0xFFFFFFFF, svcId);
if (flags & SignalOnMemLayoutChanges && flags & MemLayoutChanged)
{
*KPROCESS_GET_PTR(currentProcess, customFlags) = flags & ~MemLayoutChanged;
SignalEvent(KPROCESS_GET_RVALUE(currentProcess, onMemoryLayoutChangeEvent));
svcSignalingEnabled &= ~2;
}
} }
void postprocessSvc(void) void postprocessSvc(void)

View File

@ -1,84 +0,0 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2018 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that 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/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "globals.h"
#include "memory.h"
#include "svc/ControlMemoryUnsafe.h"
Result ControlMemoryUnsafe(u32 *out, u32 addr0, u32 size, MemOp op, MemPerm perm)
{
Result res = 0;
KProcess *currentProcess = currentCoreContext->objectContext.currentProcess;
KProcessHwInfo *hwInfo = hwInfoOfProcess(currentProcess);
KAutoObject__AddReference((KAutoObject *)currentProcess);
size = size >> 12 << 12;
switch (op & MEMOP_OP_MASK)
{
case MEMOP_FREE:
{
res = doControlMemory(hwInfo, addr0, size >> 12, 0, 0, 0, 0, 0);
break;
}
case MEMOP_COMMIT:
{
u32 pAddr = 0;
u32 state = 0xBB05;
u32 region = op & MEMOP_REGION_MASK;
perm = (perm & 7) | 0x18;
if (op & MEMOP_LINEAR)
{
void *kvAddr = kAlloc(fcramDescriptor, size >> 12, 0, region);
if (!kvAddr)
{
res = 0xD86007F3;
break;
}
memset(kvAddr, 0, size >> 2);
flushDataCacheRange(kvAddr, size);
pAddr = (u32)kvAddr + 0x40000000;
state = 0x3907;
}
res = doControlMemory(hwInfo, addr0, size >> 12, pAddr, state, perm, 0, region);
if (res >= 0 && out)
*out = addr0;
break;
}
default:
res = 0xE0E01BEE;
break;
}
((KAutoObject *)currentProcess)->vtable->DecrementReferenceCount((KAutoObject *)currentProcess);
return res;
}

View File

@ -1,208 +0,0 @@
#include "svc/ControlProcess.h"
#include "memory.h"
#include "mmu.h"
#include "synchronization.h"
typedef bool (*ThreadPredicate)(KThread *thread);
// Lock bit has to be different from Rosalina to avoid unintended unlock when using Rosalina menu
static void rescheduleThread(KThread *thread, bool lock)
{
KRecursiveLock__Lock(criticalSectionLock);
u32 oldSchedulingMask = thread->schedulingMask;
if(lock)
thread->schedulingMask |= 0x20;
else
thread->schedulingMask &= ~0x20;
KScheduler__AdjustThread(currentCoreContext->objectContext.currentScheduler, thread, oldSchedulingMask);
KRecursiveLock__Unlock(criticalSectionLock);
}
static void lockThread(KThread *thread)
{
KThread *syncThread = synchronizationMutex->owner;
if(syncThread == NULL || syncThread != thread)
rescheduleThread(thread, true);
}
Result ControlProcess(Handle processHandle, ProcessOp op, u32 varg2, u32 varg3)
{
Result res = 0;
KProcess *process;
KProcessHandleTable *handleTable = handleTableOfProcess(currentCoreContext->objectContext.currentProcess);
if(processHandle == CUR_PROCESS_HANDLE)
{
process = currentCoreContext->objectContext.currentProcess;
KAutoObject__AddReference((KAutoObject *)process);
}
else
process = KProcessHandleTable__ToKProcess(handleTable, processHandle);
if(process == NULL)
return 0xD8E007F7; // invalid handle
switch (op)
{
case PROCESSOP_GET_ALL_HANDLES:
{
KProcessHandleTable *table = handleTableOfProcess(process);
u32 *originalHandleList = (u32 *)varg2;
u32 count = 0;
u32 searchForToken = varg3;
HandleDescriptor *handleDesc = table->handleTable == NULL ? table->internalTable : table->handleTable;
for (u32 idx = 0; idx < (u32)table->maxHandleCount; ++idx, ++handleDesc)
{
if (handleDesc->pointer == NULL)
continue;
if (searchForToken)
{
KClassToken token;
handleDesc->pointer->vtable->GetClassToken(&token, handleDesc->pointer);
if (searchForToken != token.flags)
continue;
}
*originalHandleList++ = idx | ((handleDesc->info << 16) >> 1);
++count;
}
res = count;
break;
}
case PROCESSOP_SET_MMU_TO_RWX:
{
KProcessHwInfo *hwInfo = hwInfoOfProcess(process);
*KPROCESS_GET_PTR(process, customFlags) |= ForceRWXPages;
KProcessHwInfo__SetMMUTableToRWX(hwInfo);
break;
}
case PROCESSOP_GET_ON_MEMORY_CHANGE_EVENT:
{
// Only accept current process for this command
if (process != currentCoreContext->objectContext.currentProcess)
{
res = 0xD8E007F7; // invalid handle
break;
}
Handle *onMemoryLayoutChangeEvent = KPROCESS_GET_PTR(process, onMemoryLayoutChangeEvent);
if (*onMemoryLayoutChangeEvent == 0)
res = CreateEvent(onMemoryLayoutChangeEvent, RESET_ONESHOT);
if (res >= 0)
{
*KPROCESS_GET_PTR(process, customFlags) |= SignalOnMemLayoutChanges;
KAutoObject * event = KProcessHandleTable__ToKAutoObject(handleTable, *onMemoryLayoutChangeEvent);
createHandleForThisProcess((Handle *)varg2, event);
((KAutoObject *)event)->vtable->DecrementReferenceCount((KAutoObject *)event);
}
break;
}
case PROCESSOP_SIGNAL_ON_EXIT:
{
*KPROCESS_GET_PTR(process, customFlags) |= SignalOnExit;
break;
}
case PROCESSOP_GET_PA_FROM_VA:
{
KProcessHwInfo *hwInfo = hwInfoOfProcess(process);
u32 pa = KProcessHwInfo__GetPAFromVA(hwInfo, varg3);
*(u32 *)varg2 = pa;
if (pa == 0)
res = 0xE0E01BF5; ///< Invalid address
break;
}
case PROCESSOP_SCHEDULE_THREADS:
{
ThreadPredicate threadPredicate = (ThreadPredicate)varg3;
KRecursiveLock__Lock(criticalSectionLock);
if (varg2 == 0) // Unlock
{
for (KLinkedListNode *node = threadList->list.nodes.first; node != (KLinkedListNode *)&threadList->list.nodes; node = node->next)
{
KThread *thread = (KThread *)node->key;
if ((thread->schedulingMask & 0xF) == 2) // thread is terminating
continue;
if (thread->ownerProcess == process && (thread->schedulingMask & 0x20)
&& (threadPredicate == NULL || threadPredicate(thread)))
rescheduleThread(thread, false);
}
}
else // Lock
{
bool currentThreadsFound = false;
for(KLinkedListNode *node = threadList->list.nodes.first; node != (KLinkedListNode *)&threadList->list.nodes; node = node->next)
{
KThread *thread = (KThread *)node->key;
if(thread->ownerProcess != process
|| (threadPredicate != NULL && !threadPredicate(thread)))
continue;
if(thread == coreCtxs[thread->coreId].objectContext.currentThread)
currentThreadsFound = true;
else
lockThread(thread);
}
if(currentThreadsFound)
{
for(KLinkedListNode *node = threadList->list.nodes.first; node != (KLinkedListNode *)&threadList->list.nodes; node = node->next)
{
KThread *thread = (KThread *)node->key;
if(thread->ownerProcess != process
|| (threadPredicate != NULL && !threadPredicate(thread)))
continue;
if(!(thread->schedulingMask & 0x20))
{
lockThread(thread);
KRecursiveLock__Lock(criticalSectionLock);
if(thread->coreId != getCurrentCoreID())
{
u32 cpsr = __get_cpsr();
__disable_irq();
coreCtxs[thread->coreId].objectContext.currentScheduler->triggerCrossCoreInterrupt = true;
currentCoreContext->objectContext.currentScheduler->triggerCrossCoreInterrupt = true;
__set_cpsr_cx(cpsr);
}
KRecursiveLock__Unlock(criticalSectionLock);
}
}
KScheduler__TriggerCrossCoreInterrupt(currentCoreContext->objectContext.currentScheduler);
}
}
KRecursiveLock__Unlock(criticalSectionLock);
break;
}
default:
res = 0xF8C007F4;
}
((KAutoObject *)process)->vtable->DecrementReferenceCount((KAutoObject *)process);
return res;
}

View File

@ -29,7 +29,7 @@
Result CreateThreadHook(Handle *outThreadHandle, u32 ep, u32 arg, u32 stackTop, s32 priority, s32 processorId) Result CreateThreadHook(Handle *outThreadHandle, u32 ep, u32 arg, u32 stackTop, s32 priority, s32 processorId)
{ {
u32 flags = flagsOfProcess(currentCoreContext->objectContext.currentProcess); u32 flags = flagsOfProcess(currentCoreContext->objectContext.currentProcess);
if (isN3DS && CONFIG(REDIRECTAPPTHREADS) && !disableThreadRedirection && processorId == 1 && (flags & 0xF00) == 0x100) if (isN3DS && CONFIG(REDIRECTAPPTHREADS) && processorId == 1 && (flags & 0xF00) == 0x100)
processorId = 2; processorId = 2;
return CreateThread(outThreadHandle, ep, arg, stackTop, priority, processorId); return CreateThread(outThreadHandle, ep, arg, stackTop, priority, processorId);

View File

@ -1,32 +0,0 @@
#include "svc/ExitProcess.h"
void ExitProcessHook(void) {
KProcess *currentProcess = currentCoreContext->objectContext.currentProcess;
u32 flags = KPROCESS_GET_RVALUE(currentProcess, customFlags);
if (flags & SignalOnExit)
{
// Signal that the process is about to be terminated
if (PLG_GetStatus() == PLG_CFG_RUNNING)
PLG_SignalEvent(PLG_CFG_EXIT_EVENT);
// Unlock all threads that might be locked
{
KRecursiveLock__Lock(criticalSectionLock);
for (KLinkedListNode *node = threadList->list.nodes.first;
node != (KLinkedListNode *)&threadList->list.nodes;
node = node->next)
{
KThread *thread = (KThread *)node->key;
if (thread->ownerProcess == currentProcess && thread->schedulingMask & 0x20)
thread->schedulingMask &= ~0x20;
}
KRecursiveLock__Unlock(criticalSectionLock);
}
}
return ((void(*)())officialSVCs[0x3])();
}

View File

@ -29,14 +29,11 @@
Result GetHandleInfoHook(s64 *out, Handle handle, u32 type) Result GetHandleInfoHook(s64 *out, Handle handle, u32 type)
{ {
Result res = 0; if(type == 0x10000) // KDebug and KProcess: get context ID
if(type >= 0x10000)
{ {
KProcessHwInfo *hwInfo; KProcessHwInfo *hwInfo;
KProcessHandleTable *handleTable = handleTableOfProcess(currentCoreContext->objectContext.currentProcess); KProcessHandleTable *handleTable = handleTableOfProcess(currentCoreContext->objectContext.currentProcess);
KAutoObject *obj; KAutoObject *obj;
if(handle == CUR_PROCESS_HANDLE) if(handle == CUR_PROCESS_HANDLE)
{ {
obj = (KAutoObject *)(currentCoreContext->objectContext.currentProcess); obj = (KAutoObject *)(currentCoreContext->objectContext.currentProcess);
@ -48,82 +45,18 @@ Result GetHandleInfoHook(s64 *out, Handle handle, u32 type)
if(obj == NULL) if(obj == NULL)
return 0xD8E007F7; return 0xD8E007F7;
switch (type) if(strcmp(classNameOfAutoObject(obj), "KDebug") == 0)
{ hwInfo = hwInfoOfProcess(((KDebug *)obj)->owner);
case 0x10000: ///< Get ctx id (should probably move it to GetProcessInfo) else if(strcmp(classNameOfAutoObject(obj), "KProcess") == 0)
{ hwInfo = hwInfoOfProcess((KProcess *)obj);
if(strcmp(classNameOfAutoObject(obj), "KDebug") == 0) else
hwInfo = hwInfoOfProcess(((KDebug *)obj)->owner); hwInfo = NULL;
else if(strcmp(classNameOfAutoObject(obj), "KProcess") == 0)
hwInfo = hwInfoOfProcess((KProcess *)obj);
else
hwInfo = NULL;
*out = hwInfo != NULL ? KPROCESSHWINFO_GET_RVALUE(hwInfo, contextId) : -1; *out = hwInfo != NULL ? KPROCESSHWINFO_GET_RVALUE(hwInfo, contextId) : -1;
break;
}
case 0x10001: ///< Get referenced object flags (token)
{
KClassToken token;
obj->vtable->GetClassToken(&token, obj);
*out = token.flags;
break;
}
case 0x10002: ///< Get object owner
{
Handle hOut;
KClassToken token;
KProcess * owner = NULL;
obj->vtable->GetClassToken(&token, obj);
switch(token.flags)
{
case TOKEN_KEVENT:
owner = ((KEvent *)obj)->owner;
break;
case TOKEN_KSEMAPHORE:
owner = ((KSemaphore *)obj)->owner;
break;
case TOKEN_KTIMER:
owner = ((KTimer *)obj)->owner;
break;
case TOKEN_KMUTEX:
owner = ((KMutex *)obj)->owner;
break;
case TOKEN_KDEBUG:
owner = ((KDebug *)obj)->owner;
break;
case TOKEN_KTHREAD:
owner = ((KThread *)obj)->ownerProcess;
break;
case TOKEN_KADDRESSARBITER:
owner = ((KAddressArbiter *)obj)->owner;
break;
case TOKEN_KSHAREDMEMORY:
owner = ((KSharedMemory *)obj)->owner;
break;
default:
break;
}
if (owner == NULL)
res = 0xD8E007F7;
res = createHandleForThisProcess(&hOut, (KAutoObject *)owner);
*out = hOut;
break;
}
default:
res = 0xF8C007F4;
break;
}
obj->vtable->DecrementReferenceCount(obj); obj->vtable->DecrementReferenceCount(obj);
return res; return 0;
} }
else
return GetHandleInfo(out, handle, type); return GetHandleInfo(out, handle, type);
} }

View File

@ -79,14 +79,6 @@ Result GetProcessInfoHook(s64 *out, Handle processHandle, u32 type)
*out = ttb & ~((1 << (14 - TTBCR)) - 1); *out = ttb & ~((1 << (14 - TTBCR)) - 1);
break; break;
} }
case 0x10009:
{
KProcessHwInfo *hwInfo = hwInfoOfProcess(process);
u32 mmusize = KPROCESSHWINFO_GET_RVALUE(hwInfo, mmuTableSize);
u32 mmupa = (u32)PA_FROM_VA_PTR(KPROCESSHWINFO_GET_RVALUE(hwInfo, mmuTableVA));
*out = (s64)(mmusize | ((s64)mmupa << 32));
break;
}
default: default:
res = 0xD8E007ED; // invalid enum value res = 0xD8E007ED; // invalid enum value
break; break;

View File

@ -37,14 +37,7 @@ Result GetSystemInfoHook(s64 *out, s32 type, s32 param)
{ {
case 0x10000: case 0x10000:
{ {
if (param >= 0x400 && param < 0x500) { switch(param)
*out = 0;
s32 offset = param - 0x400;
s32 toCopy = (s32)sizeof(cfwInfo.launchedPath) - offset;
if (toCopy > 8) toCopy = 8;
memcpy(out, (u8*)cfwInfo.launchedPath + offset, (toCopy > 0) ? toCopy : 0);
}
else switch(param)
{ {
// Please do not use these, except 0, 1, and 0x200 // Please do not use these, except 0, 1, and 0x200
// Other types may get removed or reordered without notice // Other types may get removed or reordered without notice
@ -69,18 +62,14 @@ Result GetSystemInfoHook(s64 *out, s32 type, s32 param)
case 6: case 6:
*out = cfwInfo.splashDurationMsec; *out = cfwInfo.splashDurationMsec;
break; break;
case 7:
*out = (s64)cfwInfo.volumeSliderOverride;
break;
case 0x10: case 0x10:
*out = (s64)cfwInfo.autobootTwlTitleId; *out = (s64)cfwInfo.autobootTwlTitleId;
break; break;
case 0x11: case 0x11:
*out = cfwInfo.autobootCtrAppmemtype; *out = cfwInfo.autobootCtrAppmemtype;
break; break;
case 0x80:
*out = fcramDescriptor->appRegion.regionSizeInBytes;
break;
case 0x100: case 0x100:
*out = (s64)cfwInfo.hbldr3dsxTitleId; *out = (s64)cfwInfo.hbldr3dsxTitleId;
break; break;
@ -120,18 +109,7 @@ Result GetSystemInfoHook(s64 *out, s32 type, s32 param)
case 0x10C: case 0x10C:
*out = (s64)cfwInfo.bottomScreenFilter.invert; *out = (s64)cfwInfo.bottomScreenFilter.invert;
break; break;
case 0x10D:
*out = (s64)cfwInfo.topScreenFilter.colorCurveCorrection;
break;
case 0x10E:
*out = (s64)cfwInfo.bottomScreenFilter.colorCurveCorrection;
break;
case 0x180:
*out = cfwInfo.pluginLoaderFlags;
break;
case 0x181:
*out = disableThreadRedirection;
break;
case 0x200: // isRelease case 0x200: // isRelease
*out = cfwInfo.flags & 1; *out = cfwInfo.flags & 1;
break; break;

View File

@ -35,9 +35,8 @@
static u32 nbEnabled = 0; static u32 nbEnabled = 0;
static u32 maskedPids[MAX_DEBUG]; static u32 maskedPids[MAX_DEBUG];
static u32 masks[MAX_DEBUG][8] = {0}; static u32 masks[MAX_DEBUG][8] = {0};
static bool forceBetterSoc = false;
u8 svcSignalingEnabled = 0; bool svcSignalingEnabled = false;
bool shouldSignalSyscallDebugEvent(KProcess *process, u8 svcId) bool shouldSignalSyscallDebugEvent(KProcess *process, u8 svcId)
{ {
@ -68,7 +67,7 @@ Result SetSyscallDebugEventMask(u32 pid, bool enable, const u32 *mask)
{ {
maskedPids[nbEnabled] = pid; maskedPids[nbEnabled] = pid;
memcpy(&masks[nbEnabled++], tmpMask, 32); memcpy(&masks[nbEnabled++], tmpMask, 32);
svcSignalingEnabled |= 1; svcSignalingEnabled = true;
} }
else else
{ {
@ -88,7 +87,7 @@ Result SetSyscallDebugEventMask(u32 pid, bool enable, const u32 *mask)
} }
maskedPids[--nbEnabled] = 0; maskedPids[--nbEnabled] = 0;
memset(&masks[nbEnabled], 0, 32); memset(&masks[nbEnabled], 0, 32);
svcSignalingEnabled &= ~1; svcSignalingEnabled = false;
} }
KRecursiveLock__Unlock(&syscallDebugEventMaskLock); KRecursiveLock__Unlock(&syscallDebugEventMaskLock);
@ -102,16 +101,6 @@ Result KernelSetStateHook(u32 type, u32 varg1, u32 varg2, u32 varg3)
switch(type) switch(type)
{ {
case 0xA: // Type 10 (ConfigureNew3DSCPU)
{
if (varg1 & (1 << 2)) // Lock faster speed
forceBetterSoc = true;
else if (varg1 & (1 << 3)) // Unlock faster speed
forceBetterSoc = false;
else
res = KernelSetState(type, forceBetterSoc ? 3 : varg1, varg2, varg3);
break;
}
case 0x10000: case 0x10000:
{ {
do do
@ -201,20 +190,6 @@ Result KernelSetStateHook(u32 type, u32 varg1, u32 varg2, u32 varg3)
KRecursiveLock__Unlock(&dbgParamsLock); KRecursiveLock__Unlock(&dbgParamsLock);
break; break;
} }
case 0x10007:
{
if (signalPluginEvent == NULL && varg1)
{
KProcessHandleTable *table = handleTableOfProcess(currentCoreContext->objectContext.currentProcess);
signalPluginEvent = (KEvent *)KProcessHandleTable__ToKAutoObject(table, varg1);
}
break;
}
case 0x10080:
{
disableThreadRedirection = varg1 != 0;
break;
}
default: default:
{ {
res = KernelSetState(type, varg1, varg2, varg3); res = KernelSetState(type, varg1, varg2, varg3);

View File

@ -26,61 +26,19 @@
#include "svc/MapProcessMemoryEx.h" #include "svc/MapProcessMemoryEx.h"
Result MapProcessMemoryEx(Handle dstProcessHandle, u32 vaDst, Handle srcProcessHandle, u32 vaSrc, u32 size, MapExFlags flags) Result MapProcessMemoryEx(Handle processHandle, void *dst, void *src, u32 size)
{ {
Result res = 0;
u32 sizeInPage = size >> 12;
KLinkedList list;
KProcess *srcProcess;
KProcess *dstProcess;
KProcessHandleTable *handleTable = handleTableOfProcess(currentCoreContext->objectContext.currentProcess); KProcessHandleTable *handleTable = handleTableOfProcess(currentCoreContext->objectContext.currentProcess);
KProcessHwInfo *currentHwInfo = hwInfoOfProcess(currentCoreContext->objectContext.currentProcess);
KProcess *process = KProcessHandleTable__ToKProcess(handleTable, processHandle);
if (dstProcessHandle == CUR_PROCESS_HANDLE) if(process == NULL)
{
dstProcess = currentCoreContext->objectContext.currentProcess;
KAutoObject__AddReference((KAutoObject *)dstProcess);
}
else
dstProcess = KProcessHandleTable__ToKProcess(handleTable, dstProcessHandle);
if (dstProcess == NULL)
return 0xD8E007F7; return 0xD8E007F7;
if (srcProcessHandle == CUR_PROCESS_HANDLE) Result res = KProcessHwInfo__MapProcessMemory(currentHwInfo, hwInfoOfProcess(process), dst, src, size >> 12);
{
srcProcess = currentCoreContext->objectContext.currentProcess;
KAutoObject__AddReference((KAutoObject *)srcProcess);
}
else
srcProcess = KProcessHandleTable__ToKProcess(handleTable, srcProcessHandle);
if (srcProcess == NULL) KAutoObject *obj = (KAutoObject *)process;
{ obj->vtable->DecrementReferenceCount(obj);
res = 0xD8E007F7;
goto exit1;
}
KLinkedList__Initialize(&list);
res = KProcessHwInfo__GetListOfKBlockInfoForVA(hwInfoOfProcess(srcProcess), &list, vaSrc, sizeInPage);
if (res >= 0)
{
// Check if the destination address is free and large enough
res = KProcessHwInfo__CheckVaState(hwInfoOfProcess(dstProcess), vaDst, size, 0, 0);
if (res == 0)
res = KProcessHwInfo__MapListOfKBlockInfo(hwInfoOfProcess(dstProcess), vaDst, &list, (flags & MAPEXFLAGS_PRIVATE) ? 0xBB05 : 0x5806, MEMPERM_RW | 0x18, 0);
}
KLinkedList_KBlockInfo__Clear(&list);
((KAutoObject *)srcProcess)->vtable->DecrementReferenceCount((KAutoObject *)srcProcess);
exit1:
((KAutoObject *)dstProcess)->vtable->DecrementReferenceCount((KAutoObject *)dstProcess);
invalidateEntireInstructionCache();
flushEntireDataCache();
return res; return res;
} }

View File

@ -162,43 +162,6 @@ Result SendSyncRequestHook(Handle handle)
break; break;
} }
case 0x00C0080: // srv: publishToSubscriber
{
SessionInfo *info = SessionInfo_Lookup(clientSession->parentSession);
if (info != NULL && strcmp(info->name, "srv:") == 0 && cmdbuf[1] == 0x1002)
{
// Wake up application thread
PLG__WakeAppThread();
cmdbuf[0] = 0xC0040;
cmdbuf[1] = 0;
skip = true;
}
break;
}
case 0x00D0080: // APT:ReceiveParameter
{
SessionInfo *info = SessionInfo_Lookup(clientSession->parentSession);
if (info != NULL && strncmp(info->name, "APT:", 4) == 0 && cmdbuf[1] == 0x300)
{
res = SendSyncRequest(handle);
skip = true;
if (res >= 0)
{
u32 plgStatus = PLG_GetStatus();
u32 command = cmdbuf[3];
if ((plgStatus == PLG_CFG_RUNNING && command == 3) // COMMAND_RESPONSE
|| (plgStatus == PLG_CFG_INHOME && (command >= 10 || command <= 12))) // COMMAND_WAKEUP_BY_EXIT || COMMAND_WAKEUP_BY_PAUSE
PLG_SignalEvent(PLG_CFG_HOME_EVENT);
}
}
break;
}
case 0x4010082: case 0x4010082:
{ {
SessionInfo *info = SessionInfo_Lookup(clientSession->parentSession); SessionInfo *info = SessionInfo_Lookup(clientSession->parentSession);

View File

@ -26,7 +26,7 @@
#include "svc/SetGpuProt.h" #include "svc/SetGpuProt.h"
Result SetGpuProt(bool prot CTR_UNUSED) Result SetGpuProt(bool prot UNUSED)
{ {
return 0; return 0;
} }

View File

@ -29,30 +29,12 @@
Result UnmapProcessMemoryEx(Handle processHandle, void *dst, u32 size) Result UnmapProcessMemoryEx(Handle processHandle, void *dst, u32 size)
{ {
Result res = 0;
KProcess *process;
KProcessHwInfo *hwInfo;
KProcessHandleTable *handleTable = handleTableOfProcess(currentCoreContext->objectContext.currentProcess);
if(GET_VERSION_MINOR(kernelVersion) < 37) // < 6.x if(GET_VERSION_MINOR(kernelVersion) < 37) // < 6.x
return UnmapProcessMemory(processHandle, dst, size); // equivalent when size <= 64MB return UnmapProcessMemory(processHandle, dst, size); // equivalent when size <= 64MB
if (processHandle == CUR_PROCESS_HANDLE) KProcessHwInfo *currentHwInfo = hwInfoOfProcess(currentCoreContext->objectContext.currentProcess);
{
process = currentCoreContext->objectContext.currentProcess;
KAutoObject__AddReference((KAutoObject *)process);
}
else
process = KProcessHandleTable__ToKProcess(handleTable, processHandle);
if (process == NULL) Result res = KProcessHwInfo__UnmapProcessMemory(currentHwInfo, dst, size >> 12);
return 0xD8E007F7;
hwInfo = hwInfoOfProcess(process);
res = KProcessHwInfo__UnmapProcessMemory(hwInfo, dst, size >> 12);
((KAutoObject *)process)->vtable->DecrementReferenceCount((KAutoObject *)process);
invalidateEntireInstructionCache(); invalidateEntireInstructionCache();
flushEntireDataCache(); flushEntireDataCache();

View File

@ -69,14 +69,6 @@ ControlMemoryHookWrapper:
add sp, #12 add sp, #12
pop {pc} pop {pc}
.global ExitProcessHookWrapper
.type ExitProcessHookWrapper, %function
ExitProcessHookWrapper:
push {lr}
bl ExitProcessHook
pop {pc}
.global ControlMemoryEx .global ControlMemoryEx
.type ControlMemoryEx, %function .type ControlMemoryEx, %function
ControlMemoryEx: ControlMemoryEx:
@ -105,25 +97,3 @@ CreateThreadHookWrapper:
ldr r1, [sp, #8] ldr r1, [sp, #8]
add sp, sp, #12 add sp, sp, #12
pop {pc} pop {pc}
.global ControlMemoryUnsafeWrapper
.type ControlMemoryUnsafeWrapper, %function
ControlMemoryUnsafeWrapper:
push {lr}
str r4, [sp, #-4]!
bl ControlMemoryUnsafe
add sp, #4
pop {pc}
.global MapProcessMemoryExWrapper
.type MapProcessMemoryExWrapper, %function
MapProcessMemoryExWrapper:
push {r5, lr} @ We need to save r5 because the old implementation doesn't save it
cmp r0, #0xFFFFFFF2 @ Check magic value, for backwards compatibility
moveq r0, r6 @ If value present, flags present in r5 and dst process in r6, so move dst process back to r0
movne r5, #0 @ If value not present, clear the flags as its the old version
str r5, [sp, #-4]!
str r4, [sp, #-4]!
bl MapProcessMemoryEx
add sp, #8
pop {r5, pc}

View File

@ -96,36 +96,6 @@ KObjectMutex__Release:
blx r12 blx r12
bx lr bx lr
.global KProcessHwInfo__MapL1Section_Hook
.type KProcessHwInfo__MapL1Section_Hook, %function
KProcessHwInfo__MapL1Section_Hook:
@r0 => hwInfo
@sp + 0x34 => our ptr to state
add r1, sp, #0x34
str lr, [sp, #-4]!
bl PatchDescriptorAccessControl
ldr lr, [sp], #4
ldmfd sp, {r0-r4}
sub sp, sp, #0x14
add r4, sp, #0x48
mov r11, #0
mov pc, lr
.global KProcessHwInfo__MapL2Section_Hook
.type KProcessHwInfo__MapL2Section_Hook, %function
KProcessHwInfo__MapL2Section_Hook:
@r0 => hwInfo
@sp + 0x34 => our ptr to state
add r1, sp, #0x34
str lr, [sp, #-4]!
bl PatchDescriptorAccessControl
ldr lr, [sp], #4
ldmfd sp, {r0-r4}
sub sp, sp, #0x4C
mov r4, r1
mov r6, r2
mov pc, lr
.global safecpy .global safecpy
.type safecpy, %function .type safecpy, %function
safecpy: safecpy:

View File

@ -247,25 +247,11 @@ private:
static inline bool ApplyCodeBpsPatch(u64 prog_id, u8 *code, u32 size) static inline bool ApplyCodeBpsPatch(u64 prog_id, u8 *code, u32 size)
{ {
bool isSysmodule = (prog_id >> 32) == 0x00040130; char bps_path[] = "/luma/titles/0000000000000000/code.bps";
progIdToStr(bps_path + 28, prog_id);
util::File patch_file; util::File patch_file;
if(!patch_file.Open(bps_path, FS_OPEN_READ))
if (isSysmodule) return true;
{
char bps_path[] = "/luma/sysmodules/0000000000000000.bps";
prog_id &= ~0xF0000000ull; // clear N3DS bit
progIdToStr(bps_path + 32, prog_id);
if(!patch_file.Open(bps_path, FS_OPEN_READ))
return true;
}
else
{
char bps_path[] = "/luma/titles/0000000000000000/code.bps";
progIdToStr(bps_path + 28, prog_id);
if(!patch_file.Open(bps_path, FS_OPEN_READ))
return true;
}
const u32 patch_size = u32(patch_file.GetSize().value_or(0)); const u32 patch_size = u32(patch_file.GetSize().value_or(0));
// Temporarily use APPLICATION memory to store the source and patch data. // Temporarily use APPLICATION memory to store the source and patch data.

View File

@ -34,12 +34,6 @@
extern bool isN3DS; extern bool isN3DS;
// Note: just switch to [[attribute]] once we use clangd and cmake
// vscode-cpptools has (or had?) some issues with C23 support
#if __GNUC__ >= 15
// Required by GCC 15+ but ignored (with warning) before
__attribute__((nonstring))
#endif
static const char serviceList[34][8] = static const char serviceList[34][8] =
{ {
"APT:U", "APT:U",
@ -178,7 +172,7 @@ static const u32 kernelCaps[] =
{ {
0xFC00022C, // Kernel release version 8.0 is necessary for using the new linear mapping. Modified below. 0xFC00022C, // Kernel release version 8.0 is necessary for using the new linear mapping. Modified below.
// Normal applications only have access to 0x1FF50000-0x1FF58000, 0x1FF70000-0x1FF78000 (both as IO), // Normal applications only have access to 0x1FF50000-0x1FF58000, 0x1FF70000-0x1FF78000,
// however we can load unsigned DSP firmware binaries. // however we can load unsigned DSP firmware binaries.
0xFF81FF00, // RW static range mapping: 0x1FF00000 (DSP RAM, start) 0xFF81FF00, // RW static range mapping: 0x1FF00000 (DSP RAM, start)
0xFF81FF80, // RW static range mapping: 0x1FF80000 (DSP RAM, end) 0xFF81FF80, // RW static range mapping: 0x1FF80000 (DSP RAM, end)
@ -186,10 +180,6 @@ static const u32 kernelCaps[] =
0xFF91F000, // RO static range mapping: 0x1F000000 (VRAM, start) 0xFF91F000, // RO static range mapping: 0x1F000000 (VRAM, start)
0xFF91F600, // RO static range mapping: 0x1F600000 (VRAM, end) 0xFF91F600, // RO static range mapping: 0x1F600000 (VRAM, end)
// Give access to all Arm11-accessible IO
0xFF81EC00, // RW IO range mapping: 0x1EC00000 (PA 0x10100000, start)
0xFF81F000, // RW IO range mapping: 0x10500000 (PA 0x10500000, end)
0xFF002109, // Exflags: APPLICATION memtype + "Shared page writing" + "Allow debug" + "Access core2" 0xFF002109, // Exflags: APPLICATION memtype + "Shared page writing" + "Allow debug" + "Access core2"
0xFE000200, // Handle table size: 0x200 0xFE000200, // Handle table size: 0x200

View File

@ -23,9 +23,7 @@ Result IFile_OpenFromArchive(IFile *file, FS_Archive archive, FS_Path filePath,
Result IFile_Close(IFile *file) Result IFile_Close(IFile *file)
{ {
Result res = file->handle != 0 ? FSFILE_Close(file->handle) : 0; return FSFILE_Close(file->handle);
file->handle = 0;
return res;
} }
Result IFile_GetSize(IFile *file, u64 *size) Result IFile_GetSize(IFile *file, u64 *size)

View File

@ -8,26 +8,12 @@
#define SYSMODULE_CXI_COOKIE_MASK 0xEEEE000000000000ull #define SYSMODULE_CXI_COOKIE_MASK 0xEEEE000000000000ull
// Used by the custom loader command 0x101 (ControlApplicationMemoryModeOverride)
typedef struct ControlApplicationMemoryModeOverrideConfig {
u32 query : 1; //< Only query the current configuration, do not update it.
u32 enable_o3ds : 1; //< Enable o3ds memory mode override
u32 enable_n3ds : 1; //< Enable n3ds memory mode override
u32 o3ds_mode : 3; //< O3ds memory mode
u32 n3ds_mode : 3; //< N3ds memory mode
} ControlApplicationMemoryModeOverrideConfig;
static ControlApplicationMemoryModeOverrideConfig g_memoryOverrideConfig = { 0 };
extern u32 config, multiConfig, bootConfig; extern u32 config, multiConfig, bootConfig;
extern bool isN3DS, isSdMode, nextGamePatchDisabled; extern bool isN3DS, isSdMode;
static u64 g_cached_programHandle; // for exheader info only static u64 g_cached_programHandle; // for exheader info only
static ExHeader_Info g_exheaderInfo; static ExHeader_Info g_exheaderInfo;
// Last application exheader info, for use with custom cmd 0x102
static ExHeader_Info g_lastAppExheaderInfo;
static IFile g_cached_sysmoduleCxiFile; static IFile g_cached_sysmoduleCxiFile;
static u64 g_cached_sysmoduleCxiCookie; static u64 g_cached_sysmoduleCxiCookie;
static Ncch g_cached_sysmoduleCxiNcch; static Ncch g_cached_sysmoduleCxiNcch;
@ -124,11 +110,6 @@ static inline bool IsSysmoduleId(u64 tid)
return (tid >> 32) == 0x00040130; return (tid >> 32) == 0x00040130;
} }
static inline bool IsApplicationId(u64 tid)
{
return (tid >> 32) == 0x00040000;
}
static inline bool IsSysmoduleCxiCookie(u64 programHandle) static inline bool IsSysmoduleCxiCookie(u64 programHandle)
{ {
return (programHandle >> 32) == (SYSMODULE_CXI_COOKIE_MASK >> 32); return (programHandle >> 32) == (SYSMODULE_CXI_COOKIE_MASK >> 32);
@ -230,70 +211,6 @@ static Result loadCode(const ExHeader_Info *exhi, u64 programHandle, const prog_
return 0; return 0;
} }
static u32 plgldrRefcount = 0;
static Handle plgldrHandle = 0;
Result plgldrInit(void)
{
Result res;
if (AtomicPostIncrement(&plgldrRefcount)) return 0;
for(res = 0xD88007FA; res == (Result)0xD88007FA; svcSleepThread(500 * 1000LL)) {
res = svcConnectToPort(&plgldrHandle, "plg:ldr");
if(R_FAILED(res) && res != (Result)0xD88007FA) {
AtomicDecrement(&plgldrRefcount);
return res;
}
}
return 0;
}
void plgldrExit(void)
{
if (AtomicDecrement(&plgldrRefcount)) return;
svcCloseHandle(plgldrHandle);
}
// Get plugin loader state
Result PLGLDR__IsPluginLoaderEnabled(bool *isEnabled)
{
Result res = 0;
u32 *cmdbuf = getThreadCommandBuffer();
cmdbuf[0] = IPC_MakeHeader(2, 0, 0);
if (R_SUCCEEDED((res = svcSendSyncRequest(plgldrHandle))))
{
res = cmdbuf[1];
*isEnabled = cmdbuf[2];
}
return res;
}
// Try to load a plugin for the game
static Result PLGLDR_LoadPlugin(u32 processID, bool isHomebrew)
{
// Special case handling: games rebooting the 3DS on old models
if (!isN3DS && g_exheaderInfo.aci.local_caps.core_info.o3ds_system_mode > 0)
{
// Check if the plugin loader is enabled, otherwise skip the loading part
bool enabled = false;
PLGLDR__IsPluginLoaderEnabled(&enabled);
if (!enabled) {
return 0;
}
}
u32* cmdbuf = getThreadCommandBuffer();
cmdbuf[0] = IPC_MakeHeader(1, 2, 0);
cmdbuf[1] = processID;
cmdbuf[2] = isHomebrew;
return svcSendSyncRequest(plgldrHandle);
}
static inline bool IsHioId(u64 id) static inline bool IsHioId(u64 id)
{ {
// FS loads HIO titles at boot when it can. For HIO titles, title/programId and "program handle" // FS loads HIO titles at boot when it can. For HIO titles, title/programId and "program handle"
@ -339,8 +256,6 @@ static Result GetProgramInfoImpl(ExHeader_Info *exheaderInfo, u64 programHandle)
if (R_FAILED(res)) if (R_FAILED(res))
return res; return res;
u64 originalTitleId = exheaderInfo->aci.local_caps.title_id;
// Tweak 3dsx placeholder title exheaderInfo // Tweak 3dsx placeholder title exheaderInfo
if (hbldrIs3dsxTitle(exheaderInfo->aci.local_caps.title_id)) if (hbldrIs3dsxTitle(exheaderInfo->aci.local_caps.title_id))
{ {
@ -348,6 +263,7 @@ static Result GetProgramInfoImpl(ExHeader_Info *exheaderInfo, u64 programHandle)
} }
else else
{ {
u64 originalTitleId = exheaderInfo->aci.local_caps.title_id;
bool exhLoadedExternally = false; bool exhLoadedExternally = false;
if (CONFIG(PATCHGAMES)) if (CONFIG(PATCHGAMES))
{ {
@ -365,13 +281,6 @@ static Result GetProgramInfoImpl(ExHeader_Info *exheaderInfo, u64 programHandle)
exheaderInfo->aci.local_caps.title_id = originalTitleId; exheaderInfo->aci.local_caps.title_id = originalTitleId;
} }
if (IsApplicationId(originalTitleId)) {
if (g_memoryOverrideConfig.enable_o3ds)
exheaderInfo->aci.local_caps.core_info.o3ds_system_mode = g_memoryOverrideConfig.o3ds_mode;
if (g_memoryOverrideConfig.enable_n3ds)
exheaderInfo->aci.local_caps.core_info.n3ds_system_mode = g_memoryOverrideConfig.n3ds_mode;
}
return res; return res;
} }
@ -384,9 +293,6 @@ static Result GetProgramInfo(u64 programHandle)
{ {
res = GetProgramInfoImpl(&g_exheaderInfo, programHandle); res = GetProgramInfoImpl(&g_exheaderInfo, programHandle);
g_cached_programHandle = R_SUCCEEDED(res) ? programHandle : 0; g_cached_programHandle = R_SUCCEEDED(res) ? programHandle : 0;
if (R_SUCCEEDED(res) && (u32)((g_exheaderInfo.aci.local_caps.title_id >> 0x20) & 0xFFFFFFEDULL) == 0x00040000) {
memcpy(&g_lastAppExheaderInfo, &g_exheaderInfo, sizeof(g_lastAppExheaderInfo));
}
} }
return res; return res;
@ -430,9 +336,6 @@ static Result LoadProcessImpl(Handle *outProcessHandle, const ExHeader_Info *exh
u64 titleId = exhi->aci.local_caps.title_id; u64 titleId = exhi->aci.local_caps.title_id;
if (R_SUCCEEDED(res = loadCode(exhi, programHandle, &mapped))) if (R_SUCCEEDED(res = loadCode(exhi, programHandle, &mapped)))
{ {
u32 *code = (u32 *)mapped.text_addr;
bool isHomebrew = code[0] == 0xEA000006 && code[8] == 0xE1A0400E;
memcpy(&csh.name, csi->name, 8); memcpy(&csh.name, csi->name, 8);
csh.program_id = titleId; csh.program_id = titleId;
csh.text_addr = vaddr.text_addr; csh.text_addr = vaddr.text_addr;
@ -451,16 +354,6 @@ static Result LoadProcessImpl(Handle *outProcessHandle, const ExHeader_Info *exh
res = svcCreateProcess(outProcessHandle, codeset, exhi->aci.kernel_caps.descriptors, count); res = svcCreateProcess(outProcessHandle, codeset, exhi->aci.kernel_caps.descriptors, count);
svcCloseHandle(codeset); svcCloseHandle(codeset);
res = R_SUCCEEDED(res) ? 0 : res; res = R_SUCCEEDED(res) ? 0 : res;
// check for plugin
if (!res && ((u32)((titleId >> 0x20) & 0xFFFFFFEDULL) == 0x00040000))
{
u32 processID;
assertSuccess(svcGetProcessId(&processID, *outProcessHandle));
assertSuccess(plgldrInit());
assertSuccess(PLGLDR_LoadPlugin(processID, isHomebrew));
plgldrExit();
}
} }
} }
@ -501,16 +394,15 @@ static Result RegisterProgram(u64 *programHandle, FS_ProgramInfo *title, FS_Prog
bool loadedCxiFromStorage = false; bool loadedCxiFromStorage = false;
if (IsSysmoduleId(titleId) && CONFIG(LOADEXTFIRMSANDMODULES)) if (IsSysmoduleId(titleId) && CONFIG(LOADEXTFIRMSANDMODULES))
{ {
u64 tid2 = titleId & ~0xF0000000ull;
// Forbid having two such file handles being open at the same time // Forbid having two such file handles being open at the same time
// Also reload the file even if already cached. // Also reload the file even if already cached.
InvalidateCachedCxiFile(); InvalidateCachedCxiFile();
res = openSysmoduleCxi(&g_cached_sysmoduleCxiFile, tid2); res = openSysmoduleCxi(&g_cached_sysmoduleCxiFile, titleId);
if (R_SUCCEEDED(res)) if (R_SUCCEEDED(res))
{ {
// A .cxi with the correct name in /luma/sysmodule exists, proceed (ignoring N3DS TID bits) // A .cxi with the correct name in /luma/sysmodule exists, proceed
*programHandle = SYSMODULE_CXI_COOKIE_MASK | (u32)tid2; *programHandle = SYSMODULE_CXI_COOKIE_MASK | (u32)titleId;
g_cached_sysmoduleCxiCookie = *programHandle; g_cached_sysmoduleCxiCookie = *programHandle;
loadedCxiFromStorage = true; loadedCxiFromStorage = true;
} }
@ -548,7 +440,6 @@ void loaderHandleCommands(void *ctx)
(void)ctx; (void)ctx;
FS_ProgramInfo title; FS_ProgramInfo title;
FS_ProgramInfo update; FS_ProgramInfo update;
ControlApplicationMemoryModeOverrideConfig memModeOverride;
u32* cmdbuf; u32* cmdbuf;
u16 cmdid; u16 cmdid;
int res; int res;
@ -588,26 +479,6 @@ void loaderHandleCommands(void *ctx)
cmdbuf[2] = IPC_Desc_StaticBuffer(sizeof(ExHeader_Info), 0); //0x1000002; cmdbuf[2] = IPC_Desc_StaticBuffer(sizeof(ExHeader_Info), 0); //0x1000002;
cmdbuf[3] = (u32)&g_exheaderInfo; // official Loader makes a copy here, but this is isn't necessary cmdbuf[3] = (u32)&g_exheaderInfo; // official Loader makes a copy here, but this is isn't necessary
break; break;
// Custom
case 0x100: // DisableNextGamePatch
nextGamePatchDisabled = true;
cmdbuf[0] = IPC_MakeHeader(0x100, 1, 0);
cmdbuf[1] = (Result)0;
break;
case 0x101: // ControlApplicationMemoryModeOverride
memcpy(&memModeOverride, &cmdbuf[1], sizeof(ControlApplicationMemoryModeOverrideConfig));
if (!memModeOverride.query)
g_memoryOverrideConfig = memModeOverride;
cmdbuf[0] = IPC_MakeHeader(0x101, 2, 0);
cmdbuf[1] = (Result)0;
memcpy(&cmdbuf[2], &g_memoryOverrideConfig, sizeof(ControlApplicationMemoryModeOverrideConfig));
break;
case 0x102: // GetLastApplicationProgramInfo
cmdbuf[0] = IPC_MakeHeader(0x102, 1, 2);
cmdbuf[1] = (Result)0;
cmdbuf[2] = IPC_Desc_StaticBuffer(sizeof(ExHeader_Info), 0);
cmdbuf[3] = (u32)&g_lastAppExheaderInfo;
break;
default: // error default: // error
cmdbuf[0] = IPC_MakeHeader(0, 1, 0); cmdbuf[0] = IPC_MakeHeader(0, 1, 0);
cmdbuf[1] = 0xD900182F; cmdbuf[1] = 0xD900182F;

View File

@ -10,7 +10,7 @@
#include "hbldr.h" #include "hbldr.h"
u32 config, multiConfig, bootConfig; u32 config, multiConfig, bootConfig;
bool isN3DS, isSdMode, nextGamePatchDisabled, isLumaWithKext; bool isN3DS, isSdMode;
// MAKE SURE fsreg has been init before calling this // MAKE SURE fsreg has been init before calling this
static Result fsldrPatchPermissions(void) static Result fsldrPatchPermissions(void)
@ -33,7 +33,7 @@ static inline void loadCFWInfo(void)
s64 out; s64 out;
u64 hbldrTid = 0; u64 hbldrTid = 0;
isLumaWithKext = svcGetSystemInfo(&out, 0x20000, 0) == 1; bool isLumaWithKext = svcGetSystemInfo(&out, 0x20000, 0) == 1;
if (isLumaWithKext) if (isLumaWithKext)
{ {
svcGetSystemInfo(&out, 0x10000, 3); svcGetSystemInfo(&out, 0x10000, 3);
@ -59,12 +59,7 @@ static inline void loadCFWInfo(void)
if (numKips >= 6) if (numKips >= 6)
panic(0xDEADCAFE); panic(0xDEADCAFE);
#ifndef BUILD_FOR_EXPLOIT_DEV config = 0; // all options 0
// Most options 0, except select ones
config = BIT(PATCHVERSTRING) | BIT(PATCHGAMES) | BIT(LOADEXTFIRMSANDMODULES);
#else
config = 0;
#endif
multiConfig = 0; multiConfig = 0;
bootConfig = 0; bootConfig = 0;
isN3DS = OS_KernelConfig->app_memtype >= 6; isN3DS = OS_KernelConfig->app_memtype >= 6;
@ -120,7 +115,7 @@ void initSystem(void)
} }
static const ServiceManagerServiceEntry services[] = { static const ServiceManagerServiceEntry services[] = {
{ "Loader", 2, loaderHandleCommands, false }, { "Loader", 1, loaderHandleCommands, false },
{ "hb:ldr", 2, hbldrHandleCommands, true }, { "hb:ldr", 2, hbldrHandleCommands, true },
{ NULL }, { NULL },
}; };
@ -129,13 +124,11 @@ static const ServiceManagerNotificationEntry notifications[] = {
{ 0x000, NULL }, { 0x000, NULL },
}; };
static u8 CTR_ALIGN(4) staticBufferForHbldr[0x400]; static u8 ALIGN(4) staticBufferForHbldr[0x400];
static_assert(ARGVBUF_SIZE > 2 * PATH_MAX, "Wrong 3DSX argv buffer size"); static_assert(ARGVBUF_SIZE > 2 * PATH_MAX, "Wrong 3DSX argv buffer size");
int main(void) int main(void)
{ {
nextGamePatchDisabled = false;
// Loader doesn't use any input static buffer, so we should be fine // Loader doesn't use any input static buffer, so we should be fine
u32 *sbuf = getThreadStaticBuffers(); u32 *sbuf = getThreadStaticBuffers();
sbuf[0] = IPC_Desc_StaticBuffer(sizeof(staticBufferForHbldr), 0); sbuf[0] = IPC_Desc_StaticBuffer(sizeof(staticBufferForHbldr), 0);

View File

@ -148,7 +148,7 @@ static u32 findFunctionStart(u8 *code, u32 pos)
return 0xFFFFFFFF; return 0xFFFFFFFF;
} }
static inline bool findLayeredFsSymbols(u8 *code, u32 size, u32 *fsMountArchive, u32 *fsRegisterArchive, u32 *fsTryOpenFile, u32 *fsOpenFileDirectly, u32 *fsUnMountArchive) static inline bool findLayeredFsSymbols(u8 *code, u32 size, u32 *fsMountArchive, u32 *fsRegisterArchive, u32 *fsTryOpenFile, u32 *fsOpenFileDirectly)
{ {
u32 found = 0, u32 found = 0,
*temp = NULL; *temp = NULL;
@ -165,12 +165,6 @@ static inline bool findLayeredFsSymbols(u8 *code, u32 size, u32 *fsMountArchive,
case 0xE24DD028: case 0xE24DD028:
if(addr <= size - 16 && *fsMountArchive == 0xFFFFFFFF && addr32[1] == 0xE1A04000 && addr32[2] == 0xE59F60A8 && addr32[3] == 0xE3A0C001) temp = fsMountArchive; if(addr <= size - 16 && *fsMountArchive == 0xFFFFFFFF && addr32[1] == 0xE1A04000 && addr32[2] == 0xE59F60A8 && addr32[3] == 0xE3A0C001) temp = fsMountArchive;
break; break;
case 0xE2844001:
if(addr <= size - 12 && *fsUnMountArchive == 0xFFFFFFFF && addr32[1] == 0xE3540020 && addr32[2] == 0x3AFFFFF0) temp = fsUnMountArchive;
break;
case 0xE353003A:
if(addr <= size - 12 && *fsUnMountArchive == 0xFFFFFFFF && (addr32[1] & 0xFFFFFF0F) == 0x0A000009 && (addr32[2] & 0xFFFF0FF0) == 0xE1A00400) temp = fsUnMountArchive;
break;
case 0xE3500008: case 0xE3500008:
if(addr <= size - 12 && *fsRegisterArchive == 0xFFFFFFFF && (addr32[1] & 0xFFF00FF0) == 0xE1800400 && (addr32[2] & 0xFFF00FF0) == 0xE1800FC0) temp = fsRegisterArchive; if(addr <= size - 12 && *fsRegisterArchive == 0xFFFFFFFF && (addr32[1] & 0xFFF00FF0) == 0xE1800400 && (addr32[2] & 0xFFF00FF0) == 0xE1800FC0) temp = fsRegisterArchive;
break; break;
@ -189,14 +183,14 @@ static inline bool findLayeredFsSymbols(u8 *code, u32 size, u32 *fsMountArchive,
if(*temp != 0xFFFFFFFF) if(*temp != 0xFFFFFFFF)
{ {
found++; found++;
if(found == 5) break; if(found == 4) break;
} }
temp = NULL; temp = NULL;
} }
} }
return found == 5; return found == 4;
} }
static inline bool findLayeredFsPayloadOffset(u8 *code, u32 size, u32 roSize, u32 dataSize, u32 roAddress, u32 dataAddress, u32 *payloadOffset, u32 *pathOffset, u32 *pathAddress) static inline bool findLayeredFsPayloadOffset(u8 *code, u32 size, u32 roSize, u32 dataSize, u32 roAddress, u32 dataAddress, u32 *payloadOffset, u32 *pathOffset, u32 *pathAddress)
@ -271,22 +265,12 @@ static inline bool applyCodeIpsPatch(u64 progId, u8 *code, u32 size)
/* Here we look for "/luma/titles/[u64 titleID in hex, uppercase]/code.ips" /* Here we look for "/luma/titles/[u64 titleID in hex, uppercase]/code.ips"
If it exists it should be an IPS format patch */ If it exists it should be an IPS format patch */
bool isSysmodule = (progId >> 32) == 0x00040130; char path[] = "/luma/titles/0000000000000000/code.ips";
progIdToStr(path + 28, progId);
IFile file; IFile file;
if (isSysmodule) if(!openLumaFile(&file, path)) return true;
{
char path[] = "/luma/sysmodules/0000000000000000.ips";
progId &= ~0xF0000000ull; // clear N3DS bit
progIdToStr(path + 32, progId);
if(!openLumaFile(&file, path)) return true;
}
else
{
char path[] = "/luma/titles/0000000000000000/code.ips";
progIdToStr(path + 28, progId);
if(!openLumaFile(&file, path)) return true;
}
bool ret = false; bool ret = false;
u8 buffer[5]; u8 buffer[5];
@ -337,7 +321,6 @@ exit:
Result openSysmoduleCxi(IFile *outFile, u64 progId) Result openSysmoduleCxi(IFile *outFile, u64 progId)
{ {
progId &= ~0xF0000000ull; // clear N3DS bit
char path[] = "/luma/sysmodules/0000000000000000.cxi"; char path[] = "/luma/sysmodules/0000000000000000.cxi";
progIdToStr(path + sizeof("/luma/sysmodules/0000000000000000") - 2, progId); progIdToStr(path + sizeof("/luma/sysmodules/0000000000000000") - 2, progId);
@ -484,7 +467,7 @@ static inline bool loadTitleLocaleConfig(u64 progId, u8 *mask, u8 *regionId, u8
if(R_FAILED(IFile_GetSize(&file, &fileSize)) || fileSize < 3) goto exit; if(R_FAILED(IFile_GetSize(&file, &fileSize)) || fileSize < 3) goto exit;
if(fileSize >= 12) fileSize = 12; if(fileSize >= 12) fileSize = 12;
char buf[12+1] = "------------"; char buf[12] = "------------";
u64 total; u64 total;
if(R_FAILED(IFile_Read(&file, &total, buf, fileSize))) goto exit; if(R_FAILED(IFile_Read(&file, &total, buf, fileSize))) goto exit;
@ -508,7 +491,7 @@ static inline bool loadTitleLocaleConfig(u64 progId, u8 *mask, u8 *regionId, u8
"HK", "MO", "--", "--", "--", "--", "--", "--", "ID", "SG", "TH", "PH", "HK", "MO", "--", "--", "--", "--", "--", "--", "ID", "SG", "TH", "PH",
"MY", "--", "--", "--", "CN", "--", "--", "--", "--", "--", "--", "--", "MY", "--", "--", "--", "CN", "--", "--", "--", "--", "--", "--", "--",
"AE", "IN", "EG", "OM", "QA", "KW", "SA", "SY", "BH", "JO", "--", "--", "AE", "IN", "EG", "OM", "QA", "KW", "SA", "SY", "BH", "JO", "--", "--",
"--", "--", "--", "--", "SM", "VA", "BM"}; "--", "--", "--", "--", "SM", "VA"};
u32 i; u32 i;
for(i = 0; i < sizeof(regions) / sizeof(char *); i++) for(i = 0; i < sizeof(regions) / sizeof(char *); i++)
@ -575,7 +558,6 @@ static inline bool patchLayeredFs(u64 progId, u8 *code, u32 size, u32 textSize,
if(!archiveId) return true; if(!archiveId) return true;
u32 fsMountArchive = 0xFFFFFFFF, u32 fsMountArchive = 0xFFFFFFFF,
fsUnMountArchive = 0xFFFFFFFF,
fsRegisterArchive = 0xFFFFFFFF, fsRegisterArchive = 0xFFFFFFFF,
fsTryOpenFile = 0xFFFFFFFF, fsTryOpenFile = 0xFFFFFFFF,
fsOpenFileDirectly = 0xFFFFFFFF, fsOpenFileDirectly = 0xFFFFFFFF,
@ -583,44 +565,24 @@ static inline bool patchLayeredFs(u64 progId, u8 *code, u32 size, u32 textSize,
pathOffset = 0, pathOffset = 0,
pathAddress = 0xDEADCAFE; pathAddress = 0xDEADCAFE;
if(!findLayeredFsSymbols(code, textSize, &fsMountArchive, &fsRegisterArchive, &fsTryOpenFile, &fsOpenFileDirectly, &fsUnMountArchive) || if(!findLayeredFsSymbols(code, textSize, &fsMountArchive, &fsRegisterArchive, &fsTryOpenFile, &fsOpenFileDirectly) ||
!findLayeredFsPayloadOffset(code, textSize, roSize, dataSize, roAddress, dataAddress, &payloadOffset, &pathOffset, &pathAddress)) return false; !findLayeredFsPayloadOffset(code, textSize, roSize, dataSize, roAddress, dataAddress, &payloadOffset, &pathOffset, &pathAddress)) return false;
static const char *updateRomFsMounts[] = { "ro2:", static const char *updateRomFsMounts[] = { "rom2:",
"rom2:",
"rex:", "rex:",
"patch:", "patch:",
"ext:", "ext:",
"rom:" }; "rom:" };
u32 updateRomFsIndex;
bool isMarioKart7 = (u32)progId == 0x00030600 || //JPN MK7 //Locate update RomFSes
(u32)progId == 0x00030700 || //EUR MK7 for(updateRomFsIndex = 0; updateRomFsIndex < sizeof(updateRomFsMounts) / sizeof(char *) - 1; updateRomFsIndex++)
(u32)progId == 0x00030800 || //USA MK7
(u32)progId == 0x00030A00 || //KOR MK7
(u32)progId == 0x0008B400; //TWN MK7
// Exclude CHN as it never got updates
const char *updateRomFsMount;
if (isMarioKart7)
{ {
updateRomFsMount = "pat1"; // Isolated to prevent false-positives u32 patternSize = strlen(updateRomFsMounts[updateRomFsIndex]);
} u8 temp[7];
temp[0] = 0;
else memcpy(temp + 1, updateRomFsMounts[updateRomFsIndex], patternSize);
{ if(memsearch(code, temp, size, patternSize + 1) != NULL) break;
u32 updateRomFsIndex;
//Locate update RomFS
for(updateRomFsIndex = 0; updateRomFsIndex < sizeof(updateRomFsMounts) / sizeof(char *) - 1; updateRomFsIndex++)
{
u32 patternSize = strlen(updateRomFsMounts[updateRomFsIndex]);
u8 temp[7];
temp[0] = 0;
memcpy(temp + 1, updateRomFsMounts[updateRomFsIndex], patternSize);
if(memsearch(code, temp, size, patternSize + 1) != NULL) break;
}
updateRomFsMount = updateRomFsMounts[updateRomFsIndex];
} }
//Setup the payload //Setup the payload
@ -631,11 +593,10 @@ static inline bool patchLayeredFs(u64 progId, u8 *code, u32 size, u32 textSize,
romfsRedirPatchSubstituted2 = *(u32 *)(code + fsTryOpenFile); romfsRedirPatchSubstituted2 = *(u32 *)(code + fsTryOpenFile);
romfsRedirPatchHook2 = MAKE_BRANCH(payloadOffset + (u32)&romfsRedirPatchHook2 - (u32)romfsRedirPatch, fsTryOpenFile + 4); romfsRedirPatchHook2 = MAKE_BRANCH(payloadOffset + (u32)&romfsRedirPatchHook2 - (u32)romfsRedirPatch, fsTryOpenFile + 4);
romfsRedirPatchCustomPath = pathAddress; romfsRedirPatchCustomPath = pathAddress;
romfsRedirPatchFsMountArchive = MAKE_BRANCH_LINK(payloadOffset + (u32)&romfsRedirPatchFsMountArchive - (u32)romfsRedirPatch, fsMountArchive); romfsRedirPatchFsMountArchive = 0x100000 + fsMountArchive;
romfsRedirPatchFsUnMountArchive = MAKE_BRANCH_LINK(payloadOffset + (u32)&romfsRedirPatchFsUnMountArchive - (u32)romfsRedirPatch, fsUnMountArchive); romfsRedirPatchFsRegisterArchive = 0x100000 + fsRegisterArchive;
romfsRedirPatchFsRegisterArchive = MAKE_BRANCH_LINK(payloadOffset + (u32)&romfsRedirPatchFsRegisterArchive - (u32)romfsRedirPatch, fsRegisterArchive);
romfsRedirPatchArchiveId = archiveId; romfsRedirPatchArchiveId = archiveId;
memcpy(&romfsRedirPatchUpdateRomFsMount, updateRomFsMount, 4); memcpy(&romfsRedirPatchUpdateRomFsMount, updateRomFsMounts[updateRomFsIndex], 4);
memcpy(payload, romfsRedirPatch, romfsRedirPatchSize); memcpy(payload, romfsRedirPatch, romfsRedirPatchSize);
@ -658,10 +619,6 @@ void patchCode(u64 progId, u16 progVer, u8 *code, u32 size, u32 textSize, u32 ro
progId == 0x000400300000A102LL || //CHN Home Menu progId == 0x000400300000A102LL || //CHN Home Menu
progId == 0x000400300000B102LL; //TWN Home Menu progId == 0x000400300000B102LL; //TWN Home Menu
bool isApp = ((progId >> 32) & ~0x12) == 0x00040000;
bool isApplet = (progId >> 32) == 0x00040030;
bool isSysmodule = (progId >> 32) == 0x00040130;
if(isHomeMenu) if(isHomeMenu)
{ {
bool applyRegionFreePatch = true; bool applyRegionFreePatch = true;
@ -734,65 +691,50 @@ void patchCode(u64 progId, u16 progVer, u8 *code, u32 size, u32 textSize, u32 ro
progId == 0x0004001000022000LL || //EUR MSET progId == 0x0004001000022000LL || //EUR MSET
progId == 0x0004001000026000LL || //CHN MSET progId == 0x0004001000026000LL || //CHN MSET
progId == 0x0004001000027000LL || //KOR MSET progId == 0x0004001000027000LL || //KOR MSET
progId == 0x0004001000028000LL)) //TWN MSET progId == 0x0004001000028000LL) //TWN MSET
&& CONFIG(PATCHVERSTRING))
{ {
if (CONFIG(PATCHVERSTRING)) static const u16 pattern[] = u"Ve";
static u16 *patch;
u32 patchSize = 0,
currentNand = BOOTCFG_NAND;
u16 customVerString[19];
loadCustomVerString(customVerString, &patchSize, currentNand);
if(patchSize != 0) patch = customVerString;
else
{ {
static const u16 pattern[] = u"Ve"; patchSize = 8;
const u16 *patch; u32 currentFirm = BOOTCFG_FIRM;
u32 patchSize = 0,
currentNand = BOOTCFG_NAND;
u16 customVerString[19]; static u16 *verStringsNands[] = { u" Sys",
loadCustomVerString(customVerString, &patchSize, currentNand); u" Emu",
u"Emu2",
u"Emu3",
u"Emu4" },
if(patchSize != 0) patch = customVerString; *verStringsEmuSys[] = { u"EmuS",
else u"Em2S",
{ u"Em3S",
patchSize = 8; u"Em4S" },
static const u16 *const verStringNandEmu[] = { u" Emu", u"Emu2", u"Emu3", u"Emu4" }; *verStringsSysEmu[] = { u"SysE",
patch = currentNand == 0 ? u" Sys" : verStringNandEmu[BOOTCFG_EMUINDEX]; u"SyE2",
} u"SyE3",
u"SyE4" };
//Patch Ver. string patch = (currentFirm != 0) == (currentNand != 0) ? verStringsNands[currentNand] :
if(!patchMemory(code, textSize, (!currentNand ? verStringsSysEmu[currentFirm - 1] : verStringsEmuSys[currentNand - 1]);
pattern,
sizeof(pattern) - 2, 0,
patch,
patchSize, 1
)) goto error;
} }
// Allow date picker to select year up to 2099, not just 2050. //Patch Ver. string
// NNID user's year-of-birth seems to have a similar restriction, if(!patchMemory(code, textSize,
// I'm not removing that as long as any NNID stuff is still active. pattern,
sizeof(pattern) - 2, 0,
// Patch date picker check on entry (date load): patch,
// Look for: patchSize, 1
// 32 00 5x E3 CMP Rx, #0x32 )) goto error;
// ...
// 32 x0 A0 C3 MOVGT Rx, #0x32
u32 *off = (u32 *)code;
for (; (u8 *)off < code + textSize && ((off[0] & 0xFFF0FFFF) != 0xE3500032 || (off[2] & 0xFFFF0FFF) != 0xC3A00032); off++)
{
if (((off[0] >> 16) & 0xF) != ((off[2] >> 12) & 0xF)) // ensure same register used
continue;
}
if ((u8 *)off >= code + textSize) goto error;
off[0] = (off[0] & ~0xFF) | 99;
off[2] = (off[2] & ~0xFF) | 99;
// Patch date picker actions:
// Look for:
// 01 00 80 E2 ADD R0, R0, #1
// 32 00 50 E3 CMP R0, #0x32
off = (u32 *)code;
for (; (u8 *)off < code + textSize && (off[0] != 0xE2800001 || off[1] != 0xE3500032); off++);
if ((u8 *)off >= code + textSize) goto error;
off[1] = (off[1] & ~0xFF) | 99; // patch increment wrap-around compare instruction
off[9] = (off[9] & ~0xFF) | 99; // patch decrement wrap-around conditional move instruction
} }
else if(progId == 0x0004013000008002LL) //NS else if(progId == 0x0004013000008002LL) //NS
@ -984,15 +926,14 @@ void patchCode(u64 progId, u16 progVer, u8 *code, u32 size, u32 textSize, u32 ro
)) goto error; )) goto error;
} }
if (isSysmodule && CONFIG(LOADEXTFIRMSANDMODULES)) if(CONFIG(PATCHGAMES))
{ {
if(!patcherApplyCodeBpsPatch(progId, code, size)) goto error; bool isApp = ((progId >> 32) & ~0x12) == 0x00040000;
if(!applyCodeIpsPatch(progId, code, size)) goto error; bool isApplet = (progId >> 32) == 0x00040030;
} bool isSysmodule = (progId >> 32) == 0x00040130;
if(CONFIG(PATCHGAMES) && !(isApp && nextGamePatchDisabled)) bool shouldPatchIps = !isSysmodule || (isSysmodule && CONFIG(LOADEXTFIRMSANDMODULES));
{ if (shouldPatchIps)
if (!isSysmodule)
{ {
if(!patcherApplyCodeBpsPatch(progId, code, size)) goto error; if(!patcherApplyCodeBpsPatch(progId, code, size)) goto error;
if(!applyCodeIpsPatch(progId, code, size)) goto error; if(!applyCodeIpsPatch(progId, code, size)) goto error;
@ -1006,13 +947,12 @@ void patchCode(u64 progId, u16 progVer, u8 *code, u32 size, u32 textSize, u32 ro
countryId, countryId,
stateId; stateId;
if(isLumaWithKext && loadTitleLocaleConfig(progId, &mask, &regionId, &languageId, &countryId, &stateId)) if(loadTitleLocaleConfig(progId, &mask, &regionId, &languageId, &countryId, &stateId))
svcKernelSetState(0x10001, ((u32)stateId << 24) | ((u32)countryId << 16) | ((u32)languageId << 8) | ((u32)regionId << 4) | (u32)mask , progId); svcKernelSetState(0x10001, ((u32)stateId << 24) | ((u32)countryId << 16) | ((u32)languageId << 8) | ((u32)regionId << 4) | (u32)mask , progId);
if(!patchLayeredFs(progId, code, size, textSize, roSize, dataSize, roAddress, dataAddress)) goto error; if(!patchLayeredFs(progId, code, size, textSize, roSize, dataSize, roAddress, dataAddress)) goto error;
} }
} }
nextGamePatchDisabled = false;
return; return;
error: error:

View File

@ -12,10 +12,10 @@
#define MULTICONFIG(a) ((multiConfig >> (2 * (a))) & 3) #define MULTICONFIG(a) ((multiConfig >> (2 * (a))) & 3)
#define BOOTCONFIG(a, b) ((bootConfig >> (a)) & (b)) #define BOOTCONFIG(a, b) ((bootConfig >> (a)) & (b))
#define BOOTCFG_NAND BOOTCONFIG(0, 1) #define BOOTCFG_NAND BOOTCONFIG(0, 7)
#define BOOTCFG_EMUINDEX BOOTCONFIG(1, 3) #define BOOTCFG_FIRM BOOTCONFIG(3, 7)
#define BOOTCFG_NOFORCEFLAG BOOTCONFIG(3, 1) #define BOOTCFG_NOFORCEFLAG BOOTCONFIG(6, 1)
#define BOOTCFG_NTRCARDBOOT BOOTCONFIG(4, 1) #define BOOTCFG_NTRCARDBOOT BOOTCONFIG(7, 1)
enum multiOptions enum multiOptions
{ {
@ -31,19 +31,19 @@ enum multiOptions
enum singleOptions enum singleOptions
{ {
AUTOBOOTEMU = 0, AUTOBOOTEMU = 0,
USEEMUFIRM,
LOADEXTFIRMSANDMODULES, LOADEXTFIRMSANDMODULES,
PATCHGAMES, PATCHGAMES,
REDIRECTAPPTHREADS, REDIRECTAPPTHREADS,
PATCHVERSTRING, PATCHVERSTRING,
SHOWGBABOOT, SHOWGBABOOT,
PATCHUNITINFO, PATCHUNITINFO,
ENABLEDSIEXTFILTER,
DISABLEARM11EXCHANDLERS, DISABLEARM11EXCHANDLERS,
ENABLESAFEFIRMROSALINA, ENABLESAFEFIRMROSALINA,
}; };
extern u32 config, multiConfig, bootConfig; extern u32 config, multiConfig, bootConfig;
extern bool isN3DS, isSdMode, nextGamePatchDisabled, isLumaWithKext; extern bool isN3DS, isSdMode;
void patchCode(u64 progId, u16 progVer, u8 *code, u32 size, u32 textSize, u32 roSize, u32 dataSize, u32 roAddress, u32 dataAddress); void patchCode(u64 progId, u16 progVer, u8 *code, u32 size, u32 textSize, u32 roSize, u32 dataSize, u32 roAddress, u32 dataAddress);
bool loadTitleCodeSection(u64 progId, u8 *code, u32 size); bool loadTitleCodeSection(u64 progId, u8 *code, u32 size);

View File

@ -10,7 +10,6 @@ extern u32 romfsRedirPatchSubstituted2, romfsRedirPatchHook2;
extern u32 romfsRedirPatchArchiveName; extern u32 romfsRedirPatchArchiveName;
extern u32 romfsRedirPatchFsMountArchive; extern u32 romfsRedirPatchFsMountArchive;
extern u32 romfsRedirPatchFsUnMountArchive;
extern u32 romfsRedirPatchFsRegisterArchive; extern u32 romfsRedirPatchFsRegisterArchive;
extern u32 romfsRedirPatchArchiveId; extern u32 romfsRedirPatchArchiveId;
extern u32 romfsRedirPatchRomFsMount; extern u32 romfsRedirPatchRomFsMount;

View File

@ -30,23 +30,17 @@ romfsRedirPatch:
cmp r3, #3 cmp r3, #3
bne romfsRedirPatchSubstituted1 bne romfsRedirPatchSubstituted1
stmfd sp!, {r0-r4, lr} stmfd sp!, {r0-r4, lr}
adr r0, romfsRedirPatchArchiveName
.global romfsRedirPatchFsUnMountArchive
romfsRedirPatchFsUnMountArchive:
.word 0xdead0004
sub sp, sp, #4 sub sp, sp, #4
ldr r1, romfsRedirPatchArchiveId ldr r1, romfsRedirPatchArchiveId
mov r0, sp mov r0, sp
.global romfsRedirPatchFsMountArchive ldr r4, romfsRedirPatchFsMountArchive
romfsRedirPatchFsMountArchive: blx r4
.word 0xdead0005
mov r3, #0 mov r3, #0
mov r2, #0 mov r2, #0
ldr r1, [sp] ldr r1, [sp]
adr r0, romfsRedirPatchArchiveName adr r0, romfsRedirPatchArchiveName
.global romfsRedirPatchFsRegisterArchive ldr r4, romfsRedirPatchFsRegisterArchive
romfsRedirPatchFsRegisterArchive: blx r4
.word 0xdead0006
add sp, sp, #4 add sp, sp, #4
ldmfd sp!, {r0-r4, lr} ldmfd sp!, {r0-r4, lr}
b romfsRedirPatchSubstituted1 b romfsRedirPatchSubstituted1
@ -114,16 +108,20 @@ romfsRedirPatch:
.balign 4 .balign 4
.global romfsRedirPatchArchiveName .global romfsRedirPatchArchiveName
.global romfsRedirPatchFsMountArchive
.global romfsRedirPatchFsRegisterArchive
.global romfsRedirPatchArchiveId .global romfsRedirPatchArchiveId
.global romfsRedirPatchRomFsMount .global romfsRedirPatchRomFsMount
.global romfsRedirPatchUpdateRomFsMount .global romfsRedirPatchUpdateRomFsMount
.global romfsRedirPatchCustomPath .global romfsRedirPatchCustomPath
romfsRedirPatchArchiveName : .ascii "lf:\0" romfsRedirPatchArchiveName : .ascii "lf:\0"
romfsRedirPatchFsMountArchive : .word 0xdead0005
romfsRedirPatchFsRegisterArchive : .word 0xdead0006
romfsRedirPatchArchiveId : .word 0xdead0007 romfsRedirPatchArchiveId : .word 0xdead0007
romfsRedirPatchRomFsMount : .ascii "rom:" romfsRedirPatchRomFsMount : .ascii "rom:"
romfsRedirPatchUpdateRomFsMount : .word 0xdead0008 romfsRedirPatchUpdateRomFsMount : .word 0xdead0008
romfsRedirPatchCustomPath : .word 0xdead0009 romfsRedirPatchCustomPath : .word 0xdead0004
_romfsRedirPatchEnd: _romfsRedirPatchEnd:

View File

@ -6,10 +6,10 @@
#define MULTICONFIG(a) ((multiConfig >> (2 * (a))) & 3) #define MULTICONFIG(a) ((multiConfig >> (2 * (a))) & 3)
#define BOOTCONFIG(a, b) ((bootConfig >> (a)) & (b)) #define BOOTCONFIG(a, b) ((bootConfig >> (a)) & (b))
#define BOOTCFG_NAND BOOTCONFIG(0, 1) #define BOOTCFG_NAND BOOTCONFIG(0, 7)
#define BOOTCFG_EMUINDEX BOOTCONFIG(1, 3) #define BOOTCFG_FIRM BOOTCONFIG(3, 7)
#define BOOTCFG_NOFORCEFLAG BOOTCONFIG(3, 1) #define BOOTCFG_NOFORCEFLAG BOOTCONFIG(6, 1)
#define BOOTCFG_NTRCARDBOOT BOOTCONFIG(4, 1) #define BOOTCFG_NTRCARDBOOT BOOTCONFIG(7, 1)
enum multiOptions enum multiOptions
{ {
@ -25,13 +25,13 @@ enum multiOptions
enum singleOptions enum singleOptions
{ {
AUTOBOOTEMU = 0, AUTOBOOTEMU = 0,
USEEMUFIRM,
LOADEXTFIRMSANDMODULES, LOADEXTFIRMSANDMODULES,
PATCHGAMES, PATCHGAMES,
REDIRECTAPPTHREADS, REDIRECTAPPTHREADS,
PATCHVERSTRING, PATCHVERSTRING,
SHOWGBABOOT, SHOWGBABOOT,
PATCHUNITINFO, PATCHUNITINFO,
ENABLEDSIEXTFILTER,
DISABLEARM11EXCHANDLERS, DISABLEARM11EXCHANDLERS,
ENABLESAFEFIRMROSALINA, ENABLESAFEFIRMROSALINA,
}; };

View File

@ -16,9 +16,9 @@
#include "luma.h" #include "luma.h"
static MyThread processMonitorThread, taskRunnerThread; static MyThread processMonitorThread, taskRunnerThread;
static u8 CTR_ALIGN(8) processDataBuffer[0x40 * sizeof(ProcessData)] = {0}; static u8 ALIGN(8) processDataBuffer[0x40 * sizeof(ProcessData)] = {0};
static u8 CTR_ALIGN(8) exheaderInfoBuffer[6 * sizeof(ExHeader_Info)] = {0}; static u8 ALIGN(8) exheaderInfoBuffer[6 * sizeof(ExHeader_Info)] = {0};
static u8 CTR_ALIGN(8) threadStacks[2][THREAD_STACK_SIZE] = {0}; static u8 ALIGN(8) threadStacks[2][THREAD_STACK_SIZE] = {0};
// this is called after main exits // this is called after main exits
void __wrap_exit(int rc) void __wrap_exit(int rc)

View File

@ -311,11 +311,7 @@ Result setAppCpuTimeLimit(s64 limit)
// Prevent apps from enabling preemption on core1 (and kernel will // Prevent apps from enabling preemption on core1 (and kernel will
// redirect apps threads from core 1 to 2). // redirect apps threads from core 1 to 2).
if (IS_N3DS && CONFIG(REDIRECTAPPTHREADS)) if (IS_N3DS && CONFIG(REDIRECTAPPTHREADS))
{ return 0;
s64 disableThreadRedir = 0;
if (R_SUCCEEDED(svcGetSystemInfo(&disableThreadRedir, 0x10000, 0x181)) && !disableThreadRedir)
return 0;
}
ResourceLimitType category = RESLIMIT_CPUTIME; ResourceLimitType category = RESLIMIT_CPUTIME;
return svcSetResourceLimitValues(g_manager.reslimits[0], &category, &limit, 1); return svcSetResourceLimitValues(g_manager.reslimits[0], &category, &limit, 1);

View File

@ -145,7 +145,7 @@ static void TerminateProcessOrTitleAsync(void *argdata)
ProcessData *process; ProcessData *process;
bool notify = false; bool notify = false;
u8 variation = 0; u8 variation;
if (args->timeout >= 0) { if (args->timeout >= 0) {
assertSuccess(svcClearEvent(g_manager.allNotifiedTerminationEvent)); assertSuccess(svcClearEvent(g_manager.allNotifiedTerminationEvent));

View File

@ -44,7 +44,7 @@ typedef struct SessionManager
} SessionManager; } SessionManager;
//Page alignment is mandatory there //Page alignment is mandatory there
extern u32 CTR_ALIGN(0x1000) staticBuffers[NB_STATIC_BUFFERS][0x1000/4]; extern u32 ALIGN(0x1000) staticBuffers[NB_STATIC_BUFFERS][0x1000/4];
extern Handle PXISyncInterrupt, PXITransferMutex; extern Handle PXISyncInterrupt, PXITransferMutex;
extern Handle terminationRequestedEvent; extern Handle terminationRequestedEvent;

View File

@ -38,7 +38,7 @@ const char *serviceNames[10] =
const u32 nbStaticBuffersByService[10] = {0, 2, 2, 2, 2, 1, 4, 4, 4, 0}; const u32 nbStaticBuffersByService[10] = {0, 2, 2, 2, 2, 1, 4, 4, 4, 0};
u32 CTR_ALIGN(0x1000) staticBuffers[NB_STATIC_BUFFERS][0x400] = {{0}}; u32 ALIGN(0x1000) staticBuffers[NB_STATIC_BUFFERS][0x400] = {{0}};
static inline void initPXI(void) static inline void initPXI(void)
{ {
@ -95,9 +95,9 @@ static inline void exitPXI(void)
PXIReset(); PXIReset();
} }
static u8 CTR_ALIGN(8) receiverStack[THREAD_STACK_SIZE]; static u8 ALIGN(8) receiverStack[THREAD_STACK_SIZE];
static u8 CTR_ALIGN(8) senderStack[THREAD_STACK_SIZE]; static u8 ALIGN(8) senderStack[THREAD_STACK_SIZE];
static u8 CTR_ALIGN(8) PXISRV11HandlerStack[THREAD_STACK_SIZE]; static u8 ALIGN(8) PXISRV11HandlerStack[THREAD_STACK_SIZE];
static MyThread receiverThread = {0}, senderThread = {0}, PXISRV11HandlerThread = {0}; static MyThread receiverThread = {0}, senderThread = {0}, PXISRV11HandlerThread = {0};
Result __sync_init(void); Result __sync_init(void);

View File

@ -24,7 +24,7 @@ export HBLDR_DEFAULT_3DSX_TITLE_NAME ?= "hblauncher_loader"
#--------------------------------------------------------------------------------- #---------------------------------------------------------------------------------
TARGET := $(notdir $(CURDIR)) TARGET := $(notdir $(CURDIR))
BUILD := build BUILD := build
SOURCES := source source/gdb source/menus source/plugin source/redshift SOURCES := source source/gdb source/menus source/redshift
DATA := source/gdb/xml data DATA := source/gdb/xml data
INCLUDES := include include/gdb include/menus include/redshift INCLUDES := include include/gdb include/menus include/redshift

View File

@ -18,10 +18,6 @@
#include <3ds/types.h> #include <3ds/types.h>
/// Allows or disables thread redirection patches for the new thread if specified in the affinity field in svcCreateThread
#define AFFINITY_DISABLE_THREAD_REDIRECTION(x) ((x >= 0) ? (x | 0x40) : x)
#define AFFINITY_ALLOW_THREAD_REDIRECTION(x) ((x >= 0) ? (x & ~0x40) : x)
/// Operations for svcControlService /// Operations for svcControlService
typedef enum ServiceOp typedef enum ServiceOp
{ {
@ -73,30 +69,20 @@ void svcInvalidateEntireInstructionCache(void);
///@name Memory management ///@name Memory management
///@{ ///@{
/// Flags for svcMapProcessMemoryEx
typedef enum MapExFlags
{
MAPEXFLAGS_PRIVATE = BIT(0), ///< Maps the memory as PRIVATE (0xBB05) instead of SHARED (0x5806)
} MapExFlags;
/** /**
* @brief Maps a block of process memory. * @brief Maps a block of process memory.
* @param dstProcessHandle Handle of the process to map the memory in (destination) * @param process Handle of the process.
* @param destAddress Start address of the memory block in the destination process * @param destAddress Address of the mapped block in the current process.
* @param srcProcessHandle Handle of the process to map the memory from (source) * @param srcAddress Address of the mapped block in the source process.
* @param srcAddress Start address of the memory block in the source process * @param size Size of the block of the memory to map (truncated to a multiple of 0x1000 bytes).
* @param size Size of the block of the memory to map (truncated to a multiple of 0x1000 bytes)
* @param flags Extended flags for mapping the memory (see MapExFlags)
*/ */
Result svcMapProcessMemoryEx(Handle dstProcessHandle, u32 destAddress, Handle srcProcessHandle, u32 srcAddress, u32 size, MapExFlags flags); Result svcMapProcessMemoryEx(Handle process, u32 destAddr, u32 srcAddr, u32 size);
/** /**
* @brief Unmaps a block of process memory. * @brief Unmaps a block of process memory.
* @param process Handle of the process to unmap the memory from * @param process Handle of the process.
* @param destAddress Address of the block of memory to unmap * @param destAddress Address of the block of memory to unmap, in the current (destination) process.
* @param size Size of the block of memory to unmap (truncated to a multiple of 0x1000 bytes). * @param size Size of the block of memory to unmap (truncated to a multiple of 0x1000 bytes).
* This function should only be used to unmap memory mapped with svcMapProcessMemoryEx
*/ */
Result svcUnmapProcessMemoryEx(Handle process, u32 destAddress, u32 size); Result svcUnmapProcessMemoryEx(Handle process, u32 destAddress, u32 size);
@ -118,20 +104,6 @@ Result svcUnmapProcessMemoryEx(Handle process, u32 destAddress, u32 size);
* @sa svcControlMemory * @sa svcControlMemory
*/ */
Result svcControlMemoryEx(u32* addr_out, u32 addr0, u32 addr1, u32 size, MemOp op, MemPerm perm, bool isLoader); Result svcControlMemoryEx(u32* addr_out, u32 addr0, u32 addr1, u32 size, MemOp op, MemPerm perm, bool isLoader);
/**
* @brief Controls memory mapping, this version removes all checks which were being done
* The only operations supported are MEMOP_FREE, MEMOP_ALLOC and MEMOP_ALLOC_LINEAR
* All memory allocated with this svc, must be freed with this svc as well
* @param[out] addr_out The virtual address resulting from the operation. Usually the same as addr0.
* @param addr0 The virtual address to be used for the operation.
* @param size The requested size for @ref MEMOP_ALLOC and @ref MEMOP_ALLOC_LINEAR.
* @param op Operation flags. See @ref MemOp.
* @param perm A combination of @ref MEMPERM_READ and @ref MEMPERM_WRITE
* Value 0 is used when unmapping memory.
* @sa svcControlMemory
*/
Result svcControlMemoryUnsafe(u32 *out, u32 addr0, u32 size, MemOp op, MemPerm perm);
///@} ///@}
///@name System ///@name System
@ -162,31 +134,4 @@ Result svcCopyHandle(Handle *out, Handle outProcess, Handle in, Handle inProcess
* @param in The input handle. * @param in The input handle.
*/ */
Result svcTranslateHandle(u32 *outKAddr, char *outClassName, Handle in); Result svcTranslateHandle(u32 *outKAddr, char *outClassName, Handle in);
/// Operations for svcControlProcess
typedef enum ProcessOp
{
PROCESSOP_GET_ALL_HANDLES, ///< List all handles of the process, varg3 can be either 0 to fetch all handles, or token of the type to fetch
///< s32 count = svcControlProcess(handle, PROCESSOP_GET_ALL_HANDLES, (u32)&outBuf, 0)
///< Returns how many handles were found
PROCESSOP_SET_MMU_TO_RWX, ///< Set the whole memory of the process with rwx access (in the mmu table only)
///< svcControlProcess(handle, PROCESSOP_SET_MMU_TO_RWX, 0, 0)
PROCESSOP_GET_ON_MEMORY_CHANGE_EVENT, ///< Get the handle of an event which will be signaled each time the memory layout of this process changes
///< svcControlProcess(handle, PROCESSOP_GET_ON_MEMORY_CHANGE_EVENT, &eventHandleOut, 0)
PROCESSOP_SIGNAL_ON_EXIT, ///< Set a flag to be signaled when the process will be exited
///< svcControlProcess(handle, PROCESSOP_SIGNAL_ON_EXIT, 0, 0)
PROCESSOP_GET_PA_FROM_VA, ///< Get the physical address of the VAddr within the process
///< svcControlProcess(handle, PROCESSOP_GET_PA_FROM_VA, (u32)&PAOut, VAddr)
PROCESSOP_SCHEDULE_THREADS, ///< Lock / Unlock the process's threads
///< svcControlProcess(handle, PROCESSOP_SCHEDULE_THREADS, lock, threadPredicate)
///< lock: 0 to unlock threads, any other value to lock threads
///< threadPredicate: can be NULL or a funcptr to a predicate (typedef bool (*ThreadPredicate)(KThread *thread);)
///< The predicate must return true to operate on the thread
} ProcessOp;
Result svcControlProcess(Handle process, ProcessOp op, u32 varg2, u32 varg3);
///@} ///@}

View File

@ -77,7 +77,6 @@
#define COLOR_WHITE RGB565(0x1F, 0x3F, 0x1F) #define COLOR_WHITE RGB565(0x1F, 0x3F, 0x1F)
#define COLOR_RED RGB565(0x1F, 0x00, 0x00) #define COLOR_RED RGB565(0x1F, 0x00, 0x00)
#define COLOR_GREEN RGB565(0x00, 0x1F, 0x00) #define COLOR_GREEN RGB565(0x00, 0x1F, 0x00)
#define COLOR_LIME RGB565(0x00, 0xFF, 0x00)
#define COLOR_BLACK RGB565(0x00, 0x00, 0x00) #define COLOR_BLACK RGB565(0x00, 0x00, 0x00)
#define DRAW_MAX_FORMATTED_STRING_SIZE 512 #define DRAW_MAX_FORMATTED_STRING_SIZE 512
@ -108,4 +107,4 @@ u32 Draw_GetCurrentFramebufferAddress(bool top, bool left);
void Draw_GetCurrentScreenInfo(u32 *width, bool *is3d, bool top); void Draw_GetCurrentScreenInfo(u32 *width, bool *is3d, bool top);
void Draw_CreateBitmapHeader(u8 *dst, u32 width, u32 heigth); void Draw_CreateBitmapHeader(u8 *dst, u32 width, u32 heigth);
void Draw_ConvertFrameBufferLines(u8 *buf, u32 width, u32 startingLine, u32 numLines, u32 scaleFactorY, bool top, bool left); void Draw_ConvertFrameBufferLines(u8 *buf, u32 width, u32 startingLine, u32 numLines, bool top, bool left);

File diff suppressed because it is too large Load Diff

View File

@ -16,9 +16,6 @@
#include "memory.h" #include "memory.h"
#include "ifile.h" #include "ifile.h"
// Uncomment the line below to dump GDB communications to a file
//#define DEBUG_GDB_COMMUNICATIONS
#define MAX_DEBUG 3 #define MAX_DEBUG 3
#define MAX_DEBUG_THREAD 127 #define MAX_DEBUG_THREAD 127
#define MAX_BREAKPOINT 64 #define MAX_BREAKPOINT 64
@ -157,10 +154,6 @@ typedef struct GDBContext
char memoryOsInfoXmlData[0x800]; char memoryOsInfoXmlData[0x800];
char processesOsInfoXmlData[0x1800]; char processesOsInfoXmlData[0x1800];
#ifdef DEBUG_GDB_COMMUNICATIONS
IFile debugFile;
#endif
} GDBContext; } GDBContext;
typedef int (*GDBCommandHandler)(GDBContext *ctx); typedef int (*GDBCommandHandler)(GDBContext *ctx);

View File

@ -12,15 +12,11 @@
#define GDB_REMOTE_COMMAND_HANDLER(name) GDB_HANDLER(RemoteCommand##name) #define GDB_REMOTE_COMMAND_HANDLER(name) GDB_HANDLER(RemoteCommand##name)
#define GDB_DECLARE_REMOTE_COMMAND_HANDLER(name) GDB_DECLARE_HANDLER(RemoteCommand##name) #define GDB_DECLARE_REMOTE_COMMAND_HANDLER(name) GDB_DECLARE_HANDLER(RemoteCommand##name)
GDB_DECLARE_REMOTE_COMMAND_HANDLER(ConvertVAToPA);
GDB_DECLARE_REMOTE_COMMAND_HANDLER(SyncRequestInfo); GDB_DECLARE_REMOTE_COMMAND_HANDLER(SyncRequestInfo);
GDB_DECLARE_REMOTE_COMMAND_HANDLER(TranslateHandle); GDB_DECLARE_REMOTE_COMMAND_HANDLER(TranslateHandle);
GDB_DECLARE_REMOTE_COMMAND_HANDLER(ListAllHandles);
GDB_DECLARE_REMOTE_COMMAND_HANDLER(GetMmuConfig); GDB_DECLARE_REMOTE_COMMAND_HANDLER(GetMmuConfig);
GDB_DECLARE_REMOTE_COMMAND_HANDLER(GetMemRegions); GDB_DECLARE_REMOTE_COMMAND_HANDLER(GetMemRegions);
GDB_DECLARE_REMOTE_COMMAND_HANDLER(FlushCaches); GDB_DECLARE_REMOTE_COMMAND_HANDLER(FlushCaches);
GDB_DECLARE_REMOTE_COMMAND_HANDLER(ToggleExternalMemoryAccess); GDB_DECLARE_REMOTE_COMMAND_HANDLER(ToggleExternalMemoryAccess);
GDB_DECLARE_REMOTE_COMMAND_HANDLER(CatchSvc);
GDB_DECLARE_REMOTE_COMMAND_HANDLER(GetThreadPriority);
GDB_DECLARE_QUERY_HANDLER(Rcmd); GDB_DECLARE_QUERY_HANDLER(Rcmd);

View File

@ -44,4 +44,3 @@ Result IFile_GetSize(IFile *file, u64 *size);
Result IFile_SetSize(IFile *file, u64 size); Result IFile_SetSize(IFile *file, u64 size);
Result IFile_Read(IFile *file, u64 *total, void *buffer, u32 len); Result IFile_Read(IFile *file, u64 *total, void *buffer, u32 len);
Result IFile_Write(IFile *file, u64 *total, const void *buffer, u32 len, u32 flags); Result IFile_Write(IFile *file, u64 *total, const void *buffer, u32 len, u32 flags);
Result IFile_Flush(IFile *file);

View File

@ -38,4 +38,3 @@ MyThread *inputRedirectionCreateThread(void);
void inputRedirectionThreadMain(void); void inputRedirectionThreadMain(void);
Result InputRedirection_Disable(s64 timeout); Result InputRedirection_Disable(s64 timeout);
Result InputRedirection_DoOrUndoPatches(void); Result InputRedirection_DoOrUndoPatches(void);

View File

@ -33,13 +33,13 @@
enum singleOptions enum singleOptions
{ {
AUTOBOOTEMU = 0, AUTOBOOTEMU = 0,
USEEMUFIRM,
LOADEXTFIRMSANDMODULES, LOADEXTFIRMSANDMODULES,
PATCHGAMES, PATCHGAMES,
REDIRECTAPPTHREADS, REDIRECTAPPTHREADS,
PATCHVERSTRING, PATCHVERSTRING,
SHOWGBABOOT, SHOWGBABOOT,
PATCHUNITINFO, PATCHUNITINFO,
ENABLEDSIEXTFILTER,
DISABLEARM11EXCHANDLERS, DISABLEARM11EXCHANDLERS,
ENABLESAFEFIRMROSALINA, ENABLESAFEFIRMROSALINA,
}; };
@ -57,4 +57,3 @@ enum multiOptions
void LumaConfig_ConvertComboToString(char *out, u32 combo); void LumaConfig_ConvertComboToString(char *out, u32 combo);
Result LumaConfig_SaveSettings(void); Result LumaConfig_SaveSettings(void);
void LumaConfig_RequestSaveSettings(void);

View File

@ -62,18 +62,12 @@ typedef struct MenuItem {
typedef struct Menu { typedef struct Menu {
const char *title; const char *title;
MenuItem items[25]; MenuItem items[16];
} Menu; } Menu;
extern u32 menuCombo; extern u32 menuCombo;
extern bool isHidInitialized; extern bool isHidInitialized;
extern bool isQtmInitialized;
extern u32 mcuFwVersion; extern u32 mcuFwVersion;
extern u8 mcuInfoTable[10];
extern bool mcuInfoTableRead;
extern const char *topScreenType;
extern const char *bottomScreenType;
extern bool areScreenTypesInitialized;
// From main.c // From main.c
extern bool isN3DS; extern bool isN3DS;
@ -92,10 +86,7 @@ bool menuCheckN3ds(void);
u32 menuCountItems(const Menu *menu); u32 menuCountItems(const Menu *menu);
MyThread *menuCreateThread(void); MyThread *menuCreateThread(void);
void menuEnter(void); void menuEnter(void);
void menuLeave(void); void menuLeave(void);
void menuThreadMain(void); void menuThreadMain(void);
void menuShow(Menu *root); void menuShow(Menu *root);
void DispMessage(const char *title, const char *message);
u32 DispErrMessage(const char *title, const char *message, const Result error);
void DisplayPluginMenu(u32 *cmdbuf);

View File

@ -33,17 +33,13 @@
extern Menu rosalinaMenu; extern Menu rosalinaMenu;
void RosalinaMenu_TakeScreenshot(void); void RosalinaMenu_TakeScreenshot(void);
void RosalinaMenu_ChangeScreenBrightness(void);
void RosalinaMenu_ShowCredits(void); void RosalinaMenu_ShowCredits(void);
void RosalinaMenu_ProcessList(void); void RosalinaMenu_ProcessList(void);
void RosalinaMenu_SaveSettings(void); void RosalinaMenu_SaveSettings(void);
void RosalinaMenu_ReturnToHomeMenu(void); void RosalinaMenu_PowerOff(void);
void RosalinaMenu_Reboot(void);
void RosalinaMenu_Cheats(void); void RosalinaMenu_Cheats(void);
void RosalinaMenu_PowerOffOrReboot(void);
void RosalinaMenu_ShowSystemInfo();
bool rosalinaMenuShouldShowDebugInfo(void); bool rosalinaMenuShouldShowDebugInfo(void);
void RosalinaMenu_ShowDebugInfo(void); void RosalinaMenu_ShowDebugInfo(void);
void menuTakeSelfScreenshot(void);

View File

@ -31,12 +31,6 @@
extern Menu N3DSMenu; extern Menu N3DSMenu;
bool N3DSMenu_CheckNotN2dsXl(void);
void N3DSMenu_UpdateStatus(void); void N3DSMenu_UpdateStatus(void);
void N3DSMenu_ChangeClockRate(void); void N3DSMenu_ChangeClockRate(void);
void N3DSMenu_EnableDisableL2Cache(void); void N3DSMenu_EnableDisableL2Cache(void);
void N3DSMenu_ToggleSs3d(void);
void N3DSMenu_TestBarrierPositions(void);
void N3DSMenu_Ss3dCalibration(void);

View File

@ -33,7 +33,6 @@ extern Menu screenFiltersMenu;
typedef struct ScreenFilter { typedef struct ScreenFilter {
u16 cct; u16 cct;
bool invert; bool invert;
u8 colorCurveCorrection;
float gamma; float gamma;
float contrast; float contrast;
float brightness; float brightness;
@ -57,9 +56,4 @@ void ScreenFiltersMenu_SetWarmIncandescent(void); // 2300K
void ScreenFiltersMenu_SetCandle(void); // 1900K void ScreenFiltersMenu_SetCandle(void); // 1900K
void ScreenFiltersMenu_SetEmber(void); // 1200K void ScreenFiltersMenu_SetEmber(void); // 1200K
void ScreenFiltersMenu_SetTopScreenSrgbColorCurve(void);
void ScreenFiltersMenu_RestoreTopScreenColorCurve(void);
void ScreenFiltersMenu_SetBottomScreenSrgbColorCurve(void);
void ScreenFiltersMenu_RestoreBottomScreenColorCurve(void);
void ScreenFiltersMenu_AdvancedConfiguration(void); void ScreenFiltersMenu_AdvancedConfiguration(void);

View File

@ -1,527 +0,0 @@
// SPDX-License-Identifier: MIT
// (c) 2024 LumaTeam
#pragma once
#include <3ds/types.h>
// Originally from OAF and taken with permission,
// though it is unclear whether LUT data can be licensed
// like code is.
static const u8 ctrToSrgbTableTop[256][3] = {
{ 0x00, 0x00, 0x00, }, // i = 0x00
{ 0x01, 0x01, 0x01, }, // i = 0x01
{ 0x02, 0x01, 0x02, }, // i = 0x02
{ 0x03, 0x02, 0x03, }, // i = 0x03
{ 0x04, 0x03, 0x04, }, // i = 0x04
{ 0x05, 0x04, 0x05, }, // i = 0x05
{ 0x06, 0x04, 0x06, }, // i = 0x06
{ 0x07, 0x05, 0x06, }, // i = 0x07
{ 0x08, 0x06, 0x07, }, // i = 0x08
{ 0x08, 0x06, 0x08, }, // i = 0x09
{ 0x09, 0x07, 0x09, }, // i = 0x0A
{ 0x0A, 0x08, 0x0A, }, // i = 0x0B
{ 0x0B, 0x09, 0x0B, }, // i = 0x0C
{ 0x0C, 0x09, 0x0B, }, // i = 0x0D
{ 0x0D, 0x0A, 0x0C, }, // i = 0x0E
{ 0x0E, 0x0B, 0x0D, }, // i = 0x0F
{ 0x0F, 0x0B, 0x0E, }, // i = 0x10
{ 0x10, 0x0C, 0x0F, }, // i = 0x11
{ 0x10, 0x0D, 0x0F, }, // i = 0x12
{ 0x11, 0x0E, 0x10, }, // i = 0x13
{ 0x12, 0x0E, 0x11, }, // i = 0x14
{ 0x13, 0x0F, 0x12, }, // i = 0x15
{ 0x14, 0x10, 0x12, }, // i = 0x16
{ 0x15, 0x11, 0x13, }, // i = 0x17
{ 0x16, 0x11, 0x14, }, // i = 0x18
{ 0x16, 0x12, 0x15, }, // i = 0x19
{ 0x17, 0x13, 0x15, }, // i = 0x1A
{ 0x18, 0x14, 0x16, }, // i = 0x1B
{ 0x19, 0x14, 0x17, }, // i = 0x1C
{ 0x1A, 0x15, 0x18, }, // i = 0x1D
{ 0x1B, 0x16, 0x18, }, // i = 0x1E
{ 0x1C, 0x17, 0x19, }, // i = 0x1F
{ 0x1C, 0x17, 0x1A, }, // i = 0x20
{ 0x1D, 0x18, 0x1B, }, // i = 0x21
{ 0x1E, 0x19, 0x1B, }, // i = 0x22
{ 0x1F, 0x1A, 0x1C, }, // i = 0x23
{ 0x20, 0x1B, 0x1D, }, // i = 0x24
{ 0x21, 0x1B, 0x1E, }, // i = 0x25
{ 0x22, 0x1C, 0x1E, }, // i = 0x26
{ 0x23, 0x1D, 0x1F, }, // i = 0x27
{ 0x23, 0x1E, 0x20, }, // i = 0x28
{ 0x24, 0x1F, 0x21, }, // i = 0x29
{ 0x25, 0x1F, 0x21, }, // i = 0x2A
{ 0x26, 0x20, 0x22, }, // i = 0x2B
{ 0x27, 0x21, 0x23, }, // i = 0x2C
{ 0x28, 0x22, 0x24, }, // i = 0x2D
{ 0x29, 0x23, 0x24, }, // i = 0x2E
{ 0x2A, 0x24, 0x25, }, // i = 0x2F
{ 0x2B, 0x24, 0x26, }, // i = 0x30
{ 0x2C, 0x25, 0x27, }, // i = 0x31
{ 0x2D, 0x26, 0x28, }, // i = 0x32
{ 0x2E, 0x27, 0x28, }, // i = 0x33
{ 0x2E, 0x28, 0x29, }, // i = 0x34
{ 0x2F, 0x29, 0x2A, }, // i = 0x35
{ 0x30, 0x2A, 0x2B, }, // i = 0x36
{ 0x31, 0x2B, 0x2B, }, // i = 0x37
{ 0x32, 0x2B, 0x2C, }, // i = 0x38
{ 0x33, 0x2C, 0x2D, }, // i = 0x39
{ 0x34, 0x2D, 0x2E, }, // i = 0x3A
{ 0x35, 0x2E, 0x2F, }, // i = 0x3B
{ 0x36, 0x2F, 0x30, }, // i = 0x3C
{ 0x37, 0x30, 0x30, }, // i = 0x3D
{ 0x38, 0x31, 0x31, }, // i = 0x3E
{ 0x39, 0x32, 0x32, }, // i = 0x3F
{ 0x3A, 0x33, 0x33, }, // i = 0x40
{ 0x3B, 0x34, 0x34, }, // i = 0x41
{ 0x3C, 0x35, 0x34, }, // i = 0x42
{ 0x3D, 0x35, 0x35, }, // i = 0x43
{ 0x3E, 0x36, 0x36, }, // i = 0x44
{ 0x3F, 0x37, 0x37, }, // i = 0x45
{ 0x40, 0x38, 0x38, }, // i = 0x46
{ 0x41, 0x39, 0x39, }, // i = 0x47
{ 0x42, 0x3A, 0x3A, }, // i = 0x48
{ 0x43, 0x3B, 0x3A, }, // i = 0x49
{ 0x44, 0x3C, 0x3B, }, // i = 0x4A
{ 0x45, 0x3D, 0x3C, }, // i = 0x4B
{ 0x46, 0x3E, 0x3D, }, // i = 0x4C
{ 0x47, 0x3F, 0x3E, }, // i = 0x4D
{ 0x48, 0x40, 0x3F, }, // i = 0x4E
{ 0x49, 0x41, 0x40, }, // i = 0x4F
{ 0x4A, 0x42, 0x41, }, // i = 0x50
{ 0x4B, 0x43, 0x41, }, // i = 0x51
{ 0x4C, 0x44, 0x42, }, // i = 0x52
{ 0x4D, 0x45, 0x43, }, // i = 0x53
{ 0x4E, 0x46, 0x44, }, // i = 0x54
{ 0x4F, 0x47, 0x45, }, // i = 0x55
{ 0x50, 0x48, 0x46, }, // i = 0x56
{ 0x51, 0x49, 0x47, }, // i = 0x57
{ 0x52, 0x4A, 0x48, }, // i = 0x58
{ 0x53, 0x4B, 0x49, }, // i = 0x59
{ 0x54, 0x4C, 0x4A, }, // i = 0x5A
{ 0x55, 0x4D, 0x4B, }, // i = 0x5B
{ 0x56, 0x4E, 0x4B, }, // i = 0x5C
{ 0x57, 0x4F, 0x4C, }, // i = 0x5D
{ 0x58, 0x50, 0x4D, }, // i = 0x5E
{ 0x59, 0x51, 0x4E, }, // i = 0x5F
{ 0x5B, 0x52, 0x4F, }, // i = 0x60
{ 0x5C, 0x53, 0x50, }, // i = 0x61
{ 0x5D, 0x54, 0x51, }, // i = 0x62
{ 0x5E, 0x55, 0x52, }, // i = 0x63
{ 0x5F, 0x56, 0x53, }, // i = 0x64
{ 0x60, 0x57, 0x54, }, // i = 0x65
{ 0x61, 0x58, 0x55, }, // i = 0x66
{ 0x62, 0x59, 0x56, }, // i = 0x67
{ 0x63, 0x5A, 0x57, }, // i = 0x68
{ 0x64, 0x5B, 0x57, }, // i = 0x69
{ 0x65, 0x5C, 0x58, }, // i = 0x6A
{ 0x66, 0x5D, 0x59, }, // i = 0x6B
{ 0x67, 0x5E, 0x5A, }, // i = 0x6C
{ 0x68, 0x5F, 0x5B, }, // i = 0x6D
{ 0x69, 0x60, 0x5C, }, // i = 0x6E
{ 0x6A, 0x61, 0x5D, }, // i = 0x6F
{ 0x6B, 0x62, 0x5E, }, // i = 0x70
{ 0x6C, 0x63, 0x5F, }, // i = 0x71
{ 0x6D, 0x64, 0x60, }, // i = 0x72
{ 0x6E, 0x65, 0x61, }, // i = 0x73
{ 0x6F, 0x66, 0x62, }, // i = 0x74
{ 0x70, 0x67, 0x63, }, // i = 0x75
{ 0x71, 0x68, 0x64, }, // i = 0x76
{ 0x73, 0x69, 0x65, }, // i = 0x77
{ 0x74, 0x6A, 0x66, }, // i = 0x78
{ 0x75, 0x6B, 0x67, }, // i = 0x79
{ 0x76, 0x6C, 0x68, }, // i = 0x7A
{ 0x77, 0x6D, 0x68, }, // i = 0x7B
{ 0x78, 0x6E, 0x69, }, // i = 0x7C
{ 0x79, 0x6F, 0x6A, }, // i = 0x7D
{ 0x7A, 0x70, 0x6B, }, // i = 0x7E
{ 0x7B, 0x71, 0x6C, }, // i = 0x7F
{ 0x7C, 0x72, 0x6D, }, // i = 0x80
{ 0x7D, 0x73, 0x6E, }, // i = 0x81
{ 0x7E, 0x74, 0x6F, }, // i = 0x82
{ 0x7F, 0x75, 0x70, }, // i = 0x83
{ 0x80, 0x76, 0x71, }, // i = 0x84
{ 0x81, 0x77, 0x72, }, // i = 0x85
{ 0x82, 0x78, 0x73, }, // i = 0x86
{ 0x83, 0x79, 0x74, }, // i = 0x87
{ 0x84, 0x7A, 0x75, }, // i = 0x88
{ 0x85, 0x7B, 0x76, }, // i = 0x89
{ 0x86, 0x7C, 0x77, }, // i = 0x8A
{ 0x87, 0x7D, 0x78, }, // i = 0x8B
{ 0x88, 0x7E, 0x79, }, // i = 0x8C
{ 0x89, 0x7F, 0x7A, }, // i = 0x8D
{ 0x8A, 0x81, 0x7B, }, // i = 0x8E
{ 0x8B, 0x82, 0x7C, }, // i = 0x8F
{ 0x8C, 0x83, 0x7C, }, // i = 0x90
{ 0x8D, 0x84, 0x7D, }, // i = 0x91
{ 0x8E, 0x85, 0x7E, }, // i = 0x92
{ 0x8F, 0x86, 0x7F, }, // i = 0x93
{ 0x90, 0x87, 0x80, }, // i = 0x94
{ 0x91, 0x88, 0x81, }, // i = 0x95
{ 0x92, 0x89, 0x82, }, // i = 0x96
{ 0x93, 0x8A, 0x83, }, // i = 0x97
{ 0x94, 0x8B, 0x84, }, // i = 0x98
{ 0x95, 0x8C, 0x85, }, // i = 0x99
{ 0x96, 0x8D, 0x86, }, // i = 0x9A
{ 0x97, 0x8E, 0x87, }, // i = 0x9B
{ 0x98, 0x8F, 0x88, }, // i = 0x9C
{ 0x99, 0x90, 0x89, }, // i = 0x9D
{ 0x9A, 0x91, 0x8A, }, // i = 0x9E
{ 0x9B, 0x92, 0x8B, }, // i = 0x9F
{ 0x9C, 0x93, 0x8C, }, // i = 0xA0
{ 0x9D, 0x94, 0x8D, }, // i = 0xA1
{ 0x9E, 0x95, 0x8E, }, // i = 0xA2
{ 0x9F, 0x96, 0x8F, }, // i = 0xA3
{ 0xA0, 0x97, 0x90, }, // i = 0xA4
{ 0xA1, 0x98, 0x91, }, // i = 0xA5
{ 0xA2, 0x99, 0x92, }, // i = 0xA6
{ 0xA4, 0x9A, 0x93, }, // i = 0xA7
{ 0xA5, 0x9B, 0x94, }, // i = 0xA8
{ 0xA6, 0x9C, 0x95, }, // i = 0xA9
{ 0xA7, 0x9D, 0x96, }, // i = 0xAA
{ 0xA8, 0x9F, 0x97, }, // i = 0xAB
{ 0xA9, 0xA0, 0x98, }, // i = 0xAC
{ 0xAA, 0xA1, 0x99, }, // i = 0xAD
{ 0xAB, 0xA2, 0x9A, }, // i = 0xAE
{ 0xAC, 0xA3, 0x9B, }, // i = 0xAF
{ 0xAD, 0xA4, 0x9C, }, // i = 0xB0
{ 0xAE, 0xA5, 0x9D, }, // i = 0xB1
{ 0xAF, 0xA6, 0x9E, }, // i = 0xB2
{ 0xB0, 0xA7, 0x9F, }, // i = 0xB3
{ 0xB1, 0xA8, 0xA0, }, // i = 0xB4
{ 0xB2, 0xA9, 0xA1, }, // i = 0xB5
{ 0xB3, 0xAA, 0xA2, }, // i = 0xB6
{ 0xB4, 0xAB, 0xA3, }, // i = 0xB7
{ 0xB5, 0xAC, 0xA4, }, // i = 0xB8
{ 0xB6, 0xAD, 0xA5, }, // i = 0xB9
{ 0xB7, 0xAF, 0xA6, }, // i = 0xBA
{ 0xB8, 0xB0, 0xA7, }, // i = 0xBB
{ 0xB9, 0xB1, 0xA9, }, // i = 0xBC
{ 0xBA, 0xB2, 0xAA, }, // i = 0xBD
{ 0xBB, 0xB3, 0xAB, }, // i = 0xBE
{ 0xBC, 0xB4, 0xAC, }, // i = 0xBF
{ 0xBD, 0xB5, 0xAD, }, // i = 0xC0
{ 0xBE, 0xB6, 0xAE, }, // i = 0xC1
{ 0xBF, 0xB7, 0xAF, }, // i = 0xC2
{ 0xC0, 0xB9, 0xB0, }, // i = 0xC3
{ 0xC1, 0xBA, 0xB1, }, // i = 0xC4
{ 0xC3, 0xBB, 0xB2, }, // i = 0xC5
{ 0xC4, 0xBC, 0xB4, }, // i = 0xC6
{ 0xC5, 0xBD, 0xB5, }, // i = 0xC7
{ 0xC6, 0xBE, 0xB6, }, // i = 0xC8
{ 0xC7, 0xBF, 0xB7, }, // i = 0xC9
{ 0xC8, 0xC0, 0xB8, }, // i = 0xCA
{ 0xC9, 0xC2, 0xB9, }, // i = 0xCB
{ 0xCA, 0xC3, 0xBB, }, // i = 0xCC
{ 0xCB, 0xC4, 0xBC, }, // i = 0xCD
{ 0xCC, 0xC5, 0xBD, }, // i = 0xCE
{ 0xCD, 0xC6, 0xBE, }, // i = 0xCF
{ 0xCE, 0xC7, 0xBF, }, // i = 0xD0
{ 0xCF, 0xC8, 0xC1, }, // i = 0xD1
{ 0xD0, 0xCA, 0xC2, }, // i = 0xD2
{ 0xD2, 0xCB, 0xC3, }, // i = 0xD3
{ 0xD3, 0xCC, 0xC4, }, // i = 0xD4
{ 0xD4, 0xCD, 0xC5, }, // i = 0xD5
{ 0xD5, 0xCE, 0xC7, }, // i = 0xD6
{ 0xD6, 0xCF, 0xC8, }, // i = 0xD7
{ 0xD7, 0xD1, 0xC9, }, // i = 0xD8
{ 0xD8, 0xD2, 0xCB, }, // i = 0xD9
{ 0xD9, 0xD3, 0xCC, }, // i = 0xDA
{ 0xDA, 0xD4, 0xCD, }, // i = 0xDB
{ 0xDB, 0xD5, 0xCE, }, // i = 0xDC
{ 0xDC, 0xD7, 0xD0, }, // i = 0xDD
{ 0xDE, 0xD8, 0xD1, }, // i = 0xDE
{ 0xDF, 0xD9, 0xD2, }, // i = 0xDF
{ 0xE0, 0xDA, 0xD4, }, // i = 0xE0
{ 0xE1, 0xDB, 0xD5, }, // i = 0xE1
{ 0xE2, 0xDD, 0xD6, }, // i = 0xE2
{ 0xE3, 0xDE, 0xD8, }, // i = 0xE3
{ 0xE4, 0xDF, 0xD9, }, // i = 0xE4
{ 0xE5, 0xE0, 0xDA, }, // i = 0xE5
{ 0xE6, 0xE1, 0xDC, }, // i = 0xE6
{ 0xE7, 0xE3, 0xDD, }, // i = 0xE7
{ 0xE8, 0xE4, 0xDE, }, // i = 0xE8
{ 0xEA, 0xE5, 0xE0, }, // i = 0xE9
{ 0xEB, 0xE6, 0xE1, }, // i = 0xEA
{ 0xEC, 0xE7, 0xE2, }, // i = 0xEB
{ 0xED, 0xE9, 0xE4, }, // i = 0xEC
{ 0xEE, 0xEA, 0xE5, }, // i = 0xED
{ 0xEF, 0xEB, 0xE7, }, // i = 0xEE
{ 0xF0, 0xEC, 0xE8, }, // i = 0xEF
{ 0xF1, 0xED, 0xE9, }, // i = 0xF0
{ 0xF2, 0xEF, 0xEB, }, // i = 0xF1
{ 0xF3, 0xF0, 0xEC, }, // i = 0xF2
{ 0xF4, 0xF1, 0xEE, }, // i = 0xF3
{ 0xF5, 0xF2, 0xEF, }, // i = 0xF4
{ 0xF6, 0xF3, 0xF1, }, // i = 0xF5
{ 0xF7, 0xF5, 0xF2, }, // i = 0xF6
{ 0xF8, 0xF6, 0xF3, }, // i = 0xF7
{ 0xF9, 0xF7, 0xF5, }, // i = 0xF8
{ 0xFA, 0xF8, 0xF6, }, // i = 0xF9
{ 0xFB, 0xF9, 0xF8, }, // i = 0xFA
{ 0xFC, 0xFA, 0xF9, }, // i = 0xFB
{ 0xFD, 0xFC, 0xFA, }, // i = 0xFC
{ 0xFD, 0xFD, 0xFC, }, // i = 0xFD
{ 0xFE, 0xFE, 0xFD, }, // i = 0xFE
{ 0xFF, 0xFF, 0xFF, }, // i = 0xFF
};
static const u8 ctrToSrgbTableBottom[256][3] = {
{ 0x00, 0x00, 0x00, }, // i = 0x00
{ 0x01, 0x00, 0x00, }, // i = 0x01
{ 0x01, 0x00, 0x01, }, // i = 0x02
{ 0x02, 0x01, 0x01, }, // i = 0x03
{ 0x02, 0x01, 0x02, }, // i = 0x04
{ 0x03, 0x01, 0x03, }, // i = 0x05
{ 0x04, 0x02, 0x03, }, // i = 0x06
{ 0x04, 0x02, 0x04, }, // i = 0x07
{ 0x05, 0x02, 0x04, }, // i = 0x08
{ 0x05, 0x03, 0x05, }, // i = 0x09
{ 0x06, 0x03, 0x05, }, // i = 0x0A
{ 0x07, 0x04, 0x06, }, // i = 0x0B
{ 0x07, 0x04, 0x07, }, // i = 0x0C
{ 0x08, 0x05, 0x07, }, // i = 0x0D
{ 0x09, 0x05, 0x08, }, // i = 0x0E
{ 0x0A, 0x06, 0x08, }, // i = 0x0F
{ 0x0A, 0x06, 0x09, }, // i = 0x10
{ 0x0B, 0x07, 0x0A, }, // i = 0x11
{ 0x0C, 0x08, 0x0A, }, // i = 0x12
{ 0x0C, 0x08, 0x0B, }, // i = 0x13
{ 0x0D, 0x09, 0x0C, }, // i = 0x14
{ 0x0E, 0x09, 0x0C, }, // i = 0x15
{ 0x0F, 0x0A, 0x0D, }, // i = 0x16
{ 0x10, 0x0B, 0x0E, }, // i = 0x17
{ 0x10, 0x0B, 0x0F, }, // i = 0x18
{ 0x11, 0x0C, 0x0F, }, // i = 0x19
{ 0x12, 0x0D, 0x10, }, // i = 0x1A
{ 0x13, 0x0D, 0x11, }, // i = 0x1B
{ 0x14, 0x0E, 0x12, }, // i = 0x1C
{ 0x14, 0x0F, 0x12, }, // i = 0x1D
{ 0x15, 0x10, 0x13, }, // i = 0x1E
{ 0x16, 0x10, 0x14, }, // i = 0x1F
{ 0x17, 0x11, 0x15, }, // i = 0x20
{ 0x18, 0x12, 0x15, }, // i = 0x21
{ 0x19, 0x13, 0x16, }, // i = 0x22
{ 0x19, 0x13, 0x17, }, // i = 0x23
{ 0x1A, 0x14, 0x18, }, // i = 0x24
{ 0x1B, 0x15, 0x18, }, // i = 0x25
{ 0x1C, 0x16, 0x19, }, // i = 0x26
{ 0x1D, 0x17, 0x1A, }, // i = 0x27
{ 0x1E, 0x18, 0x1B, }, // i = 0x28
{ 0x1F, 0x18, 0x1C, }, // i = 0x29
{ 0x20, 0x19, 0x1C, }, // i = 0x2A
{ 0x21, 0x1A, 0x1D, }, // i = 0x2B
{ 0x22, 0x1B, 0x1E, }, // i = 0x2C
{ 0x22, 0x1C, 0x1F, }, // i = 0x2D
{ 0x23, 0x1D, 0x20, }, // i = 0x2E
{ 0x24, 0x1E, 0x21, }, // i = 0x2F
{ 0x25, 0x1E, 0x21, }, // i = 0x30
{ 0x26, 0x1F, 0x22, }, // i = 0x31
{ 0x27, 0x20, 0x23, }, // i = 0x32
{ 0x28, 0x21, 0x24, }, // i = 0x33
{ 0x29, 0x22, 0x25, }, // i = 0x34
{ 0x2A, 0x23, 0x26, }, // i = 0x35
{ 0x2B, 0x24, 0x27, }, // i = 0x36
{ 0x2C, 0x25, 0x27, }, // i = 0x37
{ 0x2D, 0x26, 0x28, }, // i = 0x38
{ 0x2E, 0x27, 0x29, }, // i = 0x39
{ 0x2F, 0x28, 0x2A, }, // i = 0x3A
{ 0x30, 0x29, 0x2B, }, // i = 0x3B
{ 0x31, 0x2A, 0x2C, }, // i = 0x3C
{ 0x32, 0x2A, 0x2D, }, // i = 0x3D
{ 0x33, 0x2B, 0x2E, }, // i = 0x3E
{ 0x34, 0x2C, 0x2E, }, // i = 0x3F
{ 0x35, 0x2D, 0x2F, }, // i = 0x40
{ 0x36, 0x2E, 0x30, }, // i = 0x41
{ 0x37, 0x2F, 0x31, }, // i = 0x42
{ 0x38, 0x30, 0x32, }, // i = 0x43
{ 0x39, 0x31, 0x33, }, // i = 0x44
{ 0x3A, 0x32, 0x34, }, // i = 0x45
{ 0x3B, 0x33, 0x35, }, // i = 0x46
{ 0x3C, 0x34, 0x36, }, // i = 0x47
{ 0x3D, 0x35, 0x36, }, // i = 0x48
{ 0x3E, 0x36, 0x37, }, // i = 0x49
{ 0x3F, 0x37, 0x38, }, // i = 0x4A
{ 0x40, 0x38, 0x39, }, // i = 0x4B
{ 0x41, 0x39, 0x3A, }, // i = 0x4C
{ 0x42, 0x3A, 0x3B, }, // i = 0x4D
{ 0x43, 0x3B, 0x3C, }, // i = 0x4E
{ 0x44, 0x3C, 0x3D, }, // i = 0x4F
{ 0x45, 0x3D, 0x3E, }, // i = 0x50
{ 0x46, 0x3E, 0x3F, }, // i = 0x51
{ 0x47, 0x3F, 0x40, }, // i = 0x52
{ 0x49, 0x40, 0x41, }, // i = 0x53
{ 0x4A, 0x41, 0x42, }, // i = 0x54
{ 0x4B, 0x42, 0x42, }, // i = 0x55
{ 0x4C, 0x43, 0x43, }, // i = 0x56
{ 0x4D, 0x44, 0x44, }, // i = 0x57
{ 0x4E, 0x45, 0x45, }, // i = 0x58
{ 0x4F, 0x46, 0x46, }, // i = 0x59
{ 0x50, 0x47, 0x47, }, // i = 0x5A
{ 0x51, 0x48, 0x48, }, // i = 0x5B
{ 0x52, 0x49, 0x49, }, // i = 0x5C
{ 0x53, 0x4A, 0x4A, }, // i = 0x5D
{ 0x54, 0x4B, 0x4B, }, // i = 0x5E
{ 0x55, 0x4C, 0x4C, }, // i = 0x5F
{ 0x56, 0x4D, 0x4D, }, // i = 0x60
{ 0x57, 0x4E, 0x4E, }, // i = 0x61
{ 0x58, 0x4F, 0x4F, }, // i = 0x62
{ 0x5A, 0x50, 0x50, }, // i = 0x63
{ 0x5B, 0x51, 0x51, }, // i = 0x64
{ 0x5C, 0x52, 0x52, }, // i = 0x65
{ 0x5D, 0x53, 0x53, }, // i = 0x66
{ 0x5E, 0x54, 0x54, }, // i = 0x67
{ 0x5F, 0x55, 0x54, }, // i = 0x68
{ 0x60, 0x56, 0x55, }, // i = 0x69
{ 0x61, 0x57, 0x56, }, // i = 0x6A
{ 0x62, 0x58, 0x57, }, // i = 0x6B
{ 0x63, 0x59, 0x58, }, // i = 0x6C
{ 0x64, 0x5B, 0x59, }, // i = 0x6D
{ 0x65, 0x5C, 0x5A, }, // i = 0x6E
{ 0x66, 0x5D, 0x5B, }, // i = 0x6F
{ 0x68, 0x5E, 0x5C, }, // i = 0x70
{ 0x69, 0x5F, 0x5D, }, // i = 0x71
{ 0x6A, 0x60, 0x5E, }, // i = 0x72
{ 0x6B, 0x61, 0x5F, }, // i = 0x73
{ 0x6C, 0x62, 0x60, }, // i = 0x74
{ 0x6D, 0x63, 0x61, }, // i = 0x75
{ 0x6E, 0x64, 0x62, }, // i = 0x76
{ 0x6F, 0x65, 0x63, }, // i = 0x77
{ 0x70, 0x66, 0x64, }, // i = 0x78
{ 0x71, 0x67, 0x65, }, // i = 0x79
{ 0x72, 0x68, 0x66, }, // i = 0x7A
{ 0x73, 0x69, 0x67, }, // i = 0x7B
{ 0x74, 0x6A, 0x68, }, // i = 0x7C
{ 0x76, 0x6B, 0x69, }, // i = 0x7D
{ 0x77, 0x6C, 0x6A, }, // i = 0x7E
{ 0x78, 0x6D, 0x6B, }, // i = 0x7F
{ 0x79, 0x6E, 0x6C, }, // i = 0x80
{ 0x7A, 0x70, 0x6D, }, // i = 0x81
{ 0x7B, 0x71, 0x6E, }, // i = 0x82
{ 0x7C, 0x72, 0x6F, }, // i = 0x83
{ 0x7D, 0x73, 0x70, }, // i = 0x84
{ 0x7E, 0x74, 0x71, }, // i = 0x85
{ 0x7F, 0x75, 0x72, }, // i = 0x86
{ 0x80, 0x76, 0x73, }, // i = 0x87
{ 0x82, 0x77, 0x74, }, // i = 0x88
{ 0x83, 0x78, 0x75, }, // i = 0x89
{ 0x84, 0x79, 0x76, }, // i = 0x8A
{ 0x85, 0x7A, 0x77, }, // i = 0x8B
{ 0x86, 0x7B, 0x78, }, // i = 0x8C
{ 0x87, 0x7C, 0x79, }, // i = 0x8D
{ 0x88, 0x7E, 0x7A, }, // i = 0x8E
{ 0x89, 0x7F, 0x7B, }, // i = 0x8F
{ 0x8A, 0x80, 0x7C, }, // i = 0x90
{ 0x8B, 0x81, 0x7D, }, // i = 0x91
{ 0x8C, 0x82, 0x7E, }, // i = 0x92
{ 0x8D, 0x83, 0x7F, }, // i = 0x93
{ 0x8F, 0x84, 0x80, }, // i = 0x94
{ 0x90, 0x85, 0x81, }, // i = 0x95
{ 0x91, 0x86, 0x82, }, // i = 0x96
{ 0x92, 0x87, 0x84, }, // i = 0x97
{ 0x93, 0x88, 0x85, }, // i = 0x98
{ 0x94, 0x8A, 0x86, }, // i = 0x99
{ 0x95, 0x8B, 0x87, }, // i = 0x9A
{ 0x96, 0x8C, 0x88, }, // i = 0x9B
{ 0x97, 0x8D, 0x89, }, // i = 0x9C
{ 0x98, 0x8E, 0x8A, }, // i = 0x9D
{ 0x99, 0x8F, 0x8B, }, // i = 0x9E
{ 0x9B, 0x90, 0x8C, }, // i = 0x9F
{ 0x9C, 0x91, 0x8D, }, // i = 0xA0
{ 0x9D, 0x92, 0x8E, }, // i = 0xA1
{ 0x9E, 0x94, 0x8F, }, // i = 0xA2
{ 0x9F, 0x95, 0x90, }, // i = 0xA3
{ 0xA0, 0x96, 0x91, }, // i = 0xA4
{ 0xA1, 0x97, 0x92, }, // i = 0xA5
{ 0xA2, 0x98, 0x93, }, // i = 0xA6
{ 0xA3, 0x99, 0x94, }, // i = 0xA7
{ 0xA4, 0x9A, 0x95, }, // i = 0xA8
{ 0xA5, 0x9B, 0x97, }, // i = 0xA9
{ 0xA7, 0x9C, 0x98, }, // i = 0xAA
{ 0xA8, 0x9E, 0x99, }, // i = 0xAB
{ 0xA9, 0x9F, 0x9A, }, // i = 0xAC
{ 0xAA, 0xA0, 0x9B, }, // i = 0xAD
{ 0xAB, 0xA1, 0x9C, }, // i = 0xAE
{ 0xAC, 0xA2, 0x9D, }, // i = 0xAF
{ 0xAD, 0xA3, 0x9E, }, // i = 0xB0
{ 0xAE, 0xA4, 0x9F, }, // i = 0xB1
{ 0xAF, 0xA5, 0xA0, }, // i = 0xB2
{ 0xB0, 0xA7, 0xA1, }, // i = 0xB3
{ 0xB1, 0xA8, 0xA3, }, // i = 0xB4
{ 0xB3, 0xA9, 0xA4, }, // i = 0xB5
{ 0xB4, 0xAA, 0xA5, }, // i = 0xB6
{ 0xB5, 0xAB, 0xA6, }, // i = 0xB7
{ 0xB6, 0xAC, 0xA7, }, // i = 0xB8
{ 0xB7, 0xAD, 0xA8, }, // i = 0xB9
{ 0xB8, 0xAF, 0xA9, }, // i = 0xBA
{ 0xB9, 0xB0, 0xAA, }, // i = 0xBB
{ 0xBA, 0xB1, 0xAB, }, // i = 0xBC
{ 0xBB, 0xB2, 0xAD, }, // i = 0xBD
{ 0xBC, 0xB3, 0xAE, }, // i = 0xBE
{ 0xBD, 0xB4, 0xAF, }, // i = 0xBF
{ 0xBE, 0xB5, 0xB0, }, // i = 0xC0
{ 0xC0, 0xB7, 0xB1, }, // i = 0xC1
{ 0xC1, 0xB8, 0xB2, }, // i = 0xC2
{ 0xC2, 0xB9, 0xB3, }, // i = 0xC3
{ 0xC3, 0xBA, 0xB5, }, // i = 0xC4
{ 0xC4, 0xBB, 0xB6, }, // i = 0xC5
{ 0xC5, 0xBC, 0xB7, }, // i = 0xC6
{ 0xC6, 0xBE, 0xB8, }, // i = 0xC7
{ 0xC7, 0xBF, 0xB9, }, // i = 0xC8
{ 0xC8, 0xC0, 0xBA, }, // i = 0xC9
{ 0xC9, 0xC1, 0xBB, }, // i = 0xCA
{ 0xCA, 0xC2, 0xBD, }, // i = 0xCB
{ 0xCC, 0xC3, 0xBE, }, // i = 0xCC
{ 0xCD, 0xC4, 0xBF, }, // i = 0xCD
{ 0xCE, 0xC6, 0xC0, }, // i = 0xCE
{ 0xCF, 0xC7, 0xC1, }, // i = 0xCF
{ 0xD0, 0xC8, 0xC2, }, // i = 0xD0
{ 0xD1, 0xC9, 0xC4, }, // i = 0xD1
{ 0xD2, 0xCA, 0xC5, }, // i = 0xD2
{ 0xD3, 0xCB, 0xC6, }, // i = 0xD3
{ 0xD4, 0xCD, 0xC7, }, // i = 0xD4
{ 0xD5, 0xCE, 0xC8, }, // i = 0xD5
{ 0xD6, 0xCF, 0xCA, }, // i = 0xD6
{ 0xD7, 0xD0, 0xCB, }, // i = 0xD7
{ 0xD8, 0xD1, 0xCC, }, // i = 0xD8
{ 0xD9, 0xD2, 0xCD, }, // i = 0xD9
{ 0xDB, 0xD4, 0xCE, }, // i = 0xDA
{ 0xDC, 0xD5, 0xD0, }, // i = 0xDB
{ 0xDD, 0xD6, 0xD1, }, // i = 0xDC
{ 0xDE, 0xD7, 0xD2, }, // i = 0xDD
{ 0xDF, 0xD8, 0xD3, }, // i = 0xDE
{ 0xE0, 0xD9, 0xD5, }, // i = 0xDF
{ 0xE1, 0xDB, 0xD6, }, // i = 0xE0
{ 0xE2, 0xDC, 0xD7, }, // i = 0xE1
{ 0xE3, 0xDD, 0xD8, }, // i = 0xE2
{ 0xE4, 0xDE, 0xDA, }, // i = 0xE3
{ 0xE5, 0xDF, 0xDB, }, // i = 0xE4
{ 0xE6, 0xE0, 0xDC, }, // i = 0xE5
{ 0xE7, 0xE2, 0xDD, }, // i = 0xE6
{ 0xE8, 0xE3, 0xDF, }, // i = 0xE7
{ 0xE9, 0xE4, 0xE0, }, // i = 0xE8
{ 0xEA, 0xE5, 0xE1, }, // i = 0xE9
{ 0xEB, 0xE6, 0xE3, }, // i = 0xEA
{ 0xEC, 0xE8, 0xE4, }, // i = 0xEB
{ 0xED, 0xE9, 0xE5, }, // i = 0xEC
{ 0xEE, 0xEA, 0xE7, }, // i = 0xED
{ 0xEF, 0xEB, 0xE8, }, // i = 0xEE
{ 0xF0, 0xEC, 0xE9, }, // i = 0xEF
{ 0xF1, 0xED, 0xEB, }, // i = 0xF0
{ 0xF2, 0xEF, 0xEC, }, // i = 0xF1
{ 0xF3, 0xF0, 0xED, }, // i = 0xF2
{ 0xF4, 0xF1, 0xEF, }, // i = 0xF3
{ 0xF5, 0xF2, 0xF0, }, // i = 0xF4
{ 0xF6, 0xF3, 0xF1, }, // i = 0xF5
{ 0xF7, 0xF5, 0xF3, }, // i = 0xF6
{ 0xF8, 0xF6, 0xF4, }, // i = 0xF7
{ 0xF9, 0xF7, 0xF6, }, // i = 0xF8
{ 0xFA, 0xF8, 0xF7, }, // i = 0xF9
{ 0xFB, 0xFA, 0xF8, }, // i = 0xFA
{ 0xFC, 0xFB, 0xFA, }, // i = 0xFB
{ 0xFD, 0xFC, 0xFB, }, // i = 0xFC
{ 0xFE, 0xFD, 0xFD, }, // i = 0xFD
{ 0xFE, 0xFE, 0xFE, }, // i = 0xFE
{ 0xFF, 0xFF, 0xFF, }, // i = 0xFF
};

View File

@ -31,7 +31,6 @@
extern Menu sysconfigMenu; extern Menu sysconfigMenu;
extern bool isConnectionForced; extern bool isConnectionForced;
extern s8 currVolumeSliderOverride;
void SysConfigMenu_UpdateStatus(bool control); void SysConfigMenu_UpdateStatus(bool control);
@ -41,6 +40,3 @@ void SysConfigMenu_TogglePowerButton(void);
void SysConfigMenu_ControlWifi(void); void SysConfigMenu_ControlWifi(void);
void SysConfigMenu_DisableForcedWifiConnection(void); void SysConfigMenu_DisableForcedWifiConnection(void);
void SysConfigMenu_ToggleCardIfPower(void); void SysConfigMenu_ToggleCardIfPower(void);
void SysConfigMenu_LoadConfig(void);
void SysConfigMenu_AdjustVolume(void);
void SysConfigMenu_ChangeScreenBrightness(void);

View File

@ -1,5 +0,0 @@
#pragma once
#include "plugin/plgloader.h"
#include "plugin/plgldr.h"
#include "plugin/3gx.h"

View File

@ -1,87 +0,0 @@
#pragma once
#include <3ds/types.h>
#include "ifile.h"
#define _3GX_MAGIC (0x3230303024584733) /* "3GX$0002" */
typedef struct CTR_PACKED
{
u32 authorLen;
const char* authorMsg;
u32 titleLen;
const char* titleMsg;
u32 summaryLen;
const char* summaryMsg;
u32 descriptionLen;
const char* descriptionMsg;
union {
u32 flags;
struct {
u32 embeddedExeLoadFunc : 1;
u32 embeddedSwapSaveLoadFunc : 1;
u32 memoryRegionSize : 2;
u32 compatibility : 2;
u32 eventsSelfManaged : 1;
u32 swapNotNeeded : 1;
u32 usePrivateMemory : 1;
u32 allowHomebrewLoad : 1;
u32 unused : 22;
};
};
u32 exeLoadChecksum;
u32 builtInLoadExeArgs[4];
u32 builtInSwapSaveLoadArgs[4];
} _3gx_Infos;
typedef struct CTR_PACKED
{
u32 count;
u32 * titles;
} _3gx_Targets;
typedef struct CTR_PACKED
{
u32 nbSymbols;
u32 symbolsOffset;
u32 nameTableOffset;
} _3gx_Symtable;
typedef struct CTR_PACKED
{
u32 codeOffset;
u32 rodataOffset;
u32 dataOffset;
u32 codeSize;
u32 rodataSize;
u32 dataSize;
u32 bssSize;
u32 exeLoadFuncOffset; // NOP terminated
u32 swapSaveFuncOffset; // NOP terminated
u32 swapLoadFuncOffset; // NOP terminated
} _3gx_Executable;
typedef struct CTR_PACKED
{
u64 magic;
u32 version;
u32 reserved;
_3gx_Infos infos;
_3gx_Executable executable;
_3gx_Targets targets;
_3gx_Symtable symtable;
} _3gx_Header;
enum _3gx_Compatibility {
PLG_COMPAT_CONSOLE = 0,
PLG_COMPAT_EMULATOR = 1,
PLG_COMPAT_CONSOLE_EMULATOR = 2,
};
Result Check_3gx_Magic(IFile *file);
Result Read_3gx_Header(IFile *file, _3gx_Header *header);
Result Read_3gx_ParseHeader(IFile *file, _3gx_Header *header);
Result Read_3gx_LoadSegments(IFile *file, _3gx_Header *header, void *dst);
Result Read_3gx_EmbeddedPayloads(IFile *file, _3gx_Header *header);
Result Set_3gx_LoadParams(u32* loadFunc, u32* params);
void Reset_3gx_LoadParams(void);

View File

@ -1,81 +0,0 @@
#pragma once
#include <3ds/types.h>
#define MAX_BUFFER (50)
#define MAX_ITEMS_COUNT (64)
#define HeaderMagic (0x24584733) /* "3GX$" */
typedef struct
{
bool noFlash;
u8 pluginMemoryStrategy;
u8 persistent;
u32 lowTitleId;
char path[256];
u32 config[32];
} PluginLoadParameters;
typedef struct
{
u32 nbItems;
u8 states[MAX_ITEMS_COUNT];
char title[MAX_BUFFER];
char items[MAX_ITEMS_COUNT][MAX_BUFFER];
char hints[MAX_ITEMS_COUNT][MAX_BUFFER];
} PluginMenu;
typedef enum
{
PLG_WAIT = -1,
PLG_OK = 0,
PLG_SLEEP_ENTRY = 1,
PLG_SLEEP_EXIT = 2,
PLG_ABOUT_TO_SWAP = 3,
PLG_ABOUT_TO_EXIT = 4,
PLG_HOME_ENTER = 5,
PLG_HOME_EXIT = 6,
} PLG_Event;
typedef enum
{
PLG_STRATEGY_NONE = 2,
PLG_STRATEGY_SWAP = 0,
PLG_STRATEGY_MODE3 = 1
} PluginMemoryStrategy;
typedef struct
{
u32 magic;
u32 version;
u32 heapVA;
u32 heapSize;
u32 exeSize; // Include sizeof(PluginHeader) + .text + .rodata + .data + .bss (0x1000 aligned too)
u32 isDefaultPlugin;
s32* plgldrEvent; ///< Used for synchronization
s32* plgldrReply; ///< Used for synchronization
u8 notifyHomeEvent;
u8 padding[7];
u64 waitForReplyTimeout;
u32 reserved[20];
u32 config[32];
} PluginHeader;
_Static_assert(sizeof(PluginHeader) == 0x100, "Invalid PluginHeader size");
typedef void (*OnPlgLdrEventCb_t)(s32 eventType);
Result plgLdrInit(void);
void plgLdrExit(void);
Result PLGLDR__IsPluginLoaderEnabled(bool *isEnabled);
Result PLGLDR__SetPluginLoaderState(bool enabled);
Result PLGLDR__SetPluginLoadParameters(PluginLoadParameters *parameters);
Result PLGLDR__DisplayMenu(PluginMenu *menu);
Result PLGLDR__DisplayMessage(const char *title, const char *body);
Result PLGLDR__DisplayErrMessage(const char *title, const char *body, u32 error);
Result PLGLDR__SetRosalinaMenuBlock(bool shouldBlock);
Result PLGLDR__SetSwapSettings(char* swapPath, void* saveFunc, void* loadFunc, void* args);
Result PLGLDR__SetExeLoadSettings(void* loadFunc, void* args);
Result PLGLDR__GetVersion(u32 *version);
void PLGLDR__SetEventCallback(OnPlgLdrEventCb_t cb);
void PLGLDR__Status(void);

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