Compare commits

...

577 Commits

Author SHA1 Message Date
Lorenzo Dellacà
243031aed7 no message 2020-07-06 23:58:53 +02:00
Lorenzo Dellacà
1176fa8f28 Merge branch 'master' into 3gx-master
* master:
  Change screen filters presets (adding more) menu & print CCT. Fixes #1442.
  rosalina: implement 800px top-screen screenshot, etc. Fixes #1443

# Conflicts:
#	sysmodules/rosalina/source/draw.c
2020-07-06 20:20:27 +02:00
TuxSH
e69f89a0d4 Change screen filters presets (adding more) menu & print CCT. Fixes #1442.
Most new presets come from 8bitwonder
2020-07-05 20:54:27 +01:00
TuxSH
9411a8c186 rosalina: implement 800px top-screen screenshot, etc. Fixes #1443 2020-07-05 18:44:41 +01:00
Lorenzo Dellacà
aa577d0e39 Update README.md 2020-07-04 14:43:01 +02:00
Lorenzo Dellacà
241dd35000 Update README.md 2020-07-04 14:33:01 +02:00
Lorenzo Dellacà
ca48641a7e fix make error 2020-07-04 11:51:15 +02:00
Lorenzo Dellacà
1fce207bcf trying to fix crashes (cheats, closing games) 2020-07-04 11:49:36 +02:00
Lorenzo Dellacà
c58cb2d916 credits update 2020-07-04 11:30:08 +02:00
Lorenzo Dellacà
d734e36a3a added debug info, udpated makefile to show beta version 2020-07-04 04:16:55 +02:00
Lorenzo Dellacà
28d84f30bb no message 2020-07-04 03:49:02 +02:00
Lorenzo Dellacà
0bb56031d7 no message 2020-07-04 03:38:28 +02:00
Lorenzo Dellacà
cc9977774e fix compile errors 2020-07-04 03:30:15 +02:00
Lorenzo Dellacà
a39053c3c3 Merge remote-tracking branch 'origin/master'
* origin/master: (98 commits)
  rosalina: fix for latest libctru changes
  pm: fix critical bugs where 1.0(?) titles not in the list have scheduling mode misconfigured
  loader: revert to use the NS patch due to a Nintendo bug: https://www.3dbrew.org/wiki/NCCH/Extended_Header#Flag1
  loader: replace NS N3DS CPU patch with exheader override, fix overriding exheader with homebrew
  rosalina: ntp: use PTMSYSM_SetRtcTime
  revert the memory map to the old one (mostly)
  fix module loading
  kext: fix outer memory cacheability on newer versions
  so bascially rosalina's image...
  rosalina: add hidden debug info menu
  rosalina: refactor menu handling
  rosalina: rephrase brightness warning
  rosalina: add brightness control menu
  rosalina/pm: remove fs patch, use pm instead
  rosalina: cleanup variable names
  rosalina: reorder menus
  Fix latest commit
  rosalina menu: add scrolling, cpad and inputredir support (note: no ZL/ZR due to technical reasons)
  stuff
  newlib...
  ...

# Conflicts:
#	k11_extension/source/main.c
#	k11_extension/source/svc/UnmapProcessMemoryEx.c
#	sysmodules/rosalina/Makefile
#	sysmodules/rosalina/include/menu.h
#	sysmodules/rosalina/include/utils.h
#	sysmodules/rosalina/source/errdisp.c
#	sysmodules/rosalina/source/main.c
#	sysmodules/rosalina/source/menu.c
#	sysmodules/rosalina/source/menus.c
2020-07-04 02:43:27 +02:00
TuxSH
dc4de4ce6f rosalina: fix for latest libctru changes 2020-06-26 09:43:42 +01:00
TuxSH
4e12453fff pm: fix critical bugs where 1.0(?) titles not in the list have scheduling mode misconfigured
Also fix the comments.
Thanks @fincs
2020-06-26 01:04:12 +01:00
Aurora Wright
3a0418e279 loader: revert to use the NS patch due to a Nintendo bug: https://www.3dbrew.org/wiki/NCCH/Extended_Header#Flag1 2020-05-29 23:31:05 +02:00
Aurora Wright
1899bf377b loader: replace NS N3DS CPU patch with exheader override, fix overriding exheader with homebrew 2020-05-29 20:57:05 +02:00
TuxSH
0471002d4c rosalina: ntp: use PTMSYSM_SetRtcTime 2020-05-18 22:43:00 +01:00
TuxSH
704e08dc23 revert the memory map to the old one (mostly) 2020-05-18 22:15:34 +01:00
TuxSH
905837468c fix module loading 2020-05-18 21:05:36 +01:00
TuxSH
19d95782e1 kext: fix outer memory cacheability on newer versions 2020-05-18 20:48:54 +01:00
TuxSH
adda19ecb2 so bascially rosalina's image...
was in BASE (hardcoded by kernel) while its heaps were in SYSTEM. Fix this; also put the kext where BASE was.
2020-05-18 01:15:44 +01:00
TuxSH
b02d0346fd rosalina: add hidden debug info menu 2020-05-17 22:48:26 +01:00
TuxSH
9097276a06 rosalina: refactor menu handling 2020-05-17 16:42:44 +01:00
TuxSH
e99ab11c6f rosalina: rephrase brightness warning 2020-05-16 18:31:30 +01:00
TuxSH
a564d8536a rosalina: add brightness control menu 2020-05-16 02:37:47 +01:00
TuxSH
a21eee9207 rosalina/pm: remove fs patch, use pm instead 2020-05-15 22:15:55 +01:00
TuxSH
71cddef78f rosalina: cleanup variable names 2020-05-15 20:00:13 +01:00
TuxSH
9ae913064c rosalina: reorder menus 2020-05-15 02:29:17 +01:00
TuxSH
a2313d1c03 Fix latest commit 2020-05-15 02:06:52 +01:00
TuxSH
22db3445a0 rosalina menu: add scrolling, cpad and inputredir support (note: no ZL/ZR due to technical reasons) 2020-05-14 21:05:27 +01:00
TuxSH
6417720d7d stuff 2020-05-11 10:25:33 +01:00
TuxSH
8b10906d90 newlib... 2020-05-10 18:54:51 +01:00
TuxSH
0c55324d11 rosalina shutdown/reboot: fix a few things 2020-05-10 15:35:39 +01:00
TuxSH
0b4fdc6e66 Revert "Shutdown via rosalina menu is now much faster; similar thing for reboot"
This reverts commit 9942e8b299.
2020-05-10 15:08:13 +01:00
TuxSH
d3e62df769 rosalina: implement dirty hb chainload 2020-05-10 02:58:21 +01:00
Aurora
04bd881cfa Update README.md
Reflect move to the Organization
2020-05-09 20:07:07 +02:00
TuxSH
96799455cb rosalina: allow booting homebrew w/o having to reboot if using a different memory mode 2020-05-09 02:25:33 +01:00
TuxSH
814792eb91 pm: fix handling of PMLAUNCHFLAG_FORCE_USE_O3DS_MAX_APP_MEM 2020-05-09 01:37:09 +01:00
TuxSH
2834bae318 rosalina screenshots: improve conversion time by another 10% 2020-05-08 20:51:41 +01:00
TuxSH
037fae99d6 rosalina: use kernel cached RAM mapping for pixel conversion
Conversion time goes down by 90% with this
2020-05-08 20:20:51 +01:00
TuxSH
49c8888948 rosalina: put screenshot loop inside same TU 2020-05-08 18:19:17 +01:00
TuxSH
1875556f81 Merge pull request #1417 from mtheall/master
Add printf attrtibute to Draw_DrawFormattedString
2020-05-08 16:52:52 +01:00
TuxSH
00850bf691 rosalina: fast screenshots (10s -> 0.3s on my end) 2020-05-08 16:44:30 +01:00
TuxSH
09fd199487 rosalina: Dynamically alloc/free fb cache, exempt rosalina from reslimiting 2020-05-08 01:17:46 +01:00
Michael Theall
32c53578e0 Add printf attrtibute to Draw_DrawFormattedString 2020-05-06 22:34:09 -05:00
TuxSH
0da90f61fc Fix ODR bugs 2020-05-05 18:13:32 +01:00
TuxSH
9942e8b299 Shutdown via rosalina menu is now much faster; similar thing for reboot 2020-05-05 02:01:30 +01:00
TuxSH
daaeb97834 Don't do firmlaunch patches on safe_firm (because of USM) 2020-05-03 01:53:35 +01:00
TuxSH
92da214066 loader: add dsp patch for safe_firm 2020-05-02 23:50:04 +01:00
TuxSH
0f05dd5c0a Revert "rosalina draw.c: remove wait for cmd, gpu processing engine is prone to crashes"
This reverts commit 7dc2b7123b.
2020-05-02 23:36:27 +01:00
TuxSH
166bdbeb7d Add option to run rosalina on N3DS SAFE_FIRM.
Also enables a qtm error bypass
2020-05-02 23:32:21 +01:00
TuxSH
7dc2b7123b rosalina draw.c: remove wait for cmd, gpu processing engine is prone to crashes 2020-05-02 22:38:03 +01:00
TuxSH
3d0ec9b785 Make 3dsx feature compatible with n3ds safe_firm, HOWEVER apps that actually use the GPU won't work 2020-05-02 22:37:15 +01:00
TuxSH
85cfa5cba6 loader: enable secureinfo patch on safe_firm 2020-05-02 18:26:58 +01:00
TuxSH
fdc1eaa16c pm: quick safe_firm fixes 2020-05-02 18:08:24 +01:00
TuxSH
d4dcf1a3e9 k11ext: support SAFE_FIRM in rosalinaThreadLockPredicate 2020-05-02 14:44:39 +01:00
TuxSH
43fd137d55 Use kernel version minor 2020-05-02 12:35:44 +01:00
TuxSH
6931eadc34 update bug report template again 2020-04-29 23:09:20 +01:00
TuxSH
3143e7e1d0 ntp: stop overwriting rtc hwcal cfg backup 2020-04-29 20:18:02 +01:00
TuxSH
d03396d272 pxi: stop putting thread structures on the stack 2020-04-29 16:58:52 +01:00
TuxSH
c8aa2e8a89 change notification 0x1001=>0x2000 2020-03-28 10:58:36 +00:00
TuxSH
c7a3a0278c add quick luma detection getinfo 2020-04-28 10:42:30 +01:00
TuxSH
5924f60d06 gbd: fix address lookup limit on lower fw 2020-04-28 02:45:48 +01:00
TuxSH
cd68b66c03 change kext base address to 0x70000000 2020-04-28 02:39:57 +01:00
TuxSH
44cd3928fb rosalina & pm: properly shutdown when debugger, input redir (but not both) and force connection are enabled 2020-04-28 01:31:29 +01:00
TuxSH
8c54613e44 rosalina/sysconfig: fix handling of disconnected routers in wifi forcing + handle leak 2020-04-28 00:05:55 +01:00
TuxSH
7dfa83b8c0 rosalina: fix gdb/input redir hanging if no internet & fix recovering from failures 2020-04-27 21:58:40 +01:00
TuxSH
b551061264 rosalina/sysconfig: fix wifi forcing, including a regression from v10.1.1 2020-04-27 20:00:41 +01:00
TuxSH
3e228c33c9 here we go again 2020-04-27 18:11:42 +01:00
TuxSH
2b23be8f44 rosalina/cheats: fix v10.1.1 regression where cheats were not working at all. Fixes #1404 2020-04-27 17:59:51 +01:00
TuxSH
ced78cb072 use -wrap for exit 2020-04-27 01:07:57 +01:00
TuxSH
fb17850c3d Update issue template 2020-04-27 01:00:01 +01:00
TuxSH
7f7c4852cc hbloader: raise the maximum time share APT_SetAppCpuTimeLimit can set from 30% to 89%...
... now that we understand both PM and the kernel better.

