Compare commits

..

69 Commits

Author SHA1 Message Date
Michael Scire
1019bc54e6 git subrepo push libraries
subrepo:
  subdir:   "libraries"
  merged:   "c4d0335b7"
upstream:
  origin:   "https://github.com/Atmosphere-NX/Atmosphere-libs"
  branch:   "master"
  commit:   "c4d0335b7"
git-subrepo:
  version:  "0.4.1"
  origin:   "???"
  commit:   "???"
2021-11-30 16:53:56 -08:00
Michael Scire
96631d8225 bump version to 1.2.5, fix enum for 13.2.0 2021-11-30 16:53:32 -08:00
Michael Scire
d32dd0f04a git subrepo push libraries
subrepo:
  subdir:   "libraries"
  merged:   "b670c079f"
upstream:
  origin:   "https://github.com/Atmosphere-NX/Atmosphere-libs"
  branch:   "master"
  commit:   "b670c079f"
git-subrepo:
  version:  "0.4.1"
  origin:   "???"
  commit:   "???"
2021-11-30 16:35:09 -08:00
Michael Scire
ddfc16731f ams/hos: add enum support for 13.2.0 2021-11-30 16:22:57 -08:00
Pablo Curiel
26714c7f3b ldr_embedded_usb_patches: add support for HOS 13.0.0 and 13.1.0 + remove superfluous comments. (#1718) 2021-11-26 00:39:22 -07:00
Michael Scire
767e702a70 kern: correct TotalUserPhysicalMemorySize (closes #1710) 2021-11-16 23:18:47 -08:00
Michael Scire
9d5e652fbd kern: be a little more consistent about pragma GCC location 2021-11-16 11:25:57 -08:00
Michael Scire
1d39e06f32 test/svc: add test for thread create 2021-11-08 13:29:00 -08:00
Michael Scire
21b7884653 test/svc: add test for thread pinning/SynchronizePreemptionState 2021-11-08 13:05:06 -08:00
Michael Scire
14ad2f0ba0 unit testing: catch -> doctest (faster compile, thread-safe) 2021-11-08 11:55:21 -08:00
Michael Scire
fcc7ce49d9 sm/tipc: ensure technical-correctness of sins (no page cost) 2021-11-06 20:05:32 -07:00
Michael Scire
f98c7cba98 sm: save 0x5000 of memory by sinning 2021-11-06 19:33:08 -07:00
Léo Lam
496adb0018 Minor header fixes to reduce parsing issues with Clang (#1700)
* Work around Clang's incomplete C++20 support for omitting typename

* vapours: fix Clang error about missing return in constexpr function

* stratosphere: fix call to non-constexpr strlen in constexpr function

strlen being constexpr is a non-compliant GCC extension; Clang
explicitly rejects it: https://reviews.llvm.org/D23692

* stratosphere: add a bunch of missing override specifiers

* stratosphere: work around Clang consteval bug

Minimal example: https://godbolt.org/z/MoM64v93M

The issue seems to be that Clang does not consider f(x) to be a
constant expression if x comes from a template argument that isn't
a non-type auto template argument (???)

We can work around this by relaxing GetMessageHeaderForCheck (by using
constexpr instead of consteval). This produces no functional changes
because the result of GetMessageHeaderForCheck() is assigned to a
constexpr variable, so the result is guaranteed to be computed
at compile-time.

* stratosphere: fix missing require clauses in definitions

GCC not requiring the require clauses to be repeated for member
definitions is actually a compiler bug:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96830

Clang rejects declarations with missing require clauses.

* Fix ALWAYS_INLINE_LAMBDA and parameter list relative order

While GCC doesn't seem to care about the position of the always_inline
attribute relative to the parameter list, Clang is very picky
and requires the attribute to appear after the parameter list
(and before a trailing return type)

* stratosphere: fix static constexpr member variable with incomplete type

GCC accepts this for some reason (because of the lambda?) but Clang
correctly rejects this.
2021-11-06 18:19:34 -07:00
Michael Scire
09074798cd KScheduler big brain strat for mdscr_el1 cfg change 2021-11-05 23:38:43 -07:00
Michael Scire
e256261b80 git subrepo push libraries
subrepo:
  subdir:   "libraries"
  merged:   "ff2883361"
upstream:
  origin:   "https://github.com/Atmosphere-NX/Atmosphere-libs"
  branch:   "master"
  commit:   "ff2883361"
git-subrepo:
  version:  "0.4.1"
  origin:   "???"
  commit:   "???"
2021-11-04 13:40:55 -07:00
Michael Scire
47218f0da8 ams: overhaul fs.mitm romfs ownership, bump to 1.2.4 2021-11-04 13:38:41 -07:00
Michael Scire
409a48ec73 docs: add changelog for 1.2.3 2021-11-04 00:23:23 -07:00
Michael Scire
0c93cefd39 git subrepo push libraries
subrepo:
  subdir:   "libraries"
  merged:   "e7b84767c"
upstream:
  origin:   "https://github.com/Atmosphere-NX/Atmosphere-libs"
  branch:   "master"
  commit:   "e7b84767c"
git-subrepo:
  version:  "0.4.1"
  origin:   "???"
  commit:   "???"
2021-11-04 00:00:26 -07:00
Michael Scire
0bbc907907 git subrepo pull (merge) libraries
subrepo:
  subdir:   "libraries"
  merged:   "8764bd406"
upstream:
  origin:   "https://github.com/Atmosphere-NX/Atmosphere-libs"
  branch:   "master"
  commit:   "12d0ba172"
git-subrepo:
  version:  "0.4.1"
  origin:   "???"
  commit:   "???"
2021-11-03 23:59:17 -07:00
Michael Scire
4a4a1f0e87 ams: bump api version to 1.2.3 2021-11-03 23:57:30 -07:00
Michael Scire
705dd95375 dmnt2: fix gdb register output 2021-11-03 23:56:25 -07:00
Michael Scire
2d5751356b creport: fix errant ) 2021-11-03 23:56:25 -07:00
Michael Scire
b140834b7e dmnt2: try to avoid writing out of bounds when generating packets 2021-11-03 23:56:25 -07:00
Michael Scire
e3d2af6b3f dmnt2: fix module name detection, add auto-break on hb nro launch 2021-11-03 23:56:25 -07:00
jam1garner
c17ad1e0e3 dmnt2: fix missing null-terminator for invalid command error 2021-11-03 23:56:25 -07:00
Michael Scire
6145b3b72c dmnt2: detect thread name, add monitor get mapping(s), increase buffer sizes 2021-11-03 23:56:25 -07:00
Michael Scire
aba7e4ca7d dmnt2: remove memory-map output which does nothing for us 2021-11-03 23:56:25 -07:00
Michael Scire
4cc5e9cdfd kern/dmnt2: allow retrieval of process info via extension
This also fixes ctrl-c break in gdbstub, and fixes crash on unknown monitor cmd.
2021-11-03 23:56:25 -07:00
Michael Scire
ca0308c7ca dmnt2: first pass at wait-for-application 2021-11-03 23:56:25 -07:00
Michael Scire
1d908295fe dmnt2: add monitor get base, TODO responses for monitor wait * 2021-11-03 23:56:25 -07:00
Michael Scire
277bd101c5 dmnt2: add memory-map read, improve module shared-lib names 2021-11-03 23:56:25 -07:00
Michael Scire
3dce23773a Adding setting usage to dmnt2 means dmnt2 needs settings access 2021-11-03 23:56:25 -07:00
Michael Scire
4489513f7c dmnt: enable experimental standalone usage of gdbstub, while starlink is in dev 2021-11-03 23:56:25 -07:00
Michael Scire
5eabca7f04 ams.mitm: more romfs building space/time tradeoffs.
This is needed for Animal Crossing 2.0.0, which has >99000 fucking files.

We now do several passes over dir/file tables instead of one pass,
doing entire hash tables before we touch dir/file tables. Thus we
no longer need to simultaneously allocate hash table and dir/file table space.

In addition, we now do repeated passes building a segment of hash tables
at a time, when insufficient memory is available. Similar is also now the
case for file/dir tables, we try 0x40000 work buffer and divide by 2
until we successfully alloc. We don't allow a work buffer <0x4000, for
write/perf reasons. If a game triggers that, let me know I guess.

Hard to imagine a worse torture-test for this code than animal crossing.
2021-11-03 23:52:38 -07:00
Michael Scire
a73e0e8f16 ams: add arm/armv8a to gitignore 2021-10-31 11:20:32 -07:00
Michael Scire
2161365f4f ams: update for awareness of architecture revision 2021-10-31 11:18:17 -07:00
Michael Scire
258a83684e creport: print symbols if they're present 2021-10-30 14:18:00 -07:00
Michael Scire
d2a757c39e git subrepo push libraries
subrepo:
  subdir:   "libraries"
  merged:   "ceff2f371"
upstream:
  origin:   "https://github.com/Atmosphere-NX/Atmosphere-libs"
  branch:   "master"
  commit:   "ceff2f371"
git-subrepo:
  version:  "0.4.1"
  origin:   "???"
  commit:   "???"
2021-10-30 11:21:54 -07:00
Michael Scire
6cf5205a28 spl: fix legacy physical keyslot compatibility 2021-10-30 11:21:25 -07:00
Michael Scire
b9c90b9234 git subrepo push libraries
subrepo:
  subdir:   "libraries"
  merged:   "4d0f1b792"
upstream:
  origin:   "https://github.com/Atmosphere-NX/Atmosphere-libs"
  branch:   "master"
  commit:   "4d0f1b792"
git-subrepo:
  version:  "0.4.1"
  origin:   "???"
  commit:   "???"
2021-10-29 17:47:35 -07:00
Michael Scire
94e18b8c93 ams: bump version to 1.2.2 2021-10-29 17:47:01 -07:00
Michael Scire
4e92687cab sprofile: various correctness fixes. 2021-10-29 17:38:44 -07:00
Michael Scire
2a0b99d9f9 sprofile: fix off-by-one in struct definition, fix GetImportableProfileUrls 2021-10-29 15:41:25 -07:00
Michael Scire
d1f3c4904b kern: fix minor assembly bugs, avoid unnecessary function call in KScheduler hotloop 2021-10-28 19:16:23 -07:00
Michael Scire
92321ccbc8 kern: fix 32-bit light ipc svc handler asm
Nintendo used to do what we were doing because the function wasn't directly in the handler table,
but we've always been directly in the handler table, so we were trashing the last four arguments to light ipc
when called from aarch32. Nothing uses this, but needed to be fixed.
2021-10-28 15:42:52 -07:00
Michael Scire
db3004e844 git subrepo push libraries
subrepo:
  subdir:   "libraries"
  merged:   "0a0bd74ca"
upstream:
  origin:   "https://github.com/Atmosphere-NX/Atmosphere-libs"
  branch:   "master"
  commit:   "0a0bd74ca"
git-subrepo:
  version:  "0.4.1"
  origin:   "???"
  commit:   "???"
2021-10-27 22:57:39 -07:00
Michael Scire
3e97e4addf init: disable fsdev cwd to prevent abort on fsdev usage (fsdev should not be used) 2021-10-27 22:57:09 -07:00
Michael Scire
4b7b33809f kern: optimize and bring into line with N our pstate.i management 2021-10-27 15:00:07 -07:00
Michael Scire
e81a1ce5a8 kern: audit (and fix) our hardware maintenance instructions to match official kernel 2021-10-27 12:31:53 -07:00
Michael Scire
fb59d0ad43 Unfuck emummc to not corrupt remote on subrepo push.
subrepo:
  subdir:   "emummc"
  merged:   "a9d569594"
upstream:
  origin:   "https://github.com/m4xw/emuMMC"
  branch:   "develop"
  commit:   "a9d569594"
git-subrepo:
  version:  "0.4.1"
  origin:   "???"
  commit:   "???"
2021-10-26 01:52:41 -07:00
Michael Scire
73b74b904f docs: add changelog for 1.2.1 2021-10-26 01:46:10 -07:00
Michael Scire
ed41b01b69 git subrepo push emummc
subrepo:
  subdir:   "emummc"
  merged:   "f11d22d74"
upstream:
  origin:   "https://github.com/m4xw/emuMMC"
  branch:   "develop"
  commit:   "f11d22d74"
git-subrepo:
  version:  "0.4.1"
  origin:   "???"
  commit:   "???"
2021-10-26 01:13:50 -07:00
Michael Scire
24143d8813 git subrepo push libraries
subrepo:
  subdir:   "libraries"
  merged:   "13c6987cc"
upstream:
  origin:   "https://github.com/Atmosphere-NX/Atmosphere-libs"
  branch:   "master"
  commit:   "13c6987cc"
git-subrepo:
  version:  "0.4.1"
  origin:   "???"
  commit:   "???"
2021-10-26 01:12:06 -07:00
Michael Scire
cb38b0b929 ams: bump version to 1.2.1 2021-10-26 01:09:16 -07:00
Michael Scire
dd04113f5d emummc/fusee: support 13.1.0 FS 2021-10-26 01:08:37 -07:00
Michael Scire
0e81eac9d1 sprof: update for 13.1.0 (format version 1) 2021-10-26 00:51:44 -07:00
Michael Scire
a14dc6ed89 crypto: implement md5, which now used by sprof 2021-10-25 23:15:50 -07:00
Michael Scire
9cc6be4d57 kern: other dmbs in kernel were already dmb ish 2021-10-25 17:38:50 -07:00
Michael Scire
1d5f66be56 kern: implement 13.1.0 kernel changes 2021-10-25 17:34:47 -07:00
Michael Scire
ebca23305e kern: simplify random bitmap selection to match latest Nintendo logic 2021-10-25 17:31:14 -07:00
Michael Scire
273f4a87ae kern: add (and use) generic KSystemControlBase 2021-10-25 17:31:14 -07:00
Michael Scire
1f8bf41f0b kern/test: add some scheduler tests (yields work correctly, all non-special priorities are cooperative/not pre-emptive 2021-10-25 17:31:14 -07:00
Michael Scire
ad03be9a38 hos: whoops 2021-10-25 17:31:14 -07:00
Michael Scire
d63be0737b hos: better safe than sorry 2021-10-25 17:31:14 -07:00
Michael Scire
018ae08409 hos: allow turning off ams extension hard-reqs for unit testing 2021-10-25 17:31:14 -07:00
Michael Scire
2a842791eb kern: add toggleable support for 40-bit physaddr caps 2021-10-25 17:31:14 -07:00
Michael Scire
d8a2b47b0a util: add trait/macro for is_constexpr_constructible 2021-10-25 17:31:14 -07:00
Michael Scire
7c1347e692 test: add tests for SetMemoryPermission 2021-10-25 17:31:14 -07:00
Michael Scire
0a58e803be kern/test: add wip qemu-virt board support to mesosphere 2021-10-25 17:31:14 -07:00
159 changed files with 10143 additions and 19307 deletions

4
.gitignore vendored
View File

@@ -91,7 +91,11 @@ dkms.conf
**/out **/out
**/build **/build
**/build_nintendo_nx_arm64 **/build_nintendo_nx_arm64
**/build_nintendo_nx_arm64_armv8a
**/build_nintendo_nx_arm **/build_nintendo_nx_arm
**/build_nintendo_nx_arm_armv8a
**/build_nintendo_nx_arm_armv7a
**/build_nintendo_nx_arm_armv4t
**/build_nintendo_nx_x64 **/build_nintendo_nx_x64
**/build_nintendo_nx_x86 **/build_nintendo_nx_x86

View File

@@ -112,6 +112,7 @@ dist-no-debug: all
mkdir -p atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/0100000000000042 mkdir -p atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/0100000000000042
mkdir -p atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/0100000000000420 mkdir -p atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/0100000000000420
mkdir -p atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/010000000000B240 mkdir -p atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/010000000000B240
mkdir -p atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/010000000000D609
mkdir -p atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/010000000000D623 mkdir -p atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/010000000000D623
cp stratosphere/boot2/boot2.nsp atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/0100000000000008/exefs.nsp cp stratosphere/boot2/boot2.nsp atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/0100000000000008/exefs.nsp
cp stratosphere/dmnt/dmnt.nsp atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/010000000000000D/exefs.nsp cp stratosphere/dmnt/dmnt.nsp atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/010000000000000D/exefs.nsp
@@ -125,6 +126,7 @@ dist-no-debug: all
cp stratosphere/pgl/pgl.nsp atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/0100000000000042/exefs.nsp cp stratosphere/pgl/pgl.nsp atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/0100000000000042/exefs.nsp
cp stratosphere/LogManager/LogManager.nsp atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/0100000000000420/exefs.nsp cp stratosphere/LogManager/LogManager.nsp atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/0100000000000420/exefs.nsp
cp stratosphere/htc/htc.nsp atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/010000000000B240/exefs.nsp cp stratosphere/htc/htc.nsp atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/010000000000B240/exefs.nsp
cp stratosphere/dmnt.gen2/dmnt.gen2.nsp atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/010000000000D609/exefs.nsp
cp stratosphere/TioServer/TioServer.nsp atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/010000000000D623/exefs.nsp cp stratosphere/TioServer/TioServer.nsp atmosphere-$(AMSVER)/stratosphere_romfs/atmosphere/contents/010000000000D623/exefs.nsp
@build_romfs atmosphere-$(AMSVER)/stratosphere_romfs atmosphere-$(AMSVER)/atmosphere/stratosphere.romfs @build_romfs atmosphere-$(AMSVER)/stratosphere_romfs atmosphere-$(AMSVER)/atmosphere/stratosphere.romfs
rm -r atmosphere-$(AMSVER)/stratosphere_romfs rm -r atmosphere-$(AMSVER)/stratosphere_romfs

View File

@@ -1,4 +1,106 @@
# Changelog # Changelog
## 1.2.5
+ Support was added for 13.2.0.
+ A number of minor issues were fixed and improvements were made, including:
+ A bug was fixed that caused `mesosphère` to underreport the total memory size by 8MB for certain games which use newer system-resource-size memory management.
+ This caused FIFA 19 to crash, and possibly other issues.
+ Memory management changes were made to `sm` that save 0x5000 of memory.
+ A microoptimization was made to the way `mesosphère` manages updating the debug register for hardware single-step support.
+ Support was fixed for enabling `usb!usb30_force_enabled` on 13.0.0+.
+ The work-in-progress unit testing framework was updated to use doctest instead of catch2.
+ General system stability improvements to enhance the user's experience.
## 1.2.4
+ Changes were made to the way fs.mitm builds images when providing a layeredfs romfs.
+ Cache management (to avoid unnecessary rebuild) was revised, to add a grace period of ~500ms-1s between process closing romfs image and ams.mitm needing to rebuild if romfs is re-opened.
+ This makes our cache much more effective, previously we were re-building romfs several times.
+ RomFS image ownership was overhauled, with a new reference-counting implementation added (used to implement the above grace period).
+ Certain games (e.g. Puyo Puyo Tetris 2, probably others) were sensitive to this timing, and could use access patterns which would trigger creation of romfs image while previous romfs image was in the middle of destructor.
+ This could cause a fatal error, because the destructor for the old image could run simultaneously with building the new image.
+ This also provides a speedup versus the 1.2.3 code, with Animal Crossing now taking ~8 fewer seconds to get past the Nintendo Switch logo.
+ General system stability improvements to enhance the user's experience.
## 1.2.3
+ Because ams.TMA is taking longer to develop than expected, experimental support for Atmosphère's gdbstub as a standalone is now available.
+ To enable it, set `atmosphere!enable_standalone_gdbstub` = u8!0x1 in system_settings.ini.
+ The standalone also requires `atmosphere!enable_htc` = u8!0x0, but this should be the case for everyone since ams.TMA isn't actually usable yet.
+ Once enabled, open the devkitPro provided-gdb (`aarch64-none-elf-gdb` for 64-bit or `arm-none-eabi-gdb` for 32-bit).
+ The standalone stub exposes itself on port 22225 -- so the command to connect is `target extended-remote <ip address>:22225`.
+ Type `info os processes` to get a list of process IDs that can be attached to.
+ The stub should work on both system programs, games, and homebrew -- but please note that debugging certain processes (like sockets) can cause hang due to the stub using them itself.
+ Software break-points, hardware break-points, hardware watch-points, and hardware single-step are all supported/implemented.
+ The following monitor commands are currently supported:
+ `monitor get info`: Get process info, address space layout, and information on modules.
+ `monitor get mappings`: Get all memory mappings.
+ `monitor get mapping <addr>`: Get the memory mapping for a specific address.
+ `monitor wait application`: Causes the stub to wait for an application to be launched. The next application will be started suspended.
+ User is expected to send `attach <pid>` after launching, which will cause attach-on-first-instruction. Failure to attach may cause system instability, this probably needs work.
+ **Please Note**: The GDBstub is new and may have bugs/need work. If you find issues, please report them to SciresM#0524 -- all help finding/fixing bugs is appreciated, here.
+ Generally speaking, if you would like to report information about fixes needed/discuss development of the gdbstub, join ReSwitched's #dev-support channel.
+ Changes were made to the way fs.mitm builds images when providing a layeredfs romfs.
+ Animal Crossing's 2.0.0 update contains >99000 files, and has tables so big that we ran out of memory even after the optimizations made in 0.10.5.
+ Previously, we used fixed-sized 0x40000 work buffers for file/directory tables and simultaneously built hash/content tables in one loop over files/directories.
+ We now iterate over the file/directory tables multiple times, first once to determine the hash table indices, then repeatedly to build hash tables, then once to build content tables.
+ We also now allow smaller-than-0x40000 work buffers, trying half-as-big buffers until allocation succeeds (or work buffer would be <0x4000, which is a safeguard against truly horrible performance).
+ There is a slight speed penalty to these changes, but it's on the order of seconds for the worst case (Animal Crossing) and trivial for most games with reasonable tables.
+ If you encounter a game that exhausts ams.mitm's memory (crashing it) when loading layeredfs mods, please contact `SciresM#0524`.
+ It's really hard to imagine any game being worse than Animal Crossing, but if it happens again I will drop everything to fix it as usual.
+ `creport` now attempts to parse symbol tables if present.
+ If a game executable has a symbol for a given address, the function-relative-offset will now be printed after the module-relative-offset.
+ General system stability improvements to enhance the user's experience.
## 1.2.2
+ A number of fixes were made to Atmosphère's implementation of the new "sprofile" service added in 13.0.0.
+ Nintendo is finally transmitting data over the internet to certain consoles, which has allowed for validating our service implementation.
+ Unfortunately, there were several problems, and if your console began trying to use the new services atmosphere would show a fatal error with code 0xCAF6 (sprofile::ResultInvalidState()).
+ With actual test data in hand, a test program was written and it was verified that our implementation can successfully import/access profile data now.
+ Hopefully there are no more issues, and I sincerely apologize for anyone who got an 0xCAF6 fatal due to this.
+ A number of minor improvements were made to `mesosphère`, including:
+ KThread::GetContextForSchedulerLoop was implemented in assembly (using static assertions to verify offset-of-context-in-struct is correct).
+ This saves an unnecessary function call in the middle of the scheduler hot loop, replacing it with an addition instruction, which should improve microperformance.
+ Mesosphere's hardware maintenance instructions were audited via a script and now directly match Nintendo's kernels.
+ Notably, this inserts a missing instruction synchronization barrier when validating that slab heaps may be constructed.
+ This missing ISB could cause an abort on certain (see: particularly sensitive) hardware on boot if the relevant codepath was speculatively executed (it normally only executes on game launch...)
+ The SVC handlers for performing light IPC (normally unused) from 32-bit process were fixed in Mesosphere.
+ A bug was fixed that would cause the register x27 to be overwritten with the contents of x26 when returning from a user exception handler.
+ A bug was fixed that would cause the kernel to use the userland stack pointer instead of the kernel stack pointer while generating an error report for a kernel abort.
+ General system stability improvements to enhance the user's experience.
## 1.2.1
+ Support was implemented for 13.1.0.
+ `mesosphère` was updated to reflect the kernel behavioral changes made in 13.1.0.
+ KScheduler now issues a data memory barrier when unlocking the scheduler lock and when early-returning due to top-thread-is-current during scheduling.
+ `erpt` was updated to reflect the latest official behaviors.
+ The new service added in 13.0.0 ("sprofile") was revised, and the data formats it expects was changed.
+ This still appears to be (possibly(?)) untestable due to data not being transmitted yet, but I have greater confidence things will go smoothly than I did when 1.1.0 released.
+ A number of improvements were made to `mesosphère`, including:
+ A build target was created to build targeting the qemu `virt` board.
+ This facilitates writing unit tests for the kernel (and other atmosphere components) and running them under PC.
+ **Please Note**: Official system software will not work at all under this, and the Atmosphère project has zero interest in attempting to run official software of any kind. This is unit testing machinery, and explicitly not more than that.
+ This should hopefully allow us to have greater confidence that all of atmosphere's components work the way they're theoretically supposed to in the future.
+ **Please Note**: If you are a developer who is familiar with the Horizon operating system (or capable of becoming familiar), I would greatly appreciate help writing tests and improving the testing framework.
+ Please contact `SciresM#0524` if you are capable and interested.
+ Really, if you are actually a developer who would like to help me get this off the ground, I would deeply appreciate it.
+ That said, if you are not a developer but want to be one, this probably isn't the best opportunity; I expect it to be highly technical.
+ Consider the ReSwitched discord's #hack-n-all channel for your educational purposes.
+ We are (at least for now) using [catch2](https://github.com/catchorg/Catch2) for unit tests.
+ Almost all virtual calls in the kernel are now resolved statically.
+ This eliminates substantial virtual call overhead, and should lead to improved kernel microperformance in pretty much every function.
+ The remaining red black tree find operations which weren't using the optimized "find key" variant are now using the optimized version.
+ Custom assembly was written to improve tick-to-timespan conversion.
+ This works around gcc emitting suboptimal assembly at -Os (it emits good assembly at -O3, clang is fine at both -O3 and -Os).
+ KThread and KSession structures were updated to optimize member layout, saving 0x10 bytes per KThread/KSession object.
+ Rather than unnecessarily zero-ing all data in kernel objects only to overwrite members later, we now only initialize the members we need to in kernel object constructors.
+ This is what Nintendo was doing already.
+ A set of custom optimized atomic primitives were implemented and are used in place of std::atomic<>
+ This works around a gcc bug which downgrades specified memory order to seq_cst, and introduces clrex in places where it is appropriate.
+ This should strictly improve microperformance of many system calls.
+ An compile-time toggleable extension was added to support 40-bit physical addresses in MapRange capabilities (using currently reserved bits).
+ A number of minor bugs were fixed, including:
+ Initial cache management now better reflects official behavior.
+ This fixes an issue that caused certain hardware with cache sensitivity to produce cryptic kernel panics during boot.
+ Incorrect logic when checking thread priority capabilities was fixed to reflect official behavior.
+ The scheduler was updated to reflect latest official behavior, and a number of minor bugs involving clz/ctz were fixed.
+ Accesses to the processes local region were fixed to properly use kernel linear region, not userland pointers.
+ The cache SVCs exposed for 32-bit processes now better reflect official core mask request semantics.
+ A bug was fixed that could cause a kernel panic if SvcArbitrateLock was called on a thread with exactly one reference in the middle of handling a user-mode exception.
+ General system stability improvements to enhance the user's experience.
## 1.2.0 ## 1.2.0
+ `boot` was updated to reflect the latest official behavior for display/battery management. + `boot` was updated to reflect the latest official behavior for display/battery management.
+ This should fix any issues that might result from running older releases on the OLED model, if you're somehow in a position to do so. + This should fix any issues that might result from running older releases on the OLED model, if you're somehow in a position to do so.

6
emummc/.gitrepo vendored
View File

@@ -6,7 +6,7 @@
[subrepo] [subrepo]
remote = https://github.com/m4xw/emuMMC remote = https://github.com/m4xw/emuMMC
branch = develop branch = develop
commit = f66087313546161a000ee196a788f0626caf80fa commit = a9d56959460fc794ce2cb6405402c25a3e89c47f
parent = 38f9a76ba028995ed3274da3a45b0254f09d1f59 parent = ff719641396c635b735873fb2b020c910f768a04
method = rebase method = merge
cmdver = 0.4.1 cmdver = 0.4.1

16
emummc/README.md vendored
View File

@@ -1,21 +1,21 @@
# emuMMC # emuMMC
*A SDMMC driver replacement for Nintendo's Filesystem Services, by **m4xw*** *A SDMMC driver replacement for Nintendo's Filesystem Services, by **m4xw***
### Supported Horizon Versions ### Supported Horizon Versions
**1.0.0 - 13.0.0** **1.0.0 - 13.1.0**
## Features ## Features
* Arbitrary SDMMC backend selection * Arbitrary SDMMC backend selection
**This allows loading eMMC from SD or even SD from eMMC** **This allows loading eMMC from SD or even SD from eMMC**
* On the fly hooking / patching, fully self-infesting * On the fly hooking / patching, fully self-infesting
**Only one payload required for all versions!** **Only one payload required for all versions!**
* File-based SDMMC backend support (from SD) * File-based SDMMC backend support (from SD)
**This allows loading eMMC images from hekate-backups (split or not)** **This allows loading eMMC images from hekate-backups (split or not)**
* SDMMC device based sector offset (*currently eMMC only*) * SDMMC device based sector offset (*currently eMMC only*)
**Raw partition support for eMMC from SD with less performance overhead** **Raw partition support for eMMC from SD with less performance overhead**
* Full support for `/Nintendo` folder redirection to a arbitrary path * Full support for `/Nintendo` folder redirection to a arbitrary path
**No 8 char length restriction!** **No 8 char length restriction!**
* exosphere based context configuration * exosphere based context configuration
**This includes full support for multiple emuMMC images** **This includes full support for multiple emuMMC images**
## Compiling ## Compiling

View File

@@ -57,6 +57,8 @@
#include "offsets/1203_exfat.h" #include "offsets/1203_exfat.h"
#include "offsets/1300.h" #include "offsets/1300.h"
#include "offsets/1300_exfat.h" #include "offsets/1300_exfat.h"
#include "offsets/1310.h"
#include "offsets/1310_exfat.h"
#include "../utils/fatal.h" #include "../utils/fatal.h"
#define GET_OFFSET_STRUCT_NAME(vers) g_offsets##vers #define GET_OFFSET_STRUCT_NAME(vers) g_offsets##vers
@@ -125,6 +127,8 @@ DEFINE_OFFSET_STRUCT(_1203);
DEFINE_OFFSET_STRUCT(_1203_EXFAT); DEFINE_OFFSET_STRUCT(_1203_EXFAT);
DEFINE_OFFSET_STRUCT(_1300); DEFINE_OFFSET_STRUCT(_1300);
DEFINE_OFFSET_STRUCT(_1300_EXFAT); DEFINE_OFFSET_STRUCT(_1300_EXFAT);
DEFINE_OFFSET_STRUCT(_1310);
DEFINE_OFFSET_STRUCT(_1310_EXFAT);
const fs_offsets_t *get_fs_offsets(enum FS_VER version) { const fs_offsets_t *get_fs_offsets(enum FS_VER version) {
switch (version) { switch (version) {
@@ -210,6 +214,10 @@ const fs_offsets_t *get_fs_offsets(enum FS_VER version) {
return &(GET_OFFSET_STRUCT_NAME(_1300)); return &(GET_OFFSET_STRUCT_NAME(_1300));
case FS_VER_13_0_0_EXFAT: case FS_VER_13_0_0_EXFAT:
return &(GET_OFFSET_STRUCT_NAME(_1300_EXFAT)); return &(GET_OFFSET_STRUCT_NAME(_1300_EXFAT));
case FS_VER_13_1_0:
return &(GET_OFFSET_STRUCT_NAME(_1310));
case FS_VER_13_1_0_EXFAT:
return &(GET_OFFSET_STRUCT_NAME(_1310_EXFAT));
default: default:
fatal_abort(Fatal_UnknownVersion); fatal_abort(Fatal_UnknownVersion);
} }

View File

@@ -83,6 +83,9 @@ enum FS_VER
FS_VER_13_0_0, FS_VER_13_0_0,
FS_VER_13_0_0_EXFAT, FS_VER_13_0_0_EXFAT,
FS_VER_13_1_0,
FS_VER_13_1_0_EXFAT,
FS_VER_MAX, FS_VER_MAX,
}; };

59
emummc/source/FS/offsets/1310.h vendored Normal file
View File

@@ -0,0 +1,59 @@
/*
* Copyright (c) 2019 m4xw <m4x@m4xw.net>
* Copyright (c) 2019 Atmosphere-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __FS_1310_H__
#define __FS_1310_H__
// Accessor vtable getters
#define FS_OFFSET_1310_SDMMC_ACCESSOR_GC 0x158C20
#define FS_OFFSET_1310_SDMMC_ACCESSOR_SD 0x15AA30
#define FS_OFFSET_1310_SDMMC_ACCESSOR_NAND 0x159150
// Hooks
#define FS_OFFSET_1310_SDMMC_WRAPPER_READ 0x1545C0
#define FS_OFFSET_1310_SDMMC_WRAPPER_WRITE 0x154680
#define FS_OFFSET_1310_RTLD 0x688
#define FS_OFFSET_1310_RTLD_DESTINATION ((uintptr_t)(INT64_C(-0x3C)))
#define FS_OFFSET_1310_CLKRST_SET_MIN_V_CLK_RATE 0x1537C0
// Misc funcs
#define FS_OFFSET_1310_LOCK_MUTEX 0x29690
#define FS_OFFSET_1310_UNLOCK_MUTEX 0x296E0
#define FS_OFFSET_1310_SDMMC_WRAPPER_CONTROLLER_OPEN 0x1544A0
#define FS_OFFSET_1310_SDMMC_WRAPPER_CONTROLLER_CLOSE 0x154530
// Misc Data
#define FS_OFFSET_1310_SD_MUTEX 0xE133E8
#define FS_OFFSET_1310_NAND_MUTEX 0xE0E768
#define FS_OFFSET_1310_ACTIVE_PARTITION 0xE0E7A8
#define FS_OFFSET_1310_SDMMC_DAS_HANDLE 0xDF6E18
// NOPs
#define FS_OFFSET_1310_SD_DAS_INIT 0x27744
// Nintendo Paths
#define FS_OFFSET_1310_NINTENDO_PATHS \
{ \
{.opcode_reg = 3, .adrp_offset = 0x0006EBE0, .add_rel_offset = 0x00000004}, \
{.opcode_reg = 3, .adrp_offset = 0x0007BEEC, .add_rel_offset = 0x00000004}, \
{.opcode_reg = 4, .adrp_offset = 0x00082294, .add_rel_offset = 0x00000004}, \
{.opcode_reg = 4, .adrp_offset = 0x0009422C, .add_rel_offset = 0x00000004}, \
{.opcode_reg = 0, .adrp_offset = 0, .add_rel_offset = 0}, \
}
#endif // __FS_1310_H__

59
emummc/source/FS/offsets/1310_exfat.h vendored Normal file
View File

@@ -0,0 +1,59 @@
/*
* Copyright (c) 2019 m4xw <m4x@m4xw.net>
* Copyright (c) 2019 Atmosphere-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __FS_1310_EXFAT_H__
#define __FS_1310_EXFAT_H__
// Accessor vtable getters
#define FS_OFFSET_1310_EXFAT_SDMMC_ACCESSOR_GC 0x158C20
#define FS_OFFSET_1310_EXFAT_SDMMC_ACCESSOR_SD 0x15AA30
#define FS_OFFSET_1310_EXFAT_SDMMC_ACCESSOR_NAND 0x159150
// Hooks
#define FS_OFFSET_1310_EXFAT_SDMMC_WRAPPER_READ 0x1545C0
#define FS_OFFSET_1310_EXFAT_SDMMC_WRAPPER_WRITE 0x154680
#define FS_OFFSET_1310_EXFAT_RTLD 0x688
#define FS_OFFSET_1310_EXFAT_RTLD_DESTINATION ((uintptr_t)(INT64_C(-0x3C)))
#define FS_OFFSET_1310_EXFAT_CLKRST_SET_MIN_V_CLK_RATE 0x1537C0
// Misc funcs
#define FS_OFFSET_1310_EXFAT_LOCK_MUTEX 0x29690
#define FS_OFFSET_1310_EXFAT_UNLOCK_MUTEX 0x296E0
#define FS_OFFSET_1310_EXFAT_SDMMC_WRAPPER_CONTROLLER_OPEN 0x1544A0
#define FS_OFFSET_1310_EXFAT_SDMMC_WRAPPER_CONTROLLER_CLOSE 0x154530
// Misc Data
#define FS_OFFSET_1310_EXFAT_SD_MUTEX 0xE203E8
#define FS_OFFSET_1310_EXFAT_NAND_MUTEX 0xE1B768
#define FS_OFFSET_1310_EXFAT_ACTIVE_PARTITION 0xE1B7A8
#define FS_OFFSET_1310_EXFAT_SDMMC_DAS_HANDLE 0xE03E18
// NOPs
#define FS_OFFSET_1310_EXFAT_SD_DAS_INIT 0x27744
// Nintendo Paths
#define FS_OFFSET_1310_EXFAT_NINTENDO_PATHS \
{ \
{.opcode_reg = 3, .adrp_offset = 0x0006EBE0, .add_rel_offset = 0x00000004}, \
{.opcode_reg = 3, .adrp_offset = 0x0007BEEC, .add_rel_offset = 0x00000004}, \
{.opcode_reg = 4, .adrp_offset = 0x00082294, .add_rel_offset = 0x00000004}, \
{.opcode_reg = 4, .adrp_offset = 0x0009422C, .add_rel_offset = 0x00000004}, \
{.opcode_reg = 0, .adrp_offset = 0, .add_rel_offset = 0}, \
}
#endif // __FS_1310_EXFAT_H__

View File

@@ -150,6 +150,9 @@ namespace ams::nxboot {
FsVersion_13_0_0, FsVersion_13_0_0,
FsVersion_13_0_0_Exfat, FsVersion_13_0_0_Exfat,
FsVersion_13_1_0,
FsVersion_13_1_0_Exfat,
FsVersion_Count, FsVersion_Count,
}; };
@@ -215,6 +218,9 @@ namespace ams::nxboot {
{ 0x7D, 0x20, 0x05, 0x47, 0x17, 0x8A, 0x83, 0x6A }, /* FsVersion_13_0_0 */ { 0x7D, 0x20, 0x05, 0x47, 0x17, 0x8A, 0x83, 0x6A }, /* FsVersion_13_0_0 */
{ 0x51, 0xEB, 0xFA, 0x9C, 0xCF, 0x66, 0xC0, 0x9E }, /* FsVersion_13_0_0_Exfat */ { 0x51, 0xEB, 0xFA, 0x9C, 0xCF, 0x66, 0xC0, 0x9E }, /* FsVersion_13_0_0_Exfat */
{ 0x91, 0xBA, 0x65, 0xA2, 0x1C, 0x1D, 0x50, 0xAE }, /* FsVersion_13_1_0 */
{ 0x76, 0x38, 0x27, 0xEE, 0x9C, 0x20, 0x7E, 0x5B }, /* FsVersion_13_1_0_Exfat */
}; };
const InitialProcessBinaryHeader *FindInitialProcessBinary(const pkg2::Package2Header *header, const u8 *data, ams::TargetFirmware target_firmware) { const InitialProcessBinaryHeader *FindInitialProcessBinary(const pkg2::Package2Header *header, const u8 *data, ams::TargetFirmware target_firmware) {
@@ -603,6 +609,11 @@ namespace ams::nxboot {
AddPatch(fs_meta, 0x159119, NogcPatch0, sizeof(NogcPatch0)); AddPatch(fs_meta, 0x159119, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x1426D0, NogcPatch1, sizeof(NogcPatch1)); AddPatch(fs_meta, 0x1426D0, NogcPatch1, sizeof(NogcPatch1));
break; break;
case FsVersion_13_1_0:
case FsVersion_13_1_0_Exfat:
AddPatch(fs_meta, 0x1590B9, NogcPatch0, sizeof(NogcPatch0));
AddPatch(fs_meta, 0x142670, NogcPatch1, sizeof(NogcPatch1));
break;
default: default:
break; break;
} }

View File

@@ -6,7 +6,7 @@
[subrepo] [subrepo]
remote = https://github.com/Atmosphere-NX/Atmosphere-libs remote = https://github.com/Atmosphere-NX/Atmosphere-libs
branch = master branch = master
commit = cf765c0946cc5c828364ae6bfccddc4041304f28 commit = c4d0335b79da7207b49abf1988f45b0168b692f0
parent = 8634ea0f7c4f0e68adf2dfaaddc6ae1e225c4fc2 parent = 96631d8225611b2b490ec1e8b5a84c1b0e53157a
method = merge method = merge
cmdver = 0.4.1 cmdver = 0.4.1

View File

@@ -0,0 +1,11 @@
ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>/devkitpro")
endif
include $(DEVKITPRO)/devkitARM/base_rules
export ATMOSPHERE_DEFINES += -DATMOSPHERE_ARCH_ARM_V4T
export ATMOSPHERE_SETTINGS +=
export ATMOSPHERE_CFLAGS +=
export ATMOSPHERE_CXXFLAGS +=
export ATMOSPHERE_ASFLAGS +=

View File

@@ -0,0 +1,11 @@
ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>/devkitpro")
endif
include $(DEVKITPRO)/devkitA64/base_rules
export ATMOSPHERE_DEFINES += -DATMOSPHERE_ARCH_ARM_V8A
export ATMOSPHERE_SETTINGS +=
export ATMOSPHERE_CFLAGS +=
export ATMOSPHERE_CXXFLAGS +=
export ATMOSPHERE_ASFLAGS +=

View File

@@ -39,6 +39,9 @@ export ATMOSPHERE_ARCH_NAME := arm64
export ATMOSPHERE_BOARD_NAME := nintendo_nx export ATMOSPHERE_BOARD_NAME := nintendo_nx
export ATMOSPHERE_OS_NAME := horizon export ATMOSPHERE_OS_NAME := horizon
export ATMOSPHERE_SUB_ARCH_DIR = armv8a
export ATMOSPHERE_SUB_ARCH_NAME = armv8a
export ATMOSPHERE_CPU_EXTENSIONS := arm_crypto_extension aarch64_crypto_extension export ATMOSPHERE_CPU_EXTENSIONS := arm_crypto_extension aarch64_crypto_extension
else ifeq ($(ATMOSPHERE_CPU),arm7tdmi) else ifeq ($(ATMOSPHERE_CPU),arm7tdmi)
export ATMOSPHERE_ARCH_DIR := arm export ATMOSPHERE_ARCH_DIR := arm
@@ -49,6 +52,9 @@ export ATMOSPHERE_ARCH_NAME := arm
export ATMOSPHERE_BOARD_NAME := nintendo_nx export ATMOSPHERE_BOARD_NAME := nintendo_nx
export ATMOSPHERE_OS_NAME := horizon export ATMOSPHERE_OS_NAME := horizon
export ATMOSPHERE_SUB_ARCH_DIR = armv4t
export ATMOSPHERE_SUB_ARCH_NAME = armv4t
export ATMOSPHERE_CPU_EXTENSIONS := export ATMOSPHERE_CPU_EXTENSIONS :=
endif endif
@@ -64,6 +70,9 @@ export ATMOSPHERE_ARCH_NAME := arm64
export ATMOSPHERE_BOARD_NAME := qemu_virt export ATMOSPHERE_BOARD_NAME := qemu_virt
export ATMOSPHERE_OS_NAME := horizon export ATMOSPHERE_OS_NAME := horizon
export ATMOSPHERE_SUB_ARCH_DIR = armv8a
export ATMOSPHERE_SUB_ARCH_NAME = armv8a
export ATMOSPHERE_CPU_EXTENSIONS := arm_crypto_extension aarch64_crypto_extension export ATMOSPHERE_CPU_EXTENSIONS := arm_crypto_extension aarch64_crypto_extension
endif endif
@@ -85,14 +94,27 @@ export ATMOSPHERE_BOARD_MAKE_DIR := $(ATMOSPHERE_CONFIG_MAKE_DIR)/board/$(ATMOSP
export ATMOSPHERE_OS_MAKE_DIR := $(ATMOSPHERE_CONFIG_MAKE_DIR)/os/$(ATMOSPHERE_OS_DIR) export ATMOSPHERE_OS_MAKE_DIR := $(ATMOSPHERE_CONFIG_MAKE_DIR)/os/$(ATMOSPHERE_OS_DIR)
export ATMOSPHERE_CPU_MAKE_DIR := $(ATMOSPHERE_ARCH_MAKE_DIR)/cpu/$(ATMOSPHERE_CPU_DIR) export ATMOSPHERE_CPU_MAKE_DIR := $(ATMOSPHERE_ARCH_MAKE_DIR)/cpu/$(ATMOSPHERE_CPU_DIR)
ifneq ($(strip $(ATMOSPHERE_SUB_ARCH_NAME)),)
export ATMOSPHERE_LIBRARY_DIR := lib_$(ATMOSPHERE_BOARD_NAME)_$(ATMOSPHERE_ARCH_NAME)_$(ATMOSPHERE_SUB_ARCH_NAME)
export ATMOSPHERE_BUILD_DIR := build_$(ATMOSPHERE_BOARD_NAME)_$(ATMOSPHERE_ARCH_NAME)_$(ATMOSPHERE_SUB_ARCH_NAME)
else
export ATMOSPHERE_LIBRARY_DIR := lib_$(ATMOSPHERE_BOARD_NAME)_$(ATMOSPHERE_ARCH_NAME) export ATMOSPHERE_LIBRARY_DIR := lib_$(ATMOSPHERE_BOARD_NAME)_$(ATMOSPHERE_ARCH_NAME)
export ATMOSPHERE_BUILD_DIR := build_$(ATMOSPHERE_BOARD_NAME)_$(ATMOSPHERE_ARCH_NAME) export ATMOSPHERE_BUILD_DIR := build_$(ATMOSPHERE_BOARD_NAME)_$(ATMOSPHERE_ARCH_NAME)
endif
include $(ATMOSPHERE_ARCH_MAKE_DIR)/arch.mk include $(ATMOSPHERE_ARCH_MAKE_DIR)/arch.mk
include $(ATMOSPHERE_BOARD_MAKE_DIR)/board.mk include $(ATMOSPHERE_BOARD_MAKE_DIR)/board.mk
include $(ATMOSPHERE_OS_MAKE_DIR)/os.mk include $(ATMOSPHERE_OS_MAKE_DIR)/os.mk
include $(ATMOSPHERE_CPU_MAKE_DIR)/cpu.mk include $(ATMOSPHERE_CPU_MAKE_DIR)/cpu.mk
ifneq ($(strip $(ATMOSPHERE_SUB_ARCH_NAME)),)
export ATMOSPHERE_SUB_ARCH_MAKE_DIR := $(ATMOSPHERE_CONFIG_MAKE_DIR)/arch/$(ATMOSPHERE_SUB_ARCH_DIR)
include $(ATMOSPHERE_SUB_ARCH_MAKE_DIR)/arch.mk
endif
#--------------------------------------------------------------------------------- #---------------------------------------------------------------------------------
# get atmosphere git revision information # get atmosphere git revision information
#--------------------------------------------------------------------------------- #---------------------------------------------------------------------------------
@@ -125,12 +147,20 @@ DATA := data
INCLUDES := include INCLUDES := include
GENERAL_SOURCE_DIRS=$1 $(foreach d,$(filter-out $1/arch $1/board $1/os $1/cpu $1,$(wildcard $1/*)),$(if $(wildcard $d/.),$(filter-out $d,$(call GENERAL_SOURCE_DIRS,$d)) $d,)) GENERAL_SOURCE_DIRS=$1 $(foreach d,$(filter-out $1/arch $1/board $1/os $1/cpu $1,$(wildcard $1/*)),$(if $(wildcard $d/.),$(filter-out $d,$(call GENERAL_SOURCE_DIRS,$d)) $d,))
SPECIFIC_SOURCE_DIRS=$(if $(wildcard $1/$2/$3/.*),$1/$2/$3 $(call DIR_WILDCARD,$1/$2/$3),$(if $(wildcard $1/$2/generic/.*), $1/$2/generic $(call DIR_WILDCARD,$1/$2/generic),)) SPECIFIC_SOURCE_DIRS=$(if $(wildcard $1/$2/$3/.*),$1/$2/$3 $(call DIR_WILDCARD,$1/$2/$3),$(if $(wildcard $1/$2/generic/.*), $1/$2/generic $(call DIR_WILDCARD,$1/$2/generic),))
ifneq ($(strip $(ATMOSPHERE_SUB_ARCH_NAME)),)
SPECIFIC_SOURCE_DIRS_ARCH=$(if $(wildcard $1/$2/$3/.*),$1/$2/$3 $(call DIR_WILDCARD,$1/$2/$3),$(if $(wildcard $1/$2/$4/.*),$1/$2/$4 $(call DIR_WILDCARD,$1/$2/$4),$(if $(wildcard $1/$2/generic/.*), $1/$2/generic $(call DIR_WILDCARD,$1/$2/generic),)))
else
SPECIFIC_SOURCE_DIRS_ARCH=$(if $(wildcard $1/$2/$3/.*),$1/$2/$3 $(call DIR_WILDCARD,$1/$2/$3),$(if $(wildcard $1/$2/generic/.*), $1/$2/generic $(call DIR_WILDCARD,$1/$2/generic),))
endif
UNFILTERED_SOURCE_DIRS=$1 $(foreach d,$(wildcard $1/*),$(if $(wildcard $d/.),$(call DIR_WILDCARD,$d) $d,)) UNFILTERED_SOURCE_DIRS=$1 $(foreach d,$(wildcard $1/*),$(if $(wildcard $d/.),$(call DIR_WILDCARD,$d) $d,))
ALL_SOURCE_DIRS=$(foreach d,$(call GENERAL_SOURCE_DIRS,$1), \ ALL_SOURCE_DIRS=$(foreach d,$(call GENERAL_SOURCE_DIRS,$1), \
$d \ $d \
$(call SPECIFIC_SOURCE_DIRS,$d,arch,$(ATMOSPHERE_ARCH_DIR)) \ $(call SPECIFIC_SOURCE_DIRS_ARCH,$d,arch,$(ATMOSPHERE_ARCH_DIR),$(ATMOSPHERE_SUB_ARCH_DIR)) \
$(call SPECIFIC_SOURCE_DIRS,$d,board,$(ATMOSPHERE_BOARD_DIR)) \ $(call SPECIFIC_SOURCE_DIRS,$d,board,$(ATMOSPHERE_BOARD_DIR)) \
$(call SPECIFIC_SOURCE_DIRS,$d,os,$(ATMOSPHERE_OS_DIR)) \ $(call SPECIFIC_SOURCE_DIRS,$d,os,$(ATMOSPHERE_OS_DIR)) \
$(call SPECIFIC_SOURCE_DIRS,$d,cpu,$(ATMOSPHERE_ARCH_DIR)/$(ATMOSPHERE_CPU_DIR)) \ $(call SPECIFIC_SOURCE_DIRS,$d,cpu,$(ATMOSPHERE_ARCH_DIR)/$(ATMOSPHERE_CPU_DIR)) \
@@ -147,7 +177,7 @@ FIND_SOURCE_FILES=$(foreach dir,$1,$(filter-out $(notdir $(wildcard $(dir)/*.arc
$(notdir $(wildcard $(dir)/*.os.*.$2)) \ $(notdir $(wildcard $(dir)/*.os.*.$2)) \
$(notdir $(wildcard $(dir)/.cpu.*.$2)), \ $(notdir $(wildcard $(dir)/.cpu.*.$2)), \
$(notdir $(wildcard $(dir)/*.$2)))) \ $(notdir $(wildcard $(dir)/*.$2)))) \
$(foreach dir,$1,$(call FIND_SPECIFIC_SOURCE_FILES,$(dir),arch,$(ATMOSPHERE_ARCH_NAME),$2)) \ $(foreach dir,$1,$(call FIND_SPECIFIC_SOURCE_FILES_EX,$(dir),arch,$(ATMOSPHERE_ARCH_NAME) $(ATMOSPHERE_SUB_ARCH_NAME),$2)) \
$(foreach dir,$1,$(call FIND_SPECIFIC_SOURCE_FILES,$(dir),board,$(ATMOSPHERE_BOARD_NAME),$2)) \ $(foreach dir,$1,$(call FIND_SPECIFIC_SOURCE_FILES,$(dir),board,$(ATMOSPHERE_BOARD_NAME),$2)) \
$(foreach dir,$1,$(call FIND_SPECIFIC_SOURCE_FILES,$(dir),os,$(ATMOSPHERE_OS_NAME),$2)) \ $(foreach dir,$1,$(call FIND_SPECIFIC_SOURCE_FILES,$(dir),os,$(ATMOSPHERE_OS_NAME),$2)) \
$(foreach dir,$1,$(call FIND_SPECIFIC_SOURCE_FILES_EX,$(dir),cpu,$(ATMOSPHERE_CPU_NAME) $(ATMOSPHERE_CPU_EXTENSIONS),$2)) $(foreach dir,$1,$(call FIND_SPECIFIC_SOURCE_FILES_EX,$(dir),cpu,$(ATMOSPHERE_CPU_NAME) $(ATMOSPHERE_CPU_EXTENSIONS),$2))

View File

@@ -93,3 +93,4 @@
/* Deferred includes. */ /* Deferred includes. */
#include <mesosphere/kern_k_auto_object_impls.hpp> #include <mesosphere/kern_k_auto_object_impls.hpp>
#include <mesosphere/kern_k_scheduler_impls.hpp>

View File

@@ -279,7 +279,7 @@ namespace ams::kern::arch::arm64::init {
/* Invalidate the entire tlb. */ /* Invalidate the entire tlb. */
cpu::DataSynchronizationBarrierInnerShareable(); cpu::DataSynchronizationBarrierInnerShareable();
cpu::InvalidateEntireTlb(); cpu::InvalidateEntireTlbInnerShareable();
/* Copy data, if we should. */ /* Copy data, if we should. */
const u64 negative_block_size_for_mask = static_cast<u64>(-static_cast<s64>(block_size)); const u64 negative_block_size_for_mask = static_cast<u64>(-static_cast<s64>(block_size));
@@ -350,7 +350,6 @@ namespace ams::kern::arch::arm64::init {
/* If we don't already have an L2 table, we need to make a new one. */ /* If we don't already have an L2 table, we need to make a new one. */
if (!l1_entry->IsTable()) { if (!l1_entry->IsTable()) {
KPhysicalAddress new_table = AllocateNewPageTable(allocator); KPhysicalAddress new_table = AllocateNewPageTable(allocator);
ClearNewPageTable(new_table);
*l1_entry = L1PageTableEntry(PageTableEntry::TableTag{}, new_table, attr.IsPrivilegedExecuteNever()); *l1_entry = L1PageTableEntry(PageTableEntry::TableTag{}, new_table, attr.IsPrivilegedExecuteNever());
cpu::DataSynchronizationBarrierInnerShareable(); cpu::DataSynchronizationBarrierInnerShareable();
} }
@@ -361,12 +360,12 @@ namespace ams::kern::arch::arm64::init {
if (util::IsAligned(GetInteger(virt_addr), L2ContiguousBlockSize) && util::IsAligned(GetInteger(phys_addr), L2ContiguousBlockSize) && size >= L2ContiguousBlockSize) { if (util::IsAligned(GetInteger(virt_addr), L2ContiguousBlockSize) && util::IsAligned(GetInteger(phys_addr), L2ContiguousBlockSize) && size >= L2ContiguousBlockSize) {
for (size_t i = 0; i < L2ContiguousBlockSize / L2BlockSize; i++) { for (size_t i = 0; i < L2ContiguousBlockSize / L2BlockSize; i++) {
l2_entry[i] = L2PageTableEntry(PageTableEntry::BlockTag{}, phys_addr, attr, PageTableEntry::SoftwareReservedBit_None, true); l2_entry[i] = L2PageTableEntry(PageTableEntry::BlockTag{}, phys_addr, attr, PageTableEntry::SoftwareReservedBit_None, true);
cpu::DataSynchronizationBarrierInnerShareable();
virt_addr += L2BlockSize; virt_addr += L2BlockSize;
phys_addr += L2BlockSize; phys_addr += L2BlockSize;
size -= L2BlockSize; size -= L2BlockSize;
} }
cpu::DataSynchronizationBarrierInnerShareable();
continue; continue;
} }
@@ -384,7 +383,6 @@ namespace ams::kern::arch::arm64::init {
/* If we don't already have an L3 table, we need to make a new one. */ /* If we don't already have an L3 table, we need to make a new one. */
if (!l2_entry->IsTable()) { if (!l2_entry->IsTable()) {
KPhysicalAddress new_table = AllocateNewPageTable(allocator); KPhysicalAddress new_table = AllocateNewPageTable(allocator);
ClearNewPageTable(new_table);
*l2_entry = L2PageTableEntry(PageTableEntry::TableTag{}, new_table, attr.IsPrivilegedExecuteNever()); *l2_entry = L2PageTableEntry(PageTableEntry::TableTag{}, new_table, attr.IsPrivilegedExecuteNever());
cpu::DataSynchronizationBarrierInnerShareable(); cpu::DataSynchronizationBarrierInnerShareable();
} }
@@ -395,12 +393,12 @@ namespace ams::kern::arch::arm64::init {
if (util::IsAligned(GetInteger(virt_addr), L3ContiguousBlockSize) && util::IsAligned(GetInteger(phys_addr), L3ContiguousBlockSize) && size >= L3ContiguousBlockSize) { if (util::IsAligned(GetInteger(virt_addr), L3ContiguousBlockSize) && util::IsAligned(GetInteger(phys_addr), L3ContiguousBlockSize) && size >= L3ContiguousBlockSize) {
for (size_t i = 0; i < L3ContiguousBlockSize / L3BlockSize; i++) { for (size_t i = 0; i < L3ContiguousBlockSize / L3BlockSize; i++) {
l3_entry[i] = L3PageTableEntry(PageTableEntry::BlockTag{}, phys_addr, attr, PageTableEntry::SoftwareReservedBit_None, true); l3_entry[i] = L3PageTableEntry(PageTableEntry::BlockTag{}, phys_addr, attr, PageTableEntry::SoftwareReservedBit_None, true);
cpu::DataSynchronizationBarrierInnerShareable();
virt_addr += L3BlockSize; virt_addr += L3BlockSize;
phys_addr += L3BlockSize; phys_addr += L3BlockSize;
size -= L3BlockSize; size -= L3BlockSize;
} }
cpu::DataSynchronizationBarrierInnerShareable();
continue; continue;
} }

View File

@@ -19,6 +19,9 @@
/* TODO: Different header for this? */ /* TODO: Different header for this? */
#define AMS_KERN_NUM_SUPERVISOR_CALLS 0xC0 #define AMS_KERN_NUM_SUPERVISOR_CALLS 0xC0
/* ams::kern::KThread, https://github.com/Atmosphere-NX/Atmosphere/blob/master/libraries/libmesosphere/include/mesosphere/kern_k_thread.hpp */
#define THREAD_THREAD_CONTEXT 0xD0
/* ams::kern::KThread::StackParameters, https://github.com/Atmosphere-NX/Atmosphere/blob/master/libraries/libmesosphere/include/mesosphere/kern_k_thread.hpp */ /* ams::kern::KThread::StackParameters, https://github.com/Atmosphere-NX/Atmosphere/blob/master/libraries/libmesosphere/include/mesosphere/kern_k_thread.hpp */
#define THREAD_STACK_PARAMETERS_SIZE 0x30 #define THREAD_STACK_PARAMETERS_SIZE 0x30
#define THREAD_STACK_PARAMETERS_SVC_PERMISSION 0x00 #define THREAD_STACK_PARAMETERS_SVC_PERMISSION 0x00

View File

@@ -52,10 +52,19 @@ namespace ams::kern::arch::arm64::cpu {
__asm__ __volatile__("dmb sy" ::: "memory"); __asm__ __volatile__("dmb sy" ::: "memory");
} }
ALWAYS_INLINE void DataMemoryBarrierInnerShareable() {
__asm__ __volatile__("dmb ish" ::: "memory");
}
ALWAYS_INLINE void InstructionMemoryBarrier() { ALWAYS_INLINE void InstructionMemoryBarrier() {
__asm__ __volatile__("isb" ::: "memory"); __asm__ __volatile__("isb" ::: "memory");
} }
ALWAYS_INLINE void EnsureInstructionConsistencyInnerShareable() {
DataSynchronizationBarrierInnerShareable();
InstructionMemoryBarrier();
}
ALWAYS_INLINE void EnsureInstructionConsistency() { ALWAYS_INLINE void EnsureInstructionConsistency() {
DataSynchronizationBarrier(); DataSynchronizationBarrier();
InstructionMemoryBarrier(); InstructionMemoryBarrier();
@@ -173,7 +182,6 @@ namespace ams::kern::arch::arm64::cpu {
NOINLINE void SynchronizeAllCores(); NOINLINE void SynchronizeAllCores();
/* Cache management helpers. */ /* Cache management helpers. */
void ClearPageToZeroImpl(void *);
void StoreEntireCacheForInit(); void StoreEntireCacheForInit();
void FlushEntireCacheForInit(); void FlushEntireCacheForInit();
@@ -186,10 +194,16 @@ namespace ams::kern::arch::arm64::cpu {
void InvalidateEntireInstructionCache(); void InvalidateEntireInstructionCache();
ALWAYS_INLINE void ClearPageToZero(void *page) { ALWAYS_INLINE void ClearPageToZero(void * const page) {
MESOSPHERE_ASSERT(util::IsAligned(reinterpret_cast<uintptr_t>(page), PageSize)); MESOSPHERE_ASSERT(util::IsAligned(reinterpret_cast<uintptr_t>(page), PageSize));
MESOSPHERE_ASSERT(page != nullptr); MESOSPHERE_ASSERT(page != nullptr);
ClearPageToZeroImpl(page);
uintptr_t cur = reinterpret_cast<uintptr_t>(__builtin_assume_aligned(page, PageSize));
const uintptr_t last = cur + PageSize - DataCacheLineSize;
for (/* ... */; cur <= last; cur += DataCacheLineSize) {
__asm__ __volatile__("dc zva, %[cur]" :: [cur]"r"(cur) : "memory");
}
} }
ALWAYS_INLINE void InvalidateTlbByAsid(u32 asid) { ALWAYS_INLINE void InvalidateTlbByAsid(u32 asid) {
@@ -209,6 +223,11 @@ namespace ams::kern::arch::arm64::cpu {
EnsureInstructionConsistency(); EnsureInstructionConsistency();
} }
ALWAYS_INLINE void InvalidateEntireTlbInnerShareable() {
__asm__ __volatile__("tlbi vmalle1is" ::: "memory");
EnsureInstructionConsistencyInnerShareable();
}
ALWAYS_INLINE void InvalidateEntireTlbDataOnly() { ALWAYS_INLINE void InvalidateEntireTlbDataOnly() {
__asm__ __volatile__("tlbi vmalle1is" ::: "memory"); __asm__ __volatile__("tlbi vmalle1is" ::: "memory");
DataSynchronizationBarrier(); DataSynchronizationBarrier();

View File

@@ -105,35 +105,48 @@ namespace ams::kern::arch::arm64 {
Result UnbindLocal(s32 irq); Result UnbindLocal(s32 irq);
Result ClearGlobal(s32 irq); Result ClearGlobal(s32 irq);
Result ClearLocal(s32 irq); Result ClearLocal(s32 irq);
public: private:
static ALWAYS_INLINE u32 DisableInterrupts() { [[nodiscard]] static ALWAYS_INLINE u32 GetInterruptsEnabledState() {
u64 intr_state; u64 intr_state;
__asm__ __volatile__("mrs %[intr_state], daif\n" __asm__ __volatile__("mrs %[intr_state], daif\n"
"msr daifset, #2" "ubfx %[intr_state], %[intr_state], #7, #1"
: [intr_state]"=r"(intr_state) : [intr_state]"=r"(intr_state)
:: "memory"); :: "memory");
return intr_state; return intr_state;
} }
public:
static ALWAYS_INLINE void EnableInterrupts() {
__asm__ __volatile__("msr daifclr, #2" ::: "memory");
}
static ALWAYS_INLINE u32 EnableInterrupts() { static ALWAYS_INLINE void DisableInterrupts() {
u64 intr_state; __asm__ __volatile__("msr daifset, #2" ::: "memory");
__asm__ __volatile__("mrs %[intr_state], daif\n" }
"msr daifclr, #2"
: [intr_state]"=r"(intr_state) [[nodiscard]] static ALWAYS_INLINE u32 GetInterruptsEnabledStateAndDisableInterrupts() {
:: "memory"); const auto intr_state = GetInterruptsEnabledState();
DisableInterrupts();
return intr_state;
}
[[nodiscard]] static ALWAYS_INLINE u32 GetInterruptsEnabledStateAndEnableInterrupts() {
const auto intr_state = GetInterruptsEnabledState();
EnableInterrupts();
return intr_state; return intr_state;
} }
static ALWAYS_INLINE void RestoreInterrupts(u32 intr_state) { static ALWAYS_INLINE void RestoreInterrupts(u32 intr_state) {
u64 cur_state; u64 tmp;
__asm__ __volatile__("mrs %[cur_state], daif" : [cur_state]"=r"(cur_state)); __asm__ __volatile__("mrs %[tmp], daif\n"
__asm__ __volatile__("msr daif, %[intr_state]" :: [intr_state]"r"((cur_state & ~0x80ul) | (intr_state & 0x80))); "bfi %[tmp], %[intr_state], #7, #1\n"
"msr daif, %[tmp]"
: [tmp]"=&r"(tmp)
: [intr_state]"r"(intr_state)
: "memory");
} }
static ALWAYS_INLINE bool AreInterruptsEnabled() { static ALWAYS_INLINE bool AreInterruptsEnabled() {
u64 intr_state; return GetInterruptsEnabledState() == 0;
__asm__ __volatile__("mrs %[intr_state], daif" : [intr_state]"=r"(intr_state));
return (intr_state & 0x80) == 0;
} }
}; };

View File

@@ -219,27 +219,27 @@ namespace ams::kern::arch::arm64 {
Result ChangePermissions(KProcessAddress virt_addr, size_t num_pages, PageTableEntry entry_template, DisableMergeAttribute disable_merge_attr, bool refresh_mapping, PageLinkedList *page_list, bool reuse_ll); Result ChangePermissions(KProcessAddress virt_addr, size_t num_pages, PageTableEntry entry_template, DisableMergeAttribute disable_merge_attr, bool refresh_mapping, PageLinkedList *page_list, bool reuse_ll);
static void PteDataSynchronizationBarrier() { static ALWAYS_INLINE void PteDataSynchronizationBarrier() {
cpu::DataSynchronizationBarrierInnerShareable(); cpu::DataSynchronizationBarrierInnerShareable();
} }
static void ClearPageTable(KVirtualAddress table) { static ALWAYS_INLINE void ClearPageTable(KVirtualAddress table) {
cpu::ClearPageToZero(GetVoidPointer(table)); cpu::ClearPageToZero(GetVoidPointer(table));
} }
void OnTableUpdated() const { ALWAYS_INLINE void OnTableUpdated() const {
cpu::InvalidateTlbByAsid(m_asid); cpu::InvalidateTlbByAsid(m_asid);
} }
void OnKernelTableUpdated() const { ALWAYS_INLINE void OnKernelTableUpdated() const {
cpu::InvalidateEntireTlbDataOnly(); cpu::InvalidateEntireTlbDataOnly();
} }
void OnKernelTableSinglePageUpdated(KProcessAddress virt_addr) const { ALWAYS_INLINE void OnKernelTableSinglePageUpdated(KProcessAddress virt_addr) const {
cpu::InvalidateTlbByVaDataOnly(virt_addr); cpu::InvalidateTlbByVaDataOnly(virt_addr);
} }
void NoteUpdated() const { ALWAYS_INLINE void NoteUpdated() const {
cpu::DataSynchronizationBarrier(); cpu::DataSynchronizationBarrier();
if (this->IsKernel()) { if (this->IsKernel()) {
@@ -249,7 +249,7 @@ namespace ams::kern::arch::arm64 {
} }
} }
void NoteSingleKernelPageUpdated(KProcessAddress virt_addr) const { ALWAYS_INLINE void NoteSingleKernelPageUpdated(KProcessAddress virt_addr) const {
MESOSPHERE_ASSERT(this->IsKernel()); MESOSPHERE_ASSERT(this->IsKernel());
cpu::DataSynchronizationBarrier(); cpu::DataSynchronizationBarrier();

View File

@@ -45,6 +45,7 @@ namespace ams::kern::arch::arm64 {
/* Select L1 cache. */ /* Select L1 cache. */
cpu::SetCsselrEl1(0); cpu::SetCsselrEl1(0);
cpu::InstructionMemoryBarrier();
/* Check that the L1 cache is not direct-mapped. */ /* Check that the L1 cache is not direct-mapped. */
return cpu::CacheSizeIdRegisterAccessor().GetAssociativity() != 0; return cpu::CacheSizeIdRegisterAccessor().GetAssociativity() != 0;

View File

@@ -40,6 +40,12 @@
/* of the right side, and so this does not actually cost any space. */ /* of the right side, and so this does not actually cost any space. */
#define MESOSPHERE_ENABLE_DEVIRTUALIZED_DYNAMIC_CAST #define MESOSPHERE_ENABLE_DEVIRTUALIZED_DYNAMIC_CAST
/* NOTE: This enables usage of KDebug handles as parameter for svc::GetInfo */
/* calls which require a process parameter. This enables a debugger to obtain */
/* address space/layout information, for example. However, it changes abi, and so */
/* this define allows toggling the extension. */
#define MESOSPHERE_ENABLE_GET_INFO_OF_DEBUG_PROCESS
/* NOTE: This uses currently-reserved bits inside the MapRange capability */ /* NOTE: This uses currently-reserved bits inside the MapRange capability */
/* in order to support large physical addresses (40-bit instead of 36). */ /* in order to support large physical addresses (40-bit instead of 36). */
/* This is toggleable in order to disable it if N ever uses those bits. */ /* This is toggleable in order to disable it if N ever uses those bits. */

View File

@@ -46,7 +46,7 @@ namespace ams::kern {
return m_slab_heap->Allocate(m_page_allocator); return m_slab_heap->Allocate(m_page_allocator);
} }
void Free(T *t) const { ALWAYS_INLINE void Free(T *t) const {
m_slab_heap->Free(t); m_slab_heap->Free(t);
} }
}; };

View File

@@ -62,8 +62,7 @@ namespace ams::kern {
KThread *m_idle_thread; KThread *m_idle_thread;
util::Atomic<KThread *> m_current_thread; util::Atomic<KThread *> m_current_thread;
public: public:
constexpr KScheduler() : m_state(), m_is_active(false), m_core_id(0), m_last_context_switch_time(0), m_idle_thread(nullptr), m_current_thread(nullptr) constexpr KScheduler() : m_state(), m_is_active(false), m_core_id(0), m_last_context_switch_time(0), m_idle_thread(nullptr), m_current_thread(nullptr) {
{
m_state.needs_scheduling = true; m_state.needs_scheduling = true;
m_state.interrupt_task_runnable = false; m_state.interrupt_task_runnable = false;
m_state.should_count_idle = false; m_state.should_count_idle = false;
@@ -211,18 +210,6 @@ namespace ams::kern {
static consteval bool ValidateAssemblyOffsets(); static consteval bool ValidateAssemblyOffsets();
}; };
consteval bool KScheduler::ValidateAssemblyOffsets() {
static_assert(AMS_OFFSETOF(KScheduler, m_state.needs_scheduling) == KSCHEDULER_NEEDS_SCHEDULING);
static_assert(AMS_OFFSETOF(KScheduler, m_state.interrupt_task_runnable) == KSCHEDULER_INTERRUPT_TASK_RUNNABLE);
static_assert(AMS_OFFSETOF(KScheduler, m_state.highest_priority_thread) == KSCHEDULER_HIGHEST_PRIORITY_THREAD);
static_assert(AMS_OFFSETOF(KScheduler, m_state.idle_thread_stack) == KSCHEDULER_IDLE_THREAD_STACK);
static_assert(AMS_OFFSETOF(KScheduler, m_state.prev_thread) == KSCHEDULER_PREVIOUS_THREAD);
static_assert(AMS_OFFSETOF(KScheduler, m_state.interrupt_task_manager) == KSCHEDULER_INTERRUPT_TASK_MANAGER);
return true;
}
static_assert(KScheduler::ValidateAssemblyOffsets());
class KScopedSchedulerLock : KScopedLock<KScheduler::LockType> { class KScopedSchedulerLock : KScopedLock<KScheduler::LockType> {
public: public:
explicit ALWAYS_INLINE KScopedSchedulerLock() : KScopedLock(KScheduler::s_scheduler_lock) { /* ... */ } explicit ALWAYS_INLINE KScopedSchedulerLock() : KScopedLock(KScheduler::s_scheduler_lock) { /* ... */ }

View File

@@ -0,0 +1,43 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <mesosphere/kern_common.hpp>
#include <mesosphere/kern_k_scheduler.hpp>
#include <mesosphere/kern_select_interrupt_manager.hpp>
namespace ams::kern {
/* NOTE: This header is included after all main headers. */
consteval bool KScheduler::ValidateAssemblyOffsets() {
static_assert(AMS_OFFSETOF(KScheduler, m_state.needs_scheduling) == KSCHEDULER_NEEDS_SCHEDULING);
static_assert(AMS_OFFSETOF(KScheduler, m_state.interrupt_task_runnable) == KSCHEDULER_INTERRUPT_TASK_RUNNABLE);
static_assert(AMS_OFFSETOF(KScheduler, m_state.highest_priority_thread) == KSCHEDULER_HIGHEST_PRIORITY_THREAD);
static_assert(AMS_OFFSETOF(KScheduler, m_state.idle_thread_stack) == KSCHEDULER_IDLE_THREAD_STACK);
static_assert(AMS_OFFSETOF(KScheduler, m_state.prev_thread) == KSCHEDULER_PREVIOUS_THREAD);
static_assert(AMS_OFFSETOF(KScheduler, m_state.interrupt_task_manager) == KSCHEDULER_INTERRUPT_TASK_MANAGER);
return true;
}
static_assert(KScheduler::ValidateAssemblyOffsets());
ALWAYS_INLINE void KScheduler::RescheduleOtherCores(u64 cores_needing_scheduling) {
if (const u64 core_mask = cores_needing_scheduling & ~(1ul << m_core_id); core_mask != 0) {
cpu::DataSynchronizationBarrier();
Kernel::GetInterruptManager().SendInterProcessorInterrupt(KInterruptName_Scheduler, core_mask);
}
}
}

View File

@@ -74,6 +74,9 @@ namespace ams::kern {
/* Release an instance of the lock. */ /* Release an instance of the lock. */
if ((--m_lock_count) == 0) { if ((--m_lock_count) == 0) {
/* Perform a memory barrier here. */
cpu::DataMemoryBarrierInnerShareable();
/* We're no longer going to hold the lock. Take note of what cores need scheduling. */ /* We're no longer going to hold the lock. Take note of what cores need scheduling. */
const u64 cores_needing_scheduling = SchedulerType::UpdateHighestPriorityThreads(); const u64 cores_needing_scheduling = SchedulerType::UpdateHighestPriorityThreads();

View File

@@ -405,8 +405,6 @@ namespace ams::kern {
constexpr ThreadState GetState() const { return static_cast<ThreadState>(m_thread_state & ThreadState_Mask); } constexpr ThreadState GetState() const { return static_cast<ThreadState>(m_thread_state & ThreadState_Mask); }
constexpr ThreadState GetRawState() const { return m_thread_state; } constexpr ThreadState GetRawState() const { return m_thread_state; }
NOINLINE KThreadContext *GetContextForSchedulerLoop();
constexpr uintptr_t GetConditionVariableKey() const { return m_condvar_key; } constexpr uintptr_t GetConditionVariableKey() const { return m_condvar_key; }
constexpr uintptr_t GetAddressArbiterKey() const { return m_condvar_key; } constexpr uintptr_t GetAddressArbiterKey() const { return m_condvar_key; }
@@ -624,9 +622,7 @@ namespace ams::kern {
void OnTimer(); void OnTimer();
void DoWorkerTaskImpl(); void DoWorkerTaskImpl();
public: public:
static constexpr bool IsConditionVariableThreadTreeValid() { static consteval bool IsKThreadStructurallyValid();
return ConditionVariableThreadTreeTraits::IsValid();
}
static KThread *GetThreadFromId(u64 thread_id); static KThread *GetThreadFromId(u64 thread_id);
static Result GetThreadList(s32 *out_num_threads, ams::kern::svc::KUserPointer<u64 *> out_thread_ids, s32 max_out_count); static Result GetThreadList(s32 *out_num_threads, ams::kern::svc::KUserPointer<u64 *> out_thread_ids, s32 max_out_count);
@@ -634,7 +630,18 @@ namespace ams::kern {
using ConditionVariableThreadTreeType = ConditionVariableThreadTree; using ConditionVariableThreadTreeType = ConditionVariableThreadTree;
}; };
static_assert(alignof(KThread) == 0x10); static_assert(alignof(KThread) == 0x10);
static_assert(KThread::IsConditionVariableThreadTreeValid());
consteval bool KThread::IsKThreadStructurallyValid() {
/* Check that the condition variable tree is valid. */
static_assert(ConditionVariableThreadTreeTraits::IsValid());
/* Check that the assembly offsets are valid. */
static_assert(AMS_OFFSETOF(KThread, m_thread_context) == THREAD_THREAD_CONTEXT);
return true;
}
static_assert(KThread::IsKThreadStructurallyValid());
class KScopedDisableDispatch { class KScopedDisableDispatch {
public: public:

View File

@@ -41,7 +41,7 @@ namespace ams::kern {
private: private:
u32 m_prev_intr_state; u32 m_prev_intr_state;
public: public:
ALWAYS_INLINE KScopedInterruptDisable() : m_prev_intr_state(KInterruptManager::DisableInterrupts()) { /* ... */ } ALWAYS_INLINE KScopedInterruptDisable() : m_prev_intr_state(KInterruptManager::GetInterruptsEnabledStateAndDisableInterrupts()) { /* ... */ }
ALWAYS_INLINE ~KScopedInterruptDisable() { KInterruptManager::RestoreInterrupts(m_prev_intr_state); } ALWAYS_INLINE ~KScopedInterruptDisable() { KInterruptManager::RestoreInterrupts(m_prev_intr_state); }
}; };
@@ -51,7 +51,7 @@ namespace ams::kern {
private: private:
u32 m_prev_intr_state; u32 m_prev_intr_state;
public: public:
ALWAYS_INLINE KScopedInterruptEnable() : m_prev_intr_state(KInterruptManager::EnableInterrupts()) { /* ... */ } ALWAYS_INLINE KScopedInterruptEnable() : m_prev_intr_state(KInterruptManager::GetInterruptsEnabledStateAndEnableInterrupts()) { /* ... */ }
ALWAYS_INLINE ~KScopedInterruptEnable() { KInterruptManager::RestoreInterrupts(m_prev_intr_state); } ALWAYS_INLINE ~KScopedInterruptEnable() { KInterruptManager::RestoreInterrupts(m_prev_intr_state); }
}; };

View File

@@ -76,7 +76,7 @@ namespace ams::kern::arch::arm64::cpu {
} else { } else {
m_counter = cpu::GetPerformanceCounter(m_which); m_counter = cpu::GetPerformanceCounter(m_which);
} }
DataMemoryBarrier(); DataMemoryBarrierInnerShareable();
m_done = true; m_done = true;
return nullptr; return nullptr;
} }

View File

@@ -61,139 +61,3 @@ _ZN3ams4kern4arch5arm643cpu23SynchronizeAllCoresImplEPii:
5: 5:
stlr wzr, [x0] stlr wzr, [x0]
ret ret
/* ams::kern::arch::arm64::cpu::ClearPageToZero(void *) */
.section .text._ZN3ams4kern4arch5arm643cpu19ClearPageToZeroImplEPv, "ax", %progbits
.global _ZN3ams4kern4arch5arm643cpu19ClearPageToZeroImplEPv
.type _ZN3ams4kern4arch5arm643cpu19ClearPageToZeroImplEPv, %function
_ZN3ams4kern4arch5arm643cpu19ClearPageToZeroImplEPv:
/* Efficiently clear the page using dc zva. */
dc zva, x0
add x8, x0, #0x040
dc zva, x8
add x8, x0, #0x080
dc zva, x8
add x8, x0, #0x0c0
dc zva, x8
add x8, x0, #0x100
dc zva, x8
add x8, x0, #0x140
dc zva, x8
add x8, x0, #0x180
dc zva, x8
add x8, x0, #0x1c0
dc zva, x8
add x8, x0, #0x200
dc zva, x8
add x8, x0, #0x240
dc zva, x8
add x8, x0, #0x280
dc zva, x8
add x8, x0, #0x2c0
dc zva, x8
add x8, x0, #0x300
dc zva, x8
add x8, x0, #0x340
dc zva, x8
add x8, x0, #0x380
dc zva, x8
add x8, x0, #0x3c0
dc zva, x8
add x8, x0, #0x400
dc zva, x8
add x8, x0, #0x440
dc zva, x8
add x8, x0, #0x480
dc zva, x8
add x8, x0, #0x4c0
dc zva, x8
add x8, x0, #0x500
dc zva, x8
add x8, x0, #0x540
dc zva, x8
add x8, x0, #0x580
dc zva, x8
add x8, x0, #0x5c0
dc zva, x8
add x8, x0, #0x600
dc zva, x8
add x8, x0, #0x640
dc zva, x8
add x8, x0, #0x680
dc zva, x8
add x8, x0, #0x6c0
dc zva, x8
add x8, x0, #0x700
dc zva, x8
add x8, x0, #0x740
dc zva, x8
add x8, x0, #0x780
dc zva, x8
add x8, x0, #0x7c0
dc zva, x8
add x8, x0, #0x800
dc zva, x8
add x8, x0, #0x840
dc zva, x8
add x8, x0, #0x880
dc zva, x8
add x8, x0, #0x8c0
dc zva, x8
add x8, x0, #0x900
dc zva, x8
add x8, x0, #0x940
dc zva, x8
add x8, x0, #0x980
dc zva, x8
add x8, x0, #0x9c0
dc zva, x8
add x8, x0, #0xa00
dc zva, x8
add x8, x0, #0xa40
dc zva, x8
add x8, x0, #0xa80
dc zva, x8
add x8, x0, #0xac0
dc zva, x8
add x8, x0, #0xb00
dc zva, x8
add x8, x0, #0xb40
dc zva, x8
add x8, x0, #0xb80
dc zva, x8
add x8, x0, #0xbc0
dc zva, x8
add x8, x0, #0xc00
dc zva, x8
add x8, x0, #0xc40
dc zva, x8
add x8, x0, #0xc80
dc zva, x8
add x8, x0, #0xcc0
dc zva, x8
add x8, x0, #0xd00
dc zva, x8
add x8, x0, #0xd40
dc zva, x8
add x8, x0, #0xd80
dc zva, x8
add x8, x0, #0xdc0
dc zva, x8
add x8, x0, #0xe00
dc zva, x8
add x8, x0, #0xe40
dc zva, x8
add x8, x0, #0xe80
dc zva, x8
add x8, x0, #0xec0
dc zva, x8
add x8, x0, #0xf00
dc zva, x8
add x8, x0, #0xf40
dc zva, x8
add x8, x0, #0xf80
dc zva, x8
add x8, x0, #0xfc0
dc zva, x8
ret

View File

@@ -225,7 +225,7 @@ namespace ams::kern::arch::arm64 {
if (AMS_UNLIKELY(GetCurrentThread().IsSingleStep())) { if (AMS_UNLIKELY(GetCurrentThread().IsSingleStep())) {
GetCurrentThread().ClearSingleStep(); GetCurrentThread().ClearSingleStep();
cpu::MonitorDebugSystemControlRegisterAccessor().SetSoftwareStep(false).Store(); cpu::MonitorDebugSystemControlRegisterAccessor().SetSoftwareStep(false).Store();
cpu::EnsureInstructionConsistency(); cpu::InstructionMemoryBarrier();
} }
#endif #endif

View File

@@ -201,7 +201,7 @@ namespace ams::kern::arch::arm64 {
if (user_mode) { if (user_mode) {
KThread *cur_thread = GetCurrentThreadPointer(); KThread *cur_thread = GetCurrentThreadPointer();
if (cur_thread->IsTerminationRequested()) { if (cur_thread->IsTerminationRequested()) {
KScopedInterruptEnable ei; EnableInterrupts();
cur_thread->Exit(); cur_thread->Exit();
} }
} }
@@ -212,13 +212,14 @@ namespace ams::kern::arch::arm64 {
R_UNLESS(KInterruptController::IsGlobal(irq) || KInterruptController::IsLocal(irq), svc::ResultOutOfRange()); R_UNLESS(KInterruptController::IsGlobal(irq) || KInterruptController::IsLocal(irq), svc::ResultOutOfRange());
KScopedInterruptDisable di;
if (KInterruptController::IsGlobal(irq)) { if (KInterruptController::IsGlobal(irq)) {
KScopedInterruptDisable di;
KScopedSpinLock lk(this->GetGlobalInterruptLock()); KScopedSpinLock lk(this->GetGlobalInterruptLock());
return this->BindGlobal(handler, irq, core_id, priority, manual_clear, level); return this->BindGlobal(handler, irq, core_id, priority, manual_clear, level);
} else { } else {
MESOSPHERE_ASSERT(core_id == GetCurrentCoreId()); MESOSPHERE_ASSERT(core_id == GetCurrentCoreId());
KScopedInterruptDisable di;
return this->BindLocal(handler, irq, priority, manual_clear); return this->BindLocal(handler, irq, priority, manual_clear);
} }
} }
@@ -228,13 +229,16 @@ namespace ams::kern::arch::arm64 {
R_UNLESS(KInterruptController::IsGlobal(irq) || KInterruptController::IsLocal(irq), svc::ResultOutOfRange()); R_UNLESS(KInterruptController::IsGlobal(irq) || KInterruptController::IsLocal(irq), svc::ResultOutOfRange());
KScopedInterruptDisable di;
if (KInterruptController::IsGlobal(irq)) { if (KInterruptController::IsGlobal(irq)) {
KScopedInterruptDisable di;
KScopedSpinLock lk(this->GetGlobalInterruptLock()); KScopedSpinLock lk(this->GetGlobalInterruptLock());
return this->UnbindGlobal(irq); return this->UnbindGlobal(irq);
} else { } else {
MESOSPHERE_ASSERT(core_id == GetCurrentCoreId()); MESOSPHERE_ASSERT(core_id == GetCurrentCoreId());
KScopedInterruptDisable di;
return this->UnbindLocal(irq); return this->UnbindLocal(irq);
} }
} }
@@ -244,13 +248,15 @@ namespace ams::kern::arch::arm64 {
R_UNLESS(KInterruptController::IsGlobal(irq) || KInterruptController::IsLocal(irq), svc::ResultOutOfRange()); R_UNLESS(KInterruptController::IsGlobal(irq) || KInterruptController::IsLocal(irq), svc::ResultOutOfRange());
KScopedInterruptDisable di;
if (KInterruptController::IsGlobal(irq)) { if (KInterruptController::IsGlobal(irq)) {
KScopedInterruptDisable di;
KScopedSpinLock lk(this->GetGlobalInterruptLock()); KScopedSpinLock lk(this->GetGlobalInterruptLock());
return this->ClearGlobal(irq); return this->ClearGlobal(irq);
} else { } else {
MESOSPHERE_ASSERT(core_id == GetCurrentCoreId()); MESOSPHERE_ASSERT(core_id == GetCurrentCoreId());
KScopedInterruptDisable di;
return this->ClearLocal(irq); return this->ClearLocal(irq);
} }
} }

View File

@@ -169,10 +169,10 @@ namespace ams::kern::arch::arm64 {
m_manager = std::addressof(Kernel::GetSystemPageTableManager()); m_manager = std::addressof(Kernel::GetSystemPageTableManager());
/* Allocate a page for ttbr. */ /* Allocate a page for ttbr. */
/* NOTE: It is a postcondition of page table manager allocation that the page is all-zero. */
const u64 asid_tag = (static_cast<u64>(m_asid) << 48ul); const u64 asid_tag = (static_cast<u64>(m_asid) << 48ul);
const KVirtualAddress page = m_manager->Allocate(); const KVirtualAddress page = m_manager->Allocate();
MESOSPHERE_ASSERT(page != Null<KVirtualAddress>); MESOSPHERE_ASSERT(page != Null<KVirtualAddress>);
cpu::ClearPageToZero(GetVoidPointer(page));
m_ttbr = GetInteger(KPageTableBase::GetLinearMappedPhysicalAddress(page)) | asid_tag; m_ttbr = GetInteger(KPageTableBase::GetLinearMappedPhysicalAddress(page)) | asid_tag;
/* Initialize the base page table. */ /* Initialize the base page table. */
@@ -1058,7 +1058,7 @@ namespace ams::kern::arch::arm64 {
auto sw_reserved_bits = PageTableEntry::EncodeSoftwareReservedBits(head_entry->IsHeadMergeDisabled(), head_entry->IsHeadAndBodyMergeDisabled(), tail_entry->IsTailMergeDisabled()); auto sw_reserved_bits = PageTableEntry::EncodeSoftwareReservedBits(head_entry->IsHeadMergeDisabled(), head_entry->IsHeadAndBodyMergeDisabled(), tail_entry->IsTailMergeDisabled());
/* Merge! */ /* Merge! */
PteDataSynchronizationBarrier(); /* NOTE: As of 13.1.0, Nintendo does not do: PteDataSynchronizationBarrier(); */
*l1_entry = L1PageTableEntry(PageTableEntry::BlockTag{}, phys_addr, PageTableEntry(entry_template), sw_reserved_bits, false); *l1_entry = L1PageTableEntry(PageTableEntry::BlockTag{}, phys_addr, PageTableEntry(entry_template), sw_reserved_bits, false);
/* Note that we updated. */ /* Note that we updated. */

View File

@@ -28,7 +28,7 @@ _ZN3ams4kern3svc25CallReturnFromException64Ev:
stp x20, x21, [sp, #(EXCEPTION_CONTEXT_X20_X21)] stp x20, x21, [sp, #(EXCEPTION_CONTEXT_X20_X21)]
stp x22, x23, [sp, #(EXCEPTION_CONTEXT_X22_X23)] stp x22, x23, [sp, #(EXCEPTION_CONTEXT_X22_X23)]
stp x24, x25, [sp, #(EXCEPTION_CONTEXT_X24_X25)] stp x24, x25, [sp, #(EXCEPTION_CONTEXT_X24_X25)]
stp x26, x26, [sp, #(EXCEPTION_CONTEXT_X26_X27)] stp x26, x27, [sp, #(EXCEPTION_CONTEXT_X26_X27)]
stp x28, x29, [sp, #(EXCEPTION_CONTEXT_X28_X29)] stp x28, x29, [sp, #(EXCEPTION_CONTEXT_X28_X29)]
/* Call ams::kern::arch::arm64::ReturnFromException(result). */ /* Call ams::kern::arch::arm64::ReturnFromException(result). */

View File

@@ -50,10 +50,6 @@ _ZN3ams4kern3svc26CallSendSyncRequestLight64Ev:
.global _ZN3ams4kern3svc32CallSendSyncRequestLight64From32Ev .global _ZN3ams4kern3svc32CallSendSyncRequestLight64From32Ev
.type _ZN3ams4kern3svc32CallSendSyncRequestLight64From32Ev, %function .type _ZN3ams4kern3svc32CallSendSyncRequestLight64From32Ev, %function
_ZN3ams4kern3svc32CallSendSyncRequestLight64From32Ev: _ZN3ams4kern3svc32CallSendSyncRequestLight64From32Ev:
/* Load x4-x7 from where the svc handler stores them. */
ldp x4, x5, [sp, #(8 * 0)]
ldp x6, x7, [sp, #(8 * 2)]
/* Allocate space for the light ipc data. */ /* Allocate space for the light ipc data. */
sub sp, sp, #(4 * 8) sub sp, sp, #(4 * 8)
@@ -78,13 +74,8 @@ _ZN3ams4kern3svc32CallSendSyncRequestLight64From32Ev:
/* Free the stack space for the light ipc data. */ /* Free the stack space for the light ipc data. */
add sp, sp, #(4 * 8) add sp, sp, #(4 * 8)
/* Save x4-x7 to where the svc handler stores them. */
stp x4, x5, [sp, #(8 * 0)]
stp x6, x7, [sp, #(8 * 2)]
ret ret
/* ams::kern::svc::CallReplyAndReceiveLight64() */ /* ams::kern::svc::CallReplyAndReceiveLight64() */
.section .text._ZN3ams4kern3svc26CallReplyAndReceiveLight64Ev, "ax", %progbits .section .text._ZN3ams4kern3svc26CallReplyAndReceiveLight64Ev, "ax", %progbits
.global _ZN3ams4kern3svc26CallReplyAndReceiveLight64Ev .global _ZN3ams4kern3svc26CallReplyAndReceiveLight64Ev
@@ -121,10 +112,6 @@ _ZN3ams4kern3svc26CallReplyAndReceiveLight64Ev:
.global _ZN3ams4kern3svc32CallReplyAndReceiveLight64From32Ev .global _ZN3ams4kern3svc32CallReplyAndReceiveLight64From32Ev
.type _ZN3ams4kern3svc32CallReplyAndReceiveLight64From32Ev, %function .type _ZN3ams4kern3svc32CallReplyAndReceiveLight64From32Ev, %function
_ZN3ams4kern3svc32CallReplyAndReceiveLight64From32Ev: _ZN3ams4kern3svc32CallReplyAndReceiveLight64From32Ev:
/* Load x4-x7 from where the svc handler stores them. */
ldp x4, x5, [sp, #(8 * 0)]
ldp x6, x7, [sp, #(8 * 2)]
/* Allocate space for the light ipc data. */ /* Allocate space for the light ipc data. */
sub sp, sp, #(4 * 8) sub sp, sp, #(4 * 8)
@@ -149,8 +136,4 @@ _ZN3ams4kern3svc32CallReplyAndReceiveLight64From32Ev:
/* Free the stack space for the light ipc data. */ /* Free the stack space for the light ipc data. */
add sp, sp, #(4 * 8) add sp, sp, #(4 * 8)
/* Save x4-x7 to where the svc handler stores them. */
stp x4, x5, [sp, #(8 * 0)]
stp x6, x7, [sp, #(8 * 2)]
ret ret

View File

@@ -59,7 +59,7 @@ namespace ams::kern::svc {
/* Set omit-frame-pointer to prevent GCC from emitting MOV X29, SP instructions. */ /* Set omit-frame-pointer to prevent GCC from emitting MOV X29, SP instructions. */
#pragma GCC push_options #pragma GCC push_options
#pragma GCC optimize ("-O2") #pragma GCC optimize ("-O3")
#pragma GCC optimize ("omit-frame-pointer") #pragma GCC optimize ("omit-frame-pointer")
AMS_SVC_FOREACH_KERN_DEFINITION(DECLARE_SVC_STRUCT, _) AMS_SVC_FOREACH_KERN_DEFINITION(DECLARE_SVC_STRUCT, _)

View File

@@ -548,11 +548,11 @@ namespace ams::kern::board::nintendo::nx {
/* Print the interrupt. */ /* Print the interrupt. */
{ {
constexpr auto GetBits = [] ALWAYS_INLINE_LAMBDA (u32 value, size_t ofs, size_t count) { constexpr auto GetBits = [](u32 value, size_t ofs, size_t count) ALWAYS_INLINE_LAMBDA {
return (value >> ofs) & ((1u << count) - 1); return (value >> ofs) & ((1u << count) - 1);
}; };
constexpr auto GetBit = [GetBits] ALWAYS_INLINE_LAMBDA (u32 value, size_t ofs) { constexpr auto GetBit = [GetBits](u32 value, size_t ofs) ALWAYS_INLINE_LAMBDA {
return (value >> ofs) & 1u; return (value >> ofs) & 1u;
}; };
@@ -656,9 +656,8 @@ namespace ams::kern::board::nintendo::nx {
MESOSPHERE_ASSERT(IsValidPhysicalAddress(table_phys_addr)); MESOSPHERE_ASSERT(IsValidPhysicalAddress(table_phys_addr));
Kernel::GetSystemPageTableManager().Open(table_virt_addr, 1); Kernel::GetSystemPageTableManager().Open(table_virt_addr, 1);
/* Clear the page and save it. */ /* Save the page. Note that it is a pre-condition that the page is cleared, when allocated from the system page table manager. */
/* NOTE: Nintendo does not check the result of StoreDataCache. */ /* NOTE: Nintendo does not check the result of StoreDataCache. */
cpu::ClearPageToZero(GetVoidPointer(table_virt_addr));
cpu::StoreDataCache(GetVoidPointer(table_virt_addr), PageDirectorySize); cpu::StoreDataCache(GetVoidPointer(table_virt_addr), PageDirectorySize);
g_reserved_table_phys_addr = table_phys_addr; g_reserved_table_phys_addr = table_phys_addr;

View File

@@ -341,7 +341,9 @@ namespace ams::kern::board::nintendo::nx {
/* Restore pmu registers. */ /* Restore pmu registers. */
cpu::SetPmUserEnrEl0(0); cpu::SetPmUserEnrEl0(0);
cpu::PerformanceMonitorsControlRegisterAccessor().SetEventCounterReset(true).SetCycleCounterReset(true).Store(); cpu::PerformanceMonitorsControlRegisterAccessor(0).SetEventCounterReset(true).SetCycleCounterReset(true).Store();
cpu::EnsureInstructionConsistency();
cpu::SetPmOvsClrEl0(static_cast<u64>(static_cast<u32>(~u32()))); cpu::SetPmOvsClrEl0(static_cast<u64>(static_cast<u32>(~u32())));
cpu::SetPmIntEnClrEl1(static_cast<u64>(static_cast<u32>(~u32()))); cpu::SetPmIntEnClrEl1(static_cast<u64>(static_cast<u32>(~u32())));
cpu::SetPmCntEnClrEl0(static_cast<u64>(static_cast<u32>(~u32()))); cpu::SetPmCntEnClrEl0(static_cast<u64>(static_cast<u32>(~u32())));

View File

@@ -312,7 +312,7 @@ namespace ams::kern::board::nintendo::nx {
size_t KSystemControl::Init::GetApplicationPoolSize() { size_t KSystemControl::Init::GetApplicationPoolSize() {
/* Get the base pool size. */ /* Get the base pool size. */
const size_t base_pool_size = [] ALWAYS_INLINE_LAMBDA () -> size_t { const size_t base_pool_size = []() ALWAYS_INLINE_LAMBDA -> size_t {
switch (GetMemoryArrangeForInit()) { switch (GetMemoryArrangeForInit()) {
case smc::MemoryArrangement_4GB: case smc::MemoryArrangement_4GB:
default: default:
@@ -336,7 +336,7 @@ namespace ams::kern::board::nintendo::nx {
size_t KSystemControl::Init::GetAppletPoolSize() { size_t KSystemControl::Init::GetAppletPoolSize() {
/* Get the base pool size. */ /* Get the base pool size. */
const size_t base_pool_size = [] ALWAYS_INLINE_LAMBDA () -> size_t { const size_t base_pool_size = []() ALWAYS_INLINE_LAMBDA -> size_t {
switch (GetMemoryArrangeForInit()) { switch (GetMemoryArrangeForInit()) {
case smc::MemoryArrangement_4GB: case smc::MemoryArrangement_4GB:
default: default:
@@ -490,7 +490,7 @@ namespace ams::kern::board::nintendo::nx {
if (AMS_LIKELY(s_initialized_random_generator)) { if (AMS_LIKELY(s_initialized_random_generator)) {
return KSystemControlBase::GenerateUniformRange(min, max, [] ALWAYS_INLINE_LAMBDA () -> u64 { return s_random_generator.GenerateRandomU64(); }); return KSystemControlBase::GenerateUniformRange(min, max, []() ALWAYS_INLINE_LAMBDA -> u64 { return s_random_generator.GenerateRandomU64(); });
} else { } else {
return KSystemControlBase::GenerateUniformRange(min, max, GenerateRandomU64FromSmc); return KSystemControlBase::GenerateUniformRange(min, max, GenerateRandomU64FromSmc);
} }
@@ -680,4 +680,4 @@ namespace ams::kern::board::nintendo::nx {
Kernel::GetMemoryManager().Close(KPageTable::GetHeapPhysicalAddress(address), size / PageSize); Kernel::GetMemoryManager().Close(KPageTable::GetHeapPhysicalAddress(address), size / PageSize);
} }
} }

View File

@@ -250,7 +250,7 @@ namespace ams::kern {
{ {
const u32 has_waiter_flag = 1; const u32 has_waiter_flag = 1;
WriteToUser(key, std::addressof(has_waiter_flag)); WriteToUser(key, std::addressof(has_waiter_flag));
cpu::DataMemoryBarrier(); cpu::DataMemoryBarrierInnerShareable();
} }
/* Write the value to userspace. */ /* Write the value to userspace. */

View File

@@ -19,7 +19,7 @@ namespace ams::kern {
namespace { namespace {
constexpr std::tuple<KMemoryState, const char *> MemoryStateNames[] = { constexpr const std::pair<KMemoryState, const char *> MemoryStateNames[] = {
{KMemoryState_Free , "----- Free -----"}, {KMemoryState_Free , "----- Free -----"},
{KMemoryState_Io , "Io "}, {KMemoryState_Io , "Io "},
{KMemoryState_Static , "Static "}, {KMemoryState_Static , "Static "},
@@ -41,6 +41,7 @@ namespace ams::kern {
{KMemoryState_Kernel , "Kernel "}, {KMemoryState_Kernel , "Kernel "},
{KMemoryState_GeneratedCode , "GeneratedCode "}, {KMemoryState_GeneratedCode , "GeneratedCode "},
{KMemoryState_CodeOut , "CodeOut "}, {KMemoryState_CodeOut , "CodeOut "},
{KMemoryState_Coverage , "Coverage "},
}; };
constexpr const char *GetMemoryStateName(KMemoryState state) { constexpr const char *GetMemoryStateName(KMemoryState state) {

View File

@@ -195,7 +195,7 @@ namespace ams::kern {
static_assert(KMemoryManager::Pool_Secure == KMemoryManager::Pool_System); static_assert(KMemoryManager::Pool_Secure == KMemoryManager::Pool_System);
/* Get Secure pool size. */ /* Get Secure pool size. */
const size_t secure_pool_size = [] ALWAYS_INLINE_LAMBDA (auto target_firmware) -> size_t { const size_t secure_pool_size = [](auto target_firmware) ALWAYS_INLINE_LAMBDA -> size_t {
constexpr size_t LegacySecureKernelSize = 8_MB; /* KPageBuffer pages, other small kernel allocations. */ constexpr size_t LegacySecureKernelSize = 8_MB; /* KPageBuffer pages, other small kernel allocations. */
constexpr size_t LegacySecureMiscSize = 1_MB; /* Miscellaneous pages for secure process mapping. */ constexpr size_t LegacySecureMiscSize = 1_MB; /* Miscellaneous pages for secure process mapping. */
constexpr size_t LegacySecureHeapSize = 24_MB; /* Heap pages for secure process mapping (fs). */ constexpr size_t LegacySecureHeapSize = 24_MB; /* Heap pages for secure process mapping (fs). */
@@ -274,4 +274,4 @@ namespace ams::kern {
} }
} }

View File

@@ -2398,7 +2398,7 @@ namespace ams::kern {
size_t cur_size = next_entry.block_size - (GetInteger(cur_addr) & (next_entry.block_size - 1)); size_t cur_size = next_entry.block_size - (GetInteger(cur_addr) & (next_entry.block_size - 1));
size_t tot_size = cur_size; size_t tot_size = cur_size;
auto PerformCopy = [&] ALWAYS_INLINE_LAMBDA () -> Result { auto PerformCopy = [&]() ALWAYS_INLINE_LAMBDA -> Result {
/* Ensure the address is linear mapped. */ /* Ensure the address is linear mapped. */
R_UNLESS(IsLinearMappedPhysicalAddress(cur_addr), svc::ResultInvalidCurrentMemory()); R_UNLESS(IsLinearMappedPhysicalAddress(cur_addr), svc::ResultInvalidCurrentMemory());
@@ -2484,7 +2484,7 @@ namespace ams::kern {
size_t cur_size = next_entry.block_size - (GetInteger(cur_addr) & (next_entry.block_size - 1)); size_t cur_size = next_entry.block_size - (GetInteger(cur_addr) & (next_entry.block_size - 1));
size_t tot_size = cur_size; size_t tot_size = cur_size;
auto PerformCopy = [&] ALWAYS_INLINE_LAMBDA () -> Result { auto PerformCopy = [&]() ALWAYS_INLINE_LAMBDA -> Result {
/* Ensure the address is linear mapped. */ /* Ensure the address is linear mapped. */
R_UNLESS(IsLinearMappedPhysicalAddress(cur_addr), svc::ResultInvalidCurrentMemory()); R_UNLESS(IsLinearMappedPhysicalAddress(cur_addr), svc::ResultInvalidCurrentMemory());
@@ -2943,7 +2943,7 @@ namespace ams::kern {
size_t cur_size = next_entry.block_size - (GetInteger(cur_addr) & (next_entry.block_size - 1)); size_t cur_size = next_entry.block_size - (GetInteger(cur_addr) & (next_entry.block_size - 1));
size_t tot_size = cur_size; size_t tot_size = cur_size;
auto PerformCopy = [&] ALWAYS_INLINE_LAMBDA () -> Result { auto PerformCopy = [&]() ALWAYS_INLINE_LAMBDA -> Result {
/* Ensure the address is linear mapped. */ /* Ensure the address is linear mapped. */
R_UNLESS(IsLinearMappedPhysicalAddress(cur_addr), svc::ResultInvalidCurrentMemory()); R_UNLESS(IsLinearMappedPhysicalAddress(cur_addr), svc::ResultInvalidCurrentMemory());
@@ -3023,7 +3023,7 @@ namespace ams::kern {
size_t cur_size = next_entry.block_size - (GetInteger(cur_addr) & (next_entry.block_size - 1)); size_t cur_size = next_entry.block_size - (GetInteger(cur_addr) & (next_entry.block_size - 1));
size_t tot_size = cur_size; size_t tot_size = cur_size;
auto PerformCopy = [&] ALWAYS_INLINE_LAMBDA () -> Result { auto PerformCopy = [&]() ALWAYS_INLINE_LAMBDA -> Result {
/* Ensure the address is linear mapped. */ /* Ensure the address is linear mapped. */
R_UNLESS(IsLinearMappedPhysicalAddress(cur_addr), svc::ResultInvalidCurrentMemory()); R_UNLESS(IsLinearMappedPhysicalAddress(cur_addr), svc::ResultInvalidCurrentMemory());
@@ -3092,7 +3092,7 @@ namespace ams::kern {
size_t cur_size = next_entry.block_size - (GetInteger(cur_addr) & (next_entry.block_size - 1)); size_t cur_size = next_entry.block_size - (GetInteger(cur_addr) & (next_entry.block_size - 1));
size_t tot_size = cur_size; size_t tot_size = cur_size;
auto PerformCopy = [&] ALWAYS_INLINE_LAMBDA () -> Result { auto PerformCopy = [&]() ALWAYS_INLINE_LAMBDA -> Result {
/* Ensure the address is linear mapped. */ /* Ensure the address is linear mapped. */
R_UNLESS(IsLinearMappedPhysicalAddress(cur_addr), svc::ResultInvalidCurrentMemory()); R_UNLESS(IsLinearMappedPhysicalAddress(cur_addr), svc::ResultInvalidCurrentMemory());
@@ -3172,7 +3172,7 @@ namespace ams::kern {
size_t cur_size = next_entry.block_size - (GetInteger(cur_addr) & (next_entry.block_size - 1)); size_t cur_size = next_entry.block_size - (GetInteger(cur_addr) & (next_entry.block_size - 1));
size_t tot_size = cur_size; size_t tot_size = cur_size;
auto PerformCopy = [&] ALWAYS_INLINE_LAMBDA () -> Result { auto PerformCopy = [&]() ALWAYS_INLINE_LAMBDA -> Result {
/* Ensure the address is linear mapped. */ /* Ensure the address is linear mapped. */
R_UNLESS(IsLinearMappedPhysicalAddress(cur_addr), svc::ResultInvalidCurrentMemory()); R_UNLESS(IsLinearMappedPhysicalAddress(cur_addr), svc::ResultInvalidCurrentMemory());

View File

@@ -893,7 +893,7 @@ namespace ams::kern {
size_t KProcess::GetTotalUserPhysicalMemorySize() const { size_t KProcess::GetTotalUserPhysicalMemorySize() const {
/* Get the amount of free and used size. */ /* Get the amount of free and used size. */
const size_t free_size = m_resource_limit->GetFreeValue(ams::svc::LimitableResource_PhysicalMemoryMax); const size_t free_size = m_resource_limit->GetFreeValue(ams::svc::LimitableResource_PhysicalMemoryMax);
const size_t used_size = this->GetUsedNonSystemUserPhysicalMemorySize(); const size_t used_size = this->GetUsedUserPhysicalMemorySize();
const size_t max_size = m_max_process_memory; const size_t max_size = m_max_process_memory;
if (used_size + free_size > max_size) { if (used_size + free_size > max_size) {

View File

@@ -15,10 +15,10 @@
*/ */
#include <mesosphere.hpp> #include <mesosphere.hpp>
namespace ams::kern { #pragma GCC push_options
#pragma GCC optimize ("-O3")
#pragma GCC push_options namespace ams::kern {
#pragma GCC optimize ("-O3")
bool KScheduler::s_scheduler_update_needed; bool KScheduler::s_scheduler_update_needed;
KScheduler::LockType KScheduler::s_scheduler_lock; KScheduler::LockType KScheduler::s_scheduler_lock;
@@ -79,13 +79,6 @@ namespace ams::kern {
RescheduleCurrentCore(); RescheduleCurrentCore();
} }
void KScheduler::RescheduleOtherCores(u64 cores_needing_scheduling) {
if (const u64 core_mask = cores_needing_scheduling & ~(1ul << m_core_id); core_mask != 0) {
cpu::DataSynchronizationBarrier();
Kernel::GetInterruptManager().SendInterProcessorInterrupt(KInterruptName_Scheduler, core_mask);
}
}
u64 KScheduler::UpdateHighestPriorityThread(KThread *highest_thread) { u64 KScheduler::UpdateHighestPriorityThread(KThread *highest_thread) {
if (KThread *prev_highest_thread = m_state.highest_priority_thread; AMS_LIKELY(prev_highest_thread != highest_thread)) { if (KThread *prev_highest_thread = m_state.highest_priority_thread; AMS_LIKELY(prev_highest_thread != highest_thread)) {
if (AMS_LIKELY(prev_highest_thread != nullptr)) { if (AMS_LIKELY(prev_highest_thread != nullptr)) {
@@ -254,6 +247,17 @@ namespace ams::kern {
MESOSPHERE_KTRACE_THREAD_SWITCH(next_thread); MESOSPHERE_KTRACE_THREAD_SWITCH(next_thread);
#if defined(MESOSPHERE_ENABLE_HARDWARE_SINGLE_STEP)
/* Ensure the single-step bit in mdscr reflects the correct single-step state for the new thread. */
/* NOTE: Per ARM docs, changing the single-step bit requires a "context synchronization event" to */
/* be sure that our new configuration takes. However, there are three types of synchronization event: */
/* Taking an exception, returning from an exception, and ISB. The single-step bit change only matters */
/* in EL0...which implies a return-from-exception has occurred since we set the bit. Thus, forcing */
/* an ISB is unnecessary, and we can modify the register safely and be confident it will affect the next */
/* userland instruction executed. */
cpu::MonitorDebugSystemControlRegisterAccessor().SetSoftwareStep(next_thread->IsSingleStep()).Store();
#endif
/* Switch the current process, if we're switching processes. */ /* Switch the current process, if we're switching processes. */
if (KProcess *next_process = next_thread->GetOwnerProcess(); next_process != cur_process) { if (KProcess *next_process = next_thread->GetOwnerProcess(); next_process != cur_process) {
KProcess::Switch(cur_process, next_process); KProcess::Switch(cur_process, next_process);
@@ -594,6 +598,6 @@ namespace ams::kern {
} }
} }
#pragma GCC pop_options
} }
#pragma GCC pop_options

View File

@@ -15,10 +15,10 @@
*/ */
#include <mesosphere.hpp> #include <mesosphere.hpp>
namespace ams::kern { #pragma GCC push_options
#pragma GCC optimize ("-O3")
#pragma GCC push_options namespace ams::kern {
#pragma GCC optimize ("-O3")
namespace ipc { namespace ipc {
@@ -1385,8 +1385,6 @@ namespace ams::kern {
this->NotifyAvailable(svc::ResultSessionClosed()); this->NotifyAvailable(svc::ResultSessionClosed());
} }
#pragma GCC pop_options
void KServerSession::Dump() { void KServerSession::Dump() {
MESOSPHERE_ASSERT_THIS(); MESOSPHERE_ASSERT_THIS();
@@ -1420,3 +1418,5 @@ namespace ams::kern {
} }
} }
#pragma GCC pop_options

View File

@@ -96,7 +96,7 @@ namespace ams::kern {
s_initialized_random_generator = true; s_initialized_random_generator = true;
} }
return KSystemControlBase::GenerateUniformRange(min, max, [] ALWAYS_INLINE_LAMBDA () -> u64 { return s_random_generator.GenerateRandomU64(); }); return KSystemControlBase::GenerateUniformRange(min, max, []() ALWAYS_INLINE_LAMBDA -> u64 { return s_random_generator.GenerateRandomU64(); });
} }
/* System Initialization. */ /* System Initialization. */
@@ -194,7 +194,7 @@ namespace ams::kern {
KScopedInterruptDisable intr_disable; KScopedInterruptDisable intr_disable;
KScopedSpinLock lk(s_random_lock); KScopedSpinLock lk(s_random_lock);
return KSystemControlBase::GenerateUniformRange(min, max, [] ALWAYS_INLINE_LAMBDA () -> u64 { return s_random_generator.GenerateRandomU64(); }); return KSystemControlBase::GenerateUniformRange(min, max, []() ALWAYS_INLINE_LAMBDA -> u64 { return s_random_generator.GenerateRandomU64(); });
} }
u64 KSystemControlBase::GenerateRandomU64() { u64 KSystemControlBase::GenerateRandomU64() {
@@ -292,4 +292,4 @@ namespace ams::kern {
Kernel::GetMemoryManager().Close(KPageTable::GetHeapPhysicalAddress(address), size / PageSize); Kernel::GetMemoryManager().Close(KPageTable::GetHeapPhysicalAddress(address), size / PageSize);
} }
} }

View File

@@ -1183,7 +1183,7 @@ namespace ams::kern {
KScopedSchedulerLock sl; KScopedSchedulerLock sl;
/* Determine if this is the first termination request. */ /* Determine if this is the first termination request. */
const bool first_request = [&] ALWAYS_INLINE_LAMBDA () -> bool { const bool first_request = [&]() ALWAYS_INLINE_LAMBDA -> bool {
/* Perform an atomic compare-and-swap from false to true. */ /* Perform an atomic compare-and-swap from false to true. */
bool expected = false; bool expected = false;
return m_termination_requested.CompareExchangeStrong(expected, true); return m_termination_requested.CompareExchangeStrong(expected, true);
@@ -1315,10 +1315,6 @@ namespace ams::kern {
} }
} }
KThreadContext *KThread::GetContextForSchedulerLoop() {
return std::addressof(this->GetContext());
}
KThread *KThread::GetThreadFromId(u64 thread_id) { KThread *KThread::GetThreadFromId(u64 thread_id) {
/* Lock the list. */ /* Lock the list. */
KThread::ListAccessor accessor; KThread::ListAccessor accessor;

View File

@@ -48,7 +48,7 @@ namespace ams::kern::svc {
/* Check whether the address is aligned. */ /* Check whether the address is aligned. */
const bool aligned = util::IsAligned(phys_addr, PageSize); const bool aligned = util::IsAligned(phys_addr, PageSize);
auto QueryIoMappingFromPageTable = [&] ALWAYS_INLINE_LAMBDA (uint64_t phys_addr, size_t size) -> Result { auto QueryIoMappingFromPageTable = [&](uint64_t phys_addr, size_t size) ALWAYS_INLINE_LAMBDA -> Result {
/* The size must be non-zero. */ /* The size must be non-zero. */
R_UNLESS(size > 0, svc::ResultInvalidSize()); R_UNLESS(size > 0, svc::ResultInvalidSize());

View File

@@ -38,6 +38,80 @@ namespace ams::kern::svc {
return ResultSuccess(); return ResultSuccess();
} }
Result GetInfoImpl(u64 *out, ams::svc::InfoType info_type, KProcess *process) {
switch (info_type) {
case ams::svc::InfoType_CoreMask:
*out = process->GetCoreMask();
break;
case ams::svc::InfoType_PriorityMask:
*out = process->GetPriorityMask();
break;
case ams::svc::InfoType_AliasRegionAddress:
*out = GetInteger(process->GetPageTable().GetAliasRegionStart());
break;
case ams::svc::InfoType_AliasRegionSize:
*out = process->GetPageTable().GetAliasRegionSize();
break;
case ams::svc::InfoType_HeapRegionAddress:
*out = GetInteger(process->GetPageTable().GetHeapRegionStart());
break;
case ams::svc::InfoType_HeapRegionSize:
*out = process->GetPageTable().GetHeapRegionSize();
break;
case ams::svc::InfoType_TotalMemorySize:
*out = process->GetTotalUserPhysicalMemorySize();
break;
case ams::svc::InfoType_UsedMemorySize:
*out = process->GetUsedUserPhysicalMemorySize();
break;
case ams::svc::InfoType_AslrRegionAddress:
*out = GetInteger(process->GetPageTable().GetAliasCodeRegionStart());
break;
case ams::svc::InfoType_AslrRegionSize:
*out = process->GetPageTable().GetAliasCodeRegionSize();
break;
case ams::svc::InfoType_StackRegionAddress:
*out = GetInteger(process->GetPageTable().GetStackRegionStart());
break;
case ams::svc::InfoType_StackRegionSize:
*out = process->GetPageTable().GetStackRegionSize();
break;
case ams::svc::InfoType_SystemResourceSizeTotal:
*out = process->GetTotalSystemResourceSize();
break;
case ams::svc::InfoType_SystemResourceSizeUsed:
*out = process->GetUsedSystemResourceSize();
break;
case ams::svc::InfoType_ProgramId:
*out = process->GetProgramId();
break;
case ams::svc::InfoType_UserExceptionContextAddress:
*out = GetInteger(process->GetProcessLocalRegionAddress());
break;
case ams::svc::InfoType_TotalNonSystemMemorySize:
*out = process->GetTotalNonSystemUserPhysicalMemorySize();
break;
case ams::svc::InfoType_UsedNonSystemMemorySize:
*out = process->GetUsedNonSystemUserPhysicalMemorySize();
break;
case ams::svc::InfoType_IsApplication:
*out = process->IsApplication();
break;
case ams::svc::InfoType_FreeThreadCount:
if (KResourceLimit *resource_limit = process->GetResourceLimit(); resource_limit != nullptr) {
const auto current_value = resource_limit->GetCurrentValue(ams::svc::LimitableResource_ThreadCountMax);
const auto limit_value = resource_limit->GetLimitValue(ams::svc::LimitableResource_ThreadCountMax);
*out = limit_value - current_value;
} else {
*out = 0;
}
break;
MESOSPHERE_UNREACHABLE_DEFAULT_CASE();
}
return ResultSuccess();
}
Result GetInfo(u64 *out, ams::svc::InfoType info_type, ams::svc::Handle handle, u64 info_subtype) { Result GetInfo(u64 *out, ams::svc::InfoType info_type, ams::svc::Handle handle, u64 info_subtype) {
switch (info_type) { switch (info_type) {
case ams::svc::InfoType_CoreMask: case ams::svc::InfoType_CoreMask:
@@ -66,77 +140,34 @@ namespace ams::kern::svc {
/* Get the process from its handle. */ /* Get the process from its handle. */
KScopedAutoObject process = GetCurrentProcess().GetHandleTable().GetObject<KProcess>(handle); KScopedAutoObject process = GetCurrentProcess().GetHandleTable().GetObject<KProcess>(handle);
#if defined(MESOSPHERE_ENABLE_GET_INFO_OF_DEBUG_PROCESS)
/* If we the process is valid, use it. */
if (process.IsNotNull()) {
return GetInfoImpl(out, info_type, process.GetPointerUnsafe());
}
/* Otherwise, as a mesosphere extension check if we were passed a usable KDebug. */
KScopedAutoObject debug = GetCurrentProcess().GetHandleTable().GetObject<KDebug>(handle);
R_UNLESS(debug.IsNotNull(), svc::ResultInvalidHandle());
/* Get the process from the debug object. */
/* TODO: ResultInvalidHandle()? */
R_UNLESS(debug->IsAttached(), svc::ResultProcessTerminated());
R_UNLESS(debug->OpenProcess(), svc::ResultProcessTerminated());
/* Close the process when we're done. */
ON_SCOPE_EXIT { debug->CloseProcess(); };
/* Return the info. */
return GetInfoImpl(out, info_type, debug->GetProcessUnsafe());
#else
/* Verify that the process is valid. */
R_UNLESS(process.IsNotNull(), svc::ResultInvalidHandle()); R_UNLESS(process.IsNotNull(), svc::ResultInvalidHandle());
switch (info_type) { /* Return the relevant info. */
case ams::svc::InfoType_CoreMask: return GetInfoImpl(out, info_type, process.GetPointerUnsafe());
*out = process->GetCoreMask(); #endif
break;
case ams::svc::InfoType_PriorityMask:
*out = process->GetPriorityMask();
break;
case ams::svc::InfoType_AliasRegionAddress:
*out = GetInteger(process->GetPageTable().GetAliasRegionStart());
break;
case ams::svc::InfoType_AliasRegionSize:
*out = process->GetPageTable().GetAliasRegionSize();
break;
case ams::svc::InfoType_HeapRegionAddress:
*out = GetInteger(process->GetPageTable().GetHeapRegionStart());
break;
case ams::svc::InfoType_HeapRegionSize:
*out = process->GetPageTable().GetHeapRegionSize();
break;
case ams::svc::InfoType_TotalMemorySize:
*out = process->GetTotalUserPhysicalMemorySize();
break;
case ams::svc::InfoType_UsedMemorySize:
*out = process->GetUsedUserPhysicalMemorySize();
break;
case ams::svc::InfoType_AslrRegionAddress:
*out = GetInteger(process->GetPageTable().GetAliasCodeRegionStart());
break;
case ams::svc::InfoType_AslrRegionSize:
*out = process->GetPageTable().GetAliasCodeRegionSize();
break;
case ams::svc::InfoType_StackRegionAddress:
*out = GetInteger(process->GetPageTable().GetStackRegionStart());
break;
case ams::svc::InfoType_StackRegionSize:
*out = process->GetPageTable().GetStackRegionSize();
break;
case ams::svc::InfoType_SystemResourceSizeTotal:
*out = process->GetTotalSystemResourceSize();
break;
case ams::svc::InfoType_SystemResourceSizeUsed:
*out = process->GetUsedSystemResourceSize();
break;
case ams::svc::InfoType_ProgramId:
*out = process->GetProgramId();
break;
case ams::svc::InfoType_UserExceptionContextAddress:
*out = GetInteger(process->GetProcessLocalRegionAddress());
break;
case ams::svc::InfoType_TotalNonSystemMemorySize:
*out = process->GetTotalNonSystemUserPhysicalMemorySize();
break;
case ams::svc::InfoType_UsedNonSystemMemorySize:
*out = process->GetUsedNonSystemUserPhysicalMemorySize();
break;
case ams::svc::InfoType_IsApplication:
*out = process->IsApplication();
break;
case ams::svc::InfoType_FreeThreadCount:
if (KResourceLimit *resource_limit = process->GetResourceLimit(); resource_limit != nullptr) {
const auto current_value = resource_limit->GetCurrentValue(ams::svc::LimitableResource_ThreadCountMax);
const auto limit_value = resource_limit->GetLimitValue(ams::svc::LimitableResource_ThreadCountMax);
*out = limit_value - current_value;
} else {
*out = 0;
}
break;
MESOSPHERE_UNREACHABLE_DEFAULT_CASE();
}
} }
break; break;
case ams::svc::InfoType_DebuggerAttached: case ams::svc::InfoType_DebuggerAttached:

View File

@@ -15,10 +15,10 @@
*/ */
#include <mesosphere.hpp> #include <mesosphere.hpp>
namespace ams::kern::svc { #pragma GCC push_options
#pragma GCC optimize ("-O3")
#pragma GCC push_options namespace ams::kern::svc {
#pragma GCC optimize ("-O3")
/* ============================= Common ============================= */ /* ============================= Common ============================= */
@@ -315,6 +315,6 @@ namespace ams::kern::svc {
return ReplyAndReceiveWithUserBuffer(out_index, message_buffer, message_buffer_size, handles, num_handles, reply_target, timeout_ns); return ReplyAndReceiveWithUserBuffer(out_index, message_buffer, message_buffer_size, handles, num_handles, reply_target, timeout_ns);
} }
#pragma GCC pop_options
} }
#pragma GCC pop_options

View File

@@ -210,7 +210,7 @@ namespace ams::kern::svc {
KResourceLimit *process_resource_limit = resource_limit.IsNotNull() ? resource_limit.GetPointerUnsafe() : std::addressof(Kernel::GetSystemResourceLimit()); KResourceLimit *process_resource_limit = resource_limit.IsNotNull() ? resource_limit.GetPointerUnsafe() : std::addressof(Kernel::GetSystemResourceLimit());
/* Get the pool for the process. */ /* Get the pool for the process. */
const auto pool = [] ALWAYS_INLINE_LAMBDA (u32 flags) -> KMemoryManager::Pool { const auto pool = [](u32 flags) ALWAYS_INLINE_LAMBDA -> KMemoryManager::Pool {
if (GetTargetFirmware() >= TargetFirmware_5_0_0) { if (GetTargetFirmware() >= TargetFirmware_5_0_0) {
switch (flags & ams::svc::CreateProcessFlag_PoolPartitionMask) { switch (flags & ams::svc::CreateProcessFlag_PoolPartitionMask) {
case ams::svc::CreateProcessFlag_PoolPartitionApplication: case ams::svc::CreateProcessFlag_PoolPartitionApplication:

View File

@@ -63,6 +63,7 @@ namespace ams::impl {
AMS_DEFINE_SYSTEM_THREAD(-7, mitm, InitializeThread); AMS_DEFINE_SYSTEM_THREAD(-7, mitm, InitializeThread);
AMS_DEFINE_SYSTEM_THREAD(-1, mitm_sf, QueryServerProcessThread); AMS_DEFINE_SYSTEM_THREAD(-1, mitm_sf, QueryServerProcessThread);
AMS_DEFINE_SYSTEM_THREAD(16, mitm_fs, RomFileSystemInitializeThread); AMS_DEFINE_SYSTEM_THREAD(16, mitm_fs, RomFileSystemInitializeThread);
AMS_DEFINE_SYSTEM_THREAD(16, mitm_fs, RomFileSystemFinalizeThread);
AMS_DEFINE_SYSTEM_THREAD(21, mitm, DebugThrowThread); AMS_DEFINE_SYSTEM_THREAD(21, mitm, DebugThrowThread);
AMS_DEFINE_SYSTEM_THREAD(21, mitm_sysupdater, IpcServer); AMS_DEFINE_SYSTEM_THREAD(21, mitm_sysupdater, IpcServer);
AMS_DEFINE_SYSTEM_THREAD(21, mitm_sysupdater, AsyncPrepareSdCardUpdateTask); AMS_DEFINE_SYSTEM_THREAD(21, mitm_sysupdater, AsyncPrepareSdCardUpdateTask);

View File

@@ -118,12 +118,12 @@ namespace ams::fssystem {
/* Copy API. */ /* Copy API. */
Result CopyFile(fs::fsa::IFileSystem *dst_fs, fs::fsa::IFileSystem *src_fs, const char *dst_parent_path, const char *src_path, const fs::DirectoryEntry *dir_ent, void *work_buf, size_t work_buf_size); Result CopyFile(fs::fsa::IFileSystem *dst_fs, fs::fsa::IFileSystem *src_fs, const char *dst_parent_path, const char *src_path, const fs::DirectoryEntry *dir_ent, void *work_buf, size_t work_buf_size);
NX_INLINE Result CopyFile(fs::fsa::IFileSystem *fs, const char *dst_parent_path, const char *src_path, const fs::DirectoryEntry *dir_ent, void *work_buf, size_t work_buf_size) { ALWAYS_INLINE Result CopyFile(fs::fsa::IFileSystem *fs, const char *dst_parent_path, const char *src_path, const fs::DirectoryEntry *dir_ent, void *work_buf, size_t work_buf_size) {
return CopyFile(fs, fs, dst_parent_path, src_path, dir_ent, work_buf, work_buf_size); return CopyFile(fs, fs, dst_parent_path, src_path, dir_ent, work_buf, work_buf_size);
} }
Result CopyDirectoryRecursively(fs::fsa::IFileSystem *dst_fs, fs::fsa::IFileSystem *src_fs, const char *dst_path, const char *src_path, void *work_buf, size_t work_buf_size); Result CopyDirectoryRecursively(fs::fsa::IFileSystem *dst_fs, fs::fsa::IFileSystem *src_fs, const char *dst_path, const char *src_path, void *work_buf, size_t work_buf_size);
NX_INLINE Result CopyDirectoryRecursively(fs::fsa::IFileSystem *fs, const char *dst_path, const char *src_path, void *work_buf, size_t work_buf_size) { ALWAYS_INLINE Result CopyDirectoryRecursively(fs::fsa::IFileSystem *fs, const char *dst_path, const char *src_path, void *work_buf, size_t work_buf_size) {
return CopyDirectoryRecursively(fs, fs, dst_path, src_path, work_buf, work_buf_size); return CopyDirectoryRecursively(fs, fs, dst_path, src_path, work_buf, work_buf_size);
} }
@@ -148,11 +148,11 @@ namespace ams::fssystem {
Result EnsureDirectoryRecursively(fs::fsa::IFileSystem *fs, const char *path); Result EnsureDirectoryRecursively(fs::fsa::IFileSystem *fs, const char *path);
Result EnsureParentDirectoryRecursively(fs::fsa::IFileSystem *fs, const char *path); Result EnsureParentDirectoryRecursively(fs::fsa::IFileSystem *fs, const char *path);
template<typename F> template<s64 RetryMilliSeconds = 100>
NX_INLINE Result RetryFinitelyForTargetLocked(F f) { ALWAYS_INLINE Result RetryFinitelyForTargetLocked(auto f) {
/* Retry up to 10 times, 100ms between retries. */ /* Retry up to 10 times, 100ms between retries. */
constexpr s32 MaxRetryCount = 10; constexpr s32 MaxRetryCount = 10;
constexpr TimeSpan RetryWaitTime = TimeSpan::FromMilliSeconds(100); constexpr TimeSpan RetryWaitTime = TimeSpan::FromMilliSeconds(RetryMilliSeconds);
s32 remaining_retries = MaxRetryCount; s32 remaining_retries = MaxRetryCount;
while (true) { while (true) {

View File

@@ -66,6 +66,8 @@ namespace ams::hos {
Version_12_0_3 = ::ams::TargetFirmware_12_0_3, Version_12_0_3 = ::ams::TargetFirmware_12_0_3,
Version_12_1_0 = ::ams::TargetFirmware_12_1_0, Version_12_1_0 = ::ams::TargetFirmware_12_1_0,
Version_13_0_0 = ::ams::TargetFirmware_13_0_0, Version_13_0_0 = ::ams::TargetFirmware_13_0_0,
Version_13_1_0 = ::ams::TargetFirmware_13_1_0,
Version_13_2_0 = ::ams::TargetFirmware_13_2_0,
Version_Current = ::ams::TargetFirmware_Current, Version_Current = ::ams::TargetFirmware_Current,

View File

@@ -62,20 +62,16 @@ namespace ams::settings {
char name[MaxLength]; char name[MaxLength];
static constexpr LanguageCode Encode(const char *name, size_t name_size) { static constexpr LanguageCode Encode(util::string_view name) {
LanguageCode out{}; LanguageCode out{};
for (size_t i = 0; i < MaxLength && i < name_size; i++) { for (size_t i = 0; i < MaxLength && i < name.size(); i++) {
out.name[i] = name[i]; out.name[i] = name[i];
} }
return out; return out;
} }
static constexpr LanguageCode Encode(const char *name) {
return Encode(name, std::strlen(name));
}
template<Language Lang> template<Language Lang>
static constexpr inline LanguageCode EncodeLanguage = [] { static constexpr inline LanguageCode EncodeLanguage() {
if constexpr (false) { /* ... */ } if constexpr (false) { /* ... */ }
#define AMS_MATCH_LANGUAGE(lang, enc) else if constexpr (Lang == Language_##lang) { return LanguageCode::Encode(enc); } #define AMS_MATCH_LANGUAGE(lang, enc) else if constexpr (Lang == Language_##lang) { return LanguageCode::Encode(enc); }
AMS_MATCH_LANGUAGE(Japanese, "ja") AMS_MATCH_LANGUAGE(Japanese, "ja")
@@ -98,28 +94,28 @@ namespace ams::settings {
AMS_MATCH_LANGUAGE(TraditionalChinese, "zh-Hant") AMS_MATCH_LANGUAGE(TraditionalChinese, "zh-Hant")
#undef AMS_MATCH_LANGUAGE #undef AMS_MATCH_LANGUAGE
else { static_assert(Lang != Language_Japanese); } else { static_assert(Lang != Language_Japanese); }
}(); }
static constexpr inline LanguageCode Encode(const Language language) { static constexpr inline LanguageCode Encode(const Language language) {
constexpr LanguageCode EncodedLanguages[Language_Count] = { constexpr LanguageCode EncodedLanguages[Language_Count] = {
EncodeLanguage<Language_Japanese>, EncodeLanguage<Language_Japanese>(),
EncodeLanguage<Language_AmericanEnglish>, EncodeLanguage<Language_AmericanEnglish>(),
EncodeLanguage<Language_French>, EncodeLanguage<Language_French>(),
EncodeLanguage<Language_German>, EncodeLanguage<Language_German>(),
EncodeLanguage<Language_Italian>, EncodeLanguage<Language_Italian>(),
EncodeLanguage<Language_Spanish>, EncodeLanguage<Language_Spanish>(),
EncodeLanguage<Language_Chinese>, EncodeLanguage<Language_Chinese>(),
EncodeLanguage<Language_Korean>, EncodeLanguage<Language_Korean>(),
EncodeLanguage<Language_Dutch>, EncodeLanguage<Language_Dutch>(),
EncodeLanguage<Language_Portuguese>, EncodeLanguage<Language_Portuguese>(),
EncodeLanguage<Language_Russian>, EncodeLanguage<Language_Russian>(),
EncodeLanguage<Language_Taiwanese>, EncodeLanguage<Language_Taiwanese>(),
EncodeLanguage<Language_BritishEnglish>, EncodeLanguage<Language_BritishEnglish>(),
EncodeLanguage<Language_CanadianFrench>, EncodeLanguage<Language_CanadianFrench>(),
EncodeLanguage<Language_LatinAmericanSpanish>, EncodeLanguage<Language_LatinAmericanSpanish>(),
/* 4.0.0+ */ /* 4.0.0+ */
EncodeLanguage<Language_SimplifiedChinese>, EncodeLanguage<Language_SimplifiedChinese>(),
EncodeLanguage<Language_TraditionalChinese>, EncodeLanguage<Language_TraditionalChinese>(),
}; };
return EncodedLanguages[language]; return EncodedLanguages[language];
} }

View File

@@ -54,11 +54,11 @@ namespace ams::sf::cmif {
void DisposeImpl(); void DisposeImpl();
virtual void AddReference() { virtual void AddReference() override {
ServiceObjectImplBase2::AddReferenceImpl(); ServiceObjectImplBase2::AddReferenceImpl();
} }
virtual void Release() { virtual void Release() override {
if (ServiceObjectImplBase2::ReleaseImpl()) { if (ServiceObjectImplBase2::ReleaseImpl()) {
this->DisposeImpl(); this->DisposeImpl();
} }

View File

@@ -43,7 +43,7 @@ namespace ams::sf {
return lmem::FreeToExpHeap(m_handle, buffer); return lmem::FreeToExpHeap(m_handle, buffer);
} }
virtual bool IsEqualImpl(const MemoryResource &resource) const { virtual bool IsEqualImpl(const MemoryResource &resource) const override {
return this == std::addressof(resource); return this == std::addressof(resource);
} }
}; };
@@ -76,9 +76,9 @@ namespace ams::sf {
return lmem::FreeToUnitHeap(m_handle, buffer); return lmem::FreeToUnitHeap(m_handle, buffer);
} }
virtual bool IsEqualImpl(const MemoryResource &resource) const { virtual bool IsEqualImpl(const MemoryResource &resource) const override {
return this == std::addressof(resource); return this == std::addressof(resource);
} }
}; };
} }

View File

@@ -37,9 +37,9 @@ namespace ams::sf {
return m_standard_allocator->Free(buffer); return m_standard_allocator->Free(buffer);
} }
virtual bool IsEqualImpl(const MemoryResource &resource) const { virtual bool IsEqualImpl(const MemoryResource &resource) const override {
return this == std::addressof(resource); return this == std::addressof(resource);
} }
}; };
} }

View File

@@ -31,7 +31,7 @@ namespace ams::sf {
public: public:
class Object; class Object;
using Allocator = StatelessDummyAllocator; using Allocator = StatelessDummyAllocator;
using StatelessAllocator = typename Policy::StatelessAllocator<Object>; using StatelessAllocator = typename Policy::template StatelessAllocator<Object>;
class Object final : private ::ams::sf::impl::ServiceObjectImplBase2, public Base { class Object final : private ::ams::sf::impl::ServiceObjectImplBase2, public Base {
NON_COPYABLE(Object); NON_COPYABLE(Object);

View File

@@ -40,8 +40,8 @@ namespace ams::sm {
return out; return out;
} }
static constexpr ServiceName Encode(const char *name) { static constexpr ServiceName Encode(util::string_view name) {
return Encode(name, std::strlen(name)); return Encode(name.data(), name.size());
} }
}; };

View File

@@ -43,6 +43,7 @@ namespace ams::socket {
s32 Shutdown(s32 desc, ShutdownMethod how); s32 Shutdown(s32 desc, ShutdownMethod how);
s32 Socket(Family domain, Type type, Protocol protocol);
s32 SocketExempt(Family domain, Type type, Protocol protocol); s32 SocketExempt(Family domain, Type type, Protocol protocol);
s32 Accept(s32 desc, SockAddr *out_address, SockLenT *out_addr_len); s32 Accept(s32 desc, SockAddr *out_address, SockLenT *out_addr_len);

View File

@@ -57,4 +57,42 @@ namespace ams::socket {
} }
}; };
class SystemConfigLightDefault : public Config {
public:
static constexpr size_t DefaultTcpInitialSendBufferSize = 16_KB;
static constexpr size_t DefaultTcpInitialReceiveBufferSize = 16_KB;
static constexpr size_t DefaultTcpAutoSendBufferSizeMax = 0_KB;
static constexpr size_t DefaultTcpAutoReceiveBufferSizeMax = 0_KB;
static constexpr size_t DefaultUdpSendBufferSize = 9_KB;
static constexpr size_t DefaultUdpReceiveBufferSize = 42240;
static constexpr auto DefaultSocketBufferEfficiency = 2;
static constexpr auto DefaultConcurrency = 2;
static constexpr size_t DefaultAllocatorPoolSize = 64_KB;
static constexpr size_t PerTcpSocketWorstCaseMemoryPoolSize = [] {
constexpr size_t WorstCaseTcpSendBufferSize = AlignMss(std::max(DefaultTcpInitialSendBufferSize, DefaultTcpAutoSendBufferSizeMax));
constexpr size_t WorstCaseTcpReceiveBufferSize = AlignMss(std::max(DefaultTcpInitialReceiveBufferSize, DefaultTcpAutoReceiveBufferSizeMax));
return util::AlignUp(WorstCaseTcpSendBufferSize * DefaultSocketBufferEfficiency + WorstCaseTcpReceiveBufferSize * DefaultSocketBufferEfficiency, os::MemoryPageSize);
}();
static constexpr size_t PerUdpSocketWorstCaseMemoryPoolSize = [] {
constexpr size_t WorstCaseUdpSendBufferSize = AlignMss(DefaultUdpSendBufferSize);
constexpr size_t WorstCaseUdpReceiveBufferSize = AlignMss(DefaultUdpReceiveBufferSize);
return util::AlignUp(WorstCaseUdpSendBufferSize * DefaultSocketBufferEfficiency + WorstCaseUdpReceiveBufferSize * DefaultSocketBufferEfficiency, os::MemoryPageSize);
}();
public:
constexpr SystemConfigLightDefault(void *mp, size_t mp_sz, size_t ap, int c=DefaultConcurrency)
: Config(mp, mp_sz, ap,
DefaultTcpInitialSendBufferSize, DefaultTcpInitialReceiveBufferSize,
DefaultTcpAutoSendBufferSizeMax, DefaultTcpAutoReceiveBufferSizeMax,
DefaultUdpSendBufferSize, DefaultUdpReceiveBufferSize,
DefaultSocketBufferEfficiency, c)
{
/* Mark as system. */
m_system = true;
}
};
} }

View File

@@ -51,7 +51,7 @@ namespace ams::spl::impl {
Result AllocateAesKeySlot(s32 *out_keyslot); Result AllocateAesKeySlot(s32 *out_keyslot);
Result DeallocateAesKeySlot(s32 keyslot); Result DeallocateAesKeySlot(s32 keyslot);
Result TestAesKeySlot(s32 *out_index, s32 keyslot); Result TestAesKeySlot(s32 *out_index, bool *out_virtual, s32 keyslot);
os::SystemEvent *GetAesKeySlotAvailableEvent(); os::SystemEvent *GetAesKeySlotAvailableEvent();

View File

@@ -50,7 +50,7 @@ namespace ams::time {
AMS_ASSERT(rhs.IsValid()); AMS_ASSERT(rhs.IsValid());
} }
constexpr auto ToUint64 = [] ALWAYS_INLINE_LAMBDA (const time::CalendarTime &time) { constexpr auto ToUint64 = [](const time::CalendarTime &time) ALWAYS_INLINE_LAMBDA {
return (static_cast<u64>(time.year) << 40) | return (static_cast<u64>(time.year) << 40) |
(static_cast<u64>(time.month) << 32) | (static_cast<u64>(time.month) << 32) |
(static_cast<u64>(time.day) << 24) | (static_cast<u64>(time.day) << 24) |

View File

@@ -40,12 +40,28 @@ namespace ams::tipc::impl {
#define AMS_TIPC_IMPL_EXTRACT_SYNC_METHOD_ARGUMENTS(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \ #define AMS_TIPC_IMPL_EXTRACT_SYNC_METHOD_ARGUMENTS(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \
using NAME##ArgumentsType = ::ams::tipc::impl::SyncFunctionArgsType<&NAME##ArgumentsFunctionHolder::f>; using NAME##ArgumentsType = ::ams::tipc::impl::SyncFunctionArgsType<&NAME##ArgumentsFunctionHolder::f>;
#define AMS_TIPC_IMPL_GET_MAXIMUM_REQUEST_SIZE(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \
, ::ams::tipc::impl::CommandMetaInfo<CMD_ID + 0x10, NAME##ArgumentsType>::InMessageTotalSize
#define AMS_TIPC_IMPL_GET_MAXIMUM_RESPONSE_SIZE(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \
, ::ams::tipc::impl::CommandMetaInfo<CMD_ID + 0x10, NAME##ArgumentsType>::OutMessageTotalSize
#define AMS_TIPC_IMPL_DEFINE_INTERFACE(BASECLASS, CLASSNAME, CMD_MACRO) \ #define AMS_TIPC_IMPL_DEFINE_INTERFACE(BASECLASS, CLASSNAME, CMD_MACRO) \
class CLASSNAME : public BASECLASS { \ class CLASSNAME : public BASECLASS { \
private: \ private: \
CMD_MACRO(CLASSNAME, AMS_TIPC_IMPL_DEFINE_SYNC_METHOD_HOLDER) \ CMD_MACRO(CLASSNAME, AMS_TIPC_IMPL_DEFINE_SYNC_METHOD_HOLDER) \
public: \ public: \
CMD_MACRO(CLASSNAME, AMS_TIPC_IMPL_EXTRACT_SYNC_METHOD_ARGUMENTS) \ CMD_MACRO(CLASSNAME, AMS_TIPC_IMPL_EXTRACT_SYNC_METHOD_ARGUMENTS) \
public: \
static constexpr size_t MaximumRequestSize = std::max<size_t>({ \
0 \
CMD_MACRO(CLASSNAME, AMS_TIPC_IMPL_GET_MAXIMUM_REQUEST_SIZE) \
}); \
\
static constexpr size_t MaximumResponseSize = std::max<size_t>({ \
0 \
CMD_MACRO(CLASSNAME, AMS_TIPC_IMPL_GET_MAXIMUM_RESPONSE_SIZE) \
}); \
}; };
#define AMS_TIPC_IMPL_DEFINE_CONCEPT_HELPERS(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \ #define AMS_TIPC_IMPL_DEFINE_CONCEPT_HELPERS(CLASSNAME, CMD_ID, RETURN, NAME, ARGS, ARGNAMES, VERSION_MIN, VERSION_MAX) \

View File

@@ -319,6 +319,9 @@ namespace ams::tipc::impl {
static constexpr auto OutMessageResultIndex = svc::ipc::MessageBuffer::GetRawDataIndex(OutMessageHeader, OutSpecialHeader); static constexpr auto OutMessageResultIndex = svc::ipc::MessageBuffer::GetRawDataIndex(OutMessageHeader, OutSpecialHeader);
static constexpr auto OutMessageRawDataIndex = OutMessageResultIndex + 1; static constexpr auto OutMessageRawDataIndex = OutMessageResultIndex + 1;
static constexpr size_t InMessageTotalSize = (InMessageRawDataIndex * sizeof(u32)) + InDataSize;
static constexpr size_t OutMessageTotalSize = (OutMessageRawDataIndex * sizeof(u32)) + OutDataSize;
/* Construction of argument serialization structs. */ /* Construction of argument serialization structs. */
private: private:
template<typename> template<typename>
@@ -472,7 +475,7 @@ namespace ams::tipc::impl {
using OutRawHolderType = OutRawHolder<CommandMeta::OutDataSize, CommandMeta::OutDataAlign, CommandMeta::OutMessageRawDataIndex>; using OutRawHolderType = OutRawHolder<CommandMeta::OutDataSize, CommandMeta::OutDataAlign, CommandMeta::OutMessageRawDataIndex>;
using OutHandleHolderType = OutHandleHolder<CommandMeta::NumOutMoveHandles, CommandMeta::NumOutCopyHandles, CommandMeta::OutMessageHandleIndex>; using OutHandleHolderType = OutHandleHolder<CommandMeta::NumOutMoveHandles, CommandMeta::NumOutCopyHandles, CommandMeta::OutMessageHandleIndex>;
private: private:
static consteval u64 GetMessageHeaderForCheck(const svc::ipc::MessageBuffer::MessageHeader &header) { static constexpr u64 GetMessageHeaderForCheck(const svc::ipc::MessageBuffer::MessageHeader &header) {
using Value = util::BitPack32::Field<0, BITSIZEOF(util::BitPack32)>; using Value = util::BitPack32::Field<0, BITSIZEOF(util::BitPack32)>;
const util::BitPack32 *data = header.GetData(); const util::BitPack32 *data = header.GetData();
@@ -482,7 +485,7 @@ namespace ams::tipc::impl {
return static_cast<u64>(lower) | (static_cast<u64>(upper) << BITSIZEOF(u32)); return static_cast<u64>(lower) | (static_cast<u64>(upper) << BITSIZEOF(u32));
} }
static consteval u32 GetSpecialHeaderForCheck(const svc::ipc::MessageBuffer::SpecialHeader &header) { static constexpr u32 GetSpecialHeaderForCheck(const svc::ipc::MessageBuffer::SpecialHeader &header) {
using Value = util::BitPack32::Field<0, BITSIZEOF(util::BitPack32)>; using Value = util::BitPack32::Field<0, BITSIZEOF(util::BitPack32)>;
return header.GetHeader()->Get<Value>(); return header.GetHeader()->Get<Value>();

View File

@@ -44,16 +44,17 @@ namespace ams::tipc {
} }
class DeferrableBase : public impl::DeferrableBaseTag { class DeferrableBaseImpl : public impl::DeferrableBaseTag {
private: private:
DeferralManagerBase *m_deferral_manager; DeferralManagerBase *m_deferral_manager;
ObjectHolder m_object_holder; ObjectHolder m_object_holder;
uintptr_t m_resume_key; uintptr_t m_resume_key;
u8 m_message_buffer[svc::ipc::MessageBufferSize]; const u32 m_message_buffer_size;
u8 m_message_buffer_base[0];
public: public:
ALWAYS_INLINE DeferrableBase() : m_deferral_manager(nullptr), m_object_holder(), m_resume_key() { /* ... */ } ALWAYS_INLINE DeferrableBaseImpl(u32 mb_size) : m_deferral_manager(nullptr), m_object_holder(), m_resume_key(), m_message_buffer_size(mb_size) { /* ... */ }
~DeferrableBase(); ~DeferrableBaseImpl();
ALWAYS_INLINE void SetDeferralManager(DeferralManagerBase *manager, os::NativeHandle reply_target, ServiceObjectBase *object) { ALWAYS_INLINE void SetDeferralManager(DeferralManagerBase *manager, os::NativeHandle reply_target, ServiceObjectBase *object) {
m_deferral_manager = manager; m_deferral_manager = manager;
@@ -67,7 +68,7 @@ namespace ams::tipc {
template<IsResumeKey ResumeKey> template<IsResumeKey ResumeKey>
ALWAYS_INLINE void RegisterRetry(ResumeKey key) { ALWAYS_INLINE void RegisterRetry(ResumeKey key) {
m_resume_key = ConvertToInternalResumeKey(key); m_resume_key = ConvertToInternalResumeKey(key);
std::memcpy(m_message_buffer, svc::ipc::GetMessageBuffer(), sizeof(m_message_buffer)); std::memcpy(m_message_buffer_base, svc::ipc::GetMessageBuffer(), m_message_buffer_size);
} }
template<IsResumeKey ResumeKey, typename F> template<IsResumeKey ResumeKey, typename F>
@@ -85,11 +86,49 @@ namespace ams::tipc {
m_resume_key = 0; m_resume_key = 0;
/* Restore message buffer. */ /* Restore message buffer. */
std::memcpy(svc::ipc::GetMessageBuffer(), m_message_buffer, sizeof(m_message_buffer)); std::memcpy(svc::ipc::GetMessageBuffer(), m_message_buffer_base, m_message_buffer_size);
/* Process the request. */ /* Process the request. */
return port_manager->ProcessDeferredRequest(m_object_holder); return port_manager->ProcessDeferredRequest(m_object_holder);
} }
protected:
static consteval size_t GetMessageBufferOffsetBase();
};
static_assert(std::is_standard_layout<DeferrableBaseImpl>::value);
template<size_t _MessageBufferRequiredSize>
class DeferrableBaseImplWithBuffer : public DeferrableBaseImpl {
private:
static constexpr size_t MessageBufferRequiredSize = _MessageBufferRequiredSize;
private:
u8 m_message_buffer[MessageBufferRequiredSize];
public:
DeferrableBaseImplWithBuffer();
private:
static consteval size_t GetMessageBufferOffset();
};
consteval size_t DeferrableBaseImpl::GetMessageBufferOffsetBase() {
return AMS_OFFSETOF(DeferrableBaseImpl, m_message_buffer_base);
}
template<size_t _MessageBufferRequiredSize>
consteval size_t DeferrableBaseImplWithBuffer<_MessageBufferRequiredSize>::GetMessageBufferOffset() {
return AMS_OFFSETOF(DeferrableBaseImplWithBuffer<_MessageBufferRequiredSize>, m_message_buffer);
}
template<size_t _MessageBufferRequiredSize>
ALWAYS_INLINE DeferrableBaseImplWithBuffer<_MessageBufferRequiredSize>::DeferrableBaseImplWithBuffer() : DeferrableBaseImpl(MessageBufferRequiredSize) {
static_assert(GetMessageBufferOffsetBase() == GetMessageBufferOffset());
static_assert(sizeof(DeferrableBaseImplWithBuffer<_MessageBufferRequiredSize>) >= sizeof(DeferrableBaseImpl) + MessageBufferRequiredSize);
}
template<typename Interface, size_t MaximumDefaultRequestSize = 0>
class DeferrableBase : public DeferrableBaseImplWithBuffer<std::max(Interface::MaximumRequestSize, MaximumDefaultRequestSize)> {
private:
using BaseImpl = DeferrableBaseImplWithBuffer<std::max(Interface::MaximumRequestSize, MaximumDefaultRequestSize)>;
public:
using BaseImpl::BaseImpl;
}; };
template<class T> template<class T>
@@ -100,11 +139,11 @@ namespace ams::tipc {
NON_MOVEABLE(DeferralManagerBase); NON_MOVEABLE(DeferralManagerBase);
private: private:
size_t m_object_count; size_t m_object_count;
DeferrableBase *m_objects_base[0]; DeferrableBaseImpl *m_objects_base[0];
public: public:
ALWAYS_INLINE DeferralManagerBase() : m_object_count(0) { /* ... */ } ALWAYS_INLINE DeferralManagerBase() : m_object_count(0) { /* ... */ }
void AddObject(DeferrableBase &object, os::NativeHandle reply_target, ServiceObjectBase *service_object) { void AddObject(DeferrableBaseImpl &object, os::NativeHandle reply_target, ServiceObjectBase *service_object) {
/* Set ourselves as the manager for the object. */ /* Set ourselves as the manager for the object. */
object.SetDeferralManager(this, reply_target, service_object); object.SetDeferralManager(this, reply_target, service_object);
@@ -113,7 +152,7 @@ namespace ams::tipc {
m_objects_base[m_object_count++] = std::addressof(object); m_objects_base[m_object_count++] = std::addressof(object);
} }
void RemoveObject(DeferrableBase *object) { void RemoveObject(DeferrableBaseImpl *object) {
/* If the object is present, remove it. */ /* If the object is present, remove it. */
for (size_t i = 0; i < m_object_count; ++i) { for (size_t i = 0; i < m_object_count; ++i) {
if (m_objects_base[i] == object) { if (m_objects_base[i] == object) {
@@ -148,7 +187,7 @@ namespace ams::tipc {
}; };
static_assert(std::is_standard_layout<DeferralManagerBase>::value); static_assert(std::is_standard_layout<DeferralManagerBase>::value);
inline DeferrableBase::~DeferrableBase() { inline DeferrableBaseImpl::~DeferrableBaseImpl() {
AMS_ASSUME(m_deferral_manager != nullptr); AMS_ASSUME(m_deferral_manager != nullptr);
m_deferral_manager->RemoveObject(this); m_deferral_manager->RemoveObject(this);
} }
@@ -156,7 +195,7 @@ namespace ams::tipc {
template<size_t N> requires (N > 0) template<size_t N> requires (N > 0)
class DeferralManager final : public DeferralManagerBase { class DeferralManager final : public DeferralManagerBase {
private: private:
DeferrableBase *m_objects[N]; DeferrableBaseImpl *m_objects[N];
public: public:
DeferralManager(); DeferralManager();
private: private:
@@ -167,15 +206,15 @@ namespace ams::tipc {
return AMS_OFFSETOF(DeferralManagerBase, m_objects_base); return AMS_OFFSETOF(DeferralManagerBase, m_objects_base);
} }
template<size_t N> template<size_t N> requires (N > 0)
consteval size_t DeferralManager<N>::GetObjectPointersOffset() { consteval size_t DeferralManager<N>::GetObjectPointersOffset() {
return AMS_OFFSETOF(DeferralManager<N>, m_objects); return AMS_OFFSETOF(DeferralManager<N>, m_objects);
} }
template<size_t N> template<size_t N> requires (N > 0)
inline DeferralManager<N>::DeferralManager() : DeferralManagerBase() { inline DeferralManager<N>::DeferralManager() : DeferralManagerBase() {
static_assert(GetObjectPointersOffset() == GetObjectPointersOffsetBase()); static_assert(GetObjectPointersOffset() == GetObjectPointersOffsetBase());
static_assert(sizeof(DeferralManager<N>) == sizeof(DeferralManagerBase) + N * sizeof(DeferrableBase *)); static_assert(sizeof(DeferralManager<N>) == sizeof(DeferralManagerBase) + N * sizeof(DeferrableBaseImpl *));
} }
} }

View File

@@ -686,7 +686,7 @@ namespace ams::tipc {
} }
/* Try to reply/receive. */ /* Try to reply/receive. */
const Result result = [&] ALWAYS_INLINE_LAMBDA () -> Result { const Result result = [&]() ALWAYS_INLINE_LAMBDA -> Result {
os::MultiWaitHolderType *signaled_holder = nullptr; os::MultiWaitHolderType *signaled_holder = nullptr;
ON_SCOPE_EXIT { AMS_ABORT_UNLESS(signaled_holder == nullptr); }; ON_SCOPE_EXIT { AMS_ABORT_UNLESS(signaled_holder == nullptr); };
return m_object_manager->ReplyAndReceive(std::addressof(signaled_holder), out_object, reply_target, std::addressof(m_multi_wait)); return m_object_manager->ReplyAndReceive(std::addressof(signaled_holder), out_object, reply_target, std::addressof(m_multi_wait));
@@ -747,7 +747,7 @@ namespace ams::tipc {
using PortManager = PortManagerImpl; using PortManager = PortManagerImpl;
private: private:
PortManager m_port_manager; PortManager m_port_manager;
PortInfo::Allocator m_port_allocator; typename PortInfo::Allocator m_port_allocator;
public: public:
constexpr ServerManagerImpl() : m_port_manager(), m_port_allocator() { /* ... */ } constexpr ServerManagerImpl() : m_port_manager(), m_port_allocator() { /* ... */ }

View File

@@ -188,6 +188,12 @@ namespace ams::boot2 {
return enable_htc != 0; return enable_htc != 0;
} }
bool IsStandaloneGdbstubEnabled() {
u8 enable_gdbstub = 0;
settings::fwdbg::GetSettingsItemValue(std::addressof(enable_gdbstub), sizeof(enable_gdbstub), "atmosphere", "enable_standalone_gdbstub");
return enable_gdbstub != 0;
}
bool IsAtmosphereLogManagerEnabled() { bool IsAtmosphereLogManagerEnabled() {
/* If htc is enabled, ams log manager is enabled. */ /* If htc is enabled, ams log manager is enabled. */
if (IsHtcEnabled()) { if (IsHtcEnabled()) {
@@ -403,6 +409,9 @@ namespace ams::boot2 {
LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Htc, ncm::StorageId::None), 0); LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Htc, ncm::StorageId::None), 0);
LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Cs, ncm::StorageId::None), 0); LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Cs, ncm::StorageId::None), 0);
LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::DmntGen2, ncm::StorageId::None), 0); LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::DmntGen2, ncm::StorageId::None), 0);
} else if (IsStandaloneGdbstubEnabled()) {
LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::DmntGen2, ncm::StorageId::None), 0);
LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Tma, ncm::StorageId::BuiltInSystem), 0);
} else { } else {
LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Dmnt, ncm::StorageId::None), 0); LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Dmnt, ncm::StorageId::None), 0);
LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Tma, ncm::StorageId::BuiltInSystem), 0); LaunchProgram(nullptr, ncm::ProgramLocation::Make(ncm::SystemProgramId::Tma, ncm::StorageId::BuiltInSystem), 0);

View File

@@ -89,9 +89,8 @@ namespace ams::fs {
Result DeleteSystemSaveData(SaveDataSpaceId space_id, SystemSaveDataId id, UserId user_id) { Result DeleteSystemSaveData(SaveDataSpaceId space_id, SystemSaveDataId id, UserId user_id) {
const auto attribute = SaveDataAttribute::Make(ncm::InvalidProgramId, SaveDataType::System, user_id, id); const auto attribute = SaveDataAttribute::Make(ncm::InvalidProgramId, SaveDataType::System, user_id, id);
/* TODO: Libnx binding for DeleteSaveDataFileSystemBySaveDataAttribute */ static_assert(sizeof(attribute) == sizeof(::FsSaveDataAttribute));
AMS_UNUSED(space_id, attribute); return fsDeleteSaveDataFileSystemBySaveDataAttribute(static_cast<::FsSaveDataSpaceId>(space_id), reinterpret_cast<const ::FsSaveDataAttribute *>(std::addressof(attribute)));
AMS_ABORT();
} }
Result GetSaveDataFlags(u32 *out, SaveDataId id) { Result GetSaveDataFlags(u32 *out, SaveDataId id) {

View File

@@ -196,7 +196,7 @@ namespace ams::htclow::ctrl {
/* Lock ourselves. */ /* Lock ourselves. */
std::scoped_lock lk(m_mutex); std::scoped_lock lk(m_mutex);
auto IsSupportedServiceChannel = [] ALWAYS_INLINE_LAMBDA (const impl::ChannelInternalType &channel, const impl::ChannelInternalType *supported, int num_supported) -> bool { auto IsSupportedServiceChannel = [](const impl::ChannelInternalType &channel, const impl::ChannelInternalType *supported, int num_supported) ALWAYS_INLINE_LAMBDA -> bool {
for (auto i = 0; i < num_supported; ++i) { for (auto i = 0; i < num_supported; ++i) {
if (channel.module_id == supported[i].module_id && channel.channel_id == supported[i].channel_id) { if (channel.module_id == supported[i].module_id && channel.channel_id == supported[i].channel_id) {
return true; return true;

View File

@@ -20,6 +20,8 @@ extern "C" {
constinit u32 __nx_fs_num_sessions = 1; constinit u32 __nx_fs_num_sessions = 1;
constinit u32 __nx_applet_type = AppletType_None; constinit u32 __nx_applet_type = AppletType_None;
constinit bool __nx_fsdev_support_cwd = false;
extern int __system_argc; extern int __system_argc;
extern char** __system_argv; extern char** __system_argv;

View File

@@ -308,7 +308,7 @@ namespace ams::ncm {
out_orphaned[i] = true; out_orphaned[i] = true;
} }
auto IsOrphanedContent = [] ALWAYS_INLINE_LAMBDA (const sf::InArray<ContentId> &list, const ncm::ContentId &id) -> util::optional<size_t> { auto IsOrphanedContent = [](const sf::InArray<ContentId> &list, const ncm::ContentId &id) ALWAYS_INLINE_LAMBDA -> util::optional<size_t> {
/* Check if any input content ids match our found content id. */ /* Check if any input content ids match our found content id. */
for (size_t i = 0; i < list.GetSize(); i++) { for (size_t i = 0; i < list.GetSize(); i++) {
if (list[i] == id) { if (list[i] == id) {

View File

@@ -52,6 +52,26 @@ namespace ams::os::impl {
/* Get the thread impl object from libnx. */ /* Get the thread impl object from libnx. */
ThreadImpl *thread_impl = ::threadGetSelf(); ThreadImpl *thread_impl = ::threadGetSelf();
/* Hack around libnx's main thread, to ensure stratosphere thread type consistency. */
{
auto *tlr = reinterpret_cast<uintptr_t *>(svc::GetThreadLocalRegion());
for (size_t i = sizeof(svc::ThreadLocalRegion) / sizeof(uintptr_t); i > 0; --i) {
if (auto *candidate = reinterpret_cast<ThreadImpl *>(tlr[i - 1]); candidate == thread_impl) {
ThreadImpl *embedded_thread = std::addressof(main_thread->thread_impl_storage);
*embedded_thread = *thread_impl;
if (embedded_thread->next) {
embedded_thread->next->prev_next = std::addressof(embedded_thread->next);
}
thread_impl = embedded_thread;
tlr[i-1] = reinterpret_cast<uintptr_t>(thread_impl);
break;
}
}
}
/* Get the thread priority. */ /* Get the thread priority. */
s32 horizon_priority; s32 horizon_priority;
R_ABORT_UNLESS(svc::GetThreadPriority(std::addressof(horizon_priority), thread_impl->handle)); R_ABORT_UNLESS(svc::GetThreadPriority(std::addressof(horizon_priority), thread_impl->handle));

View File

@@ -54,7 +54,7 @@ namespace ams::osdbg::impl {
static_assert(AMS_OFFSETOF(ThreadLocalRegionIlp32, tls) == 0x1C0); static_assert(AMS_OFFSETOF(ThreadLocalRegionIlp32, tls) == 0x1C0);
struct LibnxThreadVars { struct LibnxThreadVars {
static constexpr u32 Magic = util::FourCC<'!','T','V','$'>::Code; static constexpr u32 Magic = util::ReverseFourCC<'!','T','V','$'>::Code;
u32 magic; u32 magic;
::Handle handle; ::Handle handle;
@@ -69,11 +69,11 @@ namespace ams::osdbg::impl {
volatile u16 disable_counter; volatile u16 disable_counter;
volatile u16 interrupt_flag; volatile u16 interrupt_flag;
u32 reserved0; u32 reserved0;
u64 tls[(0x1E0 - 0x108) / sizeof(u64)]; u64 tls[(0x200 - sizeof(LibnxThreadVars) - 0x108) / sizeof(u64)];
LibnxThreadVars thread_vars; LibnxThreadVars thread_vars;
}; };
static_assert(sizeof(ThreadLocalRegionLibnx) == sizeof(svc::ThreadLocalRegion)); static_assert(sizeof(ThreadLocalRegionLibnx) == sizeof(svc::ThreadLocalRegion));
static_assert(AMS_OFFSETOF(ThreadLocalRegionLibnx, thread_vars) == 0x1E0); static_assert(AMS_OFFSETOF(ThreadLocalRegionLibnx, thread_vars) == 0x200 - sizeof(LibnxThreadVars));
struct LibnxThreadEntryArgs { struct LibnxThreadEntryArgs {
u64 t; u64 t;

View File

@@ -50,9 +50,9 @@ namespace ams::osdbg {
} else { } else {
/* Special-case libnx threads. */ /* Special-case libnx threads. */
if (thread_info->_thread_type_type == ThreadTypeType_Libnx) { if (thread_info->_thread_type_type == ThreadTypeType_Libnx) {
util::TSNPrintf(dst, os::ThreadNameLengthMax, "libnx Thread_0x%p", reinterpret_cast<void *>(thread_info->_thread_type)); util::TSNPrintf(dst, os::ThreadNameLengthMax, "libnx Thread_0x%010lx", reinterpret_cast<uintptr_t>(thread_info->_thread_type));
} else { } else {
util::TSNPrintf(dst, os::ThreadNameLengthMax, "Thread_0x%p", reinterpret_cast<void *>(thread_info->_thread_type)); util::TSNPrintf(dst, os::ThreadNameLengthMax, "Thread_0x%010lx", reinterpret_cast<uintptr_t>(thread_info->_thread_type));
} }
return ResultSuccess(); return ResultSuccess();

View File

@@ -41,6 +41,7 @@ namespace ams::socket::impl {
s32 Shutdown(s32 desc, ShutdownMethod how); s32 Shutdown(s32 desc, ShutdownMethod how);
s32 Socket(Family domain, Type type, Protocol protocol);
s32 SocketExempt(Family domain, Type type, Protocol protocol); s32 SocketExempt(Family domain, Type type, Protocol protocol);
s32 Accept(s32 desc, SockAddr *out_address, SockLenT *out_addr_len); s32 Accept(s32 desc, SockAddr *out_address, SockLenT *out_addr_len);

View File

@@ -206,6 +206,8 @@ namespace ams::socket::impl {
/* TODO: socket::resolver::EnableResolverCalls()? Not necessary in our case (htc), but consider calling it. */ /* TODO: socket::resolver::EnableResolverCalls()? Not necessary in our case (htc), but consider calling it. */
g_initialized = true;
return ResultSuccess(); return ResultSuccess();
} }
@@ -422,6 +424,22 @@ namespace ams::socket::impl {
return result; return result;
} }
s32 Socket(Family domain, Type type, Protocol protocol) {
/* Check pre-conditions. */
AMS_ABORT_UNLESS(IsInitialized());
/* Perform the call. */
Errno error = Errno::ESuccess;
int result = ::bsdSocket(static_cast<int>(domain), static_cast<int>(type), static_cast<int>(protocol));
TranslateResultToBsdError(error, result);
if (result < 0) {
socket::impl::SetLastError(error);
}
return result;
}
s32 SocketExempt(Family domain, Type type, Protocol protocol) { s32 SocketExempt(Family domain, Type type, Protocol protocol) {
/* Check pre-conditions. */ /* Check pre-conditions. */
AMS_ABORT_UNLESS(IsInitialized()); AMS_ABORT_UNLESS(IsInitialized());

View File

@@ -74,6 +74,10 @@ namespace ams::socket {
return impl::Shutdown(desc, how); return impl::Shutdown(desc, how);
} }
s32 Socket(Family domain, Type type, Protocol protocol) {
return impl::Socket(domain, type, protocol);
}
s32 SocketExempt(Family domain, Type type, Protocol protocol) { s32 SocketExempt(Family domain, Type type, Protocol protocol) {
return impl::SocketExempt(domain, type, protocol); return impl::SocketExempt(domain, type, protocol);
} }

View File

@@ -729,9 +729,10 @@ namespace ams::spl::impl {
return ResultSuccess(); return ResultSuccess();
} }
Result TestAesKeySlot(s32 *out_index, s32 keyslot) { Result TestAesKeySlot(s32 *out_index, bool *out_virtual, s32 keyslot) {
if (g_is_physical_keyslot_allowed && IsPhysicalAesKeySlot(keyslot)) { if (g_is_physical_keyslot_allowed && IsPhysicalAesKeySlot(keyslot)) {
*out_index = keyslot; *out_index = keyslot;
*out_virtual = false;
return ResultSuccess(); return ResultSuccess();
} }
@@ -740,7 +741,8 @@ namespace ams::spl::impl {
const s32 index = GetVirtualAesKeySlotIndex(keyslot); const s32 index = GetVirtualAesKeySlotIndex(keyslot);
R_UNLESS(g_is_aes_keyslot_allocated[index], spl::ResultInvalidKeySlot()); R_UNLESS(g_is_aes_keyslot_allocated[index], spl::ResultInvalidKeySlot());
*out_index = index; *out_index = index;
*out_virtual = true;
return ResultSuccess(); return ResultSuccess();
} }

View File

@@ -34,7 +34,7 @@ namespace ams::sprofile::srv {
constexpr const sm::ServiceName ServiceNameForSystemProcess = sm::ServiceName::Encode("sprof:sp"); constexpr const sm::ServiceName ServiceNameForSystemProcess = sm::ServiceName::Encode("sprof:sp");
constexpr inline size_t BgAgentSessionCountMax = 2; constexpr inline size_t BgAgentSessionCountMax = 2;
constexpr inline size_t SystemProcessSessionCountMax = 5; constexpr inline size_t SystemProcessSessionCountMax = 10;
constexpr inline size_t SessionCountMax = BgAgentSessionCountMax + SystemProcessSessionCountMax; constexpr inline size_t SessionCountMax = BgAgentSessionCountMax + SystemProcessSessionCountMax;
@@ -42,8 +42,8 @@ namespace ams::sprofile::srv {
struct ServerManagerOptions { struct ServerManagerOptions {
static constexpr size_t PointerBufferSize = 0x0; static constexpr size_t PointerBufferSize = 0x0;
static constexpr size_t MaxDomains = SessionCountMax; /* NOTE: Official is 3 */ static constexpr size_t MaxDomains = SessionCountMax; /* NOTE: Official is 9 */
static constexpr size_t MaxDomainObjects = 16; /* NOTE: Official is 8 */ static constexpr size_t MaxDomainObjects = 16; /* NOTE: Official is 14 */
static constexpr bool CanDeferInvokeRequest = false; static constexpr bool CanDeferInvokeRequest = false;
static constexpr bool CanManageMitmServers = false; static constexpr bool CanManageMitmServers = false;
}; };

View File

@@ -18,8 +18,8 @@
#include "sprofile_srv_types.hpp" #include "sprofile_srv_types.hpp"
#define AMS_SPROFILE_I_PROFILE_IMPORTER_INTERFACE_INFO(C, H) \ #define AMS_SPROFILE_I_PROFILE_IMPORTER_INTERFACE_INFO(C, H) \
AMS_SF_METHOD_INFO(C, H, 0, Result, ImportProfile, (const sprofile::srv::ProfileDataForImportData &data), (data)) \ AMS_SF_METHOD_INFO(C, H, 0, Result, ImportProfile, (const sprofile::srv::ProfileDataForImportData &import), (import)) \
AMS_SF_METHOD_INFO(C, H, 1, Result, Commit, (), ()) \ AMS_SF_METHOD_INFO(C, H, 1, Result, Commit, (), ()) \
AMS_SF_METHOD_INFO(C, H, 0, Result, ImportMetadata, (const sprofile::srv::ProfileMetadataForImportMetadata &data), (data)) \ AMS_SF_METHOD_INFO(C, H, 2, Result, ImportMetadata, (const sprofile::srv::ProfileMetadataForImportMetadata &import), (import)) \
AMS_SF_DEFINE_INTERFACE(ams::sprofile, IProfileImporter, AMS_SPROFILE_I_PROFILE_IMPORTER_INTERFACE_INFO) AMS_SF_DEFINE_INTERFACE(ams::sprofile, IProfileImporter, AMS_SPROFILE_I_PROFILE_IMPORTER_INTERFACE_INFO)

View File

@@ -21,6 +21,6 @@
AMS_SF_METHOD_INFO(C, H, 1, Result, GetUnsigned64, (sf::Out<u64> out, sprofile::Identifier profile, sprofile::Identifier key), (out, profile, key)) \ AMS_SF_METHOD_INFO(C, H, 1, Result, GetUnsigned64, (sf::Out<u64> out, sprofile::Identifier profile, sprofile::Identifier key), (out, profile, key)) \
AMS_SF_METHOD_INFO(C, H, 2, Result, GetSigned32, (sf::Out<s32> out, sprofile::Identifier profile, sprofile::Identifier key), (out, profile, key)) \ AMS_SF_METHOD_INFO(C, H, 2, Result, GetSigned32, (sf::Out<s32> out, sprofile::Identifier profile, sprofile::Identifier key), (out, profile, key)) \
AMS_SF_METHOD_INFO(C, H, 3, Result, GetUnsigned32, (sf::Out<u32> out, sprofile::Identifier profile, sprofile::Identifier key), (out, profile, key)) \ AMS_SF_METHOD_INFO(C, H, 3, Result, GetUnsigned32, (sf::Out<u32> out, sprofile::Identifier profile, sprofile::Identifier key), (out, profile, key)) \
AMS_SF_METHOD_INFO(C, H, 3, Result, GetByte, (sf::Out<u8> out, sprofile::Identifier profile, sprofile::Identifier key), (out, profile, key)) AMS_SF_METHOD_INFO(C, H, 4, Result, GetByte, (sf::Out<u8> out, sprofile::Identifier profile, sprofile::Identifier key), (out, profile, key))
AMS_SF_DEFINE_INTERFACE(ams::sprofile, IProfileReader, AMS_SPROFILE_I_PROFILE_READER_INTERFACE_INFO) AMS_SF_DEFINE_INTERFACE(ams::sprofile, IProfileReader, AMS_SPROFILE_I_PROFILE_READER_INTERFACE_INFO)

View File

@@ -18,9 +18,9 @@
#include "sprofile_srv_i_profile_importer.hpp" #include "sprofile_srv_i_profile_importer.hpp"
#define AMS_SPROFILE_I_SPROFILE_SERVICE_FOR_BG_AGENT_INTERFACE_INFO(C, H) \ #define AMS_SPROFILE_I_SPROFILE_SERVICE_FOR_BG_AGENT_INTERFACE_INFO(C, H) \
AMS_SF_METHOD_INFO(C, H, 100, Result, OpenProfileImporter, (sf::Out<sf::SharedPointer<::ams::sprofile::IProfileImporter>> out), (out)) \ AMS_SF_METHOD_INFO(C, H, 100, Result, OpenProfileImporter, (sf::Out<sf::SharedPointer<::ams::sprofile::IProfileImporter>> out), (out)) \
AMS_SF_METHOD_INFO(C, H, 200, Result, ReadMetadata, (sf::Out<u32> out_count, const sf::OutArray<sprofile::srv::ReadMetadataEntry> &out, const sprofile::srv::ReadMetadataArgument &arg), (out_count, out, arg)) \ AMS_SF_METHOD_INFO(C, H, 200, Result, GetImportableProfileUrls, (sf::Out<u32> out_count, const sf::OutArray<sprofile::srv::ProfileUrl> &out, const sprofile::srv::ProfileMetadataForImportMetadata &arg), (out_count, out, arg)) \
AMS_SF_METHOD_INFO(C, H, 201, Result, IsUpdateNeeded, (sf::Out<bool> out, sprofile::Identifier revision_key), (out, revision_key)) \ AMS_SF_METHOD_INFO(C, H, 201, Result, IsUpdateNeeded, (sf::Out<bool> out, sprofile::Identifier revision_key), (out, revision_key)) \
AMS_SF_METHOD_INFO(C, H, 2000, Result, Reset, (), ()) AMS_SF_METHOD_INFO(C, H, 2000, Result, Reset, (), ())
AMS_SF_DEFINE_INTERFACE(ams::sprofile, ISprofileServiceForBgAgent, AMS_SPROFILE_I_SPROFILE_SERVICE_FOR_BG_AGENT_INTERFACE_INFO) AMS_SF_DEFINE_INTERFACE(ams::sprofile, ISprofileServiceForBgAgent, AMS_SPROFILE_I_SPROFILE_SERVICE_FOR_BG_AGENT_INTERFACE_INFO)

View File

@@ -38,7 +38,7 @@ namespace ams::sprofile::srv {
bool HasProfile(Identifier id0, Identifier id1) { bool HasProfile(Identifier id0, Identifier id1) {
/* Require that we have metadata. */ /* Require that we have metadata. */
if (m_metadata.has_value()) { if (m_metadata.has_value()) {
for (auto i = 0u; i < m_metadata->num_entries; ++i) { for (auto i = 0u; i < std::min<size_t>(m_metadata->num_entries, util::size(m_metadata->entries)); ++i) {
const auto &entry = m_metadata->entries[i]; const auto &entry = m_metadata->entries[i];
if (entry.identifier_0 == id0 && entry.identifier_1 == id1) { if (entry.identifier_0 == id0 && entry.identifier_1 == id1) {
return true; return true;
@@ -63,7 +63,7 @@ namespace ams::sprofile::srv {
m_revision_key = meta.revision_key; m_revision_key = meta.revision_key;
/* Import all profiles. */ /* Import all profiles. */
for (auto i = 0u; i < meta.num_entries; ++i) { for (auto i = 0u; i < std::min<size_t>(meta.num_entries, util::size(meta.entries)); ++i) {
const auto &import_entry = meta.entries[i]; const auto &import_entry = meta.entries[i];
if (!this->HasProfile(import_entry.identifier_0, import_entry.identifier_1)) { if (!this->HasProfile(import_entry.identifier_0, import_entry.identifier_1)) {
m_importing_profiles[m_importing_count++] = import_entry.identifier_0; m_importing_profiles[m_importing_count++] = import_entry.identifier_0;

View File

@@ -19,16 +19,16 @@
namespace ams::sprofile::srv { namespace ams::sprofile::srv {
Result ProfileImporterImpl::ImportProfile(const sprofile::srv::ProfileDataForImportData &data) { Result ProfileImporterImpl::ImportProfile(const sprofile::srv::ProfileDataForImportData &import) {
return m_manager->ImportProfile(data); return m_manager->ImportProfile(import);
} }
Result ProfileImporterImpl::Commit() { Result ProfileImporterImpl::Commit() {
return m_manager->Commit(); return m_manager->Commit();
} }
Result ProfileImporterImpl::ImportMetadata(const sprofile::srv::ProfileMetadataForImportMetadata &data) { Result ProfileImporterImpl::ImportMetadata(const sprofile::srv::ProfileMetadataForImportMetadata &import) {
return m_manager->ImportMetadata(data); return m_manager->ImportMetadata(import);
} }
} }

View File

@@ -26,10 +26,14 @@ namespace ams::sprofile::srv {
ProfileManager *m_manager; ProfileManager *m_manager;
public: public:
ProfileImporterImpl(ProfileManager *manager) : m_manager(manager) { /* ... */ } ProfileImporterImpl(ProfileManager *manager) : m_manager(manager) { /* ... */ }
~ProfileImporterImpl() {
m_manager->CloseProfileImporter();
}
public: public:
Result ImportProfile(const sprofile::srv::ProfileDataForImportData &data); Result ImportProfile(const sprofile::srv::ProfileDataForImportData &import);
Result Commit(); Result Commit();
Result ImportMetadata(const sprofile::srv::ProfileMetadataForImportMetadata &data); Result ImportMetadata(const sprofile::srv::ProfileMetadataForImportMetadata &import);
}; };
static_assert(IsIProfileImporter<ProfileImporterImpl>); static_assert(IsIProfileImporter<ProfileImporterImpl>);

View File

@@ -151,7 +151,17 @@ namespace ams::sprofile::srv {
return ResultSuccess(); return ResultSuccess();
} }
Result ProfileManager::ImportProfile(const sprofile::srv::ProfileDataForImportData &data) { void ProfileManager::CloseProfileImporter() {
/* Acquire locks. */
std::scoped_lock lk1(m_profile_importer_mutex);
std::scoped_lock lk2(m_general_mutex);
std::scoped_lock lk3(m_fs_mutex);
/* Close our importer. */
m_profile_importer = util::nullopt;
}
Result ProfileManager::ImportProfile(const sprofile::srv::ProfileDataForImportData &import) {
/* Acquire locks. */ /* Acquire locks. */
std::scoped_lock lk1(m_profile_importer_mutex); std::scoped_lock lk1(m_profile_importer_mutex);
std::scoped_lock lk2(m_fs_mutex); std::scoped_lock lk2(m_fs_mutex);
@@ -159,25 +169,39 @@ namespace ams::sprofile::srv {
/* Check that we have an importer. */ /* Check that we have an importer. */
R_UNLESS(m_profile_importer.has_value(), sprofile::ResultInvalidState()); R_UNLESS(m_profile_importer.has_value(), sprofile::ResultInvalidState());
/* Check that the metadata we're importing is valid. */ /* Check that the metadata we're importing is a valid version. */
R_UNLESS(data.data.version == ProfileDataVersion, sprofile::ResultInvalidDataVersion()); R_UNLESS(IsValidProfileFormatVersion(import.header.version), sprofile::ResultInvalidDataVersion());
/* Check that the metadata we're importing has a valid hash. */
{
crypto::Md5Generator md5;
md5.Initialize();
md5.Update(std::addressof(import.header), sizeof(import.header));
md5.Update(std::addressof(import.data), sizeof(import.data) - sizeof(import.data.entries[0]) * (util::size(import.data.entries) - std::min<size_t>(import.data.num_entries, util::size(import.data.entries))));
u8 hash[crypto::Md5Generator::HashSize];
md5.GetHash(hash, sizeof(hash));
R_UNLESS(crypto::IsSameBytes(hash, import.hash, sizeof(hash)), sprofile::ResultInvalidDataHash());
}
/* Succeed if we already have the profile. */ /* Succeed if we already have the profile. */
R_SUCCEED_IF(m_profile_importer->HasProfile(data.identifier_0, data.identifier_1)); R_SUCCEED_IF(m_profile_importer->HasProfile(import.header.identifier_0, import.header.identifier_1));
/* Check that we're importing the profile. */ /* Check that we're importing the profile. */
R_UNLESS(m_profile_importer->CanImportProfile(data.identifier_0), sprofile::ResultInvalidState()); R_UNLESS(m_profile_importer->CanImportProfile(import.header.identifier_0), sprofile::ResultInvalidState());
/* Create temporary directories. */ /* Create temporary directories. */
R_TRY(this->EnsureTemporaryDirectories()); R_TRY(this->EnsureTemporaryDirectories());
/* Create profile. */ /* Create profile. */
char path[0x30]; char path[0x30];
CreateTemporaryProfilePath(path, sizeof(path), m_save_data_info.mount_name, data.identifier_0); CreateTemporaryProfilePath(path, sizeof(path), m_save_data_info.mount_name, import.header.identifier_0);
R_TRY(WriteFile(path, std::addressof(data.data), sizeof(data.data))); R_TRY(WriteFile(path, std::addressof(import.data), sizeof(import.data)));
/* Set profile imported. */ /* Set profile imported. */
m_profile_importer->OnImportProfile(data.identifier_0); m_profile_importer->OnImportProfile(import.header.identifier_0);
return ResultSuccess(); return ResultSuccess();
} }
@@ -231,7 +255,7 @@ namespace ams::sprofile::srv {
return ResultSuccess(); return ResultSuccess();
} }
Result ProfileManager::ImportMetadata(const sprofile::srv::ProfileMetadataForImportMetadata &data) { Result ProfileManager::ImportMetadata(const sprofile::srv::ProfileMetadataForImportMetadata &import) {
/* Acquire locks. */ /* Acquire locks. */
std::scoped_lock lk1(m_profile_importer_mutex); std::scoped_lock lk1(m_profile_importer_mutex);
std::scoped_lock lk2(m_fs_mutex); std::scoped_lock lk2(m_fs_mutex);
@@ -240,8 +264,23 @@ namespace ams::sprofile::srv {
R_UNLESS(m_profile_importer.has_value(), sprofile::ResultInvalidState()); R_UNLESS(m_profile_importer.has_value(), sprofile::ResultInvalidState());
R_UNLESS(m_profile_importer->CanImportMetadata(), sprofile::ResultInvalidState()); R_UNLESS(m_profile_importer->CanImportMetadata(), sprofile::ResultInvalidState());
/* Check that the metadata we're importing is valid. */ /* Check that the metadata we're importing is a valid version. */
R_UNLESS(data.metadata.version == ProfileMetadataVersion, sprofile::ResultInvalidMetadataVersion()); R_UNLESS(IsValidProfileFormatVersion(import.header.version), sprofile::ResultInvalidMetadataVersion());
/* Check that the metadata we're importing has a valid hash. */
{
crypto::Md5Generator md5;
md5.Initialize();
md5.Update(std::addressof(import.header), sizeof(import.header));
md5.Update(std::addressof(import.metadata), sizeof(import.metadata));
md5.Update(std::addressof(import.profile_urls), sizeof(import.profile_urls[0]) * std::min<size_t>(import.metadata.num_entries, util::size(import.metadata.entries)));
u8 hash[crypto::Md5Generator::HashSize];
md5.GetHash(hash, sizeof(hash));
R_UNLESS(crypto::IsSameBytes(hash, import.hash, sizeof(hash)), sprofile::ResultInvalidMetadataHash());
}
/* Create temporary directories. */ /* Create temporary directories. */
R_TRY(this->EnsureTemporaryDirectories()); R_TRY(this->EnsureTemporaryDirectories());
@@ -249,10 +288,10 @@ namespace ams::sprofile::srv {
/* Create metadata. */ /* Create metadata. */
char path[0x30]; char path[0x30];
CreateTemporaryMetadataPath(path, sizeof(path), m_save_data_info.mount_name); CreateTemporaryMetadataPath(path, sizeof(path), m_save_data_info.mount_name);
R_TRY(WriteFile(path, std::addressof(data.metadata), sizeof(data.metadata))); R_TRY(WriteFile(path, std::addressof(import.metadata), sizeof(import.metadata)));
/* Import the metadata. */ /* Import the metadata. */
m_profile_importer->ImportMetadata(data.metadata); m_profile_importer->ImportMetadata(import.metadata);
return ResultSuccess(); return ResultSuccess();
} }
@@ -309,13 +348,13 @@ namespace ams::sprofile::srv {
std::scoped_lock lk2(m_general_mutex); std::scoped_lock lk2(m_general_mutex);
/* Load the desired profile. */ /* Load the desired profile. */
R_TRY(this->LoadProfile(profile)); if (R_SUCCEEDED(this->LoadProfile(profile))) {
/* Find the specified key. */
/* Find the specified key. */ for (auto i = 0u; i < std::min<size_t>(m_service_profile->data.num_entries, util::size(m_service_profile->data.entries)); ++i) {
for (auto i = 0u; i < m_service_profile->data.num_entries; ++i) { if (m_service_profile->data.entries[i].key == key) {
if (m_service_profile->data.entries[i].key == key) { *out = m_service_profile->data.entries[i];
*out = m_service_profile->data.entries[i]; return ResultSuccess();
return ResultSuccess(); }
} }
} }
@@ -426,6 +465,8 @@ namespace ams::sprofile::srv {
} }
void ProfileManager::OnCommitted() { void ProfileManager::OnCommitted() {
/* TODO: Here, Nintendo sets the erpt ServiceProfileRevisionKey to the current revision key. */
/* If we need to, invalidate the loaded service profile. */ /* If we need to, invalidate the loaded service profile. */
if (m_service_profile.has_value()) { if (m_service_profile.has_value()) {
for (auto i = 0; i < m_profile_importer->GetImportingCount(); ++i) { for (auto i = 0; i < m_profile_importer->GetImportingCount(); ++i) {
@@ -436,8 +477,6 @@ namespace ams::sprofile::srv {
} }
} }
/* TODO: Here, Nintendo sets the erpt ServiceProfileRevisionKey to the current revision key. */
/* Reset profile metadata. */ /* Reset profile metadata. */
m_profile_metadata = util::nullopt; m_profile_metadata = util::nullopt;
@@ -445,6 +484,9 @@ namespace ams::sprofile::srv {
for (auto i = 0; i < m_profile_importer->GetImportingCount(); ++i) { for (auto i = 0; i < m_profile_importer->GetImportingCount(); ++i) {
m_update_observer_manager.OnUpdate(m_profile_importer->GetImportingProfile(i)); m_update_observer_manager.OnUpdate(m_profile_importer->GetImportingProfile(i));
} }
/* Reset profile importer. */
m_profile_importer = util::nullopt;
} }
Result ProfileManager::EnsurePrimaryDirectories() { Result ProfileManager::EnsurePrimaryDirectories() {

View File

@@ -50,6 +50,8 @@ namespace ams::sprofile::srv {
Result ResetSaveData(); Result ResetSaveData();
Result OpenProfileImporter(); Result OpenProfileImporter();
void CloseProfileImporter();
Result ImportProfile(const sprofile::srv::ProfileDataForImportData &data); Result ImportProfile(const sprofile::srv::ProfileDataForImportData &data);
Result Commit(); Result Commit();
Result ImportMetadata(const sprofile::srv::ProfileMetadataForImportMetadata &data); Result ImportMetadata(const sprofile::srv::ProfileMetadataForImportMetadata &data);

View File

@@ -34,7 +34,7 @@ namespace ams::sprofile::srv {
return ResultSuccess(); return ResultSuccess();
} }
Result ServiceForBgAgent::ReadMetadata(sf::Out<u32> out_count, const sf::OutArray<sprofile::srv::ReadMetadataEntry> &out, const sprofile::srv::ReadMetadataArgument &arg) { Result ServiceForBgAgent::GetImportableProfileUrls(sf::Out<u32> out_count, const sf::OutArray<sprofile::srv::ProfileUrl> &out, const sprofile::srv::ProfileMetadataForImportMetadata &arg) {
/* Check size. */ /* Check size. */
R_UNLESS(out.GetSize() >= arg.metadata.num_entries, sprofile::ResultInvalidArgument()); R_UNLESS(out.GetSize() >= arg.metadata.num_entries, sprofile::ResultInvalidArgument());
@@ -42,25 +42,31 @@ namespace ams::sprofile::srv {
sprofile::srv::ProfileMetadata primary_metadata; sprofile::srv::ProfileMetadata primary_metadata;
R_TRY_CATCH(m_profile_manager->LoadPrimaryMetadata(std::addressof(primary_metadata))) { R_TRY_CATCH(m_profile_manager->LoadPrimaryMetadata(std::addressof(primary_metadata))) {
R_CATCH(fs::ResultPathNotFound) { R_CATCH(fs::ResultPathNotFound) {
/* If we have no metadata, we can't get any entries. */ /* It's okay if we have no primary metadata -- this means that all profiles are importable. */
*out_count = 0; primary_metadata.num_entries = 0;
return ResultSuccess();
} }
} R_END_TRY_CATCH; } R_END_TRY_CATCH;
/* Copy matching entries. */ /* We want to return the set of profiles that can be imported, which is just the profiles we don't already have. */
u32 count = 0; u32 count = 0;
for (u32 i = 0; i < arg.metadata.num_entries; ++i) { for (u32 i = 0; i < arg.metadata.num_entries; ++i) {
const auto &arg_entry = arg.metadata.entries[i]; const auto &arg_entry = arg.metadata.entries[i];
/* Check if we have the entry. */
bool have_entry = false;
for (u32 j = 0; j < primary_metadata.num_entries; ++j) { for (u32 j = 0; j < primary_metadata.num_entries; ++j) {
const auto &pri_entry = primary_metadata.entries[j]; const auto &pri_entry = primary_metadata.entries[j];
if (pri_entry.identifier_0 == arg_entry.identifier_0 && pri_entry.identifier_1 == arg_entry.identifier_1) { if (pri_entry.identifier_0 == arg_entry.identifier_0 && pri_entry.identifier_1 == arg_entry.identifier_1) {
out[count++] = arg.entries[i]; have_entry = true;
break; break;
} }
} }
/* If we don't already have the entry, it's importable -- copy it out. */
if (!have_entry) {
out[count++] = arg.profile_urls[i];
}
} }
/* Set output count. */ /* Set output count. */
@@ -68,6 +74,7 @@ namespace ams::sprofile::srv {
return ResultSuccess(); return ResultSuccess();
} }
Result ServiceForBgAgent::IsUpdateNeeded(sf::Out<bool> out, Identifier revision_key) { Result ServiceForBgAgent::IsUpdateNeeded(sf::Out<bool> out, Identifier revision_key) {
/* Load primary metadata. */ /* Load primary metadata. */
bool loaded_metadata = true; bool loaded_metadata = true;

View File

@@ -29,7 +29,7 @@ namespace ams::sprofile::srv {
constexpr ServiceForBgAgent(MemoryResource *mr, ProfileManager *pm) : m_memory_resource(mr), m_profile_manager(pm) { /* ... */ } constexpr ServiceForBgAgent(MemoryResource *mr, ProfileManager *pm) : m_memory_resource(mr), m_profile_manager(pm) { /* ... */ }
public: public:
Result OpenProfileImporter(sf::Out<sf::SharedPointer<::ams::sprofile::IProfileImporter>> out); Result OpenProfileImporter(sf::Out<sf::SharedPointer<::ams::sprofile::IProfileImporter>> out);
Result ReadMetadata(sf::Out<u32> out_count, const sf::OutArray<sprofile::srv::ReadMetadataEntry> &out, const sprofile::srv::ReadMetadataArgument &arg); Result GetImportableProfileUrls(sf::Out<u32> out_count, const sf::OutArray<sprofile::srv::ProfileUrl> &out, const sprofile::srv::ProfileMetadataForImportMetadata &arg);
Result IsUpdateNeeded(sf::Out<bool> out, Identifier revision_key); Result IsUpdateNeeded(sf::Out<bool> out, Identifier revision_key);
Result Reset(); Result Reset();
}; };

View File

@@ -18,34 +18,11 @@
namespace ams::sprofile::srv { namespace ams::sprofile::srv {
struct ProfileMetadataEntry { constexpr inline const u32 ProfileFormatVersion = 1;
Identifier identifier_0;
Identifier identifier_1;
u8 unk_0E[0x32];
};
static_assert(util::is_pod<ProfileMetadataEntry>::value);
static_assert(sizeof(ProfileMetadataEntry) == 0x40);
constexpr inline const u32 ProfileMetadataVersion = 0; constexpr inline bool IsValidProfileFormatVersion(u32 version) {
return version == ProfileFormatVersion;
struct ProfileMetadata { }
u32 version;
u32 num_entries;
Identifier revision_key;
u8 unk_10[0x30];
ProfileMetadataEntry entries[50];
};
static_assert(util::is_pod<ProfileMetadata>::value);
static_assert(sizeof(ProfileMetadata) == 0xCC0);
struct ProfileMetadataForImportMetadata : public sf::LargeData, public sf::PrefersMapAliasTransferMode {
ProfileMetadata metadata;
u8 unk[0x8000 - sizeof(metadata)];
};
static_assert(util::is_pod<ProfileMetadataForImportMetadata>::value);
static_assert(sizeof(ProfileMetadataForImportMetadata) == 0x8000);
constexpr inline const u32 ProfileDataVersion = 0;
enum ValueType : u8 { enum ValueType : u8 {
ValueType_Byte = 0, ValueType_Byte = 0,
@@ -69,15 +46,24 @@ namespace ams::sprofile::srv {
static_assert(util::is_pod<ProfileDataEntry>::value); static_assert(util::is_pod<ProfileDataEntry>::value);
static_assert(sizeof(ProfileDataEntry) == 0x10); static_assert(sizeof(ProfileDataEntry) == 0x10);
static_assert(AMS_OFFSETOF(ProfileDataEntry, key) == 0x00);
static_assert(AMS_OFFSETOF(ProfileDataEntry, type) == 0x07);
static_assert(AMS_OFFSETOF(ProfileDataEntry, value_s64) == 0x08);
struct ProfileData { struct ProfileData {
u32 version;
u32 num_entries; u32 num_entries;
u8 unk_08[0x28]; u8 unk_04[0x0C];
u8 unk_10[0x20];
ProfileDataEntry entries[(0x4000 - 0x30) / sizeof(ProfileDataEntry)]; ProfileDataEntry entries[(0x4000 - 0x30) / sizeof(ProfileDataEntry)];
}; };
static_assert(util::is_pod<ProfileData>::value); static_assert(util::is_pod<ProfileData>::value);
static_assert(sizeof(ProfileData) == 0x4000); static_assert(sizeof(ProfileData) == 0x4000);
static_assert(AMS_OFFSETOF(ProfileData, num_entries) == 0x00);
static_assert(AMS_OFFSETOF(ProfileData, unk_04) == 0x04);
static_assert(AMS_OFFSETOF(ProfileData, unk_10) == 0x10);
static_assert(AMS_OFFSETOF(ProfileData, entries) == 0x30);
struct ServiceProfile { struct ServiceProfile {
Identifier name; Identifier name;
ProfileData data; ProfileData data;
@@ -85,29 +71,82 @@ namespace ams::sprofile::srv {
static_assert(util::is_pod<ServiceProfile>::value); static_assert(util::is_pod<ServiceProfile>::value);
static_assert(sizeof(ServiceProfile) == 0x4008); static_assert(sizeof(ServiceProfile) == 0x4008);
static_assert(AMS_OFFSETOF(ServiceProfile, name) == 0x00);
static_assert(AMS_OFFSETOF(ServiceProfile, data) == 0x08);
struct ProfileDataForImportData : public sf::LargeData, public sf::PrefersMapAliasTransferMode { struct ProfileDataForImportData : public sf::LargeData, public sf::PrefersMapAliasTransferMode {
Identifier identifier_0; struct {
Identifier identifier_1; Identifier identifier_0;
u8 unk_0E[2]; Identifier identifier_1;
u8 unk_0E[2];
u32 version;
u8 unk_14[0x1C];
} header;
u8 hash[crypto::Md5Generator::HashSize];
ProfileData data; ProfileData data;
u8 unk_4010[0x4400 - 0x4010]; u8 unk_4040[0x4400 - 0x4040];
}; };
static_assert(util::is_pod<ProfileDataForImportData>::value); static_assert(util::is_pod<ProfileDataForImportData>::value);
static_assert(sizeof(ProfileDataForImportData) == 0x4400); static_assert(sizeof(ProfileDataForImportData) == 0x4400);
struct ReadMetadataEntry { static_assert(AMS_OFFSETOF(ProfileDataForImportData, header) == 0x00);
u8 unk[0x100]; static_assert(AMS_OFFSETOF(ProfileDataForImportData, hash) == 0x30);
}; static_assert(AMS_OFFSETOF(ProfileDataForImportData, data) == 0x40);
static_assert(util::is_pod<ReadMetadataEntry>::value); static_assert(AMS_OFFSETOF(ProfileDataForImportData, unk_4040) == 0x4040);
static_assert(sizeof(ReadMetadataEntry) == 0x100);
struct ReadMetadataArgument : public sf::LargeData, public sf::PrefersMapAliasTransferMode { struct ProfileMetadataEntry {
Identifier identifier_0;
Identifier identifier_1;
u8 unk_0E[0x32];
};
static_assert(util::is_pod<ProfileMetadataEntry>::value);
static_assert(sizeof(ProfileMetadataEntry) == 0x40);
static_assert(AMS_OFFSETOF(ProfileMetadataEntry, identifier_0) == 0x00);
static_assert(AMS_OFFSETOF(ProfileMetadataEntry, identifier_1) == 0x07);
static_assert(AMS_OFFSETOF(ProfileMetadataEntry, unk_0E) == 0x0E);
struct ProfileUrl : public sf::PrefersMapAliasTransferMode {
char url[0x100];
};
static_assert(util::is_pod<ProfileUrl>::value);
static_assert(sizeof(ProfileUrl) == 0x100);
struct ProfileMetadata {
u32 num_entries;
u32 unk_04;
Identifier revision_key;
u8 unk_0F[0x1];
u8 unk_10[0x30];
ProfileMetadataEntry entries[50];
};
static_assert(util::is_pod<ProfileMetadata>::value);
static_assert(sizeof(ProfileMetadata) == 0xCC0);
static_assert(AMS_OFFSETOF(ProfileMetadata, num_entries) == 0x00);
static_assert(AMS_OFFSETOF(ProfileMetadata, unk_04) == 0x04);
static_assert(AMS_OFFSETOF(ProfileMetadata, revision_key) == 0x08);
static_assert(AMS_OFFSETOF(ProfileMetadata, unk_0F) == 0x0F);
static_assert(AMS_OFFSETOF(ProfileMetadata, unk_10) == 0x10);
static_assert(AMS_OFFSETOF(ProfileMetadata, entries) == 0x40);
struct ProfileMetadataForImportMetadata : public sf::LargeData, public sf::PrefersMapAliasTransferMode {
struct {
u32 version;
u8 unk_04[0x1C];
} header;
u8 hash[crypto::Md5Generator::HashSize];
ProfileMetadata metadata; ProfileMetadata metadata;
ReadMetadataEntry entries[(0x8000 - sizeof(metadata)) / sizeof(ReadMetadataEntry)]; ProfileUrl profile_urls[50];
u8 unk_7FC0[0x40]; u8 unk_3EF0[0x8000 - 0x3EF0];
}; };
static_assert(util::is_pod<ReadMetadataArgument>::value); static_assert(util::is_pod<ProfileMetadataForImportMetadata>::value);
static_assert(sizeof(ReadMetadataArgument) == 0x8000); static_assert(sizeof(ProfileMetadataForImportMetadata) == 0x8000);
static_assert(AMS_OFFSETOF(ProfileMetadataForImportMetadata, header) == 0x00);
static_assert(AMS_OFFSETOF(ProfileMetadataForImportMetadata, hash) == 0x20);
static_assert(AMS_OFFSETOF(ProfileMetadataForImportMetadata, metadata) == 0x30);
static_assert(AMS_OFFSETOF(ProfileMetadataForImportMetadata, profile_urls) == 0xCF0);
static_assert(AMS_OFFSETOF(ProfileMetadataForImportMetadata, unk_3EF0) == 0x3EF0);
} }

View File

@@ -17,10 +17,10 @@
#define ATMOSPHERE_RELEASE_VERSION_MAJOR 1 #define ATMOSPHERE_RELEASE_VERSION_MAJOR 1
#define ATMOSPHERE_RELEASE_VERSION_MINOR 2 #define ATMOSPHERE_RELEASE_VERSION_MINOR 2
#define ATMOSPHERE_RELEASE_VERSION_MICRO 0 #define ATMOSPHERE_RELEASE_VERSION_MICRO 5
#define ATMOSPHERE_RELEASE_VERSION ATMOSPHERE_RELEASE_VERSION_MAJOR, ATMOSPHERE_RELEASE_VERSION_MINOR, ATMOSPHERE_RELEASE_VERSION_MICRO #define ATMOSPHERE_RELEASE_VERSION ATMOSPHERE_RELEASE_VERSION_MAJOR, ATMOSPHERE_RELEASE_VERSION_MINOR, ATMOSPHERE_RELEASE_VERSION_MICRO
#define ATMOSPHERE_SUPPORTED_HOS_VERSION_MAJOR 13 #define ATMOSPHERE_SUPPORTED_HOS_VERSION_MAJOR 13
#define ATMOSPHERE_SUPPORTED_HOS_VERSION_MINOR 0 #define ATMOSPHERE_SUPPORTED_HOS_VERSION_MINOR 2
#define ATMOSPHERE_SUPPORTED_HOS_VERSION_MICRO 0 #define ATMOSPHERE_SUPPORTED_HOS_VERSION_MICRO 0

View File

@@ -64,8 +64,10 @@
#define ATMOSPHERE_TARGET_FIRMWARE_12_0_3 ATMOSPHERE_TARGET_FIRMWARE(12, 0, 3) #define ATMOSPHERE_TARGET_FIRMWARE_12_0_3 ATMOSPHERE_TARGET_FIRMWARE(12, 0, 3)
#define ATMOSPHERE_TARGET_FIRMWARE_12_1_0 ATMOSPHERE_TARGET_FIRMWARE(12, 1, 0) #define ATMOSPHERE_TARGET_FIRMWARE_12_1_0 ATMOSPHERE_TARGET_FIRMWARE(12, 1, 0)
#define ATMOSPHERE_TARGET_FIRMWARE_13_0_0 ATMOSPHERE_TARGET_FIRMWARE(13, 0, 0) #define ATMOSPHERE_TARGET_FIRMWARE_13_0_0 ATMOSPHERE_TARGET_FIRMWARE(13, 0, 0)
#define ATMOSPHERE_TARGET_FIRMWARE_13_1_0 ATMOSPHERE_TARGET_FIRMWARE(13, 1, 0)
#define ATMOSPHERE_TARGET_FIRMWARE_13_2_0 ATMOSPHERE_TARGET_FIRMWARE(13, 2, 0)
#define ATMOSPHERE_TARGET_FIRMWARE_CURRENT ATMOSPHERE_TARGET_FIRMWARE_13_0_0 #define ATMOSPHERE_TARGET_FIRMWARE_CURRENT ATMOSPHERE_TARGET_FIRMWARE_13_2_0
#define ATMOSPHERE_TARGET_FIRMWARE_MIN ATMOSPHERE_TARGET_FIRMWARE(0, 0, 0) #define ATMOSPHERE_TARGET_FIRMWARE_MIN ATMOSPHERE_TARGET_FIRMWARE(0, 0, 0)
#define ATMOSPHERE_TARGET_FIRMWARE_MAX ATMOSPHERE_TARGET_FIRMWARE_CURRENT #define ATMOSPHERE_TARGET_FIRMWARE_MAX ATMOSPHERE_TARGET_FIRMWARE_CURRENT
@@ -122,6 +124,8 @@ namespace ams {
TargetFirmware_12_0_3 = ATMOSPHERE_TARGET_FIRMWARE_12_0_3, TargetFirmware_12_0_3 = ATMOSPHERE_TARGET_FIRMWARE_12_0_3,
TargetFirmware_12_1_0 = ATMOSPHERE_TARGET_FIRMWARE_12_1_0, TargetFirmware_12_1_0 = ATMOSPHERE_TARGET_FIRMWARE_12_1_0,
TargetFirmware_13_0_0 = ATMOSPHERE_TARGET_FIRMWARE_13_0_0, TargetFirmware_13_0_0 = ATMOSPHERE_TARGET_FIRMWARE_13_0_0,
TargetFirmware_13_1_0 = ATMOSPHERE_TARGET_FIRMWARE_13_1_0,
TargetFirmware_13_2_0 = ATMOSPHERE_TARGET_FIRMWARE_13_2_0,
TargetFirmware_Current = ATMOSPHERE_TARGET_FIRMWARE_CURRENT, TargetFirmware_Current = ATMOSPHERE_TARGET_FIRMWARE_CURRENT,

View File

@@ -19,6 +19,7 @@
#include <vapours/crypto/crypto_memory_compare.hpp> #include <vapours/crypto/crypto_memory_compare.hpp>
#include <vapours/crypto/crypto_memory_clear.hpp> #include <vapours/crypto/crypto_memory_clear.hpp>
#include <vapours/crypto/crypto_md5_generator.hpp>
#include <vapours/crypto/crypto_sha1_generator.hpp> #include <vapours/crypto/crypto_sha1_generator.hpp>
#include <vapours/crypto/crypto_sha256_generator.hpp> #include <vapours/crypto/crypto_sha256_generator.hpp>
#include <vapours/crypto/crypto_aes_encryptor.hpp> #include <vapours/crypto/crypto_aes_encryptor.hpp>

View File

@@ -0,0 +1,63 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <vapours/common.hpp>
#include <vapours/assert.hpp>
#include <vapours/util.hpp>
#include <vapours/crypto/impl/crypto_md5_impl.hpp>
namespace ams::crypto {
class Md5Generator {
NON_COPYABLE(Md5Generator);
NON_MOVEABLE(Md5Generator);
private:
using Impl = impl::Md5Impl;
public:
static constexpr size_t HashSize = Impl::HashSize;
static constexpr size_t BlockSize = Impl::BlockSize;
static constexpr inline const u8 Asn1Identifier[] = {
0x30, 0x20, /* Sequence, size 0x20 */
0x30, 0x0C, /* Sequence, size 0x0C */
0x06, 0x08, /* Object Identifier */
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05, /* MD5 */
0x05, 0x00, /* Null */
0x04, 0x10, /* Octet string, size 0x10 */
};
static constexpr size_t Asn1IdentifierSize = util::size(Asn1Identifier);
private:
Impl m_impl;
public:
Md5Generator() { /* ... */ }
void Initialize() {
m_impl.Initialize();
}
void Update(const void *data, size_t size) {
m_impl.Update(data, size);
}
void GetHash(void *dst, size_t size) {
m_impl.GetHash(dst, size);
}
};
void GenerateMd5Hash(void *dst, size_t dst_size, const void *src, size_t src_size);
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) Atmosphère-NX
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <vapours/common.hpp>
#include <vapours/assert.hpp>
#include <vapours/util.hpp>
#include <vapours/crypto/impl/crypto_hash_function.hpp>
#include <vapours/crypto/crypto_memory_clear.hpp>
namespace ams::crypto::impl {
class Md5Impl {
public:
static constexpr size_t HashSize = 0x10;
static constexpr size_t BlockSize = 0x40;
private:
enum State {
State_None = 0,
State_Initialized = 1,
State_Done = 2,
};
private:
union {
struct {
u32 a, b, c, d;
} p;
u32 state[4];
} m_x;
alignas(8) u8 m_y[BlockSize];
size_t m_size;
State m_state;
public:
Md5Impl() : m_state(State_None) { /* ... */ }
~Md5Impl() { ClearMemory(this, sizeof(*this)); }
void Initialize();
void Update(const void *data, size_t size);
void GetHash(void *dst, size_t size);
private:
void ProcessBlock();
void ProcessLastBlock();
};
/* static_assert(HashFunction<Md5Impl>); */
}

View File

@@ -177,7 +177,11 @@ namespace ams {
static_assert(Value != Base::SuccessValue, "Value != Base::SuccessValue"); static_assert(Value != Base::SuccessValue, "Value != Base::SuccessValue");
public: public:
constexpr ALWAYS_INLINE operator Result() const { return MakeResult(Value); } constexpr ALWAYS_INLINE operator Result() const { return MakeResult(Value); }
constexpr ALWAYS_INLINE operator ResultSuccess() const { OnResultAbort(Value); } constexpr ALWAYS_INLINE operator ResultSuccess() const {
OnResultAbort(Value);
__builtin_unreachable();
return ResultSuccess();
}
constexpr ALWAYS_INLINE bool IsSuccess() const { return false; } constexpr ALWAYS_INLINE bool IsSuccess() const { return false; }
constexpr ALWAYS_INLINE bool IsFailure() const { return !this->IsSuccess(); } constexpr ALWAYS_INLINE bool IsFailure() const { return !this->IsSuccess(); }

View File

@@ -37,6 +37,8 @@ namespace ams::sprofile {
R_DEFINE_ERROR_RESULT(MaxObservers, 623); R_DEFINE_ERROR_RESULT(MaxObservers, 623);
R_DEFINE_ERROR_RESULT(InvalidMetadataVersion, 3210); R_DEFINE_ERROR_RESULT(InvalidMetadataVersion, 3210);
R_DEFINE_ERROR_RESULT(InvalidMetadataHash, 3211);
R_DEFINE_ERROR_RESULT(InvalidDataVersion, 3230); R_DEFINE_ERROR_RESULT(InvalidDataVersion, 3230);
R_DEFINE_ERROR_RESULT(InvalidDataHash, 3231);
} }

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