source => arm9/source

This commit is contained in:
TuxSH
2018-05-23 11:52:01 +02:00
parent 9fad2dff21
commit 52cd950ca6
61 changed files with 0 additions and 0 deletions

167
arm9/source/3dsheaders.h Normal file
View File

@@ -0,0 +1,167 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Adapted from 3DBrew and https://github.com/mid-kid/CakesForeveryWan/blob/master/source/headers.h
*/
#pragma once
typedef struct __attribute__((packed))
{
u32 address;
u32 phyRegionSize;
u32 size;
} CodeSetInfo;
typedef struct __attribute__((packed))
{
u32 saveDataSize[2];
u32 jumpID[2];
u8 reserved[0x30];
} SystemInfo;
typedef struct __attribute__((packed))
{
char appTitle[8];
u8 reserved1[5];
u8 flag;
u8 remasterVersion[2];
CodeSetInfo textCodeSet;
u32 stackSize;
CodeSetInfo roCodeSet;
u8 reserved2[4];
CodeSetInfo dataCodeSet;
u32 bssSize;
char depends[0x180];
SystemInfo systemInfo;
} SystemControlInfo;
typedef struct __attribute__((packed))
{
SystemControlInfo systemControlInfo;
u8 aci[0x200];
u8 accessDescSig[0x100];
u8 ncchPubKey[0x100];
u8 aciLim[0x200];
} ExHeader;
typedef struct __attribute__((packed))
{
u8 sig[0x100]; //RSA-2048 signature of the NCCH header, using SHA-256
char magic[4]; //NCCH
u32 contentSize; //Media unit
u8 partitionId[8];
u8 makerCode[2];
u16 version;
u8 reserved1[4];
u8 programID[8];
u8 reserved2[0x10];
u8 logoHash[0x20]; //Logo Region SHA-256 hash
char productCode[0x10];
u8 exHeaderHash[0x20]; //Extended header SHA-256 hash
u32 exHeaderSize; //Extended header size
u32 reserved3;
u8 flags[8];
u32 plainOffset; //Media unit
u32 plainSize; //Media unit
u32 logoOffset; //Media unit
u32 logoSize; //Media unit
u32 exeFsOffset; //Media unit
u32 exeFsSize; //Media unit
u32 exeFsHashSize; //Media unit
u32 reserved4;
u32 romFsOffset; //Media unit
u32 romFsSize; //Media unit
u32 romFsHashSize; //Media unit
u32 reserved5;
u8 exeFsHash[0x20]; //ExeFS superblock SHA-256 hash
u8 romFsHash[0x20]; //RomFS superblock SHA-256 hash
} Ncch;
typedef struct __attribute__((packed))
{
Ncch ncch;
ExHeader exHeader;
} Cxi;
typedef struct __attribute__((packed))
{
char sigIssuer[0x40];
u8 eccPubKey[0x3C];
u8 version;
u8 caCrlVersion;
u8 signerCrlVersion;
u8 titleKey[0x10];
u8 reserved1;
u8 ticketId[8];
u8 consoleId[4];
u8 titleId[8];
u8 reserved2[2];
u16 ticketTitleVersion;
u8 reserved3[8];
u8 licenseType;
u8 ticketCommonKeyYIndex; //Ticket common keyY index, usually 0x1 for retail system titles.
u8 reserved4[0x2A];
u8 unk[4]; //eShop Account ID?
u8 reserved5;
u8 audit;
u8 reserved6[0x42];
u8 limits[0x40];
u8 contentIndex[0xAC];
} Ticket;
typedef struct __attribute__((packed))
{
u32 offset;
u8 *address;
u32 size;
u32 procType;
u8 hash[0x20];
} FirmSection;
typedef struct __attribute__((packed))
{
char magic[4];
u32 reserved1;
u8 *arm11Entry;
u8 *arm9Entry;
u8 reserved2[0x30];
FirmSection section[4];
} Firm;
typedef struct __attribute__((packed))
{
u8 keyX[0x10];
u8 keyY[0x10];
u8 ctr[0x10];
char size[8];
u8 reserved[8];
u8 ctlBlock[0x10];
char magic[4];
u8 reserved2[0xC];
u8 slot0x16keyX[0x10];
} Arm9Bin;

View File

@@ -0,0 +1,91 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "arm9_exception_handlers.h"
#include "i2c.h"
#include "screen.h"
#define FINAL_BUFFER 0x25000000
#define REG_DUMP_SIZE 4 * 17
#define CODE_DUMP_SIZE 48
void __attribute__((noreturn)) arm9ExceptionHandlerMain(u32 *registerDump, u32 type)
{
ExceptionDumpHeader dumpHeader;
u8 codeDump[CODE_DUMP_SIZE];
dumpHeader.magic[0] = 0xDEADC0DE;
dumpHeader.magic[1] = 0xDEADCAFE;
dumpHeader.versionMajor = 1;
dumpHeader.versionMinor = 2;
dumpHeader.processor = 9;
dumpHeader.core = 0;
dumpHeader.type = type;
dumpHeader.registerDumpSize = REG_DUMP_SIZE;
dumpHeader.codeDumpSize = CODE_DUMP_SIZE;
dumpHeader.additionalDataSize = 0;
u32 cpsr = registerDump[16];
u32 pc = registerDump[15] - (type < 3 ? (((cpsr & 0x20) != 0 && type == 1) ? 2 : 4) : 8);
registerDump[15] = pc;
//Dump code
u8 *instr = (u8 *)pc + ((cpsr & 0x20) ? 2 : 4) - dumpHeader.codeDumpSize; //wouldn't work well on 32-bit Thumb instructions, but it isn't much of a problem
dumpHeader.codeDumpSize = ((u32)instr & (((cpsr & 0x20) != 0) ? 1 : 3)) != 0 ? 0 : safecpy(codeDump, instr, dumpHeader.codeDumpSize);
//Copy register dump and code dump
u8 *final = (u8 *)(FINAL_BUFFER + sizeof(ExceptionDumpHeader));
final += safecpy(final, registerDump, dumpHeader.registerDumpSize);
final += safecpy(final, codeDump, dumpHeader.codeDumpSize);
//Dump stack in place
dumpHeader.stackDumpSize = safecpy(final, (const void *)registerDump[13], 0x1000 - (registerDump[13] & 0xFFF));
dumpHeader.totalSize = sizeof(ExceptionDumpHeader) + dumpHeader.registerDumpSize + dumpHeader.codeDumpSize + dumpHeader.stackDumpSize + dumpHeader.additionalDataSize;
//Copy header (actually optimized by the compiler)
*(ExceptionDumpHeader *)FINAL_BUFFER = dumpHeader;
<<<<<<< HEAD:exceptions/arm9/source/mainHandler.c
if(ARESCREENSINITIALIZED) I2C_writeReg(I2C_DEV_MCU, 0x22, 1 << 0); //Shutdown LCD
((void (*)())0xFFFF0830)(); //Ensure that all memory transfers have completed and that the data cache has been flushed
I2C_writeReg(I2C_DEV_MCU, 0x20, 1 << 2); //Reboot
=======
if(ARESCREENSINITIALIZED) i2cWriteRegisterNoWait(I2C_DEV_MCU, 0x22, 1 << 0); //Shutdown LCD
((void (*)())0xFFFF0830)(); //Ensure that all memory transfers have completed and that the data cache has been flushed
i2cWriteRegisterNoWait(I2C_DEV_MCU, 0x20, 1 << 2); //Reboot
>>>>>>> Do the same for arm9 exceptions:source/arm9_exception_handlers.c
while(true);
}

View File

@@ -0,0 +1,48 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "types.h"
extern const u32 arm9ExceptionHandlerAddressTable[6];
extern u32 arm9ExceptionHandlerSvcBreakAddress;
<<<<<<< HEAD:exceptions/arm9/source/types.h
//Common data types
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef volatile u8 vu8;
typedef volatile u16 vu16;
typedef volatile u32 vu32;
typedef volatile u64 vu64;
#define PDN_GPU_CNT (*(vu32 *)0x10141200)
#define ARESCREENSINITIALIZED ((PDN_GPU_CNT & 0xFF) != 1)
=======
u32 safecpy(void *dst, const void *src, u32 len);
>>>>>>> Do the same for arm9 exceptions:source/arm9_exception_handlers.h

View File

@@ -0,0 +1,168 @@
@ This file is part of Luma3DS
@ Copyright (C) 2016-2019 Aurora Wright, TuxSH
@
@ This program is free software: you can redistribute it and/or modify
@ it under the terms of the GNU General Public License as published by
@ the Free Software Foundation, either version 3 of the License, or
@ (at your option) any later version.
@
@ This program is distributed in the hope that it will be useful,
@ but WITHOUT ANY WARRANTY; without even the implied warranty of
@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
@ GNU General Public License for more details.
@
@ You should have received a copy of the GNU General Public License
@ along with this program. If not, see <http://www.gnu.org/licenses/>.
@
@ Additional Terms 7.b and 7.c of GPLv3 apply to this file:
@ * Requiring preservation of specified reasonable legal notices or
@ author attributions in that material or in the Appropriate Legal
@ Notices displayed by works containing it.
@ * Prohibiting misrepresentation of the origin of that material,
@ or requiring that modified versions of such material be marked in
@ reasonable ways as different from the original version.
.macro GEN_USUAL_HANDLER name, index
\name\()Handler:
ldr sp, =_regs
stmia sp, {r0-r7}
mov r0, #\index
b _arm9ExceptionHandlerCommon
.endm
.section .arm9_exception_handlers.text, "ax", %progbits
.arm
.align 4
.global _arm9ExceptionHandlerCommon
.type _arm9ExceptionHandlerCommon, %function
_arm9ExceptionHandlerCommon:
mov r1, r0
mov r0, sp
mrs r2, spsr
mrs r3, cpsr
add r6, r0, #(8 * 4)
orr r3, #0xc0 @ mask interrupts
msr cpsr_cx, r3
ands r4, r2, #0xf @ get the mode that triggered the exception
moveq r4, #0xf @ usr => sys
bic r5, r3, #0xf
orr r5, r4
msr cpsr_c, r5 @ change processor mode
stmia r6!, {r8-lr}
msr cpsr_c, r3 @ restore processor mode
str lr, [r6], #4
str r2, [r6]
msr cpsr_cxsf, #0xdf @ finally, switch to system mode, mask interrupts and clear flags (in case of double faults)
ldr sp, =0x02000000
b arm9ExceptionHandlerMain
.global FIQHandler
.type FIQHandler, %function
GEN_USUAL_HANDLER FIQ, 0
.global undefinedInstructionHandler
.type undefinedInstructionHandler, %function
GEN_USUAL_HANDLER undefinedInstruction, 1
.global prefetchAbortHandler
.type prefetchAbortHandler, %function
prefetchAbortHandler:
msr cpsr_cx, #0xd7 @ mask interrupts (abort mode)
mrs sp, spsr
and sp, #0x3f
cmp sp, #0x13
bne _prefetchAbortNormalHandler
ldr sp, =arm9ExceptionHandlerSvcBreakAddress
ldr sp, [sp]
cmp sp, #0
beq _prefetchAbortNormalHandler
add sp, #(1*4 + 4)
cmp lr, sp
bne _prefetchAbortNormalHandler
mov sp, r8
pop {r8-r11}
ldr lr, [sp, #8]!
ldr sp, [sp, #4]
msr spsr_cxsf, sp
tst sp, #0x20
addne lr, #2 @ adjust address for later
GEN_USUAL_HANDLER _prefetchAbortNormal, 2
.global dataAbortHandler
.type dataAbortHandler, %function
dataAbortHandler:
msr cpsr_cx, #0xd7 @ mask interrupts (abort mode)
mrs sp, spsr
and sp, #0x3f
cmp sp, #0x1f
bne _dataAbortNormalHandler
sub lr, #8
adr sp, safecpy
cmp lr, sp
blo _j_dataAbortNormalHandler
adr sp, _safecpy_end
cmp lr, sp
bhs _j_dataAbortNormalHandler
msr spsr_f, #(1 << 30)
mov r12, #0
adds pc, lr, #4
_j_dataAbortNormalHandler:
add lr, #8
GEN_USUAL_HANDLER _dataAbortNormal, 3
.global safecpy
.type safecpy, %function
safecpy:
push {r4, lr}
mov r3, #0
movs r12, #1
_safecpy_loop:
ldrb r4, [r1, r3]
cmp r12, #0
beq _safecpy_loop_end
strb r4, [r0, r3]
add r3, #1
cmp r3, r2
blo _safecpy_loop
_safecpy_loop_end:
mov r0, r3
pop {r4, pc}
_safecpy_end:
.section .arm9_exception_handlers.rodata, "a", %progbits
.align 4
.global arm9ExceptionHandlerAddressTable
arm9ExceptionHandlerAddressTable:
.word 0 @ IRQ
.word FIQHandler @ FIQ
.word 0 @ SVC
.word undefinedInstructionHandler @ Undefined instruction
.word prefetchAbortHandler @ Prefetch abort
.word dataAbortHandler @ Data abort
.section .arm9_exception_handlers.bss, "w", %nobits
.align 4
.global arm9ExceptionHandlerSvcBreakAddress
arm9ExceptionHandlerSvcBreakAddress:
.word 0
_regs: .skip (4 * 17)

52
arm9/source/buttons.h Normal file
View File

@@ -0,0 +1,52 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#pragma once
#include "types.h"
#define HID_PAD (*(vu32 *)0x10146000 ^ 0xFFF)
#define BUTTON_R1 (1 << 8)
#define BUTTON_L1 (1 << 9)
#define BUTTON_A (1 << 0)
#define BUTTON_B (1 << 1)
#define BUTTON_X (1 << 10)
#define BUTTON_Y (1 << 11)
#define BUTTON_SELECT (1 << 2)
#define BUTTON_START (1 << 3)
#define BUTTON_RIGHT (1 << 4)
#define BUTTON_LEFT (1 << 5)
#define BUTTON_UP (1 << 6)
#define BUTTON_DOWN (1 << 7)
#define DPAD_BUTTONS (BUTTON_LEFT | BUTTON_RIGHT | BUTTON_UP | BUTTON_DOWN)
#define SAFE_MODE (BUTTON_R1 | BUTTON_L1 | BUTTON_A | BUTTON_UP)
#define SINGLE_PAYLOAD_BUTTONS (BUTTON_B | BUTTON_X | BUTTON_Y)
#define L_PAYLOAD_BUTTONS (BUTTON_R1 | BUTTON_A | BUTTON_START | BUTTON_SELECT)
#define MENU_BUTTONS (DPAD_BUTTONS | BUTTON_A | BUTTON_START)
#define PIN_BUTTONS (BUTTON_A | BUTTON_B | BUTTON_X | BUTTON_Y | DPAD_BUTTONS | BUTTON_START | BUTTON_SELECT)
#define NTRBOOT_BUTTONS (BUTTON_START | BUTTON_SELECT | BUTTON_X)

43
arm9/source/cache.h Normal file
View File

@@ -0,0 +1,43 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#pragma once
#include "types.h"
/***
The following functions flush the data cache, then waits for all memory transfers to be finished.
The data cache and/or the instruction cache MUST be flushed before doing one of the following:
- rebooting
- powering down
- setting the ARM11 entrypoint to execute a function
- jumping to a payload
***/
void flushEntireDCache(void); //actually: "clean and flush"
void flushDCacheRange(void *startAddress, u32 size);
void flushEntireICache(void);
void flushICacheRange(void *startAddress, u32 size);

93
arm9/source/cache.s Normal file
View File

@@ -0,0 +1,93 @@
@ This file is part of Luma3DS
@ Copyright (C) 2016-2019 Aurora Wright, TuxSH
@
@ This program is free software: you can redistribute it and/or modify
@ it under the terms of the GNU General Public License as published by
@ the Free Software Foundation, either version 3 of the License, or
@ (at your option) any later version.
@
@ This program is distributed in the hope that it will be useful,
@ but WITHOUT ANY WARRANTY; without even the implied warranty of
@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
@ GNU General Public License for more details.
@
@ You should have received a copy of the GNU General Public License
@ along with this program. If not, see <http://www.gnu.org/licenses/>.
@
@ Additional Terms 7.b and 7.c of GPLv3 apply to this file:
@ * Requiring preservation of specified reasonable legal notices or
@ author attributions in that material or in the Appropriate Legal
@ Notices displayed by works containing it.
@ * Prohibiting misrepresentation of the origin of that material,
@ or requiring that modified versions of such material be marked in
@ reasonable ways as different from the original version.
.section .text.cache, "ax", %progbits
.arm
.align 4
.global flushEntireDCache
.type flushEntireDCache, %function
flushEntireDCache:
@ Adapted from http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0155a/ch03s03s05.html,
@ and https://github.com/gemarcano/libctr9_io/blob/master/src/ctr_system_ARM.c#L39 as well
@ Note: ARM's example is actually for a 8KB DCache (which is what the 3DS has)
@ Implemented in bootROM at address 0xffff0830
mov r1, #0 @ segment counter
outer_loop:
mov r0, #0 @ line counter
inner_loop:
orr r2, r1, r0 @ generate segment and line address
mcr p15, 0, r2, c7, c14, 2 @ clean and flush the line
add r0, #0x20 @ increment to next line
cmp r0, #0x400
bne inner_loop
add r1, #0x40000000
cmp r1, #0
bne outer_loop
mcr p15, 0, r1, c7, c10, 4 @ drain write buffer
bx lr
.global flushDCacheRange
.type flushDCacheRange, %function
flushDCacheRange:
@ Implemented in bootROM at address 0xffff08a0
add r1, r0, r1 @ end address
bic r0, #0x1f @ align source address to cache line size (32 bytes)
flush_dcache_range_loop:
mcr p15, 0, r0, c7, c14, 1 @ clean and flush the line corresponding to the address r0 is holding
add r0, #0x20
cmp r0, r1
blo flush_dcache_range_loop
mov r0, #0
mcr p15, 0, r0, c7, c10, 4 @ drain write buffer
bx lr
.global flushEntireICache
.type flushEntireICache, %function
flushEntireICache:
@ Implemented in bootROM at address 0xffff0ab4
mov r0, #0
mcr p15, 0, r0, c7, c5, 0
bx lr
.global flushICacheRange
.type flushICacheRange, %function
flushICacheRange:
@ Implemented in bootROM at address 0xffff0ac0
add r1, r0, r1 @ end address
bic r0, #0x1f @ align source address to cache line size (32 bytes)
flush_icache_range_loop:
mcr p15, 0, r0, c7, c5, 1 @ flush the line corresponding to the address r0 is holding
add r0, #0x20
cmp r0, r1
blo flush_icache_range_loop
bx lr

84
arm9/source/chainloader.c Normal file
View File

@@ -0,0 +1,84 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "chainloader.h"
#include "screen.h"
void disableMpuAndJumpToEntrypoints(int argc, char **argv, void *arm11Entry, void *arm9Entry);
#pragma GCC optimize (3)
static void *xmemcpy(void *dst, const void *src, u32 len)
{
const u8 *src8 = (const u8 *)src;
u8 *dst8 = (u8 *)dst;
for (u32 i = 0; i < len; i++) {
dst8[i] = src8[i];
}
return dst;
}
static void doLaunchFirm(Firm *firm, int argc, char **argv)
{
//Copy FIRM sections to respective memory locations
for(u32 sectionNum = 0; sectionNum < 4; sectionNum++)
xmemcpy(firm->section[sectionNum].address, (u8 *)firm + firm->section[sectionNum].offset, firm->section[sectionNum].size);
disableMpuAndJumpToEntrypoints(argc, argv, firm->arm9Entry, firm->arm11Entry);
__builtin_unreachable();
}
void chainloader_main(int argc, char **argv, Firm *firm)
{
char *argvPassed[2],
absPath[24 + 255];
struct fb fbs[2];
if(argc > 0)
{
u32 i;
for(i = 0; i < sizeof(absPath) - 1 && argv[0][i] != 0; i++)
absPath[i] = argv[0][i];
absPath[i] = 0;
argvPassed[0] = (char *)absPath;
}
if(argc == 2)
{
struct fb *fbsrc = (struct fb *)argv[1];
fbs[0] = fbsrc[0];
fbs[1] = fbsrc[1];
argvPassed[1] = (char *)&fbs;
}
doLaunchFirm(firm, argc, argvPassed);
}

32
arm9/source/chainloader.h Normal file
View File

@@ -0,0 +1,32 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#pragma once
#include "types.h"
#include "firm.h"
void chainload(int argc, char **argv, Firm *firm);

429
arm9/source/config.c Normal file
View File

@@ -0,0 +1,429 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "config.h"
#include "memory.h"
#include "fs.h"
#include "strings.h"
#include "utils.h"
#include "screen.h"
#include "draw.h"
#include "emunand.h"
#include "buttons.h"
#include "pin.h"
CfgData configData;
ConfigurationStatus needConfig;
static CfgData oldConfig;
bool readConfig(void)
{
bool ret;
if(fileRead(&configData, CONFIG_FILE, sizeof(CfgData)) != sizeof(CfgData) ||
memcmp(configData.magic, "CONF", 4) != 0 ||
configData.formatVersionMajor != CONFIG_VERSIONMAJOR ||
configData.formatVersionMinor != CONFIG_VERSIONMINOR)
{
memset(&configData, 0, sizeof(CfgData));
ret = false;
}
else ret = true;
oldConfig = configData;
return ret;
}
void writeConfig(bool isConfigOptions)
{
//If the configuration is different from previously, overwrite it.
if(needConfig != CREATE_CONFIGURATION && ((isConfigOptions && configData.config == oldConfig.config && configData.multiConfig == oldConfig.multiConfig) ||
(!isConfigOptions && configData.bootConfig == oldConfig.bootConfig))) return;
if(needConfig == CREATE_CONFIGURATION)
{
memcpy(configData.magic, "CONF", 4);
configData.formatVersionMajor = CONFIG_VERSIONMAJOR;
configData.formatVersionMinor = CONFIG_VERSIONMINOR;
needConfig = MODIFY_CONFIGURATION;
}
if(!fileWrite(&configData, CONFIG_FILE, sizeof(CfgData)))
error("Error writing the configuration file");
}
void configMenu(bool oldPinStatus, u32 oldPinMode)
{
static const char *multiOptionsText[] = { "Default EmuNAND: 1( ) 2( ) 3( ) 4( )",
"Screen brightness: 4( ) 3( ) 2( ) 1( )",
"Splash: Off( ) Before( ) After( ) payloads",
"Splash duration: 1( ) 3( ) 5( ) 7( ) seconds",
"PIN lock: Off( ) 4( ) 6( ) 8( ) digits",
"New 3DS CPU: Off( ) Clock( ) L2( ) Clock+L2( )",
};
static const char *singleOptionsText[] = { "( ) Autoboot EmuNAND",
"( ) Use EmuNAND FIRM if booting with R",
"( ) Enable loading external FIRMs and modules",
"( ) Enable game patching",
"( ) Show NAND or user string in System Settings",
"( ) Show GBA boot screen in patched AGB_FIRM",
"( ) Set developer UNITINFO",
"( ) Disable ARM11 exception handlers",
};
static const char *optionsDescription[] = { "Select the default EmuNAND.\n\n"
"It will be booted when no\n"
"directional pad buttons are pressed.",
"Select the screen brightness.",
"Enable splash screen support.\n\n"
"\t* 'Before payloads' displays it\n"
"before booting payloads\n"
"(intended for splashes that display\n"
"button hints).\n\n"
"\t* 'After payloads' displays it\n"
"afterwards.",
"Select how long the splash screen\n"
"displays.\n\n"
"This has no effect if the splash\n"
"screen is not enabled.",
"Activate a PIN lock.\n\n"
"The PIN will be asked each time\n"
"Luma3DS boots.\n\n"
"4, 6 or 8 digits can be selected.\n\n"
"The ABXY buttons and the directional\n"
"pad buttons can be used as keys.\n\n"
"A message can also be displayed\n"
"(refer to the wiki for instructions).",
"Select the New 3DS CPU mode.\n\n"
"This won't apply to\n"
"New 3DS exclusive/enhanced games.\n\n"
"'Clock+L2' can cause issues with some\n"
"games.",
"If enabled, an EmuNAND\n"
"will be launched on boot.\n\n"
"Otherwise, SysNAND will.\n\n"
"Hold L on boot to switch NAND.\n\n"
"To use a different EmuNAND from the\n"
"default, hold a directional pad button\n"
"(Up/Right/Down/Left equal EmuNANDs\n"
"1/2/3/4).",
"If enabled, when holding R on boot\n"
"SysNAND will be booted with an\n"
"EmuNAND FIRM.\n\n"
"Otherwise, an EmuNAND will be booted\n"
"with the SysNAND FIRM.\n\n"
"To use a different EmuNAND from the\n"
"default, hold a directional pad button\n"
"(Up/Right/Down/Left equal EmuNANDs\n"
"1/2/3/4), also add A if you have\n"
"a matching payload.",
"Enable loading external FIRMs and\n"
"system modules.\n\n"
"This isn't needed in most cases.\n\n"
"Refer to the wiki for instructions.",
"Enable overriding the region and\n"
"language configuration and the usage\n"
"of patched code binaries, exHeaders,\n"
"IPS code patches and LayeredFS\n"
"for specific games.\n\n"
"Also makes certain DLCs\n"
"for out-of-region games work.\n\n"
"Refer to the wiki for instructions.",
"Enable showing the current NAND/FIRM:\n\n"
"\t* Sys = SysNAND\n"
"\t* Emu = EmuNAND 1\n"
"\t* EmuX = EmuNAND X\n"
"\t* SysE = SysNAND with EmuNAND 1 FIRM\n"
"\t* SyEX = SysNAND with EmuNAND X FIRM\n"
"\t* EmuS = EmuNAND 1 with SysNAND FIRM\n"
"\t* EmXS = EmuNAND X with SysNAND FIRM\n\n"
"or a user-defined custom string in\n"
"System Settings.\n\n"
"Refer to the wiki for instructions.",
"Enable showing the GBA boot screen\n"
"when booting GBA games.",
"Make the console be always detected\n"
"as a development unit, and conversely.\n"
"(which breaks online features, amiibo\n"
"and retail CIAs, but allows installing\n"
"and booting some developer software).\n\n"
"Only select this if you know what you\n"
"are doing!",
"Disables the fatal error exception\n"
"handlers for the ARM11 CPU.\n\n"
"Note: Disabling the exception handlers\n"
"will disqualify you from submitting\n"
"issues or bug reports to the Luma3DS\n"
"GitHub repository!"
};
FirmwareSource nandType = FIRMWARE_SYSNAND;
if(isSdMode)
{
nandType = FIRMWARE_EMUNAND;
locateEmuNand(&nandType);
}
struct multiOption {
u32 posXs[4];
u32 posY;
u32 enabled;
bool visible;
} multiOptions[] = {
{ .visible = nandType == FIRMWARE_EMUNAND },
{ .visible = true },
{ .visible = true },
{ .visible = true },
{ .visible = true },
{ .visible = ISN3DS },
};
struct singleOption {
u32 posY;
bool enabled;
bool visible;
} singleOptions[] = {
{ .visible = nandType == FIRMWARE_EMUNAND },
{ .visible = nandType == FIRMWARE_EMUNAND },
{ .visible = true },
{ .visible = true },
{ .visible = true },
{ .visible = true },
{ .visible = true },
{ .visible = true }
};
//Calculate the amount of the various kinds of options and pre-select the first single one
u32 multiOptionsAmount = sizeof(multiOptions) / sizeof(struct multiOption),
singleOptionsAmount = sizeof(singleOptions) / sizeof(struct singleOption),
totalIndexes = multiOptionsAmount + singleOptionsAmount - 1,
selectedOption,
singleSelected;
bool isMultiOption = false;
//Parse the existing options
for(u32 i = 0; i < multiOptionsAmount; i++)
{
//Detect the positions where the "x" should go
u32 optionNum = 0;
for(u32 j = 0; optionNum < 4 && j < strlen(multiOptionsText[i]); j++)
if(multiOptionsText[i][j] == '(') multiOptions[i].posXs[optionNum++] = j + 1;
while(optionNum < 4) multiOptions[i].posXs[optionNum++] = 0;
multiOptions[i].enabled = MULTICONFIG(i);
}
for(u32 i = 0; i < singleOptionsAmount; i++)
singleOptions[i].enabled = CONFIG(i);
initScreens();
static const char *bootTypes[] = { "B9S",
"B9S (ntrboot)",
"FIRM0",
"FIRM1" };
drawString(true, 10, 10, COLOR_TITLE, CONFIG_TITLE);
drawString(true, 10, 10 + SPACING_Y, COLOR_TITLE, "Press A to select, START to save");
drawFormattedString(false, 10, SCREEN_HEIGHT - 2 * SPACING_Y, COLOR_YELLOW, "Booted from %s via %s", isSdMode ? "SD" : "CTRNAND", bootTypes[(u32)bootType]);
//Character to display a selected option
char selected = 'x';
u32 endPos = 10 + 2 * SPACING_Y;
//Display all the multiple choice options in white
for(u32 i = 0; i < multiOptionsAmount; i++)
{
if(!multiOptions[i].visible) continue;
multiOptions[i].posY = endPos + SPACING_Y;
endPos = drawString(true, 10, multiOptions[i].posY, COLOR_WHITE, multiOptionsText[i]);
drawCharacter(true, 10 + multiOptions[i].posXs[multiOptions[i].enabled] * SPACING_X, multiOptions[i].posY, COLOR_WHITE, selected);
}
endPos += SPACING_Y / 2;
//Display all the normal options in white except for the first one
for(u32 i = 0, color = COLOR_RED; i < singleOptionsAmount; i++)
{
if(!singleOptions[i].visible) continue;
singleOptions[i].posY = endPos + SPACING_Y;
endPos = drawString(true, 10, singleOptions[i].posY, color, singleOptionsText[i]);
if(singleOptions[i].enabled) drawCharacter(true, 10 + SPACING_X, singleOptions[i].posY, color, selected);
if(color == COLOR_RED)
{
singleSelected = i;
selectedOption = i + multiOptionsAmount;
color = COLOR_WHITE;
}
}
drawString(false, 10, 10, COLOR_WHITE, optionsDescription[selectedOption]);
//Boring configuration menu
while(true)
{
u32 pressed;
do
{
pressed = waitInput(true) & MENU_BUTTONS;
}
while(!pressed);
if(pressed == BUTTON_START) break;
if(pressed != BUTTON_A)
{
//Remember the previously selected option
u32 oldSelectedOption = selectedOption;
while(true)
{
switch(pressed)
{
case BUTTON_UP:
selectedOption = !selectedOption ? totalIndexes : selectedOption - 1;
break;
case BUTTON_DOWN:
selectedOption = selectedOption == totalIndexes ? 0 : selectedOption + 1;
break;
case BUTTON_LEFT:
pressed = BUTTON_DOWN;
selectedOption = 0;
break;
case BUTTON_RIGHT:
pressed = BUTTON_UP;
selectedOption = totalIndexes;
break;
default:
break;
}
if(selectedOption < multiOptionsAmount)
{
if(!multiOptions[selectedOption].visible) continue;
isMultiOption = true;
break;
}
else
{
singleSelected = selectedOption - multiOptionsAmount;
if(!singleOptions[singleSelected].visible) continue;
isMultiOption = false;
break;
}
}
if(selectedOption == oldSelectedOption) continue;
//The user moved to a different option, print the old option in white and the new one in red. Only print 'x's if necessary
if(oldSelectedOption < multiOptionsAmount)
{
drawString(true, 10, multiOptions[oldSelectedOption].posY, COLOR_WHITE, multiOptionsText[oldSelectedOption]);
drawCharacter(true, 10 + multiOptions[oldSelectedOption].posXs[multiOptions[oldSelectedOption].enabled] * SPACING_X, multiOptions[oldSelectedOption].posY, COLOR_WHITE, selected);
}
else
{
u32 singleOldSelected = oldSelectedOption - multiOptionsAmount;
drawString(true, 10, singleOptions[singleOldSelected].posY, COLOR_WHITE, singleOptionsText[singleOldSelected]);
if(singleOptions[singleOldSelected].enabled) drawCharacter(true, 10 + SPACING_X, singleOptions[singleOldSelected].posY, COLOR_WHITE, selected);
}
if(isMultiOption) drawString(true, 10, multiOptions[selectedOption].posY, COLOR_RED, multiOptionsText[selectedOption]);
else drawString(true, 10, singleOptions[singleSelected].posY, COLOR_RED, singleOptionsText[singleSelected]);
drawString(false, 10, 10, COLOR_BLACK, optionsDescription[oldSelectedOption]);
drawString(false, 10, 10, COLOR_WHITE, optionsDescription[selectedOption]);
}
else
{
//The selected option's status changed, print the 'x's accordingly
if(isMultiOption)
{
u32 oldEnabled = multiOptions[selectedOption].enabled;
drawCharacter(true, 10 + multiOptions[selectedOption].posXs[oldEnabled] * SPACING_X, multiOptions[selectedOption].posY, COLOR_BLACK, selected);
multiOptions[selectedOption].enabled = (oldEnabled == 3 || !multiOptions[selectedOption].posXs[oldEnabled + 1]) ? 0 : oldEnabled + 1;
if(selectedOption == BRIGHTNESS) updateBrightness(multiOptions[BRIGHTNESS].enabled);
}
else
{
bool oldEnabled = singleOptions[singleSelected].enabled;
singleOptions[singleSelected].enabled = !oldEnabled;
if(oldEnabled) drawCharacter(true, 10 + SPACING_X, singleOptions[singleSelected].posY, COLOR_BLACK, selected);
}
}
//In any case, if the current option is enabled (or a multiple choice option is selected) we must display a red 'x'
if(isMultiOption) drawCharacter(true, 10 + multiOptions[selectedOption].posXs[multiOptions[selectedOption].enabled] * SPACING_X, multiOptions[selectedOption].posY, COLOR_RED, selected);
else if(singleOptions[singleSelected].enabled) drawCharacter(true, 10 + SPACING_X, singleOptions[singleSelected].posY, COLOR_RED, selected);
}
//Parse and write the new configuration
configData.multiConfig = 0;
for(u32 i = 0; i < multiOptionsAmount; i++)
configData.multiConfig |= multiOptions[i].enabled << (i * 2);
configData.config = 0;
for(u32 i = 0; i < singleOptionsAmount; i++)
configData.config |= (singleOptions[i].enabled ? 1 : 0) << i;
writeConfig(true);
u32 newPinMode = MULTICONFIG(PIN);
if(newPinMode != 0) newPin(oldPinStatus && newPinMode == oldPinMode, newPinMode);
else if(oldPinStatus)
{
if(!fileDelete(PIN_FILE))
error("Unable to delete PIN file");
}
while(HID_PAD & PIN_BUTTONS);
wait(2000ULL);
}

77
arm9/source/config.h Normal file
View File

@@ -0,0 +1,77 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#pragma once
#include "types.h"
#define CONFIG(a) (((configData.config >> (a)) & 1) != 0)
#define MULTICONFIG(a) ((configData.multiConfig >> (2 * (a))) & 3)
#define BOOTCONFIG(a, b) ((configData.bootConfig >> (a)) & (b))
#define CONFIG_FILE "config.bin"
#define CONFIG_VERSIONMAJOR 2
#define CONFIG_VERSIONMINOR 3
#define BOOTCFG_NAND BOOTCONFIG(0, 7)
#define BOOTCFG_FIRM BOOTCONFIG(3, 7)
#define BOOTCFG_NOFORCEFLAG BOOTCONFIG(6, 1)
#define BOOTCFG_NTRCARDBOOT BOOTCONFIG(7, 1)
enum multiOptions
{
DEFAULTEMU = 0,
BRIGHTNESS,
SPLASH,
SPLASH_DURATION,
PIN,
NEWCPU
};
enum singleOptions
{
AUTOBOOTEMU = 0,
USEEMUFIRM,
LOADEXTFIRMSANDMODULES,
PATCHGAMES,
PATCHVERSTRING,
SHOWGBABOOT,
PATCHUNITINFO,
DISABLEARM11EXCHANDLERS
};
typedef enum ConfigurationStatus
{
DONT_CONFIGURE = 0,
MODIFY_CONFIGURATION,
CREATE_CONFIGURATION
} ConfigurationStatus;
extern CfgData configData;
bool readConfig(void);
void writeConfig(bool isConfigOptions);
void configMenu(bool oldPinStatus, u32 oldPinMode);

615
arm9/source/crypto.c Executable file
View File

@@ -0,0 +1,615 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Crypto libs from http://github.com/b1l1s/ctr
* kernel9Loader code originally adapted from https://github.com/Reisyukaku/ReiNand/blob/228c378255ba693133dec6f3368e14d386f2cde7/source/crypto.c#L233
* decryptNusFirm code adapted from https://github.com/mid-kid/CakesForeveryWan/blob/master/source/firm.c
* ctrNandWrite logic adapted from https://github.com/d0k3/GodMode9/blob/master/source/nand/nand.c
*/
#include "crypto.h"
#include "memory.h"
#include "emunand.h"
#include "strings.h"
#include "utils.h"
#include "alignedseqmemcpy.h"
#include "fatfs/sdmmc/sdmmc.h"
/****************************************************************
* Crypto libs
****************************************************************/
/* original version by megazig */
#ifndef __thumb__
#define BSWAP32(x) {\
__asm__\
(\
"eor r1, %1, %1, ror #16\n\t"\
"bic r1, r1, #0xFF0000\n\t"\
"mov %0, %1, ror #8\n\t"\
"eor %0, %0, r1, lsr #8\n\t"\
:"=r"(x)\
:"0"(x)\
:"r1"\
);\
};
#define ADD_u128_u32(u128_0, u128_1, u128_2, u128_3, u32_0) {\
__asm__\
(\
"adds %0, %4\n\t"\
"addcss %1, %1, #1\n\t"\
"addcss %2, %2, #1\n\t"\
"addcs %3, %3, #1\n\t"\
: "+r"(u128_0), "+r"(u128_1), "+r"(u128_2), "+r"(u128_3)\
: "r"(u32_0)\
: "cc"\
);\
}
#else
#define BSWAP32(x) {x = __builtin_bswap32(x);}
#define ADD_u128_u32(u128_0, u128_1, u128_2, u128_3, u32_0) {\
__asm__\
(\
"mov r4, #0\n\t"\
"add %0, %0, %4\n\t"\
"adc %1, %1, r4\n\t"\
"adc %2, %2, r4\n\t"\
"adc %3, %3, r4\n\t"\
: "+r"(u128_0), "+r"(u128_1), "+r"(u128_2), "+r"(u128_3)\
: "r"(u32_0)\
: "cc", "r4"\
);\
}
#endif /*__thumb__*/
static void aes_setkey(u8 keyslot, const void *key, u32 keyType, u32 mode)
{
u32 *key32 = (u32 *)key;
*REG_AESCNT = (*REG_AESCNT & ~(AES_CNT_INPUT_ENDIAN | AES_CNT_INPUT_ORDER)) | mode;
if(keyslot <= 3)
{
if((mode & AES_CNT_INPUT_ORDER) == AES_INPUT_TWLREVERSED)
{
REGs_AESTWLKEYS[keyslot][keyType][0] = key32[3];
REGs_AESTWLKEYS[keyslot][keyType][1] = key32[2];
REGs_AESTWLKEYS[keyslot][keyType][2] = key32[1];
REGs_AESTWLKEYS[keyslot][keyType][3] = key32[0];
}
else
{
REGs_AESTWLKEYS[keyslot][keyType][0] = key32[0];
REGs_AESTWLKEYS[keyslot][keyType][1] = key32[1];
REGs_AESTWLKEYS[keyslot][keyType][2] = key32[2];
REGs_AESTWLKEYS[keyslot][keyType][3] = key32[3];
}
}
else if(keyslot < 0x40)
{
*REG_AESKEYCNT = (*REG_AESKEYCNT >> 6 << 6) | keyslot | AES_KEYCNT_WRITE;
REG_AESKEYFIFO[keyType] = key32[0];
REG_AESKEYFIFO[keyType] = key32[1];
REG_AESKEYFIFO[keyType] = key32[2];
REG_AESKEYFIFO[keyType] = key32[3];
}
}
static void aes_use_keyslot(u8 keyslot)
{
if(keyslot > 0x3F)
return;
*REG_AESKEYSEL = keyslot;
*REG_AESCNT = *REG_AESCNT | 0x04000000; /* mystery bit */
}
static void aes_setiv(const void *iv, u32 mode)
{
const u32 *iv32 = (const u32 *)iv;
*REG_AESCNT = (*REG_AESCNT & ~(AES_CNT_INPUT_ENDIAN | AES_CNT_INPUT_ORDER)) | mode;
//Word order for IV can't be changed in REG_AESCNT and always default to reversed
if(mode & AES_INPUT_NORMAL)
{
REG_AESCTR[0] = iv32[3];
REG_AESCTR[1] = iv32[2];
REG_AESCTR[2] = iv32[1];
REG_AESCTR[3] = iv32[0];
}
else
{
REG_AESCTR[0] = iv32[0];
REG_AESCTR[1] = iv32[1];
REG_AESCTR[2] = iv32[2];
REG_AESCTR[3] = iv32[3];
}
}
static void aes_advctr(void *ctr, u32 val, u32 mode)
{
u32 *ctr32 = (u32 *)ctr;
int i;
if(mode & AES_INPUT_BE)
{
for(i = 0; i < 4; ++i) //Endian swap
BSWAP32(ctr32[i]);
}
if(mode & AES_INPUT_NORMAL)
{
ADD_u128_u32(ctr32[3], ctr32[2], ctr32[1], ctr32[0], val);
}
else
{
ADD_u128_u32(ctr32[0], ctr32[1], ctr32[2], ctr32[3], val);
}
if(mode & AES_INPUT_BE)
{
for(i = 0; i < 4; ++i) //Endian swap
BSWAP32(ctr32[i]);
}
}
static void aes_change_ctrmode(void *ctr, u32 fromMode, u32 toMode)
{
u32 *ctr32 = (u32 *)ctr;
int i;
if((fromMode ^ toMode) & AES_CNT_INPUT_ENDIAN)
{
for(i = 0; i < 4; ++i)
BSWAP32(ctr32[i]);
}
if((fromMode ^ toMode) & AES_CNT_INPUT_ORDER)
{
u32 temp = ctr32[0];
ctr32[0] = ctr32[3];
ctr32[3] = temp;
temp = ctr32[1];
ctr32[1] = ctr32[2];
ctr32[2] = temp;
}
}
static void aes_batch(void *dst, const void *src, u32 blockCount)
{
*REG_AESBLKCNT = blockCount << 16;
*REG_AESCNT |= AES_CNT_START;
const u32 *src32 = (const u32 *)src;
u32 *dst32 = (u32 *)dst;
u32 wbc = blockCount;
u32 rbc = blockCount;
while(rbc)
{
if(wbc && ((*REG_AESCNT & 0x1F) <= 0xC)) //There's space for at least 4 ints
{
*REG_AESWRFIFO = *src32++;
*REG_AESWRFIFO = *src32++;
*REG_AESWRFIFO = *src32++;
*REG_AESWRFIFO = *src32++;
wbc--;
}
if(rbc && ((*REG_AESCNT & (0x1F << 0x5)) >= (0x4 << 0x5))) //At least 4 ints available for read
{
*dst32++ = *REG_AESRDFIFO;
*dst32++ = *REG_AESRDFIFO;
*dst32++ = *REG_AESRDFIFO;
*dst32++ = *REG_AESRDFIFO;
rbc--;
}
}
}
static void aes(void *dst, const void *src, u32 blockCount, void *iv, u32 mode, u32 ivMode)
{
*REG_AESCNT = mode |
AES_CNT_INPUT_ORDER | AES_CNT_OUTPUT_ORDER |
AES_CNT_INPUT_ENDIAN | AES_CNT_OUTPUT_ENDIAN |
AES_CNT_FLUSH_READ | AES_CNT_FLUSH_WRITE;
u32 blocks;
while(blockCount != 0)
{
if((mode & AES_ALL_MODES) != AES_ECB_ENCRYPT_MODE
&& (mode & AES_ALL_MODES) != AES_ECB_DECRYPT_MODE)
aes_setiv(iv, ivMode);
blocks = (blockCount >= 0xFFFF) ? 0xFFFF : blockCount;
//Save the last block for the next decryption CBC batch's iv
if((mode & AES_ALL_MODES) == AES_CBC_DECRYPT_MODE)
{
memcpy(iv, src + (blocks - 1) * AES_BLOCK_SIZE, AES_BLOCK_SIZE);
aes_change_ctrmode(iv, AES_INPUT_BE | AES_INPUT_NORMAL, ivMode);
}
//Process the current batch
aes_batch(dst, src, blocks);
//Save the last block for the next encryption CBC batch's iv
if((mode & AES_ALL_MODES) == AES_CBC_ENCRYPT_MODE)
{
memcpy(iv, dst + (blocks - 1) * AES_BLOCK_SIZE, AES_BLOCK_SIZE);
aes_change_ctrmode(iv, AES_INPUT_BE | AES_INPUT_NORMAL, ivMode);
}
//Advance counter for CTR mode
else if((mode & AES_ALL_MODES) == AES_CTR_MODE)
aes_advctr(iv, blocks, ivMode);
src += blocks * AES_BLOCK_SIZE;
dst += blocks * AES_BLOCK_SIZE;
blockCount -= blocks;
}
}
static void sha_wait_idle()
{
while(*REG_SHA_CNT & 1);
}
void sha(void *res, const void *src, u32 size, u32 mode)
{
sha_wait_idle();
*REG_SHA_CNT = mode | SHA_CNT_OUTPUT_ENDIAN | SHA_NORMAL_ROUND;
const u8 *src8 = (const u8 *)src;
while(size >= 0x40)
{
sha_wait_idle();
alignedseqmemcpy((void *)REG_SHA_INFIFO, src8, 0x40);
src8 += 0x40;
size -= 0x40;
}
sha_wait_idle();
alignedseqmemcpy((void *)REG_SHA_INFIFO, src8, size);
*REG_SHA_CNT = (*REG_SHA_CNT & ~SHA_NORMAL_ROUND) | SHA_FINAL_ROUND;
while(*REG_SHA_CNT & SHA_FINAL_ROUND);
sha_wait_idle();
u32 hashSize = SHA_256_HASH_SIZE;
if(mode == SHA_224_MODE)
hashSize = SHA_224_HASH_SIZE;
else if(mode == SHA_1_MODE)
hashSize = SHA_1_HASH_SIZE;
alignedseqmemcpy(res, (void *)REG_SHA_HASH, hashSize);
}
/*****************************************************************/
__attribute__((aligned(4))) static u8 nandCtr[AES_BLOCK_SIZE];
static u8 nandSlot;
static u32 fatStart = 0;
FirmwareSource firmSource = FIRMWARE_SYSNAND;
__attribute__((aligned(4))) static const u8 key1s[2][AES_BLOCK_SIZE] = {
{0x07, 0x29, 0x44, 0x38, 0xF8, 0xC9, 0x75, 0x93, 0xAA, 0x0E, 0x4A, 0xB4, 0xAE, 0x84, 0xC1, 0xD8},
{0xA2, 0xF4, 0x00, 0x3C, 0x7A, 0x95, 0x10, 0x25, 0xDF, 0x4E, 0x9E, 0x74, 0xE3, 0x0C, 0x92, 0x99}
},
key2s[2][AES_BLOCK_SIZE] = {
{0x42, 0x3F, 0x81, 0x7A, 0x23, 0x52, 0x58, 0x31, 0x6E, 0x75, 0x8E, 0x3A, 0x39, 0x43, 0x2E, 0xD0},
{0xFF, 0x77, 0xA0, 0x9A, 0x99, 0x81, 0xE9, 0x48, 0xEC, 0x51, 0xC9, 0x32, 0x5D, 0x14, 0xEC, 0x25}
};
int ctrNandInit(void)
{
__attribute__((aligned(4))) u8 cid[AES_BLOCK_SIZE],
shaSum[SHA_256_HASH_SIZE];
sdmmc_get_cid(1, (u32 *)cid);
sha(shaSum, cid, sizeof(cid), SHA_256_MODE);
memcpy(nandCtr, shaSum, sizeof(nandCtr));
nandSlot = ISN3DS ? 0x05 : 0x04;
int result;
u8 __attribute__((aligned(4))) temp[0x200];
//Read NCSD header
result = firmSource == FIRMWARE_SYSNAND ? sdmmc_nand_readsectors(0, 1, temp) : sdmmc_sdcard_readsectors(emuHeader, 1, temp);
if(!result)
{
u32 partitionNum = 1; //TWL partitions need to be first
for(u8 *partitionId = temp + 0x111; *partitionId != 1; partitionId++, partitionNum++);
u32 ctrMbrOffset = *((u32 *)(temp + 0x120) + (2 * partitionNum));
//Read CTR MBR
result = ctrNandRead(ctrMbrOffset, 1, temp);
//Calculate final CTRNAND FAT offset
if(!result) fatStart = ctrMbrOffset + *(u32 *)(temp + 0x1C6);
}
return result;
}
int ctrNandRead(u32 sector, u32 sectorCount, u8 *outbuf)
{
__attribute__((aligned(4))) u8 tmpCtr[sizeof(nandCtr)];
memcpy(tmpCtr, nandCtr, sizeof(nandCtr));
aes_advctr(tmpCtr, ((sector + fatStart) * 0x200) / AES_BLOCK_SIZE, AES_INPUT_BE | AES_INPUT_NORMAL);
//Read
int result;
if(firmSource == FIRMWARE_SYSNAND)
result = sdmmc_nand_readsectors(sector + fatStart, sectorCount, outbuf);
else
{
sector += emuOffset;
result = sdmmc_sdcard_readsectors(sector + fatStart, sectorCount, outbuf);
}
//Decrypt
aes_use_keyslot(nandSlot);
aes(outbuf, outbuf, sectorCount * 0x200 / AES_BLOCK_SIZE, tmpCtr, AES_CTR_MODE, AES_INPUT_BE | AES_INPUT_NORMAL);
return result;
}
int ctrNandWrite(u32 sector, u32 sectorCount, const u8 *inbuf)
{
u8 *buffer = (u8 *)0xFFF00000;
u32 bufferSize = 0x4000;
__attribute__((aligned(4))) u8 tmpCtr[sizeof(nandCtr)];
memcpy(tmpCtr, nandCtr, sizeof(nandCtr));
aes_advctr(tmpCtr, ((sector + fatStart) * 0x200) / AES_BLOCK_SIZE, AES_INPUT_BE | AES_INPUT_NORMAL);
aes_use_keyslot(nandSlot);
int result = 0;
for(u32 tempSector = 0; tempSector < sectorCount && !result; tempSector += bufferSize / 0x200)
{
u32 tempCount = (bufferSize / 0x200) < (sectorCount - tempSector) ? (bufferSize / 0x200) : (sectorCount - tempSector);
memcpy(buffer, inbuf + (tempSector * 0x200), tempCount * 0x200);
//Encrypt
aes(buffer, buffer, tempCount * 0x200 / AES_BLOCK_SIZE, tmpCtr, AES_CTR_MODE, AES_INPUT_BE | AES_INPUT_NORMAL);
//Write
result = sdmmc_nand_writesectors(tempSector + sector + fatStart, tempCount, buffer);
}
return result;
}
u32 decryptExeFs(Cxi *cxi)
{
if(memcmp(cxi->ncch.magic, "NCCH", 4) != 0) return 0;
if(cxi->ncch.exeFsOffset != 5) return 0;
u8 *exeFsOffset = (u8 *)cxi + 6 * 0x200;
u32 exeFsSize = (cxi->ncch.exeFsSize - 1) * 0x200;
if(exeFsSize > 0x400000) return 0;
__attribute__((aligned(4))) u8 ncchCtr[AES_BLOCK_SIZE] = {0};
for(u32 i = 0; i < 8; i++)
ncchCtr[7 - i] = cxi->ncch.partitionId[i];
ncchCtr[8] = 2;
aes_setkey(0x2C, cxi, AES_KEYY, AES_INPUT_BE | AES_INPUT_NORMAL);
aes_advctr(ncchCtr, 0x200 / AES_BLOCK_SIZE, AES_INPUT_BE | AES_INPUT_NORMAL);
aes_use_keyslot(0x2C);
aes(cxi, exeFsOffset, exeFsSize / AES_BLOCK_SIZE, ncchCtr, AES_CTR_MODE, AES_INPUT_BE | AES_INPUT_NORMAL);
return memcmp(cxi, "FIRM", 4) == 0 ? exeFsSize : 0;
}
u32 decryptNusFirm(const Ticket *ticket, Cxi *cxi, u32 ncchSize)
{
if(memcmp(ticket->sigIssuer, "Root", 4) != 0) return 0;
__attribute__((aligned(4))) static const u8 keyY0x3D[AES_BLOCK_SIZE] = {0x0C, 0x76, 0x72, 0x30, 0xF0, 0x99, 0x8F, 0x1C, 0x46, 0x82, 0x82, 0x02, 0xFA, 0xAC, 0xBE, 0x4C};
__attribute__((aligned(4))) u8 titleKey[AES_BLOCK_SIZE],
cetkIv[AES_BLOCK_SIZE] = {0};
memcpy(titleKey, ticket->titleKey, sizeof(titleKey));
memcpy(cetkIv, ticket->titleId, sizeof(ticket->titleId));
aes_setkey(0x3D, keyY0x3D, AES_KEYY, AES_INPUT_BE | AES_INPUT_NORMAL);
aes_use_keyslot(0x3D);
aes(titleKey, titleKey, 1, cetkIv, AES_CBC_DECRYPT_MODE, AES_INPUT_BE | AES_INPUT_NORMAL);
__attribute__((aligned(4))) u8 ncchIv[AES_BLOCK_SIZE] = {0};
aes_setkey(0x16, titleKey, AES_KEYNORMAL, AES_INPUT_BE | AES_INPUT_NORMAL);
aes_use_keyslot(0x16);
aes(cxi, cxi, ncchSize / AES_BLOCK_SIZE, ncchIv, AES_CBC_DECRYPT_MODE, AES_INPUT_BE | AES_INPUT_NORMAL);
return decryptExeFs(cxi);
}
static inline void twlConsoleInfoInit(void)
{
u64 twlConsoleId = ISDEVUNIT ? OTP_DEVCONSOLEID : (0x80000000ULL | (*(vu64 *)0x01FFB808 ^ 0x8C267B7B358A6AFULL));
CFG_TWLUNITINFO = CFG_UNITINFO;
OTP_TWLCONSOLEID = twlConsoleId;
*REG_AESCNT = 0;
vu32 *k3X = REGs_AESTWLKEYS[3][1],
*k1X = REGs_AESTWLKEYS[1][1];
k3X[0] = (u32)twlConsoleId;
k3X[3] = (u32)(twlConsoleId >> 32);
k1X[2] = (u32)(twlConsoleId >> 32);
k1X[3] = (u32)twlConsoleId;
aes_setkey(2, (u8 *)0x01FFD398, AES_KEYX, AES_INPUT_TWLNORMAL);
if(CFG_TWLUNITINFO != 0)
{
__attribute__((aligned(4))) static const u8 key2YDev[AES_BLOCK_SIZE] = {0x3B, 0x06, 0x86, 0x57, 0x33, 0x04, 0x88, 0x11, 0x49, 0x04, 0x6B, 0x33, 0x12, 0x02, 0xAC, 0xF3},
key3YDev[AES_BLOCK_SIZE] = {0xAA, 0xBF, 0x76, 0xF1, 0x7A, 0xB8, 0xE8, 0x66, 0x97, 0x64, 0x6A, 0x26, 0x05, 0x00, 0xA0, 0xE1};
k3X[1] = 0xEE7A4B1E;
k3X[2] = 0xAF42C08B;
aes_setkey(2, key2YDev, AES_KEYY, AES_INPUT_TWLNORMAL);
aes_setkey(3, key3YDev, AES_KEYY, AES_INPUT_TWLNORMAL);
}
else
{
u32 last3YWord = 0xE1A00005;
__attribute__((aligned(4))) u8 key3YRetail[AES_BLOCK_SIZE];
memcpy(key3YRetail, (u8 *)0x01FFD3C8, 12);
memcpy(key3YRetail + 12, &last3YWord, 4);
k3X[1] = *(vu32 *)0x01FFD3A8; //"NINT"
k3X[2] = *(vu32 *)0x01FFD3AC; //"ENDO"
aes_setkey(2, (u8 *)0x01FFD220, AES_KEYY, AES_INPUT_TWLNORMAL);
aes_setkey(3, key3YRetail, AES_KEYY, AES_INPUT_TWLNORMAL);
}
}
void setupKeyslots(void)
{
//Setup 0x24 KeyY
__attribute__((aligned(4))) static const u8 keyY0x24[AES_BLOCK_SIZE] = {0x74, 0xCA, 0x07, 0x48, 0x84, 0xF4, 0x22, 0x8D, 0xEB, 0x2A, 0x1C, 0xA7, 0x2D, 0x28, 0x77, 0x62};
aes_setkey(0x24, keyY0x24, AES_KEYY, AES_INPUT_BE | AES_INPUT_NORMAL);
//Setup 0x25 KeyX and 0x2F KeyY
__attribute__((aligned(4))) static const u8 keyX0x25s[2][AES_BLOCK_SIZE] = {
{0xCE, 0xE7, 0xD8, 0xAB, 0x30, 0xC0, 0x0D, 0xAE, 0x85, 0x0E, 0xF5, 0xE3, 0x82, 0xAC, 0x5A, 0xF3},
{0x81, 0x90, 0x7A, 0x4B, 0x6F, 0x1B, 0x47, 0x32, 0x3A, 0x67, 0x79, 0x74, 0xCE, 0x4A, 0xD7, 0x1B}
},
keyY0x2Fs[2][AES_BLOCK_SIZE] = {
{0xC3, 0x69, 0xBA, 0xA2, 0x1E, 0x18, 0x8A, 0x88, 0xA9, 0xAA, 0x94, 0xE5, 0x50, 0x6A, 0x9F, 0x16},
{0x73, 0x25, 0xC4, 0xEB, 0x14, 0x3A, 0x0D, 0x5F, 0x5D, 0xB6, 0xE5, 0xC5, 0x7A, 0x21, 0x95, 0xAC}
};
aes_setkey(0x25, keyX0x25s[ISDEVUNIT ? 1 : 0], AES_KEYX, AES_INPUT_BE | AES_INPUT_NORMAL);
aes_setkey(0x2F, keyY0x2Fs[ISDEVUNIT ? 1 : 0], AES_KEYY, AES_INPUT_BE | AES_INPUT_NORMAL);
if(ISN3DS)
{
//Setup 0x05 KeyY
__attribute__((aligned(4))) static const u8 keyY0x5[AES_BLOCK_SIZE] = {0x4D, 0x80, 0x4F, 0x4E, 0x99, 0x90, 0x19, 0x46, 0x13, 0xA2, 0x04, 0xAC, 0x58, 0x44, 0x60, 0xBE};
aes_setkey(0x05, keyY0x5, AES_KEYY, AES_INPUT_BE | AES_INPUT_NORMAL);
}
//Setup TWL keys
twlConsoleInfoInit();
__attribute__((aligned(4))) u8 keyBlocks[2][AES_BLOCK_SIZE] = {
{0xA4, 0x8D, 0xE4, 0xF1, 0x0B, 0x36, 0x44, 0xAA, 0x90, 0x31, 0x28, 0xFF, 0x4D, 0xCA, 0x76, 0xDF},
{0xDD, 0xDA, 0xA4, 0xC6, 0x2C, 0xC4, 0x50, 0xE9, 0xDA, 0xB6, 0x9B, 0x0D, 0x9D, 0x2A, 0x21, 0x98}
}, decKey[AES_BLOCK_SIZE];
//Initialize Key 0x18
aes_setkey(0x11, key1s[ISDEVUNIT ? 1 : 0], AES_KEYNORMAL, AES_INPUT_BE | AES_INPUT_NORMAL);
aes_use_keyslot(0x11);
aes(decKey, keyBlocks[0], 1, NULL, AES_ECB_DECRYPT_MODE, 0);
aes_setkey(0x18, decKey, AES_KEYX, AES_INPUT_BE | AES_INPUT_NORMAL);
//Initialize Key 0x19-0x1F
aes_setkey(0x11, key2s[ISDEVUNIT ? 1 : 0], AES_KEYNORMAL, AES_INPUT_BE | AES_INPUT_NORMAL);
aes_use_keyslot(0x11);
for(u8 slot = 0x19; slot < 0x20; slot++, keyBlocks[1][0xF]++)
{
aes(decKey, keyBlocks[1], 1, NULL, AES_ECB_DECRYPT_MODE, 0);
aes_setkey(slot, decKey, AES_KEYX, AES_INPUT_BE | AES_INPUT_NORMAL);
}
}
void kernel9Loader(Arm9Bin *arm9Section)
{
//Determine the kernel9loader version
u32 k9lVersion;
switch(arm9Section->magic[3])
{
case 0xFF:
k9lVersion = 0;
break;
case '1':
k9lVersion = 1;
break;
default:
k9lVersion = 2;
}
u32 *startOfArm9Bin = (u32 *)((u8 *)arm9Section + 0x800);
if(*startOfArm9Bin == 0x47704770 || *startOfArm9Bin == 0xB0862000) return; //Already decrypted
aes_setkey(0x11, k9lVersion == 2 ? key2s[ISDEVUNIT ? 1 : 0] : key1s[ISDEVUNIT ? 1 : 0], AES_KEYNORMAL, AES_INPUT_BE | AES_INPUT_NORMAL);
u8 arm9BinSlot = k9lVersion == 0 ? 0x15 : 0x16;
//Set keyX
__attribute__((aligned(4))) u8 keyX[AES_BLOCK_SIZE];
aes_use_keyslot(0x11);
aes(keyX, k9lVersion == 0 ? arm9Section->keyX : arm9Section->slot0x16keyX, 1, NULL, AES_ECB_DECRYPT_MODE, 0);
aes_setkey(arm9BinSlot, keyX, AES_KEYX, AES_INPUT_BE | AES_INPUT_NORMAL);
//Set keyY
__attribute__((aligned(4))) u8 keyY[AES_BLOCK_SIZE];
memcpy(keyY, arm9Section->keyY, sizeof(keyY));
aes_setkey(arm9BinSlot, keyY, AES_KEYY, AES_INPUT_BE | AES_INPUT_NORMAL);
//Set CTR
__attribute__((aligned(4))) u8 arm9BinCtr[AES_BLOCK_SIZE];
memcpy(arm9BinCtr, arm9Section->ctr, sizeof(arm9BinCtr));
//Decrypt ARM9 binary
aes_use_keyslot(arm9BinSlot);
aes(startOfArm9Bin, startOfArm9Bin, decAtoi(arm9Section->size, sizeof(arm9Section->size)) / AES_BLOCK_SIZE, arm9BinCtr, AES_CTR_MODE, AES_INPUT_BE | AES_INPUT_NORMAL);
if(*startOfArm9Bin != 0x47704770 && *startOfArm9Bin != 0xB0862000) error("Failed to decrypt the ARM9 binary.");
}
void computePinHash(u8 *outbuf, const u8 *inbuf)
{
__attribute__((aligned(4))) u8 cid[AES_BLOCK_SIZE],
cipherText[AES_BLOCK_SIZE];
sdmmc_get_cid(1, (u32 *)cid);
aes_use_keyslot(0x04); //Console-unique keyslot whose keys are set by the ARM9 bootROM
aes(cipherText, inbuf, 1, cid, AES_CBC_ENCRYPT_MODE, AES_INPUT_BE | AES_INPUT_NORMAL);
sha(outbuf, cipherText, sizeof(cipherText), SHA_256_MODE);
}