89% is the maximum value supported for this preemption mode.
2020-04-27 00:57:00 +01:00
TuxSH
f334e3b951 loader/pm: move "force init SD" code to pm. Greatly reduces the number of Arm9 svcBreak with 0xC8804465 2020-04-27 00:47:16 +01:00
TuxSH
9d62995799 rosalina: make the task runner thread actually exit 2020-04-26 21:37:18 +01:00
TuxSH
1d8b793cf7 rosalina: don't keep an ac:u handle. Partially fixes the shutdown issue 2020-04-26 20:55:52 +01:00
TuxSH
33431cb939 pm/kext: make pm terminate Rosalina, removing the need for a dodgy kext hook 2020-04-26 20:33:24 +01:00
TuxSH
e677e0142c rosalina: lower thread prios & make task runner take termination into account 2020-04-26 19:36:59 +01:00
TuxSH
b313a4aa2f rosalina: remove all remaining refs to __syscalls (which we don't init) 2020-04-26 12:07:17 +01:00
TuxSH
37c5c6f049 cheats: don't use rand() 2020-04-26 11:47:15 +01:00
TuxSH
a6d92ed8fe cheats: use pm:dbg new commands to get the application's title ID 2020-04-26 11:27:55 +01:00
TuxSH
eb37ac4142 redefine exit methods for sysmodules. Partially fixes the shutdown issue 2020-04-26 01:50:47 +01:00
TuxSH
a0d4b96915 Fix stack overflow in ProcessListMenu_DumpMemory 2020-04-25 22:48:31 +01:00
TuxSH
31891efbca Current year is 2020 2020-04-25 13:42:10 +01:00
TuxSH
58f3edda12 ARM => Arm 2020-04-25 13:17:23 +01:00
TuxSH
4a655384e2 Add .gitattributes, update README and issue template 2020-04-25 13:03:46 +01:00
TuxSH
0543c208fd Fix #1375 properly this time
Thanks @muhmuhten
2020-04-24 22:52:05 +01:00
TuxSH
0e834ec004 hbloader: allow launching 3dsx apps on < 8.x where Rosalina is supported (4.x+)
Fix kernel caps
2020-04-19 18:22:09 +01:00
TuxSH
26454dc832 loader/patcher.c: make gcc stop sometimes complaining 2020-04-19 18:03:45 +01:00
TuxSH
5c16836626 ntp: change ip to time.windows.com, apparently not blocked in China 2020-04-18 00:29:37 +01:00
TuxSH
67e28b2a82 arm9: check for combos again after the PIN has been entered/splash has been displayed 2020-04-17 01:01:35 +01:00
TuxSH
c2a2893b5c Merge pull request #1284 from izzy84075/toggle-power-button
Add a Rosalina System Configuration option to disable the power button short press
2020-04-17 00:37:59 +02:00
TuxSH
68b670f94f Merge branch 'master' into toggle-power-button 2020-04-17 00:36:07 +02:00
TuxSH
5a83a46423 Merge pull request #1349 from leoetlino/bps
loader: Add support for BPS patches
2020-04-16 23:35:14 +02:00
TuxSH
8785fd0236 Use -Os for rosalina, pm, sm. Decrease gdb buffer sizes, etc. 2020-04-16 21:05:33 +01:00
TuxSH
a67e8e60c6 rosalina: screen_filter: save up around 10K using this simple trick 2020-04-16 19:50:18 +01:00
TuxSH
c7551a731c rosalina: revert errdisp ipc handling 2020-04-16 00:16:25 +01:00
TuxSH
d9c5437902 rosalina: revert menu thread stack size now that screen filters LUT is in .bss 2020-04-15 23:15:14 +01:00
TuxSH
55d51217d8 Fix hex parsing in patcher.c (langemu). Fixes #1375
Thanks @Lizardon1
2020-04-15 22:28:38 +01:00
TuxSH
11c9caaf13 Merge pull request #1348 from mariohackandglitch/patch-1
Fix stack overflow on screen filters
2020-04-15 22:36:21 +02:00
TuxSH
c4711e5e3a Merge pull request #1388 from Margen67/readme
README: Formatting
2020-04-15 22:33:47 +02:00
Margen67
d34f0a8eca README: Formatting
Update Project CTR makerom link.
2020-04-02 17:00:22 -07:00
Léo Lam
8233d4e226 loader: Add support for BPS patches
The BPS format allows distributing patches that are smaller and that do
not contain copyrighted content if data is relocated
(unlike non-trivial IPS patches).

This is essential for games such as Majora's Mask 3D that have three
barely different code revisions. Supporting all three versions would
demand an unreasonable amount of work; with BPS patches only one
version has to be supported.

The patcher is written in C++ in order to make it possible to share the
implementation with Citra and because a C version would be a lot more
ugly and tedious to write. The patcher is non-intrusive for the rest of
the codebase and self-contained so hopefully that isn't an issue.

This adds roughly ~0x500 bytes of code to the loader sysmodule.
Code looks reasonably optimised (in IDA). Tested and works on an o3DS.
2019-12-21 18:32:18 +01:00
Léo Lam
ca49956219 loader: Compile C++ code with -std=gnu++17 2019-12-21 17:49:58 +01:00
PabloMK7
5edfbfc1f7 Fix stack overflow on screen filters 2019-12-17 15:00:37 +01:00
TuxSH
dfd50d9d75 Merge pull request #1298 from LiquidFenrir/force-wifi
add wifi connection forcing to rosalina
2019-11-05 00:15:41 +00:00
TuxSH
1946941340 Merge pull request #1306 from lioncash/null
rosalina/gdb/server: Prevent potential null dereference case
2019-11-05 00:15:07 +00:00
TuxSH
31dae90dcd Merge pull request #1307 from lioncash/null2
sm/notifications: Prevent potential null pointer dereference in ReceiveNotification
2019-11-05 00:14:49 +00:00
TuxSH
da8df54649 Merge pull request #1308 from lioncash/uninit
rosalina/errdisp: Correct uninitialized variable usage in ERRF_HandleCommands
2019-11-05 00:14:28 +00:00
TuxSH
0e1415299a Merge pull request #1332 from Oreo639/errdisp
rosilina: save errdisp info before doing anything else
2019-11-05 00:14:07 +00:00
TuxSH
93f770888d Merge pull request #1320 from nathanhitch/master
Add ability to offset ntp by any amount of minutes
2019-11-05 00:13:22 +00:00
oreo639
0886b10619 rosilina: save errdisp info before doing anything else 2019-10-23 12:12:08 -07:00
nathan hitch
e8493d18c5 Add ability to offset ntp by any amount of minutes 2019-09-16 17:13:23 +09:30
Lioncash
60a8bf56c6 rosalina/errdisp: Correct uninitialized variable usage in ERRF_HandleCommands
This was previously using the value of the uninitialized sz variable
before it was actually assigned a value, rather than assigning the size
indicated within the command buffer.
2019-08-13 03:11:47 -04:00
Lioncash
c95b59c72e sm/notifications: Prevent potential null pointer dereference in ReceiveNotification
Based off the conditions, this is a potential null pointer dereference
that can occur. We need to check for null before accessing
nbPendingNotifications.

This is unlikely to occur in common usage, however it's a fairly
straightforward amendment.
2019-08-13 03:04:03 -04:00
Lioncash
7e14c83bdd rosalina/gdb/server: Prevent potential null dereference case
While unlikely to commonly occur, this is a trivially avoidable case.
2019-08-13 02:54:12 -04:00
TuxSH
a2e46919c1 Merge pull request #1305 from piepie62/master
Fix off-by-one error with extra cheat page
2019-08-12 21:11:21 +02:00
piepie62
a4befc29c8 Fix off-by-one error with extra cheat page 2019-08-12 00:58:16 -04:00
LiquidFenrir
93e87284aa follow changes in ctrulib PR 2019-07-23 00:13:17 +02:00
LiquidFenrir
236dbb043c add wifi connection forcing to rosalina
breaks regular auto connect until reboot
allows connecting to a wifi without internet (for example, for transferring stuff with 3dslink or ftpd/3DShell)
2019-07-21 19:05:37 +02:00
TuxSH
77f0295a04 Merge pull request #1287 from leoetlino/logic
loader: Fix boolean logic error
2019-07-09 00:39:39 +02:00
Léo Lam
c3b97999f5 loader: Fix boolean logic error 2019-07-07 15:06:15 +02:00
PabloMK7
f1b787c7d9 Merge pull request #3 from AuroraWright/master
Merge 10.0.1
2019-07-06 09:37:41 +02:00
selabnayr
3061001fb1 Switch to updating all 4 bytes of the IRQ mask, on the suggestion of profi200. 2019-07-05 15:37:54 -07:00
selabnayr
0bc51d5c34 Add an entry to the System Configuration menu to toggle disabling a short press of the power button triggering a software closure. 2019-07-05 15:04:38 -07:00
TuxSH
c913de1e67 Fix layeredfs, fix #1280 #1275 #1262 & others 2019-07-03 22:19:38 +02:00
TuxSH
c9a578734e Fix N3DS applications not closing properly (fix #1271, #1270, etc.) 2019-06-30 22:59:44 +02:00
TuxSH
37544a0eb9 Fix process list 2019-06-30 13:54:41 +02:00
PabloMK7
6b13b5d06b Merge branch 'AuroraWright-master' 2019-06-29 23:35:07 +02:00
PabloMK7
9705083b65 Fix conflicting files 2019-06-29 23:34:45 +02:00
PabloMK7
2423d1802e Add plgldr string to config menu 2019-06-29 17:16:17 +02:00
TuxSH
3ad314a5ac Fix ntp menu (if user pressed A multiple times) 2019-06-29 17:05:43 +02:00
TuxSH
58a6a25eb3 ntp: also zero field 0x30001 2019-06-29 16:53:31 +02:00
TuxSH
6ed93a1f09 Merge pull request #1266 from luigoalma/master
Properly create BLX instruction
2019-06-29 16:51:57 +02:00
PabloMK7
0b68baa0dd Merge branch 'Nanquitas-master' 2019-06-29 16:26:26 +02:00
PabloMK7
8168d2c2f9 Manually merge files 2019-06-29 16:26:03 +02:00
luigoalma
76dbdf45cf Properly create BLX instruction
Rethinked and revised this function.
This previous one worked by "accident".
More a sheer luck of offsets on current firmware (as of writing)
But now, this is more mathematically correct way of creating a
THUMB -> ARM BLX instruction.
Also setting the new op in a set of 2 u16,
because patching code is in thumb.
2019-06-29 15:22:33 +01:00
TuxSH
d4e1da0174 Update Rosalina credits 2019-06-29 12:21:25 +02:00
TuxSH
fde3b70d03 Fix info os cfwversion/memory by adding null terminator to xml files (thanks @fincs) 2019-06-28 23:44:09 +02:00
TuxSH
8c03702c7d pm: fix uninitialized variable bug (thanks @fincs !) 2019-06-28 20:43:06 +02:00
TuxSH
31c6ead2ad Fix bug-report.md name 2019-06-28 20:12:44 +02:00
TuxSH
454fa16b3a Update bug-report.md.md 2019-06-28 20:01:06 +02:00
TuxSH
301e84f1ca Merge pull request #1194 from noirscape/patch-2
Taking advantage of GitHubs new issue templates.
2019-06-28 19:51:57 +02:00
TuxSH
69634fdbd5 Merge pull request #1264 from piepie62/master
Use bitflags
2019-06-28 19:44:09 +02:00
piepie62
10e823a9d5 Use bitflags 2019-06-24 15:42:32 -04:00
TuxSH
f4851cd533 fixed inverted condition in hio.c 2019-06-18 23:58:47 +02:00
TuxSH
39287d43e3 Fix null deref when connecting to port 4003 but force debug next app hasn't been selected 2019-06-18 00:02:32 +02:00
TuxSH
09b2bf5fb1 fix build with newer gcc 2019-06-16 23:20:40 +02:00
TuxSH
e989309771 Fix "disable debugger" finally 2019-06-16 22:06:05 +02:00
TuxSH
d989c45c3d Failed attempt w/ next app 2019-06-14 01:32:50 +02:00
TuxSH
84c5cf0661 Failed attempt at fixing disable debugger when 1+ sessions are open 2019-06-14 00:40:41 +02:00
Chromaryu
648541bb1f Add NTP_IP dynamic changes via -D or #define (#1261)
* Add define option on Makefile to change NTP_IP dynamically

* Remove Makefile -D option
2019-06-03 23:24:21 +02:00
TuxSH
2cf04e8a83 Make Luma arm9 code properly write date when touching files 2019-06-03 23:15:30 +02:00
TuxSH
af10782500 Merge branch 'ntp' 2019-06-03 00:58:37 +02:00
TuxSH
fe0e5ae83d Fix #1259 2019-06-03 00:58:07 +02:00
TuxSH
8e4af5c823 Add ntp client & rtc sync 2019-06-03 00:54:20 +02:00
Chris Feger
570a8d5222 CTRPF-AR Codes (#1259)
* Add most extended CTRPF codes

* Fix some stuff

* FIx a couple more things

* Make the loop break actually work

* Make break work properyly v2

* Clean up a bit

* Get rid of redundant assignment

* Fix off-by-one error

* Fix possible out-of-bounds

* Switch to statically allocated cheat page

* Style changes.
Awaiting further input for the last couple

* Use more booleans
2019-06-03 00:50:27 +02:00
TuxSH
2c8a1eb5c6 gdb hio: lseek returns 64-bit 2019-05-04 17:08:32 +02:00
TuxSH
23c40aeb8e gdb hio: add type l 2019-05-04 16:30:34 +02:00
TuxSH
c7c832a0dd Relicense gdbstub (with permission of contributors) 2019-05-03 21:06:10 +02:00
TuxSH
6423d0c1b3 gdb: fix hang when "debug next application" is used more than once 2019-05-01 19:37:46 +02:00
TuxSH
8b56098d64 Fix TIO encoding bug 2019-04-28 15:04:42 +02:00
TuxSH
2927bd5aa3 gdb: double packet size 2019-04-28 02:15:46 +02:00
TuxSH
d357db25f2 gdb TIO: fix mode and flags being swapped 2019-04-28 02:06:31 +02:00
TuxSH
9b3cc5391b tio fixes 2019-04-27 23:23:36 +02:00
TuxSH
54eeb97b24 Add GDB target IO support (called Host I/O by gdb), not working yet 2019-04-27 16:50:47 +02:00
TuxSH
593f50de91 Merge pull request #1246 from piepie62/Debuffer
Remove cheat file buffer and use buffered reading
2019-04-23 23:04:34 +02:00
piepie62
85af8d9fa4 Merge branch 'Debuffer' of https://github.com/piepie62/Luma3DS into Debuffer 2019-04-23 08:25:10 -07:00
piepie62
58ff96dc83 Merge origin into this branch 2019-04-23 08:24:50 -07:00
TuxSH
a5803d1b62 Merge pull request #1245 from piepie62/IFile-Fix
IFile: Fix reading past the end of file
2019-04-23 11:29:54 +02:00
TuxSH
eddb0988a0 Merge pull request #1243 from piepie62/master
Improve cheat execution parameters and handle CRLF properly
2019-04-23 11:29:04 +02:00
TuxSH
5d3585a33d fix gdb control C regression 2019-04-21 18:00:29 +02:00
TuxSH
4285736286 fix layeredfs regression 2019-04-21 12:15:50 +02:00
piepie62
32b8cf6172 Merge branch 'master' of https://github.com/AuroraWright/Luma3DS into Debuffer 2019-04-19 11:36:19 -07:00
TuxSH
3e724e88a8 Fix crash dumps not saving properly 2019-04-19 10:01:00 +02:00
TuxSH
687dfddd9f HBLDR_DebugNextApplicationByForce changes 2019-04-19 00:37:20 +02:00
piepie62
90a43089ba Debuffer cheat reading and strip whitespace
Effectively doubles the amount of cheats possible, while also getting rid of that annoying line limit
2019-04-18 14:01:46 -07:00
piepie62
1e0baeb30e Fix reading past the end of a file 2019-04-18 14:01:02 -07:00
piepie62
353f7d1705 Add bounds checking 2019-04-18 14:01:02 -07:00
piepie62
f5f3764f99 Improve cheat execution parameters and handle CRLF properly 2019-04-18 14:01:02 -07:00
TuxSH
eef22f8701 Fix "debug next process" with hbldr homebrew 2019-04-18 22:58:53 +02:00
TuxSH
9e1a9f2842 Implement HBLDR_DebugNextApplicationByForce
also prevent port 4003 (next application) from being extended-remote
2019-04-18 22:28:23 +02:00
TuxSH
0b33134f6c Loader services refactor 2019-04-18 19:48:01 +02:00
TuxSH
5c4d6c68b2 gdb: fix GDB_AttachToProcess returning success even when the process doesn't exist 2019-04-18 00:40:20 +02:00
TuxSH
89e42a457c gdb: hio: fix error parsing 2019-04-17 23:53:27 +02:00
TuxSH
17ca09346d gdb: fix multiple extended-remote issues, also fix possible race condtions 2019-04-17 23:12:29 +02:00
TuxSH
54de645dc3 pm: fix inverted condition 2019-04-17 02:03:02 +02:00
TuxSH
da6c02068b pm: fix reslimit bug 2019-04-17 01:31:03 +02:00
TuxSH
06bcb39721 always save errdisp to file; hio changes 2019-04-17 00:18:12 +02:00
piepie62
2b31a4ab5c Merge master into Debuffer 2019-04-15 15:19:46 -07:00
piepie62
3b4ef682fe Debuffer cheat reading and strip whitespace
Effectively doubles the amount of cheats possible, while also getting rid of that annoying line limit
2019-04-15 15:14:53 -07:00
piepie62
eab9a31dff Fix reading past the end of a file 2019-04-15 13:08:53 -07:00
piepie62
ff86ed2e77 Add bounds checking 2019-04-15 03:41:25 -07:00
piepie62
2fe1169423 Improve cheat execution parameters and handle CRLF properly 2019-04-14 23:12:14 -07:00
TuxSH
4c9fe186d7 gdb: hio support (untested yet) 2019-04-14 21:48:15 +02:00
TuxSH
e11cc090b2 gdb: add support to run new processes
Only titleId [mediaType [launchFlags]] is supported, and the launched title shouldn't rely on APT and all 3 parameters should be hex-encoded.

usage example, with titleId+mediaType:
(gdb) set remote file-exec 0004013000003702
(gdb) r 0
2019-04-13 19:18:47 +02:00
TuxSH
763a1de8d3 gdb: add extended-remote support, implement vAttach 2019-04-12 23:40:51 +02:00
TuxSH
e57b546dd4 gdb: rework meaning of selected/used 2019-04-10 23:38:10 +02:00
TuxSH
bd670cf87c gdb: add GDB_FindAllocatedContextByPid 2019-04-10 23:17:49 +02:00
TuxSH
1e0996c395 gdb: simply gdbstate 2019-04-09 23:59:05 +02:00
TuxSH
5f295c4227 increase i2c timeout 2019-04-07 16:13:14 +02:00
Aurora Wright
4f699ccb81 Fix external firm booting with old firms, minor style changes 2019-04-06 21:32:06 +07:00
TuxSH
70757e564d refactor latest commit 2019-04-05 00:55:13 +02:00
TuxSH
af822e5af5 Fix n3ds IPS screen issues/regression, closes #1236 2019-04-05 00:04:38 +02:00
TuxSH
63736d7873 Refactor process detaching code 2019-03-31 22:58:36 +02:00
TuxSH
fb800bd4c9 Add support to force-debug applications before they start running code 2019-03-31 20:01:16 +02:00
TuxSH
219f38169f Update drawString (rosalina) 2019-03-31 17:04:07 +02:00
TuxSH
c688600d33 PMDBG_GetCurrentAppTitleId => PMDBG_GetCurrentAppTitleIdAndPid 2019-03-31 16:12:31 +02:00
TuxSH
ea14d8a186 gdb: avoid race conditions 2019-03-31 01:14:40 +01:00
TuxSH
cd18b85632 gdb: refactor port/ctx alloc 2019-03-31 00:24:45 +01:00
TuxSH
22ec031495 Add client code for new custom pm commands, use them, fix pm race conditions 2019-03-30 18:12:54 +01:00
TuxSH
43b998d37d Add new pmdbg commands: GetCurrentAppTitleId, DebugNextApplicationByForce, LaunchTitleDebug 2019-03-30 15:36:49 +01:00
TuxSH
127101a683 Fix debug bug 2019-03-30 15:05:49 +01:00
TuxSH
5955ca6957 Increase max number of sessions for pmdbg 2019-03-30 14:15:23 +01:00
TuxSH
dcddcfc94d Allow PMLAUNCHFLAG_QUEUE_DEBUG_APPLICATION for non-apps 2019-03-29 23:22:16 +01:00
TuxSH
1453d9adac cubic ninja users rejoice 2019-03-29 23:01:55 +01:00
TuxSH
ef034a87d4 revert fsldr change, fix null deref in pm 2019-03-29 22:40:54 +01:00
TuxSH
e688ec9257 move patches to pm 2019-03-29 19:07:24 +01:00
TuxSH
ae1f85d341 K11Ext: add GetSystemInfo k11extSize 2019-03-29 18:23:52 +01:00
TuxSH
7177799021 Rosalina: delete "auto screenfilter restore on wakeup" functionality.
It was causing sleep mode wakeup issues and/or interfering with gsp in a
bad way.
2019-03-29 18:23:52 +01:00
TuxSH
1041d7c438 Add custom pm sysmodule 2019-03-29 00:32:45 +01:00
TuxSH
e57abad52f ctrulib changes 2019-03-29 00:09:59 +01:00
TuxSH
74bbfb95d3 service_manager: auto subscribe 2019-03-28 22:56:13 +01:00
TuxSH
8345f31c2a Fix wrong result code returned in GetServiceHandle 2019-03-27 21:56:13 +01:00
TuxSH
d44055d232 sm: simplify main loop logic 2019-03-27 20:36:40 +01:00
TuxSH
4a431b8fdf Fix bug in port closed handling 2019-03-26 23:15:37 +01:00
TuxSH
e2ed200509 Fix doPublishNotification bug 2019-03-26 20:53:48 +01:00
TuxSH
4e5f6e1eff Fix #1232
Thanks @profi200
2019-03-23 23:14:23 +01:00
TuxSH
474eb3001b Introduce service_manager, also fix hb:ldr pm/pm race condition 2019-03-16 23:40:43 +01:00
TuxSH
f72d99d9b0 Fix wrong number of menus 2019-03-16 23:34:51 +01:00
TuxSH
a9a569c79d Remove useless rules 2019-03-16 18:11:46 +01:00
TuxSH
68b8c99ad0 Fix parallel building 2019-03-16 13:10:30 +01:00
TuxSH
d8c6f94887 Fix config title 2019-03-15 23:21:12 +01:00
TuxSH
8b51141f54 Fix latest commit 2019-03-15 23:03:25 +01:00
TuxSH
0195ab34e9 Fix itcm sections overwriting argv 2019-03-15 23:03:25 +01:00
TuxSH
0bb82feb81 Fix string format case in exceptions.c 2019-03-15 23:03:25 +01:00
TuxSH
6199f598e5 Add -nocodepadding to cxis as it ought to be 2019-03-15 23:03:25 +01:00
TuxSH
b92406afe2 Fix rebase 2019-03-15 23:03:25 +01:00
TuxSH
244409fc98 Change k11 mapping logic again 2019-03-15 23:03:24 +01:00
TuxSH
f3b2a6c30d Fix some of the bugs 2019-03-15 23:03:24 +01:00
TuxSH
a65f7fbf88 Fix the linker scripts again 2019-03-15 23:03:24 +01:00
TuxSH
35ad240018 Rewrite k11ext mmu mapping func + linker script 2019-03-15 23:03:23 +01:00
TuxSH
e64f267e4c Fix section declarations in .s files 2019-03-15 23:03:23 +01:00
TuxSH
d28e961adc Use <string.h> & <3ds/exheader.h>, fix some bugs, etc.
also fix all warnings and use -Werror
2019-03-15 23:03:23 +01:00
TuxSH
e6b7dc1dc5 Add top-level Makefile + @fincs 's linker script fixes 2019-03-15 23:03:22 +01:00
TuxSH
9e7e967a5f Fix bss being PROGBITS, etc. 2019-03-15 23:03:22 +01:00
TuxSH
33d40b491e Fix firm.c sysmodule merging loop 2019-03-15 23:03:21 +01:00
TuxSH
7cb50d38b9 Fix linker script bug, see details
LD interprets "a.o b.o c.o(sectionexpr)" as 3 separate input commands, i.e. it will copy all the sections from a.o, then b.o and the sections matching (sectionexpr) from c.o in that order; (a.o b.o c.o)(sectionexpr) results in a syntax error.
2019-03-15 23:03:21 +01:00
TuxSH
d6d440a47e Sanitize arm9 build system... however link script overflows itcm 2019-03-15 23:03:21 +01:00
TuxSH
52cd950ca6 source => arm9/source 2019-03-15 23:03:20 +01:00
TuxSH
9fad2dff21 Add top-level Makefile for sysmodules 2019-03-15 23:03:20 +01:00
TuxSH
4b40dd52f4 Give a proper build system for each sysmodule, k11ext, arm11.
Previously, these Makefiles didn't correctly track header changes.
The project doesn't build as a whole, future commits will fix it.
2019-03-15 23:03:19 +01:00
TuxSH
6bd7070d38 Do the same for romfs redit => get rid of armips; update README.md 2019-03-15 23:03:18 +01:00
TuxSH
0c9365bcb7 Do the same for large patches (emunand, reboot). This greatly simplifies logic. 2019-03-15 23:03:18 +01:00
TuxSH
c0bd69309a Do the same for arm9 exceptions 2019-03-15 23:03:18 +01:00
TuxSH
55bd62d7a9 Merge the chainloader into the main ARM9 folder 2019-03-15 23:03:18 +01:00
TuxSH
020236742f Fix gdbstub UB with IO 2019-03-15 22:37:04 +01:00
TuxSH
faeb0d9395 Fix strict-aliasing-related UB 2019-03-15 22:23:44 +01:00
TuxSH
b05f993221 Fix wrong memset size in screen_filters 2019-03-15 17:04:15 +01:00
TuxSH
e796abb155 Also use alignedseqmemcpy for sha_hash 2019-03-15 16:17:57 +01:00
TuxSH
3d2c12cf09 Revert sdmmc driver, fixes regression #1225. Also fix a logic bug 2019-03-13 17:33:53 +01:00
TuxSH
8ff5111e30 Use better i2c driver from fb3ds 2019-03-13 16:34:11 +01:00
TuxSH
673ec9fc51 Fix memcpy into fifo UB 2019-03-13 13:53:29 +01:00
TuxSH
a7100a1e7f Fix implicit fallthrough in debug.c 2019-02-28 19:08:39 +01:00
TuxSH
710ad11819 Upgrade fatfs and sdmmc driver 2019-02-28 19:04:11 +01:00
TuxSH
f718297591 Fix screens not working on firmlaunch
- LCD fill was not unset
- Still needs to do screeninit on firmlaunch even though PDN_GPU_CNT is 0x1007F
2019-02-26 20:19:52 +01:00
BuildTools
1c7b55ee1e Bump copyright year 2019-02-24 18:04:32 -07:00
TuxSH
f437d92374 Merge pull request #1065 from panicbit/screen_filter
Implement blue light filters
2019-02-21 19:48:07 +01:00
TuxSH
47916b2831 Fix menu thread stack overflow
sizeof(menuThreadStack) not matching 0x3000
2019-02-21 19:47:35 +01:00
Nanquitas
4b341e039a Merge branch 'master' of https://github.com/AuroraWright/Luma3DS 2018-11-15 13:49:35 +01:00
Nanquitas
1ae01c2406 GDB: add 'catchsvc' command to catch svc with IDA
Usage:
   - 'catchsvc 0' : Don't catch svcs
   - 'catchsvc 1' : Catch all svcs
   - 'catchsvc 1;19;24;32;' : Only catch svc 0x19, svc 0x24 and svc 0x32
2018-11-15 13:44:45 +01:00
Nanquitas
2182742708 Implement plugin loader 2018-11-15 13:38:19 +01:00
noirscape
0791aabbf8 Taking advantage of GitHubs new issue templates. 2018-10-13 17:29:35 +02:00
Aurora
bd15f51af3 Fix incomplete commit (3903ac6409) 2018-09-28 03:08:35 +02:00
TuxSH
932ed4222f Merge pull request #1142 from luigoalma/master
Added Patch to Process9 11.8 to the new AMPXI function
2018-09-20 09:44:36 +02:00
luigoalma
1052e04679 Added Patch to Process9 11.8 to the new AMPXI function
Patch it to call __rt_memclr instead of internal PRNG when generating Key
and IV.
Only if UNITINFO is set, preventing on regular console usage NIM sending
to nintendo a 0 Key and IV, and allowing nintendo to know who has a
patched console.
2018-09-10 19:57:14 +01:00
Aurora Wright
3903ac6409 Implement https://github.com/AuroraWright/Luma3DS/issues/470 2018-08-21 22:07:18 +02:00
Aurora Wright
53622d777b Fix https://github.com/AuroraWright/Luma3DS/issues/1095 and https://github.com/AuroraWright/Luma3DS/issues/1118 2018-08-21 18:57:45 +02:00
tstambaugh92
2219b19d5f Fixed cheat functionality (#1117) 2018-08-09 14:21:16 +02:00
tstambaugh92
bc06b17823 Fixed cheat functionality (#1116)
Fixed functionality of BXXXXXXX codes
2018-08-07 12:50:48 +02:00
Nanquitas
2520079536 Increase code dump on exception 2018-08-04 16:22:16 +02:00
Aurora Wright
d7095ce37d Fix patchKernel9Panic on 11.8 NATIVE_FIRM (pattern tested down to 3.0) 2018-08-04 16:11:14 +02:00
Nanquitas
0a87e41c66 socAccept: Fix an omitted comment, which masked a condition 2018-08-04 16:10:35 +02:00
Aurora Wright
89cc6ede1a Fix patchKernel9Panic on 11.8 NATIVE_FIRM (pattern tested down to 3.0) 2018-07-31 04:32:29 +02:00
Nanquitas
dd6e071dde socAccept: Fix an omitted comment, which masked a condition 2018-07-05 23:33:34 +02:00
Nanquitas
bec8daf028 Fix sleep issue (freeze) when InputRedirection is enabled 2018-06-23 23:06:18 +02:00
TuxSH
2127271b33 Double-license the gdbstub. 2018-06-14 18:33:09 +02:00
TuxSH
1600171ffa Bump copyright year 2018-06-14 18:13:57 +02:00
Yuuki Hikari
7f7a9fab2d Merge pull request #1088 from ev1l0rd/patch-1
Remove AUR package from prebuilds.
2018-05-28 15:10:32 -04:00
Valentijn
b15d86f31d Remove AUR package from prebuilds.
Ater discussion with @Hikari-chin (and some other people), I've come to the conclusion that it's not a wise idea to link to an AUR package in the README.

That said, it might still be useful to provide a compiled version of armips for Linux as Windows builds are also provided. To this extent I've compiled armips for both x86 and x86_64 architectures (available in the zip file linked in the commit, or [here](https://ev1l0rd.s-ul.eu/mEIk4atQ) if you dont wish to open the commit). (It's possible to identify the binary arch with the `file` command if one wishes to verify I did this properly).
2018-05-22 20:18:39 +02:00
TuxSH
89a3dc8643 Merge pull request #1084 from ev1l0rd/patch-1
Removed links to compiled armips and makerom
2018-05-22 10:05:00 +02:00
TuxSH
3477beb05c Merge pull request #1086 from Nanquitas/patch-1
Fix GPU_PSC1_CNT address
2018-05-21 00:00:22 +02:00
Nanquitas
8447c209a7 Fix GPU_PSC1_CNT address 2018-05-13 10:58:07 +02:00
Valentijn
e78f706c1a Removed links to compiled armips and makerom
The mega link for linux armips 404's and makerom is no longer supplied in buildtools due to a change by steveice10.

Removed the compiled makerom links entirely and replaced linux armips with a link to the armips-git package on the AUR.
2018-05-12 20:12:52 +02:00
TuxSH
f776c56cd4 Merge pull request #1069 from Nanquitas/patch-1
Fix KProcessHandleTable__ToKThread on latest fw
2018-04-26 19:33:03 +02:00
Nanquitas
dc195dffad Fix KProcessHandleTable__ToKThread on latest fw 2018-04-26 19:30:50 +02:00
panicbit
74a0b2feae Simplify color LUT writes 2018-04-16 01:28:57 +02:00
panicbit
71039fc248 Remove unnecassary permission declarations 2018-04-15 17:15:06 +02:00
panicbit
d0306609c3 Apply screen filter when waking up from standby 2018-04-15 16:26:20 +02:00
panicbit
d13cde3d7b Implement blue light filters in rosalina 2018-04-15 04:55:20 +02:00
panicbit
38f54fd2b6 Add parts of redshift to rosalina 2018-04-15 04:55:20 +02:00
panicbit
b5728e9c11 Add gpu color LUT registers to rosalina 2018-04-15 04:55:14 +02:00
TuxSH
a2177c0510 Fix menu entries (again) 2018-04-05 23:40:18 +02:00
TuxSH
356a94cc2e Double the size of launchedPath 2018-04-05 23:20:30 +02:00
Yuuki Hikari
9d507e046c Merge pull request #1054 from LegoFigure11/master
Update links to the Plailect's Guide
2018-04-04 20:34:54 -04:00
LegoFigure11
47c47f967a Update links to the Plailect's Guide 2018-04-01 01:29:25 +11:00
Aurora
1182d3a627 Fix #1050 2018-03-23 02:49:16 +01:00
TuxSH
938cb6492f Revert "Revert "Switched from mapping target process memory to svcReadProcessMemory & svcWriteProcessMemory functions.""
This reverts commit 1fd689f5da.
2018-03-20 01:11:49 +01:00
TuxSH
fed62855cb Merge pull request #1000 from duckbill007/master
Gateshark cheats support
2018-03-20 01:00:25 +01:00
Mikaela Szekely
4f54596658 Implement #940 (#1043)
Thanks @Qyriad ^^
2018-03-04 00:45:47 +01:00
Aurora Wright
0b41ed04d5 Simplify loadNintendoFirm after the previous commit 2018-02-09 05:09:43 +01:00
Aurora Wright
9509a86998 Force using the external FIRM if CTRNAND couldn't be mounted or the CTRNAND FIRM has issues 2018-02-05 03:47:43 +01:00
Duckbill
6d4d80a798 Merge remote-tracking branch 'upstream/master' 2018-01-19 17:38:57 +03:00
TuxSH
76d274cfe2 getmemregions: userland never exceeds 0x40000000 2018-01-19 01:42:53 +01:00
TuxSH
ccf13be964 Merge pull request #1010 from Nanquitas/input-redirection-sockupdate
InputRedirection: check service existence instead of using OpenProcessByName
2018-01-19 01:30:15 +01:00
TuxSH
e36b27ccf0 Merge pull request #1012 from Nanquitas/rosalina-freeze-fix
Rosalina: fix freeze when attempting to open Rosalina before the syst…
2018-01-19 01:29:58 +01:00
TuxSH
34c80ad476 Merge pull request #1009 from Nanquitas/gdb-list-memregion
gdb: new getmemregions command
2018-01-19 01:28:53 +01:00
TuxSH
97ae106d8e Merge pull request #1011 from Nanquitas/patch-2
sock_util: remove unneeded check
2018-01-19 01:28:08 +01:00
Nanquitas
7cb74b74d7 Rosalina: fix freeze when attempting to open Rosalina before the system finished to boot 2018-01-18 23:39:47 +01:00
Nanquitas
337205eb08 sock_util: remove unneeded check
We loop while (server_sockfd == -1) so it's safe to assume that (server_sockfd != -1) once out of the loop.
2018-01-18 22:57:46 +01:00
Nanquitas
f36977017b InputRedirection: check service existence instead of using OpenProcessByName 2018-01-18 20:44:54 +01:00
Nanquitas
e40b547bb6 gdb: new getmemregions command 2018-01-18 17:23:43 +01:00
Duckbill
1fd689f5da Revert "Switched from mapping target process memory to svcReadProcessMemory & svcWriteProcessMemory functions."
This reverts commit c5c8dca14c.
2018-01-16 09:54:55 +03:00
Duckbill
c5c8dca14c Switched from mapping target process memory to svcReadProcessMemory & svcWriteProcessMemory functions. 2018-01-15 21:29:05 +03:00
TuxSH
11f820efa7 Check service existence before GetServiceHandle 2018-01-15 02:52:50 +01:00
TuxSH
9074688491 Make srvGetServiceHandle non-blocking if service port is full in all cases 2018-01-15 02:27:07 +01:00
Duckbill
1de27c54f1 Fix range checks 2018-01-13 16:02:54 +03:00
Duckbill
3e67e64faa Fixes after review on github 2018-01-13 13:51:28 +03:00
TuxSH
553f8d2533 Remove lto for sysmodules 2018-01-12 11:20:17 +01:00
Duckbill
ec7ae35da1 Fixes for masked 16-bit cheat opcodes, based on existing cheats. 2018-01-12 10:46:50 +03:00
Duckbill
7e8da0d236 Possible out of bounds fix 2018-01-10 09:53:36 +03:00
Duckbill
b3e6561072 Merge remote-tracking branch 'upstream/master' 2018-01-06 12:29:08 +03:00
Aurora Wright
41f32ed983 Remove the need for hardcoding the horizontal positions for the "x"s in multiple choice options 2018-01-05 19:38:58 +01:00
TuxSH
bbadf840ef struct fb shouldn't be packed 2018-01-04 22:12:31 +01:00
TuxSH
acc50aae46 Merge branch 'master' of github.com:AuroraWright/Luma3DS 2018-01-04 18:41:14 +01:00
TuxSH
6a68a77973 Rewrite the ARM9 exception handlers, ...
- Fix patchArm9ExceptionHandlersInstall for older versions

- Fix some bugs in the ARM11 exception handlers

- Other, minor, changes
2018-01-04 18:40:11 +01:00
Duckbill
0f4d66dd61 Try to load cheats if there aren't any on every open of cheats menu. 2018-01-03 11:48:10 +03:00
Duckbill
d28642d2c3 More range checks and separate code and heap allocation 2018-01-03 00:27:44 +03:00
Duckbill
ca4685cc42 Range checks added 2018-01-02 14:23:45 +03:00
Aurora
522f10582d Merge pull request #995 from joel16/master
Update MCU::HWC functions with latest changes from ctrulib
2018-01-01 18:07:32 +01:00
Joel16
239d113177 Update mcu functions with changes from ctrulib 2018-01-01 11:05:22 -06:00
Duckbill
fd80294bf2 Fix buffer overflow in case of very long cheats.txt file 2017-12-31 11:26:18 +03:00
Duckbill
b379d83469 Merge remote-tracking branch 'upstream/master' 2017-12-31 11:16:44 +03:00
Aurora
27f352fdf1 Merge pull request #991 from Qyriad/master
Implement #989: Add configurable splash duration
2017-12-29 05:08:22 +01:00
Mikaela RJ Szekely
bfec874a7c Add colon in option that I forgot 2017-12-28 22:02:06 -05:00
Mikaela RJ Szekely
93561003e8 Implement #989: Add configurable splash duration 2017-12-28 21:50:06 -05:00
TuxSH
1572bfd989 [sm] Fix process unregistering logic bug (fixes #984)
In this case pm+sm were supposed to automatically unregister ro's services (the kernel can close a dying process's handle automatically). Not doing this apparently induced a reference leak of DevMenu's as a process, preventing it to be destroyed and the memory allocation reslimit counter to be updated by KProcess's destructor accordingly.
2017-12-27 19:30:57 +01:00
Duckbill
cb945612a3 Remove ast empty cheat from list 2017-12-25 14:16:57 +03:00
Duckbill
1b440f7f3b Skip empty cheats 2017-12-25 13:57:20 +03:00
Duckbill
78791f7b66 Paging fixes 2017-12-25 13:45:09 +03:00
Duckbill
5def0c18e2 Cheat file format changed from binary to plaintext 2017-12-22 14:46:46 +03:00
Duckbill
0e67b0f026 Moved key combo calculation to loading cheat phase 2017-12-22 12:39:09 +03:00
Duckbill
8052946517 Cheats array repleced by continous buffer 2017-12-22 12:17:45 +03:00
Duckbill
b6d6cc9750 Cheat implementations 2017-12-21 20:14:04 +03:00
TuxSH
2a840f2c79 Minor date/time conversion loop style fixes 2017-12-19 02:32:51 +01:00
TuxSH
4eaf791849 Merge pull request #937 from Hayleia/timestamped-screenshots
screenshots use timestamps as name
2017-12-19 02:15:07 +01:00
Aurora Wright
be0f50b19c Disable poweroff when shell closed on NTRboothax altogether to prevent issues with unstable magnets 2017-12-18 21:02:41 +01:00
Aurora Wright
f30b7b9fb3 Merge branch 'master' of https://github.com/AuroraWright/Luma3DS 2017-12-18 20:56:45 +01:00
Aurora Wright
6a0f332e3c Shutdown when waiting for button presses if the shell is closed, except when coming from a NTRboothax boot 2017-12-18 20:56:32 +01:00
TuxSH
16530d3a52 Merge pull request #972 from LiquidFenrir/ramviewer-fix
fix mistake, processes viewed were attached even if debugger was off
2017-12-18 07:13:13 +01:00
Aurora Wright
20af9c6750 Fix issue reported in
f27cdb4543\#commitcomment-24611141, simplify 56e54cd110
2017-12-18 04:27:11 +01:00
LiquidFenrir
fee9f6b427 forgot to return, made processes viewed attached even though the debugger wasnt enabled 2017-12-17 19:31:05 +01:00
TuxSH
57d03d6333 Merge pull request #916 from LiquidFenrir/ramviewer-fix
Several ramviewer improvements
2017-12-17 03:31:36 +01:00
LiquidFenrir
0075fe2aa0 work with processes with code starting at 0x14000000 2017-12-16 19:26:55 +01:00
LiquidFenrir
d54417ac0a explicit casting 2017-12-16 19:26:27 +01:00
LiquidFenrir
648801d432 make pressing X accidentally twice less punitive 2017-12-16 04:30:40 +01:00
LiquidFenrir
2be2826b0b detect jumping address and change mode accordingly 2017-12-16 04:14:21 +01:00
LiquidFenrir
37a9fa1bf4 work again with heapless processes, and show wether you're currently viewing heap or code on screen (apart from the address) 2017-12-14 17:03:13 +01:00
LiquidFenrir
65af93c8ce other display for entering goto 2017-12-07 22:07:53 +01:00
LiquidFenrir
8353b84944 fix dump filename 2017-12-07 20:07:44 +01:00
LiquidFenrir
d6a89db495 make use of values defined in draw.h 2017-12-07 19:56:36 +01:00
LiquidFenrir
f156aa8cdb add dumper
mostly a copy of the screenshotting function/from #937
2017-12-07 19:53:44 +01:00
LiquidFenrir
f9adbcc9d9 fix same-name variables 2017-12-07 18:23:29 +01:00
TuxSH
cf8696ac70 Disable non-process memory access by default (see below), remove IDA 6.8 support...
The physical memory access "bit31" mapping (0--0x30000000 => 0x80000000--0xB0000000) as well as privileged (kernel) mappings confuse debugger clients like IDA's which interpret the value of the registers.
Access to those mappings can be toggled using "monitor toggleextmemaccess" instead (issue reported by @Nanquitas). Closes #943.

Additionally, support for the buggy IDA 6.8's buggy gdb client was removed. Please use IDA 7.0 or higher.

P.S: IDA 7.0 added client support for no-ack mode (Debugging options > Set specific options), which should be enabled to make debugging twice as smooth. "Use stepping support" should be unchecked.
2017-11-26 02:18:59 +01:00
Yuuki Hikari
9c5766f649 Merge pull request #945 from astronautlevel2/master
Switch to APT_ResetHardwareAsync() for reboot (Closes #831), fix #831
2017-11-23 20:46:01 -05:00
Alex Taber
c9701f93b9 Switch to APT_ResetHardwareAsync() for reboot (Closes #831) 2017-11-23 20:32:26 -05:00
Aurora Wright
56e54cd110 Fix https://github.com/AuroraWright/Luma3DS/issues/921 2017-11-22 19:03:39 +01:00
TuxSH
55836b48af Merge pull request #942 from Nanquitas/watchpoint-fix
Fix the impossibility to set a second watchpoint
2017-11-22 16:17:53 +01:00
Asuka Amari
09bfdb9ee1 removed unused variable 2017-11-22 07:03:00 +01:00
Nanquitas
1c2e8dec11 Fix the impossibility to set a second watchpoint 2017-11-22 03:37:23 +01:00
TuxSH
506b16db37 Fix watchpoints handling (huge thanks to @Nanquitas) 2017-11-22 01:24:35 +01:00
Asuka Amari
8f03234e58 screenshots now use timestamps as name
Instead of being called top_XXXX.bmp where XXXX means nothing,
screenshots are now called YYYY-MM-DD_HH-MM-SS.mmm_top.bmp (and same
idea for bot and top_right).

First obvious consequence, this is easier to manage in a file browser.
Now you have screenshots grouped by time, and you also have the 2 or 3
related screenshots (top, bot, top_right) close one to another.

Another consequence is that there is no need to go through existing
screenshots to find an unused number. Now osGetTime takes care of
everything. And going through files was a very time consuming process.
Now screenshots only need 4 (or 6 if 3D) seconds to be saved (instead of
40 seconds if you had 200 screenshots in your directory already).

Conflicts may happen when people change the date and time on their 3DS,
but that's why I even included milliseconds in the timestamp. People
don't set date and time everyday and they'd be unlucky to take a
screenshot at the exact time, milliseconds included, as another
screenshot right after setting the time one hour earlier...

Source for converting seconds since 1970 (or 1900...) to date and time:
https://stackoverflow.com/questions/21593692/
2017-11-18 16:37:35 +01:00
TuxSH
44b5e10323 Fix N3DS menu entry 2017-11-10 20:51:52 +01:00
LiquidFenrir
48303604b0 show address instead of offset when jumping 2017-11-05 06:56:54 +01:00
LiquidFenrir
ab2ddbc2ee fix visible blank
if jumping too close to the end, the cursor won't be at the top to avoid the blank
2017-11-05 06:48:56 +01:00
LiquidFenrir
9495bf30bf make jumping put the cursor at the top row
downside: when jumping near the end, a blank is visible
2017-11-05 06:30:41 +01:00
TuxSH
a4899a1bec Remove redundant variables in Makefile 2017-11-03 19:03:17 +01:00
LiquidFenrir
882c6cf0d4 show the "main" address to distinguish between heap and code 2017-11-03 02:19:15 +01:00
LiquidFenrir
a5e18c82d1 reset scrolling when changing modes to avoid problems when the sizes dont match 2017-11-03 02:15:28 +01:00
TuxSH
22a8661fe1 Always patch FS and P9, remove SM service checks 2017-11-02 21:52:14 +01:00
TuxSH
8258a98647 Integrate 3ds_pxi and 3ds_sm 2017-11-02 15:11:55 +01:00
LiquidFenrir
76dde0e6db Add ram viewer/editor (#877)
Huge thanks to @LiquidFenrir
2017-10-24 18:35:15 +02:00
Ian Burgwin
1a39cb27e4 fix discord invite link 2017-10-14 10:10:03 -07:00
Aurora Wright
95d2d0a6bd Update makefile 2017-10-12 20:56:47 +02:00
Aurora Wright
98d4345858 Remove unneeded check 2017-10-07 23:04:55 +02:00
Aurora Wright
1e4431dcc9 Fix ARM9 exceptions displaying ARM11-specific info 2017-10-07 20:59:21 +02:00
Aurora Wright
348b175994 Fix some fault statuses overlapping to a new line 2017-10-05 19:55:21 +02:00
Aurora Wright
76f057dafb Remove friends patch as it's useless 2017-10-05 18:45:06 +02:00
Aurora Wright
188400c5a9 Use ctrulib functions for mcu/battery level 2017-10-05 18:41:11 +02:00
Aurora
a74d9c6d3e Merge pull request #878 from Margen67/master
Update README.md
2017-10-03 01:19:26 +02:00
Margen67
f8bcfb2f58 Update README.md
Add armips buildbot link.
Other minor changes.
2017-09-26 14:44:14 -07:00
TuxSH
d63fc2bc82 Fix latest commit 2017-09-24 19:31:38 +02:00
TuxSH
8e31784996 Fix thumb breakpoint handling 2017-09-24 17:58:23 +02:00
Aurora Wright
f27cdb4543 Also fix RBGA4 (untested) 2017-09-23 22:34:28 +02:00
Aurora
a39adc8ac1 Merge pull request #869 from Streetwalrus/pxfmt
Fix RGB5_A1 conversion
2017-09-23 22:27:24 +02:00
Dan Elkouby
97bef66018 Fix RGB5_A1 conversion 2017-09-23 15:01:11 +03:00
Aurora Wright
bb5518b0f6 Merge branch 'master' of https://github.com/AuroraWright/Luma3DS 2017-09-22 18:05:10 +02:00
Aurora Wright
ac73a96ce2 Set default firmSource for CTRNAND mounting in crypto.c, move CTRNAND mounting for SD mode to firm.c 2017-09-22 18:05:03 +02:00
Ian Burgwin
7075004e58 Merge pull request #866 from Margen67/master
Update ISSUE_TEMPLATE.md
2017-09-21 14:04:38 -07:00
Margen67
ddf8ba5116 Update ISSUE_TEMPLATE.md 2017-09-21 14:02:09 -07:00
Aurora Wright
f46773ba64 Stub isTitleAllowed 2017-09-20 01:36:02 +02:00
Aurora Wright
f67d333457 Update fpdver 2017-09-19 14:46:42 +02:00
Aurora Wright
4116c1e00f Update FIRM loading magic, only deinit LCDs if they are inited, fix ntrboot naming 2017-09-07 05:24:43 +02:00
Aurora Wright
bc1aa15dd7 Add more checks, make the emuNAND SD check only occur when emuNAND is being booted 2017-08-28 14:46:18 +02:00
Aurora Wright
ecd27f7eaa Fix diskio indentation 2017-08-28 02:54:56 +02:00
Aurora Wright
618ce671ac Fix previous commit, deinit screens on ARM9 exception, add check for write protect switch on writing operations 2017-08-28 02:43:12 +02:00
Hikari-chin
2a6a655804 Error if emuNAND is booted while the SD card is write protected 2017-08-27 16:20:17 -04:00
Aurora Wright
33436ae2a6 Fix derp with previous commit 2017-08-27 16:24:04 +02:00
Aurora Wright
9f2b66ac51 Merge branch 'master' of https://github.com/AuroraWright/Luma3DS 2017-08-27 16:20:52 +02:00
Aurora Wright
df93e4797e Refactor boot mode/firmlaunch detection, fix firmlaunch from FIRM boots 2017-08-27 16:20:41 +02:00
Aurora Wright
538d1dec77 Minor style stuff 2017-08-21 19:33:31 +02:00
TuxSH
2492c8273a Fix exception display 2017-08-21 19:26:17 +02:00
Aurora Wright
d358df48a6 Wait for ntrboot buttons not to be held 2017-08-20 18:23:50 +02:00
Aurora Wright
f619dafff1 Added displaying boot source and loader on the bottom screen in the config 2017-08-20 17:00:47 +02:00
Aurora Wright
0419fc4e30 Reinstate ntrboot display in config 2017-08-20 16:16:20 +02:00
Aurora Wright
13317b9548 Change ntrboot behavior, turn Luma into a chainloader when used as ntrboot FIRM as it can not be functional, disable FIRM protection when ran from ntrboot B9S 2017-08-20 16:08:54 +02:00
Aurora Wright
18db70a669 Minor style stuff 2017-08-19 02:54:38 +02:00
TuxSH
f79923814d Detect NTRCARD and FIRM1 boot sources properly...
Always display the configuration menu if booted from NTRCARD (because it's painful to get to otherwise -- even if b9s has a 2s delay), with the mention "Booted from NTRCARD" in the title.
2017-08-19 01:40:55 +02:00
Aurora Wright
c92de03a5f Always erase exception dump in memory 2017-08-17 17:38:42 +02:00
Aurora Wright
3f356da879 Merge branch 'master' of https://github.com/AuroraWright/Luma3DS 2017-08-17 17:33:37 +02:00
Aurora Wright
9efac01c86 Fix derp 2017-08-17 17:33:18 +02:00
TuxSH
ca2622af7c Fix #778 2017-08-16 23:46:36 +02:00
Aurora Wright
aa8e0bda8c Update FatFs to R0.13 2017-08-16 19:37:39 +02:00
TuxSH
c79f11ee99 Change exception dump parser directory structure 2017-08-16 19:23:04 +02:00
Aurora Wright
04d0770b90 Add missing info for data aborts in the exception parser and turn it into a pip module 2017-08-16 18:59:12 +02:00
Aurora Wright
fbf8a1b6d9 Minor code syntax stuff 2017-08-16 18:04:22 +02:00
Aurora Wright
a3cb6a622d Merge https://github.com/AuroraWright/Luma3DS/pull/793 , clarify the exception dumps' paths 2017-08-16 16:55:07 +02:00
Aurora Wright
0790a3ceb3 Merge branch 'master' of https://github.com/AuroraWright/Luma3DS 2017-08-16 15:50:06 +02:00
Aurora Wright
4fa12f90fc Fix derp 2017-08-16 15:49:57 +02:00
TuxSH
d5d56e7634 Merge pull request #790 from WinterMute/windows-path-fix
Don't fix already transformed $DEVKITARM variable
2017-08-15 15:20:27 +02:00
TuxSH
a964089df4 Merge pull request #792 from Nanquitas/master
Exceptions: display more infos on screen (status, far, access type)
2017-08-15 15:20:17 +02:00
Dave Murphy
5fd5b4da89 Don't fix already transformed $DEVKITARM variable 2017-08-15 14:15:34 +01:00
Hikari-chin
322a7050aa Fix #791 2017-08-15 09:01:48 -04:00
Nanquitas
b7f4ac02c8 Exceptions: display more infos on screen (status, far, access type) 2017-08-15 14:09:14 +02:00
TuxSH
009f61a8b6 Merge pull request #787 from Nanquitas/master
exception_parser.py: display the fault status source
2017-08-15 02:44:18 +02:00
Nanquitas
26d0cafb39 exception_parser.py: display the fault status source 2017-08-15 00:51:20 +02:00
TuxSH
bd1d4a77fe Merge pull request #783 from Nanquitas/patch-1
Watchpoints: fix read DSCR to enable MonitorMode
2017-08-14 19:04:15 +02:00
Nanquitas
f235bc83a8 Watchpoints: fix read DSCR to enable MonitorMode 2017-08-14 16:10:50 +02:00
Aurora Wright
9c6b540905 Do not hardcode FBs in ARM11, do not set FBs twice on screen init 2017-08-13 17:36:31 +02:00
TuxSH
d2e911a58e Merge pull request #781 from profi200/master
Revert 9273a88d and make it not freeze the GPU/LCD hardware.
2017-08-13 16:00:45 +02:00
TuxSH
9344a7b434 Fix default FB addresses 2017-08-13 16:00:35 +02:00
profi200
cd194fa5b2 Revert 9273a88d and make it not freeze the GPU/LCD hardware. 2017-08-13 14:50:14 +02:00
Aurora Wright
49c0ab65df Check r0 and r1 too for firm0 detection 2017-08-11 23:54:28 +02:00
Aurora Wright
8f9c1305e4 Reinstate unsupported loader error 2017-08-11 23:48:32 +02:00
TuxSH
d4193ec11d Attempt to detect booting from firm 2017-08-11 23:33:21 +02:00
TuxSH
6b9b0472bc Merge pull request #775 from LiquidFenrir/nwmcheck
Add a warning when nwm isn't running
2017-08-11 23:00:07 +02:00
LiquidFenrir
7e74258363 check if nwm is running to fix https://github.com/AuroraWright/Luma3DS/issues/774 2017-08-11 04:29:38 +02:00
Aurora Wright
f6483ec602 Merge branch 'master' of https://github.com/AuroraWright/Luma3DS 2017-08-07 21:20:18 +02:00
Aurora Wright
36c1da1d61 Add mention of exheaders in the Enable game patching description 2017-08-07 21:20:08 +02:00
Stary 2001
6bcb1f8679 Merge pull request #763 from Streetwalrus/ir-title
Fix input redirection title index in the menu
2017-08-06 22:15:21 +01:00
Dan Elkouby
62932a9639 Fix input redirection title index in the menu
This option is the third, not the fourth, and toggling it will override
the "save settings" option's title instead.
2017-08-06 23:56:00 +03:00
Hikari-chin
a4629e4b65 Cleaned up and rearranged the Rosalina menu in preparation for future features 2017-08-01 17:38:48 +02:00
Aurora Wright
a0c2b43b34 Implement loading of exheaders from SD/CTRNAND (must be called luma/titles/TITLEID/exheader.bin), thanks to @HiddenRambler! 2017-08-01 17:38:23 +02:00
TuxSH
3907c46980 Follow ARM's documentation on hw watchpoints to the letter 2017-07-20 00:56:08 +02:00
TuxSH
7e7ab124a3 Log "logged" errdisp messages in /luma/errdisp.txt, fixes #707 2017-07-19 00:59:47 +02:00
TuxSH
cfc6cf24bf Some kext refactoring 2017-07-16 18:58:20 +02:00
TuxSH
46e9cb6b23 Fix fallthrough bug 2017-07-16 13:29:02 +02:00
TuxSH
ba14efe1f4 Suppress future -Wimplicit-fallthrough=3 warnings 2017-07-15 00:41:42 +02:00
TuxSH
3d8f62d38f Fix MaxCpuTime for 3dsx 2017-07-09 22:14:00 +02:00
Hikari-chin
3edaf0af64 Whoops 2017-07-09 14:36:06 -04:00
Aurora Wright
9273a88db7 It seems FB setup needs to be done first 2017-07-09 19:21:12 +02:00
Aurora Wright
37ba2c15de Reinstate framebuffer setup on initScreens to allow old Luma to be chainloaded if FB address changes in b9s/new Luma, remove useless clearScreens for the alternate FBs after the first init 2017-07-09 19:06:42 +02:00
Aurora Wright
557f2057f7 Fix spacing 2017-07-06 18:09:18 +02:00
Aurora Wright
6b5cc93780 Merge branch 'master' of https://github.com/AuroraWright/Luma3DS 2017-07-06 17:29:43 +02:00
Aurora Wright
9760191af8 Fix conflict between emunand selection and payload booting when "Autoboot EmuNAND" is checked, you now need to press L + DPad to boot payloads if that option is checked 2017-07-06 17:29:38 +02:00
TuxSH
8845e4dd20 Merge pull request #704 from Hikari-chin/master
LED toggle switch in Rosalina's misc menu + updated README
2017-07-05 19:26:56 +02:00
Yuuki Hikari
8cf823f548 Update README.md 2017-07-05 02:13:03 -04:00
Hikari-chin
2538769f3a Added LED toggling from the Rosalina misc. menu 2017-07-04 23:50:40 -04:00
Aurora Wright
89fca38807 Merge master into local branch 2017-07-05 01:37:36 +02:00
Aurora Wright
dcc0eed69c Fix LayeredFS for games like Pokemon Art Academy which mistakenly use two forward slashes after the mountpoint 2017-07-05 01:31:04 +02:00
Yuuki Hikari
817475257e Merge pull request #700 from LiquidFenrir/wifi-toggle
Add wireless toggling in rosalina
2017-07-04 15:09:16 -04:00
LiquidFenrir
f2861058ba add wireless toggling in rosalina
https://github.com/AuroraWright/Luma3DS/issues/619#issuecomment-309239178

ligne 353: CFG11_WIFICNT, nothing includes it in rosalina so I hardcoded it here
ligne 363: could also use svc 0x5A (SetWifiEnabled) but not sure how
2017-07-04 18:35:55 +02:00
TuxSH
5d2a7315d5 Fix SetWifiEnabled 2017-07-03 19:28:34 +02:00
TuxSH
1520ab7555 Update ISSUE_TEMPLATE.md
7.1 => 8.1
2017-07-02 22:52:49 +02:00
Aurora Wright
d4d0fbd73b Re-add dir_build variable 2017-07-02 00:46:57 +02:00
Aurora Wright
ddb8e98e95 Merge branch 'master' of https://github.com/AuroraWright/Luma3DS 2017-07-02 00:44:29 +02:00
Aurora Wright
fd69b4169f Use GNU/BSD agnostic syntax instead of detecting the OS (thanks @smartperson) 2017-07-02 00:44:14 +02:00
TuxSH
b48e0b5c5b Update ISSUE_TEMPLATE.md 2017-06-30 23:52:44 +02:00
TuxSH
31e2243c5c Update description for "enable game patching" 2017-06-28 21:59:57 +02:00
Aurora Wright
da0ee2e442 Fix external 3.x and 4.x FIRMs, fix 1.x and 2.x booting on dev units 2017-06-28 20:28:14 +02:00
Aurora Wright
b88dc9ac6a Only check in .text 2017-06-28 18:14:05 +02:00
Aurora Wright
9f78d7f62b Add region-free manuals patch 2017-06-28 17:37:12 +02:00
Aurora Wright
e67c6ed3ee Change pattern 2017-06-26 23:42:41 +02:00
Aurora Wright
2e111ca91b Revert "Revert "Merge pull request #662 from MerryMage/dsp-sig""
This reverts commit 62d51fd99d.
2017-06-26 23:39:28 +02:00
Aurora Wright
62d51fd99d Revert "Merge pull request #662 from MerryMage/dsp-sig"
This reverts commit a9289b1f21, reversing
changes made to d42e938232.
2017-06-26 22:06:10 +02:00
TuxSH
a9289b1f21 Merge pull request #662 from MerryMage/dsp-sig
Add a patch to disable DSP firmware signature check
2017-06-26 20:51:16 +02:00
Aurora Wright
d42e938232 Restore 7.1 max module size for NATIVE_FIRM 2017-06-26 19:03:57 +02:00
MerryMage
3d3dcb1f28 Add DSP signature check patch 2017-06-26 17:34:43 +01:00
Aurora Wright
82143212ce Remove the need for Homebrew and GNU tools on macOS 2017-06-26 18:32:33 +02:00
TuxSH
7246a2664e Move section0 to second quarter of VRAM 2017-06-26 17:41:40 +02:00
Aurora Wright
1291f2520a Fix derp 2017-06-26 17:11:00 +02:00
TuxSH
042ecf5343 Fix write-only hw watchpoint handling 2017-06-26 16:57:25 +02:00
Aurora Wright
6e54dcc24c Add macOS building support (you need to install coreutils and gnu-sed with homebrew) 2017-06-26 16:29:04 +02:00
TuxSH
91378ef3c1 Fix menu display bugs 2017-06-25 00:14:07 +02:00
Aurora Wright
0377cbd2b4 Merge branch 'master' of https://github.com/AuroraWright/Luma3DS 2017-06-22 15:49:31 +02:00
Aurora Wright
786ecf4fe4 Remove some configbit math 2017-06-22 15:49:23 +02:00
TuxSH
0fbdee313f Merge branch 'master' of github.com:AuroraWright/Luma3DS 2017-06-20 21:24:52 +02:00
Aurora Wright
9b8e2b933d Add missing checks in getFreeK9Space 2017-06-20 19:56:34 +02:00
TuxSH
cc64ef9670 Take fb stride into account 2017-06-20 18:29:30 +02:00
TuxSH
31ff6a1da8 Clarify option 2017-06-20 17:39:11 +02:00
TuxSH
94532e9cea Halve the time necessary to take a screenshot 2017-06-20 16:14:36 +02:00
Aurora Wright
3f93bc5988 Support 3.x+ EmuNANDs and 3.x SysNANDs (partially), external FIRMs coming soonŧ 2017-06-19 18:13:59 +02:00
TuxSH
39ca23d609 Add qGetTLSAddr 2017-06-19 16:04:19 +02:00
TuxSH
47a9c1b576 Fix FS patch for 4.x 2017-06-19 15:34:51 +02:00
TuxSH
d819cfd58f Remove useless files 2017-06-19 15:21:15 +02:00
TuxSH
17828273a5 Revamp config format, add saving of Rosalina opt.
(menu combo & 3dsx title ID)
2017-06-18 22:31:21 +02:00
TuxSH
2363817265 Fix grey strides issue (maybe) 2017-06-17 01:52:08 +02:00
TuxSH
b31018ab17 Lower the priority of the Rosalina menu 2017-06-17 00:15:36 +02:00
TuxSH
c610ec3319 Virtually full support for 4.x sysNAND
(see also: previous commit)
2017-06-16 22:37:04 +02:00
TuxSH
b71dedccfc Full support for fw >= 6.x (tested)
Virtually full support for 5.x except that svcUnmapProcessMemoryEx will be forwarded to svcUnmapProcessMemory (both are equivalent for up to 64MB chunks)
2017-06-16 04:21:48 +02:00
TuxSH
9ccfacd06d Display IP in menus when either gdb/inputredir is enabled 2017-06-15 17:38:45 +02:00
TuxSH
12b561a27d Remove unused variables 2017-06-15 01:57:57 +02:00
TuxSH
cc41003e1c Fix exheader.h 2017-06-15 01:53:34 +02:00
TuxSH
3d534c9a81 Unschedule threads properly...
...instead of using a shitty yield when opening the Rosalina menu
2017-06-14 19:35:03 +02:00
TuxSH
24de7c5272 Fix indentation of gdb.c 2017-06-14 10:04:09 +02:00
TuxSH
a1b2ea2c5b Fix firmlaunch payload path bug 2017-06-14 02:05:32 +02:00
TuxSH
19d68b6df4 Adjust config mem values 2017-06-14 01:29:55 +02:00
TuxSH
2ab41dbd01 Fix firmlaunch bug 2017-06-13 23:08:32 +02:00
TuxSH
da30c0b0f0 Fix dfsr being displayed instead of fpexc 2017-06-13 02:53:53 +02:00
TuxSH
005684d865 Fix loader bugs
new-hbmenu now works with H&S, etc.
2017-06-13 02:37:27 +02:00
TuxSH
da1eff82ba Remove debugging line 2017-06-13 02:29:01 +02:00
TuxSH
a17311c955 Merge branch 'memregion-test' 2017-06-13 02:28:38 +02:00
TuxSH
e1d0602f25 Move the kext outside Rosalina
- Stability (tm)
- Boots 1s faster on N3DS
- (∩ ͡° ͜ʖ ͡°)⊃━☆゚
2017-06-13 02:00:41 +02:00
TuxSH
2ff9718510 Merge pull request #595 from Hikari-chin/master
Fix #593
2017-06-12 18:00:22 +02:00
Hikari-chin
33af9cfe09 Fix #593 2017-06-12 01:45:38 +00:00
Aurora
79709a7ae7 Merge pull request #594 from Margen67/master
Update issue template
2017-06-11 21:01:48 +02:00
Margen67
a796a70d01 Update issue template 2017-06-11 12:00:06 -07:00
TuxSH
53e2ef24f1 Refactor pattern for ir hook 2017-06-11 17:16:14 +01:00
Ezekiel Bethel
c0059c83ac inputredirection hook in ir:user cpp emulation => c-stick works in games now, also hook refactoring 2017-06-11 17:16:13 +01:00
Ezekiel Bethel
37eb21d297 poweroff/reboot for Rosalina misc. menu 2017-06-11 17:06:43 +01:00
Aurora Wright
52a18831a7 Minor style changes (2) 2017-06-10 03:06:16 +02:00
Aurora Wright
0d7cca7b20 Minor style changes 2017-06-10 02:55:55 +02:00
Aurora Wright
bea73c51ae Merge branch 'master' of https://github.com/AuroraWright/Luma3DS 2017-06-10 02:39:08 +02:00
Aurora Wright
0c68750056 Refactor payload loading, fix messy externs, add safety checks to Nintendo FIRMs, fix some Nintendo FIRMs not being loaded as payloads 2017-06-10 02:39:00 +02:00
TuxSH
ae8ea7da16 Revert PR due to breakage for a totally unrelated reason
(will be added back later)
2017-06-10 01:39:11 +02:00
TuxSH
69762c5dce Revert "Attempt fixing svcConnectToPortInitHook.s again"
This reverts commit 901d4992c0.
2017-06-09 20:48:01 +02:00
TuxSH
901d4992c0 Attempt fixing svcConnectToPortInitHook.s again 2017-06-09 18:10:02 +02:00
Aurora Wright
4d47d891d1 Fix max module size check, static-ify more strings 2017-06-09 17:29:26 +02:00
TuxSH
a7046909ec Use static const when appropriate 2017-06-09 14:26:51 +02:00
Aurora Wright
4bc95979de Revert #949d219c726e41cca84c873e7e200be14af13f63 (breaks building on *nix) 2017-06-09 13:44:04 +02:00
TuxSH
949d219c72 lolwut this fixes building on WSL
maybe memsearch is flasky on unaligned patterns, dunno
2017-06-09 05:00:38 +02:00
TuxSH
9a3d9aed30 Always enable ARM9 exceptions, update .gitignore 2017-06-09 02:31:14 +02:00
TuxSH
4d99143da0 Merge pull request #561 from SciresM/master
Add config option to disable exception vectors.
2017-06-09 00:17:14 +02:00
TuxSH
461035b212 Fix bug(s), refactor svcConnectToPortInitHook.s, cleanup 2017-06-08 21:35:41 +02:00
Michael Scire
0694ea8367 Add config option to disable exception vectors. 2017-06-07 17:48:30 -07:00
TuxSH
427a05997d Revert "Refactor fatalExceptionHandlers.s a bit"
This reverts commit 84d736c2eb.
2017-06-08 02:02:49 +02:00
TuxSH
84d736c2eb Refactor fatalExceptionHandlers.s a bit 2017-06-07 23:58:29 +02:00
TuxSH
a16d1ebe33 Refactor k11 main hook
Much less error-prone now.
2017-06-07 22:13:05 +02:00
Aurora Wright
43f3c84316 Merge branch 'master' of https://github.com/AuroraWright/Luma3DS 2017-06-07 19:16:13 +02:00
Aurora Wright
44cafe3f46 Fix mismerges 2017-06-07 19:15:51 +02:00
TuxSH
76d7a035bd Fix country/state id spoofing 2017-06-07 01:06:39 +02:00
TuxSH
a5b638ae7b Fix uninitialized variable bugs 2017-06-06 21:04:13 +02:00
TuxSH
174089e4f3 Fix langemu bugs 2017-06-06 19:37:16 +02:00
TuxSH
4d219813fe Merge pull request #519 from sora10pls/master
Reference release notes in README.md
2017-06-06 02:52:32 +02:00
Aurora Wright
a798f453d2 Update gitignore 2017-06-06 02:17:58 +02:00
Aurora Wright
6ec21611c0 Merge branch 'master' of https://github.com/AuroraWright/Luma3DS 2017-06-06 02:13:02 +02:00
Aurora Wright
31f4419eec Refactor screen functions, completely fix config not saving bug 2017-06-06 02:12:18 +02:00
Aurora Wright
60d136f9b5 Fix #491 2017-06-06 01:22:17 +02:00
TuxSH
0ba7f9dba0 Fix chainloader 2017-06-05 21:24:18 +02:00
TuxSH
0ac6db006a Work around a GDB bug (w/r/t packet size) 2017-06-05 21:23:17 +02:00
TuxSH
26dd61e4e6 Fix (work around) Nintendo own HM bug, GG Ninty 2017-06-05 20:28:44 +02:00
TuxSH
dda11206db Fix bug in fatalExceptionHandlers.s 2017-06-05 19:32:37 +02:00
Matt
e8565d30a9 Reference release notes in README.md 2017-06-05 10:15:49 -04:00
TuxSH
2d4c103854 Merge pull request #510 from T3CHNOLOG1C/master
fix typo in readme
2017-06-05 14:46:21 +02:00
T3CHNOLOG1C
d0b9e36908 fix typo in readme 2017-06-05 06:58:19 -04:00
392 changed files with 42573 additions and 11064 deletions

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
*.xml text eol=lf

View File

@@ -1,12 +1,18 @@
---
name: Bug report
about: Use this to report bugs you encounter with Luma3DS. Make sure you upload the crash dumps if Luma3DS crashes.
---
<!--
-- THIS IS NOT A SUPPORT FORUM! For support go here:
-- Luma3DS GBATemp thread: https://gbatemp.net/threads/luma3ds-noob-proof-3ds-custom-firmware.411110/
-- Nintendo Hacking: https://discord.gg/MjzatM8y
-- Nintendo Homebrew: https://discord.gg/MjzatM8
--
-- Rosalina feature requests go here: https://github.com/AuroraWright/Luma3DS/issues/752
--
-- Also check the Wiki (https://github.com/AuroraWright/Luma3DS/wiki) before making an issue.
--
-- For GBA/DSiWare/DS/AGB_FIRM/TWL_FIRM problems: https://3ds.guide/troubleshooting
-- If you're using an emu/redNAND anything related to that must also be installed to sysNAND.
-- For GBA/DSiWare/DS/AGB_FIRM/TWL_FIRM problems: use https://github.com/MechanicalDragon0687/TWLFix-CFW and update your system.
-- If you're using an emu/redNAND try installing anything on it to sysNAND.
-- Please make sure to read "Enable game patching" https://github.com/AuroraWright/Luma3DS/wiki/Options-and-usage before posting any issues about the "Enable game patching" option(s).
--
-- Luma updaters that don't support Boot9Strap/Sighax won't work.
@@ -19,7 +25,8 @@
**SysNAND version (+emu/redNAND version if applicable):**
[e.g. 11.4.0-37U SysNAND, 11.4.0-37J EmuNAND]
[e.g. 11.13.0-45U SysNAND, 11.13.0-45E EmuNAND]
<!--You can check which version you're on in System Settings. It will be on the bottom right of the top screen.-->
**Entrypoint (How/what you're using to boot Luma3DS):**
@@ -27,18 +34,19 @@
**Luma3DS version:**
[e.g. 7.1 stable or if using nightly/hourly specify the commit like this https://github.com/AuroraWright/Luma3DS/commit/9570e6cbeca53128433abbf5e3473cb8a07fe69e]
<!--You can check which version you're on in System Settings. It will be on the bottom right of the top screen.-->
[e.g. v10.1.3 stable or if using non-releases specify the commit like this https://github.com/AuroraWright/Luma3DS/commit/0543c208fd154e6326ea5da8cbf66ffcbdef010c]
**Luma3DS configuration/options:**
Default EmuNAND: ( )
<!--This option is only available if there's at least one EmuNAND.-->
Screen brightness: ( )
Splash: ( )
Splash duration: ( )
PIN lock: ( )
New 3DS CPU: ( )
@@ -47,14 +55,14 @@ New 3DS CPU: ( )
--
Autoboot EmuNAND: ( )
<!--This option is only available if there's at least one EmuNAND.-->
Use EmuNAND FIRM if booting with R: ( )
<!--This option is only available if there's at least one EmuNAND.-->
Enable loading external FIRMs and modules: ( )
<!--Firmware (.bin) files are not required by Luma, or NTR CFW anymore.
-- If you're having issues with this option enabled try deleting them from the luma folder on the root of the SD card and disabling this option.-->
Use custom path: ( )
-- If you're having issues with this option enabled try deleting them from the luma folder on the root of the SD card or /rw/luma on CTRNAND and disabling this option.-->
Enable game patching: ( )
@@ -62,10 +70,12 @@ Show NAND or user string in System Settings: ( )
Show GBA boot screen in patched AGB_FIRM: ( )
Patch ARM9 access: ( )
Patch Arm9 access: ( )
Set developer UNITINFO: ( )
Disable Arm11 exception handlers: ( )
--
@@ -84,6 +94,6 @@ Set developer UNITINFO: ( )
**Dump file:**
<!--If the issue leads to a crash you can generate a crash dump by checking the "Enable exception handlers" option.
<!--If the issue leads to a crash you must uncheck the "Disable Arm11 exception handlers" option.
-- The error message will tell you where the dump is.
-- Zip the dmp file and drag & drop it below.-->

10
.gitignore vendored
View File

@@ -1,18 +1,20 @@
.vscode
out
build
arm11/build
sysmodules/loader/build
sysmodules/rosalina/build
chainloader/build
rosalina/build
exceptions/arm9/build
exceptions/arm11/build
.vscode
.vscode/**
*.bin
*.firm
*.o
*.d
*.elf
*.cxi
*.bmp
.DS_Store
*.dmp
.project
.cproject
.settings

143
Makefile
View File

@@ -1,140 +1,29 @@
rwildcard = $(foreach d, $(wildcard $1*), $(filter $(subst *, %, $2), $d) $(call rwildcard, $d/, $2))
ifeq ($(strip $(DEVKITARM)),)
$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
endif
ifneq ($(strip $(shell firmtool -v 2>&1 | grep usage)),)
$(error "Please install firmtool v1.1 or greater")
endif
include $(DEVKITARM)/base_tools
NAME := $(notdir $(CURDIR))
REVISION := $(shell git describe --tags --match v[0-9]* --abbrev=8 | sed 's/-[0-9]*-g/-/')
name := Luma3DS
revision := $(shell git describe --tags --match v[0-9]* --abbrev=8 | sed 's/-[0-9]*-g/-/i')
commit := $(shell git rev-parse --short=8 HEAD)
SUBFOLDERS := sysmodules arm11 arm9 k11_extension
ifeq ($(strip $(revision)),)
revision := v0.0.0-0
endif
.PHONY: all release clean $(SUBFOLDERS)
ifeq ($(strip $(commit)),)
commit := 0
endif
all: boot.firm
dir_source := source
dir_patches := patches
dir_arm11 := arm11
dir_chainloader := chainloader
dir_exceptions := exceptions
dir_arm9_exceptions := $(dir_exceptions)/arm9
dir_sysmodules := sysmodules
dir_loader := $(dir_sysmodules)/loader
dir_rosalina := $(dir_sysmodules)/rosalina
dir_build := build
dir_out := out
release: $(NAME)$(REVISION).zip
ASFLAGS := -mcpu=arm946e-s
CFLAGS := -Wall -Wextra $(ASFLAGS) -fno-builtin -std=c11 -Wno-main -O2 -flto -ffast-math
LDFLAGS := -nostartfiles -Wl,--nmagic
objects = $(patsubst $(dir_source)/%.s, $(dir_build)/%.o, \
$(patsubst $(dir_source)/%.c, $(dir_build)/%.o, \
$(call rwildcard, $(dir_source), *.s *.c)))
bundled = $(dir_build)/reboot.bin.o $(dir_build)/emunand.bin.o $(dir_build)/mmuHook.bin.o $(dir_build)/k11MainHook.bin.o $(dir_build)/svcConnectToPortInitHook.bin.o $(dir_build)/svcCustomBackdoor.bin.o\
$(dir_build)/chainloader.bin.o $(dir_build)/arm9_exceptions.bin.o
modules = $(dir_build)/loader.cxi $(dir_build)/rosalina.cxi
define bin2o
bin2s $< | $(AS) -o $(@)
endef
.PHONY: all
all: firm
.PHONY: release
release: $(dir_out)/$(name)$(revision).7z
.PHONY: firm
firm: $(dir_out)/boot.firm
.PHONY: clean
clean:
@$(MAKE) -C $(dir_arm11) clean
@$(MAKE) -C $(dir_chainloader) clean
@$(MAKE) -C $(dir_arm9_exceptions) clean
@$(MAKE) -C $(dir_loader) clean
@$(MAKE) -C $(dir_rosalina) clean
@rm -rf $(dir_out) $(dir_build)
@$(foreach dir, $(SUBFOLDERS), $(MAKE) -C $(dir) clean &&) true
@rm -rf *.firm *.zip
.PRECIOUS: $(dir_build)/%.bin
$(NAME)$(REVISION).zip: boot.firm exception_dump_parser
@zip -r $@ $^ -x "*.DS_Store*" "*__MACOSX*"
.PHONY: $(dir_arm11)
.PHONY: $(dir_chainloader)
.PHONY: $(dir_arm9_exceptions)
.PHONY: $(dir_loader)
.PHONY: $(dir_rosalina)
boot.firm: $(SUBFOLDERS)
@firmtool build $@ -D sysmodules/sysmodules.bin arm11/arm11.elf arm9/arm9.elf k11_extension/k11_extension.elf \
-A 0x18180000 -C XDMA XDMA NDMA XDMA
@echo built... $(notdir $@)
$(dir_out)/$(name)$(revision).7z: all
@mkdir -p "$(@D)"
@7z a -mx $@ ./$(@D)/* ./$(dir_exceptions)/exception_dump_parser.py
$(dir_out)/boot.firm: $(dir_build)/modules.bin $(dir_build)/arm11.elf $(dir_build)/main.elf
@mkdir -p "$(@D)"
@firmtool build $@ -D $^ -A 0x1FF60000 -C XDMA XDMA NDMA
$(dir_build)/modules.bin: $(modules)
@mkdir -p "$(@D)"
cat $^ > $@
$(dir_build)/arm11.elf: $(dir_arm11)
@mkdir -p "$(@D)"
@$(MAKE) -C $<
$(dir_build)/main.elf: $(bundled) $(objects)
$(LINK.o) -T linker.ld $(OUTPUT_OPTION) $^
$(dir_build)/loader.cxi: $(dir_loader)
@mkdir -p "$(@D)"
@$(MAKE) -C $<
$(dir_build)/rosalina.cxi: $(dir_rosalina)
@mkdir -p "$(@D)"
@$(MAKE) -C $<
$(dir_build)/%.bin.o: $(dir_build)/%.bin
@$(bin2o)
$(dir_build)/chainloader.bin: $(dir_chainloader)
@mkdir -p "$(@D)"
@$(MAKE) -C $<
$(dir_build)/arm9_exceptions.bin: $(dir_arm9_exceptions)
@mkdir -p "$(@D)"
@$(MAKE) -C $<
$(dir_build)/%.bin: $(dir_patches)/%.s
@mkdir -p "$(@D)"
@armips $<
$(dir_build)/memory.o $(dir_build)/strings.o: CFLAGS += -O3
$(dir_build)/config.o: CFLAGS += -DCONFIG_TITLE="\"$(name) $(revision) configuration\""
$(dir_build)/patches.o: CFLAGS += -DREVISION=\"$(revision)\" -DCOMMIT_HASH="0x$(commit)"
$(dir_build)/firm.o: $(dir_build)/modules.bin
$(dir_build)/firm.o: CFLAGS += -DLUMA_SECTION0_SIZE="$(shell du -b $(dir_build)/modules.bin | cut -f1)"
$(dir_build)/bundled.h: $(bundled)
@$(foreach f, $(bundled),\
echo "extern const u8" `(echo $(basename $(notdir $(f))) | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`"[];" >> $@;\
echo "extern const u32" `(echo $(basename $(notdir $(f)))| sed -e 's/^\([0-9]\)/_\1/' | tr . _)`_size";" >> $@;\
)
$(dir_build)/%.o: $(dir_source)/%.c $(dir_build)/bundled.h
@mkdir -p "$(@D)"
$(COMPILE.c) $(OUTPUT_OPTION) $<
$(dir_build)/%.o: $(dir_source)/%.s
@mkdir -p "$(@D)"
$(COMPILE.s) $(OUTPUT_OPTION) $<
$(SUBFOLDERS):
@$(MAKE) -C $@ all

View File

@@ -1,40 +1,74 @@
# Luma3DS
*Noob-proof (N)3DS "Custom Firmware"*
# Luma3DS-3GX Plugin Edition
*Noob-proof (N)3DS "Custom Firmware", with 3GX plugins support*
## What it is
### 3GX Plugin Edition
This edition of **Luma3DS** allows the loading of **.3GX plugins** in Luma3DS, which are otherwise officially unsupported.
**Luma3DS** is a program to patch the system software of (New) Nintendo 3DS handheld consoles "on the fly", adding features (such as per-game language settings and debugging capabilities for developers) and removing restrictions enforced by Nintendo (such as the region lock).
It also allows you to run unauthorized ("homebrew") content by removing signature checks.
To use it, you will need a console capable of running homebrew software on the ARM9 processor. We recommend [Plailect's guide](https://3ds.guide/) for details on how to get your system ready.
Since Luma3DS v8.0, Luma3DS has its own in-game menu, triggerable by `L+Start+Select` (see the release notes).
#
### How to install this Edition
1. download the latest `boot.firm` from [the releases page](https://github.com/mind-overflow/Luma3DS-3GX/releases/latest)
2. put the downloaded `boot.firm` file in the `root` directory of your SD card (`sd:/boot.firm`), overwriting the official Luma3DS `boot.firm`.
3. (re)boot your 3DS, and when prompted, enable:
- "Enable game patching"
- "Show NAND or user string in System Settings"
4. press `START` and let your 3DS boot.
---
You successfully installed the 3GX Plugin Loader! Now, proceed to the next step to learn how to install and enable 3GX plugins.
## Compiling
#
### How to install 3GX plugins
Plugins have to be installed in the `sd:/luma/plugins` folder.
Usually, you need to put your specific plugin in the `<TITLEID>` subdirectory, eg: `sd:/luma/plugins/<TITLEID>/<filename>.3gx`.
However, a `default.3gx` plugin can also be placed in the main `sd:/luma/plugins` directory: `sd:/luma/plugins/default.3gx`.
First you need to clone the repository with: `git clone https://github.com/AuroraWright/Luma3DS.git`
To compile, you'll need [armips](https://github.com/Kingcom/armips) and a build of a recent commit of [makerom](https://github.com/profi200/Project_CTR) added to your PATH. You'll also need to install [firmtool](https://github.com/TuxSH/firmtool), its README contains installation instructions.
For now, you'll also need to update your [libctru](https://github.com/smealum/ctrulib) install, building from the latest commit.
For your convenience, here are [Windows](http://www91.zippyshare.com/v/ePGpjk9r/file.html) and [Linux](https://mega.nz/#!uQ1T1IAD!Q91O0e12LXKiaXh_YjXD3D5m8_W3FuMI-hEa6KVMRDQ) builds of armips (thanks to who compiled them!).
Finally just run `make` and everything should work!
You can find the compiled files in the `out` folder.
So:
``` yaml
sd:/luma/plugins/default.3gx # will be loaded for all games, low priority
sd:/luma/plugins/<TITLEID>/<filename>.3gx # will only be loaded for the specified title, high priority
```
---
Now you know how to install 3GX plugins! Proceed to the next step to learn how how to enable 3GX plugins.
## Setup / Usage / Features
#
### How to enable 3GX plugins
1. when booted, press `L + D-Pad Down + Select` to open the Rosalina menu.
2. Press `D-Pad Down` again until `Plugin Loader`, is selected, then press `A` and set it to `[Enabled]`.
See https://github.com/AuroraWright/Luma3DS/wiki
Done! You learned to install the 3GX Plugin loader, install 3GX Plugins and enable them. Now, simply launch the game you want to play and press `SELECT` to open up the 3GX menu!
---
## Credits
#
### Luma3DS introduction
**Luma3DS** is a program to patch the system software of (New) Nintendo (2)3DS handheld consoles "on the fly", adding features such as per-game language settings, debugging capabilities for developers, and removing restrictions enforced by Nintendo such as the region lock.
See https://github.com/AuroraWright/Luma3DS/wiki/Credits
It also allows you to run unauthorized ("homebrew") content by removing signature checks.
To use it, you will need a console capable of running homebrew software on the Arm9 processor.
---
Since v8.0, Luma3DS has its own in-game menu, triggerable by <kbd>L+Down+Select</kbd> (see the [release notes](https://github.com/LumaTeam/Luma3DS/releases/tag/v8.0)).
## Licensing
#
### Compiling
* Prerequisites
1. git
2. [makerom](https://github.com/jakcron/Project_CTR) in PATH
3. [firmtool](https://github.com/TuxSH/firmtool)
4. Up-to-date devkitARM+libctru
1. Clone the repository with `git clone https://github.com/mind-overflow/Luma3DS-3GX.git`
2. Run `make`.
This software is licensed under the terms of the GPLv3.
You can find a copy of the license in the LICENSE.txt file.
The produced `boot.firm` is meant to be copied to the root of your SD card for usage with Boot9Strap.
#
### Setup / Usage / Features
See https://github.com/LumaTeam/Luma3DS/wiki
#
### Credits
See https://github.com/LumaTeam/Luma3DS/wiki/Credits
#
### Licensing
This software is licensed under the terms of the GPLv3. You can find a copy of the license in the LICENSE.txt file.
Files in the GDB stub are instead triple-licensed as MIT or "GPLv2 or any later version", in which case it's specified in the file header.

View File

@@ -1,39 +1,147 @@
rwildcard = $(foreach d, $(wildcard $1*), $(filter $(subst *, %, $2), $d) $(call rwildcard, $d/, $2))
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITARM)),)
$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
endif
include $(DEVKITARM)/base_tools
TOPDIR ?= $(CURDIR)
include $(DEVKITARM)/base_rules
name := $(shell basename $(CURDIR))
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
#---------------------------------------------------------------------------------
TARGET := $(notdir $(CURDIR))
BUILD := build
SOURCES := source source/svc
DATA := data
INCLUDES := include include/svc
dir_source := source
dir_build := build
dir_out := ../$(dir_build)
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH := -march=armv6k -mtune=mpcore -mfloat-abi=hard -mtp=soft
DEFINES := -DARM11 -D_3DS
ASFLAGS := -mcpu=mpcore
CFLAGS := -Wall -Wextra -MMD -MP -marm $(ASFLAGS) -fno-builtin -std=c11 -Wno-main -O2 -flto -ffast-math
LDFLAGS := -nostartfiles -Wl,--nmagic
CFLAGS := -g -std=gnu11 -Wall -Wextra -Werror -O2 -mword-relocations \
-fomit-frame-pointer -ffunction-sections -fdata-sections \
-Wno-main -fno-builtin $(ARCH) $(DEFINES)
objects = $(patsubst $(dir_source)/%.s, $(dir_build)/%.o, \
$(patsubst $(dir_source)/%.c, $(dir_build)/%.o, \
$(call rwildcard, $(dir_source), *.s *.c)))
CFLAGS += $(INCLUDE)
.PHONY: all
all: $(dir_out)/$(name).elf
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions -std=gnu++11
.PHONY: clean
ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(TOPDIR)/linker.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS :=
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS :=
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export OUTPUT := $(CURDIR)/$(TARGET)
export TOPDIR := $(CURDIR)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
export OFILES_BIN := $(addsuffix .o,$(BINFILES))
export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SRC)
export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES)))
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
.PHONY: $(BUILD) clean all
#---------------------------------------------------------------------------------
all: $(BUILD)
$(BUILD):
@[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@rm -rf $(dir_build)
@echo clean ...
@rm -fr $(BUILD) $(TARGET).bin $(TARGET).elf
$(dir_out)/$(name).elf: $(objects)
$(LINK.o) -T linker.ld $(OUTPUT_OPTION) $^
$(dir_build)/%.o: $(dir_source)/%.c
@mkdir -p "$(@D)"
$(COMPILE.c) $(OUTPUT_OPTION) $<
#---------------------------------------------------------------------------------
else
.PHONY: all
$(dir_build)/%.o: $(dir_source)/%.s
@mkdir -p "$(@D)"
$(COMPILE.s) $(OUTPUT_OPTION) $<
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
all : $(OUTPUT).bin
$(OUTPUT).bin : $(OUTPUT).elf
$(OBJCOPY) -S -O binary $< $@
@echo built ... $(notdir $@)
$(OUTPUT).elf : $(OFILES)
%.elf: $(OFILES)
@echo linking $(notdir $@)
@$(LD) $(LDFLAGS) $(OFILES) $(LIBPATHS) $(LIBS) -o $@
@$(NM) -CSn $@ > $(notdir $*.lst)
$(OFILES_SRC) : $(HFILES_BIN)
#---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#---------------------------------------------------------------------------------
%.bin.o %_bin.h : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------

View File

@@ -1,16 +1,158 @@
OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm", "elf32-littlearm")
OUTPUT_ARCH(arm)
ENTRY(_start)
/* Mostly copied from https://github.com/devkitPro/buildscripts/blob/master/dkarm-eabi/crtls/3dsx.ld */
PHDRS
{
main PT_LOAD;
}
SECTIONS
{
. = 0x1FF80000;
PROVIDE(__start__ = 0x1FF80000);
PROVIDE(__stack_top__ = 0x1FFFE000);
PROVIDE(__stack_bottom__ = 0x1FFFD000);
.text : ALIGN(4) { *(.text.start) *(.text*); . = ALIGN(4); }
.rodata : ALIGN(4) { *(.rodata*); . = ALIGN(4); }
.data : ALIGN(4) { *(.data*); . = ALIGN(4); }
.bss : ALIGN(8) { __bss_start = .; *(.bss* COMMON); . = ALIGN(8); __bss_end = .; }
. = __start__;
__stack_top__ = 0x1FFFF000;
. = ALIGN(4);
.text :
{
KEEP( *(.text.start) )
KEEP( *(.init) )
/* .text */
*(.text)
*(.text.*)
*(.glue_7)
*(.glue_7t)
*(.stub)
*(.gnu.warning)
*(.gnu.linkonce.t*)
/* .fini */
KEEP( *(.fini) )
. = ALIGN(32);
} :main
.rodata :
{
*(.rodata)
*(.roda)
*(.rodata.*)
*all.rodata*(*)
*(.gnu.linkonce.r*)
SORT(CONSTRUCTORS)
. = ALIGN(8);
}
.preinit_array :
{
PROVIDE (__preinit_array_start = .);
KEEP (*(.preinit_array))
PROVIDE (__preinit_array_end = .);
}
.init_array :
{
PROVIDE (__init_array_start = .);
KEEP (*(SORT(.init_array.*)))
KEEP (*(.init_array))
PROVIDE (__init_array_end = .);
}
.fini_array :
{
PROVIDE (__fini_array_start = .);
KEEP (*(.fini_array))
KEEP (*(SORT(.fini_array.*)))
PROVIDE (__fini_array_end = .);
}
.ctors :
{
KEEP (*crtbegin.o(.ctors)) /* MUST be first -- GCC requires it */
KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors))
KEEP (*(SORT(.ctors.*)))
KEEP (*(.ctors))
. = ALIGN(4); /* REQUIRED. LD is flaky without it. */
}
.dtors :
{
KEEP (*crtbegin.o(.dtors))
KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors))
KEEP (*(SORT(.dtors.*)))
KEEP (*(.dtors))
. = ALIGN(4); /* REQUIRED. LD is flaky without it. */
}
.ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) __exidx_start = .;}
ARM.exidx : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) __exidx_end = .;}
.data :
{
*(.data)
*(.data.*)
KEEP (*(.large_patch*))
*(.gnu.linkonce.d*)
CONSTRUCTORS
. = ALIGN(32);
}
.bss (NOLOAD) :
{
. = ALIGN(32);
PROVIDE (__bss_start__ = ABSOLUTE(.));
*(.dynbss)
*(.bss)
*(.bss.*)
*(.gnu.linkonce.b*)
*(COMMON)
. = ALIGN(8);
PROVIDE (__bss_end__ = ABSOLUTE(.));
} :NONE
PROVIDE (__end__ = ABSOLUTE(.));
/* ==================
==== Metadata ====
================== */
/* Discard sections that difficult post-processing */
/DISCARD/ : { *(.group .comment .note) }
/* Stabs debugging sections. */
.stab 0 : { *(.stab) }
.stabstr 0 : { *(.stabstr) }
.stab.excl 0 : { *(.stab.excl) }
.stab.exclstr 0 : { *(.stab.exclstr) }
.stab.index 0 : { *(.stab.index) }
.stab.indexstr 0 : { *(.stab.indexstr) }
/* DWARF debug sections.
Symbols in the DWARF debugging sections are relative to the beginning
of the section so we begin them at 0. */
/* DWARF 1 */
.debug 0 : { *(.debug) }
.line 0 : { *(.line) }
/* GNU DWARF 1 extensions */
.debug_srcinfo 0 : { *(.debug_srcinfo) }
.debug_sfnames 0 : { *(.debug_sfnames) }
/* DWARF 1.1 and DWARF 2 */
.debug_aranges 0 : { *(.debug_aranges) }
.debug_pubnames 0 : { *(.debug_pubnames) }
/* DWARF 2 */
.debug_info 0 : { *(.debug_info) }
.debug_abbrev 0 : { *(.debug_abbrev) }
.debug_line 0 : { *(.debug_line) }
.debug_frame 0 : { *(.debug_frame) }
.debug_str 0 : { *(.debug_str) }
.debug_loc 0 : { *(.debug_loc) }
.debug_macinfo 0 : { *(.debug_macinfo) }
}

7
arm11/linker.specs Normal file
View File

@@ -0,0 +1,7 @@
%rename link old_link
*link:
%(old_link) -T %:getenv(TOPDIR /linker.ld) --nmagic --gc-sections
*startfile:
crti%O%s crtbegin%O%s

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -37,9 +37,13 @@ extern u32 prepareForFirmlaunchSize;
extern volatile Arm11Operation operation;
static void initScreensSequence(u32 brightnessLevel)
static void initScreens(u32 brightnessLevel, struct fb *fbs)
{
*(vu32 *)0x10141200 = 0x1007F;
*(vu32 *)0x10202204 = 0x01000000; //set LCD fill black to hide potential garbage -- NFIRM does it before firmlaunching
*(vu32 *)0x10202A04 = 0x01000000;
*(vu32 *)0x10202014 = 0x00000001;
*(vu32 *)0x1020200C &= 0xFFFEFFFE;
*(vu32 *)0x10202240 = brightnessLevel;
@@ -70,10 +74,13 @@ static void initScreensSequence(u32 brightnessLevel)
*(vu32 *)0x1040045C = 0x00f00190;
*(vu32 *)0x10400460 = 0x01c100d1;
*(vu32 *)0x10400464 = 0x01920002;
*(vu32 *)0x10400468 = 0x18300000;
*(vu32 *)0x10400468 = (u32)fbs[0].top_left;
*(vu32 *)0x1040046C = (u32)fbs[1].top_left;
*(vu32 *)0x10400470 = 0x80341;
*(vu32 *)0x10400474 = 0x00010501;
*(vu32 *)0x10400478 = 0;
*(vu32 *)0x10400494 = (u32)fbs[0].top_right;
*(vu32 *)0x10400498 = (u32)fbs[1].top_right;
*(vu32 *)0x10400490 = 0x000002D0;
*(vu32 *)0x1040049C = 0x00000000;
@@ -104,7 +111,8 @@ static void initScreensSequence(u32 brightnessLevel)
*(vu32 *)0x1040055C = 0x00f00140;
*(vu32 *)0x10400560 = 0x01c100d1;
*(vu32 *)0x10400564 = 0x01920052;
*(vu32 *)0x10400568 = 0x18300000 + 0x46500;
*(vu32 *)0x10400568 = (u32)fbs[0].bottom;
*(vu32 *)0x1040056C = (u32)fbs[1].bottom;
*(vu32 *)0x10400570 = 0x80301;
*(vu32 *)0x10400574 = 0x00010501;
*(vu32 *)0x10400578 = 0;
@@ -114,16 +122,33 @@ static void initScreensSequence(u32 brightnessLevel)
//Disco register
for(u32 i = 0; i < 256; i++)
*(vu32 *)0x10400584 = 0x10101 * i;
*(vu32 *)0x10202204 = 0x00000000; //unset LCD fill
*(vu32 *)0x10202A04 = 0x00000000;
}
static void setupFramebuffers(struct fb *fbs)
{
*(vu32 *)0x10202204 = 0x01000000; //set LCD fill black to hide potential garbage -- NFIRM does it before firmlaunching
*(vu32 *)0x10202A04 = 0x01000000;
*(vu32 *)0x10400468 = (u32)fbs[0].top_left;
*(vu32 *)0x1040046c = (u32)fbs[1].top_left;
*(vu32 *)0x10400494 = (u32)fbs[0].top_right;
*(vu32 *)0x10400498 = (u32)fbs[1].top_right;
*(vu32 *)0x10400568 = (u32)fbs[0].bottom;
*(vu32 *)0x1040056c = (u32)fbs[1].bottom;
//Set framebuffer format, framebuffer select and stride
*(vu32 *)0x10400470 = 0x80341;
*(vu32 *)0x10400478 = 0;
*(vu32 *)0x10400490 = 0x2D0;
*(vu32 *)0x10400570 = 0x80301;
*(vu32 *)0x10400578 = 0;
*(vu32 *)0x10400590 = 0x2D0;
*(vu32 *)0x10202204 = 0x00000000; //unset LCD fill
*(vu32 *)0x10202A04 = 0x00000000;
}
static void clearScreens(struct fb *fb)
@@ -178,8 +203,8 @@ void main(void)
{
case ARM11_READY:
continue;
case INIT_SCREENS_SEQUENCE:
initScreensSequence(*(vu32 *)ARM11_PARAMETERS_ADDRESS);
case INIT_SCREENS:
initScreens(*(vu32 *)ARM11_PARAMETERS_ADDRESS, (struct fb *)(ARM11_PARAMETERS_ADDRESS + 4));
break;
case SETUP_FRAMEBUFFERS:
setupFramebuffers((struct fb *)ARM11_PARAMETERS_ADDRESS);
@@ -192,7 +217,7 @@ void main(void)
break;
case UPDATE_BRIGHTNESS:
updateBrightness(*(vu32 *)ARM11_PARAMETERS_ADDRESS);
break;
break;
case DEINIT_SCREENS:
deinitScreens();
break;

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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

View File

@@ -1,5 +1,5 @@
@ This file is part of Luma3DS
@ Copyright (C) 2016-2017 Aurora Wright, TuxSH
@ Copyright (C) 2016-2020 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
@@ -21,8 +21,8 @@
@ * 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
.section .text.start, "ax", %progbits
.align 4
.global _start
.type _start, %function
@@ -53,20 +53,25 @@ start:
mcr p15, 0, r0, c7, c7, 0
mcr p15, 0, r0, c7, c10, 4
@ Clear BSS
ldr r0, =__bss_start
mov r1, #0
ldr r2, =__bss_end
sub r2, r0
bl memset32
ldr sp, =__stack_top__
mov fp, #0
@ Clear BSS
ldr r0, =__bss_start__
mov r1, #0
ldr r2, =__bss_end__
sub r2, r0
bl memset
@ Call the init array
bl __libc_init_array
b main
.global prepareForFirmlaunch
.type prepareForFirmlaunch, %function
prepareForFirmlaunch:
str r0, [r1] @ tell ARM9 we're done
str r0, [r1] @ tell Arm9 we're done
mov r0, #0x20000000
_wait_for_core0_entrypoint_loop:

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -50,11 +50,11 @@ struct fb {
u8 *top_left;
u8 *top_right;
u8 *bottom;
} __attribute__((packed));
};
typedef enum
{
INIT_SCREENS_SEQUENCE = 0,
INIT_SCREENS = 0,
SETUP_FRAMEBUFFERS,
CLEAR_SCREENS,
SWAP_FRAMEBUFFERS,

176
arm9/Makefile Normal file
View File

@@ -0,0 +1,176 @@
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITARM)),)
$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
endif
TOPDIR ?= $(CURDIR)
include $(DEVKITARM)/base_rules
export REVISION := $(shell git describe --tags --match v[0-9]* --abbrev=8 | sed 's/-[0-9]*-g/-/')
export VERSION_MAJOR := $(shell git describe --tags --match v[0-9]* | cut -c2- | cut -f1 -d- | cut -f1 -d.)
export VERSION_MINOR := $(shell git describe --tags --match v[0-9]* | cut -c2- | cut -f1 -d- | cut -f2 -d.)
export VERSION_BUILD := $(shell git describe --tags --match v[0-9]* | cut -c2- | cut -f1 -d- | cut -f3 -d.)
export COMMIT := $(shell git rev-parse --short=8 HEAD)
export IS_RELEASE := 0
ifeq ($(strip $(REVISION)),)
export REVISION := v0.0.0-0
export VERSION_MAJOR := 0
export VERSION_MINOR := 0
export VERSION_BUILD := 0
endif
ifeq ($(strip $(COMMIT)),)
export COMMIT := 0
endif
ifeq ($(strip $(VERSION_BUILD)),)
export VERSION_BUILD := 0
endif
ifeq ($(strip $(shell git describe --tags --match v[0-9]* | grep -)),)
export IS_RELEASE := 1
endif
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
#---------------------------------------------------------------------------------
APP_TITLE := Luma3DS
TARGET := $(notdir $(CURDIR))
BUILD := build
SOURCES := source source/fatfs source/fatfs/sdmmc
DATA := data
INCLUDES := include
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH := -marm -march=armv5te -mtune=arm946e-s
DEFINES := -DARM9 -D_3DS
CFLAGS := -g -std=gnu11 -Wall -Wextra -Werror -O2 -mword-relocations \
-fomit-frame-pointer -ffunction-sections -fdata-sections \
-Wno-main $(ARCH) $(DEFINES)
CFLAGS += $(INCLUDE)
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions -std=gnu++11
ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(TOPDIR)/linker.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS :=
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS :=
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export OUTPUT := $(CURDIR)/$(TARGET)
export TOPDIR := $(CURDIR)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
export APP_TITLE := $(notdir $(TOPDIR)/..)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
export OFILES_BIN := $(addsuffix .o,$(BINFILES))
export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SRC)
export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES)))
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
.PHONY: $(BUILD) clean all
#---------------------------------------------------------------------------------
all: $(BUILD)
$(BUILD):
@[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@echo clean ...
@rm -fr $(BUILD) $(TARGET).bin $(TARGET).elf
#---------------------------------------------------------------------------------
else
.PHONY: all
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
all : $(OUTPUT).elf
$(OUTPUT).elf : $(OFILES)
%.elf: $(OFILES)
@echo linking $(notdir $@)
@$(LD) $(LDFLAGS) $(OFILES) $(LIBPATHS) $(LIBS) -o $@
@$(NM) -CSn $@ > $(notdir $*.lst)
$(OFILES_SRC) : $(HFILES_BIN)
memory.o strings.o: CFLAGS += -O3
config.o: CFLAGS += -DCONFIG_TITLE="\"$(APP_TITLE) $(REVISION)_3gx_beta configuration\""
patches.o: CFLAGS += -DVERSION_MAJOR="$(VERSION_MAJOR)" -DVERSION_MINOR="$(VERSION_MINOR)"\
-DVERSION_BUILD="$(VERSION_BUILD)" -DISRELEASE="$(IS_RELEASE)" -DCOMMIT_HASH="0x$(COMMIT)"
#---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#---------------------------------------------------------------------------------
%.bin.o %_bin.h : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------

209
arm9/linker.ld Normal file
View File

@@ -0,0 +1,209 @@
OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm", "elf32-littlearm")
OUTPUT_ARCH(arm)
ENTRY(_start)
PHDRS
{
crt0 PT_LOAD;
itcm PT_LOAD;
main PT_LOAD;
}
/* Mostly copied from https://github.com/devkitPro/buildscripts/blob/master/dkarm-eabi/crtls/3dsx.ld */
MEMORY
{
main : ORIGIN = 0x08006000, LENGTH = 0x080F0000 - 0x08006000
itcm : ORIGIN = 0x01FF8000, LENGTH = 0x01FFB800 - 0x01FF8000 /* Unused ITCM slice. */
}
SECTIONS
{
PROVIDE(__start__ = 0x08006000);
PROVIDE(__stack_top__ = 0x08100000);
PROVIDE(__stack_bottom__ = 0x080F0000);
PROVIDE(__itcm_stack_top__ = 0x01FFB800);
PROVIDE(__itcm_stack_bottom__ = 0x01FFA800);
. = __start__;
.crt0 :
{
KEEP( *(.text.start) )
KEEP( *(.init) )
. = ALIGN(32);
} >main :crt0
.itcm_loadable :
{
PROVIDE (__itcm_start__ = ABSOLUTE(.));
PROVIDE (__itcm_lma__ = LOADADDR(.itcm_loadable));
KEEP(*(.arm9_exception_handlers.text))
*(.arm9_exception_handlers.text*)
KEEP(*(.chainloader.text.start))
chainloader.o(.text*)
i2c.o(.text*)
arm9_exception_handlers.o(.text*)
*(.arm9_exception_handlers.rodata*)
chainloader.o(.rodata*)
i2c.o(.rodata*)
arm9_exception_handlers.o(.rodata*)
*(.arm9_exception_handlers.data*)
chainloader.o(.data*)
i2c.o(.data*)
arm9_exception_handlers.o(.data*)
. = ALIGN(32);
} >itcm AT>main :itcm
.itcm_bss (NOLOAD) :
{
. = ALIGN(32);
PROVIDE (__itcm_bss_start__ = ABSOLUTE(.));
*(.arm9_exception_handlers.bss*)
chainloader.o(.bss* COMMON)
i2c.o(.bss* COMMON)
arm9_exception_handlers.o(.bss* COMMON)
. = ALIGN(32);
PROVIDE (__itcm_end__ = ABSOLUTE(.));
} >itcm :NONE
.text :
{
/* .text */
*(.text)
*(.text.*)
*(.glue_7)
*(.glue_7t)
*(.stub)
*(.gnu.warning)
*(.gnu.linkonce.t*)
/* .fini */
KEEP( *(.fini) )
. = ALIGN(8);
} >main :main
.rodata :
{
*(.rodata)
*(.roda)
*(.rodata.*)
*all.rodata*(*)
*(.gnu.linkonce.r*)
SORT(CONSTRUCTORS)
. = ALIGN(8);
} >main
.preinit_array :
{
PROVIDE (__preinit_array_start = .);
KEEP (*(.preinit_array))
PROVIDE (__preinit_array_end = .);
} >main
.init_array ALIGN(4) :
{
PROVIDE (__init_array_start = .);
KEEP (*(SORT(.init_array.*)))
KEEP (*(.init_array))
PROVIDE (__init_array_end = .);
} >main
.fini_array ALIGN(4) :
{
PROVIDE (__fini_array_start = .);
KEEP (*(.fini_array))
KEEP (*(SORT(.fini_array.*)))
PROVIDE (__fini_array_end = .);
} >main
.ctors ALIGN(4) :
{
KEEP (*crtbegin.o(.ctors)) /* MUST be first -- GCC requires it */
KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors))
KEEP (*(SORT(.ctors.*)))
KEEP (*(.ctors))
. = ALIGN(4); /* REQUIRED. LD is flaky without it. */
} >main
.dtors ALIGN(4) :
{
KEEP (*crtbegin.o(.dtors))
KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors))
KEEP (*(SORT(.dtors.*)))
KEEP (*(.dtors))
. = ALIGN(4); /* REQUIRED. LD is flaky without it. */
} >main
.ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) __exidx_start = ABSOLUTE(.);} >main
ARM.exidx : { *(.ARM.exidx* .gnu.linkonce.armexidx.*) __exidx_end = ABSOLUTE(.);} >main
.data :
{
*(.data)
*(.data.*)
KEEP (*(.large_patch*))
*(.gnu.linkonce.d*)
CONSTRUCTORS
. = ALIGN(32);
} >main
.bss (NOLOAD) :
{
. = ALIGN(32);
PROVIDE (__bss_start__ = ABSOLUTE(.));
*(.dynbss)
*(.bss)
*(.bss.*)
*(.gnu.linkonce.b*)
*(COMMON)
. = ALIGN(8);
PROVIDE (__bss_end__ = ABSOLUTE(.));
} >main :NONE
__end__ = ABSOLUTE(.) ;
/* ==================
==== Metadata ====
================== */
/* Discard sections that difficult post-processing */
/DISCARD/ : { *(.group .comment .note) }
/* Stabs debugging sections. */
.stab 0 : { *(.stab) }
.stabstr 0 : { *(.stabstr) }
.stab.excl 0 : { *(.stab.excl) }
.stab.exclstr 0 : { *(.stab.exclstr) }
.stab.index 0 : { *(.stab.index) }
.stab.indexstr 0 : { *(.stab.indexstr) }
/* DWARF debug sections.
Symbols in the DWARF debugging sections are relative to the beginning
of the section so we begin them at 0. */
/* DWARF 1 */
.debug 0 : { *(.debug) }
.line 0 : { *(.line) }
/* GNU DWARF 1 extensions */
.debug_srcinfo 0 : { *(.debug_srcinfo) }
.debug_sfnames 0 : { *(.debug_sfnames) }
/* DWARF 1.1 and DWARF 2 */
.debug_aranges 0 : { *(.debug_aranges) }
.debug_pubnames 0 : { *(.debug_pubnames) }
/* DWARF 2 */
.debug_info 0 : { *(.debug_info) }
.debug_abbrev 0 : { *(.debug_abbrev) }
.debug_line 0 : { *(.debug_line) }
.debug_frame 0 : { *(.debug_frame) }
.debug_str 0 : { *(.debug_str) }
.debug_loc 0 : { *(.debug_loc) }
.debug_macinfo 0 : { *(.debug_macinfo) }
}

