Compare commits

..

No commits in common. "master" and "v1.9.0" have entirely different histories.

339 changed files with 8230 additions and 60560 deletions

View File

@ -1,40 +0,0 @@
---
name: Bug report
about: Report a bug you found in GodMode9
title: "[BUG] ..."
labels: bug
assignees: ''
---
---
name: Bug report
about: Report a bug you found
title: "[BUG] ..."
labels: bug
assignees: ''
---
**So you want to report a bug?**
Hold on, there are ways you could make things easier for us:
* Give a clear description of the bug (what happened?).
* Give us clear steps to reproduce (when/how did it happen?).
* Give us info about your system (where did it happen?).
* A photograph or even a short video of the bug happening is always helpful!
**Info about your system**
Include this info to make our work easier:
* Console type (O3DS/N3DS)
* Anything special about your console? (defects, custom modifications,...)
* Bootloader (boot9strap/fastboot3ds)
* Did you chainload GodMode9 via Luma?
* Helpful hint: *if you followed the Guide, boot9strap is your bootloader and Luma is your chainloader.*
**Help yourself**
*Especially for any kind of boot issue ("GodMode9 doesn't boot")*, but also in many other cases these steps make a lot of sense and we will ask you to do them anyways:
* Check your SD card (using h2testw, f.e.) or try a different one (you wouldn't believe how common failing/fake SD cards are, and what kinds of bugs are caused by them).
* Switch to fastboot3DS using [https://github.com/d0k3/OpenFirmInstaller](OpenFirmInstaller).
**Have you actually read this?**
[] I have read the information above

View File

@ -1,17 +0,0 @@
---
name: Feature request
about: Suggest an idea for this GodMode9
title: "[FEATURE REQUEST] ..."
labels: feature request
assignees: ''
---
**Got a great idea on how to improve GodMode9?**
That's always appreciated. Please make sure you add all the required info here.
**Describe the feature you'd like**
Add a clear and concise description of what you want to happen.
**Describe alternatives you've considered**
Add a clear and concise description of any alternative solutions or features you've considered.

View File

@ -1,42 +0,0 @@
name: CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
container: devkitpro/devkitarm
steps:
- uses: actions/checkout@v1
- name: Fix apt sources
run: |
apt-get update
apt-get -y install dirmngr
echo 'deb http://us.archive.ubuntu.com/ubuntu/ bionic main' >> /etc/apt/sources.list
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3B4FE6ACC0B21F32
apt-get update
- name: Install and update packages
run: |
apt-get -y install python3 python3-pip p7zip-full libarchive13
python3 --version
python3 -m pip install --upgrade pip setuptools
python3 -m pip install cryptography git+https://github.com/TuxSH/firmtool.git
- name: Build Project
run: make release -j$(nproc)
- name: Prepare build artifact
working-directory: release
run: |
ZIPNAME=$(ls GodMode9-*.zip)
rm $ZIPNAME
echo "OUTNAME=${ZIPNAME%.zip}" >> $GITHUB_ENV
- uses: actions/upload-artifact@v4
with:
name: ${{ env.OUTNAME }}
path: release/*
if-no-files-found: error

9
.gitignore vendored
View File

@ -5,7 +5,6 @@
*.obj
*.elf
*.map
*.dis
# Precompiled Headers
*.gch
@ -36,14 +35,10 @@
# OS leftovers
desktop.ini
.DS_Store
# Sublime files
*.sublime-*
# Visual Studio Code files
.vscode
# Build directories
/build
/output
@ -53,6 +48,6 @@ desktop.ini
/data/README_internal.md
# User additions
/data/aeskeydb.bin
/data/aeskeydb_.bin
/zzz_backup
/arm9/source/language.inl
*.trf

19
.travis.yml Normal file
View File

@ -0,0 +1,19 @@
language: c
sudo: true
dist: bionic
before_install:
- wget "https://github.com/devkitPro/pacman/releases/latest/download/devkitpro-pacman.deb" -O dkp-pacman.deb
- export DEVKITPRO=/opt/devkitpro
- export DEVKITARM=${DEVKITPRO}/devkitARM
install:
- sudo dpkg -i dkp-pacman.deb
- sudo dkp-pacman -S --noconfirm devkitARM
- sudo apt-get -y install python3 python3-pip p7zip-full
- sudo pip3 install --upgrade pip setuptools
- sudo pip3 install cryptography
- sudo pip3 install git+https://github.com/TuxSH/firmtool.git
script:
- make release

View File

@ -16,31 +16,14 @@ export RELDIR := release
export COMMON_DIR := ../common
# Definitions for initial RAM disk
VRAM_TAR := $(OUTDIR)/vram0.tar
VRAM_DATA := data/*
VRAM_FLAGS := --make-new --path-limit 99
ifeq ($(NTRBOOT),1)
VRAM_SCRIPTS := resources/gm9/scripts/*
endif
# Definitions for translation files
JSON_FOLDER := resources/languages
TRF_FOLDER := resources/gm9/languages
SOURCE_JSON := $(JSON_FOLDER)/source.json
LANGUAGE_INL := arm9/source/language.inl
JSON_FILES := $(filter-out $(SOURCE_JSON),$(wildcard $(JSON_FOLDER)/*.json))
TRF_FILES := $(subst $(JSON_FOLDER),$(TRF_FOLDER),$(JSON_FILES:.json=.trf))
VRAM_OUT := $(OUTDIR)/vram0.tar
VRAM_DATA := data
VRAM_FLAGS := --make-new --path-limit 99 --size-limit 3145728
ifeq ($(OS),Windows_NT)
ifeq ($(TERM),cygwin)
PY3 := py -3 # Windows / CMD/PowerShell
else
PY3 := py # Windows / MSYS2
endif
PY3 := py -3
else
PY3 := python3 # Unix-like
PY3 := python3
endif
# Definitions for ARM binaries
@ -50,18 +33,18 @@ export ASFLAGS := -g -x assembler-with-cpp $(INCLUDE)
export CFLAGS := -DDBUILTS="\"$(DBUILTS)\"" -DDBUILTL="\"$(DBUILTL)\"" -DVERSION="\"$(VERSION)\"" -DFLAVOR="\"$(FLAVOR)\"" \
-g -Os -Wall -Wextra -Wcast-align -Wformat=2 -Wno-main \
-fomit-frame-pointer -ffast-math -std=gnu11 -MMD -MP \
-Wno-unused-function -Wno-format-truncation -Wno-format-nonliteral $(INCLUDE) -ffunction-sections -fdata-sections
export LDFLAGS := -Tlink.ld -nostartfiles -Wl,--gc-sections,-z,max-page-size=4096
ELF := arm9/arm9_code.elf arm9/arm9_data.elf arm11/arm11.elf
-Wno-unused-function -Wno-format-truncation $(INCLUDE) -ffunction-sections -fdata-sections
export LDFLAGS := -Tlink.ld -nostartfiles -Wl,--gc-sections,-z,max-page-size=512
ELF := arm9/arm9.elf arm11/arm11.elf
.PHONY: all firm $(VRAM_TAR) elf release clean
.PHONY: all firm vram0 elf release clean
all: firm
clean:
@set -e; for elf in $(ELF); do \
$(MAKE) --no-print-directory -C $$(dirname $$elf) clean; \
done
@rm -rf $(OUTDIR) $(RELDIR) $(FIRM) $(FIRMD) $(VRAM_TAR) $(LANGUAGE_INL) $(TRF_FILES)
@rm -rf $(OUTDIR) $(RELDIR) $(FIRM) $(FIRMD) $(VRAM_OUT)
unmarked_readme: .FORCE
@$(PY3) utils/unmark.py -f README.md data/README_internal.md
@ -85,44 +68,29 @@ release: clean unmarked_readme
@cp $(OUTDIR)/$(FLAVOR)_dev.firm.sha $(RELDIR)/
@cp $(ELF) $(RELDIR)/elf
@cp $(CURDIR)/README.md $(RELDIR)
@cp $(CURDIR)/resources/lua-doc.md $(RELDIR)/lua-doc.md
@cp -R $(CURDIR)/resources/gm9 $(RELDIR)/gm9
@cp -R $(CURDIR)/resources/sample $(RELDIR)/sample
@-7za a $(RELDIR)/$(FLAVOR)-$(VERSION)-$(DBUILTS).zip ./$(RELDIR)/*
$(VRAM_TAR): $(SPLASH) $(OVERRIDE_FONT) $(VRAM_DATA) $(VRAM_SCRIPTS)
@mkdir -p "$(@D)"
@echo "Creating $@"
@$(PY3) utils/add2tar.py $(VRAM_FLAGS) $(VRAM_TAR) $(shell ls -d -1 $^)
$(LANGUAGE_INL): $(SOURCE_JSON)
@echo "Creating $@"
@$(PY3) utils/transcp.py $< $@
$(TRF_FOLDER)/%.trf: $(JSON_FOLDER)/%.json
@$(PY3) utils/transriff.py $< $@
vram0:
@mkdir -p "$(OUTDIR)"
@echo "Creating $(VRAM_OUT)"
@$(PY3) utils/add2tar.py $(VRAM_FLAGS) $(VRAM_OUT) $(shell ls -d $(SPLASH) $(OVERRIDE_FONT) $(VRAM_DATA)/*)
%.elf: .FORCE
@echo "Building $@"
@$(MAKE) --no-print-directory -C $(@D) $(@F)
@$(MAKE) --no-print-directory -C $(@D)
# Indicate a few explicit dependencies:
# The ARM9 data section depends on the VRAM drive
arm9/arm9_data.elf: $(VRAM_TAR) $(LANGUAGE_INL)
# And the code section depends on the data section being built already
arm9/arm9_code.elf: arm9/arm9_data.elf
firm: $(ELF) $(TRF_FILES)
firm: $(ELF) vram0
@test `wc -c <$(VRAM_OUT)` -le 3145728
@mkdir -p $(call dirname,"$(FIRM)") $(call dirname,"$(FIRMD)")
@echo "[FLAVOR] $(FLAVOR)"
@echo "[VERSION] $(VERSION)"
@echo "[BUILD] $(DBUILTL)"
@echo "[FIRM] $(FIRM)"
@$(PY3) -m firmtool build $(FIRM) $(FTFLAGS) -g -D $(ELF) -C NDMA NDMA XDMA
@$(PY3) -m firmtool build $(FIRM) $(FTFLAGS) -g -A 0x18000000 -D $(ELF) $(VRAM_OUT) -C NDMA XDMA memcpy
@echo "[FIRM] $(FIRMD)"
@$(PY3) -m firmtool build $(FIRMD) $(FTDFLAGS) -g -D $(ELF) -C NDMA NDMA XDMA
vram0: $(VRAM_TAR) .FORCE # legacy target name
@$(PY3) -m firmtool build $(FIRMD) $(FTDFLAGS) -g -A 0x18000000 -D $(ELF) $(VRAM_OUT) -C NDMA XDMA memcpy
.FORCE:

View File

@ -1,38 +1,35 @@
LIBS ?=
OBJECTS := $(patsubst $(SOURCE)/%.s, $(BUILD)/%.o, \
$(patsubst $(SOURCE)/%.c, $(BUILD)/%.o, \
$(call rwildcard, $(SOURCE), *.s *.c)))
OBJECTS_COMMON := $(patsubst $(COMMON_DIR)/%.c, $(BUILD)/%.cmn.o, \
$(call rwildcard, $(COMMON_DIR), *.c))
.PHONY: all
all: $(TARGET).elf
.PHONY: clean
clean:
@rm -rf $(BUILD) $(TARGET).elf $(TARGET).dis $(TARGET).map
$(TARGET).elf: $(OBJECTS) $(OBJECTS_COMMON)
@mkdir -p "$(@D)"
@$(CC) $(LDFLAGS) $^ -o $@ $(LIBS)
@$(OBJDUMP) -S -h $@ > $@.dis
$(BUILD)/%.cmn.o: $(COMMON_DIR)/%.c
@mkdir -p "$(@D)"
@echo "[$(PROCESSOR)] $<"
@$(CC) -c $(CFLAGS) -o $@ $<
$(BUILD)/%.o: $(SOURCE)/%.c
@mkdir -p "$(@D)"
@echo "[$(PROCESSOR)] $<"
@$(CC) -c $(CFLAGS) -o $@ $<
$(BUILD)/%.o: $(SOURCE)/%.s
@mkdir -p "$(@D)"
@echo "[$(PROCESSOR)] $<"
@$(CC) -c $(ASFLAGS) -o $@ $<
include $(call rwildcard, $(BUILD), *.d)
OBJECTS := $(patsubst $(SOURCE)/%.s, $(BUILD)/%.o, \
$(patsubst $(SOURCE)/%.c, $(BUILD)/%.o, \
$(call rwildcard, $(SOURCE), *.s *.c)))
OBJECTS_COMMON := $(patsubst $(COMMON_DIR)/%.c, $(BUILD)/%.cmn.o, \
$(call rwildcard, $(COMMON_DIR), *.c))
.PHONY: all
all: $(TARGET).elf
.PHONY: clean
clean:
@rm -rf $(BUILD) $(TARGET).elf $(TARGET).map
$(TARGET).elf: $(OBJECTS) $(OBJECTS_COMMON)
@mkdir -p "$(@D)"
@$(CC) $(LDFLAGS) $^ -o $@
$(BUILD)/%.cmn.o: $(COMMON_DIR)/%.c
@mkdir -p "$(@D)"
@echo "[$(PROCESSOR)] $<"
@$(CC) -c $(CFLAGS) -o $@ $<
$(BUILD)/%.o: $(SOURCE)/%.c
@mkdir -p "$(@D)"
@echo "[$(PROCESSOR)] $<"
@$(CC) -c $(CFLAGS) -o $@ $<
$(BUILD)/%.o: $(SOURCE)/%.s
@mkdir -p "$(@D)"
@echo "[$(PROCESSOR)] $<"
@$(CC) -c $(ASFLAGS) -o $@ $<
include $(call rwildcard, $(BUILD), *.d)

View File

@ -1,4 +1,3 @@
export OBJDUMP := arm-none-eabi-objdump
dirname = $(shell dirname $(1))
@ -26,12 +25,6 @@ else ifeq ($(FLAVOR),ZuishMode9)
CFLAGS += -DDEFAULT_FONT=\"font_zuish_8x8.pbm\"
endif
ifeq ($(LARGEDLC),1)
CFLAGS += -DTITLE_MAX_CONTENTS=1536
else
CFLAGS += -DTITLE_MAX_CONTENTS=1024
endif
ifeq ($(SALTMODE),1)
CFLAGS += -DSALTMODE
endif
@ -68,10 +61,6 @@ ifdef SD_TIMEOUT
CFLAGS += -DSD_TIMEOUT=$(SD_TIMEOUT)
endif
ifeq ($(NO_LUA),1)
CFLAGS += -DNO_LUA
endif
ifdef N_PANES
CFLAGS += -DN_PANES=$(N_PANES)
endif

View File

@ -39,9 +39,9 @@ GodMode9 is designed to be intuitive, buttons leading to the results you'd expec
## How to build this / developer info
Build `GodMode9.firm` via `make firm`. This requires [firmtool](https://github.com/TuxSH/firmtool), [Python 3.5+](https://www.python.org/downloads/) and [devkitARM](https://sourceforge.net/projects/devkitpro/) installed).
You may run `make release` to get a nice, release-ready package of all required files. To build __SafeMode9__ (a bricksafe variant of GodMode9, with limited write permissions) instead of GodMode9, compile with `make FLAVOR=SafeMode9`. To switch screens, compile with `make SWITCH_SCREENS=1`. For additional customization, you may choose the internal font by replacing `font_default.frf` inside the `data` directory. You may also hardcode the brightness via `make FIXED_BRIGHTNESS=x`, whereas `x` is a value between 0...15.
You may run `make release` to get a nice, release-ready package of all required files. To build __SafeMode9__ (a bricksafe variant of GodMode9, with limited write permissions) instead of GodMode9, compile with `make FLAVOR=SafeMode9`. To switch screens, compile with `make SWITCH_SCREENS=1`. For additional customization, you may choose the internal font by replacing `font_default.pbm` inside the `data` directory. You may also hardcode the brightness via `make FIXED_BRIGHTNESS=x`, whereas `x` is a value between 0...15.
Further customization is possible by hardcoding `aeskeydb.bin` (just put the file into the `data` folder when compiling). All files put into the `data` folder will turn up in the `V:` drive, but keep in mind there's a hard 223.5KiB limit for all files inside, including overhead. A standalone script runner is compiled by providing `autorun.lua` or `autorun.gm9` (again, in the `data` folder) and building with `make SCRIPT_RUNNER=1`. There's more possibility for customization, read the Makefiles to learn more.
Further customization is possible by hardcoding `aeskeydb.bin` (just put the file into the `data` folder when compiling). All files put into the `data` folder will turn up in the `V:` drive, but keep in mind there's a hard 3MB limit for all files inside, including overhead. A standalone script runner is compiled by providing `autorun.gm9` (again, in the `data` folder) and building with `make SCRIPT_RUNNER=1`. There's more possibility for customization, read the Makefiles to learn more.
To build a .firm signed with SPI boot keys (for ntrboot and the like), run `make NTRBOOT=1`. You may need to rename the output files if the ntrboot installer you use uses hardcoded filenames. Some features such as boot9 / boot11 access are not currently available from the ntrboot environment.
@ -61,14 +61,10 @@ GodMode9 provides a write permissions system, which will protect you from accide
## Support files
For certain functionality, GodMode9 may need 'support files'. Support files should be placed into either `0:/gm9/support` or `1:/gm9/support`. Support files contain additional information that is required in decryption operations. A list of support files, and what they do, is found below. Please don't ask for support files - find them yourself.
* __`aeskeydb.bin`__: This should contain 0x25keyX, 0x18keyX and 0x1BkeyX to enable decryption of 7x / Secure3 / Secure4 encrypted NCCH files, 0x11key95 / 0x11key96 for FIRM decrypt support and 0x11keyOTP / 0x11keyIVOTP for 'secret' sector 0x96 crypto support. Entrypoints other than [boot9strap](https://github.com/SciresM/boot9strap) or [fastboot3ds](https://github.com/derrekr/fastboot3DS) may require a aeskeydb.bin file. This is now included in standard releases of GM9. No need to hunt down the file!
* __`seeddb.bin`__: This file is optional and required to decrypt and mount seed-encrypted NCCHs and CIAs (if the seed in question is not installed to your NAND). Note that your seeddb.bin must also contain the seed for the specific game you need to decrypt.
* __`encTitleKeys.bin`__ / __`decTitleKeys.bin`__: These files are optional and provide titlekeys, which are required to decrypt and install contents downloaded from CDN (for DSi and 3DS content).
* __`aeskeydb.bin`__: This should contain 0x25keyX, 0x18keyX and 0x1BkeyX to enable decryption of 7x / Secure3 / Secure4 encrypted NCCH files, 0x11key95 / 0x11key96 for FIRM decrypt support and 0x11keyOTP / 0x11keyIVOTP for 'secret' sector 0x96 crypto support. Entrypoints other than [boot9strap](https://github.com/SciresM/boot9strap) or [fastboot3ds](https://github.com/derrekr/fastboot3DS) may require a aeskeydb.bin file. A known perfect `aeskeydb.bin` can be found somewhere on the net, is exactly 1024 byte big and has an MD5 of A5B28945A7C051D7A0CD18AF0E580D1B. Have fun hunting!
* __`seeddb.bin`__: This file is required to decrypt and mount seed encrypted NCCHs and CIAs if the seed in question is not installed to your NAND. Note that your seeddb.bin must also contain the seed for the specific game you need to decrypt.
* __`encTitleKeys.bin`__ / __`decTitleKeys.bin`__: These files are optional and provide titlekeys, which are required to create updatable CIAs from NCCH / NCSD files. CIAs created without these files will still work, but won't be updatable from eShop.
### Fonts and translations
GodMode9 also supports custom fonts and translations as support files. These both use custom formats, fonts use FRF (Font RIFF) files which can be created using the `fontriff.py` Python script in the 'utils' folder. Translations use TRF (Translation RIFF) files from the `transriff.py` script. Examples of the inputs to these scripts can be found in the 'fonts' and 'languages' folders of the 'resources' folder respectively.
TRF files can be placed in `0:/gm9/languages` to show in the language menu accessible from the HOME menu and shown on first load. Official translations are provided from the community via the [GodMode9 Crowdin](https://crowdin.com/project/GodMode9). Languages can use a special font by having an FRF with the same name, for example `en.trf` and `en.frf`.
## Drives in GodMode9
GodMode9 provides access to system data via drives, a listing of what each drive contains and additional info follows below. Some of these drives are removable (such as drive `7:`), some will only turn up if they are available (drive `8:` and everything associated with EmuNAND, f.e.). Information on the 3DS console file system is also found on [3Dbrew.org](https://3dbrew.org/wiki/Flash_Filesystem).
@ -90,22 +86,12 @@ GodMode9 provides access to system data via drives, a listing of what each drive
* __`C: GAMECART`__: This is read-only and provides access to the game cartridge currently inserted into the cart slot. This can be used for dumps of CTR and TWL mode cartridges. Flash cards are supported only to a limited extent.
* __`G: GAME IMAGE`__: CIA/NCSD/NCCH/EXEFS/ROMFS/FIRM images can be accessed via this drive when mounted. This is read-only.
* __`K: AESKEYDB IMAGE`__: An `aeskeydb.bin` image can be mounted and accessed via this drive. The drive shows all keys inside the aeskeydb.bin. This is read-only.
* __`T: TICKET.DB IMAGE / BDRI IMAGE`__: Ticket database files can be mounted and accessed via this drive. This provides easy and quick access to all tickets inside the `ticket.db`. This drive also provides access to other BDRI images, such as the Title database (`title.db`).
* __`T: TICKET.DB IMAGE`__: Ticket database files can be mounted and accessed via this drive. This provides easy and quick access to all tickets inside the `ticket.db`. This is read-only.
* __`M: MEMORY VIRTUAL`__: This provides access to various memory regions. This is protected by a special write permission, and caution is advised when doing modifications inside this drive. This drive also gives access to `boot9.bin`, `boot11.bin` (boot9strap only) and `otp.mem` (sighaxed systems only).
* __`V: VRAM VIRTUAL`__: This drive resides in part of ARM9 internal memory and contains files essential to GodMode9. The font (in FRF format), the splash logo (in PNG format) and the readme file are found there, as well as any file that is provided inside the `data` folder at build time. This is read-only.
* __`Y: TITLE MANAGER`__: The title manager is accessed via the HOME menu and provides easy access to all installed titles.
* __`V: VRAM VIRTUAL`__: This drive resides in the first VRAM bank and contains files essential to GodMode9. The font (in PBM format), the splash logo (in PNG format) and the readme file are found there, as well as any file that is provided inside the `data` folder at build time. This is read-only.
* __`Z: LAST SEARCH`__: After a search operation, search results are found inside this drive. The drive can be accessed at a later point to return to the former search results.
## Digital preservation
GodMode9 is one of the most important tools for digital preservation of 3DS content data. Here's some stuff you should know:
* __Dumping game cartridges (size < 4GiB)__: Game cartridges turn up inside the `C:` drive (see above). For most carts all you need to do is copy the `.3DS` game image to some place of your choice. Game images dumped by GodMode9 contain no identifying info such as private headers or savegames. Private headers can be dumped in a separate image.
* __Dumping game cartridges (size = 4GiB)__: Everything written above applies here as well. However, the FAT32 file system (which is what the 3DS uses) is limited to _4GiB - 1byte_. Take note that the `.3DS` game image, as provided by GodMode9 actually misses the last byte in these cases. That byte is 0xFF and unused in all known cases. It is not required for playing the image. If you need to check, we also provide split files (`.000`, `.001)`, which contain all the data. If you need a valid checksum for the `.3DS` game image, append a 0xFF byte before checking.
* __Building CIAs (all types)__: You may convert compatible file types (game images, installed content, CDN content) to the CIA installable format using the A button menu. To get a list of installed content, press HOME, select `Title manager` and choose a drive. Take note that `standard` built CIAs are decrypted by default (decryption allows better compression by ZIP and 7Z). If you should need an encrypted CIA for some reason, apply the encryption to the CIA afterwards.
* __Building CIAs (legit type)__: Installed content can be built as `legit` or `standard` CIA. Legit CIAs preserve more of the original data and are thus recommended for preservation purposes. When building legit CIAs, GodMode9 keeps the original crypto and tries to find a genuine, signature-valid ticket. If it doesn't find one on your system, it will use a generic ticket instead. If it only finds a personalized one, it still offers to use a generic ticket. It is not recommended to use personalized tickets - only choose this if you know what you're doing.
* __Checking CIAs__: You may also check your CIA files with the builtin `CIA checker tool`. Legit CIAs with generic tickets are identified as `Universal Pirate Legit`, which is the recommended preservation format where `Universal Legit` is not available. Note: apart from system titles, `Universal Legit` is only available for a handful of preinstalled games from special edition 3DS consoles.
## What you can do with GodMode9
With the possibilites GodMode9 provides, not everything may be obvious at first glance. In short, __GodMode9 includes improved versions of basically everything that Decrypt9 has, and more__. Any kind of dumps and injections are handled via standard copy operations and more specific operations are found inside the A button menu. The A button menu also works for batch operations when multiple files are selected. For your convenience a (incomplete!) list of what GodMode9 can do follows below.
@ -114,17 +100,16 @@ With the possibilites GodMode9 provides, not everything may be obvious at first
* __Make screenshots__: Press R+L anywhere. Screenshots are stored in PNG format.
* __Use multiple panes__: Press R+left|right. This enables you to stay in one location in the first pane and open another in the second pane.
* __Search drives and folders__: Just press R+A on the drive / folder you want to search.
* __Compare and verify files__: Press the A button on the first file, select `Calculate SHA-256`. Do the same for the second file. If the two files are identical, you will get a message about them being identical. On the SDCARD drive (`0:`) you can also write an SHA file, so you can check for any modifications at a later point.
* __Compare and verify files__: Press the A button on the first file, select `Calculate SHA-256`. Do the same for the second file. If the two files are identical, you will get a message about them being identical. On the SDCARD drive (`0:`) you can also write a SHA file, so you can check for any modifications at a later point.
* __Hexview and hexedit any file__: Press the A button on a file and select `Show in Hexeditor`. A button again enables edit mode, hold the A button and press arrow buttons to edit bytes. You will get an additional confirmation prompt to take over changes. Take note that for certain files, write permissions can't be enabled.
* __View text files in a text viewer__: Press the A button on a file and select `Show in Textviewer` (only shows up for actual text files). You can enable wordwrapped mode via R+Y, and navigate around the file via R+X and the dpad.
* __Chainload FIRM payloads__: Press the A button on a FIRM file, select `FIRM options` -> `Boot FIRM`. Keep in mind you should not run FIRMs from dubious sources and that the write permissions system is no longer in place after booting a payload.
* __Chainload FIRM payloads from a neat menu__: The `payloads` menu is found inside the HOME button menu. It provides any FIRM found in `0:/gm9/payloads` for quick chainloading.
* __Chainload FIRM payloads from a neat menu__: The `payloads` menu is found inside the HOME button menu. It provides any FIRM found in `0:/gm9/payloads` for quick chainloading.
* __Inject a file to another file__: Put exactly one file (the file to be injected from) into the clipboard (via the Y button). Press A on the file to be injected to. There will be an option to inject the first file into it.
### Scripting functionality
* __Run .lua scripts from anywhere on your SD card__: You can run Lua scripts via the A button menu. For an overview of usable commands have a look into the documentation and sample scripts included in the release archive. *Don't run scripts from untrusted sources.*
* __Run Lua scripts via a neat menu__: Press the HOME button, select `More...` -> `Lua scripts...`. Any script you put into `0:/gm9/luascripts` (subdirs included) will be found here. Scripts ran via this method won't have the confirmation at the beginning either.
* __Run legacy .gm9 scripts__: The old format of .gm9 scripts is still available, but is deprecated and will see no further development.
* __Run .gm9 scripts from anywhere on your SD card__: You can run scripts in .gm9 format via the A button menu. .gm9 scripts use a shell-like language and can be edited in any text editor. For an overview of usable commands have a look into the sample scripts included in the release archive. *Don't run scripts from untrusted sources.*
* __Run .gm9 scripts via a neat menu__: Press the HOME button, select `More...` -> `Scripts...`. Any script you put into `0:/gm9/scripts` (subdirs included) will be found here. Scripts ran via this method won't have the confirmation at the beginning either.
### SD card handling
* __Format your SD card / setup an EmuNAND__: Press the HOME button, select `More...` -> `SD format menu`. This also allows to setup a RedNAND (single/multi) or GW type EmuNAND on your SD card. You will get a warning prompt and an unlock sequence before any operation starts.
@ -134,18 +119,16 @@ With the possibilites GodMode9 provides, not everything may be obvious at first
* __Set (and use) the RTC clock__: For correct modification / creation dates in your file system, you need to setup the RTC clock first. Press the HOME Button and select `More...` to find the option. Keep in mind that modifying the RTC clock means you should also fix system OS time afterwards.
### Game file handling
* __List titles installed on your system__: Press HOME and select `Title manager`. This will also work via R+A for `CTRNAND` and `A:`/`B:` drives. This will list all titles installed in the selected location.
* __Install titles to your system__: Just press A on any file you want installed and select `Install game image` from the submenu. Works with NCCH / NCSD / CIA / DSiWare SRLs / 3DS CDN TMDs / DSi CDN TMDs / NUS TMDs.
* __(Batch) Uninstall titles from your system__: Most easily done via the HOME menu `Title manager`. Just select one or more titles and find the option inside the `Manage title...` submenu.
* __Build CIAs from NCCH / NCSD (.3DS) / SRL / TMD__: Press A on the file you want converted and the option will be shown. Installed contents are found most easily via the HOME menu `Title manager`. Where applicable, you will also be able to generate legit CIAs. Note: this works also from a file search and title listing.
* __List titles installed on your system__: Press R+A on a /title dir or a subdir below that. This will also work directly for `CTRNAND`, `TWLN` and `A:`/`B:` drives. This will list all titles installed in the selected location. Works best with the below two features.
* __Build CIAs from NCCH / NCSD (.3DS) / TMD (installed contents)__: Press A on the file you want converted and the option will be shown. Installed contents are found (among others) in `1:/titles/`(SysNAND) and `A:/titles/`(SD installed). Where applicable, you will also be able to generate legit CIAs. Note: this works also from a file search and title listing.
* __Dump CXIs / NDS from TMD (installed contents)__: This works the same as building CIAs, but dumps decrypted CXIs or NDS rom dumps instead. Note: this works also from a file search and title listing.
* __Decrypt, encrypt and verify NCCH / NCSD / CIA / BOSS / FIRM images__: Options are found inside the A button menu. You will be able to decrypt/encrypt to the standard output directory or (where applicable) in place.
* __Decrypt content downloaded from CDN / NUS__: Press A on the file you want decrypted. For this to work, you need at least a TMD file (`encTitlekeys.bin` / `decTitlekeys.bin` also required, see _Support files_ below) or a CETK file. Either keep the names provided by CDN / NUS, or rename the downloaded content to `(anything).nus` or `(anything).cdn` and the CETK to `(anything).cetk`.
* __Batch mode for the above operations__: Just select multiple files of the same type via the L button, then press the A button on one of the selected files.
* __Access any file inside NCCH / NCSD / CIA / FIRM / NDS images__: Just mount the file via the A button menu and browse to the file you want. For CDN / NUS content, prior decryption is required for full access.
* __Rename your NCCH / NCSD / CIA / NDS / GBA files to proper names__: Find this feature inside the A button menu. Proper names include title id, game name, product code and region.
* __Trim NCCH / NCSD / NDS / GBA / FIRM / NAND images__: This feature is found inside the A button menu. It allows you to trim excess data from supported file types. *Warning: Excess data may not be empty, bonus drives are stored there for NAND images, NCSD card2 images store savedata there, for FIRMs parts of the A9LH exploit may be stored there*.
* __Dump 3DS / NDS / DSi type retail game cartridges__: Insert the cartridge and take a look inside the `C:` drive. You may also dump private headers from 3DS game cartridges. The `C:` drive also gives you read/write access to the saves on the cartridges. Note: For 4GiB cartridges, the last byte is not included in the .3ds file dump. This is due to restrictrions of the FAT32 file system.
* __Trim NCCH / NCSD / NDS / FIRM / NAND images__: This feature is found inside the A button menu. It allows you to trim excess data from supported file types. *Warning: Excess data may not be empty, bonus drives are stored there for NAND images, NCSD card2 images store savedata there, for FIRMs parts of the A9LH exploit may be stored there*.
* __Dump 3DS / NDS / DSi type retail game cartridges__: Insert the cartridge and take a look inside the `C:` drive. You may also dump private headers from 3DS game cartridges. The `C:` drive also gives you read/write access to the saves on the cartridges.
### NAND handling
* __Directly mount and access NAND dumps or standard FAT images__: Just press the A button on these files to get the option. You can only mount NAND dumps from the same console.
@ -155,14 +138,14 @@ With the possibilites GodMode9 provides, not everything may be obvious at first
* __Embed an essential backup right into a NAND dump__: This is available in the A button menu for NAND dumps. Essential backups contain NAND header, `movable.sed`, `LocalFriendCodeSeed_B`, `SecureInfo_A`, NAND CID and OTP. If your local SysNAND does not contain an embedded backup, you will be asked to do one at startup. To update the essential SysNAND backup at a later point in time, press A on `S:/nand.bin` and select `NAND image options...` -> `Update embedded backup`.
* __Install an AES key database to your NAND__: For `aeskeydb.bin` files the option is found in `aeskeydb.bin options` -> `Install aeskeydb.bin`. Only the recommended key database can be installed (see above). With an installed key database, it is possible to run the GodMode9 bootloader completely from NAND.
* __Install FIRM files to your NAND__: Found inside the A button menu for FIRM files, select `FIRM options` -> `Install FIRM`. __Use this with caution__ - installing an incompatible FIRM file will lead to a __brick__. The FIRMs signature will automagically be replaced with a sighax signature to ensure compatibility.
* __Actually use that extra NAND space__: You can set up a __bonus drive__ via the HOME menu, which will be available via drive letter `8:`. (Only available on systems that have the extra space.)
* __Actually use that extra NAND space__: You can setup a __bonus drive__ via the HOME menu, which will be available via drive letter `8:`. (Only available on systems that have the extra space.)
* __Fix certain problems on your NANDs__: You can fix CMACs for a whole drive (works on `A:`, `B:`, `S:` and `E:`) via an entry in the R+A button menu, or even restore borked NAND headers back to a functional state (inside the A button menu of borked NANDs and available for `S:/nand_hdr.bin`). Recommended only for advanced users!
### System file handling
* __Check and fix CMACs (for any file that has them)__: The option will turn up in the A button menu if it is available for a given file (f.e. system savegames, `ticket.db`, etc...). This can also be done for multiple files at once if they are marked.
* __Mount ticket.db files and dump tickets__: Mount the file via the A button menu. Tickets are sorted into `eshop` (stuff from eshop), `system` (system tickets), `unknown` (typically empty) and `hidden` (hidden tickets, found via a deeper scan) categories. All tickets displayed are legit, fake tickets are ignored
* __Inject any NCCH CXI file into Health & Safety__: The option is found inside the A button menu for any NCCH CXI file. NCCH CXIs are found, f.e. inside of CIAs. Keep in mind there is a (system internal) size restriction on H&S injectable apps.
* __Inject and dump GBA VC saves__: Find the options to do this inside the A button menu for `agbsave.bin` in the `S:` drive. Keep in mind that you need to start the specific GBA game on your console before dumping / injecting the save. _To inject a save it needs to be in the clipboard_.
* __Inject and dump GBA VC saves__: Find the options to do this inside the A button menu for `agbsave.bin` in the `S:` drive. Keep in mind that you need to start the specific GBA game on your console before dumping / injecting the save.
* __Dump a copy of boot9, boot11 & your OTP__: This works on sighax, via boot9strap only. These files are found inside the `M:` drive and can be copied from there to any other place.
### Support file handling
@ -173,8 +156,6 @@ With the possibilites GodMode9 provides, not everything may be obvious at first
## License
You may use this under the terms of the GNU General Public License GPL v2 or under the terms of any later revisions of the GPL. Refer to the provided `LICENSE.txt` file for further information.
## Contact info
You can chat directly with us via IRC @ #GodMode9 on [libera.chat](https://web.libera.chat/#GodMode9) or [Discord](https://discord.gg/BRcbvtFxX4)!
## Credits
This tool would not have been possible without the help of numerous people. Thanks go to (in no particular order)...
@ -184,13 +165,9 @@ This tool would not have been possible without the help of numerous people. Than
* **Wolfvak** for ARM11 code, FIRM binary launcher, exception handlers, PCX code, Makefile and for help on countless other occasions
* **SciresM** for helping me figure out RomFS and for boot9strap
* **SciresM**, **Myria**, **Normmatt**, **TuxSH** and **hedgeberg** for figuring out sighax and giving us access to bootrom
* **ihaveamac** for implementing Lua support, and first developing the simple CIA generation method and for being of great help in porting it
* **DarkRTA** for linker support during the implementation of Lua
* **luigoalma** for fixing Lua to compile without issues
* **Gruetzig** for re-implementing the Lua os module
* **ihaveamac** for first developing the simple CIA generation method and for being of great help in porting it
* **wwylele** and **aspargas2** for documenting and implementing the DISA, DIFF, and BDRI formats
* **dratini0** for savefile management, based on [TWLSaveTool](https://github.com/TuxSH/TWLSaveTool/)
* **Pk11** for unicode support and her ongoing work on GodMode9 translations and translation support
* **b1l1s** for helping me figure out A9LH compatibility
* **Gelex** and **AuroraWright** for helping me figure out various things
* **stuckpixel** for the new 6x10 font and help on various things
@ -199,16 +176,12 @@ This tool would not have been possible without the help of numerous people. Than
* **profi200** for always useful advice and helpful hints on various things
* **windows-server-2003** for the initial implementation of if-else-goto in .gm9 scripts
* **Kazuma77** for pushing forward scripting, for testing and for always useful advice
* **TurdPooCharger** for being one of the most meticulous software testers around
* **JaySea**, **YodaDaCoda**, **liomajor**, **Supster131**, **imanoob**, **Kasher_CS** and countless others from freenode #Cakey and the GBAtemp forums for testing, feedback and helpful hints
* **Shadowhand** for being awesome and [hosting my nightlies](https://d0k3.secretalgorithm.com/)
* **Plailect** for putting his trust in my tools and recommending this in [The Guide](https://3ds.guide/)
* **SirNapkin1334** for testing, bug reports and for hosting the original GodMode9 Discord server
* **Lilith Valentine** for testing and helpful advice
* **SirNapkin1334** for testing, bug reports and for hosting the official [GodMode9 Discord channel](https://discord.gg/EGu6Qxw)
* **Project Nayuki** for [qrcodegen](https://github.com/nayuki/QR-Code-generator)
* **Amazingmax fonts** for the Amazdoom font
* **TakWolf** for [fusion-pixel-font](https://github.com/TakWolf/fusion-pixel-font) used for Chinese and Korean
* The fine folks on **the official GodMode9 IRC channel and Discord server**
* The fine folks on **freenode #Cakey**
* All **[3dbrew.org](https://www.3dbrew.org/wiki/Main_Page) editors**
* Everyone I possibly forgot, if you think you deserve to be mentioned, just contact us!
* Everyone I possibly forgot, if you think you deserve to be mentioned, just contact me!

View File

@ -1,17 +1,17 @@
PROCESSOR := ARM11
TARGET := $(shell basename "$(CURDIR)")
TARGET := $(shell basename $(CURDIR))
SOURCE := source
BUILD := build
SUBARCH := -D$(PROCESSOR) -march=armv6k -mtune=mpcore -marm -mfloat-abi=hard -mfpu=vfpv2 -mtp=soft
SUBARCH := -D$(PROCESSOR) -marm -march=armv6k -mtune=mpcore -mfloat-abi=hard -mfpu=vfpv2 -mtp=soft
INCDIRS := source
INCLUDE := $(foreach dir,$(INCDIRS),-I"$(shell pwd)/$(dir)")
ASFLAGS += $(SUBARCH) $(INCLUDE)
CFLAGS += $(SUBARCH) $(INCLUDE) -flto
LDFLAGS += $(SUBARCH) -Wl,--use-blx,-Map,$(TARGET).map -flto
LDFLAGS += $(SUBARCH) -Wl,-Map,$(TARGET).map -flto
include ../Makefile.common
include ../Makefile.build

View File

@ -4,19 +4,28 @@ ENTRY(__boot)
MEMORY
{
AXIWRAM (RWX) : ORIGIN = 0x1FF80000, LENGTH = 96K
AXIWRAM (RWX) : ORIGIN = 0x1FF80000, LENGTH = 128K
HIGHRAM (RWX) : ORIGIN = 0xFFFF0000, LENGTH = 4K
}
SECTIONS
{
.vector : ALIGN(4K)
{
__vector_pa = LOADADDR(.vector);
__vector_va = ABSOLUTE(.);
KEEP(*(.vector))
. = ALIGN(4K);
__vector_len = . - __vector_va;
} >HIGHRAM AT>AXIWRAM
.text : ALIGN(4K)
{
__text_pa = LOADADDR(.text);
__text_va = ABSOLUTE(.);
*(.text*)
. = ALIGN(4K);
__text_va_end = .;
__text_len = . - __text_va;
} >AXIWRAM
.data : ALIGN(4K)
@ -25,7 +34,7 @@ SECTIONS
__data_va = ABSOLUTE(.);
*(.data*)
. = ALIGN(4K);
__data_va_end = .;
__data_len = . - __data_va;
} >AXIWRAM
.rodata : ALIGN(4K)
@ -34,16 +43,7 @@ SECTIONS
__rodata_va = ABSOLUTE(.);
*(.rodata*)
. = ALIGN(4K);
__rodata_va_end = .;
} >AXIWRAM
.shared (NOLOAD) : ALIGN(4K)
{
__shared_pa = LOADADDR(.shared);
__shared_va = ABSOLUTE(.);
*(.shared*)
. = ALIGN(4K);
__shared_va_end = .;
__rodata_len = . - __rodata_va;
} >AXIWRAM
.bss (NOLOAD) : ALIGN(4K)
@ -52,6 +52,6 @@ SECTIONS
__bss_va = ABSOLUTE(.);
*(.bss*)
. = ALIGN(4K);
__bss_va_end = .;
__bss_len = . - __bss_va;
} >AXIWRAM
}

View File

@ -1,219 +1,217 @@
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
// kinda hardcoded and all over the place, but it needs to stay simple
#include <types.h>
#include <arm.h>
#include <vram.h>
static const u8 num_font[16*8];
#define SCREEN ((u16*)(VRAM_TOP_LA))
void draw_char(u16 *fb, int c, int x, int y)
{
for (int _y = 0; _y < 8; _y++) {
for (int _x = 0; _x < 8; _x++) {
u16 *fbpos = fb + (240 - (y + _y)) + (240 * (x + _x));
u8 mask = (num_font[(c * 8) + _y] >> (8 - _x)) & 1;
if (mask)
*fbpos = ~0;
else
*fbpos = 0;
}
}
}
void draw_hex(u16 *fb, u32 num, int x, int y)
{
x += 7*8;
for (int i = 0; i < 8; i++) {
draw_char(fb, num & 0xf, x, y);
num >>= 4;
x -= 8;
}
}
void do_exception(u32 type, u32 *regs)
{
for (int i = 0; i < 400*240; i++)
SCREEN[i] = 0;
draw_hex(SCREEN, type, 8, 16);
for (int i = 0; i < 20; i += 2) {
draw_hex(SCREEN, i, 8, 32 + (i * 4));
draw_hex(SCREEN, regs[i], 80, 32 + (i * 4));
draw_hex(SCREEN, i + 1, 208, 32 + (i * 4));
draw_hex(SCREEN, regs[i + 1], 280, 32 + (i * 4));
}
while(1)
ARM_WFI();
}
static const u8 num_font[] = {
0b00000000,
0b00011000,
0b00100100,
0b00101100,
0b00110100,
0b00100100,
0b00011000,
0b00000000, // 0
0b00000000,
0b00011000,
0b00101000,
0b00001000,
0b00001000,
0b00001000,
0b00111100,
0b00000000, // 1
0b00000000,
0b00011000,
0b00100100,
0b00000100,
0b00001000,
0b00010000,
0b00111100,
0b00000000, // 2
0b00000000,
0b00111000,
0b00000100,
0b00011000,
0b00000100,
0b00000100,
0b00111000,
0b00000000, // 3
0b00000000,
0b00100100,
0b00100100,
0b00111100,
0b00000100,
0b00000100,
0b00000100,
0b00000000, // 4
0b00000000,
0b00111100,
0b00100000,
0b00111000,
0b00000100,
0b00000100,
0b00111000,
0b00000000, // 5
0b00000000,
0b00011100,
0b00100000,
0b00111000,
0b00100100,
0b00100100,
0b00011000,
0b00000000, // 6
0b00000000,
0b00111100,
0b00000100,
0b00000100,
0b00001000,
0b00010000,
0b00010000,
0b00000000, // 7
0b00000000,
0b00011000,
0b00100100,
0b00011000,
0b00100100,
0b00100100,
0b00011000,
0b00000000, // 8
0b00000000,
0b00011000,
0b00100100,
0b00011100,
0b00000100,
0b00000100,
0b00111000,
0b00000000, // 9
0b00000000,
0b00011000,
0b00100100,
0b00111100,
0b00100100,
0b00100100,
0b00100100,
0b00000000, // A
0b00000000,
0b00111000,
0b00100100,
0b00111000,
0b00100100,
0b00100100,
0b00111000,
0b00000000, // B
0b00000000,
0b00011100,
0b00100000,
0b00100000,
0b00100000,
0b00100000,
0b00011100,
0b00000000, // C
0b00000000,
0b00110000,
0b00101000,
0b00100100,
0b00100100,
0b00101000,
0b00110000,
0b00000000, // C
0b00000000,
0b00111100,
0b00100000,
0b00111100,
0b00100000,
0b00100000,
0b00111100,
0b00000000, // E
0b00000000,
0b00111100,
0b00100000,
0b00111100,
0b00100000,
0b00100000,
0b00100000,
0b00000000, // F
};
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#include <types.h>
#include <arm.h>
#include <vram.h>
static const u8 num_font[16*8];
#define SCREEN ((u16*)(VRAM_TOP_LA))
void draw_char(u16 *fb, int c, int x, int y)
{
for (int _y = 0; _y < 8; _y++) {
for (int _x = 0; _x < 8; _x++) {
u16 *fbpos = fb + (240 - (y + _y)) + (240 * (x + _x));
u8 mask = (num_font[(c * 8) + _y] >> (8 - _x)) & 1;
if (mask)
*fbpos = ~0;
else
*fbpos = 0;
}
}
}
void draw_hex(u16 *fb, u32 num, int x, int y)
{
x += 7*8;
for (int i = 0; i < 8; i++) {
draw_char(fb, num & 0xf, x, y);
num >>= 4;
x -= 8;
}
}
void do_exception(u32 type, u32 *regs)
{
for (int i = 0; i < 400*240; i++)
SCREEN[i] = 0;
draw_hex(SCREEN, type, 8, 16);
for (int i = 0; i < 20; i += 2) {
draw_hex(SCREEN, i, 8, 32 + (i * 4));
draw_hex(SCREEN, regs[i], 80, 32 + (i * 4));
draw_hex(SCREEN, i + 1, 208, 32 + (i * 4));
draw_hex(SCREEN, regs[i + 1], 280, 32 + (i * 4));
}
while(1)
ARM_WFI();
}
static const u8 num_font[] = {
0b00000000,
0b00011000,
0b00100100,
0b00101100,
0b00110100,
0b00100100,
0b00011000,
0b00000000, // 0
0b00000000,
0b00011000,
0b00101000,
0b00001000,
0b00001000,
0b00001000,
0b00111100,
0b00000000, // 1
0b00000000,
0b00011000,
0b00100100,
0b00000100,
0b00001000,
0b00010000,
0b00111100,
0b00000000, // 2
0b00000000,
0b00111000,
0b00000100,
0b00011000,
0b00000100,
0b00000100,
0b00111000,
0b00000000, // 3
0b00000000,
0b00100100,
0b00100100,
0b00111100,
0b00000100,
0b00000100,
0b00000100,
0b00000000, // 4
0b00000000,
0b00111100,
0b00100000,
0b00111000,
0b00000100,
0b00000100,
0b00111000,
0b00000000, // 5
0b00000000,
0b00011100,
0b00100000,
0b00111000,
0b00100100,
0b00100100,
0b00011000,
0b00000000, // 6
0b00000000,
0b00111100,
0b00000100,
0b00000100,
0b00001000,
0b00010000,
0b00010000,
0b00000000, // 7
0b00000000,
0b00011000,
0b00100100,
0b00011000,
0b00100100,
0b00100100,
0b00011000,
0b00000000, // 8
0b00000000,
0b00011000,
0b00100100,
0b00011100,
0b00000100,
0b00000100,
0b00111000,
0b00000000, // 9
0b00000000,
0b00011000,
0b00100100,
0b00111100,
0b00100100,
0b00100100,
0b00100100,
0b00000000, // A
0b00000000,
0b00111000,
0b00100100,
0b00111000,
0b00100100,
0b00100100,
0b00111000,
0b00000000, // B
0b00000000,
0b00011100,
0b00100000,
0b00100000,
0b00100000,
0b00100000,
0b00011100,
0b00000000, // C
0b00000000,
0b00110000,
0b00101000,
0b00100100,
0b00100100,
0b00101000,
0b00110000,
0b00000000, // C
0b00000000,
0b00111100,
0b00100000,
0b00111100,
0b00100000,
0b00100000,
0b00111100,
0b00000000, // E
0b00000000,
0b00111100,
0b00100000,
0b00111100,
0b00100000,
0b00100000,
0b00100000,
0b00000000, // F
};

View File

@ -16,21 +16,17 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <common.h>
#include <types.h>
#include <arm.h>
#include <stdatomic.h>
#include "arm/gic.h"
#include "system/event.h"
/* Generic Interrupt Controller Registers */
#define REG_GIC(cpu, o, t) REG_ARM_PMR(0x200 + ((cpu) * 0x100) + (o), t)
#define REG_GIC_CONTROL(c) (*REG_GIC(c, 0x00, u32))
#define REG_GIC_PRIOMASK(c) (*REG_GIC(c, 0x04, u32))
#define REG_GIC_POI(c) (*REG_GIC(c, 0x08, u32))
#define REG_GIC_POI(c) (*REG_GIC(c, 0x08, u32))
#define REG_GIC_IRQACK(c) (*REG_GIC(c, 0x0C, u32))
#define REG_GIC_IRQEND(c) (*REG_GIC(c, 0x10, u32))
#define REG_GIC_LASTPRIO(c) (*REG_GIC(c, 0x14, u32))
@ -42,259 +38,185 @@
/* Interrupt Distributor Registers */
#define REG_DIC(off, type) REG_ARM_PMR(0x1000 + (off), type)
#define REG_DIC_CONTROL (*REG_DIC(0x00, u32))
#define REG_DIC_TYPE (*REG_DIC(0x04, u32))
#define REG_DIC_SETENABLE REG_DIC(0x100, u32) // 32 intcfg per reg
#define REG_DIC_CONTROL (*REG_DIC(0x00, u32))
#define REG_DIC_TYPE (*REG_DIC(0x04, u32))
#define REG_DIC_SETENABLE REG_DIC(0x100, u32)
#define REG_DIC_CLRENABLE REG_DIC(0x180, u32)
#define REG_DIC_SETPENDING REG_DIC(0x200, u32)
#define REG_DIC_CLRPENDING REG_DIC(0x280, u32)
#define REG_DIC_PRIORITY REG_DIC(0x400, u8) // 1 intcfg per reg (in upper 4 bits)
#define REG_DIC_TARGETCPU REG_DIC(0x800, u8) // 1 intcfg per reg
#define REG_DIC_CFGREG REG_DIC(0xC00, u32) // 16 intcfg per reg
#define REG_DIC_SOFTINT (*REG_DIC(0xF00, u32))
// used only on reset routines
#define REG_DIC_PRIORITY32 REG_DIC(0x400, u32) // 4 intcfg per reg (in upper 4 bits)
#define REG_DIC_TARGETCPU32 REG_DIC(0x800, u32) // 4 intcfg per reg
#define GIC_PRIO_NEVER32 \
(GIC_PRIO_NEVER | (GIC_PRIO_NEVER << 8) | \
(GIC_PRIO_NEVER << 16) | (GIC_PRIO_NEVER << 24))
#define GIC_PRIO_HIGH32 \
(GIC_PRIO_HIGHEST | (GIC_PRIO_HIGHEST << 8) | \
(GIC_PRIO_HIGHEST << 16) | (GIC_PRIO_HIGHEST << 24))
/* CPU source ID is present in Interrupt Acknowledge register? */
#define IRQN_SRC_MASK (0x7 << 10)
#define REG_DIC_PRIORITY REG_DIC(0x400, u8)
#define REG_DIC_TARGETPROC REG_DIC(0x800, u8)
#define REG_DIC_CFGREG REG_DIC(0xC00, u32)
#define REG_DIC_SOFTINT (*REG_DIC(0xF00, u32))
/* Interrupt Handling */
#define LOCAL_IRQS (32)
#define DIC_MAX_IRQ (LOCAL_IRQS + MAX_IRQ)
#define COREMASK_VALID(x) (((x) > 0) && ((x) < BIT(MAX_CPU)))
#define IRQN_IS_LOCAL(n) ((n) < LOCAL_IRQS)
#define IRQN_IS_VALID(n) ((n) < DIC_MAX_IRQ)
static gicIrqHandler gicIrqHandlers[DIC_MAX_IRQ];
static _Atomic(u32) gicIrqPending[DIC_MAX_IRQ / 32];
#define LOCAL_IRQ_OFF(c, n) (((c) * LOCAL_IRQS) + (n))
#define GLOBAL_IRQ_OFF(n) (((MAX_CPU-1) * LOCAL_IRQS) + (n))
#define IRQ_TABLE_OFF(c, n) \
(IRQN_IS_LOCAL(n) ? LOCAL_IRQ_OFF((c), (n)) : GLOBAL_IRQ_OFF(n))
static struct {
u8 tgt;
u8 prio;
} gicIrqConfig[DIC_MAX_IRQ];
static IRQ_Handler IRQ_Handlers[IRQ_TABLE_OFF(0, MAX_IRQ)];
// gets used whenever a NULL pointer is passed to gicEnableInterrupt
static void gicDummyHandler(u32 irqn) { (void)irqn; return; }
static const struct {
u8 low, high, mode;
} gicDefaultIrqCfg[] = {
{ .low = 0x00, .high = 0x1F, .mode = GIC_RISINGEDGE_NN },
{ .low = 0x20, .high = 0x23, .mode = GIC_LEVELHIGH_1N },
{ .low = 0x24, .high = 0x24, .mode = GIC_RISINGEDGE_1N },
{ .low = 0x25, .high = 0x27, .mode = GIC_LEVELHIGH_1N },
{ .low = 0x28, .high = 0x2D, .mode = GIC_RISINGEDGE_1N },
{ .low = 0x30, .high = 0x3B, .mode = GIC_LEVELHIGH_1N },
{ .low = 0x40, .high = 0x4E, .mode = GIC_RISINGEDGE_1N },
{ .low = 0x4F, .high = 0x4F, .mode = GIC_LEVELHIGH_1N },
{ .low = 0x50, .high = 0x57, .mode = GIC_RISINGEDGE_1N },
{ .low = 0x58, .high = 0x58, .mode = GIC_LEVELHIGH_1N },
{ .low = 0x59, .high = 0x75, .mode = GIC_RISINGEDGE_1N },
{ .low = 0x76, .high = 0x77, .mode = GIC_LEVELHIGH_1N },
{ .low = 0x78, .high = 0x78, .mode = GIC_RISINGEDGE_1N },
{ .low = 0x79, .high = 0x7d, .mode = GIC_LEVELHIGH_1N },
};
static u8 gicGetDefaultIrqCfg(u32 irqn) {
for (unsigned i = 0; i < countof(gicDefaultIrqCfg); i++) {
if ((irqn >= gicDefaultIrqCfg[i].low) && (irqn <= gicDefaultIrqCfg[i].high))
return gicDefaultIrqCfg[i].mode;
static IRQ_Handler GIC_GetCB(u32 irqn)
{
irqn &= ~(15 << 10); // clear source CPU bits
if (IRQN_IS_VALID(irqn)) {
return IRQ_Handlers[IRQ_TABLE_OFF(ARM_CoreID(), irqn)];
} else {
// Possibly have a dummy handler function that
// somehow notifies of an unhandled interrupt?
return NULL;
}
// TODO: would it be considerably faster to use bsearch?
return GIC_RISINGEDGE_1N;
}
void gicTopHandler(void)
static void GIC_SetCB(u32 irqn, u32 cpu, IRQ_Handler handler)
{
if (IRQN_IS_VALID(irqn)) {
IRQ_Handlers[IRQ_TABLE_OFF(cpu, irqn)] = handler;
}
}
static void GIC_ClearCB(u32 irqn, u32 cpu)
{
GIC_SetCB(irqn, cpu, NULL);
}
void GIC_MainHandler(void)
{
while(1) {
u32 irqn, irqsource, index, mask;
/**
If more than one of these CPUs reads the Interrupt Acknowledge Register at the
same time, they can all acknowledge the same interrupt. The interrupt service
routine must ensure that only one of them tries to process the interrupt, with the
others returning after writing the ID to the End of Interrupt Register.
*/
irqsource = REG_GIC_IRQACK(GIC_THIS_CPU_ALIAS);
if (irqsource == GIC_IRQ_SPURIOUS) // no further processing is needed
IRQ_Handler handler;
u32 irqn = REG_GIC_IRQACK(GIC_THIS_CPU_ALIAS);
if (irqn == GIC_IRQ_SPURIOUS)
break;
irqn = irqsource & ~IRQN_SRC_MASK;
handler = GIC_GetCB(irqn);
if (handler != NULL)
handler(irqn);
index = irqn / 32;
mask = BIT(irqn % 32);
atomic_fetch_or(&gicIrqPending[index], mask);
(gicIrqHandlers[irqn])(irqsource);
// if the id is < 16, the source CPU can be obtained from irqn
// if the handler isn't set, it'll try to branch to 0 and trigger a prefetch abort
REG_GIC_IRQEND(GIC_THIS_CPU_ALIAS) = irqsource;
REG_GIC_IRQEND(GIC_THIS_CPU_ALIAS) = irqn;
}
}
void gicGlobalReset(void)
void GIC_GlobalReset(void)
{
u32 dic_type;
unsigned gicn, intn;
int gicn, intn;
dic_type = REG_DIC_TYPE;
// Number of local controllers
gicn = ((REG_DIC_TYPE >> 5) & 3) + 1;
// number of local controllers
gicn = ((dic_type >> 5) & 3) + 1;
// Number of interrupt lines (up to 224 external + 32 fixed internal)
intn = ((REG_DIC_TYPE & 7) + 1) << 5;
// number of interrupt lines (up to 224 external + 32 fixed internal per CPU)
intn = ((dic_type & 7) + 1) * 32;
// clamp it down to the amount of CPUs designed to handle
if (gicn > MAX_CPU)
gicn = MAX_CPU;
// clear the interrupt handler and config table
getEventIRQ()->reset();
memset(gicIrqHandlers, 0, sizeof(gicIrqHandlers));
memset(gicIrqConfig, 0, sizeof(gicIrqConfig));
// Clear the interrupt table
for (unsigned int i = 0; i < sizeof(IRQ_Handlers)/sizeof(*IRQ_Handlers); i++)
IRQ_Handlers[i] = NULL;
// disable all MP11 GICs
for (unsigned i = 0; i < gicn; i++)
// Disable all MP11 GICs
for (int i = 0; i < gicn; i++)
REG_GIC_CONTROL(i) = 0;
// disable the main DIC
// Disable the main DIC
REG_DIC_CONTROL = 0;
// clear all external interrupts
for (unsigned i = 1; i < (intn / 32); i++) {
// Clear all DIC interrupts
for (int i = 1; i < (intn / 32); i++) {
REG_DIC_CLRENABLE[i] = ~0;
REG_DIC_CLRPENDING[i] = ~0;
}
// reset all external priorities to highest by default
// clear target processor regs
for (unsigned i = 4; i < (intn / 4); i++) {
REG_DIC_PRIORITY32[i] = GIC_PRIO_HIGH32;
REG_DIC_TARGETCPU32[i] = 0;
// Reset all DIC priorities to lowest and clear target processor regs
for (int i = 32; i < intn; i++) {
REG_DIC_PRIORITY[i] = 0;
REG_DIC_TARGETPROC[i] = 0;
}
// set all interrupts to active level triggered in N-N model
for (unsigned i = 16; i < (intn / 16); i++)
REG_DIC_CFGREG[i] = 0;
// Set all interrupts to rising edge triggered and 1-N model
for (int i = 2; i < (intn / 16); i++)
REG_DIC_CFGREG[i] = ~0;
// re enable the main DIC
// Enable the main DIC
REG_DIC_CONTROL = 1;
for (unsigned i = 0; i < gicn; i++) {
// compare all priority bits
for (int i = 0; i < gicn; i++) {
// Compare all priority bits
REG_GIC_POI(i) = 3;
// don't mask any interrupt with low priority
// Don't mask any interrupt with low priority
REG_GIC_PRIOMASK(i) = 0xF0;
// enable all the MP11 GICs
// Enable the MP11 GIC
REG_GIC_CONTROL(i) = 1;
}
}
void gicLocalReset(void)
void GIC_LocalReset(void)
{
u32 irq_s;
// disable all local interrupts
// Clear out local interrupt configuration bits
REG_DIC_CLRENABLE[0] = ~0;
REG_DIC_CLRPENDING[0] = ~0;
for (unsigned i = 0; i < 4; i++) {
REG_DIC_PRIORITY32[i] = GIC_PRIO_HIGH32;
// local IRQs are always unmasked by default
// REG_DIC_TARGETCPU[i] = 0;
// not needed, always read as corresponding MP11 core
for (int i = 0; i < 32; i++) {
REG_DIC_PRIORITY[i] = 0;
REG_DIC_TARGETPROC[i] = 0;
}
// ack until it gets a spurious IRQ
for (int i = 0; i < 2; i++)
REG_DIC_CFGREG[i] = ~0;
// Acknowledge until it gets a spurious IRQ
do {
irq_s = REG_GIC_PENDING(GIC_THIS_CPU_ALIAS);
REG_GIC_IRQEND(GIC_THIS_CPU_ALIAS) = irq_s;
} while(irq_s != GIC_IRQ_SPURIOUS);
}
static void gicSetIrqCfg(u32 irqn) {
u32 smt, cfg;
smt = irqn & 15;
cfg = REG_DIC_CFGREG[irqn / 16];
cfg &= ~(3 << smt);
cfg |= gicGetDefaultIrqCfg(irqn) << smt;
REG_DIC_CFGREG[irqn / 16] = cfg;
}
void gicSetInterruptConfig(u32 irqn, u32 coremask, u32 prio, gicIrqHandler handler)
int GIC_Enable(u32 irqn, u32 coremask, u32 prio, IRQ_Handler handler)
{
if (handler == NULL) // maybe add runtime ptr checks here too?
handler = gicDummyHandler;
if (!IRQN_IS_VALID(irqn))
return -1;
gicIrqConfig[irqn].tgt = coremask;
gicIrqConfig[irqn].prio = prio;
gicIrqHandlers[irqn] = handler;
// in theory this should be replaced by a faster CLZ lookup
// in practice, meh, MAX_CPU will only be 2 anyway...
for (int i = 0; i < MAX_CPU; i++) {
if (coremask & BIT(i))
GIC_SetCB(irqn, i, handler);
}
REG_DIC_CLRPENDING[irqn >> 5] |= BIT(irqn & 0x1F);
REG_DIC_SETENABLE[irqn >> 5] |= BIT(irqn & 0x1F);
REG_DIC_PRIORITY[irqn] = prio << 4;
REG_DIC_TARGETPROC[irqn] = coremask;
return 0;
}
void gicClearInterruptConfig(u32 irqn)
int GIC_Disable(u32 irqn, u32 coremask)
{
memset(&gicIrqConfig[irqn], 0, sizeof(gicIrqConfig[irqn]));
gicIrqHandlers[irqn] = NULL;
if (irqn >= MAX_IRQ)
return -1;
for (int i = 0; i < MAX_CPU; i++) {
if (coremask & BIT(i))
GIC_ClearCB(irqn, i);
}
REG_DIC_CLRPENDING[irqn >> 5] |= BIT(irqn & 0x1F);
REG_DIC_CLRENABLE[irqn >> 5] |= BIT(irqn & 0x1F);
REG_DIC_TARGETPROC[irqn] = 0;
return 0;
}
void gicEnableInterrupt(u32 irqn)
void GIC_TriggerSoftIRQ(u32 irqn, u32 mode, u32 coremask)
{
REG_DIC_PRIORITY[irqn] = gicIrqConfig[irqn].prio;
REG_DIC_TARGETCPU[irqn] = gicIrqConfig[irqn].tgt;
gicSetIrqCfg(irqn);
REG_DIC_CLRPENDING[irqn / 32] |= BIT(irqn & 0x1F);
REG_DIC_SETENABLE[irqn / 32] |= BIT(irqn & 0x1F);
}
void gicDisableInterrupt(u32 irqn)
{
REG_DIC_CLRENABLE[irqn / 32] |= BIT(irqn & 0x1F);
REG_DIC_CLRPENDING[irqn / 32] |= BIT(irqn & 0x1F);
}
void gicTriggerSoftInterrupt(u32 softirq)
{
REG_DIC_SOFTINT = softirq;
}
static void irqEvReset(void) {
memset(&gicIrqPending, 0, sizeof(gicIrqPending));
}
static u32 irqEvTest(u32 param, u32 clear) {
u32 index, tstmask, clrmask;
if (param >= DIC_MAX_IRQ)
bkpt;
index = param / 32;
tstmask = BIT(param % 32);
clrmask = clear ? tstmask : 0;
return !!(atomic_fetch_and(&gicIrqPending[index], ~clrmask) & tstmask);
}
static const EventInterface evIRQ = {
.reset = irqEvReset,
.test = irqEvTest
};
const EventInterface *getEventIRQ(void) {
return &evIRQ;
REG_DIC_SOFTINT = (mode << 24) | (coremask << 16) | irqn;
}

View File

@ -1,6 +1,6 @@
/*
* This file is part of GodMode9
* Copyright (C) 2017-2020 Wolfvak
* Copyright (C) 2017-2019 Wolfvak
*
* 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
@ -17,96 +17,28 @@
*/
#pragma once
#include <types.h>
#include <common.h>
#include <arm.h>
typedef void (*gicIrqHandler)(u32 irqn);
enum {
GIC_LEVELHIGH_NN = 0, // no interrupts use level high triggers so far
GIC_LEVELHIGH_1N = 1,
GIC_RISINGEDGE_NN = 2,
GIC_RISINGEDGE_1N = 3
// With the 1-N model, an interrupt that is taken on any CPU clears the Pending
// status on all CPUs.
// With the N-N model, all CPUs receive the interrupt independently. The Pending
// status is cleared only for the CPU that takes it, not for the other CPUs
};
enum {
GIC_PRIO0 = 0x00,
GIC_PRIO1 = 0x10,
GIC_PRIO2 = 0x20,
GIC_PRIO3 = 0x30,
GIC_PRIO4 = 0x40,
GIC_PRIO5 = 0x50,
GIC_PRIO6 = 0x60,
GIC_PRIO7 = 0x70,
GIC_PRIO14 = 0xE0,
GIC_PRIO15 = 0xF0,
};
#define GIC_PRIO_HIGHEST GIC_PRIO0
#define GIC_PRIO_LOWEST GIC_PRIO14
#define GIC_PRIO_NEVER GIC_PRIO15
void gicGlobalReset(void);
void gicLocalReset(void);
/*
Notes from https://static.docs.arm.com/ddi0360/f/DDI0360F_arm11_mpcore_r2p0_trm.pdf
INTERRUPT ENABLE:
Interrupts 0-15 fields are read as one, that is, always enabled, and write to these fields
have no effect.
Notpresent interrupts (depending on the Interrupt Controller Type Register and
interrupt number field) related fields are read as zero and writes to these fields have no
effect.
INTERRUPT PRIORITY:
The first four registers are aliased for each MP11 CPU, that is, the priority set for
ID0-15 and ID29-31 can be different for each MP11 CPU. The priority of IPIs ID0-15
depends on the receiving CPU, not the sending CPU.
INTERRUPT CPU TARGET:
For MP11 CPU n, CPU targets 29, 30 and 31 are read as (1 << n). Writes are ignored.
For IT0-IT28, these fields are read as zero and writes are ignored.
INTERRUPT CONFIGURATION:
For ID0-ID15, bit 1 of the configuration pair is always read as one, that is, rising edge
sensitive.
For ID0-ID15, bit 0 (software model) can be configured and applies to the interrupts
sent from the writing MP11 CPU.
For ID29, and ID30, the configuration pair is always read as b10, that is rising edge
sensitive and N-N software model because these IDs are allocated to timer and
watchdog interrupts that are CPU-specific
*/
#define COREMASK_ALL (BIT(MAX_CPU) - 1)
void gicSetInterruptConfig(u32 irqn, u32 coremask, u32 prio, gicIrqHandler handler);
void gicClearInterruptConfig(u32 irqn);
void gicEnableInterrupt(u32 irqn);
void gicDisableInterrupt(u32 irqn);
enum {
GIC_SOFTIRQ_LIST = 0,
GIC_SOFTIRQ_OTHERS = 1, // all except self
GIC_SOFTIRQ_SELF = 2,
};
typedef void (*IRQ_Handler)(u32 irqn);
#define GIC_SOFTIRQ_SOURCE(n) (((n) >> 10) & 0xF)
#define GIC_SOFTIRQ_ID(n) ((n) & 0x3FF)
#define GIC_SOFTIRQ_NUMBER(n) ((n) & 0x3FF)
#define GIC_SOFTIRQ_FMT(id, filter, coremask) \
((id) | ((coremask) << 16) | ((filter) << 24))
// id & 0xf, coremask & 3, filter & 3
// coremask is only used with filter == GIC_SOFTIRQ_LIST
enum {
GIC_SOFTIRQ_NORMAL = 0,
GIC_SOFTIRQ_NOTSELF = 1,
GIC_SOFTIRQ_SELF = 2
};
#define GIC_SOFTIRQ_SRC(x) (((x) >> 10) % MAX_CPU)
enum {
GIC_HIGHEST_PRIO = 0x0,
GIC_LOWEST_PRIO = 0xE,
};
void gicTriggerSoftInterrupt(u32 softirq);
void GIC_GlobalReset(void);
void GIC_LocalReset(void);
int GIC_Enable(u32 irqn, u32 coremask, u32 prio, IRQ_Handler handler);
int GIC_Disable(u32 irqn, u32 coremask);
void GIC_TriggerSoftIRQ(u32 irqn, u32 mode, u32 coremask);

View File

@ -54,7 +54,7 @@
#define DESCRIPTOR_TYPE_MASK (3)
enum {
enum DescriptorType {
L1_UNMAPPED,
L1_COARSE,
L1_SECTION,
@ -67,61 +67,76 @@ enum {
typedef struct {
u32 desc[4096];
} __attribute__((aligned(16384))) mmuLevel1Table;
} __attribute__((aligned(16384))) MMU_Lvl1_Table;
typedef struct {
u32 desc[256];
} __attribute__((aligned(1024))) mmuLevel2Table;
} __attribute__((aligned(1024))) MMU_Lvl2_Table;
static mmuLevel1Table mmuGlobalTT;
static MMU_Lvl1_Table MMU_Lvl1_TT;
// simple watermark allocator for 2nd level page tables
#define MAX_SECOND_LEVEL (8)
static mmuLevel2Table mmuCoarseTables[MAX_SECOND_LEVEL];
static u32 mmuCoarseAllocated = 0;
static mmuLevel2Table *mmuAllocateLevel2Table(void)
/* function to allocate 2nd level page tables */
#define MAX_SECOND_LEVEL (4)
static MMU_Lvl2_Table Lvl2_Tables[MAX_SECOND_LEVEL];
static u32 Lvl2_Allocated = 0;
static MMU_Lvl2_Table *Alloc_Lvl2(void)
{
return &mmuCoarseTables[mmuCoarseAllocated++];
if (Lvl2_Allocated == MAX_SECOND_LEVEL)
return NULL;
return &Lvl2_Tables[Lvl2_Allocated++];
}
// functions to convert from internal page flag format to ARM
/* functions to convert from internal page flag format to ARM */
// {TEX, CB} pairs
static const u8 mmuTypeLUT[MMU_MEMORY_TYPES][2] = {
[MMU_STRONG_ORDER] = {0, 0},
[MMU_UNCACHEABLE] = {1, 0},
[MMU_DEV_SHARED] = {0, 1},
[MMU_DEV_NONSHARED] = {2, 0},
[MMU_CACHE_WT] = {0, 2},
[MMU_CACHE_WB] = {1, 3},
[MMU_CACHE_WBA] = {1, 3},
/* {TEX, CB} */
static const u8 MMU_TypeLUT[MEMORY_TYPES][2] = {
[STRONGLY_ORDERED] = {0, 0},
[NON_CACHEABLE] = {1, 0},
[DEVICE_SHARED] = {0, 1},
[DEVICE_NONSHARED] = {2, 0},
[CACHED_WT] = {0, 2},
[CACHED_WB] = {1, 3},
[CACHED_WB_ALLOC] = {1, 3},
};
static u32 mmuGetTEX(u32 f)
{ return mmuTypeLUT[MMU_FLAGS_TYPE(f)][0]; }
static u32 mmuGetCB(u32 f)
{ return mmuTypeLUT[MMU_FLAGS_TYPE(f)][1]; }
static u32 mmuGetNX(u32 f)
{ return MMU_FLAGS_NOEXEC(f) ? 1 : 0; }
static u32 mmuGetShared(u32 f)
{ return MMU_FLAGS_SHARED(f) ? 1 : 0; }
// access permissions
static const u8 mmuAccessLUT[MMU_ACCESS_TYPES] = {
[MMU_NO_ACCESS] = 0,
[MMU_READ_ONLY] = 0x21,
[MMU_READ_WRITE] = 0x01,
};
static u32 mmuGetAP(u32 f)
{ return mmuAccessLUT[MMU_FLAGS_ACCESS(f)]; }
// other misc helper functions
static unsigned mmuWalkTT(u32 va)
static u32 MMU_GetTEX(u32 f)
{
mmuLevel2Table *coarsepd;
u32 desc = mmuGlobalTT.desc[L1_VA_IDX(va)];
return MMU_TypeLUT[MMU_FLAGS_TYPE(f)][0];
}
static u32 MMU_GetCB(u32 f)
{
return MMU_TypeLUT[MMU_FLAGS_TYPE(f)][1];
}
static u32 MMU_GetAP(u32 f)
{
switch(MMU_FLAGS_ACCESS(f)) {
default:
case NO_ACCESS:
return 0;
case READ_ONLY:
return 0x21;
case READ_WRITE:
return 0x01;
}
}
static u32 MMU_GetNX(u32 f)
{
return MMU_FLAGS_NOEXEC(f) ? 1 : 0;
}
static u32 MMU_GetShared(u32 f)
{
return MMU_FLAGS_SHARED(f) ? 1 : 0;
}
static enum DescriptorType MMU_WalkTT(u32 va)
{
MMU_Lvl2_Table *coarsepd;
u32 desc = MMU_Lvl1_TT.desc[L1_VA_IDX(va)];
switch(desc & DESCRIPTOR_TYPE_MASK) {
case DESCRIPTOR_L1_UNMAPPED:
@ -137,7 +152,7 @@ static unsigned mmuWalkTT(u32 va)
return L1_RESERVED;
}
coarsepd = (mmuLevel2Table*)(desc & COARSE_MASK);
coarsepd = (MMU_Lvl2_Table*)(desc & COARSE_MASK);
desc = coarsepd->desc[L2_VA_IDX(va)];
switch(desc & DESCRIPTOR_TYPE_MASK) {
@ -154,20 +169,21 @@ static unsigned mmuWalkTT(u32 va)
}
}
static mmuLevel2Table *mmuCoarseFix(u32 va)
static MMU_Lvl2_Table *MMU_CoarseFix(u32 va)
{
u32 type;
mmuLevel2Table *coarsepd;
enum DescriptorType type;
MMU_Lvl2_Table *coarsepd;
type = mmuWalkTT(va);
type = MMU_WalkTT(va);
switch(type) {
case L1_UNMAPPED:
coarsepd = mmuAllocateLevel2Table();
mmuGlobalTT.desc[L1_VA_IDX(va)] = (u32)coarsepd | DESCRIPTOR_L1_COARSE;
coarsepd = Alloc_Lvl2();
if (coarsepd != NULL)
MMU_Lvl1_TT.desc[L1_VA_IDX(va)] = (u32)coarsepd | DESCRIPTOR_L1_COARSE;
break;
case L2_UNMAPPED:
coarsepd = (mmuLevel2Table*)(mmuGlobalTT.desc[L1_VA_IDX(va)] & COARSE_MASK);
coarsepd = (MMU_Lvl2_Table*)(MMU_Lvl1_TT.desc[L1_VA_IDX(va)] & COARSE_MASK);
break;
default:
@ -180,91 +196,122 @@ static mmuLevel2Table *mmuCoarseFix(u32 va)
/* Sections */
static u32 mmuSectionFlags(u32 f)
{ // converts the internal format to the hardware L1 section format
return (mmuGetShared(f) << 16) | (mmuGetTEX(f) << 12) |
(mmuGetAP(f) << 10) | (mmuGetNX(f) << 4) |
(mmuGetCB(f) << 2) | DESCRIPTOR_L1_SECTION;
static u32 MMU_SectionFlags(u32 f)
{
return (MMU_GetShared(f) << 16) | (MMU_GetTEX(f) << 12) |
(MMU_GetAP(f) << 10) | (MMU_GetNX(f) << 4) |
(MMU_GetCB(f) << 2) | DESCRIPTOR_L1_SECTION;
}
static void mmuMapSection(u32 va, u32 pa, u32 flags)
static bool MMU_MapSection(u32 va, u32 pa, u32 flags)
{
mmuGlobalTT.desc[L1_VA_IDX(va)] = pa | mmuSectionFlags(flags);
enum DescriptorType type = MMU_WalkTT(va);
if (type == L1_UNMAPPED) {
MMU_Lvl1_TT.desc[L1_VA_IDX(va)] = pa | MMU_SectionFlags(flags);
return true;
}
return false;
}
/* Large Pages */
static u32 MMU_LargePageFlags(u32 f)
{
return (MMU_GetNX(f) << 15) | (MMU_GetTEX(f) << 12) |
(MMU_GetShared(f) << 10) | (MMU_GetAP(f) << 4) |
(MMU_GetCB(f) << 2) | DESCRIPTOR_L2_LARGEPAGE;
}
static bool MMU_MapLargePage(u32 va, u32 pa, u32 flags)
{
MMU_Lvl2_Table *l2 = MMU_CoarseFix(va);
if (l2 == NULL)
return false;
for (u32 i = va; i < (va + 0x10000); i += 0x1000)
l2->desc[L2_VA_IDX(i)] = pa | MMU_LargePageFlags(flags);
return true;
}
/* Pages */
static u32 mmuPageFlags(u32 f)
static u32 MMU_PageFlags(u32 f)
{
return (mmuGetShared(f) << 10) | (mmuGetTEX(f) << 6) |
(mmuGetAP(f) << 4) | (mmuGetCB(f) << 2) |
(mmuGetNX(f) ? DESCRIPTOR_L2_PAGE_NX : DESCRIPTOR_L2_PAGE_EXEC);
return (MMU_GetShared(f) << 10) | (MMU_GetTEX(f) << 6) |
(MMU_GetAP(f) << 4) | (MMU_GetCB(f) << 2) |
(MMU_GetNX(f) ? DESCRIPTOR_L2_PAGE_NX : DESCRIPTOR_L2_PAGE_EXEC);
}
static void mmuMapPage(u32 va, u32 pa, u32 flags)
static bool MMU_MapPage(u32 va, u32 pa, u32 flags)
{
mmuLevel2Table *l2 = mmuCoarseFix(va);
l2->desc[L2_VA_IDX(va)] = pa | mmuPageFlags(flags);
MMU_Lvl2_Table *l2 = MMU_CoarseFix(va);
if (l2 == NULL)
return false;
l2->desc[L2_VA_IDX(va)] = pa | MMU_PageFlags(flags);
return true;
}
static bool mmuMappingFits(u32 va, u32 pa, u32 sz, u32 alignment)
static bool MMU_MappingFits(u32 va, u32 pa, u32 len, u32 abits)
{
return !((va | pa | sz) & (alignment));
return !((va | pa | len) & (BIT(abits) - 1));
}
u32 mmuMapArea(u32 va, u32 pa, u32 size, u32 flags)
u32 MMU_Map(u32 va, u32 pa, u32 size, u32 flags)
{
static const struct {
u32 size;
void (*mapfn)(u32,u32,u32);
u32 bits;
bool (*mapfn)(u32,u32,u32);
} VMappers[] = {
{
.size = BIT(SECT_ADDR_SHIFT),
.mapfn = mmuMapSection,
.bits = SECT_ADDR_SHIFT,
.mapfn = MMU_MapSection,
},
{
.size = BIT(PAGE_ADDR_SHIFT),
.mapfn = mmuMapPage,
.bits = LPAGE_ADDR_SHIFT,
.mapfn = MMU_MapLargePage,
},
{
.bits = PAGE_ADDR_SHIFT,
.mapfn = MMU_MapPage,
},
};
while(size > 0) {
size_t i = 0;
for (i = 0; i < countof(VMappers); i++) {
u32 pgsize = VMappers[i].size;
u32 abits = VMappers[i].bits;
if (mmuMappingFits(va, pa, size, pgsize-1)) {
(VMappers[i].mapfn)(va, pa, flags);
if (MMU_MappingFits(va, pa, size, abits)) {
bool mapped = (VMappers[i].mapfn)(va, pa, flags);
u32 offset = BIT(abits);
va += pgsize;
pa += pgsize;
size -= pgsize;
// no fun allowed
if (!mapped)
return size;
va += offset;
pa += offset;
size -= offset;
break;
}
}
/* alternatively return the unmapped remaining size:
if (i == countof(VMappers))
return size;
*/
}
return 0;
}
void mmuInvalidate(void)
void MMU_Init(void)
{
ARM_MCR(p15, 0, 0, c8, c7, 0);
}
void mmuInvalidateVA(u32 addr)
{
ARM_MCR(p15, 0, addr, c8, c7, 2);
}
void mmuInitRegisters(void)
{
u32 ttbr0 = (u32)(&mmuGlobalTT) | 0x12;
u32 ttbr0 = (u32)(&MMU_Lvl1_TT) | 0x12;
// Set up TTBR0/1 and the TTCR
ARM_MCR(p15, 0, ttbr0, c2, c0, 0);

View File

@ -20,22 +20,21 @@
#include <types.h>
enum {
MMU_STRONG_ORDER = 0,
MMU_UNCACHEABLE,
MMU_DEV_SHARED,
MMU_DEV_NONSHARED,
MMU_CACHE_WT,
MMU_CACHE_WB,
MMU_CACHE_WBA,
MMU_MEMORY_TYPES,
enum MMU_MemoryType {
STRONGLY_ORDERED = 0,
NON_CACHEABLE,
DEVICE_SHARED,
DEVICE_NONSHARED,
CACHED_WT,
CACHED_WB,
CACHED_WB_ALLOC,
MEMORY_TYPES,
};
enum {
MMU_NO_ACCESS = 0,
MMU_READ_ONLY,
MMU_READ_WRITE,
MMU_ACCESS_TYPES,
enum MMU_MemoryAccess {
NO_ACCESS = 0,
READ_ONLY,
READ_WRITE,
};
#define MMU_FLAGS(t, ap, nx, s) ((s) << 25 | (nx) << 24 | (ap) << 8 | (t))
@ -46,9 +45,5 @@ enum {
#define MMU_FLAGS_NOEXEC(f) ((f) & BIT(24))
#define MMU_FLAGS_SHARED(f) ((f) & BIT(25))
u32 mmuMapArea(u32 va, u32 pa, u32 size, u32 flags);
void mmuInvalidate(void);
void mmuInvalidateVA(u32 addr); // DO NOT USE
void mmuInitRegisters(void);
u32 MMU_Map(u32 va, u32 pa, u32 size, u32 flags);
void MMU_Init(void);

View File

@ -1,32 +1,32 @@
/*
* This file is part of GodMode9
* Copyright (C) 2018-2019 Wolfvak
*
* 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 2 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/>.
*/
#include <types.h>
#include <arm.h>
#define REG_SCU_CNT (*REG_ARM_PMR(0x00, u32))
#define REG_SCU_CFG (*REG_ARM_PMR(0x04, u32))
#define REG_SCU_CPU (*REG_ARM_PMR(0x08, u32))
#define REG_SCU_INV (*REG_ARM_PMR(0x0C, u32))
void SCU_Init(void)
{
REG_SCU_CNT = 0x1FFE;
REG_SCU_INV = 0xFFFF;
REG_SCU_CNT = 0x3FFF;
}
/*
* This file is part of GodMode9
* Copyright (C) 2018-2019 Wolfvak
*
* 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 2 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/>.
*/
#include <types.h>
#include <arm.h>
#define REG_SCU_CNT (*REG_ARM_PMR(0x00, u32))
#define REG_SCU_CFG (*REG_ARM_PMR(0x04, u32))
#define REG_SCU_CPU (*REG_ARM_PMR(0x08, u32))
#define REG_SCU_INV (*REG_ARM_PMR(0x0C, u32))
void SCU_Init(void)
{
REG_SCU_CNT = 0x1FFE;
REG_SCU_INV = 0xFFFF;
REG_SCU_CNT = 0x3FFF;
}

View File

@ -1,23 +1,23 @@
/*
* This file is part of GodMode9
* Copyright (C) 2018-2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
void SCU_Init(void);
/*
* This file is part of GodMode9
* Copyright (C) 2018-2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
void SCU_Init(void);

View File

@ -30,7 +30,3 @@
#define CLK_MS_TO_TICKS(m) (((BASE_CLKRATE / 1000) * (m)) - 1)
void TIMER_WaitTicks(u32 ticks);
static inline void TIMER_WaitMS(u32 ms) {
TIMER_WaitTicks(CLK_MS_TO_TICKS(ms));
}

View File

@ -28,46 +28,47 @@
.macro TRAP_ENTRY xrq
msr cpsr_f, #(\xrq << 29)
b xrqMain
b XRQ_Main
.endm
xrqVectorTable:
ldr pc, =xrqReset
ldr pc, =xrqUndefined
ldr pc, =xrqSVC
ldr pc, =xrqPrefetchAbort
ldr pc, =xrqDataAbort
b . @ ignore the reserved exception
ldr pc, =xrqIRQ
ldr pc, =xrqFIQ
.pool
xrqVectorTableEnd:
.section .vector, "ax"
vectors:
b XRQ_Reset
b XRQ_Undefined
b XRQ_SVC
b XRQ_PrefetchAbt
b XRQ_DataAbt
b XRQ_Reserved
b XRQ_IRQ
b XRQ_FIQ
xrqReset:
XRQ_Reset:
TRAP_ENTRY 0
xrqUndefined:
XRQ_Undefined:
TRAP_ENTRY 1
xrqSVC:
XRQ_SVC:
TRAP_ENTRY 2
xrqPrefetchAbort:
XRQ_PrefetchAbt:
TRAP_ENTRY 3
xrqDataAbort:
XRQ_DataAbt:
TRAP_ENTRY 4
xrqFIQ:
XRQ_Reserved:
TRAP_ENTRY 5
XRQ_FIQ:
TRAP_ENTRY 7
xrqMain:
clrex
cpsid aif
ldr sp, =(xrqStackTop - 32*4)
XRQ_Main:
ldr sp, =(exception_stack_top - 32*4)
stmia sp, {r0-r7}
cpsid aif
mrs r1, cpsr
lsr r0, r1, #29
@ -81,7 +82,11 @@ xrqMain:
add r3, sp, #8*4
msr cpsr_c, r2
nop
nop
stmia r3!, {r8-r14}
nop
nop
msr cpsr_c, r1
mrc p15, 0, r4, c5, c0, 0 @ data fault status register
@ -94,8 +99,7 @@ xrqMain:
bl do_exception
xrqIRQ:
clrex
XRQ_IRQ:
sub lr, lr, #4 @ Fix return address
srsfd sp!, #SR_SVC_MODE @ Store IRQ mode LR and SPSR on the SVC stack
cps #SR_SVC_MODE @ Switch to SVC mode
@ -104,26 +108,17 @@ xrqIRQ:
and r4, sp, #7 @ Fix SP to be 8byte aligned
sub sp, sp, r4
bl gicTopHandler
mov lr, pc
ldr pc, =GIC_MainHandler
add sp, sp, r4
pop {r0-r4, r12, lr}
rfeia sp! @ Return from exception
@ u32 xrqInstallVectorTable(void)
.global xrqInstallVectorTable
.type xrqInstallVectorTable, %function
xrqInstallVectorTable:
ldr r0, =xrqPage
ldr r1, =xrqVectorTable
mov r2, #(xrqVectorTableEnd - xrqVectorTable)
b memcpy
.section .bss.xrqPage
.section .bss.xrq_stk
.align 12
.global xrqPage
xrqPage:
.space 8192 @ reserve two 4K aligned pages for vectors and abort stack
.global xrqStackTop
xrqStackTop:
exception_stack: @ reserve a single aligned page for the exception stack
.space 4096
exception_stack_top:
.global exception_stack_top

View File

@ -76,12 +76,10 @@ __boot:
b 1b
corezero_start:
@ assumes the .bss section size is 128 byte aligned (or zero)
@ assume __bss_len is 128 byte aligned
ldr r0, =__bss_pa
ldr r1, =__bss_va_end @ calculate the length of .bss using the VA start and end
ldr r2, =__bss_va
sub r1, r1, r2
add r1, r0, r1 @ fixup to be PA start and end
ldr r1, =__bss_len
add r1, r0, r1
mov r2, #0
mov r3, #0
mov r4, #0

View File

@ -1,146 +1,146 @@
// Somewhat based on xerpi's CODEC driver for Linux
/*
* This file is part of GodMode9
* Copyright (C) 2017 Sergi Granell, Paul LaMendola
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#include <common.h>
#include <types.h>
#include <hid_map.h>
#include "hw/codec.h"
#include <spi.h>
#define CPAD_THRESH_X (750)
#define CPAD_THRESH_Y (150)
/* SPI stuff */
static void CODEC_WriteRead(u32 *txb, u8 txl, u32 *rxb, u8 rxl)
{
SPI_XferInfo xfers[2];
xfers[0].buf = txb;
xfers[0].len = txl;
xfers[0].read = false;
xfers[1].buf = rxb;
xfers[1].len = rxl;
xfers[1].read = true;
SPI_DoXfer(SPI_DEV_CODEC, xfers, 2, true);
}
static void CODEC_RegSelect(u8 reg)
{
SPI_XferInfo xfer;
u32 cmd;
cmd = reg << 8;
xfer.buf = &cmd;
xfer.len = 2;
xfer.read = false;
SPI_DoXfer(SPI_DEV_CODEC, &xfer, 1, true);
}
static u8 CODEC_RegRead(u8 reg)
{
u32 cmd, ret;
cmd = (reg << 1) | 1;
CODEC_WriteRead(&cmd, 1, &ret, 1);
return ret;
}
static void CODEC_RegReadBuf(u8 reg, u32 *out, u8 size)
{
u32 cmd = (reg << 1) | 1;
CODEC_WriteRead(&cmd, 1, out, size);
}
static void CODEC_RegWrite(u8 reg, u8 val)
{
SPI_XferInfo xfer;
u32 cmd;
cmd = (val << 8) | (reg << 1);
xfer.buf = &cmd;
xfer.len = 2;
xfer.read = false;
SPI_DoXfer(SPI_DEV_CODEC, &xfer, 1, true);
}
static void CODEC_RegMask(u8 reg, u8 mask0, u8 mask1)
{
CODEC_RegWrite(reg, (CODEC_RegRead(reg) & ~mask1) | (mask0 & mask1));
}
// elder god magic
void CODEC_Init(void)
{
CODEC_RegSelect(0x67);
CODEC_RegWrite(0x24, 0x98);
CODEC_RegWrite(0x26, 0x00);
CODEC_RegWrite(0x25, 0x43);
CODEC_RegWrite(0x24, 0x18);
CODEC_RegWrite(0x17, 0x43);
CODEC_RegWrite(0x19, 0x69);
CODEC_RegWrite(0x1B, 0x80);
CODEC_RegWrite(0x27, 0x11);
CODEC_RegWrite(0x26, 0xEC);
CODEC_RegWrite(0x24, 0x18);
CODEC_RegWrite(0x25, 0x53);
CODEC_RegMask(0x26, 0x80, 0x80);
CODEC_RegMask(0x24, 0x00, 0x80);
CODEC_RegMask(0x25, 0x10, 0x3C);
}
void CODEC_GetRawData(u32 *buffer)
{
CODEC_RegSelect(0xFB);
CODEC_RegReadBuf(1, buffer, 0x34);
}
void CODEC_Get(CODEC_Input *input)
{
u32 raw_data_buf[0x34 / 4];
u8 *raw_data = (u8*)raw_data_buf;
s16 cpad_x, cpad_y;
bool ts_pressed;
CODEC_GetRawData(raw_data_buf);
cpad_x = ((raw_data[0x24] << 8 | raw_data[0x25]) & 0xFFF) - 2048;
cpad_y = ((raw_data[0x14] << 8 | raw_data[0x15]) & 0xFFF) - 2048;
// X axis is inverted
input->cpad_x = (abs(cpad_x) > CPAD_THRESH_X) ? -cpad_x : 0;
input->cpad_y = (abs(cpad_y) > CPAD_THRESH_Y) ? cpad_y : 0;
ts_pressed = !(raw_data[0] & BIT(4));
if (ts_pressed) {
input->ts_x = (raw_data[0] << 8) | raw_data[1];
input->ts_y = (raw_data[10] << 8) | raw_data[11];
} else {
input->ts_x = 0xFFFF;
input->ts_y = 0xFFFF;
}
}
// Somewhat based on xerpi's CODEC driver for Linux
/*
* This file is part of GodMode9
* Copyright (C) 2017 Sergi Granell, Paul LaMendola
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#include <common.h>
#include <types.h>
#include <hid_map.h>
#include "hw/codec.h"
#include <spi.h>
#define CPAD_THRESH_X (750)
#define CPAD_THRESH_Y (150)
/* SPI stuff */
static void CODEC_WriteRead(u32 *txb, u8 txl, u32 *rxb, u8 rxl)
{
SPI_XferInfo xfers[2];
xfers[0].buf = txb;
xfers[0].len = txl;
xfers[0].read = false;
xfers[1].buf = rxb;
xfers[1].len = rxl;
xfers[1].read = true;
SPI_DoXfer(SPI_DEV_CODEC, xfers, 2, true);
}
static void CODEC_RegSelect(u8 reg)
{
SPI_XferInfo xfer;
u32 cmd;
cmd = reg << 8;
xfer.buf = &cmd;
xfer.len = 2;
xfer.read = false;
SPI_DoXfer(SPI_DEV_CODEC, &xfer, 1, true);
}
static u8 CODEC_RegRead(u8 reg)
{
u32 cmd, ret;
cmd = (reg << 1) | 1;
CODEC_WriteRead(&cmd, 1, &ret, 1);
return ret;
}
static void CODEC_RegReadBuf(u8 reg, u32 *out, u8 size)
{
u32 cmd = (reg << 1) | 1;
CODEC_WriteRead(&cmd, 1, out, size);
}
static void CODEC_RegWrite(u8 reg, u8 val)
{
SPI_XferInfo xfer;
u32 cmd;
cmd = (val << 8) | (reg << 1);
xfer.buf = &cmd;
xfer.len = 2;
xfer.read = false;
SPI_DoXfer(SPI_DEV_CODEC, &xfer, 1, true);
}
static void CODEC_RegMask(u8 reg, u8 mask0, u8 mask1)
{
CODEC_RegWrite(reg, (CODEC_RegRead(reg) & ~mask1) | (mask0 & mask1));
}
// elder god magic
void CODEC_Init(void)
{
CODEC_RegSelect(0x67);
CODEC_RegWrite(0x24, 0x98);
CODEC_RegWrite(0x26, 0x00);
CODEC_RegWrite(0x25, 0x43);
CODEC_RegWrite(0x24, 0x18);
CODEC_RegWrite(0x17, 0x43);
CODEC_RegWrite(0x19, 0x69);
CODEC_RegWrite(0x1B, 0x80);
CODEC_RegWrite(0x27, 0x11);
CODEC_RegWrite(0x26, 0xEC);
CODEC_RegWrite(0x24, 0x18);
CODEC_RegWrite(0x25, 0x53);
CODEC_RegMask(0x26, 0x80, 0x80);
CODEC_RegMask(0x24, 0x00, 0x80);
CODEC_RegMask(0x25, 0x10, 0x3C);
}
void CODEC_GetRawData(u32 *buffer)
{
CODEC_RegSelect(0xFB);
CODEC_RegReadBuf(1, buffer, 0x34);
}
void CODEC_Get(CODEC_Input *input)
{
u32 raw_data_buf[0x34 / 4];
u8 *raw_data = (u8*)raw_data_buf;
s16 cpad_x, cpad_y;
bool ts_pressed;
CODEC_GetRawData(raw_data_buf);
cpad_x = ((raw_data[0x24] << 8 | raw_data[0x25]) & 0xFFF) - 2048;
cpad_y = ((raw_data[0x14] << 8 | raw_data[0x15]) & 0xFFF) - 2048;
// X axis is inverted
input->cpad_x = (abs(cpad_x) > CPAD_THRESH_X) ? -cpad_x : 0;
input->cpad_y = (abs(cpad_y) > CPAD_THRESH_Y) ? cpad_y : 0;
ts_pressed = !(raw_data[0] & BIT(4));
if (ts_pressed) {
input->ts_x = (raw_data[0] << 8) | raw_data[1];
input->ts_y = (raw_data[10] << 8) | raw_data[11];
} else {
input->ts_x = 0xFFFF;
input->ts_y = 0xFFFF;
}
}

View File

@ -1,32 +1,32 @@
/*
* This file is part of GodMode9
* Copyright (C) 2017 Sergi Granell, Paul LaMendola
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
typedef struct {
s16 cpad_x, cpad_y;
u16 ts_x, ts_y;
} CODEC_Input;
void CODEC_Init(void);
void CODEC_GetRawData(u32 *buffer);
void CODEC_Get(CODEC_Input *input);
/*
* This file is part of GodMode9
* Copyright (C) 2017 Sergi Granell, Paul LaMendola
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
typedef struct {
s16 cpad_x, cpad_y;
s16 ts_x, ts_y;
} CODEC_Input;
void CODEC_Init(void);
void CODEC_GetRawData(u32 *buffer);
void CODEC_Get(CODEC_Input *input);

View File

@ -1,34 +1,34 @@
/*
* This file is part of GodMode9
* Copyright (C) 2017 derrek, profi200
* Copyright (C) 2019 Wolfvak
*
* 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/>.
*/
#pragma once
#include <types.h>
#define REG_GPIO ((vu16*)(0x10100000 + 0x47000))
static inline void GPIO_setBit(u16 reg, u8 bitNum)
{
REG_GPIO[reg] |= 1u<<bitNum;
}
static inline void GPIO_clearBit(u16 reg, u8 bitNum)
{
REG_GPIO[reg] &= ~(1u<<bitNum);
}
/*
* This file is part of GodMode9
* Copyright (C) 2017 derrek, profi200
* Copyright (C) 2019 Wolfvak
*
* 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/>.
*/
#pragma once
#include <types.h>
#define REG_GPIO ((vu16*)(0x10100000 + 0x47000))
static inline void GPIO_setBit(u16 reg, u8 bitNum)
{
REG_GPIO[reg] |= 1u<<bitNum;
}
static inline void GPIO_clearBit(u16 reg, u8 bitNum)
{
REG_GPIO[reg] &= ~(1u<<bitNum);
}

View File

@ -16,289 +16,216 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <common.h>
#include <types.h>
#include <vram.h>
#include <arm.h>
#include "arm/timer.h"
#include "hw/i2c.h"
#include "hw/mcu.h"
#include "hw/gpulcd.h"
#include "system/event.h"
static struct
/* LCD Configuration Registers */
#define REG_LCD(x) ((vu32*)(0x10202000 + (x)))
void LCD_SetBrightness(u8 brightness)
{
u16 lcdIds; // Bits 0-7 top screen, 8-15 bottom screen.
bool lcdIdsRead;
u8 lcdPower; // 1 = on. Bit 4 top light, bit 2 bottom light, bit 0 LCDs.
u8 lcdLights[2]; // LCD backlight brightness. Top, bottom.
u32 framebufs[2]; // For each screen
u8 doubleBuf[2]; // Top, bottom, 1 = enable.
u16 strides[2]; // Top, bottom
u32 formats[2]; // Top, bottom
} g_gfxState = {0};
static void setupDisplayController(u8 lcd);
static void resetLcdsMaybe(void);
static void waitLcdsReady(void);
static u32 gxModeWidth(unsigned c) {
switch(c) {
case 0: return 4;
case 1: return 3;
default: return 2;
}
*REG_LCD(0x240) = brightness;
*REG_LCD(0xA40) = brightness;
}
unsigned GFX_init(GfxFbFmt mode)
u8 LCD_GetBrightness(void)
{
unsigned err = 0;
REG_CFG11_GPUPROT = 0;
// Reset
REG_PDN_GPU_CNT = PDN_GPU_CNT_CLK_E;
ARM_WaitCycles(12);
REG_PDN_GPU_CNT = PDN_GPU_CNT_CLK_E | PDN_GPU_CNT_RST_ALL;
REG_GX_GPU_CLK = 0x100;
REG_GX_PSC_VRAM = 0;
REG_GX_PSC_FILL0_CNT = 0;
REG_GX_PSC_FILL1_CNT = 0;
REG_GX_PPF_CNT = 0;
// LCD framebuffer setup.
g_gfxState.strides[0] = 240 * gxModeWidth(mode);
g_gfxState.strides[1] = 240 * gxModeWidth(mode);
g_gfxState.framebufs[0] = VRAM_TOP_LA;
g_gfxState.framebufs[1] = VRAM_BOT_A;
g_gfxState.formats[0] = mode | BIT(6) | BIT(9);
g_gfxState.formats[1] = mode | BIT(9);
setupDisplayController(0);
setupDisplayController(1);
REG_LCD_PDC0_SWAP = 0; // Select framebuf 0.
REG_LCD_PDC1_SWAP = 0;
REG_LCD_PDC0_CNT = PDC_CNT_OUT_E | PDC_CNT_I_MASK_ERR | PDC_CNT_I_MASK_H | PDC_CNT_E; // Start
REG_LCD_PDC1_CNT = PDC_CNT_OUT_E | PDC_CNT_I_MASK_ERR | PDC_CNT_I_MASK_H | PDC_CNT_E;
// LCD reg setup.
REG_LCD_ABL0_FILL = 1u<<24; // Force blackscreen
REG_LCD_ABL1_FILL = 1u<<24; // Force blackscreen
REG_LCD_PARALLAX_CNT = 0;
REG_LCD_PARALLAX_PWM = 0xA390A39;
REG_LCD_RST = 0;
REG_LCD_UNK00C = 0x10001;
// Clear used VRAM
REG_GX_PSC_FILL0_S_ADDR = VRAM_TOP_LA >> 3;
REG_GX_PSC_FILL0_E_ADDR = VRAM_END >> 3;
REG_GX_PSC_FILL0_VAL = 0;
REG_GX_PSC_FILL0_CNT = BIT(9) | BIT(0);
// Backlight and other stuff.
REG_LCD_ABL0_LIGHT = 0;
REG_LCD_ABL0_CNT = 0;
REG_LCD_ABL0_LIGHT_PWM = 0;
REG_LCD_ABL1_LIGHT = 0;
REG_LCD_ABL1_CNT = 0;
REG_LCD_ABL1_LIGHT_PWM = 0;
REG_LCD_RST = 1;
REG_LCD_UNK00C = 0;
TIMER_WaitMS(10);
resetLcdsMaybe();
MCU_controlLCDPower(2u); // Power on LCDs.
if(eventWait(getEventMCU(), 0x3Fu<<24, 0x3Fu<<24) != 2u<<24) __builtin_trap();
waitLcdsReady();
REG_LCD_ABL0_LIGHT_PWM = 0x1023E;
REG_LCD_ABL1_LIGHT_PWM = 0x1023E;
MCU_controlLCDPower(0x28u); // Power on backlights.
if(eventWait(getEventMCU(), 0x3Fu<<24, 0x3Fu<<24) != 0x28u<<24) __builtin_trap();
g_gfxState.lcdPower = 0x15; // All on.
// Make sure the fills finished.
REG_LCD_ABL0_FILL = 0;
REG_LCD_ABL1_FILL = 0;
// GPU stuff.
REG_GX_GPU_CLK = 0x70100;
*((vu32*)0x10400050) = 0x22221200;
*((vu32*)0x10400054) = 0xFF2;
GFX_setBrightness(0x80, 0x80);
return err;
return *REG_LCD(0x240);
}
static u16 getLcdIds(void)
void LCD_Initialize(u8 brightness)
{
u16 ids;
if(!g_gfxState.lcdIdsRead)
{
g_gfxState.lcdIdsRead = true;
u16 top, bot;
I2C_writeReg(I2C_DEV_LCD0, 0x40, 0xFF);
I2C_readRegBuf(I2C_DEV_LCD0, 0x40, (u8*)&top, 2);
I2C_writeReg(I2C_DEV_LCD1, 0x40, 0xFF);
I2C_readRegBuf(I2C_DEV_LCD1, 0x40, (u8*)&bot, 2);
ids = top>>8;
ids |= bot & 0xFF00u;
g_gfxState.lcdIds = ids;
}
else ids = g_gfxState.lcdIds;
return ids;
*REG_LCD(0x014) = 0x00000001;
*REG_LCD(0x00C) &= 0xFFFEFFFE;
*REG_LCD(0x240) = brightness;
*REG_LCD(0xA40) = brightness;
*REG_LCD(0x244) = 0x1023E;
*REG_LCD(0xA44) = 0x1023E;
}
static void resetLcdsMaybe(void)
void LCD_Deinitialize(void)
{
const u16 ids = getLcdIds();
*REG_LCD(0x244) = 0;
*REG_LCD(0xA44) = 0;
*REG_LCD(0x00C) = 0x10001;
*REG_LCD(0x014) = 0;
}
// Top screen
if(ids & 0xFFu) I2C_writeReg(I2C_DEV_LCD0, 0xFE, 0xAA);
else
{
I2C_writeReg(I2C_DEV_LCD0, 0x11, 0x10);
I2C_writeReg(I2C_DEV_LCD0, 0x50, 1);
/* GPU Control Registers */
#define REG_GPU_CNT ((vu32*)(0x10141200))
/* GPU DMA */
#define REG_GPU_PSC(n, x) ((vu32*)(0x10400010 + ((n) * 0x10) + (x)))
#define GPU_PSC_START (0x00)
#define GPU_PSC_END (0x04)
#define GPU_PSC_FILLVAL (0x08)
#define GPU_PSC_CNT (0x0C)
#define GPUDMA_ADDR(x) ((x) >> 3)
#define PSC_START (BIT(0))
#define PSC_DONE (BIT(1))
#define PSC_32BIT (2 << 8)
#define PSC_24BIT (1 << 8)
#define PSC_16BIT (0 << 8)
void GPU_PSCFill(u32 start, u32 end, u32 fv)
{
u32 mp;
if (start > end)
return;
start = GPUDMA_ADDR(start);
end = GPUDMA_ADDR(end);
mp = (start + end) / 2;
*REG_GPU_PSC(0, GPU_PSC_START) = start;
*REG_GPU_PSC(0, GPU_PSC_END) = mp;
*REG_GPU_PSC(0, GPU_PSC_FILLVAL) = fv;
*REG_GPU_PSC(0, GPU_PSC_CNT) = PSC_START | PSC_32BIT;
*REG_GPU_PSC(1, GPU_PSC_START) = mp;
*REG_GPU_PSC(1, GPU_PSC_END) = end;
*REG_GPU_PSC(1, GPU_PSC_FILLVAL) = fv;
*REG_GPU_PSC(1, GPU_PSC_CNT) = PSC_START | PSC_32BIT;
while(!((*REG_GPU_PSC(0, GPU_PSC_CNT) | *REG_GPU_PSC(1, GPU_PSC_CNT)) & PSC_DONE));
}
/* GPU Display Registers */
#define GPU_PDC(n, x) ((vu32*)(0x10400400 + ((n) * 0x100) + x))
#define PDC_PARALLAX (BIT(5))
#define PDC_MAINSCREEN (BIT(6))
#define PDC_FIXSTRIP (BIT(7))
void GPU_SetFramebuffers(const u32 *framebuffers)
{
*GPU_PDC(0, 0x68) = framebuffers[0];
*GPU_PDC(0, 0x6C) = framebuffers[1];
*GPU_PDC(0, 0x94) = framebuffers[2];
*GPU_PDC(0, 0x98) = framebuffers[3];
*GPU_PDC(1, 0x68) = framebuffers[4];
*GPU_PDC(1, 0x6C) = framebuffers[5];
*GPU_PDC(0, 0x78) = 0;
*GPU_PDC(1, 0x78) = 0;
}
void GPU_SetFramebufferMode(u32 screen, u8 mode)
{
u32 stride, cfg;
vu32 *fbcfg_reg, *fbstr_reg;
mode &= 7;
screen &= 1;
cfg = PDC_FIXSTRIP | mode;
if (screen) {
fbcfg_reg = GPU_PDC(1, 0x70);
fbstr_reg = GPU_PDC(1, 0x90);
} else {
fbcfg_reg = GPU_PDC(0, 0x70);
fbstr_reg = GPU_PDC(0, 0x90);
cfg |= PDC_MAINSCREEN;
}
// Bottom screen
if(ids>>8) I2C_writeReg(I2C_DEV_LCD1, 0xFE, 0xAA);
else I2C_writeReg(I2C_DEV_LCD1, 0x11, 0x10);
I2C_writeReg(I2C_DEV_LCD0, 0x60, 0);
I2C_writeReg(I2C_DEV_LCD1, 0x60, 0);
I2C_writeReg(I2C_DEV_LCD0, 1, 0x10);
I2C_writeReg(I2C_DEV_LCD1, 1, 0x10);
}
static void waitLcdsReady(void)
{
const u16 ids = getLcdIds();
if((ids & 0xFFu) == 0 || (ids>>8) == 0) // Unknown LCD?
{
TIMER_WaitMS(150);
stride = 240;
switch(mode) {
case PDC_RGBA8:
stride *= 4;
break;
case PDC_RGB24:
stride *= 3;
break;
default:
stride *= 2;
break;
}
else
{
u32 i = 0;
do
{
u16 top, bot;
I2C_writeReg(I2C_DEV_LCD0, 0x40, 0x62);
I2C_readRegBuf(I2C_DEV_LCD0, 0x40, (u8*)&top, 2);
I2C_writeReg(I2C_DEV_LCD1, 0x40, 0x62);
I2C_readRegBuf(I2C_DEV_LCD1, 0x40, (u8*)&bot, 2);
if((top>>8) == 1 && (bot>>8) == 1) break;
*fbcfg_reg = cfg;
*fbstr_reg = stride;
}
TIMER_WaitMS(33);
} while(i++ < 10);
void GPU_Init(void)
{
if (*REG_GPU_CNT == 0x1007F) {
MCU_PushToLCD(false);
LCD_Deinitialize();
*REG_GPU_CNT = 0x10001;
TIMER_WaitTicks(CLK_MS_TO_TICKS(40));
}
}
void GFX_powerOnBacklights(GfxBlight mask)
{
g_gfxState.lcdPower |= mask;
mask <<= 1;
MCU_controlLCDPower(mask); // Power on backlights.
eventWait(getEventMCU(), 0x3F<<24, 0x3F<<24);
/*if(mcuEventWait(0x3Fu<<24) != (u32)mask<<24)
__builtin_trap();*/
}
void GFX_powerOffBacklights(GfxBlight mask)
{
g_gfxState.lcdPower &= ~mask;
MCU_controlLCDPower(mask); // Power off backlights.
eventWait(getEventMCU(), 0x3F<<24, 0x3F<<24);
/*if(mcuEventWait(0x3Fu<<24) != (u32)mask<<24)
__builtin_trap();*/
}
u8 GFX_getBrightness(void)
{
return REG_LCD_ABL0_LIGHT;
}
void GFX_setBrightness(u8 top, u8 bot)
{
g_gfxState.lcdLights[0] = top;
g_gfxState.lcdLights[1] = bot;
REG_LCD_ABL0_LIGHT = top;
REG_LCD_ABL1_LIGHT = bot;
}
void GFX_setForceBlack(bool top, bool bot)
{
REG_LCD_ABL0_FILL = (u32)top<<24; // Force blackscreen
REG_LCD_ABL1_FILL = (u32)bot<<24; // Force blackscreen
}
static void setupDisplayController(u8 lcd)
{
if(lcd > 1) return;
static const u32 displayCfgs[2][24] =
{
{
// PDC0 regs 0-0x4C.
450, 209, 449, 449, 0, 207, 209, 453<<16 | 449,
1<<16 | 0, 413, 2, 402, 402, 402, 1, 2,
406<<16 | 402, 0, 0<<4 | 0, 0<<16 | 0xFF<<8 | 0,
// PDC0 regs 0x5C-0x64.
400<<16 | 240, // Width and height.
449<<16 | 209,
402<<16 | 2,
// PDC0 reg 0x9C.
0<<16 | 0
},
{
// PDC1 regs 0-0x4C.
450, 209, 449, 449, 205, 207, 209, 453<<16 | 449,
1<<16 | 0, 413, 82, 402, 402, 79, 80, 82,
408<<16 | 404, 0, 1<<4 | 1, 0<<16 | 0<<8 | 0xFF,
// PDC1 regs 0x5C-0x64.
320<<16 | 240, // Width and height.
449<<16 | 209,
402<<16 | 82,
// PDC1 reg 0x9C.
0<<16 | 0
}
};
const u32 *const cfg = displayCfgs[lcd];
vu32 *const regs = (vu32*)(GX_REGS_BASE + 0x400 + (0x100u * lcd));
for (unsigned i = 0; i < 0x50/4; i++)
regs[i] = cfg[i];
for (unsigned i = 0; i < 0xC/4; i++)
regs[23 + i] = cfg[20 + i];
regs[36] = g_gfxState.strides[lcd]; // PDC reg 0x90 stride.
regs[39] = cfg[23]; // PDC reg 0x9C.
// PDC regs 0x68, 0x6C, 0x94, 0x98 and 0x70.
regs[26] = g_gfxState.framebufs[lcd]; // Framebuffer A first address.
regs[27] = g_gfxState.framebufs[lcd]; // Framebuffer A second address.
regs[37] = g_gfxState.framebufs[lcd]; // Framebuffer B first address.
regs[38] = g_gfxState.framebufs[lcd]; // Framebuffer B second address.
regs[28] = g_gfxState.formats[lcd]; // Format
regs[32] = 0; // Gamma table index 0.
for(u32 i = 0; i < 256; i++) regs[33] = 0x10101u * i;
LCD_Initialize(0x20);
*REG_GPU_CNT = 0x1007F;
*GPU_PDC(0, 0x00) = 0x000001C2;
*GPU_PDC(0, 0x04) = 0x000000D1;
*GPU_PDC(0, 0x08) = 0x000001C1;
*GPU_PDC(0, 0x0C) = 0x000001C1;
*GPU_PDC(0, 0x10) = 0x00000000;
*GPU_PDC(0, 0x14) = 0x000000CF;
*GPU_PDC(0, 0x18) = 0x000000D1;
*GPU_PDC(0, 0x1C) = 0x01C501C1;
*GPU_PDC(0, 0x20) = 0x00010000;
*GPU_PDC(0, 0x24) = 0x0000019D;
*GPU_PDC(0, 0x28) = 0x00000002;
*GPU_PDC(0, 0x2C) = 0x00000192;
*GPU_PDC(0, 0x30) = 0x00000192;
*GPU_PDC(0, 0x34) = 0x00000192;
*GPU_PDC(0, 0x38) = 0x00000001;
*GPU_PDC(0, 0x3C) = 0x00000002;
*GPU_PDC(0, 0x40) = 0x01960192;
*GPU_PDC(0, 0x44) = 0x00000000;
*GPU_PDC(0, 0x48) = 0x00000000;
*GPU_PDC(0, 0x5C) = 0x00F00190;
*GPU_PDC(0, 0x60) = 0x01C100D1;
*GPU_PDC(0, 0x64) = 0x01920002;
*GPU_PDC(0, 0x68) = VRAM_START;
*GPU_PDC(0, 0x6C) = VRAM_START;
*GPU_PDC(0, 0x70) = 0x00080340;
*GPU_PDC(0, 0x74) = 0x00010501;
*GPU_PDC(0, 0x78) = 0x00000000;
*GPU_PDC(0, 0x90) = 0x000003C0;
*GPU_PDC(0, 0x94) = VRAM_START;
*GPU_PDC(0, 0x98) = VRAM_START;
*GPU_PDC(0, 0x9C) = 0x00000000;
for (u32 i = 0; i < 256; i++)
*GPU_PDC(0, 0x84) = 0x10101 * i;
*GPU_PDC(1, 0x00) = 0x000001C2;
*GPU_PDC(1, 0x04) = 0x000000D1;
*GPU_PDC(1, 0x08) = 0x000001C1;
*GPU_PDC(1, 0x0C) = 0x000001C1;
*GPU_PDC(1, 0x10) = 0x000000CD;
*GPU_PDC(1, 0x14) = 0x000000CF;
*GPU_PDC(1, 0x18) = 0x000000D1;
*GPU_PDC(1, 0x1C) = 0x01C501C1;
*GPU_PDC(1, 0x20) = 0x00010000;
*GPU_PDC(1, 0x24) = 0x0000019D;
*GPU_PDC(1, 0x28) = 0x00000052;
*GPU_PDC(1, 0x2C) = 0x00000192;
*GPU_PDC(1, 0x30) = 0x00000192;
*GPU_PDC(1, 0x34) = 0x0000004F;
*GPU_PDC(1, 0x38) = 0x00000050;
*GPU_PDC(1, 0x3C) = 0x00000052;
*GPU_PDC(1, 0x40) = 0x01980194;
*GPU_PDC(1, 0x44) = 0x00000000;
*GPU_PDC(1, 0x48) = 0x00000011;
*GPU_PDC(1, 0x5C) = 0x00F00140;
*GPU_PDC(1, 0x60) = 0x01C100d1;
*GPU_PDC(1, 0x64) = 0x01920052;
*GPU_PDC(1, 0x68) = VRAM_START;
*GPU_PDC(1, 0x6C) = VRAM_START;
*GPU_PDC(1, 0x70) = 0x00080300;
*GPU_PDC(1, 0x74) = 0x00010501;
*GPU_PDC(1, 0x78) = 0x00000000;
*GPU_PDC(1, 0x90) = 0x000003C0;
*GPU_PDC(1, 0x9C) = 0x00000000;
for (u32 i = 0; i < 256; i++)
*GPU_PDC(1, 0x84) = 0x10101 * i;
}

View File

@ -21,166 +21,21 @@
#define VBLANK_INTERRUPT (0x2A)
enum
{
PDN_GPU_CNT_RST_REGS = 1u, // And more?
PDN_GPU_CNT_RST_PSC = 1u<<1, // ?
PDN_GPU_CNT_RST_GEOSHADER = 1u<<2, // ?
PDN_GPU_CNT_RST_RASTERIZER = 1u<<3, // ?
PDN_GPU_CNT_RST_PPF = 1u<<4,
PDN_GPU_CNT_RST_PDC = 1u<<5, // ?
PDN_GPU_CNT_RST_PDC2 = 1u<<6, // Maybe pixel pipeline or so?
void LCD_SetBrightness(u8 brightness);
u8 LCD_GetBrightness(void);
PDN_GPU_CNT_RST_ALL = (PDN_GPU_CNT_RST_PDC2<<1) - 1
void LCD_Deinitialize(void);
void GPU_PSCFill(u32 start, u32 end, u32 fv);
enum {
PDC_RGBA8 = 0,
PDC_RGB24 = 1,
PDC_RGB565 = 2,
PDC_RGB5A1 = 3,
PDC_RGBA4 = 4,
};
typedef enum
{
GFX_RGBA8 = 0, ///< RGBA8. (4 bytes)
GFX_BGR8 = 1, ///< BGR8. (3 bytes)
GFX_RGB565 = 2, ///< RGB565. (2 bytes)
GFX_RGB5A1 = 3, ///< RGB5A1. (2 bytes)
GFX_RGBA4 = 4 ///< RGBA4. (2 bytes)
} GfxFbFmt;
typedef enum
{
GFX_EVENT_PSC0 = 0u,
GFX_EVENT_PSC1 = 1u,
GFX_EVENT_PDC0 = 2u,
GFX_EVENT_PDC1 = 3u,
GFX_EVENT_PPF = 4u,
GFX_EVENT_P3D = 5u
} GfxEvent;
typedef enum
{
GFX_BLIGHT_BOT = 1u<<2,
GFX_BLIGHT_TOP = 1u<<4,
GFX_BLIGHT_BOTH = GFX_BLIGHT_TOP | GFX_BLIGHT_BOT
} GfxBlight;
#define REG_CFG11_GPUPROT *((vu16*)(0x10140140))
#define REG_PDN_GPU_CNT *((vu32*)(0x10141200))
#define PDN_GPU_CNT_CLK_E (1u<<16)
#define PDN_VRAM_CNT_CLK_E (1u)
#define GX_REGS_BASE (0x10400000)
#define REG_GX_GPU_CLK *((vu32*)(GX_REGS_BASE + 0x0004)) // ?
// PSC (memory fill) regs.
#define REG_GX_PSC_FILL0_S_ADDR *((vu32*)(GX_REGS_BASE + 0x0010)) // Start address
#define REG_GX_PSC_FILL0_E_ADDR *((vu32*)(GX_REGS_BASE + 0x0014)) // End address
#define REG_GX_PSC_FILL0_VAL *((vu32*)(GX_REGS_BASE + 0x0018)) // Fill value
#define REG_GX_PSC_FILL0_CNT *((vu32*)(GX_REGS_BASE + 0x001C))
#define REG_GX_PSC_FILL1_S_ADDR *((vu32*)(GX_REGS_BASE + 0x0020))
#define REG_GX_PSC_FILL1_E_ADDR *((vu32*)(GX_REGS_BASE + 0x0024))
#define REG_GX_PSC_FILL1_VAL *((vu32*)(GX_REGS_BASE + 0x0028))
#define REG_GX_PSC_FILL1_CNT *((vu32*)(GX_REGS_BASE + 0x002C))
#define REG_GX_PSC_VRAM *((vu32*)(GX_REGS_BASE + 0x0030)) // gsp mudule only changes bit 8-11.
#define REG_GX_PSC_STAT *((vu32*)(GX_REGS_BASE + 0x0034))
// PDC0/1 regs see lcd.h.
// PPF (transfer engine) regs.
#define REG_GX_PPF_IN_ADDR *((vu32*)(GX_REGS_BASE + 0x0C00))
#define REG_GX_PPF_OUT_ADDR *((vu32*)(GX_REGS_BASE + 0x0C04))
#define REG_GX_PPF_DT_OUTDIM *((vu32*)(GX_REGS_BASE + 0x0C08)) // Display transfer output dimensions.
#define REG_GX_PPF_DT_INDIM *((vu32*)(GX_REGS_BASE + 0x0C0C)) // Display transfer input dimensions.
#define REG_GX_PPF_FlAGS *((vu32*)(GX_REGS_BASE + 0x0C10))
#define REG_GX_PPF_UNK14 *((vu32*)(GX_REGS_BASE + 0x0C14)) // Transfer interval?
#define REG_GX_PPF_CNT *((vu32*)(GX_REGS_BASE + 0x0C18))
#define REG_GX_PPF_IRQ_POS *((vu32*)(GX_REGS_BASE + 0x0C1C)) // ?
#define REG_GX_PPF_LEN *((vu32*)(GX_REGS_BASE + 0x0C20)) // Texture copy size in bytes.
#define REG_GX_PPF_TC_INDIM *((vu32*)(GX_REGS_BASE + 0x0C24)) // Texture copy input width and gap in 16 byte units.
#define REG_GX_PPF_TC_OUTDIM *((vu32*)(GX_REGS_BASE + 0x0C28)) // Texture copy output width and gap in 16 byte units.
// P3D (GPU internal) regs. See gpu_regs.h.
#define REG_GX_P3D(reg) *((vu32*)(GX_REGS_BASE + 0x1000 + ((reg) * 4)))
// LCD/ABL regs.
#define LCD_REGS_BASE (0x10202000)
#define REG_LCD_PARALLAX_CNT *((vu32*)(LCD_REGS_BASE + 0x000)) // Controls PWM for the parallax barrier?
#define REG_LCD_PARALLAX_PWM *((vu32*)(LCD_REGS_BASE + 0x004)) // Frequency/other PWM stuff maybe?
#define REG_LCD_UNK00C *((vu32*)(LCD_REGS_BASE + 0x00C)) // Wtf is "FIX"?
#define REG_LCD_RST *((vu32*)(LCD_REGS_BASE + 0x014)) // Reset active low.
#define REG_LCD_ABL0_CNT *((vu32*)(LCD_REGS_BASE + 0x200)) // Bit 0 enables ABL aka power saving mode.
#define REG_LCD_ABL0_FILL *((vu32*)(LCD_REGS_BASE + 0x204))
#define REG_LCD_ABL0_LIGHT *((vu32*)(LCD_REGS_BASE + 0x240))
#define REG_LCD_ABL0_LIGHT_PWM *((vu32*)(LCD_REGS_BASE + 0x244))
#define REG_LCD_ABL1_CNT *((vu32*)(LCD_REGS_BASE + 0xA00)) // Bit 0 enables ABL aka power saving mode.
#define REG_LCD_ABL1_FILL *((vu32*)(LCD_REGS_BASE + 0xA04))
#define REG_LCD_ABL1_LIGHT *((vu32*)(LCD_REGS_BASE + 0xA40))
#define REG_LCD_ABL1_LIGHT_PWM *((vu32*)(LCD_REGS_BASE + 0xA44))
// Technically these regs belong in gx.h but they are used for LCD configuration so...
// Pitfall warning: The 3DS LCDs are physically rotated 90° CCW.
// PDC0 (top screen display controller) regs.
#define REG_LCD_PDC0_HTOTAL *((vu32*)(GX_REGS_BASE + 0x400))
#define REG_LCD_PDC0_VTOTAL *((vu32*)(GX_REGS_BASE + 0x424))
#define REG_LCD_PDC0_HPOS *((const vu32*)(GX_REGS_BASE + 0x450))
#define REG_LCD_PDC0_VPOS *((const vu32*)(GX_REGS_BASE + 0x454))
#define REG_LCD_PDC0_FB_A1 *((vu32*)(GX_REGS_BASE + 0x468))
#define REG_LCD_PDC0_FB_A2 *((vu32*)(GX_REGS_BASE + 0x46C))
#define REG_LCD_PDC0_FMT *((vu32*)(GX_REGS_BASE + 0x470))
#define REG_LCD_PDC0_CNT *((vu32*)(GX_REGS_BASE + 0x474))
#define REG_LCD_PDC0_SWAP *((vu32*)(GX_REGS_BASE + 0x478))
#define REG_LCD_PDC0_STAT *((const vu32*)(GX_REGS_BASE + 0x47C))
#define REG_LCD_PDC0_GTBL_IDX *((vu32*)(GX_REGS_BASE + 0x480)) // Gamma table index.
#define REG_LCD_PDC0_GTBL_FIFO *((vu32*)(GX_REGS_BASE + 0x484)) // Gamma table FIFO.
#define REG_LCD_PDC0_STRIDE *((vu32*)(GX_REGS_BASE + 0x490))
#define REG_LCD_PDC0_FB_B1 *((vu32*)(GX_REGS_BASE + 0x494))
#define REG_LCD_PDC0_FB_B2 *((vu32*)(GX_REGS_BASE + 0x498))
// PDC1 (bottom screen display controller) regs.
#define REG_LCD_PDC1_HTOTAL *((vu32*)(GX_REGS_BASE + 0x500))
#define REG_LCD_PDC1_VTOTAL *((vu32*)(GX_REGS_BASE + 0x524))
#define REG_LCD_PDC1_HPOS *((const vu32*)(GX_REGS_BASE + 0x550))
#define REG_LCD_PDC1_VPOS *((const vu32*)(GX_REGS_BASE + 0x554))
#define REG_LCD_PDC1_FB_A1 *((vu32*)(GX_REGS_BASE + 0x568))
#define REG_LCD_PDC1_FB_A2 *((vu32*)(GX_REGS_BASE + 0x56C))
#define REG_LCD_PDC1_FMT *((vu32*)(GX_REGS_BASE + 0x570))
#define REG_LCD_PDC1_CNT *((vu32*)(GX_REGS_BASE + 0x574))
#define REG_LCD_PDC1_SWAP *((vu32*)(GX_REGS_BASE + 0x578))
#define REG_LCD_PDC1_STAT *((const vu32*)(GX_REGS_BASE + 0x57C))
#define REG_LCD_PDC1_GTBL_IDX *((vu32*)(GX_REGS_BASE + 0x580)) // Gamma table index.
#define REG_LCD_PDC1_GTBL_FIFO *((vu32*)(GX_REGS_BASE + 0x584)) // Gamma table FIFO.
#define REG_LCD_PDC1_STRIDE *((vu32*)(GX_REGS_BASE + 0x590))
#define REG_LCD_PDC1_FB_B1 *((vu32*)(GX_REGS_BASE + 0x594))
#define REG_LCD_PDC1_FB_B2 *((vu32*)(GX_REGS_BASE + 0x598))
// REG_LCD_PDC_CNT
#define PDC_CNT_E (1u)
#define PDC_CNT_I_MASK_H (1u<<8) // Disables H(Blank?) IRQs.
#define PDC_CNT_I_MASK_V (1u<<9) // Disables VBlank IRQs.
#define PDC_CNT_I_MASK_ERR (1u<<10) // Disables error IRQs. What kind of errors?
#define PDC_CNT_OUT_E (1u<<16) // Output enable?
// REG_LCD_PDC_SWAP
// Masks
#define PDC_SWAP_NEXT (1u) // Next framebuffer.
#define PDC_SWAP_CUR (1u<<4) // Currently displaying framebuffer?
// Bits
#define PDC_SWAP_RST_FIFO (1u<<8) // Which FIFO?
#define PDC_SWAP_I_H (1u<<16) // H(Blank?) IRQ bit.
#define PDC_SWAP_I_V (1u<<17) // VBlank IRQ bit.
#define PDC_SWAP_I_ERR (1u<<18) // Error IRQ bit?
#define PDC_SWAP_I_ALL (PDC_SWAP_I_ERR | PDC_SWAP_I_V | PDC_SWAP_I_H)
unsigned GFX_init(GfxFbFmt mode);
void GFX_setForceBlack(bool top, bool bot);
void GFX_powerOnBacklights(GfxBlight mask);
void GFX_powerOffBacklights(GfxBlight mask);
u8 GFX_getBrightness(void);
void GFX_setBrightness(u8 top, u8 bot);
void GPU_SetFramebufferMode(u32 screen, u8 mode);
void GPU_SetFramebuffers(const u32 *framebuffers);
void GPU_Init(void);

View File

@ -1,65 +1,73 @@
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#include <common.h>
#include <types.h>
#include <hid_map.h>
#include "hw/codec.h"
#include "hw/hid.h"
#include "hw/mcu.h"
#define REG_HID (~(*(vu16*)(0x10146000)) & BUTTON_ANY)
static u32 HID_ConvertCPAD(s16 cpad_x, s16 cpad_y)
{
u32 ret = 0;
if (cpad_x > 0) {
ret |= BUTTON_RIGHT;
} else if (cpad_x < 0) {
ret |= BUTTON_LEFT;
}
if (cpad_y > 0) {
ret |= BUTTON_UP;
} else if (cpad_y < 0) {
ret |= BUTTON_DOWN;
}
return ret;
}
u64 HID_GetState(void)
{
CODEC_Input codec;
u64 ret = 0;
CODEC_Get(&codec);
ret = REG_HID | mcuGetSpecialHID();
if (!(ret & BUTTON_ARROW))
ret |= HID_ConvertCPAD(codec.cpad_x, codec.cpad_y);
if (codec.ts_x <= 0xFFF)
ret |= BUTTON_TOUCH;
ret |= (((u64)codec.ts_x << 16) | (u64)codec.ts_y) << 32;
return ret;
}
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#include <common.h>
#include <types.h>
#include <hid_map.h>
#include "hw/codec.h"
#include "hw/hid.h"
#include "hw/mcu.h"
#define REG_HID (~(*(vu16*)(0x10146000)) & BUTTON_ANY)
static u32 HID_ConvertCPAD(s16 cpad_x, s16 cpad_y)
{
u32 ret = 0;
switch(int_sign(cpad_x)) {
default:
break;
case 1:
ret |= BUTTON_RIGHT;
break;
case -1:
ret |= BUTTON_LEFT;
}
switch(int_sign(cpad_y)) {
default:
break;
case 1:
ret |= BUTTON_UP;
break;
case -1:
ret |= BUTTON_DOWN;
}
return ret;
}
u64 HID_GetState(void)
{
CODEC_Input codec;
u64 ret = 0;
CODEC_Get(&codec);
ret = REG_HID | MCU_GetSpecialHID();
if (!(ret & BUTTON_ARROW))
ret |= HID_ConvertCPAD(codec.cpad_x, codec.cpad_y);
if (codec.ts_x <= 0xFFF)
ret |= BUTTON_TOUCH;
ret |= (((u64)codec.ts_x << 16) | (u64)codec.ts_y) << 32;
return ret;
}

View File

@ -1,24 +1,24 @@
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
#include <hid_map.h>
u64 HID_GetState(void);
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
#include <hid_map.h>
u64 HID_GetState(void);

View File

@ -31,9 +31,6 @@
#define I2C_IRQ_ENABLE (1u<<6)
#define I2C_ENABLE (1u<<7)
#define I2C_DEV_LCD0 5
#define I2C_DEV_LCD1 6
#define I2C_GET_ACK(reg) ((bool)((reg)>>4 & 1u))
@ -65,13 +62,3 @@ bool I2C_readRegBuf(int devId, u8 regAddr, u8 *out, u32 size);
* @return Returns true on success and false on failure.
*/
bool I2C_writeRegBuf(int devId, u8 regAddr, const u8 *in, u32 size);
static inline u8 I2C_readReg(int devId, u8 regAddr) {
u8 v;
I2C_readRegBuf(devId, regAddr, &v, 1);
return v;
}
static inline void I2C_writeReg(int devId, u8 regAddr, u8 v) {
I2C_writeRegBuf(devId, regAddr, &v, 1);
}

View File

@ -20,39 +20,40 @@
#include <types.h>
#include <arm.h>
#include <stdatomic.h>
#include "common.h"
#include "arm/timer.h"
#include "hw/gpio.h"
#include "hw/gpulcd.h"
#include "hw/mcu.h"
#include "system/event.h"
#define MCUEV_HID_MASK ( \
MCUEV_HID_PWR_DOWN | MCUEV_HID_PWR_HOLD | \
MCUEV_HID_HOME_DOWN | MCUEV_HID_HOME_UP | MCUEV_HID_WIFI_SWITCH)
enum {
MCU_PWR_BTN = 0,
MCU_PWR_HOLD = 1,
MCU_HOME_BTN = 2,
MCU_HOME_LIFT = 3,
MCU_WIFI_SWITCH = 4,
MCU_SHELL_CLOSE = 5,
MCU_SHELL_OPEN = 6,
MCU_VOL_SLIDER = 22,
};
enum {
MCUREG_VOLUME_SLIDER = 0x09,
REG_VOL_SLIDER = 0x09,
MCUREG_BATTERY_LEVEL = 0x0B,
MCUREG_CONSOLE_STATE = 0x0F,
REG_BATTERY_LEVEL = 0x0B,
REG_CONSOLE_STATE = 0x0F,
MCUREG_INT_MASK = 0x10,
MCUREG_INT_EN = 0x18,
REG_INT_MASK = 0x10,
REG_INT_EN = 0x18,
MCUREG_LCD_STATE = 0x22,
REG_LCD_STATE = 0x22,
MCUREG_LED_WIFI = 0x2A,
MCUREG_LED_CAMERA = 0x2B,
MCUREG_LED_SLIDER = 0x2C,
MCUREG_LED_STATUS = 0x2D,
REG_LED_WIFI = 0x2A,
REG_LED_CAMERA = 0x2B,
REG_LED_SLIDER = 0x2C,
REG_LED_NOTIF = 0x2D,
MCUREG_RTC = 0x30,
REG_RTC = 0x30,
};
typedef struct {
@ -63,70 +64,47 @@ typedef struct {
u32 red[8];
u32 green[8];
u32 blue[8];
} PACKED_STRUCT mcuStatusLED;
} PACKED_STRUCT MCU_NotificationLED;
static u8 volumeSliderValue;
static u32 shellState;
static _Atomic(u32) pendingEvents;
static u8 cached_volume_slider = 0;
static u32 spec_hid = 0, shell_state = SHELL_OPEN;
static void mcuEventUpdate(void)
static void MCU_UpdateVolumeSlider(void)
{
u32 mask;
// lazily update the mask on each test attempt
if (!getEventIRQ()->test(MCU_INTERRUPT, true))
return;
// reading the pending mask automagically acknowledges
// the interrupts so all of them must be processed in one go
mcuReadRegBuf(MCUREG_INT_MASK, (u8*)&mask, sizeof(mask));
if (mask & MCUEV_HID_VOLUME_SLIDER)
volumeSliderValue = mcuReadReg(MCUREG_VOLUME_SLIDER);
if (mask & MCUEV_HID_SHELL_OPEN) {
mcuResetLEDs();
shellState = SHELL_OPEN;
}
if (mask & MCUEV_HID_SHELL_CLOSE) {
shellState = SHELL_CLOSED;
}
atomic_fetch_or(&pendingEvents, mask);
cached_volume_slider = MCU_ReadReg(REG_VOL_SLIDER);
}
u8 mcuGetVolumeSlider(void)
static void MCU_UpdateShellState(bool open)
{
mcuEventUpdate();
return volumeSliderValue;
shell_state = open ? SHELL_OPEN : SHELL_CLOSED;
}
u32 mcuGetSpecialHID(void)
u8 MCU_GetVolumeSlider(void)
{
u32 ret = 0, pend = getEventMCU()->test(MCUEV_HID_MASK, MCUEV_HID_MASK);
// hopefully gets unrolled
if (pend & (MCUEV_HID_PWR_DOWN | MCUEV_HID_PWR_HOLD))
ret |= BUTTON_POWER;
if (pend & MCUEV_HID_HOME_DOWN)
ret |= BUTTON_HOME;
if (pend & MCUEV_HID_HOME_UP)
ret &= ~BUTTON_HOME;
return ret | shellState;
return cached_volume_slider;
}
void mcuSetStatusLED(u32 period_ms, u32 color)
u32 MCU_GetSpecialHID(void)
{
u32 r, g, b, delay;
mcuStatusLED ledState;
u32 ret = spec_hid | shell_state;
spec_hid = 0;
return ret;
}
delay = clamp((period_ms * 0x200) / 1000, 1, 0xFF);
void MCU_SetNotificationLED(u32 period_ms, u32 color)
{
u32 r, g, b;
MCU_NotificationLED led_state;
ledState.delay = delay;
ledState.smoothing = delay;
ledState.loop_delay = 0x10;
ledState.unk = 0;
// handle proper non-zero periods
// so small the hardware can't handle it
if (period_ms != 0 && period_ms < 63)
period_ms = 63;
led_state.delay = (period_ms * 0x10) / 1000;
led_state.smoothing = 0x40;
led_state.loop_delay = 0x10;
led_state.unk = 0;
// all colors look like 0x00ZZ00ZZ
// in order to alternate between
@ -134,65 +112,100 @@ void mcuSetStatusLED(u32 period_ms, u32 color)
r = (color >> 16) & 0xFF;
r |= r << 16;
for (int i = 0; i < 8; i++)
ledState.red[i] = r;
led_state.red[i] = r;
g = (color >> 8) & 0xFF;
g |= g << 16;
for (int i = 0; i < 8; i++)
ledState.green[i] = g;
led_state.green[i] = g;
b = color & 0xFF;
b |= b << 16;
for (int i = 0; i < 8; i++)
ledState.blue[i] = b;
led_state.blue[i] = b;
mcuWriteRegBuf(MCUREG_LED_STATUS, (const u8*)&ledState, sizeof(ledState));
MCU_WriteRegBuf(REG_LED_NOTIF, (const u8*)&led_state, sizeof(led_state));
}
void mcuResetLEDs(void)
void MCU_ResetLED(void)
{
mcuWriteReg(MCUREG_LED_WIFI, 0);
mcuWriteReg(MCUREG_LED_CAMERA, 0);
mcuWriteReg(MCUREG_LED_SLIDER, 0);
mcuSetStatusLED(0, 0);
MCU_WriteReg(REG_LED_WIFI, 0);
MCU_WriteReg(REG_LED_CAMERA, 0);
MCU_WriteReg(REG_LED_SLIDER, 0);
MCU_SetNotificationLED(0, 0);
}
void mcuReset(void)
void MCU_PushToLCD(bool enable)
{
u32 intmask = 0;
MCU_WriteReg(REG_LCD_STATE, enable ? 0x2A : 0x01);
}
atomic_init(&pendingEvents, 0);
void MCU_HandleInterrupts(u32 __attribute__((unused)) irqn)
{
u32 ints;
// set register mask and clear any pending registers
mcuWriteRegBuf(MCUREG_INT_EN, (const u8*)&intmask, sizeof(intmask));
mcuReadRegBuf(MCUREG_INT_MASK, (u8*)&intmask, sizeof(intmask));
// Reading the pending mask automagically acknowledges
// the interrupts so all of them must be processed in one go
MCU_ReadRegBuf(REG_INT_MASK, (u8*)&ints, sizeof(ints));
mcuResetLEDs();
while(ints != 0) {
u32 mcu_int_id = 31 - __builtin_clz(ints);
volumeSliderValue = mcuReadReg(MCUREG_VOLUME_SLIDER);
shellState = SHELL_OPEN;
// assume the shell is always open on boot
// knowing the average 3DS user, there will be plenty
// of laughs when this comes back to bite us in the rear
switch(mcu_int_id) {
case MCU_PWR_BTN:
case MCU_PWR_HOLD:
spec_hid |= BUTTON_POWER;
break;
case MCU_HOME_BTN:
spec_hid |= BUTTON_HOME;
break;
case MCU_HOME_LIFT:
spec_hid &= ~BUTTON_HOME;
break;
case MCU_WIFI_SWITCH:
spec_hid |= BUTTON_WIFI;
break;
case MCU_SHELL_OPEN:
MCU_PushToLCD(true);
MCU_UpdateShellState(true);
TIMER_WaitTicks(CLK_MS_TO_TICKS(5));
MCU_ResetLED();
break;
case MCU_SHELL_CLOSE:
MCU_PushToLCD(false);
MCU_UpdateShellState(false);
TIMER_WaitTicks(CLK_MS_TO_TICKS(5));
break;
case MCU_VOL_SLIDER:
MCU_UpdateVolumeSlider();
break;
default:
break;
}
ints &= ~BIT(mcu_int_id);
}
}
void MCU_Init(void)
{
u32 clrpend, mask = 0xFFBF0800;
/* set register mask and clear any pending registers */
MCU_WriteRegBuf(REG_INT_EN, (const u8*)&mask, sizeof(mask));
MCU_ReadRegBuf(REG_INT_MASK, (u8*)&clrpend, sizeof(clrpend));
MCU_ResetLED();
MCU_UpdateVolumeSlider();
MCU_UpdateShellState(MCU_ReadReg(REG_CONSOLE_STATE) & BIT(1));
GPIO_setBit(19, 9);
}
static void evReset(void) {
atomic_store(&pendingEvents, 0);
}
static u32 evTest(u32 mask, u32 clear) {
mcuEventUpdate();
return atomic_fetch_and(&pendingEvents, ~clear) & mask;
}
static const EventInterface evMCU = {
.reset = evReset,
.test = evTest
};
const EventInterface *getEventMCU(void) {
return &evMCU;
}

View File

@ -1,73 +1,60 @@
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
#include "arm/timer.h"
#include "hw/i2c.h"
#define MCU_INTERRUPT (0x71)
#define I2C_MCU_DEVICE (3)
enum {
MCUEV_HID_PWR_DOWN = BIT(0),
MCUEV_HID_PWR_HOLD = BIT(1),
MCUEV_HID_HOME_DOWN = BIT(2),
MCUEV_HID_HOME_UP = BIT(3),
MCUEV_HID_WIFI_SWITCH = BIT(4),
MCUEV_HID_SHELL_CLOSE = BIT(5),
MCUEV_HID_SHELL_OPEN = BIT(6),
MCUEV_HID_VOLUME_SLIDER = BIT(22),
};
u8 mcuGetVolumeSlider(void);
u32 mcuGetSpecialHID(void);
void mcuSetStatusLED(u32 period_ms, u32 color);
void mcuResetLEDs(void);
void mcuReset(void);
static inline u8 mcuReadReg(u8 addr)
{
u8 val;
I2C_readRegBuf(I2C_MCU_DEVICE, addr, &val, 1);
return val;
}
static inline bool mcuReadRegBuf(u8 addr, u8 *buf, u32 size)
{
return I2C_readRegBuf(I2C_MCU_DEVICE, addr, buf, size);
}
static inline bool mcuWriteReg(u8 addr, u8 val)
{
return I2C_writeRegBuf(I2C_MCU_DEVICE, addr, &val, 1);
}
static inline bool mcuWriteRegBuf(u8 addr, const u8 *buf, u32 size)
{
return I2C_writeRegBuf(I2C_MCU_DEVICE, addr, buf, size);
}
static inline void MCU_controlLCDPower(u8 bits)
{
mcuWriteReg(0x22u, bits);
}
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
#include "hw/i2c.h"
#define MCU_INTERRUPT (0x71)
#define I2C_MCU_DEVICE (3)
u8 MCU_GetVolumeSlider(void);
u32 MCU_GetSpecialHID(void);
void MCU_SetNotificationLED(u32 period_ms, u32 color);
void MCU_ResetLED(void);
void MCU_PushToLCD(bool enable);
void MCU_HandleInterrupts(u32 irqn);
void MCU_Init(void);
static inline u8 MCU_ReadReg(u8 addr)
{
u8 val;
I2C_readRegBuf(I2C_MCU_DEVICE, addr, &val, 1);
return val;
}
static inline bool MCU_ReadRegBuf(u8 addr, u8 *buf, u32 size)
{
return I2C_readRegBuf(I2C_MCU_DEVICE, addr, buf, size);
}
static inline bool MCU_WriteReg(u8 addr, u8 val)
{
return I2C_writeRegBuf(I2C_MCU_DEVICE, addr, &val, 1);
}
static inline bool MCU_WriteRegBuf(u8 addr, const u8 *buf, u32 size)
{
return I2C_writeRegBuf(I2C_MCU_DEVICE, addr, buf, size);
}

View File

@ -1,93 +1,93 @@
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#include <types.h>
#include <spi.h>
#include "hw/nvram.h"
// returns manuf id, memory type and size
// size = (1 << id[2]) ?
// apparently unreliable on some Sanyo chips?
#define CMD_RDID 0x9F
#define CMD_READ 0x03
#define CMD_WREN 0x06
#define CMD_WRDI 0x04
#define CMD_RDSR 0x05
#define CMD_DPD 0xB9 // deep power down
#define CMD_RDP 0xAB // release from deep power down
static u32 NVRAM_SendStatusCommand(u32 cmd, u32 width)
{
u32 ret;
SPI_XferInfo xfer[2];
xfer[0].buf = &cmd;
xfer[0].len = 1;
xfer[0].read = false;
xfer[1].buf = &ret;
xfer[1].len = width;
xfer[1].read = true;
ret = 0;
SPI_DoXfer(SPI_DEV_NVRAM, xfer, 2, true);
return ret;
}
u32 NVRAM_Status(void)
{
return NVRAM_SendStatusCommand(CMD_RDSR, 1);
}
u32 NVRAM_ReadID(void)
{
return NVRAM_SendStatusCommand(CMD_RDID, 3);
}
void NVRAM_DeepStandby(void)
{
NVRAM_SendStatusCommand(CMD_DPD, 0);
}
void NVRAM_Wakeup(void)
{
NVRAM_SendStatusCommand(CMD_RDP, 0);
}
void NVRAM_Read(u32 address, u32 *buffer, u32 len)
{
SPI_XferInfo xfer[2];
u32 cmd;
address &= BIT(24) - 1;
cmd = __builtin_bswap32(address) | CMD_READ;
xfer[0].buf = &cmd;
xfer[0].len = 4;
xfer[0].read = false;
xfer[1].buf = buffer;
xfer[1].len = len;
xfer[1].read = true;
SPI_DoXfer(SPI_DEV_NVRAM, xfer, 2, true);
}
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#include <types.h>
#include <spi.h>
#include "hw/nvram.h"
// returns manuf id, memory type and size
// size = (1 << id[2]) ?
// apparently unreliable on some Sanyo chips?
#define CMD_RDID 0x9F
#define CMD_READ 0x03
#define CMD_WREN 0x06
#define CMD_WRDI 0x04
#define CMD_RDSR 0x05
#define CMD_DPD 0xB9 // deep power down
#define CMD_RDP 0xAB // release from deep power down
static u32 NVRAM_SendStatusCommand(u32 cmd, u32 width)
{
u32 ret;
SPI_XferInfo xfer[2];
xfer[0].buf = &cmd;
xfer[0].len = 1;
xfer[0].read = false;
xfer[1].buf = &ret;
xfer[1].len = width;
xfer[1].read = true;
ret = 0;
SPI_DoXfer(SPI_DEV_NVRAM, xfer, 2, true);
return ret;
}
u32 NVRAM_Status(void)
{
return NVRAM_SendStatusCommand(CMD_RDSR, 1);
}
u32 NVRAM_ReadID(void)
{
return NVRAM_SendStatusCommand(CMD_RDID, 3);
}
void NVRAM_DeepStandby(void)
{
NVRAM_SendStatusCommand(CMD_DPD, 0);
}
void NVRAM_Wakeup(void)
{
NVRAM_SendStatusCommand(CMD_RDP, 0);
}
void NVRAM_Read(u32 address, u32 *buffer, u32 len)
{
SPI_XferInfo xfer[2];
u32 cmd;
address &= BIT(24) - 1;
cmd = __builtin_bswap32(address) | CMD_READ;
xfer[0].buf = &cmd;
xfer[0].len = 4;
xfer[0].read = false;
xfer[1].buf = buffer;
xfer[1].len = len;
xfer[1].read = true;
SPI_DoXfer(SPI_DEV_NVRAM, xfer, 2, true);
}

View File

@ -1,34 +1,34 @@
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
#include <spi.h>
#define NVRAM_SR_WIP BIT(0) // work in progress / busy
#define NVRAM_SR_WEL BIT(1) // write enable latch
u32 NVRAM_Status(void);
u32 NVRAM_ReadID(void);
void NVRAM_Read(u32 offset, u32 *buffer, u32 len);
void NVRAM_DeepStandby(void);
void NVRAM_Wakeup(void);
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
#include <spi.h>
#define NVRAM_SR_WIP BIT(0) // work in progress / busy
#define NVRAM_SR_WEL BIT(1) // write enable latch
u32 NVRAM_Status(void);
u32 NVRAM_ReadID(void);
void NVRAM_Read(u32 offset, u32 *buffer, u32 len);
void NVRAM_DeepStandby(void);
void NVRAM_Wakeup(void);

View File

@ -31,198 +31,180 @@
#include "hw/nvram.h"
#include "system/sys.h"
#include "system/event.h"
#include "system/xalloc.h"
static GlobalSharedMemory SharedMemory_State;
#ifndef FIXED_BRIGHTNESS
static const u8 brightness_lvls[] = {
0x10, 0x17, 0x1E, 0x25,
0x2C, 0x34, 0x3C, 0x44,
0x4D, 0x56, 0x60, 0x6B,
0x79, 0x8C, 0xA7, 0xD2
};
#ifndef FIXED_BRIGHTNESS
static int prev_bright_lvl;
static bool auto_brightness;
static int prev_bright_lvl = -1;
#endif
static SystemSHMEM __attribute__((section(".shared"))) sharedMem;
static bool auto_brightness = true;
static void vblankUpdate(void)
void VBlank_Handler(u32 __attribute__((unused)) irqn)
{
if (!getEventIRQ()->test(VBLANK_INTERRUPT, true))
return;
#ifndef FIXED_BRIGHTNESS
int cur_bright_lvl = (mcuGetVolumeSlider() >> 2) % countof(brightness_lvls);
int cur_bright_lvl = (MCU_GetVolumeSlider() >> 2) % countof(brightness_lvls);
if ((cur_bright_lvl != prev_bright_lvl) && auto_brightness) {
prev_bright_lvl = cur_bright_lvl;
u8 br = brightness_lvls[cur_bright_lvl];
GFX_setBrightness(br, br);
LCD_SetBrightness(brightness_lvls[cur_bright_lvl]);
}
#endif
// handle shell events
static const u32 mcuEvShell = MCUEV_HID_SHELL_OPEN | MCUEV_HID_SHELL_CLOSE;
u32 shell = getEventMCU()->test(mcuEvShell, mcuEvShell);
if (shell & MCUEV_HID_SHELL_CLOSE) {
GFX_powerOffBacklights(GFX_BLIGHT_BOTH);
} else if (shell & MCUEV_HID_SHELL_OPEN) {
GFX_powerOnBacklights(GFX_BLIGHT_BOTH);
}
sharedMem.hidState.full = HID_GetState();
// the state should probably be stored on its own
// section without caching enabled, since it must
// be readable by the ARM9 at all times anyway
SharedMemory_State.hid_state = HID_GetState();
ARM_WbDC_Range(&SharedMemory_State, sizeof(SharedMemory_State));
ARM_DMB();
}
static u32 pxiRxUpdate(u32 *args)
{
u32 msg, lo, hi;
static bool legacy_boot = false;
if (!getEventIRQ()->test(PXI_RX_INTERRUPT, true))
return PXICMD_NONE;
void PXI_RX_Handler(u32 __attribute__((unused)) irqn)
{
u32 ret, msg, cmd, argc, args[PXI_MAX_ARGS];
msg = PXI_Recv();
lo = msg & 0xFFFF;
hi = msg >> 16;
cmd = msg & 0xFFFF;
argc = msg >> 16;
PXI_RecvArray(args, hi);
return lo;
if (argc >= PXI_MAX_ARGS) {
PXI_Send(0xFFFFFFFF);
return;
}
PXI_RecvArray(args, argc);
switch (cmd) {
case PXI_LEGACY_MODE:
{
// TODO: If SMP is enabled, an IPI should be sent here (with a DSB)
legacy_boot = true;
ret = 0;
break;
}
case PXI_GET_SHMEM:
{
ret = (u32)&SharedMemory_State;
break;
}
case PXI_SET_VMODE:
{
int mode = args[0] ? PDC_RGB24 : PDC_RGB565;
GPU_SetFramebufferMode(0, mode);
GPU_SetFramebufferMode(1, mode);
ret = 0;
break;
}
case PXI_I2C_READ:
{
ARM_InvDC_Range((void*)args[2], args[3]);
ret = I2C_readRegBuf(args[0], args[1], (u8*)args[2], args[3]);
ARM_WbDC_Range((void*)args[2], args[3]);
ARM_DMB();
break;
}
case PXI_I2C_WRITE:
{
ARM_InvDC_Range((void*)args[2], args[3]);
ARM_DMB();
ret = I2C_writeRegBuf(args[0], args[1], (u8*)args[2], args[3]);
break;
}
case PXI_NVRAM_ONLINE:
{
ret = (NVRAM_Status() & NVRAM_SR_WIP) == 0;
break;
}
case PXI_NVRAM_READ:
{
ARM_InvDC_Range((void*)args[1], args[2]);
NVRAM_Read(args[0], (u32*)args[1], args[2]);
ARM_WbDC_Range((void*)args[1], args[2]);
ARM_DMB();
ret = 0;
break;
}
case PXI_NOTIFY_LED:
{
MCU_SetNotificationLED(args[0], args[1]);
ret = 0;
break;
}
case PXI_BRIGHTNESS:
{
ret = LCD_GetBrightness();
if ((args[0] > 0) && (args[0] < 0x100)) {
LCD_SetBrightness(args[0]);
auto_brightness = false;
} else {
prev_bright_lvl = -1;
auto_brightness = true;
}
break;
}
case PXI_XALLOC:
{
ret = (u32)XAlloc(args[0]);
break;
}
/* New CMD template:
case CMD_ID:
{
<var declarations/assignments>
<execute the command>
<set the return value>
break;
}
*/
default:
ret = 0xFFFFFFFF;
break;
}
PXI_Send(ret);
}
void __attribute__((noreturn)) MainLoop(void)
{
bool runPxiCmdProcessor = true;
#ifdef FIXED_BRIGHTNESS
u8 fixed_bright_lvl = brightness_lvls[clamp(FIXED_BRIGHTNESS, 0, countof(brightness_lvls)-1)];
GFX_setBrightness(fixed_bright_lvl, fixed_bright_lvl);
#else
prev_bright_lvl = -1;
auto_brightness = true;
LCD_SetBrightness(FIXED_BRIGHTNESS);
#endif
// initialize state stuff
getEventIRQ()->reset();
getEventMCU()->reset();
memset(&sharedMem, 0, sizeof(sharedMem));
// enable PXI RX interrupt
GIC_Enable(PXI_RX_INTERRUPT, BIT(0), GIC_HIGHEST_PRIO + 2, PXI_RX_Handler);
// configure interrupts
gicSetInterruptConfig(PXI_RX_INTERRUPT, BIT(0), GIC_PRIO0, NULL);
gicSetInterruptConfig(VBLANK_INTERRUPT, BIT(0), GIC_PRIO0, NULL);
gicSetInterruptConfig(MCU_INTERRUPT, BIT(0), GIC_PRIO0, NULL);
// enable MCU interrupts
GIC_Enable(MCU_INTERRUPT, BIT(0), GIC_HIGHEST_PRIO + 1, MCU_HandleInterrupts);
// enable interrupts
gicEnableInterrupt(MCU_INTERRUPT);
// perform gpu init after initializing mcu but before
// enabling the pxi system and the vblank handler
GFX_init(GFX_RGB565);
gicEnableInterrupt(PXI_RX_INTERRUPT);
gicEnableInterrupt(VBLANK_INTERRUPT);
// set up VBlank interrupt to always have the highest priority
GIC_Enable(VBLANK_INTERRUPT, BIT(0), GIC_HIGHEST_PRIO, VBlank_Handler);
// ARM9 won't try anything funny until this point
PXI_Barrier(PXI_BOOT_BARRIER);
PXI_Barrier(ARM11_READY_BARRIER);
// Process commands until the ARM9 tells
// us it's time to boot something else
// also handles VBlank events as needed
// Process IRQs until the ARM9 tells us it's time to boot something else
do {
u32 pxiCmd, pxiReply, args[PXI_MAX_ARGS];
vblankUpdate();
pxiCmd = pxiRxUpdate(args);
switch(pxiCmd) {
// ignore args and just wait until the next event
case PXICMD_NONE:
ARM_WFI();
break;
// revert to legacy boot mode
case PXICMD_LEGACY_BOOT:
runPxiCmdProcessor = false;
pxiReply = 0;
break;
// returns the shared memory address
case PXICMD_GET_SHMEM_ADDRESS:
pxiReply = (u32)&sharedMem;
break;
// takes in a single argument word and performs either an
// I2C read or write depending on the value of the top bit
case PXICMD_I2C_OP:
{
u32 devId, regAddr, size;
devId = (args[0] & 0xff);
regAddr = (args[0] >> 8) & 0xFF;
size = (args[0] >> 16) % SHMEM_BUFFER_SIZE;
if (args[0] & BIT(31)) {
pxiReply = I2C_writeRegBuf(devId, regAddr, sharedMem.dataBuffer.b, size);
} else {
pxiReply = I2C_readRegBuf(devId, regAddr, sharedMem.dataBuffer.b, size);
}
break;
}
// checks whether the NVRAM chip is online (not doing any work)
case PXICMD_NVRAM_ONLINE:
pxiReply = (NVRAM_Status() & NVRAM_SR_WIP) == 0;
break;
// reads data from the NVRAM chip
case PXICMD_NVRAM_READ:
NVRAM_Read(args[0], sharedMem.dataBuffer.w, args[1]);
pxiReply = 0;
break;
// sets the notification LED with the given color and period
case PXICMD_SET_NOTIFY_LED:
mcuSetStatusLED(args[0], args[1]);
pxiReply = 0;
break;
// sets the LCDs brightness (if FIXED_BRIGHTNESS is disabled)
case PXICMD_SET_BRIGHTNESS:
{
pxiReply = GFX_getBrightness();
#ifndef FIXED_BRIGHTNESS
s32 newbrightness = (s32)args[0];
if ((newbrightness > 0) && (newbrightness < 0x100)) {
GFX_setBrightness(newbrightness, newbrightness);
auto_brightness = false;
} else {
prev_bright_lvl = -1;
auto_brightness = true;
}
#endif
break;
}
// replies -1 on default
default:
pxiReply = 0xFFFFFFFF;
break;
}
if (pxiCmd != PXICMD_NONE)
PXI_Send(pxiReply); // was a command sent from the ARM9, send a response
} while(runPxiCmdProcessor);
// perform deinit in reverse order
gicDisableInterrupt(VBLANK_INTERRUPT);
gicDisableInterrupt(PXI_RX_INTERRUPT);
// unconditionally reinitialize the screens
// in RGB24 framebuffer mode
GFX_init(GFX_BGR8);
gicDisableInterrupt(MCU_INTERRUPT);
// Wait for the ARM9 to do its firmlaunch setup
PXI_Barrier(PXI_FIRMLAUNCH_BARRIER);
ARM_WFI();
} while(!legacy_boot);
SYS_CoreZeroShutdown();
SYS_CoreShutdown();

View File

@ -1,26 +0,0 @@
#pragma once
#include <types.h>
typedef struct {
void (*reset)(void);
u32 (*test)(u32 param, u32 clear);
} EventInterface;
const EventInterface *getEventIRQ(void);
const EventInterface *getEventMCU(void);
static inline void eventReset(const EventInterface *ei) {
ei->reset();
}
static inline u32 eventTest(const EventInterface *ei, u32 param, u32 clear) {
return ei->test(param, clear);
}
static inline u32 eventWait(const EventInterface *ei, u32 param, u32 clear) {
while(1) {
u32 ret = ei->test(param, clear);
if (ret) return ret;
}
}

View File

@ -1,35 +1,35 @@
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
#define DEF_SECT_(n) extern u32 __##n##_pa, __##n##_va, __##n##_va_end;
DEF_SECT_(text)
DEF_SECT_(data)
DEF_SECT_(rodata)
DEF_SECT_(bss)
DEF_SECT_(shared)
#undef DEF_SECT_
#define SECTION_VA(n) ((u32)&__##n##_va)
#define SECTION_PA(n) ((u32)&__##n##_pa)
#define SECTION_LEN(n) (((u32)(&__##n##_va_end) - (u32)(&__##n##_va)))
#define SECTION_TRI(n) SECTION_VA(n), SECTION_PA(n), SECTION_LEN(n)
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
#define DEF_SECT_(n) extern u32 __##n##_pa, __##n##_va, __##n##_len;
DEF_SECT_(vector)
DEF_SECT_(text)
DEF_SECT_(data)
DEF_SECT_(rodata)
DEF_SECT_(bss)
#undef DEF_SECT_
#define SECTION_VA(n) ((u32)&__##n##_va)
#define SECTION_PA(n) ((u32)&__##n##_pa)
#define SECTION_LEN(n) ((u32)&__##n##_len)
#define SECTION_TRI(n) SECTION_VA(n), SECTION_PA(n), SECTION_LEN(n)

View File

@ -24,7 +24,7 @@
#include "arm/gic.h"
#include "arm/mmu.h"
#include "arm/scu.h"
#include "arm/xrq.h"
#include "arm/timer.h"
#include "hw/codec.h"
#include "hw/gpulcd.h"
@ -57,20 +57,18 @@ static void SYS_EnableClkMult(void)
// state might get a bit messed up so it has to be done
// as early as possible in the initialization chain
if (SYS_IsNewConsole() && !SYS_ClkMultEnabled()) {
gicSetInterruptConfig(88, BIT(0), GIC_PRIO_HIGHEST, NULL);
gicEnableInterrupt(88);
GIC_Enable(88, BIT(0), GIC_HIGHEST_PRIO, NULL);
*CFG11_MPCORE_CLKCNT = 0x8001;
do {
ARM_WFI();
} while(!(*CFG11_MPCORE_CLKCNT & 0x8000));
gicDisableInterrupt(88);
gicClearInterruptConfig(88);
GIC_Disable(88, BIT(0));
}
}
void SYS_CoreZeroInit(void)
{
gicGlobalReset();
GIC_GlobalReset();
*LEGACY_BOOT_ENTRYPOINT = 0;
@ -79,54 +77,57 @@ void SYS_CoreZeroInit(void)
SCU_Init();
// Map all sections here
mmuMapArea(SECTION_TRI(text), MMU_FLAGS(MMU_CACHE_WT, MMU_READ_ONLY, 0, 1));
mmuMapArea(SECTION_TRI(data), MMU_FLAGS(MMU_CACHE_WBA, MMU_READ_WRITE, 1, 1));
mmuMapArea(SECTION_TRI(rodata), MMU_FLAGS(MMU_CACHE_WT, MMU_READ_ONLY, 1, 1));
mmuMapArea(SECTION_TRI(bss), MMU_FLAGS(MMU_CACHE_WBA, MMU_READ_WRITE, 1, 1));
mmuMapArea(SECTION_TRI(shared), MMU_FLAGS(MMU_STRONG_ORDER, MMU_READ_WRITE, 1, 1));
// High exception vectors
mmuMapArea(0xFFFF0000, xrqInstallVectorTable(), 4UL << 10, MMU_FLAGS(MMU_CACHE_WT, MMU_READ_ONLY, 0, 0));
// BootROM
mmuMapArea(0x00010000, 0x00010000, 32UL << 10, MMU_FLAGS(MMU_CACHE_WT, MMU_READ_ONLY, 0, 1));
MMU_Map(SECTION_TRI(vector), MMU_FLAGS(CACHED_WT, READ_ONLY, 0, 0));
MMU_Map(SECTION_TRI(text), MMU_FLAGS(CACHED_WT, READ_ONLY, 0, 1));
MMU_Map(SECTION_TRI(data), MMU_FLAGS(CACHED_WB_ALLOC, READ_WRITE, 1, 1));
MMU_Map(SECTION_TRI(rodata), MMU_FLAGS(CACHED_WT, READ_ONLY, 1, 1));
MMU_Map(SECTION_TRI(bss), MMU_FLAGS(CACHED_WB_ALLOC, READ_WRITE, 1, 1));
// IO Registers
mmuMapArea(0x10100000, 0x10100000, 4UL << 20, MMU_FLAGS(MMU_DEV_SHARED, MMU_READ_WRITE, 1, 1));
MMU_Map(0x10100000, 0x10100000, 4UL << 20, MMU_FLAGS(DEVICE_SHARED, READ_WRITE, 1, 1));
// MPCore Private Memory Region
mmuMapArea(0x17E00000, 0x17E00000, 8UL << 10, MMU_FLAGS(MMU_DEV_SHARED, MMU_READ_WRITE, 1, 1));
MMU_Map(0x17E00000, 0x17E00000, 8UL << 10, MMU_FLAGS(DEVICE_SHARED, READ_WRITE, 1, 1));
// VRAM
mmuMapArea(0x18000000, 0x18000000, 6UL << 20, MMU_FLAGS(MMU_CACHE_WT, MMU_READ_WRITE, 1, 1));
MMU_Map(0x18000000, 0x18000000, 6UL << 20, MMU_FLAGS(CACHED_WT, READ_WRITE, 1, 1));
// FCRAM
if (SYS_IsNewConsole()) {
mmuMapArea(0x20000000, 0x20000000, 256UL << 20, MMU_FLAGS(MMU_CACHE_WB, MMU_READ_WRITE, 1, 1));
MMU_Map(0x20000000, 0x20000000, 256UL << 20, MMU_FLAGS(CACHED_WB, READ_WRITE, 1, 1));
} else {
mmuMapArea(0x20000000, 0x20000000, 128UL << 20, MMU_FLAGS(MMU_CACHE_WB, MMU_READ_WRITE, 1, 1));
MMU_Map(0x20000000, 0x20000000, 128UL << 20, MMU_FLAGS(CACHED_WB, READ_WRITE, 1, 1));
}
// screen init magicks
TIMER_WaitMS(64);
// Initialize peripherals
PXI_Reset();
I2C_init();
mcuReset();
MCU_Init();
SPI_Init();
CODEC_Init();
GPU_Init();
GPU_PSCFill(VRAM_START, VRAM_END, 0);
GPU_SetFramebuffers((u32[]){VRAM_TOP_LA, VRAM_TOP_LB,
VRAM_TOP_RA, VRAM_TOP_RB,
VRAM_BOT_A, VRAM_BOT_B});
GPU_SetFramebufferMode(0, PDC_RGB24);
GPU_SetFramebufferMode(1, PDC_RGB24);
MCU_PushToLCD(true);
TIMER_WaitTicks(CLK_MS_TO_TICKS(5));
}
void SYS_CoreInit(void)
{
// Reset local GIC registers
gicLocalReset();
GIC_LocalReset();
// Set up MMU registers
mmuInitRegisters();
MMU_Init();
// Enable fancy ARM11 features
ARM_SetACR(ARM_GetACR() |
@ -143,7 +144,7 @@ void SYS_CoreInit(void)
void SYS_CoreZeroShutdown(void)
{
ARM_DisableInterrupts();
gicGlobalReset();
GIC_GlobalReset();
}
void __attribute__((noreturn)) SYS_CoreShutdown(void)
@ -152,7 +153,7 @@ void __attribute__((noreturn)) SYS_CoreShutdown(void)
ARM_DisableInterrupts();
gicLocalReset();
GIC_LocalReset();
ARM_WbInvDC();
ARM_InvIC();

View File

@ -1,38 +1,38 @@
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
/*
how to run the SYS_Core(Zero){Init,Shutdown} functions:
for init:
- FIRST run CoreZeroInit ONCE
- all cores must run CoreInit ONCE
for shutdown:
- all non-zero cores must call CoreShutdown
- core zero must call CoreZeroShutdown, then CoreShutdown
*/
void SYS_CoreZeroInit(void);
void SYS_CoreInit(void);
void SYS_CoreZeroShutdown(void);
void __attribute__((noreturn)) SYS_CoreShutdown(void);
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include <types.h>
/*
how to run the SYS_Core(Zero){Init,Shutdown} functions:
for init:
- FIRST run CoreZeroInit ONCE
- all cores must run CoreInit ONCE
for shutdown:
- all non-zero cores must call CoreShutdown
- core zero must call CoreZeroShutdown, then CoreShutdown
*/
void SYS_CoreZeroInit(void);
void SYS_CoreInit(void);
void SYS_CoreZeroShutdown(void);
void __attribute__((noreturn)) SYS_CoreShutdown(void);

37
arm11/source/system/xalloc.c Executable file
View File

@ -0,0 +1,37 @@
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
// super simple watermark allocator for ARM9 <-> ARM11 xfers
// designed to be request once, free never
#include "system/xalloc.h"
static char ALIGN(4096) xalloc_buf[XALLOC_BUF_SIZE];
static size_t mark = 0;
void *XAlloc(size_t size)
{ // not thread-safe at all
void *ret;
size_t end = size + mark;
if (end >= XALLOC_BUF_SIZE)
return NULL;
ret = &xalloc_buf[mark];
mark = end;
return ret;
}

46
arm11/source/arm/xrq.h → arm11/source/system/xalloc.h Normal file → Executable file
View File

@ -1,21 +1,25 @@
/*
* This file is part of GodMode9
* Copyright (C) 2020 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
u32 xrqInstallVectorTable(void);
/*
* This file is part of GodMode9
* Copyright (C) 2019 Wolfvak
*
* 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 2 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/>.
*/
#pragma once
#include "types.h"
#define XALLOC_BUF_SIZE (16384)
void *XAlloc(size_t size);

View File

@ -1,24 +1,17 @@
PROCESSOR := ARM9
TARGET := $(shell basename "$(CURDIR)")
TARGET := $(shell basename $(CURDIR))
SOURCE := source
BUILD := build
SUBARCH := -D$(PROCESSOR) -march=armv5te -mtune=arm946e-s -mthumb -mfloat-abi=soft
INCDIRS := source source/common source/filesys source/crypto source/fatfs source/nand source/virtual source/game source/gamecart source/lodepng source/lua source/qrcodegen source/system source/utils
SUBARCH := -D$(PROCESSOR) -marm -march=armv5te -mtune=arm946e-s -mfloat-abi=soft -mno-thumb-interwork
INCDIRS := source source/common source/filesys source/crypto source/fatfs source/nand source/virtual source/game source/gamecart source/lodepng source/qrcodegen source/system source/utils
INCLUDE := $(foreach dir,$(INCDIRS),-I"$(shell pwd)/$(dir)")
ASFLAGS += $(SUBARCH) $(INCLUDE)
CFLAGS += $(SUBARCH) $(INCLUDE) -fno-builtin-memcpy -flto
LDFLAGS += $(SUBARCH) -Wl,--use-blx,-Map,$(TARGET).map -flto
LIBS += -lm
LDFLAGS += $(SUBARCH) -Wl,-Map,$(TARGET).map -flto
include ../Makefile.common
include ../Makefile.build
arm9_data.elf: arm9.elf
$(OBJCOPY) -O elf32-littlearm -j .rodata* -j .data* -j .bss* $< $@
arm9_code.elf: arm9.elf
$(OBJCOPY) -O elf32-littlearm -j .text* -j .vectors* $< $@

View File

@ -4,10 +4,8 @@ ENTRY(_start)
MEMORY
{
AHBWRAM (RWX) : ORIGIN = 0x08006000, LENGTH = 512K
VECTORS (RX) : ORIGIN = 0x08000000, LENGTH = 64
CODEMEM (RX) : ORIGIN = 0x08000040, LENGTH = 512K - 64
BOOTROM (R) : ORIGIN = 0x08080000, LENGTH = 128K /* BootROM mirrors, don't touch! */
DATAMEM (RW) : ORIGIN = 0x080A0000, LENGTH = 384K
}
SECTIONS
@ -18,7 +16,7 @@ SECTIONS
KEEP(*(.vectors));
. = ALIGN(4);
__vectors_len = ABSOLUTE(.) - __vectors_vma;
} >VECTORS AT>CODEMEM
} >VECTORS AT>AHBWRAM
.text : ALIGN(4) {
__text_s = ABSOLUTE(.);
@ -26,28 +24,24 @@ SECTIONS
*(.text*);
. = ALIGN(4);
__text_e = ABSOLUTE(.);
} >CODEMEM
} >AHBWRAM
.rodata : ALIGN(4) {
*(.rodata*);
. = ALIGN(4);
__exidx_start = .;
*(.ARM.exidx* .gnu.linkonce.armexidx.*)
__exidx_end = .;
. = ALIGN(4);
} >DATAMEM
} >AHBWRAM
.data : ALIGN(4) {
*(.data*);
. = ALIGN(4);
} >DATAMEM
} >AHBWRAM
.bss (NOLOAD) : ALIGN(4) {
.bss : ALIGN(4) {
__bss_start = .;
*(.bss*);
. = ALIGN(4);
__bss_end = .;
} >DATAMEM
} >AHBWRAM
__end__ = ABSOLUTE(.);
}

View File

@ -19,7 +19,7 @@ static void SetNotificationLED(u32 period_ms, u32 rgb565_color)
(rgb565_color >> 5) << (8+2) |
(rgb565_color << 3));
u32 args[] = {period_ms, rgb888_color};
PXI_DoCMD(PXICMD_SET_NOTIFY_LED, args, 2);
PXI_DoCMD(PXI_NOTIFY_LED, args, 2);
}
// there's some weird thing going on when reading this
@ -27,12 +27,12 @@ static void SetNotificationLED(u32 period_ms, u32 rgb565_color)
// separate things - hopefully LTO won't get in the way
u32 HID_ReadState(void)
{
return ARM_GetSHMEM()->hidState.keys;
return ARM_GetSHMEM()->hid_state;
}
u32 HID_ReadRawTouchState(void)
{
return ARM_GetSHMEM()->hidState.touch;
return ARM_GetSHMEM()->hid_state >> 32;
}
// ts_mult indicates a scalar for each axis
@ -147,14 +147,7 @@ u32 InputWait(u32 timeout_sec) {
do {
u32 newpad = HID_ReadState();
// handle closed shell (wait for open)
if (newpad & SHELL_CLOSED) {
while (HID_ReadState() & SHELL_CLOSED);
continue;
}
// no buttons pressed, check for I/O changes instead
if (!(newpad & ~(SHELL_OPEN|SHELL_CLOSED))) {
if (!(newpad & ~(SHELL_OPEN|SHELL_CLOSED))) { // no buttons pressed, check for I/O changes instead
u32 state = CART_STATE;
if (state != oldcart)
return state ? CART_INSERT : CART_EJECT;
@ -177,6 +170,12 @@ u32 InputWait(u32 timeout_sec) {
(delay && (timer_msec(timer) < delay))))
continue;
// handle closed shell (wait for open)
if (newpad & SHELL_CLOSED) {
while (HID_ReadState() & SHELL_CLOSED);
continue;
}
// screenshot handling
if ((newpad & BUTTON_ANY) == (BUTTON_R1 | BUTTON_L1))
CreateScreenshot();

View File

@ -9,8 +9,8 @@
#define CART_STATE (~(*(volatile u8*)0x10000010) & 0x1)
#define SD_STATE ((*(volatile u16*)0x1000601C) & (0x1<<5))
#define HID_RAW_TX(t) ((s32)(((t) / (1 << 16)) & 0xFFF))
#define HID_RAW_TY(t) ((s32)((t) & 0xFFF))
#define HID_RAW_TX(t) ((s32)(((t) / (1 << 16)) & 0xFFF))
#define HID_RAW_TY(t) ((s32)((t) & 0xFFF))
u32 HID_ReadState(void);
@ -18,8 +18,8 @@ u32 HID_ReadState(void);
// the touchscreen at the screen coordinates [screen_x, screen_y]
// note: no point can be at the center
typedef struct {
u32 ts_raw;
int screen_x, screen_y;
u32 ts_raw;
int screen_x, screen_y;
} HID_CalibrationData;
u32 HID_ReadRawTouchState(void);

View File

@ -12,7 +12,7 @@ u32 SetScreenBrightness(int level) {
arg = 0;
}
return PXI_DoCMD(PXICMD_SET_BRIGHTNESS, &arg, 1);
return PXI_DoCMD(PXI_BRIGHTNESS, &arg, 1);
}
u32 GetBatteryPercent() {

View File

@ -7,23 +7,23 @@ bool is_valid_dstime(DsTime* dstime) {
(DSTIMEGET(dstime, bcd_m) >= 60) ||
(DSTIMEGET(dstime, bcd_s) >= 60))
return false;
// check the date...
u32 year = 2000 + DSTIMEGET(dstime, bcd_Y);
u32 month = DSTIMEGET(dstime, bcd_M);
u32 day = DSTIMEGET(dstime, bcd_D);
// date: year & month
if ((year >= 2100) || (month == 0) || (month > 12))
return false;
// date: day
// see: https://github.com/devkitPro/libnds/blob/9678bf09389cb1fcdc99dfa0357ec0cbe51dd0b7/source/arm7/clock.c#L224-L262
u32 months_lastday[1+12] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
u32 leap = (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) ? 1 : 0;
u32 days_in_month = months_lastday[month] + ((month == 2) ? leap : 0);
if (day > days_in_month) return false;
return true;
}

View File

@ -16,7 +16,7 @@ typedef struct {
u8 bcd_D;
u8 bcd_M;
u8 bcd_Y;
u8 leap_count;
u8 leap_count;
} PACKED_STRUCT DsTime;
bool is_valid_dstime(DsTime* dstime);

View File

@ -27,7 +27,7 @@ void CreateScreenshot(void) {
fvx_rmkdir(OUTPUT_PATH);
get_dstime(&dstime);
snprintf(filename, sizeof(filename), OUTPUT_PATH "/snap_%02X%02X%02X%02X%02X%02X.png",
snprintf(filename, 64, OUTPUT_PATH "/snap_%02X%02X%02X%02X%02X%02X.png",
dstime.bcd_Y, dstime.bcd_M, dstime.bcd_D,
dstime.bcd_h, dstime.bcd_m, dstime.bcd_s);
filename[63] = '\0';

View File

@ -2,8 +2,8 @@
#include "common.h"
extern const u8 sig_nand_firm_retail[256];
extern const u8 sig_nand_firm_retail_alt[256];
extern const u8 sig_nand_firm_dev[256];
extern const u8 sig_nand_ncsd_retail[256];
extern const u8 sig_nand_ncsd_dev[256];
const u8 sig_nand_firm_retail[256];
const u8 sig_nand_firm_retail_alt[256];
const u8 sig_nand_firm_dev[256];
const u8 sig_nand_ncsd_retail[256];
const u8 sig_nand_ncsd_dev[256];

View File

@ -1,10 +1,8 @@
#include <stdarg.h>
#include "language.h"
#include "swkbd.h"
#include "timer.h"
#include "hid.h"
#include "utf.h"
static inline char to_uppercase(char c) {
@ -60,7 +58,10 @@ static bool BuildKeyboard(TouchBox* swkbd, const char* keys, const u8* layout) {
}
// next row
if (layout[l++] != 0) return false;
if (layout[l++] != 0) {
ShowPrompt(false, "Oh shit %lu %lu", k, l);
return false; // error!!!! THIS HAS TO GO!
}
p_y += SWKBD_STDKEY_HEIGHT + SWKDB_KEY_SPACING;
}
@ -72,7 +73,7 @@ static bool BuildKeyboard(TouchBox* swkbd, const char* keys, const u8* layout) {
static void DrawKey(const TouchBox* key, const bool pressed, const u32 uppercase) {
const char* keystrs[] = { SWKBD_KEYSTR };
const u32 color = (pressed) ? COLOR_SWKBD_PRESSED :
const u32 color = (pressed) ? COLOR_SWKBD_PRESSED :
(key->id == KEY_ENTER) ? COLOR_SWKBD_ENTER :
((key->id == KEY_CAPS) && (uppercase > 1)) ? COLOR_SWKBD_CAPS :
COLOR_SWKBD_NORMAL;
@ -81,7 +82,7 @@ static void DrawKey(const TouchBox* key, const bool pressed, const u32 uppercase
if (key->id == KEY_TXTBOX) return;
char keystr[16];
if (key->id >= 0x80) snprintf(keystr, sizeof(keystr), "%s", keystrs[key->id - 0x80]);
if (key->id >= 0x80) snprintf(keystr, 16, "%s", keystrs[key->id - 0x80]);
else {
keystr[0] = (uppercase) ? to_uppercase(key->id) : key->id;
keystr[1] = 0;
@ -92,7 +93,7 @@ static void DrawKey(const TouchBox* key, const bool pressed, const u32 uppercase
const u32 f_offs_y = (key->h - FONT_HEIGHT_EXT) / 2;
DrawRectangle(BOT_SCREEN, key->x, key->y, key->w, key->h, color);
DrawString(BOT_SCREEN, keystr, key->x + f_offs_x, key->y + f_offs_y, COLOR_SWKBD_CHARS, color);
DrawString(BOT_SCREEN, keystr, key->x + f_offs_x, key->y + f_offs_y, COLOR_SWKBD_CHARS, color, false);
}
static void DrawKeyBoardBox(TouchBox* swkbd, u32 color) {
@ -121,50 +122,34 @@ static void DrawKeyBoard(TouchBox* swkbd, const u32 uppercase) {
}
static void DrawTextBox(const TouchBox* txtbox, const char* inputstr, const u32 cursor, u32* scroll) {
const u32 input_shown_length = (txtbox->w / FONT_WIDTH_EXT) - 2;
const u32 input_shown = (txtbox->w / FONT_WIDTH_EXT) - 2;
const u32 inputstr_size = strlen(inputstr); // we rely on a zero terminated string
const u16 x = txtbox->x;
const u16 y = txtbox->y;
const u16 y = txtbox->y;
// fix scroll
if (cursor < *scroll) {
*scroll = cursor;
} else {
int scroll_adjust = -input_shown_length;
for (u32 i = *scroll; i < cursor; i++) {
if (i >= inputstr_size || (inputstr[i] & 0xC0) != 0x80) scroll_adjust++;
}
for (int i = 0; i < scroll_adjust; i++)
*scroll += *scroll >= inputstr_size ? 1 : GetCharSize(inputstr + *scroll);
}
u32 input_shown_size = 0;
for (u32 i = 0; i < input_shown_length || (*scroll + input_shown_size < inputstr_size && (inputstr[*scroll + input_shown_size] & 0xC0) == 0x80); input_shown_size++) {
if (*scroll + input_shown_size >= inputstr_size || (inputstr[*scroll + input_shown_size] & 0xC0) != 0x80) i++;
}
if (cursor < *scroll) *scroll = cursor;
else if (cursor - *scroll > input_shown) *scroll = cursor - input_shown;
// draw input string
DrawStringF(BOT_SCREEN, x, y, COLOR_STD_FONT, COLOR_STD_BG, "%c%-*.*s%c",
DrawStringF(BOT_SCREEN, x, y, COLOR_STD_FONT, COLOR_STD_BG, "%c%-*.*s%-*.*s%c",
(*scroll) ? '<' : '|',
(int) input_shown_size,
(int) input_shown_size,
(*scroll > inputstr_size) ? "" : inputstr + *scroll,
(inputstr_size - (s32) *scroll > input_shown_size) ? '>' : '|'
);
// draw cursor
u16 cpos = 0;
for (u16 i = *scroll; i < cursor; i++) {
if (i >= inputstr_size || (inputstr[i] & 0xC0) != 0x80) cpos++;
}
DrawStringF(BOT_SCREEN, x-(FONT_WIDTH_EXT/2), y+10, COLOR_STD_FONT, COLOR_STD_BG, "%-*.*s^%-*.*s",
(int) (1 + cpos),
(int) (1 + cpos),
(inputstr_size > input_shown) ? input_shown : inputstr_size,
(inputstr_size > input_shown) ? input_shown : inputstr_size,
inputstr + *scroll,
(inputstr_size > input_shown) ? 0 : input_shown - inputstr_size,
(inputstr_size > input_shown) ? 0 : input_shown - inputstr_size,
"",
(int) (input_shown_length - cpos),
(int) (input_shown_length - cpos),
(inputstr_size - (s32) *scroll > input_shown) ? '>' : '|'
);
// draw cursor
DrawStringF(BOT_SCREEN, x-(FONT_WIDTH_EXT/2), y+10, COLOR_STD_FONT, COLOR_STD_BG, "%-*.*s^%-*.*s",
1 + cursor - *scroll,
1 + cursor - *scroll,
"",
input_shown - (cursor - *scroll),
input_shown - (cursor - *scroll),
""
);
}
@ -181,17 +166,8 @@ static void MoveTextBoxCursor(const TouchBox* txtbox, const char* inputstr, cons
const TouchBox* tb = TouchBoxGet(&id, x, y, txtbox, 0);
if (id == KEY_TXTBOX) {
u16 x_tb = x - tb->x;
const u32 inputstr_size = strlen(inputstr);
const u16 cpos_x = (x_tb < (FONT_WIDTH_EXT/2)) ? 0 : (x_tb - (FONT_WIDTH_EXT/2)) / FONT_WIDTH_EXT;
u16 cpos_length = 0;
u16 cpos_size = 0;
while ((cpos_length < cpos_x && cpos_length < input_shown) || (*scroll + cpos_size < inputstr_size && (inputstr[*scroll + cpos_size] & 0xC0) == 0x80)) {
if (*scroll + cpos_size >= inputstr_size || (inputstr[*scroll + cpos_size] & 0xC0) != 0x80) cpos_length++;
cpos_size++;
}
u32 cursor_next = *scroll + cpos_size;
u16 cpos = (x_tb < (FONT_WIDTH_EXT/2)) ? 0 : (x_tb - (FONT_WIDTH_EXT/2)) / FONT_WIDTH_EXT;
u32 cursor_next = *scroll + ((cpos <= input_shown) ? cpos : input_shown);
// move cursor to position pointed to
if (*cursor != cursor_next) {
if (cursor_next < max_size) *cursor = cursor_next;
@ -200,10 +176,10 @@ static void MoveTextBoxCursor(const TouchBox* txtbox, const char* inputstr, cons
}
// move beyound visible field
if (timer_msec(timer) >= scroll_cooldown) {
if ((cpos_length == 0) && (*scroll > 0))
*scroll -= GetPrevCharSize(inputstr + *scroll);
else if ((cpos_length >= input_shown) && (*cursor < (max_size-1)))
*scroll += GetCharSize(inputstr + *scroll);
if ((cpos == 0) && (*scroll > 0))
(*scroll)--;
else if ((cpos >= input_shown) && (*cursor < (max_size-1)))
(*scroll)++;
}
}
}
@ -223,7 +199,6 @@ static char KeyboardWait(TouchBox* swkbd, bool uppercase) {
else if (pressed & BUTTON_R1) return KEY_CAPS;
else if (pressed & BUTTON_RIGHT) return KEY_RIGHT;
else if (pressed & BUTTON_LEFT) return KEY_LEFT;
else if (pressed & BUTTON_SELECT) return KEY_SWITCH;
else if (pressed & BUTTON_TOUCH) break;
}
@ -253,13 +228,6 @@ bool ShowKeyboard(char* inputstr, const u32 max_size, const char *format, ...) {
TouchBox swkbd_numpad[32];
TouchBox* textbox = swkbd_alphabet; // always use this textbox
static bool show_instr = true;
const char* instr = STR_KEYBOARD_CONTROLS_DETAILS;
if (show_instr) {
ShowPrompt(false, "%s", instr);
show_instr = false;
}
// generate keyboards
if (!BuildKeyboard(swkbd_alphabet, keys_alphabet, layout_alphabet)) return false;
if (!BuildKeyboard(swkbd_special, keys_special, layout_special)) return false;
@ -269,7 +237,7 @@ bool ShowKeyboard(char* inputstr, const u32 max_size, const char *format, ...) {
char str[512]; // arbitrary limit, should be more than enough
va_list va;
va_start(va, format);
vsnprintf(str, sizeof(str), format, va);
vsnprintf(str, 512, format, va);
va_end(va);
u32 str_width = GetDrawStringWidth(str);
if (str_width < (24 * FONT_WIDTH_EXT)) str_width = 24 * FONT_WIDTH_EXT;
@ -313,51 +281,22 @@ bool ShowKeyboard(char* inputstr, const u32 max_size, const char *format, ...) {
break;
} else if (key == KEY_BKSPC) {
if (cursor) {
int size = GetPrevCharSize(inputstr + cursor);
if (cursor <= inputstr_size) {
memmove(inputstr + cursor - size, inputstr + cursor, inputstr_size - cursor + size);
inputstr_size -= size;
memmove(inputstr + cursor - 1, inputstr + cursor, inputstr_size - cursor + 1);
inputstr_size--;
}
cursor -= size;
cursor--;
}
} else if (key == KEY_LEFT) {
if (cursor) cursor -= GetPrevCharSize(inputstr + cursor);
if (cursor) cursor--;
} else if (key == KEY_RIGHT) {
int size = cursor > inputstr_size ? 1 : GetCharSize(inputstr + cursor);
if (cursor + size < max_size) cursor += size;
if (cursor < (max_size-1)) cursor++;
} else if (key == KEY_ALPHA) {
swkbd = swkbd_alphabet;
} else if (key == KEY_SPECIAL) {
swkbd = swkbd_special;
} else if (key == KEY_NUMPAD) {
swkbd = swkbd_numpad;
} else if (key == KEY_SWITCH) {
ClearScreen(BOT_SCREEN, COLOR_STD_BG);
return ShowStringPrompt(inputstr, max_size, "%s", str);
} else if (key == KEY_UNICODE) {
if (cursor > 3 && cursor <= inputstr_size) {
u16 codepoint = 0;
for (char *c = inputstr + cursor - 4; c < inputstr + cursor; c++) {
if ((*c >= '0' && *c <= '9') || (*c >= 'A' && *c <= 'F') || (*c >= 'a' && *c <= 'f')) {
codepoint <<= 4;
codepoint |= *c - (*c <= '9' ? '0' : ((*c <= 'F' ? 'A' : 'a') - 10));
} else {
codepoint = 0;
break;
}
}
if(codepoint != 0) {
char character[5] = {0};
u16 input[2] = {codepoint, 0};
utf16_to_utf8((u8*)character, input, 4, 1);
u32 char_size = GetCharSize(character);
memmove(inputstr + cursor - 4 + char_size, inputstr + cursor, max_size - cursor + 4 - char_size);
memcpy(inputstr + cursor - 4, character, char_size);
cursor -= 4 - char_size;
}
}
} else if (key && (key < 0x80)) {
if ((cursor < (max_size-1)) && (inputstr_size < max_size)) {
// pad string (if cursor beyound string size)

View File

@ -18,17 +18,16 @@ enum {
KEY_LEFT = 0x88,
KEY_RIGHT = 0x89,
KEY_ESCAPE = 0x8A,
KEY_SWITCH = 0x8B,
KEY_UNICODE = 0x8C,
KEY_TXTBOX = 0xFF
};
// special key strings
#define SWKBD_KEYSTR "", "DEL", "INS", "SUBMIT", "CAPS", "#$@", "123", "ABC", "←", "→", "ESC", "SWITCH", "U+"
#define SWKBD_KEYSTR "", "DEL", "INS", "SUBMIT", "CAPS", "#$@", "123", "ABC", "\x1b", "\x1a", "ESC"
#define COLOR_SWKBD_NORMAL COLOR_GREY
#define COLOR_SWKBD_PRESSED COLOR_LIGHTGREY
#define COLOR_SWKBD_BOX COLOR_DARKGREY
#define COLOR_SWKBD_TEXTBOX COLOR_DARKGREY
#define COLOR_SWKBD_CHARS COLOR_BLACK
#define COLOR_SWKBD_ENTER COLOR_TINTEDBLUE
#define COLOR_SWKBD_CAPS COLOR_TINTEDYELLOW
@ -57,7 +56,7 @@ enum {
'4', '5', '6', 'D', 'C', \
'3', '2', '1', 'B', 'A', \
'0', '.', '_', KEY_LEFT, KEY_RIGHT, \
KEY_ALPHA, KEY_UNICODE, ' ', KEY_BKSPC
KEY_ALPHA, ' ', KEY_BKSPC
// offset, num of keys in row, width of special keys (...), 0
#define SWKBD_LAYOUT_ALPHABET \
@ -81,9 +80,9 @@ enum {
5, 0, \
5, 0, \
5, 18, 18, 0, \
4, 20, 20, 31, 20, 0, \
3, 30, 34, 30, 0, \
0
#define ShowKeyboardOrPrompt (TouchIsCalibrated() ? ShowKeyboard : ShowStringPrompt)
bool PRINTF_ARGS(3) ShowKeyboard(char* inputstr, u32 max_size, const char *format, ...);
bool ShowKeyboard(char* inputstr, u32 max_size, const char *format, ...);

View File

@ -7,7 +7,7 @@ u64 timer_start( void ) {
if (!(*TIMER_CNT0 & *TIMER_CNT1 & *TIMER_CNT2 & *TIMER_CNT3 & TIMER_ACTIVE) ||
!(*TIMER_CNT1 & *TIMER_CNT2 & *TIMER_CNT3 & TIMER_COUNT_UP))
timer_init = true;
if (timer_init) {
// deactivate, then reset timers
*TIMER_CNT0 = 0;
@ -17,7 +17,7 @@ u64 timer_start( void ) {
// start timers
*TIMER_CNT0 = TIMER_ACTIVE;
*TIMER_CNT1 = *TIMER_CNT2 = *TIMER_CNT3 = TIMER_ACTIVE | TIMER_COUNT_UP;
// timer initialized
timer_init = false;
}

View File

@ -2,7 +2,6 @@
#include "ui.h"
#include "hid.h"
#include "crc16.h"
#include "language.h"
#include "spiflash.h"
#include "support.h"
@ -47,8 +46,8 @@ bool ShowTouchCalibrationDialog(void)
// clear screen, draw instructions
ClearScreen(BOT_SCREEN, COLOR_STD_BG);
DrawStringCenter(BOT_SCREEN, COLOR_STD_FONT, COLOR_STD_BG, "%s",
STR_TOUCH_CROSSHAIRS_TO_CALIBRATE_TOUCHSCREEN_USE_STYLUS);
DrawStringCenter(BOT_SCREEN, COLOR_STD_FONT, COLOR_STD_BG,
"Touch the red crosshairs to\ncalibrate your touchscreen.\n \nUse the stylus for best\nresults!");
// set calibration defaults
SetCalibrationDefaults();
@ -90,7 +89,7 @@ bool CalibrateTouchFromSupportFile(void) {
size_t size = LoadSupportFile(TOUCH_CALIB_FILENAME, calibrations, sizeof(calibrations));
u32 n_dots = size / sizeof(HID_CalibrationData);
is_calibrated = (n_dots == 0) ? false :
is_calibrated = (n_dots == 0) ? false :
HID_SetCalibrationData(calibrations, n_dots, SCREEN_WIDTH_BOT, SCREEN_HEIGHT);
return is_calibrated;
}
@ -100,11 +99,11 @@ bool CalibrateTouchFromFlash(void) {
// set calibration defaults
SetCalibrationDefaults();
// check SPIflash status
if (!spiflash_get_status())
return false;
// check NVRAM console ID
u32 console_id = 0;
if (!spiflash_read(0x001C, 4, (u8*)&console_id))

File diff suppressed because it is too large Load Diff

View File

@ -21,11 +21,6 @@
#define FONT_WIDTH_EXT GetFontWidth()
#define FONT_HEIGHT_EXT GetFontHeight()
#define UTF_MAX_BYTES_PER_RUNE 4
#define UTF_BUFFER_BYTESIZE(rune_count) (((rune_count) + 1) * UTF_MAX_BYTES_PER_RUNE)
#define PRINTF_ARGS(n) __attribute__ ((format (printf, (n), (n) + 1)))
#define TOP_SCREEN ((u16*)VRAM_TOP_LA)
#define BOT_SCREEN ((u16*)VRAM_BOT_A)
@ -45,14 +40,13 @@
#ifndef AUTO_UNLOCK
bool PRINTF_ARGS(2) ShowUnlockSequence(u32 seqlvl, const char *format, ...);
bool ShowUnlockSequence(u32 seqlvl, const char *format, ...);
#else
#define ShowUnlockSequence ShowPrompt
#endif
const u8* GetFontFromPbm(const void* pbm, const u32 riff_size, u32* w, u32* h);
const u8* GetFontFromRiff(const void* riff, const u32 riff_size, u32* w, u32* h, u16* count);
bool SetFont(const void* font, const u32 font_size);
u8* GetFontFromPbm(const void* pbm, const u32 pbm_size, u32* w, u32* h);
bool SetFontFromPbm(const void* pbm, const u32 pbm_size);
u16 GetColor(const u16 *screen, int x, int y);
@ -63,39 +57,35 @@ void DrawRectangle(u16 *screen, int x, int y, u32 width, u32 height, u32 color);
void DrawBitmap(u16 *screen, int x, int y, u32 w, u32 h, const u16* bitmap);
void DrawQrCode(u16 *screen, const u8* qrcode);
void DrawCharacter(u16 *screen, u32 character, int x, int y, u32 color, u32 bgcolor);
void DrawString(u16 *screen, const char *str, int x, int y, u32 color, u32 bgcolor);
void PRINTF_ARGS(6) DrawStringF(u16 *screen, int x, int y, u32 color, u32 bgcolor, const char *format, ...);
void PRINTF_ARGS(4) DrawStringCenter(u16 *screen, u32 color, u32 bgcolor, const char *format, ...);
u32 GetCharSize(const char* str);
u32 GetPrevCharSize(const char* str);
void DrawCharacter(u16 *screen, int character, int x, int y, u32 color, u32 bgcolor);
void DrawString(u16 *screen, const char *str, int x, int y, u32 color, u32 bgcolor, bool fix_utf8);
void DrawStringF(u16 *screen, int x, int y, u32 color, u32 bgcolor, const char *format, ...);
void DrawStringCenter(u16 *screen, u32 color, u32 bgcolor, const char *format, ...);
u32 GetDrawStringHeight(const char* str);
u32 GetDrawStringWidth(const char* str);
u32 GetFontWidth(void);
u32 GetFontHeight(void);
void MultiLineString(char* dest, const char* orig, int llen, int maxl);
void WordWrapString(char* str, int llen);
void ResizeString(char* dest, const char* orig, int nlength, int tpos, bool align_right);
void TruncateString(char* dest, const char* orig, int nlength, int tpos);
void ResizeString(char* dest, const char* orig, int nsize, int tpos, bool align_right);
void TruncateString(char* dest, const char* orig, int nsize, int tpos);
void FormatNumber(char* str, u64 number);
void FormatBytes(char* str, u64 bytes);
void PRINTF_ARGS(1) ShowString(const char *format, ...);
void PRINTF_ARGS(2) ShowStringF(u16* screen, const char *format, ...);
void PRINTF_ARGS(4) ShowIconString(u16* icon, int w, int h, const char *format, ...);
void PRINTF_ARGS(5) ShowIconStringF(u16* screen, u16* icon, int w, int h, const char *format, ...);
bool PRINTF_ARGS(2) ShowPrompt(bool ask, const char *format, ...);
u32 PRINTF_ARGS(3) ShowSelectPrompt(int n, const char** options, const char *format, ...);
u32 PRINTF_ARGS(4) ShowFileScrollPrompt(int n, const DirEntry** entries, bool hide_ext, const char *format, ...);
u32 PRINTF_ARGS(4) ShowHotkeyPrompt(u32 n, const char** options, const u32* keys, const char *format, ...);
bool PRINTF_ARGS(3) ShowStringPrompt(char* inputstr, u32 max_size, const char *format, ...);
u64 PRINTF_ARGS(3) ShowHexPrompt(u64 start_val, u32 n_digits, const char *format, ...);
u64 PRINTF_ARGS(2) ShowNumberPrompt(u64 start_val, const char *format, ...);
bool PRINTF_ARGS(3) ShowDataPrompt(u8* data, u32* size, const char *format, ...);
bool PRINTF_ARGS(2) ShowRtcSetterPrompt(void* time, const char *format, ...);
void ShowString(const char *format, ...);
void ShowStringF(u16* screen, const char *format, ...);
void ShowIconString(u16* icon, int w, int h, const char *format, ...);
void ShowIconStringF(u16* screen, u16* icon, int w, int h, const char *format, ...);
bool ShowPrompt(bool ask, const char *format, ...);
u32 ShowSelectPrompt(u32 n, const char** options, const char *format, ...);
u32 ShowFileScrollPrompt(u32 n, const DirEntry** entries, bool hide_ext, const char *format, ...);
u32 ShowHotkeyPrompt(u32 n, const char** options, const u32* keys, const char *format, ...);
bool ShowStringPrompt(char* inputstr, u32 max_size, const char *format, ...);
u64 ShowHexPrompt(u64 start_val, u32 n_digits, const char *format, ...);
u64 ShowNumberPrompt(u64 start_val, const char *format, ...);
bool ShowDataPrompt(u8* data, u32* size, const char *format, ...);
bool ShowRtcSetterPrompt(void* time, const char *format, ...);
bool ShowProgress(u64 current, u64 total, const char* opstr);
int ShowBrightnessConfig(int set_brightness);

View File

@ -189,7 +189,7 @@ int utf16_to_utf8(u8 *out, const u16 *in, int len_out, int len_in)
units = decode_utf16(&code, in);
if(units == -1)
return -1;
if (len_in >= units)
len_in -= units;
else return -1;
@ -238,7 +238,7 @@ int utf8_to_utf16(u16 *out, const u8 *in, int len_out, int len_in)
units = decode_utf8(&code, in);
if(units == -1)
return -1;
if (len_in >= units)
len_in -= units;
else return -1;

View File

@ -101,7 +101,7 @@ void add_ctr(void* ctr, uint32_t carry)
int32_t i;
for(i = 0; i < 4; i++) {
//FIXME this assumes alignment...
//FIXME this assumes alignment...
counter[i] = ((uint32_t)outctr[i*4+0]<<24) | ((uint32_t)outctr[i*4+1]<<16) | ((uint32_t)outctr[i*4+2]<<8) | ((uint32_t)outctr[i*4+3]<<0);
}
@ -213,11 +213,11 @@ void ctr_decrypt_byte(void *inbuf, void *outbuf, size_t size, size_t off, uint32
uint8_t *in = inbuf;
uint8_t *out = outbuf;
uint32_t i;
for (i=0; i<AES_BLOCK_SIZE; i++) // setup local ctr
ctr_local[i] = ctr[i];
add_ctr(ctr_local, off / AES_BLOCK_SIZE);
if (off_fix) // handle misaligned offset (at beginning)
{
size_t last_byte = ((off_fix + bytes_left) >= AES_BLOCK_SIZE) ?
@ -229,7 +229,7 @@ void ctr_decrypt_byte(void *inbuf, void *outbuf, size_t size, size_t off, uint32
*(out++) = temp[i];
bytes_left -= last_byte - off_fix;
}
if (bytes_left >= AES_BLOCK_SIZE)
{
size_t blocks = bytes_left / AES_BLOCK_SIZE;
@ -238,7 +238,7 @@ void ctr_decrypt_byte(void *inbuf, void *outbuf, size_t size, size_t off, uint32
out += AES_BLOCK_SIZE * blocks;
bytes_left -= AES_BLOCK_SIZE * blocks;
}
if (bytes_left) // handle misaligned offset (at end)
{
for (i=0; i<bytes_left; i++)
@ -300,25 +300,25 @@ void aes_cmac(void* inbuf, void* outbuf, size_t size)
AES_CNT_INPUT_ENDIAN | AES_CNT_OUTPUT_ENDIAN;
uint32_t* out = (uint32_t*) outbuf;
uint32_t* in = (uint32_t*) inbuf;
// create xorpad for last block
set_ctr(zeroes);
aes_decrypt(xorpad, xorpad, 1, mode);
char* xorpadb = (void*) xorpad;
char finalxor = (xorpadb[0] & 0x80) ? 0x87 : 0x00;
for (uint32_t i = 0; i < 15; i++) {
xorpadb[i] <<= 1;
xorpadb[i] <<= 1;
xorpadb[i] |= xorpadb[i+1] >> 7;
}
xorpadb[15] <<= 1;
xorpadb[15] ^= finalxor;
// process blocks
for (uint32_t i = 0; i < 4; i++)
out[i] = 0;
while (size-- > 0) {
for (uint32_t i = 0; i < 4; i++)
out[i] ^= *(in++);
out[i] ^= *(in++);
if (!size) { // last block
for (uint32_t i = 0; i < 4; i++)
out[i] ^= xorpad[i];

View File

@ -1,16 +1,16 @@
#include "crc16.h"
#define CRC16_TABVAL \
0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, \
0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400
0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, \
0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400
// see: https://github.com/TASVideos/desmume/blob/master/desmume/src/bios.cpp#L1070tions
u16 crc16_quick(const void* src, u32 len) {
static const u16 tabval[] = { CRC16_TABVAL };
const u16 tabval[] = { CRC16_TABVAL };
u16* data = (u16*) src;
u16 crc = 0xFFFF;
for (len >>= 1; len; len--) {
u16 curr = *(data++);
for (u32 i = 0; i < 4; i++) {
@ -21,6 +21,6 @@ u16 crc16_quick(const void* src, u32 len) {
crc ^= tval;
}
}
return crc;
}

View File

@ -73,7 +73,7 @@ u32 crc32_calculate_from_file(const char* fileName, u32 offset, u32 length) {
return crc32;
}
fvx_lseek(&inputFile, offset);
bool ret = true;
for (u64 pos = 0; (pos < length) && ret; pos += bufsiz) {
UINT read_bytes = min(bufsiz, length - pos);
@ -83,7 +83,7 @@ u32 crc32_calculate_from_file(const char* fileName, u32 offset, u32 length) {
ret = false;
if (ret) crc32 = crc32_calculate(crc32, buffer, read_bytes);
}
fvx_close(&inputFile);
free(buffer);
return ~crc32;

View File

@ -17,7 +17,7 @@ static u64 keyYState = 0;
u32 GetUnitKeysType(void)
{
static u32 keys_type = KEYS_UNKNOWN;
if (keys_type == KEYS_UNKNOWN) {
static const u8 slot0x2CSampleRetail[16] = {
0xBC, 0xC4, 0x16, 0x2C, 0x2A, 0x06, 0x91, 0xEE, 0x47, 0x18, 0x86, 0xB8, 0xEB, 0x2F, 0xB5, 0x48 };
@ -35,18 +35,15 @@ u32 GetUnitKeysType(void)
keys_type = KEYS_DEVKIT;
}
}
return keys_type;
}
void CryptAesKeyInfo(AesKeyInfo* info) {
static const u8 zeros[16] = { 0 };
static const u8 keyY_dev[16] = {
0xA2, 0x32, 0x4A, 0x7E, 0x7C, 0xE6, 0x1A, 0x9A, 0x45, 0x4A, 0x52, 0x19, 0xB3, 0x5B, 0xE9, 0x3B };
const u8* aeskeyY = GetUnitKeysType() == KEYS_DEVKIT ? &keyY_dev[0] : &zeros[0];
static u8 zeroes[16] = { 0 };
u8 ctr[16] = { 0 };
memcpy(ctr, (void*) info, 12); // CTR -> slot + type + id + zeroes
setup_aeskeyY(0x2C, aeskeyY);
setup_aeskeyY(0x2C, zeroes);
use_aeskey(0x2C);
set_ctr(ctr);
aes_decrypt(info->key, info->key, 1, AES_CNT_CTRNAND_MODE);
@ -70,15 +67,15 @@ u32 CheckKeySlot(u32 keyslot, char type)
{ 0xBC, 0x83, 0x7C, 0xC9, 0x99, 0xC8, 0x80, 0x9E, 0x8A, 0xDE, 0x4A, 0xFA, 0xAA, 0x72, 0x08, 0x28 } }
};
u64* state = (type == 'X') ? &keyXState : (type == 'Y') ? &keyYState : (type == 'N') ? &keyState : NULL;
// just to be safe...
if (keyslot >= 0x40)
return 1;
// check if key is already loaded
if ((type != 'I') && ((*state >> keyslot) & 1))
return 0;
// if is not, we may still be able to verify the currently set one (for NCCH keys)
for (u32 p = 0; (type == 'X') && (p < sizeof(keyNcchSamples) / sizeof(AesNcchSampleInfo)); p++) {
if (keyNcchSamples[p].slot != keyslot) // only for keyslots in the keyNcchSamples table!
@ -96,7 +93,7 @@ u32 CheckKeySlot(u32 keyslot, char type)
return 0;
}
}
// not set up if getting here
return 1;
}
@ -105,13 +102,13 @@ u32 CheckKeySlot(u32 keyslot, char type)
// to get rid of these, you may replace this function with anything that works for you
u32 LoadKeyDb(const char* path_db, AesKeyInfo* keydb, u32 bsize) {
UINT fsize = 0;
if (path_db) {
if (fvx_qread (path_db, keydb, 0, bsize, &fsize) != FR_OK) fsize = 0;
} else if (fvx_qread ("S:/" KEYDB_NAME, keydb, 0, bsize, &fsize) != FR_OK) {
fsize = LoadSupportFile(KEYDB_NAME, keydb, bsize); // load key database support file
}
u32 nkeys = 0;
if (fsize && !(fsize % sizeof(AesKeyInfo)))
nkeys = fsize / sizeof(AesKeyInfo);
@ -122,24 +119,24 @@ u32 LoadKeyFromFile(void* key, u32 keyslot, char type, char* id)
{
u8 keystore[16] __attribute__((aligned(32))) = {0};
bool found = false;
// checking the obvious
if ((keyslot >= 0x40) || ((type != 'X') && (type != 'Y') && (type != 'N') && (type != 'I')))
return 1;
// check if already loaded
if (!key && !id && (CheckKeySlot(keyslot, type) == 0)) return 0;
// use keystore if key == NULL
if (!key) key = keystore;
// try to get key from 'aeskeydb.bin' file
AesKeyInfo* keydb = (AesKeyInfo*) malloc(STD_BUFFER_SIZE);
u32 nkeys = (keydb) ? LoadKeyDb(NULL, keydb, STD_BUFFER_SIZE) : 0;
for (u32 i = 0; i < nkeys; i++) {
AesKeyInfo* info = &(keydb[i]);
if (!((info->slot == keyslot) && (info->type == type) &&
if (!((info->slot == keyslot) && (info->type == type) &&
((!id && !(info->id[0])) || (id && (strncmp(id, info->id, 10) == 0))) &&
(!info->keyUnitType || (info->keyUnitType == GetUnitKeysType()))))
continue;
@ -149,23 +146,23 @@ u32 LoadKeyFromFile(void* key, u32 keyslot, char type, char* id)
memcpy(key, info->key, 16);
break;
}
free(keydb);
// load legacy slot0x??Key?.bin file instead
if (!found && (type != 'I')) {
char fname[64];
snprintf(fname, sizeof(fname), "slot0x%02lXKey%s%s.bin", keyslot,
snprintf(fname, 64, "slot0x%02lXKey%s%s.bin", keyslot,
(type == 'X') ? "X" : (type == 'Y') ? "Y" : (type == 'I') ? "IV" : "", (id) ? id : "");
found = (LoadSupportFile(fname, key, 16) == 16);
}
// key still not found (duh)
if (!found) return 1; // out of options here
// done if this is an IV
if (type == 'I') return 0;
// now, setup the key
if (type == 'X') {
setup_aeskeyX(keyslot, key);
@ -180,7 +177,7 @@ u32 LoadKeyFromFile(void* key, u32 keyslot, char type, char* id)
keyYState |= 1ull << keyslot;
}
use_aeskey(keyslot);
return 0;
}
@ -189,11 +186,11 @@ u32 InitKeyDb(const char* path)
// use this to quickly initialize all applicable keys in aeskeydb.bin
static const u64 keyslot_whitelist = (1ull<<0x02)|(1ull<<0x03)|(1ull<<0x05)|(1ull<<0x18)|(1ull<<0x19)|(1ull<<0x1A)|(1ull<<0x1B)|
(1ull<<0x1C)|(1ull<<0x1D)|(1ull<<0x1E)|(1ull<<0x1F)|(1ull<<0x24)|(1ull<<0x25)|(1ull<<0x2F);
// try to load aeskeydb.bin file
AesKeyInfo* keydb = (AesKeyInfo*) malloc(STD_BUFFER_SIZE);
u32 nkeys = (keydb) ? LoadKeyDb(path, keydb, STD_BUFFER_SIZE) : 0;
// apply all applicable keys
for (u32 i = 0; i < nkeys; i++) {
AesKeyInfo* info = &(keydb[i]);
@ -205,7 +202,7 @@ u32 InitKeyDb(const char* path)
if ((info->type == 'I') || (*(info->id)) || (info->keyUnitType && (info->keyUnitType != GetUnitKeysType())) ||
(CheckKeySlot(info->slot, info->type) == 0)) continue; // most likely valid, but not applicable or already set
if (info->isEncrypted) CryptAesKeyInfo(info); // decrypt key
// apply key
u8 key[16] __attribute__((aligned(32))) = {0};
char type = info->type;
@ -225,7 +222,29 @@ u32 InitKeyDb(const char* path)
}
use_aeskey(keyslot);
}
free(keydb);
return (nkeys) ? 0 : 1;
}
// creates dependency to "sha.h", not required for base keydb functions
u32 CheckRecommendedKeyDb(const char* path)
{
// SHA-256 of the recommended aeskeydb.bin file
// equals MD5 A5B28945A7C051D7A0CD18AF0E580D1B
const u8 recommended_sha[0x20] = {
0x40, 0x76, 0x54, 0x3D, 0xA3, 0xFF, 0x91, 0x1C, 0xE1, 0xCC, 0x4E, 0xC7, 0x2F, 0x92, 0xE4, 0xB7,
0x2B, 0x24, 0x00, 0x15, 0xBE, 0x9B, 0xFC, 0xDE, 0x7F, 0xED, 0x95, 0x1D, 0xD5, 0xAB, 0x2D, 0xCB
};
// try to load aeskeydb.bin file
AesKeyInfo* keydb = (AesKeyInfo*) malloc(STD_BUFFER_SIZE);
if (!keydb) return 1;
u32 nkeys = LoadKeyDb(path, keydb, STD_BUFFER_SIZE);
// compare with recommended SHA
bool res = (nkeys && (sha_cmp(recommended_sha, keydb, nkeys * sizeof(AesKeyInfo), SHA256_MODE) == 0));
free(keydb);
return res ? 0 : 1;
}

View File

@ -14,10 +14,10 @@
#define KEYS_UNKNOWN 0
#define KEYS_DEVKIT 1
#define KEYS_RETAIL 2
typedef struct {
u8 slot; // keyslot, 0x00...0x3F
u8 slot; // keyslot, 0x00...0x3F
char type; // type 'X' / 'Y' / 'N' for normalKey / 'I' for IV
char id[10]; // key ID for special keys, all zero for standard keys
u8 reserved[2]; // reserved space
@ -30,3 +30,4 @@ u32 GetUnitKeysType(void);
void CryptAesKeyInfo(AesKeyInfo* info);
u32 LoadKeyFromFile(void* key, u32 keyslot, char type, char* id);
u32 InitKeyDb(const char* path);
u32 CheckRecommendedKeyDb(const char* path);

View File

@ -3,7 +3,7 @@
typedef struct
{
u32 data[16];
u32 data[16];
} _sha_block;
void sha_init(u32 mode)
@ -13,9 +13,9 @@ void sha_init(u32 mode)
}
void sha_update(const void* src, u32 size)
{
{
const u32* src32 = (const u32*)src;
while(size >= 0x40) {
while(*REG_SHACNT & 1);
*((volatile _sha_block*)REG_SHAINFIFO) = *((const _sha_block*)src32);

View File

@ -328,13 +328,3 @@ R0.13c (October 14, 2018)
Fixed creating a sub-directory in the fragmented sub-directory on the exFAT volume collapses FAT chain of the parent directory. (appeared at R0.12)
Fixed f_getcwd() cause output buffer overrun when the buffer has a valid drive number. (appeared at R0.13b)
R0.14 (October 14, 2019)
Added support for 64-bit LBA and GUID partition table (FF_LBA64 = 1)
Changed some API functions, f_mkfs() and f_fdisk().
Fixed f_open() function cannot find the file with file name in length of FF_MAX_LFN characters.
Fixed f_readdir() function cannot retrieve long file names in length of FF_MAX_LFN - 1 characters.
Fixed f_readdir() function returns file names with wrong case conversion. (appeared at R0.12)
Fixed f_mkfs() function can fail to create exFAT volume in the second partition. (appeared at R0.12)

View File

@ -1,4 +1,4 @@
FatFs Module Source Files R0.14
FatFs Module Source Files R0.13c
FILES

View File

@ -63,7 +63,7 @@ FATpartition DriveInfo[13] = {
{ TYPE_RAMDRV, SUBTYPE_NONE, 0, 0, 0xFF } // Z - RAMDRIVE
};
static BYTE imgnand_mode = 0x00;
static BYTE imgnand_mode = 0x00;
@ -81,7 +81,7 @@ DWORD get_fattime( void ) {
((DSTIMEGET(&dstime, bcd_D)&0x1F) << 16) |
((DSTIMEGET(&dstime, bcd_M)&0x0F) << 21) |
(((DSTIMEGET(&dstime, bcd_Y)+(2000-1980))&0x7F) << 25);
return fattime;
}
@ -113,10 +113,10 @@ DSTATUS disk_initialize (
imgnand_mode = (GetMountState() & IMG_NAND) ? 0x01 : 0x00;
FATpartition* fat_info = PART_INFO(pdrv);
BYTE type = PART_TYPE(pdrv);
fat_info->offset = fat_info->size = 0;
fat_info->keyslot = 0xFF;
if (type == TYPE_SDCARD) {
if (sdmmc_sdcard_init() != 0) return STA_NOINIT|STA_NODISK;
fat_info->size = getMMCDevice(1)->total_size;
@ -149,7 +149,7 @@ DSTATUS disk_initialize (
InitRamDrive();
fat_info->size = (GetRamDriveSize() + 0x1FF) / 0x200;
}
return RES_OK;
}
@ -166,9 +166,9 @@ DRESULT disk_read (
DWORD sector, /* Sector address in LBA */
UINT count /* Number of sectors to read */
)
{
{
BYTE type = PART_TYPE(pdrv);
if (type == TYPE_NONE) {
return RES_PARERR;
} else if (type == TYPE_SDCARD) {
@ -205,7 +205,7 @@ DRESULT disk_write (
)
{
BYTE type = PART_TYPE(pdrv);
if (type == TYPE_NONE) {
return RES_PARERR;
} else if (type == TYPE_SDCARD) {
@ -245,7 +245,7 @@ DRESULT disk_ioctl (
{
BYTE type = PART_TYPE(pdrv);
FATpartition* fat_info = PART_INFO(pdrv);
switch (cmd) {
case GET_SECTOR_SIZE:
*((DWORD*) buff) = 0x200;
@ -262,7 +262,7 @@ DRESULT disk_ioctl (
// nothing else to do here - sdmmc.c handles the rest
return RES_OK;
}
return RES_PARERR;
}
#endif

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
/*----------------------------------------------------------------------------/
/ FatFs - Generic FAT Filesystem module R0.14 /
/ FatFs - Generic FAT Filesystem module R0.13c /
/-----------------------------------------------------------------------------/
/
/ Copyright (C) 2019, ChaN, all right reserved.
/ Copyright (C) 2018, ChaN, all right reserved.
/
/ FatFs module is an open source software. Redistribution and use of FatFs in
/ source and binary forms, with or without modification, are permitted provided
@ -20,7 +20,7 @@
#ifndef FF_DEFINED
#define FF_DEFINED 86606 /* Revision ID */
#define FF_DEFINED 86604 /* Revision ID */
#ifdef __cplusplus
extern "C" {
@ -45,16 +45,16 @@ typedef unsigned __int64 QWORD;
typedef unsigned int UINT; /* int must be 16-bit or 32-bit */
typedef unsigned char BYTE; /* char must be 8-bit */
typedef uint16_t WORD; /* 16-bit unsigned integer */
typedef uint16_t WCHAR; /* 16-bit unsigned integer */
typedef uint32_t DWORD; /* 32-bit unsigned integer */
typedef uint64_t QWORD; /* 64-bit unsigned integer */
typedef WORD WCHAR; /* UTF-16 character type */
#else /* Earlier than C99 */
#define FF_INTDEF 1
typedef unsigned int UINT; /* int must be 16-bit or 32-bit */
typedef unsigned char BYTE; /* char must be 8-bit */
typedef unsigned short WORD; /* 16-bit unsigned integer */
typedef unsigned short WCHAR; /* 16-bit unsigned integer */
typedef unsigned long DWORD; /* 32-bit unsigned integer */
typedef WORD WCHAR; /* UTF-16 character type */
#endif
@ -65,7 +65,7 @@ typedef struct {
BYTE pd; /* Physical drive number */
BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */
} PARTITION;
extern PARTITION VolToPart[]; /* Volume - Partition mapping table */
extern PARTITION VolToPart[]; /* Volume - Partition resolution table */
#endif
#if FF_STR_VOLUME_ID
@ -105,24 +105,15 @@ typedef char TCHAR;
/* Type of file size and LBA variables */
/* Type of file size variables */
#if FF_FS_EXFAT
#if FF_INTDEF != 2
#error exFAT feature wants C99 or later
#endif
typedef QWORD FSIZE_t;
#if FF_LBA64
typedef QWORD LBA_t;
#else
typedef DWORD LBA_t;
#endif
#else
#if FF_LBA64
#error exFAT needs to be enabled when enable 64-bit LBA
#endif
typedef DWORD FSIZE_t;
typedef DWORD LBA_t;
#endif
@ -164,14 +155,14 @@ typedef struct {
#endif
DWORD n_fatent; /* Number of FAT entries (number of clusters + 2) */
DWORD fsize; /* Size of an FAT [sectors] */
LBA_t volbase; /* Volume base sector */
LBA_t fatbase; /* FAT base sector */
LBA_t dirbase; /* Root directory base sector/cluster */
LBA_t database; /* Data base sector */
DWORD volbase; /* Volume base sector */
DWORD fatbase; /* FAT base sector */
DWORD dirbase; /* Root directory base sector/cluster */
DWORD database; /* Data base sector */
#if FF_FS_EXFAT
LBA_t bitbase; /* Allocation bitmap base sector */
DWORD bitbase; /* Allocation bitmap base sector */
#endif
LBA_t winsect; /* Current sector appearing in the win[] */
DWORD winsect; /* Current sector appearing in the win[] */
BYTE win[FF_MAX_SS]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */
} FATFS;
@ -208,9 +199,9 @@ typedef struct {
BYTE err; /* Abort flag (error code) */
FSIZE_t fptr; /* File read/write pointer (Zeroed on file open) */
DWORD clust; /* Current cluster of fpter (invalid when fptr is 0) */
LBA_t sect; /* Sector number appearing in buf[] (0:invalid) */
DWORD sect; /* Sector number appearing in buf[] (0:invalid) */
#if !FF_FS_READONLY
LBA_t dir_sect; /* Sector number containing the directory entry (not used at exFAT) */
DWORD dir_sect; /* Sector number containing the directory entry (not used at exFAT) */
BYTE* dir_ptr; /* Pointer to the directory entry in the win[] (not used at exFAT) */
#endif
#if FF_USE_FASTSEEK
@ -229,7 +220,7 @@ typedef struct {
FFOBJID obj; /* Object identifier */
DWORD dptr; /* Current read/write offset */
DWORD clust; /* Current cluster */
LBA_t sect; /* Current sector (0:Read operation has terminated) */
DWORD sect; /* Current sector (0:Read operation has terminated) */
BYTE* dir; /* Pointer to the directory item in the win[] */
BYTE fn[12]; /* SFN (in/out) {body[8],ext[3],status[1]} */
#if FF_USE_LFN
@ -259,18 +250,6 @@ typedef struct {
/* Format parameter structure (MKFS_PARM) */
typedef struct {
BYTE fmt; /* Format option (FM_FAT, FM_FAT32, FM_EXFAT and FM_SFD) */
BYTE n_fat; /* Number of FATs */
UINT align; /* Data area alignment (sector) */
UINT n_root; /* Number of root directory entries */
DWORD au_size; /* Cluster size (byte) */
} MKFS_PARM;
/* File function return code (FRESULT) */
typedef enum {
@ -326,10 +305,10 @@ FRESULT f_getfree (const TCHAR* path, DWORD* nclst, FATFS** fatfs); /* Get numbe
FRESULT f_getlabel (const TCHAR* path, TCHAR* label, DWORD* vsn); /* Get volume label */
FRESULT f_setlabel (const TCHAR* label); /* Set volume label */
FRESULT f_forward (FIL* fp, UINT(*func)(const BYTE*,UINT), UINT btf, UINT* bf); /* Forward data to the stream */
FRESULT f_expand (FIL* fp, FSIZE_t fsz, BYTE opt); /* Allocate a contiguous block to the file */
FRESULT f_expand (FIL* fp, FSIZE_t szf, BYTE opt); /* Allocate a contiguous block to the file */
FRESULT f_mount (FATFS* fs, const TCHAR* path, BYTE opt); /* Mount/Unmount a logical drive */
FRESULT f_mkfs (const TCHAR* path, const MKFS_PARM* opt, void* work, UINT len); /* Create a FAT volume */
FRESULT f_fdisk (BYTE pdrv, const LBA_t ptbl[], void* work); /* Divide a physical drive into some partitions */
FRESULT f_mkfs (const TCHAR* path, BYTE opt, DWORD au, void* work, UINT len); /* Create a FAT volume */
FRESULT f_fdisk (BYTE pdrv, const DWORD* szt, void* work); /* Divide a physical drive into some partitions */
FRESULT f_setcp (WORD cp); /* Set current code page */
int f_putc (TCHAR c, FIL* fp); /* Put a character to the file */
int f_puts (const TCHAR* str, FIL* cp); /* Put a string to the file */

View File

@ -2,7 +2,7 @@
/ FatFs Functional Configurations
/---------------------------------------------------------------------------*/
#define FFCONF_DEF 86606 /* Revision ID */
#define FFCONF_DEF 86604 /* Revision ID */
/*---------------------------------------------------------------------------/
/ Function Configurations
@ -110,11 +110,11 @@
/ requiers certain internal working buffer occupies (FF_MAX_LFN + 1) * 2 bytes and
/ additional (FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT is enabled.
/ The FF_MAX_LFN defines size of the working buffer in UTF-16 code unit and it can
/ be in range of 12 to 255. It is recommended to be set it 255 to fully support LFN
/ be in range of 12 to 255. It is recommended to be set 255 to fully support LFN
/ specification.
/ When use stack for the working buffer, take care on stack overflow. When use heap
/ memory for the working buffer, memory management functions, ff_memalloc() and
/ ff_memfree() exemplified in ffsystem.c, need to be added to the project. */
/ ff_memfree() in ffsystem.c, need to be added to the project. */
#define FF_LFN_UNICODE 2
@ -200,22 +200,24 @@
/ GET_SECTOR_SIZE command. */
#define FF_LBA64 0
/* This option switches support for 64-bit LBA. (0:Disable or 1:Enable)
/ To enable the 64-bit LBA, also exFAT needs to be enabled. (FF_FS_EXFAT == 1) */
#define FF_MIN_GPT 0x100000000
/* Minimum number of sectors to switch GPT format to create partition in f_mkfs and
/ f_fdisk function. 0x100000000 max. This option has no effect when FF_LBA64 == 0. */
#define FF_USE_TRIM 0
/* This option switches support for ATA-TRIM. (0:Disable or 1:Enable)
/ To enable Trim function, also CTRL_TRIM command should be implemented to the
/ disk_ioctl() function. */
#define FF_FS_NOFSINFO 0
/* If you need to know correct free space on the FAT32 volume, set bit 0 of this
/ option, and f_getfree() function at first time after volume mount will force
/ a full FAT scan. Bit 1 controls the use of last allocated cluster number.
/
/ bit0=0: Use free cluster count in the FSINFO if available.
/ bit0=1: Do not trust free cluster count in the FSINFO.
/ bit1=0: Use last allocated cluster number in the FSINFO if available.
/ bit1=1: Do not trust last allocated cluster number in the FSINFO.
*/
/*---------------------------------------------------------------------------/
/ System Configurations
@ -230,14 +232,14 @@
#define FF_FS_EXFAT 0
/* This option switches support for exFAT filesystem. (0:Disable or 1:Enable)
/ To enable exFAT, also LFN needs to be enabled. (FF_USE_LFN >= 1)
/ To enable exFAT, also LFN needs to be enabled.
/ Note that enabling exFAT discards ANSI C (C89) compatibility. */
#define FF_FS_NORTC 0
#define FF_NORTC_MON 1
#define FF_NORTC_MDAY 1
#define FF_NORTC_YEAR 2019
#define FF_NORTC_YEAR 2018
/* The option FF_FS_NORTC switches timestamp functiton. If the system does not have
/ any RTC function or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable
/ the timestamp function. Every object modified by FatFs will have a fixed timestamp
@ -245,19 +247,7 @@
/ To enable timestamp function (FF_FS_NORTC = 0), get_fattime() function need to be
/ added to the project to read current time form real-time clock. FF_NORTC_MON,
/ FF_NORTC_MDAY and FF_NORTC_YEAR have no effect.
/ These options have no effect in read-only configuration (FF_FS_READONLY = 1). */
#define FF_FS_NOFSINFO 0
/* If you need to know correct free space on the FAT32 volume, set bit 0 of this
/ option, and f_getfree() function at first time after volume mount will force
/ a full FAT scan. Bit 1 controls the use of last allocated cluster number.
/
/ bit0=0: Use free cluster count in the FSINFO if available.
/ bit0=1: Do not trust free cluster count in the FSINFO.
/ bit1=0: Use last allocated cluster number in the FSINFO if available.
/ bit1=1: Do not trust last allocated cluster number in the FSINFO.
*/
/ These options have no effect at read-only configuration (FF_FS_READONLY = 1). */
#define FF_FS_LOCK 32

View File

@ -1,5 +1,5 @@
/*------------------------------------------------------------------------*/
/* Unicode handling functions for FatFs R0.13+ */
/* Unicode handling functions for FatFs R0.13c */
/*------------------------------------------------------------------------*/
/* This module will occupy a huge memory in the .const section when the /
/ FatFs is configured for LFN with DBCS. If the system has any Unicode /
@ -7,7 +7,7 @@
/ that function to avoid silly memory consumption. /
/-------------------------------------------------------------------------*/
/*
/ Copyright (C) 2014, ChaN, all right reserved.
/ Copyright (C) 2018, ChaN, all right reserved.
/
/ FatFs module is an open source software. Redistribution and use of FatFs in
/ source and binary forms, with or without modification, are permitted provided
@ -25,7 +25,11 @@
#include "ff.h"
#if FF_USE_LFN /* This module will be blanked if non-LFN configuration */
#if FF_USE_LFN /* This module will be blanked at non-LFN configuration */
#if FF_DEFINED != 86604 /* Revision ID */
#error Wrong include file (ff.h).
#endif
#define MERGE2(a, b) a ## b
#define CVTBL(tbl, cp) MERGE2(tbl, cp)
@ -15241,7 +15245,7 @@ WCHAR ff_uni2oem ( /* Returns OEM code character, zero on error */
return c;
}
WCHAR ff_oem2uni ( /* Returns Unicode character in UTF-16, zero on error */
WCHAR ff_oem2uni ( /* Returns Unicode character, zero on error */
WCHAR oem, /* OEM code to be converted */
WORD cp /* Code page for the conversion */
)
@ -15308,7 +15312,7 @@ WCHAR ff_uni2oem ( /* Returns OEM code character, zero on error */
}
WCHAR ff_oem2uni ( /* Returns Unicode character in UTF-16, zero on error */
WCHAR ff_oem2uni ( /* Returns Unicode character, zero on error */
WCHAR oem, /* OEM code to be converted */
WORD cp /* Code page for the conversion */
)
@ -15407,7 +15411,7 @@ WCHAR ff_uni2oem ( /* Returns OEM code character, zero on error */
}
WCHAR ff_oem2uni ( /* Returns Unicode character in UTF-16, zero on error */
WCHAR ff_oem2uni ( /* Returns Unicode character, zero on error */
WCHAR oem, /* OEM code to be converted (DBC if >=0x100) */
WORD cp /* Code page for the conversion */
)

View File

@ -5,7 +5,7 @@ u32 ValidateMbrHeader(MbrHeader* mbr) {
u32 sector = 1; // check partitions
for (u32 i = 0; i < 4; i++) {
MbrPartitionInfo* partition = mbr->partitions + i;
if (!partition->count && i) continue;
if (!partition->count && i) continue;
else if (!partition->count) return 1; // first partition can't be empty
if ((partition->type != 0x1) && (partition->type != 0x4) && (partition->type != 0x6) &&
(partition->type != 0xB) && (partition->type != 0xC) && (partition->type != 0xE))
@ -22,7 +22,7 @@ u32 ValidateFatHeader(void* fat) {
if (strncmp(fat32->fs_type, "FAT32 ", 8) == 0)
return 0; // is FAT32 header
Fat16Header* fat16 = (Fat16Header*) fat;
if ((strncmp(fat16->fs_type, "FAT16 ", 8) == 0) ||
if ((strncmp(fat16->fs_type, "FAT16 ", 8) == 0) ||
(strncmp(fat16->fs_type, "FAT12 ", 8) == 0) ||
(strncmp(fat16->fs_type, "FAT ", 8) == 0))
return 0; // is FAT16 / FAT12 header

View File

@ -15,7 +15,7 @@ typedef struct {
typedef struct {
char text[446];
MbrPartitionInfo partitions[4];
MbrPartitionInfo partitions[4];
u16 magic; // 0xAA55
} PACKED_ALIGN(2) MbrHeader;
@ -50,7 +50,7 @@ typedef struct {
u32 clr_root; // 0x02
u16 sct_fsinfo; // 0x01
u16 sct_backup; // 0x06
u8 reserved3[12];
u8 reserved3[12];
u8 ndrive; // 0x80
u8 head_cur; // 0x00
u8 boot_sig; // 0x29

View File

@ -1,6 +1,5 @@
#include "filetype.h"
#include "fsutil.h"
#include "image.h"
#include "fatmbr.h"
#include "nand.h"
#include "game.h"
@ -8,21 +7,20 @@
#include "keydb.h"
#include "ctrtransfer.h"
#include "scripting.h"
#include "gm9lua.h"
#include "png.h"
#include "ui.h" // only for font file detection
u64 IdentifyFileType(const char* path) {
static const u8 romfs_magic[] = { ROMFS_MAGIC };
static const u8 diff_magic[] = { DIFF_MAGIC };
static const u8 disa_magic[] = { DISA_MAGIC };
static const u8 tickdb_magic[] = { TICKDB_MAGIC };
static const u8 smdh_magic[] = { SMDH_MAGIC };
static const u8 threedsx_magic[] = { THREEDSX_EXT_MAGIC };
static const u8 png_magic[] = { PNG_MAGIC };
const u8 romfs_magic[] = { ROMFS_MAGIC };
const u8 diff_magic[] = { DIFF_MAGIC };
const u8 disa_magic[] = { DISA_MAGIC };
const u8 tickdb_magic[] = { TICKDB_MAGIC };
const u8 smdh_magic[] = { SMDH_MAGIC };
const u8 threedsx_magic[] = { THREEDSX_EXT_MAGIC };
const u8 png_magic[] = { PNG_MAGIC };
if (!path) return 0; // safety
u8 ALIGN(32) header[0x2C0]; // minimum required size
u8 ALIGN(32) header[0x200]; // minimum required size
void* data = (void*) header;
size_t fsize = FileGetSize(path);
char* fname = strrchr(path, '/');
@ -38,7 +36,7 @@ u64 IdentifyFileType(const char* path) {
} else {
ext = "";
}
if (FileGetData(path, header, 0x2C0, 0) < min(0x2C0, fsize)) return 0;
if (FileGetData(path, header, 0x200, 0) < min(0x200, fsize)) return 0;
if (!fsize) return 0;
if (fsize >= 0x200) {
@ -87,14 +85,11 @@ u64 IdentifyFileType(const char* path) {
return GAME_ROMFS; // RomFS file (check could be better)
} else if (ValidateTmd((TitleMetaData*) data) == 0) {
if (fsize == TMD_SIZE_N(getbe16(header + 0x1DE)) + TMD_CDNCERT_SIZE)
return GAME_CDNTMD; // TMD file from NUS/CDN
return GAME_TMD | FLAG_NUSCDN; // TMD file from NUS/CDN
else if (fsize >= TMD_SIZE_N(getbe16(header + 0x1DE)))
return GAME_TMD; // TMD file
} else if (ValidateTwlTmd((TitleMetaData*) data) == 0) {
if (fsize == TMD_SIZE_TWL + TMD_CDNCERT_SIZE)
return GAME_TWLTMD; // TMD file from NUS/CDN (TWL)
} else if (ValidateTicket((Ticket*) data) == 0) {
return GAME_TICKET; // Ticket file
return GAME_TICKET; // Ticket file (not used for anything right now)
} else if (ValidateFirmHeader((FirmHeader*) data, fsize) == 0) {
return SYS_FIRM; // FIRM file
} else if ((ValidateAgbSaveHeader((AgbSaveHeader*) data) == 0) && (fsize >= AGBSAVE_MAX_SIZE)) {
@ -116,22 +111,9 @@ u64 IdentifyFileType(const char* path) {
}
}
}
if (fsize == sizeof(TitleInfoEntry) && (strncasecmp(path, "T:/", 3) == 0)) {
const char* mntpath = GetMountPath();
if (mntpath && *mntpath) {
if ((strncasecmp(mntpath, "1:/dbs/title.db", 16) == 0) ||
(strncasecmp(mntpath, "4:/dbs/title.db", 16) == 0) ||
(strncasecmp(mntpath, "A:/dbs/title.db", 16) == 0) ||
(strncasecmp(mntpath, "B:/dbs/title.db", 16) == 0))
return GAME_TIE;
}
} else if (GetFontFromPbm(data, fsize, NULL, NULL)) {
if (GetFontFromPbm(data, fsize, NULL, NULL)) {
return FONT_PBM;
} else if (GetFontFromRiff(data, fsize, NULL, NULL, NULL)) {
return FONT_RIFF;
} else if (GetLanguage(data, fsize, NULL, NULL, NULL)) {
return TRANSLATION;
} else if ((fsize > sizeof(AgbHeader)) &&
(ValidateAgbHeader((AgbHeader*) data) == 0)) {
return GAME_GBA;
@ -142,7 +124,7 @@ u64 IdentifyFileType(const char* path) {
(memcmp(data, threedsx_magic, sizeof(threedsx_magic)) == 0)) {
return GAME_3DSX; // 3DSX (executable) file
} else if ((fsize > sizeof(CmdHeader)) &&
(CMD_SIZE((CmdHeader*) data) == fsize)) {
CheckCmdSize((CmdHeader*) data, fsize) == 0) {
return GAME_CMD; // CMD file
} else if ((fsize > sizeof(NcchInfoHeader)) &&
(GetNcchInfoVersion((NcchInfoHeader*) data)) &&
@ -151,6 +133,14 @@ u64 IdentifyFileType(const char* path) {
} else if ((strncasecmp(ext, "png", 4) == 0) &&
(fsize > sizeof(png_magic)) && (memcmp(data, png_magic, sizeof(png_magic)) == 0)) {
return GFX_PNG;
} else if ((strncasecmp(ext, "cdn", 4) == 0) || (strncasecmp(ext, "nus", 4) == 0)) {
char path_cetk[256];
char* ext_cetk = path_cetk + (ext - path);
strncpy(path_cetk, path, 256);
path_cetk[255] = '\0';
strncpy(ext_cetk, "cetk", 5);
if (FileGetSize(path_cetk) > 0)
return GAME_NUSCDN; // NUS/CDN type 2
} else if (strncasecmp(fname, TIKDB_NAME_ENC, sizeof(TIKDB_NAME_ENC)+1) == 0) {
return BIN_TIKDB | FLAG_ENC; // titlekey database / encrypted
} else if (strncasecmp(fname, TIKDB_NAME_DEC, sizeof(TIKDB_NAME_DEC)+1) == 0) {
@ -159,16 +149,10 @@ u64 IdentifyFileType(const char* path) {
return BIN_KEYDB; // key database
} else if ((sscanf(fname, "slot%02lXKey", &id) == 1) && (strncasecmp(ext, "bin", 4) == 0) && (fsize = 16) && (id < 0x40)) {
return BIN_LEGKEY; // legacy key file
} else if ((strncmp((char*) data, CIFINISH_MAGIC, strlen(CIFINISH_MAGIC)) == 0) &&
(fsize == CIFINISH_SIZE((void*) data)) && (fsize > sizeof(CifinishHeader))) {
return BIN_CIFNSH;
} else if (ValidateText((char*) data, (fsize > 0x200) ? 0x200 : fsize)) {
u64 type = 0;
if ((fsize < SCRIPT_MAX_SIZE) && (strcasecmp(ext, SCRIPT_EXT) == 0))
if ((fsize <= SCRIPT_MAX_SIZE) && (strncasecmp(ext, SCRIPT_EXT, strnlen(SCRIPT_EXT, 16) + 1) == 0))
type |= TXT_SCRIPT; // should be a script (which is also generic text)
// this should check if it's compiled lua bytecode (done with luac), which is NOT text
else if ((fsize < LUASCRIPT_MAX_SIZE) && (strcasecmp(ext, LUASCRIPT_EXT) == 0))
type |= TXT_LUA;
if (fsize < STD_BUFFER_SIZE) type |= TXT_GENERIC;
return type;
} else if ((strncmp(path + 2, "/Nintendo DSiWare/", 18) == 0) &&
@ -182,13 +166,13 @@ u64 IdentifyFileType(const char* path) {
char* name_cdn = path_cdn + (fname - path);
strncpy(path_cdn, path, 256);
path_cdn[255] = '\0';
strncpy(name_cdn, "tmd", 4); // this will not catch tmd with version
strncpy(name_cdn, "tmd", 4);
if (FileGetSize(path_cdn) > 0)
return GAME_NUSCDN; // NUS/CDN, recognized by TMD
return GAME_NUSCDN; // NUS/CDN type 1
strncpy(name_cdn, "cetk", 5);
if (FileGetSize(path_cdn) > 0)
return GAME_NUSCDN; // NUS/CDN, recognized by CETK
return GAME_NUSCDN; // NUS/CDN type 1
}
return 0;
}

View File

@ -8,65 +8,55 @@
#define GAME_NCSD (1ULL<<3)
#define GAME_NCCH (1ULL<<4)
#define GAME_TMD (1ULL<<5)
#define GAME_CDNTMD (1ULL<<6)
#define GAME_TWLTMD (1ULL<<7)
#define GAME_CMD (1ULL<<8)
#define GAME_EXEFS (1ULL<<9)
#define GAME_ROMFS (1ULL<<10)
#define GAME_BOSS (1ULL<<11)
#define GAME_NUSCDN (1ULL<<12)
#define GAME_TICKET (1ULL<<13)
#define GAME_TIE (1ULL<<14)
#define GAME_SMDH (1ULL<<15)
#define GAME_3DSX (1ULL<<16)
#define GAME_NDS (1ULL<<17)
#define GAME_GBA (1ULL<<18)
#define GAME_TAD (1ULL<<19)
#define SYS_FIRM (1ULL<<20)
#define SYS_DIFF (1ULL<<21)
#define SYS_DISA (1ULL<<22)
#define SYS_AGBSAVE (1ULL<<23)
#define SYS_TICKDB (1ULL<<24)
#define BIN_CIFNSH (1ULL<<25)
#define BIN_NCCHNFO (1ULL<<26)
#define BIN_TIKDB (1ULL<<27)
#define BIN_KEYDB (1ULL<<28)
#define BIN_LEGKEY (1ULL<<29)
#define TXT_SCRIPT (1ULL<<30)
#define TXT_GENERIC (1ULL<<31)
#define GFX_PNG (1ULL<<32)
#define FONT_PBM (1ULL<<33)
#define FONT_RIFF (1ULL<<34)
#define NOIMG_NAND (1ULL<<35)
#define HDR_NAND (1ULL<<36)
#define TRANSLATION (1ULL<<37)
#define TXT_LUA (1ULL<<38)
#define TYPE_BASE 0xFFFFFFFFFFULL // 40 bit reserved for base types
#define GAME_CMD (1ULL<<6)
#define GAME_EXEFS (1ULL<<7)
#define GAME_ROMFS (1ULL<<8)
#define GAME_BOSS (1ULL<<9)
#define GAME_NUSCDN (1ULL<<10)
#define GAME_TICKET (1ULL<<11)
#define GAME_SMDH (1ULL<<12)
#define GAME_3DSX (1ULL<<13)
#define GAME_NDS (1ULL<<14)
#define GAME_GBA (1ULL<<15)
#define GAME_TAD (1ULL<<16)
#define SYS_FIRM (1ULL<<17)
#define SYS_DIFF (1ULL<<18)
#define SYS_DISA (1ULL<<19)
#define SYS_AGBSAVE (1ULL<<20)
#define SYS_TICKDB (1ULL<<21)
#define BIN_NCCHNFO (1ULL<<22)
#define BIN_TIKDB (1ULL<<23)
#define BIN_KEYDB (1ULL<<24)
#define BIN_LEGKEY (1ULL<<25)
#define TXT_SCRIPT (1ULL<<26)
#define TXT_GENERIC (1ULL<<27)
#define GFX_PNG (1ULL<<28)
#define FONT_PBM (1ULL<<29)
#define NOIMG_NAND (1ULL<<30)
#define HDR_NAND (1ULL<<31)
#define TYPE_BASE 0xFFFFFFFFULL // 32 bit reserved for base types
// #define FLAG_FIRM (1ULL<<58) // <--- for CXIs containing FIRMs
// #define FLAG_GBAVC (1ULL<<59) // <--- for GBAVC CXIs
#define FLAG_DSIW (1ULL<<60)
#define FLAG_ENC (1ULL<<61)
#define FLAG_CTR (1ULL<<62)
// #define FLAG_FIRM (1ULL<<57) // <--- for CXIs containing FIRMs
// #define FLAG_GBAVC (1ULL<<58) // <--- for GBAVC CXIs
#define FLAG_DSIW (1ULL<<59)
#define FLAG_ENC (1ULL<<60)
#define FLAG_CTR (1ULL<<61)
#define FLAG_NUSCDN (1ULL<<62)
#define FLAG_CXI (1ULL<<63)
#define FTYPE_MOUNTABLE(tp) (tp&(IMG_FAT|IMG_NAND|GAME_CIA|GAME_NCSD|GAME_NCCH|GAME_EXEFS|GAME_ROMFS|GAME_NDS|GAME_TAD|SYS_FIRM|SYS_DIFF|SYS_DISA|SYS_TICKDB|BIN_KEYDB))
#define FTYPE_VERIFICABLE(tp) (tp&(IMG_NAND|GAME_CIA|GAME_NCSD|GAME_NCCH|GAME_TMD|GAME_CDNTMD|GAME_TWLTMD|GAME_TIE|GAME_TAD|GAME_TICKET|GAME_BOSS|SYS_FIRM))
#define FTYPE_VERIFICABLE(tp) (tp&(IMG_NAND|GAME_CIA|GAME_NCSD|GAME_NCCH|GAME_TMD|GAME_BOSS|SYS_FIRM))
#define FTYPE_DECRYPTABLE(tp) (tp&(GAME_CIA|GAME_NCSD|GAME_NCCH|GAME_BOSS|GAME_NUSCDN|SYS_FIRM|BIN_KEYDB))
#define FTYPE_ENCRYPTABLE(tp) (tp&(GAME_CIA|GAME_NCSD|GAME_NCCH|GAME_BOSS|BIN_KEYDB))
#define FTYPE_CIABUILD(tp) ((tp&(GAME_NCSD|GAME_NCCH|GAME_TMD|GAME_CDNTMD|GAME_TWLTMD|GAME_TIE|GAME_TAD)) || ((tp&GAME_NDS)&&(tp&(FLAG_DSIW))))
#define FTYPE_CIABUILD_L(tp) (tp&(GAME_TMD|GAME_CDNTMD|GAME_TIE|GAME_TAD))
#define FTYPE_CIAINSTALL(tp) ((tp&(GAME_NCSD|GAME_NCCH|GAME_CIA|GAME_CDNTMD|GAME_TWLTMD)) || ((tp&GAME_NDS)&&(tp&(FLAG_DSIW))))
#define FTYPE_TIKINSTALL(tp) (tp&(GAME_TICKET))
#define FTYPE_CIFINSTALL(tp) (tp&(BIN_CIFNSH))
#define FTYPE_TIKDUMP(tp) (tp&(GAME_TIE))
#define FTYPE_CXIDUMP(tp) (tp&(GAME_TMD|GAME_TIE))
#define FTYPE_UNINSTALL(tp) (tp&(GAME_TIE))
#define FTYPE_CIABUILD(tp) ((tp&(GAME_NCSD|GAME_NCCH|GAME_TMD)) || ((tp&GAME_NDS)&&(tp&(FLAG_DSIW))))
#define FTYPE_CIABUILD_L(tp) (FTYPE_CIABUILD(tp) && (tp&(GAME_TMD)))
#define FTYPE_CXIDUMP(tp) (tp&(GAME_TMD))
#define FTYPE_TIKBUILD(tp) (tp&(GAME_TICKET|SYS_TICKDB|BIN_TIKDB))
#define FTYPE_KEYBUILD(tp) (tp&(BIN_KEYDB|BIN_LEGKEY))
#define FTYPE_TITLEINFO(tp) (tp&(GAME_TIE|GAME_CIA|GAME_TMD|GAME_CDNTMD|GAME_TWLTMD))
#define FTYPE_TITLEINFO(tp) (tp&(GAME_SMDH|GAME_NCCH|GAME_NCSD|GAME_CIA|GAME_TMD|GAME_NDS|GAME_GBA|GAME_TAD|GAME_3DSX))
#define FTYPE_CIACHECK(tp) (tp&GAME_CIA)
#define FTYPE_RENAMABLE(tp) (tp&(GAME_NCCH|GAME_NCSD|GAME_CIA|GAME_NDS|GAME_GBA))
#define FTYPE_TRIMABLE(tp) (tp&(IMG_NAND|GAME_NCCH|GAME_NCSD|GAME_NDS|GAME_GBA|SYS_FIRM))
#define FTYPE_TRIMABLE(tp) (tp&(IMG_NAND|GAME_NCCH|GAME_NCSD|GAME_NDS|SYS_FIRM))
#define FTYPE_TRANSFERABLE(tp) ((u64) (tp&(IMG_FAT|FLAG_CTR)) == (u64) (IMG_FAT|FLAG_CTR))
#define FTYPE_NCSDFIXABLE(tp) (tp&(HDR_NAND|NOIMG_NAND))
#define FTYPE_HASCODE(tp) (((u64) (tp&(GAME_NCCH|FLAG_CXI)) == (u64) (GAME_NCCH|FLAG_CXI))|(tp&GAME_NCSD))
@ -78,11 +68,9 @@
#define FTYPE_KEYINIT(tp) (tp&(BIN_KEYDB))
#define FTYPE_KEYINSTALL(tp) (tp&(BIN_KEYDB))
#define FTYPE_SCRIPT(tp) (tp&(TXT_SCRIPT))
#define FTYPE_LUA(tp) (tp&(TXT_LUA))
#define FTYPE_FONT(tp) (tp&(FONT_PBM|FONT_RIFF))
#define FTYPE_TRANSLATION(tp) (tp&(TRANSLATION))
#define FTYPE_FONT(tp) (tp&(FONT_PBM))
#define FTYPE_GFX(tp) (tp&(GFX_PNG))
#define FTYPE_SETABLE(tp) (tp&(FONT_PBM|FONT_RIFF|TRANSLATION))
#define FTYPE_SETABLE(tp) (tp&(FONT_PBM))
#define FTYPE_BOOTABLE(tp) (tp&(SYS_FIRM))
#define FTYPE_INSTALLABLE(tp) (tp&(SYS_FIRM))
#define FTYPE_AGBSAVE(tp) (tp&(SYS_AGBSAVE))

View File

@ -1,7 +1,6 @@
#include "fsdrive.h"
#include "fsgame.h"
#include "fsinit.h"
#include "language.h"
#include "virtual.h"
#include "vcart.h"
#include "sddata.h"
@ -12,18 +11,16 @@
// last search pattern, path & mode
static char search_pattern[256] = { 0 };
static char search_path[256] = { 0 };
static bool title_manager_mode = false;
static bool search_title_mode = false;
int DriveType(const char* path) {
int type = DRV_UNKNOWN;
int pdrv = GetMountedFSNum(path);
if (CheckAliasDrive(path)) {
type = DRV_FAT | DRV_ALIAS | ((*path == 'A') ? DRV_SYSNAND : DRV_EMUNAND);
} else if (*search_pattern && *search_path && (strncmp(path, "Z:", 3) == 0)) {
type = DRV_SEARCH;
} else if (title_manager_mode && (strncmp(path, "Y:", 3) == 0)) {
type = DRV_VIRTUAL | DRV_TITLEMAN;
} else if ((pdrv >= 0) && (pdrv < NORM_FS)) {
if (pdrv == 0) {
type = DRV_FAT | DRV_SDCARD | DRV_STDFAT;
@ -42,75 +39,72 @@ int DriveType(const char* path) {
} else if ((pdrv >= 7) && (pdrv <= 9) &&
(GetMountState() & (IMG_FAT|IMG_NAND))) {
type = DRV_FAT | DRV_IMAGE | DRV_STDFAT;
}
}
} else if (CheckVirtualDrive(path)) {
int vsrc = GetVirtualSource(path);
if (vsrc == VRT_SYSNAND) {
type = DRV_VIRTUAL | DRV_SYSNAND;
} else if (vsrc == VRT_EMUNAND) {
type = DRV_VIRTUAL | DRV_EMUNAND;
} else if ((vsrc == VRT_IMGNAND) || (vsrc == VRT_DISADIFF) || (vsrc == VRT_BDRI)) {
} else if ((vsrc == VRT_IMGNAND) || (vsrc == VRT_DISADIFF)) {
type = DRV_VIRTUAL | DRV_IMAGE;
} else if (vsrc == VRT_XORPAD) {
type = DRV_VIRTUAL | DRV_XORPAD;
} else if (vsrc == VRT_MEMORY) {
type = DRV_VIRTUAL | DRV_MEMORY;
} else if ((vsrc == VRT_GAME) || (vsrc == VRT_KEYDB)) {
} else if ((vsrc == VRT_GAME) || (vsrc == VRT_KEYDB) || (vsrc == VRT_TICKDB)) {
type = DRV_VIRTUAL | DRV_GAME | DRV_IMAGE;
} else if (vsrc == VRT_CART) {
type = DRV_VIRTUAL | DRV_CART;
} else if (vsrc == VRT_VRAM) {
type = DRV_VIRTUAL | DRV_VRAM;
}
}
}
return type;
}
void SetFSSearch(const char* pattern, const char* path) {
void SetFSSearch(const char* pattern, const char* path, bool mode) {
if (pattern && path) {
strncpy(search_pattern, pattern, 256);
search_pattern[255] = '\0';
strncpy(search_path, path, 256);
search_path[255] = '\0';
search_title_mode = mode;
} else *search_pattern = *search_path = '\0';
}
void SetTitleManagerMode(bool mode) {
title_manager_mode = mode;
}
bool GetFATVolumeLabel(const char* drv, char* label) {
return (f_getlabel(drv, label, NULL) == FR_OK);
}
bool GetRootDirContentsWorker(DirStruct* contents) {
const char* drvname[] = { FS_DRVNAME };
static const char* drvname[] = { FS_DRVNAME };
static const char* drvnum[] = { FS_DRVNUM };
u32 n_entries = 0;
char sdlabel[DRV_LABEL_LEN];
if (!GetFATVolumeLabel("0:", sdlabel) || !(*sdlabel))
strcpy(sdlabel, STR_LAB_NOLABEL);
strcpy(sdlabel, "NOLABEL");
char carttype[16];
GetVCartTypeString(carttype);
// virtual root objects hacked in
for (u32 i = 0; (i < countof(drvnum)) && (n_entries < MAX_DIR_ENTRIES); i++) {
for (u32 i = 0; (i < NORM_FS+VIRT_FS) && (n_entries < MAX_DIR_ENTRIES); i++) {
DirEntry* entry = &(contents->entry[n_entries]);
if (!DriveType(drvnum[i])) continue; // drive not available
entry->p_name = 4;
entry->name = entry->path + entry->p_name;
memset(entry->path, 0x00, 256);
memset(entry->path, 0x00, 64);
snprintf(entry->path, 4, "%s", drvnum[i]);
if ((*(drvnum[i]) >= '7') && (*(drvnum[i]) <= '9') && !(GetMountState() & IMG_NAND)) // Drive 7...9 handling
snprintf(entry->name, 252, "[%s] %s", drvnum[i],
(*(drvnum[i]) == '7') ? STR_LAB_FAT_IMAGE :
(*(drvnum[i]) == '8') ? STR_LAB_BONUS_DRIVE :
(*(drvnum[i]) == '9') ? STR_LAB_RAMDRIVE : "UNK");
snprintf(entry->name, 32, "[%s] %s", drvnum[i],
(*(drvnum[i]) == '7') ? "FAT IMAGE" :
(*(drvnum[i]) == '8') ? "BONUS DRIVE" :
(*(drvnum[i]) == '9') ? "RAMDRIVE" : "UNK");
else if (*(drvnum[i]) == 'G') // Game drive special handling
snprintf(entry->name, 252, "[%s] %s %s", drvnum[i],
snprintf(entry->name, 32, "[%s] %s %s", drvnum[i],
(GetMountState() & GAME_CIA ) ? "CIA" :
(GetMountState() & GAME_NCSD ) ? "NCSD" :
(GetMountState() & GAME_NCCH ) ? "NCCH" :
@ -120,17 +114,17 @@ bool GetRootDirContentsWorker(DirStruct* contents) {
(GetMountState() & SYS_FIRM ) ? "FIRM" :
(GetMountState() & GAME_TAD ) ? "DSIWARE" : "UNK", drvname[i]);
else if (*(drvnum[i]) == 'C') // Game cart handling
snprintf(entry->name, 252, "[%s] %s (%s)", drvnum[i], drvname[i], carttype);
snprintf(entry->name, 32, "[%s] %s (%s)", drvnum[i], drvname[i], carttype);
else if (*(drvnum[i]) == '0') // SD card handling
snprintf(entry->name, 252, "[%s] %s (%s)", drvnum[i], drvname[i], sdlabel);
else snprintf(entry->name, 252, "[%s] %s", drvnum[i], drvname[i]);
snprintf(entry->name, 32, "[%s] %s (%s)", drvnum[i], drvname[i], sdlabel);
else snprintf(entry->name, 32, "[%s] %s", drvnum[i], drvname[i]);
entry->size = GetTotalSpace(entry->path);
entry->type = T_ROOT;
entry->marked = 0;
n_entries++;
}
contents->n_entries = n_entries;
return contents->n_entries;
}
@ -139,11 +133,11 @@ bool GetDirContentsWorker(DirStruct* contents, char* fpath, int fnsize, const ch
FILINFO fno;
char* fname = fpath + strnlen(fpath, fnsize - 1);
bool ret = false;
if (fvx_opendir(&pdir, fpath) != FR_OK)
return false;
if (*(fname-1) != '/') *(fname++) = '/';
while (fvx_readdir(&pdir, &fno) == FR_OK) {
if ((strncmp(fno.fname, ".", 2) == 0) || (strncmp(fno.fname, "..", 3) == 0))
continue; // filter out virtual entries
@ -157,10 +151,6 @@ bool GetDirContentsWorker(DirStruct* contents, char* fpath, int fnsize, const ch
break;
} else if (!pattern || (fvx_match_name(fname, pattern) == FR_OK)) {
DirEntry* entry = &(contents->entry[contents->n_entries]);
if (contents->n_entries >= MAX_DIR_ENTRIES) {
ret = true; // Too many entries, still okay if we stop here
break;
}
strncpy(entry->path, fpath, 256);
entry->path[255] = '\0';
entry->p_name = fname - fpath;
@ -173,8 +163,12 @@ bool GetDirContentsWorker(DirStruct* contents, char* fpath, int fnsize, const ch
entry->size = fno.fsize;
}
entry->marked = 0;
if (!recursive || (entry->type != T_DIR))
++(contents->n_entries);
if (!recursive || (entry->type != T_DIR)) {
if (++(contents->n_entries) >= MAX_DIR_ENTRIES) {
ret = true; // Too many entries, still okay if we stop here
break;
}
}
}
if (recursive && (fno.fattrib & AM_DIR)) {
if (!GetDirContentsWorker(contents, fpath, fnsize, pattern, recursive))
@ -182,7 +176,7 @@ bool GetDirContentsWorker(DirStruct* contents, char* fpath, int fnsize, const ch
}
}
fvx_closedir(&pdir);
return ret;
}
@ -212,12 +206,9 @@ void SearchDirContents(DirStruct* contents, const char* path, const char* patter
void GetDirContents(DirStruct* contents, const char* path) {
if (*search_path && (DriveType(path) & DRV_SEARCH)) {
ShowString("%s", STR_SEARCHING_PLEASE_WAIT);
ShowString("Searching, please wait...");
SearchDirContents(contents, search_path, search_pattern, true);
ClearScreenF(true, false, COLOR_STD_BG);
} else if (title_manager_mode && (DriveType(path) & DRV_TITLEMAN)) {
SearchDirContents(contents, "T:", "*", false);
SetupTitleManager(contents);
if (search_title_mode) SetDirGoodNames(contents);
ClearScreenF(true, false, COLOR_STD_BG);
} else SearchDirContents(contents, path, NULL, false);
if (*path) SortDirStruct(contents);
@ -231,8 +222,8 @@ uint64_t GetFreeSpace(const char* path)
int pdrv = GetMountedFSNum(path);
FATFS* fsobj = GetMountedFSObject(path);
if ((pdrv < 0) || !fsobj) return 0;
snprintf(fsname, sizeof(fsname), "%i:", pdrv);
snprintf(fsname, 3, "%i:", pdrv);
if (f_getfree(fsname, &free_clusters, &fsptr) != FR_OK)
return 0;

View File

@ -4,7 +4,8 @@
#include "fsdir.h"
#define NORM_FS 10
#define IMGN_FS 3 // image normal filesystems
#define IMGN_FS 3 // image normal filesystems
#define VIRT_FS 12
// primary drive types
#define DRV_UNKNOWN (0<<0)
@ -25,36 +26,30 @@
#define DRV_VRAM (1UL<<13)
#define DRV_ALIAS (1UL<<14)
#define DRV_BONUS (1UL<<15)
#define DRV_TITLEMAN (1UL<<16)
#define DRV_SEARCH (1UL<<17)
#define DRV_STDFAT (1UL<<18) // standard FAT drive without limitations
#define DRV_SEARCH (1UL<<16)
#define DRV_STDFAT (1UL<<17) // standard FAT drive without limitations
#define DRV_LABEL_LEN (36)
#define FS_DRVNAME \
STR_LAB_SDCARD, \
STR_LAB_SYSNAND_CTRNAND, STR_LAB_SYSNAND_TWLN, STR_LAB_SYSNAND_TWLP, STR_LAB_SYSNAND_SD, STR_LAB_SYSNAND_VIRTUAL, \
STR_LAB_EMUNAND_CTRNAND, STR_LAB_EMUNAND_TWLN, STR_LAB_EMUNAND_TWLP, STR_LAB_EMUNAND_SD, STR_LAB_EMUNAND_VIRTUAL, \
STR_LAB_IMGNAND_CTRNAND, STR_LAB_IMGNAND_TWLN, STR_LAB_IMGNAND_TWLP, STR_LAB_IMGNAND_VIRTUAL, \
STR_LAB_GAMECART, \
STR_LAB_GAME_IMAGE, STR_LAB_AESKEYDB_IMAGE, STR_LAB_BDRI_IMAGE, STR_LAB_DISA_DIFF_IMAGE, \
STR_LAB_MEMORY_VIRTUAL, \
STR_LAB_VRAM_VIRTUAL, \
STR_LAB_TITLE_MANAGER, \
STR_LAB_LAST_SEARCH
"SDCARD", \
"SYSNAND CTRNAND", "SYSNAND TWLN", "SYSNAND TWLP", "SYSNAND SD", "SYSNAND VIRTUAL", \
"EMUNAND CTRNAND", "EMUNAND TWLN", "EMUNAND TWLP", "EMUNAND SD", "EMUNAND VIRTUAL", \
"IMGNAND CTRNAND", "IMGNAND TWLN", "IMGNAND TWLP", "IMGNAND VIRTUAL", \
"GAMECART", \
"GAME IMAGE", "AESKEYDB IMAGE", "TICKET.DB IMAGE", "DISA/DIFF IMAGE", \
"MEMORY VIRTUAL", \
"VRAM VIRTUAL", \
"LAST SEARCH" \
#define FS_DRVNUM \
"0:", "1:", "2:", "3:", "A:", "S:", "4:", "5:", "6:", "B:", "E:", "7:", "8:", "9:", \
"I:", "C:", "G:", "K:", "T:", "D:", "M:", "V:", "Y:", "Z:"
"0:", "1:", "2:", "3:", "A:", "S:", "4:", "5:", "6:", "B:", "E:", "7:", "8:", "9:", "I:", "C:", "G:", "K:", "T:", "D:", "M:", "V:", "Z:"
/** Function to identify the type of a drive **/
int DriveType(const char* path);
/** Set search pattern / path / mode for special Z: drive **/
void SetFSSearch(const char* pattern, const char* path);
/** Enable title manager for special processing of mounted title.db **/
void SetTitleManagerMode(bool mode);
void SetFSSearch(const char* pattern, const char* path, bool mode);
/** Read the FAT volume label of a partition **/
bool GetFATVolumeLabel(const char* drv, char* label);

View File

@ -1,17 +1,14 @@
#include "fsgame.h"
#include "fsperm.h"
#include "gameutil.h"
#include "language.h"
#include "tie.h"
#include "ui.h"
#include "vff.h"
#include "ff.h"
void SetupTitleManager(DirStruct* contents) {
void SetDirGoodNames(DirStruct* contents) {
char goodname[256];
ShowProgress(0, 0, "");
for (u32 s = 0; s < contents->n_entries; s++) {
DirEntry* entry = &(contents->entry[s]);
// set good name for entry
u32 plen = strnlen(entry->path, 256);
if (!ShowProgress(s+1, contents->n_entries, entry->path)) break;
if ((GetGoodName(goodname, entry->path, false) != 0) ||
@ -20,11 +17,6 @@ void SetupTitleManager(DirStruct* contents) {
entry->p_name = plen + 1;
entry->name = entry->path + entry->p_name;
snprintf(entry->name, 256 - entry->p_name, "%s", goodname);
// grab title size from tie
TitleInfoEntry tie;
if (fvx_qread(entry->path, &tie, 0, sizeof(TitleInfoEntry), NULL) != FR_OK)
continue;
entry->size = tie.title_size;
}
}
@ -33,17 +25,17 @@ bool GoodRenamer(DirEntry* entry, bool ask) {
if ((GetGoodName(goodname, entry->path, false) != 0) ||
(strncmp(goodname + strnlen(goodname, 256) - 4, ".tmd", 4) == 0)) // no TMD, please
return false;
if (ask) { // ask for confirmatiom
char oldname_tr[UTF_BUFFER_BYTESIZE(32)];
char oldname_tr[32+1];
char newname_ww[256];
TruncateString(oldname_tr, entry->name, 32, 8);
strncpy(newname_ww, goodname, 256);
WordWrapString(newname_ww, 32);
if (!ShowPrompt(true, "%s\n%s\n \n%s", oldname_tr, STR_RENAME_TO_GOOD_NAME, newname_ww))
if (!ShowPrompt(true, "%s\nRename to good name?\n \n%s", oldname_tr, newname_ww))
return true; // call it a success because user choice
}
char npath[256]; // get new path
strncpy(npath, entry->path, 256);
char* nname = strrchr(npath, '/');
@ -55,6 +47,6 @@ bool GoodRenamer(DirEntry* entry, bool ask) {
if (f_rename(entry->path, npath) != FR_OK) return false;
strncpy(entry->path, npath, 256);
entry->name = entry->path + (nname - npath);
return true;
}

View File

@ -3,5 +3,5 @@
#include "common.h"
#include "fsdir.h"
void SetupTitleManager(DirStruct* contents);
void SetDirGoodNames(DirStruct* contents);
bool GoodRenamer(DirEntry* entry, bool ask);

View File

@ -18,16 +18,16 @@ bool InitSDCardFS() {
bool InitExtFS() {
static bool ramdrv_ready = false;
for (u32 i = 1; i < NORM_FS; i++) {
char fsname[8];
snprintf(fsname, sizeof(fsname), "%lu:", i);
snprintf(fsname, 7, "%lu:", i);
if (fs_mounted[i]) continue;
fs_mounted[i] = (f_mount(fs + i, fsname, 1) == FR_OK);
if ((!fs_mounted[i] || !ramdrv_ready) && (i == NORM_FS - 1) && !(GetMountState() & IMG_NAND)) {
u8* buffer = (u8*) malloc(STD_BUFFER_SIZE);
if (!buffer) bkpt; // whatever, this won't go wrong anyways
f_mkfs(fsname, NULL, buffer, STD_BUFFER_SIZE); // format ramdrive if required
f_mkfs(fsname, FM_ANY, 0, buffer, STD_BUFFER_SIZE); // format ramdrive if required
free(buffer);
f_mount(NULL, fsname, 1);
fs_mounted[i] = (f_mount(fs + i, fsname, 1) == FR_OK);
@ -44,7 +44,7 @@ bool InitImgFS(const char* path) {
u32 drv_i = NORM_FS - IMGN_FS;
char fsname[8];
for (; drv_i < NORM_FS; drv_i++) {
snprintf(fsname, sizeof(fsname), "%lu:", drv_i);
snprintf(fsname, 7, "%lu:", drv_i);
if (!(DriveType(fsname)&DRV_IMAGE)) break;
}
// deinit virtual filesystem
@ -58,20 +58,20 @@ bool InitImgFS(const char* path) {
else if ((type&IMG_FAT) && (drv_i < NORM_FS - IMGN_FS + 1)) drv_i = NORM_FS - IMGN_FS + 1;
// reinit image filesystem
for (u32 i = NORM_FS - IMGN_FS; i < drv_i; i++) {
snprintf(fsname, sizeof(fsname), "%lu:", i);
snprintf(fsname, 7, "%lu:", i);
fs_mounted[i] = (f_mount(fs + i, fsname, 1) == FR_OK);
}
return GetMountState();
}
void DeinitExtFS() {
InitImgFS(NULL);
SetupNandSdDrive(NULL, NULL, NULL, 0);
SetupNandSdDrive(NULL, NULL, NULL, 1);
InitImgFS(NULL);
for (u32 i = NORM_FS - 1; i > 0; i--) {
if (fs_mounted[i]) {
char fsname[8];
snprintf(fsname, sizeof(fsname), "%lu:", i);
snprintf(fsname, 7, "%lu:", i);
f_mount(NULL, fsname, 1);
fs_mounted[i] = false;
}
@ -91,7 +91,7 @@ void DismountDriveType(u32 type) { // careful with this - no safety checks
}
for (u32 i = 0; i < NORM_FS; i++) {
char fsname[8];
snprintf(fsname, sizeof(fsname), "%lu:", i);
snprintf(fsname, 7, "%lu:", i);
if (!fs_mounted[i] || !(type & DriveType(fsname)))
continue;
f_mount(NULL, fsname, 1);

View File

@ -6,7 +6,7 @@
// init SD card filesystem - required(?) for everything else
bool InitSDCardFS();
// init fill external fileystem
// init fill external fileystem
bool InitExtFS();
// mount and init image file system
@ -21,7 +21,7 @@ void DeinitSDCardFS();
// dismount drives of a certain type
void DismountDriveType(u32 type);
// returns the mount state of the SD card
// returns the mount state of the SD card
bool CheckSDMountState(void);
// get number of mounted file system (only for FATFS filesystems)

View File

@ -4,11 +4,10 @@
#include "image.h"
#include "unittype.h"
#include "essentials.h"
#include "language.h"
#include "ui.h"
#include "sdmmc.h"
#define PATH_SYS_LVL1 "S:/twln.bin", "S:/twlp.bin"
#define PATH_SYS_LVL1 "S:/twln.bin", "S:/twlp.bin"
#define PATH_SYS_LVL2 "1:/rw/sys/LocalFriendCodeSeed_B", "1:/rw/sys/LocalFriendCodeSeed_A", \
"1:/rw/sys/SecureInfo_A", "1:/rw/sys/SecureInfo_B", \
"1:/private/movable.sed", "1:/ro/sys/HWCAL0.dat", "1:/ro/sys/HWCAL1.dat", \
@ -21,10 +20,10 @@
static u32 write_permissions = PERM_BASE;
bool CheckWritePermissions(const char* path) {
char area_name[UTF_BUFFER_BYTESIZE(16)];
char area_name[16];
int drvtype = DriveType(path);
u32 perm;
// create a standardized path string
char path_f[256];
char* p = (char*) path;
@ -38,16 +37,16 @@ bool CheckWritePermissions(const char* path) {
// check mounted image write permissions
if ((drvtype & DRV_IMAGE) && !CheckWritePermissions(GetMountPath()))
return false; // endless loop when mounted file inside image, but not possible
// SD card write protection check
if ((drvtype & (DRV_SDCARD | DRV_EMUNAND | DRV_ALIAS)) && SD_WRITE_PROTECTED) {
ShowPrompt(false, "%s", STR_SD_WRITE_PROTECTED_CANT_CONTINUE);
ShowPrompt(false, "SD card is write protected!\nCan't continue.");
return false;
}
// check drive type, get permission type
if (drvtype & DRV_SYSNAND) {
static const u32 perms[] = { PERM_SYS_LVL0, PERM_SYS_LVL1, PERM_SYS_LVL2, PERM_SYS_LVL3 };
u32 perms[] = { PERM_SYS_LVL0, PERM_SYS_LVL1, PERM_SYS_LVL2, PERM_SYS_LVL3 };
u32 lvl = (drvtype & (DRV_TWLNAND|DRV_ALIAS|DRV_CTRNAND)) ? 1 : 0;
if (drvtype & (DRV_CTRNAND|DRV_VIRTUAL)) { // check for paths
const char* path_lvl3[] = { PATH_SYS_LVL3 };
@ -64,9 +63,9 @@ bool CheckWritePermissions(const char* path) {
if ((drvtype & DRV_CTRNAND) || (lvl == 2)) lvl = 3;
}
perm = perms[lvl];
snprintf(area_name, sizeof(area_name), STR_SYSNAND_LVL_N, lvl);
snprintf(area_name, 16, "SysNAND (lvl%lu)", lvl);
} else if (drvtype & DRV_EMUNAND) {
static const u32 perms[] = { PERM_EMU_LVL0, PERM_EMU_LVL1 };
u32 perms[] = { PERM_EMU_LVL0, PERM_EMU_LVL1 };
u32 lvl = (drvtype & (DRV_ALIAS|DRV_CTRNAND)) ? 1 : 0;
if (drvtype & DRV_VIRTUAL) { // check for paths
const char* path_lvl1[] = { PATH_EMU_LVL1 };
@ -74,58 +73,58 @@ bool CheckWritePermissions(const char* path) {
if (strncasecmp(path_f, path_lvl1[i], 256) == 0) lvl = 1;
}
perm = perms[lvl];
snprintf(area_name, sizeof(area_name), STR_EMUNAND_LVL_N, lvl);
snprintf(area_name, 16, "EmuNAND (lvl%lu)", lvl);
} else if (drvtype & DRV_GAME) {
perm = PERM_GAME;
snprintf(area_name, sizeof(area_name), "%s", STR_GAME_IMAGES);
snprintf(area_name, 16, "game images");
} else if (drvtype & DRV_CART) {
perm = PERM_CART;
snprintf(area_name, sizeof(area_name), "%s", STR_GAMECART_SAVES);
snprintf(area_name, 16, "gamecart saves");
} else if (drvtype & DRV_VRAM) {
perm = PERM_VRAM;
snprintf(area_name, sizeof(area_name), "vram0");
snprintf(area_name, 16, "vram0");
} else if (drvtype & DRV_XORPAD) {
perm = PERM_XORPAD;
snprintf(area_name, sizeof(area_name), "XORpads");
snprintf(area_name, 16, "XORpads");
} else if (drvtype & DRV_IMAGE) {
perm = PERM_IMAGE;
snprintf(area_name, sizeof(area_name), "%s", STR_IMAGES);
snprintf(area_name, 16, "images");
} else if (drvtype & DRV_MEMORY) {
perm = PERM_MEMORY;
snprintf(area_name, sizeof(area_name), "%s", STR_MEMORY_AREAS);
snprintf(area_name, 16, "memory areas");
} else if (strncasecmp(path_f, "0:/Nintendo 3DS", 15) == 0) { // this check could be better
perm = PERM_SDDATA;
snprintf(area_name, sizeof(area_name), "%s", STR_SD_SYSTEM_DATA);
snprintf(area_name, 16, "SD system data");
} else if (drvtype & DRV_SDCARD) {
perm = PERM_SDCARD;
snprintf(area_name, sizeof(area_name), "%s", STR_SD_CARD);
snprintf(area_name, 16, "SD card");
} else if (drvtype & DRV_RAMDRIVE) {
perm = PERM_RAMDRIVE;
snprintf(area_name, sizeof(area_name), "%s", STR_RAM_DRIVE);
snprintf(area_name, 16, "RAM drive");
} else {
return false;
}
// check permission, return if already set
if ((write_permissions & perm) == perm)
return true;
// offer unlock if possible
if (!(perm & (PERM_VRAM|PERM_GAME|PERM_XORPAD))) {
// ask the user
if (!ShowPrompt(true, STR_WRITING_TO_DRIVE_IS_LOCKED_UNLOCK_NOW, area_name))
if (!ShowPrompt(true, "Writing to %s is locked!\nUnlock it now?", area_name))
return false;
return SetWritePermissions(perm, true);
}
// unlock not possible
ShowPrompt(false, STR_UNLOCK_WRITE_FOR_DRIVE_NOT_ALLOWED, area_name);
ShowPrompt(false, "Unlock write permission for\n%s is not allowed.", area_name);
return false;
}
bool CheckDirWritePermissions(const char* path) {
static const char* path_chk[] = { PATH_SYS_LVL3, PATH_SYS_LVL2, PATH_SYS_LVL1, PATH_EMU_LVL1 };
const char* path_chk[] = { PATH_SYS_LVL3, PATH_SYS_LVL2, PATH_SYS_LVL1, PATH_EMU_LVL1 };
for (u32 i = 0; i < sizeof(path_chk) / sizeof(char*); i++) {
const char* path_cmp = path_chk[i];
u32 p = 0;
@ -142,75 +141,75 @@ bool SetWritePermissions(u32 perm, bool add_perm) {
if (!add_perm) write_permissions = perm;
return true;
}
switch (perm) {
case PERM_BASE:
if (!ShowUnlockSequence(1, "%s", STR_ENABLE_BASE_WRITE))
if (!ShowUnlockSequence(1, "You want to enable base\nwriting permissions."))
return false;
break;
case PERM_SDCARD:
if (!ShowUnlockSequence(1, "%s", STR_ENABLE_SD_WRITE))
if (!ShowUnlockSequence(1, "You want to enable SD card\nwriting permissions."))
return false;
break;
case PERM_IMAGE:
if (!ShowUnlockSequence(1, "%s", STR_ENABLE_IMAGE_WRITE))
if (!ShowUnlockSequence(1, "You want to enable image\nwriting permissions."))
return false;
break;
case PERM_RAMDRIVE:
if (!ShowUnlockSequence(1, "%s", STR_ENABLE_RAM_DRIVE_WRITE))
if (!ShowUnlockSequence(1, "You want to enable RAM drive\nwriting permissions."))
return false;
break;
case PERM_EMU_LVL0:
if (!ShowUnlockSequence(1, "%s", STR_ENABLE_EMUNAND_0_WRITE))
if (!ShowUnlockSequence(1, "You want to enable EmuNAND\nlvl0 writing permissions."))
return false;
break;
case PERM_SYS_LVL0:
if (!ShowUnlockSequence(1, "%s", STR_ENABLE_SYSNAND_0_WRITE))
if (!ShowUnlockSequence(1, "You want to enable SysNAND\nlvl0 writing permissions."))
return false;
break;
case PERM_EMU_LVL1:
if (!ShowUnlockSequence(2, "%s", STR_ENABLE_EMUNAND_1_WRITE))
if (!ShowUnlockSequence(2, "You want to enable EmuNAND\nlvl1 writing permissions.\n \nThis enables you to modify\nrecoverable system data,\nuser data & savegames."))
return false;
break;
case PERM_SYS_LVL1:
if (!ShowUnlockSequence(2, "%s", STR_ENABLE_SYSNAND_1_WRITE))
if (!ShowUnlockSequence(2, "You want to enable SysNAND\nlvl1 writing permissions.\n \nThis enables you to modify\nsystem data, installations,\nuser data & savegames."))
return false;
break;
case PERM_SDDATA:
if (!ShowUnlockSequence(2, "You want to enable SD data\nwriting permissions.\n \nThis enables you to modify\ninstallations, user data &\nsavegames."))
return false;
break;
case PERM_CART:
if (!ShowUnlockSequence(2, "%s", STR_ENABLE_GAMECART_SAVE_WRITE))
if (!ShowUnlockSequence(2, "You want to enable gamecart\nsave writing permissions."))
return false;
break;
#ifndef SAFEMODE
case PERM_SYS_LVL2:
if (!ShowUnlockSequence(3, "%s", STR_ENABLE_SYSNAND_2_WRITE))
if (!ShowUnlockSequence(3, "!Better be careful!\n \nYou want to enable SysNAND\nlvl2 writing permissions.\n \nThis enables you to modify\nirrecoverable system data!"))
return false;
break;
case PERM_MEMORY:
if (!ShowUnlockSequence(4, "%s", STR_ENABLE_MEMORY_WRITE))
return false;
break;
case PERM_SDDATA:
if (!ShowUnlockSequence(5, "%s", STR_ENABLE_SD_DATA_WRITE))
if (!ShowUnlockSequence(4, "!Better be careful!\n \nYou want to enable memory\nwriting permissions.\n \nWriting to certain areas may\nlead to unexpected results."))
return false;
break;
case PERM_SYS_LVL3:
if (!ShowUnlockSequence(6, "%s", STR_ENABLE_SYSNAND_3_WRITE))
if (!ShowUnlockSequence(6, "!THIS IS YOUR ONLY WARNING!\n \nYou want to enable SysNAND\nlvl3 writing permissions.\n \nThis enables you to OVERWRITE\nyour bootloader installation,\nessential system files and/or\nBRICK your console!"))
return false;
break;
default:
ShowPrompt(false, "%s", STR_UNLOCK_WRITE_NOT_ALLOWED);
ShowPrompt(false, "Unlock write permission is not allowed.");
return false;
break;
#else
default:
ShowPrompt(false, "%s", STR_CANT_UNLOCK_WRITE_TRY_GODMODE9);
ShowPrompt(false, "Can't unlock write permission.\nTry GodMode9 instead!");
return false;
break;
#endif
}
write_permissions = add_perm ? write_permissions | perm : perm;
return true;
}

View File

@ -21,7 +21,7 @@
#define PERM_BASE (PERM_SDCARD | PERM_IMAGE | PERM_RAMDRIVE | PERM_EMU_LVL0 | PERM_SYS_LVL0)
// permission levels / colors
#define PERM_BLUE (GetWritePermissions()&(PERM_MEMORY|(PERM_SDDATA&~PERM_SDCARD)))
#define PERM_BLUE (GetWritePermissions()&PERM_MEMORY)
#define PERM_RED (GetWritePermissions()&(PERM_SYS_LVL3&~PERM_SYS_LVL2))
#define PERM_ORANGE (GetWritePermissions()&(PERM_SYS_LVL2&~PERM_SYS_LVL1))
#define PERM_YELLOW (GetWritePermissions()&((PERM_SYS_LVL1&~PERM_SYS_LVL0)|(PERM_EMU_LVL1&~PERM_EMU_LVL0)|(PERM_SDDATA&~PERM_SDCARD)|PERM_CART))

View File

@ -11,10 +11,9 @@
#include "ff.h"
#include "ui.h"
#include "swkbd.h"
#include "language.h"
#define SKIP_CUR (1UL<<11)
#define OVERWRITE_CUR (1UL<<12)
#define SKIP_CUR (1UL<<10)
#define OVERWRITE_CUR (1UL<<11)
#define _MAX_FS_OPT 8 // max file selector options
@ -44,19 +43,19 @@ bool FormatSDCard(u64 hidden_mb, u32 cluster_size, const char* label) {
u32 emu_size = (u32) ((hidden_mb * 1024 * 1024) / 512);
u32 fat_sector = align(emu_sector + emu_size, 0x2000); // align to 4MB
u32 fat_size = (fat_sector < sd_size) ? sd_size - fat_sector : 0;
// FAT size check
if (fat_size < 0x80000) { // minimum free space: 256MB
ShowPrompt(false, "%s", STR_ERROR_SD_TOO_SMALL);
ShowPrompt(false, "Error: SD card is too small");
return false;
}
// Write protection check
if (SD_WRITE_PROTECTED) {
ShowPrompt(false, "%s", STR_SD_WRITE_PROTECTED_CANT_CONTINUE);
ShowPrompt(false, "SD card is write protected!\nCan't continue.");
return false;
}
// build the MBR
memcpy(mbrdata + 0x08, &fat_sector, 4);
memcpy(mbrdata + 0x0C, &fat_size, 4);
@ -65,56 +64,50 @@ bool FormatSDCard(u64 hidden_mb, u32 cluster_size, const char* label) {
memcpy(mbr + 0x1BE, mbrdata, 0x42);
if (hidden_mb) memcpy(mbr, "GATEWAYNAND", 12); // legacy
else memset(mbr + 0x1CE, 0, 0x10);
// one last warning....
// 0:/Nintendo 3DS/ write permission is ignored here, this warning is enough
if (!ShowUnlockSequence(5, "%s", STR_WARNING_PROCEEDING_WILL_FORMAT_SD_DELETE_ALL_DATA))
if (!ShowUnlockSequence(5, "!WARNING!\n \nProceeding will format this SD.\nThis will irreversibly delete\nALL data on it."))
return false;
ShowString("%s", STR_FORMATTING_SD_PLEASE_WAIT);
ShowString("Formatting SD, please wait...");
// write the MBR to disk
// !this assumes a fully deinitialized file system!
if ((sdmmc_sdcard_init() != 0) || (sdmmc_sdcard_writesectors(0, 1, mbr) != 0) ||
(emu_size && ((sdmmc_nand_readsectors(0, 1, ncsd) != 0) || (sdmmc_sdcard_writesectors(1, 1, ncsd) != 0)))) {
ShowPrompt(false, "%s", STR_ERROR_SD_CARD_IO_FAILURE);
ShowPrompt(false, "Error: SD card i/o failure");
return false;
}
// format the SD card
VolToPart[0].pt = 1; // workaround to prevent FatFS rebuilding the MBR
InitSDCardFS();
UINT c_size = cluster_size;
u8* buffer = (u8*) malloc(STD_BUFFER_SIZE);
if (!buffer) bkpt; // will not happen
MKFS_PARM opt0, opt1;
opt0.fmt = opt1.fmt = FM_FAT32;
opt0.au_size = cluster_size;
opt1.au_size = 0;
opt0.align = opt1.align = 0;
opt0.n_fat = opt1.n_fat = 1;
opt0.n_root = opt1.n_root = 0;
bool ret = ((f_mkfs("0:", &opt0, buffer, STD_BUFFER_SIZE) == FR_OK) ||
(f_mkfs("0:", &opt1, buffer, STD_BUFFER_SIZE) == FR_OK)) &&
bool ret = ((f_mkfs("0:", FM_FAT32, c_size, buffer, STD_BUFFER_SIZE) == FR_OK) ||
(f_mkfs("0:", FM_FAT32, 0, buffer, STD_BUFFER_SIZE) == FR_OK)) &&
(f_setlabel((label) ? label : "0:GM9SD") == FR_OK);
free(buffer);
DeinitSDCardFS();
VolToPart[0].pt = 0; // revert workaround to prevent SD mount problems
return ret;
}
bool SetupBonusDrive(void) {
if (!ShowUnlockSequence(3, "%s", STR_FORMAT_BONUS_DRIVE_DELETE_ALL_DATA))
if (!ShowUnlockSequence(3, "Format the bonus drive?\nThis will irreversibly delete\nALL data on it."))
return false;
ShowString("%s", STR_FORMATTING_DRIVE_PLEASE_WAIT);
ShowString("Formatting drive, please wait...");
if (GetMountState() & IMG_NAND) InitImgFS(NULL);
u8* buffer = (u8*) malloc(STD_BUFFER_SIZE);
if (!buffer) bkpt;
bool ret = (f_mkfs("8:", NULL, buffer, STD_BUFFER_SIZE) == FR_OK);
bool ret = (f_mkfs("8:", FM_ANY, 0, buffer, STD_BUFFER_SIZE) == FR_OK);
free(buffer);
if (ret) {
f_setlabel("8:BONUS");
InitExtFS();
@ -125,20 +118,20 @@ bool SetupBonusDrive(void) {
bool FileUnlock(const char* path) {
FIL file;
FRESULT res;
if (!(DriveType(path) & DRV_FAT)) return true; // can't really check this
if ((res = fx_open(&file, path, FA_READ | FA_OPEN_EXISTING)) != FR_OK) {
char pathstr[UTF_BUFFER_BYTESIZE(32)];
char pathstr[32 + 1];
TruncateString(pathstr, path, 32, 8);
if (GetMountState() && (res == FR_LOCKED) &&
(ShowPrompt(true, "%s\n%s", pathstr, STR_FILE_IS_MOUNTED_UNMOUNT_TO_UNLOCK))) {
if (GetMountState() && (res == FR_LOCKED) &&
(ShowPrompt(true, "%s\nFile is currently mounted.\nUnmount to unlock?", pathstr))) {
InitImgFS(NULL);
if (fx_open(&file, path, FA_READ | FA_OPEN_EXISTING) != FR_OK)
return false;
} else return false;
}
fx_close(&file);
return true;
}
@ -162,25 +155,25 @@ size_t FileGetSize(const char* path) {
return fno.fsize;
}
bool FileGetSha(const char* path, u8* hash, u64 offset, u64 size, bool sha1) {
bool FileGetSha256(const char* path, u8* sha256, u64 offset, u64 size) {
bool ret = true;
FIL file;
u64 fsize;
if (fvx_open(&file, path, FA_READ | FA_OPEN_EXISTING) != FR_OK)
return false;
fsize = fvx_size(&file);
if (offset + size > fsize) return false;
if (!size) size = fsize - offset;
fvx_lseek(&file, offset);
u32 bufsiz = min(STD_BUFFER_SIZE, fsize);
u8* buffer = (u8*) malloc(bufsiz);
if (!buffer) return false;
ShowProgress(0, 0, path);
sha_init(sha1 ? SHA1_MODE : SHA256_MODE);
sha_init(SHA256_MODE);
for (u64 pos = 0; (pos < size) && ret; pos += bufsiz) {
UINT read_bytes = min(bufsiz, size - pos);
UINT bytes_read = 0;
@ -190,13 +183,13 @@ bool FileGetSha(const char* path, u8* hash, u64 offset, u64 size, bool sha1) {
ret = false;
sha_update(buffer, bytes_read);
}
sha_get(hash);
sha_get(sha256);
fvx_close(&file);
free(buffer);
ShowProgress(1, 1, path);
return ret;
}
@ -204,13 +197,13 @@ u32 FileFindData(const char* path, u8* data, u32 size_data, u32 offset_file) {
FIL file; // used for FAT & virtual
u64 found = (u64) -1;
u64 fsize = FileGetSize(path);
if (fvx_open(&file, path, FA_READ | FA_OPEN_EXISTING) != FR_OK)
return found;
u8* buffer = (u8*) malloc(STD_BUFFER_SIZE);
if (!buffer) return false;
// main routine
for (u32 pass = 0; pass < 2; pass++) {
bool show_progress = false;
@ -237,10 +230,10 @@ u32 FileFindData(const char* path, u8* data, u32 size_data, u32 offset_file) {
break;
}
}
free(buffer);
fvx_close(&file);
return found;
}
@ -248,13 +241,13 @@ bool FileInjectFile(const char* dest, const char* orig, u64 off_dest, u64 off_or
FIL ofile;
FIL dfile;
bool allow_expand = (flags && (*flags & ALLOW_EXPAND));
if (!CheckWritePermissions(dest)) return false;
if (strncasecmp(dest, orig, 256) == 0) {
ShowPrompt(false, "%s", STR_ERROR_CANT_INJECT_FILE_INTO_ITSELF);
ShowPrompt(false, "Error: Can't inject file into itself");
return false;
}
// open destination / origin
if (fvx_open(&dfile, dest, FA_WRITE | ((allow_expand) ? FA_OPEN_ALWAYS : FA_OPEN_EXISTING)) != FR_OK)
return false;
@ -267,23 +260,23 @@ bool FileInjectFile(const char* dest, const char* orig, u64 off_dest, u64 off_or
fvx_lseek(&ofile, off_orig);
if (!size && (off_orig < fvx_size(&ofile)))
size = fvx_size(&ofile) - off_orig;
// check file limits
if (!allow_expand && (off_dest + size > fvx_size(&dfile))) {
ShowPrompt(false, "%s", STR_OPERATION_WOULD_WRITE_BEYOND_EOF);
ShowPrompt(false, "Operation would write beyond end of file");
fvx_close(&dfile);
fvx_close(&ofile);
return false;
} else if (off_orig + size > fvx_size(&ofile)) {
ShowPrompt(false, "%s", STR_NOT_ENOUGH_DATA_IN_FILE);
ShowPrompt(false, "Not enough data in file");
fvx_close(&dfile);
fvx_close(&ofile);
return false;
}
u8* buffer = (u8*) malloc(STD_BUFFER_SIZE);
if (!buffer) return false;
bool ret = true;
ShowProgress(0, 0, orig);
for (u64 pos = 0; (pos < size) && ret; pos += STD_BUFFER_SIZE) {
@ -296,46 +289,46 @@ bool FileInjectFile(const char* dest, const char* orig, u64 off_dest, u64 off_or
ret = false;
if (ret && !ShowProgress(pos + bytes_read, size, orig)) {
if (flags && (*flags & NO_CANCEL)) {
ShowPrompt(false, "%s", STR_CANCEL_IS_NOT_ALLOWED_HERE);
} else ret = !ShowPrompt(true, "%s", STR_B_DETECTED_CANCEL);
ShowPrompt(false, "Cancel is not allowed here");
} else ret = !ShowPrompt(true, "B button detected. Cancel?");
ShowProgress(0, 0, orig);
ShowProgress(pos + bytes_read, size, orig);
}
}
ShowProgress(1, 1, orig);
free(buffer);
fvx_close(&dfile);
fvx_close(&ofile);
return ret;
}
bool FileSetByte(const char* dest, u64 offset, u64 size, u8 fillbyte, u32* flags) {
FIL dfile;
bool allow_expand = (flags && (*flags & ALLOW_EXPAND));
if (!CheckWritePermissions(dest)) return false;
// open destination
if (fvx_open(&dfile, dest, FA_WRITE | ((allow_expand) ? FA_OPEN_ALWAYS : FA_OPEN_EXISTING)) != FR_OK)
return false;
fvx_lseek(&dfile, offset);
if (!size && (offset < fvx_size(&dfile)))
size = fvx_size(&dfile) - offset;
// check file limits
if (!allow_expand && (offset + size > fvx_size(&dfile))) {
ShowPrompt(false, "%s", STR_OPERATION_WOULD_WRITE_BEYOND_EOF);
ShowPrompt(false, "Operation would write beyond end of file");
fvx_close(&dfile);
return false;
}
u32 bufsiz = min(STD_BUFFER_SIZE, size);
u8* buffer = (u8*) malloc(bufsiz);
if (!buffer) return false;
memset(buffer, fillbyte, bufsiz);
bool ret = true;
ShowProgress(0, 0, dest);
for (u64 pos = 0; (pos < size) && ret; pos += bufsiz) {
@ -346,26 +339,26 @@ bool FileSetByte(const char* dest, u64 offset, u64 size, u8 fillbyte, u32* flags
ret = false;
if (ret && !ShowProgress(pos + bytes_written, size, dest)) {
if (flags && (*flags & NO_CANCEL)) {
ShowPrompt(false, "%s", STR_CANCEL_IS_NOT_ALLOWED_HERE);
} else ret = !ShowPrompt(true, "%s", STR_B_DETECTED_CANCEL);
ShowPrompt(false, "Cancel is not allowed here");
} else ret = !ShowPrompt(true, "B button detected. Cancel?");
ShowProgress(0, 0, dest);
ShowProgress(pos + bytes_written, size, dest);
}
}
ShowProgress(1, 1, dest);
free(buffer);
fvx_close(&dfile);
return ret;
}
bool FileCreateDummy(const char* cpath, const char* filename, u64 size) {
char npath[256]; // 256 is the maximum length of a full path
if (!CheckWritePermissions(cpath)) return false;
if (filename) snprintf(npath, sizeof(npath), "%s/%s", cpath, filename);
else snprintf(npath, sizeof(npath), "%s", cpath);
if (filename) snprintf(npath, 255, "%s/%s", cpath, filename);
else snprintf(npath, 255, "%s", cpath);
// create dummy file (fail if already existing)
// then, expand the file size via cluster preallocation
FIL dfile;
@ -374,14 +367,14 @@ bool FileCreateDummy(const char* cpath, const char* filename, u64 size) {
f_lseek(&dfile, size > 0xFFFFFFFF ? 0xFFFFFFFF : (FSIZE_t) size);
f_sync(&dfile);
fx_close(&dfile);
return (fa_stat(npath, NULL) == FR_OK);
}
bool DirCreate(const char* cpath, const char* dirname) {
char npath[256]; // 256 is the maximum length of a full path
if (!CheckWritePermissions(cpath)) return false;
snprintf(npath, sizeof(npath), "%s/%s", cpath, dirname);
snprintf(npath, 255, "%s/%s", cpath, dirname);
if (fa_mkdir(npath) != FR_OK) return false;
return (fa_stat(npath, NULL) == FR_OK);
}
@ -426,7 +419,7 @@ bool DirInfoWorker(char* fpath, bool virtual, u64* tsize, u32* tdirs, u32* tfile
}
f_closedir(&pdir);
}
return ret;
}
@ -449,25 +442,24 @@ bool PathMoveCopyRec(char* dest, char* orig, u32* flags, bool move, u8* buffer,
bool silent = (flags && (*flags & SILENT));
bool append = (flags && (*flags & APPEND_ALL));
bool calcsha = (flags && (*flags & CALC_SHA) && !append);
bool sha1 = (flags && (*flags & USE_SHA1));
bool ret = false;
// check destination write permission (special paths only)
if (((*dest == '1') || (strncmp(dest, "0:/Nintendo 3DS", 16) == 0)) &&
(!flags || !(*flags & OVERRIDE_PERM)) &&
(!flags || !(*flags & OVERRIDE_PERM)) &&
!CheckWritePermissions(dest)) return false;
FILINFO fno;
if (fvx_stat(orig, &fno) != FR_OK) return false; // origin does not exist
if (move && (to_virtual || fno.fattrib & AM_VRT)) return false; // trying to move a virtual file
// path string (for output)
char deststr[UTF_BUFFER_BYTESIZE(36)];
char deststr[36 + 1];
TruncateString(deststr, dest, 36, 8);
// the copy process takes place here
if (!ShowProgress(0, 0, orig) && !(flags && (*flags & NO_CANCEL))) {
if (ShowPrompt(true, "%s\n%s", deststr, STR_B_DETECTED_CANCEL)) return false;
if (ShowPrompt(true, "%s\nB button detected. Cancel?", deststr)) return false;
ShowProgress(0, 0, orig);
}
if (move && fvx_stat(dest, NULL) != FR_OK) { // moving if dest not existing
@ -475,24 +467,24 @@ bool PathMoveCopyRec(char* dest, char* orig, u32* flags, bool move, u8* buffer,
} else if (fno.fattrib & AM_DIR) { // processing folders (same for move & copy)
DIR pdir;
char* fname = orig + strnlen(orig, 256);
if (append) {
if (!silent) ShowPrompt(false, "%s\n%s", deststr, STR_ERROR_CANNOT_APPEND_FOLDER);
if (!silent) ShowPrompt(false, "%s\nError: Cannot append a folder", deststr);
return false;
}
// create the destination folder if it does not already exist
if (fvx_opendir(&pdir, dest) != FR_OK) {
if (fvx_mkdir(dest) != FR_OK) {
if (!silent) ShowPrompt(false, "%s\n%s", deststr, STR_ERROR_OVERWRITING_FILE_WITH_DIR);
if (!silent) ShowPrompt(false, "%s\nError: Overwriting file with dir", deststr);
return false;
}
} else fvx_closedir(&pdir);
if (fvx_opendir(&pdir, orig) != FR_OK)
return false;
*(fname++) = '/';
while (fvx_readdir(&pdir, &fno) == FR_OK) {
if ((strncmp(fno.fname, ".", 2) == 0) || (strncmp(fno.fname, "..", 3) == 0))
continue; // filter out virtual entries
@ -511,13 +503,13 @@ bool PathMoveCopyRec(char* dest, char* orig, u32* flags, bool move, u8* buffer,
if (!res) break;
}
}
fvx_closedir(&pdir);
*(--fname) = '\0';
} else if (move) { // moving if destination exists
if (fvx_stat(dest, &fno) != FR_OK) return false;
if (fno.fattrib & AM_DIR) {
if (!silent) ShowPrompt(false, "%s\n%s", deststr, STR_ERROR_OVERWRITING_DIR_WITH_FILE);
if (!silent) ShowPrompt(false, "%s\nError: Overwriting dir with file", deststr);
return false;
}
if (fvx_unlink(dest) != FR_OK) return false;
@ -527,37 +519,37 @@ bool PathMoveCopyRec(char* dest, char* orig, u32* flags, bool move, u8* buffer,
FIL dfile;
u64 osize;
u64 dsize;
if (fvx_open(&ofile, orig, FA_READ | FA_OPEN_EXISTING) != FR_OK) {
if (!FileUnlock(orig) || (fvx_open(&ofile, orig, FA_READ | FA_OPEN_EXISTING) != FR_OK))
return false;
ShowProgress(0, 0, orig); // reinit progress bar
}
if ((!append || (fvx_open(&dfile, dest, FA_WRITE | FA_OPEN_EXISTING) != FR_OK)) &&
(fvx_open(&dfile, dest, FA_WRITE | FA_CREATE_ALWAYS) != FR_OK)) {
if (!silent) ShowPrompt(false, "%s\n%s", deststr, STR_ERROR_CANNOT_OPEN_DESTINATION_FILE);
if (!silent) ShowPrompt(false, "%s\nError: Cannot open destination file", deststr);
fvx_close(&ofile);
return false;
}
ret = true; // destination file exists by now, so we need to handle deletion
osize = fvx_size(&ofile);
dsize = append ? fvx_size(&dfile) : 0; // always 0 if not appending to file
if ((fvx_lseek(&dfile, (osize + dsize)) != FR_OK) || (fvx_sync(&dfile) != FR_OK) || (fvx_tell(&dfile) != (osize + dsize))) { // check space via cluster preallocation
if (!silent) ShowPrompt(false, "%s\n%s", deststr, STR_ERROR_NOT_ENOUGH_SPACE_AVAILABLE);
if (!silent) ShowPrompt(false, "%s\nError: Not enough space available", deststr);
ret = false;
}
fvx_lseek(&dfile, dsize);
fvx_sync(&dfile);
fvx_lseek(&ofile, 0);
fvx_sync(&ofile);
if (calcsha) sha_init(sha1 ? SHA1_MODE : SHA256_MODE);
if (calcsha) sha_init(SHA256_MODE);
for (u64 pos = 0; (pos < osize) && ret; pos += bufsiz) {
UINT bytes_read = 0;
UINT bytes_written = 0;
UINT bytes_written = 0;
if ((fvx_read(&ofile, buffer, bufsiz, &bytes_read) != FR_OK) ||
(fvx_write(&dfile, buffer, bytes_read, &bytes_written) != FR_OK) ||
(bytes_read != bytes_written))
@ -567,8 +559,8 @@ bool PathMoveCopyRec(char* dest, char* orig, u32* flags, bool move, u8* buffer,
u64 total = osize;
if (ret && !ShowProgress(current, total, orig)) {
if (flags && (*flags & NO_CANCEL)) {
ShowPrompt(false, "%s\n%s", deststr, STR_CANCEL_IS_NOT_ALLOWED_HERE);
} else ret = !ShowPrompt(true, "%s\n%s", deststr, STR_B_DETECTED_CANCEL);
ShowPrompt(false, "%s\nCancel is not allowed here", deststr);
} else ret = !ShowPrompt(true, "%s\nB button detected. Cancel?", deststr);
ShowProgress(0, 0, orig);
ShowProgress(current, total, orig);
}
@ -576,20 +568,20 @@ bool PathMoveCopyRec(char* dest, char* orig, u32* flags, bool move, u8* buffer,
sha_update(buffer, bytes_read);
}
ShowProgress(1, 1, orig);
fvx_close(&ofile);
fvx_close(&dfile);
if (!ret && ((dsize == 0) || (fvx_lseek(&dfile, dsize) != FR_OK) || (f_truncate(&dfile) != FR_OK))) {
fvx_unlink(dest);
} else if (!to_virtual && calcsha) {
u8 hash[0x20];
u8 sha256[0x20];
char* ext_sha = dest + strnlen(dest, 256);
snprintf(ext_sha, 256 - (ext_sha - dest), ".sha%c", sha1 ? '1' : '\0');
sha_get(hash);
FileSetData(dest, hash, sha1 ? 20 : 32, 0, true);
strncpy(ext_sha, ".sha", 256 - (ext_sha - dest));
sha_get(sha256);
FileSetData(dest, sha256, 0x20, 0, true);
}
}
return ret;
}
@ -599,45 +591,45 @@ bool PathMoveCopy(const char* dest, const char* orig, u32* flags, bool move) {
if (!CheckWritePermissions(dest)) return false;
if (move && !CheckDirWritePermissions(orig)) return false;
}
// reset local flags
if (flags) *flags = *flags & ~(SKIP_CUR|OVERWRITE_CUR);
// preparations
int ddrvtype = DriveType(dest);
int odrvtype = DriveType(orig);
char ldest[256]; // 256 is the maximum length of a full path
char lorig[256];
strncpy(ldest, dest, 256);
strncpy(lorig, orig, 256);
char deststr[UTF_BUFFER_BYTESIZE(36)];
strncpy(ldest, dest, 255);
strncpy(lorig, orig, 255);
char deststr[36 + 1];
TruncateString(deststr, ldest, 36, 8);
// moving only for regular FAT drives (= not alias drives)
if (move && !(ddrvtype & odrvtype & DRV_STDFAT)) {
ShowPrompt(false, "%s", STR_ERROR_ONLY_FAT_FILES_CAN_BE_MOVED);
ShowPrompt(false, "Error: Only FAT files can be moved");
return false;
}
// is destination part of origin?
u32 olen = strnlen(lorig, 255);
if ((strncasecmp(ldest, lorig, olen) == 0) && (ldest[olen] == '/')) {
ShowPrompt(false, "%s\n%s", deststr, STR_ERROR_DESTINATION_IS_PART_OF_ORIGIN);
ShowPrompt(false, "%s\nError: Destination is part of origin", deststr);
return false;
}
if (!(ddrvtype & DRV_VIRTUAL)) { // FAT destination handling
// get destination name
char* dname = strrchr(ldest, '/');
if (!dname) return false;
dname++;
// check & fix destination == origin
while (strncasecmp(ldest, lorig, 255) == 0) {
if (!ShowKeyboardOrPrompt(dname, 255 - (dname - ldest), "%s\n%s", deststr, STR_ERROR_DESTINATION_EQUALS_ORIGIN_CHOOSE_ANOTHER_NAME))
if (!ShowKeyboardOrPrompt(dname, 255 - (dname - ldest), "%s\nDestination equals origin\nChoose another name?", deststr))
return false;
}
// check if destination exists
if (flags && !(*flags & (OVERWRITE_CUR|OVERWRITE_ALL|APPEND_ALL)) && (fa_stat(ldest, NULL) == FR_OK)) {
if (*flags & SKIP_ALL) {
@ -645,11 +637,12 @@ bool PathMoveCopy(const char* dest, const char* orig, u32* flags, bool move) {
return true;
}
const char* optionstr[5] =
{STR_CHOOSE_NEW_NAME, STR_OVERWRITE_FILES, STR_SKIP_FILES, STR_OVERWRITE_ALL, STR_SKIP_ALL};
u32 user_select = ShowSelectPrompt((*flags & ASK_ALL) ? 5 : 3, optionstr, STR_DESTINATION_ALREADY_EXISTS, deststr);
{"Choose new name", "Overwrite file(s)", "Skip file(s)", "Overwrite all", "Skip all"};
u32 user_select = ShowSelectPrompt((*flags & ASK_ALL) ? 5 : 3, optionstr,
"Destination already exists:\n%s", deststr);
if (user_select == 1) {
do {
if (!ShowKeyboardOrPrompt(dname, 255 - (dname - ldest), "%s", STR_CHOOSE_NEW_DESTINATION_NAME))
if (!ShowKeyboardOrPrompt(dname, 255 - (dname - ldest), "Choose new destination name"))
return false;
} while (fa_stat(ldest, NULL) == FR_OK);
} else if (user_select == 2) {
@ -666,61 +659,61 @@ bool PathMoveCopy(const char* dest, const char* orig, u32* flags, bool move) {
return false;
}
}
// ensure the destination path exists
if (flags && (*flags & BUILD_PATH)) fvx_rmkpath(ldest);
// setup buffer
u8* buffer = (u8*) malloc(STD_BUFFER_SIZE);
if (!buffer) {
ShowPrompt(false, "%s", STR_OUT_OF_MEMORY);
ShowPrompt(false, "Out of memory.");
return false;
}
// actual move / copy operation
bool same_drv = (strncasecmp(lorig, ldest, 2) == 0);
bool res = PathMoveCopyRec(ldest, lorig, flags, move && same_drv, buffer, STD_BUFFER_SIZE);
if (move && res && (!flags || !(*flags&SKIP_CUR))) PathDelete(lorig);
free(buffer);
return res;
} else { // virtual destination handling
// can't write an SHA file to a virtual destination
if (flags) *flags &= ~CALC_SHA;
bool force_unmount = false;
// handle NAND image unmounts
if ((ddrvtype & (DRV_SYSNAND|DRV_EMUNAND|DRV_IMAGE)) && !(GetVirtualSource(dest) & (VRT_DISADIFF | VRT_BDRI))) {
if (ddrvtype & (DRV_SYSNAND|DRV_EMUNAND|DRV_IMAGE)) {
FILINFO fno;
// virtual NAND files over 4 MB require unmount, totally arbitrary limit (hacky!)
if ((fvx_stat(ldest, &fno) == FR_OK) && (fno.fsize > 4 * 1024 * 1024))
force_unmount = true;
}
// prevent illegal operations
if (force_unmount && (odrvtype & ddrvtype & (DRV_SYSNAND|DRV_EMUNAND|DRV_IMAGE))) {
ShowPrompt(false, "%s", STR_COPY_OPERATION_IS_NOT_ALLOWED);
return false;
ShowPrompt(false, "Copy operation is not allowed");
return false;
}
// check destination == origin
if (strncasecmp(ldest, lorig, 255) == 0) {
ShowPrompt(false, "%s\n%s", deststr, STR_DESTINATION_EQUALS_ORIGIN);
ShowPrompt(false, "%s\nDestination equals origin", deststr);
return false;
}
// setup buffer
u8* buffer = (u8*) malloc(STD_BUFFER_SIZE);
if (!buffer) {
ShowPrompt(false, "%s", STR_OUT_OF_MEMORY);
ShowPrompt(false, "Out of memory.");
return false;
}
// actual virtual copy operation
if (force_unmount) DismountDriveType(DriveType(ldest)&(DRV_SYSNAND|DRV_EMUNAND|DRV_IMAGE));
bool res = PathMoveCopyRec(ldest, lorig, flags, false, buffer, STD_BUFFER_SIZE);
if (force_unmount) InitExtFS();
free(buffer);
return res;
}
@ -731,26 +724,26 @@ bool PathCopy(const char* destdir, const char* orig, u32* flags) {
char dest[256]; // maximum path name length in FAT
char* oname = strrchr(orig, '/');
if (oname == NULL) return false; // not a proper origin path
snprintf(dest, sizeof(dest), "%s/%s", destdir, (++oname));
snprintf(dest, 255, "%s/%s", destdir, (++oname));
// virtual destination special handling
if (GetVirtualSource(destdir) & ~VRT_BDRI) {
if (GetVirtualSource(destdir)) {
u64 osize = FileGetSize(orig);
VirtualFile dvfile;
if (!osize) return false;
if (!GetVirtualFile(&dvfile, dest, FA_WRITE)) {
if (!GetVirtualFile(&dvfile, dest)) {
VirtualDir vdir;
if (!GetVirtualDir(&vdir, destdir)) return false;
while (true) { // search by size should be a last resort solution
if (!ReadVirtualDir(&dvfile, &vdir)) return false;
if (dvfile.size == osize) break; // file found
}
if (!ShowPrompt(true, STR_ENTRY_NOT_FOUND_PATH_INJECT_INTO_PATH_INSTEAD, dest, dvfile.name))
if (!ShowPrompt(true, "Entry not found: %s\nInject into %s instead?", dest, dvfile.name))
return false;
snprintf(dest, sizeof(dest), "%s/%s", destdir, dvfile.name);
snprintf(dest, 255, "%s/%s", destdir, dvfile.name);
} else if (osize < dvfile.size) { // if origin is smaller than destination...
char deststr[UTF_BUFFER_BYTESIZE(36)];
char origstr[UTF_BUFFER_BYTESIZE(36)];
char deststr[36 + 1];
char origstr[36 + 1];
char osizestr[32];
char dsizestr[32];
TruncateString(deststr, dest, 36, 8);
@ -758,12 +751,12 @@ bool PathCopy(const char* destdir, const char* orig, u32* flags) {
FormatBytes(osizestr, osize);
FormatBytes(dsizestr, dvfile.size);
if (dvfile.size > osize) {
if (!ShowPrompt(true, STR_FILE_SMALLER_THAN_SPACE_SIZES_CONTINUE, origstr, osizestr, deststr, dsizestr))
if (!ShowPrompt(true, "File smaller than available space:\n%s (%s)\n%s (%s)\nContinue?", origstr, osizestr, deststr, dsizestr))
return false;
}
}
}
return PathMoveCopy(dest, orig, flags, false);
}
@ -772,8 +765,8 @@ bool PathMove(const char* destdir, const char* orig, u32* flags) {
char dest[256]; // maximum path name length in FAT
char* oname = strrchr(orig, '/');
if (oname == NULL) return false; // not a proper origin path
snprintf(dest, sizeof(dest), "%s/%s", destdir, (++oname));
snprintf(dest, 255, "%s/%s", destdir, (++oname));
return PathMoveCopy(dest, orig, flags, true);
}
@ -785,17 +778,15 @@ bool PathDelete(const char* path) {
bool PathRename(const char* path, const char* newname) {
char npath[256]; // 256 is the maximum length of a full path
char* oldname = strrchr(path, '/');
if (!CheckDirWritePermissions(path)) return false;
if (!oldname) return false;
oldname++;
strncpy(npath, path, oldname - path);
strncpy(npath + (oldname - path), newname, 255 - (oldname - path));
if (fvx_rename(path, npath) != FR_OK) return false;
if ((strncasecmp(path, npath, 256) != 0) &&
((fvx_stat(path, NULL) == FR_OK) || (fvx_stat(npath, NULL) != FR_OK)))
return false; // safety check
if ((fvx_stat(path, NULL) == FR_OK) || (fvx_stat(npath, NULL) != FR_OK)) return false; // safety check
return true;
}
@ -809,20 +800,20 @@ bool FileSelectorWorker(char* result, const char* text, const char* path, const
char path_local[256];
strncpy(path_local, path, 256);
path_local[255] = '\0';
bool no_dirs = flags & NO_DIRS;
bool no_files = flags & NO_FILES;
bool hide_ext = flags & HIDE_EXT;
bool select_dirs = flags & SELECT_DIRS;
// main loop
while (true) {
u32 n_found = 0;
u32 pos = 0;
GetDirContents(contents, path_local);
while (pos < contents->n_entries) {
char opt_names[_MAX_FS_OPT+1][UTF_BUFFER_BYTESIZE(32)];
char opt_names[_MAX_FS_OPT+1][32+1];
DirEntry* res_entry[MAX_DIR_ENTRIES+1] = { NULL };
u32 n_opt = 0;
for (; pos < contents->n_entries; pos++) {
@ -832,13 +823,13 @@ bool FileSelectorWorker(char* result, const char* text, const char* path, const
(entry->type == T_DOTDOT) || (strncmp(entry->name, "._", 2) == 0))
continue;
if (!new_style && n_opt == _MAX_FS_OPT) {
snprintf(opt_names[n_opt++], 32, "%s", STR_BRACKET_MORE);
snprintf(opt_names[n_opt++], 32, "[more...]");
break;
}
if (!new_style) {
char temp_str[256];
snprintf(temp_str, sizeof(temp_str), "%s", entry->name);
snprintf(temp_str, 256, "%s", entry->name);
if (hide_ext && (entry->type == T_FILE)) {
char* dot = strrchr(temp_str, '.');
if (dot) *dot = '\0';
@ -849,9 +840,9 @@ bool FileSelectorWorker(char* result, const char* text, const char* path, const
n_found++;
}
if ((pos >= contents->n_entries) && (n_opt < n_found) && !new_style)
snprintf(opt_names[n_opt++], 32, "%s", STR_BRACKET_MORE);
snprintf(opt_names[n_opt++], 32, "[more...]");
if (!n_opt) break;
const char* optionstr[_MAX_FS_OPT+1] = { NULL };
for (u32 i = 0; i <= _MAX_FS_OPT; i++) optionstr[i] = opt_names[i];
u32 user_select = new_style ? ShowFileScrollPrompt(n_opt, (const DirEntry**)res_entry, hide_ext, "%s", text)
@ -872,10 +863,10 @@ bool FileSelectorWorker(char* result, const char* text, const char* path, const
}
}
if (!n_found) { // not a single matching entry found
char pathstr[UTF_BUFFER_BYTESIZE(32)];
char pathstr[32+1];
TruncateString(pathstr, path_local, 32, 8);
ShowPrompt(false, "%s\n%s", pathstr, STR_NO_USABLE_ENTRIES_FOUND);
return false;
ShowPrompt(false, "%s\nNo usable entries found.", pathstr);
return false;
}
}
}
@ -883,8 +874,7 @@ bool FileSelectorWorker(char* result, const char* text, const char* path, const
bool FileSelector(char* result, const char* text, const char* path, const char* pattern, u32 flags, bool new_style) {
void* buffer = (void*) malloc(sizeof(DirStruct));
if (!buffer) return false;
// for this to work, result needs to be at least 256 bytes in size
bool ret = FileSelectorWorker(result, text, path, pattern, flags, buffer, new_style);
free(buffer);
return ret;

View File

@ -7,13 +7,12 @@
#define NO_CANCEL (1UL<<1)
#define SILENT (1UL<<2)
#define CALC_SHA (1UL<<3)
#define USE_SHA1 (1UL<<4)
#define BUILD_PATH (1UL<<5)
#define ALLOW_EXPAND (1UL<<6)
#define ASK_ALL (1UL<<7)
#define SKIP_ALL (1UL<<8)
#define OVERWRITE_ALL (1UL<<9)
#define APPEND_ALL (1UL<<10)
#define BUILD_PATH (1UL<<4)
#define ALLOW_EXPAND (1UL<<5)
#define ASK_ALL (1UL<<6)
#define SKIP_ALL (1UL<<7)
#define OVERWRITE_ALL (1UL<<8)
#define APPEND_ALL (1UL<<9)
// file selector flags
#define NO_DIRS (1UL<<0)
@ -44,7 +43,7 @@ size_t FileGetData(const char* path, void* data, size_t size, size_t foffset);
size_t FileGetSize(const char* path);
/** Get SHA-256 of file **/
bool FileGetSha(const char* path, u8* hash, u64 offset, u64 size, bool sha1);
bool FileGetSha256(const char* path, u8* sha256, u64 offset, u64 size);
/** Find data in file **/
u32 FileFindData(const char* path, u8* data, u32 size_data, u32 offset_file);

View File

@ -1,14 +1,11 @@
#include "image.h"
#include "vff.h"
#include "nandcmac.h"
static FIL mount_file;
static u64 mount_state = 0;
static char mount_path[256] = { 0 };
static bool fix_cmac = false;
int ReadImageBytes(void* buffer, u64 offset, u64 count) {
UINT bytes_read;
@ -17,7 +14,7 @@ int ReadImageBytes(void* buffer, u64 offset, u64 count) {
if (!mount_state) return FR_INVALID_OBJECT;
if (fvx_tell(&mount_file) != offset) {
if (fvx_size(&mount_file) < offset) return -1;
fvx_lseek(&mount_file, offset);
fvx_lseek(&mount_file, offset);
}
ret = fvx_read(&mount_file, buffer, count, &bytes_read);
return (ret != 0) ? (int) ret : (bytes_read != count) ? -1 : 0;
@ -31,7 +28,6 @@ int WriteImageBytes(const void* buffer, u64 offset, u64 count) {
if (fvx_tell(&mount_file) != offset)
fvx_lseek(&mount_file, offset);
ret = fvx_write(&mount_file, buffer, count, &bytes_written);
if (ret == 0) fix_cmac = true;
return (ret != 0) ? (int) ret : (bytes_written != count) ? -1 : 0;
}
@ -60,20 +56,18 @@ const char* GetMountPath(void) {
}
u64 MountImage(const char* path) {
u64 type = (path) ? IdentifyFileType(path) : 0;
if (mount_state) {
fvx_close(&mount_file);
if (fix_cmac) FixFileCmac(mount_path, false);
fix_cmac = false;
mount_state = 0;
*mount_path = 0;
}
u64 type = (path) ? IdentifyFileType(path) : 0;
if (!type) return 0;
if ((fvx_open(&mount_file, path, FA_READ | FA_WRITE | FA_OPEN_EXISTING) != FR_OK) &&
(fvx_open(&mount_file, path, FA_READ | FA_OPEN_EXISTING) != FR_OK))
return 0;
fvx_lseek(&mount_file, 0);
fvx_sync(&mount_file);
strncpy(mount_path, path, 256);
strncpy(mount_path, path, 255);
return (mount_state = type);
}

View File

@ -15,10 +15,10 @@ typedef struct {
static FilCryptInfo filcrypt[NUM_FILCRYPTINFO] = { 0 };
static char alias_drv[NUM_ALIAS_DRV]; // 1 char ASCII drive number of the alias drive / 0x00 if unused
static char alias_path[NUM_ALIAS_DRV][128]; // full path to resolve the alias into
char alias_drv[NUM_ALIAS_DRV]; // 1 char ASCII drive number of the alias drive / 0x00 if unused
char alias_path[NUM_ALIAS_DRV][128]; // full path to resolve the alias into
static u8 sd_keyy[NUM_ALIAS_DRV][16] __attribute__((aligned(4))); // key Y belonging to alias drive
u8 sd_keyy[NUM_ALIAS_DRV][16] __attribute__((aligned(4))); // key Y belonging to alias drive
int alias_num (const TCHAR* path) {
int num = -1;
@ -35,14 +35,14 @@ int alias_num (const TCHAR* path) {
void dealias_path (TCHAR* alias, const TCHAR* path) {
int num = alias_num(path);
u32 p_offs = (path[2] == '/' && ((path[3] == '/') || (path[3] == '\0'))) ? 3 : 2;
if (num >= 0) // set alias (alias is assumed to be 256 byte!)
if (num >= 0) // set alias (alias is assumed to be 256 byte)
snprintf(alias, 256, "%s%s", alias_path[num], path + p_offs);
else snprintf(alias, 256, "%s", path);
else strncpy(alias, path, 256);
}
FilCryptInfo* fx_find_cryptinfo(FIL* fptr) {
FilCryptInfo* info = NULL;
for (u32 i = 0; i < NUM_FILCRYPTINFO; i++) {
if (!info && !filcrypt[i].fptr) // use first free
info = &filcrypt[i];
@ -51,7 +51,7 @@ FilCryptInfo* fx_find_cryptinfo(FIL* fptr) {
break;
}
}
return info;
}
@ -59,27 +59,27 @@ FRESULT fx_decrypt_dsiware (FIL* fp, void* buff, FSIZE_t ofs, UINT len) {
const u32 mode = AES_CNT_TITLEKEY_DECRYPT_MODE;
const u32 num_tbl = sizeof(TadContentTable) / sizeof(u32);
const FSIZE_t ofs0 = f_tell(fp);
u8 __attribute__((aligned(16))) iv[AES_BLOCK_SIZE];
u32 tbl[num_tbl];
u8 hdr[TAD_HEADER_LEN];
FRESULT res;
UINT br;
// read and decrypt header
if ((res = f_lseek(fp, TAD_HEADER_OFFSET)) != FR_OK) return res;
if ((res = f_read(fp, hdr, TAD_HEADER_LEN, &br)) != FR_OK) return res;
if (br != TAD_HEADER_LEN) return FR_DENIED;
memcpy(iv, hdr + TAD_HEADER_LEN - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
cbc_decrypt(hdr, hdr, sizeof(TadHeader) / AES_BLOCK_SIZE, mode, iv);
// setup the table
if (BuildTadContentTable(tbl, hdr) != 0) return FR_DENIED;
if (tbl[num_tbl-1] > f_size(fp)) return FR_DENIED; // obviously missing data
// process sections
u32 sct_start = 0;
u32 sct_end = 0;
@ -87,21 +87,21 @@ FRESULT fx_decrypt_dsiware (FIL* fp, void* buff, FSIZE_t ofs, UINT len) {
sct_end = tbl[i];
if (sct_start == sct_end) continue; // nothing in section
if ((ofs + len <= sct_start) || (ofs >= sct_end)) continue; // section not in data
const u32 crypt_end = sct_end - (AES_BLOCK_SIZE * 2);
const u32 data_end = min(crypt_end, ofs + len);
u32 data_pos = max(ofs, sct_start);
if (ofs >= crypt_end) continue; // nothing to do
if ((sct_start < ofs) || (sct_end > ofs + len)) { // incomplete section, ugh
u8 __attribute__((aligned(16))) block[AES_BLOCK_SIZE];
// load iv0
FSIZE_t block0_ofs = data_pos - (data_pos % AES_BLOCK_SIZE);
FSIZE_t iv0_ofs = ((block0_ofs > sct_start) ? block0_ofs : sct_end) - AES_BLOCK_SIZE;
if ((res = f_lseek(fp, iv0_ofs)) != FR_OK) return res;
if ((res = f_read(fp, iv, AES_BLOCK_SIZE, &br)) != FR_OK) return res;
// load and decrypt block0 (if misaligned)
if (data_pos % AES_BLOCK_SIZE) {
if ((res = f_lseek(fp, block0_ofs)) != FR_OK) return res;
@ -110,7 +110,7 @@ FRESULT fx_decrypt_dsiware (FIL* fp, void* buff, FSIZE_t ofs, UINT len) {
data_pos = min(block0_ofs + AES_BLOCK_SIZE, data_end);
memcpy(buff, block + (ofs - block0_ofs), data_pos - ofs);
}
// decrypt blocks in between
u32 num_blocks = (data_end - data_pos) / AES_BLOCK_SIZE;
if (num_blocks) {
@ -118,7 +118,7 @@ FRESULT fx_decrypt_dsiware (FIL* fp, void* buff, FSIZE_t ofs, UINT len) {
cbc_decrypt(blocks, blocks, num_blocks, mode, iv);
data_pos += num_blocks * AES_BLOCK_SIZE;
}
// decrypt last block
if (data_pos < data_end) {
u8* lbuff = (u8*) buff + (data_pos - ofs);
@ -137,7 +137,7 @@ FRESULT fx_decrypt_dsiware (FIL* fp, void* buff, FSIZE_t ofs, UINT len) {
cbc_decrypt(blocks, blocks, num_blocks, mode, iv);
}
}
return f_lseek(fp, ofs0);
}
@ -145,7 +145,7 @@ FRESULT fx_open (FIL* fp, const TCHAR* path, BYTE mode) {
int num = alias_num(path);
FilCryptInfo* info = fx_find_cryptinfo(fp);
if (info) info->fptr = NULL;
if (info && (num >= 0)) {
// DSIWare Export, mark with the magic number
if (strncmp(path + 2, "/" DSIWARE_MAGIC, 1 + 16) == 0) {
@ -172,7 +172,7 @@ FRESULT fx_open (FIL* fp, const TCHAR* path, BYTE mode) {
memcpy(info->keyy, sd_keyy[num], 16);
info->fptr = fp;
}
return fa_open(fp, path, mode);
}
@ -193,12 +193,12 @@ FRESULT fx_write (FIL* fp, const void* buff, UINT btw, UINT* bw) {
FilCryptInfo* info = fx_find_cryptinfo(fp);
FSIZE_t off = f_tell(fp);
FRESULT res = FR_OK;
if (info && info->fptr) {
if (memcmp(info->ctr, DSIWARE_MAGIC, 16) == 0) return FR_DENIED;
void* crypt_buff = (void*) malloc(min(btw, STD_BUFFER_SIZE));
if (!crypt_buff) return FR_DENIED;
setup_aeskeyY(0x34, info->keyy);
use_aeskey(0x34);
*bw = 0;
@ -210,7 +210,7 @@ FRESULT fx_write (FIL* fp, const void* buff, UINT btw, UINT* bw) {
res = f_write(fp, (const void*) crypt_buff, pcount, &bwl);
*bw += bwl;
}
free(crypt_buff);
} else res = f_write(fp, buff, btw, bw);
return res;
@ -255,12 +255,12 @@ FRESULT fa_unlink (const TCHAR* path) {
// special functions for access of virtual NAND SD drives
bool SetupNandSdDrive(const char* path, const char* sd_path, const char* movable, int num) {
char alias[128];
// initial checks
if ((num >= NUM_ALIAS_DRV) || (num < 0)) return false;
alias_drv[num] = 0;
if (!sd_path || !movable || !path) return true;
// grab the key Y from movable.sed
UINT bytes_read = 0;
FIL file;
@ -272,13 +272,13 @@ bool SetupNandSdDrive(const char* path, const char* sd_path, const char* movable
return false;
}
f_close(&file);
// build the alias path (id0)
u32 sha256sum[8];
sha_quick(sha256sum, sd_keyy[num], 0x10, SHA256_MODE);
snprintf(alias, sizeof(alias), "%s/Nintendo 3DS/%08lX%08lX%08lX%08lX",
snprintf(alias, 127, "%s/Nintendo 3DS/%08lX%08lX%08lX%08lX",
sd_path, sha256sum[0], sha256sum[1], sha256sum[2], sha256sum[3]);
// find the alias path (id1)
char* id1 = alias + strnlen(alias, 127);
DIR pdir;
@ -297,7 +297,7 @@ bool SetupNandSdDrive(const char* path, const char* sd_path, const char* movable
}
f_closedir(&pdir);
if (!(*id1)) return false;
// create the alias drive
return SetupAliasDrive(path, alias, num);
}
@ -307,12 +307,12 @@ bool SetupAliasDrive(const char* path, const char* alias, int num) {
if ((num >= NUM_ALIAS_DRV) || (num < 0)) return false;
alias_drv[num] = 0;
if (!alias || !path) return true;
// take over drive path and alias
strncpy(alias_path[num], alias, 128);
if (path[1] != ':') return false;
alias_drv[num] = path[0];
return true;
}

View File

@ -12,16 +12,16 @@ bool CheckSupportFile(const char* fname)
// try VRAM0 first
if (FindVTarFileInfo(fname, NULL))
return true;
// try support file paths
const char* base_paths[] = { SUPPORT_FILE_PATHS };
for (u32 i = 0; i < countof(base_paths); i++) {
char path[256];
snprintf(path, sizeof(path), "%s/%s", base_paths[i], fname);
snprintf(path, 256, "%s/%s", base_paths[i], fname);
if (fvx_stat(path, NULL) == FR_OK)
return true;
}
return false;
}
@ -34,17 +34,17 @@ size_t LoadSupportFile(const char* fname, void* buffer, size_t max_len)
memcpy(buffer, data, len64);
return (size_t) len64;
}
// try support file paths
const char* base_paths[] = { SUPPORT_FILE_PATHS };
for (u32 i = 0; i < countof(base_paths); i++) {
UINT len32;
char path[256];
snprintf(path, sizeof(path), "%s/%s", base_paths[i], fname);
snprintf(path, 256, "%s/%s", base_paths[i], fname);
if (fvx_qread(path, buffer, 0, max_len, &len32) == FR_OK)
return len32;
}
return 0;
}
@ -68,12 +68,12 @@ bool SaveSupportFile(const char* fname, void* buffer, size_t len)
// write support file
if (idx >= 0) {
char path[256];
snprintf(path, sizeof(path), "%s/%s", base_paths[idx], fname);
snprintf(path, 256, "%s/%s", base_paths[idx], fname);
fvx_unlink(path);
if (fvx_qwrite(path, buffer, 0, len, NULL) == FR_OK)
return true;
}
return false;
}
@ -102,7 +102,7 @@ bool GetSupportDir(char* path, const char* dname)
if ((fvx_stat(path, &fno) == FR_OK) && (fno.fattrib & AM_DIR))
return true;
}
return false;
}
@ -115,7 +115,6 @@ bool CheckSupportDir(const char* dname)
bool FileSelectorSupport(char* result, const char* text, const char* dname, const char* pattern)
{
char path[256];
// result needs to be at least 256 bytes long for this to work!
if (!GetSupportDir(path, dname)) return false;
return FileSelector(result, text, path, pattern, HIDE_EXT, false);
}

View File

@ -3,9 +3,7 @@
#include "common.h"
// scripts / payloads dir names
#define LANGUAGES_DIR "languages"
#define SCRIPTS_DIR "scripts"
#define LUASCRIPTS_DIR "luascripts"
#define PAYLOADS_DIR "payloads"
bool CheckSupportFile(const char* fname);
@ -13,6 +11,5 @@ size_t LoadSupportFile(const char* fname, void* buffer, size_t max_len);
bool SaveSupportFile(const char* fname, void* buffer, size_t len);
bool SetAsSupportFile(const char* fname, const char* source);
bool GetSupportDir(char* path, const char* dname);
bool CheckSupportDir(const char* fpath);
bool FileSelectorSupport(char* result, const char* text, const char* dname, const char* pattern);

View File

@ -7,7 +7,7 @@
#else
#define _MAX_FN_LEN (8+3)
#endif
#define _VFIL_ENABLED (!_FS_TINY)
#define _VDIR_ENABLED ((sizeof(DIR) - sizeof(FFOBJID) >= sizeof(VirtualDir)) && (FF_USE_LFN != 0))
@ -18,7 +18,7 @@ FRESULT fvx_open (FIL* fp, const TCHAR* path, BYTE mode) {
#if _VFIL_ENABLED
VirtualFile* vfile = VFIL(fp);
memset(fp, 0, sizeof(FIL));
if (GetVirtualFile(vfile, path, mode)) {
if (GetVirtualFile(vfile, path)) {
fp->obj.fs = NULL;
fp->obj.objsize = vfile->size;
fp->fptr = 0;
@ -81,7 +81,7 @@ FRESULT fvx_sync (FIL* fp) {
FRESULT fvx_stat (const TCHAR* path, FILINFO* fno) {
if (GetVirtualSource(path)) {
VirtualFile vfile;
if (!GetVirtualFile(&vfile, path, FA_READ)) return FR_NO_PATH;
if (!GetVirtualFile(&vfile, path)) return FR_NO_PATH;
if (fno) {
fno->fsize = vfile.size;
fno->fdate = (1<<5)|(1<<0); // 1 for month / day
@ -102,7 +102,7 @@ FRESULT fvx_rename (const TCHAR* path_old, const TCHAR* path_new) {
FRESULT fvx_unlink (const TCHAR* path) {
if (GetVirtualSource(path)) {
VirtualFile vfile;
if (!GetVirtualFile(&vfile, path, FA_READ)) return FR_NO_PATH;
if (!GetVirtualFile(&vfile, path)) return FR_NO_PATH;
if (DeleteVirtualFile(&vfile) != 0) return FR_DENIED;
return FR_OK;
} else return fa_unlink( path );
@ -151,22 +151,22 @@ FRESULT fvx_qread (const TCHAR* path, void* buff, FSIZE_t ofs, UINT btr, UINT* b
FIL fp;
FRESULT res;
UINT brt = 0;
res = fvx_open(&fp, path, FA_READ | FA_OPEN_EXISTING);
if (res != FR_OK) return res;
res = fvx_lseek(&fp, ofs);
if (res != FR_OK) {
fvx_close(&fp);
return res;
}
res = fvx_read(&fp, buff, btr, &brt);
fvx_close(&fp);
if (br) *br = brt;
else if ((res == FR_OK) && (brt != btr)) res = FR_DENIED;
return res;
}
@ -174,63 +174,25 @@ FRESULT fvx_qwrite (const TCHAR* path, const void* buff, FSIZE_t ofs, UINT btw,
FIL fp;
FRESULT res;
UINT bwt = 0;
res = fvx_open(&fp, path, FA_WRITE | FA_OPEN_ALWAYS);
if (res != FR_OK) return res;
res = fvx_lseek(&fp, ofs);
if (res != FR_OK) {
fvx_close(&fp);
return res;
}
res = fvx_write(&fp, buff, btw, &bwt);
fvx_close(&fp);
if (bw) *bw = bwt;
else if ((res == FR_OK) && (bwt != btw)) res = FR_DENIED;
return res;
}
FRESULT fvx_qcreate (const TCHAR* path, UINT btc) {
FIL fp;
FRESULT res;
res = fvx_open(&fp, path, FA_WRITE | FA_CREATE_ALWAYS);
if (res != FR_OK) return res;
res = fvx_lseek(&fp, btc);
fvx_close(&fp);
return res;
}
/* // untested / unused, might come in handy at a later point
FRESULT fvx_qfill (const TCHAR* path, const void* buff, UINT btb) {
FIL fp;
FRESULT res;
UINT bwtt = 0;
UINT fsiz = 0;
res = fvx_open(&fp, path, FA_WRITE | FA_OPEN_EXISTING);
if (res != FR_OK) return res;
fsiz = fvx_size(&fp);
while (bwtt < fsiz) {
UINT btw = ((fsiz - bwtt) >= btb) ? btb : (fsiz - bwtt);
UINT bwt;
res = fvx_write(&fp, buff, btw, &bwt);
if ((res == FR_OK) && (bwt != btw)) res = FR_DENIED;
if (res != FR_OK) break;
bwtt += bwt;
}
fvx_close(&fp);
return res;
}*/
FSIZE_t fvx_qsize (const TCHAR* path) {
FILINFO fno;
return (fvx_stat(path, &fno) == FR_OK) ? fno.fsize : 0;
@ -257,8 +219,7 @@ FRESULT worker_fvx_rmkdir (TCHAR* tpath) {
FRESULT fvx_rmkdir (const TCHAR* path) {
#if !_LFN_UNICODE // this will not work for unicode
TCHAR tpath[_MAX_FN_LEN+1];
if (strlen(path) > _MAX_FN_LEN) return FR_INVALID_NAME;
strcpy(tpath, path);
strncpy(tpath, path, _MAX_FN_LEN);
return worker_fvx_rmkdir( tpath );
#else
return FR_DENIED;
@ -268,8 +229,7 @@ FRESULT fvx_rmkdir (const TCHAR* path) {
FRESULT fvx_rmkpath (const TCHAR* path) {
#if !_LFN_UNICODE // this will not work for unicode
TCHAR tpath[_MAX_FN_LEN+1];
if (strlen(path) > _MAX_FN_LEN) return FR_INVALID_NAME;
strcpy(tpath, path);
strncpy(tpath, path, _MAX_FN_LEN);
TCHAR* slash = strrchr(tpath, '/');
if (!slash) return FR_DENIED;
*slash = '\0';
@ -283,21 +243,21 @@ FRESULT fvx_rmkpath (const TCHAR* path) {
FRESULT worker_fvx_runlink (TCHAR* tpath) {
FILINFO fno;
FRESULT res;
// this code handles directory content deletion
if ((res = fvx_stat(tpath, &fno)) != FR_OK) return res; // tpath does not exist
if (fno.fattrib & AM_DIR) { // process folder contents
DIR pdir;
TCHAR* fname = tpath + strnlen(tpath, 255);
if ((res = fa_opendir(&pdir, tpath)) != FR_OK) return res;
*(fname++) = '/';
while (fvx_readdir(&pdir, &fno) == FR_OK) {
if ((strncmp(fno.fname, ".", 2) == 0) || (strncmp(fno.fname, "..", 3) == 0))
continue; // filter out virtual entries
strcpy(fname, fno.fname);
strncpy(fname, fno.fname, tpath + 255 - fname);
if (fno.fname[0] == 0) {
break;
} else { // return value won't matter
@ -307,7 +267,7 @@ FRESULT worker_fvx_runlink (TCHAR* tpath) {
fvx_closedir(&pdir);
*(--fname) = '\0';
}
return fvx_unlink( tpath );
}
#endif
@ -315,8 +275,7 @@ FRESULT worker_fvx_runlink (TCHAR* tpath) {
FRESULT fvx_runlink (const TCHAR* path) {
#if !_LFN_UNICODE // this will not work for unicode
TCHAR tpath[_MAX_FN_LEN+1];
if (strlen(path) > _MAX_FN_LEN) return FR_INVALID_NAME;
strcpy(tpath, path);
strncpy(tpath, path, _MAX_FN_LEN);
return worker_fvx_runlink( tpath );
#else
return FR_DENIED;
@ -347,7 +306,7 @@ FRESULT fvx_match_name(const TCHAR* path, const TCHAR* pattern) {
if (fvx_match_name(path, pattern + 1) == FR_OK) return FR_OK;
}
}
return FR_NO_FILE;
}
@ -359,42 +318,40 @@ FRESULT fvx_preaddir (DIR* dp, FILINFO* fno, const TCHAR* pattern) {
}
FRESULT fvx_findpath (TCHAR* path, const TCHAR* pattern, BYTE mode) {
if (strlen(pattern) > _MAX_FN_LEN) return FR_INVALID_NAME;
strcpy(path, pattern);
strncpy(path, pattern, _MAX_FN_LEN);
TCHAR* fname = strrchr(path, '/');
if (!fname) return FR_DENIED;
*fname = '\0';
TCHAR* npattern = strrchr(pattern, '/');
if (!npattern) return FR_DENIED;
npattern++;
DIR pdir;
FILINFO fno;
FRESULT res;
if ((res = fvx_opendir(&pdir, path)) != FR_OK) return res;
*(fname++) = '/';
*fname = '\0';
while ((fvx_preaddir(&pdir, &fno, npattern) == FR_OK) && *(fno.fname)) {
int cmp = strncmp(fno.fname, fname, _MAX_FN_LEN);
if (((mode & FN_HIGHEST) && (cmp > 0)) || ((mode & FN_LOWEST) && (cmp < 0)) || !(*fname))
strcpy(fname, fno.fname);
strncpy(fname, fno.fname, _MAX_FN_LEN - (fname - path));
if (!(mode & (FN_HIGHEST|FN_LOWEST))) break;
}
fvx_closedir( &pdir );
return (*fname) ? FR_OK : FR_NO_PATH;
}
FRESULT fvx_findnopath (TCHAR* path, const TCHAR* pattern) {
if (strlen(pattern) > _MAX_FN_LEN) return FR_INVALID_NAME;
strcpy(path, pattern);
strncpy(path, pattern, _MAX_FN_LEN);
TCHAR* fname = strrchr(path, '/');
if (!fname) return FR_DENIED;
fname++;
TCHAR* rep[16];
u32 n_rep = 0;
for (u32 i = 0; fname[i]; i++) {
@ -405,7 +362,7 @@ FRESULT fvx_findnopath (TCHAR* path, const TCHAR* pattern) {
if (n_rep >= 16) return FR_DENIED;
}
if (!n_rep) return (fvx_stat(path, NULL) == FR_OK) ? FR_NO_PATH : FR_OK;
while (fvx_stat(path, NULL) == FR_OK) {
for (int i = n_rep - 1; (i >= 0); i--) {
if (*(rep[i]) == '9') {
@ -417,10 +374,6 @@ FRESULT fvx_findnopath (TCHAR* path, const TCHAR* pattern) {
}
}
}
return FR_OK;
}
bool fvx_opened(const FIL* fp) {
return (fp->obj.fs != NULL);
}

View File

@ -8,7 +8,6 @@
#define fvx_tell(fp) ((fp)->fptr)
#define fvx_size(fp) ((fp)->obj.objsize)
#define fvx_eof(fp) (fvx_tell(fp) == fvx_size(fp))
#define FN_ANY 0x00
#define FN_HIGHEST 0x01
@ -30,10 +29,9 @@ FRESULT fvx_opendir (DIR* dp, const TCHAR* path);
FRESULT fvx_closedir (DIR* dp);
FRESULT fvx_readdir (DIR* dp, FILINFO* fno);
// additional quick read / write / create functions
// additional quick read / write functions
FRESULT fvx_qread (const TCHAR* path, void* buff, FSIZE_t ofs, UINT btr, UINT* br);
FRESULT fvx_qwrite (const TCHAR* path, const void* buff, FSIZE_t ofs, UINT btw, UINT* bw);
FRESULT fvx_qcreate (const TCHAR* path, UINT btc);
// additional quick file info functions
FSIZE_t fvx_qsize (const TCHAR* path);
@ -48,6 +46,3 @@ FRESULT fvx_match_name(const TCHAR* path, const TCHAR* pattern);
FRESULT fvx_preaddir (DIR* dp, FILINFO* fno, const TCHAR* pattern);
FRESULT fvx_findpath (TCHAR* path, const TCHAR* pattern, BYTE mode);
FRESULT fvx_findnopath (TCHAR* path, const TCHAR* pattern);
// additional state function
bool fvx_opened(const FIL* fp);

View File

@ -2,81 +2,11 @@
#include "vff.h"
#define FAT_ENTRY_SIZE 2 * sizeof(u32)
#define REPLACE_SIZE_MISMATCH 2
#define getfatflag(uv) (((uv) & 0x80000000UL) != 0)
#define getfatindex(uv) ((uv) & 0x7FFFFFFFUL)
#define buildfatuv(index, flag) ((index) | ((flag) ? 0x80000000UL : 0))
typedef struct {
char magic[4]; // "BDRI"
u32 version; // == 0x30000
u64 info_offset; // == 0x20
u64 image_size; // in blocks; and including the pre-header
u32 image_block_size;
u8 padding1[4];
u8 unknown[4];
u32 data_block_size;
u64 dht_offset;
u32 dht_bucket_count;
u8 padding2[4];
u64 fht_offset;
u32 fht_bucket_count;
u8 padding3[4];
u64 fat_offset;
u32 fat_entry_count; // exculdes 0th entry
u8 padding4[4];
u64 data_offset;
u32 data_block_count; // == fat_entry_count
u8 padding5[4];
u32 det_start_block;
u32 det_block_count;
u32 max_dir_count;
u8 padding6[4];
u32 fet_start_block;
u32 fet_block_count;
u32 max_file_count;
u8 padding7[4];
} __attribute__((packed)) BDRIFsHeader;
typedef struct {
char magic[8]; // varies based on media type and importdb vs titledb
u8 reserved[0x78];
BDRIFsHeader fs_header;
} __attribute__((packed)) TitleDBPreHeader;
typedef struct {
char magic[4]; // "TICK"
u32 unknown1; // usually (assuming always) == 1
u32 unknown2;
u32 unknown3;
BDRIFsHeader fs_header;
} __attribute__((packed)) TickDBPreHeader;
typedef struct {
u32 parent_index;
u8 title_id[8];
u32 next_sibling_index;
u8 padding1[4];
u32 start_block_index;
u64 size; // in bytes
u8 padding2[8];
u32 hash_bucket_next_index;
} __attribute__((packed)) TdbFileEntry;
typedef struct {
u32 total_entry_count;
u32 max_entry_count; // == max_file_count + 1
u8 padding[32];
u32 next_dummy_index;
} __attribute__((packed)) DummyFileEntry;
typedef struct {
u32 unknown; // usually (assuming always) == 1
u32 ticket_size; // == 0x350 == sizeof(Ticket)
Ticket ticket;
} __attribute__((packed, aligned(4))) TicketEntry;
static FIL* bdrifp;
static FRESULT BDRIRead(UINT ofs, UINT btr, void* buf) {
@ -106,8 +36,8 @@ static FRESULT BDRIWrite(UINT ofs, UINT btw, const void* buf) {
bool CheckDBMagic(const u8* pre_header, bool tickdb) {
const TitleDBPreHeader* title = (TitleDBPreHeader*) pre_header;
const TickDBPreHeader* tick = (TickDBPreHeader*) pre_header;
return (tickdb ? ((strncmp(tick->magic, "TICK", 4) == 0) && (tick->unknown1 == 1)) :
return (tickdb ? ((strncmp(tick->magic, "TICK", 4) == 0) && (tick->unknown1 == 1)) :
((strcmp(title->magic, "NANDIDB") == 0) || (strcmp(title->magic, "NANDTDB") == 0) ||
(strcmp(title->magic, "TEMPIDB") == 0) || (strcmp(title->magic, "TEMPTDB") == 0))) &&
(strcmp((tickdb ? tick->fs_header : title->fs_header).magic, "BDRI") == 0) &&
@ -127,163 +57,140 @@ static u32 GetHashBucket(const u8* tid, u32 parent_dir_index, u32 bucket_count)
return hash % bucket_count;
}
static u32 GetBDRIEntrySize(const BDRIFsHeader* fs_header, const u32 fs_header_offset, const u8* title_id, u32* size) {
if ((fs_header->info_offset != 0x20) || (fs_header->fat_entry_count != fs_header->data_block_count)) // Could be more thorough
return 1;
const u32 data_offset = fs_header_offset + fs_header->data_offset;
const u32 fet_offset = data_offset + fs_header->fet_start_block * fs_header->data_block_size;
const u32 fht_offset = fs_header_offset + fs_header->fht_offset;
u32 index = 0;
TdbFileEntry file_entry;
u64 tid_be = getbe64(title_id);
u8* title_id_be = (u8*) &tid_be;
const u32 hash_bucket = GetHashBucket(title_id_be, 1, fs_header->fht_bucket_count);
if (BDRIRead(fht_offset + hash_bucket * sizeof(u32), sizeof(u32), &(file_entry.hash_bucket_next_index)) != FR_OK)
return 1;
// Find the file entry for the tid specified, fail if it doesn't exist
do {
if (file_entry.hash_bucket_next_index == 0)
return 1;
index = file_entry.hash_bucket_next_index;
if (BDRIRead(fet_offset + index * sizeof(TdbFileEntry), sizeof(TdbFileEntry), &file_entry) != FR_OK)
return 1;
} while (memcmp(title_id_be, file_entry.title_id, 8) != 0);
*size = file_entry.size;
return 0;
}
static u32 ReadBDRIEntry(const BDRIFsHeader* fs_header, const u32 fs_header_offset, const u8* title_id, u8* entry, const u32 expected_size) {
if ((fs_header->info_offset != 0x20) || (fs_header->fat_entry_count != fs_header->data_block_count)) // Could be more thorough
return 1;
const u32 data_offset = fs_header_offset + fs_header->data_offset;
const u32 det_offset = data_offset + fs_header->det_start_block * fs_header->data_block_size;
const u32 fet_offset = data_offset + fs_header->fet_start_block * fs_header->data_block_size;
const u32 fht_offset = fs_header_offset + fs_header->fht_offset;
const u32 fat_offset = fs_header_offset + fs_header->fat_offset;
u32 index = 0;
TdbFileEntry file_entry;
u64 tid_be = getbe64(title_id);
u8* title_id_be = (u8*) &tid_be;
const u32 hash_bucket = GetHashBucket(title_id_be, 1, fs_header->fht_bucket_count);
if (BDRIRead(fht_offset + hash_bucket * sizeof(u32), sizeof(u32), &(file_entry.hash_bucket_next_index)) != FR_OK)
// Read the index of the first file entry from the directory entry table
if (BDRIRead(det_offset + 0x2C, sizeof(u32), &(file_entry.next_sibling_index)) != FR_OK)
return 1;
// Find the file entry for the tid specified, fail if it doesn't exist
do {
if (file_entry.hash_bucket_next_index == 0)
if (file_entry.next_sibling_index == 0)
return 1;
index = file_entry.hash_bucket_next_index;
index = file_entry.next_sibling_index;
if (BDRIRead(fet_offset + index * sizeof(TdbFileEntry), sizeof(TdbFileEntry), &file_entry) != FR_OK)
return 1;
} while (memcmp(title_id_be, file_entry.title_id, 8) != 0);
if (expected_size && (file_entry.size != expected_size))
return 1;
const u32 hash_bucket = GetHashBucket(file_entry.title_id, file_entry.parent_index, fs_header->fht_bucket_count);
u32 index_hash = 0;
if (BDRIRead(fht_offset + hash_bucket * sizeof(u32), sizeof(u32), &index_hash) != FR_OK)
return 1;
if (index != index_hash)
return 1;
index = file_entry.start_block_index + 1; // FAT entry index
u32 bytes_read = 0;
u32 fat_entry[2];
while (bytes_read < file_entry.size) { // Read the full entry, walking the FAT node chain
u32 read_start = index - 1; // Data region block index
u32 read_count = 0;
if (BDRIRead(fat_offset + index * FAT_ENTRY_SIZE, FAT_ENTRY_SIZE, fat_entry) != FR_OK)
return 1;
if ((bytes_read == 0) && !getfatflag(fat_entry[0]))
return 1;
u32 next_index = getfatindex(fat_entry[1]);
if (getfatflag(fat_entry[1])) { // Multi-entry node
if (BDRIRead(fat_offset + (index + 1) * FAT_ENTRY_SIZE, FAT_ENTRY_SIZE, fat_entry) != FR_OK)
return 1;
if (!getfatflag(fat_entry[0]) || getfatflag(fat_entry[1]) || (getfatindex(fat_entry[0]) != index) || (getfatindex(fat_entry[0]) >= getfatindex(fat_entry[1])))
return 1;
read_count = getfatindex(fat_entry[1]) + 1 - index;
} else { // Single-entry node
read_count = 1;
}
index = next_index;
u32 btr = min(file_entry.size - bytes_read, read_count * fs_header->data_block_size);
if (entry && (BDRIRead(data_offset + read_start * fs_header->data_block_size, btr, entry + bytes_read) != FR_OK))
return 1;
bytes_read += btr;
}
return 0;
}
static u32 RemoveBDRIEntry(const BDRIFsHeader* fs_header, const u32 fs_header_offset, const u8* title_id) {
if ((fs_header->info_offset != 0x20) || (fs_header->fat_entry_count != fs_header->data_block_count)) // Could be more thorough
return 1;
const u32 data_offset = fs_header_offset + fs_header->data_offset;
const u32 det_offset = data_offset + fs_header->det_start_block * fs_header->data_block_size;
const u32 fet_offset = data_offset + fs_header->fet_start_block * fs_header->data_block_size;
const u32 fht_offset = fs_header_offset + fs_header->fht_offset;
const u32 fat_offset = fs_header_offset + fs_header->fat_offset;
u32 index = 0, previous_index = 0;
TdbFileEntry file_entry;
u64 tid_be = getbe64(title_id);
u8* title_id_be = (u8*) &tid_be;
// Read the index of the first file entry from the directory entry table
if (BDRIRead(det_offset + 0x2C, sizeof(u32), &(file_entry.next_sibling_index)) != FR_OK)
return 1;
// Find the file entry for the tid specified, fail if it doesn't exist
do {
previous_index = index;
index = file_entry.next_sibling_index;
if (index == 0)
return 1;
if (BDRIRead(fet_offset + index * sizeof(TdbFileEntry), sizeof(TdbFileEntry), &file_entry) != FR_OK)
return 1;
} while (memcmp(title_id_be, file_entry.title_id, 8) != 0);
DummyFileEntry dummy_entry;
// Read the 0th entry in the FET, which is always a dummy entry
if (BDRIRead(fet_offset, sizeof(DummyFileEntry), &dummy_entry) != FR_OK)
return 1;
if (dummy_entry.max_entry_count != fs_header->max_file_count + 1)
return 1;
if ((BDRIWrite(fet_offset + index * sizeof(TdbFileEntry), sizeof(TdbFileEntry), &dummy_entry) != FR_OK) ||
(BDRIWrite(fet_offset + 0x28, sizeof(u32), &index) != FR_OK) ||
(BDRIWrite((previous_index == 0) ? det_offset + 0x2C : fet_offset + previous_index * sizeof(TdbFileEntry) + 0xC, sizeof(u32), &(file_entry.next_sibling_index)) != FR_OK))
return 1;
const u32 hash_bucket = GetHashBucket(file_entry.title_id, file_entry.parent_index, fs_header->fht_bucket_count);
u32 index_hash = 0;
if (BDRIRead(fht_offset + hash_bucket * sizeof(u32), sizeof(u32), &index_hash) != FR_OK)
return 1;
if (index_hash == index) {
if (BDRIWrite(fht_offset + hash_bucket * sizeof(u32), sizeof(u32), &(file_entry.hash_bucket_next_index)) != FR_OK)
return 1;
@ -291,97 +198,96 @@ static u32 RemoveBDRIEntry(const BDRIFsHeader* fs_header, const u32 fs_header_of
do {
if (index_hash == 0) // This shouldn't happen if the entry was properly added
break;
if (BDRIRead(fet_offset + index_hash * sizeof(TdbFileEntry) + 0x28, sizeof(u32), &index_hash) != FR_OK)
return 1;
} while (index_hash != index);
if ((index_hash != 0) && BDRIWrite(fet_offset + index_hash * sizeof(TdbFileEntry) + 0x28, sizeof(u32), &(file_entry.hash_bucket_next_index)) != FR_OK)
return 1;
}
u32 fat_entry[2];
if (BDRIRead(fat_offset, FAT_ENTRY_SIZE, fat_entry) != FR_OK)
return 1;
if (getfatflag(fat_entry[1]) || (fat_entry[0] != 0))
return 1;
u32 next_free_index = getfatindex(fat_entry[1]), fat_index = file_entry.start_block_index + 1;
if (BDRIWrite(fat_offset + sizeof(u32), sizeof(u32), &fat_index) != FR_OK)
return 1;
fat_entry[1] = fat_index;
do {
fat_index = getfatindex(fat_entry[1]);
if (BDRIRead(fat_offset + FAT_ENTRY_SIZE * fat_index, FAT_ENTRY_SIZE, fat_entry) != FR_OK)
return 1;
} while (getfatindex(fat_entry[1]) != 0);
fat_entry[1] |= next_free_index;
if ((BDRIWrite(fat_offset + fat_index * FAT_ENTRY_SIZE, FAT_ENTRY_SIZE, fat_entry) != FR_OK) ||
(BDRIRead(fat_offset + next_free_index * FAT_ENTRY_SIZE, FAT_ENTRY_SIZE, fat_entry) != FR_OK))
return 1;
fat_entry[0] = buildfatuv(fat_index, false);
if (BDRIWrite(fat_offset + next_free_index * FAT_ENTRY_SIZE, FAT_ENTRY_SIZE, fat_entry) != FR_OK)
return 1;
return 0;
}
static u32 AddBDRIEntry(const BDRIFsHeader* fs_header, const u32 fs_header_offset, const u8* title_id, const u8* entry, const u32 size, bool replace) {
if ((fs_header->info_offset != 0x20) || (fs_header->fat_entry_count != fs_header->data_block_count)) // Could be more thorough
return 1;
if (!entry || !size)
return 1;
const u32 data_offset = fs_header_offset + fs_header->data_offset;
const u32 det_offset = data_offset + fs_header->det_start_block * fs_header->data_block_size;
const u32 fet_offset = data_offset + fs_header->fet_start_block * fs_header->data_block_size;
const u32 fht_offset = fs_header_offset + fs_header->fht_offset;
const u32 fat_offset = fs_header_offset + fs_header->fat_offset;
const u32 size_blocks = (size / fs_header->data_block_size) + (((size % fs_header->data_block_size) == 0) ? 0 : 1);
u32 index = 0, max_index = 0;
TdbFileEntry file_entry;
u64 tid_be = getbe64(title_id);
u8* title_id_be = (u8*) &tid_be;
bool do_replace = false;
// Read the index of the first file entry from the directory entry table
if (BDRIRead(det_offset + 0x2C, sizeof(u32), &(file_entry.next_sibling_index)) != FR_OK)
if (BDRIRead(det_offset + 0x2C, sizeof(u32), &(file_entry.next_sibling_index)) != FR_OK)
return 1;
// Try to find the file entry for the tid specified
while (file_entry.next_sibling_index != 0) {
index = file_entry.next_sibling_index;
max_index = max(index, max_index);
max_index = max(index, max_index);
if (BDRIRead(fet_offset + index * sizeof(TdbFileEntry), sizeof(TdbFileEntry), &file_entry) != FR_OK)
return 1;
// If an entry for the tid already existed that is already the specified size and replace was specified, just replace the existing entry
if (memcmp(title_id_be, file_entry.title_id, 8) == 0) {
if (!replace) return 1;
else if (file_entry.size != size) return REPLACE_SIZE_MISMATCH;
if (!replace || (file_entry.size != size)) return 1;
else {
do_replace = true;
break;
}
}
}
u32 fat_entry[2];
u32 fat_index = 0;
if (!do_replace) {
if (BDRIRead(fat_offset, FAT_ENTRY_SIZE, fat_entry) != FR_OK)
return 1;
@ -478,48 +384,48 @@ static u32 AddBDRIEntry(const BDRIFsHeader* fs_header, const u32 fs_header_offse
if (BDRIWrite(fat_offset + previous_free_index * FAT_ENTRY_SIZE, FAT_ENTRY_SIZE, fat_entry) != FR_OK)
return 1;
} else fat_index = file_entry.start_block_index + 1;
u32 bytes_written = 0, fat_index_write = fat_index;
while (bytes_written < size) { // Write the full entry, walking the FAT node chain
// Can't assume contiguity here, because we might be replacing an existing entry
while (bytes_written < file_entry.size) { // Write the full entry, walking the FAT node chain
// Can't assume contiguity here, because we might be replacing an existing entry
u32 write_start = fat_index_write - 1; // Data region block index
u32 write_count = 0;
if (BDRIRead(fat_offset + fat_index_write * FAT_ENTRY_SIZE, FAT_ENTRY_SIZE, fat_entry) != FR_OK)
return 1;
if ((bytes_written == 0) && !getfatflag(fat_entry[0]))
return 1;
u32 next_index = getfatindex(fat_entry[1]);
if (getfatflag(fat_entry[1])) { // Multi-entry node
if (BDRIRead(fat_offset + (fat_index_write + 1) * FAT_ENTRY_SIZE, FAT_ENTRY_SIZE, fat_entry) != FR_OK)
return 1;
if (!getfatflag(fat_entry[0]) || getfatflag(fat_entry[1]) || (getfatindex(fat_entry[0]) != fat_index_write) || (getfatindex(fat_entry[0]) >= getfatindex(fat_entry[1])))
return 1;
write_count = getfatindex(fat_entry[1]) + 1 - fat_index_write;
} else { // Single-entry node
write_count = 1;
}
fat_index_write = next_index;
u32 btw = min(size - bytes_written, write_count * fs_header->data_block_size);
u32 btw = min(file_entry.size - bytes_written, write_count * fs_header->data_block_size);
if (BDRIWrite(data_offset + write_start * fs_header->data_block_size, btw, entry + bytes_written) != FR_OK)
return 1;
bytes_written += btw;
}
if (!do_replace) {
DummyFileEntry dummy_entry;
// Read the 0th entry in the FET, which is always a dummy entry
if (BDRIRead(fet_offset, sizeof(DummyFileEntry), &dummy_entry) != FR_OK)
if (BDRIRead(fet_offset, sizeof(DummyFileEntry), &dummy_entry) != FR_OK)
return 1;
if (dummy_entry.max_entry_count != fs_header->max_file_count + 1)
@ -561,83 +467,80 @@ static u32 AddBDRIEntry(const BDRIFsHeader* fs_header, const u32 fs_header_offse
if (BDRIWrite(fet_offset + index * sizeof(TdbFileEntry), sizeof(TdbFileEntry), &file_entry) != FR_OK)
return 1;
}
return 0;
}
static u32 GetNumBDRIEntries(const BDRIFsHeader* fs_header, const u32 fs_header_offset) {
if ((fs_header->info_offset != 0x20) || (fs_header->fat_entry_count != fs_header->data_block_count)) // Could be more thorough
return 0;
return 0;
const u32 data_offset = fs_header_offset + fs_header->data_offset;
const u32 det_offset = data_offset + fs_header->det_start_block * fs_header->data_block_size;
const u32 fet_offset = data_offset + fs_header->fet_start_block * fs_header->data_block_size;
u32 num_entries = 0;
TdbFileEntry file_entry;
// Read the index of the first file entry from the directory entry table
if (BDRIRead(det_offset + 0x2C, sizeof(u32), &(file_entry.next_sibling_index)) != FR_OK)
return 0;
while (file_entry.next_sibling_index != 0) {
num_entries++;
if (BDRIRead(fet_offset + file_entry.next_sibling_index * sizeof(TdbFileEntry), sizeof(TdbFileEntry), &file_entry) != FR_OK)
return 0;
}
return num_entries;
}
static u32 ListBDRIEntryTitleIDs(const BDRIFsHeader* fs_header, const u32 fs_header_offset, u8* title_ids, u32 max_title_ids) {
if ((fs_header->info_offset != 0x20) || (fs_header->fat_entry_count != fs_header->data_block_count))
return 0;
const u32 data_offset = fs_header_offset + fs_header->data_offset;
const u32 det_offset = data_offset + fs_header->det_start_block * fs_header->data_block_size;
const u32 fet_offset = data_offset + fs_header->fet_start_block * fs_header->data_block_size;
u32 num_entries = 0;
TdbFileEntry file_entry;
for (u32 i = 0; i < max_title_ids; i++)
memset(title_ids, 0, max_title_ids * 8);
// Read the index of the first file entry from the directory entry table
if (BDRIRead(det_offset + 0x2C, sizeof(u32), &(file_entry.next_sibling_index)) != FR_OK)
return 1;
while ((file_entry.next_sibling_index != 0) && (num_entries < max_title_ids)) {
if (BDRIRead(fet_offset + file_entry.next_sibling_index * sizeof(TdbFileEntry), sizeof(TdbFileEntry), &file_entry) != FR_OK)
return 1;
u64 tid_be = getbe64(file_entry.title_id);
memcpy(title_ids + num_entries * 8, (u8*) &tid_be, 8);
memcpy(title_ids + num_entries * 8, file_entry.title_id, 8);
num_entries++;
}
return 0;
}
u32 GetNumTitleInfoEntries(const char* path) {
FIL file;
TitleDBPreHeader pre_header;
if (fvx_open(&file, path, FA_READ | FA_OPEN_EXISTING) != FR_OK)
return 0;
bdrifp = &file;
if ((BDRIRead(0, sizeof(TitleDBPreHeader), &pre_header) != FR_OK) ||
!CheckDBMagic((u8*) &pre_header, false)) {
fvx_close(bdrifp);
bdrifp = NULL;
return 0;
}
u32 num = GetNumBDRIEntries(&(pre_header.fs_header), sizeof(TitleDBPreHeader) - sizeof(BDRIFsHeader));
fvx_close(bdrifp);
bdrifp = NULL;
return num;
@ -646,12 +549,12 @@ u32 GetNumTitleInfoEntries(const char* path) {
u32 GetNumTickets(const char* path) {
FIL file;
TickDBPreHeader pre_header;
if (fvx_open(&file, path, FA_READ | FA_OPEN_EXISTING) != FR_OK)
return 0;
bdrifp = &file;
if ((BDRIRead(0, sizeof(TickDBPreHeader), &pre_header) != FR_OK) ||
!CheckDBMagic((u8*) &pre_header, true)) {
fvx_close(bdrifp);
@ -660,7 +563,7 @@ u32 GetNumTickets(const char* path) {
}
u32 num = GetNumBDRIEntries(&(pre_header.fs_header), sizeof(TickDBPreHeader) - sizeof(BDRIFsHeader));
fvx_close(bdrifp);
bdrifp = NULL;
return num;
@ -669,12 +572,12 @@ u32 GetNumTickets(const char* path) {
u32 ListTitleInfoEntryTitleIDs(const char* path, u8* title_ids, u32 max_title_ids) {
FIL file;
TitleDBPreHeader pre_header;
if (fvx_open(&file, path, FA_READ | FA_OPEN_EXISTING) != FR_OK)
return 1;
bdrifp = &file;
if ((BDRIRead(0, sizeof(TitleDBPreHeader), &pre_header) != FR_OK) ||
!CheckDBMagic((u8*) &pre_header, false) ||
(ListBDRIEntryTitleIDs(&(pre_header.fs_header), sizeof(TitleDBPreHeader) - sizeof(BDRIFsHeader), title_ids, max_title_ids) != 0)) {
@ -682,7 +585,7 @@ u32 ListTitleInfoEntryTitleIDs(const char* path, u8* title_ids, u32 max_title_id
bdrifp = NULL;
return 1;
}
fvx_close(bdrifp);
bdrifp = NULL;
return 0;
@ -691,12 +594,12 @@ u32 ListTitleInfoEntryTitleIDs(const char* path, u8* title_ids, u32 max_title_id
u32 ListTicketTitleIDs(const char* path, u8* title_ids, u32 max_title_ids) {
FIL file;
TickDBPreHeader pre_header;
if (fvx_open(&file, path, FA_READ | FA_OPEN_EXISTING) != FR_OK)
return 1;
bdrifp = &file;
if ((BDRIRead(0, sizeof(TickDBPreHeader), &pre_header) != FR_OK) ||
!CheckDBMagic((u8*) &pre_header, true) ||
(ListBDRIEntryTitleIDs(&(pre_header.fs_header), sizeof(TickDBPreHeader) - sizeof(BDRIFsHeader), title_ids, max_title_ids) != 0)) {
@ -704,7 +607,7 @@ u32 ListTicketTitleIDs(const char* path, u8* title_ids, u32 max_title_ids) {
bdrifp = NULL;
return 1;
}
fvx_close(bdrifp);
bdrifp = NULL;
return 0;
@ -713,12 +616,12 @@ u32 ListTicketTitleIDs(const char* path, u8* title_ids, u32 max_title_ids) {
u32 ReadTitleInfoEntryFromDB(const char* path, const u8* title_id, TitleInfoEntry* tie) {
FIL file;
TitleDBPreHeader pre_header;
if (fvx_open(&file, path, FA_READ | FA_OPEN_EXISTING) != FR_OK)
return 1;
bdrifp = &file;
if ((BDRIRead(0, sizeof(TitleDBPreHeader), &pre_header) != FR_OK) ||
!CheckDBMagic((u8*) &pre_header, false) ||
(ReadBDRIEntry(&(pre_header.fs_header), sizeof(TitleDBPreHeader) - sizeof(BDRIFsHeader), title_id, (u8*) tie,
@ -727,67 +630,52 @@ u32 ReadTitleInfoEntryFromDB(const char* path, const u8* title_id, TitleInfoEntr
bdrifp = NULL;
return 1;
}
fvx_close(bdrifp);
bdrifp = NULL;
return 0;
}
u32 ReadTicketFromDB(const char* path, const u8* title_id, Ticket** ticket) {
u32 ReadTicketFromDB(const char* path, const u8* title_id, Ticket* ticket)
{
FIL file;
TickDBPreHeader pre_header;
TicketEntry* te = NULL;
u32 entry_size;
*ticket = NULL;
TicketEntry te;
if (fvx_open(&file, path, FA_READ | FA_OPEN_EXISTING) != FR_OK)
return 1;
bdrifp = &file;
if ((BDRIRead(0, sizeof(TickDBPreHeader), &pre_header) != FR_OK) ||
!CheckDBMagic((u8*) &pre_header, true) ||
(GetBDRIEntrySize(&(pre_header.fs_header), sizeof(TickDBPreHeader) - sizeof(BDRIFsHeader), title_id, &entry_size) != 0) ||
entry_size < sizeof(TicketEntry) + 0x14 ||
(te = (TicketEntry*)malloc(entry_size), te == NULL) ||
(ReadBDRIEntry(&(pre_header.fs_header), sizeof(TickDBPreHeader) - sizeof(BDRIFsHeader), title_id, (u8*) te,
entry_size) != 0)) {
free(te); // if allocated
(ReadBDRIEntry(&(pre_header.fs_header), sizeof(TickDBPreHeader) - sizeof(BDRIFsHeader), title_id, (u8*) &te,
sizeof(TicketEntry)) != 0)) {
fvx_close(bdrifp);
bdrifp = NULL;
return 1;
}
fvx_close(bdrifp);
bdrifp = NULL;
if (te->ticket_size != GetTicketSize(&te->ticket)) {
free(te);
if (te.ticket_size != sizeof(Ticket))
return 1;
}
if (ticket) {
u32 size = te->ticket_size;
memmove(te, &te->ticket, size); // recycle this memory, instead of allocating another
Ticket* tik = realloc(te, size);
if(!tik) tik = (Ticket*)te;
*ticket = tik;
return 0;
}
free(te);
if (ticket) *ticket = te.ticket;
return 0;
}
u32 RemoveTitleInfoEntryFromDB(const char* path, const u8* title_id) {
FIL file;
TitleDBPreHeader pre_header;
if (fvx_open(&file, path, FA_READ | FA_WRITE | FA_OPEN_EXISTING) != FR_OK)
return 1;
bdrifp = &file;
if ((BDRIRead(0, sizeof(TitleDBPreHeader), &pre_header) != FR_OK) ||
!CheckDBMagic((u8*) &pre_header, false) ||
(RemoveBDRIEntry(&(pre_header.fs_header), sizeof(TitleDBPreHeader) - sizeof(BDRIFsHeader), title_id) != 0)) {
@ -795,7 +683,7 @@ u32 RemoveTitleInfoEntryFromDB(const char* path, const u8* title_id) {
bdrifp = NULL;
return 1;
}
fvx_close(bdrifp);
bdrifp = NULL;
return 0;
@ -804,12 +692,12 @@ u32 RemoveTitleInfoEntryFromDB(const char* path, const u8* title_id) {
u32 RemoveTicketFromDB(const char* path, const u8* title_id) {
FIL file;
TickDBPreHeader pre_header;
if (fvx_open(&file, path, FA_READ | FA_WRITE | FA_OPEN_EXISTING) != FR_OK)
return 1;
bdrifp = &file;
if ((BDRIRead(0, sizeof(TickDBPreHeader), &pre_header) != FR_OK) ||
!CheckDBMagic((u8*) &pre_header, true) ||
(RemoveBDRIEntry(&(pre_header.fs_header), sizeof(TickDBPreHeader) - sizeof(BDRIFsHeader), title_id) != 0)) {
@ -817,7 +705,7 @@ u32 RemoveTicketFromDB(const char* path, const u8* title_id) {
bdrifp = NULL;
return 1;
}
fvx_close(&file);
bdrifp = NULL;
return 0;
@ -826,13 +714,13 @@ u32 RemoveTicketFromDB(const char* path, const u8* title_id) {
u32 AddTitleInfoEntryToDB(const char* path, const u8* title_id, const TitleInfoEntry* tie, bool replace) {
FIL file;
TitleDBPreHeader pre_header;
if (fvx_open(&file, path, FA_READ | FA_WRITE | FA_OPEN_EXISTING) != FR_OK)
return 1;
bdrifp = &file;
if ((BDRIRead(0, sizeof(TitleDBPreHeader), &pre_header) != FR_OK) ||
if ((BDRIRead(0, sizeof(TitleDBPreHeader), &pre_header) != FR_OK) ||
!CheckDBMagic((u8*) &pre_header, false) ||
(AddBDRIEntry(&(pre_header.fs_header), sizeof(TitleDBPreHeader) - sizeof(BDRIFsHeader), title_id,
(const u8*) tie, sizeof(TitleInfoEntry), replace) != 0)) {
@ -840,7 +728,7 @@ u32 AddTitleInfoEntryToDB(const char* path, const u8* title_id, const TitleInfoE
bdrifp = NULL;
return 1;
}
fvx_close(bdrifp);
bdrifp = NULL;
return 0;
@ -849,40 +737,27 @@ u32 AddTitleInfoEntryToDB(const char* path, const u8* title_id, const TitleInfoE
u32 AddTicketToDB(const char* path, const u8* title_id, const Ticket* ticket, bool replace) {
FIL file;
TickDBPreHeader pre_header;
u32 entry_size = sizeof(TicketEntry) + GetTicketContentIndexSize(ticket);
TicketEntry* te = (TicketEntry*)malloc(entry_size);
if (!te) {
TicketEntry te;
te.unknown = 1;
te.ticket_size = sizeof(Ticket);
te.ticket = *ticket;
if (fvx_open(&file, path, FA_READ | FA_WRITE | FA_OPEN_EXISTING) != FR_OK)
return 1;
}
te->unknown = 1;
te->ticket_size = GetTicketSize(ticket);
memcpy(&te->ticket, ticket, te->ticket_size);
if (fvx_open(&file, path, FA_READ | FA_WRITE | FA_OPEN_EXISTING) != FR_OK) {
free(te);
return 1;
}
bdrifp = &file;
u32 add_bdri_res = 0;
if ((BDRIRead(0, sizeof(TickDBPreHeader), &pre_header) != FR_OK) ||
!CheckDBMagic((u8*) &pre_header, true) ||
((add_bdri_res = AddBDRIEntry(&(pre_header.fs_header), sizeof(TickDBPreHeader) - sizeof(BDRIFsHeader), title_id,
(const u8*) te, entry_size, replace)) == 1) ||
(add_bdri_res == REPLACE_SIZE_MISMATCH && ((RemoveBDRIEntry(&(pre_header.fs_header), sizeof(TickDBPreHeader) - sizeof(BDRIFsHeader), title_id) != 0) ||
(AddBDRIEntry(&(pre_header.fs_header), sizeof(TickDBPreHeader) - sizeof(BDRIFsHeader), title_id,
(const u8*) te, entry_size, replace) != 0)))) {
free(te);
(AddBDRIEntry(&(pre_header.fs_header), sizeof(TickDBPreHeader) - sizeof(BDRIFsHeader), title_id,
(const u8*) &te, sizeof(TicketEntry), replace) != 0)) {
fvx_close(bdrifp);
bdrifp = NULL;
return 1;
}
free(te);
fvx_close(bdrifp);
bdrifp = NULL;
return 0;
}
}

View File

@ -2,17 +2,106 @@
#include "common.h"
#include "ticket.h"
#include "tie.h"
// There's probably a better place to put this
#define SD_TITLEDB_PATH(emu) ((emu) ? "B:/dbs/title.db" : "A:/dbs/title.db")
// https://www.3dbrew.org/wiki/Inner_FAT
// https://www.3dbrew.org/wiki/Title_Database
typedef struct {
char magic[4]; // "BDRI"
u32 version; // == 0x30000
u64 info_offset; // == 0x20
u64 image_size; // in blocks; and including the pre-header
u32 image_block_size;
u8 padding1[4];
u8 unknown[4];
u32 data_block_size;
u64 dht_offset;
u32 dht_bucket_count;
u8 padding2[4];
u64 fht_offset;
u32 fht_bucket_count;
u8 padding3[4];
u64 fat_offset;
u32 fat_entry_count; // exculdes 0th entry
u8 padding4[4];
u64 data_offset;
u32 data_block_count; // == fat_entry_count
u8 padding5[4];
u32 det_start_block;
u32 det_block_count;
u32 max_dir_count;
u8 padding6[4];
u32 fet_start_block;
u32 fet_block_count;
u32 max_file_count;
u8 padding7[4];
} __attribute__((packed)) BDRIFsHeader;
typedef struct {
char magic[8]; // varies based on media type and importdb vs titledb
u8 reserved[0x78];
BDRIFsHeader fs_header;
} __attribute__((packed)) TitleDBPreHeader;
typedef struct {
char magic[4]; // "TICK"
u32 unknown1; // usually (assuming always) == 1
u32 unknown2;
u32 unknown3;
BDRIFsHeader fs_header;
} __attribute__((packed)) TickDBPreHeader;
typedef struct {
u32 parent_index;
u8 title_id[8];
u32 next_sibling_index;
u8 padding1[4];
u32 start_block_index;
u64 size; // in bytes
u8 padding2[8];
u32 hash_bucket_next_index;
} __attribute__((packed)) TdbFileEntry;
typedef struct {
u32 total_entry_count;
u32 max_entry_count; // == max_file_count + 1
u8 padding[32];
u32 next_dummy_index;
} __attribute__((packed)) DummyFileEntry;
typedef struct {
u64 title_size; // in bytes
u32 title_type; // usually == 0x40
u32 title_version;
u8 flags_0[4];
u32 tmd_content_id;
u32 cmd_content_id;
u8 flags_1[4];
u32 extdata_id_low; // 0 if the title doesn't use extdata
u8 reserved1[4];
u8 flags_2[8];
char product_code[16];
u8 reserved2[16];
u8 unknown[4]; // appears to not matter what's here
u8 reserved3[44];
} __attribute__((packed)) TitleInfoEntry;
typedef struct {
u32 unknown; // usually (assuming always) == 1
u32 ticket_size; // == 0x350 == sizeof(Ticket)
Ticket ticket;
} __attribute__((packed, aligned(4))) TicketEntry;
u32 GetNumTitleInfoEntries(const char* path);
u32 GetNumTickets(const char* path);
u32 ListTitleInfoEntryTitleIDs(const char* path, u8* title_ids, u32 max_title_ids);
u32 ListTicketTitleIDs(const char* path, u8* title_ids, u32 max_title_ids);
u32 ReadTitleInfoEntryFromDB(const char* path, const u8* title_id, TitleInfoEntry* tie);
u32 ReadTicketFromDB(const char* path, const u8* title_id, Ticket** ticket);
u32 ReadTicketFromDB(const char* path, const u8* title_id, Ticket* ticket);
u32 RemoveTitleInfoEntryFromDB(const char* path, const u8* title_id);
u32 RemoveTicketFromDB(const char* path, const u8* title_id);
u32 AddTitleInfoEntryToDB(const char* path, const u8* title_id, const TitleInfoEntry* tie, bool replace);
u32 AddTicketToDB(const char* path, const u8* title_id, const Ticket* ticket, bool replace);
u32 AddTicketToDB(const char* path, const u8* title_id, const Ticket* ticket, bool replace);

View File

@ -7,7 +7,7 @@ u32 CheckBossHash(BossHeader* boss, bool encrypted) {
u8 hash_area[0x14] __attribute__((aligned(4))) = { 0 };
u8 boss_sha256[0x20];
u8 l_sha256[0x20];
// calculate hash
memcpy(hash_area, ((u8*) boss) + 0x28, 0x12);
memcpy(boss_sha256, boss->hash_header, 0x20);
@ -16,13 +16,13 @@ u32 CheckBossHash(BossHeader* boss, bool encrypted) {
CryptBoss(boss_sha256, 0x28 + 0x12, 0x20, boss);
}
sha_quick(l_sha256, hash_area, 0x14, SHA256_MODE);
return (memcmp(boss_sha256, l_sha256, 0x20) == 0) ? 0 : 1;
}
u32 ValidateBossHeader(BossHeader* header, u32 fsize) {
u8 boss_magic[] = { BOSS_MAGIC };
// base checks
if ((memcmp(header->magic, boss_magic, sizeof(boss_magic)) != 0) ||
(fsize && (fsize != getbe32(header->filesize))) ||
@ -31,12 +31,12 @@ u32 ValidateBossHeader(BossHeader* header, u32 fsize) {
(getbe16(header->cnthdr_hash_type) != 0x0002) ||
(getbe16(header->cnthdr_rsa_size) != 0x0002))
return 1;
// hash check
if ((CheckBossHash(header, false) != 0) &&
(CheckBossHash(header, true) != 0))
return 1;
return 0;
}
@ -59,14 +59,14 @@ u32 CryptBoss(void* data, u32 offset, u32 size, BossHeader* boss) {
size -= 0x28 - offset;
offset = 0x28;
}
// decrypt BOSS data
u8 ctr[16] = { 0 };
memcpy(ctr, boss->ctr12, 12);
ctr[15] = 0x01;
use_aeskey(0x38);
ctr_decrypt_byte(data, data, size, offset - 0x28, AES_CNT_CTRNAND_MODE, ctr);
return 0;
}
@ -76,7 +76,7 @@ u32 CryptBossSequential(void* data, u32 offset, u32 size) {
// unexpected results otherwise
static BossHeader boss = { 0 };
static BossHeader* bossptr = NULL;
// fetch boss header from data
if ((offset == 0) && (size >= sizeof(BossHeader))) {
bossptr = NULL;
@ -87,9 +87,9 @@ u32 CryptBossSequential(void* data, u32 offset, u32 size) {
return 1;
bossptr = &boss;
}
// safety check, boss pointer
if (!bossptr) return 1;
return CryptBoss(data, offset, size, bossptr);
}

View File

@ -14,7 +14,7 @@
typedef struct {
// actual BOSS header
u8 magic[8]; // "boss" + 0x00010001, see above
u8 filesize[4]; // big endian
u8 filesize[4]; // big endian
u8 release_date[8];
u8 unknown0[2]; // always 0x0001
u8 padding[2];
@ -27,7 +27,7 @@ typedef struct {
u8 hash_header[0x20];
u8 signature_header[0x100];
// payload header, first 0x1C byte used for hash (0x15A)
u8 programId[8];
u8 programId[8];
u8 unknown2[4]; // typically zero
u8 data_type[4];
u8 size_payload[4];

File diff suppressed because it is too large Load Diff

View File

@ -1,816 +1,21 @@
#include "cert.h"
#include "disadiff.h"
#include "rsa.h"
#include "ff.h"
typedef struct {
char magic[4]; // "CERT"
u8 unk[4]; // afaik, always 0
u8 used_size[4]; // size used after this header
u8 garbage[4]; // literally garbage values
} PACKED_STRUCT CertsDbPartitionHeader;
u32 LoadCertFromCertDb(u64 offset, Certificate* cert, u32* mod, u32* exp) {
Certificate cert_local;
FIL db;
UINT bytes_read;
static inline void GetCertDBPath(char* path, bool emunand) {
path[0] = emunand ? '4' : '1';
strcpy(&path[1], ":/dbs/certs.db");
}
#define CERT_RETAIL_CA3_IDENT BIT(0)
#define CERT_RETAIL_XSc_IDENT BIT(1)
#define CERT_RETAIL_CPb_IDENT BIT(2)
#define CERT_DEV_CA4_IDENT BIT(3)
#define CERT_DEV_XS9_IDENT BIT(4)
#define CERT_DEV_CPa_IDENT BIT(5)
#define CERT_NO_STORE_SPACE (0xFF)
static struct {
u32 loaded_certs_flg;
u8 retail_CA3_raw[CERT_RSA4096_SIG_SIZE + CERT_RSA2048_BODY_SIZE];
u8 retail_XSc_raw[CERT_RSA2048_SIG_SIZE + CERT_RSA2048_BODY_SIZE];
u8 retail_CPb_raw[CERT_RSA2048_SIG_SIZE + CERT_RSA2048_BODY_SIZE];
u8 dev_CA4_raw[CERT_RSA4096_SIG_SIZE + CERT_RSA2048_BODY_SIZE];
u8 dev_XS9_raw[CERT_RSA2048_SIG_SIZE + CERT_RSA2048_BODY_SIZE];
u8 dev_CPa_raw[CERT_RSA2048_SIG_SIZE + CERT_RSA2048_BODY_SIZE];
Certificate retail_CA3;
Certificate retail_XSc;
Certificate retail_CPb;
Certificate dev_CA4;
Certificate dev_XS9;
Certificate dev_CPa;
} _CommonCertsStorage = {
0, // none loaded yet, ident defines used to say what's loaded
{0}, {0}, {0}, {0}, {0}, {0}, // no data yet
// cert structs pre-point already to raw certs
{
(CertificateSignature*)&_CommonCertsStorage.retail_CA3_raw[0],
(CertificateBody*)&_CommonCertsStorage.retail_CA3_raw[CERT_RSA4096_SIG_SIZE]
},
{
(CertificateSignature*)&_CommonCertsStorage.retail_XSc_raw[0],
(CertificateBody*)&_CommonCertsStorage.retail_XSc_raw[CERT_RSA2048_SIG_SIZE]
},
{
(CertificateSignature*)&_CommonCertsStorage.retail_CPb_raw[0],
(CertificateBody*)&_CommonCertsStorage.retail_CPb_raw[CERT_RSA2048_SIG_SIZE]
},
{
(CertificateSignature*)&_CommonCertsStorage.dev_CA4_raw[0],
(CertificateBody*)&_CommonCertsStorage.dev_CA4_raw[CERT_RSA4096_SIG_SIZE]
},
{
(CertificateSignature*)&_CommonCertsStorage.dev_XS9_raw[0],
(CertificateBody*)&_CommonCertsStorage.dev_XS9_raw[CERT_RSA2048_SIG_SIZE]
},
{
(CertificateSignature*)&_CommonCertsStorage.dev_CPa_raw[0],
(CertificateBody*)&_CommonCertsStorage.dev_CPa_raw[CERT_RSA2048_SIG_SIZE]
}
};
static inline void _Certificate_CleanupImpl(Certificate* cert);
bool Certificate_IsValid(const Certificate* cert) {
if (!cert || !cert->sig || !cert->data)
return false;
u32 sig_type = getbe32(cert->sig->sig_type);
if (sig_type < 0x10000 || sig_type > 0x10005)
return false;
u32 keytype = getbe32(cert->data->keytype);
if (keytype > 2)
return false;
size_t issuer_len = strnlen(cert->data->issuer, 0x40);
size_t name_len = strnlen(cert->data->name, 0x40);
// if >= 0x40, cert can't fit as issuer for other objects later
// since later objects using the certificate as their issuer will have them use it as certissuer-certname
if (!issuer_len || !name_len || (issuer_len + name_len + 1) >= 0x40)
return false;
return true;
}
bool Certificate_IsRSA(const Certificate* cert) {
if (!Certificate_IsValid(cert)) return false;
if (getbe32(cert->data->keytype) >= 2) return false;
return true;
}
bool Certificate_IsECC(const Certificate* cert) {
if (!Certificate_IsValid(cert)) return false;
if (getbe32(cert->data->keytype) != 2) return false;
return true;
}
u32 Certificate_GetSignatureSize(const Certificate* cert, u32* size) {
if (!size || !Certificate_IsValid(cert)) return 1;
u32 sig_type = getbe32(cert->sig->sig_type);
if (sig_type == 0x10000 || sig_type == 0x10003)
*size = 0x200;
else if (sig_type == 0x10001 || sig_type == 0x10004)
*size = 0x100;
else if (sig_type == 0x10002 || sig_type == 0x10005)
*size = 0x3C;
else
// not much in terms of error checking here
if (f_open(&db, "1:/dbs/certs.db", FA_READ | FA_OPEN_EXISTING) != FR_OK)
return 1;
f_lseek(&db, offset);
if (!cert) cert = &cert_local;
f_read(&db, cert, CERT_SIZE, &bytes_read);
f_close(&db);
if (mod) memcpy(mod, cert->mod, 0x100);
if (exp) *exp = getle32(cert->exp);
return 0;
}
u32 Certificate_GetModulusSize(const Certificate* cert, u32* size) {
if (!size || !Certificate_IsRSA(cert)) return 1;
u32 keytype = getbe32(cert->data->keytype);
if (keytype == 0)
*size = 4096 / 8;
else if (keytype == 1)
*size = 2048 / 8;
else return 1;
return 0;
}
u32 Certificate_GetModulus(const Certificate* cert, void* mod) {
u32 size;
if (!mod || Certificate_GetModulusSize(cert, &size)) return 1;
memcpy(mod, cert->data->pub_key_data, size);
return 0;
}
u32 Certificate_GetExponent(const Certificate* cert, void* exp) {
u32 size;
if (!exp || Certificate_GetModulusSize(cert, &size)) return 1;
memcpy(exp, &cert->data->pub_key_data[size], 4);
return 0;
}
u32 Certificate_GetEccSingleCoordinateSize(const Certificate* cert, u32* size) {
if (!size || !Certificate_IsECC(cert)) return 1;
u32 keytype = getbe32(cert->data->keytype);
if (keytype == 2)
*size = 0x3C / 2;
else return 1;
return 0;
}
u32 Certificate_GetEccXY(const Certificate* cert, void* X, void* Y) {
u32 size;
if (!X || !Y || Certificate_GetEccSingleCoordinateSize(cert, &size)) return 1;
memcpy(X, cert->data->pub_key_data, size);
memcpy(Y, &cert->data->pub_key_data[size], size);
return 0;
}
static inline u32 _Certificate_GetSignatureChunkSizeFromType(u32 sig_type) {
if (sig_type == 0x10000 || sig_type == 0x10003)
return CERT_RSA4096_SIG_SIZE;
else if (sig_type == 0x10001 || sig_type == 0x10004)
return CERT_RSA2048_SIG_SIZE;
else if (sig_type == 0x10002 || sig_type == 0x10005)
return CERT_ECC_SIG_SIZE;
return 0;
}
u32 Certificate_GetSignatureChunkSize(const Certificate* cert, u32* size) {
if (!size || !Certificate_IsValid(cert)) return 1;
u32 _size = _Certificate_GetSignatureChunkSizeFromType(getbe32(cert->sig->sig_type));
if (_size == 0) return 1;
*size = _size;
return 0;
}
static inline u32 _Certificate_GetDataChunkSizeFromType(u32 keytype) {
if (keytype == 0)
return CERT_RSA4096_BODY_SIZE;
else if (keytype == 1)
return CERT_RSA2048_BODY_SIZE;
else if (keytype == 2)
return CERT_ECC_BODY_SIZE;
return 0;
}
u32 Certificate_GetDataChunkSize(const Certificate* cert, u32* size) {
if (!size || !Certificate_IsValid(cert)) return 1;
u32 _size = _Certificate_GetDataChunkSizeFromType(getbe32(cert->data->keytype));
if (_size == 0) return 1;
*size = _size;
return 0;
}
u32 Certificate_GetFullSize(const Certificate* cert, u32* size) {
if (!size || !Certificate_IsValid(cert)) return 1;
u32 sig_size = _Certificate_GetSignatureChunkSizeFromType(getbe32(cert->sig->sig_type));
u32 data_size = _Certificate_GetDataChunkSizeFromType(getbe32(cert->data->keytype));
if (sig_size == 0 || data_size == 0)
return 1;
*size = sig_size + data_size;
return 0;
}
static inline u32 _Certificate_KeytypeSignatureSize(u32 keytype) {
if (keytype == 0)
return 0x200;
else if (keytype == 1)
return 0x100;
else if (keytype == 2)
return 0x3C;
return 0;
}
static inline u32 _Certificate_VerifyRSA4096(const Certificate* cert, const void* sig, const void* data, u32 data_size, bool sha256) {
(void)cert; (void)sig; (void)data; (void)data_size; (void)sha256;
return 2; // not implemented
}
// noipa, to avoid form of inlining, cloning, etc, to avoid the extra stack usage when unneeded
static __attribute__((noipa)) bool _Certificate_SetKey2048Misaligned(const Certificate* cert) {
u32 mod[2048/8];
u32 exp;
memcpy(mod, cert->data->pub_key_data, 2048/8);
exp = getle32(&cert->data->pub_key_data[2048/8]);
return RSA_setKey2048(3, mod, exp);
}
static inline u32 _Certificate_VerifyRSA2048(const Certificate* cert, const void* sig, const void* data, u32 data_size, bool sha256) {
if (!sha256)
return 2; // not implemented
int ret;
if (((u32)&cert->data->pub_key_data[0]) & 0x3)
ret = !_Certificate_SetKey2048Misaligned(cert);
else
ret = !RSA_setKey2048(3, (const u32*)(const void*)&cert->data->pub_key_data[0], getle32(&cert->data->pub_key_data[2048/8]));
if (ret)
return ret;
return !RSA_verify2048(sig, data, data_size);
}
static inline u32 _Certificate_VerifyECC(const Certificate* cert, const void* sig, const void* data, u32 data_size, bool sha256) {
(void)cert; (void)sig; (void)data; (void)data_size; (void)sha256;
return 2; // not implemented
}
u32 Certificate_VerifySignatureBlock(const Certificate* cert, const void* sig, u32 sig_size, const void* data, u32 data_size, bool sha256) {
if (!sig || !sig_size || (!data && data_size) || !Certificate_IsValid(cert))
return 1;
u32 keytype = getbe32(cert->data->keytype);
u32 _sig_size = _Certificate_KeytypeSignatureSize(keytype);
if (sig_size != _sig_size)
return 1;
if (keytype == 0)
return _Certificate_VerifyRSA4096(cert, sig, data, data_size, sha256);
if (keytype == 1)
return _Certificate_VerifyRSA2048(cert, sig, data, data_size, sha256);
if (keytype == 2)
return _Certificate_VerifyECC(cert, sig, data, data_size, sha256);
return 1;
}
static inline void* _Certificate_SafeRealloc(void* ptr, size_t size, size_t oldsize) {
void* new_ptr;
size_t min_size = min(oldsize, size);
if ((u32)ptr >= (u32)&_CommonCertsStorage && (u32)ptr < (u32)&_CommonCertsStorage + sizeof(_CommonCertsStorage)) {
new_ptr = malloc(size);
if (new_ptr) memcpy(new_ptr, ptr, min_size);
} else {
new_ptr = realloc(ptr, size);
}
if (!new_ptr) return NULL;
memset(&((u8*)new_ptr)[min_size], 0, size - min_size);
return new_ptr;
}
// will reallocate memory for certificate signature and body to fit the max possible size.
// will also allocate an empty object if Certificate is NULL initialized.
// if certificate points to static storage, an allocated version will be created.
// if function fails, the Certificate, even if previously NULL initialized, still has to be passed to cleaned up after use.
u32 Certificate_MakeEditSafe(Certificate* cert) {
if (!cert) return 1;
bool isvalid = Certificate_IsValid(cert);
if ((cert->sig || cert->data) && !isvalid) return 1;
Certificate cert_local;
u32 sig_size = isvalid ? _Certificate_GetSignatureChunkSizeFromType(getbe32(cert->sig->sig_type)) : 0;
u32 data_size = isvalid ? _Certificate_GetDataChunkSizeFromType(getbe32(cert->data->keytype)) : 0;
if (isvalid && (sig_size == 0 || data_size == 0)) return 1;
cert_local.sig = _Certificate_SafeRealloc(cert->sig, CERT_RSA4096_SIG_SIZE, sig_size);
if (!cert_local.sig) return 1;
cert->sig = cert_local.sig;
cert_local.data = _Certificate_SafeRealloc(cert->data, CERT_RSA4096_BODY_SIZE, data_size);
if (!cert_local.data) return 1;
cert->data = cert_local.data;
return 0;
}
static u32 _Certificate_AllocCopyOutImpl(const Certificate* cert, Certificate* out_cert) {
u32 sig_size = _Certificate_GetSignatureChunkSizeFromType(getbe32(cert->sig->sig_type));
u32 data_size = _Certificate_GetDataChunkSizeFromType(getbe32(cert->data->keytype));
if (sig_size == 0 || data_size == 0)
return 1;
out_cert->sig = (CertificateSignature*)malloc(sig_size);
out_cert->data = (CertificateBody*)malloc(data_size);
if (!out_cert->sig || !out_cert->data) {
_Certificate_CleanupImpl(out_cert);
return 1;
}
memcpy(out_cert->sig, cert->sig, sig_size);
memcpy(out_cert->data, cert->data, data_size);
return 0;
}
u32 Certificate_AllocCopyOut(const Certificate* cert, Certificate* out_cert) {
if (!out_cert || !Certificate_IsValid(cert)) return 1;
return _Certificate_AllocCopyOutImpl(cert, out_cert);
}
static u32 _Certificate_RawCopyImpl(const Certificate* cert, void* raw) {
u32 sig_size = _Certificate_GetSignatureChunkSizeFromType(getbe32(cert->sig->sig_type));
u32 data_size = _Certificate_GetDataChunkSizeFromType(getbe32(cert->data->keytype));
if (sig_size == 0 || data_size == 0)
return 1;
memcpy(raw, cert->sig, sig_size);
memcpy(&((u8*)raw)[sig_size], cert->data, data_size);
return 0;
}
u32 Certificate_RawCopy(const Certificate* cert, void* raw) {
if (!raw || !Certificate_IsValid(cert)) return 1;
return _Certificate_RawCopyImpl(cert, raw);
}
// ptr free check, to not free if ptr is pointing to static storage!!
static inline void _Certificate_SafeFree(void* ptr) {
if ((u32)ptr >= (u32)&_CommonCertsStorage && (u32)ptr < (u32)&_CommonCertsStorage + sizeof(_CommonCertsStorage))
return;
free(ptr);
}
static inline void _Certificate_CleanupImpl(Certificate* cert) {
_Certificate_SafeFree(cert->sig);
_Certificate_SafeFree(cert->data);
cert->sig = NULL;
cert->data = NULL;
}
u32 Certificate_Cleanup(Certificate* cert) {
if (!cert) return 1;
_Certificate_CleanupImpl(cert);
return 0;
}
static u32 _Issuer_To_StorageIdent(const char* issuer) {
if (strncmp(issuer, "Root-CA0000000", 14) != 0)
return CERT_NO_STORE_SPACE;
if (issuer[14] == '3') { // retail
if (issuer[15] == 0)
return CERT_RETAIL_CA3_IDENT;
if (issuer[15] != '-')
return CERT_NO_STORE_SPACE;
if (!strcmp(&issuer[16], "XS0000000c"))
return CERT_RETAIL_XSc_IDENT;
if (!strcmp(&issuer[16], "CP0000000b"))
return CERT_RETAIL_CPb_IDENT;
}
if (issuer[14] == '4') { // dev
if (issuer[15] == 0)
return CERT_DEV_CA4_IDENT;
if (issuer[15] != '-')
return CERT_NO_STORE_SPACE;
if (!strcmp(&issuer[16], "XS00000009"))
return CERT_DEV_XS9_IDENT;
if (!strcmp(&issuer[16], "CP0000000a"))
return CERT_DEV_CPa_IDENT;
}
return CERT_NO_STORE_SPACE;
}
static bool _LoadFromCertStorage(Certificate* cert, u32 ident) {
if (ident == CERT_NO_STORE_SPACE)
return false;
Certificate* _cert = NULL;
switch (ident) {
case CERT_RETAIL_CA3_IDENT:
if (_CommonCertsStorage.loaded_certs_flg & CERT_RETAIL_CA3_IDENT)
_cert = &_CommonCertsStorage.retail_CA3;
break;
case CERT_RETAIL_XSc_IDENT:
if (_CommonCertsStorage.loaded_certs_flg & CERT_RETAIL_XSc_IDENT)
_cert = &_CommonCertsStorage.retail_XSc;
break;
case CERT_RETAIL_CPb_IDENT:
if (_CommonCertsStorage.loaded_certs_flg & CERT_RETAIL_CPb_IDENT)
_cert = &_CommonCertsStorage.retail_CPb;
break;
case CERT_DEV_CA4_IDENT:
if (_CommonCertsStorage.loaded_certs_flg & CERT_DEV_CA4_IDENT)
_cert = &_CommonCertsStorage.dev_CA4;
break;
case CERT_DEV_XS9_IDENT:
if (_CommonCertsStorage.loaded_certs_flg & CERT_DEV_XS9_IDENT)
_cert = &_CommonCertsStorage.dev_XS9;
break;
case CERT_DEV_CPa_IDENT:
if (_CommonCertsStorage.loaded_certs_flg & CERT_DEV_CPa_IDENT)
_cert = &_CommonCertsStorage.dev_CPa;
break;
default:
break;
}
if (!_cert)
return false;
*cert = *_cert;
return true;
}
static void _SaveToCertStorage(const Certificate* cert, u32 ident) {
if (ident == CERT_NO_STORE_SPACE)
return;
Certificate* _cert = NULL;
u8* raw_space = NULL;
u32 raw_size = 0;
switch (ident) {
case CERT_RETAIL_CA3_IDENT:
if (!(_CommonCertsStorage.loaded_certs_flg & CERT_RETAIL_CA3_IDENT)) {
_cert = &_CommonCertsStorage.retail_CA3;
raw_space = &_CommonCertsStorage.retail_CA3_raw[0];
raw_size = sizeof(_CommonCertsStorage.retail_CA3_raw);
}
break;
case CERT_RETAIL_XSc_IDENT:
if (!(_CommonCertsStorage.loaded_certs_flg & CERT_RETAIL_XSc_IDENT)) {
_cert = &_CommonCertsStorage.retail_XSc;
raw_space = &_CommonCertsStorage.retail_XSc_raw[0];
raw_size = sizeof(_CommonCertsStorage.retail_XSc_raw);
}
break;
case CERT_RETAIL_CPb_IDENT:
if (!(_CommonCertsStorage.loaded_certs_flg & CERT_RETAIL_CPb_IDENT)) {
_cert = &_CommonCertsStorage.retail_CPb;
raw_space = &_CommonCertsStorage.retail_CPb_raw[0];
raw_size = sizeof(_CommonCertsStorage.retail_CPb_raw);
}
break;
case CERT_DEV_CA4_IDENT:
if (!(_CommonCertsStorage.loaded_certs_flg & CERT_DEV_CA4_IDENT)) {
_cert = &_CommonCertsStorage.dev_CA4;
raw_space = &_CommonCertsStorage.dev_CA4_raw[0];
raw_size = sizeof(_CommonCertsStorage.dev_CA4_raw);
}
break;
case CERT_DEV_XS9_IDENT:
if (!(_CommonCertsStorage.loaded_certs_flg & CERT_DEV_XS9_IDENT)) {
_cert = &_CommonCertsStorage.dev_XS9;
raw_space = &_CommonCertsStorage.dev_XS9_raw[0];
raw_size = sizeof(_CommonCertsStorage.dev_XS9_raw);
}
break;
case CERT_DEV_CPa_IDENT:
if (!(_CommonCertsStorage.loaded_certs_flg & CERT_DEV_CPa_IDENT)) {
_cert = &_CommonCertsStorage.dev_CPa;
raw_space = &_CommonCertsStorage.dev_CPa_raw[0];
raw_size = sizeof(_CommonCertsStorage.dev_CPa_raw);
}
break;
default:
break;
}
if (!_cert || !raw_space || !raw_size)
return;
u32 sig_size = _Certificate_GetSignatureChunkSizeFromType(getbe32(cert->sig->sig_type));
u32 data_size = _Certificate_GetDataChunkSizeFromType(getbe32(cert->data->keytype));
if (sig_size == 0 || data_size == 0)
return;
if (sig_size + data_size != raw_size)
return;
if (!_Certificate_RawCopyImpl(cert, raw_space)) {
_CommonCertsStorage.loaded_certs_flg |= ident;
}
}
// grumble grumble, gotta avoid repeated code when possible or at least if significant enough
static u32 _DisaOpenCertDb(char (*path)[16], bool emunand, DisaDiffRWInfo* info, u8** cache, u32* offset, u32* max_offset) {
GetCertDBPath(*path, emunand);
u8* _cache = NULL;
if (GetDisaDiffRWInfo(*path, info, false) != 0) return 1;
_cache = (u8*)malloc(info->size_dpfs_lvl2);
if (!_cache) return 1;
if (BuildDisaDiffDpfsLvl2Cache(*path, info, _cache, info->size_dpfs_lvl2) != 0) {
free(_cache);
return 1;
}
CertsDbPartitionHeader header;
if (ReadDisaDiffIvfcLvl4(*path, info, 0, sizeof(CertsDbPartitionHeader), &header) != sizeof(CertsDbPartitionHeader)) {
free(_cache);
return 1;
}
if (getbe32(header.magic) != 0x43455254 /* 'CERT' */ ||
getbe32(header.unk) != 0 ||
getle32(header.used_size) & 0xFF) {
free(_cache);
return 1;
}
*cache = _cache;
*offset = sizeof(CertsDbPartitionHeader);
*max_offset = getle32(header.used_size) + sizeof(CertsDbPartitionHeader);
return 0;
}
static u32 _ProcessNextCertDbEntry(const char* path, DisaDiffRWInfo* info, Certificate* cert, u32 *full_size, char (*full_issuer)[0x41], u32* offset, u32 max_offset) {
u8 sig_type_data[4];
u8 keytype_data[4];
if (*offset + 4 > max_offset) return 1;
if (ReadDisaDiffIvfcLvl4(path, info, *offset, 4, sig_type_data) != 4)
return 1;
u32 sig_type = getbe32(sig_type_data);
if (sig_type == 0x10002 || sig_type == 0x10005) return 1; // ECC signs not allowed on db
u32 sig_size = _Certificate_GetSignatureChunkSizeFromType(sig_type);
if (sig_size == 0) return 1;
u32 keytype_off = *offset + sig_size + offsetof(CertificateBody, keytype);
if (keytype_off + 4 > max_offset) return 1;
if (ReadDisaDiffIvfcLvl4(path, info, keytype_off, 4, keytype_data) != 4)
return 1;
u32 keytype = getbe32(keytype_data);
if (keytype == 2) return 1; // ECC keys not allowed on db
u32 data_size = _Certificate_GetDataChunkSizeFromType(keytype);
if (data_size == 0) return 1;
*full_size = sig_size + data_size;
if (*offset + *full_size > max_offset) return 1;
cert->sig = (CertificateSignature*)malloc(sig_size);
cert->data = (CertificateBody*)malloc(data_size);
if (!cert->sig || !cert->data)
return 1;
if (ReadDisaDiffIvfcLvl4(path, info, *offset, sig_size, cert->sig) != sig_size)
return 1;
if (ReadDisaDiffIvfcLvl4(path, info, *offset + sig_size, data_size, cert->data) != data_size)
return 1;
if (!Certificate_IsValid(cert))
return 1;
if (snprintf(*full_issuer, 0x41, "%s-%s", cert->data->issuer, cert->data->name) > 0x40)
return 1;
return 0;
}
// certificates returned by this call are not to be deemed safe to edit, pointers or pointed data
u32 LoadCertFromCertDb(Certificate* cert, const char* issuer) {
if (!issuer || !cert) return 1;
u32 _ident = _Issuer_To_StorageIdent(issuer);
if (_LoadFromCertStorage(cert, _ident)) {
return 0;
}
int ret = 1;
for (int i = 0; i < 2 && ret; ++i) {
Certificate cert_local = CERTIFICATE_NULL_INIT;
char path[16];
DisaDiffRWInfo info;
u8* cache;
u32 offset, max_offset;
if (_DisaOpenCertDb(&path, i ? true : false, &info, &cache, &offset, &max_offset))
return 1;
// certs.db has no filesystem.. its pretty plain, certificates after another
// but also, certificates are not equally sized
// so most cases of bad data, leads to giving up
while (offset < max_offset) {
char full_issuer[0x41];
u32 full_size;
if (_ProcessNextCertDbEntry(path, &info, &cert_local, &full_size, &full_issuer, &offset, max_offset))
break;
if (!strcmp(full_issuer, issuer)) {
ret = 0;
break;
}
_Certificate_CleanupImpl(&cert_local);
offset += full_size;
}
if (ret) {
_Certificate_CleanupImpl(&cert_local);
} else {
*cert = cert_local;
_SaveToCertStorage(&cert_local, _ident);
}
free(cache);
}
return ret;
}
// I dont expect many certs on a cert bundle, so I'll cap it to 8
u32 BuildRawCertBundleFromCertDb(void* rawout, size_t* size, const char* const* cert_issuers, int count) {
if (!rawout || !size || !cert_issuers || count < 0 || count > 8) return 1;
if (!*size && count) return 1;
if (!count) { // *shrug*
*size = 0;
return 0;
}
for (int i = 0; i < count; ++i) {
if (!cert_issuers[i])
return 1;
}
Certificate certs[8];
u8 certs_loaded = 0;
memset(certs, 0, sizeof(certs));
int loaded_count = 0;
// search static storage first
for (int i = 0; i < count; ++i) {
u32 _ident = _Issuer_To_StorageIdent(cert_issuers[i]);
if (_LoadFromCertStorage(&certs[i], _ident)) {
certs_loaded |= BIT(i);
++loaded_count;
}
}
int ret = 0;
for (int i = 0; i < 2 && loaded_count != count && !ret; ++i) {
Certificate cert_local = CERTIFICATE_NULL_INIT;
char path[16];
DisaDiffRWInfo info;
u8* cache;
u32 offset, max_offset;
if (_DisaOpenCertDb(&path, i ? true : false, &info, &cache, &offset, &max_offset))
continue;
while (offset < max_offset) {
char full_issuer[0x41];
u32 full_size;
if (_ProcessNextCertDbEntry(path, &info, &cert_local, &full_size, &full_issuer, &offset, max_offset))
break;
for (int j = 0; j < count; j++) {
if (certs_loaded & BIT(j)) continue;
if (!strcmp(full_issuer, cert_issuers[j])) {
ret = _Certificate_AllocCopyOutImpl(&cert_local, &certs[j]);
if (ret) break;
certs_loaded |= BIT(j);
++loaded_count;
}
}
// while at it, try to save to static storage, if applicable
u32 _ident = _Issuer_To_StorageIdent(full_issuer);
_SaveToCertStorage(&cert_local, _ident);
_Certificate_CleanupImpl(&cert_local);
if (loaded_count == count || ret) // early exit
break;
offset += full_size;
}
free(cache);
}
if (!ret && loaded_count == count) {
u8* out = (u8*)rawout;
size_t limit = *size, written = 0;
for (int i = 0; i < count; ++i) {
u32 sig_size = _Certificate_GetSignatureChunkSizeFromType(getbe32(certs[i].sig->sig_type));
u32 data_size = _Certificate_GetDataChunkSizeFromType(getbe32(certs[i].data->keytype));
if (sig_size == 0 || data_size == 0) {
ret = 1;
break;
}
u32 full_size = sig_size + data_size;
if (written + full_size > limit) {
ret = 1;
break;
}
if (_Certificate_RawCopyImpl(&certs[i], out)) {
ret = 1;
break;
}
out += full_size;
written += full_size;
}
if (!ret)
*size = written;
} else {
ret = 1;
}
for (int i = 0; i < count; ++i) {
if (certs_loaded & BIT(i))
_Certificate_CleanupImpl(&certs[i]);
}
return ret;
}

View File

@ -2,54 +2,21 @@
#include "common.h"
#define CERT_MAX_SIZE (sizeof(CertificateSignature) + 0x23C + sizeof(CertificateBody) + 0x238)
#define CERT_RSA4096_SIG_SIZE (sizeof(CertificateSignature) + 0x23C)
#define CERT_RSA2048_SIG_SIZE (sizeof(CertificateSignature) + 0x13C)
#define CERT_ECC_SIG_SIZE (sizeof(CertificateSignature) + 0x7C)
#define CERT_RSA4096_BODY_SIZE (sizeof(CertificateBody) + 0x238)
#define CERT_RSA2048_BODY_SIZE (sizeof(CertificateBody) + 0x138)
#define CERT_ECC_BODY_SIZE (sizeof(CertificateBody) + 0x78)
#define CERTIFICATE_NULL_INIT ((Certificate){NULL, NULL})
#define CERT_SIZE sizeof(Certificate)
// from: http://3dbrew.org/wiki/Certificates
// all numbers in big endian
typedef struct {
u8 sig_type[4];
u8 signature[];
} PACKED_ALIGN(1) CertificateSignature;
u8 sig_type[4]; // expected: 0x010004 / RSA_2048 SHA256
u8 signature[0x100];
u8 padding0[0x3C];
u8 issuer[0x40];
u8 keytype[4]; // expected: 0x01 / RSA_2048
u8 name[0x40];
u8 unknown[4];
u8 mod[0x100];
u8 exp[0x04];
u8 padding1[0x34];
} PACKED_STRUCT Certificate;
typedef struct {
char issuer[0x40];
u8 keytype[4];
char name[0x40];
u8 expiration[4];
u8 pub_key_data[];
} PACKED_ALIGN(1) CertificateBody;
typedef struct {
CertificateSignature* sig;
CertificateBody* data;
} Certificate;
bool Certificate_IsValid(const Certificate* cert);
bool Certificate_IsRSA(const Certificate* cert);
bool Certificate_IsECC(const Certificate* cert);
u32 Certificate_GetSignatureSize(const Certificate* cert, u32* size);
u32 Certificate_GetModulusSize(const Certificate* cert, u32* size);
u32 Certificate_GetModulus(const Certificate* cert, void* mod);
u32 Certificate_GetExponent(const Certificate* cert, void* exp);
u32 Certificate_GetEccSingleCoordinateSize(const Certificate* cert, u32* size);
u32 Certificate_GetEccXY(const Certificate* cert, void* X, void* Y);
u32 Certificate_GetSignatureChunkSize(const Certificate* cert, u32* size);
u32 Certificate_GetDataChunkSize(const Certificate* cert, u32* size);
u32 Certificate_GetFullSize(const Certificate* cert, u32* size);
u32 Certificate_VerifySignatureBlock(const Certificate* cert, const void* sig, u32 sig_size, const void* data, u32 data_size, bool sha256);
u32 Certificate_MakeEditSafe(Certificate* cert);
u32 Certificate_AllocCopyOut(const Certificate* cert, Certificate* out_cert);
u32 Certificate_RawCopy(const Certificate* cert, void* raw);
u32 Certificate_Cleanup(Certificate* cert);
u32 LoadCertFromCertDb(Certificate* cert, const char* issuer);
u32 BuildRawCertBundleFromCertDb(void* rawout, size_t* size, const char* const* cert_issuers, int count);
u32 LoadCertFromCertDb(u64 offset, Certificate* cert, u32* mod, u32* exp);

View File

@ -4,12 +4,11 @@
#include "ff.h"
#include "aes.h"
#include "sha.h"
#include "cert.h"
u32 ValidateCiaHeader(CiaHeader* header) {
if ((header->size_header != CIA_HEADER_SIZE) ||
(header->size_cert != CIA_CERT_SIZE) ||
(header->size_ticket != TICKET_COMMON_SIZE) ||
(header->size_ticket != TICKET_SIZE) ||
(header->size_tmd < TMD_SIZE_MIN) ||
(header->size_tmd > TMD_SIZE_MAX) ||
(header->size_content == 0))
@ -19,20 +18,20 @@ u32 ValidateCiaHeader(CiaHeader* header) {
u32 GetCiaInfo(CiaInfo* info, CiaHeader* header) {
if ((u8*) info != (u8*) header) memcpy(info, header, 0x20); // take over first 0x20 byte
info->offset_cert = align(header->size_header, 64);
info->offset_ticket = info->offset_cert + align(header->size_cert, 64);
info->offset_tmd = info->offset_ticket + align(header->size_ticket, 64);
info->offset_content = info->offset_tmd + align(header->size_tmd, 64);
info->offset_meta = (header->size_meta) ? info->offset_content + align(header->size_content, 64) : 0;
info->offset_content_list = info->offset_tmd + sizeof(TitleMetaData);
info->size_content_list = info->size_tmd - sizeof(TitleMetaData);
info->size_cia = (header->size_meta) ? info->offset_meta + info->size_meta :
info->offset_content + info->size_content;
info->max_contents = (info->size_tmd - sizeof(TitleMetaData)) / sizeof(TmdContentChunk);
return 0;
}
@ -51,30 +50,37 @@ u32 FixCiaHeaderForTmd(CiaHeader* header, TitleMetaData* tmd) {
}
u32 BuildCiaCert(u8* ciacert) {
static const u8 cert_hash_expected[0x20] = {
const u8 cert_hash_expected[0x20] = {
0xC7, 0x2E, 0x1C, 0xA5, 0x61, 0xDC, 0x9B, 0xC8, 0x05, 0x58, 0x58, 0x9C, 0x63, 0x08, 0x1C, 0x8A,
0x10, 0x78, 0xDF, 0x42, 0x99, 0x80, 0x3A, 0x68, 0x58, 0xF0, 0x41, 0xF9, 0xCB, 0x10, 0xE6, 0x35
};
static const u8 cert_hash_expected_dev[0x20] = {
const u8 cert_hash_expected_dev[0x20] = {
0xFB, 0xD2, 0xC0, 0x47, 0x95, 0xB9, 0x4C, 0xC8, 0x0B, 0x64, 0x58, 0x96, 0xF6, 0x61, 0x0F, 0x52,
0x18, 0x83, 0xAF, 0xE0, 0xF4, 0xE5, 0x62, 0xBA, 0x69, 0xEE, 0x72, 0x2A, 0xC2, 0x4E, 0x95, 0xB3
};
static const char* const retail_issuers[] = {"Root-CA00000003", "Root-CA00000003-XS0000000c", "Root-CA00000003-CP0000000b"};
static const char* const dev_issuers[] = {"Root-CA00000004", "Root-CA00000004-XS00000009", "Root-CA00000004-CP0000000a"};
size_t size = CIA_CERT_SIZE;
if (BuildRawCertBundleFromCertDb(ciacert, &size, !IS_DEVKIT ? retail_issuers : dev_issuers, 3) ||
size != CIA_CERT_SIZE) {
// open certs.db file on SysNAND
FIL db;
UINT bytes_read;
if (f_open(&db, "1:/dbs/certs.db", FA_READ | FA_OPEN_EXISTING) != FR_OK)
return 1;
}
// grab CIA cert from 4 offsets
f_lseek(&db, 0x0C10);
f_read(&db, ciacert + 0x000, 0x1F0, &bytes_read);
f_lseek(&db, 0x3A00);
f_read(&db, ciacert + 0x1F0, 0x210, &bytes_read);
f_lseek(&db, 0x3F10);
f_read(&db, ciacert + 0x400, 0x300, &bytes_read);
f_lseek(&db, 0x3C10);
f_read(&db, ciacert + 0x700, 0x300, &bytes_read);
f_close(&db);
// check the certificate hash
u8 cert_hash[0x20];
sha_quick(cert_hash, ciacert, CIA_CERT_SIZE, SHA256_MODE);
if (memcmp(cert_hash, IS_DEVKIT ? cert_hash_expected_dev : cert_hash_expected, 0x20) != 0)
return 1;
return 0;
}
@ -89,12 +95,12 @@ u32 BuildCiaMeta(CiaMeta* meta, void* exthdr, void* smdh) {
return 0;
}
u32 BuildCiaHeader(CiaHeader* header, u32 ticket_size) {
u32 BuildCiaHeader(CiaHeader* header) {
memset(header, 0, sizeof(CiaHeader));
// sizes in header - fill only known sizes, others zero
header->size_header = sizeof(CiaHeader);
header->size_cert = CIA_CERT_SIZE;
header->size_ticket = ticket_size;
header->size_ticket = sizeof(Ticket);
header->size_tmd = 0;
header->size_meta = 0;
header->size_content = 0;

View File

@ -34,8 +34,8 @@ typedef struct {
u8 header_padding[0x40 - (CIA_HEADER_SIZE % 0x40)];
u8 cert[CIA_CERT_SIZE];
// cert is aligned and needs no padding
TicketCommon ticket;
u8 ticket_padding[0x40 - (TICKET_COMMON_SIZE % 0x40)];
Ticket ticket;
u8 ticket_padding[0x40 - (TICKET_SIZE % 0x40)];
TitleMetaData tmd;
TmdContentChunk content_list[TMD_MAX_CONTENTS];
} PACKED_ALIGN(16) CiaStub;
@ -66,7 +66,7 @@ u32 FixCiaHeaderForTmd(CiaHeader* header, TitleMetaData* tmd);
u32 BuildCiaCert(u8* ciacert);
u32 BuildCiaMeta(CiaMeta* meta, void* exthdr, void* smdh);
u32 BuildCiaHeader(CiaHeader* header, u32 ticket_size);
u32 BuildCiaHeader(CiaHeader* header);
u32 DecryptCiaContentSequential(void* data, u32 size, u8* ctr, const u8* titlekey);
u32 EncryptCiaContentSequential(void* data, u32 size, u8* ctr, const u8* titlekey);

View File

@ -1,23 +0,0 @@
#pragma once
#include "common.h"
#define CIFINISH_MAGIC "CIFINISH"
#define CIFINISH_TITLE_MAGIC "TITLE"
#define CIFINISH_SIZE(c) (sizeof(CifinishHeader) + ((((CifinishHeader*)(c))->n_entries) * sizeof(CifinishTitle)))
// see: https://github.com/ihaveamac/custom-install/blob/ac0be9d61d7ebef9356df23036dc53e8e862011a/custominstall.py#L163
typedef struct {
char magic[8];
u32 version;
u32 n_entries;
} __attribute__((packed, aligned(4))) CifinishHeader;
typedef struct {
char magic[5];
u8 padding0;
u8 has_seed; // 1 if it does, otherwise 0
u8 padding1;
u64 title_id;
u8 seed[16];
} __attribute__((packed, aligned(4))) CifinishTitle;

View File

@ -1,63 +1,11 @@
#include "cmd.h"
CmdHeader* BuildAllocCmdData(TitleMetaData* tmd) {
CmdHeader proto;
CmdHeader* cmd = NULL;
u32 content_count = getbe16(tmd->content_count);
u16 max_cnt_idx = 0;
u32 CheckCmdSize(CmdHeader* cmd, u64 fsize) {
u64 cmdsize = sizeof(CmdHeader) +
(cmd->n_entries * sizeof(u32)) +
(cmd->n_cmacs * sizeof(u32)) +
(cmd->n_entries * 0x10);
// sanity check
if (!content_count)
return NULL;
// find max content id
TmdContentChunk* chunk = (TmdContentChunk*) (tmd + 1);
for (u32 i = 0; (i < content_count) && (i < TMD_MAX_CONTENTS); i++, chunk++)
if (getbe16(chunk->index) > max_cnt_idx) max_cnt_idx = getbe16(chunk->index);
// allocate memory for CMD / basic setup
proto.cmd_id = 1;
proto.n_entries = max_cnt_idx + 1;
proto.n_cmacs = content_count;
proto.unknown = 1;
memset(proto.cmac, 0x00, 0x10);
cmd = (CmdHeader*) malloc(CMD_SIZE(&proto));
if (!cmd) return NULL;
memset(cmd, 0x00, CMD_SIZE(&proto));
memcpy(cmd, &proto, sizeof(CmdHeader));
cmd->unknown = 0x0; // this means no CMACs, only valid for NAND
// copy content ids
u32* cnt_id = (u32*) (cmd + 1);
u32* cnt_id_2nd = cnt_id + cmd->n_entries;
chunk = (TmdContentChunk*) (tmd + 1);
memset(cnt_id, 0xFF, cmd->n_entries * sizeof(u32));
for (u32 i = 0; (i < content_count) && (i < TMD_MAX_CONTENTS); i++, chunk++) {
u32 chunk_id = getbe32(chunk->id);
cnt_id[getbe16(chunk->index)] = chunk_id;
*(cnt_id_2nd++) = chunk_id;
}
// bubble sort the second content id list
bool bs_finished = false;
cnt_id_2nd = cnt_id + cmd->n_entries;
while (!bs_finished) {
bs_finished = true;
for (u32 b = 1; b < cmd->n_cmacs; b++) {
if (cnt_id_2nd[b] < cnt_id_2nd[b-1]) {
u32 swp = cnt_id_2nd[b];
cnt_id_2nd[b] = cnt_id_2nd[b-1];
cnt_id_2nd[b-1] = swp;
bs_finished = false;
}
}
}
// set CMACs to 0x00
u8* cnt_cmac = (u8*) (cnt_id_2nd + cmd->n_cmacs);
memset(cnt_cmac, 0x00, 0x10 * cmd->n_entries);
// we still need to fix / set the CMACs inside the CMD file!
return cmd;
return (fsize == cmdsize) ? 0 : 1;
}

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