124
arm9/source/crypto.h Executable file
View File

@@ -0,0 +1,124 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Crypto libs from http://github.com/b1l1s/ctr
* kernel9Loader code originally adapted from https://github.com/Reisyukaku/ReiNand/blob/228c378255ba693133dec6f3368e14d386f2cde7/source/crypto.c#L233
* decryptNusFirm code adapted from https://github.com/mid-kid/CakesForeveryWan/blob/master/source/firm.c
* ctrNandWrite logic adapted from https://github.com/d0k3/GodMode9/blob/master/source/nand/nand.c
*/
#pragma once
#include "types.h"
/**************************AES****************************/
#define REG_AESCNT ((vu32 *)0x10009000)
#define REG_AESBLKCNT ((vu32 *)0x10009004)
#define REG_AESWRFIFO ((vu32 *)0x10009008)
#define REG_AESRDFIFO ((vu32 *)0x1000900C)
#define REG_AESKEYSEL ((vu8 *)0x10009010)
#define REG_AESKEYCNT ((vu8 *)0x10009011)
#define REG_AESCTR ((vu32 *)0x10009020)
#define REG_AESKEYFIFO ((vu32 *)0x10009100)
#define REG_AESKEYXFIFO ((vu32 *)0x10009104)
#define REG_AESKEYYFIFO ((vu32 *)0x10009108)
#define REGs_AESTWLKEYS (*((vu32 (*)[4][3][4])0x10009040))
#define AES_CCM_DECRYPT_MODE (0u << 27)
#define AES_CCM_ENCRYPT_MODE (1u << 27)
#define AES_CTR_MODE (2u << 27)
#define AES_CTR_MODE (2u << 27)
#define AES_CBC_DECRYPT_MODE (4u << 27)
#define AES_CBC_ENCRYPT_MODE (5u << 27)
#define AES_ECB_DECRYPT_MODE (6u << 27)
#define AES_ECB_ENCRYPT_MODE (7u << 27)
#define AES_ALL_MODES (7u << 27)
#define AES_CNT_START 0x80000000
#define AES_CNT_INPUT_ORDER 0x02000000
#define AES_CNT_OUTPUT_ORDER 0x01000000
#define AES_CNT_INPUT_ENDIAN 0x00800000
#define AES_CNT_OUTPUT_ENDIAN 0x00400000
#define AES_CNT_FLUSH_READ 0x00000800
#define AES_CNT_FLUSH_WRITE 0x00000400
#define AES_INPUT_BE (AES_CNT_INPUT_ENDIAN)
#define AES_INPUT_LE 0
#define AES_INPUT_NORMAL (AES_CNT_INPUT_ORDER)
#define AES_INPUT_REVERSED 0
#define AES_INPUT_TWLNORMAL 0
#define AES_INPUT_TWLREVERSED (AES_CNT_INPUT_ORDER)
#define AES_BLOCK_SIZE 0x10
#define AES_KEYCNT_WRITE (1 << 0x7)
#define AES_KEYNORMAL 0
#define AES_KEYX 1
#define AES_KEYY 2
/**************************SHA****************************/
#define REG_SHA_CNT ((vu32 *)0x1000A000)
#define REG_SHA_BLKCNT ((vu32 *)0x1000A004)
#define REG_SHA_HASH ((vu32 *)0x1000A040)
#define REG_SHA_INFIFO ((vu32 *)0x1000A080)
#define SHA_CNT_STATE 0x00000003
#define SHA_CNT_UNK2 0x00000004
#define SHA_CNT_OUTPUT_ENDIAN 0x00000008
#define SHA_CNT_MODE 0x00000030
#define SHA_CNT_ENABLE 0x00010000
#define SHA_CNT_ACTIVE 0x00020000
#define SHA_HASH_READY 0x00000000
#define SHA_NORMAL_ROUND 0x00000001
#define SHA_FINAL_ROUND 0x00000002
#define SHA_OUTPUT_BE SHA_CNT_OUTPUT_ENDIAN
#define SHA_OUTPUT_LE 0
#define SHA_256_MODE 0
#define SHA_224_MODE 0x00000010
#define SHA_1_MODE 0x00000020
#define SHA_256_HASH_SIZE (256 / 8)
#define SHA_224_HASH_SIZE (224 / 8)
#define SHA_1_HASH_SIZE (160 / 8)
extern FirmwareSource firmSource;
void sha(void *res, const void *src, u32 size, u32 mode);
int ctrNandInit(void);
int ctrNandRead(u32 sector, u32 sectorCount, u8 *outbuf);
int ctrNandWrite(u32 sector, u32 sectorCount, const u8 *inbuf);
u32 decryptExeFs(Cxi *cxi);
u32 decryptNusFirm(const Ticket *ticket, Cxi *cxi, u32 ncchSize);
void setupKeyslots(void);
void kernel9Loader(Arm9Bin *arm9Section);
void computePinHash(u8 *outbuf, const u8 *inbuf);

128
arm9/source/draw.c Normal file
View File

@@ -0,0 +1,128 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Code to print to the screen by mid-kid @CakesFW
* https://github.com/mid-kid/CakesForeveryWan
*/
#include "draw.h"
#include "strings.h"
#include "screen.h"
#include "utils.h"
#include "fs.h"
#include "fmt.h"
#include "font.h"
#include "config.h"
bool loadSplash(void)
{
static const char *topSplashFile = "splash.bin",
*bottomSplashFile = "splashbottom.bin";
bool isTopSplashValid = getFileSize(topSplashFile) == SCREEN_TOP_FBSIZE,
isBottomSplashValid = getFileSize(bottomSplashFile) == SCREEN_BOTTOM_FBSIZE;
//Don't delay boot nor init the screens if no splash images or invalid splash images are on the SD
if(!isTopSplashValid && !isBottomSplashValid) return false;
initScreens();
if(isTopSplashValid) isTopSplashValid = fileRead(fbs[1].top_left, topSplashFile, SCREEN_TOP_FBSIZE) == SCREEN_TOP_FBSIZE;
if(isBottomSplashValid) isBottomSplashValid = fileRead(fbs[1].bottom, bottomSplashFile, SCREEN_BOTTOM_FBSIZE) == SCREEN_BOTTOM_FBSIZE;
if(!isTopSplashValid && !isBottomSplashValid) return false;
swapFramebuffers(true);
u32 durationIndex = MULTICONFIG(SPLASH_DURATION);
wait(1000ULL + (durationIndex * 2000ULL));
return true;
}
void drawCharacter(bool isTopScreen, u32 posX, u32 posY, u32 color, char character)
{
u8 *select = isTopScreen ? fbs[0].top_left : fbs[0].bottom;
for(u32 y = 0; y < 8; y++)
{
char charPos = font[character * 8 + y];
for(u32 x = 0; x < 8; x++)
if(((charPos >> (7 - x)) & 1) == 1)
{
u32 screenPos = (posX * SCREEN_HEIGHT * 3 + (SCREEN_HEIGHT - y - posY - 1) * 3) + x * 3 * SCREEN_HEIGHT;
select[screenPos] = color >> 16;
select[screenPos + 1] = color >> 8;
select[screenPos + 2] = color;
}
}
}
u32 drawString(bool isTopScreen, u32 posX, u32 posY, u32 color, const char *string)
{
for(u32 i = 0, line_i = 0; i < strlen(string); i++)
switch(string[i])
{
case '\n':
posY += SPACING_Y;
line_i = 0;
break;
case '\t':
line_i += 2;
break;
default:
//Make sure we never get out of the screen
if(line_i >= ((isTopScreen ? SCREEN_TOP_WIDTH : SCREEN_BOTTOM_WIDTH) - posX) / SPACING_X)
{
posY += SPACING_Y;
line_i = 1; //Little offset so we know the same string continues
if(string[i] == ' ') break; //Spaces at the start look weird
}
drawCharacter(isTopScreen, posX + line_i * SPACING_X, posY, color, string[i]);
line_i++;
break;
}
return posY;
}
u32 drawFormattedString(bool isTopScreen, u32 posX, u32 posY, u32 color, const char *fmt, ...)
{
char buf[DRAW_MAX_FORMATTED_STRING_SIZE + 1];
va_list args;
va_start(args, fmt);
vsprintf(buf, fmt, args);
va_end(args);
return drawString(isTopScreen, posX, posY, color, buf);
}

50
arm9/source/draw.h Normal file
View File

@@ -0,0 +1,50 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Code to print to the screen by mid-kid @CakesFW
* https://github.com/mid-kid/CakesForeveryWan/
*/
#pragma once
#include "types.h"
#define SPACING_Y 10
#define SPACING_X 8
#define COLOR_TITLE 0xFF9900
#define COLOR_WHITE 0xFFFFFF
#define COLOR_RED 0x0000FF
#define COLOR_BLACK 0x000000
#define COLOR_YELLOW 0x00FFFF
#define DRAW_MAX_FORMATTED_STRING_SIZE 512
bool loadSplash(void);
void drawCharacter(bool isTopScreen, u32 posX, u32 posY, u32 color, char character);
u32 drawString(bool isTopScreen, u32 posX, u32 posY, u32 color, const char *string);
u32 drawFormattedString(bool isTopScreen, u32 posX, u32 posY, u32 color, const char *fmt, ...);

218
arm9/source/emunand.c Normal file
View File