7
arm9/linker.specs Normal file
View File

@@ -0,0 +1,7 @@
%rename link old_link
*link:
%(old_link) -T %:getenv(TOPDIR /linker.ld) --nmagic --gc-sections
*startfile:
crti%O%s crtbegin%O%s

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -30,21 +30,21 @@
#pragma once
typedef struct __attribute__((packed))
typedef struct
{
u32 address;
u32 phyRegionSize;
u32 size;
} CodeSetInfo;
typedef struct __attribute__((packed))
typedef struct
{
u32 saveDataSize[2];
u32 jumpID[2];
u8 reserved[0x30];
} SystemInfo;
typedef struct __attribute__((packed))
typedef struct
{
char appTitle[8];
u8 reserved1[5];
@@ -60,7 +60,7 @@ typedef struct __attribute__((packed))
SystemInfo systemInfo;
} SystemControlInfo;
typedef struct __attribute__((packed))
typedef struct
{
SystemControlInfo systemControlInfo;
u8 aci[0x200];
@@ -69,7 +69,7 @@ typedef struct __attribute__((packed))
u8 aciLim[0x200];
} ExHeader;
typedef struct __attribute__((packed))
typedef struct
{
u8 sig[0x100]; //RSA-2048 signature of the NCCH header, using SHA-256
char magic[4]; //NCCH
@@ -102,13 +102,13 @@ typedef struct __attribute__((packed))
u8 romFsHash[0x20]; //RomFS superblock SHA-256 hash
} Ncch;
typedef struct __attribute__((packed))
typedef struct
{
Ncch ncch;
ExHeader exHeader;
} Cxi;
typedef struct __attribute__((packed))
typedef struct
{
char sigIssuer[0x40];
u8 eccPubKey[0x3C];
@@ -134,7 +134,7 @@ typedef struct __attribute__((packed))
u8 contentIndex[0xAC];
} Ticket;
typedef struct __attribute__((packed))
typedef struct
{
u32 offset;
u8 *address;
@@ -143,7 +143,7 @@ typedef struct __attribute__((packed))
u8 hash[0x20];
} FirmSection;
typedef struct __attribute__((packed))
typedef struct
{
char magic[4];
u32 reserved1;
@@ -153,7 +153,7 @@ typedef struct __attribute__((packed))
FirmSection section[4];
} Firm;
typedef struct __attribute__((packed))
typedef struct
{
u8 keyX[0x10];
u8 keyY[0x10];

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -23,9 +23,6 @@
* 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 flushCaches(void);
void *alignedseqmemcpy(void *dst, const void *src, u32 len);

View File

@@ -1,5 +1,5 @@
@ This file is part of Luma3DS
@ Copyright (C) 2016-2017 Aurora Wright, TuxSH
@ Copyright (C) 2016-2020 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
@@ -21,40 +21,45 @@
@ * 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.alignedseqmemcpy, "ax", %progbits
.arm
@ Align on cache line boundaries & make sure the loops don't cross them.
.align 5
.global alignedseqmemcpy
.type alignedseqmemcpy, %function
alignedseqmemcpy:
@ src=r1 and dst=r0 are expected to be 4-byte-aligned
push {r4-r10, lr}
.section .text.start
.align 4
.global _start
_start:
ldr sp, =__stack_top__
b main
lsrs r12, r2, #5
sub r2, r2, r12, lsl #5
beq 2f
.text
.balign 4
.global disableMpuAndJumpToEntrypoints
.type disableMpuAndJumpToEntrypoints, %function
disableMpuAndJumpToEntrypoints:
mov r4, r0
mov r5, r1
mov r6, r2
mov r7, r3
1:
ldmia r1!, {r3-r10}
stmia r0!, {r3-r10}
subs r12, #1
bne 1b
bl flushCaches
2:
lsrs r12, r2, #2
sub r2, r2, r12, lsl #2
beq 4f
@ 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
3:
ldr r3, [r1], #4
str r3, [r0], #4
subs r12, #1
bne 3b
@ Set the ARM11 entrypoint
mov r0, #0x20000000
str r7, [r0, #-4]
4:
tst r2, #2
ldrneh r3, [r1], #2
strneh r3, [r0], #2
@ Jump to the ARM9 entrypoint
mov r0, r4
mov r1, r5
ldr r2, =0x1BEEF
bx r6
tst r2, #1
ldrneb r3, [r1], #1
strneb r3, [r0], #1
pop {r4-r10, pc}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -24,56 +24,19 @@
* reasonable ways as different from the original version.
*/
#include "arm9_exception_handlers.h"
#include "i2c.h"
#include "handlers.h"
#include "screen.h"
#define FINAL_BUFFER 0x25000000
#define REG_DUMP_SIZE 4 * 17
#define CODE_DUMP_SIZE 48
bool cannotAccessAddress(const void *address)
{
u32 regionSettings[8];
u32 addr = (u32)address;
u32 dataAccessPermissions = readMPUConfig(regionSettings);
for(u32 i = 0; i < 8; i++)
{
if((dataAccessPermissions & 0xF) == 0 || (regionSettings[i] & 1) == 0)
continue; //No access / region not enabled
u32 regionAddrBase = regionSettings[i] & ~0xFFF;
u32 regionSize = 1 << (((regionSettings[i] >> 1) & 0x1F) + 1);
if(addr >= regionAddrBase && addr < regionAddrBase + regionSize)
return false;
dataAccessPermissions >>= 4;
}
return true;
}
static u32 __attribute__((noinline)) copyMemory(void *dst, const void *src, u32 size, u32 alignment)
{
u8 *out = (u8 *)dst;
const u8 *in = (const u8 *)src;
if(((u32)src & (alignment - 1)) != 0 || cannotAccessAddress(src) || (size != 0 && cannotAccessAddress((u8 *)src + size - 1)))
return 0;
for(u32 i = 0; i < size; i++)
*out++ = *in++;
return size;
}
void __attribute__((noreturn)) mainHandler(u32 *regs, u32 type)
void __attribute__((noreturn)) arm9ExceptionHandlerMain(u32 *registerDump, u32 type)
{
ExceptionDumpHeader dumpHeader;
u32 registerDump[REG_DUMP_SIZE / 4];
u8 codeDump[CODE_DUMP_SIZE];
dumpHeader.magic[0] = 0xDEADC0DE;
@@ -89,34 +52,32 @@ void __attribute__((noreturn)) mainHandler(u32 *regs, u32 type)
dumpHeader.codeDumpSize = CODE_DUMP_SIZE;
dumpHeader.additionalDataSize = 0;
//Dump registers
//Current order of saved regs: cpsr, pc, r8-r14, r0-r7
u32 cpsr = regs[0];
u32 pc = regs[1] - (type < 3 ? (((cpsr & 0x20) != 0 && type == 1) ? 2 : 4) : 8);
u32 cpsr = registerDump[16];
u32 pc = registerDump[15] - (type < 3 ? (((cpsr & 0x20) != 0 && type == 1) ? 2 : 4) : 8);
registerDump[15] = pc;
registerDump[16] = cpsr;
for(u32 i = 0; i < 7; i++) registerDump[8 + i] = regs[2 + i];
for(u32 i = 0; i < 8; i++) registerDump[i] = regs[9 + i];
//Dump code
u8 *instr = (u8 *)pc + ((cpsr & 0x20) ? 2 : 4) - dumpHeader.codeDumpSize; //Doesn't work well on 32-bit Thumb instructions, but it isn't much of a problem
dumpHeader.codeDumpSize = copyMemory(codeDump, instr, dumpHeader.codeDumpSize, ((cpsr & 0x20) != 0) ? 2 : 4);
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
//Copy register dump and code dump
u8 *final = (u8 *)(FINAL_BUFFER + sizeof(ExceptionDumpHeader));
final += copyMemory(final, registerDump, dumpHeader.registerDumpSize, 1);
final += copyMemory(final, codeDump, dumpHeader.codeDumpSize, 1);
final += safecpy(final, registerDump, dumpHeader.registerDumpSize);
final += safecpy(final, codeDump, dumpHeader.codeDumpSize);
//Dump stack in place
dumpHeader.stackDumpSize = copyMemory(final, (const void *)registerDump[13], 0x1000 - (registerDump[13] & 0xFFF), 1);
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;
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
i2cWriteRegister(I2C_DEV_MCU, 0x20, 1 << 2); //Reboot
I2C_writeReg(I2C_DEV_MCU, 0x20, 1 << 2); //Reboot
while(true);
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -24,12 +24,9 @@
* reasonable ways as different from the original version.
*/
/*
* memcpy 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);
extern const u32 arm9ExceptionHandlerAddressTable[6];
extern u32 arm9ExceptionHandlerSvcBreakAddress;
u32 safecpy(void *dst, const void *src, u32 len);

View File

@@ -0,0 +1,168 @@
@ This file is part of Luma3DS
@ Copyright (C) 2016-2020 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, "aw", %nobits
.align 4
.global arm9ExceptionHandlerSvcBreakAddress
arm9ExceptionHandlerSvcBreakAddress:
.skip 4
_regs: .skip (4 * 17)

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -45,7 +45,8 @@
#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 (DPAD_BUTTONS | BUTTON_B | BUTTON_X | BUTTON_Y)
#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)

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -33,7 +33,7 @@
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
- setting the Arm11 entrypoint to execute a function
- jumping to a payload
***/

View File

@@ -1,5 +1,5 @@
@ This file is part of Luma3DS
@ Copyright (C) 2016-2017 Aurora Wright, TuxSH
@ Copyright (C) 2016-2020 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
@@ -22,7 +22,7 @@
@ or requiring that modified versions of such material be marked in
@ reasonable ways as different from the original version.
.text
.section .text.cache, "ax", %progbits
.arm
.align 4
@@ -31,7 +31,7 @@
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)
@ 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

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -24,13 +24,38 @@
* reasonable ways as different from the original version.
*/
#include "memory.h"
#include "cache.h"
#include "firm.h"
#include "chainloader.h"
#include "screen.h"
void main(int argc, char **argv)
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)
{
Firm *firm = (Firm *)0x20001000;
char *argvPassed[2],
absPath[24 + 255];
struct fb fbs[2];
@@ -55,5 +80,5 @@ void main(int argc, char **argv)
argvPassed[1] = (char *)&fbs;
}
launchFirm(firm, argc, argvPassed);
doLaunchFirm(firm, argc, argvPassed);
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -25,6 +25,8 @@
*/
#pragma once
#include <3ds/types.h>
void installKernelExtension(void);
#include "types.h"
#include "firm.h"
void chainload(int argc, char **argv, Firm *firm);

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

@@ -0,0 +1,439 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2020 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 "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",
"( ) Enable Rosalina on SAFE_FIRM",
};
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!",
"Enables Rosalina, the kernel ext.\n"
"and sysmodule reimplementations on\n"
"SAFE_FIRM (New 3DS only).\n\n"
"Also suppresses QTM error 0xF96183FE,\n"
"allowing to use 8.1-11.3 N3DS on\n"
"New 2DS XL consoles.\n\n"
"Only select this if you know what you\n"
"are doing!",
};
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 },
{ .visible = ISN3DS },
};
//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 = 0,
singleSelected = 0;
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);
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -28,23 +28,25 @@
#include "types.h"
#define CONFIG(a) (((configData.config >> (a + 17)) & 1) != 0)
#define MULTICONFIG(a) ((configData.config >> (a * 2 + 7)) & 3)
#define BOOTCONFIG(a, b) ((configData.config >> a) & b)
#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 1
#define CONFIG_VERSIONMINOR 12
#define CONFIG_VERSIONMAJOR 2
#define CONFIG_VERSIONMINOR 4
#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
};
@@ -57,8 +59,9 @@ enum singleOptions
PATCHGAMES,
PATCHVERSTRING,
SHOWGBABOOT,
PATCHACCESS,
PATCHUNITINFO
PATCHUNITINFO,
DISABLEARM11EXCHANDLERS,
ENABLESAFEFIRMROSALINA,
};
typedef enum ConfigurationStatus
@@ -68,6 +71,8 @@ typedef enum ConfigurationStatus
CREATE_CONFIGURATION
} ConfigurationStatus;
extern CfgData configData;
bool readConfig(void);
void writeConfig(bool isPayloadLaunch);
void writeConfig(bool isConfigOptions);
void configMenu(bool oldPinStatus, u32 oldPinMode);

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -33,8 +33,10 @@
#include "crypto.h"
#include "memory.h"
#include "strings.h"
#include "emunand.h"
#include "utils.h"
#include "alignedseqmemcpy.h"
#include "strings.h"
#include "fatfs/sdmmc/sdmmc.h"
/****************************************************************
@@ -287,24 +289,18 @@ 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 u32 *src32 = (const u32 *)src;
int i;
const u8 *src8 = (const u8 *)src;
while(size >= 0x40)
{
sha_wait_idle();
for(i = 0; i < 4; ++i)
{
*REG_SHA_INFIFO = *src32++;
*REG_SHA_INFIFO = *src32++;
*REG_SHA_INFIFO = *src32++;
*REG_SHA_INFIFO = *src32++;
}
alignedseqmemcpy((void *)REG_SHA_INFIFO, src8, 0x40);
src8 += 0x40;
size -= 0x40;
}
sha_wait_idle();
memcpy((void *)REG_SHA_INFIFO, src32, size);
alignedseqmemcpy((void *)REG_SHA_INFIFO, src8, size);
*REG_SHA_CNT = (*REG_SHA_CNT & ~SHA_NORMAL_ROUND) | SHA_FINAL_ROUND;
@@ -317,7 +313,7 @@ void sha(void *res, const void *src, u32 size, u32 mode)
else if(mode == SHA_1_MODE)
hashSize = SHA_1_HASH_SIZE;
memcpy(res, (void *)REG_SHA_HASH, hashSize);
alignedseqmemcpy(res, (void *)REG_SHA_HASH, hashSize);
}
/*****************************************************************/
@@ -326,7 +322,7 @@ __attribute__((aligned(4))) static u8 nandCtr[AES_BLOCK_SIZE];
static u8 nandSlot;
static u32 fatStart = 0;
FirmwareSource firmSource;
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},
@@ -421,12 +417,17 @@ int ctrNandWrite(u32 sector, u32 sectorCount, const u8 *inbuf)
return result;
}
bool decryptExeFs(Cxi *cxi)
u32 decryptExeFs(Cxi *cxi)
{
if(memcmp(cxi->ncch.magic, "NCCH", 4) != 0) return false;
if(memcmp(cxi->ncch.magic, "NCCH", 4) != 0) return 0;
u8 *exeFsOffset = (u8 *)cxi + (cxi->ncch.exeFsOffset + 1) * 0x200;
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++)
@@ -438,14 +439,14 @@ bool decryptExeFs(Cxi *cxi)
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;
return memcmp(cxi, "FIRM", 4) == 0 ? exeFsSize : 0;
}
bool decryptNusFirm(const Ticket *ticket, Cxi *cxi, u32 ncchSize)
u32 decryptNusFirm(const Ticket *ticket, Cxi *cxi, u32 ncchSize)
{
if(memcmp(ticket->sigIssuer, "Root", 4) != 0) return false;
if(memcmp(ticket->sigIssuer, "Root", 4) != 0) return 0;
__attribute__((aligned(4))) 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))) 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));
@@ -484,8 +485,8 @@ static inline void twlConsoleInfoInit(void)
aes_setkey(2, (u8 *)0x01FFD398, AES_KEYX, AES_INPUT_TWLNORMAL);
if(CFG_TWLUNITINFO != 0)
{
__attribute__((aligned(4))) 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};
__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;
@@ -510,15 +511,15 @@ static inline void twlConsoleInfoInit(void)
void setupKeyslots(void)
{
//Setup 0x24 KeyY
__attribute__((aligned(4))) u8 keyY0x24[AES_BLOCK_SIZE] = {0x74, 0xCA, 0x07, 0x48, 0x84, 0xF4, 0x22, 0x8D, 0xEB, 0x2A, 0x1C, 0xA7, 0x2D, 0x28, 0x77, 0x62};
__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))) const u8 keyX0x25s[2][AES_BLOCK_SIZE] = {
__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] = {
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}
};
@@ -526,10 +527,10 @@ void setupKeyslots(void)
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)
if(ISN3DS)
{
//Setup 0x05 KeyY
__attribute__((aligned(4))) u8 keyY0x5[AES_BLOCK_SIZE] = {0x4D, 0x80, 0x4F, 0x4E, 0x99, 0x90, 0x19, 0x46, 0x13, 0xA2, 0x04, 0xAC, 0x58, 0x44, 0x60, 0xBE};
__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);
}
@@ -541,7 +542,7 @@ void setupKeyslots(void)
{0xDD, 0xDA, 0xA4, 0xC6, 0x2C, 0xC4, 0x50, 0xE9, 0xDA, 0xB6, 0x9B, 0x0D, 0x9D, 0x2A, 0x21, 0x98}
}, decKey[AES_BLOCK_SIZE];
//Initialize Key 0x18
//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);
@@ -580,6 +581,9 @@ void kernel9Loader(Arm9Bin *arm9Section)
u8 arm9BinSlot = k9lVersion == 0 ? 0x15 : 0x16;
// Get size
u32 arm9SectionSize = decAtoi(arm9Section->size, 8);
//Set keyX
__attribute__((aligned(4))) u8 keyX[AES_BLOCK_SIZE];
aes_use_keyslot(0x11);
@@ -595,11 +599,11 @@ void kernel9Loader(Arm9Bin *arm9Section)
__attribute__((aligned(4))) u8 arm9BinCtr[AES_BLOCK_SIZE];
memcpy(arm9BinCtr, arm9Section->ctr, sizeof(arm9BinCtr));
//Decrypt ARM9 binary
//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);
aes(startOfArm9Bin, startOfArm9Bin, arm9SectionSize / 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.");
if(*startOfArm9Bin != 0x47704770 && *startOfArm9Bin != 0xB0862000) error("Failed to decrypt the Arm9 binary.");
}
void computePinHash(u8 *outbuf, const u8 *inbuf)
@@ -608,7 +612,7 @@ void computePinHash(u8 *outbuf, const u8 *inbuf)
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_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);
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -110,8 +110,6 @@
#define SHA_224_HASH_SIZE (224 / 8)
#define SHA_1_HASH_SIZE (160 / 8)
extern u32 emuOffset,
emuHeader;
extern FirmwareSource firmSource;
void sha(void *res, const void *src, u32 size, u32 mode);
@@ -119,8 +117,8 @@ 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);
bool decryptExeFs(Cxi *cxi);
bool decryptNusFirm(const Ticket *ticket, Cxi *cxi, u32 ncchSize);
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);

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -30,17 +30,18 @@
*/
#include "draw.h"
#include "strings.h"
#include "memory.h"
#include "screen.h"
#include "utils.h"
#include "fs.h"
#include "fmt.h"
#include "font.h"
#include "config.h"
bool loadSplash(void)
{
const char *topSplashFile = "splash.bin",
*bottomSplashFile = "splashbottom.bin";
static const char *topSplashFile = "splash.bin",
*bottomSplashFile = "splashbottom.bin";
bool isTopSplashValid = getFileSize(topSplashFile) == SCREEN_TOP_FBSIZE,
isBottomSplashValid = getFileSize(bottomSplashFile) == SCREEN_BOTTOM_FBSIZE;
@@ -49,7 +50,6 @@ bool loadSplash(void)
if(!isTopSplashValid && !isBottomSplashValid) return false;
initScreens();
clearScreens(true);
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;
@@ -57,7 +57,9 @@ bool loadSplash(void)
if(!isTopSplashValid && !isBottomSplashValid) return false;
swapFramebuffers(true);
wait(3000ULL);
u32 durationIndex = MULTICONFIG(SPLASH_DURATION);
wait(1000ULL + (durationIndex * 2000ULL));
return true;
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -28,10 +28,12 @@
* Code for locating the SDMMC struct by Normmatt
*/
#include "emunand.h"
#include "memory.h"
#include "utils.h"
#include "fatfs/sdmmc/sdmmc.h"
#include "../build/bundled.h"
#include "large_patches.h"
u32 emuOffset,
emuHeader;
@@ -102,22 +104,41 @@ void locateEmuNand(FirmwareSource *nandType)
static inline bool getFreeK9Space(u8 *pos, u32 size, u8 **freeK9Space)
{
const u8 pattern[] = {0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00};
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) return false;
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
const u8 pattern[] = {0x21, 0x20, 0x18, 0x20};
static const u8 pattern[] = {0x21, 0x20, 0x18, 0x20};
const u8 *off = memsearch(pos, pattern, size, sizeof(pattern));
@@ -131,7 +152,7 @@ static inline u32 getSdmmc(u8 *pos, u32 size, u32 *sdmmc)
static inline u32 patchNandRw(u8 *pos, u32 size, u32 branchOffset)
{
//Look for read/write code
const u8 pattern[] = {0x1E, 0x00, 0xC8, 0x05};
static const u8 pattern[] = {0x1E, 0x00, 0xC8, 0x05};
u16 *readOffset = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
@@ -154,7 +175,7 @@ static inline u32 patchNandRw(u8 *pos, u32 size, u32 branchOffset)
static inline u32 patchMpu(u8 *pos, u32 size)
{
//Look for MPU pattern
const u8 pattern[] = {0x03, 0x00, 0x24, 0x00};
static const u8 pattern[] = {0x03, 0x00, 0x24, 0x00};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
@@ -166,7 +187,7 @@ static inline u32 patchMpu(u8 *pos, u32 size)
return 0;
}
u32 patchEmuNand(u8 *arm9Section, u32 kernel9Size, u8 *process9Offset, u32 process9Size, u8 *kernel9Address)
u32 patchEmuNand(u8 *arm9Section, u32 kernel9Size, u8 *process9Offset, u32 process9Size, u8 *kernel9Address, u32 firmVersion)
{
u8 *freeK9Space;
@@ -174,20 +195,17 @@ u32 patchEmuNand(u8 *arm9Section, u32 kernel9Size, u8 *process9Offset, u32 proce
u32 ret = 0;
//Copy EmuNAND code
memcpy(freeK9Space, emunand_bin, emunand_bin_size);
//Add the data of the found EmuNAND
u32 *posOffset = (u32 *)memsearch(freeK9Space, "NAND", emunand_bin_size, 4),
*posHeader = (u32 *)memsearch(freeK9Space, "NCSD", emunand_bin_size, 4);
*posOffset = emuOffset;
*posHeader = emuHeader;
emunandPatchNandOffset = emuOffset;
emunandPatchNcsdHeaderOffset = emuHeader;
//Find and add the SDMMC struct
u32 *posSdmmc = (u32 *)memsearch(freeK9Space, "SDMC", emunand_bin_size, 4);
u32 sdmmc;
ret += getSdmmc(process9Offset, process9Size, &sdmmc);
if(!ret) *posSdmmc = 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);

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -34,5 +34,8 @@
#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 patchEmuNand(u8 *arm9Section, u32 kernel9Size, u8 *process9Offset, u32 process9Size, u8 *kernel9Address, u32 firmVersion);

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -26,27 +26,25 @@
#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 "../build/bundled.h"
#include "buttons.h"
#include "arm9_exception_handlers.h"
void installArm9Handlers(void)
{
memcpy((void *)0x01FF8000, arm9_exceptions_bin + 32, arm9_exceptions_bin_size - 32);
vu32 *dstVeneers = (vu32 *)0x08000000;
/* IRQHandler is at 0x08000000, but we won't handle it for some reasons
svcHandler is at 0x08000010, but we won't handle svc either */
const u32 offsets[] = {0x08, 0x18, 0x20, 0x28};
for(u32 i = 0; i < 4; i++)
for(u32 i = 0; i < 6; i++)
{
*(vu32 *)(0x08000000 + offsets[i]) = 0xE51FF004;
*(vu32 *)(0x08000000 + offsets[i] + 4) = *((u32 *)arm9_exceptions_bin + 1 + i);
if(arm9ExceptionHandlerAddressTable[i] != 0)
{
dstVeneers[2 * i] = 0xE51FF004;
dstVeneers[2 * i + 1] = arm9ExceptionHandlerAddressTable[i];
}
}
}
@@ -60,25 +58,35 @@ void detectAndProcessExceptionDumps(void)
const vu8 *stackDump = (vu8 *)regs + dumpHeader->registerDumpSize + dumpHeader->codeDumpSize;
const vu8 *additionalData = stackDump + dumpHeader->stackDumpSize;
const char *handledExceptionNames[] = {
static const char *handledExceptionNames[] = {
"FIQ", "undefined instruction", "prefetch abort", "data abort"
};
const char *specialExceptions[] = {
},
*specialExceptions[] = {
"kernel panic", "svcBreak"
};
const char *registerNames[] = {
},
*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->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)
{
@@ -100,23 +108,42 @@ void detectAndProcessExceptionDumps(void)
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->additionalDataSize != 0)
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]);
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE, "%-7s%08lX", registerNames[i], regs[i]);
if(i != 16 || dumpHeader->processor != 9)
posY = drawFormattedString(true, 10 + 22 * SPACING_X, posY, COLOR_WHITE, "%-7s%08X", registerNames[i + 1], regs[i + 1]);
if(i != 16)
posY = drawFormattedString(true, 10 + 22 * SPACING_X, posY, COLOR_WHITE, "%-7s%08lX", registerNames[i + 1], regs[i + 1]);
else if(dumpHeader->processor == 11)
posY = drawFormattedString(true, 10 + 22 * SPACING_X, posY, COLOR_WHITE, "%-7s%08lX", registerNames[i + 1], regs[20]);
}
if(dumpHeader->processor == 11 && dumpHeader->type == 3)
posY = drawFormattedString(true, 10, posY + SPACING_Y, COLOR_WHITE, "%-7s%08lX Access type: %s", "FAR", regs[19], regs[17] & (1u << 11) ? "Write" : "Read");
posY += SPACING_Y;
u32 mode = regs[16] & 0xF;
@@ -127,15 +154,25 @@ void detectAndProcessExceptionDumps(void)
for(u32 line = 0; line < 19 && stackDump < additionalData; line++)
{
posYBottom = drawFormattedString(false, 10, posYBottom + SPACING_Y, COLOR_WHITE, "%08X:", regs[13] + 8 * line);
posYBottom = drawFormattedString(false, 10, posYBottom + SPACING_Y, COLOR_WHITE, "%08lX:", 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);
}
char folderPath[12],
path[36],
fileName[24];
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[32],
path[128],
fileName[32];
sprintf(folderPath, "dumps/arm%u", dumpHeader->processor);
findDumpFile(folderPath, fileName);
@@ -143,15 +180,16 @@ void detectAndProcessExceptionDumps(void)
if(fileWrite((void *)dumpHeader, path, dumpHeader->totalSize))
{
posY = drawString(true, 10, posY + SPACING_Y, COLOR_WHITE, "You can find a dump in the following file:");
posY = drawString(true, 10, posY + SPACING_Y, COLOR_WHITE, path) + SPACING_Y;
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");
memset32((void *)dumpHeader, 0, dumpHeader->totalSize);
waitInput(false);
exit:
memset((void *)dumpHeader, 0, dumpHeader->totalSize);
mcuPowerOff();
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -28,9 +28,6 @@
#include "types.h"
#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))
void installArm9Handlers(void);
u32 installArm11Handlers(u32 *exceptionsPage, u32 stackAddress, u32 codeSetOffset, u32 *dAbtHandler, u32 dAbtHandlerMemAddress);
void detectAndProcessExceptionDumps(void);

View File

@@ -286,3 +286,45 @@ R0.12c (March 04, 2017)
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

@@ -1,4 +1,4 @@
FatFs Module Source Files R0.12c
FatFs Module Source Files R0.13c
FILES
@@ -10,12 +10,12 @@ FILES
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.
integer.h Integer type definitions for FatFs.
option Optional external modules.
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 have to provide a low level disk I/O module written to
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.

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

@@ -0,0 +1,138 @@
/*-----------------------------------------------------------------------*/
/* 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"
#include "../i2c.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
// From GodMode9
#define BCDVALID(b) (((b)<=0x99)&&(((b)&0xF)<=0x9)&&((((b)>>4)&0xF)<=0x9))
#define BCD2NUM(b) (BCDVALID(b) ? (((b)&0xF)+((((b)>>4)&0xF)*10)) : 0xFF)
#define NUM2BCD(n) ((n<99) ? (((n/10)*0x10)|(n%10)) : 0x99)
#define DSTIMEGET(bcd,n) (BCD2NUM((bcd)->n))
// see: http://3dbrew.org/wiki/I2C_Registers#Device_3 (register 30)
typedef struct DsTime {
u8 bcd_s;
u8 bcd_m;
u8 bcd_h;
u8 weekday;
u8 bcd_D;
u8 bcd_M;
u8 bcd_Y;
u8 leap_count;
} DsTime;
/*-----------------------------------------------------------------------*/
/* Get current FAT time */
/*-----------------------------------------------------------------------*/
DWORD get_fattime( void ) {
DsTime dstime;
I2C_readRegBuf(I2C_DEV_MCU, 0x30, (u8 *)&dstime, sizeof(DsTime));
DWORD fattime =
((DSTIMEGET(&dstime, bcd_s)&0x3F) >> 1 ) |
((DSTIMEGET(&dstime, bcd_m)&0x3F) << 5 ) |
((DSTIMEGET(&dstime, bcd_h)&0x3F) << 11) |
((DSTIMEGET(&dstime, bcd_D)&0x1F) << 16) |
((DSTIMEGET(&dstime, bcd_M)&0x0F) << 21) |
(((DSTIMEGET(&dstime, bcd_Y)+(2000-1980))&0x7F) << 25);
return fattime;
}

View File

@@ -38,6 +38,7 @@ 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);
DWORD get_fattime( void ); // not a disk control function, but fits here
/* Disk Status Bits (DSTATUS) */

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,8 @@
/*----------------------------------------------------------------------------/
/ FatFs - Generic FAT file system module R0.12c /
/ FatFs - Generic FAT Filesystem module R0.13c /
/-----------------------------------------------------------------------------/
/
/ Copyright (C) 2017, ChaN, all right reserved.
/ Copyright (C) 2018, ChaN, all right reserved.
/
/ FatFs module is an open source software. Redistribution and use of FatFs in
/ source and binary forms, with or without modification, are permitted provided
@@ -15,28 +15,52 @@
/ 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 _FATFS
#define _FATFS 68300 /* Revision ID */
#ifndef FF_DEFINED
#define FF_DEFINED 86604 /* Revision ID */
#ifdef __cplusplus
extern "C" {
#endif
#include "integer.h" /* Basic integer types */
#include "ffconf.h" /* FatFs configuration options */
#if _FATFS != _FFCONF
#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 _MULTI_PARTITION /* Multiple partition configuration */
#if FF_MULTI_PARTITION /* Multiple partition configuration */
typedef struct {
BYTE pd; /* Physical drive number */
BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */
@@ -44,34 +68,48 @@ typedef struct {
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 */
#if _LFN_UNICODE /* Unicode (UTF-16) string */
#if _USE_LFN == 0
#error _LFN_UNICODE must be 0 at non-LFN cfg.
#endif
#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
#endif
#else /* ANSI/OEM string */
#ifndef _INC_TCHAR
#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 _FS_EXFAT
#if _USE_LFN == 0
#error LFN must be enabled when enable exFAT
#if FF_FS_EXFAT
#if FF_INTDEF != 2
#error exFAT feature wants C99 or later
#endif
typedef QWORD FSIZE_t;
#else
@@ -80,36 +118,36 @@ typedef DWORD FSIZE_t;
/* File system object structure (FATFS) */
/* Filesystem object structure (FATFS) */
typedef struct {
BYTE fs_type; /* File system type (0:N/A) */
BYTE drv; /* Physical drive number */
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; /* File system mount ID */
WORD id; /* Volume mount ID */
WORD n_rootdir; /* Number of root directory entries (FAT12/16) */
WORD csize; /* Cluster size [sectors] */
#if _MAX_SS != _MIN_SS
#if FF_MAX_SS != FF_MIN_SS
WORD ssize; /* Sector size (512, 1024, 2048 or 4096) */
#endif
#if _USE_LFN != 0
#if FF_USE_LFN
WCHAR* lfnbuf; /* LFN working buffer */
#endif
#if _FS_EXFAT
BYTE* dirbuf; /* Directory entry block scratchpad buffer */
#if FF_FS_EXFAT
BYTE* dirbuf; /* Directory entry block scratchpad buffer for exFAT */
#endif
#if _FS_REENTRANT
_SYNC_t sobj; /* Identifier of sync object */
#if FF_FS_REENTRANT
FF_SYNC_t sobj; /* Identifier of sync object */
#endif
#if !_FS_READONLY
#if !FF_FS_READONLY
DWORD last_clst; /* Last allocated cluster */
DWORD free_clst; /* Number of free clusters */
#endif
#if _FS_RPATH != 0
#if FF_FS_RPATH
DWORD cdir; /* Current directory start cluster (0:root) */
#if _FS_EXFAT
#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) */
@@ -121,53 +159,56 @@ typedef struct {
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[_MAX_SS]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */
BYTE win[FF_MAX_SS]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */
} FATFS;
/* Object ID and allocation information (_FDID) */
/* Object ID and allocation information (FFOBJID) */
typedef struct {
FATFS* fs; /* Pointer to the owner file system object */
WORD id; /* Owner file system mount ID */
BYTE attr; /* Object attribute */
BYTE stat; /* Object chain status (b1-0: =0:not contiguous, =2:contiguous (no data on FAT), =3:flagmented in this session, b2:sub-directory stretched) */
DWORD sclust; /* Object start cluster (0:no cluster or root directory) */
FSIZE_t objsize; /* Object size (valid when sclust != 0) */
#if _FS_EXFAT
DWORD n_cont; /* Size of first fragment, clusters - 1 (valid when stat == 3) */
DWORD n_frag; /* Size of last fragment needs to be written (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 sclust != 0 and non-directory object) */
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 _FS_LOCK != 0
UINT lockid; /* File lock ID origin from 1 (index of file semaphore table Files[]) */
#if FF_FS_LOCK
UINT lockid; /* File lock ID origin from 1 (index of file semaphore table Files[]) */
#endif
} _FDID;
} FFOBJID;
/* File object structure (FIL) */
typedef struct {
_FDID obj; /* Object identifier (must be the 1st member to detect invalid object pointer) */
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 !_FS_READONLY
DWORD dir_sect; /* Sector number containing the directory entry */
BYTE* dir_ptr; /* Pointer to the directory entry in the win[] */
#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 _USE_FASTSEEK
#if FF_USE_FASTSEEK
DWORD* cltbl; /* Pointer to the cluster link map table (nulled on open, set by application) */
#endif
#if !_FS_TINY
BYTE buf[_MAX_SS]; /* File private data read/write window */
#if !FF_FS_TINY
BYTE buf[FF_MAX_SS]; /* File private data read/write window */
#endif
} FIL;
@@ -176,16 +217,16 @@ typedef struct {
/* Directory object structure (DIR) */
typedef struct {
_FDID obj; /* Object identifier */
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 _USE_LFN != 0
#if FF_USE_LFN
DWORD blk_ofs; /* Offset of current entry block being processed (0xFFFFFFFF:Invalid) */
#endif
#if _USE_FIND
#if FF_USE_FIND
const TCHAR* pat; /* Pointer to the name matching pattern */
#endif
} DIR;
@@ -199,11 +240,11 @@ typedef struct {
WORD fdate; /* Modified date */
WORD ftime; /* Modified time */
BYTE fattrib; /* File attribute */
#if _USE_LFN != 0
TCHAR altname[13]; /* Altenative file name */
TCHAR fname[_MAX_LFN + 1]; /* Primary file name */
#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[13]; /* File name */
TCHAR fname[12 + 1]; /* File name */
#endif
} FILINFO;
@@ -230,7 +271,7 @@ typedef enum {
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 > _FS_LOCK */
FR_TOO_MANY_OPEN_FILES, /* (18) Number of open files > FF_FS_LOCK */
FR_INVALID_PARAMETER /* (19) Given parameter is invalid */
} FRESULT;
@@ -268,6 +309,7 @@ FRESULT f_expand (FIL* fp, FSIZE_t szf, BYTE opt); /* Allocate a contiguous
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 */
@@ -280,6 +322,7 @@ TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the fil
#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)
@@ -292,26 +335,27 @@ TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the fil
/* Additional user defined functions */
/* RTC function */
#if !_FS_READONLY && !_FS_NORTC
#if !FF_FS_READONLY && !FF_FS_NORTC
DWORD get_fattime (void);
#endif
/* Unicode support functions */
#if _USE_LFN != 0 /* Unicode - OEM code conversion */
WCHAR ff_convert (WCHAR chr, UINT dir); /* OEM-Unicode bidirectional conversion */
WCHAR ff_wtoupper (WCHAR chr); /* Unicode upper-case conversion */
#if _USE_LFN == 3 /* Memory functions */
/* 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
#endif
/* Sync functions */
#if _FS_REENTRANT
int ff_cre_syncobj (BYTE vol, _SYNC_t* sobj); /* Create a sync object */
int ff_req_grant (_SYNC_t sobj); /* Lock sync object */
void ff_rel_grant (_SYNC_t sobj); /* Unlock sync object */
int ff_del_syncobj (_SYNC_t sobj); /* Delete a sync object */
#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
@@ -358,4 +402,4 @@ int ff_del_syncobj (_SYNC_t sobj); /* Delete a sync object */
}
#endif
#endif /* _FATFS */
#endif /* FF_DEFINED */

View File

@@ -1,67 +1,66 @@
/*---------------------------------------------------------------------------/
/ FatFs - FAT file system module configuration file
/ FatFs Functional Configurations
/---------------------------------------------------------------------------*/
#define _FFCONF 68300 /* Revision ID */
#define FFCONF_DEF 86604 /* Revision ID */
/*---------------------------------------------------------------------------/
/ Function Configurations
/---------------------------------------------------------------------------*/
#define _FS_READONLY 0
#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 _FS_MINIMIZE 0
#define FF_FS_MINIMIZE 0
/* This option defines minimization level to remove some basic API functions.
/
/ 0: All basic functions are enabled.
/ 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 _USE_STRFUNC 0
/* This option switches string functions, f_gets(), f_putc(), f_puts() and
/ f_printf().
#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 _USE_FIND 1
#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 _USE_MKFS 0
#define FF_USE_MKFS 0
/* This option switches f_mkfs() function. (0:Disable or 1:Enable) */
#define _USE_FASTSEEK 0
#define FF_USE_FASTSEEK 0
/* This option switches fast seek function. (0:Disable or 1:Enable) */
#define _USE_EXPAND 0
#define FF_USE_EXPAND 0
/* This option switches f_expand function. (0:Disable or 1:Enable) */
#define _USE_CHMOD 0
#define FF_USE_CHMOD 0
/* This option switches attribute manipulation functions, f_chmod() and f_utime().
/ (0:Disable or 1:Enable) Also _FS_READONLY needs to be 0 to enable this option. */
/ (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */
#define _USE_LABEL 0
#define FF_USE_LABEL 0
/* This option switches volume label functions, f_getlabel() and f_setlabel().
/ (0:Disable or 1:Enable) */
#define _USE_FORWARD 0
#define FF_USE_FORWARD 0
/* This option switches f_forward() function. (0:Disable or 1:Enable) */
@@ -69,11 +68,10 @@
/ Locale and Namespace Configurations
/---------------------------------------------------------------------------*/
#define _CODE_PAGE 437
#define FF_CODE_PAGE 437
/* This option specifies the OEM code page to be used on the target system.
/ Incorrect setting of the code page can cause a file open failure.
/ Incorrect code page setting can cause a file open failure.
/
/ 1 - ASCII (No support of extended character. Non-LFN cfg. only)
/ 437 - U.S.
/ 720 - Arabic
/ 737 - Greek
@@ -95,47 +93,65 @@
/ 936 - Simplified Chinese (DBCS)
/ 949 - Korean (DBCS)
/ 950 - Traditional Chinese (DBCS)
/ 0 - Include all code pages above and configured by f_setcp()
*/
#define _USE_LFN 2
#define _MAX_LFN 255
/* The _USE_LFN switches the support of long file name (LFN).
#define FF_USE_LFN 2
#define FF_MAX_LFN 255
/* The FF_USE_LFN switches the support for LFN (long file name).
/
/ 0: Disable support of LFN. _MAX_LFN has no effect.
/ 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, Unicode handling functions (option/unicode.c) must be added
/ to the project. The working buffer occupies (_MAX_LFN + 1) * 2 bytes and
/ additional 608 bytes at exFAT enabled. _MAX_LFN can be in range from 12 to 255.
/ It should be set 255 to support full featured LFN operations.
/ 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(), must be added to the project. */
/ ff_memfree() in ffsystem.c, need to be added to the project. */
#define _LFN_UNICODE 0
/* This option switches character encoding on the API. (0:ANSI/OEM or 1:UTF-16)
/ To use Unicode string for the path name, enable LFN and set _LFN_UNICODE = 1.
/ This option also affects behavior of string I/O functions. */
#define _STRF_ENCODE 3
/* When _LFN_UNICODE == 1, this option selects the character encoding ON THE FILE to
/ be read/written via string I/O functions, f_gets(), f_putc(), f_puts and f_printf().
#define FF_LFN_UNICODE 2
/* This option switches the character encoding on the API when LFN is enabled.
/
/ 0: ANSI/OEM
/ 1: UTF-16LE
/ 2: UTF-16BE
/ 3: UTF-8
/ 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)
/
/ This option has no effect when _LFN_UNICODE == 0. */
/ Also behavior of string I/O functions will be affected by this option.
/ When LFN is not enabled, this option has no effect. */
#define _FS_RPATH 1
/* This option configures support of relative path.
#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.
@@ -147,45 +163,50 @@
/ Drive/Volume Configurations
/---------------------------------------------------------------------------*/
#define _VOLUMES 2
#define FF_VOLUMES 2
/* Number of volumes (logical drives) to be used. (1-10) */
#define _STR_VOLUME_ID 0
#define _VOLUME_STRS "RAM","NAND","CF","SD","SD2","USB","USB2","USB3"
/* _STR_VOLUME_ID switches string support of volume ID.
/ When _STR_VOLUME_ID is set to 1, also pre-defined strings can be used as drive
/ number in the path name. _VOLUME_STRS defines the drive ID strings for each
/ logical drives. Number of items must be equal to _VOLUMES. Valid characters for
/ the drive ID strings are: A-Z and 0-9. */
#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 _MULTI_PARTITION 0
/* This option switches support of multi-partition on a physical drive.
#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 multi-partition is enabled (1), each logical drive number can be bound to
/ 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 _MIN_SS 512
#define _MAX_SS 512
/* These options configure the range of sector size to be supported. (512, 1024,
/ 2048 or 4096) Always set both 512 for most systems, generic memory card and
#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 _MAX_SS is larger than _MIN_SS, FatFs is configured
/ to variable sector size and GET_SECTOR_SIZE command needs to be implemented to
/ the disk_ioctl() function. */
/ 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 _USE_TRIM 0
/* This option switches support of ATA-TRIM. (0:Disable or 1:Enable)
#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 _FS_NOFSINFO 0
#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.
@@ -202,36 +223,36 @@
/ System Configurations
/---------------------------------------------------------------------------*/
#define _FS_TINY 0
#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 _MAX_SS bytes.
/ 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 file system object (FATFS) is used for the file data transfer. */
/ buffer in the filesystem object (FATFS) is used for the file data transfer. */
#define _FS_EXFAT 0
/* This option switches support of exFAT file system. (0:Disable or 1:Enable)
/ When enable exFAT, also LFN needs to be enabled. (_USE_LFN >= 1)
#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 _FS_NORTC 1
#define _NORTC_MON 1
#define _NORTC_MDAY 1
#define _NORTC_YEAR 2017
/* The option _FS_NORTC switches timestamp functiton. If the system does not have
/ any RTC function or valid timestamp is not needed, set _FS_NORTC = 1 to disable
/ the timestamp function. All objects modified by FatFs will have a fixed timestamp
/ defined by _NORTC_MON, _NORTC_MDAY and _NORTC_YEAR in local time.
/ To enable timestamp function (_FS_NORTC = 0), get_fattime() function need to be
/ added to the project to get current time form real-time clock. _NORTC_MON,
/ _NORTC_MDAY and _NORTC_YEAR have no effect.
/ These options have no effect at read-only configuration (_FS_READONLY = 1). */
#define FF_FS_NORTC 0
#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 _FS_LOCK 0
/* The option _FS_LOCK switches file lock function to control duplicated file open
/ and illegal operation to open objects. This option must be 0 when _FS_READONLY
#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
@@ -241,28 +262,27 @@
/ lock control is independent of re-entrancy. */
#define _FS_REENTRANT 0
#define _FS_TIMEOUT 1000
#define _SYNC_t HANDLE
/* The option _FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs
/* #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. _FS_TIMEOUT and _SYNC_t have no effect.
/ 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 _FS_TIMEOUT defines timeout period in unit of time tick.
/ The _SYNC_t defines O/S dependent sync object type. e.g. HANDLE, ID, OS_EVENT*,
/ 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. */
/* #include <windows.h> // O/S definitions */
/*--- 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

@@ -2,8 +2,8 @@
/* Integer type definitions for FatFs module */
/*-------------------------------------------*/
#ifndef _FF_INTEGER
#define _FF_INTEGER
#ifndef FF_INTEGER
#define FF_INTEGER
#ifdef _WIN32 /* FatFs development platform */

View File

@@ -291,6 +291,8 @@ static u32 calcSDSize(u8 *csd, int type)
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
@@ -474,7 +476,7 @@ u32 sdmmc_sdcard_init()
{
u32 ret = 0;
InitSD();
if(Nand_Init() != 0) ret &= 1;
if(SD_Init() != 0) ret &= 2;
if(Nand_Init() != 0) ret |= 1;
if(SD_Init() != 0) ret |= 2;
return ret;
}
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -31,363 +31,14 @@
#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 "../build/bundled.h"
#include "chainloader.h"
static inline bool loadFirmFromStorage(FirmwareType firmType)
{
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, firmType == NATIVE_FIRM1X2X ? firmwareFiles[0] : firmwareFiles[(u32)firmType], 0x400000 + sizeof(Cxi) + 0x200);
if(!firmSize) return false;
if(firmSize <= sizeof(Cxi) + 0x200) error("The FIRM in /luma is not valid.");
if(memcmp(firm, "FIRM", 4) != 0)
{
u8 cetk[0xA50];
if(fileRead(cetk, firmType == NATIVE_FIRM1X2X ? cetkFiles[0] : cetkFiles[(u32)firmType], sizeof(cetk)) != sizeof(cetk) ||
!decryptNusFirm((Ticket *)(cetk + 0x140), (Cxi *)firm, firmSize))
error("The FIRM in /luma is encrypted or corrupted.");
}
//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 FIRM in /luma is not for this console.");
return true;
}
static inline void mergeSection0(FirmwareType firmType, bool loadFromStorage)
{
u32 srcModuleSize;
const char *extModuleSizeError = "The external FIRM modules are too large.";
u32 nbModules = 0,
isCustomModule = false;
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)
{
//2) Merge that info with our own modules'
for(u8 *src = (u8 *)0x1FF60000; src < (u8 *)(0x1FF60000 + LUMA_SECTION0_SIZE); src += srcModuleSize)
{
const char *name = ((Cxi *)src)->exHeader.systemControlInfo.appTitle;
u32 i;
for(i = 0; i < nbModules && memcmp(name, moduleList[i].name, 8) != 0; i++);
if(i == nbModules) isCustomModule = true;
memcpy(moduleList[i].name, ((Cxi *)src)->exHeader.systemControlInfo.appTitle, 8);
moduleList[i].src = src;
srcModuleSize = moduleList[i].size = ((Cxi *)src)->ncch.contentSize * 0x200;
}
if(isCustomModule) nbModules++;
}
//3) Read or copy the modules
u8 *dst = firm->section[0].address;
for(u32 i = 0, dstModuleSize; i < nbModules; i++)
{
dstModuleSize = 0;
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 > 0x60000) 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.");
dst += dstModuleSize;
}
}
if(!dstModuleSize)
{
memcpy(dst, moduleList[i].src, moduleList[i].size);
dst += moduleList[i].size;
}
}
//4) Patch NATIVE_FIRM if necessary
if(isCustomModule)
{
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 loadFirm(FirmwareType *firmType, FirmwareSource nandType, bool loadFromStorage, bool isSafeMode)
{
//Load FIRM from CTRNAND
u32 firmVersion = firmRead(firm, (u32)*firmType);
if(firmVersion == 0xFFFFFFFF) error("Failed to get the CTRNAND FIRM.");
bool mustLoadFromStorage = false;
if(!ISN3DS && *firmType == NATIVE_FIRM && !ISDEVUNIT)
{
if(firmVersion < 0x18)
{
//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;
}
//We can't boot a 3.x/4.x NATIVE_FIRM, load one from SD/CTRNAND
else if(firmVersion < 0x25) mustLoadFromStorage = true;
}
if((loadFromStorage || mustLoadFromStorage) && loadFirmFromStorage(*firmType)) firmVersion = 0xFFFFFFFF;
else
{
if(mustLoadFromStorage) error("An old unsupported FIRM has been detected.\nCopy a firmware.bin in /luma to boot.");
if(!decryptExeFs((Cxi *)firm)) error("The CTRNAND FIRM is corrupted.");
if(ISDEVUNIT) firmVersion = 0xFFFFFFFF;
}
return firmVersion;
}
u32 patchNativeFirm(u32 firmVersion, FirmwareSource nandType, bool loadFromStorage, bool isSafeMode, bool doUnitinfoPatch, bool enableExceptionHandlers)
{
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;
installMMUHook(arm11Section1, firm->section[1].size, &freeK11Space);
installK11MainHook(arm11Section1, firm->section[1].size, isSafeMode, baseK11VA, arm11SvcTable, arm11ExceptionsPage, &freeK11Space);
installSvcConnectToPortInitHook(arm11SvcTable, arm11ExceptionsPage, &freeK11Space);
installSvcCustomBackdoor(arm11SvcTable, &freeK11Space, 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);
//Apply FIRM0/1 writes patches on SysNAND to protect A9LH
else 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);
}
//11.0 FIRM patches
if(firmVersion >= (ISN3DS ? 0x21 : 0x52))
{
//Apply anti-anti-DG patches
ret += patchTitleInstallMinVersionChecks(process9Offset, process9Size, firmVersion);
}
//Apply UNITINFO patches
if(doUnitinfoPatch)
{
ret += patchUnitInfoValueSet(arm9Section, kernel9Size);
if(!ISDEVUNIT) ret += patchCheckForDevCommonKey(process9Offset, process9Size);
}
if(enableExceptionHandlers)
{
//ARM9 exception handlers
ret += patchArm9ExceptionHandlersInstall(arm9Section, kernel9Size);
ret += patchSvcBreak9(arm9Section, kernel9Size, (u32)firm->section[2].address);
ret += patchKernel9Panic(arm9Section, kernel9Size);
}
if(CONFIG(PATCHACCESS))
ret += patchP9AccessChecks(process9Offset, process9Size);
mergeSection0(NATIVE_FIRM, 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, 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, true);
firm->section[0].size = 0;
}
return ret;
}
u32 patch1x2xNativeAndSafeFirm(bool enableExceptionHandlers)
{
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);
if(enableExceptionHandlers)
{
//ARM9 exception handlers
ret += patchArm9ExceptionHandlersInstall(arm9Section, kernel9Size);
ret += patchSvcBreak9(arm9Section, kernel9Size, (u32)firm->section[2].address);
}
return ret;
}
static Firm *firm = (Firm *)0x20001000;
static __attribute__((noinline)) bool overlaps(u32 as, u32 ae, u32 bs, u32 be)
{
@@ -405,9 +56,9 @@ static __attribute__((noinline)) bool inRange(u32 as, u32 ae, u32 bs, u32 be)
return false;
}
bool checkFirmPayload(u32 payloadSize)
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
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,
@@ -417,7 +68,7 @@ bool checkFirmPayload(u32 payloadSize)
for(u32 i = 0; i < 4; i++)
size += firm->section[i].size;
if(size != payloadSize) return false;
if(firmSize < size) return false;
for(u32 i = 0; i < 4; i++)
{
@@ -454,14 +105,457 @@ bool checkFirmPayload(u32 payloadSize)
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;
}
// SAFE_FIRM only for N3DS and only if ENABLESAFEFIRMROSALINA is on
if((firmType == NATIVE_FIRM || firmType == SAFE_FIRM) && (ISN3DS || firmVersion >= 0x1D))
{
//2) Merge that info with our own modules'
for(u8 *src = (u8 *)0x18180000; memcmp(((Cxi *)src)->ncch.magic, "NCCH", 4) == 0; 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.";
// SAFE_FIRM only for N3DS and only if ENABLESAFEFIRMROSALINA is on
u32 maxModuleSize = (firmType == NATIVE_FIRM || firmType == SAFE_FIRM) ? 0x80000 : 0x600000;
for(u32 i = 0, dstModuleSize; 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/SAFE_FIRM (N3DS) 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 with UNITINFO patch on to prevent NIM from actually sending any
if(doUnitinfoPatch && firmVersion >= (ISN3DS ? 0x35 : 0x64)) ret += patchP9AMTicketWrapperZeroKeyIV(process9Offset, process9Size, firmVersion);
//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);
if(ISN3DS && CONFIG(ENABLESAFEFIRMROSALINA))
{
u8 *arm11Section1 = (u8 *)firm + firm->section[1].offset;
//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);
ret += installK11Extension(arm11Section1, firm->section[1].size, false, baseK11VA, arm11ExceptionsPage, &freeK11Space);
ret += patchKernel11(arm11Section1, firm->section[1].size, baseK11VA, arm11SvcTable, arm11ExceptionsPage);
// Add some other patches to the mix, as we can now launch homebrew on SAFE_FIRM:
//Apply firmlaunch patches
//Or don't, this makes usm not work
//ret += patchFirmlaunches(process9Offset, process9Size, process9MemAddr);
ret += patchKernel9Panic(arm9Section, kernel9Size);
ret += patchP9AccessChecks(process9Offset, process9Size);
mergeSection0(NATIVE_FIRM, 0x45, false); // may change in the future
firm->section[0].size = 0;
}
return ret;
}
void launchFirm(int argc, char **argv)
{
u32 *chainloaderAddress = (u32 *)0x01FF9000;
prepareArm11ForFirmlaunch();
memcpy(chainloaderAddress, chainloader_bin, chainloader_bin_size);
// No need to flush caches here, the chainloader is in ITCM
((void (*)(int, char **, u32))chainloaderAddress)(argc, argv, 0x0000BEEF);
chainload(argc, argv, firm);
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -29,13 +29,10 @@
#include "types.h"
#include "3dsheaders.h"
static Firm *const firm = (Firm *const)0x20001000;
u32 loadFirm(FirmwareType *firmType, FirmwareSource nandType, bool loadFromStorage, bool isSafeMode);
u32 patchNativeFirm(u32 firmVersion, FirmwareSource nandType, bool loadFromStorage, bool isSafeMode, bool doUnitinfoPatch, bool enableExceptionHandlers);
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(bool enableExceptionHandlers);
bool checkFirmPayload(u32 payloadSize);
u32 patch1x2xNativeAndSafeFirm(void);
void launchFirm(int argc, char **argv);

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -59,7 +59,7 @@ This code is based on a file that contains the following:
//TuxSH's changes: add support for 64-bit numbers, remove floating-point code
#include "strings.h"
#include "memory.h"
#include "fmt.h"
#define ZEROPAD (1<<0) //Pad with zero
@@ -148,7 +148,7 @@ static char *processNumber(char *str, s64 num, bool isHex, s32 size, s32 precisi
return str;
}
u32 vsprintf(char *buf, const char *fmt, va_list args)
int vsprintf(char *buf, const char *fmt, va_list args)
{
char *str;
@@ -218,7 +218,7 @@ u32 vsprintf(char *buf, const char *fmt, va_list args)
fmt++;
integerType = 1;
}
}
else if(*fmt == 'h')
{
@@ -263,7 +263,7 @@ u32 vsprintf(char *buf, const char *fmt, va_list args)
//Integer number formats - set up the flags and "break"
case 'X':
flags |= UPPERCASE;
//Falls through
case 'x':
isHex = true;
break;
@@ -271,7 +271,7 @@ u32 vsprintf(char *buf, const char *fmt, va_list args)
case 'd':
case 'i':
flags |= SIGN;
//Falls through
case 'u':
isHex = false;
break;
@@ -306,14 +306,14 @@ u32 vsprintf(char *buf, const char *fmt, va_list args)
}
*str = 0;
return str - buf;
return (int)(str - buf);
}
u32 sprintf(char *buf, const char *fmt, ...)
int sprintf(char *buf, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
u32 res = vsprintf(buf, fmt, args);
int res = vsprintf(buf, fmt, args);
va_end(args);
return res;
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -28,5 +28,5 @@
#include "memory.h"
#include <stdarg.h>
u32 vsprintf(char *buf, const char *fmt, va_list args);
u32 sprintf(char *buf, const char *fmt, ...);
int vsprintf(char *buf, const char *fmt, va_list args);
int sprintf(char *buf, const char *fmt, ...);

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -26,19 +26,17 @@
#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 "config.h"
#include "fatfs/ff.h"
#include "buttons.h"
#include "firm.h"
#include "crypto.h"
#include "../build/bundled.h"
#include "strings.h"
static FATFS sdFs,
nandFs;
@@ -52,8 +50,7 @@ static bool switchToMainDir(bool isSd)
case FR_OK:
return true;
case FR_NO_PATH:
f_mkdir(mainDir);
return switchToMainDir(isSd);
return f_mkdir(mainDir) == FR_OK && switchToMainDir(isSd);
default:
return false;
}
@@ -68,6 +65,7 @@ bool mountFs(bool isSd, bool switchToCtrNand)
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;
@@ -75,10 +73,10 @@ u32 fileRead(void *dest, const char *path, u32 maxSize)
u32 size = f_size(&file);
if(dest == NULL) ret = size;
else if(size <= maxSize)
f_read(&file, dest, size, (unsigned int *)&ret);
f_close(&file);
result = f_read(&file, dest, size, (unsigned int *)&ret);
result |= f_close(&file);
return ret;
return result == FR_OK ? ret : 0;
}
u32 getFileSize(const char *path)
@@ -89,17 +87,18 @@ u32 getFileSize(const char *path)
bool fileWrite(const void *buffer, const char *path, u32 size)
{
FIL file;
FRESULT result = FR_OK;
switch(f_open(&file, path, FA_WRITE | FA_OPEN_ALWAYS))
{
case FR_OK:
{
unsigned int written;
f_write(&file, buffer, size, &written);
f_truncate(&file);
f_close(&file);
result = f_write(&file, buffer, size, &written);
if(result == FR_OK) result = f_truncate(&file);
result |= f_close(&file);
return (u32)written == size;
return result == FR_OK && (u32)written == size;
}
case FR_NO_PATH:
for(u32 i = 1; path[i] != 0; i++)
@@ -108,82 +107,58 @@ bool fileWrite(const void *buffer, const char *path, u32 size)
char folder[i + 1];
memcpy(folder, path, i);
folder[i] = 0;
f_mkdir(folder);
result = f_mkdir(folder);
}
return fileWrite(buffer, path, size);
return result == FR_OK && fileWrite(buffer, path, size);
default:
return false;
}
}
void fileDelete(const char *path)
bool fileDelete(const char *path)
{
f_unlink(path);
return f_unlink(path) == FR_OK;
}
void loadPayload(u32 pressed, const char *payloadPath)
bool findPayload(char *path, u32 pressed)
{
u32 payloadSize = 0,
maxPayloadSize = (u32)((u8 *)0x27FFE000 - (u8 *)firm);
const char *pattern;
char absPath[24 + _MAX_LFN];
char path[10 + _MAX_LFN];
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");
if(payloadPath == NULL)
{
const char *pattern;
DIR dir;
FILINFO info;
FRESULT result;
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");
result = f_findfirst(&dir, &info, "payloads", pattern);
DIR dir;
FILINFO info;
FRESULT result;
if(result != FR_OK) return false;
result = f_findfirst(&dir, &info, "payloads", pattern);
f_closedir(&dir);
if(result != FR_OK) return;
if(!info.fname[0]) return false;
f_closedir(&dir);
sprintf(path, "payloads/%s", info.fname);
if(!info.fname[0]) return;
sprintf(path, "payloads/%s", info.fname);
}
else sprintf(path, "%s", payloadPath);
payloadSize = fileRead(firm, path, maxPayloadSize);
if(payloadSize <= 0x200 || !checkFirmPayload(payloadSize)) return;
writeConfig(true);
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);
return true;
}
void payloadMenu(void)
bool payloadMenu(char *path)
{
DIR dir;
char path[62] = "payloads";
if(f_opendir(&dir, path) != FR_OK) return;
if(f_opendir(&dir, "payloads") != FR_OK) return false;
FILINFO info;
u32 payloadNum = 0;
@@ -206,9 +181,7 @@ void payloadMenu(void)
payloadNum++;
}
f_closedir(&dir);
if(!payloadNum) return;
if(f_closedir(&dir) != FR_OK || !payloadNum) return false;
u32 pressed = 0,
selectedPayload = 0;
@@ -230,9 +203,9 @@ void payloadMenu(void)
{
do
{
pressed = waitInput(true);
pressed = waitInput(true) & MENU_BUTTONS;
}
while(!(pressed & MENU_BUTTONS));
while(!pressed);
u32 oldSelectedPayload = selectedPayload;
@@ -264,21 +237,23 @@ void payloadMenu(void)
if(pressed != BUTTON_START)
{
sprintf(path, "payloads/%s.firm", payloadList[selectedPayload]);
loadPayload(0, path);
error("The payload is too large or corrupted.");
return true;
}
while(HID_PAD & MENU_BUTTONS);
wait(2000ULL);
return false;
}
u32 firmRead(void *dest, u32 firmType)
{
const char *firmFolders[][2] = {{"00000002", "20000002"},
{"00000102", "20000102"},
{"00000202", "20000202"},
{"00000003", "20000003"},
{"00000001", "20000001"}};
static const char *firmFolders[][2] = {{"00000002", "20000002"},
{"00000102", "20000102"},
{"00000202", "20000202"},
{"00000003", "20000003"},
{"00000001", "20000001"}};
char folderPath[35],
path[48];
@@ -304,14 +279,12 @@ u32 firmRead(void *dest, u32 firmType)
if(tempVersion < firmVersion) firmVersion = tempVersion;
}
f_closedir(&dir);
if(firmVersion == 0xFFFFFFFF) goto exit;
if(f_closedir(&dir) != FR_OK || firmVersion == 0xFFFFFFFF) goto exit;
//Complete the string with the .app name
sprintf(path, "%s/%08x.app", folderPath, firmVersion);
sprintf(path, "%s/%08lx.app", folderPath, firmVersion);
if(fileRead(dest, path, 0x400000 + sizeof(Cxi) + 0x200) <= sizeof(Cxi) + 0x200) firmVersion = 0xFFFFFFFF;
if(fileRead(dest, path, 0x400000 + sizeof(Cxi) + 0x200) <= sizeof(Cxi) + 0x400) firmVersion = 0xFFFFFFFF;
exit:
return firmVersion;
@@ -326,7 +299,7 @@ void findDumpFile(const char *folderPath, char *fileName)
{
FILINFO info;
sprintf(fileName, "crash_dump_%08u.dmp", n);
sprintf(fileName, "crash_dump_%08lu.dmp", n);
result = f_findfirst(&dir, &info, folderPath, fileName);
if(result != FR_OK || !info.fname[0]) break;

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -34,8 +34,8 @@ 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);
void fileDelete(const char *path);
void loadPayload(u32 pressed, const char *payloadPath);
void payloadMenu(void);
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);

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