@@ -0,0 +1,218 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Code for locating the SDMMC struct by Normmatt
*/
#include "emunand.h"
#include "memory.h"
#include "utils.h"
#include "fatfs/sdmmc/sdmmc.h"
#include "large_patches.h"
u32 emuOffset,
emuHeader;
void locateEmuNand(FirmwareSource *nandType)
{
static u8 __attribute__((aligned(4))) temp[0x200];
static u32 nandSize = 0,
fatStart;
if(!nandSize)
{
nandSize = getMMCDevice(0)->total_size;
sdmmc_sdcard_readsectors(0, 1, temp);
fatStart = *(u32 *)(temp + 0x1C6); //First sector of the FAT partition
}
for(u32 i = 0; i < 3; i++)
{
static const u32 roundedMinsizes[] = {0x1D8000, 0x26E000};
u32 nandOffset;
switch(i)
{
case 1:
nandOffset = ROUND_TO_4MB(nandSize + 1); //"Default" layout
break;
case 2:
nandOffset = roundedMinsizes[ISN3DS ? 1 : 0]; //"Minsize" layout
break;
case 0:
nandOffset = *nandType == FIRMWARE_EMUNAND ? 0 : (nandSize > 0x200000 ? 0x400000 : 0x200000); //"Legacy" layout
break;
}
if(*nandType != FIRMWARE_EMUNAND) nandOffset *= ((u32)*nandType - 1);
if(fatStart >= nandOffset + roundedMinsizes[ISN3DS ? 1 : 0])
{
//Check for RedNAND
if(!sdmmc_sdcard_readsectors(nandOffset + 1, 1, temp) && memcmp(temp + 0x100, "NCSD", 4) == 0)
{
emuOffset = nandOffset + 1;
emuHeader = nandOffset + 1;
return;
}
//Check for Gateway EmuNAND
else if(i != 2 && !sdmmc_sdcard_readsectors(nandOffset + nandSize, 1, temp) && memcmp(temp + 0x100, "NCSD", 4) == 0)
{
emuOffset = nandOffset;
emuHeader = nandOffset + nandSize;
return;
}
}
if(*nandType == FIRMWARE_EMUNAND) break;
}
//Fallback to the first EmuNAND if there's no second/third/fourth one, or to SysNAND if there isn't any
if(*nandType != FIRMWARE_EMUNAND)
{
*nandType = FIRMWARE_EMUNAND;
locateEmuNand(nandType);
}
else *nandType = FIRMWARE_SYSNAND;
}
static inline bool getFreeK9Space(u8 *pos, u32 size, u8 **freeK9Space)
{
static const u8 pattern[] = {0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00};
//Looking for the last free space before Process9
*freeK9Space = memsearch(pos, pattern, size, sizeof(pattern));
if(*freeK9Space == NULL || (u32)(pos + size - *freeK9Space) < 0x455 + emunandPatchSize ||
*(u32 *)(*freeK9Space + 0x455 + emunandPatchSize - 4) != 0xFFFFFFFF) return false;
*freeK9Space += 0x455;
return true;
}
static inline u32 getOldSdmmc(u32 *sdmmc, u32 firmVersion)
{
switch(firmVersion)
{
case 0x18:
*sdmmc = 0x080D91D8;
break;
case 0x1D:
case 0x1F:
*sdmmc = 0x080D8CD0;
break;
default:
return 1;
}
return 0;
}
static inline u32 getSdmmc(u8 *pos, u32 size, u32 *sdmmc)
{
//Look for struct code
static const u8 pattern[] = {0x21, 0x20, 0x18, 0x20};
const u8 *off = memsearch(pos, pattern, size, sizeof(pattern));
if(off == NULL) return 1;
*sdmmc = *(u32 *)(off + 9) + *(u32 *)(off + 0xD);
return 0;
}
static inline u32 patchNandRw(u8 *pos, u32 size, u32 branchOffset)
{
//Look for read/write code
static const u8 pattern[] = {0x1E, 0x00, 0xC8, 0x05};
u16 *readOffset = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
if(readOffset == NULL) return 1;
readOffset -= 3;
u16 *writeOffset = (u16 *)memsearch((u8 *)(readOffset + 5), pattern, 0x100, sizeof(pattern));
if(writeOffset == NULL) return 1;
writeOffset -= 3;
*readOffset = *writeOffset = 0x4C00;
readOffset[1] = writeOffset[1] = 0x47A0;
((u32 *)writeOffset)[1] = ((u32 *)readOffset)[1] = branchOffset;
return 0;
}
static inline u32 patchMpu(u8 *pos, u32 size)
{
//Look for MPU pattern
static const u8 pattern[] = {0x03, 0x00, 0x24, 0x00};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
if(off == NULL) return 1;
off[1] = 0x0036;
off[0xC] = off[0x12] = 0x0603;
return 0;
}
u32 patchEmuNand(u8 *arm9Section, u32 kernel9Size, u8 *process9Offset, u32 process9Size, u8 *kernel9Address, u32 firmVersion)
{
u8 *freeK9Space;
if(!getFreeK9Space(arm9Section, kernel9Size, &freeK9Space)) return 1;
u32 ret = 0;
//Add the data of the found EmuNAND
emunandPatchNandOffset = emuOffset;
emunandPatchNcsdHeaderOffset = emuHeader;
//Find and add the SDMMC struct
u32 sdmmc;
ret += !ISN3DS && firmVersion < 0x25 ? getOldSdmmc(&sdmmc, firmVersion) : getSdmmc(process9Offset, process9Size, &sdmmc);
if(!ret) emunandPatchSdmmcStructPtr = sdmmc;
//Copy EmuNAND code
memcpy(freeK9Space, emunandPatch, emunandPatchSize);
//Add EmuNAND hooks
u32 branchOffset = (u32)(freeK9Space - arm9Section + kernel9Address);
ret += patchNandRw(process9Offset, process9Size, branchOffset);
//Set MPU
ret += patchMpu(arm9Section, kernel9Size);
return ret;
}

41
arm9/source/emunand.h Normal file
View File

@@ -0,0 +1,41 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Code for locating the SDMMC struct by Normmatt
*/
#pragma once
#include "types.h"
#define ROUND_TO_4MB(a) (((a) + 0x2000 - 1) & (~(0x2000 - 1)))
extern u32 emuOffset,
emuHeader;
void locateEmuNand(FirmwareSource *nandType);
u32 patchEmuNand(u8 *arm9Section, u32 kernel9Size, u8 *process9Offset, u32 process9Size, u8 *kernel9Address, u32 firmVersion);

196
arm9/source/exceptions.c Normal file
View File

@@ -0,0 +1,196 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "exceptions.h"
#include "fs.h"
#include "strings.h"
#include "memory.h"
#include "screen.h"
#include "draw.h"
#include "utils.h"
#include "fmt.h"
#include "buttons.h"
#include "arm9_exception_handlers.h"
void installArm9Handlers(void)
{
vu32 *dstVeneers = (vu32 *)0x08000000;
for(u32 i = 0; i < 6; i++)
{
if(arm9ExceptionHandlerAddressTable[i] != 0)
{
dstVeneers[2 * i] = 0xE51FF004;
dstVeneers[2 * i + 1] = arm9ExceptionHandlerAddressTable[i];
}
}
}
void detectAndProcessExceptionDumps(void)
{
volatile ExceptionDumpHeader *dumpHeader = (volatile ExceptionDumpHeader *)0x25000000;
if(dumpHeader->magic[0] != 0xDEADC0DE || dumpHeader->magic[1] != 0xDEADCAFE || (dumpHeader->processor != 9 && dumpHeader->processor != 11)) return;
const vu32 *regs = (vu32 *)((vu8 *)dumpHeader + sizeof(ExceptionDumpHeader));
const vu8 *stackDump = (vu8 *)regs + dumpHeader->registerDumpSize + dumpHeader->codeDumpSize;
const vu8 *additionalData = stackDump + dumpHeader->stackDumpSize;
static const char *handledExceptionNames[] = {
"FIQ", "undefined instruction", "prefetch abort", "data abort"
},
*specialExceptions[] = {
"kernel panic", "svcBreak"
},
*registerNames[] = {
"R0", "R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8", "R9", "R10", "R11", "R12",
"SP", "LR", "PC", "CPSR", "FPEXC"
},
*faultStatusNames[] = {
"Alignment", "Instr.cache maintenance op.",
"Ext.Abort on translation - Lv1", "Ext.Abort on translation - Lv2",
"Translation - Section", "Translation - Page", "Access bit - Section", "Access bit - Page",
"Domain - Section", "Domain - Page", "Permission - Section", "Permission - Page",
"Precise External Abort", "Imprecise External Abort", "Debug event"
};
static const u32 faultStatusValues[] = {
0b1, 0b100, 0b1100, 0b1110, 0b101, 0b111, 0b11, 0b110, 0b1001, 0b1011, 0b1101,
0b1111, 0b1000, 0b10110, 0b10
};
initScreens();
drawString(true, 10, 10, COLOR_RED, "An exception occurred");
u32 posY;
if(dumpHeader->processor == 11) posY = drawFormattedString(true, 10, 30, COLOR_WHITE, "Processor: ARM11 (core %u)", dumpHeader->core);
else posY = drawString(true, 10, 30, COLOR_WHITE, "Processor: ARM9");
if(dumpHeader->type == 2)
{
if((regs[16] & 0x20) == 0 && dumpHeader->codeDumpSize >= 4)
{
u32 instr = *(vu32 *)(stackDump - 4);
if(instr == 0xE12FFF7E)
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE, "Exception type: %s (%s)", handledExceptionNames[dumpHeader->type], specialExceptions[0]);
else if(instr == 0xEF00003C)
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE, "Exception type: %s (%s)", handledExceptionNames[dumpHeader->type], specialExceptions[1]);
else
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE, "Exception type: %s", handledExceptionNames[dumpHeader->type]);
}
else if((regs[16] & 0x20) != 0 && dumpHeader->codeDumpSize >= 2)
{
u16 instr = *(vu16 *)(stackDump - 2);
if(instr == 0xDF3C)
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE, "Exception type: %s (%s)", handledExceptionNames[dumpHeader->type], specialExceptions[0]);
else
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE, "Exception type: %s", handledExceptionNames[dumpHeader->type]);
}
else
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE, "Exception type: %s", handledExceptionNames[dumpHeader->type]);
}
else
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE, "Exception type: %s", handledExceptionNames[dumpHeader->type]);
if(dumpHeader->processor == 11 && dumpHeader->type >= 2)
{
u32 xfsr = (dumpHeader->type == 2 ? regs[18] : regs[17]) & 0xF;
for(u32 i = 0; i < 15; i++)
if(xfsr == faultStatusValues[i])
{
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE, "Fault status: %s", faultStatusNames[i]);
break;
}
}
if(dumpHeader->additionalDataSize != 0)
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE,
"Current process: %.8s (%016llX)", (const char *)additionalData, *(vu64 *)(additionalData + 8));
posY += SPACING_Y;
for(u32 i = 0; i < 17; i += 2)
{
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE, "%-7s%08X", registerNames[i], regs[i]);
if(i != 16)
posY = drawFormattedString(true, 10 + 22 * SPACING_X, posY, COLOR_WHITE, "%-7s%08X", registerNames[i + 1], regs[i + 1]);
else if(dumpHeader->processor == 11)
posY = drawFormattedString(true, 10 + 22 * SPACING_X, posY, COLOR_WHITE, "%-7s%08X", registerNames[i + 1], regs[20]);
}
if(dumpHeader->processor == 11 && dumpHeader->type == 3)
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE, "%-7s%08X Access type: %s", "FAR", regs[19], regs[17] & (1u << 11) ? "Write" : "Read");
posY += SPACING_Y;
u32 mode = regs[16] & 0xF;
if(dumpHeader->type == 3 && (mode == 7 || mode == 11))
posY = drawString(true, 10, posY + SPACING_Y, COLOR_YELLOW, "Incorrect dump: failed to dump code and/or stack") + SPACING_Y;
u32 posYBottom = drawString(false, 10, 10, COLOR_WHITE, "Stack dump:") + SPACING_Y;
for(u32 line = 0; line < 19 && stackDump < additionalData; line++)
{
posYBottom = drawFormattedString(false, 10, posYBottom + SPACING_Y, COLOR_WHITE, "%08X:", regs[13] + 8 * line);
for(u32 i = 0; i < 8 && stackDump < additionalData; i++, stackDump++)
drawFormattedString(false, 10 + 10 * SPACING_X + 3 * i * SPACING_X, posYBottom, COLOR_WHITE, "%02X", *stackDump);
}
static const char *choiceMessage[] = {"Press A to save the crash dump", "Press any other button to shutdown"};
drawString(true, 10, posY + SPACING_Y, COLOR_WHITE, choiceMessage[0]);
drawString(true, 10, posY + SPACING_Y + SPACING_Y , COLOR_WHITE, choiceMessage[1]);
if(waitInput(false) != BUTTON_A) goto exit;
drawString(true, 10, posY + SPACING_Y, COLOR_BLACK, choiceMessage[0]);
drawString(true, 10, posY + SPACING_Y + SPACING_Y , COLOR_BLACK, choiceMessage[1]);
char folderPath[12],
path[36],
fileName[24];
sprintf(folderPath, "dumps/arm%u", dumpHeader->processor);
findDumpFile(folderPath, fileName);
sprintf(path, "%s/%s", folderPath, fileName);
if(fileWrite((void *)dumpHeader, path, dumpHeader->totalSize))
{
posY = drawString(true, 10, posY + SPACING_Y, COLOR_WHITE, "You can find the dump in the following file:");
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE, "%s:/luma/%s", isSdMode ? "SD" : "CTRNAND", path) + SPACING_Y;
}
else posY = drawString(true, 10, posY + SPACING_Y, COLOR_RED, "Error writing the dump file");
drawString(true, 10, posY + SPACING_Y, COLOR_WHITE, "Press any button to shutdown");
waitInput(false);
exit:
memset32((void *)dumpHeader, 0, dumpHeader->totalSize);
mcuPowerOff();
}

33
arm9/source/exceptions.h Normal file
View File

@@ -0,0 +1,33 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#pragma once
#include "types.h"
void installArm9Handlers(void);
u32 installArm11Handlers(u32 *exceptionsPage, u32 stackAddress, u32 codeSetOffset, u32 *dAbtHandler, u32 dAbtHandlerMemAddress);
void detectAndProcessExceptionDumps(void);

View File

@@ -0,0 +1,330 @@
----------------------------------------------------------------------------
Revision history of FatFs module
----------------------------------------------------------------------------
R0.00 (February 26, 2006)
Prototype.
R0.01 (April 29, 2006)
The first release.
R0.02 (June 01, 2006)
Added FAT12 support.
Removed unbuffered mode.
Fixed a problem on small (<32M) partition.
R0.02a (June 10, 2006)
Added a configuration option (_FS_MINIMUM).
R0.03 (September 22, 2006)
Added f_rename().
Changed option _FS_MINIMUM to _FS_MINIMIZE.
R0.03a (December 11, 2006)
Improved cluster scan algorithm to write files fast.
Fixed f_mkdir() creates incorrect directory on FAT32.
R0.04 (February 04, 2007)
Added f_mkfs().
Supported multiple drive system.
Changed some interfaces for multiple drive system.
Changed f_mountdrv() to f_mount().
R0.04a (April 01, 2007)
Supported multiple partitions on a physical drive.
Added a capability of extending file size to f_lseek().
Added minimization level 3.
Fixed an endian sensitive code in f_mkfs().
R0.04b (May 05, 2007)
Added a configuration option _USE_NTFLAG.
Added FSINFO support.
Fixed DBCS name can result FR_INVALID_NAME.
Fixed short seek (<= csize) collapses the file object.
R0.05 (August 25, 2007)
Changed arguments of f_read(), f_write() and f_mkfs().
Fixed f_mkfs() on FAT32 creates incorrect FSINFO.
Fixed f_mkdir() on FAT32 creates incorrect directory.
R0.05a (February 03, 2008)
Added f_truncate() and f_utime().
Fixed off by one error at FAT sub-type determination.
Fixed btr in f_read() can be mistruncated.
Fixed cached sector is not flushed when create and close without write.
R0.06 (April 01, 2008)
Added fputc(), fputs(), fprintf() and fgets().
Improved performance of f_lseek() on moving to the same or following cluster.
R0.07 (April 01, 2009)
Merged Tiny-FatFs as a configuration option. (_FS_TINY)
Added long file name feature. (_USE_LFN)
Added multiple code page feature. (_CODE_PAGE)
Added re-entrancy for multitask operation. (_FS_REENTRANT)
Added auto cluster size selection to f_mkfs().
Added rewind option to f_readdir().
Changed result code of critical errors.
Renamed string functions to avoid name collision.
R0.07a (April 14, 2009)
Septemberarated out OS dependent code on reentrant cfg.
Added multiple sector size feature.
R0.07c (June 21, 2009)
Fixed f_unlink() can return FR_OK on error.
Fixed wrong cache control in f_lseek().
Added relative path feature.
Added f_chdir() and f_chdrive().
Added proper case conversion to extended character.
R0.07e (November 03, 2009)
Septemberarated out configuration options from ff.h to ffconf.h.
Fixed f_unlink() fails to remove a sub-directory on _FS_RPATH.
Fixed name matching error on the 13 character boundary.
Added a configuration option, _LFN_UNICODE.
Changed f_readdir() to return the SFN with always upper case on non-LFN cfg.
R0.08 (May 15, 2010)
Added a memory configuration option. (_USE_LFN = 3)
Added file lock feature. (_FS_SHARE)
Added fast seek feature. (_USE_FASTSEEK)
Changed some types on the API, XCHAR->TCHAR.
Changed .fname in the FILINFO structure on Unicode cfg.
String functions support UTF-8 encoding files on Unicode cfg.
R0.08a (August 16, 2010)
Added f_getcwd(). (_FS_RPATH = 2)
Added sector erase feature. (_USE_ERASE)
Moved file lock semaphore table from fs object to the bss.
Fixed f_mkfs() creates wrong FAT32 volume.
R0.08b (January 15, 2011)
Fast seek feature is also applied to f_read() and f_write().
f_lseek() reports required table size on creating CLMP.
Extended format syntax of f_printf().
Ignores duplicated directory separators in given path name.
R0.09 (September 06, 2011)
f_mkfs() supports multiple partition to complete the multiple partition feature.
Added f_fdisk().
R0.09a (August 27, 2012)
Changed f_open() and f_opendir() reject null object pointer to avoid crash.
Changed option name _FS_SHARE to _FS_LOCK.
Fixed assertion failure due to OS/2 EA on FAT12/16 volume.
R0.09b (January 24, 2013)
Added f_setlabel() and f_getlabel().
R0.10 (October 02, 2013)
Added selection of character encoding on the file. (_STRF_ENCODE)
Added f_closedir().
Added forced full FAT scan for f_getfree(). (_FS_NOFSINFO)
Added forced mount feature with changes of f_mount().
Improved behavior of volume auto detection.
Improved write throughput of f_puts() and f_printf().
Changed argument of f_chdrive(), f_mkfs(), disk_read() and disk_write().
Fixed f_write() can be truncated when the file size is close to 4GB.
Fixed f_open(), f_mkdir() and f_setlabel() can return incorrect value on error.
R0.10a (January 15, 2014)
Added arbitrary strings as drive number in the path name. (_STR_VOLUME_ID)
Added a configuration option of minimum sector size. (_MIN_SS)
2nd argument of f_rename() can have a drive number and it will be ignored.
Fixed f_mount() with forced mount fails when drive number is >= 1. (appeared at R0.10)
Fixed f_close() invalidates the file object without volume lock.
Fixed f_closedir() returns but the volume lock is left acquired. (appeared at R0.10)
Fixed creation of an entry with LFN fails on too many SFN collisions. (appeared at R0.07)
R0.10b (May 19, 2014)
Fixed a hard error in the disk I/O layer can collapse the directory entry.
Fixed LFN entry is not deleted when delete/rename an object with lossy converted SFN. (appeared at R0.07)
R0.10c (November 09, 2014)
Added a configuration option for the platforms without RTC. (_FS_NORTC)
Changed option name _USE_ERASE to _USE_TRIM.
Fixed volume label created by Mac OS X cannot be retrieved with f_getlabel(). (appeared at R0.09b)
Fixed a potential problem of FAT access that can appear on disk error.
Fixed null pointer dereference on attempting to delete the root direcotry. (appeared at R0.08)
R0.11 (February 09, 2015)
Added f_findfirst(), f_findnext() and f_findclose(). (_USE_FIND)
Fixed f_unlink() does not remove cluster chain of the file. (appeared at R0.10c)
Fixed _FS_NORTC option does not work properly. (appeared at R0.10c)
R0.11a (September 05, 2015)
Fixed wrong media change can lead a deadlock at thread-safe configuration.
Added code page 771, 860, 861, 863, 864, 865 and 869. (_CODE_PAGE)
Removed some code pages actually not exist on the standard systems. (_CODE_PAGE)
Fixed errors in the case conversion teble of code page 437 and 850 (ff.c).
Fixed errors in the case conversion teble of Unicode (cc*.c).
R0.12 (April 12, 2016)
Added support for exFAT file system. (_FS_EXFAT)
Added f_expand(). (_USE_EXPAND)
Changed some members in FINFO structure and behavior of f_readdir().
Added an option _USE_CHMOD.
Removed an option _WORD_ACCESS.
Fixed errors in the case conversion table of Unicode (cc*.c).
R0.12a (July 10, 2016)
Added support for creating exFAT volume with some changes of f_mkfs().
Added a file open method FA_OPEN_APPEND. An f_lseek() following f_open() is no longer needed.
f_forward() is available regardless of _FS_TINY.
Fixed f_mkfs() creates wrong volume. (appeared at R0.12)
Fixed wrong memory read in create_name(). (appeared at R0.12)
Fixed compilation fails at some configurations, _USE_FASTSEEK and _USE_FORWARD.
R0.12b (September 04, 2016)
Made f_rename() be able to rename objects with the same name but case.
Fixed an error in the case conversion teble of code page 866. (ff.c)
Fixed writing data is truncated at the file offset 4GiB on the exFAT volume. (appeared at R0.12)
Fixed creating a file in the root directory of exFAT volume can fail. (appeared at R0.12)
Fixed f_mkfs() creating exFAT volume with too small cluster size can collapse unallocated memory. (appeared at R0.12)
Fixed wrong object name can be returned when read directory at Unicode cfg. (appeared at R0.12)
Fixed large file allocation/removing on the exFAT volume collapses allocation bitmap. (appeared at R0.12)
Fixed some internal errors in f_expand() and f_lseek(). (appeared at R0.12)
R0.12c (March 04, 2017)
Improved write throughput at the fragmented file on the exFAT volume.
Made memory usage for exFAT be able to be reduced as decreasing _MAX_LFN.
Fixed successive f_getfree() can return wrong count on the FAT12/16 volume. (appeared at R0.12)
Fixed configuration option _VOLUMES cannot be set 10. (appeared at R0.10c)
R0.13 (May 21, 2017)
Changed heading character of configuration keywords "_" to "FF_".
Removed ASCII-only configuration, FF_CODE_PAGE = 1. Use FF_CODE_PAGE = 437 instead.
Added f_setcp(), run-time code page configuration. (FF_CODE_PAGE = 0)
Improved cluster allocation time on stretch a deep buried cluster chain.
Improved processing time of f_mkdir() with large cluster size by using FF_USE_LFN = 3.
Improved NoFatChain flag of the fragmented file to be set after it is truncated and got contiguous.
Fixed archive attribute is left not set when a file on the exFAT volume is renamed. (appeared at R0.12)
Fixed exFAT FAT entry can be collapsed when write or lseek operation to the existing file is done. (appeared at R0.12c)
Fixed creating a file can fail when a new cluster allocation to the exFAT directory occures. (appeared at R0.12c)
R0.13a (October 14, 2017)
Added support for UTF-8 encoding on the API. (FF_LFN_UNICODE = 2)
Added options for file name output buffer. (FF_LFN_BUF, FF_SFN_BUF).
Added dynamic memory allocation option for working buffer of f_mkfs() and f_fdisk().
Fixed f_fdisk() and f_mkfs() create the partition table with wrong CHS parameters. (appeared at R0.09)
Fixed f_unlink() can cause lost clusters at fragmented file on the exFAT volume. (appeared at R0.12c)
Fixed f_setlabel() rejects some valid characters for exFAT volume. (appeared at R0.12)
R0.13b (April 07, 2018)
Added support for UTF-32 encoding on the API. (FF_LFN_UNICODE = 3)
Added support for Unix style volume ID. (FF_STR_VOLUME_ID = 2)
Fixed accesing any object on the exFAT root directory beyond the cluster boundary can fail. (appeared at R0.12c)
Fixed f_setlabel() does not reject some invalid characters. (appeared at R0.09b)
R0.13c (October 14, 2018)
Supported stdint.h for C99 and later. (integer.h was included in ff.h)
Fixed reading a directory gets infinite loop when the last directory entry is not empty. (appeared at R0.12)
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)

View File

@@ -0,0 +1,21 @@
FatFs Module Source Files R0.13c
FILES
00readme.txt This file.
00history.txt Revision history.
ff.c FatFs module.
ffconf.h Configuration file of FatFs module.
ff.h Common include file for FatFs and application module.
diskio.h Common include file for FatFs and disk I/O module.
diskio.c An example of glue function to attach existing disk I/O module to FatFs.
ffunicode.c Optional Unicode utility functions.
ffsystem.c An example of optional O/S related functions.
Low level disk I/O module is not included in this archive because the FatFs
module is only a generic file system layer and it does not depend on any specific
storage device. You need to provide a low level disk I/O module written to
control the storage device that attached to the target system.

101
arm9/source/fatfs/diskio.c Normal file
View File

@@ -0,0 +1,101 @@
/*-----------------------------------------------------------------------*/
/* Low level disk I/O module skeleton for FatFs (C)ChaN, 2014 */
/*-----------------------------------------------------------------------*/
/* If a working storage control module is available, it should be */
/* attached to the FatFs via a glue function rather than modifying it. */
/* This is an example of glue functions to attach various exsisting */
/* storage control modules to the FatFs module with a defined API. */
/*-----------------------------------------------------------------------*/
#include "diskio.h" /* FatFs lower layer API */
#include "sdmmc/sdmmc.h"
#include "../crypto.h"
/* Definitions of physical drive number for each media */
#define SDCARD 0
#define CTRNAND 1
/*-----------------------------------------------------------------------*/
/* Get Drive Status */
/*-----------------------------------------------------------------------*/
DSTATUS disk_status (
__attribute__((unused))
BYTE pdrv /* Physical drive nmuber to identify the drive */
)
{
return RES_OK;
}
/*-----------------------------------------------------------------------*/
/* Inidialize a Drive */
/*-----------------------------------------------------------------------*/
DSTATUS disk_initialize (
BYTE pdrv /* Physical drive nmuber to identify the drive */
)
{
static u32 sdmmcInitResult = 4;
if(sdmmcInitResult == 4) sdmmcInitResult = sdmmc_sdcard_init();
return ((pdrv == SDCARD && !(sdmmcInitResult & 2)) ||
(pdrv == CTRNAND && !(sdmmcInitResult & 1) && !ctrNandInit())) ? 0 : STA_NOINIT;
}
/*-----------------------------------------------------------------------*/
/* Read Sector(s) */
/*-----------------------------------------------------------------------*/
DRESULT disk_read (
BYTE pdrv, /* Physical drive nmuber to identify the drive */
BYTE *buff, /* Data buffer to store read data */
DWORD sector, /* Sector address in LBA */
UINT count /* Number of sectors to read */
)
{
return ((pdrv == SDCARD && !sdmmc_sdcard_readsectors(sector, count, buff)) ||
(pdrv == CTRNAND && !ctrNandRead(sector, count, buff))) ? RES_OK : RES_PARERR;
}
/*-----------------------------------------------------------------------*/
/* Write Sector(s) */
/*-----------------------------------------------------------------------*/
#if _USE_WRITE
DRESULT disk_write (
BYTE pdrv, /* Physical drive nmuber to identify the drive */
const BYTE *buff, /* Data to be written */
DWORD sector, /* Sector address in LBA */
UINT count /* Number of sectors to write */
)
{
return ((pdrv == SDCARD && (*(vu16 *)(SDMMC_BASE + REG_SDSTATUS0) & TMIO_STAT0_WRPROTECT) != 0 && !sdmmc_sdcard_writesectors(sector, count, buff)) ||
(pdrv == CTRNAND && !ctrNandWrite(sector, count, buff))) ? RES_OK : RES_PARERR;
}
#endif
/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions */
/*-----------------------------------------------------------------------*/
#if _USE_IOCTL
DRESULT disk_ioctl (
__attribute__((unused))
BYTE pdrv, /* Physical drive nmuber (0..) */
BYTE cmd, /* Control code */
__attribute__((unused))
void *buff /* Buffer to send/receive control data */
)
{
return cmd == CTRL_SYNC ? RES_OK : RES_PARERR;
}
#endif

View File

@@ -0,0 +1,80 @@
/*-----------------------------------------------------------------------/
/ Low level disk interface modlue include file (C)ChaN, 2014 /
/-----------------------------------------------------------------------*/
#ifndef _DISKIO_DEFINED
#define _DISKIO_DEFINED
#ifdef __cplusplus
extern "C" {
#endif
#define _USE_WRITE 1 /* 1: Enable disk_write function */
#define _USE_IOCTL 1 /* 1: Enable disk_ioctl fucntion */
#include "integer.h"
/* Status of Disk Functions */
typedef BYTE DSTATUS;
/* Results of Disk Functions */
typedef enum {
RES_OK = 0, /* 0: Successful */
RES_ERROR, /* 1: R/W Error */
RES_WRPRT, /* 2: Write Protected */
RES_NOTRDY, /* 3: Not Ready */
RES_PARERR /* 4: Invalid Parameter */
} DRESULT;
/*---------------------------------------*/
/* Prototypes for disk control functions */
DSTATUS disk_initialize (BYTE pdrv);
DSTATUS disk_status (BYTE pdrv);
DRESULT disk_read (BYTE pdrv, BYTE* buff, DWORD sector, UINT count);
DRESULT disk_write (BYTE pdrv, const BYTE* buff, DWORD sector, UINT count);
DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void* buff);
/* Disk Status Bits (DSTATUS) */
#define STA_NOINIT 0x01 /* Drive not initialized */
#define STA_NODISK 0x02 /* No medium in the drive */
#define STA_PROTECT 0x04 /* Write protected */
/* Command code for disk_ioctrl fucntion */
/* Generic command (Used by FatFs) */
#define CTRL_SYNC 0 /* Complete pending write process (needed at _FS_READONLY == 0) */
#define GET_SECTOR_COUNT 1 /* Get media size (needed at _USE_MKFS == 1) */
#define GET_SECTOR_SIZE 2 /* Get sector size (needed at _MAX_SS != _MIN_SS) */
#define GET_BLOCK_SIZE 3 /* Get erase block size (needed at _USE_MKFS == 1) */
#define CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used (needed at _USE_TRIM == 1) */
/* Generic command (Not used by FatFs) */
#define CTRL_POWER 5 /* Get/Set power status */
#define CTRL_LOCK 6 /* Lock/Unlock media removal */
#define CTRL_EJECT 7 /* Eject media */
#define CTRL_FORMAT 8 /* Create physical format on the media */
/* MMC/SDC specific ioctl command */
#define MMC_GET_TYPE 10 /* Get card type */
#define MMC_GET_CSD 11 /* Get CSD */
#define MMC_GET_CID 12 /* Get CID */
#define MMC_GET_OCR 13 /* Get OCR */
#define MMC_GET_SDSTAT 14 /* Get SD status */
/* ATA/CF specific ioctl command */
#define ATA_GET_REV 20 /* Get F/W revision */
#define ATA_GET_MODEL 21 /* Get model name */
#define ATA_GET_SN 22 /* Get serial number */
#ifdef __cplusplus
}
#endif
#endif

6554
arm9/source/fatfs/ff.c Normal file

File diff suppressed because it is too large Load Diff

405
arm9/source/fatfs/ff.h Normal file
View File

@@ -0,0 +1,405 @@
/*----------------------------------------------------------------------------/
/ FatFs - Generic FAT Filesystem module R0.13c /
/-----------------------------------------------------------------------------/
/
/ 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
/ that the following condition is met:
/ 1. Redistributions of source code must retain the above copyright notice,
/ this condition and the following disclaimer.
/
/ This software is provided by the copyright holder and contributors "AS IS"
/ and any warranties related to this software are DISCLAIMED.
/ The copyright owner or contributors be NOT LIABLE for any damages caused
/ by use of this software.
/
/----------------------------------------------------------------------------*/
#ifndef FF_DEFINED
#define FF_DEFINED 86604 /* Revision ID */
#ifdef __cplusplus
extern "C" {
#endif
#include "ffconf.h" /* FatFs configuration options */
#if FF_DEFINED != FFCONF_DEF
#error Wrong configuration file (ffconf.h).
#endif
/* Integer types used for FatFs API */
#if defined(_WIN32) /* Main development platform */
#define FF_INTDEF 2
#include <windows.h>
typedef unsigned __int64 QWORD;
#elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__cplusplus) /* C99 or later */
#define FF_INTDEF 2
#include <stdint.h>
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 */
#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 */
#endif
/* Definitions of volume management */
#if FF_MULTI_PARTITION /* Multiple partition configuration */
typedef struct {
BYTE pd; /* Physical drive number */
BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */
} PARTITION;
extern PARTITION VolToPart[]; /* Volume - Partition resolution table */
#endif
#if FF_STR_VOLUME_ID
#ifndef FF_VOLUME_STRS
extern const char* VolumeStr[FF_VOLUMES]; /* User defied volume ID */
#endif
#endif
/* Type of path name strings on FatFs API */
#ifndef _INC_TCHAR
#define _INC_TCHAR
#if FF_USE_LFN && FF_LFN_UNICODE == 1 /* Unicode in UTF-16 encoding */
typedef WCHAR TCHAR;
#define _T(x) L ## x
#define _TEXT(x) L ## x
#elif FF_USE_LFN && FF_LFN_UNICODE == 2 /* Unicode in UTF-8 encoding */
typedef char TCHAR;
#define _T(x) u8 ## x
#define _TEXT(x) u8 ## x
#elif FF_USE_LFN && FF_LFN_UNICODE == 3 /* Unicode in UTF-32 encoding */
typedef DWORD TCHAR;
#define _T(x) U ## x
#define _TEXT(x) U ## x
#elif FF_USE_LFN && (FF_LFN_UNICODE < 0 || FF_LFN_UNICODE > 3)
#error Wrong FF_LFN_UNICODE setting
#else /* ANSI/OEM code in SBCS/DBCS */
typedef char TCHAR;
#define _T(x) x
#define _TEXT(x) x
#endif
#endif
/* 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;
#else
typedef DWORD FSIZE_t;
#endif
/* Filesystem object structure (FATFS) */
typedef struct {
BYTE fs_type; /* Filesystem type (0:not mounted) */
BYTE pdrv; /* Associated physical drive */
BYTE n_fats; /* Number of FATs (1 or 2) */
BYTE wflag; /* win[] flag (b0:dirty) */
BYTE fsi_flag; /* FSINFO flags (b7:disabled, b0:dirty) */
WORD id; /* Volume mount ID */
WORD n_rootdir; /* Number of root directory entries (FAT12/16) */
WORD csize; /* Cluster size [sectors] */
#if FF_MAX_SS != FF_MIN_SS
WORD ssize; /* Sector size (512, 1024, 2048 or 4096) */
#endif
#if FF_USE_LFN
WCHAR* lfnbuf; /* LFN working buffer */
#endif
#if FF_FS_EXFAT
BYTE* dirbuf; /* Directory entry block scratchpad buffer for exFAT */
#endif
#if FF_FS_REENTRANT
FF_SYNC_t sobj; /* Identifier of sync object */
#endif
#if !FF_FS_READONLY
DWORD last_clst; /* Last allocated cluster */
DWORD free_clst; /* Number of free clusters */
#endif
#if FF_FS_RPATH
DWORD cdir; /* Current directory start cluster (0:root) */
#if FF_FS_EXFAT
DWORD cdc_scl; /* Containing directory start cluster (invalid when cdir is 0) */
DWORD cdc_size; /* b31-b8:Size of containing directory, b7-b0: Chain status */
DWORD cdc_ofs; /* Offset in the containing directory (invalid when cdir is 0) */
#endif
#endif
DWORD n_fatent; /* Number of FAT entries (number of clusters + 2) */
DWORD fsize; /* Size of an FAT [sectors] */
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
DWORD bitbase; /* Allocation bitmap base sector */
#endif
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;
/* Object ID and allocation information (FFOBJID) */
typedef struct {
FATFS* fs; /* Pointer to the hosting volume of this object */
WORD id; /* Hosting volume mount ID */
BYTE attr; /* Object attribute */
BYTE stat; /* Object chain status (b1-0: =0:not contiguous, =2:contiguous, =3:fragmented in this session, b2:sub-directory stretched) */
DWORD sclust; /* Object data start cluster (0:no cluster or root directory) */
FSIZE_t objsize; /* Object size (valid when sclust != 0) */
#if FF_FS_EXFAT
DWORD n_cont; /* Size of first fragment - 1 (valid when stat == 3) */
DWORD n_frag; /* Size of last fragment needs to be written to FAT (valid when not zero) */
DWORD c_scl; /* Containing directory start cluster (valid when sclust != 0) */
DWORD c_size; /* b31-b8:Size of containing directory, b7-b0: Chain status (valid when c_scl != 0) */
DWORD c_ofs; /* Offset in the containing directory (valid when file object and sclust != 0) */
#endif
#if FF_FS_LOCK
UINT lockid; /* File lock ID origin from 1 (index of file semaphore table Files[]) */
#endif
} FFOBJID;
/* File object structure (FIL) */
typedef struct {
FFOBJID obj; /* Object identifier (must be the 1st member to detect invalid object pointer) */
BYTE flag; /* File status flags */
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) */
DWORD sect; /* Sector number appearing in buf[] (0:invalid) */
#if !FF_FS_READONLY
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
DWORD* cltbl; /* Pointer to the cluster link map table (nulled on open, set by application) */
#endif
#if !FF_FS_TINY
BYTE buf[FF_MAX_SS]; /* File private data read/write window */
#endif
} FIL;
/* Directory object structure (DIR) */
typedef struct {
FFOBJID obj; /* Object identifier */
DWORD dptr; /* Current read/write offset */
DWORD clust; /* Current cluster */
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
DWORD blk_ofs; /* Offset of current entry block being processed (0xFFFFFFFF:Invalid) */
#endif
#if FF_USE_FIND
const TCHAR* pat; /* Pointer to the name matching pattern */
#endif
} DIR;
/* File information structure (FILINFO) */
typedef struct {
FSIZE_t fsize; /* File size */
WORD fdate; /* Modified date */
WORD ftime; /* Modified time */
BYTE fattrib; /* File attribute */
#if FF_USE_LFN
TCHAR altname[FF_SFN_BUF + 1];/* Altenative file name */
TCHAR fname[FF_LFN_BUF + 1]; /* Primary file name */
#else
TCHAR fname[12 + 1]; /* File name */
#endif
} FILINFO;
/* File function return code (FRESULT) */
typedef enum {
FR_OK = 0, /* (0) Succeeded */
FR_DISK_ERR, /* (1) A hard error occurred in the low level disk I/O layer */
FR_INT_ERR, /* (2) Assertion failed */
FR_NOT_READY, /* (3) The physical drive cannot work */
FR_NO_FILE, /* (4) Could not find the file */
FR_NO_PATH, /* (5) Could not find the path */
FR_INVALID_NAME, /* (6) The path name format is invalid */
FR_DENIED, /* (7) Access denied due to prohibited access or directory full */
FR_EXIST, /* (8) Access denied due to prohibited access */
FR_INVALID_OBJECT, /* (9) The file/directory object is invalid */
FR_WRITE_PROTECTED, /* (10) The physical drive is write protected */
FR_INVALID_DRIVE, /* (11) The logical drive number is invalid */
FR_NOT_ENABLED, /* (12) The volume has no work area */
FR_NO_FILESYSTEM, /* (13) There is no valid FAT volume */
FR_MKFS_ABORTED, /* (14) The f_mkfs() aborted due to any problem */
FR_TIMEOUT, /* (15) Could not get a grant to access the volume within defined period */
FR_LOCKED, /* (16) The operation is rejected according to the file sharing policy */
FR_NOT_ENOUGH_CORE, /* (17) LFN working buffer could not be allocated */
FR_TOO_MANY_OPEN_FILES, /* (18) Number of open files > FF_FS_LOCK */
FR_INVALID_PARAMETER /* (19) Given parameter is invalid */
} FRESULT;
/*--------------------------------------------------------------*/
/* FatFs module application interface */
FRESULT f_open (FIL* fp, const TCHAR* path, BYTE mode); /* Open or create a file */
FRESULT f_close (FIL* fp); /* Close an open file object */
FRESULT f_read (FIL* fp, void* buff, UINT btr, UINT* br); /* Read data from the file */
FRESULT f_write (FIL* fp, const void* buff, UINT btw, UINT* bw); /* Write data to the file */
FRESULT f_lseek (FIL* fp, FSIZE_t ofs); /* Move file pointer of the file object */
FRESULT f_truncate (FIL* fp); /* Truncate the file */
FRESULT f_sync (FIL* fp); /* Flush cached data of the writing file */
FRESULT f_opendir (DIR* dp, const TCHAR* path); /* Open a directory */
FRESULT f_closedir (DIR* dp); /* Close an open directory */
FRESULT f_readdir (DIR* dp, FILINFO* fno); /* Read a directory item */
FRESULT f_findfirst (DIR* dp, FILINFO* fno, const TCHAR* path, const TCHAR* pattern); /* Find first file */
FRESULT f_findnext (DIR* dp, FILINFO* fno); /* Find next file */
FRESULT f_mkdir (const TCHAR* path); /* Create a sub directory */
FRESULT f_unlink (const TCHAR* path); /* Delete an existing file or directory */
FRESULT f_rename (const TCHAR* path_old, const TCHAR* path_new); /* Rename/Move a file or directory */
FRESULT f_stat (const TCHAR* path, FILINFO* fno); /* Get file status */
FRESULT f_chmod (const TCHAR* path, BYTE attr, BYTE mask); /* Change attribute of a file/dir */
FRESULT f_utime (const TCHAR* path, const FILINFO* fno); /* Change timestamp of a file/dir */
FRESULT f_chdir (const TCHAR* path); /* Change current directory */
FRESULT f_chdrive (const TCHAR* path); /* Change current drive */
FRESULT f_getcwd (TCHAR* buff, UINT len); /* Get current directory */
FRESULT f_getfree (const TCHAR* path, DWORD* nclst, FATFS** fatfs); /* Get number of free clusters on the drive */
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 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, 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 */
int f_printf (FIL* fp, const TCHAR* str, ...); /* Put a formatted string to the file */
TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the file */
#define f_eof(fp) ((int)((fp)->fptr == (fp)->obj.objsize))
#define f_error(fp) ((fp)->err)
#define f_tell(fp) ((fp)->fptr)
#define f_size(fp) ((fp)->obj.objsize)
#define f_rewind(fp) f_lseek((fp), 0)
#define f_rewinddir(dp) f_readdir((dp), 0)
#define f_rmdir(path) f_unlink(path)
#define f_unmount(path) f_mount(0, path, 0)
#ifndef EOF
#define EOF (-1)
#endif
/*--------------------------------------------------------------*/
/* Additional user defined functions */
/* RTC function */
#if !FF_FS_READONLY && !FF_FS_NORTC
DWORD get_fattime (void);
#endif
/* LFN support functions */
#if FF_USE_LFN >= 1 /* Code conversion (defined in unicode.c) */
WCHAR ff_oem2uni (WCHAR oem, WORD cp); /* OEM code to Unicode conversion */
WCHAR ff_uni2oem (DWORD uni, WORD cp); /* Unicode to OEM code conversion */
DWORD ff_wtoupper (DWORD uni); /* Unicode upper-case conversion */
#endif
#if FF_USE_LFN == 3 /* Dynamic memory allocation */
void* ff_memalloc (UINT msize); /* Allocate memory block */
void ff_memfree (void* mblock); /* Free memory block */
#endif
/* Sync functions */
#if FF_FS_REENTRANT
int ff_cre_syncobj (BYTE vol, FF_SYNC_t* sobj); /* Create a sync object */
int ff_req_grant (FF_SYNC_t sobj); /* Lock sync object */
void ff_rel_grant (FF_SYNC_t sobj); /* Unlock sync object */
int ff_del_syncobj (FF_SYNC_t sobj); /* Delete a sync object */
#endif
/*--------------------------------------------------------------*/
/* Flags and offset address */
/* File access mode and open method flags (3rd argument of f_open) */
#define FA_READ 0x01
#define FA_WRITE 0x02
#define FA_OPEN_EXISTING 0x00
#define FA_CREATE_NEW 0x04
#define FA_CREATE_ALWAYS 0x08
#define FA_OPEN_ALWAYS 0x10
#define FA_OPEN_APPEND 0x30
/* Fast seek controls (2nd argument of f_lseek) */
#define CREATE_LINKMAP ((FSIZE_t)0 - 1)
/* Format options (2nd argument of f_mkfs) */
#define FM_FAT 0x01
#define FM_FAT32 0x02
#define FM_EXFAT 0x04
#define FM_ANY 0x07
#define FM_SFD 0x08
/* Filesystem type (FATFS.fs_type) */
#define FS_FAT12 1
#define FS_FAT16 2
#define FS_FAT32 3
#define FS_EXFAT 4
/* File attribute bits for directory entry (FILINFO.fattrib) */
#define AM_RDO 0x01 /* Read only */
#define AM_HID 0x02 /* Hidden */
#define AM_SYS 0x04 /* System */
#define AM_DIR 0x10 /* Directory */
#define AM_ARC 0x20 /* Archive */
#ifdef __cplusplus
}
#endif
#endif /* FF_DEFINED */

288
arm9/source/fatfs/ffconf.h Normal file
View File

@@ -0,0 +1,288 @@
/*---------------------------------------------------------------------------/
/ FatFs Functional Configurations
/---------------------------------------------------------------------------*/
#define FFCONF_DEF 86604 /* Revision ID */
/*---------------------------------------------------------------------------/
/ Function Configurations
/---------------------------------------------------------------------------*/
#define FF_FS_READONLY 0
/* This option switches read-only configuration. (0:Read/Write or 1:Read-only)
/ Read-only configuration removes writing API functions, f_write(), f_sync(),
/ f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree()
/ and optional writing functions as well. */
#define FF_FS_MINIMIZE 0
/* This option defines minimization level to remove some basic API functions.
/
/ 0: Basic functions are fully enabled.
/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_truncate() and f_rename()
/ are removed.
/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1.
/ 3: f_lseek() function is removed in addition to 2. */
#define FF_USE_STRFUNC 0
/* This option switches string functions, f_gets(), f_putc(), f_puts() and f_printf().
/
/ 0: Disable string functions.
/ 1: Enable without LF-CRLF conversion.
/ 2: Enable with LF-CRLF conversion. */
#define FF_USE_FIND 1
/* This option switches filtered directory read functions, f_findfirst() and
/ f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */
#define FF_USE_MKFS 0
/* This option switches f_mkfs() function. (0:Disable or 1:Enable) */
#define FF_USE_FASTSEEK 0
/* This option switches fast seek function. (0:Disable or 1:Enable) */
#define FF_USE_EXPAND 0
/* This option switches f_expand function. (0:Disable or 1:Enable) */
#define FF_USE_CHMOD 0
/* This option switches attribute manipulation functions, f_chmod() and f_utime().
/ (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */
#define FF_USE_LABEL 0
/* This option switches volume label functions, f_getlabel() and f_setlabel().
/ (0:Disable or 1:Enable) */
#define FF_USE_FORWARD 0
/* This option switches f_forward() function. (0:Disable or 1:Enable) */
/*---------------------------------------------------------------------------/
/ Locale and Namespace Configurations
/---------------------------------------------------------------------------*/
#define FF_CODE_PAGE 437
/* This option specifies the OEM code page to be used on the target system.
/ Incorrect code page setting can cause a file open failure.
/
/ 437 - U.S.
/ 720 - Arabic
/ 737 - Greek
/ 771 - KBL
/ 775 - Baltic
/ 850 - Latin 1
/ 852 - Latin 2
/ 855 - Cyrillic
/ 857 - Turkish
/ 860 - Portuguese
/ 861 - Icelandic
/ 862 - Hebrew
/ 863 - Canadian French
/ 864 - Arabic
/ 865 - Nordic
/ 866 - Russian
/ 869 - Greek 2
/ 932 - Japanese (DBCS)
/ 936 - Simplified Chinese (DBCS)
/ 949 - Korean (DBCS)
/ 950 - Traditional Chinese (DBCS)
/ 0 - Include all code pages above and configured by f_setcp()
*/
#define FF_USE_LFN 2
#define FF_MAX_LFN 255
/* The FF_USE_LFN switches the support for LFN (long file name).
/
/ 0: Disable LFN. FF_MAX_LFN has no effect.
/ 1: Enable LFN with static working buffer on the BSS. Always NOT thread-safe.
/ 2: Enable LFN with dynamic working buffer on the STACK.
/ 3: Enable LFN with dynamic working buffer on the HEAP.
/
/ To enable the LFN, ffunicode.c needs to be added to the project. The LFN function
/ 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 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() in ffsystem.c, need to be added to the project. */
#define FF_LFN_UNICODE 2
/* This option switches the character encoding on the API when LFN is enabled.
/
/ 0: ANSI/OEM in current CP (TCHAR = char)
/ 1: Unicode in UTF-16 (TCHAR = WCHAR)
/ 2: Unicode in UTF-8 (TCHAR = char)
/ 3: Unicode in UTF-32 (TCHAR = DWORD)
/
/ Also behavior of string I/O functions will be affected by this option.
/ When LFN is not enabled, this option has no effect. */
#define FF_LFN_BUF 255
#define FF_SFN_BUF 12
/* This set of options defines size of file name members in the FILINFO structure
/ which is used to read out directory items. These values should be suffcient for
/ the file names to read. The maximum possible length of the read file name depends
/ on character encoding. When LFN is not enabled, these options have no effect. */
#define FF_STRF_ENCODE 3
/* When FF_LFN_UNICODE >= 1 with LFN enabled, string I/O functions, f_gets(),
/ f_putc(), f_puts and f_printf() convert the character encoding in it.
/ This option selects assumption of character encoding ON THE FILE to be
/ read/written via those functions.
/
/ 0: ANSI/OEM in current CP
/ 1: Unicode in UTF-16LE
/ 2: Unicode in UTF-16BE
/ 3: Unicode in UTF-8
*/
#define FF_FS_RPATH 1
/* This option configures support for relative path.
/
/ 0: Disable relative path and remove related functions.
/ 1: Enable relative path. f_chdir() and f_chdrive() are available.
/ 2: f_getcwd() function is available in addition to 1.
*/
/*---------------------------------------------------------------------------/
/ Drive/Volume Configurations
/---------------------------------------------------------------------------*/
#define FF_VOLUMES 2
/* Number of volumes (logical drives) to be used. (1-10) */
#define FF_STR_VOLUME_ID 0
#define FF_VOLUME_STRS "RAM","NAND","CF","SD","SD2","USB","USB2","USB3"
/* FF_STR_VOLUME_ID switches support for volume ID in arbitrary strings.
/ When FF_STR_VOLUME_ID is set to 1 or 2, arbitrary strings can be used as drive
/ number in the path name. FF_VOLUME_STRS defines the volume ID strings for each
/ logical drives. Number of items must not be less than FF_VOLUMES. Valid
/ characters for the volume ID strings are A-Z, a-z and 0-9, however, they are
/ compared in case-insensitive. If FF_STR_VOLUME_ID >= 1 and FF_VOLUME_STRS is
/ not defined, a user defined volume string table needs to be defined as:
/
/ const char* VolumeStr[FF_VOLUMES] = {"ram","flash","sd","usb",...
*/
#define FF_MULTI_PARTITION 0
/* This option switches support for multiple volumes on the physical drive.
/ By default (0), each logical drive number is bound to the same physical drive
/ number and only an FAT volume found on the physical drive will be mounted.
/ When this function is enabled (1), each logical drive number can be bound to
/ arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk()
/ funciton will be available. */
#define FF_MIN_SS 512
#define FF_MAX_SS 512
/* This set of options configures the range of sector size to be supported. (512,
/ 1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and
/ harddisk. But a larger value may be required for on-board flash memory and some
/ type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is configured
/ for variable sector size mode and disk_ioctl() function needs to implement
/ GET_SECTOR_SIZE command. */
#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
/---------------------------------------------------------------------------*/
#define FF_FS_TINY 0
/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny)
/ At the tiny configuration, size of file object (FIL) is shrinked FF_MAX_SS bytes.
/ Instead of private sector buffer eliminated from the file object, common sector
/ buffer in the filesystem object (FATFS) is used for the file data transfer. */
#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)
/ Note that enabling exFAT discards ANSI C (C89) compatibility. */
#define FF_FS_NORTC 1
#define FF_NORTC_MON 1
#define FF_NORTC_MDAY 1
#define FF_NORTC_YEAR 2019
/* 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
/ defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time.
/ 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 at read-only configuration (FF_FS_READONLY = 1). */
#define FF_FS_LOCK 0
/* The option FF_FS_LOCK switches file lock function to control duplicated file open
/ and illegal operation to open objects. This option must be 0 when FF_FS_READONLY
/ is 1.
/
/ 0: Disable file lock function. To avoid volume corruption, application program
/ should avoid illegal open, remove and rename to the open objects.
/ >0: Enable file lock function. The value defines how many files/sub-directories
/ can be opened simultaneously under file lock control. Note that the file
/ lock control is independent of re-entrancy. */
/* #include <somertos.h> // O/S definitions */
#define FF_FS_REENTRANT 0
#define FF_FS_TIMEOUT 1000
#define FF_SYNC_t HANDLE
/* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs
/ module itself. Note that regardless of this option, file access to different
/ volume is always re-entrant and volume control functions, f_mount(), f_mkfs()
/ and f_fdisk() function, are always not re-entrant. Only file/directory access
/ to the same volume is under control of this function.
/
/ 0: Disable re-entrancy. FF_FS_TIMEOUT and FF_SYNC_t have no effect.
/ 1: Enable re-entrancy. Also user provided synchronization handlers,
/ ff_req_grant(), ff_rel_grant(), ff_del_syncobj() and ff_cre_syncobj()
/ function, must be added to the project. Samples are available in
/ option/syscall.c.
/
/ The FF_FS_TIMEOUT defines timeout period in unit of time tick.
/ The FF_SYNC_t defines O/S dependent sync object type. e.g. HANDLE, ID, OS_EVENT*,
/ SemaphoreHandle_t and etc. A header file for O/S definitions needs to be
/ included somewhere in the scope of ff.h. */
/*--- End of configuration options ---*/

View File

@@ -0,0 +1,170 @@
/*------------------------------------------------------------------------*/
/* Sample Code of OS Dependent Functions for FatFs */
/* (C)ChaN, 2018 */
/*------------------------------------------------------------------------*/
#include "ff.h"
#if FF_USE_LFN == 3 /* Dynamic memory allocation */
/*------------------------------------------------------------------------*/
/* Allocate a memory block */
/*------------------------------------------------------------------------*/
void* ff_memalloc ( /* Returns pointer to the allocated memory block (null if not enough core) */
UINT msize /* Number of bytes to allocate */
)
{
return malloc(msize); /* Allocate a new memory block with POSIX API */
}
/*------------------------------------------------------------------------*/
/* Free a memory block */
/*------------------------------------------------------------------------*/
void ff_memfree (
void* mblock /* Pointer to the memory block to free (nothing to do if null) */
)
{
free(mblock); /* Free the memory block with POSIX API */
}
#endif
#if FF_FS_REENTRANT /* Mutal exclusion */
/*------------------------------------------------------------------------*/
/* Create a Synchronization Object */
/*------------------------------------------------------------------------*/
/* This function is called in f_mount() function to create a new
/ synchronization object for the volume, such as semaphore and mutex.
/ When a 0 is returned, the f_mount() function fails with FR_INT_ERR.
*/
//const osMutexDef_t Mutex[FF_VOLUMES]; /* Table of CMSIS-RTOS mutex */
int ff_cre_syncobj ( /* 1:Function succeeded, 0:Could not create the sync object */
BYTE vol, /* Corresponding volume (logical drive number) */
FF_SYNC_t* sobj /* Pointer to return the created sync object */
)
{
/* Win32 */
*sobj = CreateMutex(NULL, FALSE, NULL);
return (int)(*sobj != INVALID_HANDLE_VALUE);
/* uITRON */
// T_CSEM csem = {TA_TPRI,1,1};
// *sobj = acre_sem(&csem);
// return (int)(*sobj > 0);
/* uC/OS-II */
// OS_ERR err;
// *sobj = OSMutexCreate(0, &err);
// return (int)(err == OS_NO_ERR);
/* FreeRTOS */
// *sobj = xSemaphoreCreateMutex();
// return (int)(*sobj != NULL);
/* CMSIS-RTOS */
// *sobj = osMutexCreate(&Mutex[vol]);
// return (int)(*sobj != NULL);
}
/*------------------------------------------------------------------------*/
/* Delete a Synchronization Object */
/*------------------------------------------------------------------------*/
/* This function is called in f_mount() function to delete a synchronization
/ object that created with ff_cre_syncobj() function. When a 0 is returned,
/ the f_mount() function fails with FR_INT_ERR.
*/
int ff_del_syncobj ( /* 1:Function succeeded, 0:Could not delete due to an error */
FF_SYNC_t sobj /* Sync object tied to the logical drive to be deleted */
)
{
/* Win32 */
return (int)CloseHandle(sobj);
/* uITRON */
// return (int)(del_sem(sobj) == E_OK);
/* uC/OS-II */
// OS_ERR err;
// OSMutexDel(sobj, OS_DEL_ALWAYS, &err);
// return (int)(err == OS_NO_ERR);
/* FreeRTOS */
// vSemaphoreDelete(sobj);
// return 1;
/* CMSIS-RTOS */
// return (int)(osMutexDelete(sobj) == osOK);
}
/*------------------------------------------------------------------------*/
/* Request Grant to Access the Volume */
/*------------------------------------------------------------------------*/
/* This function is called on entering file functions to lock the volume.
/ When a 0 is returned, the file function fails with FR_TIMEOUT.
*/
int ff_req_grant ( /* 1:Got a grant to access the volume, 0:Could not get a grant */
FF_SYNC_t sobj /* Sync object to wait */
)
{
/* Win32 */
return (int)(WaitForSingleObject(sobj, FF_FS_TIMEOUT) == WAIT_OBJECT_0);
/* uITRON */
// return (int)(wai_sem(sobj) == E_OK);
/* uC/OS-II */
// OS_ERR err;
// OSMutexPend(sobj, FF_FS_TIMEOUT, &err));
// return (int)(err == OS_NO_ERR);
/* FreeRTOS */
// return (int)(xSemaphoreTake(sobj, FF_FS_TIMEOUT) == pdTRUE);
/* CMSIS-RTOS */
// return (int)(osMutexWait(sobj, FF_FS_TIMEOUT) == osOK);
}
/*------------------------------------------------------------------------*/
/* Release Grant to Access the Volume */
/*------------------------------------------------------------------------*/
/* This function is called on leaving file functions to unlock the volume.
*/
void ff_rel_grant (
FF_SYNC_t sobj /* Sync object to be signaled */
)
{
/* Win32 */
ReleaseMutex(sobj);
/* uITRON */
// sig_sem(sobj);
/* uC/OS-II */
// OSMutexPost(sobj);
/* FreeRTOS */
// xSemaphoreGive(sobj);
/* CMSIS-RTOS */
// osMutexRelease(sobj);
}
#endif

15597
arm9/source/fatfs/ffunicode.c Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,38 @@
/*-------------------------------------------*/
/* Integer type definitions for FatFs module */
/*-------------------------------------------*/
#ifndef FF_INTEGER
#define FF_INTEGER
#ifdef _WIN32 /* FatFs development platform */
#include <windows.h>
#include <tchar.h>
typedef unsigned __int64 QWORD;
#else /* Embedded platform */
/* These types MUST be 16-bit or 32-bit */
typedef int INT;
typedef unsigned int UINT;
/* This type MUST be 8-bit */
typedef unsigned char BYTE;
/* These types MUST be 16-bit */
typedef short SHORT;
typedef unsigned short WORD;
typedef unsigned short WCHAR;
/* These types MUST be 32-bit */
typedef long LONG;
typedef unsigned long DWORD;
/* This type MUST be 64-bit (Remove this for ANSI C (C89) compatibility) */
typedef unsigned long long QWORD;
#endif
#endif

View File

@@ -0,0 +1,5 @@
#pragma once
#include "../../types.h"
void waitcycles(u32 us);

View File