@@ -0,0 +1,225 @@
/*
* 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"
#include "utils.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;
}
bool I2C_writeRegBuf(I2cDevice devId, u8 regAddr, const u8 *in, u32 size)
{
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;
}
}
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;
}
bool I2C_writeReg(I2cDevice devId, u8 regAddr, u8 data)
{
return I2C_writeRegBuf(devId, regAddr, &data, 1);
}

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

@@ -0,0 +1,102 @@
#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);
/**
* @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);

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -26,13 +26,13 @@
#pragma once
#define PA_FROM_VA_PTR(addr) PA_PTR(convertVAToPA(addr))
#include "types.h"
#include "utils.h"
extern const u8 emunandPatch[];
extern const u32 emunandPatchSize;
extern u32 emunandPatchSdmmcStructPtr, emunandPatchNandOffset, emunandPatchNcsdHeaderOffset;
Result svc0x2F(void *function, ...); // custom backdoor before kernel ext. is installed (and only before!)
void *convertVAToPA(const void *VA);
extern u8 kernel_extension[];
extern u32 kernel_extension_size;
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
#define copy_launch_stub_stack_top 0x01FFB800
#define copy_launch_stub_stack_bottom 0x01FFA800
#define copy_launch_stub_addr 0x01FF9000
#define argv_addr (copy_launch_stub_stack_bottom - 0x100)
#define fname_addr (copy_launch_stub_stack_bottom - 0x200)
#define low_tid_addr (copy_launch_stub_stack_bottom - 0x300)
#define firm_addr 0x20001000
#define 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
svc 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)
svc 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
svc 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

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -31,51 +31,95 @@
#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 u8 __itcm_start__[], __itcm_lma__[], __itcm_bss_start__[], __itcm_end__[];
extern CfgData configData;
extern ConfigurationStatus needConfig;
extern FirmwareSource firmSource;
bool isFirmlaunch = false,
isSdMode;
u16 launchedPath[41];
bool isSdMode;
u16 launchedPath[80+1];
BootType bootType;
void main(int argc, char **argv, u32 magicWord)
{
bool isSafeMode = false,
isNoForceFlagSet = false;
bool isFirmProtEnabled,
isSafeMode = false,
needToInitSd = false,
isNoForceFlagSet = false,
isInvalidLoader = false,
isNtrBoot;
FirmwareType firmType;
FirmwareSource nandType;
const vu8 *bootMediaStatus = (const vu8 *)0x1FFFE00C;
const vu32 *bootPartitionsStatus = (const vu32 *)0x1FFFE010;
u32 firmlaunchTidLow = 0;
if((magicWord & 0xFFFF) == 0xBEEF && argc >= 1) //Normal boot
//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 < 40 && argv[0][i] != 0; i++) //Copy and convert the path to UTF-16
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 < 40 && p[i] != 0; i++)
for(i = 0; i < sizeof(launchedPath)/2 - 1 && p[i] != 0; i++)
launchedPath[i] = p[i];
launchedPath[i] = 0;
isFirmlaunch = true;
for(i = 0; i < 8; i++)
firmlaunchTidLow = (argv[1][2 * i] > '9' ? argv[1][2 * i] - 'a' + 10 : argv[1][2 * i] - '0') | (firmlaunchTidLow << 4);
}
else
else if(magicWord == 0xB002) //FIRM/NTRCARD boot
{
const char argv[] = "firm0:";
for(u32 i = 0; i < sizeof(argv); i++) //Copy and convert the path to UTF-16
launchedPath[i] = argv[i];
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 isInvalidLoader = true;
// Set up the additional sections, overwrites argc
memcpy(__itcm_start__, __itcm_lma__, __itcm_bss_start__ - __itcm_start__);
memset(__itcm_bss_start__, 0, __itcm_end__ - __itcm_bss_start__);
I2C_init();
if(isInvalidLoader) error("Launched using an unsupported loader.");
installArm9Handlers();
if(memcmp(launchedPath, u"sdmc", 8) == 0)
{
@@ -84,17 +128,21 @@ void main(int argc, char **argv, u32 magicWord)
}
else if(memcmp(launchedPath, u"nand", 8) == 0)
{
firmSource = FIRMWARE_SYSNAND;
if(!mountFs(false, true)) error("Failed to mount CTRNAND.");
isSdMode = false;
}
else if(memcmp(launchedPath, u"firm", 8) == 0)
else if(bootType == NTR || memcmp(launchedPath, u"firm", 8) == 0)
{
setupKeyslots();
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
{
@@ -108,37 +156,38 @@ void main(int argc, char **argv, u32 magicWord)
error("Launched from an unsupported location: %s.", mountPoint);
}
detectAndProcessExceptionDumps();
//Attempt to read the configuration file
needConfig = readConfig() ? MODIFY_CONFIGURATION : CREATE_CONFIGURATION;
//Determine if this is a firmlaunch boot
if(isFirmlaunch)
if(bootType == FIRMLAUNCH)
{
if(needConfig == CREATE_CONFIGURATION) mcuPowerOff();
switch(argv[1][14])
switch(firmlaunchTidLow & 0xF)
{
case '2':
firmType = (FirmwareType)(argv[1][10] - '0');
case 2:
firmType = (FirmwareType)((firmlaunchTidLow >> 8) & 0xF);
break;
case '3':
case 3:
firmType = SAFE_FIRM;
break;
case '1':
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;
@@ -146,7 +195,6 @@ void main(int argc, char **argv, u32 magicWord)
//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)
{
@@ -154,14 +202,21 @@ void main(int argc, char **argv, u32 magicWord)
firmSource = (BOOTCFG_NAND != 0) == (BOOTCFG_FIRM != 0) ? FIRMWARE_SYSNAND : (FirmwareSource)BOOTCFG_FIRM;
//Prevent multiple boot options-forcing
isNoForceFlagSet = true;
if(nandType != BOOTCFG_NAND || firmSource != BOOTCFG_FIRM) isNoForceFlagSet = true;
goto boot;
}
/* Else, force the last used boot options unless a button is pressed
//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(!pressed && !BOOTCFG_NOFORCEFLAG)
if(needToInitSd || memcmp((void *)0x20000300, "TLNC", 4) == 0 || (!pressed && !BOOTCFG_NOFORCEFLAG))
{
nandType = (FirmwareSource)BOOTCFG_NAND;
firmSource = (FirmwareSource)BOOTCFG_FIRM;
@@ -171,11 +226,21 @@ void main(int argc, char **argv, u32 magicWord)
}
u32 pinMode = MULTICONFIG(PIN);
bool shouldLoadConfigMenu = needConfig == CREATE_CONFIGURATION || ((pressed & (BUTTON_SELECT | BUTTON_L1)) == BUTTON_SELECT);
bool pinExists = pinMode != 0 && verifyPin(pinMode);
//If no configuration file exists or SELECT is held, load configuration menu
bool shouldLoadConfigMenu = needConfig == CREATE_CONFIGURATION || ((pressed & (BUTTON_SELECT | BUTTON_L1)) == BUTTON_SELECT);
/* If the PIN has been verified, wait to make it easier to press the SAFE_MODE combo or the configuration menu button
(if not already pressed, for the latter) */
if(pinExists && !shouldLoadConfigMenu)
{
while(HID_PAD & PIN_BUTTONS);
wait(2000ULL);
//Update pressed buttons
pressed = HID_PAD;
}
shouldLoadConfigMenu = needConfig == CREATE_CONFIGURATION || ((pressed & (BUTTON_SELECT | BUTTON_L1)) == BUTTON_SELECT);
if(shouldLoadConfigMenu)
{
configMenu(pinExists, pinMode);
@@ -190,13 +255,7 @@ void main(int argc, char **argv, u32 magicWord)
firmSource = FIRMWARE_SYSNAND;
isSafeMode = 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);
}
needToInitSd = true;
goto boot;
}
@@ -205,15 +264,29 @@ void main(int argc, char **argv, u32 magicWord)
if(splashMode == 1 && loadSplash()) pressed = HID_PAD;
bool autoBootEmu = CONFIG(AUTOBOOTEMU);
if((pressed & (BUTTON_START | BUTTON_L1)) == BUTTON_START)
{
payloadMenu();
loadHomebrewFirm(0);
pressed = HID_PAD;
}
else if(((pressed & SINGLE_PAYLOAD_BUTTONS) && !(pressed & (BUTTON_L1 | BUTTON_R1 | BUTTON_A))) ||
((pressed & L_PAYLOAD_BUTTONS) && (pressed & BUTTON_L1))) loadPayload(pressed, NULL);
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(splashMode == 2 && loadSplash()) pressed = HID_PAD;
//Check SAFE_MODE combo again
if(!CFG_BOOTENV && pressed == SAFE_MODE)
{
nandType = FIRMWARE_SYSNAND;
firmSource = FIRMWARE_SYSNAND;
isSafeMode = true;
needToInitSd = true;
goto boot;
}
//If booting from CTRNAND, always use SysNAND
if(!isSdMode) nandType = FIRMWARE_SYSNAND;
@@ -235,7 +308,7 @@ void main(int argc, char **argv, u32 magicWord)
/* Else, boot the NAND the user set to autoboot or the opposite one, depending on L,
with their own FIRM */
else firmSource = nandType = (CONFIG(AUTOBOOTEMU) == ((pressed & BUTTON_L1) == BUTTON_L1)) ? FIRMWARE_SYSNAND : FIRMWARE_EMUNAND;
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)
@@ -271,29 +344,29 @@ boot:
{
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(!isFirmlaunch)
if(bootType != FIRMLAUNCH)
{
configData.config = (configData.config & 0xFFFFFF80) | ((u32)isNoForceFlagSet << 6) | ((u32)firmSource << 3) | (u32)nandType;
configData.bootConfig = ((bootType == NTR ? 1 : 0) << 7) | ((u32)isNoForceFlagSet << 6) | ((u32)firmSource << 3) | (u32)nandType;
writeConfig(false);
}
if(isSdMode && !mountFs(false, false)) error("Failed to mount CTRNAND.");
bool loadFromStorage = CONFIG(LOADEXTFIRMSANDMODULES);
u32 firmVersion = loadFirm(&firmType, firmSource, loadFromStorage, isSafeMode);
u32 firmVersion = loadNintendoFirm(&firmType, firmSource, loadFromStorage, isSafeMode);
bool doUnitinfoPatch = CONFIG(PATCHUNITINFO), enableExceptionHandlers = CONFIG(PATCHUNITINFO);
u32 res;
bool doUnitinfoPatch = CONFIG(PATCHUNITINFO);
u32 res = 0;
switch(firmType)
{
case NATIVE_FIRM:
res = patchNativeFirm(firmVersion, nandType, loadFromStorage, isSafeMode, doUnitinfoPatch, enableExceptionHandlers);
res = patchNativeFirm(firmVersion, nandType, loadFromStorage, isFirmProtEnabled, needToInitSd, doUnitinfoPatch);
break;
case TWL_FIRM:
res = patchTwlFirm(firmVersion, loadFromStorage, doUnitinfoPatch);
@@ -304,12 +377,12 @@ boot:
case SAFE_FIRM:
case SYSUPDATER_FIRM:
case NATIVE_FIRM1X2X:
res = patch1x2xNativeAndSafeFirm(enableExceptionHandlers);
res = patch1x2xNativeAndSafeFirm();
break;
}
if(res != 0) error("Failed to apply %u FIRM patch(es).", res);
if(!isFirmlaunch) deinitScreens();
if(bootType != FIRMLAUNCH) deinitScreens();
launchFirm(0, NULL);
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -26,51 +26,11 @@
/*
* 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
* memcpy, memset 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 value, u32 size)
{
u8 *destc = (u8 *)dest;
for(u32 i = 0; i < size; i++) destc[i] = (u8)value;
return dest;
}
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;

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

@@ -0,0 +1,36 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2020 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
*/
#pragma once
#include <string.h>
#include "types.h"
u8 *memsearch(u8 *startPos, const void *pattern, u32 size, u32 patternSize);

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -39,7 +39,10 @@
#include "memory.h"
#include "config.h"
#include "utils.h"
#include "../build/bundled.h"
#include "arm9_exception_handlers.h"
#include "large_patches.h"
#define K11EXT_VA 0x70000000
u8 *getProcess9Info(u8 *pos, u32 size, u32 *process9Size, u32 *process9MemAddr)
{
@@ -57,7 +60,7 @@ u8 *getProcess9Info(u8 *pos, u32 size, u32 *process9Size, u32 *process9MemAddr)
u32 *getKernel11Info(u8 *pos, u32 size, u32 *baseK11VA, u8 **freeK11Space, u32 **arm11SvcHandler, u32 **arm11ExceptionsPage)
{
const u8 pattern[] = {0x00, 0xB0, 0x9C, 0xE5};
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.");
@@ -78,120 +81,204 @@ u32 *getKernel11Info(u8 *pos, u32 size, u32 *baseK11VA, u8 **freeK11Space, u32 *
return arm11SvcTable;
}
void installMMUHook(u8 *pos, u32 size, u8 **freeK11Space)
// 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 u8 pattern[] = {0x0E, 0x32, 0xA0, 0xE3, 0x02, 0xC2, 0xA0, 0xE3};
const u32 *off;
u32 *off = (u32 *)memsearch(pos, pattern, size, 8);
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;
memcpy(*freeK11Space, mmuHook_bin, mmuHook_bin_size);
*off = MAKE_BRANCH_LINK(off, *freeK11Space);
(*freeK11Space) += mmuHook_bin_size;
return 4 * nbPushedRegs + localVariablesSpaceSize;
}
void installK11MainHook(u8 *pos, u32 size, bool isSafeMode, u32 baseK11VA, u32 *arm11SvcTable, u32 *arm11ExceptionsPage, u8 **freeK11Space)
static inline u32 *getKernel11HandlerVAPos(u8 *pos, u32 *arm11ExceptionsPage, u32 baseK11VA, u32 id)
{
const u8 pattern[] = {0x00, 0x00, 0xA0, 0xE1, 0x03, 0xF0, 0x20, 0xE3, 0xFD, 0xFF, 0xFF, 0xEA};
u32 off = ((-((arm11ExceptionsPage[id] & 0xFFFFFF) << 2)) & (0xFFFFFF << 2)) - 8;
u32 pointedInstructionVA = 0xFFFF0000 + 4 * id - off;
return (u32 *)(pos + pointedInstructionVA - baseK11VA + 8);
}
u32 *off = (u32 *)memsearch(pos, pattern, size, 12);
// look for cpsie i and place our function call in the nop 2 instructions before
while(*off != 0xF1080080) off--;
off -= 2;
memcpy(*freeK11Space, k11MainHook_bin, k11MainHook_bin_size);
u32 relocBase = 0xFFFF0000 + (*freeK11Space - (u8 *)arm11ExceptionsPage);
*off = MAKE_BRANCH_LINK(baseK11VA + ((u8 *)off - pos), relocBase);
off = (u32 *)(pos + (arm11SvcTable[0x50] - baseK11VA)); //svcBindInterrupt
while(off[0] != 0xE1A05000 || off[1] != 0xE2100102 || off[2] != 0x5A00000B) off++;
off--;
signed int offset = (*off & 0xFFFFFF) << 2;
offset = offset << 6 >> 6; // sign extend
offset += 8;
u32 InterruptManager_mapInterrupt = baseK11VA + ((u8 *)off - pos) + offset;
u32 interruptManager = *(u32 *)(off - 4 + (*(off - 6) & 0xFFF) / 4);
off = (u32 *)memsearch(*freeK11Space, "bind", k11MainHook_bin_size, 4);
*off++ = InterruptManager_mapInterrupt;
// Relocate stuff
*off++ += relocBase;
*off++ += relocBase;
off++;
*off++ = interruptManager;
off += 10;
struct CfwInfo
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
{
char magic[4];
u32 basePA;
u32 stolenSystemMemRegionSize;
void *originalHandlers[4];
u32 L1MMUTableAddrs[4];
u8 versionMajor;
u8 versionMinor;
u8 versionBuild;
u8 flags;
volatile bool done;
u32 commitHash;
struct CfwInfo
{
char magic[4];
u32 config;
} __attribute__((packed)) *info = (struct CfwInfo *)off;
u8 versionMajor;
u8 versionMinor;
u8 versionBuild;
u8 flags;
const char *rev = REVISION;
u32 commitHash;
u16 configFormatVersionMajor, configFormatVersionMinor;
u32 config, multiConfig, bootConfig;
u64 hbldr3dsxTitleId;
u32 rosalinaMenuCombo;
u32 rosalinaFlags;
} 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 - K11EXT_VA;
u32 stolenSystemMemRegionSize = kextTotalSize; // no need to steal any more mem on N3DS. Currently, everything fits in BASE on O3DS too (?)
u32 dstKextPA = (ISN3DS ? 0x2E000000 : 0x26C00000) - stolenSystemMemRegionSize; // start of BASE memregion (note: linear heap ---> <--- the rest)
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] = K11EXT_VA;
hookVeneers[4] = 0xE51FF004;
hookVeneers[5] = K11EXT_VA + 8;
hookVeneers[6] = 0xE51FF004;
hookVeneers[7] = K11EXT_VA + 0xC;
(*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 - K11EXT_VA + 0x18000000);
p->basePA = dstKextPA;
p->done = false;
p->stolenSystemMemRegionSize = stolenSystemMemRegionSize;
for(u32 i = 0; i < 4; i++)
{
u32 *handlerPos = getKernel11HandlerVAPos(pos, arm11ExceptionsPage, baseK11VA, 1 + i);
p->originalHandlers[i] = (void *)*handlerPos;
*handlerPos = K11EXT_VA + 0x10 + 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->versionMajor = (u8)(rev[1] - '0');
info->versionMinor = (u8)(rev[3] - '0');
info->multiConfig = configData.multiConfig;
info->bootConfig = configData.bootConfig;
info->hbldr3dsxTitleId = configData.hbldr3dsxTitleId;
info->rosalinaMenuCombo = configData.rosalinaMenuCombo;
info->rosalinaFlags = configData.rosalinaFlags;
info->versionMajor = VERSION_MAJOR;
info->versionMinor = VERSION_MINOR;
info->versionBuild = VERSION_BUILD;
if(rev[4] == '.')
info->versionBuild = (u8)(rev[5] - '0');
const char *revpos;
for(revpos = rev + 4; *revpos != 0 && *revpos != '-'; revpos++);
bool isRelease = *revpos != '-';
if(isRelease) info->flags = 1;
if(ISRELEASE) info->flags = 1;
if(ISN3DS) info->flags |= 1 << 4;
if(isSafeMode) info->flags |= 1 << 5;
if(needToInitSd) info->flags |= 1 << 5;
if(isSdMode) info->flags |= 1 << 6;
(*freeK11Space) += k11MainHook_bin_size;
return 0;
}
void installSvcConnectToPortInitHook(u32 *arm11SvcTable, u32 *arm11ExceptionsPage, u8 **freeK11Space)
u32 patchKernel11(u8 *pos, u32 size, u32 baseK11VA, u32 *arm11SvcTable, u32 *arm11ExceptionsPage)
{
u32 addr = 0xFFFF0000 + (u32)*freeK11Space - (u32)arm11ExceptionsPage;
u32 svcSleepThreadAddr = arm11SvcTable[0x0A], svcConnectToPortAddr = arm11SvcTable[0x2D];
static const u8 patternKPanic[] = {0x02, 0x0B, 0x44, 0xE2};
static const u8 patternKThreadDebugReschedule[] = {0x34, 0x20, 0xD4, 0xE5, 0x00, 0x00, 0x55, 0xE3, 0x80, 0x00, 0xA0, 0x13};
arm11SvcTable[0x2D] = addr;
memcpy(*freeK11Space, svcConnectToPortInitHook_bin, svcConnectToPortInitHook_bin_size);
//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
u32 *off = (u32 *)memsearch(*freeK11Space, "orig", svcConnectToPortInitHook_bin_size, 4);
off[0] = svcConnectToPortAddr;
off[1] = svcSleepThreadAddr;
u8 *ControlMemoryPos = instrPos + 8 + displ;
u32 *off;
(*freeK11Space) += svcConnectToPortInitHook_bin_size;
}
// Patch ControlMemory bounds checks for mem mapping
for (off = (u32 *)ControlMemoryPos; *off != 0xE0E01BF5; ++off);
*off = 0;
/*
Here we replace currentProcess->processID == 1 by additionnalParameter == 1.
This patch should be generic enough to work even on firmware version 5.0.
void installSvcCustomBackdoor(u32 *arm11SvcTable, u8 **freeK11Space, u32 *arm11ExceptionsPage)
{
memcpy(*freeK11Space, svcCustomBackdoor_bin, svcCustomBackdoor_bin_size);
*((u32 *)*freeK11Space + 1) = arm11SvcTable[0x2F]; // temporary location
arm11SvcTable[0x2F] = 0xFFFF0000 + *freeK11Space - (u8 *)arm11ExceptionsPage;
(*freeK11Space) += svcCustomBackdoor_bin_size;
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] = K11EXT_VA + 0x28;
off = (u32 *)memsearch(pos, patternKThreadDebugReschedule, size, sizeof(patternKThreadDebugReschedule));
if(off == NULL)
return 1;
off[-5] = 0xE51FF004;
off[-4] = K11EXT_VA + 0x2C;
return 0;
}
u32 patchSignatureChecks(u8 *pos, u32 size)
{
//Look for signature checks
const u8 pattern[] = {0xC0, 0x1C, 0x76, 0xE7},
pattern2[] = {0xB5, 0x22, 0x4D, 0x0C};
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));
@@ -208,8 +295,8 @@ u32 patchSignatureChecks(u8 *pos, u32 size)
u32 patchOldSignatureChecks(u8 *pos, u32 size)
{
// Look for signature checks
const u8 pattern[] = {0xC0, 0x1C, 0xBD, 0xE7},
pattern2[] = {0xB5, 0x23, 0x4E, 0x0C};
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));
@@ -226,10 +313,10 @@ u32 patchOldSignatureChecks(u8 *pos, u32 size)
u32 patchFirmlaunches(u8 *pos, u32 size, u32 process9MemAddr)
{
//Look for firmlaunch code
const u8 pattern[] = {0xE2, 0x20, 0x20, 0x90};
static const u8 pattern[] = {0xE2, 0x20, 0x20, 0x90};
u32 pathLen;
for(pathLen = 0; pathLen < 41 && launchedPath[pathLen] != 0; pathLen++);
for(pathLen = 0; pathLen < sizeof(launchedPath)/2 && launchedPath[pathLen] != 0; pathLen++);
if(launchedPath[pathLen] != 0) return 1;
@@ -239,18 +326,17 @@ u32 patchFirmlaunches(u8 *pos, u32 size, u32 process9MemAddr)
off -= 0x13;
//Firmlaunch function offset - offset in BLX opcode (A4-16 - ARM DDI 0100E) + 1
//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);
//Copy firmlaunch code
memcpy(off, reboot_bin, reboot_bin_size);
//Put the fOpen offset in the right location
u32 *pos_fopen = (u32 *)memsearch(off, "OPEN", reboot_bin_size, 4);
*pos_fopen = fOpenOffset;
rebootPatchFopenPtr = fOpenOffset;
u16 *fname = (u16 *)memsearch(off, "FILE", reboot_bin_size, 8);
memcpy(fname, launchedPath, 2 * (1 + pathLen));
//Copy the launched path
memcpy(rebootPatchFileName, launchedPath, 2 * (1 + pathLen));
//Copy firmlaunch code
memcpy(off, rebootPatch, rebootPatchSize);
return 0;
}
@@ -262,7 +348,7 @@ u32 patchFirmWrites(u8 *pos, u32 size)
if(off == NULL) return 1;
const u8 pattern[] = {0x00, 0x28, 0x01, 0xDA};
static const u8 pattern[] = {0x00, 0x28, 0x01, 0xDA};
u16 *off2 = (u16 *)memsearch(off - 0x100, pattern, 0x100, sizeof(pattern));
@@ -277,7 +363,7 @@ u32 patchFirmWrites(u8 *pos, u32 size)
u32 patchOldFirmWrites(u8 *pos, u32 size)
{
//Look for FIRM writing code
const u8 pattern[] = {0x04, 0x1E, 0x1D, 0xDB};
static const u8 pattern[] = {0x04, 0x1E, 0x1D, 0xDB};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
@@ -291,7 +377,7 @@ u32 patchOldFirmWrites(u8 *pos, u32 size)
u32 patchTitleInstallMinVersionChecks(u8 *pos, u32 size, u32 firmVersion)
{
const u8 pattern[] = {0xFF, 0x00, 0x00, 0x02};
static const u8 pattern[] = {0xFF, 0x00, 0x00, 0x02};
u8 *off = memsearch(pos, pattern, size, sizeof(pattern));
@@ -300,14 +386,14 @@ u32 patchTitleInstallMinVersionChecks(u8 *pos, u32 size, u32 firmVersion)
off++;
//Zero out the first TitleID in the list
memset32(off, 0, 8);
memset(off, 0, 8);
return 0;
}
u32 patchZeroKeyNcchEncryptionCheck(u8 *pos, u32 size)
{
const u8 pattern[] = {0x28, 0x2A, 0xD0, 0x08};
static const u8 pattern[] = {0x28, 0x2A, 0xD0, 0x08};
u8 *temp = memsearch(pos, pattern, size, sizeof(pattern));
@@ -321,7 +407,7 @@ u32 patchZeroKeyNcchEncryptionCheck(u8 *pos, u32 size)
u32 patchNandNcchEncryptionCheck(u8 *pos, u32 size)
{
const u8 pattern[] = {0x07, 0xD1, 0x28, 0x7A};
static const u8 pattern[] = {0x07, 0xD1, 0x28, 0x7A};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
@@ -335,7 +421,7 @@ u32 patchNandNcchEncryptionCheck(u8 *pos, u32 size)
u32 patchCheckForDevCommonKey(u8 *pos, u32 size)
{
const u8 pattern[] = {0x03, 0x7C, 0x28, 0x00};
static const u8 pattern[] = {0x03, 0x7C, 0x28, 0x00};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
@@ -348,8 +434,8 @@ u32 patchCheckForDevCommonKey(u8 *pos, u32 size)
u32 patchK11ModuleLoading(u32 section0size, u32 modulesSize, u8 *pos, u32 size)
{
const u8 moduleLoadingPattern[] = {0xE2, 0x05, 0x00, 0x57},
modulePidPattern[] = {0x06, 0xA0, 0xE1, 0xF2}; //GetSystemInfo
static const u8 moduleLoadingPattern[] = {0xE2, 0x05, 0x00, 0x57},
modulePidPattern[] = {0x06, 0xA0, 0xE1, 0xF2}; //GetSystemInfo
u8 *off = memsearch(pos, moduleLoadingPattern, size, 4);
@@ -362,7 +448,7 @@ u32 patchK11ModuleLoading(u32 section0size, u32 modulesSize, u8 *pos, u32 size)
off32 += 2;
off32[1] = off32[0] + modulesSize;
for(; *off32 != section0size; off32++);
*off32 += ((modulesSize + 0x1FF) >> 9) << 9;
*off32 = ((modulesSize + 0x1FF) >> 9) << 9;
off = memsearch(pos, modulePidPattern, size, 4);
@@ -375,13 +461,15 @@ u32 patchK11ModuleLoading(u32 section0size, u32 modulesSize, u8 *pos, u32 size)
u32 patchArm9ExceptionHandlersInstall(u8 *pos, u32 size)
{
const u8 pattern[] = {0x80, 0xE5, 0x40, 0x1C};
static const u8 pattern[] = {0x80, 0xE5, 0x40, 0x1C};
u8 *temp = memsearch(pos, pattern, size, sizeof(pattern));
if(temp == NULL) return 1;
u32 *off = (u32 *)(temp - 0xA);
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
{
@@ -409,7 +497,7 @@ u32 patchSvcBreak9(u8 *pos, u32 size, u32 kernel9Address)
//Stub svcBreak with "bkpt 65535" so we can debug the panic
//Look for the svc handler
const u8 pattern[] = {0x00, 0xE0, 0x4F, 0xE1}; //mrs lr, spsr
static const u8 pattern[] = {0x00, 0xE0, 0x4F, 0xE1}; //mrs lr, spsr
u32 *arm9SvcTable = (u32 *)memsearch(pos, pattern, size, sizeof(pattern));
@@ -418,20 +506,28 @@ u32 patchSvcBreak9(u8 *pos, u32 size, u32 kernel9Address)
while(*arm9SvcTable != 0) arm9SvcTable++; //Look for SVC0 (NULL)
u32 *addr = (u32 *)(pos + arm9SvcTable[0x3C] - kernel9Address);
*addr = 0xE12FFF7F;
/*
mov r8, sp
bkpt 0xffff
*/
addr[0] = 0xE1A0800D;
addr[1] = 0xE12FFF7F;
arm9ExceptionHandlerSvcBreakAddress = arm9SvcTable[0x3C]; //BreakPtr
return 0;
}
u32 patchKernel9Panic(u8 *pos, u32 size)
{
const u8 pattern[] = {0xFF, 0xEA, 0x04, 0xD0};
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 - 0x12);
u32 *off = (u32 *)(temp - 0x34);
*off = 0xE12FFF7E;
return 0;
@@ -439,7 +535,7 @@ u32 patchKernel9Panic(u8 *pos, u32 size)
u32 patchP9AccessChecks(u8 *pos, u32 size)
{
const u8 pattern[] = {0x00, 0x08, 0x49, 0x68};
static const u8 pattern[] = {0x00, 0x08, 0x49, 0x68};
u8 *temp = memsearch(pos, pattern, size, sizeof(pattern));
@@ -455,7 +551,7 @@ u32 patchP9AccessChecks(u8 *pos, u32 size)
u32 patchUnitInfoValueSet(u8 *pos, u32 size)
{
//Look for UNITINFO value being set during kernel sync
const u8 pattern[] = {0x01, 0x10, 0xA0, 0x13};
static const u8 pattern[] = {0x01, 0x10, 0xA0, 0x13};
u8 *off = memsearch(pos, pattern, size, sizeof(pattern));
@@ -467,9 +563,37 @@ u32 patchUnitInfoValueSet(u8 *pos, u32 size)
return 0;
}
u32 patchP9AMTicketWrapperZeroKeyIV(u8 *pos, u32 size, u32 firmVersion)
{
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));
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
if(function == 0 || off == NULL) return firmVersion == 0xFFFFFFFF ? 0 : 1;
//After the found code it's a BL call (at &off[2]), that will be replaced
//From Thumb, op distance for setting in BLX can be got with,
//(Destination_offset - blx_op_offset+2) / 2
s32 opjumpdistance = (s32)(function - ((u32)&off[3])) / 2;
//Beyond limit
if(opjumpdistance < -0x1fffff || opjumpdistance > 0x1fffff) return 1;
//r0 and r1 for old call are already correct for this one
//BLX __rt_memclr
u32 op = (0xE800F000U | (((u32)opjumpdistance & 0x7FF) << 16) | (((u32)opjumpdistance >> 11) & 0x3FF) | (((u32)opjumpdistance >> 21) & 0x400)) & ~(1<<16);
off[2] = op;
off[3] = op >> 16;
return 0;
}
u32 patchLgySignatureChecks(u8 *pos, u32 size)
{
const u8 pattern[] = {0x47, 0xC1, 0x17, 0x49};
static const u8 pattern[] = {0x47, 0xC1, 0x17, 0x49};
u8 *temp = memsearch(pos, pattern, size, sizeof(pattern));
@@ -485,7 +609,7 @@ u32 patchLgySignatureChecks(u8 *pos, u32 size)
u32 patchTwlInvalidSignatureChecks(u8 *pos, u32 size)
{
const u8 pattern[] = {0x20, 0xF6, 0xE7, 0x7F};
static const u8 pattern[] = {0x20, 0xF6, 0xE7, 0x7F};
u8 *temp = memsearch(pos, pattern, size, sizeof(pattern));
@@ -499,7 +623,7 @@ u32 patchTwlInvalidSignatureChecks(u8 *pos, u32 size)
u32 patchTwlNintendoLogoChecks(u8 *pos, u32 size)
{
const u8 pattern[] = {0xC0, 0x30, 0x06, 0xF0};
static const u8 pattern[] = {0xC0, 0x30, 0x06, 0xF0};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
@@ -513,7 +637,7 @@ u32 patchTwlNintendoLogoChecks(u8 *pos, u32 size)
u32 patchTwlWhitelistChecks(u8 *pos, u32 size)
{
const u8 pattern[] = {0x22, 0x00, 0x20, 0x30};
static const u8 pattern[] = {0x22, 0x00, 0x20, 0x30};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
@@ -527,7 +651,7 @@ u32 patchTwlWhitelistChecks(u8 *pos, u32 size)
u32 patchTwlFlashcartChecks(u8 *pos, u32 size, u32 firmVersion)
{
const u8 pattern[] = {0x25, 0x20, 0x00, 0x0E};
static const u8 pattern[] = {0x25, 0x20, 0x00, 0x0E};
u8 *temp = memsearch(pos, pattern, size, sizeof(pattern));
@@ -547,7 +671,7 @@ u32 patchTwlFlashcartChecks(u8 *pos, u32 size, u32 firmVersion)
u32 patchOldTwlFlashcartChecks(u8 *pos, u32 size)
{
const u8 pattern[] = {0x06, 0xF0, 0xA0, 0xFD};
static const u8 pattern[] = {0x06, 0xF0, 0xA0, 0xFD};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
@@ -561,7 +685,7 @@ u32 patchOldTwlFlashcartChecks(u8 *pos, u32 size)
u32 patchTwlShaHashChecks(u8 *pos, u32 size)
{
const u8 pattern[] = {0x10, 0xB5, 0x14, 0x22};
static const u8 pattern[] = {0x10, 0xB5, 0x14, 0x22};
u16 *off = (u16 *)memsearch(pos, pattern, size, sizeof(pattern));
@@ -575,7 +699,7 @@ u32 patchTwlShaHashChecks(u8 *pos, u32 size)
u32 patchAgbBootSplash(u8 *pos, u32 size)
{
const u8 pattern[] = {0x00, 0x00, 0x01, 0xEF};
static const u8 pattern[] = {0x00, 0x00, 0x01, 0xEF};
u8 *off = memsearch(pos, pattern, size, sizeof(pattern));

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -37,14 +37,10 @@
#include "types.h"
extern CfgData configData;
u8 *getProcess9Info(u8 *pos, u32 size, u32 *process9Size, u32 *process9MemAddr);
u32 *getKernel11Info(u8 *pos, u32 size, u32 *baseK11VA, u8 **freeK11Space, u32 **arm11SvcHandler, u32 **arm11ExceptionsPage);
void installMMUHook(u8 *pos, u32 size, u8 **freeK11Space);
void installK11MainHook(u8 *pos, u32 size, bool isSafeMode, u32 baseK11VA, u32 *arm11SvcTable, u32 *arm11ExceptionsPage, u8 **freeK11Space);
void installSvcConnectToPortInitHook(u32 *arm11SvcTable, u32 *arm11ExceptionsPage, u8 **freeK11Space);
void installSvcCustomBackdoor(u32 *arm11SvcTable, u8 **freeK11Space, 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);
@@ -60,6 +56,7 @@ 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 patchP9AMTicketWrapperZeroKeyIV(u8 *pos, u32 size, u32 firmVersion);
u32 patchLgySignatureChecks(u8 *pos, u32 size);
u32 patchTwlInvalidSignatureChecks(u8 *pos, u32 size);
u32 patchTwlNintendoLogoChecks(u8 *pos, u32 size);

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -40,7 +40,7 @@
static char pinKeyToLetter(u32 pressed)
{
const char keys[] = "AB--RLUD--XY";
static const char *keys = "AB--RLUD--XY";
u32 i;
for(i = 31; pressed > 1; i--) pressed /= 2;
@@ -69,7 +69,7 @@ void newPin(bool allowSkipping, u32 pinMode)
{
if(reset)
{
for(u32 i = 0; i < cnt; i++)
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;
@@ -146,21 +146,32 @@ bool verifyPin(u32 pinMode)
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]);
const char *messageFile = "pinmessage.txt";
char message[801];
u32 messageSize = fileRead(message, messageFile, sizeof(message) - 1);
if(messageSize != 0)
bool isBottomSplashValid = getFileSize("splashpin.bin") == SCREEN_BOTTOM_FBSIZE;
if(isBottomSplashValid)
{
message[messageSize] = 0;
drawString(false, 10, 10, COLOR_WHITE, message);
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};
@@ -173,7 +184,7 @@ bool verifyPin(u32 pinMode)
{
if(reset)
{
for(u32 i = 0; i < cnt; i++)
for(u32 i = 0; i < cnt; i++)
drawCharacter(true, 10 + (16 + 2 * i) * SPACING_X, 10 + 3 * SPACING_Y, COLOR_BLACK, '*');
cnt = 0;
@@ -214,7 +225,7 @@ bool verifyPin(u32 pinMode)
{
reset = true;
drawString(true, 10, 10 + 5 * SPACING_Y, COLOR_RED, "Wrong PIN, try again");
drawString(true, 10, 10 + 5 * SPACING_Y, COLOR_RED, "Wrong PIN, try again");
}
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -35,7 +35,21 @@
#include "i2c.h"
#include "utils.h"
struct fb fbs[2];
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};
@@ -45,7 +59,7 @@ static void invokeArm11Function(Arm11Operation op)
{
while(*operation != ARM11_READY);
*operation = op;
while(*operation != ARM11_READY);
while(*operation != ARM11_READY);
}
void prepareArm11ForFirmlaunch(void)
@@ -78,45 +92,29 @@ void clearScreens(bool isAlternate)
invokeArm11Function(CLEAR_SCREENS);
}
static void initScreensSequence(void)
{
*(vu32 *)ARM11_PARAMETERS_ADDRESS = brightness[MULTICONFIG(BRIGHTNESS)];
invokeArm11Function(INIT_SCREENS_SEQUENCE);
}
static void setupFramebuffers(void)
{
fbs[0].top_left = (u8 *)0x18300000;
fbs[1].top_left = (u8 *)0x18400000;
fbs[0].top_right = (u8 *)0x18300000;
fbs[1].top_right = (u8 *)0x18400000;
fbs[0].bottom = (u8 *)0x18346500;
fbs[1].bottom = (u8 *)0x18446500;
memcpy((void *)ARM11_PARAMETERS_ADDRESS, fbs, sizeof(fbs));
invokeArm11Function(SETUP_FRAMEBUFFERS);
}
void initScreens(void)
{
static bool needToSetup = true;
if(needToSetup)
if(needToSetupScreens)
{
if(!ARESCREENSINITIALIZED)
if(!ARESCREENSINITIALIZED || bootType == FIRMLAUNCH)
{
initScreensSequence();
*(vu32 *)ARM11_PARAMETERS_ADDRESS = brightness[MULTICONFIG(BRIGHTNESS)];
memcpy((void *)(ARM11_PARAMETERS_ADDRESS + 4), fbs, sizeof(fbs));
invokeArm11Function(INIT_SCREENS);
//Turn on backlight
i2cWriteRegister(I2C_DEV_MCU, 0x22, 0x2A);
I2C_writeReg(I2C_DEV_MCU, 0x22, 0x2A);
wait(5);
}
else updateBrightness(MULTICONFIG(BRIGHTNESS));
setupFramebuffers();
needToSetup = false;
memcpy((void *)ARM11_PARAMETERS_ADDRESS, fbs, sizeof(fbs));
invokeArm11Function(SETUP_FRAMEBUFFERS);
clearScreens(true);
needToSetupScreens = false;
}
clearScreens(false);
clearScreens(true);
swapFramebuffers(false);
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -33,9 +33,9 @@
#include "types.h"
#define PDN_GPU_CNT (*(vu8 *)0x10141200)
#define PDN_GPU_CNT (*(vu32 *)0x10141200)
#define ARESCREENSINITIALIZED (PDN_GPU_CNT != 1)
#define ARESCREENSINITIALIZED ((PDN_GPU_CNT & 0xFF) != 1)
#define ARM11_PARAMETERS_ADDRESS 0x1FFFF000
@@ -49,11 +49,11 @@ struct fb {
u8 *top_left;
u8 *top_right;
u8 *bottom;
} __attribute__((packed));
};
typedef enum
{
INIT_SCREENS_SEQUENCE = 0,
INIT_SCREENS = 0,
SETUP_FRAMEBUFFERS,
CLEAR_SCREENS,
SWAP_FRAMEBUFFERS,
@@ -64,7 +64,8 @@ typedef enum
} Arm11Operation;
extern struct fb fbs[2];
extern CfgData configData;
extern bool needToSetupScreens;
void prepareArm11ForFirmlaunch(void);
void deinitScreens(void);

View File

@@ -1,5 +1,5 @@
@ This file is part of Luma3DS
@ Copyright (C) 2016-2017 Aurora Wright, TuxSH
@ Copyright (C) 2016-2020 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
@@ -22,14 +22,28 @@
@ or requiring that modified versions of such material be marked in
@ reasonable ways as different from the original version.
.section .text.start
.section .text.start, "ax", %progbits
.align 4
.global _start
_start:
@ Disable interrupts and switch to supervisor mode (also clear flags)
mov r4, #0x13
orr r4, #0x1C0
msr cpsr_cxsf, r4
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
@@ -63,7 +77,7 @@ _start:
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 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)
@@ -94,19 +108,59 @@ _start:
orr r0, r0, #(1<<0) @ - MPU enable
mcr p15, 0, r0, c1, c0, 0 @ write control register
@ Fix mounting of SDMC
ldr r0, =0x10000020
mov r1, #0x340
str r1, [r0]
@ Clear BSS
ldr r0, =__bss_start
ldr r0, =__bss_start__
mov r1, #0
ldr r2, =__bss_end
ldr r2, =__bss_end__
sub r2, r0
bl memset32
bl memset
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

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -25,25 +25,6 @@
*/
#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)
{

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -28,7 +28,5 @@
#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);

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -61,15 +61,18 @@ typedef volatile s64 vs64;
#define ISN3DS (CFG11_SOCINFO & 2)
#define ISDEVUNIT (CFG_UNITINFO != 0)
typedef struct __attribute__((packed))
typedef struct __attribute__((packed, aligned(4)))
{
char magic[4];
u16 formatVersionMajor, formatVersionMinor;
u32 config;
u32 config, multiConfig, bootConfig;
u64 hbldr3dsxTitleId;
u32 rosalinaMenuCombo;
u32 rosalinaFlags;
} CfgData;
typedef struct __attribute__((packed))
typedef struct
{
char magic[4];
u16 formatVersionMajor, formatVersionMinor;
@@ -78,7 +81,7 @@ typedef struct __attribute__((packed))
u8 hash[32];
} PinData;
typedef struct __attribute__((packed))
typedef struct
{
u32 magic[2];
u16 versionMinor, versionMajor;
@@ -112,8 +115,19 @@ typedef enum FirmwareType
NATIVE_FIRM1X2X
} FirmwareType;
extern bool isFirmlaunch,
isSdMode;
extern u16 launchedFirmTidLow[8];
extern u16 launchedPath[41];
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];

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -35,8 +35,8 @@
#include "draw.h"
#include "cache.h"
#include "fmt.h"
#include <stdarg.h>
#include "memory.h"
#include "fs.h"
static void startChrono(void)
{
@@ -71,6 +71,7 @@ u32 waitInput(bool isMenu)
u64 initialValue = 0ULL;
u32 key,
oldKey = HID_PAD;
bool shouldShellShutdown = bootType != B9SNTR && bootType != NTR;
if(isMenu)
{
@@ -85,7 +86,17 @@ u32 waitInput(bool isMenu)
if(!key)
{
if((i2cReadRegister(I2C_DEV_MCU, 0x10) & 1)== 1) mcuPowerOff();
if(shouldShellShutdown)
{
u8 shellState = I2C_readReg(I2C_DEV_MCU, 0xF);
wait(5);
if(!(shellState & 2)) mcuPowerOff();
}
u8 intStatus = I2C_readReg(I2C_DEV_MCU, 0x10);
wait(5);
if(intStatus & 1) mcuPowerOff(); //Power button pressed
oldKey = 0;
dPadDelay = 0;
continue;
@@ -104,12 +115,15 @@ u32 waitInput(bool isMenu)
void mcuPowerOff(void)
{
if(!isFirmlaunch && ARESCREENSINITIALIZED) clearScreens(false);
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();
i2cWriteRegister(I2C_DEV_MCU, 0x20, 1 << 0);
I2C_writeReg(I2C_DEV_MCU, 0x20, 1 << 0);
while(true);
}
@@ -124,23 +138,19 @@ void wait(u64 amount)
void error(const char *fmt, ...)
{
if(!isFirmlaunch)
{
char buf[DRAW_MAX_FORMATTED_STRING_SIZE + 1];
char buf[DRAW_MAX_FORMATTED_STRING_SIZE + 1];
va_list args;
va_start(args, fmt);
vsprintf(buf, fmt, args);
va_end(args);
va_list args;
va_start(args, fmt);
vsprintf(buf, fmt, args);
va_end(args);
initScreens();
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");
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);
}
waitInput(false);
mcuPowerOff();
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -36,6 +36,9 @@
#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);

View File

@@ -1,44 +0,0 @@
rwildcard = $(foreach d, $(wildcard $1*), $(filter $(subst *, %, $2), $d) $(call rwildcard, $d/, $2))
ifeq ($(strip $(DEVKITARM)),)
$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
endif
include $(DEVKITARM)/base_tools
name := $(shell basename $(CURDIR))
dir_source := source
dir_build := build
dir_out := ../$(dir_build)
ASFLAGS := -mcpu=arm946e-s
CFLAGS := -Wall -Wextra -marm $(ASFLAGS) -fno-builtin -std=c11 -Wno-main -O2 -flto -ffast-math
LDFLAGS := -nostartfiles -Wl,--nmagic
objects = $(patsubst $(dir_source)/%.s, $(dir_build)/%.o, \
$(patsubst $(dir_source)/%.c, $(dir_build)/%.o, \
$(call rwildcard, $(dir_source), *.s *.c)))
.PHONY: all
all: $(dir_out)/$(name).bin
.PHONY: clean
clean:
@rm -rf $(dir_build)
$(dir_out)/$(name).bin: $(dir_build)/$(name).elf
$(OBJCOPY) -S -O binary $< $@
$(dir_build)/$(name).elf: $(objects)
$(LINK.o) -T linker.ld $(OUTPUT_OPTION) $^
$(dir_build)/memory.o: CFLAGS += -O3
$(dir_build)/%.o: $(dir_source)/%.c
@mkdir -p "$(@D)"
$(COMPILE.c) $(OUTPUT_OPTION) $<
$(dir_build)/%.o: $(dir_source)/%.s
@mkdir -p "$(@D)"
$(COMPILE.s) $(OUTPUT_OPTION) $<

View File

@@ -1,21 +0,0 @@
OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm", "elf32-littlearm")
OUTPUT_ARCH(arm)
ENTRY(_start)
SECTIONS
{
. = 0x01FF9000;
__start__ = ABSOLUTE(.);
.text : ALIGN(4) { *(.text.start) *(.text*); . = ALIGN(4); }
.rodata : ALIGN(4) { *(.rodata*); . = ALIGN(4); }
.data : ALIGN(4) { *(.data*); . = ALIGN(8); *(.bss* COMMON); . = ALIGN(8); }
. = ALIGN(4);
__end__ = ABSOLUTE(.);
__stack_top__ = 0x01FFB800;
__stack_bottom__ = 0x01FFA800;
}

View File

@@ -1,60 +0,0 @@
@ 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.
.text
.arm
.align 4
.global flushCaches
.type flushCaches, %function
flushCaches:
@ Clean and flush both the data cache and instruction caches
@ Adpated 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 addresses 0xffff0830 (DCache) and 0xffff0ab4 (ICache)
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
@ Flush instruction cache
mcr p15, 0, r1, c7, c5, 0
bx lr

View File

@@ -1,42 +0,0 @@
/*
* 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.
*/
#include "firm.h"
#include "memory.h"
#include "cache.h"
void disableMpuAndJumpToEntrypoints(int argc, char **argv, void *arm11Entry, void *arm9Entry);
void launchFirm(Firm *firm, int argc, char **argv)
{
//Copy FIRM sections to respective memory locations
for(u32 sectionNum = 0; sectionNum < 4; sectionNum++)
memcpy(firm->section[sectionNum].address, (u8 *)firm + firm->section[sectionNum].offset, firm->section[sectionNum].size);
disableMpuAndJumpToEntrypoints(argc, argv, firm->arm9Entry, firm->arm11Entry);
__builtin_unreachable();
}

View File

@@ -1,40 +0,0 @@
/*
* 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.
*/
/*
* memcpy 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];
}

View File

@@ -2,7 +2,7 @@
# Requires Python >= 3.2 or >= 2.7
# This file is part of Luma3DS
# Copyright (C) 2016 Aurora Wright, TuxSH
# Copyright (C) 2016-2020 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
@@ -22,7 +22,7 @@
# Notices displayed by works containing it.
__author__ = "TuxSH"
__copyright__ = "Copyright (c) 2016 TuxSH"
__copyright__ = "Copyright (c) 2016-2020 TuxSH"
__license__ = "GPLv3"
__version__ = "v1.2"
@@ -90,8 +90,15 @@ def makeRegisterLine(A, rA, B, rB):
handledExceptionNames = ("FIQ", "undefined instruction", "prefetch abort", "data abort")
registerNames = tuple("r{0}".format(i) for i in range(13)) + ("sp", "lr", "pc", "cpsr") + ("dfsr", "ifsr", "far") + ("fpexc", "fpinst", "fpinst2")
svcBreakReasons = ("(svcBreak: panic)", "(svcBreak: assertion failed)", "(svcBreak: user-related)")
faultStatusSources = {
0b1:'Alignment', 0b100:'Instruction cache maintenance operation fault',
0b1100:'External Abort on translation - First-level', 0b1110:'External Abort on translation - Second-level',
0b101:'Translation - Section', 0b111:'Translation - Page', 0b11:'Access bit - Section', 0b110:'Access bit - Page',
0b1001:'Domain - Section', 0b1011:'Domain - Page', 0b1101:'Permission - Section', 0b1111:'Permission - Page',
0b1000:'Precise External Abort', 0b10110:'Imprecise External Abort', 0b10:'Debug event'
}
if __name__ == "__main__":
def main(args=None):
parser = argparse.ArgumentParser(description="Parse Luma3DS exception dumps")
parser.add_argument("filename")
args = parser.parse_args()
@@ -114,8 +121,8 @@ if __name__ == "__main__":
addtionalDataOffset = stackOffset + stackDumpSize
additionalData = data[addtionalDataOffset : addtionalDataOffset + additionalDataSize]
if processor == 9: print("Processor: ARM9")
else: print("Processor: ARM11 (core {0})".format(processor >> 16))
if processor == 9: print("Processor: Arm9")
else: print("Processor: Arm11 (core {0})".format(processor >> 16))
typeDetailsStr = ""
if exceptionType == 2:
@@ -134,6 +141,11 @@ if __name__ == "__main__":
typeDetailsStr = " (VFP exception)"
print("Exception type: {0}{1}".format("unknown" if exceptionType >= len(handledExceptionNames) else handledExceptionNames[exceptionType], typeDetailsStr))
if processor == 11 and exceptionType >= 2:
xfsr = registers[18] if exceptionType == 2 else registers[17]
print("Fault status: " + faultStatusSources[xfsr & 0xf])
if additionalDataSize != 0:
print("Current process: {0} ({1:016x})".format(additionalData[:8].decode("ascii"), unpack_from("<Q", additionalData, 8)[0]))
@@ -143,16 +155,21 @@ if __name__ == "__main__":
print(makeRegisterLine(registerNames[i], registers[i], registerNames[i+1], registers[i+1]))
if nbRegisters % 2 == 1: print("{0:<15}{1:<20}".format(registerNames[nbRegisters - 1], "{0:08x}".format(registers[nbRegisters - 1])))
if processor == 11 and exceptionType == 3:
print("{0:<15}{1:<20}Access type: {2}".format("FAR", "{0:08x}".format(registers[19]), "Write" if registers[17] & (1 << 11) != 0 else "Read"))
thumb = registers[16] & 0x20 != 0
addr = registers[15] - codeDumpSize + (2 if thumb else 4)
addr = registers[15] - codeDumpSize / 2 + (2 if thumb else 4)
print("\nCode dump:\n")
objdump_res = ""
try:
path = os.path.join(os.environ["DEVKITARM"], "bin", "arm-none-eabi-objdump")
if os.name == "nt":
path = ''.join((path[1], ':', path[2:])).replace('/', '\\')
if os.name == "nt" and path[0] == '/':
path = ''.join(('c:', path[0], path[5:]))
objdump_res = subprocess.check_output((
path, "-marm", "-b", "binary",
@@ -160,6 +177,7 @@ if __name__ == "__main__":
"--stop-address="+hex(addr + codeDumpSize), "-D", "-z", "-M",
"reg-names-std" + (",force-thumb" if thumb else ""), args.filename
)).decode("utf-8")
objdump_res = '\n'.join(objdump_res[objdump_res.find('<.data+'):].split('\n')[1:])
except: objdump_res = ""
@@ -167,3 +185,6 @@ if __name__ == "__main__":
print("\nStack dump:\n")
print(hexdump(registers[13], stackDump))
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,13 @@
from setuptools import setup, find_packages
setup(
name='luma3ds_exception_dump_parser',
version='1.2',
url='https://github.com/AuroraWright/Luma3DS',
author='TuxSH',
license='GPLv3',
description='Parses Luma3DS exception dumps',
install_requires=[''],
packages=find_packages(),
entry_points={'console_scripts': ['luma3ds_exception_dump_parser=luma3ds_exception_dump_parser.__main__:main']},
)

View File

@@ -1,42 +0,0 @@
rwildcard = $(foreach d, $(wildcard $1*), $(filter $(subst *, %, $2), $d) $(call rwildcard, $d/, $2))
ifeq ($(strip $(DEVKITARM)),)
$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
endif
include $(DEVKITARM)/base_tools
name := arm9_exceptions
dir_source := source
dir_build := build
dir_out := ../../$(dir_build)
ASFLAGS := -mcpu=arm946e-s
CFLAGS := -Wall -Wextra -mthumb $(ASFLAGS) -fno-builtin -std=c11 -Wno-main -O2 -flto -ffast-math
LDFLAGS := -nostdlib
objects = $(patsubst $(dir_source)/%.s, $(dir_build)/%.o, \
$(patsubst $(dir_source)/%.c, $(dir_build)/%.o, \
$(call rwildcard, $(dir_source), *.s *.c)))
.PHONY: all
all: $(dir_out)/$(name).bin
.PHONY: clean
clean:
@rm -rf $(dir_build)
$(dir_out)/$(name).bin: $(dir_build)/$(name).elf
$(OBJCOPY) -S -O binary $< $@
$(dir_build)/$(name).elf: $(objects)
$(CC) $(LDFLAGS) -T linker.ld $(OUTPUT_OPTION) $^
$(dir_build)/%.o: $(dir_source)/%.c
@mkdir -p "$(@D)"
$(COMPILE.c) $(OUTPUT_OPTION) $<
$(dir_build)/%.o: $(dir_source)/%.s
@mkdir -p "$(@D)"
$(COMPILE.s) $(OUTPUT_OPTION) $<

View File

@@ -1,14 +0,0 @@
OUTPUT_FORMAT("elf32-littlearm", "elf32-bigarm", "elf32-littlearm")
OUTPUT_ARCH(arm)
ENTRY(_start)
SECTIONS
{
. = 0x01FF7FE0;
.text : ALIGN(4) { *(.text.start) *(.text*); . = ALIGN(4); }
.rodata : ALIGN(4) { *(.rodata*); . = ALIGN(4); }
.data : ALIGN(4) { *(.data*); . = ALIGN(8); *(.bss* COMMON); . = ALIGN(8); }
. = ALIGN(4);
}

View File

@@ -1,113 +0,0 @@
@ 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.
.macro GEN_HANDLER name
.global \name
.type \name, %function
\name:
ldr sp, =#0x02000000 @ We make the (full descending) stack point to the end of ITCM for our exception handlers.
@ It doesn't matter if we're overwriting stuff here, since we're going to reboot.
stmfd sp!, {r0-r7} @ FIQ has its own r8-r14 regs
ldr r1, =\@ @ macro expansion counter
b _commonHandler
.size \name, . - \name
.endm
.text
.arm
.align 4
.global _commonHandler
.type _commonHandler, %function
_commonHandler:
mrs r2, spsr
mov r6, sp
mrs r3, cpsr
orr r3, #0x1c0 @ disable Imprecise Aborts, IRQ and FIQ (equivalent to "cpsid aif" on arm11)
msr cpsr_cx, r3
tst r2, #0x20
bne noSvcBreak
cmp r1, #2
bne noSvcBreak
sub r0, lr, #4 @ calling cannotAccessAddress cause more problems that it actually solves... (I've to save a lot of regs and that's a pain tbh)
lsr r0, #20 @ we'll just do some address checks (to see if it's in ARM9 internal memory)
cmp r0, #0x80
bne noSvcBreak
ldr r4, [lr, #-4]
ldr r5, =#0xe12fff7f
cmp r4, r5
bne noSvcBreak
bic r5, r3, #0xf
orr r5, #0x3
msr cpsr_c, r5 @ switch to supervisor mode
ldmfd sp, {r8-r11}^
ldr r2, [sp, #0x1c] @ implementation details of the official svc handler
ldr r4, [sp, #0x18]
msr cpsr_c, r3 @ restore processor mode
tst r2, #0x20
addne lr, r4, #2 @ adjust address for later
moveq lr, r4
noSvcBreak:
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
stmfd r6!, {r8-lr}
msr cpsr_c, r3 @ restore processor mode
mov sp, r6
stmfd sp!, {r2,lr} @ it's a bit of a mess, but we will fix that later
@ order of saved regs now: cpsr, pc + (2/4/8), r8-r14, r0-r7
mov r0, sp
b mainHandler
GEN_HANDLER FIQHandler
GEN_HANDLER undefinedInstructionHandler
GEN_HANDLER prefetchAbortHandler
GEN_HANDLER dataAbortHandler
.global readMPUConfig
.type readMPUConfig, %function
readMPUConfig:
stmfd sp!, {r4-r8, lr}
mrc p15,0,r1,c6,c0,0
mrc p15,0,r2,c6,c1,0
mrc p15,0,r3,c6,c2,0
mrc p15,0,r4,c6,c3,0
mrc p15,0,r5,c6,c4,0
mrc p15,0,r6,c6,c5,0
mrc p15,0,r7,c6,c6,0
mrc p15,0,r8,c6,c7,0
stmia r0, {r1-r8}
mrc p15,0,r0,c5,c0,2 @ read data access permission bits
ldmfd sp!, {r4-r8, pc}

View File

@@ -1,143 +0,0 @@
/*
* 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.
*/
/*
* Thanks to whoever contributed in the development of this file
*/
#include "i2c.h"
//-----------------------------------------------------------------------------
static const struct { u8 bus_id, reg_addr; } dev_data[] = {
{0, 0x4A}, {0, 0x7A}, {0, 0x78},
{1, 0x4A}, {1, 0x78}, {1, 0x2C},
{1, 0x2E}, {1, 0x40}, {1, 0x44},
{2, 0xD6}, {2, 0xD0}, {2, 0xD2},
{2, 0xA4}, {2, 0x9A}, {2, 0xA0},
};
static inline u8 i2cGetDeviceBusId(u8 device_id)
{
return dev_data[device_id].bus_id;
}
static inline u8 i2cGetDeviceRegAddr(u8 device_id)
{
return dev_data[device_id].reg_addr;
}
//-----------------------------------------------------------------------------
static vu8 *reg_data_addrs[] = {
(vu8 *)(I2C1_REG_OFF + I2C_REG_DATA),
(vu8 *)(I2C2_REG_OFF + I2C_REG_DATA),
(vu8 *)(I2C3_REG_OFF + I2C_REG_DATA),
};
static inline vu8 *i2cGetDataReg(u8 bus_id)
{
return reg_data_addrs[bus_id];
}
//-----------------------------------------------------------------------------
static vu8 *reg_cnt_addrs[] = {
(vu8 *)(I2C1_REG_OFF + I2C_REG_CNT),
(vu8 *)(I2C2_REG_OFF + I2C_REG_CNT),
(vu8 *)(I2C3_REG_OFF + I2C_REG_CNT),
};
static inline vu8 *i2cGetCntReg(u8 bus_id)
{
return reg_cnt_addrs[bus_id];
}
//-----------------------------------------------------------------------------
static inline void i2cWaitBusy(u8 bus_id)
{
while (*i2cGetCntReg(bus_id) & 0x80);
}
static inline bool i2cGetResult(u8 bus_id)
{
i2cWaitBusy(bus_id);
return (*i2cGetCntReg(bus_id) >> 4) & 1;
}
static void i2cStop(u8 bus_id, u8 arg0)
{
*i2cGetCntReg(bus_id) = (arg0 << 5) | 0xC0;
i2cWaitBusy(bus_id);
*i2cGetCntReg(bus_id) = 0xC5;
}
//-----------------------------------------------------------------------------
static bool i2cSelectDevice(u8 bus_id, u8 dev_reg)
{
i2cWaitBusy(bus_id);
*i2cGetDataReg(bus_id) = dev_reg;
*i2cGetCntReg(bus_id) = 0xC2;
return i2cGetResult(bus_id);
}
static bool i2cSelectRegister(u8 bus_id, u8 reg)
{
i2cWaitBusy(bus_id);
*i2cGetDataReg(bus_id) = reg;
*i2cGetCntReg(bus_id) = 0xC0;
return i2cGetResult(bus_id);
}
//-----------------------------------------------------------------------------
bool i2cWriteRegister(u8 dev_id, u8 reg, u8 data)
{
u8 bus_id = i2cGetDeviceBusId(dev_id);
u8 dev_addr = i2cGetDeviceRegAddr(dev_id);
for(u32 i = 0; i < 8; i++)
{
if(i2cSelectDevice(bus_id, dev_addr) && i2cSelectRegister(bus_id, reg))
{
i2cWaitBusy(bus_id);
*i2cGetDataReg(bus_id) = data;
*i2cGetCntReg(bus_id) = 0xC1;
i2cStop(bus_id, 0);
if(i2cGetResult(bus_id)) return true;
}
*i2cGetCntReg(bus_id) = 0xC5;
i2cWaitBusy(bus_id);
}
return false;
}

View File

@@ -1,48 +0,0 @@
/*
* 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.
*/
/*
* Thanks to whoever contributed in the development of this file
*/
#pragma once
#include "types.h"
#define I2C1_REG_OFF 0x10161000
#define I2C2_REG_OFF 0x10144000
#define I2C3_REG_OFF 0x10148000
#define I2C_REG_DATA 0
#define I2C_REG_CNT 1
#define I2C_REG_CNTEX 2
#define I2C_REG_SCL 4
#define I2C_DEV_MCU 3
#define I2C_DEV_GYRO 10
#define I2C_DEV_IR 13
bool i2cWriteRegister(u8 dev_id, u8 reg, u8 data);

View File

@@ -1,41 +0,0 @@
/*
* 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 <stdint.h>
#include <stdlib.h>
#include <stdbool.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;

143
k11_extension/Makefile Normal file
View File

@@ -0,0 +1,143 @@
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITARM)),)
$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
endif
TOPDIR ?= $(CURDIR)
include $(DEVKITARM)/base_rules
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
#---------------------------------------------------------------------------------
TARGET := $(notdir $(CURDIR))
BUILD := build
SOURCES := source source/svc
DATA := data
INCLUDES := include include/svc
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH := -march=armv6k -mtune=mpcore -mfloat-abi=hard -mtp=soft
DEFINES := -DARM11 -D_3DS
CFLAGS := -g -std=gnu11 -Wall -Wextra -Werror -O2 -mword-relocations \
-fomit-frame-pointer -ffunction-sections -fdata-sections \
-Wno-main $(ARCH) $(DEFINES)
CFLAGS += $(INCLUDE)
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions -std=gnu++11
ASFLAGS := -g $(ARCH)
LDFLAGS = -specs=$(TOPDIR)/linker.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
LIBS :=
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS :=
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export OUTPUT := $(CURDIR)/$(TARGET)
export TOPDIR := $(CURDIR)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
export OFILES_BIN := $(addsuffix .o,$(BINFILES))
export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SRC)
export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES)))
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
.PHONY: $(BUILD) clean all
#---------------------------------------------------------------------------------
all: $(BUILD)
$(BUILD):
@[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@echo clean ...
@rm -fr $(BUILD) $(TARGET).elf
#---------------------------------------------------------------------------------
else
.PHONY: all
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
all : $(OUTPUT).elf
$(OUTPUT).elf : $(OFILES)
%.elf: $(OFILES)
@echo linking $(notdir $@)
@$(LD) $(LDFLAGS) $(OFILES) $(LIBPATHS) $(LIBS) -o $@
@$(NM) -CSn $@ > $(notdir $*.lst)
$(OFILES_SRC) : $(HFILES_BIN)
#---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#---------------------------------------------------------------------------------
%.bin.o %_bin.h : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------

View File

@@ -0,0 +1,38 @@
#pragma once
#include "types.h"
#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))
#define CONFIG(a) (((cfwInfo.config >> (a)) & 1) != 0)
#define MULTICONFIG(a) ((cfwInfo.multiConfig >> (2 * (a))) & 3)
#define BOOTCONFIG(a, b) ((cfwInfo.bootConfig >> (a)) & (b))
#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,
ENABLESAFEFIRMROSALINA,
};

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -24,18 +24,16 @@
* reasonable ways as different from the original version.
*/
#include "synchronization.h"
#include "utils.h"
#pragma once
#include "types.h"
#include "globals.h"
#include "kernel.h"
#include "utils.h"
extern SGI0Handler_t SGI0Handler;
extern KRecursiveLock dbgParamsLock;
extern u32 dbgParamWatchpointId, dbgParamDVA, dbgParamWCR, dbgParamContextId;
void executeFunctionOnCores(SGI0Handler_t handler, u8 targetList, u8 targetListFilter)
{
u32 coreID = getCurrentCoreID();
SGI0Handler = handler;
if(targetListFilter == 0 && (targetListFilter & (1 << coreID)) != 0)
__asm__ volatile("cpsie i"); // make sure interrupts aren't masked
MPCORE_GID_SGI = (targetListFilter << 24) | (targetList << 16) | 0;
}
KSchedulableInterruptEvent *enableMonitorModeDebugging(KBaseInterruptEvent *this, u32 interruptID);
KSchedulableInterruptEvent *disableWatchpoint(KBaseInterruptEvent *this, u32 interruptID);
KSchedulableInterruptEvent *setWatchpointWithContextId(KBaseInterruptEvent *this, u32 interruptID);

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -28,16 +28,15 @@
#include "types.h"
bool isExceptionFatal(u32 spsr);
bool isExceptionFatal(u32 spsr, u32 *regs, u32 index);
bool isDataAbortExceptionRangeControlled(u32 spsr, u32 addr);
void FIQHandler(void);
void undefinedInstructionHandler(void);
void prefetchAbortHandler(void);
void dataAbortHandler(void);
typedef struct __attribute__((packed))
typedef struct
{
u32 magic[2];
u16 versionMinor, versionMajor;

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -26,6 +26,7 @@
#pragma once
#include "config.h"
#include "kernel.h"
extern KRecursiveLock *criticalSectionLock;
@@ -43,8 +44,12 @@ extern KAutoObject * (*KProcessHandleTable__ToKAutoObject)(KProcessHandleTable *
extern void (*KSynchronizationObject__Signal)(KSynchronizationObject *this, bool isPulse);
extern Result (*WaitSynchronization1)(void *this_unused, KThread *thread, KSynchronizationObject *syncObject, s64 timeout);
extern Result (*KProcessHandleTable__CreateHandle)(KProcessHandleTable *this, Handle *out, KAutoObject *obj, u8 token);
extern Result (*KProcessHwInfo__QueryMemory)(KProcessHwInfo *this, MemoryInfo *memoryInfo, PageInfo *pageInfo, void *address);
extern Result (*KProcessHwInfo__MapProcessMemory)(KProcessHwInfo *this, KProcessHwInfo *other, void *dst, void *src, u32 nbPages);
extern Result (*KProcessHwInfo__UnmapProcessMemory)(KProcessHwInfo *this, void *addr, u32 nbPages);
extern Result (*KProcessHwInfo__CheckVaState)(KProcessHwInfo *hwInfo, u32 va, u32 size, u32 state, u32 perm);
extern Result (*KProcessHwInfo__GetListOfKBlockInfoForVA)(KProcessHwInfo *hwInfo, KLinkedList *list, u32 va, u32 sizeInPage);
extern Result (*KProcessHwInfo__MapListOfKBlockInfo)(KProcessHwInfo *this, u32 va, KLinkedList *list, u32 state, u32 perm, u32 sbz);
extern Result (*KEvent__Clear)(KEvent *this);
extern void (*KObjectMutex__WaitAndAcquire)(KObjectMutex *this);
extern void (*KObjectMutex__ErrorOccured)(void);
@@ -52,9 +57,13 @@ extern void (*KObjectMutex__ErrorOccured)(void);
extern void (*KScheduler__AdjustThread)(KScheduler *this, KThread *thread, u32 oldSchedulingMask);
extern void (*KScheduler__AttemptSwitchingThreadContext)(KScheduler *this);
extern void (*KLinkedList_KBlockInfo__Clear)(KLinkedList *list);
extern Result (*ControlMemory)(u32 *addrOut, u32 addr0, u32 addr1, u32 size, MemOp op, MemPerm perm, bool isLoader);
extern void (*SleepThread)(s64 ns);
extern Result (*CreateEvent)(Handle *out, ResetType resetType);
extern Result (*CloseHandle)(Handle handle);
extern Result (*GetHandleInfo)(s64 *out, Handle handle, u32 type);
extern Result (*GetSystemInfo)(s64 *out, s32 type, s32 param);
extern Result (*GetProcessInfo)(s64 *out, Handle processHandle, u32 type);
extern Result (*GetThreadInfo)(s64 *out, Handle threadHandle, u32 type);
@@ -63,6 +72,8 @@ extern Result (*SendSyncRequest)(Handle handle);
extern Result (*OpenProcess)(Handle *out, u32 processId);
extern Result (*GetProcessId)(u32 *out, Handle process);
extern Result (*DebugActiveProcess)(Handle *out, u32 processId);
extern Result (*SignalEvent)(Handle event);
extern Result (*UnmapProcessMemory)(Handle processHandle, void *dst, u32 size);
extern Result (*KernelSetState)(u32 type, u32 varg1, u32 varg2, u32 varg3);
extern void (*flushDataCacheRange)(void *addr, u32 len);
@@ -75,11 +86,9 @@ extern bool (*kernelToUsrMemcpy8)(void *dst, const void *src, u32 len);
extern bool (*kernelToUsrMemcpy32)(u32 *dst, const u32 *src, u32 len);
extern s32 (*kernelToUsrStrncpy)(char *dst, const char *src, u32 len);
extern Result (*CustomBackdoor)(void *function, ...);
extern void (*svcFallbackHandler)(u8 svcId);
extern void (*kernelpanic)(void);
extern void (*PostprocessSvc)(void);
extern void (*officialPostProcessSvc)(void);
extern Result (*SignalDebugEvent)(DebugEventType type, u32 info, ...);
@@ -89,11 +98,23 @@ extern u32 *exceptionStackTop;
extern u32 TTBCR;
extern u32 L1MMUTableAddrs[4];
extern u32 kernelVersion;
extern void *kernelUsrCopyFuncsStart, *kernelUsrCopyFuncsEnd;
extern bool *isDevUnit;
extern vu8 *configPage;
extern u32 kernelVersion;
extern FcramLayout fcramLayout;
extern KCoreContext *coreCtxs;
extern void *originalHandlers[8];
extern u32 nbSection0Modules;
extern u8 __start__[], __end__[], __bss_start__[], __bss_end__[];
extern Result (*InterruptManager__MapInterrupt)(InterruptManager *manager, KBaseInterruptEvent *iEvent, u32 interruptID,
u32 coreID, u32 priority, bool disableUponReceipt, bool levelHighActive);
extern InterruptManager *interruptManager;
extern KBaseInterruptEvent *customInterruptEvent;
@@ -101,7 +122,7 @@ extern void (*initFPU)(void);
extern void (*mcuReboot)(void);
extern void (*coreBarrier)(void);
typedef struct PACKED CfwInfo
typedef struct CfwInfo
{
char magic[4];
@@ -112,10 +133,18 @@ typedef struct PACKED CfwInfo
u32 commitHash;
u32 config;
u16 configFormatVersionMajor, configFormatVersionMinor;
u32 config, multiConfig, bootConfig;
u64 hbldr3dsxTitleId;
u32 rosalinaMenuCombo;
u32 rosalinaFlags;
} CfwInfo;
extern CfwInfo cfwInfo;
extern u32 kextBasePa;
extern u32 stolenSystemMemRegionSize;
extern u32 rosalinaState;
extern bool hasStartedRosalinaNetworkFuncsOnce;
extern vu32 rosalinaState;
extern bool hasStartedRosalinaNetworkFuncsOnce;
KLinkedList* KLinkedList__Initialize(KLinkedList *list);

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -56,6 +56,5 @@ void SessionInfo_ChangeVtable(KSession *session);
void SessionInfo_Add(KSession *session, const char *name);
void SessionInfo_Remove(KSession *session);
bool doLangEmu(Result *res, Handle handle, u32 *cmdbuf);
Result doPublishToProcessHook(Handle handle, u32 *cmdbuf);
bool doLangEmu(Result *res, u32 *cmdbuf);
bool doErrfThrowHook(u32 *cmdbuf);

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -28,6 +28,8 @@
#include "types.h"
extern u32 kernelVersion;
struct KMutex;
struct KProcessO3DS;
struct KProcessN3DS;
@@ -103,6 +105,14 @@ typedef struct ALIGN(4) KMutex
union KProcess *owner;
} KMutex;
typedef struct KAddressArbiter
{
KAutoObject autoObject;
struct KThread *first;
struct KThread *last;
union KProcess *owner;
} KAddressArbiter;
/* 92 */
typedef struct KMutexLinkedList
{
@@ -110,6 +120,30 @@ typedef struct KMutexLinkedList
KMutex *last;
} KMutexLinkedList;
enum
{
TOKEN_KAUTOOBJECT = 0,
TOKEN_KSYNCHRONIZATIONOBJECT = 1,
TOKEN_KEVENT = 0x1F,
TOKEN_KSEMAPHORE = 0x2F,
TOKEN_KTIMER = 0x35,
TOKEN_KMUTEX = 0x39,
TOKEN_KDEBUG = 0x4D,
TOKEN_KSERVERPORT = 0x55,
TOKEN_KDMAOBJECT = 0x59,
TOKEN_KCLIENTPORT = 0x65,
TOKEN_KCODESET = 0x68,
TOKEN_KSESSION = 0x70,
TOKEN_KTHREAD = 0x8D,
TOKEN_KSERVERSESSION = 0x95,
TOKEN_KADDRESSARBITER = 0x98,
TOKEN_KCLIENTSESSION = 0xA5,
TOKEN_KPORT = 0xA8,
TOKEN_KSHAREDMEMORY = 0xB0,
TOKEN_KPROCESS = 0xC5,
TOKEN_KRESOURCELIMIT = 0xC8
};
/* 45 */
typedef struct KClassToken
{
@@ -204,7 +238,7 @@ typedef struct PACKED ALIGN(4) KThread
KMutexLinkedList *mutexList;
KLinkedList mutexesUsed;
s32 dynamicPriority;
u32 processor;
u32 coreId;
KPreemptionTimer *preemptionTimer;
u32 unknown_1;
bool isAlive;
@@ -538,6 +572,20 @@ typedef struct KBlockInfo
u32 pageCount;
} KBlockInfo;
typedef struct KSharedMemory
{
KAutoObject autoObject;
KLinkedList ownedKBlockInfo;
union KProcess *owner;
u32 ownerPermissions;
u32 otherPermissions;
u8 isBlockInfoGenerated;
s8 allBlockInfoGenerated;
u8 unknown_1;
u8 unknown_2;
u32 address;
} KSharedMemory;
/* 25 */
typedef struct KMemoryBlock
{
@@ -948,6 +996,7 @@ typedef struct KCoreContext
} KCoreContext;
static KCoreContext * const currentCoreContext = (KCoreContext *)0xFFFF1000;
extern KCoreContext *coreCtxs;
#define DEFINE_CONSOLE_SPECIFIC_STRUCTS(console, nbCores)
/* 60 */
@@ -1034,10 +1083,26 @@ typedef struct KProcess##sys\
KThread *mainThread;\
u32 interruptEnabledFlags[4];\
KProcessHandleTable handleTable;\
u8 gap234[52];\
/* Custom fields for plugin system
{ */ \
u32 customFlags; /* see KProcess_CustomFlags enum below */ \
Handle onMemoryLayoutChangeEvent;\
Handle onProcessExitEvent;\
Handle resumeProcessExitEvent;\
/* } */ \
u8 gap234[36];\
u64 unused;\
} KProcess##sys;
enum KProcess_CustomFlags
{
ForceRWXPages = 1 << 0,
SignalOnMemLayoutChanges = 1 << 1,
SignalOnExit = 1 << 2,
MemLayoutChanged = 1 << 16
};
INSTANCIATE_KPROCESS(N3DS);
INSTANCIATE_KPROCESS(O3DS8x);
INSTANCIATE_KPROCESS(O3DSPre8x);
@@ -1121,25 +1186,42 @@ typedef union KCacheMaintenanceInterruptEvent
KCacheMaintenanceInterruptEventO3DS O3DS;
} KCacheMaintenanceInterruptEvent;
typedef struct FcramLayout
{
u32 applicationAddr;
u32 applicationSize;
u32 systemAddr;
u32 systemSize;
u32 baseAddr;
u32 baseSize;
} FcramLayout;
extern bool isN3DS;
extern void *officialSVCs[0x7E];
extern u32 kernelVersion;
#define KPROCESS_OFFSETOF(field) (isN3DS ? offsetof(KProcessN3DS, field) :\
((kernelVersion >= SYSTEM_VERSION(2, 44, 6)) ? offsetof(KProcessO3DS8x, field) :\
offsetof(KProcessO3DSPre8x, field)))
#define KPROCESSRELATED_OFFSETOFF(classname, field) (isN3DS ? offsetof(classname##N3DS, field) :\
((GET_VERSION_MINOR(kernelVersion) >= 44) ? offsetof(classname##O3DS8x, field) :\
offsetof(classname##O3DSPre8x, field)))
#define KPROCESS_GET_PTR(obj, field) (isN3DS ? &(obj)->N3DS.field :\
((kernelVersion >= SYSTEM_VERSION(2, 44, 6)) ? &(obj)->O3DS8x.field :\
&(obj)->O3DSPre8x.field ))
#define KPROCESSRELATED_GET_PTR(obj, field) (isN3DS ? &(obj)->N3DS.field :\
((GET_VERSION_MINOR(kernelVersion) >= 44) ? &(obj)->O3DS8x.field :\
&(obj)->O3DSPre8x.field))
#define KPROCESS_GET_PTR_TYPE(type, obj, field) (isN3DS ? (type *)(&(obj)->N3DS.field) :\
((kernelVersion >= SYSTEM_VERSION(2, 44, 6)) ? (type *)(&(obj)->O3DS8x.field) :\
(type *)(&(obj)->O3DSPre8x.field) ))
#define KPROCESSRELATED_GET_PTR_TYPE(type, obj, field) (isN3DS ? (type *)(&(obj)->N3DS.field) :\
((GET_VERSION_MINOR(kernelVersion) >= 44) ? (type *)(&(obj)->O3DS8x.field) :\
(type *)(&(obj)->O3DSPre8x.field)))
#define KPROCESS_GET_RVALUE(obj, field) *(KPROCESS_GET_PTR(obj, field))
#define KPROCESS_OFFSETOF(field) KPROCESSRELATED_OFFSETOFF(KProcess, field)
#define KPROCESS_GET_PTR(obj, field) KPROCESSRELATED_GET_PTR(obj, field)
#define KPROCESS_GET_PTR_TYPE(type, obj, field) KPROCESSRELATED_GET_PTR_TYPE(type, obj, field)
#define KPROCESS_GET_RVALUE(obj, field) *(KPROCESS_GET_PTR(obj, field))
#define KPROCESS_GET_RVALUE_TYPE(type, obj, field) *(KPROCESS_GET_PTR_TYPE(type, obj, field))
#define KPROCESS_GET_RVALUE_TYPE(type, obj, field) *(KPROCESS_GET_PTR(type, obj, field))
#define KPROCESSHWINFO_OFFSETOF(field) KPROCESSRELATED_OFFSETOFF(KProcessHwInfo, field)
#define KPROCESSHWINFO_GET_PTR(obj, field) KPROCESSRELATED_GET_PTR(obj, field)
#define KPROCESSHWINFO_GET_PTR_TYPE(type, obj, field) KPROCESSRELATED_GET_PTR_TYPE(type, obj, field)
#define KPROCESSHWINFO_GET_RVALUE(obj, field) *(KPROCESSHWINFO_GET_PTR(obj, field))
#define KPROCESSHWINFO_GET_RVALUE_TYPE(type, obj, field) *(KPROCESSHWINFO_GET_PTR_TYPE(type, obj, field))
static inline u32 idOfProcess(KProcess *process)
{
@@ -1166,12 +1248,26 @@ static inline KDebug *debugOfProcess(KProcess *process)
return KPROCESS_GET_RVALUE(process, debug);
}
static inline const char *classNameOfAutoObject(KAutoObject *object)
{
const char *name;
if(GET_VERSION_MINOR(kernelVersion) >= 46)
{
KClassToken tok;
object->vtable->GetClassToken(&tok, object);
name = tok.name;
}
else
name = object->vtable->GetClassName(object);
return name;
}
extern Result (*KProcessHandleTable__CreateHandle)(KProcessHandleTable *this, Handle *out, KAutoObject *obj, u8 token);
static inline Result createHandleForProcess(Handle *out, KProcess *process, KAutoObject *obj)
{
u8 token;
if(kernelVersion >= SYSTEM_VERSION(2, 46, 0))
if(GET_VERSION_MINOR(kernelVersion) >= 46)
{
KClassToken tok;
obj->vtable->GetClassToken(&tok, obj);

129
k11_extension/include/mmu.h Normal file
View File

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

View File

@@ -1,6 +1,6 @@
/*
* This file is part of Luma3DS
* Copyright (C) 2016-2017 Aurora Wright, TuxSH
* Copyright (C) 2016-2020 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
@@ -33,5 +33,6 @@
extern void *officialSVCs[0x7E];
void postprocessSvc(void);
void svcDefaultHandler(u8 svcId);
void *svcHook(u8 *pageEnd);

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