@@ -0,0 +1,16 @@
.text
.arm
.align 4
.global waitcycles
.type waitcycles, %function
waitcycles:
push {r0-r2, lr}
str r0, [sp, #4]
waitcycles_loop:
ldr r3, [sp, #4]
subs r2, r3, #1
str r2, [sp, #4]
cmp r3, #0
bne waitcycles_loop
pop {r0-r2, pc}

View File

@@ -0,0 +1,482 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2014-2015, Normmatt
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU General Public License Version 2, as described below:
*
* This file is free software: you may copy, redistribute 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 file 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 "sdmmc.h"
#include "delay.h"
static struct mmcdevice handleNAND;
static struct mmcdevice handleSD;
static inline u16 sdmmc_read16(u16 reg)
{
return *(vu16 *)(SDMMC_BASE + reg);
}
static inline void sdmmc_write16(u16 reg, u16 val)
{
*(vu16 *)(SDMMC_BASE + reg) = val;
}
static inline u32 sdmmc_read32(u16 reg)
{
return *(vu32 *)(SDMMC_BASE + reg);
}
static inline void sdmmc_write32(u16 reg, u32 val)
{
*(vu32 *)(SDMMC_BASE + reg) = val;
}
static inline void sdmmc_mask16(u16 reg, const u16 clear, const u16 set)
{
u16 val = sdmmc_read16(reg);
val &= ~clear;
val |= set;
sdmmc_write16(reg, val);
}
static inline void setckl(u32 data)
{
sdmmc_mask16(REG_SDCLKCTL, 0x100, 0);
sdmmc_mask16(REG_SDCLKCTL, 0x2FF, data & 0x2FF);
sdmmc_mask16(REG_SDCLKCTL, 0x0, 0x100);
}
mmcdevice *getMMCDevice(int drive)
{
if(drive == 0) return &handleNAND;
return &handleSD;
}
static int geterror(struct mmcdevice *ctx)
{
return (int)((ctx->error << 29) >> 31);
}
static void inittarget(struct mmcdevice *ctx)
{
sdmmc_mask16(REG_SDPORTSEL, 0x3, (u16)ctx->devicenumber);
setckl(ctx->clk);
if(ctx->SDOPT == 0) sdmmc_mask16(REG_SDOPT, 0, 0x8000);
else sdmmc_mask16(REG_SDOPT, 0x8000, 0);
}
static void __attribute__((noinline)) sdmmc_send_command(struct mmcdevice *ctx, u32 cmd, u32 args)
{
u32 getSDRESP = (cmd << 15) >> 31;
u16 flags = (cmd << 15) >> 31;
const int readdata = cmd & 0x20000;
const int writedata = cmd & 0x40000;
if(readdata || writedata)
flags |= TMIO_STAT0_DATAEND;
ctx->error = 0;
while((sdmmc_read16(REG_SDSTATUS1) & TMIO_STAT1_CMD_BUSY)); //mmc working?
sdmmc_write16(REG_SDIRMASK0, 0);
sdmmc_write16(REG_SDIRMASK1, 0);
sdmmc_write16(REG_SDSTATUS0, 0);
sdmmc_write16(REG_SDSTATUS1, 0);
sdmmc_mask16(REG_DATACTL32, 0x1800, 0);
sdmmc_write16(REG_SDCMDARG0, args & 0xFFFF);
sdmmc_write16(REG_SDCMDARG1, args >> 16);
sdmmc_write16(REG_SDCMD, cmd & 0xFFFF);
u32 size = ctx->size;
u8 *rDataPtr = ctx->rData;
const u8 *tDataPtr = ctx->tData;
bool rUseBuf = rDataPtr != NULL;
bool tUseBuf = tDataPtr != NULL;
u16 status0 = 0;
while(true)
{
vu16 status1 = sdmmc_read16(REG_SDSTATUS1);
vu16 ctl32 = sdmmc_read16(REG_DATACTL32);
if((ctl32 & 0x100))
{
if(readdata)
{
if(rUseBuf)
{
sdmmc_mask16(REG_SDSTATUS1, TMIO_STAT1_RXRDY, 0);
if(size > 0x1FF)
{
//Gabriel Marcano: This implementation doesn't assume alignment.
//I've removed the alignment check doen with former rUseBuf32 as a result
for(int i = 0; i < 0x200; i += 4)
{
u32 data = sdmmc_read32(REG_SDFIFO32);
*rDataPtr++ = data;
*rDataPtr++ = data >> 8;
*rDataPtr++ = data >> 16;
*rDataPtr++ = data >> 24;
}
size -= 0x200;
}
}
sdmmc_mask16(REG_DATACTL32, 0x800, 0);
}
}
if(!(ctl32 & 0x200))
{
if(writedata)
{
if(tUseBuf)
{
sdmmc_mask16(REG_SDSTATUS1, TMIO_STAT1_TXRQ, 0);
if(size > 0x1FF)
{
for(int i = 0; i < 0x200; i += 4)
{
u32 data = *tDataPtr++;
data |= (u32)*tDataPtr++ << 8;
data |= (u32)*tDataPtr++ << 16;
data |= (u32)*tDataPtr++ << 24;
sdmmc_write32(REG_SDFIFO32, data);
}
size -= 0x200;
}
}
sdmmc_mask16(REG_DATACTL32, 0x1000, 0);
}
}
if(status1 & TMIO_MASK_GW)
{
ctx->error |= 4;
break;
}
if(!(status1 & TMIO_STAT1_CMD_BUSY))
{
status0 = sdmmc_read16(REG_SDSTATUS0);
if(sdmmc_read16(REG_SDSTATUS0) & TMIO_STAT0_CMDRESPEND)
{
ctx->error |= 0x1;
}
if(status0 & TMIO_STAT0_DATAEND)
{
ctx->error |= 0x2;
}
if((status0 & flags) == flags)
break;
}
}
ctx->stat0 = sdmmc_read16(REG_SDSTATUS0);
ctx->stat1 = sdmmc_read16(REG_SDSTATUS1);
sdmmc_write16(REG_SDSTATUS0, 0);
sdmmc_write16(REG_SDSTATUS1, 0);
if(getSDRESP != 0)
{
ctx->ret[0] = (u32)(sdmmc_read16(REG_SDRESP0) | (sdmmc_read16(REG_SDRESP1) << 16));
ctx->ret[1] = (u32)(sdmmc_read16(REG_SDRESP2) | (sdmmc_read16(REG_SDRESP3) << 16));
ctx->ret[2] = (u32)(sdmmc_read16(REG_SDRESP4) | (sdmmc_read16(REG_SDRESP5) << 16));
ctx->ret[3] = (u32)(sdmmc_read16(REG_SDRESP6) | (sdmmc_read16(REG_SDRESP7) << 16));
}
}
int __attribute__((noinline)) sdmmc_sdcard_writesectors(u32 sector_no, u32 numsectors, const u8 *in)
{
if(handleSD.isSDHC == 0) sector_no <<= 9;
inittarget(&handleSD);
sdmmc_write16(REG_SDSTOP, 0x100);
sdmmc_write16(REG_SDBLKCOUNT32, numsectors);
sdmmc_write16(REG_SDBLKLEN32, 0x200);
sdmmc_write16(REG_SDBLKCOUNT, numsectors);
handleSD.tData = in;
handleSD.size = numsectors << 9;
sdmmc_send_command(&handleSD, 0x52C19, sector_no);
return geterror(&handleSD);
}
int __attribute__((noinline)) sdmmc_sdcard_readsectors(u32 sector_no, u32 numsectors, u8 *out)
{
if(handleSD.isSDHC == 0) sector_no <<= 9;
inittarget(&handleSD);
sdmmc_write16(REG_SDSTOP, 0x100);
sdmmc_write16(REG_SDBLKCOUNT32, numsectors);
sdmmc_write16(REG_SDBLKLEN32, 0x200);
sdmmc_write16(REG_SDBLKCOUNT, numsectors);
handleSD.rData = out;
handleSD.size = numsectors << 9;
sdmmc_send_command(&handleSD, 0x33C12, sector_no);
return geterror(&handleSD);
}
int __attribute__((noinline)) sdmmc_nand_readsectors(u32 sector_no, u32 numsectors, u8 *out)
{
if(handleNAND.isSDHC == 0) sector_no <<= 9;
inittarget(&handleNAND);
sdmmc_write16(REG_SDSTOP, 0x100);
sdmmc_write16(REG_SDBLKCOUNT32, numsectors);
sdmmc_write16(REG_SDBLKLEN32, 0x200);
sdmmc_write16(REG_SDBLKCOUNT, numsectors);
handleNAND.rData = out;
handleNAND.size = numsectors << 9;
sdmmc_send_command(&handleNAND, 0x33C12, sector_no);
inittarget(&handleSD);
return geterror(&handleNAND);
}
int __attribute__((noinline)) sdmmc_nand_writesectors(u32 sector_no, u32 numsectors, const u8 *in) //experimental
{
if(handleNAND.isSDHC == 0) sector_no <<= 9;
inittarget(&handleNAND);
sdmmc_write16(REG_SDSTOP, 0x100);
sdmmc_write16(REG_SDBLKCOUNT32, numsectors);
sdmmc_write16(REG_SDBLKLEN32, 0x200);
sdmmc_write16(REG_SDBLKCOUNT, numsectors);
handleNAND.tData = in;
handleNAND.size = numsectors << 9;
sdmmc_send_command(&handleNAND, 0x52C19, sector_no);
inittarget(&handleSD);
return geterror(&handleNAND);
}
static u32 calcSDSize(u8 *csd, int type)
{
u32 result = 0;
if(type == -1) type = csd[14] >> 6;
switch(type)
{
case 0:
{
u32 block_len = csd[9] & 0xF;
block_len = 1u << block_len;
u32 mult = (u32)((csd[4] >> 7) | ((csd[5] & 3) << 1));
mult = 1u << (mult + 2);
result = csd[8] & 3;
result = (result << 8) | csd[7];
result = (result << 2) | (csd[6] >> 6);
result = (result + 1) * mult * block_len / 512;
break;
}
case 1:
result = csd[7] & 0x3F;
result = (result << 8) | csd[6];
result = (result << 8) | csd[5];
result = (result + 1) * 1024;
break;
default:
break; //Do nothing otherwise FIXME perhaps return some error?
}
return result;
}
static void InitSD()
{
*(vu32 *)0x10000020 = 0; //InitFS stuff
*(vu32 *)0x10000020 = 0x200; //InitFS stuff
*(vu16 *)0x10006100 &= 0xF7FFu; //SDDATACTL32
*(vu16 *)0x10006100 &= 0xEFFFu; //SDDATACTL32
*(vu16 *)0x10006100 |= 0x402u; //SDDATACTL32
*(vu16 *)0x100060D8 = (*(vu16 *)0x100060D8 & 0xFFDD) | 2;
*(vu16 *)0x10006100 &= 0xFFFFu; //SDDATACTL32
*(vu16 *)0x100060D8 &= 0xFFDFu; //SDDATACTL
*(vu16 *)0x10006104 = 512; //SDBLKLEN32
*(vu16 *)0x10006108 = 1; //SDBLKCOUNT32
*(vu16 *)0x100060E0 &= 0xFFFEu; //SDRESET
*(vu16 *)0x100060E0 |= 1u; //SDRESET
*(vu16 *)0x10006020 |= TMIO_MASK_ALL; //SDIR_MASK0
*(vu16 *)0x10006022 |= TMIO_MASK_ALL>>16; //SDIR_MASK1
*(vu16 *)0x100060FC |= 0xDBu; //SDCTL_RESERVED7
*(vu16 *)0x100060FE |= 0xDBu; //SDCTL_RESERVED8
*(vu16 *)0x10006002 &= 0xFFFCu; //SDPORTSEL
*(vu16 *)0x10006024 = 0x20;
*(vu16 *)0x10006028 = 0x40EE;
*(vu16 *)0x10006002 &= 0xFFFCu; ////SDPORTSEL
*(vu16 *)0x10006026 = 512; //SDBLKLEN
*(vu16 *)0x10006008 = 0; //SDSTOP
}
static int Nand_Init()
{
//NAND
handleNAND.isSDHC = 0;
handleNAND.SDOPT = 0;
handleNAND.res = 0;
handleNAND.initarg = 1;
handleNAND.clk = 0x80;
handleNAND.devicenumber = 1;
inittarget(&handleNAND);
waitcycles(0xF000);
sdmmc_send_command(&handleNAND, 0, 0);
do
{
do
{
sdmmc_send_command(&handleNAND, 0x10701, 0x100000);
}
while(!(handleNAND.error & 1));
}
while((handleNAND.ret[0] & 0x80000000) == 0);
sdmmc_send_command(&handleNAND, 0x10602, 0x0);
if((handleNAND.error & 0x4)) return -1;
sdmmc_send_command(&handleNAND, 0x10403, handleNAND.initarg << 0x10);
if((handleNAND.error & 0x4)) return -1;
sdmmc_send_command(&handleNAND, 0x10609, handleNAND.initarg << 0x10);
if((handleNAND.error & 0x4)) return -1;
handleNAND.total_size = calcSDSize((u8*)&handleNAND.ret[0], 0);
handleNAND.clk = 1;
setckl(1);
sdmmc_send_command(&handleNAND, 0x10407, handleNAND.initarg << 0x10);
if((handleNAND.error & 0x4)) return -1;
handleNAND.SDOPT = 1;
sdmmc_send_command(&handleNAND, 0x10506, 0x3B70100);
if((handleNAND.error & 0x4)) return -1;
sdmmc_send_command(&handleNAND, 0x10506, 0x3B90100);
if((handleNAND.error & 0x4)) return -1;
sdmmc_send_command(&handleNAND, 0x1040D, handleNAND.initarg << 0x10);
if((handleNAND.error & 0x4)) return -1;
sdmmc_send_command(&handleNAND, 0x10410, 0x200);
if((handleNAND.error & 0x4)) return -1;
handleNAND.clk |= 0x200;
inittarget(&handleSD);
return 0;
}
static int SD_Init()
{
//SD
handleSD.isSDHC = 0;
handleSD.SDOPT = 0;
handleSD.res = 0;
handleSD.initarg = 0;
handleSD.clk = 0x80;
handleSD.devicenumber = 0;
inittarget(&handleSD);
waitcycles(1u << 22); //Card needs a little bit of time to be detected, it seems FIXME test again to see what a good number is for the delay
//If not inserted
if(!(*((vu16 *)(SDMMC_BASE + REG_SDSTATUS0)) & TMIO_STAT0_SIGSTATE)) return 5;
sdmmc_send_command(&handleSD, 0, 0);
sdmmc_send_command(&handleSD, 0x10408, 0x1AA);
u32 temp = (handleSD.error & 0x1) << 0x1E;
u32 temp2 = 0;
do
{
do
{
sdmmc_send_command(&handleSD, 0x10437, handleSD.initarg << 0x10);
sdmmc_send_command(&handleSD, 0x10769, 0x00FF8000 | temp);
temp2 = 1;
}
while(!(handleSD.error & 1));
}
while((handleSD.ret[0] & 0x80000000) == 0);
if(!((handleSD.ret[0] >> 30) & 1) || !temp)
temp2 = 0;
handleSD.isSDHC = temp2;
sdmmc_send_command(&handleSD, 0x10602, 0);
if((handleSD.error & 0x4)) return -1;
sdmmc_send_command(&handleSD, 0x10403, 0);
if((handleSD.error & 0x4)) return -2;
handleSD.initarg = handleSD.ret[0] >> 0x10;
sdmmc_send_command(&handleSD, 0x10609, handleSD.initarg << 0x10);
if((handleSD.error & 0x4)) return -3;
handleSD.total_size = calcSDSize((u8*)&handleSD.ret[0], -1);
handleSD.clk = 1;
setckl(1);
sdmmc_send_command(&handleSD, 0x10507, handleSD.initarg << 0x10);
if((handleSD.error & 0x4)) return -4;
sdmmc_send_command(&handleSD, 0x10437, handleSD.initarg << 0x10);
if((handleSD.error & 0x4)) return -5;
handleSD.SDOPT = 1;
sdmmc_send_command(&handleSD, 0x10446, 0x2);
if((handleSD.error & 0x4)) return -6;
sdmmc_send_command(&handleSD, 0x1040D, handleSD.initarg << 0x10);
if((handleSD.error & 0x4)) return -7;
sdmmc_send_command(&handleSD, 0x10410, 0x200);
if((handleSD.error & 0x4)) return -8;
handleSD.clk |= 0x200;
return 0;
}
void sdmmc_get_cid(bool isNand, u32 *info)
{
struct mmcdevice *device = isNand ? &handleNAND : &handleSD;
inittarget(device);
// use cmd7 to put sd card in standby mode
// CMD7
sdmmc_send_command(device, 0x10507, 0);
// get sd card info
// use cmd10 to read CID
sdmmc_send_command(device, 0x1060A, device->initarg << 0x10);
for(int i = 0; i < 4; ++i)
info[i] = device->ret[i];
// put sd card back to transfer mode
// CMD7
sdmmc_send_command(device, 0x10507, device->initarg << 0x10);
}
u32 sdmmc_sdcard_init()
{
u32 ret = 0;
InitSD();
if(Nand_Init() != 0) ret |= 1;
if(SD_Init() != 0) ret |= 2;
return ret;
}

View File

@@ -0,0 +1,100 @@
#pragma once
#include "../../types.h"
#define SDMMC_BASE 0x10006000
#define REG_SDCMD 0x00
#define REG_SDPORTSEL 0x02
#define REG_SDCMDARG 0x04
#define REG_SDCMDARG0 0x04
#define REG_SDCMDARG1 0x06
#define REG_SDSTOP 0x08
#define REG_SDBLKCOUNT 0x0A
#define REG_SDRESP0 0x0C
#define REG_SDRESP1 0x0E
#define REG_SDRESP2 0x10
#define REG_SDRESP3 0x12
#define REG_SDRESP4 0x14
#define REG_SDRESP5 0x16
#define REG_SDRESP6 0x18
#define REG_SDRESP7 0x1A
#define REG_SDSTATUS0 0x1C
#define REG_SDSTATUS1 0x1E
#define REG_SDIRMASK0 0x20
#define REG_SDIRMASK1 0x22
#define REG_SDCLKCTL 0x24
#define REG_SDBLKLEN 0x26
#define REG_SDOPT 0x28
#define REG_SDFIFO 0x30
#define REG_DATACTL 0xD8
#define REG_SDRESET 0xE0
#define REG_SDPROTECTED 0xF6 //bit 0 determines if sd is protected or not?
#define REG_DATACTL32 0x100
#define REG_SDBLKLEN32 0x104
#define REG_SDBLKCOUNT32 0x108
#define REG_SDFIFO32 0x10C
#define REG_CLK_AND_WAIT_CTL 0x138
#define REG_RESET_SDIO 0x1E0
#define TMIO_STAT0_CMDRESPEND 0x0001
#define TMIO_STAT0_DATAEND 0x0004
#define TMIO_STAT0_CARD_REMOVE 0x0008
#define TMIO_STAT0_CARD_INSERT 0x0010
#define TMIO_STAT0_SIGSTATE 0x0020
#define TMIO_STAT0_WRPROTECT 0x0080
#define TMIO_STAT0_CARD_REMOVE_A 0x0100
#define TMIO_STAT0_CARD_INSERT_A 0x0200
#define TMIO_STAT0_SIGSTATE_A 0x0400
#define TMIO_STAT1_CMD_IDX_ERR 0x0001
#define TMIO_STAT1_CRCFAIL 0x0002
#define TMIO_STAT1_STOPBIT_ERR 0x0004
#define TMIO_STAT1_DATATIMEOUT 0x0008
#define TMIO_STAT1_RXOVERFLOW 0x0010
#define TMIO_STAT1_TXUNDERRUN 0x0020
#define TMIO_STAT1_CMDTIMEOUT 0x0040
#define TMIO_STAT1_RXRDY 0x0100
#define TMIO_STAT1_TXRQ 0x0200
#define TMIO_STAT1_ILL_FUNC 0x2000
#define TMIO_STAT1_CMD_BUSY 0x4000
#define TMIO_STAT1_ILL_ACCESS 0x8000
#define TMIO_MASK_ALL 0x837F031D
#define TMIO_MASK_GW (TMIO_STAT1_ILL_ACCESS | TMIO_STAT1_CMDTIMEOUT | TMIO_STAT1_TXUNDERRUN | TMIO_STAT1_RXOVERFLOW | \
TMIO_STAT1_DATATIMEOUT | TMIO_STAT1_STOPBIT_ERR | TMIO_STAT1_CRCFAIL | TMIO_STAT1_CMD_IDX_ERR)
#define TMIO_MASK_READOP (TMIO_STAT1_RXRDY | TMIO_STAT1_DATAEND)
#define TMIO_MASK_WRITEOP (TMIO_STAT1_TXRQ | TMIO_STAT1_DATAEND)
typedef struct mmcdevice {
u8 *rData;
const u8 *tData;
u32 size;
u32 error;
u16 stat0;
u16 stat1;
u32 ret[4];
u32 initarg;
u32 isSDHC;
u32 clk;
u32 SDOPT;
u32 devicenumber;
u32 total_size; //size in sectors of the device
u32 res;
} mmcdevice;
u32 sdmmc_sdcard_init();
int sdmmc_sdcard_readsectors(u32 sector_no, u32 numsectors, u8 *out);
int sdmmc_sdcard_writesectors(u32 sector_no, u32 numsectors, const u8 *in);
int sdmmc_nand_readsectors(u32 sector_no, u32 numsectors, u8 *out);
int sdmmc_nand_writesectors(u32 sector_no, u32 numsectors, const u8 *in);
void sdmmc_get_cid(bool isNand, u32 *info);
mmcdevice *getMMCDevice(int drive);

533
arm9/source/firm.c Executable file
View File

@@ -0,0 +1,533 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "firm.h"
#include "config.h"
#include "utils.h"
#include "fs.h"
#include "exceptions.h"
#include "patches.h"
#include "memory.h"
#include "strings.h"
#include "cache.h"
#include "emunand.h"
#include "crypto.h"
#include "screen.h"
#include "fmt.h"
#include "chainloader.h"
static Firm *firm = (Firm *)0x20001000;
static __attribute__((noinline)) bool overlaps(u32 as, u32 ae, u32 bs, u32 be)
{
if(as <= bs && bs <= ae)
return true;
if(bs <= as && as <= be)
return true;
return false;
}
static __attribute__((noinline)) bool inRange(u32 as, u32 ae, u32 bs, u32 be)
{
if(as >= bs && ae <= be)
return true;
return false;
}
static bool checkFirm(u32 firmSize)
{
if(memcmp(firm->magic, "FIRM", 4) != 0 || firm->arm9Entry == NULL) //Allow for the ARM11 entrypoint to be zero in which case nothing is done on the ARM11 side
return false;
bool arm9EpFound = false,
arm11EpFound = false;
u32 size = 0x200;
for(u32 i = 0; i < 4; i++)
size += firm->section[i].size;
if(firmSize < size) return false;
for(u32 i = 0; i < 4; i++)
{
FirmSection *section = &firm->section[i];
//Allow empty sections
if(section->size == 0)
continue;
if((section->offset < 0x200) ||
(section->address + section->size < section->address) || //Overflow check
((u32)section->address & 3) || (section->offset & 0x1FF) || (section->size & 0x1FF) || //Alignment check
(overlaps((u32)section->address, (u32)section->address + section->size, (u32)firm, (u32)firm + size)) ||
((!inRange((u32)section->address, (u32)section->address + section->size, 0x08000000, 0x08000000 + 0x00100000)) &&
(!inRange((u32)section->address, (u32)section->address + section->size, 0x18000000, 0x18000000 + 0x00600000)) &&
(!inRange((u32)section->address, (u32)section->address + section->size, 0x1FF00000, 0x1FFFFC00)) &&
(!inRange((u32)section->address, (u32)section->address + section->size, 0x20000000, 0x20000000 + 0x8000000))))
return false;
__attribute__((aligned(4))) u8 hash[0x20];
sha(hash, (u8 *)firm + section->offset, section->size, SHA_256_MODE);
if(memcmp(hash, section->hash, 0x20) != 0)
return false;
if(firm->arm9Entry >= section->address && firm->arm9Entry < (section->address + section->size))
arm9EpFound = true;
if(firm->arm11Entry >= section->address && firm->arm11Entry < (section->address + section->size))
arm11EpFound = true;
}
return arm9EpFound && (firm->arm11Entry == NULL || arm11EpFound);
}
static inline u32 loadFirmFromStorage(FirmwareType firmType)
{
static const char *firmwareFiles[] = {
"native.firm",
"twl.firm",
"agb.firm",
"safe.firm",
"sysupdater.firm"
},
*cetkFiles[] = {
"cetk",
"cetk_twl",
"cetk_agb",
"cetk_safe",
"cetk_sysupdater"
};
u32 firmSize = fileRead(firm, firmwareFiles[(u32)firmType], 0x400000 + sizeof(Cxi) + 0x200);
if(!firmSize) return 0;
static const char *extFirmError = "The external FIRM is not valid.";
if(firmSize <= sizeof(Cxi) + 0x200) error(extFirmError);
if(memcmp(firm, "FIRM", 4) != 0)
{
if(firmSize <= sizeof(Cxi) + 0x400) error(extFirmError);
u8 cetk[0xA50];
if(fileRead(cetk, cetkFiles[(u32)firmType], sizeof(cetk)) != sizeof(cetk))
error("The cetk is missing or corrupted.");
firmSize = decryptNusFirm((Ticket *)(cetk + 0x140), (Cxi *)firm, firmSize);
if(!firmSize) error("Unable to decrypt the external FIRM.");
}
if(!checkFirm(firmSize)) error("The external FIRM is invalid or corrupted.");
return firmSize;
}
u32 loadNintendoFirm(FirmwareType *firmType, FirmwareSource nandType, bool loadFromStorage, bool isSafeMode)
{
u32 firmVersion,
firmSize;
bool ctrNandError = isSdMode && !mountFs(false, false);
if(!ctrNandError)
{
//Load FIRM from CTRNAND
firmVersion = firmRead(firm, (u32)*firmType);
if(firmVersion == 0xFFFFFFFF) ctrNandError = true;
else
{
firmSize = decryptExeFs((Cxi *)firm);
if(!firmSize || !checkFirm(firmSize)) ctrNandError = true;
}
}
bool loadedFromStorage = false;
if(loadFromStorage || ctrNandError)
{
u32 result = loadFirmFromStorage(*firmType);
if(result != 0)
{
loadedFromStorage = true;
firmSize = result;
}
else if(ctrNandError) error("Unable to mount CTRNAND or load the CTRNAND FIRM.\nPlease use an external one.");
}
//Check that the FIRM is right for the console from the ARM9 section address
if((firm->section[3].offset != 0 ? firm->section[3].address : firm->section[2].address) != (ISN3DS ? (u8 *)0x8006000 : (u8 *)0x8006800))
error("The %s FIRM is not for this console.", loadedFromStorage ? "external" : "CTRNAND");
if(!ISN3DS && *firmType == NATIVE_FIRM && firm->section[0].address == (u8 *)0x1FF80000)
{
//We can't boot < 3.x EmuNANDs
if(nandType != FIRMWARE_SYSNAND) error("An old unsupported EmuNAND has been detected.\nLuma3DS is unable to boot it.");
if(isSafeMode) error("SAFE_MODE is not supported on 1.x/2.x FIRM.");
*firmType = NATIVE_FIRM1X2X;
}
if(loadedFromStorage || ISDEVUNIT)
{
firmVersion = 0xFFFFFFFF;
if(!ISN3DS && *firmType == NATIVE_FIRM)
{
__attribute__((aligned(4))) static const u8 hashes[3][0x20] = {
{0x39, 0x75, 0xB5, 0x28, 0x24, 0x5E, 0x8B, 0x56, 0xBC, 0x83, 0x79, 0x41, 0x09, 0x2C, 0x42, 0xE6,
0x26, 0xB6, 0x80, 0x59, 0xA5, 0x56, 0xF9, 0xF9, 0x6E, 0xF3, 0x63, 0x05, 0x58, 0xDF, 0x35, 0xEF},
{0x81, 0x9E, 0x71, 0x58, 0xE5, 0x44, 0x73, 0xF7, 0x48, 0x78, 0x7C, 0xEF, 0x5E, 0x30, 0xE2, 0x28,
0x78, 0x0B, 0x21, 0x23, 0x94, 0x63, 0xE8, 0x4E, 0x06, 0xBB, 0xD6, 0x8D, 0xA0, 0x99, 0xAE, 0x98},
{0x1D, 0xD5, 0xB0, 0xC2, 0xD9, 0x4A, 0x4A, 0xF3, 0x23, 0xDD, 0x2F, 0x65, 0x21, 0x95, 0x9B, 0x7E,
0xF2, 0x71, 0x7E, 0xB6, 0x7A, 0x3A, 0x74, 0x78, 0x0D, 0xE3, 0xB5, 0x0C, 0x2B, 0x7F, 0x85, 0x37}
};
u32 i;
for(i = 0; i < 3; i++) if(memcmp(firm->section[1].hash, hashes[i], 0x20) == 0) break;
switch(i)
{
case 0:
firmVersion = 0x18;
break;
case 1:
firmVersion = 0x1D;
break;
case 2:
firmVersion = 0x1F;
break;
}
}
}
return firmVersion;
}
void loadHomebrewFirm(u32 pressed)
{
char path[10 + 255];
bool found = !pressed ? payloadMenu(path) : findPayload(path, pressed);
if(!found) return;
u32 maxPayloadSize = (u32)((u8 *)0x27FFE000 - (u8 *)firm),
payloadSize = fileRead(firm, path, maxPayloadSize);
if(payloadSize <= 0x200 || !checkFirm(payloadSize)) error("The payload is invalid or corrupted.");
char absPath[24 + 255];
if(isSdMode) sprintf(absPath, "sdmc:/luma/%s", path);
else sprintf(absPath, "nand:/rw/luma/%s", path);
char *argv[2] = {absPath, (char *)fbs};
initScreens();
launchFirm((firm->reserved2[0] & 1) ? 2 : 1, argv);
}
static inline void mergeSection0(FirmwareType firmType, u32 firmVersion, bool loadFromStorage)
{
u32 srcModuleSize,
nbModules = 0;
struct
{
char name[8];
u8 *src;
u32 size;
} moduleList[6];
//1) Parse info concerning Nintendo's modules
for(u8 *src = (u8 *)firm + firm->section[0].offset, *srcEnd = src + firm->section[0].size; src < srcEnd; src += srcModuleSize, nbModules++)
{
memcpy(moduleList[nbModules].name, ((Cxi *)src)->exHeader.systemControlInfo.appTitle, 8);
moduleList[nbModules].src = src;
srcModuleSize = moduleList[nbModules].size = ((Cxi *)src)->ncch.contentSize * 0x200;
}
if(firmType == NATIVE_FIRM && (ISN3DS || firmVersion >= 0x1D))
{
//2) Merge that info with our own modules'
for(u8 *src = (u8 *)0x18180000; src < (u8 *)(0x18180000 + LUMA_SECTION0_SIZE); src += srcModuleSize)
{
const char *name = ((Cxi *)src)->exHeader.systemControlInfo.appTitle;
u32 i;
for(i = 0; i < 5 && memcmp(name, moduleList[i].name, 8) != 0; i++);
if(i == 5)
{
nbModules++;
memcpy(moduleList[i].name, ((Cxi *)src)->exHeader.systemControlInfo.appTitle, 8);
}
moduleList[i].src = src;
srcModuleSize = moduleList[i].size = ((Cxi *)src)->ncch.contentSize * 0x200;
}
}
//3) Read or copy the modules
u8 *dst = firm->section[0].address;
const char *extModuleSizeError = "The external FIRM modules are too large.";
for(u32 i = 0, dstModuleSize, maxModuleSize = firmType == NATIVE_FIRM ? 0x80000 : 0x600000; i < nbModules; i++, dst += dstModuleSize, maxModuleSize -= dstModuleSize)
{
if(loadFromStorage)
{
char fileName[24];
//Read modules from files if they exist
sprintf(fileName, "sysmodules/%.8s.cxi", moduleList[i].name);
dstModuleSize = getFileSize(fileName);
if(dstModuleSize != 0)
{
if(dstModuleSize > maxModuleSize) error(extModuleSizeError);
if(dstModuleSize <= sizeof(Cxi) + 0x200 ||
fileRead(dst, fileName, dstModuleSize) != dstModuleSize ||
memcmp(((Cxi *)dst)->ncch.magic, "NCCH", 4) != 0 ||
memcmp(moduleList[i].name, ((Cxi *)dst)->exHeader.systemControlInfo.appTitle, sizeof(((Cxi *)dst)->exHeader.systemControlInfo.appTitle)) != 0)
error("An external FIRM module is invalid or corrupted.");
continue;
}
}
dstModuleSize = moduleList[i].size;
if(dstModuleSize > maxModuleSize) error(extModuleSizeError);
memcpy(dst, moduleList[i].src, dstModuleSize);
}
//4) Patch NATIVE_FIRM if necessary
if(nbModules == 6)
{
if(patchK11ModuleLoading(firm->section[0].size, dst - firm->section[0].address, (u8 *)firm + firm->section[1].offset, firm->section[1].size) != 0)
error("Failed to inject custom sysmodule");
}
}
u32 patchNativeFirm(u32 firmVersion, FirmwareSource nandType, bool loadFromStorage, bool isFirmProtEnabled, bool needToInitSd, bool doUnitinfoPatch)
{
u8 *arm9Section = (u8 *)firm + firm->section[2].offset,
*arm11Section1 = (u8 *)firm + firm->section[1].offset;
if(ISN3DS)
{
//Decrypt ARM9Bin and patch ARM9 entrypoint to skip kernel9loader
kernel9Loader((Arm9Bin *)arm9Section);
firm->arm9Entry = (u8 *)0x801B01C;
}
//Find the Process9 .code location, size and memory address
u32 process9Size,
process9MemAddr;
u8 *process9Offset = getProcess9Info(arm9Section, firm->section[2].size, &process9Size, &process9MemAddr);
//Find the Kernel11 SVC table and handler, exceptions page and free space locations
u32 baseK11VA;
u8 *freeK11Space;
u32 *arm11SvcHandler,
*arm11ExceptionsPage,
*arm11SvcTable = getKernel11Info(arm11Section1, firm->section[1].size, &baseK11VA, &freeK11Space, &arm11SvcHandler, &arm11ExceptionsPage);
u32 kernel9Size = (u32)(process9Offset - arm9Section) - sizeof(Cxi) - 0x200,
ret = 0;
//Skip on FIRMs < 4.0
if(ISN3DS || firmVersion >= 0x1D)
{
ret += installK11Extension(arm11Section1, firm->section[1].size, needToInitSd, baseK11VA, arm11ExceptionsPage, &freeK11Space);
ret += patchKernel11(arm11Section1, firm->section[1].size, baseK11VA, arm11SvcTable, arm11ExceptionsPage);
}
//Apply signature patches
ret += patchSignatureChecks(process9Offset, process9Size);
//Apply EmuNAND patches
if(nandType != FIRMWARE_SYSNAND) ret += patchEmuNand(arm9Section, kernel9Size, process9Offset, process9Size, firm->section[2].address, firmVersion);
//Apply FIRM0/1 writes patches on SysNAND to protect A9LH
else if(isFirmProtEnabled) ret += patchFirmWrites(process9Offset, process9Size);
//Apply firmlaunch patches
ret += patchFirmlaunches(process9Offset, process9Size, process9MemAddr);
//Apply dev unit check patches related to NCCH encryption
if(!ISDEVUNIT)
{
ret += patchZeroKeyNcchEncryptionCheck(process9Offset, process9Size);
ret += patchNandNcchEncryptionCheck(process9Offset, process9Size);
}
//Apply anti-anti-DG patches on 11.0+
if(firmVersion >= (ISN3DS ? 0x21 : 0x52)) ret += patchTitleInstallMinVersionChecks(process9Offset, process9Size, firmVersion);
//patch P9 AM ticket wrapper on 11.8+ to use 0 Key and IV, only on UNITINFO patch to prevent NIM from actually send any
if(doUnitinfoPatch && firmVersion >= (ISN3DS ? 0x35 : 0x64)) ret += patchP9AMTicketWrapperZeroKeyIV(process9Offset, process9Size);
//Apply UNITINFO patches
if(doUnitinfoPatch)
{
ret += patchUnitInfoValueSet(arm9Section, kernel9Size);
if(!ISDEVUNIT) ret += patchCheckForDevCommonKey(process9Offset, process9Size);
}
//ARM9 exception handlers
ret += patchArm9ExceptionHandlersInstall(arm9Section, kernel9Size);
ret += patchSvcBreak9(arm9Section, kernel9Size, (u32)firm->section[2].address);
ret += patchKernel9Panic(arm9Section, kernel9Size);
ret += patchP9AccessChecks(process9Offset, process9Size);
mergeSection0(NATIVE_FIRM, firmVersion, loadFromStorage);
firm->section[0].size = 0;
return ret;
}
u32 patchTwlFirm(u32 firmVersion, bool loadFromStorage, bool doUnitinfoPatch)
{
u8 *arm9Section = (u8 *)firm + firm->section[3].offset;
//On N3DS, decrypt ARM9Bin and patch ARM9 entrypoint to skip kernel9loader
if(ISN3DS)
{
kernel9Loader((Arm9Bin *)arm9Section);
firm->arm9Entry = (u8 *)0x801301C;
}
//Find the Process9 .code location, size and memory address
u32 process9Size,
process9MemAddr;
u8 *process9Offset = getProcess9Info(arm9Section, firm->section[3].size, &process9Size, &process9MemAddr);
u32 kernel9Size = (u32)(process9Offset - arm9Section) - sizeof(Cxi) - 0x200,
ret = 0;
ret += patchLgySignatureChecks(process9Offset, process9Size);
ret += patchTwlInvalidSignatureChecks(process9Offset, process9Size);
ret += patchTwlNintendoLogoChecks(process9Offset, process9Size);
ret += patchTwlWhitelistChecks(process9Offset, process9Size);
if(ISN3DS || firmVersion > 0x11) ret += patchTwlFlashcartChecks(process9Offset, process9Size, firmVersion);
else if(!ISN3DS && firmVersion == 0x11) ret += patchOldTwlFlashcartChecks(process9Offset, process9Size);
ret += patchTwlShaHashChecks(process9Offset, process9Size);
//Apply UNITINFO patch
if(doUnitinfoPatch) ret += patchUnitInfoValueSet(arm9Section, kernel9Size);
if(loadFromStorage)
{
mergeSection0(TWL_FIRM, 0, true);
firm->section[0].size = 0;
}
return ret;
}
u32 patchAgbFirm(bool loadFromStorage, bool doUnitinfoPatch)
{
u8 *arm9Section = (u8 *)firm + firm->section[3].offset;
//On N3DS, decrypt ARM9Bin and patch ARM9 entrypoint to skip kernel9loader
if(ISN3DS)
{
kernel9Loader((Arm9Bin *)arm9Section);
firm->arm9Entry = (u8 *)0x801301C;
}
//Find the Process9 .code location, size and memory address
u32 process9Size,
process9MemAddr;
u8 *process9Offset = getProcess9Info(arm9Section, firm->section[3].size, &process9Size, &process9MemAddr);
u32 kernel9Size = (u32)(process9Offset - arm9Section) - sizeof(Cxi) - 0x200,
ret = 0;
ret += patchLgySignatureChecks(process9Offset, process9Size);
if(CONFIG(SHOWGBABOOT)) ret += patchAgbBootSplash(process9Offset, process9Size);
//Apply UNITINFO patch
if(doUnitinfoPatch) ret += patchUnitInfoValueSet(arm9Section, kernel9Size);
if(loadFromStorage)
{
mergeSection0(AGB_FIRM, 0, true);
firm->section[0].size = 0;
}
return ret;
}
u32 patch1x2xNativeAndSafeFirm(void)
{
u8 *arm9Section = (u8 *)firm + firm->section[2].offset;
if(ISN3DS)
{
//Decrypt ARM9Bin and patch ARM9 entrypoint to skip kernel9loader
kernel9Loader((Arm9Bin *)arm9Section);
firm->arm9Entry = (u8 *)0x801B01C;
}
//Find the Process9 .code location, size and memory address
u32 process9Size,
process9MemAddr;
u8 *process9Offset = getProcess9Info(arm9Section, firm->section[2].size, &process9Size, &process9MemAddr);
u32 kernel9Size = (u32)(process9Offset - arm9Section) - sizeof(Cxi) - 0x200,
ret = 0;
ret += ISN3DS ? patchFirmWrites(process9Offset, process9Size) : patchOldFirmWrites(process9Offset, process9Size);
ret += ISN3DS ? patchSignatureChecks(process9Offset, process9Size) : patchOldSignatureChecks(process9Offset, process9Size);
//ARM9 exception handlers
ret += patchArm9ExceptionHandlersInstall(arm9Section, kernel9Size);
ret += patchSvcBreak9(arm9Section, kernel9Size, (u32)firm->section[2].address);
return ret;
}
void launchFirm(int argc, char **argv)
{
prepareArm11ForFirmlaunch();
chainload(argc, argv, firm);
}

38
arm9/source/firm.h Normal file
View File

@@ -0,0 +1,38 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#pragma once
#include "types.h"
#include "3dsheaders.h"
u32 loadNintendoFirm(FirmwareType *firmType, FirmwareSource nandType, bool loadFromStorage, bool isSafeMode);
void loadHomebrewFirm(u32 pressed);
u32 patchNativeFirm(u32 firmVersion, FirmwareSource nandType, bool loadFromStorage, bool isFirmProtEnabled, bool needToInitSd, bool doUnitinfoPatch);
u32 patchTwlFirm(u32 firmVersion, bool loadFromStorage, bool doUnitinfoPatch);
u32 patchAgbFirm(bool loadFromStorage, bool doUnitinfoPatch);
u32 patch1x2xNativeAndSafeFirm(void);
void launchFirm(int argc, char **argv);

319
arm9/source/fmt.c Normal file
View File

@@ -0,0 +1,319 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/* File : barebones/ee_printf.c
This file contains an implementation of ee_printf that only requires a method to output a char to a UART without pulling in library code.
This code is based on a file that contains the following:
Copyright (C) 2002 Michael Ringgaard. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
//TuxSH's changes: add support for 64-bit numbers, remove floating-point code
#include "strings.h"
#include "fmt.h"
#define ZEROPAD (1<<0) //Pad with zero
#define SIGN (1<<1) //Unsigned/signed long
#define PLUS (1<<2) //Show plus
#define SPACE (1<<3) //Spacer
#define LEFT (1<<4) //Left justified
#define HEX_PREP (1<<5) //0x
#define UPPERCASE (1<<6) //'ABCDEF'
#define IS_DIGIT(c) ((c) >= '0' && (c) <= '9')
static s32 skipAtoi(const char **s)
{
s32 i = 0;
while(IS_DIGIT(**s)) i = i * 10 + *((*s)++) - '0';
return i;
}
static char *processNumber(char *str, s64 num, bool isHex, s32 size, s32 precision, u32 type)
{
char sign = 0;
if(type & SIGN)
{
if(num < 0)
{
sign = '-';
num = -num;
size--;
}
else if(type & PLUS)
{
sign = '+';
size--;
}
else if(type & SPACE)
{
sign = ' ';
size--;
}
}
static const char *lowerDigits = "0123456789abcdef",
*upperDigits = "0123456789ABCDEF";
s32 i = 0;
char tmp[20];
const char *dig = (type & UPPERCASE) ? upperDigits : lowerDigits;
if(num == 0)
{
if(precision != 0) tmp[i++] = '0';
type &= ~HEX_PREP;
}
else
{
while(num != 0)
{
u64 base = isHex ? 16ULL : 10ULL;
tmp[i++] = dig[(u64)num % base];
num = (s64)((u64)num / base);
}
}
if(type & LEFT || precision != -1) type &= ~ZEROPAD;
if(type & HEX_PREP && isHex) size -= 2;
if(i > precision) precision = i;
size -= precision;
if(!(type & (ZEROPAD | LEFT))) while(size-- > 0) *str++ = ' ';
if(sign) *str++ = sign;
if(type & HEX_PREP && isHex)
{
*str++ = '0';
*str++ = 'x';
}
if(type & ZEROPAD) while(size-- > 0) *str++ = '0';
while(i < precision--) *str++ = '0';
while(i-- > 0) *str++ = tmp[i];
while(size-- > 0) *str++ = ' ';
return str;
}
u32 vsprintf(char *buf, const char *fmt, va_list args)
{
char *str;
for(str = buf; *fmt; fmt++)
{
if(*fmt != '%')
{
*str++ = *fmt;
continue;
}
//Process flags
u32 flags = 0; //Flags to number()
bool loop = true;
while(loop)
{
switch(*++fmt)
{
case '-': flags |= LEFT; break;
case '+': flags |= PLUS; break;
case ' ': flags |= SPACE; break;
case '#': flags |= HEX_PREP; break;
case '0': flags |= ZEROPAD; break;
default: loop = false; break;
}
}
//Get field width
s32 fieldWidth = -1; //Width of output field
if(IS_DIGIT(*fmt)) fieldWidth = skipAtoi(&fmt);
else if(*fmt == '*')
{
fmt++;
fieldWidth = va_arg(args, s32);
if(fieldWidth < 0)
{
fieldWidth = -fieldWidth;
flags |= LEFT;
}
}
//Get the precision
s32 precision = -1; //Min. # of digits for integers; max number of chars for from string
if(*fmt == '.')
{
fmt++;
if(IS_DIGIT(*fmt)) precision = skipAtoi(&fmt);
else if(*fmt == '*')
{
fmt++;
precision = va_arg(args, s32);
}
if(precision < 0) precision = 0;
}
//Get the conversion qualifier
u32 integerType = 0;
if(*fmt == 'l')
{
if(*++fmt == 'l')
{
fmt++;
integerType = 1;
}
}
else if(*fmt == 'h')
{
if(*++fmt == 'h')
{
fmt++;
integerType = 3;
}
else integerType = 2;
}
bool isHex;
switch(*fmt)
{
case 'c':
if(!(flags & LEFT)) while(--fieldWidth > 0) *str++ = ' ';
*str++ = (u8)va_arg(args, s32);
while(--fieldWidth > 0) *str++ = ' ';
continue;
case 's':
{
char *s = va_arg(args, char *);
if(!s) s = "<NULL>";
u32 len = (precision != -1) ? strnlen(s, precision) : strlen(s);
if(!(flags & LEFT)) while((s32)len < fieldWidth--) *str++ = ' ';
for(u32 i = 0; i < len; i++) *str++ = *s++;
while((s32)len < fieldWidth--) *str++ = ' ';
continue;
}
case 'p':
if(fieldWidth == -1)
{
fieldWidth = 8;
flags |= ZEROPAD;
}
str = processNumber(str, va_arg(args, u32), true, fieldWidth, precision, flags);
continue;
//Integer number formats - set up the flags and "break"
case 'X':
flags |= UPPERCASE;
//Falls through
case 'x':
isHex = true;
break;
case 'd':
case 'i':
flags |= SIGN;
//Falls through
case 'u':
isHex = false;
break;
default:
if(*fmt != '%') *str++ = '%';
if(*fmt) *str++ = *fmt;
else fmt--;
continue;
}
s64 num;
if(flags & SIGN)
{
if(integerType == 1) num = va_arg(args, s64);
else num = va_arg(args, s32);
if(integerType == 2) num = (s16)num;
else if(integerType == 3) num = (s8)num;
}
else
{
if(integerType == 1) num = va_arg(args, u64);
else num = va_arg(args, u32);
if(integerType == 2) num = (u16)num;
else if(integerType == 3) num = (u8)num;
}
str = processNumber(str, num, isHex, fieldWidth, precision, flags);
}
*str = 0;
return str - buf;
}
u32 sprintf(char *buf, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
u32 res = vsprintf(buf, fmt, args);
va_end(args);
return res;
}

32
arm9/source/fmt.h Normal file
View File

@@ -0,0 +1,32 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#pragma once
#include "memory.h"
#include <stdarg.h>
u32 vsprintf(char *buf, const char *fmt, va_list args);
u32 sprintf(char *buf, const char *fmt, ...);

144
arm9/source/font.h Normal file
View File

@@ -0,0 +1,144 @@
/*
This file was autogenerated by raw2c.
Visit http://www.devkitpro.org
*/
//---------------------------------------------------------------------------------
#ifndef _font_h_
#define _font_h_
//---------------------------------------------------------------------------------
static const unsigned char font[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x81, 0xa5, 0x81, 0xbd, 0x99, 0x81, 0x7e,
0x7e, 0xff, 0xdb, 0xff, 0xc3, 0xe7, 0xff, 0x7e, 0x6c, 0xfe, 0xfe, 0xfe, 0x7c, 0x38, 0x10, 0x00,
0x10, 0x38, 0x7c, 0xfe, 0x7c, 0x38, 0x10, 0x00, 0x3c, 0x3c, 0x18, 0xff, 0xe7, 0x18, 0x3c, 0x00,
0x10, 0x38, 0x7c, 0xfe, 0xee, 0x10, 0x38, 0x00, 0x00, 0x00, 0x18, 0x3c, 0x3c, 0x18, 0x00, 0x00,
0xff, 0xff, 0xe7, 0xc3, 0xc3, 0xe7, 0xff, 0xff, 0x00, 0x3c, 0x66, 0x42, 0x42, 0x66, 0x3c, 0x00,
0xff, 0xc3, 0x99, 0xbd, 0xbd, 0x99, 0xc3, 0xff, 0x0f, 0x07, 0x0f, 0x7d, 0xcc, 0xcc, 0xcc, 0x78,
0x3c, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x7e, 0x18, 0x08, 0x0c, 0x0a, 0x0a, 0x08, 0x78, 0xf0, 0x00,
0x18, 0x14, 0x1a, 0x16, 0x72, 0xe2, 0x0e, 0x1c, 0x10, 0x54, 0x38, 0xee, 0x38, 0x54, 0x10, 0x00,
0x80, 0xe0, 0xf8, 0xfe, 0xf8, 0xe0, 0x80, 0x00, 0x02, 0x0e, 0x3e, 0xfe, 0x3e, 0x0e, 0x02, 0x00,
0x18, 0x3c, 0x5a, 0x18, 0x5a, 0x3c, 0x18, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x00,
0x7f, 0xdb, 0xdb, 0xdb, 0x7b, 0x1b, 0x1b, 0x00, 0x1c, 0x22, 0x38, 0x44, 0x44, 0x38, 0x88, 0x70,
0x00, 0x00, 0x00, 0x00, 0x7e, 0x7e, 0x7e, 0x00, 0x18, 0x3c, 0x5a, 0x18, 0x5a, 0x3c, 0x18, 0x7e,
0x18, 0x3c, 0x5a, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x5a, 0x3c, 0x18, 0x00,
0x00, 0x18, 0x0c, 0xfe, 0x0c, 0x18, 0x00, 0x00, 0x00, 0x30, 0x60, 0xfe, 0x60, 0x30, 0x00, 0x00,
0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xfe, 0x00, 0x00, 0x00, 0x24, 0x42, 0xff, 0x42, 0x24, 0x00, 0x00,
0x00, 0x10, 0x38, 0x7c, 0xfe, 0xfe, 0x00, 0x00, 0x00, 0xfe, 0xfe, 0x7c, 0x38, 0x10, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3c, 0x3c, 0x18, 0x18, 0x00, 0x18, 0x00,
0x6c, 0x24, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6c, 0x6c, 0xfe, 0x6c, 0xfe, 0x6c, 0x6c, 0x00,
0x10, 0x7c, 0xd0, 0x7c, 0x16, 0xfc, 0x10, 0x00, 0x00, 0x66, 0xac, 0xd8, 0x36, 0x6a, 0xcc, 0x00,
0x38, 0x4c, 0x38, 0x78, 0xce, 0xcc, 0x7a, 0x00, 0x30, 0x10, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x30, 0x60, 0x60, 0x60, 0x30, 0x18, 0x00, 0x60, 0x30, 0x18, 0x18, 0x18, 0x30, 0x60, 0x00,
0x00, 0x66, 0x3c, 0xff, 0x3c, 0x66, 0x00, 0x00, 0x00, 0x30, 0x30, 0xfc, 0x30, 0x30, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x10, 0x20, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x02, 0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0x00,
0x7c, 0xce, 0xde, 0xf6, 0xe6, 0xe6, 0x7c, 0x00, 0x18, 0x38, 0x78, 0x18, 0x18, 0x18, 0x7e, 0x00,
0x7c, 0xc6, 0x06, 0x1c, 0x70, 0xc6, 0xfe, 0x00, 0x7c, 0xc6, 0x06, 0x3c, 0x06, 0xc6, 0x7c, 0x00,
0x1c, 0x3c, 0x6c, 0xcc, 0xfe, 0x0c, 0x1e, 0x00, 0xfe, 0xc0, 0xfc, 0x06, 0x06, 0xc6, 0x7c, 0x00,
0x7c, 0xc6, 0xc0, 0xfc, 0xc6, 0xc6, 0x7c, 0x00, 0xfe, 0xc6, 0x0c, 0x18, 0x30, 0x30, 0x30, 0x00,
0x7c, 0xc6, 0xc6, 0x7c, 0xc6, 0xc6, 0x7c, 0x00, 0x7c, 0xc6, 0xc6, 0x7e, 0x06, 0xc6, 0x7c, 0x00,
0x00, 0x30, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x30, 0x10, 0x20,
0x0c, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0c, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x7e, 0x00, 0x00,
0x60, 0x30, 0x18, 0x0c, 0x18, 0x30, 0x60, 0x00, 0x78, 0xcc, 0x0c, 0x18, 0x30, 0x00, 0x30, 0x00,
0x7c, 0x82, 0x9e, 0xa6, 0x9e, 0x80, 0x7c, 0x00, 0x7c, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0x00,
0xfc, 0x66, 0x66, 0x7c, 0x66, 0x66, 0xfc, 0x00, 0x7c, 0xc6, 0xc0, 0xc0, 0xc0, 0xc6, 0x7c, 0x00,
0xfc, 0x66, 0x66, 0x66, 0x66, 0x66, 0xfc, 0x00, 0xfe, 0x62, 0x68, 0x78, 0x68, 0x62, 0xfe, 0x00,
0xfe, 0x62, 0x68, 0x78, 0x68, 0x60, 0xf0, 0x00, 0x7c, 0xc6, 0xc6, 0xc0, 0xce, 0xc6, 0x7e, 0x00,
0xc6, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0xc6, 0x00, 0x3c, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00,
0x1e, 0x0c, 0x0c, 0x0c, 0xcc, 0xcc, 0x78, 0x00, 0xe6, 0x66, 0x6c, 0x78, 0x6c, 0x66, 0xe6, 0x00,
0xf0, 0x60, 0x60, 0x60, 0x62, 0x66, 0xfe, 0x00, 0x82, 0xc6, 0xee, 0xfe, 0xd6, 0xc6, 0xc6, 0x00,
0xc6, 0xe6, 0xf6, 0xde, 0xce, 0xc6, 0xc6, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00,
0xfc, 0x66, 0x66, 0x7c, 0x60, 0x60, 0xf0, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xd6, 0xde, 0x7c, 0x06,
0xfc, 0x66, 0x66, 0x7c, 0x66, 0x66, 0xe6, 0x00, 0x7c, 0xc6, 0xc0, 0x7c, 0x06, 0xc6, 0x7c, 0x00,
0x7e, 0x5a, 0x5a, 0x18, 0x18, 0x18, 0x3c, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00,
0xc6, 0xc6, 0xc6, 0xc6, 0x6c, 0x38, 0x10, 0x00, 0xc6, 0xc6, 0xd6, 0xfe, 0xee, 0xc6, 0x82, 0x00,
0xc6, 0x6c, 0x38, 0x38, 0x38, 0x6c, 0xc6, 0x00, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x18, 0x3c, 0x00,
0xfe, 0xc6, 0x8c, 0x18, 0x32, 0x66, 0xfe, 0x00, 0x78, 0x60, 0x60, 0x60, 0x60, 0x60, 0x78, 0x00,
0xc0, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x02, 0x00, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78, 0x00,
0x10, 0x38, 0x6c, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff,
0x30, 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x76, 0x00,
0xe0, 0x60, 0x60, 0x7c, 0x66, 0x66, 0x7c, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc0, 0xc6, 0x7c, 0x00,
0x1c, 0x0c, 0x0c, 0x7c, 0xcc, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0x7c, 0x00,
0x1c, 0x36, 0x30, 0x78, 0x30, 0x30, 0x78, 0x00, 0x00, 0x00, 0x76, 0xcc, 0xcc, 0x7c, 0x0c, 0x78,
0xe0, 0x60, 0x6c, 0x76, 0x66, 0x66, 0xe6, 0x00, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x3c, 0x00,
0x00, 0x0c, 0x00, 0x1c, 0x0c, 0x0c, 0xcc, 0x78, 0xe0, 0x60, 0x66, 0x6c, 0x78, 0x6c, 0xe6, 0x00,
0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00, 0x00, 0x00, 0xcc, 0xfe, 0xd6, 0xd6, 0xd6, 0x00,
0x00, 0x00, 0xdc, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0x7c, 0x00,
0x00, 0x00, 0xdc, 0x66, 0x66, 0x7c, 0x60, 0xf0, 0x00, 0x00, 0x7c, 0xcc, 0xcc, 0x7c, 0x0c, 0x1e,
0x00, 0x00, 0xde, 0x76, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x00, 0x7c, 0xc0, 0x7c, 0x06, 0x7c, 0x00,
0x10, 0x30, 0xfc, 0x30, 0x30, 0x34, 0x18, 0x00, 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00,
0x00, 0x00, 0xc6, 0xc6, 0x6c, 0x38, 0x10, 0x00, 0x00, 0x00, 0xc6, 0xd6, 0xd6, 0xfe, 0x6c, 0x00,
0x00, 0x00, 0xc6, 0x6c, 0x38, 0x6c, 0xc6, 0x00, 0x00, 0x00, 0xcc, 0xcc, 0xcc, 0x7c, 0x0c, 0xf8,
0x00, 0x00, 0xfc, 0x98, 0x30, 0x64, 0xfc, 0x00, 0x0e, 0x18, 0x18, 0x30, 0x18, 0x18, 0x0e, 0x00,
0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00, 0xe0, 0x30, 0x30, 0x18, 0x30, 0x30, 0xe0, 0x00,
0x76, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0x00,
0x7c, 0xc6, 0xc0, 0xc0, 0xc6, 0x7c, 0x18, 0x70, 0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00,
0x0e, 0x10, 0x7c, 0xc6, 0xfe, 0xc0, 0x7c, 0x00, 0x7c, 0x82, 0x38, 0x0c, 0x7c, 0xcc, 0x76, 0x00,
0xcc, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x76, 0x00, 0xe0, 0x10, 0x78, 0x0c, 0x7c, 0xcc, 0x76, 0x00,
0x30, 0x30, 0x78, 0x0c, 0x7c, 0xcc, 0x76, 0x00, 0x00, 0x00, 0x7c, 0xc0, 0xc0, 0x7c, 0x18, 0x70,
0x7c, 0x82, 0x7c, 0xc6, 0xfe, 0xc0, 0x7c, 0x00, 0xc6, 0x00, 0x7c, 0xc6, 0xfe, 0xc0, 0x7c, 0x00,
0xe0, 0x10, 0x7c, 0xc6, 0xfe, 0xc0, 0x7c, 0x00, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x3c, 0x00,
0x7c, 0x82, 0x38, 0x18, 0x18, 0x18, 0x3c, 0x00, 0xe0, 0x10, 0x38, 0x18, 0x18, 0x18, 0x3c, 0x00,
0xc6, 0x00, 0x7c, 0xc6, 0xfe, 0xc6, 0xc6, 0x00, 0x38, 0x38, 0x7c, 0xc6, 0xfe, 0xc6, 0xc6, 0x00,
0x0e, 0x10, 0xfe, 0x60, 0x78, 0x60, 0xfe, 0x00, 0x00, 0x00, 0x7c, 0x12, 0x7e, 0xd0, 0x7e, 0x00,
0x7e, 0xc8, 0xc8, 0xfe, 0xc8, 0xc8, 0xce, 0x00, 0x7c, 0x82, 0x7c, 0xc6, 0xc6, 0xc6, 0x7c, 0x00,
0xc6, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0xe0, 0x10, 0x7c, 0xc6, 0xc6, 0xc6, 0x7c, 0x00,
0x7c, 0x82, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00, 0xe0, 0x10, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00,
0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0x7c, 0x0c, 0xf8, 0xc6, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00,
0xc6, 0x00, 0xc6, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x18, 0x7c, 0xd6, 0xd0, 0xd6, 0x7c, 0x18, 0x00,
0x38, 0x6c, 0x60, 0xf0, 0x60, 0xf2, 0xdc, 0x00, 0x66, 0x3c, 0x18, 0x7e, 0x18, 0x7e, 0x18, 0x00,
0xf8, 0xcc, 0xf8, 0xc4, 0xcc, 0xde, 0xcc, 0x06, 0x0e, 0x1b, 0x18, 0x3c, 0x18, 0x18, 0xd8, 0x70,
0x0e, 0x10, 0x78, 0x0c, 0x7c, 0xcc, 0x76, 0x00, 0x0e, 0x10, 0x38, 0x18, 0x18, 0x18, 0x3c, 0x00,
0x0e, 0x10, 0x7c, 0xc6, 0xc6, 0xc6, 0x7c, 0x00, 0x0e, 0x10, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00,
0x66, 0x98, 0xdc, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x98, 0xe6, 0xf6, 0xde, 0xce, 0xc6, 0x00,
0x38, 0x0c, 0x3c, 0x34, 0x00, 0x7e, 0x00, 0x00, 0x38, 0x6c, 0x6c, 0x38, 0x00, 0x7c, 0x00, 0x00,
0x30, 0x00, 0x30, 0x60, 0xc6, 0xc6, 0x7c, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xc0, 0xc0, 0x00, 0x00,
0x00, 0x00, 0x00, 0xfc, 0x0c, 0x0c, 0x00, 0x00, 0xc0, 0xc8, 0xd0, 0xfe, 0x46, 0x8c, 0x1e, 0x00,
0xc0, 0xc8, 0xd0, 0xec, 0x5c, 0xbe, 0x0c, 0x00, 0x18, 0x00, 0x18, 0x18, 0x3c, 0x3c, 0x18, 0x00,
0x00, 0x36, 0x6c, 0xd8, 0x6c, 0x36, 0x00, 0x00, 0x00, 0xd8, 0x6c, 0x36, 0x6c, 0xd8, 0x00, 0x00,
0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa,
0xdb, 0x77, 0xdb, 0xee, 0xdb, 0x77, 0xdb, 0xee, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0xf6, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x36, 0x36, 0x36,
0x00, 0x00, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18, 0x36, 0x36, 0xf6, 0x06, 0xf6, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0xfe, 0x06, 0xf6, 0x36, 0x36, 0x36,
0x36, 0x36, 0xf6, 0x06, 0xfe, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0xfe, 0x00, 0x00, 0x00,
0x18, 0x18, 0xf8, 0x18, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x1f, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0xff, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1f, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0xff, 0x18, 0x18, 0x18,
0x18, 0x18, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36,
0x36, 0x36, 0x37, 0x30, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x30, 0x37, 0x36, 0x36, 0x36,
0x36, 0x36, 0xf7, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xf7, 0x36, 0x36, 0x36,
0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00,
0x36, 0x36, 0xf7, 0x00, 0xf7, 0x36, 0x36, 0x36, 0x18, 0x18, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0xff, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x3f, 0x00, 0x00, 0x00,
0x18, 0x18, 0x1f, 0x18, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0x3f, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xff, 0x36, 0x36, 0x36,
0x18, 0x18, 0xff, 0x18, 0xff, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xf8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1f, 0x18, 0x18, 0x18, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0,
0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x74, 0xcc, 0xc8, 0xdc, 0x76, 0x00, 0x78, 0xcc, 0xd8, 0xcc, 0xc6, 0xc6, 0xdc, 0x40,
0xfe, 0x62, 0x60, 0x60, 0x60, 0x60, 0xf0, 0x00, 0x00, 0x02, 0x7e, 0xec, 0x6c, 0x6c, 0x48, 0x00,
0xfe, 0x62, 0x30, 0x18, 0x30, 0x62, 0xfe, 0x00, 0x00, 0x00, 0x7e, 0xd0, 0xc8, 0xc8, 0x70, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xf8, 0x80, 0x00, 0x00, 0x7e, 0xd8, 0x18, 0x18, 0x10, 0x00,
0x38, 0x10, 0x7c, 0xd6, 0xd6, 0x7c, 0x10, 0x38, 0x7c, 0xc6, 0xc6, 0xfe, 0xc6, 0xc6, 0x7c, 0x00,
0x7c, 0xc6, 0xc6, 0xc6, 0x6c, 0x28, 0xee, 0x00, 0x3c, 0x22, 0x18, 0x7c, 0xcc, 0xcc, 0x78, 0x00,
0x00, 0x00, 0x66, 0x99, 0x99, 0x66, 0x00, 0x00, 0x00, 0x06, 0x7c, 0x9e, 0xf2, 0x7c, 0xc0, 0x00,
0x00, 0x00, 0x7c, 0xc0, 0xf8, 0xc0, 0x7c, 0x00, 0x00, 0x7c, 0xc6, 0xc6, 0xc6, 0xc6, 0xc6, 0x00,
0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe, 0x00, 0x00, 0x18, 0x18, 0x7e, 0x18, 0x18, 0x00, 0x7e, 0x00,
0x30, 0x18, 0x0c, 0x18, 0x30, 0x00, 0x7c, 0x00, 0x18, 0x30, 0x60, 0x30, 0x18, 0x00, 0x7c, 0x00,
0x0e, 0x1b, 0x1b, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xd8, 0xd8, 0x70,
0x00, 0x18, 0x00, 0x7e, 0x00, 0x18, 0x00, 0x00, 0x00, 0x76, 0xdc, 0x00, 0x76, 0xdc, 0x00, 0x00,
0x38, 0x6c, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x0f, 0x0c, 0x0c, 0x0c, 0xec, 0x6c, 0x3c, 0x00,
0xd8, 0x6c, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x30, 0xc0, 0xf0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3c, 0x3c, 0x3c, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
const int font_size = sizeof(font);
//---------------------------------------------------------------------------------
#endif //_font_h_
//---------------------------------------------------------------------------------

309
arm9/source/fs.c Normal file
View File

@@ -0,0 +1,309 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "fs.h"
#include "memory.h"
#include "strings.h"
#include "fmt.h"
#include "crypto.h"
#include "cache.h"
#include "screen.h"
#include "draw.h"
#include "utils.h"
#include "fatfs/ff.h"
#include "buttons.h"
#include "firm.h"
#include "crypto.h"
static FATFS sdFs,
nandFs;
static bool switchToMainDir(bool isSd)
{
const char *mainDir = isSd ? "/luma" : "/rw/luma";
switch(f_chdir(mainDir))
{
case FR_OK:
return true;
case FR_NO_PATH:
return f_mkdir(mainDir) == FR_OK && switchToMainDir(isSd);
default:
return false;
}
}
bool mountFs(bool isSd, bool switchToCtrNand)
{
return isSd ? f_mount(&sdFs, "0:", 1) == FR_OK && switchToMainDir(true) :
f_mount(&nandFs, "1:", 1) == FR_OK && (!switchToCtrNand || (f_chdrive("1:") == FR_OK && switchToMainDir(false)));
}
u32 fileRead(void *dest, const char *path, u32 maxSize)
{
FIL file;
FRESULT result = FR_OK;
u32 ret = 0;
if(f_open(&file, path, FA_READ) != FR_OK) return ret;
u32 size = f_size(&file);
if(dest == NULL) ret = size;
else if(size <= maxSize)
result = f_read(&file, dest, size, (unsigned int *)&ret);
result |= f_close(&file);
return result == FR_OK ? ret : 0;
}
u32 getFileSize(const char *path)
{
return fileRead(NULL, path, 0);
}
bool fileWrite(const void *buffer, const char *path, u32 size)
{
FIL file;
FRESULT result;
switch(f_open(&file, path, FA_WRITE | FA_OPEN_ALWAYS))
{
case FR_OK:
{
unsigned int written;
result = f_write(&file, buffer, size, &written);
if(result == FR_OK) result = f_truncate(&file);
result |= f_close(&file);
return result == FR_OK && (u32)written == size;
}
case FR_NO_PATH:
for(u32 i = 1; path[i] != 0; i++)
if(path[i] == '/')
{
char folder[i + 1];
memcpy(folder, path, i);
folder[i] = 0;
result = f_mkdir(folder);
}
return result == FR_OK && fileWrite(buffer, path, size);
default:
return false;
}
}
bool fileDelete(const char *path)
{
return f_unlink(path) == FR_OK;
}
bool findPayload(char *path, u32 pressed)
{
const char *pattern;
if(pressed & BUTTON_LEFT) pattern = PATTERN("left");
else if(pressed & BUTTON_RIGHT) pattern = PATTERN("right");
else if(pressed & BUTTON_UP) pattern = PATTERN("up");
else if(pressed & BUTTON_DOWN) pattern = PATTERN("down");
else if(pressed & BUTTON_START) pattern = PATTERN("start");
else if(pressed & BUTTON_B) pattern = PATTERN("b");
else if(pressed & BUTTON_X) pattern = PATTERN("x");
else if(pressed & BUTTON_Y) pattern = PATTERN("y");
else if(pressed & BUTTON_R1) pattern = PATTERN("r");
else if(pressed & BUTTON_A) pattern = PATTERN("a");
else pattern = PATTERN("select");
DIR dir;
FILINFO info;
FRESULT result;
result = f_findfirst(&dir, &info, "payloads", pattern);
if(result != FR_OK) return false;
f_closedir(&dir);
if(!info.fname[0]) return false;
sprintf(path, "payloads/%s", info.fname);
return true;
}
bool payloadMenu(char *path)
{
DIR dir;
if(f_opendir(&dir, "payloads") != FR_OK) return false;
FILINFO info;
u32 payloadNum = 0;
char payloadList[20][49];
while(f_readdir(&dir, &info) == FR_OK && info.fname[0] != 0 && payloadNum < 20)
{
if(info.fname[0] == '.') continue;
u32 nameLength = strlen(info.fname);
if(nameLength < 6 || nameLength > 52) continue;
nameLength -= 5;
if(memcmp(info.fname + nameLength, ".firm", 5) != 0) continue;
memcpy(payloadList[payloadNum], info.fname, nameLength);
payloadList[payloadNum][nameLength] = 0;
payloadNum++;
}
if(f_closedir(&dir) != FR_OK || !payloadNum) return false;
u32 pressed = 0,
selectedPayload = 0;
if(payloadNum != 1)
{
initScreens();
drawString(true, 10, 10, COLOR_TITLE, "Luma3DS chainloader");
drawString(true, 10, 10 + SPACING_Y, COLOR_TITLE, "Press A to select, START to quit");
for(u32 i = 0, posY = 10 + 3 * SPACING_Y, color = COLOR_RED; i < payloadNum; i++, posY += SPACING_Y)
{
drawString(true, 10, posY, color, payloadList[i]);
if(color == COLOR_RED) color = COLOR_WHITE;
}
while(pressed != BUTTON_A && pressed != BUTTON_START)
{
do
{
pressed = waitInput(true) & MENU_BUTTONS;
}
while(!pressed);
u32 oldSelectedPayload = selectedPayload;
switch(pressed)
{
case BUTTON_UP:
selectedPayload = !selectedPayload ? payloadNum - 1 : selectedPayload - 1;
break;
case BUTTON_DOWN:
selectedPayload = selectedPayload == payloadNum - 1 ? 0 : selectedPayload + 1;
break;
case BUTTON_LEFT:
selectedPayload = 0;
break;
case BUTTON_RIGHT:
selectedPayload = payloadNum - 1;
break;
default:
continue;
}
if(oldSelectedPayload == selectedPayload) continue;
drawString(true, 10, 10 + (3 + oldSelectedPayload) * SPACING_Y, COLOR_WHITE, payloadList[oldSelectedPayload]);
drawString(true, 10, 10 + (3 + selectedPayload) * SPACING_Y, COLOR_RED, payloadList[selectedPayload]);
}
}
if(pressed != BUTTON_START)
{
sprintf(path, "payloads/%s.firm", payloadList[selectedPayload]);
return true;
}
while(HID_PAD & MENU_BUTTONS);
wait(2000ULL);
return false;
}
u32 firmRead(void *dest, u32 firmType)
{
static const char *firmFolders[][2] = {{"00000002", "20000002"},
{"00000102", "20000102"},
{"00000202", "20000202"},
{"00000003", "20000003"},
{"00000001", "20000001"}};
char folderPath[35],
path[48];
sprintf(folderPath, "1:/title/00040138/%s/content", firmFolders[firmType][ISN3DS ? 1 : 0]);
DIR dir;
u32 firmVersion = 0xFFFFFFFF;
if(f_opendir(&dir, folderPath) != FR_OK) goto exit;
FILINFO info;
//Parse the target directory
while(f_readdir(&dir, &info) == FR_OK && info.fname[0] != 0)
{
//Not a cxi
if(info.fname[9] != 'a' || strlen(info.fname) != 12) continue;
u32 tempVersion = hexAtoi(info.altname, 8);
//Found an older cxi
if(tempVersion < firmVersion) firmVersion = tempVersion;
}
if(f_closedir(&dir) != FR_OK || firmVersion == 0xFFFFFFFF) goto exit;
//Complete the string with the .app name
sprintf(path, "%s/%08x.app", folderPath, firmVersion);
if(fileRead(dest, path, 0x400000 + sizeof(Cxi) + 0x200) <= sizeof(Cxi) + 0x400) firmVersion = 0xFFFFFFFF;
exit:
return firmVersion;
}
void findDumpFile(const char *folderPath, char *fileName)
{
DIR dir;
FRESULT result;
for(u32 n = 0; n <= 99999999; n++)
{
FILINFO info;
sprintf(fileName, "crash_dump_%08u.dmp", n);
result = f_findfirst(&dir, &info, folderPath, fileName);
if(result != FR_OK || !info.fname[0]) break;
}
if(result == FR_OK) f_closedir(&dir);
}

41
arm9/source/fs.h Normal file
View File

@@ -0,0 +1,41 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#pragma once
#include "types.h"
#define PATTERN(a) a "_*.firm"
bool mountFs(bool isSd, bool switchToCtrNand);
u32 fileRead(void *dest, const char *path, u32 maxSize);
u32 getFileSize(const char *path);
bool fileWrite(const void *buffer, const char *path, u32 size);
bool fileDelete(const char *path);
bool findPayload(char *path, u32 pressed);
bool payloadMenu(char *path);
u32 firmRead(void *dest, u32 firmType);
void findDumpFile(const char *folderPath, char *fileName);

239
arm9/source/i2c.c Normal file
View File

@@ -0,0 +1,239 @@
/*
* This file is part of fastboot 3DS
* Copyright (C) 2017 derrek, profi200
*
* 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/>.
*/
#include <stdbool.h>
#include "types.h"
#include "i2c.h"
#define I2C1_REGS_BASE (0x10161000)
#define I2C2_REGS_BASE (0x10144000)
#define I2C3_REGS_BASE (0x10148000)
typedef struct
{
vu8 REG_I2C_DATA;
vu8 REG_I2C_CNT;
vu16 REG_I2C_CNTEX;
vu16 REG_I2C_SCL;
} I2cRegs;
static const struct
{
u8 busId;
u8 devAddr;
} i2cDevTable[] =
{
{0, 0x4A},
{0, 0x7A},
{0, 0x78},
{1, 0x4A},
{1, 0x78},
{1, 0x2C},
{1, 0x2E},
{1, 0x40},
{1, 0x44},
{2, 0xA6}, // TODO: Find out if 0xA6 or 0xD6 is correct
{2, 0xD0},
{2, 0xD2},
{2, 0xA4},
{2, 0x9A},
{2, 0xA0},
{1, 0xEE},
{0, 0x40},
{2, 0x54}
};
static void i2cWaitBusy(I2cRegs *const regs)
{
while(regs->REG_I2C_CNT & I2C_ENABLE);
}
static I2cRegs* i2cGetBusRegsBase(u8 busId)
{
I2cRegs *base;
switch(busId)
{
case 0:
base = (I2cRegs*)I2C1_REGS_BASE;
break;
case 1:
base = (I2cRegs*)I2C2_REGS_BASE;
break;
case 2:
base = (I2cRegs*)I2C3_REGS_BASE;
break;
default:
base = NULL;
}
return base;
}
void I2C_init(void)
{
I2cRegs *regs = i2cGetBusRegsBase(0); // Bus 1
i2cWaitBusy(regs);
regs->REG_I2C_CNTEX = 2; // ?
regs->REG_I2C_SCL = 1280; // ?
regs = i2cGetBusRegsBase(1); // Bus 2
i2cWaitBusy(regs);
regs->REG_I2C_CNTEX = 2; // ?
regs->REG_I2C_SCL = 1280; // ?
regs = i2cGetBusRegsBase(2); // Bus 3
i2cWaitBusy(regs);
regs->REG_I2C_CNTEX = 2; // ?
regs->REG_I2C_SCL = 1280; // ?
}
static bool i2cStartTransfer(I2cDevice devId, u8 regAddr, bool read, I2cRegs *const regs)
{
const u8 devAddr = i2cDevTable[devId].devAddr;
u32 i = 0;
for(; i < 8; i++)
{
i2cWaitBusy(regs);
// Select device and start.
regs->REG_I2C_DATA = devAddr;
regs->REG_I2C_CNT = I2C_ENABLE | I2C_IRQ_ENABLE | I2C_START;
i2cWaitBusy(regs);
if(!I2C_GET_ACK(regs->REG_I2C_CNT)) // If ack flag is 0 it failed.
{
regs->REG_I2C_CNT = I2C_ENABLE | I2C_IRQ_ENABLE | I2C_ERROR | I2C_STOP;
continue;
}
// Select register and change direction to write.
regs->REG_I2C_DATA = regAddr;
regs->REG_I2C_CNT = I2C_ENABLE | I2C_IRQ_ENABLE | I2C_DIRE_WRITE;
i2cWaitBusy(regs);
if(!I2C_GET_ACK(regs->REG_I2C_CNT)) // If ack flag is 0 it failed.
{
regs->REG_I2C_CNT = I2C_ENABLE | I2C_IRQ_ENABLE | I2C_ERROR | I2C_STOP;
continue;
}
// Select device in read mode for read transfer.
if(read)
{
regs->REG_I2C_DATA = devAddr | 1u; // Set bit 0 for read.
regs->REG_I2C_CNT = I2C_ENABLE | I2C_IRQ_ENABLE | I2C_START;
i2cWaitBusy(regs);
if(!I2C_GET_ACK(regs->REG_I2C_CNT)) // If ack flag is 0 it failed.
{
regs->REG_I2C_CNT = I2C_ENABLE | I2C_IRQ_ENABLE | I2C_ERROR | I2C_STOP;
continue;
}
}
break;
}
if(i < 8) return true;
else return false;
}
bool I2C_readRegBuf(I2cDevice devId, u8 regAddr, u8 *out, u32 size)
{
const u8 busId = i2cDevTable[devId].busId;
I2cRegs *const regs = i2cGetBusRegsBase(busId);
if(!i2cStartTransfer(devId, regAddr, true, regs)) return false;
while(--size)
{
regs->REG_I2C_CNT = I2C_ENABLE | I2C_IRQ_ENABLE | I2C_DIRE_READ | I2C_ACK;
i2cWaitBusy(regs);
*out++ = regs->REG_I2C_DATA;
}
regs->REG_I2C_CNT = I2C_ENABLE | I2C_IRQ_ENABLE | I2C_DIRE_READ | I2C_STOP;
i2cWaitBusy(regs);
*out = regs->REG_I2C_DATA; // Last byte
return true;
}
<<<<<<< HEAD
bool I2C_writeRegBuf(I2cDevice devId, u8 regAddr, const u8 *in, u32 size)
=======
bool i2cWriteRegisterNoWait(u8 dev_id, u8 reg, u8 data)
>>>>>>> Do the same for arm9 exceptions
{
const u8 busId = i2cDevTable[devId].busId;
I2cRegs *const regs = i2cGetBusRegsBase(busId);
if(!i2cStartTransfer(devId, regAddr, false, regs)) return false;
while(--size)
{
regs->REG_I2C_DATA = *in++;
regs->REG_I2C_CNT = I2C_ENABLE | I2C_IRQ_ENABLE | I2C_DIRE_WRITE;
i2cWaitBusy(regs);
if(!I2C_GET_ACK(regs->REG_I2C_CNT)) // If ack flag is 0 it failed.
{
regs->REG_I2C_CNT = I2C_ENABLE | I2C_IRQ_ENABLE | I2C_ERROR | I2C_STOP;
return false;
}
}
<<<<<<< HEAD
regs->REG_I2C_DATA = *in;
regs->REG_I2C_CNT = I2C_ENABLE | I2C_IRQ_ENABLE | I2C_DIRE_WRITE | I2C_STOP;
i2cWaitBusy(regs);
if(!I2C_GET_ACK(regs->REG_I2C_CNT)) // If ack flag is 0 it failed.
{
regs->REG_I2C_CNT = I2C_ENABLE | I2C_IRQ_ENABLE | I2C_ERROR | I2C_STOP;
return false;
}
return true;
}
u8 I2C_readReg(I2cDevice devId, u8 regAddr)
{
u8 data;
if(!I2C_readRegBuf(devId, regAddr, &data, 1)) return 0xFF;
return data;
}
=======
return ret;
}
bool i2cWriteRegister(u8 dev_id, u8 reg, u8 data)
{
bool ret = i2cWriteRegisterNoWait(dev_id, reg, data);
wait(3ULL);
>>>>>>> Do the same for arm9 exceptions
bool I2C_writeReg(I2cDevice devId, u8 regAddr, u8 data)
{
return I2C_writeRegBuf(devId, regAddr, &data, 1);
}

108
arm9/source/i2c.h Normal file
View File

@@ -0,0 +1,108 @@
#pragma once
/*
* This file is part of fastboot 3DS
* Copyright (C) 2017 derrek, profi200
*
* 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/>.
*/
#include <stdbool.h>
#include "types.h"
#define I2C_STOP (1u)
#define I2C_START (1u<<1)
#define I2C_ERROR (1u<<2)
#define I2C_ACK (1u<<4)
#define I2C_DIRE_WRITE (0u)
#define I2C_DIRE_READ (1u<<5)
#define I2C_IRQ_ENABLE (1u<<6)
#define I2C_ENABLE (1u<<7)
#define I2C_GET_ACK(reg) ((bool)((reg)>>4 & 1u))
typedef enum
{
I2C_DEV_POWER = 0, // Unconfirmed
I2C_DEV_CAMERA = 1, // Unconfirmed
I2C_DEV_CAMERA2 = 2, // Unconfirmed
I2C_DEV_MCU = 3,
I2C_DEV_GYRO = 10,
I2C_DEV_DEBUG_PAD = 12,
I2C_DEV_IR = 13,
I2C_DEV_EEPROM = 14, // Unconfirmed
I2C_DEV_NFC = 15,
I2C_DEV_QTM = 16,
I2C_DEV_N3DS_HID = 17
} I2cDevice;
/**
* @brief Initializes the I2C buses. Call this only once.
*/
void I2C_init(void);
/**
* @brief Reads data from a I2C register to a buffer.
*
* @param[in] devId The device ID. Use the enum above.
* @param[in] regAddr The register address.
* @param out The output buffer pointer.
* @param[in] size The read size.
*
* @return Returns true on success and false on failure.
*/
bool I2C_readRegBuf(I2cDevice devId, u8 regAddr, u8 *out, u32 size);
/**
* @brief Writes a buffer to a I2C register.
*
* @param[in] devId The device ID. Use the enum above.
* @param[in] regAddr The register address.
* @param[in] in The input buffer pointer.
* @param[in] size The write size.
*
* @return Returns true on success and false on failure.
*/
bool I2C_writeRegBuf(I2cDevice devId, u8 regAddr, const u8 *in, u32 size);
/**
* @brief Reads a byte from a I2C register.
*
* @param[in] devId The device ID. Use the enum above.
* @param[in] regAddr The register address.
*
* @return Returns the value read on success otherwise 0xFF.
*/
u8 I2C_readReg(I2cDevice devId, u8 regAddr);
<<<<<<< HEAD
/**
* @brief Writes a byte to a I2C register.
*
* @param[in] devId The device ID. Use the enum above.
* @param[in] regAddr The register address.
* @param[in] data The data to write.
*
* @return Returns true on success and false on failure.
*/
bool I2C_writeReg(I2cDevice devId, u8 regAddr, u8 data);
=======
u8 i2cReadRegister(u8 dev_id, u8 reg);
bool i2cWriteRegister(u8 dev_id, u8 reg, u8 data);
bool i2cWriteRegisterNoWait(u8 dev_id, u8 reg, u8 data);
>>>>>>> Do the same for arm9 exceptions

View File

@@ -0,0 +1,38 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#pragma once
#include "types.h"
extern const u8 emunandPatch[];
extern const u32 emunandPatchSize;
extern u32 emunandPatchSdmmcStructPtr, emunandPatchNandOffset, emunandPatchNcsdHeaderOffset;
extern const u8 rebootPatch[];
extern const u32 rebootPatchSize;
extern u32 rebootPatchFopenPtr;
extern u16 rebootPatchFileName[80+1];

291
arm9/source/large_patches.s Normal file
View File

@@ -0,0 +1,291 @@
.section .large_patch.emunand, "aw", %progbits
.arm
.align 4
@ Code originally by Normmatt
.global emunandPatch
emunandPatch:
@ Original code that still needs to be executed
mov r4, r0
mov r5, r1
mov r7, r2
mov r6, r3
@ End
@ If we're already trying to access the SD, return
ldr r2, [r0, #4]
ldr r1, emunandPatchSdmmcStructPtr
cmp r2, r1
beq out
str r1, [r0, #4] @ Set object to be SD
ldr r2, [r0, #8] @ Get sector to read
cmp r2, #0 @ For GW compatibility, see if we're trying to read the ncsd header (sector 0)
ldr r3, emunandPatchNandOffset
add r2, r3 @ Add the offset to the NAND in the SD
ldreq r3, emunandPatchNcsdHeaderOffset
addeq r2, r3 @ If we're reading the ncsd header, add the offset of that sector
str r2, [r0, #8] @ Store sector to read
out:
@ Restore registers.
mov r1, r5
mov r2, r7
mov r3, r6
@ Return 4 bytes behind where we got called,
@ due to the offset of this function being stored there
mov r0, lr
add r0, #4
bx r0
.pool
.global emunandPatchSdmmcStructPtr
.global emunandPatchNandOffset
.global emunandPatchNcsdHeaderOffset
emunandPatchSdmmcStructPtr: .word 0 @ Pointer to sdmmc struct
emunandPatchNandOffset: .word 0 @ For rednand this should be 1
emunandPatchNcsdHeaderOffset: .word 0 @ Depends on nand manufacturer + emunand type (GW/RED)
.pool
.balign 4
_emunandPatchEnd:
.global emunandPatchSize
emunandPatchSize:
.word _emunandPatchEnd - emunandPatch
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ Code originally from delebile and mid-kid
.section .large_patch.reboot, "aw", %progbits
.arm
.align 4
.set copy_launch_stub_stack_top, 0x01FFB800
.set copy_launch_stub_stack_bottom, 0x01FFA800
.set copy_launch_stub_addr, 0x01FF9000
.set argv_addr, (copy_launch_stub_stack_bottom - 0x100)
.set fname_addr, (copy_launch_stub_stack_bottom - 0x200)
.set low_tid_addr, (copy_launch_stub_stack_bottom - 0x300)
.set firm_addr, 0x20001000
.set firm_maxsize, 0x07FFF000
.global rebootPatch
rebootPatch:
@ Interesting registers and locations to keep in mind, set just before this code is ran:
@ - r1: FIRM path in exefs.
@ - r7 (or r8): pointer to file object
@ - *r7: vtable
@ - *(vtable + 0x28): fread function
@ - *(r7 + 8): file handle
sub r7, r0, #8
mov r8, r1
pxi_wait_recv:
ldr r2, =0x44846
ldr r0, =0x10008000
readPxiLoop1:
ldrh r1, [r0, #4]
lsls r1, #0x17
bmi readPxiLoop1
ldr r0, [r0, #0xC]
cmp r0, r2
bne pxi_wait_recv
@ Open file
add r0, r7, #8
adr r1, rebootPatchFileName
mov r2, #1
adr r6, rebootPatchFopenPtr
ldr r6, [r6]
orr r6, #1
blx r6
cmp r0, #0
bne panic
@ Read file
mov r0, r7
adr r1, bytes_read
ldr r2, =firm_addr
ldr r3, =firm_maxsize
ldr r6, [r7]
ldr r6, [r6, #0x28]
blx r6
@ Copy the low TID (in UTF-16) of the wanted firm
ldr r0, =low_tid_addr
add r1, r8, #0x1A
mov r2, #0x10
bl memcpy16
@ Copy argv[0]
ldr r0, =fname_addr
adr r1, rebootPatchFileName
mov r2, #82
bl memcpy16
ldr r0, =argv_addr
ldr r1, =fname_addr
ldr r2, =low_tid_addr
stmia r0, {r1, r2}
@ Set kernel state
mov r0, #0
mov r1, #0
mov r2, #0
mov r3, #0
swi 0x7C
goto_reboot:
@ Jump to reboot code
ldr r0, kernel_func_displ
add r0, pc @ pc is two instructions ahead of the instruction being executed (12 = 2*4 + 4)
swi 0x7B
die:
b die
memcpy16:
cmp r2, #0
bxeq lr
add r2, r0, r2
copy_loop16:
ldrh r3, [r1], #2
strh r3, [r0], #2
cmp r0, r2
blo copy_loop16
bx lr
panic:
mov r1, r0 @ unused register
mov r0, #0
swi 0x3C @ svcBreak(USERBREAK_PANIC)
b die
kernel_func_displ:
.word kernelcode_start - goto_reboot - 12
bytes_read:
.word 0
.global rebootPatchFopenPtr
rebootPatchFopenPtr:
.word 0
.pool
.global rebootPatchFileName
rebootPatchFileName:
.skip 2*(80+1)
.balign 4
kernelcode_start:
msr cpsr_cxsf, #0xD3 @ disable interrupts and clear flags
ldr sp, =copy_launch_stub_stack_top
ldr r0, =copy_launch_stub_addr
adr r1, copy_launch_stub
mov r2, #(copy_launch_stub_end - copy_launch_stub)
bl memcpy32
@ Disable MPU
ldr r0, =0x42078 @ alt vector select, enable itcm
mcr p15, 0, r0, c1, c0, 0
bl flushCaches
ldr r0, =copy_launch_stub_addr
bx r0
copy_launch_stub:
ldr r4, =firm_addr
mov r5, #0
load_section_loop:
@ Such checks. Very ghetto. Wow.
add r3, r4, #0x40
add r3, r5,lsl #5
add r3, r5,lsl #4
ldmia r3, {r6-r8}
cmp r8, #0
movne r0, r7
addne r1, r4, r6
movne r2, r8
blne memcpy32
add r5, #1
cmp r5, #4
blo load_section_loop
mov r0, #2 @ argc
ldr r1, =argv_addr @ argv
ldr r2, =0xBABE @ magic word
mov r5, #0x20000000
ldr r6, [r4, #0x08]
str r6, [r5, #-4] @ store arm11 entrypoint
ldr lr, [r4, #0x0c]
bx lr
memcpy32:
add r2, r0, r2
copy_loop32:
ldr r3, [r1], #4
str r3, [r0], #4
cmp r0, r2
blo copy_loop32
bx lr
.pool
copy_launch_stub_end:
flushCaches:
@ Clean and flush data cache
mov r1, #0 @ segment counter
outer_loop:
mov r0, #0 @ line counter
inner_loop:
orr r2, r1, r0 @ generate segment and line address
mcr p15, 0, r2, c7, c14, 2 @ clean and flush the line
add r0, #0x20 @ increment to next line
cmp r0, #0x400
bne inner_loop
add r1, #0x40000000
cmp r1, #0
bne outer_loop
@ Drain write buffer
mcr p15, 0, r1, c7, c10, 4
@ Flush instruction cache
mcr p15, 0, r1, c7, c5, 0
bx lr
.pool
.balign 4
_rebootPatchEnd:
.global rebootPatchSize
rebootPatchSize:
.word _rebootPatchEnd - rebootPatch

362
arm9/source/main.c Normal file
View File

@@ -0,0 +1,362 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "config.h"
#include "emunand.h"
#include "fs.h"
#include "firm.h"
#include "utils.h"
#include "exceptions.h"
#include "draw.h"
#include "strings.h"
#include "buttons.h"
#include "pin.h"
#include "crypto.h"
#include "memory.h"
#include "screen.h"
#include "i2c.h"
#include "fatfs/sdmmc/sdmmc.h"
extern CfgData configData;
extern ConfigurationStatus needConfig;
extern FirmwareSource firmSource;
bool isSdMode;
u16 launchedPath[80+1];
BootType bootType;
void main(int argc, char **argv, u32 magicWord)
{
bool isFirmProtEnabled,
isSafeMode = false,
needToInitSd = false,
isNoForceFlagSet = false,
isNtrBoot;
FirmwareType firmType;
FirmwareSource nandType;
const vu8 *bootMediaStatus = (const vu8 *)0x1FFFE00C;
const vu32 *bootPartitionsStatus = (const vu32 *)0x1FFFE010;
I2C_init();
//Shell closed, no error booting NTRCARD, NAND paritions not even considered
isNtrBoot = bootMediaStatus[3] == 2 && !bootMediaStatus[1] && !bootPartitionsStatus[0] && !bootPartitionsStatus[1];
if((magicWord & 0xFFFF) == 0xBEEF && argc >= 1) //Normal (B9S) boot
{
bootType = isNtrBoot ? B9SNTR : B9S;
u32 i;
for(i = 0; i < sizeof(launchedPath)/2 - 1 && argv[0][i] != 0; i++) //Copy and convert the path to UTF-16
launchedPath[i] = argv[0][i];
launchedPath[i] = 0;
}
else if(magicWord == 0xBABE && argc == 2) //Firmlaunch
{
bootType = FIRMLAUNCH;
u32 i;
u16 *p = (u16 *)argv[0];
for(i = 0; i < sizeof(launchedPath)/2 - 1 && p[i] != 0; i++)
launchedPath[i] = p[i];
launchedPath[i] = 0;
}
else if(magicWord == 0xB002) //FIRM/NTRCARD boot
{
if(isNtrBoot) bootType = NTR;
else
{
const char *path;
if(!((vu8 *)bootPartitionsStatus)[2])
{
bootType = FIRM0;
path = "firm0:";
}
else
{
bootType = FIRM1;
path = "firm1:";
}
for(u32 i = 0; i < 7; i++) //Copy and convert the path to UTF-16
launchedPath[i] = path[i];
}
setupKeyslots();
}
else error("Launched using an unsupported loader.");
if(memcmp(launchedPath, u"sdmc", 8) == 0)
{
if(!mountFs(true, false)) error("Failed to mount SD.");
isSdMode = true;
}
else if(memcmp(launchedPath, u"nand", 8) == 0)
{
if(!mountFs(false, true)) error("Failed to mount CTRNAND.");
isSdMode = false;
}
else if(bootType == NTR || memcmp(launchedPath, u"firm", 8) == 0)
{
if(mountFs(true, false)) isSdMode = true;
else if(mountFs(false, true)) isSdMode = false;
else error("Failed to mount SD and CTRNAND.");
if(bootType == NTR)
{
while(HID_PAD & NTRBOOT_BUTTONS);
loadHomebrewFirm(0);
mcuPowerOff();
}
}
else
{
char mountPoint[5];
u32 i;
for(i = 0; i < 4 && launchedPath[i] != u':'; i++)
mountPoint[i] = (char)launchedPath[i];
mountPoint[i] = 0;
error("Launched from an unsupported location: %s.", mountPoint);
}
//Attempt to read the configuration file
needConfig = readConfig() ? MODIFY_CONFIGURATION : CREATE_CONFIGURATION;
//Determine if this is a firmlaunch boot
if(bootType == FIRMLAUNCH)
{
if(needConfig == CREATE_CONFIGURATION) mcuPowerOff();
switch(argv[1][14])
{
case '2':
firmType = (FirmwareType)(argv[1][10] - '0');
break;
case '3':
firmType = SAFE_FIRM;
break;
case '1':
firmType = SYSUPDATER_FIRM;
break;
}
nandType = (FirmwareSource)BOOTCFG_NAND;
firmSource = (FirmwareSource)BOOTCFG_FIRM;
isFirmProtEnabled = !BOOTCFG_NTRCARDBOOT;
goto boot;
}
detectAndProcessExceptionDumps();
installArm9Handlers();
firmType = NATIVE_FIRM;
isFirmProtEnabled = bootType != NTR;
//Get pressed buttons
u32 pressed = HID_PAD;
//If it's a MCU reboot, try to force boot options
if(CFG_BOOTENV && needConfig != CREATE_CONFIGURATION)
{
//Always force a SysNAND boot when quitting AGB_FIRM
if(CFG_BOOTENV == 7)
{
nandType = FIRMWARE_SYSNAND;
firmSource = (BOOTCFG_NAND != 0) == (BOOTCFG_FIRM != 0) ? FIRMWARE_SYSNAND : (FirmwareSource)BOOTCFG_FIRM;
//Prevent multiple boot options-forcing
if(nandType != BOOTCFG_NAND || firmSource != BOOTCFG_FIRM) isNoForceFlagSet = true;
goto boot;
}
//Account for DSiWare soft resets if exiting TWL_FIRM
if(CFG_BOOTENV == 3)
{
static const u8 TLNC[] = {0x54, 0x4C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4E, 0x43};
if(memcmp((void *)0x20000C00, TLNC, 10) == 0) needToInitSd = true;
}
/* Force the last used boot options if autobooting a TWL title, or unless a button is pressed
or the no-forcing flag is set */
if(needToInitSd || memcmp((void *)0x20000300, "TLNC", 4) == 0 || (!pressed && !BOOTCFG_NOFORCEFLAG))
{
nandType = (FirmwareSource)BOOTCFG_NAND;
firmSource = (FirmwareSource)BOOTCFG_FIRM;
goto boot;
}
}
u32 pinMode = MULTICONFIG(PIN);
bool pinExists = pinMode != 0 && verifyPin(pinMode);
//If no configuration file exists or SELECT is held or if booted from NTRCARD, load configuration menu
bool shouldLoadConfigMenu = needConfig == CREATE_CONFIGURATION || ((pressed & (BUTTON_SELECT | BUTTON_L1)) == BUTTON_SELECT);
if(shouldLoadConfigMenu)
{
configMenu(pinExists, pinMode);
//Update pressed buttons
pressed = HID_PAD;
}
if(!CFG_BOOTENV && pressed == SAFE_MODE)
{
nandType = FIRMWARE_SYSNAND;
firmSource = FIRMWARE_SYSNAND;
isSafeMode = true;
needToInitSd = true;
//If the PIN has been verified, wait to make it easier to press the SAFE_MODE combo
if(pinExists && !shouldLoadConfigMenu)
{
while(HID_PAD & PIN_BUTTONS);
wait(2000ULL);
}
goto boot;
}
u32 splashMode = MULTICONFIG(SPLASH);
if(splashMode == 1 && loadSplash()) pressed = HID_PAD;
bool autoBootEmu = CONFIG(AUTOBOOTEMU);
if((pressed & (BUTTON_START | BUTTON_L1)) == BUTTON_START)
{
loadHomebrewFirm(0);
pressed = HID_PAD;
}
else if((((pressed & SINGLE_PAYLOAD_BUTTONS) || (!autoBootEmu && (pressed & DPAD_BUTTONS))) && !(pressed & (BUTTON_L1 | BUTTON_R1))) ||
(((pressed & L_PAYLOAD_BUTTONS) || (autoBootEmu && (pressed & DPAD_BUTTONS))) && (pressed & BUTTON_L1))) loadHomebrewFirm(pressed);
if(splashMode == 2) loadSplash();
//If booting from CTRNAND, always use SysNAND
if(!isSdMode) nandType = FIRMWARE_SYSNAND;
//If R is pressed, boot the non-updated NAND with the FIRM of the opposite one
else if(pressed & BUTTON_R1)
{
if(CONFIG(USEEMUFIRM))
{
nandType = FIRMWARE_SYSNAND;
firmSource = FIRMWARE_EMUNAND;
}
else
{
nandType = FIRMWARE_EMUNAND;
firmSource = FIRMWARE_SYSNAND;
}
}
/* Else, boot the NAND the user set to autoboot or the opposite one, depending on L,
with their own FIRM */
else firmSource = nandType = (autoBootEmu == ((pressed & BUTTON_L1) == BUTTON_L1)) ? FIRMWARE_SYSNAND : FIRMWARE_EMUNAND;
//If we're booting EmuNAND or using EmuNAND FIRM, determine which one from the directional pad buttons, or otherwise from the config
if(nandType == FIRMWARE_EMUNAND || firmSource == FIRMWARE_EMUNAND)
{
FirmwareSource tempNand;
switch(pressed & DPAD_BUTTONS)
{
case BUTTON_UP:
tempNand = FIRMWARE_EMUNAND;
break;
case BUTTON_RIGHT:
tempNand = FIRMWARE_EMUNAND2;
break;
case BUTTON_DOWN:
tempNand = FIRMWARE_EMUNAND3;
break;
case BUTTON_LEFT:
tempNand = FIRMWARE_EMUNAND4;
break;
default:
tempNand = (FirmwareSource)(1 + MULTICONFIG(DEFAULTEMU));
break;
}
if(nandType == FIRMWARE_EMUNAND) nandType = tempNand;
else firmSource = tempNand;
}
boot:
//If we need to boot EmuNAND, make sure it exists
if(nandType != FIRMWARE_SYSNAND)
{
locateEmuNand(&nandType);
if(nandType == FIRMWARE_SYSNAND) firmSource = FIRMWARE_SYSNAND;
else if((*(vu16 *)(SDMMC_BASE + REG_SDSTATUS0) & TMIO_STAT0_WRPROTECT) == 0) //Make sure the SD card isn't write protected
error("The SD card is locked, EmuNAND can not be used.\nPlease turn the write protection switch off.");
}
//Same if we're using EmuNAND as the FIRM source
else if(firmSource != FIRMWARE_SYSNAND)
locateEmuNand(&firmSource);
if(bootType != FIRMLAUNCH)
{
configData.bootConfig = ((bootType == NTR ? 1 : 0) << 7) | ((u32)isNoForceFlagSet << 6) | ((u32)firmSource << 3) | (u32)nandType;
writeConfig(false);
}
bool loadFromStorage = CONFIG(LOADEXTFIRMSANDMODULES);
u32 firmVersion = loadNintendoFirm(&firmType, firmSource, loadFromStorage, isSafeMode);
bool doUnitinfoPatch = CONFIG(PATCHUNITINFO);
u32 res;
switch(firmType)
{
case NATIVE_FIRM:
res = patchNativeFirm(firmVersion, nandType, loadFromStorage, isFirmProtEnabled, needToInitSd, doUnitinfoPatch);
break;
case TWL_FIRM:
res = patchTwlFirm(firmVersion, loadFromStorage, doUnitinfoPatch);
break;
case AGB_FIRM:
res = patchAgbFirm(loadFromStorage, doUnitinfoPatch);
break;
case SAFE_FIRM:
case SYSUPDATER_FIRM:
case NATIVE_FIRM1X2X:
res = patch1x2xNativeAndSafeFirm();
break;
}
if(res != 0) error("Failed to apply %u FIRM patch(es).", res);
if(bootType != FIRMLAUNCH) deinitScreens();
launchFirm(0, NULL);
}

95
arm9/source/memory.c Normal file
View File

@@ -0,0 +1,95 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Boyer-Moore Horspool algorithm adapted from http://www-igm.univ-mlv.fr/~lecroq/string/node18.html#SECTION00180
* memcpy, memset32 and memcmp adapted from https://github.com/mid-kid/CakesForeveryWan/blob/557a8e8605ab3ee173af6497486e8f22c261d0e2/source/memfuncs.c
*/
#include "memory.h"
void memcpy(void *dest, const void *src, u32 size)
{
u8 *destc = (u8 *)dest;
const u8 *srcc = (const u8 *)src;
for(u32 i = 0; i < size; i++)
destc[i] = srcc[i];
}
void memset(void *dest, u32 filler, u32 size)
{
u8 *destc = (u8 *)dest;
for(u32 i = 0; i < size; i++)
destc[i] = (u8)filler;
}
void memset32(void *dest, u32 filler, u32 size)
{
u32 *dest32 = (u32 *)dest;
for(u32 i = 0; i < size / 4; i++)
dest32[i] = filler;
}
int memcmp(const void *buf1, const void *buf2, u32 size)
{
const u8 *buf1c = (const u8 *)buf1,
*buf2c = (const u8 *)buf2;
for(u32 i = 0; i < size; i++)
{
int cmp = buf1c[i] - buf2c[i];
if(cmp != 0) return cmp;
}
return 0;
}
u8 *memsearch(u8 *startPos, const void *pattern, u32 size, u32 patternSize)
{
const u8 *patternc = (const u8 *)pattern;
u32 table[256];
//Preprocessing
for(u32 i = 0; i < 256; i++)
table[i] = patternSize;
for(u32 i = 0; i < patternSize - 1; i++)
table[patternc[i]] = patternSize - i - 1;
//Searching
u32 j = 0;
while(j <= size - patternSize)
{
u8 c = startPos[j + patternSize - 1];
if(patternc[patternSize - 1] == c && memcmp(pattern, startPos + j, patternSize - 1) == 0)
return startPos + j;
j += table[c];
}
return NULL;
}

40
arm9/source/memory.h Normal file
View File

@@ -0,0 +1,40 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Boyer-Moore Horspool algorithm adapted from http://www-igm.univ-mlv.fr/~lecroq/string/node18.html#SECTION00180
* memcpy, memset32 and memcmp adapted from https://github.com/mid-kid/CakesForeveryWan/blob/557a8e8605ab3ee173af6497486e8f22c261d0e2/source/memfuncs.c
*/
#pragma once
#include "types.h"
void memcpy(void *dest, const void *src, u32 size);
void memset(void *dest, u32 filler, u32 size) __attribute__((used));
void memset32(void *dest, u32 filler, u32 size);
int memcmp(const void *buf1, const void *buf2, u32 size);
u8 *memsearch(u8 *startPos, const void *pattern, u32 size, u32 patternSize);

692
arm9/source/patches.c Normal file
View File

@@ -0,0 +1,692 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Signature patches by an unknown author
* Signature patches for old FIRMs by SciresM
* firmlaunches patching code originally by delebile
* FIRM partition writes patches by delebile
* Idea for svcBreak patches from yellows8 and others on #3dsdev
* TWL_FIRM patches by Steveice10 and others
*/
#include "patches.h"
#include "fs.h"
#include "exceptions.h"
#include "memory.h"
#include "config.h"
#include "utils.h"
#include "arm9_exception_handlers.h"
#include "large_patches.h"
u8 *getProcess9Info(u8 *pos, u32 size, u32 *process9Size, u32 *process9MemAddr)
{
u8 *temp = memsearch(pos, "NCCH", size, 4);
if(temp == NULL) error("Failed to get Process9 data.");
Cxi *off = (Cxi *)(temp - 0x100);
*process9Size = (off->ncch.exeFsSize - 1) * 0x200;
*process9MemAddr = off->exHeader.systemControlInfo.textCodeSet.address;
return (u8 *)off + (off->ncch.exeFsOffset + 1) * 0x200;
}
u32 *getKernel11Info(u8 *pos, u32 size, u32 *baseK11VA, u8 **freeK11Space, u32 **arm11SvcHandler, u32 **arm11ExceptionsPage)
{
static const u8 pattern[] = {0x00, 0xB0, 0x9C, 0xE5};
*arm11ExceptionsPage = (u32 *)memsearch(pos, pattern, size, sizeof(pattern));
if(*arm11ExceptionsPage == NULL) error("Failed to get Kernel11 data.");
u32 *arm11SvcTable;
*arm11ExceptionsPage -= 0xB;
u32 svcOffset = (-(((*arm11ExceptionsPage)[2] & 0xFFFFFF) << 2) & (0xFFFFFF << 2)) - 8; //Branch offset + 8 for prefetch
u32 pointedInstructionVA = 0xFFFF0008 - svcOffset;
*baseK11VA = pointedInstructionVA & 0xFFFF0000; //This assumes that the pointed instruction has an offset < 0x10000, iirc that's always the case
arm11SvcTable = *arm11SvcHandler = (u32 *)(pos + *(u32 *)(pos + pointedInstructionVA - *baseK11VA + 8) - *baseK11VA); //SVC handler address
while(*arm11SvcTable) arm11SvcTable++; //Look for SVC0 (NULL)
u32 *freeSpace;
for(freeSpace = *arm11ExceptionsPage; freeSpace < *arm11ExceptionsPage + 0x400 && *freeSpace != 0xFFFFFFFF; freeSpace++);
*freeK11Space = (u8 *) freeSpace;
return arm11SvcTable;
}
// For ARM prologs in the form of: push {regs} ... sub sp, #off (this obviously doesn't intend to cover all cases)
static inline u32 computeARMFrameSize(const u32 *prolog)
{
const u32 *off;
for(off = prolog; (*off >> 16) != 0xE92D; off++); // look for stmfd sp! = push
u32 nbPushedRegs = 0;
for(u32 val = *off & 0xFFFF; val != 0; val >>= 1) // 1 bit = 1 pushed register
nbPushedRegs += val & 1;
for(; (*off >> 8) != 0xE24DD0; off++); // look for sub sp, #offset
u32 localVariablesSpaceSize = *off & 0xFF;
return 4 * nbPushedRegs + localVariablesSpaceSize;
}
static inline u32 *getKernel11HandlerVAPos(u8 *pos, u32 *arm11ExceptionsPage, u32 baseK11VA, u32 id)
{
u32 off = ((-((arm11ExceptionsPage[id] & 0xFFFFFF) << 2)) & (0xFFFFFF << 2)) - 8;
u32 pointedInstructionVA = 0xFFFF0000 + 4 * id - off;
return (u32 *)(pos + pointedInstructionVA - baseK11VA + 8);
}
u32 installK11Extension(u8 *pos, u32 size, bool needToInitSd, u32 baseK11VA, u32 *arm11ExceptionsPage, u8 **freeK11Space)
{
//The parameters to be passed on to the kernel ext
//Please keep that in sync with the definition in k11_extension/source/main.c
struct KExtParameters
{
u32 __attribute__((aligned(0x400))) L2MMUTableFor0x40000000[256];
u32 basePA;
void *originalHandlers[4];
u32 L1MMUTableAddrs[4];
struct CfwInfo
{
char magic[4];
u8 versionMajor;
u8 versionMinor;
u8 versionBuild;
u8 flags;
u32 commitHash;
u16 configFormatVersionMajor, configFormatVersionMinor;
u32 config, multiConfig, bootConfig;
u64 hbldr3dsxTitleId;
u32 rosalinaMenuCombo;
} info;
};
static const u8 patternHook1[] = {0x02, 0xC2, 0xA0, 0xE3, 0xFF}; //MMU setup hook
static const u8 patternHook2[] = {0x08, 0x00, 0xA4, 0xE5, 0x02, 0x10, 0x80, 0xE0, 0x08, 0x10, 0x84, 0xE5}; //FCRAM layout setup hook
static const u8 patternHook3_4[] = {0x00, 0x00, 0xA0, 0xE1, 0x03, 0xF0, 0x20, 0xE3, 0xFD, 0xFF, 0xFF, 0xEA}; //SGI0 setup code, etc.
//Our kernel11 extension is initially loaded in VRAM
u32 kextTotalSize = *(u32 *)0x18000020 - 0x40000000;
u32 dstKextPA = (ISN3DS ? 0x2E000000 : 0x26C00000) - kextTotalSize;
u32 *hookVeneers = (u32 *)*freeK11Space;
u32 relocBase = 0xFFFF0000 + (*freeK11Space - (u8 *)arm11ExceptionsPage);
hookVeneers[0] = 0xE51FF004; //ldr pc, [pc, #-8+4]
hookVeneers[1] = 0x18000004;
hookVeneers[2] = 0xE51FF004;
hookVeneers[3] = 0x40000000;
hookVeneers[4] = 0xE51FF004;
hookVeneers[5] = 0x40000008;
hookVeneers[6] = 0xE51FF004;
hookVeneers[7] = 0x4000000C;
(*freeK11Space) += 32;
//MMU setup hook
u32 *off = (u32 *)memsearch(pos, patternHook1, size, sizeof(patternHook1));
if(off == NULL) return 1;
*off = MAKE_BRANCH_LINK(off, hookVeneers);
//Most important hook: FCRAM layout setup hook
off = (u32 *)memsearch(pos, patternHook2, size, sizeof(patternHook2));
if(off == NULL) return 1;
off += 2;
*off = MAKE_BRANCH_LINK(baseK11VA + ((u8 *)off - pos), relocBase + 8);
//Bind SGI0 hook
//Look for cpsie i and place our hook in the nop 2 instructions before
off = (u32 *)memsearch(pos, patternHook3_4, size, 12);
if(off == NULL) return 1;
for(; *off != 0xF1080080; off--);
off -= 2;
*off = MAKE_BRANCH_LINK(baseK11VA + ((u8 *)off - pos), relocBase + 16);
//Config hook (after the configuration memory fields have been filled)
for(; *off != 0xE1A00000; off++);
off += 4;
*off = MAKE_BRANCH_LINK(baseK11VA + ((u8 *)off - pos), relocBase + 24);
struct KExtParameters *p = (struct KExtParameters *)(*(u32 *)0x18000024 - 0x40000000 + 0x18000000);
p->basePA = dstKextPA;
for(u32 i = 0; i < 4; i++)
{
u32 *handlerPos = getKernel11HandlerVAPos(pos, arm11ExceptionsPage, baseK11VA, 1 + i);
p->originalHandlers[i] = (void *)*handlerPos;
*handlerPos = 0x40000010 + 4 * i;
}
struct CfwInfo *info = &p->info;
memcpy(&info->magic, "LUMA", 4);
info->commitHash = COMMIT_HASH;
info->configFormatVersionMajor = configData.formatVersionMajor;
info->configFormatVersionMinor = configData.formatVersionMinor;
info->config = configData.config;
info->multiConfig = configData.multiConfig;
info->bootConfig = configData.bootConfig;
info->hbldr3dsxTitleId = configData.hbldr3dsxTitleId;
info->rosalinaMenuCombo = configData.rosalinaMenuCombo;
info->versionMajor = VERSION_MAJOR;
info->versionMinor = VERSION_MINOR;
info->versionBuild = VERSION_BUILD;
if(ISRELEASE) info->flags = 1;
if(ISN3DS) info->flags |= 1 << 4;
if(needToInitSd) info->flags |= 1 << 5;
if(isSdMode) info->flags |= 1 << 6;
return 0;
}
u32 patchKernel11(u8 *pos, u32 size, u32 baseK11VA, u32 *arm11SvcTable, u32 *arm11ExceptionsPage)
{
static const u8 patternKPanic[] = {0x02, 0x0B, 0x44, 0xE2};
static const u8 patternKThreadDebugReschedule[] = {0x34, 0x20, 0xD4, 0xE5, 0x00, 0x00, 0x55, 0xE3, 0x80, 0x00, 0xA0, 0x13};
//Assumption: ControlMemory, DebugActiveProcess and KernelSetState are in the first 0x20000 bytes
//Patch ControlMemory
u8 *instrPos = pos + (arm11SvcTable[1] + 20 - baseK11VA);
s32 displ = (*(u32 *)instrPos & 0xFFFFFF) << 2;
displ = (displ << 6) >> 6; // sign extend
u8 *ControlMemoryPos = instrPos + 8 + displ;
u32 *off;
/*
Here we replace currentProcess->processID == 1 by additionnalParameter == 1.
This patch should be generic enough to work even on firmware version 5.0.
It effectively changes the prototype of the ControlMemory function which
only caller is the svc 0x01 handler on OFW.
*/
for(off = (u32 *)ControlMemoryPos; (off[0] & 0xFFF0FFFF) != 0xE3500001 || (off[1] & 0xFFFF0FFF) != 0x13A00000; off++);
off -= 2;
*off = 0xE59D0000 | (*off & 0x0000F000) | (8 + computeARMFrameSize((u32 *)ControlMemoryPos)); // ldr r0, [sp, #(frameSize + 8)]
//Patch DebugActiveProcess
for(off = (u32 *)(pos + (arm11SvcTable[0x60] - baseK11VA)); *off != 0xE3110001; off++);
*off = 0xE3B01001; // tst r1, #1 -> movs r1, #1
for(off = (u32 *)(pos + (arm11SvcTable[0x7C] - baseK11VA)); off[0] != 0xE5D00001 || off[1] != 0xE3500000; off++);
off[2] = 0xE1A00000; // in case 6: beq -> nop
//Patch kernelpanic
off = (u32 *)memsearch(pos, patternKPanic, size, sizeof(patternKPanic));
if(off == NULL)
return 1;
off[-6] = 0xE12FFF7E;
//Redirect enableUserExceptionHandlersForCPUExc (= true)
for(off = arm11ExceptionsPage; *off != 0x96007F9; off++);
off[1] = 0x40000028;
off = (u32 *)memsearch(pos, patternKThreadDebugReschedule, size, sizeof(patternKThreadDebugReschedule));
if(off == NULL)
return 1;
off[-5] = 0xE51FF004;
off[-4] = 0x4000002C;
return 0;
}
u32 patchSignatureChecks(u8 *pos, u32 size)
{
//Look for signature checks
static const u8 pattern[] = {0xC0, 0x1C, 0x76, 0xE7},
pattern2[] = {0xB5, 0x22, 0x4D, 0x0C};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
u8 *temp = memsearch(pos, pattern2, size, sizeof(pattern2));
if(off == NULL || temp == NULL) return 1;
u16 *off2 = (u16 *)(temp - 1);
*off = off2[0] = 0x2000;
off2[1] = 0x4770;
return 0;
}
u32 patchOldSignatureChecks(u8 *pos, u32 size)
{
// Look for signature checks
static const u8 pattern[] = {0xC0, 0x1C, 0xBD, 0xE7},
pattern2[] = {0xB5, 0x23, 0x4E, 0x0C};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
u8 *temp = memsearch(pos, pattern2, size, sizeof(pattern2));
if(off == NULL || temp == NULL) return 1;
u16 *off2 = (u16 *)(temp - 1);
*off = off2[0] = 0x2000;
off2[1] = 0x4770;
return 0;
}
u32 patchFirmlaunches(u8 *pos, u32 size, u32 process9MemAddr)
{
//Look for firmlaunch code
static const u8 pattern[] = {0xE2, 0x20, 0x20, 0x90};
u32 pathLen;
for(pathLen = 0; pathLen < sizeof(launchedPath)/2 && launchedPath[pathLen] != 0; pathLen++);
if(launchedPath[pathLen] != 0) return 1;
u8 *off = memsearch(pos, pattern, size, sizeof(pattern));
if(off == NULL) return 1;
off -= 0x13;
//Firmlaunch function offset - offset in BLX opcode (A4-16 - ARM DDI 0100E) + 1
u32 fOpenOffset = (u32)(off + 9 - (-((*(u32 *)off & 0x00FFFFFF) << 2) & (0xFFFFFF << 2)) - pos + process9MemAddr);
//Put the fOpen offset in the right location
rebootPatchFopenPtr = fOpenOffset;
//Copy the launched path
memcpy(rebootPatchFileName, launchedPath, 2 * (1 + pathLen));
//Copy firmlaunch code
memcpy(off, rebootPatch, rebootPatchSize);
return 0;
}
u32 patchFirmWrites(u8 *pos, u32 size)
{
//Look for FIRM writing code
u8 *off = memsearch(pos, "exe:", size, 4);
if(off == NULL) return 1;
static const u8 pattern[] = {0x00, 0x28, 0x01, 0xDA};
u16 *off2 = (u16 *)memsearch(off - 0x100, pattern, 0x100, sizeof(pattern));
if(off2 == NULL) return 1;
off2[0] = 0x2000;
off2[1] = 0x46C0;
return 0;
}
u32 patchOldFirmWrites(u8 *pos, u32 size)
{
//Look for FIRM writing code
static const u8 pattern[] = {0x04, 0x1E, 0x1D, 0xDB};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
if(off == NULL) return 1;
off[0] = 0x2400;
off[1] = 0xE01D;
return 0;
}
u32 patchTitleInstallMinVersionChecks(u8 *pos, u32 size, u32 firmVersion)
{
static const u8 pattern[] = {0xFF, 0x00, 0x00, 0x02};
u8 *off = memsearch(pos, pattern, size, sizeof(pattern));
if(off == NULL) return firmVersion == 0xFFFFFFFF ? 0 : 1;
off++;
//Zero out the first TitleID in the list
memset32(off, 0, 8);
return 0;
}
u32 patchZeroKeyNcchEncryptionCheck(u8 *pos, u32 size)
{
static const u8 pattern[] = {0x28, 0x2A, 0xD0, 0x08};
u8 *temp = memsearch(pos, pattern, size, sizeof(pattern));
if(temp == NULL) return 1;
u16 *off = (u16 *)(temp - 1);
*off = 0x2001; //mov r0, #1
return 0;
}
u32 patchNandNcchEncryptionCheck(u8 *pos, u32 size)
{
static const u8 pattern[] = {0x07, 0xD1, 0x28, 0x7A};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
if(off == NULL) return 1;
off--;
*off = 0x2001; //mov r0, #1
return 0;
}
u32 patchCheckForDevCommonKey(u8 *pos, u32 size)
{
static const u8 pattern[] = {0x03, 0x7C, 0x28, 0x00};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
if(off == NULL) return 1;
*off = 0x2301; //mov r3, #1
return 0;
}
u32 patchK11ModuleLoading(u32 section0size, u32 modulesSize, u8 *pos, u32 size)
{
static const u8 moduleLoadingPattern[] = {0xE2, 0x05, 0x00, 0x57},
modulePidPattern[] = {0x06, 0xA0, 0xE1, 0xF2}; //GetSystemInfo
u8 *off = memsearch(pos, moduleLoadingPattern, size, 4);
if(off == NULL) return 1;
off[1]++;
u32 *off32;
for(off32 = (u32 *)(off - 3); *off32 != 0xE59F0000; off32++);
off32 += 2;
off32[1] = off32[0] + modulesSize;
for(; *off32 != section0size; off32++);
*off32 += ((modulesSize + 0x1FF) >> 9) << 9;
off = memsearch(pos, modulePidPattern, size, 4);
if(off == NULL) return 1;
off[0xB] = 6;
return 0;
}
u32 patchArm9ExceptionHandlersInstall(u8 *pos, u32 size)
{
static const u8 pattern[] = {0x80, 0xE5, 0x40, 0x1C};
u8 *temp = memsearch(pos, pattern, size, sizeof(pattern));
if(temp == NULL) return 1;
u32 *off;
for(off = (u32 *)(temp - 2); *off != 0xE5801000; off--); //Until str r1, [r0]
for(u32 r0 = 0x08000000; *off != 0xE3A01040; off++) //Until mov r1, #0x40
{
//Discard everything that's not str rX, [r0, #imm](!)
if((*off & 0xFE5F0000) != 0xE4000000) continue;
u32 rD = (*off >> 12) & 0xF,
offset = (*off & 0xFFF) * ((((*off >> 23) & 1) == 0) ? -1 : 1);
bool writeback = ((*off >> 21) & 1) != 0,
pre = ((*off >> 24) & 1) != 0;
u32 addr = r0 + ((pre || !writeback) ? offset : 0);
if((addr & 7) != 0 && addr != 0x08000014 && addr != 0x08000004) *off = 0xE1A00000; //nop
else *off = 0xE5800000 | (rD << 12) | (addr & 0xFFF); //Preserve IRQ and SVC handlers
if(!pre) addr += offset;
if(writeback) r0 = addr;
}
return 0;
}
u32 patchSvcBreak9(u8 *pos, u32 size, u32 kernel9Address)
{
//Stub svcBreak with "bkpt 65535" so we can debug the panic
//Look for the svc handler
static const u8 pattern[] = {0x00, 0xE0, 0x4F, 0xE1}; //mrs lr, spsr
u32 *arm9SvcTable = (u32 *)memsearch(pos, pattern, size, sizeof(pattern));
if(arm9SvcTable == NULL) return 1;
while(*arm9SvcTable != 0) arm9SvcTable++; //Look for SVC0 (NULL)
u32 *addr = (u32 *)(pos + arm9SvcTable[0x3C] - kernel9Address);
/*
mov r8, sp
bkpt 0xffff
*/
addr[0] = 0xE1A0800D;
addr[1] = 0xE12FFF7F;
arm9ExceptionHandlerSvcBreakAddress = arm9SvcTable[0x3C]; //BreakPtr
return 0;
}
u32 patchKernel9Panic(u8 *pos, u32 size)
{
static const u8 pattern[] = {0x00, 0x20, 0x92, 0x15};
u8 *temp = memsearch(pos, pattern, size, sizeof(pattern));
if(temp == NULL) return 1;
u32 *off = (u32 *)(temp - 0x34);
*off = 0xE12FFF7E;
return 0;
}
u32 patchP9AccessChecks(u8 *pos, u32 size)
{
static const u8 pattern[] = {0x00, 0x08, 0x49, 0x68};
u8 *temp = memsearch(pos, pattern, size, sizeof(pattern));
if(temp == NULL) return 1;
u16 *off = (u16 *)(temp - 3);
off[0] = 0x2001; //mov r0, #1
off[1] = 0x4770; //bx lr
return 0;
}
u32 patchUnitInfoValueSet(u8 *pos, u32 size)
{
//Look for UNITINFO value being set during kernel sync
static const u8 pattern[] = {0x01, 0x10, 0xA0, 0x13};
u8 *off = memsearch(pos, pattern, size, sizeof(pattern));
if(off == NULL) return 1;
off[0] = ISDEVUNIT ? 0 : 1;
off[3] = 0xE3;
return 0;
}
u32 patchLgySignatureChecks(u8 *pos, u32 size)
{
static const u8 pattern[] = {0x47, 0xC1, 0x17, 0x49};
u8 *temp = memsearch(pos, pattern, size, sizeof(pattern));
if(temp == NULL) return 1;
u16 *off = (u16 *)(temp + 1);
off[0] = 0x2000;
off[1] = 0xB04E;
off[2] = 0xBD70;
return 0;
}
u32 patchTwlInvalidSignatureChecks(u8 *pos, u32 size)
{
static const u8 pattern[] = {0x20, 0xF6, 0xE7, 0x7F};
u8 *temp = memsearch(pos, pattern, size, sizeof(pattern));
if(temp == NULL) return 1;
u16 *off = (u16 *)(temp - 1);
*off = 0x2001; //mov r0, #1
return 0;
}
u32 patchTwlNintendoLogoChecks(u8 *pos, u32 size)
{
static const u8 pattern[] = {0xC0, 0x30, 0x06, 0xF0};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
if(off == NULL) return 1;
off[1] = 0x2000;
off[2] = 0;
return 0;
}
u32 patchTwlWhitelistChecks(u8 *pos, u32 size)
{
static const u8 pattern[] = {0x22, 0x00, 0x20, 0x30};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
if(off == NULL) return 1;
off[2] = 0x2000;
off[3] = 0;
return 0;
}
u32 patchTwlFlashcartChecks(u8 *pos, u32 size, u32 firmVersion)
{
static const u8 pattern[] = {0x25, 0x20, 0x00, 0x0E};
u8 *temp = memsearch(pos, pattern, size, sizeof(pattern));
if(temp == NULL)
{
if(firmVersion == 0xFFFFFFFF) return patchOldTwlFlashcartChecks(pos, size);
return 1;
}
u16 *off = (u16 *)(temp + 3);
off[0] = off[6] = off[0xC] = 0x2001; //mov r0, #1
off[1] = off[7] = off[0xD] = 0; //nop
return 0;
}
u32 patchOldTwlFlashcartChecks(u8 *pos, u32 size)
{
static const u8 pattern[] = {0x06, 0xF0, 0xA0, 0xFD};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
if(off == NULL) return 1;
off[0] = off[6] = 0x2001; //mov r0, #1
off[1] = off[7] = 0; //nop
return 0;
}
u32 patchTwlShaHashChecks(u8 *pos, u32 size)
{
static const u8 pattern[] = {0x10, 0xB5, 0x14, 0x22};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
if(off == NULL) return 1;
off[0] = 0x2001; //mov r0, #1
off[1] = 0x4770;
return 0;
}
u32 patchAgbBootSplash(u8 *pos, u32 size)
{
static const u8 pattern[] = {0x00, 0x00, 0x01, 0xEF};
u8 *off = memsearch(pos, pattern, size, sizeof(pattern));
if(off == NULL) return 1;
off[2] = 0x26;
return 0;
}
u32 patchP9AMTicketWrapperZeroKeyIV(u8* pos, u32 size)
{
static const u8 __rt_memclr_pattern[] = {0x00, 0x20, 0xA0, 0xE3, 0x04, 0x00, 0x51, 0xE3, 0x07, 0x00, 0x00, 0x3A};
static const u8 pattern[] = {0x20, 0x21, 0xA6, 0xA8};
u32 function = (u32)memsearch(pos, __rt_memclr_pattern, size, sizeof(__rt_memclr_pattern));
u32 *off = (u32*)memsearch(pos, pattern, size, sizeof(pattern));
if(function == 0 || off == NULL) return 1;
s32 opjumpdistance = (s32)(function - ((u32)&off[2])) / 2;
//beyond limit
if(opjumpdistance < -0x1fffff || opjumpdistance > 0x1fffff) return 1;
//r0 and r1 for old call are already correctly for this one
//BLX __rt_memclr
off[1] = 0xE800F000U | (((u32)opjumpdistance & 0x7FF) << 16) | (((u32)opjumpdistance >> 11) & 0x3FF) | (((u32)opjumpdistance >> 21) & 0x400);
return 0;
}

67
arm9/source/patches.h Normal file
View File

@@ -0,0 +1,67 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Signature patches by an unknown author
* Signature patches for old FIRMs by SciresM
* firmlaunches patching code originally by delebile
* FIRM partition writes patches by delebile
* Idea for svcBreak patches from yellows8 and others on #3dsdev
* TWL_FIRM patches by Steveice10 and others
*/
#pragma once
#include "types.h"
u8 *getProcess9Info(u8 *pos, u32 size, u32 *process9Size, u32 *process9MemAddr);
u32 *getKernel11Info(u8 *pos, u32 size, u32 *baseK11VA, u8 **freeK11Space, u32 **arm11SvcHandler, u32 **arm11ExceptionsPage);
u32 installK11Extension(u8 *pos, u32 size, bool needToInitSd, u32 baseK11VA, u32 *arm11ExceptionsPage, u8 **freeK11Space);
u32 patchKernel11(u8 *pos, u32 size, u32 baseK11VA, u32 *arm11SvcTable, u32 *arm11ExceptionsPage);
u32 patchSignatureChecks(u8 *pos, u32 size);
u32 patchOldSignatureChecks(u8 *pos, u32 size);
u32 patchFirmlaunches(u8 *pos, u32 size, u32 process9MemAddr);
u32 patchFirmWrites(u8 *pos, u32 size);
u32 patchOldFirmWrites(u8 *pos, u32 size);
u32 patchTitleInstallMinVersionChecks(u8 *pos, u32 size, u32 firmVersion);
u32 patchZeroKeyNcchEncryptionCheck(u8 *pos, u32 size);
u32 patchNandNcchEncryptionCheck(u8 *pos, u32 size);
u32 patchCheckForDevCommonKey(u8 *pos, u32 size);
u32 patchK11ModuleLoading(u32 section0size, u32 modulesSize, u8 *startPos, u32 size);
u32 patchArm9ExceptionHandlersInstall(u8 *pos, u32 size);
u32 patchSvcBreak9(u8 *pos, u32 size, u32 kernel9Address);
u32 patchKernel9Panic(u8 *pos, u32 size);
u32 patchP9AccessChecks(u8 *pos, u32 size);
u32 patchUnitInfoValueSet(u8 *pos, u32 size);
u32 patchLgySignatureChecks(u8 *pos, u32 size);
u32 patchTwlInvalidSignatureChecks(u8 *pos, u32 size);
u32 patchTwlNintendoLogoChecks(u8 *pos, u32 size);
u32 patchTwlWhitelistChecks(u8 *pos, u32 size);
u32 patchTwlFlashcartChecks(u8 *pos, u32 size, u32 firmVersion);
u32 patchOldTwlFlashcartChecks(u8 *pos, u32 size);
u32 patchTwlShaHashChecks(u8 *pos, u32 size);
u32 patchAgbBootSplash(u8 *pos, u32 size);
u32 patchP9AMTicketWrapperZeroKeyIV(u8* pos, u32 size);

233
arm9/source/pin.c Normal file
View File

@@ -0,0 +1,233 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Code originally by reworks
*/
#include "draw.h"
#include "config.h"
#include "screen.h"
#include "utils.h"
#include "memory.h"
#include "buttons.h"
#include "fs.h"
#include "pin.h"
#include "crypto.h"
static char pinKeyToLetter(u32 pressed)
{
static const char *keys = "AB--RLUD--XY";
u32 i;
for(i = 31; pressed > 1; i--) pressed /= 2;
return keys[31 - i];
}
void newPin(bool allowSkipping, u32 pinMode)
{
clearScreens(false);
u8 length = 4 + 2 * (pinMode - 1);
drawString(true, 10, 10, COLOR_TITLE, "Enter a new PIN using ABXY and the DPad");
drawString(true, 10, 10 + SPACING_Y, COLOR_TITLE, allowSkipping ? "Press START to skip, SELECT to reset" : "Press SELECT to reset");
drawFormattedString(true, 10, 10 + 3 * SPACING_Y, COLOR_WHITE, "PIN (%u digits): ", length);
//Pad to AES block length with zeroes
__attribute__((aligned(4))) u8 enteredPassword[AES_BLOCK_SIZE] = {0};
bool reset = false;
u8 cnt = 0;
while(cnt < length)
{
if(reset)
{
for(u32 i = 0; i < cnt; i++)
drawCharacter(true, 10 + (16 + 2 * i) * SPACING_X, 10 + 3 * SPACING_Y, COLOR_BLACK, (char)enteredPassword[i]);
cnt = 0;
reset = false;
}
u32 pressed;
do
{
pressed = waitInput(false);
}
while(!(pressed & PIN_BUTTONS));
pressed &= PIN_BUTTONS;
if(!allowSkipping) pressed &= ~BUTTON_START;
if(pressed & BUTTON_START) return;
if(pressed & BUTTON_SELECT)
{
reset = true;
continue;
}
if(!pressed) continue;
//Add character to password
enteredPassword[cnt] = (u8)pinKeyToLetter(pressed);
//Visualize character on screen
drawCharacter(true, 10 + (16 + 2 * cnt) * SPACING_X, 10 + 3 * SPACING_Y, COLOR_WHITE, enteredPassword[cnt]);
cnt++;
}
PinData pin;
memcpy(pin.magic, "PINF", 4);
pin.formatVersionMajor = PIN_VERSIONMAJOR;
pin.formatVersionMinor = PIN_VERSIONMINOR;
__attribute__((aligned(4))) u8 tmp[SHA_256_HASH_SIZE],
lengthBlock[AES_BLOCK_SIZE] = {0};
lengthBlock[0] = length;
computePinHash(tmp, lengthBlock);
memcpy(pin.lengthHash, tmp, sizeof(tmp));
computePinHash(tmp, enteredPassword);
memcpy(pin.hash, tmp, sizeof(tmp));
if(!fileWrite(&pin, PIN_FILE, sizeof(PinData)))
error("Error writing the PIN file");
}
bool verifyPin(u32 pinMode)
{
PinData pin;
if(fileRead(&pin, PIN_FILE, sizeof(PinData)) != sizeof(PinData) ||
memcmp(pin.magic, "PINF", 4) != 0 ||
pin.formatVersionMajor != PIN_VERSIONMAJOR ||
pin.formatVersionMinor != PIN_VERSIONMINOR)
return false;
__attribute__((aligned(4))) u8 tmp[SHA_256_HASH_SIZE],
lengthBlock[AES_BLOCK_SIZE] = {0};
lengthBlock[0] = 4 + 2 * (pinMode - 1);
computePinHash(tmp, lengthBlock);
//Test vector verification (check if SD card has been used on another console or PIN length changed)
if(memcmp(pin.lengthHash, tmp, sizeof(tmp)) != 0) return false;
initScreens();
swapFramebuffers(true);
drawString(true, 10, 10, COLOR_TITLE, "Enter the PIN using ABXY and the DPad to proceed");
drawString(true, 10, 10 + SPACING_Y, COLOR_TITLE, "Press START to shutdown, SELECT to clear");
drawFormattedString(true, 10, 10 + 3 * SPACING_Y, COLOR_WHITE, "PIN (%u digits): ", lengthBlock[0]);
bool isBottomSplashValid = getFileSize("splashpin.bin") == SCREEN_BOTTOM_FBSIZE;
if(isBottomSplashValid)
{
isBottomSplashValid = fileRead(fbs[0].bottom, "splashpin.bin", SCREEN_BOTTOM_FBSIZE) == SCREEN_BOTTOM_FBSIZE;
}
else
{
static const char *messageFile = "pinmessage.txt";
char message[801];
u32 messageSize = fileRead(message, messageFile, sizeof(message) - 1);
if(messageSize != 0)
{
message[messageSize] = 0;
drawString(false, 10, 10, COLOR_WHITE, message);
}
}
swapFramebuffers(false);
//Pad to AES block length with zeroes
__attribute__((aligned(4))) u8 enteredPassword[AES_BLOCK_SIZE] = {0};
bool unlock = false,
reset = false;
u8 cnt = 0;
while(!unlock)
{
if(reset)
{
for(u32 i = 0; i < cnt; i++)
drawCharacter(true, 10 + (16 + 2 * i) * SPACING_X, 10 + 3 * SPACING_Y, COLOR_BLACK, '*');
cnt = 0;
reset = false;
}
u32 pressed;
do
{
pressed = waitInput(false);
}
while(!(pressed & PIN_BUTTONS));
if(pressed & BUTTON_START) mcuPowerOff();
pressed &= PIN_BUTTONS;
if(pressed & BUTTON_SELECT)
{
reset = true;
continue;
}
if(!pressed) continue;
//Add character to password
enteredPassword[cnt] = (u8)pinKeyToLetter(pressed);
//Visualize character on screen
drawCharacter(true, 10 + (16 + 2 * cnt) * SPACING_X, 10 + 3 * SPACING_Y, COLOR_WHITE, '*');
if(++cnt < lengthBlock[0]) continue;
computePinHash(tmp, enteredPassword);
unlock = memcmp(pin.hash, tmp, sizeof(tmp)) == 0;
if(!unlock)
{
reset = true;
drawString(true, 10, 10 + 5 * SPACING_Y, COLOR_RED, "Wrong PIN, try again");
}
}
return true;
}

40
arm9/source/pin.h Normal file
View File

@@ -0,0 +1,40 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Code originally by reworks
*/
#pragma once
#include "types.h"
#define PIN_FILE "pin.bin"
#define PIN_VERSIONMAJOR 1
#define PIN_VERSIONMINOR 3
void newPin(bool allowSkipping, u32 pinMode);
bool verifyPin(u32 pinMode);

119
arm9/source/screen.c Normal file
View File

@@ -0,0 +1,119 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Screen init code by dark_samus, bil1s, Normmatt, delebile and others
* Screen deinit code by tiniVi
*/
#include "screen.h"
#include "config.h"
#include "memory.h"
#include "i2c.h"
#include "utils.h"
bool needToSetupScreens = true;
struct fb fbs[2] =
{
{
.top_left = (u8 *)0x18300000,
.top_right = (u8 *)0x18300000,
.bottom = (u8 *)0x18346500,
},
{
.top_left = (u8 *)0x18400000,
.top_right = (u8 *)0x18400000,
.bottom = (u8 *)0x18446500,
},
};
static const u32 brightness[4] = {0x5F, 0x4C, 0x39, 0x26};
static volatile Arm11Operation *operation = (volatile Arm11Operation *)0x1FF80004;
static void invokeArm11Function(Arm11Operation op)
{
while(*operation != ARM11_READY);
*operation = op;
while(*operation != ARM11_READY);
}
void prepareArm11ForFirmlaunch(void)
{
invokeArm11Function(PREPARE_ARM11_FOR_FIRMLAUNCH);
}
void deinitScreens(void)
{
if(ARESCREENSINITIALIZED) invokeArm11Function(DEINIT_SCREENS);
}
void updateBrightness(u32 brightnessIndex)
{
*(vu32 *)ARM11_PARAMETERS_ADDRESS = brightness[brightnessIndex];
invokeArm11Function(UPDATE_BRIGHTNESS);
}
void swapFramebuffers(bool isAlternate)
{
*(volatile bool *)ARM11_PARAMETERS_ADDRESS = isAlternate;
invokeArm11Function(SWAP_FRAMEBUFFERS);
}
void clearScreens(bool isAlternate)
{
struct fb *fbTemp = isAlternate ? &fbs[1] : &fbs[0];
*(volatile struct fb *)ARM11_PARAMETERS_ADDRESS = *fbTemp;
invokeArm11Function(CLEAR_SCREENS);
}
void initScreens(void)
{
if(needToSetupScreens)
{
if(!ARESCREENSINITIALIZED || bootType == FIRMLAUNCH)
{
*(vu32 *)ARM11_PARAMETERS_ADDRESS = brightness[MULTICONFIG(BRIGHTNESS)];
memcpy((void *)(ARM11_PARAMETERS_ADDRESS + 4), fbs, sizeof(fbs));
invokeArm11Function(INIT_SCREENS);
//Turn on backlight
I2C_writeReg(I2C_DEV_MCU, 0x22, 0x2A);
}
else updateBrightness(MULTICONFIG(BRIGHTNESS));
memcpy((void *)ARM11_PARAMETERS_ADDRESS, fbs, sizeof(fbs));
invokeArm11Function(SETUP_FRAMEBUFFERS);
clearScreens(true);
needToSetupScreens = false;
}
clearScreens(false);
swapFramebuffers(false);
}

75
arm9/source/screen.h Normal file
View File

@@ -0,0 +1,75 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* Screen init code by dark_samus, bil1s, Normmatt, delebile and others
* Screen deinit code by tiniVi
*/
#pragma once
#include "types.h"
#define PDN_GPU_CNT (*(vu32 *)0x10141200)
#define ARESCREENSINITIALIZED ((PDN_GPU_CNT & 0xFF) != 1)
#define ARM11_PARAMETERS_ADDRESS 0x1FFFF000
#define SCREEN_TOP_WIDTH 400
#define SCREEN_BOTTOM_WIDTH 320
#define SCREEN_HEIGHT 240
#define SCREEN_TOP_FBSIZE (3 * SCREEN_TOP_WIDTH * SCREEN_HEIGHT)
#define SCREEN_BOTTOM_FBSIZE (3 * SCREEN_BOTTOM_WIDTH * SCREEN_HEIGHT)
struct fb {
u8 *top_left;
u8 *top_right;
u8 *bottom;
};
typedef enum
{
INIT_SCREENS = 0,
SETUP_FRAMEBUFFERS,
CLEAR_SCREENS,
SWAP_FRAMEBUFFERS,
UPDATE_BRIGHTNESS,
DEINIT_SCREENS,
PREPARE_ARM11_FOR_FIRMLAUNCH,
ARM11_READY,
} Arm11Operation;
extern struct fb fbs[2];
extern bool needToSetupScreens;
void prepareArm11ForFirmlaunch(void);
void deinitScreens(void);
void swapFramebuffers(bool isAlternate);
void updateBrightness(u32 brightnessIndex);
void clearScreens(bool isAlternate);
void initScreens(void);

179
arm9/source/start.s Normal file
View File

@@ -0,0 +1,179 @@
@ This file is part of Luma3DS
@ Copyright (C) 2016-2019 Aurora Wright, TuxSH
@
@ This program is free software: you can redistribute it and/or modify
@ it under the terms of the GNU General Public License as published by
@ the Free Software Foundation, either version 3 of the License, or
@ (at your option) any later version.
@
@ This program is distributed in the hope that it will be useful,
@ but WITHOUT ANY WARRANTY; without even the implied warranty of
@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
@ GNU General Public License for more details.
@
@ You should have received a copy of the GNU General Public License
@ along with this program. If not, see <http://www.gnu.org/licenses/>.
@
@ Additional Terms 7.b and 7.c of GPLv3 apply to this file:
@ * Requiring preservation of specified reasonable legal notices or
@ author attributions in that material or in the Appropriate Legal
@ Notices displayed by works containing it.
@ * Prohibiting misrepresentation of the origin of that material,
@ or requiring that modified versions of such material be marked in
@ reasonable ways as different from the original version.
.section .text.start, "ax", %progbits
.align 4
.global _start
_start:
@ Disable interrupts and switch to supervisor mode (also clear flags)
msr cpsr_cxsf, #0xD3
@ Check if r0-r2 are 0 (r0-sp are supposed to be 0), and for regions 0, 5 and 7 of the MPU config
@ This is not foolproof but should work well enough
cmp r0, #0
cmpeq r1, #0
cmpeq r2, #0
ldreq r4, =0x20000035
mrceq p15, 0, r5, c6, c0, 0
cmpeq r4, r5
mrceq p15, 0, r5, c6, c5, 0
ldreq r4, =0x07FF801D
cmpeq r4, r5
mrceq p15, 0, r5, c6, c7, 0
ldreq r4, =0x1FFFE019
cmpeq r4, r5
ldreq r2, =0xB002
mov r9, r0
mov r10, r1
mov r11, r2
@ Change the stack pointer
mov sp, #0x08100000
@ Disable caches / MPU
mrc p15, 0, r4, c1, c0, 0 @ read control register
bic r4, #(1<<16) @ - DTCM disable
bic r4, #(1<<12) @ - instruction cache disable
bic r4, #(1<<2) @ - data cache disable
bic r4, #(1<<0) @ - MPU disable
mcr p15, 0, r4, c1, c0, 0 @ write control register
@ Invalidate both caches, discarding any data they may contain,
@ then drain the write buffer
mov r4, #0
mcr p15, 0, r4, c7, c5, 0
mcr p15, 0, r4, c7, c6, 0
mcr p15, 0, r4, c7, c10, 4
@ Give read/write access to all the memory regions
ldr r0, =0x33333333
mcr p15, 0, r0, c5, c0, 2 @ write data access
mcr p15, 0, r0, c5, c0, 3 @ write instruction access
@ Set MPU permissions and cache settings
ldr r0, =0xFFFF001D @ ffff0000 32k | bootrom (unprotected part)
ldr r1, =0xFFF0001B @ fff00000 16k | dtcm
ldr r2, =0x01FF801D @ 01ff8000 32k | itcm
ldr r3, =0x08000027 @ 08000000 1M | arm9 mem
ldr r4, =0x10000029 @ 10000000 2M | io mem (ARM9 / first 2MB)
ldr r5, =0x20000035 @ 20000000 128M | fcram
ldr r6, =0x1FF00027 @ 1FF00000 1M | dsp / axi wram
ldr r7, =0x1800002D @ 18000000 8M | vram (+ 2MB)
mov r8, #0x29
mcr p15, 0, r0, c6, c0, 0
mcr p15, 0, r1, c6, c1, 0
mcr p15, 0, r2, c6, c2, 0
mcr p15, 0, r3, c6, c3, 0
mcr p15, 0, r4, c6, c4, 0
mcr p15, 0, r5, c6, c5, 0
mcr p15, 0, r6, c6, c6, 0
mcr p15, 0, r7, c6, c7, 0
mcr p15, 0, r8, c3, c0, 0 @ Write bufferable 0, 3, 5
mcr p15, 0, r8, c2, c0, 0 @ Data cacheable 0, 3, 5
mcr p15, 0, r8, c2, c0, 1 @ Inst cacheable 0, 3, 5
@ Set DTCM address and size to the default values
ldr r1, =0xFFF0000A @ set DTCM address and size
mcr p15, 0, r1, c9, c1, 0 @ set the dtcm Region Register
@ Enable caches / MPU / ITCM
mrc p15, 0, r0, c1, c0, 0 @ read control register
orr r0, r0, #(1<<18) @ - ITCM enable
orr r0, r0, #(1<<16) @ - DTCM enable
orr r0, r0, #(1<<13) @ - alternate exception vectors enable
orr r0, r0, #(1<<12) @ - instruction cache enable
orr r0, r0, #(1<<2) @ - data cache enable
orr r0, r0, #(1<<0) @ - MPU enable
mcr p15, 0, r0, c1, c0, 0 @ write control register
@ Clear BSS
ldr r0, =__bss_start__
mov r1, #0
ldr r2, =__bss_end__
sub r2, r0
bl memset32
@ Set additional sections up
ldr r0, =__itcm_start__
ldr r1, =__itcm_lma__
ldr r2, =__itcm_bss_start__
sub r2, r0
bl memcpy
ldr r0, =__itcm_bss_start__
mov r1, #0
ldr r2, =__itcm_end__
sub r2, r0
bl memset32
@ bl __libc_init_array
mov r0, r9
mov r1, r10
mov r2, r11
b main
.pool
.section .chainloader.text.start, "ax", %progbits
.align 4
.global chainload
.type chainload, %function
chainload:
ldr sp, =__itcm_stack_top__
b chainloader_main
.pool
.global disableMpuAndJumpToEntrypoints
.type disableMpuAndJumpToEntrypoints, %function
disableMpuAndJumpToEntrypoints:
mov r4, r0
mov r5, r1
mov r6, r2
mov r7, r3
@ Flush caches
ldr r12, =0xFFFF0830
blx r12
ldr r12, =0xFFFF0AB4
blx r12
@ Disable caches / MPU
mrc p15, 0, r0, c1, c0, 0 @ read control register
bic r0, #(1<<12) @ - instruction cache disable
bic r0, #(1<<2) @ - data cache disable
bic r0, #(1<<0) @ - MPU disable
mcr p15, 0, r0, c1, c0, 0 @ write control register
@ Set the ARM11 entrypoint
mov r0, #0x20000000
str r7, [r0, #-4]
@ Jump to the ARM9 entrypoint
mov r0, r4
mov r1, r5
ldr r2, =0x3BEEF
bx r6
.pool

68
arm9/source/strings.c Normal file
View File

@@ -0,0 +1,68 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#include "strings.h"
#include "memory.h"
u32 strlen(const char *string)
{
char *stringEnd = (char *)string;
while(*stringEnd != 0) stringEnd++;
return stringEnd - string;
}
u32 strnlen(const char *string, u32 maxlen)
{
u32 size;
for(size = 0; size < maxlen && *string; string++, size++);
return size;
}
u32 hexAtoi(const char *in, u32 digits)
{
u32 res = 0;
char *tmp = (char *)in;
for(u32 i = 0; i < digits && *tmp != 0; tmp++, i++)
res = (*tmp > '9' ? *tmp - 'A' + 10 : *tmp - '0') + (res << 4);
return res;
}
u32 decAtoi(const char *in, u32 digits)
{
u32 res = 0;
char *tmp = (char *)in;
for(u32 i = 0; i < digits && *tmp != 0; tmp++, i++)
res = *tmp - '0' + res * 10;
return res;
}

34
arm9/source/strings.h Normal file
View File

@@ -0,0 +1,34 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#pragma once
#include "types.h"
u32 strlen(const char *string);
u32 strnlen(const char *string, u32 maxlen);
u32 hexAtoi(const char *in, u32 digits);
u32 decAtoi(const char *in, u32 digits);

132
arm9/source/types.h Normal file
View File

@@ -0,0 +1,132 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
#pragma once
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdarg.h>
//Common data types
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef volatile u8 vu8;
typedef volatile u16 vu16;
typedef volatile u32 vu32;
typedef volatile u64 vu64;
typedef int8_t s8;
typedef int16_t s16;
typedef int32_t s32;
typedef int64_t s64;
typedef volatile s8 vs8;
typedef volatile s16 vs16;
typedef volatile s32 vs32;
typedef volatile s64 vs64;
#include "3dsheaders.h"
#define CFG_BOOTENV (*(vu32 *)0x10010000)
#define CFG_UNITINFO (*(vu8 *)0x10010010)
#define CFG_TWLUNITINFO (*(vu8 *)0x10010014)
#define OTP_DEVCONSOLEID (*(vu64 *)0x10012000)
#define OTP_TWLCONSOLEID (*(vu64 *)0x10012100)
#define CFG11_SOCINFO (*(vu32 *)0x10140FFC)
#define ISN3DS (CFG11_SOCINFO & 2)
#define ISDEVUNIT (CFG_UNITINFO != 0)
typedef struct __attribute__((packed))
{
char magic[4];
u16 formatVersionMajor, formatVersionMinor;
u32 config, multiConfig, bootConfig;
u64 hbldr3dsxTitleId;
u32 rosalinaMenuCombo;
} CfgData;
typedef struct __attribute__((packed))
{
char magic[4];
u16 formatVersionMajor, formatVersionMinor;
u8 lengthHash[32];
u8 hash[32];
} PinData;
typedef struct __attribute__((packed))
{
u32 magic[2];
u16 versionMinor, versionMajor;
u16 processor, core;
u32 type;
u32 totalSize;
u32 registerDumpSize;
u32 codeDumpSize;
u32 stackDumpSize;
u32 additionalDataSize;
} ExceptionDumpHeader;
typedef enum FirmwareSource
{
FIRMWARE_SYSNAND = 0,
FIRMWARE_EMUNAND,
FIRMWARE_EMUNAND2,
FIRMWARE_EMUNAND3,
FIRMWARE_EMUNAND4
} FirmwareSource;
typedef enum FirmwareType
{
NATIVE_FIRM = 0,
TWL_FIRM,
AGB_FIRM,
SAFE_FIRM,
SYSUPDATER_FIRM,
NATIVE_FIRM1X2X
} FirmwareType;
typedef enum bootType
{
B9S = 0,
B9SNTR,
FIRM0,
FIRM1,
FIRMLAUNCH,
NTR
} BootType;
extern bool isSdMode;
extern BootType bootType;
extern u16 launchedFirmTidLow[8];
extern u16 launchedPath[80+1];

147
arm9/source/utils.c Normal file
View File

@@ -0,0 +1,147 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* waitInput function based on code by d0k3 https://github.com/d0k3/Decrypt9WIP/blob/master/source/hid.c
*/
#include "utils.h"
#include "i2c.h"
#include "buttons.h"
#include "screen.h"
#include "draw.h"
#include "cache.h"
#include "fmt.h"
#include "strings.h"
#include "fs.h"
static void startChrono(void)
{
static bool isChronoStarted = false;
if(isChronoStarted) return;
REG_TIMER_CNT(0) = 0; //67MHz
for(u32 i = 1; i < 4; i++) REG_TIMER_CNT(i) = 4; //Count-up
for(u32 i = 0; i < 4; i++) REG_TIMER_VAL(i) = 0;
REG_TIMER_CNT(0) = 0x80; //67MHz; enabled
for(u32 i = 1; i < 4; i++) REG_TIMER_CNT(i) = 0x84; //Count-up; enabled
isChronoStarted = true;
}
static u64 chrono(void)
{
u64 res = 0;
for(u32 i = 0; i < 4; i++) res |= REG_TIMER_VAL(i) << (16 * i);
res /= (TICKS_PER_SEC / 1000);
return res;
}
u32 waitInput(bool isMenu)
{
static u64 dPadDelay = 0ULL;
u64 initialValue = 0ULL;
u32 key,
oldKey = HID_PAD;
bool shouldShellShutdown = bootType != B9SNTR && bootType != NTR;
if(isMenu)
{
dPadDelay = dPadDelay > 0ULL ? 87ULL : 143ULL;
startChrono();
initialValue = chrono();
}
while(true)
{
key = HID_PAD;
if(!key)
{
if((!(I2C_readReg(I2C_DEV_MCU, 0xF) & 2) && shouldShellShutdown) ||
(I2C_readReg(I2C_DEV_MCU, 0x10) & 1) == 1) mcuPowerOff();
oldKey = 0;
dPadDelay = 0;
continue;
}
if(key == oldKey && (!isMenu || (!(key & DPAD_BUTTONS) || chrono() - initialValue < dPadDelay))) continue;
//Make sure the key is pressed
u32 i;
for(i = 0; i < 0x13000 && key == HID_PAD; i++);
if(i == 0x13000) break;
}
return key;
}
void mcuPowerOff(void)
{
if(!needToSetupScreens) clearScreens(false);
//Shutdown LCD
if(ARESCREENSINITIALIZED) I2C_writeReg(I2C_DEV_MCU, 0x22, 1 << 0);
//Ensure that all memory transfers have completed and that the data cache has been flushed
flushEntireDCache();
I2C_writeReg(I2C_DEV_MCU, 0x20, 1 << 0);
while(true);
}
void wait(u64 amount)
{
startChrono();
u64 initialValue = chrono();
while(chrono() - initialValue < amount);
}
void error(const char *fmt, ...)
{
char buf[DRAW_MAX_FORMATTED_STRING_SIZE + 1];
va_list args;
va_start(args, fmt);
vsprintf(buf, fmt, args);
va_end(args);
initScreens();
drawString(true, 10, 10, COLOR_RED, "An error has occurred:");
u32 posY = drawString(true, 10, 30, COLOR_WHITE, buf);
drawString(true, 10, posY + 2 * SPACING_Y, COLOR_WHITE, "Press any button to shutdown");
waitInput(false);
mcuPowerOff();
}

45
arm9/source/utils.h Normal file
View File

@@ -0,0 +1,45 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2019 Aurora Wright, TuxSH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Additional Terms 7.b and 7.c of GPLv3 apply to this file:
* * Requiring preservation of specified reasonable legal notices or
* author attributions in that material or in the Appropriate Legal
* Notices displayed by works containing it.
* * Prohibiting misrepresentation of the origin of that material,
* or requiring that modified versions of such material be marked in
* reasonable ways as different from the original version.
*/
/*
* waitInput function based on code by d0k3 https://github.com/d0k3/Decrypt9WIP/blob/master/source/hid.c
*/
#pragma once
#include "types.h"
#define TICKS_PER_SEC 67027964ULL
#define REG_TIMER_CNT(i) *(vu16 *)(0x10003002 + 4 * i)
#define REG_TIMER_VAL(i) *(vu16 *)(0x10003000 + 4 * i)
#define MAKE_BRANCH(src,dst) (0xEA000000 | ((u32)((((u8 *)(dst) - (u8 *)(src)) >> 2) - 2) & 0xFFFFFF))
#define MAKE_BRANCH_LINK(src,dst) (0xEB000000 | ((u32)((((u8 *)(dst) - (u8 *)(src)) >> 2) - 2) & 0xFFFFFF))
u32 waitInput(bool isMenu);
void mcuPowerOff(void);
void wait(u64 amount);
void error(const char *fmt, ...);