32 Commits
Author SHA1 Message Date
Yaya48andClaude Opus 5.5 9ad22f00bd StarletBootstrapProbe: --broadway-h1a's report and budget, from the final review
Two findings of the review of 2df9dfc909 (StarOS H-1A, D2):
- The report reads the bench window too (hw0c_report(): HW-M4-0D's
  area, and H-1A's record if it was never read), but a refused access
  there did not fail the run, as one during the run does. It does now:
  the failure on stderr, and the run fails.
- --cycles' bound of 2^34 was raised whenever "--broadway-h1a" appeared
  among the arguments, even as the value of --ipc-script or --stage-spk
  (a file of that name), the run then not in the client's mode.
  ClientRequested reads the options with their grammar: the word after
  --ipc-script, --stage-spk or --cycles is a value, never an option.

StarletProbeBroadwayTest: ClientRequested.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 21:59:34 +01:00
Yaya48andClaude Opus 5.5 2df9dfc909 StarletBootstrapProbe: read --cycles where it stands, as before
--broadway-h1a had moved --cycles' reading after the options, which
changed the usage errors' text for a missing value or a second --cycles.
The bound is now known before the options are read (whether
--broadway-h1a is among them), and --cycles is read in place, with
master's messages: without --broadway-h1a, every run and every refusal
is master's, byte for byte.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 21:03:10 +01:00
Yaya48andClaude Opus 5.5 9cce9b35ef StarletBootstrapProbe: --broadway-h1a ends as the loader's monitor does
The first whole run of StarOS's H-1A image (interpreter, 2^34 cycles)
ran every round: Broadway posted 3000, the Starlet answered 3000, its
record COHERENT, END NONE, S0 PASS. But the probe never ended it: the
image's trace, 1 KiB, is full before its REV:BOOT:IDLE line, and the
probe looked for that line only. StarOS's main.c does not: its monitor
takes the Starlet for done once the SBR1 record's state is IDLE or after,
with EXI given back to Broadway (StarletDone), and its bench ended.

In this mode the probe now does the same: it reads the record, which
--broadway-h1a therefore requires (--sbr1-record), prints the trace as it
stands (and says on stderr when it is full: its last lines are in the
SBR1 ring the probe prints), then the client's report under SBL:STARLET
DONE. The run passes when the trace shows the boot's start, no panic or
fatal line, and the record's state is IDLE (or the trace's IDLE line).
Without --broadway-h1a nothing changes.

StarletProbeBroadwayTest: StarletDone against StarOS's states.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 18:18:05 +01:00
Yaya48andClaude Opus 5.5 f391ae6c85 StarletBootstrapProbe: --broadway-h1a
The probe stands in for Broadway with StarOS's own bench loader code, so
that StarOS's H-1A bench (docs/architecture/h-1a.md, D-H1A-7) runs whole:
its Starlet image on the ARM core, its Broadway side from StarOS's
boot/wii/loader hw0c.c, hw0d.c and h1a.c, vendored unchanged in
Tools/StarletBootstrapProbe/StarOSLoader (StarOS 480119d, stored -text so
their bytes stay StarOS's) with their contract headers, and built over a
host HAL in BroadwayHAL/. CMake computes the nine files' SHA-256s at
configure; the probe prints them when the mode starts.

As StarOS's loader around the jump: hw0c_setup() before the Starlet's
first instruction, one hw0c_step() between each two slices, the timebase
243 MHz / 4 from the Starlet's cycles, until it says 1; once the image's
trace is terminal and the bench is done, the trace, then the report
between main.c's status and END lines on stdout. If the budget runs out,
the report under SBL:TIMEOUT, and the run fails. The client reaches PPC
memory only in the bench window 0x13500000..0x13510000, by whole words:
the first access outside fails the run, and is not made. Dolphin's memory
is coherent: the run rehearses the protocol, the capture and the judge,
not the console's caches.

--cycles may reach 2^34 in this mode only (MAX_CLIENT_CYCLES), 2^30 as
before otherwise. --broadway-h1a takes neither --ipc-script nor
--stage-spk, whose behaviour is unchanged.

StarletProbeBroadwayTest: the window's bounds, the clock, Gecko's number
formats, the budgets, the built-in sources; and, each in a death test's
own process (the loader's state is global), the real loader code against
a scripted Starlet: 3000 rounds and a COHERENT record, no READY, no
Starlet END, a budget too short; a second client refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 18:00:12 +01:00
Yaya48andClaude Opus 5.5 a709fddfa8 StarletBootstrapProbe: --ipc-script
The probe stands in for Broadway, so that a real request can enter StarOS's
image through the Hollywood IPC registers and its reply be read back (StarOS
docs/contracts/hollywood-ipc-injection.md, approved for development). A
script is data: whole words stored in one range of PPC memory,
0x135E0000..0x13600000, PPCMSG and PPCCTRL written, PPCCTRL and ARMMSG read,
every wait bounded in ARM cycles. Steps run between the probe's slices. The
probe knows nothing of the code under test and answers nothing for it.

A script refused when read ends the run with exit status 5, before StarOS
starts. A step that fails, or a terminal trace line with steps left, fails
the run with its line on stderr. The option given twice, or without its
file, is a usage error.

The one change in Source/Core: WiiIPC::SetStarletAttached, an opt-in flag
UpdateInterrupts reads beside GetStarlet(), because the probe runs an
ARMCore with no Starlet object in the System. The IPC cause is then raised
by the model's own line, X1 and IX1 included, with no second model of it.
Reset clears the flag, and nothing sets it without --ipc-script.

ProbeScript.h holds the parser and the runner, tested by
StarletProbeScriptTest over a fake bus; StarletProbeInterruptTest holds the
flag's behaviour with and without it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 00:55:58 +01:00
Yaya48andClaude Opus 5.5 9d66381b3d StarletBootstrapProbe: --stage-spk
StarOS's I2-C image admits its User services from an SPK1 package that
the loader stages in MEM2 before the Starlet's first instruction (StarOS
docs/contracts/spk-staging.md). --stage-spk <file> places the file at
the package window's base, 0x13720000, once the image is loaded: the
address is the contract's, never an argument. The bytes are copied as
the file holds them (big-endian words) and read back before the first
instruction; a window that does not read back fails the run.

The file is read and checked before anything is set up. A missing or
unreadable file, an empty one, one whose length is not whole 32-bit
words or that exceeds the 128 KiB window ends the run with its reason on
stderr and exit status 4, before StarOS starts. The option given twice
or without its file is a usage error (exit 2). The probe checks none of
SPK1's fields or digests: that is StarOS's job.

The size rule and the window are in ProbeStaging.h, tested by
StarletProbeStagingTest. Without the option the probe runs as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 18:36:14 +01:00
Yaya48andClaude Opus 5.5 dd2336f278 Starlet: keep a matched alarm's timer cause until HW_ALARM is rewritten
A console run (StarOS M3C gate H1, 2026-10-16) acknowledged the timer
through HW_ARMIRQFLAG before rewriting HW_ALARM, tens of microseconds after
the match, and read the cause still set. MINI's IRQ handler rewrites
HW_ALARM first, then acknowledges. The model fired the cause once on the
crossing, and a write-one-to-clear ended it for good, so the probe hid the
difference.

Once the counter reaches HW_ALARM, the timer's cause now stays asserted:
an acknowledgement sets it again until HW_ALARM is written. Writing the
comparator re-arms it (an immediate match when equal to the counter, as
before); a counter write does not end the match. One run does not tell a
latch from a "counter >= alarm" comparison: the latch is the smaller model
that explains it. The state is saved (STATE_VERSION 197).

Tests: StarletTimer.MatchedAlarmStaysAssertedUntilRewritten (both write
paths, a counter write, MINI's order, the next match) and
MatchedAlarmSurvivesStateRoundTrip.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 12:51:16 +02:00
Yaya48andClaude Opus 5.5 6c44367b5c Starlet: re-sample the interrupt lines on HW_ARMFIQMASK writes too
Review of d486779f50 (StarOS decision 44):
- A write to HW_ARMFIQMASK re-samples the attached core's IRQ and FIQ lines,
  as writes to HW_ARMIRQFLAG and HW_ARMIRQMASK do.
- Tests: FIQ masking and unmasking of a latched cause (wide and
  byte-assembled writes, then an acknowledgement); two pending IRQ sources,
  where acknowledging one keeps the line asserted and acknowledging the
  last lowers it.

The attached core cannot be used after it is destroyed: Starlet::Shutdown
resets m_core then m_memory with nothing in between, ~Starlet destroys
m_core (declared after m_memory) first, Init attaches only after the last
path that can fail, StarletMemory::Reset keeps the core, which is still
alive, and the probe's core is a local declared after its memory.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 02:49:39 +02:00
Yaya48andClaude Opus 5.5 d486779f50 Starlet: re-sample the ARM IRQ and FIQ lines on interrupt register writes
The core's IRQ and FIQ lines were set from WiiIPC's flags and masks only at
the start of each scheduler slice (Starlet::RunSlice, StarletBootstrapProbe).
Acknowledging an interrupt (HW_ARMIRQFLAG, write one to clear) or masking it
(HW_ARMIRQMASK) left the line asserted until the next slice, so code that
acknowledged an interrupt and unmasked IRQ within the same slice took it
again with no cause pending. Hollywood's interrupt output is level-sensitive.

StarletMemory now re-samples the lines of the core attached with
AttachInterruptLines on every write to those two registers, on both its
wide and byte-assembled write paths; Starlet and StarletBootstrapProbe
attach theirs. Raising a cause still reaches the core at the next slice, as
before. ARMCore exposes IsIRQLineAsserted and IsFIQLineAsserted for the
unit test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 02:19:55 +02:00
Yaya48andClaude Opus 5.5 bef2c8cf02 StarletBootstrapProbe: print the SBR1 ring with --sbr1-record
The probe printed the ring's length only. StarOS's EXP-003 images put
lines in the ring that REV_TRACE has no room for (the MEM2 monitor, the
measurements), so under Dolphin nothing showed them. After the record's
summary, --sbr1-record now prints the ring's text between "SBR1 RING
BEGIN" and "SBR1 RING END" on stderr, as StarOS's Broadway loader prints
it over the Gecko on the console: at most the ring's 4032 bytes, a byte
outside printable ASCII and newline, and the backslash, written \xHH.

The formatting is in ProbeRing.h, tested by StarletProbeRingTest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 17:50:01 +02:00
Yaya48andClaude Opus 5.5 b457eb18c3 StarletBootstrapProbe: --cycles
The probe ran every image for a fixed 512 slices of 4096 ARM cycles
(2097152). StarOS's EXP-003 images hash MEM2 and time series of
operations, which need more (StarOS experiments/proposals/mmu-console.md,
P-7 and P-8). --cycles <n> sets the budget: a decimal number of cycles,
a whole number of slices, from one slice to 2^30, given once; anything
else is a usage error (exit 2), never rounded. Without it the probe runs
2097152 cycles, as before, and the timeout messages name the budget.

The parser is in ProbeBudget.h, tested by StarletProbeBudgetTest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 17:34:06 +02:00
Yaya48andClaude Opus 5.5 6ede30f99e StarletBootstrapProbe: wait for StarOS's whole panic path
--expect-panic passed as soon as __panic_state was nonzero at the end of
a 4096-cycle slice. StarOS's handler stores the guard first, then the
code, then publishes the SBR1 record, so the run could stop with the path
half done. The probe now keeps running until the path is finished and
still is two slices later, and fails if the run budget ends first:
- __panic_state 1 and __panic_code 1;
- with --sbr1-record: STARLET_STATE 5 (Panic), FATAL_REASON 0 and
  EXI_OWNER 1 (handed back to the PPC);
- with --sbr1-absent: every word of the record area still zero.
The failure names the first unmet condition. The check is
StarOSPanicCheck.h, pure, with the SBR1 constants moved there, and
StarletProbePanicCheckTest covers each condition; each of 7 mutants of
the check fails a test. Runs that do not expect a panic are unchanged.

With StarOS's panic test image (eb930ee), interpreter and JIT: the
scenarios pass, two slices later than before. Three images derived from
it pass the previous probe and now fail: EXI kept by the Starlet
(--sbr1-record), __panic_code never stored, the record written although
absent (--sbr1-absent). (StarOS MMU-001 review of F1.)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 00:20:23 +02:00
Yaya48andClaude Opus 5.5 a62c65615a IOS LLE: StarOS's panic words must not alias
LoadBootstrapELF accepted __panic_state and __panic_code at the same
address, or as two words sharing bytes: the code's store would then also
set the guard, and nothing could tell the two apart. They must now be two
non-overlapping words of the data segment, like the other checks, before
any byte is written. BootstrapELFTest.PanicWordsMustNotAlias: the same
word and three partial overlaps, all inside the data segment, are
rejected; adjacent words are accepted. With the rule disabled, the test
fails. (StarOS MMU-001 review of F1.)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 00:20:22 +02:00
Yaya48andClaude Opus 5.5 15da28ad7b StarletBootstrapProbe: --sbr1-record and --sbr1-absent
StarOS's SBR1 boot record (MEM1 0x00200000) is created by its Broadway
loader before the image runs; the probe never had one, so the paths
that publish into it ran only on the console. --sbr1-record writes the
record as the loader and the ARM relay leave it (header, relay at its
last step, EXI channel 1 given to the Starlet, magic last); after the run
both options print the record's magic, state, reason, EXI owner, fault
code, ring length and dropped count, and how many of its 1024 words are
nonzero (0 is expected with --sbr1-absent). Without either option the
probe behaves as before.

With the StarOS M1 images (interpreter and JIT): idle publishes state 3
and hands EXI back (owner 1, ring 258 bytes, no Gecko emulated);
fatal-data state 4 reason 3; undefined-entry state 6, fault 1, ring
empty, as on the console (gates HW2-HW4).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 22:40:28 +02:00
Yaya48andClaude Opus 5.5 2bae49bdad IOS LLE: the ARM926 TLB is unified (StarOS MMU-001 F1 review)
The ARM926EJ-S has one TLB for instructions and data, with lockdown
entries that whole-TLB invalidation preserves. Two comments said the
I and D TLBs were separate; they now say what the software TLB really
differs in: capacity and replacement (a direct-mapped cache of 4096
1 KiB granules), and lockdown, which is not modelled (c10 writes are
ignored). No code change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 22:03:22 +02:00
Yaya48andClaude Opus 5.5 612cab7b30 StarletBootstrapProbe: report StarOS's panic words
StarOS's panic path (ADR-0014 R6) writes no trace line: it sets the guard
word __panic_state, stores __panic_code and halts. LoadBootstrapELF now
returns both symbols when an image has them (optional, but both or
neither, as words of the data segment), and the probe stops a run whose
guard is set: it prints the trace published so far and
"Starlet panic state <n> code <n>", and passes --expect-panic when the
state is 1. Images without these symbols (StarletOS) load and run as
before; a REV:PANIC trace line still satisfies --expect-panic.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 21:21:58 +02:00
Yaya48andClaude Opus 5.5 cdec826bb8 StarletBootstrapProbe: --mmu-faults
Enables the ARM926 MMU aborts of ARMCore (SetMMUFaultsEnabled) for the
run. Without the option the probe behaves as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 21:09:18 +02:00
Yaya48andClaude Opus 5.5 9b493a1e16 IOS LLE: optional ARM926 MMU aborts and CP15 privilege (StarOS MMU-001 F1)
ARMCore::SetMMUFaultsEnabled(true) makes the Starlet core deliver the
faults of the ARM926EJ-S MMU instead of the identity fallback:
- translation (section 0x5, page 0x7), domain (0x9, 0xb) and permission
  (0xd, 0xf) faults from the descriptors, the DACR (no access and the
  reserved value fault; manager skips AP) and AP with the S and R bits;
  ARMv5 has no execute permission, so a fetch needs read permission;
- data aborts (vector 0x10, LR = instruction + 8 in both states) set the
  FSR and the FAR (the MVA); prefetch aborts (vector 0x0c, LR + 4) set the
  IFSR (c5 opcode2 1) and leave the FAR unchanged;
- alignment faults (0x1) when control bit A is set;
- base-restored data aborts: the first faulting access ends the
  instruction's bus traffic and its register results are undone; words
  stored before the fault stay written;
- LDRT/STRT/LDRBT/STRBT check User permissions in any mode;
- the TLB keeps each granule's domain and AP, never caches a faulting
  walk, and c8 single-entry operations drop only the page that maps the
  MVA, so an entry stays stale until the guest invalidates it;
- MRC/MCR to CP15 from User mode is an undefined instruction.

The JIT stays usable: with the option on, every block entry goes through
C++, which checks the fetch under the current mode and DACR, and only
instructions that touch neither memory, CP15, the PSRs nor the exception
model run natively; the rest use the interpreter.

Off by default. The IOS LLE path keeps its identity fallback, its
savestate format (the option and the IFSR are not serialized) and its
idle-loop fast-forwarding; the only change there is that the data
accessors read one abort flag that stays clear.

20 StarletARMCoreMMUFaults tests, each run in the interpreter and the
JIT; the existing Starlet tests pass unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 21:09:18 +02:00
Yaya48andClaude Opus 5.5 f9193539fb StarletBootstrapProbe: back MEM1 and MEM2 as on a retail Wii
The probe never initialised Dolphin's MEM1 and MEM2, so any Starlet
access there was an access to unmapped memory: StarOS reads its SBR1
record header at 0x00200000 on every boot, which raised two alerts
(Unknown Pointer, then Invalid range in CopyFromEmu) and read 0. The
probe now initialises both, zeroed, at their retail sizes (24 and
64 MiB), and shuts them down after the run. The read still returns 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 17:49:56 +02:00
Yaya48andClaude Opus 5.5 61ebfffa97 StarletBootstrapProbe: fail on a Dolphin alert instead of opening a dialog
With no handler registered, Dolphin shows an alert in a modal MessageBox
on Windows, and the probe waits until someone closes it. A run that hits
an alert then looks like a hang (StarOS EXP-001). The probe now writes the
alert to stderr and exits at once with status 3.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 17:35:58 +02:00
Yaya48andClaude Opus 5.5 ba86a7486c IOS LLE: optional Broadway hardware window after a WiiConnect24 shutdown reply (StarletOS phase 11 J1)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-06 22:36:20 +02:00
Yaya48andClaude Opus 5.5 3d12571127 IOS LLE: execute ARMv5TE enhanced DSP instructions (StarletOS phase 11 I1)
SMLAxy, SMLAWy, SMULWy, SMLALxy, SMULxy, QADD, QSUB, QDADD and QDSUB were
decoded as compare data processing that writes no register; the ARM926EJ-S
implements them. The interpreter now executes them with the Q flag and the
JIT leaves them to it. Adds ARMv5TEEnhancedDSPInstructions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-06 22:16:53 +02:00
Yaya48andClaude Opus 5.5 ba5b6de0d0 IOS LLE: shadow comparison for REV_WATCH (StarletOS phase 11 H1)
Reads and IPC-reply audits compare each watched range with what the
Starlet and the devices wrote, revealing other writers; register-list
transfers in a watched virtual range log their translation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-06 22:08:04 +02:00
Yaya48andClaude Opus 5.5 76a133f3a4 IOS LLE: optional Starlet write watch REV_WATCH (StarletOS phase 11 F1)
Logs Starlet CPU stores (instruction address, LR) and device DMA writes
in the given physical ranges. The ARM JIT keeps fastmem but sends accesses
overlapping a watched range to its bus slow path, recording the
instruction address there. Nothing changes without the variable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-06 20:21:09 +02:00
Yaya48andClaude Opus 5.5 81ebec368b IOS LLE: IPC trace prints filesystem IOCTL paths (StarletOS phase 11 M1e)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-06 19:44:05 +02:00
Yaya48andClaude Opus 5.5 3ce435786c IOS LLE: optional emulated Wii Remotes in bootstrap mode (StarletOS phase 11 M1)
With REV_BOOTSTRAP_WIIMOTE=1 a bootstrap-ELF session gets the emulated Wii
Remotes of the original-IOS mode, using the identities paired in the
attached NAND's SYSCONF. The NAND is never rewritten for it; without the
variable nothing changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-06 19:25:04 +02:00
Yaya48andClaude Opus 5.5 09fba9bbb5 docs: StarletOS X11 window build and the phase 11 reference launch
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-06 19:10:35 +02:00
Yaya48andClaude Opus 5.5 cd8c8cedca IOS LLE: optional IPC request/reply metadata trace (StarletOS phase 11 L2)
With DOLPHIN_IPC_TRACE=1 and the original IOS on the emulated Starlet, log
each request Broadway posts (X1: command, descriptor, argument words, an
OPEN's path) and each reply Starlet posts (Y1: original command, result).
Buffer contents are never read; nothing changes without the variable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-06 18:40:56 +02:00
Yaya48 78738093ec docs: record Linux Starlet bootstrap qualification 2026-10-03 23:38:28 +02:00
Yaya48 54f5a74bbf Track exact StarletOS bootstrap integration and checkpoint provenance
Recover 16 modified and 6 previously untracked integration files. All 22 source SHA-256s match the pre-publication StarletOS snapshot. Add handoff instructions, byte-preserving attributes and private backup exclusion. This commit publishes existing behavior; it does not claim a new full build or hardware qualification. The two preceding local commits and staged files were screened before publication.
2026-10-03 16:27:07 +02:00
Yaya48 a8dbbab62d IOS LLE: emulate SD CMD6 and document Wii conformance run 2026-09-23 14:31:21 +02:00
Yaya48 c230971f07 IOS LLE: checkpoint NAND conformance and diagnostic tooling
Preserve formatted NAND boot and Wii Remote pairing, add DMA/SRAM conformance tests and a Wii comparison probe. Keep P1 profiling tools and native update A/B evidence; reject the unhelpful targeted SRAM shortcut.
2026-09-23 13:30:17 +02:00
112 changed files with 21672 additions and 7648 deletions

No files matched your search

+31
View File
@@ -1 +1,32 @@
*.sln text eol=crlf
# Preserve the qualified StarletOS integration bytes across operating systems.
CMakeLists.txt -text
Run-Wii-Starlet-Bootstrap.ps1 -text
Source/Core/Core/Boot/Boot.cpp -text
Source/Core/Core/CMakeLists.txt -text
Source/Core/Core/Config/MainSettings.cpp -text
Source/Core/Core/Config/MainSettings.h -text
Source/Core/Core/ConfigManager.cpp -text
Source/Core/Core/HW/HW.cpp -text
Source/Core/Core/HW/WII_IPC.cpp -text
Source/Core/Core/HW/WII_IPC.h -text
Source/Core/Core/PowerPC/MMU.cpp -text
Source/Core/Core/IOS/Starlet/ARMCore.cpp -text
Source/Core/Core/IOS/Starlet/ARMCore.h -text
Source/Core/Core/IOS/Starlet/ARMJitX64.cpp -text
Source/Core/Core/IOS/Starlet/ARMJitX64.h -text
Source/Core/Core/IOS/Starlet/BootstrapELF.cpp -text
Source/Core/Core/IOS/Starlet/BootstrapELF.h -text
Source/Core/Core/IOS/Starlet/Starlet.cpp -text
Source/Core/Core/IOS/Starlet/Starlet.h -text
Source/Core/Core/IOS/Starlet/StarletMemory.cpp -text
Source/Core/Core/IOS/Starlet/StarletMemory.h -text
Source/Core/DolphinNoGUI/PlatformHeadless.cpp -text
Source/UnitTests/CMakeLists.txt -text
Source/UnitTests/Core/CMakeLists.txt -text
Source/UnitTests/Core/IOS/Starlet/BootstrapELFTest.cpp -text
Source/UnitTests/Core/IOS/Starlet/DMATest.cpp -text
Tools/StarletBootstrapProbe/StarletBootstrapProbe.cpp -text
docs/Wii_Starlet_Bootstrap.md -text
docs/StarletOS_Checkpoint.json -text
+7
View File
@@ -71,3 +71,10 @@ CMakeUserPresets.json
/.codex-tools/
/.starlet-profile/
/yaya48-starlet-log.txt
/Run-Wii-Formatter-Test.ps1
# Generated bytecode from the performance analysis helpers
/Tools/PerformanceTrace/__pycache__/
# Historical local script backup; active script is tracked.
/Run-Wii-Starlet-Bootstrap.ps1.before-*
+30
View File
@@ -0,0 +1,30 @@
# Instructions for the StarletOS Dolphin fork
Read `docs/StarletOS_Handoff.md`, `docs/StarletOS_Checkpoint.json` and
`docs/Wii_Starlet_Bootstrap.md` before working on the Starlet integration.
Also read the companion StarletOS HANDOFF and current phase SPEC/STATUS when
changing support for its tests. Current user instructions take precedence.
- One writer per checkout. Inspect Git status and the latest handoff before
editing; preserve unrelated changes and never overwrite another agent's work.
- Fetch the user's fork before work and inspect divergence. Use fast-forward
pulls only on a clean branch; never reset or force-push to hide divergence.
- The publication destination is `https://git.yaya48.xyz/Yaya48/dolphin`.
On the original checkout it is named `yaya`; on a fresh clone it is normally
`origin`. The github.com/dolphin-emu upstream is NOT the publication target.
- Preserve qualified source bytes/line endings. Do not broadly normalize the
repository. Exact integration files are protected by `.gitattributes`.
- Do not commit dumps, console keys/OTP/SEEPROM, Nintendo binaries, real device
identifiers, credentials, private emulator profiles or diagnostic captures.
Stage explicit paths and inspect staged contents AND pending commits before
publishing. Never use force-add to bypass these exclusions.
- Respect companion phase boundaries and public-source/clean-room rules. A
fake emulated device is supporting test evidence, not the physical contract.
- Update the handoff with changes, reasons, commands/results, limitations and
the next exact action at every stop. Preserve old evidence and distinguish
source inspection, build results, emulation and physical observations.
- Commit and push completed work to the user's fork, verify the remote SHA,
then update StarletOS's pinned Dolphin commit/hashes. Never leave a required
source change only in a private bundle or a copy in another repository.
- Keep generated caches and private evidence locally; no blanket cleanup of
ignored files. Do not modify a removable SD or console for a Git-only task.
+3
View File
@@ -0,0 +1,3 @@
# Shared instructions
Read AGENTS.md and docs/StarletOS_Handoff.md before working in this fork.
+887 -879
View File
File diff suppressed because it is too large. Load diff
+13 -2
View File
@@ -5,10 +5,14 @@ param(
[switch]$DisableJIT,
[switch]$ProfileJitMemory,
[switch]$SafeTextureCache = $true,
[switch]$Ethernet,
[switch]$PerformanceTrace,
[switch]$Wait
)
@@ -27,6 +31,7 @@ $dolphinArguments = @(
'-u', $userPath,
'-n', '0000000100000002',
'-C', "Dolphin.Core.WiiStarletJIT=$(-not $DisableJIT)",
'-C', "Dolphin.Core.WiiStarletJITMemoryProfiling=$($ProfileJitMemory.IsPresent)",
'-C', "Dolphin.Core.WiiLLEEthernet=$($Ethernet.IsPresent)",
# Keep the next BootMii run diagnostic rather than observational. BootMii reports its loader
# stages and panic codes through GPIO bits 16-23; the Starlet bus logs those writes under IOS.
@@ -47,8 +52,14 @@ if ($Ethernet) {
$dolphinArguments += @('-C', 'Logger.Logs.IOS_USB=True', '-C', 'Logger.Logs.IOS_NET=True')
}
$dolphin = Start-Process -FilePath $dolphinPath -ArgumentList $dolphinArguments `
-WorkingDirectory $repoRoot -PassThru
$priorPerformanceTrace = [Environment]::GetEnvironmentVariable('DOLPHIN_PERF_TRACE', 'Process')
try {
if ($PerformanceTrace) { $env:DOLPHIN_PERF_TRACE = '1' }
$dolphin = Start-Process -FilePath $dolphinPath -ArgumentList $dolphinArguments `
-WorkingDirectory $repoRoot -PassThru
} finally {
[Environment]::SetEnvironmentVariable('DOLPHIN_PERF_TRACE', $priorPerformanceTrace, 'Process')
}
$dolphin.PriorityClass = 'High'
+322
View File
@@ -0,0 +1,322 @@
param(
[string]$ELF = '../starlet-ios-rust/target/armebv5te-none-eabi/release/revolution-ios-bootstrap',
[string]$BuildDirectory = '.starlet_msvc2',
[string]$UserDirectory = '.starlet_user3',
[ValidateSet('Idle', 'Panic', 'Fatal', 'Fault', 'Phase2', 'Phase3Raw', 'Phase3Ios', 'Phase4Fs', 'Phase5Dir', 'Phase5Es', 'Phase5Client', 'Phase6Write', 'Phase6Verify', 'Phase8Client', 'Phase9Resolve', 'Phase9Launch', 'Phase9Menu', 'Phase9Rescue', 'Phase10AOh1')][string]$ExpectedOutcome = 'Idle',
[string]$PpcDol = '',
[int]$TimeoutSeconds = 30,
# Phase9Launch: the launched program's minimum check count. 5 for the
# P09-H02 payload and a requested P09-H02M launch; 3 for a P09-H02M launch
# made by the kernel's watchdog (no launcher mailbox to check).
[ValidateRange(1, 5)][int]$Phase9MinimumChecks = 5,
# Phase10AOh1: the program's minimum check count. 40 for the P10A-H07
# reduced smoke; 16 for the P10A-H07B launched payload.
[ValidateRange(1, 1000)][int]$Phase10AMinimumChecks = 40,
[switch]$JIT,
[switch]$FullDolphin
)
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$elfCandidate = if ([System.IO.Path]::IsPathRooted($ELF)) { $ELF } else { Join-Path $repoRoot $ELF }
$elfPath = (Resolve-Path -LiteralPath $elfCandidate).Path
$dolPath = if ($PpcDol) { (Resolve-Path -LiteralPath $PpcDol).Path } else { '' }
$probePath = Join-Path $repoRoot "$BuildDirectory/Binaries/Tests/StarletBootstrapProbe.exe"
if (-not $FullDolphin) {
if ($PpcDol) { throw 'PpcDol requires FullDolphin' }
if (-not (Test-Path -LiteralPath $probePath -PathType Leaf)) {
throw "Build StarletBootstrapProbe first: $probePath"
}
$probeArguments = @($elfPath)
if ($JIT) { $probeArguments += '--jit' }
if ($ExpectedOutcome -eq 'Panic') { $probeArguments += '--expect-panic' }
if ($ExpectedOutcome -eq 'Fatal') { $probeArguments += '--expect-fatal-data' }
if ($ExpectedOutcome -eq 'Fault') { $probeArguments += '--expect-undefined-fault' }
if ($ExpectedOutcome -eq 'Phase2') { $probeArguments += '--expect-phase2' }
& $probePath @probeArguments
exit $LASTEXITCODE
}
$dolphinPath = Join-Path $repoRoot "$BuildDirectory/Binaries/DolphinNoGUI.exe"
$userPath = (Resolve-Path -LiteralPath (Join-Path $repoRoot $UserDirectory)).Path
$logPath = Join-Path $userPath 'Logs/dolphin.log'
if (-not (Test-Path -LiteralPath $dolphinPath -PathType Leaf)) {
throw "Build DolphinNoGUI first: $dolphinPath"
}
if ($TimeoutSeconds -lt 1) { throw 'TimeoutSeconds must be positive' }
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $logPath) | Out-Null
$bootArguments = if ($dolPath) { @('-e', "`"$dolPath`"") } else { @('-n', '0000000100000002') }
$arguments = @('-u', "`"$userPath`"") + $bootArguments + @(
'-C', 'Dolphin.Core.WiiIOSLLE=True',
'-C', 'Dolphin.Core.WiiSDCard=False',
'-C', "Dolphin.Core.WiiStarletJIT=$($JIT.IsPresent)",
'-C', "`"Dolphin.General.WiiStarletBootstrapELF=$elfPath`"",
'-C', 'Logger.Options.WriteToFile=True',
'-C', 'Logger.Options.Verbosity=4',
'-C', 'Logger.Logs.IOS=True',
'-v', 'Null', '-p', 'headless'
)
$position = if (Test-Path -LiteralPath $logPath) { (Get-Item -LiteralPath $logPath).Length } else { 0 }
$pending = ''
$trace = [System.Collections.Generic.List[string]]::new()
$rescueStarted = $false
$outcome = $null
$faultLine = $null
$probeCounters = $null
$probeChecks = $null
$dolphin = Start-Process -FilePath $dolphinPath -ArgumentList $arguments `
-WorkingDirectory $repoRoot -PassThru -WindowStyle Hidden
try {
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
while ((Get-Date) -lt $deadline) {
if (Test-Path -LiteralPath $logPath) {
$stream = [System.IO.File]::Open($logPath, [System.IO.FileMode]::Open,
[System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
try {
if ($position -gt $stream.Length) { $position = 0; $pending = '' }
[void]$stream.Seek($position, [System.IO.SeekOrigin]::Begin)
$reader = [System.IO.StreamReader]::new($stream, [System.Text.Encoding]::UTF8,
$false, 4096, $true)
try { $chunk = $reader.ReadToEnd() } finally { $reader.Dispose() }
$position = $stream.Position
} finally {
$stream.Dispose()
}
if ($chunk.Length -gt 0) {
$lines = ($pending + $chunk) -split "`n"
$pending = $lines[-1]
for ($index = 0; $index -lt $lines.Length - 1; ++$index) {
$line = $lines[$index]
if ($line -match 'Starlet bootstrap: (.+)$') {
$message = $Matches[1].TrimEnd("`r")
$trace.Add($message)
Write-Host $message
if ($message -eq 'REV:BOOT:IDLE' -and $ExpectedOutcome -notin @('Phase3Raw', 'Phase3Ios', 'Phase4Fs', 'Phase5Dir', 'Phase5Es', 'Phase5Client', 'Phase6Write', 'Phase6Verify', 'Phase8Client', 'Phase9Launch', 'Phase9Menu', 'Phase9Rescue', 'Phase10AOh1')) {
$outcome = if ($ExpectedOutcome -eq 'Phase2') { 'Phase2' } else { 'Idle' }
}
elseif ($message -like 'REV:PANIC*') { $outcome = 'Panic' }
# Revolution IOS Phase 09 P09-H01: the read-only System Menu resolution ends.
elseif ($ExpectedOutcome -eq 'Phase9Resolve' -and $message -like 'REV:P9:H01 DONE*') { $outcome = 'Phase9Resolve' }
elseif ($ExpectedOutcome -eq 'Phase9Resolve' -and $message -like 'REV:P9:H01 *FAIL*') { $outcome = 'Phase9ResolveFailed' }
# Revolution IOS Phase 09 P09-H04: the System Menu's observation ends with the kernel's
# summary (no request for a while, or none at all); a load failure ends it too.
elseif ($ExpectedOutcome -eq 'Phase9Menu' -and ($message -like 'REV:P9:H04 QUIET *' -or $message -like 'REV:P9:H04 NOIPC *')) { $outcome = 'Phase9Menu' }
elseif ($ExpectedOutcome -eq 'Phase9Menu' -and $message -like 'REV:P9:H0[34] FAIL*') { $outcome = 'Phase9MenuFailed' }
# P09-H04 rescue: the kernel stopped the Menu and launches the rescue screen, whose
# status (0x52500005 once drawn) ends the run below.
elseif ($ExpectedOutcome -eq 'Phase9Rescue' -and $message -like 'REV:P9:H04 RESCUE GO *') { $rescueStarted = $true }
elseif ($ExpectedOutcome -eq 'Phase9Rescue' -and ($message -like 'REV:P9:H0[34] FAIL*' -or $message -like 'REV:P9:H04 RESCUE PLAN FAIL*')) { $outcome = 'Phase9RescueFailed' }
elseif ($message -like 'REV:FATAL*') { $outcome = 'Fatal' }
} elseif ($line -match 'Starlet bootstrap exception|Starlet bootstrap trace length is invalid') {
$outcome = 'Fault'
$faultLine = $line.TrimEnd("`r")
Write-Host $faultLine
} elseif ($line -match 'Broadway ios-probe status=(0x[0-9a-f]+)') {
$probeStatus = $Matches[1]
Write-Host "PPC: $probeStatus"
if ($probeStatus -eq '0x52500002') { $outcome = 'Phase3Raw' }
elseif ($probeStatus -eq '0x52500005' -and $ExpectedOutcome -eq 'Phase10AOh1') { $outcome = 'Phase10AOh1' }
elseif ($probeStatus -eq '0x52500003') { $outcome = 'Phase3Ios' }
# Phase 09 P09-H02: the payload's success is final only with the kernel's
# release and first-request lines (checked after each chunk below).
elseif ($probeStatus -eq '0x52500005' -and $ExpectedOutcome -eq 'Phase9Launch') { $payloadPassed = $true }
elseif ($ExpectedOutcome -eq 'Phase9Rescue') { if ($probeStatus -eq '0x52500005' -and $rescueStarted) { $outcome = 'Phase9Rescue' } }
elseif ($probeStatus -eq '0x52500005') { $outcome = $(if ($ExpectedOutcome -in @('Phase5Dir', 'Phase5Es', 'Phase5Client', 'Phase6Write', 'Phase6Verify', 'Phase8Client')) { $ExpectedOutcome } else { 'Phase4Fs' }) }
# Phase 09 P09-H02M: a later program's status (the launched monitor
# starting) voids an earlier program's pass and its checks.
elseif ($ExpectedOutcome -eq 'Phase9Launch' -and $probeStatus -notmatch '^0x5250e') { $payloadPassed = $false; $probeChecks = $null }
elseif ($probeStatus -match '^0x5250e') { $outcome = 'ProbeFailed' }
} elseif ($line -match 'Broadway ios-probe counters sent=(\d+) received=(\d+) invalid=(\d+) duplicate=(\d+) timeout=(\d+)') {
$probeCounters = @([int]$Matches[1], [int]$Matches[2], [int]$Matches[3],
[int]$Matches[4], [int]$Matches[5])
Write-Host "PPC counters: $($probeCounters -join '/')"
} elseif ($line -match 'Broadway ios-probe checks=(\d+) failures=(\d+)') {
$probeChecks = @([int]$Matches[1], [int]$Matches[2])
Write-Host "PPC checks: $($probeChecks -join '/')"
}
}
}
}
if (-not $outcome -and $ExpectedOutcome -eq 'Phase9Launch' -and $payloadPassed -and $probeChecks -and
@($trace | Where-Object { $_ -like 'REV:P9:H02 GO *' }).Count -eq 1 -and
@($trace | Where-Object { $_ -like 'REV:P9:H02 FIRST CMD *' }).Count -eq 1) {
$outcome = 'Phase9Launch'
}
if ($outcome) { break }
if ($dolphin.HasExited) { break }
Start-Sleep -Milliseconds 200
}
if ($outcome -ne $ExpectedOutcome) {
$exitDetail = if ($dolphin.HasExited) { "Dolphin exited with code $($dolphin.ExitCode). " } else { '' }
throw "$exitDetail Bootstrap outcome '$outcome' (expected '$ExpectedOutcome'); see $logPath"
}
if ($ExpectedOutcome -eq 'Fault') {
if ($faultLine -notmatch 'Starlet bootstrap exception 1: LR=0x[0-9a-f]+ SPSR=0x[0-9a-f]+ PC=0x[0-9a-f]+') {
throw "Expected an undefined-instruction exception with registers; see $logPath"
}
}
if ($ExpectedOutcome -eq 'Fatal') {
if (-not $trace.Contains('REV:BOOT:ENTRY') -or
-not $trace.Contains('REV:BOOT:BSS_OK') -or
-not $trace.Contains('REV:FATAL:DATA') -or
$trace.Contains('REV:BOOT:DATA_OK')) {
throw "Fatal data check did not produce the expected markers; see $logPath"
}
}
if ($ExpectedOutcome -eq 'Phase2') {
$requiredPhase2 = @('REV:P2:START', 'ARCH PASS', 'CRITICAL PASS', 'TIMER PASS',
'MONOTONIC PASS', 'MEM PASS', 'IRQ PASS', 'BARRIER PASS', 'LOGGING PASS',
'REV:P2:PASS', 'REV:P2:KERNEL_READY', 'REV:BOOT:IDLE')
$missingPhase2 = @($requiredPhase2 | Where-Object { -not $trace.Contains($_) })
if ($missingPhase2.Count -gt 0 -or @($trace | Where-Object { $_ -like '* FAIL' }).Count -gt 0) {
throw "Phase 02 self-test markers are incomplete; see $logPath"
}
}
if ($ExpectedOutcome -eq 'Phase3Raw' -and
(-not $trace.Contains('REV:P3A:START') -or
-not $trace.Contains('REV:P3A:ARM_128') -or
-not $trace.Contains('REV:P3A:ARM_PASS') -or
-not $probeCounters -or
$probeCounters[0] -ne 128 -or $probeCounters[1] -ne 128 -or
$probeCounters[2] -ne 0 -or $probeCounters[3] -ne 0 -or
$probeCounters[4] -ne 0)) {
throw "Phase 03A Starlet markers are incomplete; see $logPath"
}
if ($ExpectedOutcome -eq 'Phase3Ios' -and
(-not $trace.Contains('REV:P3B:START') -or
-not $trace.Contains('REV:P3B:OPEN_OK') -or
-not $trace.Contains('REV:P3B:PING_OK') -or
-not $trace.Contains('REV:P3B:CLOSE_OK') -or
-not $probeCounters -or $probeCounters[0] -lt 200 -or
$probeCounters[0] -ne $probeCounters[1] -or
$probeCounters[2] -ne 0 -or $probeCounters[3] -ne 0 -or
$probeCounters[4] -ne 0 -or
-not $probeChecks -or $probeChecks[0] -lt 260 -or
$probeChecks[1] -ne 0)) {
throw "Phase 03B IOS probe markers or counters are incomplete; see $logPath"
}
# Revolution IOS Phase 04D: the shared /dev/fs cases (ppc/common/fs_cases.h).
if ($ExpectedOutcome -eq 'Phase4Fs' -and
(-not $trace.Contains('REV:P3B:START') -or
@($trace | Where-Object { $_ -like 'REV:P4:FS MOUNT GEN * AUTH YES *' }).Count -ne 1 -or
-not $probeCounters -or $probeCounters[0] -lt 100 -or
$probeCounters[0] -ne $probeCounters[1] -or
$probeCounters[2] -ne 0 -or $probeCounters[3] -ne 0 -or
$probeCounters[4] -ne 0 -or
-not $probeChecks -or $probeChecks[0] -lt 30 -or
$probeChecks[1] -ne 0)) {
throw "Phase 04D /dev/fs markers or counters are incomplete; see $logPath"
}
# Revolution IOS Phase 05B: the READDIR/GETUSAGE cases (ppc/common/fs_dir_cases.h).
if ($ExpectedOutcome -eq 'Phase5Dir' -and
(-not $trace.Contains('REV:P3B:START') -or
@($trace | Where-Object { $_ -like 'REV:P4:FS MOUNT GEN * AUTH YES *' }).Count -ne 1 -or
-not $probeCounters -or $probeCounters[0] -lt 600 -or
$probeCounters[0] -ne $probeCounters[1] -or
$probeCounters[2] -ne 0 -or $probeCounters[3] -ne 0 -or
$probeCounters[4] -ne 0 -or
-not $probeChecks -or $probeChecks[0] -lt 13 -or
$probeChecks[1] -ne 0)) {
throw "Phase 05B READDIR/GETUSAGE markers or counters are incomplete; see $logPath"
}
# Revolution IOS Phase 05C/05D: the /dev/es cases (ppc/common/es_cases.h).
if ($ExpectedOutcome -eq 'Phase5Es' -and
(-not $trace.Contains('REV:P3B:START') -or
@($trace | Where-Object { $_ -like 'REV:P4:FS MOUNT GEN * AUTH YES *' }).Count -ne 1 -or
-not $probeCounters -or $probeCounters[0] -lt 600 -or
$probeCounters[0] -ne $probeCounters[1] -or
$probeCounters[2] -ne 0 -or $probeCounters[3] -ne 0 -or
$probeCounters[4] -ne 0 -or
-not $probeChecks -or $probeChecks[0] -lt 18 -or
$probeChecks[1] -ne 0)) {
throw "Phase 05C /dev/es markers or counters are incomplete; see $logPath"
}
# P10A-H07 reduced smoke: real service on the emulator USB double; no
# local loopback and no physical acceptance. No synthetic IPC counters.
if ($ExpectedOutcome -eq 'Phase10AOh1' -and
(-not $trace.Contains('REV:P10A:OH1 READY REAL USB') -or
@($trace | Where-Object { $_ -like 'REV:P4:FS MOUNT GEN * AUTH YES *' }).Count -ne 1 -or
-not $probeChecks -or $probeChecks[0] -lt $Phase10AMinimumChecks -or $probeChecks[1] -ne 0)) {
throw 'Phase 10A OH1 reduced smoke markers or checks are incomplete'
}
# Revolution IOS Phase 05F: the unchanged libogc stock client (ppc/stock-client).
if ($ExpectedOutcome -eq 'Phase5Client' -and
(-not $trace.Contains('REV:P3B:START') -or
@($trace | Where-Object { $_ -like 'REV:P4:FS MOUNT GEN * AUTH YES *' }).Count -ne 1 -or
-not $probeCounters -or $probeCounters[0] -lt 16 -or
$probeCounters[0] -ne $probeCounters[1] -or
-not $probeChecks -or $probeChecks[0] -lt 16 -or
$probeChecks[1] -ne 0)) {
throw "Phase 05F stock client markers or counters are incomplete; see $logPath"
}
# Revolution IOS Phase 06H: the writable scenario (ppc/fs-write-probe, mode Write) on the
# emulator-only writable kernel over the disposable NAND (REV_BOOTSTRAP_NAND_DISPOSABLE).
if ($ExpectedOutcome -eq 'Phase6Write' -and
(-not $trace.Contains('REV:P3B:START') -or
@($trace | Where-Object { $_ -like 'REV:P6:FS MOUNT GEN * WRITABLE' }).Count -ne 1 -or
@($trace | Where-Object { $_ -like 'REV:P6:FS GEN * REMOUNT *' }).Count -ne 0 -or
-not $probeCounters -or $probeCounters[0] -lt 100 -or
$probeCounters[0] -ne $probeCounters[1] -or
$probeCounters[2] -ne 0 -or $probeCounters[3] -ne 0 -or
$probeCounters[4] -ne 0 -or
-not $probeChecks -or $probeChecks[0] -lt 60 -or
$probeChecks[1] -ne 0)) {
throw "Phase 06H writable scenario markers or counters are incomplete; see $logPath"
}
# Revolution IOS Phase 06H: the resulting image after a fresh boot of the read-only kernel
# (ppc/fs-write-probe, mode Verify).
if ($ExpectedOutcome -eq 'Phase6Verify' -and
(-not $trace.Contains('REV:P3B:START') -or
@($trace | Where-Object { $_ -like 'REV:P4:FS MOUNT GEN * AUTH YES *' }).Count -ne 1 -or
-not $probeCounters -or $probeCounters[0] -lt 30 -or
$probeCounters[0] -ne $probeCounters[1] -or
$probeCounters[2] -ne 0 -or $probeCounters[3] -ne 0 -or
$probeCounters[4] -ne 0 -or
-not $probeChecks -or $probeChecks[0] -lt 25 -or
$probeChecks[1] -ne 0)) {
throw "Phase 06H verification markers or counters are incomplete; see $logPath"
}
# Revolution IOS Phase 08 H07R (section 69): the libogc read-after-reboot client
# (ppc/p8-client/reboot.c), the same boot.dol as on the console, on the emulator-only
# writable kernel over the disposable NAND. It writes only its status word (0x52500005 when
# every check of its part passed); the part is proven by the NAND copy, outside this script.
if ($ExpectedOutcome -eq 'Phase8Client' -and
(-not $trace.Contains('REV:P3B:START') -or
@($trace | Where-Object { $_ -like 'REV:P6:FS MOUNT GEN * WRITABLE' }).Count -ne 1)) {
throw "Phase 08 client markers are incomplete; see $logPath"
}
# Revolution IOS Phase 09 P09-H02: Broadway stopped and restarted into the payload while the
# kernel stays resident; the payload's own checks passed.
if ($ExpectedOutcome -eq 'Phase9Launch' -and
(@($trace | Where-Object { $_ -like 'REV:P9:H02 GO *' }).Count -ne 1 -or
@($trace | Where-Object { $_ -like 'REV:P9:H02 FIRST CMD *' }).Count -ne 1 -or
-not $probeChecks -or $probeChecks[0] -lt $Phase9MinimumChecks -or $probeChecks[1] -ne 0)) {
throw "Phase 09 launch markers or checks are incomplete; see $logPath"
}
# Revolution IOS Phase 09 P09-H04: the Menu was resolved, profiled, loaded and released
# (M0-M4) before the observation ended.
if ($ExpectedOutcome -in @('Phase9Menu', 'Phase9Rescue')) {
$missingMenu = @('REV:P9:H04 M0 ', 'REV:P9:H04 M1 ', 'REV:P9:H04 M2 STOPPED LOWMEM VERIFY OK', 'REV:P9:H04 M3 ', 'REV:P9:H04 M4 ') |
Where-Object { $prefix = $_; @($trace | Where-Object { $_.StartsWith($prefix) }).Count -ne 1 }
if (@($missingMenu).Count -gt 0) {
throw "Phase 09 System Menu milestones are incomplete ($($missingMenu -join ', ')); see $logPath"
}
}
$required = @('REV:BOOT:ENTRY', 'REV:BOOT:BSS_OK', 'REV:BOOT:DATA_OK',
'REV:BOOT:STACK_OK', 'REV:BOOT:RUST', 'Revolution IOS',
'Starlet Rust bootstrap reached')
$missing = @($required | Where-Object { -not $trace.Contains($_) })
if ($ExpectedOutcome -in @('Idle', 'Phase2') -and $missing.Count -gt 0) {
throw "Bootstrap reached idle without all expected markers; see $logPath"
}
Write-Host "Starlet bootstrap $outcome passed ($($trace.Count) trace lines)."
} finally {
if (-not $dolphin.HasExited) {
Stop-Process -Id $dolphin.Id
$dolphin.WaitForExit()
}
}
+2
View File
@@ -122,6 +122,8 @@ add_library(common
OneShotEvent.h
PcapFile.cpp
PcapFile.h
PerformanceTrace.cpp
PerformanceTrace.h
Profiler.cpp
Profiler.h
Projection.h
+9 -1
View File
@@ -9,6 +9,7 @@
#include "Common/Assert.h"
#include "Common/CommonTypes.h"
#include "Common/MemoryUtil.h"
#include "Common/PerformanceTrace.h"
namespace Common
{
@@ -72,6 +73,8 @@ public:
void FreeCodeSpace()
{
ASSERT(!m_is_child);
if (region)
PerformanceTrace::CodeReset("Generated", this, region, region + total_region_size);
Common::FreeMemoryPages(region, total_region_size);
region = nullptr;
region_size = 0;
@@ -97,7 +100,12 @@ public:
{
Common::UnWriteProtectMemory(region, region_size, allow_execute);
}
void ResetCodePtr() { T::SetCodePtr(region, region + region_size); }
void ResetCodePtr()
{
if (region)
PerformanceTrace::CodeReset("Generated", this, region, region + region_size);
T::SetCodePtr(region, region + region_size);
}
size_t GetSpaceLeft() const
{
ASSERT(static_cast<size_t>(T::GetCodePtr() - region) < region_size);
+17
View File
@@ -11,6 +11,7 @@
#include "Common/CommonTypes.h"
#include "Common/IOFile.h"
#include "Common/PerformanceTrace.h"
#ifdef _WIN32
#include <process.h>
@@ -66,8 +67,24 @@ bool IsEnabled()
return s_is_enabled;
}
bool IsTraceEnabled()
{
return PerformanceTrace::Enabled();
}
void Register(const void* base_address, u32 code_size, const std::string& symbol_name)
{
// Block mappings (including invalidation) are emitted by JitCache itself.
if (!symbol_name.starts_with("JIT_PPC_"))
{
// Vertex decoding also uses JitRegister. Do not attribute it to the guest CPU.
const char* domain = symbol_name.starts_with("JIT_") ? "PPC" :
symbol_name.starts_with("VertexLoader") ? "VertexDecode" :
"OtherGenerated";
PerformanceTrace::CodeMap(domain, nullptr, base_address,
static_cast<const u8*>(base_address) + code_size, 0, 0,
symbol_name.c_str());
}
#ifdef USE_VTUNE
iJIT_Method_Load jmethod = {0};
jmethod.method_id = iJIT_GetNewMethodID();
+4 -2
View File
@@ -15,12 +15,14 @@ void Init(const std::string& perf_dir);
void Shutdown();
void Register(const void* base_address, u32 code_size, const std::string& symbol_name);
bool IsEnabled();
// ETW mappings can be requested without enabling perf-map/VTune registration.
bool IsTraceEnabled();
template <typename... Args>
inline void Register(const void* base_address, u32 code_size, fmt::format_string<Args...> format,
Args&&... args)
{
if (!IsEnabled())
if (!IsEnabled() && !IsTraceEnabled())
return;
Register(base_address, code_size, fmt::format(format, std::forward<Args>(args)...));
@@ -30,7 +32,7 @@ template <typename... Args>
inline void Register(const void* start, const void* end, fmt::format_string<Args...> format,
Args&&... args)
{
if (!IsEnabled())
if (!IsEnabled() && !IsTraceEnabled())
return;
u32 code_size = (u32)((const char*)end - (const char*)start);
+294
View File
@@ -0,0 +1,294 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "Common/PerformanceTrace.h"
#include <atomic>
#include <cstdlib>
#include <cstring>
#ifdef _WIN32
#include <Windows.h>
#include <TraceLoggingProvider.h>
#pragma comment(lib, "advapi32.lib")
TRACELOGGING_DEFINE_PROVIDER(s_dolphin_perf, "Dolphin.Performance",
(0x54ee9231, 0x28be, 0x4ab0, 0x98, 0x1e, 0xb2, 0x6f, 0x97, 0x9c, 0x56,
0xa4));
#endif
namespace Common::PerformanceTrace
{
namespace
{
constexpr u32 SCHEMA = 1;
constexpr u32 SAMPLE_MASK = 1023;
struct ThreadState
{
bool sampling = false;
u32 rng = 0x9e3779b9;
u64 roots = 0;
u64 selected = 0;
u64 last_snapshot = 0;
ScopeStack stack;
std::array<u64, static_cast<size_t>(Counter::Count)> counters{};
};
thread_local ThreadState s_thread;
#ifdef _WIN32
struct Registration
{
Registration() : status(TraceLoggingRegister(s_dolphin_perf)) {}
~Registration()
{
if (status == ERROR_SUCCESS)
TraceLoggingUnregister(s_dolphin_perf);
}
ULONG status;
};
#endif
} // namespace
bool ScopeStack::Begin(Region region, u64 now)
{
if (m_depth == m_stack.size() || static_cast<size_t>(region) >= m_timings.size())
{
++m_errors;
return false;
}
m_stack[m_depth++] = {region, now, 0};
return true;
}
bool ScopeStack::End(u64 now)
{
if (m_depth == 0)
{
++m_errors;
return false;
}
const Entry entry = m_stack[--m_depth];
if (now < entry.start || now - entry.start < entry.children)
{
++m_errors;
return false;
}
const u64 elapsed = now - entry.start;
auto& timing = m_timings[static_cast<size_t>(entry.region)];
++timing.calls;
timing.inclusive += elapsed;
timing.exclusive += elapsed - entry.children;
if (m_depth != 0)
m_stack[m_depth - 1].children += elapsed;
return true;
}
void ScopeStack::Reset()
{
m_depth = 0;
m_errors = 0;
m_timings = {};
}
bool Requested()
{
#ifdef _WIN32
static const bool requested = [] {
const char* value = std::getenv("DOLPHIN_PERF_TRACE");
return value && std::strcmp(value, "1") == 0;
}();
return requested;
#else
return false;
#endif
}
bool Enabled()
{
#ifdef _WIN32
if (!Requested())
return false;
static Registration registration;
return registration.status == ERROR_SUCCESS && TraceLoggingProviderEnabled(s_dolphin_perf, 0, 0);
#else
return false;
#endif
}
u64 Now()
{
#ifdef _WIN32
LARGE_INTEGER value;
QueryPerformanceCounter(&value);
return static_cast<u64>(value.QuadPart);
#else
return 0;
#endif
}
u64 Frequency()
{
#ifdef _WIN32
static const u64 frequency = [] {
LARGE_INTEGER value;
QueryPerformanceFrequency(&value);
return static_cast<u64>(value.QuadPart);
}();
return frequency;
#else
return 0;
#endif
}
void Add(Counter counter, u64 value)
{
if (Requested() && static_cast<size_t>(counter) < s_thread.counters.size())
s_thread.counters[static_cast<size_t>(counter)] += value;
}
u64 NewGeneration()
{
static std::atomic<u64> generation{0};
return Requested() ? generation.fetch_add(1, std::memory_order_relaxed) + 1 : 0;
}
SampleRoot::SampleRoot(bool force_for_test)
{
m_denominator = force_for_test ? 1 : SAMPLE_MASK + 1;
if (!Enabled() || s_thread.sampling)
return;
++s_thread.roots;
auto& x = s_thread.rng;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
if (!force_for_test && (x & SAMPLE_MASK) != 0)
return;
++s_thread.selected;
s_thread.stack.Reset();
m_start = Now();
m_active = s_thread.stack.Begin(Region::Slice, m_start);
s_thread.sampling = m_active;
}
SampleRoot::~SampleRoot()
{
if (!m_active)
return;
const u64 end = Now();
s_thread.stack.End(end);
s_thread.sampling = false;
#ifdef _WIN32
// Sampled wall times, NOT exact total CPU times. Nested regions are exclusive here.
for (size_t i = 0; i < s_thread.stack.Timings().size(); ++i)
{
const auto& timing = s_thread.stack.Timings()[i];
if (timing.calls == 0)
continue;
TraceLoggingWrite(s_dolphin_perf, "ScopeSample", TraceLoggingUInt32(SCHEMA, "Schema"),
TraceLoggingUInt64(m_start, "BeginQPC"), TraceLoggingUInt64(end, "EndQPC"),
TraceLoggingUInt64(s_thread.selected, "Sample"),
TraceLoggingUInt32(m_denominator, "SamplingDenominator"),
TraceLoggingUInt32(static_cast<u32>(i), "Region"),
TraceLoggingUInt64(timing.calls, "Calls"),
TraceLoggingUInt64(timing.inclusive, "InclusiveQPC"),
TraceLoggingUInt64(timing.exclusive, "ExclusiveQPC"),
TraceLoggingUInt64(s_thread.stack.Errors(), "AccountingErrors"));
}
#endif
}
Scope::Scope(Region region)
{
if (s_thread.sampling)
m_active = s_thread.stack.Begin(region, Now());
}
Scope::~Scope()
{
if (m_active)
s_thread.stack.End(Now());
}
void Snapshot(u64 core_id, u64 instructions, u64 native_instructions, u64 slow_reads,
u64 slow_writes, u64 compiles, u64 fallbacks, u32 pc, bool waiting)
{
if (!Enabled())
return;
const u64 now = Now();
if (now - s_thread.last_snapshot < Frequency())
return;
s_thread.last_snapshot = now;
#ifdef _WIN32
TraceLoggingWrite(
s_dolphin_perf, "Snapshot", TraceLoggingUInt32(SCHEMA, "Schema"),
TraceLoggingUInt64(now, "QPC"), TraceLoggingUInt64(Frequency(), "QPCFrequency"),
TraceLoggingUInt64(core_id, "CoreId"), TraceLoggingUInt64(instructions, "Instructions"),
TraceLoggingUInt64(native_instructions, "NativeInstructions"),
TraceLoggingUInt64(slow_reads, "SlowReads"), TraceLoggingUInt64(slow_writes, "SlowWrites"),
TraceLoggingUInt64(compiles, "Compiles"), TraceLoggingUInt64(fallbacks, "Fallbacks"),
TraceLoggingUInt32(pc, "GuestPC"), TraceLoggingBool(waiting, "Waiting"),
TraceLoggingUInt64(s_thread.roots, "Roots"),
TraceLoggingUInt64(s_thread.selected, "SelectedRoots"));
for (size_t i = 0; i < s_thread.counters.size(); ++i)
{
TraceLoggingWrite(s_dolphin_perf, "Counter", TraceLoggingUInt32(SCHEMA, "Schema"),
TraceLoggingUInt64(now, "QPC"),
TraceLoggingUInt32(static_cast<u32>(i), "Counter"),
TraceLoggingUInt64(s_thread.counters[i], "Value"));
}
#endif
}
void CodeMap(const char* domain, const void* owner, const void* begin, const void* end,
u32 guest_pc, u64 identity, const char* kind)
{
if (!begin || reinterpret_cast<uintptr_t>(end) <= reinterpret_cast<uintptr_t>(begin) ||
!Enabled())
return;
#ifdef _WIN32
TraceLoggingWrite(s_dolphin_perf, "CodeMap", TraceLoggingUInt32(SCHEMA, "Schema"),
TraceLoggingUInt64(Now(), "QPC"), TraceLoggingString(domain, "Domain"),
TraceLoggingPointer(owner, "Owner"), TraceLoggingPointer(begin, "Begin"),
TraceLoggingPointer(end, "End"), TraceLoggingUInt32(guest_pc, "GuestPC"),
TraceLoggingUInt64(identity, "Identity"), TraceLoggingString(kind, "Kind"));
#endif
}
void CodeReset(const char* domain, const void* owner, const void* begin, const void* end)
{
CodeMap(domain, owner, begin, end, 0, 0, "invalidate");
}
void Frame(const char* kind, s64 guest_ticks, u32 guest_frequency)
{
if (!Enabled())
return;
#ifdef _WIN32
TraceLoggingWrite(s_dolphin_perf, "Frame", TraceLoggingUInt32(SCHEMA, "Schema"),
TraceLoggingUInt64(Now(), "QPC"),
TraceLoggingUInt64(Frequency(), "QPCFrequency"),
TraceLoggingString(kind, "Kind"), TraceLoggingInt64(guest_ticks, "GuestTicks"),
TraceLoggingUInt32(guest_frequency, "GuestFrequency"));
#endif
}
void Marker(const char* name)
{
if (!Enabled())
return;
#ifdef _WIN32
TraceLoggingWrite(s_dolphin_perf, "Marker", TraceLoggingUInt32(SCHEMA, "Schema"),
TraceLoggingUInt64(Now(), "QPC"),
TraceLoggingUInt64(Frequency(), "QPCFrequency"),
TraceLoggingString(name, "Name"));
#endif
}
void Queue(const void* owner, u64 frames, u64 bytes, u64 oldest_qpc, u64 peak)
{
if (!Enabled())
return;
#ifdef _WIN32
TraceLoggingWrite(s_dolphin_perf, "USBQueue", TraceLoggingUInt32(SCHEMA, "Schema"),
TraceLoggingUInt64(Now(), "QPC"), TraceLoggingPointer(owner, "Owner"),
TraceLoggingUInt64(frames, "Frames"), TraceLoggingUInt64(bytes, "Bytes"),
TraceLoggingUInt64(oldest_qpc, "OldestQPC"),
TraceLoggingUInt64(peak, "PeakFrames"));
#endif
}
} // namespace Common::PerformanceTrace
+126
View File
@@ -0,0 +1,126 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <array>
#include <cstddef>
#include "Common/CommonTypes.h"
namespace Common::PerformanceTrace
{
// Opt-in diagnostic events, never guest state. Windows provider:
// Dolphin.Performance / {54ee9231-28be-4ab0-981e-b26f979c56a4}, schema 1.
// Set DOLPHIN_PERF_TRACE=1 before process creation and start ETW before launching.
enum class Region : u32
{
Slice,
ARM,
Jit,
Compile,
Devices,
NAND,
Journal,
JournalBuild,
JournalWrite,
JournalFlush,
NAT,
DMARead,
DMAWrite,
AES,
SHA,
Count
};
enum class Counter : u32
{
JournalTransactions,
JournalBytes,
JournalErrors,
NatRXFrames,
NatRXBytes,
NatTXFrames,
NatTXBytes,
NatPollErrors,
UsbRXFrames,
UsbRXBytes,
UsbDrops,
UsbDeliveredBytes,
NANDReads,
NANDPrograms,
NANDErases,
Count
};
struct Timing
{
u64 calls = 0;
u64 inclusive = 0;
u64 exclusive = 0;
};
// Clock-independent accounting, also exercised with deterministic timestamps in tests.
class ScopeStack
{
public:
bool Begin(Region region, u64 now);
bool End(u64 now);
void Reset();
size_t Depth() const { return m_depth; }
u64 Errors() const { return m_errors; }
const auto& Timings() const { return m_timings; }
private:
struct Entry
{
Region region;
u64 start;
u64 children;
};
std::array<Entry, 32> m_stack{};
std::array<Timing, static_cast<size_t>(Region::Count)> m_timings{};
size_t m_depth = 0;
u64 m_errors = 0;
};
bool Requested();
bool Enabled();
u64 Now();
u64 Frequency();
u64 NewGeneration();
void Add(Counter counter, u64 value = 1);
void Snapshot(u64 core_id, u64 instructions, u64 native_instructions, u64 slow_reads,
u64 slow_writes, u64 compiles, u64 fallbacks, u32 pc, bool waiting);
void CodeMap(const char* domain, const void* owner, const void* begin, const void* end,
u32 guest_pc, u64 identity, const char* kind);
void CodeReset(const char* domain, const void* owner, const void* begin, const void* end);
void Frame(const char* kind, s64 guest_ticks = 0, u32 guest_frequency = 0);
void Marker(const char* name);
void Queue(const void* owner, u64 frames, u64 bytes, u64 oldest_qpc, u64 peak);
// Only scopes inside a randomly selected root slice read the clock. No per-access timers.
class SampleRoot
{
public:
explicit SampleRoot(bool force_for_test = false);
~SampleRoot();
SampleRoot(const SampleRoot&) = delete;
SampleRoot& operator=(const SampleRoot&) = delete;
private:
bool m_active = false;
u64 m_start = 0;
u32 m_denominator = 1024;
};
class Scope
{
public:
explicit Scope(Region region);
~Scope();
Scope(const Scope&) = delete;
Scope& operator=(const Scope&) = delete;
private:
bool m_active = false;
};
} // namespace Common::PerformanceTrace
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+440 -438
View File
@@ -1,441 +1,443 @@
// Copyright 2017 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <array>
#include <set>
#include <string>
#include <utility>
#include "Common/Common.h"
#include "Common/CommonTypes.h"
#include "Common/Config/Config.h"
#include "Core/USBUtils.h"
#include "DiscIO/Enums.h"
// DSP Backend Types
#define BACKEND_NULLSOUND _trans("No Audio Output")
#define BACKEND_ALSA "ALSA"
#define BACKEND_CUBEB "Cubeb"
#define BACKEND_OPENAL "OpenAL"
#define BACKEND_PULSEAUDIO "Pulse"
#define BACKEND_OPENSLES "OpenSLES"
#define BACKEND_WASAPI _trans("WASAPI (Exclusive Mode)")
namespace PowerPC
{
enum class CPUCore;
}
namespace AudioCommon
{
enum class DPL2Quality;
}
namespace ExpansionInterface
{
enum class EXIDeviceType : int;
enum class Slot : int;
} // namespace ExpansionInterface
namespace SerialInterface
{
enum SIDevices : int;
}
namespace HSP
{
enum class HSPDeviceType : int;
}
namespace Config
{
// Main.Core
extern const Info<bool> MAIN_SKIP_IPL;
extern const Info<PowerPC::CPUCore> MAIN_CPU_CORE;
extern const Info<bool> MAIN_JIT_FOLLOW_BRANCH;
extern const Info<bool> MAIN_FASTMEM;
extern const Info<bool> MAIN_PAGE_TABLE_FASTMEM;
extern const Info<bool> MAIN_FASTMEM_ARENA;
extern const Info<bool> MAIN_LARGE_ENTRY_POINTS_MAP;
extern const Info<bool> MAIN_ACCURATE_CPU_CACHE;
// Should really be in the DSP section, but we're kind of stuck with bad decisions made in the past.
extern const Info<bool> MAIN_DSP_HLE;
extern const Info<int> MAIN_MAX_FALLBACK;
extern const Info<int> MAIN_TIMING_VARIANCE;
extern const Info<bool> MAIN_CORRECT_TIME_DRIFT;
extern const Info<bool> MAIN_RUSH_FRAME_PRESENTATION;
extern const Info<bool> MAIN_SMOOTH_EARLY_PRESENTATION;
extern const Info<bool> MAIN_CPU_THREAD;
extern const Info<bool> MAIN_LOAD_GAME_INTO_MEMORY;
extern const Info<bool> MAIN_SYNC_ON_SKIP_IDLE;
extern const Info<std::string> MAIN_DEFAULT_ISO;
extern const Info<bool> MAIN_ENABLE_CHEATS;
extern const Info<int> MAIN_GC_LANGUAGE;
extern const Info<bool> MAIN_OVERRIDE_REGION_SETTINGS;
extern const Info<bool> MAIN_DPL2_DECODER;
extern const Info<AudioCommon::DPL2Quality> MAIN_DPL2_QUALITY;
extern const Info<int> MAIN_AUDIO_LATENCY;
extern const Info<int> MAIN_AUDIO_BUFFER_SIZE;
extern const Info<bool> MAIN_AUDIO_FILL_GAPS;
extern const Info<bool> MAIN_AUDIO_PRESERVE_PITCH;
extern const Info<std::string> MAIN_MEMCARD_A_PATH;
extern const Info<std::string> MAIN_MEMCARD_B_PATH;
const Info<std::string>& GetInfoForMemcardPath(ExpansionInterface::Slot slot);
extern const Info<std::string> MAIN_AGP_CART_A_PATH;
extern const Info<std::string> MAIN_AGP_CART_B_PATH;
const Info<std::string>& GetInfoForAGPCartPath(ExpansionInterface::Slot slot);
extern const Info<std::string> MAIN_GCI_FOLDER_A_PATH;
extern const Info<std::string> MAIN_GCI_FOLDER_B_PATH;
const Info<std::string>& GetInfoForGCIPath(ExpansionInterface::Slot slot);
extern const Info<std::string> MAIN_GCI_FOLDER_A_PATH_OVERRIDE;
extern const Info<std::string> MAIN_GCI_FOLDER_B_PATH_OVERRIDE;
const Info<std::string>& GetInfoForGCIPathOverride(ExpansionInterface::Slot slot);
extern const Info<int> MAIN_MEMORY_CARD_SIZE;
extern const Info<ExpansionInterface::EXIDeviceType> MAIN_SLOT_A;
extern const Info<ExpansionInterface::EXIDeviceType> MAIN_SLOT_B;
extern const Info<ExpansionInterface::EXIDeviceType> MAIN_SERIAL_PORT_1;
extern const Info<ExpansionInterface::EXIDeviceType> MAIN_SERIAL_PORT_2;
const Info<ExpansionInterface::EXIDeviceType>& GetInfoForEXIDevice(ExpansionInterface::Slot slot);
extern const Info<std::string> MAIN_BBA_MAC;
extern const Info<std::string> MAIN_BBA_XLINK_IP;
extern const Info<bool> MAIN_BBA_XLINK_CHAT_OSD;
extern const Info<std::string> MAIN_BBA_BUILTIN_DNS;
extern const Info<std::string> MAIN_BBA_BUILTIN_IP;
extern const Info<std::string> MAIN_BBA_TAPSERVER_DESTINATION;
extern const Info<std::string> MAIN_MODEM_TAPSERVER_DESTINATION;
const Info<SerialInterface::SIDevices>& GetInfoForSIDevice(int channel);
const Info<bool>& GetInfoForAdapterRumble(int channel);
const Info<bool>& GetInfoForSimulateKonga(int channel);
extern const Info<bool> MAIN_WII_SD_CARD;
extern const Info<bool> MAIN_WII_SD_CARD_ENABLE_FOLDER_SYNC;
extern const Info<u64> MAIN_WII_SD_CARD_FILESIZE;
extern const Info<bool> MAIN_WII_KEYBOARD;
extern const Info<bool> MAIN_WIIMOTE_CONTINUOUS_SCANNING;
extern const Info<std::string> MAIN_WIIMOTE_AUTO_CONNECT_ADDRESSES;
extern const Info<bool> MAIN_WIIMOTE_ENABLE_SPEAKER;
extern const Info<bool> MAIN_CONNECT_WIIMOTES_FOR_CONTROLLER_INTERFACE;
extern const Info<bool> MAIN_MMU;
extern const Info<bool> MAIN_PAUSE_ON_PANIC;
extern const Info<int> MAIN_BB_DUMP_PORT;
extern const Info<bool> MAIN_SYNC_GPU;
extern const Info<int> MAIN_SYNC_GPU_MAX_DISTANCE;
extern const Info<int> MAIN_SYNC_GPU_MIN_DISTANCE;
extern const Info<float> MAIN_SYNC_GPU_OVERCLOCK;
extern const Info<bool> MAIN_FAST_DISC_SPEED;
extern const Info<bool> MAIN_LOW_DCBZ_HACK;
extern const Info<bool> MAIN_FLOAT_EXCEPTIONS;
extern const Info<bool> MAIN_DIVIDE_BY_ZERO_EXCEPTIONS;
extern const Info<bool> MAIN_FPRF;
extern const Info<bool> MAIN_ACCURATE_NANS;
extern const Info<bool> MAIN_ACCURATE_FMADDS;
extern const Info<bool> MAIN_DISABLE_ICACHE;
extern const Info<float> MAIN_EMULATION_SPEED;
extern const Info<bool> MAIN_PRECISION_FRAME_TIMING;
extern const Info<float> MAIN_OVERCLOCK;
extern const Info<bool> MAIN_OVERCLOCK_ENABLE;
extern const Info<float> MAIN_VI_OVERCLOCK;
extern const Info<bool> MAIN_VI_OVERCLOCK_ENABLE;
extern const Info<bool> MAIN_RAM_OVERRIDE_ENABLE;
extern const Info<u32> MAIN_MEM1_SIZE;
extern const Info<u32> MAIN_MEM2_SIZE;
// Should really be part of System::GFX, but again, we're stuck with past mistakes.
extern const Info<std::string> MAIN_GFX_BACKEND;
extern const Info<HSP::HSPDeviceType> MAIN_HSP_DEVICE;
extern const Info<u32> MAIN_ARAM_EXPANSION_SIZE;
enum class GPUDeterminismMode
{
Auto,
Disabled,
// This is currently the only mode. There will probably be at least
// one more at some point.
FakeCompletion,
};
extern const Info<std::string> MAIN_GPU_DETERMINISM_MODE;
GPUDeterminismMode GetGPUDeterminismMode();
extern const Info<std::string> MAIN_PERF_MAP_DIR;
extern const Info<bool> MAIN_CUSTOM_RTC_ENABLE;
extern const Info<u32> MAIN_CUSTOM_RTC_VALUE;
extern const Info<bool> MAIN_AUTO_DISC_CHANGE;
extern const Info<bool> MAIN_ALLOW_SD_WRITES;
extern const Info<bool> MAIN_ENABLE_SAVESTATES;
extern const Info<DiscIO::Region> MAIN_FALLBACK_REGION;
extern const Info<bool> MAIN_REAL_WII_REMOTE_REPEAT_REPORTS;
extern const Info<s32> MAIN_OVERRIDE_BOOT_IOS;
extern const Info<bool> MAIN_WII_IOS_LLE;
// Copyright 2017 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <array>
#include <set>
#include <string>
#include <utility>
#include "Common/Common.h"
#include "Common/CommonTypes.h"
#include "Common/Config/Config.h"
#include "Core/USBUtils.h"
#include "DiscIO/Enums.h"
// DSP Backend Types
#define BACKEND_NULLSOUND _trans("No Audio Output")
#define BACKEND_ALSA "ALSA"
#define BACKEND_CUBEB "Cubeb"
#define BACKEND_OPENAL "OpenAL"
#define BACKEND_PULSEAUDIO "Pulse"
#define BACKEND_OPENSLES "OpenSLES"
#define BACKEND_WASAPI _trans("WASAPI (Exclusive Mode)")
namespace PowerPC
{
enum class CPUCore;
}
namespace AudioCommon
{
enum class DPL2Quality;
}
namespace ExpansionInterface
{
enum class EXIDeviceType : int;
enum class Slot : int;
} // namespace ExpansionInterface
namespace SerialInterface
{
enum SIDevices : int;
}
namespace HSP
{
enum class HSPDeviceType : int;
}
namespace Config
{
// Main.Core
extern const Info<bool> MAIN_SKIP_IPL;
extern const Info<PowerPC::CPUCore> MAIN_CPU_CORE;
extern const Info<bool> MAIN_JIT_FOLLOW_BRANCH;
extern const Info<bool> MAIN_FASTMEM;
extern const Info<bool> MAIN_PAGE_TABLE_FASTMEM;
extern const Info<bool> MAIN_FASTMEM_ARENA;
extern const Info<bool> MAIN_LARGE_ENTRY_POINTS_MAP;
extern const Info<bool> MAIN_ACCURATE_CPU_CACHE;
// Should really be in the DSP section, but we're kind of stuck with bad decisions made in the past.
extern const Info<bool> MAIN_DSP_HLE;
extern const Info<int> MAIN_MAX_FALLBACK;
extern const Info<int> MAIN_TIMING_VARIANCE;
extern const Info<bool> MAIN_CORRECT_TIME_DRIFT;
extern const Info<bool> MAIN_RUSH_FRAME_PRESENTATION;
extern const Info<bool> MAIN_SMOOTH_EARLY_PRESENTATION;
extern const Info<bool> MAIN_CPU_THREAD;
extern const Info<bool> MAIN_LOAD_GAME_INTO_MEMORY;
extern const Info<bool> MAIN_SYNC_ON_SKIP_IDLE;
extern const Info<std::string> MAIN_DEFAULT_ISO;
extern const Info<bool> MAIN_ENABLE_CHEATS;
extern const Info<int> MAIN_GC_LANGUAGE;
extern const Info<bool> MAIN_OVERRIDE_REGION_SETTINGS;
extern const Info<bool> MAIN_DPL2_DECODER;
extern const Info<AudioCommon::DPL2Quality> MAIN_DPL2_QUALITY;
extern const Info<int> MAIN_AUDIO_LATENCY;
extern const Info<int> MAIN_AUDIO_BUFFER_SIZE;
extern const Info<bool> MAIN_AUDIO_FILL_GAPS;
extern const Info<bool> MAIN_AUDIO_PRESERVE_PITCH;
extern const Info<std::string> MAIN_MEMCARD_A_PATH;
extern const Info<std::string> MAIN_MEMCARD_B_PATH;
const Info<std::string>& GetInfoForMemcardPath(ExpansionInterface::Slot slot);
extern const Info<std::string> MAIN_AGP_CART_A_PATH;
extern const Info<std::string> MAIN_AGP_CART_B_PATH;
const Info<std::string>& GetInfoForAGPCartPath(ExpansionInterface::Slot slot);
extern const Info<std::string> MAIN_GCI_FOLDER_A_PATH;
extern const Info<std::string> MAIN_GCI_FOLDER_B_PATH;
const Info<std::string>& GetInfoForGCIPath(ExpansionInterface::Slot slot);
extern const Info<std::string> MAIN_GCI_FOLDER_A_PATH_OVERRIDE;
extern const Info<std::string> MAIN_GCI_FOLDER_B_PATH_OVERRIDE;
const Info<std::string>& GetInfoForGCIPathOverride(ExpansionInterface::Slot slot);
extern const Info<int> MAIN_MEMORY_CARD_SIZE;
extern const Info<ExpansionInterface::EXIDeviceType> MAIN_SLOT_A;
extern const Info<ExpansionInterface::EXIDeviceType> MAIN_SLOT_B;
extern const Info<ExpansionInterface::EXIDeviceType> MAIN_SERIAL_PORT_1;
extern const Info<ExpansionInterface::EXIDeviceType> MAIN_SERIAL_PORT_2;
const Info<ExpansionInterface::EXIDeviceType>& GetInfoForEXIDevice(ExpansionInterface::Slot slot);
extern const Info<std::string> MAIN_BBA_MAC;
extern const Info<std::string> MAIN_BBA_XLINK_IP;
extern const Info<bool> MAIN_BBA_XLINK_CHAT_OSD;
extern const Info<std::string> MAIN_BBA_BUILTIN_DNS;
extern const Info<std::string> MAIN_BBA_BUILTIN_IP;
extern const Info<std::string> MAIN_BBA_TAPSERVER_DESTINATION;
extern const Info<std::string> MAIN_MODEM_TAPSERVER_DESTINATION;
const Info<SerialInterface::SIDevices>& GetInfoForSIDevice(int channel);
const Info<bool>& GetInfoForAdapterRumble(int channel);
const Info<bool>& GetInfoForSimulateKonga(int channel);
extern const Info<bool> MAIN_WII_SD_CARD;
extern const Info<bool> MAIN_WII_SD_CARD_ENABLE_FOLDER_SYNC;
extern const Info<u64> MAIN_WII_SD_CARD_FILESIZE;
extern const Info<bool> MAIN_WII_KEYBOARD;
extern const Info<bool> MAIN_WIIMOTE_CONTINUOUS_SCANNING;
extern const Info<std::string> MAIN_WIIMOTE_AUTO_CONNECT_ADDRESSES;
extern const Info<bool> MAIN_WIIMOTE_ENABLE_SPEAKER;
extern const Info<bool> MAIN_CONNECT_WIIMOTES_FOR_CONTROLLER_INTERFACE;
extern const Info<bool> MAIN_MMU;
extern const Info<bool> MAIN_PAUSE_ON_PANIC;
extern const Info<int> MAIN_BB_DUMP_PORT;
extern const Info<bool> MAIN_SYNC_GPU;
extern const Info<int> MAIN_SYNC_GPU_MAX_DISTANCE;
extern const Info<int> MAIN_SYNC_GPU_MIN_DISTANCE;
extern const Info<float> MAIN_SYNC_GPU_OVERCLOCK;
extern const Info<bool> MAIN_FAST_DISC_SPEED;
extern const Info<bool> MAIN_LOW_DCBZ_HACK;
extern const Info<bool> MAIN_FLOAT_EXCEPTIONS;
extern const Info<bool> MAIN_DIVIDE_BY_ZERO_EXCEPTIONS;
extern const Info<bool> MAIN_FPRF;
extern const Info<bool> MAIN_ACCURATE_NANS;
extern const Info<bool> MAIN_ACCURATE_FMADDS;
extern const Info<bool> MAIN_DISABLE_ICACHE;
extern const Info<float> MAIN_EMULATION_SPEED;
extern const Info<bool> MAIN_PRECISION_FRAME_TIMING;
extern const Info<float> MAIN_OVERCLOCK;
extern const Info<bool> MAIN_OVERCLOCK_ENABLE;
extern const Info<float> MAIN_VI_OVERCLOCK;
extern const Info<bool> MAIN_VI_OVERCLOCK_ENABLE;
extern const Info<bool> MAIN_RAM_OVERRIDE_ENABLE;
extern const Info<u32> MAIN_MEM1_SIZE;
extern const Info<u32> MAIN_MEM2_SIZE;
// Should really be part of System::GFX, but again, we're stuck with past mistakes.
extern const Info<std::string> MAIN_GFX_BACKEND;
extern const Info<HSP::HSPDeviceType> MAIN_HSP_DEVICE;
extern const Info<u32> MAIN_ARAM_EXPANSION_SIZE;
enum class GPUDeterminismMode
{
Auto,
Disabled,
// This is currently the only mode. There will probably be at least
// one more at some point.
FakeCompletion,
};
extern const Info<std::string> MAIN_GPU_DETERMINISM_MODE;
GPUDeterminismMode GetGPUDeterminismMode();
extern const Info<std::string> MAIN_PERF_MAP_DIR;
extern const Info<bool> MAIN_CUSTOM_RTC_ENABLE;
extern const Info<u32> MAIN_CUSTOM_RTC_VALUE;
extern const Info<bool> MAIN_AUTO_DISC_CHANGE;
extern const Info<bool> MAIN_ALLOW_SD_WRITES;
extern const Info<bool> MAIN_ENABLE_SAVESTATES;
extern const Info<DiscIO::Region> MAIN_FALLBACK_REGION;
extern const Info<bool> MAIN_REAL_WII_REMOTE_REPEAT_REPORTS;
extern const Info<s32> MAIN_OVERRIDE_BOOT_IOS;
extern const Info<bool> MAIN_WII_IOS_LLE;
extern const Info<bool> MAIN_WII_STARLET_JIT;
extern const Info<bool> MAIN_WII_STARLET_JIT_MEMORY_PROFILING;
extern const Info<bool> MAIN_WII_LLE_ETHERNET;
extern const Info<std::string> MAIN_WII_NUS_SHOP_URL;
extern const Info<bool> MAIN_WII_WIILINK_ENABLE;
// Main.DSP
extern const Info<bool> MAIN_DSP_THREAD;
extern const Info<bool> MAIN_DSP_CAPTURE_LOG;
extern const Info<bool> MAIN_DSP_JIT;
extern const Info<bool> MAIN_DUMP_AUDIO;
extern const Info<bool> MAIN_DUMP_AUDIO_SILENT;
extern const Info<bool> MAIN_DUMP_UCODE;
extern const Info<std::string> MAIN_AUDIO_BACKEND;
extern const Info<int> MAIN_AUDIO_VOLUME;
extern const Info<bool> MAIN_AUDIO_MUTED;
extern const Info<bool> MAIN_AUDIO_MUTE_ON_DISABLED_SPEED_LIMIT;
#ifdef _WIN32
extern const Info<std::string> MAIN_WASAPI_DEVICE;
#endif
bool ShouldUseDPL2Decoder();
// Main.Display
extern const Info<std::string> MAIN_FULLSCREEN_DISPLAY_RES;
extern const Info<bool> MAIN_FULLSCREEN;
extern const Info<bool> MAIN_RENDER_TO_MAIN;
extern const Info<int> MAIN_RENDER_WINDOW_XPOS;
extern const Info<int> MAIN_RENDER_WINDOW_YPOS;
extern const Info<int> MAIN_RENDER_WINDOW_WIDTH;
extern const Info<int> MAIN_RENDER_WINDOW_HEIGHT;
extern const Info<bool> MAIN_RENDER_WINDOW_AUTOSIZE;
extern const Info<bool> MAIN_KEEP_WINDOW_ON_TOP;
extern const Info<bool> MAIN_DISABLE_SCREENSAVER;
extern const Info<bool> MAIN_TIME_TRACKING;
// Main.General
extern const Info<std::string> MAIN_DUMP_PATH;
extern const Info<std::string> MAIN_LOAD_PATH;
extern const Info<std::string> MAIN_RESOURCEPACK_PATH;
extern const Info<std::string> MAIN_FS_PATH;
extern const Info<std::string> MAIN_WII_NUS_SHOP_URL;
extern const Info<bool> MAIN_WII_WIILINK_ENABLE;
// Main.DSP
extern const Info<bool> MAIN_DSP_THREAD;
extern const Info<bool> MAIN_DSP_CAPTURE_LOG;
extern const Info<bool> MAIN_DSP_JIT;
extern const Info<bool> MAIN_DUMP_AUDIO;
extern const Info<bool> MAIN_DUMP_AUDIO_SILENT;
extern const Info<bool> MAIN_DUMP_UCODE;
extern const Info<std::string> MAIN_AUDIO_BACKEND;
extern const Info<int> MAIN_AUDIO_VOLUME;
extern const Info<bool> MAIN_AUDIO_MUTED;
extern const Info<bool> MAIN_AUDIO_MUTE_ON_DISABLED_SPEED_LIMIT;
#ifdef _WIN32
extern const Info<std::string> MAIN_WASAPI_DEVICE;
#endif
bool ShouldUseDPL2Decoder();
// Main.Display
extern const Info<std::string> MAIN_FULLSCREEN_DISPLAY_RES;
extern const Info<bool> MAIN_FULLSCREEN;
extern const Info<bool> MAIN_RENDER_TO_MAIN;
extern const Info<int> MAIN_RENDER_WINDOW_XPOS;
extern const Info<int> MAIN_RENDER_WINDOW_YPOS;
extern const Info<int> MAIN_RENDER_WINDOW_WIDTH;
extern const Info<int> MAIN_RENDER_WINDOW_HEIGHT;
extern const Info<bool> MAIN_RENDER_WINDOW_AUTOSIZE;
extern const Info<bool> MAIN_KEEP_WINDOW_ON_TOP;
extern const Info<bool> MAIN_DISABLE_SCREENSAVER;
extern const Info<bool> MAIN_TIME_TRACKING;
// Main.General
extern const Info<std::string> MAIN_DUMP_PATH;
extern const Info<std::string> MAIN_LOAD_PATH;
extern const Info<std::string> MAIN_RESOURCEPACK_PATH;
extern const Info<std::string> MAIN_FS_PATH;
extern const Info<std::string> MAIN_WII_LLE_DUMP_PATH;
extern const Info<std::string> MAIN_WII_SD_CARD_IMAGE_PATH;
extern const Info<std::string> MAIN_WII_SD_CARD_SYNC_FOLDER_PATH;
extern const Info<std::string> MAIN_WFS_PATH;
extern const Info<bool> MAIN_SHOW_LAG;
extern const Info<bool> MAIN_SHOW_FRAME_COUNT;
extern const Info<std::string> MAIN_WIRELESS_MAC;
extern const Info<std::string> MAIN_GDB_SOCKET;
extern const Info<int> MAIN_GDB_PORT;
extern const Info<int> MAIN_ISO_PATH_COUNT;
extern const Info<std::string> MAIN_SKYLANDERS_PATH;
std::vector<std::string> GetIsoPaths();
void SetIsoPaths(std::span<const std::string> paths);
// Main.GBA
#ifdef HAS_LIBMGBA
extern const Info<std::string> MAIN_GBA_BIOS_PATH;
extern const std::array<Info<std::string>, 5> MAIN_GBA_ROM_PATHS;
extern const Info<std::string> MAIN_GBA_SAVES_PATH;
extern const Info<bool> MAIN_GBA_SAVES_IN_ROM_PATH;
static constexpr std::size_t GBPLAYER_GBA_INDEX = 4;
#endif
// Main.Network
extern const Info<bool> MAIN_NETWORK_SSL_DUMP_READ;
extern const Info<bool> MAIN_NETWORK_SSL_DUMP_WRITE;
extern const Info<bool> MAIN_NETWORK_SSL_VERIFY_CERTIFICATES;
extern const Info<bool> MAIN_NETWORK_SSL_DUMP_ROOT_CA;
extern const Info<bool> MAIN_NETWORK_SSL_DUMP_PEER_CERT;
extern const Info<bool> MAIN_NETWORK_DUMP_BBA;
extern const Info<bool> MAIN_NETWORK_DUMP_AS_PCAP;
extern const Info<int> MAIN_NETWORK_TIMEOUT;
// Main.Interface
extern const Info<bool> MAIN_USE_HIGH_CONTRAST_TOOLTIPS;
extern const Info<bool> MAIN_USE_PANIC_HANDLERS;
extern const Info<bool> MAIN_ABORT_ON_PANIC_ALERT;
extern const Info<bool> MAIN_OSD_MESSAGES;
extern const Info<int> MAIN_OSD_FONT_SIZE;
extern const Info<bool> MAIN_SKIP_NKIT_WARNING;
extern const Info<bool> MAIN_CONFIRM_ON_STOP;
enum class ShowCursor
{
Never,
Constantly,
OnMovement,
};
extern const Info<ShowCursor> MAIN_SHOW_CURSOR;
extern const Info<bool> MAIN_LOCK_CURSOR;
extern const Info<std::string> MAIN_INTERFACE_LANGUAGE;
extern const Info<bool> MAIN_SHOW_ACTIVE_TITLE;
extern const Info<bool> MAIN_USE_BUILT_IN_TITLE_DATABASE;
extern const Info<std::string> MAIN_THEME_NAME;
extern const Info<bool> MAIN_PAUSE_ON_FOCUS_LOST;
extern const Info<bool> MAIN_ENABLE_DEBUGGING;
// Main.Analytics
extern const Info<std::string> MAIN_ANALYTICS_ID;
extern const Info<bool> MAIN_ANALYTICS_ENABLED;
extern const Info<bool> MAIN_ANALYTICS_PERMISSION_ASKED;
// Main.GameList
extern const Info<bool> MAIN_GAMELIST_LIST_DRIVES;
extern const Info<bool> MAIN_GAMELIST_LIST_WAD;
extern const Info<bool> MAIN_GAMELIST_LIST_ELF_DOL;
extern const Info<bool> MAIN_GAMELIST_LIST_WII;
extern const Info<bool> MAIN_GAMELIST_LIST_GC;
extern const Info<bool> MAIN_GAMELIST_LIST_TRI;
extern const Info<bool> MAIN_GAMELIST_LIST_JPN;
extern const Info<bool> MAIN_GAMELIST_LIST_PAL;
extern const Info<bool> MAIN_GAMELIST_LIST_USA;
extern const Info<bool> MAIN_GAMELIST_LIST_AUSTRALIA;
extern const Info<bool> MAIN_GAMELIST_LIST_FRANCE;
extern const Info<bool> MAIN_GAMELIST_LIST_GERMANY;
extern const Info<bool> MAIN_GAMELIST_LIST_ITALY;
extern const Info<bool> MAIN_GAMELIST_LIST_KOREA;
extern const Info<bool> MAIN_GAMELIST_LIST_NETHERLANDS;
extern const Info<bool> MAIN_GAMELIST_LIST_RUSSIA;
extern const Info<bool> MAIN_GAMELIST_LIST_SPAIN;
extern const Info<bool> MAIN_GAMELIST_LIST_TAIWAN;
extern const Info<bool> MAIN_GAMELIST_LIST_WORLD;
extern const Info<bool> MAIN_GAMELIST_LIST_UNKNOWN;
extern const Info<int> MAIN_GAMELIST_LIST_SORT;
extern const Info<int> MAIN_GAMELIST_LIST_SORT_SECONDARY;
extern const Info<bool> MAIN_GAMELIST_COLUMN_PLATFORM;
extern const Info<bool> MAIN_GAMELIST_COLUMN_DESCRIPTION;
extern const Info<bool> MAIN_GAMELIST_COLUMN_BANNER;
extern const Info<bool> MAIN_GAMELIST_COLUMN_TITLE;
extern const Info<bool> MAIN_GAMELIST_COLUMN_MAKER;
extern const Info<bool> MAIN_GAMELIST_COLUMN_FILE_NAME;
extern const Info<bool> MAIN_GAMELIST_COLUMN_FILE_PATH;
extern const Info<bool> MAIN_GAMELIST_COLUMN_GAME_ID;
extern const Info<bool> MAIN_GAMELIST_COLUMN_REGION;
extern const Info<bool> MAIN_GAMELIST_COLUMN_FILE_SIZE;
extern const Info<bool> MAIN_GAMELIST_COLUMN_FILE_FORMAT;
extern const Info<bool> MAIN_GAMELIST_COLUMN_BLOCK_SIZE;
extern const Info<bool> MAIN_GAMELIST_COLUMN_COMPRESSION;
extern const Info<bool> MAIN_GAMELIST_COLUMN_TIME_PLAYED;
extern const Info<bool> MAIN_GAMELIST_COLUMN_TAGS;
// Main.FifoPlayer
extern const Info<bool> MAIN_FIFOPLAYER_LOOP_REPLAY;
extern const Info<bool> MAIN_FIFOPLAYER_EARLY_MEMORY_UPDATES;
// Main.AutoUpdate
extern const Info<std::string> MAIN_AUTOUPDATE_UPDATE_TRACK;
extern const Info<std::string> MAIN_AUTOUPDATE_HASH_OVERRIDE;
// Main.Movie
extern const Info<bool> MAIN_MOVIE_PAUSE_MOVIE;
extern const Info<std::string> MAIN_MOVIE_MOVIE_AUTHOR;
extern const Info<bool> MAIN_MOVIE_DUMP_FRAMES;
extern const Info<bool> MAIN_MOVIE_DUMP_FRAMES_SILENT;
extern const Info<bool> MAIN_MOVIE_SHOW_INPUT_DISPLAY;
extern const Info<bool> MAIN_MOVIE_SHOW_RTC;
extern const Info<bool> MAIN_MOVIE_SHOW_RERECORD;
extern const Info<bool> MAIN_MOVIE_SHOW_OSD;
// Main.Input
extern const Info<bool> MAIN_INPUT_BACKGROUND_INPUT;
extern const Config::Info<std::string> MAIN_SDL_HINT_JOYSTICK_ENHANCED_REPORTS;
extern const Config::Info<std::string> MAIN_SDL_HINT_JOYSTICK_WGI;
extern const Config::Info<std::string> MAIN_SDL_HINT_JOYSTICK_HIDAPI_PS5_PLAYER_LED;
extern const Config::Info<std::string> MAIN_SDL_HINT_JOYSTICK_DIRECTINPUT;
extern const Config::Info<std::string> MAIN_SDL_HINT_JOYSTICK_HIDAPI_COMBINE_JOY_CONS;
extern const Config::Info<std::string> MAIN_SDL_HINT_JOYSTICK_HIDAPI_VERTICAL_JOY_CONS;
// Main.Debug
extern const Info<bool> MAIN_DEBUG_JIT_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_LOAD_STORE_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_LOAD_STORE_LXZ_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_LOAD_STORE_LWZ_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_LOAD_STORE_LBZX_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_LOAD_STORE_FLOATING_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_LOAD_STORE_PAIRED_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_FLOATING_POINT_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_INTEGER_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_PAIRED_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_SYSTEM_REGISTERS_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_BRANCH_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_REGISTER_CACHE_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_ENABLE_PROFILING;
// Main.BluetoothPassthrough
extern const Info<bool> MAIN_BLUETOOTH_PASSTHROUGH_ENABLED;
extern const Info<int> MAIN_BLUETOOTH_PASSTHROUGH_VID;
extern const Info<int> MAIN_BLUETOOTH_PASSTHROUGH_PID;
extern const Info<std::string> MAIN_BLUETOOTH_PASSTHROUGH_LINK_KEYS;
// Main.USBPassthrough
extern const Info<bool> MAIN_USB_PASSTHROUGH_DISGUISE_PLAYSTATION_AS_WII;
extern const Info<std::string> MAIN_USB_PASSTHROUGH_DEVICES;
std::set<USBUtils::DeviceInfo> GetUSBDeviceWhitelist();
void SetUSBDeviceWhitelist(const std::set<USBUtils::DeviceInfo>& devices);
// Main.EmulatedUSBDevices
extern const Info<bool> MAIN_EMULATE_SKYLANDER_PORTAL;
extern const Info<bool> MAIN_EMULATE_INFINITY_BASE;
extern const Info<bool> MAIN_EMULATE_WII_SPEAK;
extern const Info<std::string> MAIN_WII_SPEAK_MICROPHONE;
extern const Info<bool> MAIN_WII_SPEAK_MUTED;
extern const Info<s16> MAIN_WII_SPEAK_VOLUME_MODIFIER;
static constexpr std::size_t EMULATED_LOGITECH_MIC_COUNT = 4;
extern const std::array<Info<bool>, EMULATED_LOGITECH_MIC_COUNT> MAIN_EMULATE_LOGITECH_MIC;
extern const std::array<Info<std::string>, EMULATED_LOGITECH_MIC_COUNT>
MAIN_LOGITECH_MIC_MICROPHONE;
extern const std::array<Info<bool>, EMULATED_LOGITECH_MIC_COUNT> MAIN_LOGITECH_MIC_MUTED;
extern const std::array<Info<s16>, EMULATED_LOGITECH_MIC_COUNT> MAIN_LOGITECH_MIC_VOLUME_MODIFIER;
extern const Info<std::string> MAIN_TRIFORCE_IP_REDIRECTIONS;
// Main.WiimoteAudioRouting
static constexpr std::size_t WIIMOTE_SPEAKER_COUNT = 4;
extern const Info<bool> MAIN_WIIMOTE_AUDIO_ROUTING_ENABLED;
extern const std::array<Info<bool>, WIIMOTE_SPEAKER_COUNT> MAIN_WIIMOTE_AUDIO_OUTPUT_ENABLED;
extern const std::array<Info<std::string>, WIIMOTE_SPEAKER_COUNT> MAIN_WIIMOTE_AUDIO_OUTPUT_DEVICE;
// GameCube path utility functions
// Replaces NTSC-K with some other region, and doesn't replace non-NTSC-K regions
DiscIO::Region ToGameCubeRegion(DiscIO::Region region);
// The region argument must be valid for GameCube (i.e. must not be NTSC-K)
enum class RegionDirectoryStyle
{
Legacy,
Modern,
};
const char* GetDirectoryForRegion(DiscIO::Region region,
RegionDirectoryStyle style = RegionDirectoryStyle::Legacy);
std::string GetBootROMPath(const std::string& region_directory);
// Builds the memory card according to the configuration with the given region and size. If the
// given region is std::nullopt, the region in the configured path is used if there is one, or the
// fallback region otherwise.
std::string GetMemcardPath(ExpansionInterface::Slot slot, std::optional<DiscIO::Region> region,
u16 size_mb = 0x80);
std::string GetMemcardPath(std::string configured_filename, ExpansionInterface::Slot slot,
std::optional<DiscIO::Region> region, u16 size_mb = 0x80);
bool IsDefaultMemcardPathConfigured(ExpansionInterface::Slot slot);
std::string GetGCIFolderPath(ExpansionInterface::Slot slot, std::optional<DiscIO::Region> region);
std::string GetGCIFolderPath(std::string configured_folder, ExpansionInterface::Slot slot,
std::optional<DiscIO::Region> region);
bool IsDefaultGCIFolderPathConfigured(ExpansionInterface::Slot slot);
bool AreCheatsEnabled();
bool IsDebuggingEnabled();
} // namespace Config
extern const Info<std::string> MAIN_WII_STARLET_BOOTSTRAP_ELF;
extern const Info<std::string> MAIN_WII_SD_CARD_IMAGE_PATH;
extern const Info<std::string> MAIN_WII_SD_CARD_SYNC_FOLDER_PATH;
extern const Info<std::string> MAIN_WFS_PATH;
extern const Info<bool> MAIN_SHOW_LAG;
extern const Info<bool> MAIN_SHOW_FRAME_COUNT;
extern const Info<std::string> MAIN_WIRELESS_MAC;
extern const Info<std::string> MAIN_GDB_SOCKET;
extern const Info<int> MAIN_GDB_PORT;
extern const Info<int> MAIN_ISO_PATH_COUNT;
extern const Info<std::string> MAIN_SKYLANDERS_PATH;
std::vector<std::string> GetIsoPaths();
void SetIsoPaths(std::span<const std::string> paths);
// Main.GBA
#ifdef HAS_LIBMGBA
extern const Info<std::string> MAIN_GBA_BIOS_PATH;
extern const std::array<Info<std::string>, 5> MAIN_GBA_ROM_PATHS;
extern const Info<std::string> MAIN_GBA_SAVES_PATH;
extern const Info<bool> MAIN_GBA_SAVES_IN_ROM_PATH;
static constexpr std::size_t GBPLAYER_GBA_INDEX = 4;
#endif
// Main.Network
extern const Info<bool> MAIN_NETWORK_SSL_DUMP_READ;
extern const Info<bool> MAIN_NETWORK_SSL_DUMP_WRITE;
extern const Info<bool> MAIN_NETWORK_SSL_VERIFY_CERTIFICATES;
extern const Info<bool> MAIN_NETWORK_SSL_DUMP_ROOT_CA;
extern const Info<bool> MAIN_NETWORK_SSL_DUMP_PEER_CERT;
extern const Info<bool> MAIN_NETWORK_DUMP_BBA;
extern const Info<bool> MAIN_NETWORK_DUMP_AS_PCAP;
extern const Info<int> MAIN_NETWORK_TIMEOUT;
// Main.Interface
extern const Info<bool> MAIN_USE_HIGH_CONTRAST_TOOLTIPS;
extern const Info<bool> MAIN_USE_PANIC_HANDLERS;
extern const Info<bool> MAIN_ABORT_ON_PANIC_ALERT;
extern const Info<bool> MAIN_OSD_MESSAGES;
extern const Info<int> MAIN_OSD_FONT_SIZE;
extern const Info<bool> MAIN_SKIP_NKIT_WARNING;
extern const Info<bool> MAIN_CONFIRM_ON_STOP;
enum class ShowCursor
{
Never,
Constantly,
OnMovement,
};
extern const Info<ShowCursor> MAIN_SHOW_CURSOR;
extern const Info<bool> MAIN_LOCK_CURSOR;
extern const Info<std::string> MAIN_INTERFACE_LANGUAGE;
extern const Info<bool> MAIN_SHOW_ACTIVE_TITLE;
extern const Info<bool> MAIN_USE_BUILT_IN_TITLE_DATABASE;
extern const Info<std::string> MAIN_THEME_NAME;
extern const Info<bool> MAIN_PAUSE_ON_FOCUS_LOST;
extern const Info<bool> MAIN_ENABLE_DEBUGGING;
// Main.Analytics
extern const Info<std::string> MAIN_ANALYTICS_ID;
extern const Info<bool> MAIN_ANALYTICS_ENABLED;
extern const Info<bool> MAIN_ANALYTICS_PERMISSION_ASKED;
// Main.GameList
extern const Info<bool> MAIN_GAMELIST_LIST_DRIVES;
extern const Info<bool> MAIN_GAMELIST_LIST_WAD;
extern const Info<bool> MAIN_GAMELIST_LIST_ELF_DOL;
extern const Info<bool> MAIN_GAMELIST_LIST_WII;
extern const Info<bool> MAIN_GAMELIST_LIST_GC;
extern const Info<bool> MAIN_GAMELIST_LIST_TRI;
extern const Info<bool> MAIN_GAMELIST_LIST_JPN;
extern const Info<bool> MAIN_GAMELIST_LIST_PAL;
extern const Info<bool> MAIN_GAMELIST_LIST_USA;
extern const Info<bool> MAIN_GAMELIST_LIST_AUSTRALIA;
extern const Info<bool> MAIN_GAMELIST_LIST_FRANCE;
extern const Info<bool> MAIN_GAMELIST_LIST_GERMANY;
extern const Info<bool> MAIN_GAMELIST_LIST_ITALY;
extern const Info<bool> MAIN_GAMELIST_LIST_KOREA;
extern const Info<bool> MAIN_GAMELIST_LIST_NETHERLANDS;
extern const Info<bool> MAIN_GAMELIST_LIST_RUSSIA;
extern const Info<bool> MAIN_GAMELIST_LIST_SPAIN;
extern const Info<bool> MAIN_GAMELIST_LIST_TAIWAN;
extern const Info<bool> MAIN_GAMELIST_LIST_WORLD;
extern const Info<bool> MAIN_GAMELIST_LIST_UNKNOWN;
extern const Info<int> MAIN_GAMELIST_LIST_SORT;
extern const Info<int> MAIN_GAMELIST_LIST_SORT_SECONDARY;
extern const Info<bool> MAIN_GAMELIST_COLUMN_PLATFORM;
extern const Info<bool> MAIN_GAMELIST_COLUMN_DESCRIPTION;
extern const Info<bool> MAIN_GAMELIST_COLUMN_BANNER;
extern const Info<bool> MAIN_GAMELIST_COLUMN_TITLE;
extern const Info<bool> MAIN_GAMELIST_COLUMN_MAKER;
extern const Info<bool> MAIN_GAMELIST_COLUMN_FILE_NAME;
extern const Info<bool> MAIN_GAMELIST_COLUMN_FILE_PATH;
extern const Info<bool> MAIN_GAMELIST_COLUMN_GAME_ID;
extern const Info<bool> MAIN_GAMELIST_COLUMN_REGION;
extern const Info<bool> MAIN_GAMELIST_COLUMN_FILE_SIZE;
extern const Info<bool> MAIN_GAMELIST_COLUMN_FILE_FORMAT;
extern const Info<bool> MAIN_GAMELIST_COLUMN_BLOCK_SIZE;
extern const Info<bool> MAIN_GAMELIST_COLUMN_COMPRESSION;
extern const Info<bool> MAIN_GAMELIST_COLUMN_TIME_PLAYED;
extern const Info<bool> MAIN_GAMELIST_COLUMN_TAGS;
// Main.FifoPlayer
extern const Info<bool> MAIN_FIFOPLAYER_LOOP_REPLAY;
extern const Info<bool> MAIN_FIFOPLAYER_EARLY_MEMORY_UPDATES;
// Main.AutoUpdate
extern const Info<std::string> MAIN_AUTOUPDATE_UPDATE_TRACK;
extern const Info<std::string> MAIN_AUTOUPDATE_HASH_OVERRIDE;
// Main.Movie
extern const Info<bool> MAIN_MOVIE_PAUSE_MOVIE;
extern const Info<std::string> MAIN_MOVIE_MOVIE_AUTHOR;
extern const Info<bool> MAIN_MOVIE_DUMP_FRAMES;
extern const Info<bool> MAIN_MOVIE_DUMP_FRAMES_SILENT;
extern const Info<bool> MAIN_MOVIE_SHOW_INPUT_DISPLAY;
extern const Info<bool> MAIN_MOVIE_SHOW_RTC;
extern const Info<bool> MAIN_MOVIE_SHOW_RERECORD;
extern const Info<bool> MAIN_MOVIE_SHOW_OSD;
// Main.Input
extern const Info<bool> MAIN_INPUT_BACKGROUND_INPUT;
extern const Config::Info<std::string> MAIN_SDL_HINT_JOYSTICK_ENHANCED_REPORTS;
extern const Config::Info<std::string> MAIN_SDL_HINT_JOYSTICK_WGI;
extern const Config::Info<std::string> MAIN_SDL_HINT_JOYSTICK_HIDAPI_PS5_PLAYER_LED;
extern const Config::Info<std::string> MAIN_SDL_HINT_JOYSTICK_DIRECTINPUT;
extern const Config::Info<std::string> MAIN_SDL_HINT_JOYSTICK_HIDAPI_COMBINE_JOY_CONS;
extern const Config::Info<std::string> MAIN_SDL_HINT_JOYSTICK_HIDAPI_VERTICAL_JOY_CONS;
// Main.Debug
extern const Info<bool> MAIN_DEBUG_JIT_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_LOAD_STORE_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_LOAD_STORE_LXZ_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_LOAD_STORE_LWZ_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_LOAD_STORE_LBZX_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_LOAD_STORE_FLOATING_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_LOAD_STORE_PAIRED_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_FLOATING_POINT_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_INTEGER_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_PAIRED_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_SYSTEM_REGISTERS_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_BRANCH_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_REGISTER_CACHE_OFF;
extern const Info<bool> MAIN_DEBUG_JIT_ENABLE_PROFILING;
// Main.BluetoothPassthrough
extern const Info<bool> MAIN_BLUETOOTH_PASSTHROUGH_ENABLED;
extern const Info<int> MAIN_BLUETOOTH_PASSTHROUGH_VID;
extern const Info<int> MAIN_BLUETOOTH_PASSTHROUGH_PID;
extern const Info<std::string> MAIN_BLUETOOTH_PASSTHROUGH_LINK_KEYS;
// Main.USBPassthrough
extern const Info<bool> MAIN_USB_PASSTHROUGH_DISGUISE_PLAYSTATION_AS_WII;
extern const Info<std::string> MAIN_USB_PASSTHROUGH_DEVICES;
std::set<USBUtils::DeviceInfo> GetUSBDeviceWhitelist();
void SetUSBDeviceWhitelist(const std::set<USBUtils::DeviceInfo>& devices);
// Main.EmulatedUSBDevices
extern const Info<bool> MAIN_EMULATE_SKYLANDER_PORTAL;
extern const Info<bool> MAIN_EMULATE_INFINITY_BASE;
extern const Info<bool> MAIN_EMULATE_WII_SPEAK;
extern const Info<std::string> MAIN_WII_SPEAK_MICROPHONE;
extern const Info<bool> MAIN_WII_SPEAK_MUTED;
extern const Info<s16> MAIN_WII_SPEAK_VOLUME_MODIFIER;
static constexpr std::size_t EMULATED_LOGITECH_MIC_COUNT = 4;
extern const std::array<Info<bool>, EMULATED_LOGITECH_MIC_COUNT> MAIN_EMULATE_LOGITECH_MIC;
extern const std::array<Info<std::string>, EMULATED_LOGITECH_MIC_COUNT>
MAIN_LOGITECH_MIC_MICROPHONE;
extern const std::array<Info<bool>, EMULATED_LOGITECH_MIC_COUNT> MAIN_LOGITECH_MIC_MUTED;
extern const std::array<Info<s16>, EMULATED_LOGITECH_MIC_COUNT> MAIN_LOGITECH_MIC_VOLUME_MODIFIER;
extern const Info<std::string> MAIN_TRIFORCE_IP_REDIRECTIONS;
// Main.WiimoteAudioRouting
static constexpr std::size_t WIIMOTE_SPEAKER_COUNT = 4;
extern const Info<bool> MAIN_WIIMOTE_AUDIO_ROUTING_ENABLED;
extern const std::array<Info<bool>, WIIMOTE_SPEAKER_COUNT> MAIN_WIIMOTE_AUDIO_OUTPUT_ENABLED;
extern const std::array<Info<std::string>, WIIMOTE_SPEAKER_COUNT> MAIN_WIIMOTE_AUDIO_OUTPUT_DEVICE;
// GameCube path utility functions
// Replaces NTSC-K with some other region, and doesn't replace non-NTSC-K regions
DiscIO::Region ToGameCubeRegion(DiscIO::Region region);
// The region argument must be valid for GameCube (i.e. must not be NTSC-K)
enum class RegionDirectoryStyle
{
Legacy,
Modern,
};
const char* GetDirectoryForRegion(DiscIO::Region region,
RegionDirectoryStyle style = RegionDirectoryStyle::Legacy);
std::string GetBootROMPath(const std::string& region_directory);
// Builds the memory card according to the configuration with the given region and size. If the
// given region is std::nullopt, the region in the configured path is used if there is one, or the
// fallback region otherwise.
std::string GetMemcardPath(ExpansionInterface::Slot slot, std::optional<DiscIO::Region> region,
u16 size_mb = 0x80);
std::string GetMemcardPath(std::string configured_filename, ExpansionInterface::Slot slot,
std::optional<DiscIO::Region> region, u16 size_mb = 0x80);
bool IsDefaultMemcardPathConfigured(ExpansionInterface::Slot slot);
std::string GetGCIFolderPath(ExpansionInterface::Slot slot, std::optional<DiscIO::Region> region);
std::string GetGCIFolderPath(std::string configured_folder, ExpansionInterface::Slot slot,
std::optional<DiscIO::Region> region);
bool IsDefaultGCIFolderPathConfigured(ExpansionInterface::Slot slot);
bool AreCheatsEnabled();
bool IsDebuggingEnabled();
} // namespace Config
File diff suppressed because it is too large. Load diff
+159 -159
View File
@@ -1,159 +1,159 @@
// Copyright 2008 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "Core/HW/HW.h"
#include <memory>
#include <string>
#include "Common/ChunkFile.h"
#include "Common/MsgHandler.h"
#include "Core/Config/MainSettings.h"
#include "Core/Core.h"
#include "Core/CoreTiming.h"
#include "Core/HW/AddressSpace.h"
#include "Core/HW/AudioInterface.h"
#include "Core/HW/CPU.h"
#include "Core/HW/DSP.h"
#include "Core/HW/DVD/DVDInterface.h"
#include "Core/HW/EXI/EXI.h"
#include "Core/HW/GPFifo.h"
#include "Core/HW/HSP/HSP.h"
#include "Core/HW/Memmap.h"
#include "Core/HW/MemoryInterface.h"
#include "Core/HW/ProcessorInterface.h"
#include "Core/HW/SI/SI.h"
#include "Core/HW/SystemTimers.h"
#include "Core/HW/VideoInterface.h"
#include "Core/HW/WII_IPC.h"
#include "Core/IOS/IOS.h"
#include "Core/IOS/Starlet/Starlet.h"
#include "Core/State.h"
#include "Core/System.h"
namespace HW
{
void Init(Core::System& system, const Sram* override_sram)
{
system.GetCoreTiming().Init();
system.GetSystemTimers().PreInit();
State::Init(system);
// Init the whole Hardware
system.GetAudioInterface().Init();
system.GetVideoInterface().Init();
system.GetSerialInterface().Init();
system.GetProcessorInterface().Init();
system.GetExpansionInterface().Init(override_sram); // Needs to be initialized before Memory
system.GetHSP().Init();
system.GetMemory().Init(); // Needs to be initialized before AddressSpace
AddressSpace::Init();
system.GetMemoryInterface().Init();
system.GetDSP().Init(Config::Get(Config::MAIN_DSP_HLE));
system.GetDVDInterface().Init();
system.GetGPFifo().Init();
system.GetCPU().Init(Config::Get(Config::MAIN_CPU_CORE));
system.GetSystemTimers().Init();
if (system.IsWii())
{
system.GetWiiIPC().Init();
if (Config::Get(Config::MAIN_WII_IOS_LLE))
{
auto starlet = std::make_unique<IOS::LLE::Starlet>(system);
std::string error;
if (starlet->Init(Config::Get(Config::MAIN_WII_LLE_DUMP_PATH), &error))
{
system.SetStarlet(std::move(starlet));
system.GetWiiIPC().HoldBroadwayForStarletBoot();
}
else
{
PanicAlertFmtT("Could not start Wii IOS LLE: {0}", error);
Core::SetState(system, Core::State::Stopping);
return;
}
}
else
{
IOS::HLE::Init(system); // Depends on Memory
}
}
system.GetMemory().InitMMIO(system);
}
void Shutdown(Core::System& system)
{
// IOS should always be shut down regardless of IsWii because it can be running in GC mode (MIOS).
if (system.GetStarlet())
{
system.GetStarlet()->Shutdown();
system.SetStarlet(nullptr);
}
if (system.GetIOS())
IOS::HLE::Shutdown(system); // Depends on Memory
system.GetWiiIPC().Shutdown();
system.GetSystemTimers().Shutdown();
system.GetCPU().Shutdown();
system.GetDVDInterface().Shutdown();
system.GetDSP().Shutdown();
system.GetMemoryInterface().Shutdown();
AddressSpace::Shutdown();
system.GetMemory().Shutdown();
system.GetHSP().Shutdown();
system.GetExpansionInterface().Shutdown();
system.GetSerialInterface().Shutdown();
system.GetAudioInterface().Shutdown();
State::Shutdown();
system.GetCoreTiming().Shutdown();
}
void DoState(Core::System& system, PointerWrap& p)
{
system.GetMemory().DoState(p);
p.DoMarker("Memory");
system.GetMemoryInterface().DoState(p);
p.DoMarker("MemoryInterface");
system.GetVideoInterface().DoState(p);
p.DoMarker("VideoInterface");
system.GetSerialInterface().DoState(p);
p.DoMarker("SerialInterface");
system.GetProcessorInterface().DoState(p);
p.DoMarker("ProcessorInterface");
system.GetDSP().DoState(p);
p.DoMarker("DSP");
system.GetDVDInterface().DoState(p);
p.DoMarker("DVDInterface");
system.GetGPFifo().DoState(p);
p.DoMarker("GPFifo");
system.GetExpansionInterface().DoState(p);
p.DoMarker("ExpansionInterface");
system.GetAudioInterface().DoState(p);
p.DoMarker("AudioInterface");
system.GetHSP().DoState(p);
p.DoMarker("HSP");
if (system.IsWii())
{
system.GetWiiIPC().DoState(p);
p.DoMarker("IOS");
if (system.GetStarlet())
{
system.GetStarlet()->DoState(p);
p.DoMarker("IOS::LLE");
}
else if (system.GetIOS())
{
system.GetIOS()->DoState(p);
p.DoMarker("IOS::HLE");
}
}
p.DoMarker("WIIHW");
}
} // namespace HW
// Copyright 2008 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "Core/HW/HW.h"
#include <memory>
#include <string>
#include "Common/ChunkFile.h"
#include "Common/MsgHandler.h"
#include "Core/Config/MainSettings.h"
#include "Core/Core.h"
#include "Core/CoreTiming.h"
#include "Core/HW/AddressSpace.h"
#include "Core/HW/AudioInterface.h"
#include "Core/HW/CPU.h"
#include "Core/HW/DSP.h"
#include "Core/HW/DVD/DVDInterface.h"
#include "Core/HW/EXI/EXI.h"
#include "Core/HW/GPFifo.h"
#include "Core/HW/HSP/HSP.h"
#include "Core/HW/Memmap.h"
#include "Core/HW/MemoryInterface.h"
#include "Core/HW/ProcessorInterface.h"
#include "Core/HW/SI/SI.h"
#include "Core/HW/SystemTimers.h"
#include "Core/HW/VideoInterface.h"
#include "Core/HW/WII_IPC.h"
#include "Core/IOS/IOS.h"
#include "Core/IOS/Starlet/Starlet.h"
#include "Core/State.h"
#include "Core/System.h"
namespace HW
{
void Init(Core::System& system, const Sram* override_sram)
{
system.GetCoreTiming().Init();
system.GetSystemTimers().PreInit();
State::Init(system);
// Init the whole Hardware
system.GetAudioInterface().Init();
system.GetVideoInterface().Init();
system.GetSerialInterface().Init();
system.GetProcessorInterface().Init();
system.GetExpansionInterface().Init(override_sram); // Needs to be initialized before Memory
system.GetHSP().Init();
system.GetMemory().Init(); // Needs to be initialized before AddressSpace
AddressSpace::Init();
system.GetMemoryInterface().Init();
system.GetDSP().Init(Config::Get(Config::MAIN_DSP_HLE));
system.GetDVDInterface().Init();
system.GetGPFifo().Init();
system.GetCPU().Init(Config::Get(Config::MAIN_CPU_CORE));
system.GetSystemTimers().Init();
if (system.IsWii())
{
system.GetWiiIPC().Init();
if (Config::Get(Config::MAIN_WII_IOS_LLE))
{
auto starlet = IOS::LLE::Starlet::Create(system);
std::string error;
if (starlet->Init(Config::Get(Config::MAIN_WII_LLE_DUMP_PATH), &error))
{
system.SetStarlet(std::move(starlet));
system.GetWiiIPC().HoldBroadwayForStarletBoot();
}
else
{
PanicAlertFmtT("Could not start Wii IOS LLE: {0}", error);
Core::SetState(system, Core::State::Stopping);
return;
}
}
else
{
IOS::HLE::Init(system); // Depends on Memory
}
}
system.GetMemory().InitMMIO(system);
}
void Shutdown(Core::System& system)
{
// IOS should always be shut down regardless of IsWii because it can be running in GC mode (MIOS).
if (system.GetStarlet())
{
system.GetStarlet()->Shutdown();
system.SetStarlet(nullptr);
}
if (system.GetIOS())
IOS::HLE::Shutdown(system); // Depends on Memory
system.GetWiiIPC().Shutdown();
system.GetSystemTimers().Shutdown();
system.GetCPU().Shutdown();
system.GetDVDInterface().Shutdown();
system.GetDSP().Shutdown();
system.GetMemoryInterface().Shutdown();
AddressSpace::Shutdown();
system.GetMemory().Shutdown();
system.GetHSP().Shutdown();
system.GetExpansionInterface().Shutdown();
system.GetSerialInterface().Shutdown();
system.GetAudioInterface().Shutdown();
State::Shutdown();
system.GetCoreTiming().Shutdown();
}
void DoState(Core::System& system, PointerWrap& p)
{
system.GetMemory().DoState(p);
p.DoMarker("Memory");
system.GetMemoryInterface().DoState(p);
p.DoMarker("MemoryInterface");
system.GetVideoInterface().DoState(p);
p.DoMarker("VideoInterface");
system.GetSerialInterface().DoState(p);
p.DoMarker("SerialInterface");
system.GetProcessorInterface().DoState(p);
p.DoMarker("ProcessorInterface");
system.GetDSP().DoState(p);
p.DoMarker("DSP");
system.GetDVDInterface().DoState(p);
p.DoMarker("DVDInterface");
system.GetGPFifo().DoState(p);
p.DoMarker("GPFifo");
system.GetExpansionInterface().DoState(p);
p.DoMarker("ExpansionInterface");
system.GetAudioInterface().DoState(p);
p.DoMarker("AudioInterface");
system.GetHSP().DoState(p);
p.DoMarker("HSP");
if (system.IsWii())
{
system.GetWiiIPC().DoState(p);
p.DoMarker("IOS");
if (system.GetStarlet())
{
system.GetStarlet()->DoState(p);
p.DoMarker("IOS::LLE");
}
else if (system.GetIOS())
{
system.GetIOS()->DoState(p);
p.DoMarker("IOS::HLE");
}
}
p.DoMarker("WIIHW");
}
} // namespace HW
+155 -1
View File
@@ -3,6 +3,10 @@
#include "Core/HW/WII_IPC.h"
#include <algorithm>
#include <cstdlib>
#include <string>
#include "Common/ChunkFile.h"
#include "Common/CommonTypes.h"
#include "Common/Logging/Log.h"
@@ -10,6 +14,7 @@
#include "Core/CoreTiming.h"
#include "Core/HW/DVD/DVDInterface.h"
#include "Core/HW/MMIO.h"
#include "Core/HW/Memmap.h"
#include "Core/HW/ProcessorInterface.h"
#include "Core/IOS/IOS.h"
#include "Core/IOS/Starlet/Starlet.h"
@@ -136,12 +141,156 @@ void WiiIPC::Reset()
{
INFO_LOG_FMT(WII_IPC, "Resetting ...");
InitState();
m_starlet_attached = false;
}
void WiiIPC::Shutdown()
{
}
namespace
{
// StarletOS phase 11 (proposal L2): with DOLPHIN_IPC_TRACE=1 while the emulated Starlet runs
// (the original IOS or a bootstrap ELF), each IPC request Broadway posts (X1) and each reply
// Starlet posts (Y1) is logged with its metadata only: the command, the descriptor and the five
// argument words (an OPEN's path), then the reply's result. Proposal M1e adds the paths of the
// filesystem IOCTLs. No other buffer content is read.
bool IPCTraceEnabled()
{
static const bool enabled = [] {
const char* value = std::getenv("DOLPHIN_IPC_TRACE");
return value != nullptr && value[0] == '1';
}();
return enabled;
}
// A NUL-terminated absolute path of printable bytes in a 64-byte field, or "" otherwise.
std::string TracePath(Memory::MemoryManager& memory, u32 address)
{
if (memory.GetPointerForRange(address, 64) == nullptr)
return {};
const std::string path = memory.GetString(address, 64);
if (path.empty() || path.size() >= 64 || path[0] != '/' ||
!std::ranges::all_of(path, [](char c) { return c >= 0x20 && c < 0x7f; }))
return {};
return path;
}
// The paths a filesystem request names, by its input shape: a 64-byte path (DELETE, GET_ATTR),
// a 76-byte attribute record with the path at +6 (CREATE_DIR, CREATE_FILE, SET_ATTR), two
// 64-byte paths (RENAME), or an IOCTLV whose first input vector is a 64-byte path (READ_DIR,
// GET_USAGE). " F -" when the field holds no valid path.
std::string TraceFilesystemPaths(Memory::MemoryManager& memory, u32 command, const u32* arg)
{
const auto field = [&memory](u32 address) {
const std::string path = TracePath(memory, address);
return path.empty() ? std::string("-") : path;
};
if (command == 6)
{
if (arg[2] == 0x40)
return " F " + field(arg[1]);
if (arg[2] == 0x4c)
return " F " + field(arg[1] + 6);
if (arg[2] == 0x80)
return " F " + field(arg[1]) + " > " + field(arg[1] + 0x40);
}
else if (command == 7 && arg[1] != 0 && memory.GetPointerForRange(arg[3], 8) != nullptr &&
memory.Read_U32(arg[3] + 4) == 0x40)
{
return " F " + field(memory.Read_U32(arg[3]));
}
return {};
}
// Phase 11 J1: the shutdown request whose reply opens the hardware window, and the window's
// access count.
u32 s_hardware_trigger = 0;
u32 s_hardware_accesses = 0;
constexpr u32 HARDWARE_WINDOW_LIMIT = 20000;
void CloseHardwareWindow(const char* why)
{
if (!g_starletos_hardware_window)
return;
g_starletos_hardware_window = false;
NOTICE_LOG_FMT(WII_IPC, "HWTRACE close {} after {} accesses", why, s_hardware_accesses);
}
void TraceIPCRequest(Core::System& system, u32 address)
{
if (StarletOSHardwareTraceRequested())
CloseHardwareWindow("at the next request");
auto& memory = system.GetMemory();
if (memory.GetPointerForRange(address, 0x20) == nullptr)
{
NOTICE_LOG_FMT(WII_IPC, "IPCTRACE RQ {:08x} unreadable", address);
return;
}
const u32 command = memory.Read_U32(address);
const u32 fd = memory.Read_U32(address + 8);
u32 arg[5];
for (u32 i = 0; i < 5; ++i)
arg[i] = memory.Read_U32(address + 0xc + 4 * i);
std::string path;
if (command == 1 && memory.GetPointerForRange(arg[0], 64) != nullptr)
path = " P " + memory.GetString(arg[0], 64);
else
path = TraceFilesystemPaths(memory, command, arg);
NOTICE_LOG_FMT(WII_IPC, "IPCTRACE RQ {:08x} C {} FD {} A {:08x} {:08x} {:08x} {:08x} {:08x}{}",
address, command, static_cast<s32>(fd), arg[0], arg[1], arg[2], arg[3], arg[4],
path);
if (StarletOSHardwareTraceRequested() && command == 6 && arg[0] == 0x28 && arg[2] == 0x20 &&
arg[4] == 0x20)
{
s_hardware_trigger = address;
}
}
void TraceIPCReply(Core::System& system, u32 address)
{
auto& memory = system.GetMemory();
if (memory.GetPointerForRange(address, 0x10) == nullptr)
{
NOTICE_LOG_FMT(WII_IPC, "IPCTRACE RP {:08x} unreadable", address);
return;
}
NOTICE_LOG_FMT(WII_IPC, "IPCTRACE RP {:08x} C {} RC {}", address, memory.Read_U32(address + 8),
static_cast<s32>(memory.Read_U32(address + 4)));
if (StarletOSHardwareTraceRequested() && s_hardware_trigger != 0 &&
address == s_hardware_trigger)
{
s_hardware_trigger = 0;
s_hardware_accesses = 0;
g_starletos_hardware_window = true;
NOTICE_LOG_FMT(WII_IPC, "HWTRACE open at the reply {:08x}", address);
}
}
} // namespace
bool g_starletos_hardware_window = false;
bool StarletOSHardwareTraceRequested()
{
static const bool requested = [] {
const char* value = std::getenv("DOLPHIN_HW_WINDOW");
return IPCTraceEnabled() && value != nullptr && value[0] == '1';
}();
return requested;
}
void TraceStarletOSHardwareAccess(Core::System& system, bool write, u32 address, u32 size,
u64 value)
{
if (++s_hardware_accesses > HARDWARE_WINDOW_LIMIT)
{
CloseHardwareWindow("at the access limit");
return;
}
NOTICE_LOG_FMT(WII_IPC, "HWTRACE {} {:08x}/{} {:0{}x} PC {:08x}", write ? 'W' : 'R', address,
size, value, size * 2, system.GetPPCState().pc);
}
void WiiIPC::RegisterMMIO(MMIO::Mapping* mmio, u32 base)
{
// Both IPC message registers are general-purpose read/write registers on
@@ -168,6 +317,8 @@ void WiiIPC::RegisterMMIO(MMIO::Mapping* mmio, u32 base)
wii_ipc.m_ppc_irq_flags |= INT_CAUSE_IPC_BROADWAY;
if (wii_ipc.m_ctrl.X1)
{
if (system.GetStarlet() && IPCTraceEnabled() && (val >> 0 & 1))
TraceIPCRequest(system, wii_ipc.m_ppc_msg);
if (system.GetStarlet())
wii_ipc.m_arm_irq_flags |= INT_CAUSE_IPC_STARLET;
else if (system.GetIOS())
@@ -328,7 +479,7 @@ void WiiIPC::UpdateInterrupts()
if ((m_ctrl.X1 & m_ctrl.IX1) || (m_ctrl.X2 & m_ctrl.IX2))
{
if (m_system.GetStarlet())
if (m_system.GetStarlet() || m_starlet_attached)
m_arm_irq_flags |= INT_CAUSE_IPC_STARLET;
else
m_ppc_irq_flags |= INT_CAUSE_IPC_STARLET;
@@ -386,6 +537,9 @@ void WiiIPC::WriteStarletRegister(u32 offset, u32 value)
break;
case IPC_ARMCTRL:
m_ctrl.arm(value);
// StarletOS phase 11: Y1 (bit 0) posts the reply whose pointer is in ARMMSG.
if (IPCTraceEnabled() && (value & 1))
TraceIPCReply(m_system, m_arm_msg);
break;
case PPC_IRQFLAG:
m_ppc_irq_flags &= ~value;
+12
View File
@@ -123,6 +123,14 @@ struct CtrlRegister
}
};
// StarletOS phase 11 (J1), emulator only: with DOLPHIN_IPC_TRACE=1 and DOLPHIN_HW_WINDOW=1,
// Broadway's hardware register accesses (MMIO) are logged from the reply to a WiiConnect24
// shutdown request (IOCTL 0x28, 32-byte input and output) until Broadway's next IPC request.
bool StarletOSHardwareTraceRequested();
extern bool g_starletos_hardware_window;
void TraceStarletOSHardwareAccess(Core::System& system, bool write, u32 address, u32 size,
u64 value);
class WiiIPC
{
public:
@@ -156,6 +164,9 @@ public:
bool IsStarletIRQAsserted() const;
bool IsStarletFIQAsserted() const;
void SetStarletInterrupt(u32 cause, bool asserted);
// Set by a tool that runs an ARMCore with no IOS::LLE::Starlet object in the System, for
// UpdateInterrupts to raise the Starlet's IPC cause all the same. Reset clears it.
void SetStarletAttached(bool attached) { m_starlet_attached = attached; }
Common::Flags<GPIO> GetGPIOOutFlags() const { return m_gpio_out; }
@@ -181,6 +192,7 @@ private:
u32 m_resets = 0;
bool m_broadway_in_reset = false;
bool m_starlet_attached = false;
CoreTiming::EventType* m_event_type_update_interrupts = nullptr;
File diff suppressed because it is too large. Load diff
+82 -4
View File
@@ -7,6 +7,7 @@
#include <cstddef>
#include <memory>
#include <unordered_map>
#include <utility>
#include <vector>
#include "Common/CommonTypes.h"
@@ -59,6 +60,9 @@ public:
// Returns Dolphin's 4 GiB physical fastmem view when this bus is backed by Wii RAM. Device,
// boot-ROM and SRAM addresses must still use the bus callbacks.
virtual u8* GetFastmemBase() const { return nullptr; }
// StarletOS phase 11 (F1): physical (start, size) ranges whose accesses must stay on the bus
// even under fastmem, so a write watch sees them with their instruction address.
virtual std::vector<std::pair<u32, u32>> GetWatchRanges() const { return {}; }
// Optional direct Starlet SRAM view. The two state pointers let generated code preserve the
// boot0 overlay and SRAM A/B split mapping exactly while avoiding a host call for ordinary SRAM.
virtual u8* GetFastmemSRAMBase() const { return nullptr; }
@@ -112,7 +116,8 @@ public:
static constexpr u32 CPSR_T = 1U << 5;
static constexpr u32 CPSR_MODE_MASK = 0x1f;
explicit ARMCore(ARMBus& bus);
// Host-only diagnostic choice, fixed for this core's lifetime and not part of guest state.
explicit ARMCore(ARMBus& bus, bool profile_jit_memory = false);
~ARMCore();
void Reset(u32 reset_vector = 0);
@@ -124,6 +129,8 @@ public:
u32 GetRegister(size_t index) const;
void SetRegister(size_t index, u32 value);
u32 GetCPSR() const { return m_cpsr; }
// The address of the instruction being executed (interpreter).
u32 GetInstructionAddress() const { return m_instruction_address; }
void SetCPSR(u32 value);
Mode GetMode() const;
@@ -152,6 +159,8 @@ public:
}
bool IsWaitingForInterrupt() const { return m_waiting_for_interrupt; }
bool IsWaitingForMemoryPoll() const { return m_waiting_for_memory_poll; }
bool IsIRQLineAsserted() const { return m_irq_line; }
bool IsFIQLineAsserted() const { return m_fiq_line; }
u32 GetMemoryPollAddress() const { return m_memory_poll_address; }
bool IsWaitingForExternalEvent() const
{
@@ -165,6 +174,17 @@ public:
u64 GetExecutedInstructions() const { return m_executed_instructions; }
void SetJitEnabled(bool enabled);
bool IsJitEnabled() const { return m_jit_enabled; }
// StarOS MMU-001 (F1): the ARM926 MMU's aborts and the CP15 privilege rule. When enabled, a
// translation, domain or permission fault (and, with control bit A, an alignment fault) raises
// a data abort (FSR c5 opcode2 0, FAR c6) or a prefetch abort (IFSR c5 opcode2 1; FAR left
// unchanged), access permissions follow AP, the S and R control bits and the DACR, TLB entries
// can be invalidated one MVA at a time, and CP15 from User mode is undefined. Off by default:
// the IOS LLE path keeps its identity fallback for fault descriptors and its savestate format.
void SetMMUFaultsEnabled(bool enabled);
bool AreMMUFaultsEnabled() const { return m_mmu_faults; }
u32 GetInstructionFaultStatus() const { return m_instruction_fault_status; }
bool IsJitMemoryProfilingEnabled() const { return m_profile_jit_memory; }
u64 GetTraceGeneration() const { return m_trace_generation; }
u64 GetJitExecutedInstructions() const;
u64 GetJitNativeExecutedInstructions() const;
size_t GetJitCompiledBlockCount() const;
@@ -237,6 +257,26 @@ private:
u32 virtual_page = 0;
u32 physical_page = 0;
u32 generation = 0;
// Filled only with MMU faults enabled: the descriptor's domain (bits 3:0), the AP of this
// 1 KiB granule (5:4), whether it came from a second-level page (bit 6), and log2 of the
// size the descriptor maps (15:8), so that one MVA invalidation drops its whole page.
u32 protection = 0;
};
enum class AccessKind
{
Read,
Write,
Fetch,
};
// The result of a page-table walk with MMU faults enabled.
struct CheckedWalk
{
u32 physical_address = 0;
// 0, or the FSR value of a translation fault: status in bits 3:0, domain in bits 7:4.
u32 fault_status = 0;
u32 protection = 0;
};
struct InstructionCacheEntry
@@ -282,6 +322,20 @@ private:
u32* second_descriptor_value) const;
u32 ReadPhysical32(u32 address) const;
void InvalidateTLB();
// MMU faults enabled only.
u32 ModifiedVirtualAddress(u32 address) const;
CheckedWalk WalkPageTablesChecked(u32 modified_address) const;
const TLBEntry* LookupTLBChecked(u32 modified_address, u32* fault_status) const;
u32 PermissionFault(const TLBEntry& entry, AccessKind kind, bool user) const;
bool IsUserAccess() const;
u32 DataAddress(u32 address, bool write) const;
void RaiseDataAbort(u32 fault_status, u32 modified_address) const;
void CheckAlignment(u32 address, u32 mask) const;
bool TryTranslateFetch(u32 address, u32* physical_address, u32* fault_status) const;
bool EnterPrefetchAbortIfFaulted(u32 address);
void ExecuteARMWithAborts(u32 instruction);
void ExecuteThumbWithAborts(u16 instruction);
void InvalidateTLBEntry(u32 modified_address);
u16 FetchThumbInstruction(u32 address);
u32 FetchARMInstruction(u32 address);
void InvalidateInstructionCache();
@@ -302,8 +356,12 @@ private:
void ExecuteSingleDataTransfer(u32 instruction);
void ExecuteHalfwordDataTransfer(u32 instruction);
void ExecuteBlockDataTransfer(u32 instruction);
// Phase 11 H1: a register-list transfer overlapping a watched range, with its translation.
void TraceWatchedBlockTransfer(u32 address, u32 size, bool load) const;
void ExecuteMultiply(u32 instruction);
void ExecuteMultiplyLong(u32 instruction);
// ARMv5TE signed halfword multiplies and saturating arithmetic.
void ExecuteEnhancedDSP(u32 instruction);
void ExecuteBranch(u32 instruction);
void ExecuteCoprocessor(u32 instruction);
void ExecutePSRTransfer(u32 instruction);
@@ -322,6 +380,8 @@ private:
void WriteCP15(u32 opcode1, u32 crn, u32 crm, u32 opcode2, u32 value);
ARMBus& m_bus;
const bool m_profile_jit_memory;
u64 m_trace_generation = 0; // Host diagnostics only; never serialized.
std::array<u32, 16> m_registers{};
u32 m_cpsr = 0;
@@ -341,9 +401,13 @@ private:
u32 m_spsr_und = 0;
CP15State m_cp15{};
// ARM926 has separate instruction/data TLBs. A unified 1 KiB-granularity
// software cache keeps the observable translations while avoiding a
// page-table walk on every interpreted access.
// The ARM926EJ-S has one TLB for instructions and data: set-associative main entries plus
// lockdown entries (c10) that whole-TLB invalidation preserves (ARM926EJ-S TRM). This software
// TLB is unified too, but it is a 4096-entry direct-mapped cache of 1 KiB granules, so its
// capacity and replacement differ: an entry can stay here after the hardware would have
// replaced it, or be replaced here while the hardware keeps it. Lockdown is not modelled (c10
// writes are ignored). It keeps the observable translations while avoiding a page-table walk on
// every interpreted access.
mutable std::array<TLBEntry, TLB_ENTRY_COUNT> m_tlb{};
std::array<InstructionCacheEntry, INSTRUCTION_CACHE_ENTRY_COUNT> m_instruction_cache{};
mutable u32 m_tlb_generation = 1;
@@ -358,6 +422,8 @@ private:
u32 m_memory_poll_address = 0;
bool m_pc_written = false;
u32 m_instruction_address = 0;
// Phase 11 H1: the bus's watched ranges (REV_WATCH), empty when off.
std::vector<std::pair<u32, u32>> m_watch_ranges;
u32 m_last_undefined_instruction = 0;
u64 m_executed_instructions = 0;
u64 m_memory_poll_entry_count = 0;
@@ -369,6 +435,18 @@ private:
u64 m_next_profile_instruction = PROFILE_SAMPLE_INTERVAL;
std::unordered_map<u32, u64> m_pc_samples;
bool m_jit_enabled = false;
// StarOS MMU-001 (F1). Not serialized: the option is a host choice made before the run, and
// the IOS LLE savestate format stays unchanged.
bool m_mmu_faults = false;
u32 m_instruction_fault_status = 0;
// Set by LDRT/STRT/LDRBT/STRBT around their access: User permissions in a privileged mode.
bool m_user_access = false;
// The first faulting access of an instruction records its abort here. Later accesses of the
// same instruction neither read nor write the bus, and the instruction's register results are
// undone before the data abort is taken (ARM926 base-restored abort model).
mutable bool m_abort_pending = false;
mutable u32 m_abort_status = 0;
mutable u32 m_abort_address = 0;
#if defined(_M_X86_64)
std::unique_ptr<ARMJitX64> m_jit;
#endif
+218 -89
View File
@@ -10,6 +10,7 @@
#include "Common/BitSet.h"
#include "Common/CommonTypes.h"
#include "Common/PerformanceTrace.h"
#include "Common/x64ABI.h"
#include "Core/HW/Memmap.h"
#include "Core/IOS/Starlet/ARMCore.h"
@@ -55,6 +56,7 @@ SlowMemoryRegion ClassifySlowMemoryAddress(u32 address)
ARMJitX64::ARMJitX64(ARMCore& core) : m_core(core)
{
m_fastmem_base = m_core.m_bus.GetFastmemBase();
m_watch_ranges = m_core.m_bus.GetWatchRanges();
// SRAM is a plain Hollywood memory array just like MEM1/MEM2. The generated address checks
// below still side-exit for boot0 overlays and the unmapped split-window gap, so only actual
// SRAM reaches this pointer; MMIO and ROM writes retain the exact bus path.
@@ -94,6 +96,7 @@ ARMJitX64::ARMJitX64(ARMCore& core) : m_core(core)
ARMJitX64::~ARMJitX64()
{
Common::PerformanceTrace::CodeReset("ARM", this, region, region + region_size);
FreeCodeSpace();
}
@@ -128,6 +131,7 @@ void ARMJitX64::RequestClear()
void ARMJitX64::ClearCodeCache()
{
Common::PerformanceTrace::CodeReset("ARM", this, m_block_code_begin, region + region_size);
m_discarded_block_count += m_blocks.size();
m_blocks.clear();
std::ranges::fill(m_fast_entries, FastEntry{});
@@ -150,6 +154,7 @@ void ARMJitX64::InvalidateTranslationContext()
u32 ARMJitX64::Run(u64 cycle_budget)
{
const Common::PerformanceTrace::Scope trace(Common::PerformanceTrace::Region::Jit);
if (cycle_budget == 0 || !m_run_entry)
return 0;
@@ -189,6 +194,11 @@ void ARMJitX64::GenerateDispatcher()
MOV(64, R(RAX), ImmPtr(&m_clear_pending));
CMP(8, MatR(RAX), Imm8(0));
FixupBranch invalidated = J_CC(CC_NE, Jump::Near);
// With MMU faults enabled, every block entry goes through C++, which checks the fetch under the
// current mode and DACR: the native caches below validate descriptors, not permissions.
MOV(64, R(RAX), ImmPtr(&m_core.m_mmu_faults));
CMP(8, MatR(RAX), Imm8(0));
FixupBranch checked_dispatch = J_CC(CC_NE, Jump::Near);
// Four-way native block cache. The key includes CPSR.T in bit zero and uses the ARM926 modified
// virtual address (MVA) for low FCSE addresses. Different IOS process identifiers can therefore
@@ -374,6 +384,11 @@ void ARMJitX64::GenerateDispatcher()
MOV(32, R(ABI_PARAM3), R(EAX));
MOV(32, R(ABI_PARAM2), Imm32(static_cast<u32>(DispatchReason::PageMiss)));
FixupBranch dispatch_reason_page = J(Jump::Near);
SetJumpTarget(checked_dispatch);
XOR(32, R(ABI_PARAM4), R(ABI_PARAM4));
XOR(32, R(ABI_PARAM3), R(ABI_PARAM3));
MOV(32, R(ABI_PARAM2), Imm32(static_cast<u32>(DispatchReason::Checked)));
FixupBranch dispatch_reason_checked = J(Jump::Near);
SetJumpTarget(empty_entry);
SetJumpTarget(empty_entry_no_mmu);
MOV(32, R(ABI_PARAM4), R(EDX));
@@ -382,6 +397,7 @@ void ARMJitX64::GenerateDispatcher()
SetJumpTarget(dispatch_reason_translation);
SetJumpTarget(dispatch_reason_key);
SetJumpTarget(dispatch_reason_page);
SetJumpTarget(dispatch_reason_checked);
MOV(64, R(ABI_PARAM1), ImmPtr(this));
ABI_CallFunction(Dispatch);
TEST(64, R(RAX), R(RAX));
@@ -405,6 +421,7 @@ void ARMJitX64::GenerateDispatcher()
RET();
m_block_code_begin = AlignCode16();
Common::PerformanceTrace::CodeMap("ARM", this, region, m_block_code_begin, 0, 0, "dispatcher");
}
u32 ARMJitX64::MakeFastEntryKey(u32 address, u32 control, u32 process_id)
@@ -421,9 +438,62 @@ size_t ARMJitX64::GetFastEntrySetIndex(u32 key)
return static_cast<u32>(key * 0x9e3779b1U) >> 16;
}
const u8* ARMJitX64::DispatchChecked(ARMJitX64* jit)
{
ARMCore& core = jit->m_core;
++jit->m_dispatch_slow_count;
u32 physical_address = 0;
u32 fault_status = 0;
// A fetch that faults is left to the interpreter, whose next step takes the prefetch abort.
if (!core.TryTranslateFetch(core.m_registers[15], &physical_address, &fault_status))
return nullptr;
const bool thumb = (core.m_cpsr & ARMCore::CPSR_T) != 0;
const u8* first_descriptor = nullptr;
const u8* second_descriptor = nullptr;
u32 first_descriptor_value = 0;
u32 second_descriptor_value = 0;
// No fast entry is recorded: the generated dispatcher sends the next entry here again.
Block* const block = jit->GetOrCompileBlock(
core.m_registers[15] | (thumb ? 1U : 0U), &physical_address, &first_descriptor,
&first_descriptor_value, &second_descriptor, &second_descriptor_value);
return block && block->runnable ? block->entry : nullptr;
}
bool ARMJitX64::IsCheckedNativeARM(u32 instruction)
{
if ((instruction >> 28) == 0xf)
return false;
// B and BL.
if ((instruction & 0x0e000000) == 0x0a000000)
return true;
// Data processing only: not the multiply and extra load/store space, not the miscellaneous
// space (MRS, MSR, BX, BLX, CLZ, DSP: opcodes 8 to 11 with S clear), and not a write of PC,
// which may be an exception return.
if ((instruction & 0x0c000000) != 0 || (instruction & 0x02000090) == 0x00000090 ||
(instruction & 0x01900000) == 0x01000000)
{
return false;
}
return ((instruction >> 12) & 0xf) != 15;
}
bool ARMJitX64::IsCheckedNativeThumb(u16 instruction)
{
// Shifts, add/subtract, move/compare/add/subtract immediate, ALU operations, conditional
// branches (not SWI or the undefined condition) and unconditional branches.
if ((instruction & 0xc000) == 0x0000 || (instruction & 0xfc00) == 0x4000 ||
(instruction & 0xf800) == 0xe000)
{
return true;
}
return (instruction & 0xf000) == 0xd000 && ((instruction >> 8) & 0xf) < 0xe;
}
const u8* ARMJitX64::Dispatch(ARMJitX64* jit, DispatchReason reason, u32 generated_key,
u32 generated_set_offset)
{
if (reason == DispatchReason::Checked)
return DispatchChecked(jit);
const bool thumb = (jit->m_core.m_cpsr & ARMCore::CPSR_T) != 0;
const u32 key = jit->m_core.m_registers[15] | (thumb ? 1U : 0U);
const u32 fast_key =
@@ -562,13 +632,17 @@ ARMJitX64::Block* ARMJitX64::GetOrCompileBlock(u32 address, u32* physical_addres
return nullptr;
}
const u8* const trace_begin = GetCodePtr();
Block block = CompileBlock(virtual_address, thumb);
Common::PerformanceTrace::CodeMap("ARM", this, trace_begin, GetCodePtr(), virtual_address,
block_key, thumb ? "thumb" : "arm");
++m_lifetime_compiled_block_count;
return &m_blocks.emplace(block_key, block).first->second;
}
ARMJitX64::Block ARMJitX64::CompileBlock(u32 address, bool thumb)
{
const Common::PerformanceTrace::Scope trace(Common::PerformanceTrace::Region::Compile);
const u8* const body = AlignCode16();
LoadRegisterCache();
MOV(8, MPCWritten(), Imm8(0));
@@ -757,6 +831,10 @@ ARMJitX64::Block ARMJitX64::CompileBlock(u32 address, bool thumb)
bool ARMJitX64::EmitDirectARM(u32 instruction, u32 address, bool* terminal, bool* dispatcher_exit)
{
// With MMU faults, the interpreter (through FallbackARM, which ends the block) runs every
// instruction that could fault or change the next fetch's permission.
if (m_core.m_mmu_faults && !IsCheckedNativeARM(instruction))
return false;
// The IOS scheduler executes a small set of ARM926 system-control writes in virtually every
// syscall and interrupt path. Decode those architectural operations once while compiling the
// block instead of entering the complete interpreter decoder every time the block runs.
@@ -1154,7 +1232,9 @@ bool ARMJitX64::CanEmitARMDataProcessing(u32 instruction) const
if ((instruction & 0x0fff0ff0) == 0x016f0f10 || (instruction & 0x0f8000f0) == 0x00800090 ||
(instruction & 0x0fc000f0) == 0x00000090 || (instruction & 0x0fb00ff0) == 0x01000090 ||
(instruction & 0x0fbf0fff) == 0x010f0000 || (instruction & 0x0fb0fff0) == 0x0120f000 ||
(instruction & 0x0fb0f000) == 0x0320f000 || (instruction & 0x0e000090) == 0x00000090)
(instruction & 0x0fb0f000) == 0x0320f000 || (instruction & 0x0e000090) == 0x00000090 ||
// ARMv5TE enhanced DSP multiplies and saturating arithmetic: interpreter (StarletOS I1).
(instruction & 0x0f900090) == 0x01000080 || (instruction & 0x0f900ff0) == 0x01000050)
{
return false;
}
@@ -1466,6 +1546,15 @@ bool ARMJitX64::EmitARMBlockTransfer(u32 instruction, u32 address, bool* termina
}
std::vector<FixupBranch> slow_paths;
// StarletOS phase 11 (H1): a transfer whose virtual range overlaps a watched range runs through
// the architectural helper, so the interpreter logs its translation.
for (const auto& [start, size] : m_watch_ranges)
{
MOV(32, R(EDX), R(EAX));
SUB(32, R(EDX), Imm32(start - (range_size - 1)));
CMP(32, R(EDX), Imm32(size + range_size - 1));
slow_paths.push_back(J_CC(CC_B, Jump::Near));
}
if ((m_core.m_cp15.control & 1U) != 0)
{
MOV(32, R(EDX), R(EAX));
@@ -1841,6 +1930,8 @@ void ARMJitX64::EmitExchangeBranch(OpArg target, bool link, u32 return_address)
bool ARMJitX64::EmitDirectThumb(u16 instruction, u32 address, bool* terminal)
{
if (m_core.m_mmu_faults && !IsCheckedNativeThumb(instruction))
return false;
if ((instruction & 0xff00) == 0xdf00)
{
FlushRegisterCache();
@@ -2246,6 +2337,16 @@ void ARMJitX64::EmitFastmemAddress(std::vector<FixupBranch>* slow_paths, u32 acc
slow_paths->push_back(J_CC(CC_NZ, Jump::Near));
}
// StarletOS phase 11 (F1): an access overlapping a watched range takes the bus slow path.
// Overlap: start - (range_size - 1) <= address < start + size, as one unsigned comparison.
for (const auto& [start, size] : m_watch_ranges)
{
MOV(32, R(EDX), R(EAX));
SUB(32, R(EDX), Imm32(start - (range_size - 1)));
CMP(32, R(EDX), Imm32(size + range_size - 1));
slow_paths->push_back(J_CC(CC_B, Jump::Near));
}
// Return the resolved host pointer in R11. Wii RAM uses Dolphin's 4 GiB fastmem view.
CMP(32, R(EAX), Imm32(Memory::MEM1_SIZE_RETAIL - range_size));
FixupBranch in_mem1 = J_CC(CC_BE, Jump::Near);
@@ -2256,8 +2357,10 @@ void ARMJitX64::EmitFastmemAddress(std::vector<FixupBranch>* slow_paths, u32 acc
// Addresses above MEM2 are only directly accessible when they hit the high Starlet SRAM
// mirror. Everything else remains on the exact bus/MMIO path.
if (sram_access == SRAMFastmemAccess::None || !m_sram_base || !m_boot0_mapped ||
!m_sram_split_mode)
// SRAM writes are still bus-only. Reject them before testing the direct-read aperture;
// retain R9's physical address for the exact slow write without redundant SRAM checks.
if (sram_access == SRAMFastmemAccess::None || sram_access == SRAMFastmemAccess::Write ||
!m_sram_base || !m_boot0_mapped || !m_sram_split_mode)
{
slow_paths->push_back(J(Jump::Near));
SetJumpTarget(below_mem2);
@@ -2311,37 +2414,20 @@ void ARMJitX64::EmitFastmemAddress(std::vector<FixupBranch>* slow_paths, u32 acc
MOV(32, R(EAX), R(R9));
AND(32, R(EAX), Imm32(0x1ffff));
// Full-chain profiling gives a narrow safe aperture for reads. Direct writes to the measured
// IOS pages 0x00/0x19 passed isolated bounds tests, but reproducibly terminated BootMii during
// its hardware setup. Keep every SRAM write on the exact bus path until write coherency with
// the live boot chain is understood. Boot0, split-window holes and register-list transfers also
// remain on the bus.
// Limit scalar direct reads to pages measured across the boot chain and native IOS update.
// EDX is an aperture page in [0, 31]; the mask avoids a growing chain of comparisons. Keep
// ECX intact for the caller's unaligned ARM word rotation. Boot0 and split-window holes still
// use the bus. Writes and register-list transfers were rejected above: direct SRAM writes
// previously regressed BootMii despite passing isolated bounds tests.
MOV(32, R(EDX), R(EAX));
SHR(32, R(EDX), Imm8(12));
if (sram_access == SRAMFastmemAccess::Write)
{
slow_paths->push_back(J(Jump::Near));
}
else
{
CMP(32, R(EDX), Imm32(0x00));
const FixupBranch profiled_read_page_00 = J_CC(CC_E, Jump::Near);
CMP(32, R(EDX), Imm32(0x10));
const FixupBranch irq_vector_read_page_10 = J_CC(CC_E, Jump::Near);
CMP(32, R(EDX), Imm32(0x12));
const FixupBranch profiled_read_page_12 = J_CC(CC_E, Jump::Near);
CMP(32, R(EDX), Imm32(0x14));
const FixupBranch profiled_read_page_14 = J_CC(CC_E, Jump::Near);
CMP(32, R(EDX), Imm32(0x19));
const FixupBranch profiled_read_page_19 = J_CC(CC_E, Jump::Near);
CMP(32, R(EDX), Imm32(0x1e));
slow_paths->push_back(J_CC(CC_NE, Jump::Near));
SetJumpTarget(profiled_read_page_00);
SetJumpTarget(irq_vector_read_page_10);
SetJumpTarget(profiled_read_page_12);
SetJumpTarget(profiled_read_page_14);
SetJumpTarget(profiled_read_page_19);
}
constexpr u32 profiled_read_pages = (1U << 0x00) | (1U << 0x01) | (1U << 0x02) | (1U << 0x04) |
(1U << 0x10) | (1U << 0x12) | (1U << 0x13) | (1U << 0x14) |
(1U << 0x15) | (1U << 0x16) | (1U << 0x19) | (1U << 0x1a) |
(1U << 0x1c) | (1U << 0x1d) | (1U << 0x1e);
MOV(32, R(R8), Imm32(profiled_read_pages));
BT(32, R(R8), R(EDX));
slow_paths->push_back(J_CC(CC_NC, Jump::Near));
MOV(64, R(R8), ImmPtr(m_sram_split_mode));
CMP(8, MatR(R8), Imm8(0));
@@ -2390,6 +2476,9 @@ void ARMJitX64::EmitThumbMemorySlowPath(const std::vector<FixupBranch>& slow_pat
{
for (const FixupBranch& slow_path : slow_paths)
SetJumpTarget(slow_path);
// Phase 11 F1: the bus write below reports this instruction to the write watch.
if (!m_watch_ranges.empty())
MOV(32, MInstructionAddress(), Imm32(address));
// IOS Thumb code repeatedly accesses SRAM and MMIO. These instructions are already decoded:
// perform the exact bus transaction without re-entering ExecuteThumb and the block dispatcher.
@@ -2408,17 +2497,25 @@ void ARMJitX64::EmitThumbMemorySlowPath(const std::vector<FixupBranch>& slow_pat
MOV(32, R(ABI_PARAM4), Imm32(0));
MOV(32, R(ABI_PARAM3), Imm32(access_size));
MOV(64, R(ABI_PARAM1), ImmPtr(this));
ABI_CallFunction(ReadMemorySlow);
ABI_CallFunction(m_core.IsJitMemoryProfilingEnabled() ? ReadMemorySlow<true> :
ReadMemorySlow<false>);
if (sign_extend)
MOVSX(32, access_size * 8, EAX, R(EAX));
MOV(32, MStoredRegister(rd), R(EAX));
}
else
{
MOV(32, R(ABI_PARAM4), MStoredRegister(rd));
MOV(32, R(ABI_PARAM3), Imm32(access_size));
MOV(32, R(ABI_PARAM3), MStoredRegister(rd));
MOV(64, R(ABI_PARAM1), ImmPtr(this));
ABI_CallFunction(WriteMemorySlow);
if (access_size == 1)
ABI_CallFunction(m_core.IsJitMemoryProfilingEnabled() ? WriteMemorySlow<1, true> :
WriteMemorySlow<1, false>);
else if (access_size == 2)
ABI_CallFunction(m_core.IsJitMemoryProfilingEnabled() ? WriteMemorySlow<2, true> :
WriteMemorySlow<2, false>);
else
ABI_CallFunction(m_core.IsJitMemoryProfilingEnabled() ? WriteMemorySlow<4, true> :
WriteMemorySlow<4, false>);
}
if (access_size > 1)
{
@@ -2476,6 +2573,9 @@ void ARMJitX64::EmitARMMemorySlowPath(const std::vector<FixupBranch>& slow_paths
{
for (const FixupBranch& slow_path : slow_paths)
SetJumpTarget(slow_path);
// Phase 11 F1: the bus write below reports this instruction to the write watch.
if (!m_watch_ranges.empty())
MOV(32, MInstructionAddress(), Imm32(address));
// A normal ARM single-data transfer that misses RAM/SRAM fastmem is still a fully decoded
// instruction. Execute only its physical bus transaction here and stay inside the translated
@@ -2514,16 +2614,21 @@ void ARMJitX64::EmitARMMemorySlowPath(const std::vector<FixupBranch>& slow_paths
MOV(32, R(ABI_PARAM4), R(RBP));
MOV(32, R(ABI_PARAM3), Imm32(access_size));
MOV(64, R(ABI_PARAM1), ImmPtr(this));
ABI_CallFunction(ReadMemorySlow);
ABI_CallFunction(m_core.IsJitMemoryProfilingEnabled() ? ReadMemorySlow<true> :
ReadMemorySlow<false>);
MOV(32, MStoredRegister(rd), R(EAX));
}
else
{
MOV(32, R(ABI_PARAM2), R(R9));
MOV(32, R(ABI_PARAM4), MStoredRegister(rd));
MOV(32, R(ABI_PARAM3), Imm32(access_size));
MOV(32, R(ABI_PARAM3), MStoredRegister(rd));
MOV(64, R(ABI_PARAM1), ImmPtr(this));
ABI_CallFunction(WriteMemorySlow);
if (byte)
ABI_CallFunction(m_core.IsJitMemoryProfilingEnabled() ? WriteMemorySlow<1, true> :
WriteMemorySlow<1, false>);
else
ABI_CallFunction(m_core.IsJitMemoryProfilingEnabled() ? WriteMemorySlow<4, true> :
WriteMemorySlow<4, false>);
}
if (writeback)
MOV(32, MStoredRegister(rn), R(RBX));
@@ -2876,8 +2981,15 @@ void ARMJitX64::FallbackThumb(ARMJitX64* jit, u16 instruction, u32 address)
core->RecordJitFallback(address, true);
core->m_instruction_address = address;
core->m_pc_written = false;
core->ExecuteThumb(instruction);
core->TryEnterThumbMemoryPoll(instruction);
if (core->m_mmu_faults)
{
core->ExecuteThumbWithAborts(instruction);
}
else
{
core->ExecuteThumb(instruction);
core->TryEnterThumbMemoryPoll(instruction);
}
if (!core->m_pc_written)
core->m_registers[15] = address + ((core->m_cpsr & ARMCore::CPSR_T) ? 2 : 4);
}
@@ -2899,9 +3011,13 @@ void ARMJitX64::FallbackARM(ARMJitX64* jit, u32 instruction, u32 address)
}
else if (core->ConditionPassed(instruction >> 28))
{
core->ExecuteARM(instruction);
if (core->m_mmu_faults)
core->ExecuteARMWithAborts(instruction);
else
core->ExecuteARM(instruction);
}
core->TryEnterARMSliceStablePoll(instruction);
if (!core->m_mmu_faults)
core->TryEnterARMSliceStablePoll(instruction);
if (!core->m_pc_written)
core->m_registers[15] = address + ((core->m_cpsr & ARMCore::CPSR_T) ? 2 : 4);
}
@@ -2959,29 +3075,35 @@ void ARMJitX64::ExceptionReturn(ARMJitX64* jit, u32 target)
core.WritePC(target);
}
template <bool profile>
u32 ARMJitX64::ReadMemorySlow(ARMJitX64* jit, u32 physical_address, u32 access_size,
u32 byte_offset)
{
++jit->m_slow_read_count;
if ((jit->m_slow_read_count & 0xff) == 0)
++jit->m_slow_memory_address_samples[physical_address & ~3ULL];
switch (ClassifySlowMemoryAddress(physical_address))
// The helper is selected at code generation, so disabling detailed diagnostics adds no
// per-access mode branch. Keep the aggregate counter and the exact bus transaction in both.
if constexpr (profile)
{
case SlowMemoryRegion::RAM:
++jit->m_slow_ram_read_count;
break;
case SlowMemoryRegion::SRAM:
++jit->m_slow_sram_read_count;
++(physical_address < 0xfff00000 ? jit->m_slow_sram_low_access_count :
jit->m_slow_sram_high_access_count);
++jit->m_slow_sram_page_read_access_count[(physical_address & 0x1ffff) >> 12];
break;
case SlowMemoryRegion::MMIO:
++jit->m_slow_mmio_read_count;
break;
case SlowMemoryRegion::Other:
++jit->m_slow_other_read_count;
break;
if ((jit->m_slow_read_count & 0xff) == 0)
++jit->m_slow_memory_address_samples[physical_address & ~3ULL];
switch (ClassifySlowMemoryAddress(physical_address))
{
case SlowMemoryRegion::RAM:
++jit->m_slow_ram_read_count;
break;
case SlowMemoryRegion::SRAM:
++jit->m_slow_sram_read_count;
++(physical_address < 0xfff00000 ? jit->m_slow_sram_low_access_count :
jit->m_slow_sram_high_access_count);
++jit->m_slow_sram_page_read_access_count[(physical_address & 0x1ffff) >> 12];
break;
case SlowMemoryRegion::MMIO:
++jit->m_slow_mmio_read_count;
break;
case SlowMemoryRegion::Other:
++jit->m_slow_other_read_count;
break;
}
}
ARMCore& core = jit->m_core;
if (access_size == 1)
@@ -2998,45 +3120,52 @@ u32 ARMJitX64::ReadMemorySlow(ARMJitX64* jit, u32 physical_address, u32 access_s
return std::rotr(value, static_cast<int>((byte_offset & 3) * 8));
}
void ARMJitX64::WriteMemorySlow(ARMJitX64* jit, u32 physical_address, u32 access_size, u32 value)
template <u32 access_size, bool profile>
void ARMJitX64::WriteMemorySlow(ARMJitX64* jit, u32 physical_address, u32 value)
{
// Select width while compiling the guest instruction, not on every dynamic bus write.
// Mapping, protection, MMIO side effects, endian conversion and aggregate counts stay live.
static_assert(access_size == 1 || access_size == 2 || access_size == 4);
++jit->m_slow_write_count;
if ((jit->m_slow_write_count & 0xff) == 0)
++jit->m_slow_memory_address_samples[(1ULL << 32) | (physical_address & ~3ULL)];
switch (ClassifySlowMemoryAddress(physical_address))
if constexpr (profile)
{
case SlowMemoryRegion::RAM:
++jit->m_slow_ram_write_count;
break;
case SlowMemoryRegion::SRAM:
++jit->m_slow_sram_write_count;
++(physical_address < 0xfff00000 ? jit->m_slow_sram_low_access_count :
jit->m_slow_sram_high_access_count);
++jit->m_slow_sram_page_write_access_count[(physical_address & 0x1ffff) >> 12];
break;
case SlowMemoryRegion::MMIO:
++jit->m_slow_mmio_write_count;
break;
case SlowMemoryRegion::Other:
++jit->m_slow_other_write_count;
break;
if ((jit->m_slow_write_count & 0xff) == 0)
++jit->m_slow_memory_address_samples[(1ULL << 32) | (physical_address & ~3ULL)];
switch (ClassifySlowMemoryAddress(physical_address))
{
case SlowMemoryRegion::RAM:
++jit->m_slow_ram_write_count;
break;
case SlowMemoryRegion::SRAM:
++jit->m_slow_sram_write_count;
++(physical_address < 0xfff00000 ? jit->m_slow_sram_low_access_count :
jit->m_slow_sram_high_access_count);
++jit->m_slow_sram_page_write_access_count[(physical_address & 0x1ffff) >> 12];
break;
case SlowMemoryRegion::MMIO:
++jit->m_slow_mmio_write_count;
break;
case SlowMemoryRegion::Other:
++jit->m_slow_other_write_count;
break;
}
}
ARMCore& core = jit->m_core;
if (access_size == 1)
if constexpr (access_size == 1)
{
core.m_bus.Write8(physical_address, static_cast<u8>(value));
return;
}
if (access_size == 2)
else if constexpr (access_size == 2)
{
const u16 halfword = static_cast<u16>(value);
core.m_bus.Write16(physical_address, core.m_big_endian ? halfword : std::byteswap(halfword));
return;
}
if (!core.m_big_endian)
value = std::byteswap(value);
core.m_bus.Write32(physical_address & ~3U, value);
else
{
if (!core.m_big_endian)
value = std::byteswap(value);
core.m_bus.Write32(physical_address & ~3U, value);
}
}
std::vector<std::pair<u64, u64>> ARMJitX64::TakeHotSlowMemorySamples(size_t maximum_count)
+12 -1
View File
@@ -157,6 +157,8 @@ private:
KeyMiss,
PageMiss,
EmptyEntry,
// MMU faults enabled: every block entry checks its fetch (ARMCore::SetMMUFaultsEnabled).
Checked,
};
void PoisonMemory() override;
@@ -172,6 +174,11 @@ private:
u32* first_descriptor_value_out, const u8** second_descriptor_out,
u32* second_descriptor_value_out);
Block CompileBlock(u32 address, bool thumb);
static const u8* DispatchChecked(ARMJitX64* jit);
// With MMU faults enabled, the instructions that run natively: they touch neither memory, CP15,
// the PSRs nor the exception model, so they can neither fault nor change a fetch's permission.
static bool IsCheckedNativeARM(u32 instruction);
static bool IsCheckedNativeThumb(u16 instruction);
bool EmitDirectARM(u32 instruction, u32 address, bool* terminal, bool* dispatcher_exit);
bool EmitARMMultiplyLong(u32 instruction);
bool CanEmitARMDataProcessing(u32 instruction) const;
@@ -227,8 +234,10 @@ private:
static void ExecuteUserBankBlockTransfer(ARMJitX64* jit, u32 instruction, u32 address);
static void ExecuteThumbPushPop(ARMJitX64* jit, u16 instruction, u32 address);
static void ExceptionReturn(ARMJitX64* jit, u32 target);
template <bool profile>
static u32 ReadMemorySlow(ARMJitX64* jit, u32 physical_address, u32 access_size, u32 byte_offset);
static void WriteMemorySlow(ARMJitX64* jit, u32 physical_address, u32 access_size, u32 value);
template <u32 access_size, bool profile>
static void WriteMemorySlow(ARMJitX64* jit, u32 physical_address, u32 value);
static u32 TranslateAddress(ARMJitX64* jit, u32 address);
static void EnterUndefinedARM(ARMJitX64* jit, u32 instruction, u32 address);
static void EnterSVCARM(ARMJitX64* jit, u32 address);
@@ -248,6 +257,8 @@ private:
std::array<u8, FAST_ENTRY_SET_COUNT> m_fast_entry_next_victim{};
std::array<FastTranslationEntry, FAST_TRANSLATION_ENTRY_COUNT> m_fast_translations{};
u8* m_fastmem_base = nullptr;
// Phase 11 F1: watched physical ranges, routed to the bus slow path.
std::vector<std::pair<u32, u32>> m_watch_ranges;
u8* m_sram_base = nullptr;
const bool* m_boot0_mapped = nullptr;
const bool* m_sram_split_mode = nullptr;
+36
View File
@@ -11,6 +11,7 @@
#include "Common/ChunkFile.h"
#include "Common/Logging/Log.h"
#include "Common/PerformanceTrace.h"
namespace IOS::LLE
{
@@ -43,6 +44,8 @@ AX88772::AX88772(Transmit transmit) : m_transmit(std::move(transmit))
void AX88772::Reset()
{
m_trace_rx_times = {};
m_trace_rx_head = m_trace_rx_peak = 0;
m_address = m_configuration = 0;
m_control_valid = m_control_stalled = false;
m_control.clear();
@@ -77,6 +80,11 @@ bool AX88772::LinkUp() const
void AX88772::DoState(PointerWrap& p)
{
if (p.IsReadMode())
{
m_trace_rx_times = {};
m_trace_rx_head = m_trace_rx_peak = 0;
}
p.Do(m_mac);
p.Do(m_eeprom);
p.Do(m_phy);
@@ -403,6 +411,8 @@ bool AX88772::ApplyControl(std::span<const u8> data)
if (value & 1)
{
m_rx.clear();
m_trace_rx_times = {};
m_trace_rx_head = 0;
m_rx_offset = 0;
}
if (value & 2)
@@ -451,7 +461,10 @@ void AX88772::ReceiveFrame(std::span<const u8> frame)
{
if (!LinkUp() || (m_rx_control & 0x80) == 0 || (m_medium & 0x100) == 0 || frame.size() < 14 ||
frame.size() > MAX_FRAME || m_rx.size() >= MAX_QUEUE)
{
Common::PerformanceTrace::Add(Common::PerformanceTrace::Counter::UsbDrops);
return;
}
const bool broadcast =
std::all_of(frame.begin(), frame.begin() + 6, [](u8 b) { return b == 0xff; });
const bool multicast = (frame[0] & 1) != 0;
@@ -465,7 +478,28 @@ void AX88772::ReceiveFrame(std::span<const u8> frame)
packet.insert(packet.end(), frame.begin(), frame.end());
if (length & 1)
packet.push_back(0);
if (Common::PerformanceTrace::Requested())
{
m_trace_rx_times[(m_trace_rx_head + m_rx.size()) % m_trace_rx_times.size()] =
Common::PerformanceTrace::Now();
m_trace_rx_peak = std::max(m_trace_rx_peak, m_rx.size() + 1);
}
m_rx.push_back(std::move(packet));
Common::PerformanceTrace::Add(Common::PerformanceTrace::Counter::UsbRXFrames);
Common::PerformanceTrace::Add(Common::PerformanceTrace::Counter::UsbRXBytes, frame.size());
}
void AX88772::TraceQueue() const
{
if (!Common::PerformanceTrace::Enabled())
return;
u64 bytes = 0;
for (const auto& packet : m_rx)
bytes += packet.size();
if (!m_rx.empty())
bytes -= m_rx_offset;
Common::PerformanceTrace::Queue(this, m_rx.size(), bytes,
m_rx.empty() ? 0 : m_trace_rx_times[m_trace_rx_head], m_trace_rx_peak);
}
AX88772::Result AX88772::Transfer(u8 endpoint, u8 direction, std::span<u8> buffer, size_t* actual)
@@ -560,9 +594,11 @@ AX88772::Result AX88772::Transfer(u8 endpoint, u8 direction, std::span<u8> buffe
*actual = std::min(buffer.size(), packet.size() - m_rx_offset);
std::copy_n(packet.begin() + m_rx_offset, *actual, buffer.begin());
m_rx_offset += *actual;
Common::PerformanceTrace::Add(Common::PerformanceTrace::Counter::UsbDeliveredBytes, *actual);
if (m_rx_offset == packet.size())
{
m_rx.pop_front();
m_trace_rx_head = (m_trace_rx_head + 1) % m_trace_rx_times.size();
m_rx_offset = 0;
}
return Result::Completed;
+4
View File
@@ -36,6 +36,7 @@ public:
void ReceiveFrame(std::span<const u8> frame);
Result Transfer(u8 endpoint, u8 direction, std::span<u8> buffer, size_t* actual);
u8 GetAddress() const { return m_address; }
void TraceQueue() const;
private:
static constexpr u8 INTERRUPT_INTERVAL_MS = 10;
@@ -77,5 +78,8 @@ private:
// Diagnostics only; not part of guest-visible/savestate state.
u32 m_control_log_count = 0;
u64 m_interrupt_reports = 0;
std::array<u64, 128> m_trace_rx_times{};
size_t m_trace_rx_head = 0;
size_t m_trace_rx_peak = 0;
};
} // namespace IOS::LLE
@@ -0,0 +1,241 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "Core/IOS/Starlet/BootstrapELF.h"
#include <algorithm>
#include <array>
#include <optional>
#include <string_view>
#include "Core/IOS/Starlet/ARMCore.h"
namespace IOS::LLE
{
namespace
{
constexpr u32 TEXT_BASE = 0xffff0000;
constexpr u64 TEXT_END = 0x1'0000'0000ULL;
constexpr u32 DATA_BASE = 0xfffe0000;
constexpr u32 DATA_END = 0xfffe4000;
// Revolution IOS Phase 06H: MEM2, for the optional disposable-image text segment.
constexpr u32 MEM2_BASE = 0x10000000;
constexpr u64 MEM2_END = 0x14000000ULL;
constexpr u32 TRACE_SIZE = 1032;
constexpr u32 ELF_HEADER_SIZE = 52;
constexpr u32 PROGRAM_HEADER_SIZE = 32;
constexpr u32 SECTION_HEADER_SIZE = 40;
constexpr u32 SYMBOL_SIZE = 16;
struct Segment
{
u32 offset = 0;
u32 address = 0;
u32 file_size = 0;
u32 memory_size = 0;
};
bool Fits(std::span<const u8> image, u64 offset, u64 size)
{
return offset <= image.size() && size <= image.size() - offset;
}
u16 Read16(std::span<const u8> image, size_t offset)
{
return static_cast<u16>((static_cast<u16>(image[offset]) << 8) | image[offset + 1]);
}
u32 Read32(std::span<const u8> image, size_t offset)
{
return (static_cast<u32>(image[offset]) << 24) | (static_cast<u32>(image[offset + 1]) << 16) |
(static_cast<u32>(image[offset + 2]) << 8) | image[offset + 3];
}
bool Fail(std::string* error, std::string_view reason)
{
if (error)
*error = reason;
return false;
}
std::optional<std::string_view> SymbolName(std::span<const u8> image, u32 strings_offset,
u32 strings_size, u32 name_offset)
{
if (name_offset >= strings_size)
return std::nullopt;
const size_t start = static_cast<size_t>(strings_offset) + name_offset;
const auto first = image.begin() + start;
const auto last = image.begin() + strings_offset + strings_size;
const auto end = std::find(first, last, 0);
if (end == last)
return std::nullopt;
return std::string_view(reinterpret_cast<const char*>(&*first), static_cast<size_t>(end - first));
}
} // namespace
bool LoadBootstrapELF(std::span<const u8> image, ARMBus& bus, BootstrapELFInfo* info,
std::string* error, bool allow_mem2_text)
{
if (!info)
return Fail(error, "missing bootstrap ELF result");
if (!Fits(image, 0, ELF_HEADER_SIZE) || image[0] != 0x7f || image[1] != 'E' || image[2] != 'L' ||
image[3] != 'F' || image[4] != 1 || image[5] != 2 || image[6] != 1 ||
Read16(image, 16) != 2 || Read16(image, 18) != 40 || Read32(image, 20) != 1 ||
Read16(image, 40) != ELF_HEADER_SIZE)
{
return Fail(error, "expected ELF32 big-endian ARM executable");
}
const u32 entry = Read32(image, 24);
const u32 program_offset = Read32(image, 28);
const u32 section_offset = Read32(image, 32);
const u16 program_size = Read16(image, 42);
const u16 program_count = Read16(image, 44);
const u16 section_size = Read16(image, 46);
const u16 section_count = Read16(image, 48);
const bool program_count_valid = program_count == 2 || (allow_mem2_text && program_count == 3);
if (entry != TEXT_BASE || program_size != PROGRAM_HEADER_SIZE || !program_count_valid ||
section_size != SECTION_HEADER_SIZE || section_count == 0 ||
!Fits(image, program_offset, static_cast<u64>(program_size) * program_count) ||
!Fits(image, section_offset, static_cast<u64>(section_size) * section_count))
{
return Fail(error, "bootstrap ELF has an unsupported entry or header table");
}
std::array<Segment, 3> storage;
const std::span<Segment> segments(storage.data(), program_count);
u32 text_count = 0;
u32 data_count = 0;
u32 mem2_count = 0;
for (u32 index = 0; index < segments.size(); ++index)
{
const size_t offset = program_offset + index * PROGRAM_HEADER_SIZE;
const u32 file_offset = Read32(image, offset + 4);
const u32 address = Read32(image, offset + 8);
const u32 physical_address = Read32(image, offset + 12);
const u32 file_size = Read32(image, offset + 16);
const u32 memory_size = Read32(image, offset + 20);
const u32 flags = Read32(image, offset + 24);
const bool text =
address == TEXT_BASE && flags == 5 && static_cast<u64>(address) + memory_size <= TEXT_END;
const bool data =
address == DATA_BASE && flags == 6 && static_cast<u64>(address) + memory_size <= DATA_END;
const bool mem2 = allow_mem2_text && flags == 5 && address >= MEM2_BASE &&
static_cast<u64>(address) + memory_size <= MEM2_END;
if (Read32(image, offset) != 1 || address != physical_address || file_size == 0 ||
memory_size < file_size || !Fits(image, file_offset, file_size) ||
(!text && !data && !mem2))
{
return Fail(error, "bootstrap ELF has an invalid SRAM load segment");
}
text_count += text;
data_count += data;
mem2_count += mem2;
segments[index] = {file_offset, address, file_size, memory_size};
}
if (text_count != 1 || data_count != 1 || mem2_count != program_count - 2u)
return Fail(error, "bootstrap ELF must have one text and one data segment");
BootstrapELFInfo parsed{entry};
bool found_trace = false;
bool found_fault_code = false;
bool found_fault_lr = false;
bool found_fault_spsr = false;
for (u32 index = 0; index < section_count; ++index)
{
const size_t offset = section_offset + index * SECTION_HEADER_SIZE;
if (Read32(image, offset + 4) != 2)
continue;
const u32 symbols_offset = Read32(image, offset + 16);
const u32 symbols_size = Read32(image, offset + 20);
const u32 strings_index = Read32(image, offset + 24);
const u32 entry_size = Read32(image, offset + 36);
if (entry_size != SYMBOL_SIZE || symbols_size % SYMBOL_SIZE != 0 ||
!Fits(image, symbols_offset, symbols_size) || strings_index >= section_count)
{
return Fail(error, "bootstrap ELF has an invalid symbol table");
}
const size_t strings_header = section_offset + strings_index * SECTION_HEADER_SIZE;
const u32 strings_offset = Read32(image, strings_header + 16);
const u32 strings_size = Read32(image, strings_header + 20);
if (Read32(image, strings_header + 4) != 3 || !Fits(image, strings_offset, strings_size))
{
return Fail(error, "bootstrap ELF has an invalid symbol string table");
}
for (u32 symbol = 0; symbol < symbols_size / SYMBOL_SIZE; ++symbol)
{
const size_t symbol_offset = symbols_offset + symbol * SYMBOL_SIZE;
const auto name =
SymbolName(image, strings_offset, strings_size, Read32(image, symbol_offset));
if (!name)
return Fail(error, "bootstrap ELF has an invalid symbol name");
const u32 address = Read32(image, symbol_offset + 4);
if (*name == "REV_TRACE")
{
if (Read32(image, symbol_offset + 8) != TRACE_SIZE)
return Fail(error, "bootstrap ELF trace layout does not match the monitor");
parsed.trace = address;
found_trace = true;
}
else if (*name == "__fault_code")
{
parsed.fault_code = address;
found_fault_code = true;
}
else if (*name == "__fault_lr")
{
parsed.fault_lr = address;
found_fault_lr = true;
}
else if (*name == "__fault_spsr")
{
parsed.fault_spsr = address;
found_fault_spsr = true;
}
else if (*name == "__panic_state")
{
parsed.panic_state = address;
}
else if (*name == "__panic_code")
{
parsed.panic_code = address;
}
}
}
const auto data_segment =
std::find_if(segments.begin(), segments.end(),
[](const Segment& segment) { return segment.address == DATA_BASE; });
const auto in_data = [data_segment](u32 address, u32 size) {
return address >= data_segment->address &&
static_cast<u64>(address) + size <=
static_cast<u64>(data_segment->address) + data_segment->memory_size;
};
if (!found_trace || !found_fault_code || !found_fault_lr || !found_fault_spsr ||
!in_data(parsed.trace, TRACE_SIZE) || !in_data(parsed.fault_code, 4) ||
!in_data(parsed.fault_lr, 4) || !in_data(parsed.fault_spsr, 4))
{
return Fail(error, "bootstrap ELF is missing the trace or fault symbols");
}
// The panic words are optional, but both or neither, as two distinct words of the data segment:
// aliased, the code's store would also set the guard, and a probe could not tell them apart.
const bool panic_words_overlap =
static_cast<u64>(parsed.panic_state) < static_cast<u64>(parsed.panic_code) + 4 &&
static_cast<u64>(parsed.panic_code) < static_cast<u64>(parsed.panic_state) + 4;
if ((parsed.panic_state != 0) != (parsed.panic_code != 0) ||
(parsed.panic_state != 0 && (!in_data(parsed.panic_state, 4) ||
!in_data(parsed.panic_code, 4) || panic_words_overlap)))
{
return Fail(error, "bootstrap ELF has an invalid panic symbol");
}
for (const Segment& segment : segments)
{
for (u32 index = 0; index < segment.file_size; ++index)
bus.Write8(segment.address + index, image[segment.offset + index]);
for (u32 index = segment.file_size; index < segment.memory_size; ++index)
bus.Write8(segment.address + index, 0);
}
*info = parsed;
return true;
}
} // namespace IOS::LLE
@@ -0,0 +1,35 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <span>
#include <string>
#include "Common/CommonTypes.h"
namespace IOS::LLE
{
class ARMBus;
struct BootstrapELFInfo
{
u32 entry = 0;
u32 trace = 0;
u32 fault_code = 0;
u32 fault_lr = 0;
u32 fault_spsr = 0;
// Optional (StarOS ADR-0014 R6): the panic path's guard and code words, 0 when the image has
// none. A nonzero guard means the panic handler ran.
u32 panic_state = 0;
u32 panic_code = 0;
};
// Load the Phase 01 ELF into a bus already configured with the high SRAM mapping.
// All file and address validation completes before the first bus write.
// Revolution IOS Phase 06H: `allow_mem2_text` (set only with the emulator-only disposable
// writable NAND) additionally accepts one read/execute segment wholly inside MEM2. The SRAM
// text and data segments stay mandatory; without the flag the rules are unchanged.
bool LoadBootstrapELF(std::span<const u8> image, ARMBus& bus, BootstrapELFInfo* info,
std::string* error, bool allow_mem2_text = false);
} // namespace IOS::LLE
+31 -12
View File
@@ -13,6 +13,7 @@
#include "Common/FileUtil.h"
#include "Common/Logging/Log.h"
#include "Common/PerformanceTrace.h"
namespace IOS::LLE
{
@@ -137,31 +138,49 @@ bool NANDJournal::Open(const std::string& path, const Common::SHA1::Digest& sour
bool NANDJournal::Append(const Pages& pages, bool replace)
{
namespace Trace = Common::PerformanceTrace;
const Trace::Scope trace(Trace::Region::Journal);
if (!m_file || pages.size() > PAGE_COUNT)
return false;
if (pages.empty() && !replace)
return true;
std::vector<u8> record;
record.reserve(TRANSACTION_HEADER_SIZE + pages.size() * ENTRY_SIZE);
Put32(record, TRANSACTION_MAGIC);
Put32(record, replace ? 1 : 0);
Put32(record, static_cast<u32>(pages.size()));
for (const auto& [page, data] : pages)
Common::SHA1::Digest checksum;
{
if (page >= PAGE_COUNT)
return false;
Put32(record, page);
record.insert(record.end(), data.begin(), data.end());
const Trace::Scope build_trace(Trace::Region::JournalBuild);
record.reserve(TRANSACTION_HEADER_SIZE + pages.size() * ENTRY_SIZE);
Put32(record, TRANSACTION_MAGIC);
Put32(record, replace ? 1 : 0);
Put32(record, static_cast<u32>(pages.size()));
for (const auto& [page, data] : pages)
{
if (page >= PAGE_COUNT)
return false;
Put32(record, page);
record.insert(record.end(), data.begin(), data.end());
}
checksum = Common::SHA1::CalculateDigest(record);
}
const auto checksum = Common::SHA1::CalculateDigest(record);
if (!m_file.WriteArray(record.data(), record.size()) || !m_file.WriteArray(checksum) ||
!m_file.Flush())
bool success;
{
const Trace::Scope write_trace(Trace::Region::JournalWrite);
success = m_file.WriteArray(record.data(), record.size()) && m_file.WriteArray(checksum);
}
if (success)
{
const Trace::Scope flush_trace(Trace::Region::JournalFlush);
success = m_file.Flush();
}
if (!success)
{
Trace::Add(Trace::Counter::JournalErrors);
// Never acknowledge volatile writes as successful after a storage error.
ERROR_LOG_FMT(IOS, "Persistent NAND write failed; subsequent NAND writes are disabled");
m_file.Close();
return false;
}
Trace::Add(Trace::Counter::JournalTransactions);
Trace::Add(Trace::Counter::JournalBytes, record.size() + checksum.size());
return true;
}
} // namespace IOS::LLE
@@ -18,6 +18,7 @@
#include "Common/DynamicLibrary.h"
#include "Common/Logging/Log.h"
#include "Common/Network.h"
#include "Common/PerformanceTrace.h"
#include "Common/StringUtil.h"
namespace IOS::LLE
@@ -192,6 +193,8 @@ bool SlirpNetwork::Start(const std::string& directory, Receive receive, std::str
auto& self = *static_cast<Impl*>(opaque);
if (length >= 14 && length <= 1518 && self.receive)
{
Common::PerformanceTrace::Add(Common::PerformanceTrace::Counter::NatRXFrames);
Common::PerformanceTrace::Add(Common::PerformanceTrace::Counter::NatRXBytes, length);
if (++self.rx_frames <= 8)
INFO_LOG_FMT(IOS_NET, "Starlet NAT -> USB Ethernet: frame {} ({} bytes)", self.rx_frames,
length);
@@ -244,8 +247,11 @@ bool SlirpNetwork::Start(const std::string& directory, Receive receive, std::str
void SlirpNetwork::Input(std::span<const u8> frame)
{
const Common::PerformanceTrace::Scope trace(Common::PerformanceTrace::Region::NAT);
if (m_impl && frame.size() >= 14 && frame.size() <= 1518)
{
Common::PerformanceTrace::Add(Common::PerformanceTrace::Counter::NatTXFrames);
Common::PerformanceTrace::Add(Common::PerformanceTrace::Counter::NatTXBytes, frame.size());
if (++m_impl->tx_frames <= 8)
INFO_LOG_FMT(IOS_NET, "Starlet USB Ethernet -> NAT: frame {} ({} bytes, type {:#06x})",
m_impl->tx_frames, frame.size(), (u16(frame[12]) << 8) | frame[13]);
@@ -256,6 +262,7 @@ void SlirpNetwork::Input(std::span<const u8> frame)
void SlirpNetwork::Poll(u64 arm_cycles)
{
const Common::PerformanceTrace::Scope trace(Common::PerformanceTrace::Region::NAT);
if (!m_impl)
return;
auto& self = *m_impl;
@@ -285,6 +292,7 @@ void SlirpNetwork::Poll(u64 arm_cycles)
#endif
if (result < 0)
{
Common::PerformanceTrace::Add(Common::PerformanceTrace::Counter::NatPollErrors);
#ifdef _WIN32
const int error = WSAGetLastError();
#else
+266 -50
View File
@@ -4,17 +4,24 @@
#include "Core/IOS/Starlet/Starlet.h"
#include <algorithm>
#include <cstdlib>
#include <memory>
#include <string_view>
#include <vector>
#include "Common/ChunkFile.h"
#include "Common/GekkoDisassembler.h"
#include "Common/IOFile.h"
#include "Common/Logging/Log.h"
#include "Common/PerformanceTrace.h"
#include "Common/Timer.h"
#include "Core/Config/MainSettings.h"
#include "Core/CoreTiming.h"
#include "Core/HW/Memmap.h"
#include "Core/HW/ProcessorInterface.h"
#include "Core/HW/WII_IPC.h"
#include "Core/IOS/Starlet/ARMCore.h"
#include "Core/IOS/Starlet/BootstrapELF.h"
#include "Core/IOS/Starlet/StarletMemory.h"
#include "Core/PowerPC/MMU.h"
#include "Core/PowerPC/PowerPC.h"
@@ -22,6 +29,11 @@
namespace IOS::LLE
{
std::unique_ptr<Starlet> Starlet::Create(Core::System& system)
{
return std::make_unique<Starlet>(system);
}
Starlet::Starlet(Core::System& system) : m_system(system)
{
}
@@ -36,20 +48,113 @@ bool Starlet::Init(const std::string& dump_directory, std::string* error)
// Allocate the concrete bus here; its device-state members are part of the
// allocation size and must stay in lockstep with StarletMemory's definition.
m_memory = std::make_unique<StarletMemory>(m_system);
if (!m_memory->Init(dump_directory, error))
const std::string bootstrap_path = Config::Get(Config::MAIN_WII_STARLET_BOOTSTRAP_ELF);
if (bootstrap_path.empty() && !m_memory->Init(dump_directory, error))
{
m_memory.reset();
return false;
}
if (!bootstrap_path.empty())
{
File::IOFile file(bootstrap_path, "rb");
const u64 size = file ? file.GetSize() : 0;
if (size == 0 || size > 16 * 1024 * 1024)
{
if (error)
*error = "WiiStarletBootstrapELF must name a readable ELF of at most 16 MiB";
m_memory.reset();
return false;
}
std::vector<u8> image(static_cast<size_t>(size));
if (!file.ReadBytes(image.data(), image.size()))
{
if (error)
*error = "could not read WiiStarletBootstrapELF";
m_memory.reset();
return false;
}
m_memory->PrepareBootstrap();
// Revolution IOS Phase 06H, emulator only: a disposable writable NAND, and with it the
// MEM2 text segment of the disposable-image kernel. Nothing else accepts either.
const char* disposable_source = std::getenv("REV_BOOTSTRAP_NAND_DISPOSABLE");
const bool disposable = disposable_source && *disposable_source;
BootstrapELFInfo info;
if (!LoadBootstrapELF(image, *m_memory, &info, error, disposable))
{
m_memory.reset();
return false;
}
m_bootstrap = info;
INFO_LOG_FMT(IOS, "Starlet bootstrap ELF loaded: {} entry={:#010x} trace={:#010x}",
bootstrap_path, info.entry, info.trace);
if (disposable)
{
const char* read_only_path = std::getenv("REV_BOOTSTRAP_NAND");
const char* copy_path = std::getenv("REV_BOOTSTRAP_NAND_COPY");
if ((read_only_path && *read_only_path) || !copy_path || !*copy_path)
{
if (error)
*error = "REV_BOOTSTRAP_NAND_DISPOSABLE needs REV_BOOTSTRAP_NAND_COPY and excludes "
"REV_BOOTSTRAP_NAND";
m_memory.reset();
return false;
}
if (!m_memory->AttachDisposableNAND(disposable_source, copy_path, error))
{
m_memory.reset();
return false;
}
WARN_LOG_FMT(IOS, "Starlet bootstrap NAND DISPOSABLE: source {} (read-only), copy {}",
disposable_source, copy_path);
}
// Revolution IOS Phase 04B: optionally expose a raw NAND image, strictly read-only, so a
// bootstrap ELF can validate its NAND driver. Program and erase always fail in this mode.
if (const char* nand_path = std::getenv("REV_BOOTSTRAP_NAND"); nand_path && *nand_path)
{
if (!m_memory->AttachReadOnlyNAND(nand_path, error))
{
m_memory.reset();
return false;
}
INFO_LOG_FMT(IOS, "Starlet bootstrap NAND attached read-only: {}", nand_path);
}
// Revolution IOS Phase 04C: optional keys.bin so OTP reads match the attached dump.
if (const char* keys_path = std::getenv("REV_BOOTSTRAP_KEYS"); keys_path && *keys_path)
{
if (!m_memory->AttachKeys(keys_path, error))
{
m_memory.reset();
return false;
}
INFO_LOG_FMT(IOS, "Starlet bootstrap keys attached");
}
// StarletOS phase 11 (M1), emulator only: the emulated Wii Remotes for a Revolution session,
// with the identity paired in the attached NAND. Off unless asked for.
if (const char* wiimotes = std::getenv("REV_BOOTSTRAP_WIIMOTE"); wiimotes && *wiimotes == '1')
{
if (!m_memory->EnableBootstrapWiimotes(error))
{
m_memory.reset();
return false;
}
INFO_LOG_FMT(IOS, "Starlet bootstrap emulated Wii Remotes enabled");
}
}
// ARMCore owns generation-tagged software TLB and instruction caches, so
// construct it only after the complete physical bus exists.
m_core = std::make_unique<ARMCore>(*m_memory);
m_core = std::make_unique<ARMCore>(*m_memory,
Config::Get(Config::MAIN_WII_STARLET_JIT_MEMORY_PROFILING));
// m_core is declared after m_memory, so it is destroyed first.
m_memory->AttachInterruptLines(m_core.get());
#if defined(_M_X86_64)
m_core->SetJitEnabled(Config::Get(Config::MAIN_WII_STARLET_JIT));
#else
m_core->SetJitEnabled(false);
#endif
m_core->Reset(StarletMemory::BOOT_ROM_BASE);
m_core->Reset(m_bootstrap ? m_bootstrap->entry : StarletMemory::BOOT_ROM_BASE);
m_memory->SetWatchCore(m_core.get());
if (m_bootstrap)
m_core->SetBigEndian(true);
m_next_jit_diagnostic_instruction = 25'000'000;
m_next_realtime_diagnostic_ms = Common::Timer::NowMs() + 1000;
m_realtime_diagnostic_slice_count = 0;
@@ -62,6 +167,8 @@ bool Starlet::Init(const std::string& dump_directory, std::string* error)
m_system.GetCoreTiming().ScheduleEvent(0, m_run_event);
INFO_LOG_FMT(IOS, "Starlet LLE started at PC {:#010x} ({})", m_core->GetRegister(15),
m_core->IsJitEnabled() ? "JIT" : "interpreter");
INFO_LOG_FMT(IOS, "Starlet JIT detailed memory profiling={} (aggregate counts remain active)",
m_core->IsJitMemoryProfilingEnabled());
return true;
}
@@ -97,6 +204,7 @@ void Starlet::Shutdown()
m_run_event = nullptr;
m_core.reset();
m_memory.reset();
m_bootstrap.reset();
}
void Starlet::DoState(PointerWrap& p)
@@ -106,6 +214,14 @@ void Starlet::DoState(PointerWrap& p)
return;
m_memory->DoState(p);
m_core->DoState(p);
if (p.IsReadMode())
{
m_bootstrap_trace_length = 0;
m_last_probe_status = 0;
m_bootstrap_line_length = 0;
m_bootstrap_outcome_logged = false;
m_bootstrap_fault_logged = false;
}
}
u32 Starlet::GetPC() const
@@ -176,6 +292,7 @@ void Starlet::RunCallback(Core::System& system, u64, s64 cycles_late)
void Starlet::RunSlice(s64 cycles_late)
{
const Common::PerformanceTrace::SampleRoot trace_root;
if (!m_initialized)
return;
@@ -196,6 +313,41 @@ void Starlet::RunSlice(s64 cycles_late)
ARM_IDLE_SLICE_CYCLES :
(ipc_handshake_active ? ARM_IPC_SLICE_CYCLES : ARM_ACTIVE_SLICE_CYCLES);
m_core->RunCycles(arm_cycles);
if (m_bootstrap && !m_bootstrap_outcome_logged)
TraceBootstrap();
// Observe the PPC test program's result word. This is diagnostic only: all
// request and response traffic still passes through shared RAM and IPC MMIO.
if (m_bootstrap)
{
constexpr u32 PPC_PROBE_STATUS_ADDRESS = 0x00003c00;
const u32 status = m_system.GetMemory().Read_U32(PPC_PROBE_STATUS_ADDRESS);
if ((status & 0xffff0000) == 0x52500000 && status != m_last_probe_status)
{
m_last_probe_status = status;
INFO_LOG_FMT(IOS, "Broadway ios-probe status={:#010x}", status);
if (status == 0x52500002 || status == 0x52500003 || status == 0x52500005 ||
(status & 0xfffff000) == 0x5250e000)
{
constexpr u32 PPC_PROBE_COUNTERS_ADDRESS = 0x00003c20;
INFO_LOG_FMT(IOS,
"Broadway ios-probe counters sent={} received={} invalid={} duplicate={} "
"timeout={}",
m_system.GetMemory().Read_U32(PPC_PROBE_COUNTERS_ADDRESS),
m_system.GetMemory().Read_U32(PPC_PROBE_COUNTERS_ADDRESS + 4),
m_system.GetMemory().Read_U32(PPC_PROBE_COUNTERS_ADDRESS + 8),
m_system.GetMemory().Read_U32(PPC_PROBE_COUNTERS_ADDRESS + 12),
m_system.GetMemory().Read_U32(PPC_PROBE_COUNTERS_ADDRESS + 16));
// 0x52500005 / 0x5250e2xx: Revolution IOS Phase 04D /dev/fs cases.
if (status == 0x52500003 || status == 0x52500005 ||
(status & 0xffffff00) == 0x5250e100 || (status & 0xffffff00) == 0x5250e200)
{
INFO_LOG_FMT(IOS, "Broadway ios-probe checks={} failures={}",
m_system.GetMemory().Read_U32(PPC_PROBE_COUNTERS_ADDRESS + 20),
m_system.GetMemory().Read_U32(PPC_PROBE_COUNTERS_ADDRESS + 24));
}
}
}
}
// Keep host-clock reads and diagnostic formatting off the normal scheduler path.
const bool check_realtime_diagnostic =
@@ -205,6 +357,13 @@ void Starlet::RunSlice(s64 cycles_late)
const u64 now_ms = check_realtime_diagnostic ? Common::Timer::NowMs() : 0;
if (check_realtime_diagnostic && now_ms >= m_next_realtime_diagnostic_ms)
{
Common::PerformanceTrace::Snapshot(
m_core->GetTraceGeneration(), m_core->GetExecutedInstructions(),
m_core->GetJitNativeExecutedInstructions(), m_core->GetJitSlowReadCount(),
m_core->GetJitSlowWriteCount(), m_core->GetJitLifetimeCompiledBlockCount(),
m_core->GetJitFallbackInstructionCount(), m_core->GetRegister(15),
m_core->IsWaitingForExternalEvent());
m_memory->TraceNetwork();
m_next_realtime_diagnostic_ms = now_ms + 1000;
const PowerPC::PowerPCState& ppc = m_system.GetPPCState();
const PowerPC::TryReadInstResult instruction = m_system.GetMMU().TryReadInstruction(ppc.pc);
@@ -282,18 +441,19 @@ void Starlet::RunSlice(s64 cycles_late)
INFO_LOG_FMT(IOS,
"Starlet live JIT: instructions={} native={:.1f}% fallbacks={} blocks={} "
"translations={} slow-reads={} "
"slow-writes={} slow-regions=ram:{}/sram:{}/mmio:{}/other:{} "
"slow-writes={} memory-profile={} slow-regions=ram:{}/sram:{}/mmio:{}/other:{} "
"interval-fallbacks={} idle-polls={} ipc-armctrl={:#04x} "
"PC={:#010x} "
"CPSR={:#010x} irqflag={:#010x} irqmask={:#010x} fiqmask={:#010x}",
jit_executed, jit_executed == 0 ? 0.0 : 100.0 * jit_native / jit_executed,
m_core->GetJitFallbackInstructionCount(), m_core->GetJitCompiledBlockCount(),
m_core->GetJitAddressTranslationCount(), m_core->GetJitSlowReadCount(),
m_core->GetJitSlowWriteCount(), m_core->GetJitSlowRAMAccessCount(),
m_core->GetJitSlowSRAMAccessCount(), m_core->GetJitSlowMMIOAccessCount(),
m_core->GetJitSlowOtherAccessCount(), interval_fallbacks,
m_core->GetMemoryPollEntryCount(), ipc_arm_ctrl, m_core->GetRegister(15),
m_core->GetCPSR(), m_system.GetWiiIPC().ReadStarletRegister(0x38),
m_core->GetJitSlowWriteCount(), m_core->IsJitMemoryProfilingEnabled(),
m_core->GetJitSlowRAMAccessCount(), m_core->GetJitSlowSRAMAccessCount(),
m_core->GetJitSlowMMIOAccessCount(), m_core->GetJitSlowOtherAccessCount(),
interval_fallbacks, m_core->GetMemoryPollEntryCount(), ipc_arm_ctrl,
m_core->GetRegister(15), m_core->GetCPSR(),
m_system.GetWiiIPC().ReadStarletRegister(0x38),
m_system.GetWiiIPC().ReadStarletRegister(0x3c),
m_system.GetWiiIPC().ReadStarletRegister(0x40));
INFO_LOG_FMT(IOS,
@@ -322,50 +482,53 @@ void Starlet::RunSlice(s64 cycles_late)
m_core->GetJitFastEntryReplacementCount(),
m_core->GetJitInstructionCacheClearCount(), m_core->GetJitCodeSpaceClearCount(),
m_core->GetJitDiscardedBlockCount());
std::array<u32, 4> hot_sram_read_pages{};
std::array<u64, 4> hot_sram_read_page_counts{};
std::array<u32, 4> hot_sram_write_pages{};
std::array<u64, 4> hot_sram_write_page_counts{};
const auto rank_sram_page = [](u32 page, u64 count, auto& pages, auto& counts) {
for (size_t rank = 0; rank < counts.size(); ++rank)
{
if (count <= counts[rank])
continue;
for (size_t move = counts.size() - 1; move > rank; --move)
if (m_core->IsJitMemoryProfilingEnabled())
{
std::array<u32, 4> hot_sram_read_pages{};
std::array<u64, 4> hot_sram_read_page_counts{};
std::array<u32, 4> hot_sram_write_pages{};
std::array<u64, 4> hot_sram_write_page_counts{};
const auto rank_sram_page = [](u32 page, u64 count, auto& pages, auto& counts) {
for (size_t rank = 0; rank < counts.size(); ++rank)
{
counts[move] = counts[move - 1];
pages[move] = pages[move - 1];
if (count <= counts[rank])
continue;
for (size_t move = counts.size() - 1; move > rank; --move)
{
counts[move] = counts[move - 1];
pages[move] = pages[move - 1];
}
counts[rank] = count;
pages[rank] = page;
break;
}
counts[rank] = count;
pages[rank] = page;
break;
};
for (u32 page = 0; page < 32; ++page)
{
rank_sram_page(page, m_core->GetJitSlowSRAMPageReadAccessCount(page), hot_sram_read_pages,
hot_sram_read_page_counts);
rank_sram_page(page, m_core->GetJitSlowSRAMPageWriteAccessCount(page), hot_sram_write_pages,
hot_sram_write_page_counts);
}
INFO_LOG_FMT(
IOS,
"Starlet slow SRAM aliases=low:{}/high:{} reads:{}/writes:{} "
"hot-reads={:#04x}:{}, {:#04x}:{}, {:#04x}:{}, {:#04x}:{} "
"hot-writes={:#04x}:{}, {:#04x}:{}, {:#04x}:{}, {:#04x}:{}",
m_core->GetJitSlowSRAMLowAccessCount(), m_core->GetJitSlowSRAMHighAccessCount(),
m_core->GetJitSlowSRAMReadAccessCount(), m_core->GetJitSlowSRAMWriteAccessCount(),
hot_sram_read_pages[0], hot_sram_read_page_counts[0], hot_sram_read_pages[1],
hot_sram_read_page_counts[1], hot_sram_read_pages[2], hot_sram_read_page_counts[2],
hot_sram_read_pages[3], hot_sram_read_page_counts[3], hot_sram_write_pages[0],
hot_sram_write_page_counts[0], hot_sram_write_pages[1], hot_sram_write_page_counts[1],
hot_sram_write_pages[2], hot_sram_write_page_counts[2], hot_sram_write_pages[3],
hot_sram_write_page_counts[3]);
for (const auto& [key, samples] : m_core->TakeHotJitSlowMemorySamples(8))
{
const bool write = (key >> 32) != 0;
INFO_LOG_FMT(IOS, "Starlet slow memory {} address={:#010x} samples={}",
write ? "write" : "read", static_cast<u32>(key), samples);
}
};
for (u32 page = 0; page < 32; ++page)
{
rank_sram_page(page, m_core->GetJitSlowSRAMPageReadAccessCount(page), hot_sram_read_pages,
hot_sram_read_page_counts);
rank_sram_page(page, m_core->GetJitSlowSRAMPageWriteAccessCount(page), hot_sram_write_pages,
hot_sram_write_page_counts);
}
INFO_LOG_FMT(IOS,
"Starlet slow SRAM aliases=low:{}/high:{} reads:{}/writes:{} "
"hot-reads={:#04x}:{}, {:#04x}:{}, {:#04x}:{}, {:#04x}:{} "
"hot-writes={:#04x}:{}, {:#04x}:{}, {:#04x}:{}, {:#04x}:{}",
m_core->GetJitSlowSRAMLowAccessCount(), m_core->GetJitSlowSRAMHighAccessCount(),
m_core->GetJitSlowSRAMReadAccessCount(), m_core->GetJitSlowSRAMWriteAccessCount(),
hot_sram_read_pages[0], hot_sram_read_page_counts[0], hot_sram_read_pages[1],
hot_sram_read_page_counts[1], hot_sram_read_pages[2], hot_sram_read_page_counts[2],
hot_sram_read_pages[3], hot_sram_read_page_counts[3], hot_sram_write_pages[0],
hot_sram_write_page_counts[0], hot_sram_write_pages[1],
hot_sram_write_page_counts[1], hot_sram_write_pages[2],
hot_sram_write_page_counts[2], hot_sram_write_pages[3],
hot_sram_write_page_counts[3]);
for (const auto& [key, samples] : m_core->TakeHotJitSlowMemorySamples(8))
{
const bool write = (key >> 32) != 0;
INFO_LOG_FMT(IOS, "Starlet slow memory {} address={:#010x} samples={}",
write ? "write" : "read", static_cast<u32>(key), samples);
}
const ARMCore::HotPCSample current = m_core->GetCurrentPCSample();
INFO_LOG_FMT(IOS, "Starlet current PC {:#010x} {} instruction={:#010x}", current.address,
@@ -399,4 +562,57 @@ void Starlet::RunSlice(s64 cycles_late)
const s64 next = std::max<s64>(1, static_cast<s64>(broadway_cycles) - cycles_late);
m_system.GetCoreTiming().ScheduleEvent(next, m_run_event);
}
void Starlet::TraceBootstrap()
{
const BootstrapELFInfo& bootstrap = *m_bootstrap;
const u32 fault_code = m_memory->Read32(bootstrap.fault_code);
if (fault_code != 0 && !m_bootstrap_fault_logged)
{
ERROR_LOG_FMT(IOS,
"Starlet bootstrap exception {}: LR={:#010x} SPSR={:#010x} PC={:#010x}",
fault_code, m_memory->Read32(bootstrap.fault_lr),
m_memory->Read32(bootstrap.fault_spsr), m_core->GetRegister(15));
m_bootstrap_fault_logged = true;
m_bootstrap_outcome_logged = true;
return;
}
if (m_memory->Read32(bootstrap.trace) != 0x52455631)
return;
const u32 length = m_memory->Read32(bootstrap.trace + 4);
if (length > 1024)
{
ERROR_LOG_FMT(IOS, "Starlet bootstrap trace length is invalid: {}", length);
m_bootstrap_outcome_logged = true;
return;
}
if (length < m_bootstrap_trace_length)
{
m_bootstrap_trace_length = 0;
m_bootstrap_line_length = 0;
}
for (u32 index = m_bootstrap_trace_length; index < length; ++index)
{
const char character = static_cast<char>(m_memory->Read8(bootstrap.trace + 8 + index));
if (character == '\n')
{
const std::string_view line(m_bootstrap_line.data(), m_bootstrap_line_length);
INFO_LOG_FMT(IOS, "Starlet bootstrap: {}", line);
if (line == "REV:BOOT:IDLE" || line.starts_with("REV:PANIC") ||
line.starts_with("REV:FATAL"))
{
INFO_LOG_FMT(IOS, "Starlet bootstrap stopped at PC={:#010x} after {} instructions",
m_core->GetRegister(15), m_core->GetExecutedInstructions());
m_bootstrap_outcome_logged = true;
}
m_bootstrap_line_length = 0;
}
else if (m_bootstrap_line_length < m_bootstrap_line.size())
{
m_bootstrap_line[m_bootstrap_line_length++] = character;
}
}
m_bootstrap_trace_length = length;
}
} // namespace IOS::LLE
+12
View File
@@ -3,11 +3,13 @@
#pragma once
#include <array>
#include <memory>
#include <optional>
#include <string>
#include "Common/CommonTypes.h"
#include "Core/IOS/Starlet/BootstrapELF.h"
class PointerWrap;
@@ -32,6 +34,8 @@ class StarletMemory;
class Starlet final
{
public:
// Allocate in Starlet.cpp so callers never depend on this class's size.
static std::unique_ptr<Starlet> Create(Core::System& system);
explicit Starlet(Core::System& system);
~Starlet();
@@ -77,10 +81,18 @@ private:
static void RunCallback(Core::System& system, u64 userdata, s64 cycles_late);
void RunSlice(s64 cycles_late);
void TraceBootstrap();
Core::System& m_system;
std::unique_ptr<StarletMemory> m_memory;
std::unique_ptr<ARMCore> m_core;
std::optional<BootstrapELFInfo> m_bootstrap;
std::array<char, 256> m_bootstrap_line{};
u32 m_bootstrap_line_length = 0;
u32 m_bootstrap_trace_length = 0;
u32 m_last_probe_status = 0;
bool m_bootstrap_outcome_logged = false;
bool m_bootstrap_fault_logged = false;
CoreTiming::EventType* m_run_event = nullptr;
u64 m_next_jit_diagnostic_instruction = 25'000'000;
u64 m_next_realtime_diagnostic_ms = 0;
File diff suppressed because it is too large. Load diff
+68 -1
View File
@@ -11,6 +11,7 @@
#include <memory>
#include <mutex>
#include <optional>
#include <span>
#include <string>
#include <vector>
@@ -55,6 +56,39 @@ public:
}
bool Init(const std::string& dump_directory, std::string* error);
// Set up empty SRAM with BOOT0 hidden and the IOS-style high SRAM split for an external ELF.
void PrepareBootstrap();
// Bootstrap-ELF mode only: expose a raw NAND image to the NAND controller strictly read-only.
// No journal is opened; every program or erase command then fails with the controller error
// bit, so a Revolution IOS read-only driver can be validated without any write path.
bool AttachReadOnlyNAND(const std::string& path, std::string* error);
// Revolution IOS Phase 06H, emulator only: a disposable writable NAND. `source` is opened
// read-only exactly as above and is never written. `copy` must not exist; it is created as a
// byte-for-byte copy of the source, and every committed program or erase is mirrored into it
// before the in-memory overlay changes, so it holds the mutated image for independent
// checking. No journal is opened.
bool AttachDisposableNAND(const std::string& source, const std::string& copy,
std::string* error);
// Revolution IOS Phase 04C: bootstrap mode loads no keys, so the OTP reads zero. This
// loads a 1024-byte BootMii keys.bin so OTP reads return the console's own words.
bool AttachKeys(const std::string& path, std::string* error);
// StarletOS phase 11 (M1), emulator only: give a bootstrap-ELF session the emulated Wii
// Remotes of the original-IOS mode, with the identities already paired in the attached NAND's
// SYSCONF (keys needed to decrypt it). Never writes the NAND: without a paired identity the
// remotes keep their default addresses. Call after AttachKeys and a NAND attach.
bool EnableBootstrapWiimotes(std::string* error);
// StarletOS phase 11 (F1), emulator only: REV_WATCH=start:size[,start:size...] (hex) logs
// every Starlet CPU store (with the instruction's address and LR) and every device DMA write
// that touches one of those physical ranges. The ARM JIT sends the accesses that hit a watched
// range to its bus slow path, with the instruction address. `core` gives that address.
void SetWatchCore(const ARMCore* core);
// The core whose IRQ and FIQ lines follow Hollywood's ARM interrupt registers. A write to
// HW_ARMIRQFLAG, HW_ARMIRQMASK or HW_ARMFIQMASK re-samples both lines at once, as the
// level-sensitive Hollywood output follows them on hardware, instead of at the next scheduler
// slice: an acknowledged or masked interrupt is never taken again in between. Raising a cause
// still reaches the line at the next slice. The owner of both attaches the core once it exists
// and destroys it before the memory.
void AttachInterruptLines(ARMCore* core);
void Reset();
void DoState(PointerWrap& p);
@@ -68,17 +102,27 @@ public:
bool IsIdlePollAddress(u32 address, u32 size) const override;
bool IsSliceStablePollAddress(u32 address, u32 size) const override;
u8* GetFastmemBase() const override;
std::vector<std::pair<u32, u32>> GetWatchRanges() const override;
u8* GetFastmemSRAMBase() const override;
const bool* GetFastmemBoot0Mapped() const override;
const bool* GetFastmemSRAMSplitMode() const override;
const u8* GetDirectMemoryPointer(u32 address, u32 size) const override;
u64 GetCycles() const { return m_arm_cycles; }
void TraceNetwork() const;
std::optional<u32> TryReadBroadwayResetInstruction(u32 address) const;
void SetWiimoteSource(size_t index, WiimoteCommon::HIDWiimote* source);
bool EnableEthernetNAT(const std::string& runtime_directory, std::string* error);
private:
// Synthetic NAND fixtures exercise startup pairing without any console dumps or keys.
friend class StarletPairingTest;
void UpdateInterruptLines(u32 address);
void KeepMatchedAlarmAsserted(u32 address);
ARMCore* m_interrupt_core = nullptr;
friend class StarletDMATest;
static constexpr u32 NAND_PAGE_DATA_SIZE = 0x800;
static constexpr u32 NAND_PAGE_SPARE_SIZE = 0x40;
static constexpr u32 NAND_RAW_PAGE_SIZE = NAND_PAGE_DATA_SIZE + NAND_PAGE_SPARE_SIZE;
@@ -96,6 +140,9 @@ private:
void WriteMapped8(u32 address, u8 value);
u8 ReadDMA8(u32 address) const;
void WriteDMA8(u32 address, u8 value);
u8* GetDMAMemoryPointer(u32 address, size_t size) const;
void ReadDMABuffer(u32 address, std::span<u8> buffer) const;
void WriteDMABuffer(u32 address, std::span<const u8> buffer);
bool IsBootROMAddress(u32 address) const;
u32 GetBootROMOffset(u32 address) const;
u32 GetSRAMOffset(u32 address) const;
@@ -177,7 +224,7 @@ private:
void CompleteNANDCommand(u32 command);
bool ReadRawNANDPage(u32 page, NANDPage* raw);
bool CommitNANDPages(const NANDJournal::Pages& pages);
bool InstallEmulatedWiimotePairings();
bool InstallEmulatedWiimotePairings(bool allow_nand_rewrite = true);
bool ReadNANDPage(u32 command);
bool ReadNANDID(u32 command);
bool ReadNANDStatus(u32 command);
@@ -241,6 +288,7 @@ private:
bool m_sd_card_high_capacity = false;
bool m_sd_app_command = false;
bool m_sd_card_selected = false;
bool m_sd_high_speed = false;
u32 m_sd_block_length = 512;
u32 m_sdhc_status_before_write = 0;
u32 m_wifi_sdio_status_before_write = 0;
@@ -310,11 +358,30 @@ private:
bool m_seeprom_write_all = false;
u64 m_arm_cycles = 0;
u32 m_timer_offset = 0;
// The counter has reached HW_ALARM since it was last written.
bool m_alarm_matched = false;
bool m_initialized = false;
// Phase 11 F1 write watch (REV_WATCH); empty when off.
std::vector<std::pair<u32, u32>> m_watch_ranges;
const ARMCore* m_watch_core = nullptr;
bool m_watch_in_dma_buffer = false;
// Phase 11 H1: each watched range as the Starlet and the devices wrote it, and which of its
// bytes they wrote. Starlet reads and IPC replies compare guest memory with it.
std::vector<std::vector<u8>> m_watch_shadow;
std::vector<std::vector<u8>> m_watch_known;
bool WatchHit(u32 address, u32 size) const;
void WatchCPU(u32 address, u32 size, u32 value);
void WatchDMA(u32 address, const u8* data, u32 size);
void WatchRecord(u32 address, const u8* data, u32 size);
void WatchRead(u32 address, u32 size);
void WatchAudit();
bool m_nand_read_only = false;
bool m_boot0_mapped = true;
bool m_sram_split_mode = false;
// Host persistence is not serialized; savestates contain the complete overlay above.
std::unique_ptr<NANDJournal> m_nand_journal;
// Phase 06H: the disposable copy mirroring committed NAND pages (bootstrap mode only).
File::IOFile m_nand_disposable_copy;
std::unique_ptr<AX88772> m_ethernet;
std::unique_ptr<SlirpNetwork> m_ethernet_network;
};
@@ -15,6 +15,7 @@
#include "Common/CommonTypes.h"
#include "Common/JitRegister.h"
#include "Common/PerformanceTrace.h"
#include "Core/Config/MainSettings.h"
#include "Core/Core.h"
#include "Core/Host.h"
@@ -189,6 +190,10 @@ void JitBaseBlockCache::FinalizeBlock(JitBlock& block, bool block_link,
LinkBlock(block);
}
Common::PerformanceTrace::CodeMap("PPC", this, block.near_begin, block.near_end,
block.effectiveAddress, block.physicalAddress, "block-near");
Common::PerformanceTrace::CodeMap("PPC", this, block.far_begin, block.far_end,
block.effectiveAddress, block.physicalAddress, "block-far");
const Common::Symbol* symbol = nullptr;
if (Common::JitRegister::IsEnabled() &&
(symbol = m_jit.m_ppc_symbol_db.GetSymbolFromAddr(block.effectiveAddress)) != nullptr)
@@ -497,6 +502,8 @@ void JitBaseBlockCache::UnlinkBlock(const JitBlock& block)
void JitBaseBlockCache::DestroyBlock(JitBlock& block)
{
Common::PerformanceTrace::CodeReset("PPC", this, block.near_begin, block.near_end);
Common::PerformanceTrace::CodeReset("PPC", this, block.far_begin, block.far_end);
if (m_entry_points_ptr)
{
if (m_entry_points_ptr[block.fast_block_map_index] == block.normalEntry)
+15 -2
View File
@@ -54,6 +54,7 @@
#include "Core/HW/WII_IPC.h"
#include "Core/IOS/Starlet/Starlet.h"
#include "Core/IOS/Starlet/StarletMemory.h"
#include "Core/HW/WII_IPC.h"
#include "Core/PowerPC/GDBStub.h"
#include "Core/PowerPC/JitInterface.h"
#include "Core/PowerPC/PowerPC.h"
@@ -270,8 +271,12 @@ T MMU::ReadFromHardware(u32 em_address)
}
else
{
return static_cast<T>(
m_memory.GetMMIOMapping()->Read<std::make_unsigned_t<T>>(m_system, em_address));
const auto value =
m_memory.GetMMIOMapping()->Read<std::make_unsigned_t<T>>(m_system, em_address);
// StarletOS phase 11 (J1): Broadway's hardware reads in the IPC trace's window.
if (IOS::g_starletos_hardware_window) [[unlikely]]
IOS::TraceStarletOSHardwareAccess(m_system, false, em_address, sizeof(T), value);
return static_cast<T>(value);
}
}
@@ -459,6 +464,10 @@ void MMU::WriteToHardware(u32 em_address, const u32 data, const u32 size)
return;
}
// StarletOS phase 11 (J1): Broadway's hardware writes in the IPC trace's window.
if (IOS::g_starletos_hardware_window) [[unlikely]]
IOS::TraceStarletOSHardwareAccess(m_system, true, em_address, size, data);
switch (size)
{
case 1:
@@ -1485,6 +1494,10 @@ u32 MMU::IsOptimizableMMIOAccess(u32 address, u32 access_size) const
if (m_power_pc.GetMemChecks().HasAny())
return 0;
// StarletOS phase 11 (J1): no inlined MMIO reads while the hardware window may open.
if (IOS::StarletOSHardwareTraceRequested())
return 0;
if (!m_ppc_state.msr.DR)
return 0;
+1 -1
View File
@@ -97,7 +97,7 @@ struct CompressAndDumpStateArgs
static Common::WorkQueueThreadSP<CompressAndDumpStateArgs> s_compress_and_dump_thread;
// Don't forget to increase this after doing changes on the savestate system
constexpr u32 STATE_VERSION = 196; // Correct Hollywood DI/reset pending interrupt bit mapping.
constexpr u32 STATE_VERSION = 197; // Hollywood's alarm stays matched until HW_ALARM is rewritten.
// Increase this if the StateExtendedHeader definition changes
constexpr u32 EXTENDED_HEADER_VERSION = 1; // Last changed in PR 12217
+36 -1
View File
@@ -4,7 +4,9 @@
#include <cstdio>
#include <thread>
#include "Common/Logging/Log.h"
#include "Core/Core.h"
#include "Core/HW/Memmap.h"
#include "Core/System.h"
#include "DolphinNoGUI/Platform.h"
@@ -26,10 +28,43 @@ void PlatformHeadless::SetTitle(const std::string& title)
void PlatformHeadless::MainLoop()
{
bool diff_observed = false;
while (m_running.IsSet())
{
UpdateRunningFlag();
Core::HostDispatchJobs(Core::System::GetInstance());
auto& system = Core::System::GetInstance();
Core::HostDispatchJobs(system);
if (!diff_observed && Core::IsRunning(system))
{
auto& memory = system.GetMemory();
const u32 status = memory.Read_U32(0x00003c00);
if (status == 0x52500004 || (status & 0xffffff00) == 0x5250e100)
{
diff_observed = true;
INFO_LOG_FMT(IOS, "IOS_PROBE_DIFF_DONE status={:#010x}", status);
constexpr u32 trace_base = 0x00003d00;
const u32 count = memory.Read_U32(trace_base);
if (count > 8)
{
ERROR_LOG_FMT(IOS, "IOS_PROBE_DIFF_BAD_COUNT count={}", count);
}
else
{
for (u32 index = 0; index < count; ++index)
{
const u32 record = trace_base + 0x20 + index * 24;
INFO_LOG_FMT(IOS,
"IOS_PROBE_JSON {{\"schema\":1,\"index\":{},\"operation\":{},"
"\"argument\":{},\"return\":{},\"output\":{},\"ticks\":{},"
"\"status\":{}}}",
index, memory.Read_U32(record), memory.Read_U32(record + 4),
static_cast<s32>(memory.Read_U32(record + 8)),
memory.Read_U32(record + 12), memory.Read_U32(record + 16),
memory.Read_U32(record + 20));
}
}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
@@ -9,6 +9,7 @@
#include <implot.h>
#include "Common/HookableEvent.h"
#include "Common/PerformanceTrace.h"
#include "Core/Config/GraphicsSettings.h"
#include "Core/Core.h"
#include "VideoCommon/VideoConfig.h"
@@ -24,6 +25,7 @@ PerformanceMetrics::PerformanceMetrics()
void PerformanceMetrics::Reset()
{
Common::PerformanceTrace::Marker("PerformanceMetricsReset");
m_fps_counter.Reset();
m_vps_counter.Reset();
@@ -38,11 +40,13 @@ void PerformanceMetrics::Reset()
void PerformanceMetrics::CountFrame()
{
Common::PerformanceTrace::Frame("produced");
m_fps_counter.Count();
}
void PerformanceMetrics::CountVBlank()
{
Common::PerformanceTrace::Frame("vblank");
m_vps_counter.Count();
}
@@ -62,6 +66,7 @@ void PerformanceMetrics::AdjustClockSpeed(s64 ticks, u32 new_ppc_clock, u32 old_
void PerformanceMetrics::CountPerformanceMarker(s64 core_ticks, u32 ticks_per_second)
{
Common::PerformanceTrace::Frame("guest-clock", core_ticks, ticks_per_second);
const auto clock_time = Clock::now();
const auto work_time = clock_time - m_time_sleeping;
+58 -21
View File
@@ -1,25 +1,62 @@
enable_testing()
add_custom_target(unittests)
add_custom_command(TARGET unittests POST_BUILD COMMAND ${CMAKE_CTEST_COMMAND} "--output-on-failure")
string(APPEND CMAKE_RUNTIME_OUTPUT_DIRECTORY "/Tests")
add_executable(tests EXCLUDE_FROM_ALL UnitTestsMain.cpp StubHost.cpp)
set_target_properties(tests PROPERTIES FOLDER Tests)
target_link_libraries(tests PRIVATE fmt::fmt gtest::gtest core uicommon)
add_test(NAME tests COMMAND tests)
add_custom_command(TARGET tests POST_BUILD
COMMAND ${CMAKE_COMMAND} -E remove_directory "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Sys"
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/Data/Sys" "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Sys"
)
enable_testing()
add_custom_target(unittests)
add_custom_command(TARGET unittests POST_BUILD COMMAND ${CMAKE_CTEST_COMMAND} "--output-on-failure")
string(APPEND CMAKE_RUNTIME_OUTPUT_DIRECTORY "/Tests")
add_executable(tests EXCLUDE_FROM_ALL UnitTestsMain.cpp StubHost.cpp)
set_target_properties(tests PROPERTIES FOLDER Tests)
target_link_libraries(tests PRIVATE fmt::fmt gtest::gtest core uicommon)
add_test(NAME tests COMMAND tests)
add_custom_command(TARGET tests POST_BUILD
COMMAND ${CMAKE_COMMAND} -E remove_directory "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Sys"
COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_SOURCE_DIR}/Data/Sys" "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/Sys"
)
add_dependencies(unittests tests)
macro(add_dolphin_test target)
add_library(${target} OBJECT ${ARGN})
target_link_libraries(${target} PUBLIC fmt::fmt gtest::gtest PRIVATE core uicommon)
target_link_libraries(tests PRIVATE ${target})
endmacro()
# StarletBootstrapProbe's --broadway-h1a client (Tools/StarletBootstrapProbe/ProbeBroadway.h):
# StarOS's bench loader sources, vendored unchanged in StarOSLoader/, over the probe's host HAL in
# BroadwayHAL/. Their SHA-256s, computed here, are built in: the probe prints them.
set(STAROS_LOADER_DIR ${CMAKE_SOURCE_DIR}/Tools/StarletBootstrapProbe/StarOSLoader)
set(STAROS_LOADER_SOURCES "// Generated by Source/UnitTests/CMakeLists.txt: the vendored StarOS loader sources.\n#pragma once\n#define STAROS_LOADER_SHA256 \\\n")
foreach(name hw0c.c hw0c.h hw0d.c hw0d.h h1a.c h1a.h staros_hw0c.h staros_hw0d.h staros_h1a.h)
file(SHA256 ${STAROS_LOADER_DIR}/${name} hash)
string(APPEND STAROS_LOADER_SOURCES " \"${name} ${hash}\\n\" \\\n")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${STAROS_LOADER_DIR}/${name})
endforeach()
string(APPEND STAROS_LOADER_SOURCES " \"\"\n")
file(CONFIGURE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/StarletProbeBroadway/ProbeBroadwaySources.h
CONTENT "${STAROS_LOADER_SOURCES}" @ONLY)
add_library(StarletProbeBroadway STATIC EXCLUDE_FROM_ALL
${CMAKE_SOURCE_DIR}/Tools/StarletBootstrapProbe/ProbeBroadway.cpp
${STAROS_LOADER_DIR}/hw0c.c ${STAROS_LOADER_DIR}/hw0d.c ${STAROS_LOADER_DIR}/h1a.c)
set_target_properties(StarletProbeBroadway PROPERTIES C_STANDARD 11 C_STANDARD_REQUIRED ON)
target_compile_definitions(StarletProbeBroadway PRIVATE STAROS_HW0C STAROS_HW0D STAROS_H1A
STAROS_HW0F_HOST STAROS_HW0D_HOST STAROS_H1A_HOST)
target_include_directories(StarletProbeBroadway
PRIVATE ${CMAKE_SOURCE_DIR}/Tools/StarletBootstrapProbe/BroadwayHAL ${STAROS_LOADER_DIR}
${CMAKE_CURRENT_BINARY_DIR}/StarletProbeBroadway
PUBLIC ${CMAKE_SOURCE_DIR}/Tools/StarletBootstrapProbe)
target_link_libraries(StarletProbeBroadway PUBLIC common PRIVATE fmt::fmt)
add_subdirectory(Common)
add_subdirectory(Core)
# Runs a real Starlet ELF through the fork's CPU and SRAM bus without NAND or a frontend.
add_executable(StarletBootstrapProbe EXCLUDE_FROM_ALL
${CMAKE_SOURCE_DIR}/Tools/StarletBootstrapProbe/StarletBootstrapProbe.cpp StubHost.cpp)
target_link_libraries(StarletBootstrapProbe PRIVATE fmt::fmt core uicommon StarletProbeBroadway)
macro(add_dolphin_test target)
add_library(${target} OBJECT ${ARGN})
target_link_libraries(${target} PUBLIC fmt::fmt gtest::gtest PRIVATE core uicommon)
target_link_libraries(tests PRIVATE ${target})
endmacro()
add_subdirectory(Common)
add_subdirectory(Core)
add_subdirectory(VideoCommon)
# Opt-in local trace qualification; never starts a console or accesses a NAND dump.
if(WIN32 AND _M_X86_64)
add_executable(TraceProbeP1 EXCLUDE_FROM_ALL
${CMAKE_SOURCE_DIR}/Tools/PerformanceTrace/TraceProbeP1.cpp StubHost.cpp)
target_link_libraries(TraceProbeP1 PRIVATE fmt::fmt core uicommon)
endif()
+1
View File
@@ -17,6 +17,7 @@ add_dolphin_test(FloatUtilsTest FloatUtilsTest.cpp)
add_dolphin_test(MathUtilTest MathUtilTest.cpp)
add_dolphin_test(MutexTest MutexTest.cpp)
add_dolphin_test(NandPathsTest NandPathsTest.cpp)
add_dolphin_test(PerformanceTraceTest PerformanceTraceTest.cpp)
add_dolphin_test(SettingsHandlerTest SettingsHandlerTest.cpp)
add_dolphin_test(SPSCQueueTest SPSCQueueTest.cpp)
add_dolphin_test(StringUtilTest StringUtilTest.cpp)
@@ -0,0 +1,56 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "Common/PerformanceTrace.h"
#include <gtest/gtest.h>
using namespace Common::PerformanceTrace;
TEST(PerformanceTrace, NestedTimesAreExclusive)
{
ScopeStack stack;
ASSERT_TRUE(stack.Begin(Region::Slice, 100));
ASSERT_TRUE(stack.Begin(Region::ARM, 110));
ASSERT_TRUE(stack.Begin(Region::Journal, 120));
ASSERT_TRUE(stack.End(150));
ASSERT_TRUE(stack.End(180));
ASSERT_TRUE(stack.End(200));
const auto& t = stack.Timings();
EXPECT_EQ(t[static_cast<size_t>(Region::Slice)].inclusive, 100u);
EXPECT_EQ(t[static_cast<size_t>(Region::Slice)].exclusive, 30u);
EXPECT_EQ(t[static_cast<size_t>(Region::ARM)].exclusive, 40u);
EXPECT_EQ(t[static_cast<size_t>(Region::Journal)].exclusive, 30u);
EXPECT_EQ(stack.Errors(), 0u);
EXPECT_EQ(stack.Depth(), 0u);
}
TEST(PerformanceTrace, RecursiveRegionAndReset)
{
ScopeStack stack;
ASSERT_TRUE(stack.Begin(Region::ARM, 0));
ASSERT_TRUE(stack.Begin(Region::ARM, 10));
ASSERT_TRUE(stack.End(20));
ASSERT_TRUE(stack.End(30));
EXPECT_EQ(stack.Timings()[static_cast<size_t>(Region::ARM)].exclusive, 30u);
EXPECT_EQ(stack.Timings()[static_cast<size_t>(Region::ARM)].calls, 2u);
stack.Reset();
EXPECT_EQ(stack.Timings()[static_cast<size_t>(Region::ARM)].calls, 0u);
EXPECT_EQ(stack.Depth(), 0u);
}
TEST(PerformanceTrace, InvalidClockAndUnderflowAreReported)
{
ScopeStack stack;
EXPECT_FALSE(stack.End(0));
ASSERT_TRUE(stack.Begin(Region::ARM, 100));
EXPECT_FALSE(stack.End(99));
EXPECT_EQ(stack.Errors(), 2u);
EXPECT_EQ(stack.Timings()[static_cast<size_t>(Region::ARM)].inclusive, 0u);
}
TEST(PerformanceTrace, DepthOverflowIsBounded)
{
ScopeStack stack;
for (u64 i = 0; i < 32; ++i)
ASSERT_TRUE(stack.Begin(Region::ARM, i));
EXPECT_FALSE(stack.Begin(Region::ARM, 32));
for (u64 i = 0; i < 32; ++i)
ASSERT_TRUE(stack.End(40 + i));
EXPECT_EQ(stack.Depth(), 0u);
EXPECT_EQ(stack.Errors(), 1u);
}
+70 -45
View File
@@ -1,55 +1,80 @@
add_dolphin_test(MMIOTest MMIOTest.cpp)
add_dolphin_test(PageFaultTest PageFaultTest.cpp)
add_dolphin_test(CoreTimingTest CoreTimingTest.cpp)
add_dolphin_test(PatchAllowlistTest PatchAllowlistTest.cpp)
add_dolphin_test(DSPAcceleratorTest DSP/DSPAcceleratorTest.cpp)
add_dolphin_test(DSPAssemblyTest
DSP/DSPAssemblyTest.cpp
DSP/DSPTestBinary.cpp
DSP/DSPTestText.cpp
DSP/HermesBinary.cpp
DSP/HermesText.cpp
)
add_dolphin_test(MMIOTest MMIOTest.cpp)
add_dolphin_test(PageFaultTest PageFaultTest.cpp)
add_dolphin_test(CoreTimingTest CoreTimingTest.cpp)
add_dolphin_test(PatchAllowlistTest PatchAllowlistTest.cpp)
add_dolphin_test(DSPAcceleratorTest DSP/DSPAcceleratorTest.cpp)
add_dolphin_test(DSPAssemblyTest
DSP/DSPAssemblyTest.cpp
DSP/DSPTestBinary.cpp
DSP/DSPTestText.cpp
DSP/HermesBinary.cpp
DSP/HermesText.cpp
)
add_dolphin_test(ESFormatsTest IOS/ES/FormatsTest.cpp)
add_dolphin_test(StarletARMCoreTest IOS/Starlet/ARMCoreTest.cpp)
add_dolphin_test(StarletBootstrapELFTest IOS/Starlet/BootstrapELFTest.cpp)
# StarletBootstrapProbe's StarOS panic check (Tools/StarletBootstrapProbe/StarOSPanicCheck.h).
add_dolphin_test(StarletProbePanicCheckTest IOS/Starlet/ProbePanicCheckTest.cpp)
target_include_directories(StarletProbePanicCheckTest PRIVATE ${CMAKE_SOURCE_DIR}/Tools/StarletBootstrapProbe)
# StarletBootstrapProbe's --cycles budget (Tools/StarletBootstrapProbe/ProbeBudget.h).
add_dolphin_test(StarletProbeBudgetTest IOS/Starlet/ProbeBudgetTest.cpp)
target_include_directories(StarletProbeBudgetTest PRIVATE ${CMAKE_SOURCE_DIR}/Tools/StarletBootstrapProbe)
# StarletBootstrapProbe's SBR1 ring text (Tools/StarletBootstrapProbe/ProbeRing.h).
add_dolphin_test(StarletProbeRingTest IOS/Starlet/ProbeRingTest.cpp)
target_include_directories(StarletProbeRingTest PRIVATE ${CMAKE_SOURCE_DIR}/Tools/StarletBootstrapProbe)
# StarletBootstrapProbe's --stage-spk checks (Tools/StarletBootstrapProbe/ProbeStaging.h).
add_dolphin_test(StarletProbeStagingTest IOS/Starlet/ProbeStagingTest.cpp)
target_include_directories(StarletProbeStagingTest PRIVATE ${CMAKE_SOURCE_DIR}/Tools/StarletBootstrapProbe)
# StarletBootstrapProbe's --ipc-script (Tools/StarletBootstrapProbe/ProbeScript.h) and its flag.
add_dolphin_test(StarletProbeScriptTest IOS/Starlet/ProbeScriptTest.cpp)
target_include_directories(StarletProbeScriptTest PRIVATE ${CMAKE_SOURCE_DIR}/Tools/StarletBootstrapProbe)
add_dolphin_test(StarletProbeInterruptTest IOS/Starlet/ProbeInterruptTest.cpp)
# StarletBootstrapProbe's --broadway-h1a client (Tools/StarletBootstrapProbe/ProbeBroadway.h).
add_dolphin_test(StarletProbeBroadwayTest IOS/Starlet/ProbeBroadwayTest.cpp)
target_link_libraries(StarletProbeBroadwayTest PUBLIC StarletProbeBroadway)
target_include_directories(StarletProbeBroadwayTest PRIVATE ${STAROS_LOADER_DIR})
add_dolphin_test(StarletDMATest IOS/Starlet/DMATest.cpp)
add_dolphin_test(StarletSRAMReadTest IOS/Starlet/SRAMReadTest.cpp)
add_dolphin_test(StarletSRAMWriteTest IOS/Starlet/SRAMWriteTest.cpp)
add_dolphin_test(StarletNANDJournalTest IOS/Starlet/NANDJournalTest.cpp)
add_dolphin_test(StarletPairingTest IOS/Starlet/PairingTest.cpp)
add_dolphin_test(StarletEthernetTest IOS/Starlet/AX88772Test.cpp)
target_include_directories(StarletEthernetTest PRIVATE ${PROJECT_SOURCE_DIR}/Externals/libslirp/include)
add_dolphin_test(FileSystemTest IOS/FS/FileSystemTest.cpp)
add_dolphin_test(SkylandersTest IOS/USB/SkylandersTest.cpp)
if(_M_X86_64)
add_dolphin_test(PowerPCTest
PowerPC/DivUtilsTest.cpp
PowerPC/PageTableHostMappingTest.cpp
add_dolphin_test(SkylandersTest IOS/USB/SkylandersTest.cpp)
if(_M_X86_64)
add_dolphin_test(PowerPCTest
PowerPC/DivUtilsTest.cpp
PowerPC/PageTableHostMappingTest.cpp
PowerPC/Jit64Common/ConvertDoubleToSingle.cpp
PowerPC/Jit64Common/DCache.cpp
PowerPC/Jit64Common/Fres.cpp
PowerPC/Jit64Common/Frsqrte.cpp
)
elseif(_M_ARM_64)
add_dolphin_test(PowerPCTest
PowerPC/DivUtilsTest.cpp
PowerPC/PageTableHostMappingTest.cpp
PowerPC/JitArm64/ConvertSingleDouble.cpp
PowerPC/JitArm64/FPRF.cpp
PowerPC/JitArm64/Fres.cpp
PowerPC/JitArm64/Frsqrte.cpp
PowerPC/JitArm64/MovI2R.cpp
)
else()
add_dolphin_test(PowerPCTest
PowerPC/DivUtilsTest.cpp
PowerPC/PageTableHostMappingTest.cpp
)
endif()
target_sources(PowerPCTest PRIVATE
PowerPC/TestValues.h
StubJit.h
)
PowerPC/Jit64Common/Fres.cpp
PowerPC/Jit64Common/Frsqrte.cpp
)
elseif(_M_ARM_64)
add_dolphin_test(PowerPCTest
PowerPC/DivUtilsTest.cpp
PowerPC/PageTableHostMappingTest.cpp
PowerPC/JitArm64/ConvertSingleDouble.cpp
PowerPC/JitArm64/FPRF.cpp
PowerPC/JitArm64/Fres.cpp
PowerPC/JitArm64/Frsqrte.cpp
PowerPC/JitArm64/MovI2R.cpp
)
else()
add_dolphin_test(PowerPCTest
PowerPC/DivUtilsTest.cpp
PowerPC/PageTableHostMappingTest.cpp
)
endif()
target_sources(PowerPCTest PRIVATE
PowerPC/TestValues.h
StubJit.h
)
@@ -4,14 +4,18 @@
#include <algorithm>
#include <array>
#include <bit>
#include <chrono>
#include <initializer_list>
#include <iostream>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "Common/ChunkFile.h"
#include "Common/CommonTypes.h"
#include "Common/Swap.h"
#include "Core/Core.h"
#include "Core/HW/WII_IPC.h"
#include "Core/IOS/Starlet/ARMCore.h"
@@ -176,6 +180,7 @@ public:
const u8* GetDirectMemoryPointer(u32 address, u32 size) const override
{
++m_direct_pointer_count;
const size_t offset = ToOffset(address);
if (size == 0 || offset > m_memory.size() || size > m_memory.size() - offset)
return nullptr;
@@ -192,7 +197,6 @@ public:
void SetSRAMFastmemEnabled(bool enabled) { m_sram_fastmem_enabled = enabled; }
void SetBoot0Mapped(bool mapped) { m_boot0_mapped = mapped; }
void SetSRAMSplitMode(bool split) { m_sram_split_mode = split; }
void WriteSRAM32(u32 offset, u32 value)
{
ASSERT_LT(offset + 3, SRAM_SIZE);
@@ -241,6 +245,7 @@ public:
u64 GetRead8Count() const { return m_read8_count; }
u64 GetRead16Count() const { return m_read16_count; }
u64 GetRead32Count() const { return m_read32_count; }
u64 GetDirectPointerCount() const { return m_direct_pointer_count; }
u32 GetMMIOWord() const { return m_mmio_word; }
void ResetReadCounts()
{
@@ -270,6 +275,7 @@ private:
u64 m_read8_count = 0;
u64 m_read16_count = 0;
u64 m_read32_count = 0;
mutable u64 m_direct_pointer_count = 0;
u32 m_mmio_word = 0;
bool m_idle_poll_safe = true;
bool m_slice_stable_poll_safe = false;
@@ -562,6 +568,208 @@ TEST(StarletRegisters, WideTimerAndInterruptAccessesMatchHardwareSemantics)
EXPECT_EQ(memory.Read32(arm_irq_mask), 0x800619efu);
}
TEST(StarletInterrupts, InterruptRegisterWritesResampleTheAttachedCoreLines)
{
constexpr u32 hardware_base = 0x0d800000;
constexpr u32 arm_irq_flag = hardware_base + 0x38;
constexpr u32 arm_irq_mask = hardware_base + 0x3c;
constexpr u32 arm_fiq_mask = hardware_base + 0x40;
Core::DeclareAsCPUThread();
auto& system = Core::System::GetInstance();
auto& ipc = system.GetWiiIPC();
ipc.Reset();
StarletMemory memory(system);
memory.Reset();
ARMCore core(memory);
memory.AttachInterruptLines(&core);
// A latched, unmasked timer interrupt, sampled at a scheduler slice's start.
memory.Write32(arm_irq_mask, INT_CAUSE_TIMER);
ipc.SetStarletInterrupt(INT_CAUSE_TIMER, true);
core.SetIRQLine(ipc.IsStarletIRQAsserted());
ASSERT_TRUE(core.IsIRQLineAsserted());
// Acknowledging it lowers the line at once, not at the next slice.
memory.Write32(arm_irq_flag, INT_CAUSE_TIMER);
EXPECT_FALSE(core.IsIRQLineAsserted());
// Raising a cause still waits for the slice; masking and unmasking a latched cause do not.
ipc.SetStarletInterrupt(INT_CAUSE_TIMER, true);
EXPECT_FALSE(core.IsIRQLineAsserted());
memory.Write32(arm_irq_mask, 0);
EXPECT_FALSE(core.IsIRQLineAsserted());
memory.Write32(arm_irq_mask, INT_CAUSE_TIMER);
EXPECT_TRUE(core.IsIRQLineAsserted());
// The byte-assembled write path acknowledges as the wide one does.
for (u32 i = 0; i < 4; ++i)
memory.Write8(arm_irq_flag + i, static_cast<u8>(INT_CAUSE_TIMER >> (24 - 8 * i)));
EXPECT_FALSE(core.IsIRQLineAsserted());
// An acknowledgement re-samples the FIQ line from the same flags.
memory.Write32(arm_fiq_mask, INT_CAUSE_TIMER);
ipc.SetStarletInterrupt(INT_CAUSE_TIMER, true);
core.SetFIQLine(ipc.IsStarletFIQAsserted());
ASSERT_TRUE(core.IsFIQLineAsserted());
memory.Write32(arm_irq_flag, INT_CAUSE_TIMER);
EXPECT_FALSE(core.IsFIQLineAsserted());
}
TEST(StarletInterrupts, FIQMaskWritesResampleTheAttachedCoreLine)
{
constexpr u32 hardware_base = 0x0d800000;
constexpr u32 arm_irq_flag = hardware_base + 0x38;
constexpr u32 arm_fiq_mask = hardware_base + 0x40;
Core::DeclareAsCPUThread();
auto& system = Core::System::GetInstance();
auto& ipc = system.GetWiiIPC();
ipc.Reset();
StarletMemory memory(system);
memory.Reset();
ARMCore core(memory);
memory.AttachInterruptLines(&core);
// A latched cause routed to no FIQ, sampled at a scheduler slice's start.
ipc.SetStarletInterrupt(INT_CAUSE_TIMER, true);
core.SetFIQLine(ipc.IsStarletFIQAsserted());
ASSERT_FALSE(core.IsFIQLineAsserted());
// Unmasking it as an FIQ raises the line at once; masking it lowers the line at once.
memory.Write32(arm_fiq_mask, INT_CAUSE_TIMER);
EXPECT_TRUE(core.IsFIQLineAsserted());
EXPECT_FALSE(core.IsIRQLineAsserted());
memory.Write32(arm_fiq_mask, 0);
EXPECT_FALSE(core.IsFIQLineAsserted());
// The byte-assembled write path re-samples the same way.
for (u32 i = 0; i < 4; ++i)
memory.Write8(arm_fiq_mask + i, static_cast<u8>(INT_CAUSE_TIMER >> (24 - 8 * i)));
EXPECT_TRUE(core.IsFIQLineAsserted());
memory.Write32(arm_irq_flag, INT_CAUSE_TIMER);
EXPECT_FALSE(core.IsFIQLineAsserted());
}
TEST(StarletTimer, MatchedAlarmStaysAssertedUntilRewritten)
{
constexpr u32 hardware_base = 0x0d800000;
constexpr u32 timer = hardware_base + 0x10;
constexpr u32 alarm = hardware_base + 0x14;
constexpr u32 arm_irq_flag = hardware_base + 0x38;
constexpr u32 arm_irq_mask = hardware_base + 0x3c;
Core::DeclareAsCPUThread();
auto& system = Core::System::GetInstance();
auto& ipc = system.GetWiiIPC();
ipc.Reset();
StarletMemory memory(system);
memory.Reset();
ARMCore core(memory);
memory.AttachInterruptLines(&core);
const auto timer_cause = [&ipc] { return ipc.ReadStarletRegister(0x38) & INT_CAUSE_TIMER; };
memory.Write32(arm_irq_mask, INT_CAUSE_TIMER);
memory.Write32(alarm, 64);
memory.AdvanceCycles(64 * 128);
ASSERT_EQ(memory.Read32(timer), 64u);
ASSERT_EQ(timer_cause(), INT_CAUSE_TIMER);
core.SetIRQLine(ipc.IsStarletIRQAsserted());
ASSERT_TRUE(core.IsIRQLineAsserted());
// Acknowledged before HW_ALARM is rewritten, after the counter moved on: the
// cause and the line stay asserted (the console's StarOS M3C gate H1).
memory.AdvanceCycles(32 * 128);
memory.Write32(arm_irq_flag, INT_CAUSE_TIMER);
EXPECT_EQ(timer_cause(), INT_CAUSE_TIMER);
EXPECT_TRUE(core.IsIRQLineAsserted());
for (u32 i = 0; i < 4; ++i)
memory.Write8(arm_irq_flag + i, static_cast<u8>(INT_CAUSE_TIMER >> (24 - 8 * i)));
EXPECT_EQ(timer_cause(), INT_CAUSE_TIMER);
// A counter write does not end the match either.
memory.Write32(timer, 0);
memory.Write32(arm_irq_flag, INT_CAUSE_TIMER);
EXPECT_EQ(timer_cause(), INT_CAUSE_TIMER);
// MINI's order: rewrite HW_ALARM ahead, then acknowledge. The rewrite alone
// acknowledges nothing; the acknowledgement then clears the cause and the line.
memory.Write32(alarm, memory.Read32(timer) + 64);
EXPECT_EQ(timer_cause(), INT_CAUSE_TIMER);
memory.Write32(arm_irq_flag, INT_CAUSE_TIMER);
EXPECT_EQ(timer_cause(), 0u);
EXPECT_FALSE(core.IsIRQLineAsserted());
// The next match latches again.
memory.AdvanceCycles(64 * 128);
EXPECT_EQ(timer_cause(), INT_CAUSE_TIMER);
memory.Write32(arm_irq_flag, INT_CAUSE_TIMER);
EXPECT_EQ(timer_cause(), INT_CAUSE_TIMER);
}
TEST(StarletTimer, MatchedAlarmSurvivesStateRoundTrip)
{
constexpr u32 alarm = 0x0d800014;
constexpr u32 arm_irq_flag = 0x0d800038;
Core::DeclareAsCPUThread();
auto& system = Core::System::GetInstance();
auto& ipc = system.GetWiiIPC();
ipc.Reset();
StarletMemory memory(system);
memory.Reset();
memory.Write32(alarm, 8);
memory.AdvanceCycles(8 * 128);
ASSERT_EQ(ipc.ReadStarletRegister(0x38) & INT_CAUSE_TIMER, INT_CAUSE_TIMER);
std::vector<u8> state_buffer(1024 * 1024);
u8* state_pointer = state_buffer.data();
PointerWrap writer(&state_pointer, state_buffer.size(), PointerWrap::Mode::Write);
memory.DoState(writer);
ASSERT_TRUE(writer.IsWriteMode());
const size_t state_size = state_pointer - state_buffer.data();
// A reset forgets the match: the acknowledgement clears the cause.
memory.Reset();
memory.Write32(arm_irq_flag, INT_CAUSE_TIMER);
ASSERT_EQ(ipc.ReadStarletRegister(0x38) & INT_CAUSE_TIMER, 0u);
// The restored state holds it again.
state_pointer = state_buffer.data();
PointerWrap reader(&state_pointer, state_size, PointerWrap::Mode::Read);
memory.DoState(reader);
ASSERT_TRUE(reader.IsReadMode());
memory.Write32(arm_irq_flag, INT_CAUSE_TIMER);
EXPECT_EQ(ipc.ReadStarletRegister(0x38) & INT_CAUSE_TIMER, INT_CAUSE_TIMER);
}
TEST(StarletInterrupts, AcknowledgingOneOfTwoPendingSourcesKeepsIRQAsserted)
{
constexpr u32 hardware_base = 0x0d800000;
constexpr u32 arm_irq_flag = hardware_base + 0x38;
constexpr u32 arm_irq_mask = hardware_base + 0x3c;
Core::DeclareAsCPUThread();
auto& system = Core::System::GetInstance();
auto& ipc = system.GetWiiIPC();
ipc.Reset();
StarletMemory memory(system);
memory.Reset();
ARMCore core(memory);
memory.AttachInterruptLines(&core);
memory.Write32(arm_irq_mask, INT_CAUSE_TIMER | INT_CAUSE_NAND);
ipc.SetStarletInterrupt(INT_CAUSE_TIMER, true);
ipc.SetStarletInterrupt(INT_CAUSE_NAND, true);
core.SetIRQLine(ipc.IsStarletIRQAsserted());
ASSERT_TRUE(core.IsIRQLineAsserted());
// One source acknowledged: the other still holds the line.
memory.Write32(arm_irq_flag, INT_CAUSE_TIMER);
EXPECT_TRUE(core.IsIRQLineAsserted());
EXPECT_EQ(memory.Read32(arm_irq_flag) & (INT_CAUSE_TIMER | INT_CAUSE_NAND), INT_CAUSE_NAND);
// The last one acknowledged: the line drops.
memory.Write32(arm_irq_flag, INT_CAUSE_NAND);
EXPECT_FALSE(core.IsIRQLineAsserted());
EXPECT_EQ(memory.Read32(arm_irq_flag) & (INT_CAUSE_TIMER | INT_CAUSE_NAND), 0u);
}
TEST(StarletInterrupts, DriveAndResetUseDistinctHollywoodLines)
{
// Hollywood IRQ numbers, not the Broadway Processor Interface's DVD line.
@@ -1751,6 +1959,83 @@ TEST(StarletARMCore, ARMJitCompilesLongMultiplyFamily)
#endif
}
TEST(StarletARMCore, ARMv5TEEnhancedDSPInstructions)
{
// StarletOS phase 11 (I1): encodings from GNU as (-march=armv5te); results from the ARM
// Architecture Reference Manual. r0 = Rm, r1 = Rs or Rn, r7 = accumulator, r3/r4 results.
struct Case
{
u32 instruction;
u32 r0;
u32 r1;
u32 r3;
u32 r4;
u32 r7;
u32 expected_r3;
u32 expected_r4;
bool expected_q;
};
constexpr std::array cases = {
// smlabb r4, r0, r1, r7: a 88-byte entry 9 of a table (Revolution's RAM layer).
Case{0xe1047180, 9, 88, 0, 0, 0x13780000, 0, 0x13780318, false},
Case{0xe1640180, 0xffff0003, 0x0002fffe, 0, 0, 0, 0, 0xfffffffa, false}, // smulbb
Case{0xe16401a0, 0xffff0003, 0x0002fffe, 0, 0, 0, 0, 2, false}, // smultb
// smlatt r4, r0, r1, r7: 0x3fff0001 + 0x7fffffff overflows, wraps and sets Q.
Case{0xe10471e0, 0x7fff0000, 0x7fff0000, 0, 0, 0x7fffffff, 0, 0xbfff0000, true},
Case{0xe1247180, 0x00020000, 0x00000003, 0, 0, 10, 0, 16, false}, // smlawb
Case{0xe12401e0, 0xfffe0000, 0x00030000, 0, 0, 0, 0, 0xfffffffa, false}, // smulwt
// smlalbb r3, r4, r0, r1: 0x00000000_ffffffff + 1 carries into RdHi.
Case{0xe1443180, 1, 1, 0xffffffff, 0, 0, 0, 1, false},
Case{0xe1014050, 0x7fffffff, 1, 0, 0, 0, 0, 0x7fffffff, true}, // qadd
Case{0xe1214050, 0x80000000, 1, 0, 0, 0, 0, 0x80000000, true}, // qsub
Case{0xe1414050, 1, 0x40000000, 0, 0, 0, 0, 0x7fffffff, true}, // qdadd
Case{0xe1614050, 0, 3, 0, 0, 0, 0, 0xfffffffa, false}, // qdsub
};
for (const Case& test : cases)
{
TestBus interpreter_bus;
ARMCore interpreter(interpreter_bus);
#if defined(_M_X86_64)
TestBus jit_bus;
ARMCore jit(jit_bus);
std::array<ARMCore*, 2> cores = {&interpreter, &jit};
jit_bus.WriteARM(0, test.instruction);
jit_bus.WriteARM(4, 0xeafffffe); // b .
#else
std::array<ARMCore*, 1> cores = {&interpreter};
#endif
interpreter_bus.WriteARM(0, test.instruction);
interpreter_bus.WriteARM(4, 0xeafffffe); // b .
for (ARMCore* core : cores)
{
core->SetCPSR(static_cast<u32>(ARMCore::Mode::System));
core->SetRegister(0, test.r0);
core->SetRegister(1, test.r1);
core->SetRegister(3, test.r3);
core->SetRegister(4, test.r4);
core->SetRegister(7, test.r7);
core->SetRegister(15, 0);
}
#if defined(_M_X86_64)
jit.SetJitEnabled(true);
#endif
for (ARMCore* core : cores)
{
ASSERT_EQ(core->RunCycles(2), 2u);
EXPECT_EQ(core->GetRegister(4), test.expected_r4) << std::hex << test.instruction;
if (test.instruction == 0xe1443180)
EXPECT_EQ(core->GetRegister(3), test.expected_r3);
EXPECT_EQ((core->GetCPSR() & ARMCore::CPSR_Q) != 0, test.expected_q)
<< std::hex << test.instruction;
// The DSP instruction must not touch the condition flags (it is not a compare).
EXPECT_EQ(core->GetCPSR() & (ARMCore::CPSR_N | ARMCore::CPSR_Z | ARMCore::CPSR_C |
ARMCore::CPSR_V),
0u);
}
}
}
TEST(StarletARMCore, FCSESwitchPreservesTaggedTLBTranslations)
{
TestBus bus(0x10000);
@@ -2662,7 +2947,7 @@ TEST(StarletARMCore, ThumbJitBusMemoryPreservesBoot0AndSRAMHoles)
{
SCOPED_TRACE(address);
TestBus bus;
ARMCore core(bus);
ARMCore core(bus, true);
bus.SetFastmemEnabled(true);
bus.SetSRAMFastmemEnabled(true);
bus.SetBoot0Mapped(true);
@@ -2735,7 +3020,7 @@ TEST(StarletARMCore, ARMJitProfilesSlowSRAMPagesByDirection)
{
#if defined(_M_X86_64)
TestBus bus;
ARMCore core(bus);
ARMCore core(bus, true);
bus.SetFastmemEnabled(true);
bus.SetSRAMFastmemEnabled(true);
bus.SetBoot0Mapped(false);
@@ -2764,7 +3049,7 @@ TEST(StarletARMCore, ARMJitKeepsSplitSRAMMirrorWritesOnExactBusPath)
{
#if defined(_M_X86_64)
TestBus bus;
ARMCore core(bus);
ARMCore core(bus, true);
bus.SetFastmemEnabled(true);
bus.SetSRAMFastmemEnabled(true);
bus.SetBoot0Mapped(false);
@@ -3377,6 +3662,56 @@ TEST(StarletARMCore, MMUSectionTranslation)
// The first fetch walks the section table; the second hits the 1 KiB
// translation cache.
EXPECT_EQ(bus.GetRead32Count(), 3u);
EXPECT_EQ(bus.GetDirectPointerCount(), 0u);
}
TEST(StarletARMCore, InterpreterPageWalksUseBusWithoutResolvingValidationPointers)
{
for (const bool big_endian : {false, true})
{
// Section; coarse large/small/extended-small; fine large/small/tiny pages.
for (const auto [first_type, second_type] :
{std::pair{2u, 0u}, {1u, 1u}, {1u, 2u}, {1u, 3u}, {3u, 1u}, {3u, 2u}, {3u, 3u}})
{
SCOPED_TRACE(testing::Message()
<< "be=" << big_endian << " first=" << first_type << " second=" << second_type);
TestBus bus(0x20000);
ARMCore core(bus);
core.SetBigEndian(big_endian);
const auto word = [&](u32 address, u32 value) {
bus.WriteARM(address, big_endian ? value : Common::swap32(value));
};
word(0, 0xe5921000); // ldr r1, [r2]
word(4, 0xe5923000); // ldr r3, [r2]: hit both TLB and instruction cache
word(0x4000, 0x00000c02); // Identity-map code.
constexpr u32 virtual_address = 0x80012344;
constexpr u32 physical_address = 0x12344;
if (first_type == 2)
{
word(0x6000, 0x00000c02);
}
else
{
word(0x6000, 0x8000 | first_type);
const u32 index =
first_type == 1 ? (virtual_address >> 10) & 0x3fc : (virtual_address >> 8) & 0xffc;
const u32 mask = second_type == 1 ? 0xffff0000u :
(first_type == 3 && second_type == 3) ? 0xfffffc00u :
0xfffff000u;
const u32 permissions = first_type == 3 && second_type == 3 ? 0x30 : 0xff0;
word(0x8000 + index, (physical_address & mask) | permissions | second_type);
}
word(physical_address, 0x12345678);
core.GetCP15State().translation_table_base = 0x4000;
core.GetCP15State().control |= 1;
core.SetRegister(2, virtual_address);
core.Run(2);
EXPECT_EQ(core.GetRegister(1), 0x12345678u);
EXPECT_EQ(core.GetRegister(3), 0x12345678u);
EXPECT_EQ(bus.GetDirectPointerCount(), 0u);
EXPECT_EQ(bus.GetRead32Count(), first_type == 2 ? 6u : 7u);
}
}
}
TEST(StarletARMCore, JitCachesProvisionalIdentityTranslationForFaultPages)
@@ -3402,7 +3737,498 @@ TEST(StarletARMCore, JitCachesProvisionalIdentityTranslationForFaultPages)
EXPECT_EQ(core.GetRegister(3), 0x12345678u);
EXPECT_EQ(core.GetJitFallbackInstructionCount(), 0u);
EXPECT_EQ(core.GetJitNativeExecutedInstructions(), 3u);
EXPECT_GT(bus.GetDirectPointerCount(), 0u); // Native descriptor validation is still present.
#endif
}
// StarOS MMU-001 (F1): ARM926 MMU aborts with ARMCore::SetMMUFaultsEnabled. Every case runs in the
// interpreter and, on x86-64, in the JIT; both must reach the same state.
class MMUFaultMachine
{
public:
static constexpr u32 TABLE = 0x4000; // first-level table, 16 KiB aligned
static constexpr u32 COARSE = 0x8000; // one coarse second-level table
// Section 0x800 maps physical 0 privileged-only (AP 01), section 0x880 the same bytes with full
// access (AP 11), both in domain 0. Code is written once and run from either view.
static constexpr u32 KERNEL = 0x80000000;
static constexpr u32 CODE = KERNEL + 0x1000;
static constexpr u32 USER_CODE = 0x88001000;
static constexpr u32 FAR_SENTINEL = 0xdeadbeef;
static constexpr u32 SVC_CPSR = 0xd3;
static constexpr u32 USER_CPSR = 0xd0;
static constexpr u32 ABORT_MODE = 0x17;
static constexpr u32 UNDEFINED_MODE = 0x1b;
explicit MMUFaultMachine(bool jit) : m_bus(0x100000), m_core(m_bus)
{
// High vectors: undefined and SWI stop on themselves; both aborts branch to a handler that
// records SPSR (r8), DFSR (r9), FAR (r10) and IFSR (r11) through MRS/MRC, then marks its kind
// in r12 (0xd data, 0xc prefetch) and stops.
for (u32 vector = 0; vector < 0x20; vector += 4)
m_bus.WriteARM(0xffff0000 + vector, 0xeafffffe); // b .
m_bus.WriteARM(0xffff000c, 0xea00004b); // b 0xffff0140
m_bus.WriteARM(0xffff0010, 0xea00003a); // b 0xffff0100
for (const auto [handler, kind] : {std::pair{0xffff0100u, 0xe3a0c00du},
std::pair{0xffff0140u, 0xe3a0c00cu}})
{
m_bus.WriteARM(handler, 0xe14f8000); // mrs r8, spsr
m_bus.WriteARM(handler + 4, 0xee159f10); // mrc p15, 0, r9, c5, c0, 0 (DFSR)
m_bus.WriteARM(handler + 8, 0xee16af10); // mrc p15, 0, r10, c6, c0, 0 (FAR)
m_bus.WriteARM(handler + 12, 0xee15bf30); // mrc p15, 0, r11, c5, c0, 1 (IFSR)
m_bus.WriteARM(handler + 16, kind); // mov r12, #kind
m_bus.WriteARM(handler + 20, 0xeafffffe); // b .
}
MapSection(0x800, 0, 1, 0);
MapSection(0x880, 0, 3, 0);
MapSection(0xfff, 0xfff00000, 1, 0);
auto& cp15 = m_core.GetCP15State();
cp15.translation_table_base = TABLE;
cp15.domain_access_control = 1; // domain 0 client, every other domain no access
cp15.control |= 1;
cp15.fault_address = FAR_SENTINEL;
m_core.SetMMUFaultsEnabled(true);
m_core.SetJitEnabled(jit);
m_core.SetRegister(15, CODE);
}
void MapSection(u32 index, u32 physical, u32 ap, u32 domain)
{
m_bus.WriteARM(TABLE + index * 4,
(physical & 0xfff00000) | (ap << 10) | (domain << 5) | 0x12);
}
// The section of `virtual_address` points at the coarse table, whose entry for it maps a small
// page of `physical` with the same AP in its four subpages.
void MapSmallPage(u32 virtual_address, u32 physical, u32 ap, u32 domain)
{
m_bus.WriteARM(TABLE + (virtual_address >> 20) * 4, COARSE | (domain << 5) | 0x11);
m_bus.WriteARM(COARSE + ((virtual_address >> 12) & 0xff) * 4,
(physical & 0xfffff000) | ((ap * 0x55) << 4) | 2);
}
// Code at a physical address (its view in section 0x800 or 0x880 is `physical` + base).
void Code(u32 physical, std::initializer_list<u32> instructions)
{
for (const u32 instruction : instructions)
{
m_bus.WriteARM(physical, instruction);
physical += 4;
}
}
void Start(u32 cpsr, u32 pc)
{
m_core.SetCPSR(cpsr);
m_core.SetRegister(15, pc);
}
void Run(u64 cycles = 48) { m_core.RunCycles(cycles); }
void ExpectDataAbort(u32 instruction_address, u32 dfsr, u32 far, u32 spsr)
{
EXPECT_EQ(m_core.GetCPSR() & 0x1f, ABORT_MODE);
EXPECT_EQ(m_core.GetRegister(12), 0xdu) << "not the data abort vector";
EXPECT_EQ(m_core.GetRegister(14), instruction_address + 8);
EXPECT_EQ(m_core.GetRegister(8), spsr);
EXPECT_EQ(m_core.GetRegister(9), dfsr);
EXPECT_EQ(m_core.GetRegister(10), far);
}
void ExpectPrefetchAbort(u32 instruction_address, u32 ifsr, u32 spsr)
{
EXPECT_EQ(m_core.GetCPSR() & 0x1f, ABORT_MODE);
EXPECT_EQ(m_core.GetRegister(12), 0xcu) << "not the prefetch abort vector";
EXPECT_EQ(m_core.GetRegister(14), instruction_address + 4);
EXPECT_EQ(m_core.GetRegister(8), spsr);
EXPECT_EQ(m_core.GetRegister(11), ifsr);
// A prefetch abort leaves the FAR as it was.
EXPECT_EQ(m_core.GetRegister(10), FAR_SENTINEL);
}
TestBus& Bus() { return m_bus; }
ARMCore& Core() { return m_core; }
private:
TestBus m_bus;
ARMCore m_core;
};
template <typename Case>
void ForEachEngine(Case run_case)
{
for (const bool jit : {false, true})
{
#if !defined(_M_X86_64)
if (jit)
continue;
#endif
SCOPED_TRACE(jit ? "JIT" : "interpreter");
MMUFaultMachine machine(jit);
run_case(machine);
}
}
using M = MMUFaultMachine;
TEST(StarletARMCoreMMUFaults, SectionTranslationFaultIsADataAbort)
{
ForEachEngine([](M& m) {
m.Code(0x1000, {0xe5921000}); // ldr r1, [r2]
m.Core().SetRegister(1, 0x11111111);
m.Core().SetRegister(2, 0x90000004); // section 0x900 has no descriptor
m.Run();
m.ExpectDataAbort(M::CODE, 0x05, 0x90000004, M::SVC_CPSR);
EXPECT_EQ(m.Core().GetRegister(1), 0x11111111u);
});
}
TEST(StarletARMCoreMMUFaults, PageTranslationFaultReportsItsDomain)
{
ForEachEngine([](M& m) {
m.MapSmallPage(0x90000000, 0x2000, 3, 2);
m.Code(0x1000, {0xe5921000}); // ldr r1, [r2]
m.Core().SetRegister(2, 0x90001000); // the next small page has no descriptor
m.Run();
m.ExpectDataAbort(M::CODE, 0x27, 0x90001000, M::SVC_CPSR);
});
}
TEST(StarletARMCoreMMUFaults, DomainWithoutAccessFaultsForSectionsAndPages)
{
ForEachEngine([](M& m) {
m.MapSection(0x900, 0, 3, 2);
m.Code(0x1000, {0xe5921000}); // ldr r1, [r2]
m.Core().SetRegister(2, 0x90002000);
m.Run();
m.ExpectDataAbort(M::CODE, 0x29, 0x90002000, M::SVC_CPSR);
});
ForEachEngine([](M& m) {
m.MapSmallPage(0x91000000, 0x2000, 3, 4);
m.Code(0x1000, {0xe5921000}); // ldr r1, [r2]
m.Core().SetRegister(2, 0x91000010);
m.Run();
m.ExpectDataAbort(M::CODE, 0x4b, 0x91000010, M::SVC_CPSR);
});
}
TEST(StarletARMCoreMMUFaults, UserAccessFollowsAP)
{
// AP 01: privileged only. AP 10: User read-only. AP 11: full access.
ForEachEngine([](M& m) {
m.Code(0x1000, {0xe5921000}); // ldr r1, [r2]
m.Core().SetRegister(2, M::KERNEL + 0x2000);
m.Start(M::USER_CPSR, M::USER_CODE);
m.Run();
m.ExpectDataAbort(M::USER_CODE, 0x0d, M::KERNEL + 0x2000, M::USER_CPSR);
});
ForEachEngine([](M& m) {
m.MapSection(0x920, 0, 2, 0);
m.Bus().WriteARM(0x2000, 0x12345678);
m.Code(0x1000, {0xe5921000, 0xe5823000}); // ldr r1, [r2]; str r3, [r2]
m.Core().SetRegister(2, 0x92002000);
m.Core().SetRegister(3, 0xabcdef01);
m.Start(M::USER_CPSR, M::USER_CODE);
m.Run();
EXPECT_EQ(m.Core().GetRegister(1), 0x12345678u);
m.ExpectDataAbort(M::USER_CODE + 4, 0x0d, 0x92002000, M::USER_CPSR);
EXPECT_EQ(m.Bus()[0x2000], 0x12u) << "the faulting store wrote memory";
});
}
TEST(StarletARMCoreMMUFaults, APZeroDependsOnTheSAndRBits)
{
struct Case
{
u32 control_bits;
bool user;
bool write;
bool allowed;
};
constexpr u32 S = 1U << 8;
constexpr u32 R = 1U << 9;
for (const Case c : {Case{0, false, false, false}, Case{S, false, false, true},
Case{S, false, true, false}, Case{S, true, false, false},
Case{R, true, false, true}, Case{R, false, true, false},
Case{S | R, false, false, false}})
{
SCOPED_TRACE(testing::Message() << "control " << std::hex << c.control_bits << " user "
<< c.user << " write " << c.write);
ForEachEngine([&](M& m) {
m.MapSection(0x900, 0, 0, 0);
m.Bus().WriteARM(0x2000, 0x0badf00d);
m.Core().GetCP15State().control |= c.control_bits;
m.Code(0x1000, {c.write ? 0xe5821000u : 0xe5921000u}); // str/ldr r1, [r2]
m.Core().SetRegister(1, 0x11111111);
m.Core().SetRegister(2, 0x90002000);
const u32 code = c.user ? M::USER_CODE : M::CODE;
m.Start(c.user ? M::USER_CPSR : M::SVC_CPSR, code);
m.Run();
if (c.allowed)
{
EXPECT_NE(m.Core().GetCPSR() & 0x1f, M::ABORT_MODE);
EXPECT_EQ(m.Core().GetRegister(1), c.write ? 0x11111111u : 0x0badf00du);
}
else
{
m.ExpectDataAbort(code, 0x0d, 0x90002000, c.user ? M::USER_CPSR : M::SVC_CPSR);
}
});
}
}
TEST(StarletARMCoreMMUFaults, ManagerDomainSkipsAP)
{
ForEachEngine([](M& m) {
m.MapSection(0x900, 0, 0, 5);
m.Core().GetCP15State().domain_access_control = 1 | (3 << 10);
m.Bus().WriteARM(0x2000, 0x600dcafe);
m.Code(0x1000, {0xe5921000, 0xe5823004}); // ldr r1, [r2]; str r3, [r2, #4]
m.Core().SetRegister(2, 0x90002000);
m.Core().SetRegister(3, 0x01020304);
m.Start(M::USER_CPSR, M::USER_CODE);
m.Run(8);
EXPECT_EQ(m.Core().GetCPSR() & 0x1f, 0x10u);
EXPECT_EQ(m.Core().GetRegister(1), 0x600dcafeu);
EXPECT_EQ(m.Bus()[0x2004], 0x01u);
});
}
TEST(StarletARMCoreMMUFaults, FetchFromAnUnmappedSectionIsAPrefetchAbort)
{
ForEachEngine([](M& m) {
m.Code(0x1000, {0xe12fff13}); // bx r3
m.Core().SetRegister(3, 0x90000000);
m.Run();
m.ExpectPrefetchAbort(0x90000000, 0x05, M::SVC_CPSR);
});
}
TEST(StarletARMCoreMMUFaults, UserFetchFromPrivilegedCodeIsAPrefetchAbort)
{
// ARMv5 has no execute permission: a fetch needs read permission, so AP 01 stops User code.
ForEachEngine([](M& m) {
m.Code(0x1000, {0xe12fff13}); // bx r3
m.Core().SetRegister(3, M::CODE + 0x40);
m.Start(M::USER_CPSR, M::USER_CODE);
m.Run();
m.ExpectPrefetchAbort(M::CODE + 0x40, 0x0d, M::USER_CPSR);
});
}
TEST(StarletARMCoreMMUFaults, CachedCodeIsCheckedAgainAtEveryEntry)
{
// The JIT compiles the block in Supervisor mode; entering it again in User mode must fault.
ForEachEngine([](M& m) {
m.Code(0x1040, {0xe3a07001, 0xeafffffe}); // mov r7, #1; b .
m.Start(M::SVC_CPSR, M::CODE + 0x40);
m.Run(8);
EXPECT_EQ(m.Core().GetRegister(7), 1u);
m.Core().SetRegister(7, 0);
m.Start(M::USER_CPSR, M::CODE + 0x40);
m.Run();
m.ExpectPrefetchAbort(M::CODE + 0x40, 0x0d, M::USER_CPSR);
EXPECT_EQ(m.Core().GetRegister(7), 0u);
});
}
TEST(StarletARMCoreMMUFaults, RevokingTheCodeDomainStopsTheNextFetch)
{
ForEachEngine([](M& m) {
m.MapSection(0x930, 0, 1, 3);
m.Core().GetCP15State().domain_access_control = 1 | (1 << 6);
m.Code(0x1000, {0xee034f10, 0xe3a07001}); // mcr p15, 0, r4, c3, c0, 0; mov r7, #1
m.Core().SetRegister(4, 1); // domain 3: no access
m.Start(M::SVC_CPSR, 0x93001000);
m.Run();
m.ExpectPrefetchAbort(0x93001004, 0x39, M::SVC_CPSR);
EXPECT_EQ(m.Core().GetRegister(7), 0u);
});
}
TEST(StarletARMCoreMMUFaults, BlockTransferAbortRestoresTheBase)
{
ForEachEngine([](M& m) {
m.Code(0x1000, {0xe8b0000e}); // ldmia r0!, {r1, r2, r3}
for (u32 reg = 1; reg <= 3; ++reg)
m.Core().SetRegister(reg, 0x11111111 * reg);
m.Core().SetRegister(0, 0x800ffffc); // the second word is in unmapped section 0x801
m.Run();
m.ExpectDataAbort(M::CODE, 0x05, 0x80100000, M::SVC_CPSR);
EXPECT_EQ(m.Core().GetRegister(0), 0x800ffffcu);
for (u32 reg = 1; reg <= 3; ++reg)
EXPECT_EQ(m.Core().GetRegister(reg), 0x11111111 * reg);
});
ForEachEngine([](M& m) {
m.Code(0x1000, {0xe8a00006}); // stmia r0!, {r1, r2}
m.Core().SetRegister(0, 0x800ffffc);
m.Core().SetRegister(1, 0xa1a2a3a4);
m.Core().SetRegister(2, 0xb1b2b3b4);
m.Run();
m.ExpectDataAbort(M::CODE, 0x05, 0x80100000, M::SVC_CPSR);
EXPECT_EQ(m.Core().GetRegister(0), 0x800ffffcu);
// The word stored before the fault stays written, as on ARM926.
EXPECT_EQ(m.Bus()[0xffffc], 0xa1u);
});
}
TEST(StarletARMCoreMMUFaults, LDRTChecksUserPermissionsInAPrivilegedMode)
{
ForEachEngine([](M& m) {
m.Bus().WriteARM(0x2000, 0x13572468);
m.Code(0x1000, {0xe5921000, 0xe4b23000}); // ldr r1, [r2]; ldrt r3, [r2], #0
m.Core().SetRegister(2, M::KERNEL + 0x2000);
m.Run();
EXPECT_EQ(m.Core().GetRegister(1), 0x13572468u);
m.ExpectDataAbort(M::CODE + 4, 0x0d, M::KERNEL + 0x2000, M::SVC_CPSR);
});
}
TEST(StarletARMCoreMMUFaults, AlignmentFaultsNeedTheABit)
{
ForEachEngine([](M& m) {
m.Core().GetCP15State().control |= 2;
m.Code(0x1000, {0xe5921000}); // ldr r1, [r2]
m.Core().SetRegister(2, M::KERNEL + 0x2002);
m.Run();
m.ExpectDataAbort(M::CODE, 0x01, M::KERNEL + 0x2002, M::SVC_CPSR);
});
ForEachEngine([](M& m) {
m.Bus().WriteARM(0x2000, 0x11223344);
m.Code(0x1000, {0xe5921000}); // ldr r1, [r2]: rotated, no fault
m.Core().SetRegister(2, M::KERNEL + 0x2002);
m.Run(4);
EXPECT_EQ(m.Core().GetRegister(1), 0x33441122u);
});
}
TEST(StarletARMCoreMMUFaults, CP15FromUserModeIsUndefined)
{
ForEachEngine([](M& m) {
m.Code(0x1000, {0xee034f10}); // mcr p15, 0, r4, c3, c0, 0
m.Core().SetRegister(4, 0xffffffff);
m.Start(M::USER_CPSR, M::USER_CODE);
m.Run(8);
EXPECT_EQ(m.Core().GetCPSR() & 0x1f, M::UNDEFINED_MODE);
EXPECT_EQ(m.Core().GetRegister(15), 0xffff0004u);
EXPECT_EQ(m.Core().GetCP15State().domain_access_control, 1u);
});
}
TEST(StarletARMCoreMMUFaults, TLBEntriesStaleUntilTheirOwnInvalidation)
{
ForEachEngine([](M& m) {
m.MapSmallPage(0x94000000, 0x3000, 3, 0);
m.Bus().WriteARM(0x3000, 0xcafef00d);
m.Code(0x1000, {
0xe5921000, // ldr r1, [r2]: fills the TLB
0xe5854000, // str r4, [r5]: clears the page's descriptor
0xe5923000, // ldr r3, [r2]: the stale entry still translates
0xee086f37, // mcr p15, 0, r6, c8, c7, 1: another page's MVA
0xe5927000, // ldr r7, [r2]: still stale
0xee082f37, // mcr p15, 0, r2, c8, c7, 1: this page's MVA
0xe5920000, // ldr r0, [r2]: translation fault
});
m.Core().SetRegister(0, 0x5a5a5a5a);
m.Core().SetRegister(2, 0x94000000);
m.Core().SetRegister(4, 0);
m.Core().SetRegister(5, M::KERNEL + M::COARSE);
m.Core().SetRegister(6, 0x95000000);
m.Run(64);
EXPECT_EQ(m.Core().GetRegister(1), 0xcafef00du);
EXPECT_EQ(m.Core().GetRegister(3), 0xcafef00du);
EXPECT_EQ(m.Core().GetRegister(7), 0xcafef00du);
m.ExpectDataAbort(M::CODE + 24, 0x07, 0x94000000, M::SVC_CPSR);
EXPECT_EQ(m.Core().GetRegister(0), 0x5a5a5a5au);
});
}
TEST(StarletARMCoreMMUFaults, DACRChangesNeedNoTLBMaintenance)
{
ForEachEngine([](M& m) {
m.MapSection(0x960, 0, 3, 6);
m.Core().GetCP15State().domain_access_control = 1 | (1 << 12);
m.Bus().WriteARM(0x2000, 0x76543210);
m.Code(0x1000, {0xe5921000, 0xee034f10, 0xe5923000}); // ldr; mcr c3 (r4); ldr r3
m.Core().SetRegister(2, 0x96002000);
m.Core().SetRegister(3, 0x33333333);
m.Core().SetRegister(4, 1);
m.Run();
EXPECT_EQ(m.Core().GetRegister(1), 0x76543210u);
m.ExpectDataAbort(M::CODE + 8, 0x69, 0x96002000, M::SVC_CPSR);
EXPECT_EQ(m.Core().GetRegister(3), 0x33333333u);
});
}
TEST(StarletARMCoreMMUFaults, FCSEFaultsReportTheModifiedAddress)
{
ForEachEngine([](M& m) {
m.Core().GetCP15State().process_id = 0x02000000;
m.Code(0x1000, {0xe5921000}); // ldr r1, [r2]
m.Core().SetRegister(2, 0x00001000);
m.Run();
m.ExpectDataAbort(M::CODE, 0x05, 0x02001000, M::SVC_CPSR);
});
ForEachEngine([](M& m) {
m.Core().GetCP15State().process_id = 0x02000000;
m.MapSection(0x020, 0, 3, 0);
m.Code(0x1000, {0xe5921000}); // ldr r1, [r2]: MVA 0x02001000, this instruction itself
m.Core().SetRegister(2, 0x00001000);
m.Run(4);
EXPECT_EQ(m.Core().GetRegister(1), 0xe5921000u);
});
}
TEST(StarletARMCoreMMUFaults, ThumbDataAbortReturnsToTheInstructionPlusEight)
{
ForEachEngine([](M& m) {
m.Bus().WriteThumb(0x1080, 0x6811); // ldr r1, [r2, #0]
m.Core().SetRegister(2, 0x90000000);
m.Start(M::SVC_CPSR | 0x20, M::CODE + 0x80);
m.Run();
m.ExpectDataAbort(M::CODE + 0x80, 0x05, 0x90000000, M::SVC_CPSR | 0x20);
EXPECT_EQ(m.Core().GetCPSR() & 0x20, 0u);
});
}
TEST(StarletARMCoreMMUFaults, TheJITStillRunsNativeCode)
{
#if defined(_M_X86_64)
MMUFaultMachine m(true);
m.Code(0x1000, {
0xe3a00000, // mov r0, #0
0xe2800001, // add r0, r0, #1
0xe3500010, // cmp r0, #16
0x1afffffc, // bne 0x1004
0xeafffffe, // b .
});
m.Run(96);
EXPECT_EQ(m.Core().GetRegister(0), 16u);
EXPECT_GT(m.Core().GetJitNativeExecutedInstructions(), 0u);
#endif
}
TEST(StarletARMCoreMMUFaults, DisabledFaultsKeepTheIdentityFallbackAndUserCP15)
{
// The IOS LLE model is unchanged unless SetMMUFaultsEnabled(true) is called.
for (const bool jit : {false, true})
{
#if !defined(_M_X86_64)
if (jit)
continue;
#endif
SCOPED_TRACE(jit ? "JIT" : "interpreter");
MMUFaultMachine m(jit);
m.Core().SetMMUFaultsEnabled(false);
m.Bus().WriteARM(0x2000, 0x44556677);
m.Code(0x1000, {0xe5921000, 0xee034f10, 0xeafffffe}); // ldr; mcr c3 (r4); b .
m.Core().SetRegister(2, 0x00002000); // section 0x000: no descriptor
m.Core().SetRegister(4, 0x55555555);
m.Start(M::USER_CPSR, M::USER_CODE);
m.Run(8);
EXPECT_EQ(m.Core().GetRegister(1), 0x44556677u);
EXPECT_EQ(m.Core().GetCP15State().domain_access_control, 0x55555555u);
EXPECT_EQ(m.Core().GetCPSR() & 0x1f, 0x10u);
}
}
} // namespace
} // namespace IOS::LLE
@@ -0,0 +1,312 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <array>
#include <string>
#include <unordered_map>
#include <utility>
#include <gtest/gtest.h>
#include "Core/IOS/Starlet/ARMCore.h"
#include "Core/IOS/Starlet/BootstrapELF.h"
namespace IOS::LLE
{
namespace
{
constexpr u32 TEXT_BASE = 0xffff0000;
constexpr u32 DATA_BASE = 0xfffe0000;
class RecordingBus final : public ARMBus
{
public:
u8 Read8(u32 address) override
{
const auto it = bytes.find(address);
return it == bytes.end() ? 0 : it->second;
}
void Write8(u32 address, u8 value) override { bytes[address] = value; }
std::unordered_map<u32, u8> bytes;
};
void Put16(std::array<u8, 0x300>& image, size_t offset, u16 value)
{
image[offset] = static_cast<u8>(value >> 8);
image[offset + 1] = static_cast<u8>(value);
}
void Put32(std::array<u8, 0x300>& image, size_t offset, u32 value)
{
image[offset] = static_cast<u8>(value >> 24);
image[offset + 1] = static_cast<u8>(value >> 16);
image[offset + 2] = static_cast<u8>(value >> 8);
image[offset + 3] = static_cast<u8>(value);
}
std::array<u8, 0x300> MakeImage()
{
std::array<u8, 0x300> image{};
image[0] = 0x7f;
image[1] = 'E';
image[2] = 'L';
image[3] = 'F';
image[4] = 1; // ELF32
image[5] = 2; // big endian
image[6] = 1;
Put16(image, 16, 2); // ET_EXEC
Put16(image, 18, 40); // ARM
Put32(image, 20, 1); // ELF version
Put32(image, 24, TEXT_BASE);
Put32(image, 28, 52); // program headers
Put32(image, 32, 0x200); // section headers
Put16(image, 40, 52);
Put16(image, 42, 32);
Put16(image, 44, 2);
Put16(image, 46, 40);
Put16(image, 48, 3);
Put32(image, 52, 1);
Put32(image, 56, 0x100);
Put32(image, 60, TEXT_BASE);
Put32(image, 64, TEXT_BASE);
Put32(image, 68, 4);
Put32(image, 72, 8);
Put32(image, 76, 5);
image[0x100] = 0xea; // ARM branch instruction
Put32(image, 84, 1);
Put32(image, 88, 0x110);
Put32(image, 92, DATA_BASE);
Put32(image, 96, DATA_BASE);
Put32(image, 100, 4);
Put32(image, 104, 0x420);
Put32(image, 108, 6);
image[0x110] = 0x12;
image[0x111] = 0x34;
image[0x112] = 0x56;
image[0x113] = 0x78;
constexpr char names[] = "\0REV_TRACE\0__fault_code\0__fault_lr\0__fault_spsr";
for (size_t index = 0; index < sizeof(names); ++index)
image[0x180 + index] = static_cast<u8>(names[index]);
Put32(image, 0x228 + 4, 3); // SHT_STRTAB
Put32(image, 0x228 + 16, 0x180);
Put32(image, 0x228 + 20, sizeof(names));
Put32(image, 0x250 + 4, 2); // SHT_SYMTAB
Put32(image, 0x250 + 16, 0x120);
Put32(image, 0x250 + 20, 5 * 16);
Put32(image, 0x250 + 24, 1);
Put32(image, 0x250 + 36, 16);
const auto symbol = [&image](size_t index, u32 name, u32 address, u32 size) {
const size_t offset = 0x120 + index * 16;
Put32(image, offset, name);
Put32(image, offset + 4, address);
Put32(image, offset + 8, size);
};
symbol(1, 1, DATA_BASE + 8, 1032);
symbol(2, 11, DATA_BASE + 0x410, 4);
symbol(3, 24, DATA_BASE + 0x414, 4);
symbol(4, 35, DATA_BASE + 0x418, 4);
return image;
}
TEST(BootstrapELFTest, LoadsSegmentsAndZerosUninitializedData)
{
const auto image = MakeImage();
RecordingBus bus;
BootstrapELFInfo info;
std::string error;
ASSERT_TRUE(LoadBootstrapELF(image, bus, &info, &error)) << error;
EXPECT_EQ(info.entry, TEXT_BASE);
EXPECT_EQ(info.trace, DATA_BASE + 8);
EXPECT_EQ(info.fault_spsr, DATA_BASE + 0x418);
EXPECT_EQ(bus.Read8(TEXT_BASE), 0xea);
EXPECT_EQ(bus.Read8(TEXT_BASE + 4), 0);
EXPECT_EQ(bus.Read32(DATA_BASE), 0x12345678u);
EXPECT_EQ(bus.Read32(DATA_BASE + 0x41c), 0u);
EXPECT_EQ(bus.bytes.size(), size_t{8 + 0x420});
}
TEST(BootstrapELFTest, RejectsMalformedImageBeforeWritingMemory)
{
auto image = MakeImage();
RecordingBus bus;
BootstrapELFInfo info;
std::string error;
image[5] = 1;
EXPECT_FALSE(LoadBootstrapELF(image, bus, &info, &error));
EXPECT_TRUE(bus.bytes.empty());
image = MakeImage();
Put32(image, 0x120 + 2 * 16 + 4, DATA_BASE + 0x420);
EXPECT_FALSE(LoadBootstrapELF(image, bus, &info, &error));
EXPECT_TRUE(bus.bytes.empty());
image = MakeImage();
Put32(image, 88, 0x300);
EXPECT_FALSE(LoadBootstrapELF(image, bus, &info, &error));
EXPECT_TRUE(bus.bytes.empty());
}
// Revolution IOS Phase 06H: the optional MEM2 text segment of the emulator-only
// disposable-image kernel, accepted only when the caller allows it.
constexpr u32 MEM2_TEXT = 0x12600000;
std::array<u8, 0x300> MakeMem2Image(u32 address, u32 flags)
{
auto image = MakeImage();
Put16(image, 44, 3);
Put32(image, 116, 1);
Put32(image, 120, 0x114);
Put32(image, 124, address);
Put32(image, 128, address);
Put32(image, 132, 4);
Put32(image, 136, 0x10);
Put32(image, 140, flags);
Put32(image, 0x114, 0xe12fff1e); // BX LR
return image;
}
TEST(BootstrapELFTest, Mem2TextSegmentOnlyWhenAllowed)
{
RecordingBus bus;
BootstrapELFInfo info;
std::string error;
auto image = MakeMem2Image(MEM2_TEXT, 5);
EXPECT_FALSE(LoadBootstrapELF(image, bus, &info, &error));
EXPECT_TRUE(bus.bytes.empty());
ASSERT_TRUE(LoadBootstrapELF(image, bus, &info, &error, true)) << error;
EXPECT_EQ(bus.Read32(MEM2_TEXT), 0xe12fff1eu);
EXPECT_EQ(bus.Read32(MEM2_TEXT + 0xc), 0u);
EXPECT_EQ(bus.Read8(TEXT_BASE), 0xea);
EXPECT_EQ(bus.Read32(DATA_BASE), 0x12345678u);
EXPECT_EQ(bus.bytes.size(), size_t{8 + 0x420 + 0x10});
RecordingBus plain;
const auto two_segments = MakeImage();
EXPECT_TRUE(LoadBootstrapELF(two_segments, plain, &info, &error, true)) << error;
}
TEST(BootstrapELFTest, RejectsInvalidMem2TextSegmentBeforeWritingMemory)
{
RecordingBus bus;
BootstrapELFInfo info;
std::string error;
// Writable, outside MEM2, crossing its end, or a second SRAM text segment.
for (const auto& image : {MakeMem2Image(MEM2_TEXT, 6), MakeMem2Image(0x0fff0000, 5),
MakeMem2Image(0x13fffff8, 5), MakeMem2Image(TEXT_BASE, 5)})
{
EXPECT_FALSE(LoadBootstrapELF(image, bus, &info, &error, true));
EXPECT_TRUE(bus.bytes.empty());
}
}
TEST(ARMCoreTest, Armv5DoublewordTransfersAndAlignmentAbort)
{
RecordingBus bus;
bus.Write32(TEXT_BASE, 0xe1c020d0); // LDRD r2, r3, [r0]
bus.Write32(TEXT_BASE + 4, 0xe1c120f0); // STRD r2, r3, [r1]
bus.Write32(DATA_BASE, 0x11223344);
bus.Write32(DATA_BASE + 4, 0x55667788);
ARMCore core(bus);
core.Reset(TEXT_BASE);
core.SetBigEndian(true);
core.SetRegister(0, DATA_BASE);
core.SetRegister(1, DATA_BASE + 8);
core.Step();
EXPECT_EQ(core.GetRegister(2), 0x11223344u);
EXPECT_EQ(core.GetRegister(3), 0x55667788u);
core.Step();
EXPECT_EQ(bus.Read32(DATA_BASE + 8), 0x11223344u);
EXPECT_EQ(bus.Read32(DATA_BASE + 12), 0x55667788u);
core.Reset(TEXT_BASE);
core.SetBigEndian(true);
core.SetRegister(0, DATA_BASE + 4);
core.Step();
EXPECT_EQ(core.GetRegister(15), TEXT_BASE + 0x10);
EXPECT_EQ(core.GetRegister(14), TEXT_BASE + 8);
EXPECT_EQ(core.GetCP15State().fault_address, DATA_BASE + 4);
}
// StarOS ADR-0014 R6: the optional panic words. The string table moves past the section headers
// to make room for two more symbols.
std::array<u8, 0x300> MakePanicImage(u32 state, u32 code)
{
auto image = MakeImage();
constexpr char names[] =
"\0REV_TRACE\0__fault_code\0__fault_lr\0__fault_spsr\0__panic_state\0__panic_code";
for (size_t index = 0; index < sizeof(names); ++index)
image[0x278 + index] = static_cast<u8>(names[index]);
Put32(image, 0x228 + 16, 0x278);
Put32(image, 0x228 + 20, sizeof(names));
Put32(image, 0x250 + 20, 7 * 16);
const auto symbol = [&image](size_t index, u32 name, u32 address) {
const size_t offset = 0x120 + index * 16;
Put32(image, offset, name);
Put32(image, offset + 4, address);
Put32(image, offset + 8, 4);
};
// An omitted word keeps its slot, with the empty name.
symbol(5, state != 0 ? 48 : 0, state);
symbol(6, code != 0 ? 62 : 0, code);
return image;
}
TEST(BootstrapELFTest, PanicWordsAreOptionalButBothInData)
{
RecordingBus bus;
BootstrapELFInfo info;
std::string error;
ASSERT_TRUE(LoadBootstrapELF(MakeImage(), bus, &info, &error)) << error;
EXPECT_EQ(info.panic_state, 0u);
EXPECT_EQ(info.panic_code, 0u);
ASSERT_TRUE(LoadBootstrapELF(MakePanicImage(DATA_BASE + 0x41c, DATA_BASE + 4), bus, &info, &error))
<< error;
EXPECT_EQ(info.panic_state, DATA_BASE + 0x41c);
EXPECT_EQ(info.panic_code, DATA_BASE + 4);
for (const auto [state, code] : {std::pair{DATA_BASE + 0x41c, 0u}, std::pair{0u, DATA_BASE + 4},
std::pair{DATA_BASE + 0x41c, DATA_BASE + 0x420}})
{
RecordingBus rejected;
EXPECT_FALSE(LoadBootstrapELF(MakePanicImage(state, code), rejected, &info, &error));
EXPECT_EQ(error, "bootstrap ELF has an invalid panic symbol");
EXPECT_TRUE(rejected.bytes.empty());
}
}
TEST(BootstrapELFTest, PanicWordsMustNotAlias)
{
BootstrapELFInfo info;
std::string error;
// The same word, or two words sharing bytes, in either order; all inside the 0x420-byte data
// segment, so only the aliasing rule rejects them.
for (const auto [state, code] :
{std::pair{DATA_BASE + 4, DATA_BASE + 4}, std::pair{DATA_BASE + 4, DATA_BASE + 6},
std::pair{DATA_BASE + 7, DATA_BASE + 4}, std::pair{DATA_BASE + 0x41c, DATA_BASE + 0x41a}})
{
RecordingBus rejected;
EXPECT_FALSE(LoadBootstrapELF(MakePanicImage(state, code), rejected, &info, &error))
<< std::hex << state << ' ' << code;
EXPECT_EQ(error, "bootstrap ELF has an invalid panic symbol");
EXPECT_TRUE(rejected.bytes.empty());
}
// Adjacent words do not alias.
for (const auto [state, code] :
{std::pair{DATA_BASE + 4, DATA_BASE + 8}, std::pair{DATA_BASE + 8, DATA_BASE + 4}})
{
RecordingBus bus;
EXPECT_TRUE(LoadBootstrapELF(MakePanicImage(state, code), bus, &info, &error)) << error;
EXPECT_EQ(info.panic_state, state);
EXPECT_EQ(info.panic_code, code);
}
}
} // namespace
} // namespace IOS::LLE
@@ -0,0 +1,433 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <algorithm>
#include <array>
#include <limits>
#include <memory>
#include <span>
#include <vector>
#include <gtest/gtest.h>
#include "Common/Config/Config.h"
#include "Common/Crypto/SHA1.h"
#include "Common/FileUtil.h"
#include "Core/Config/MainSettings.h"
#include "Core/ConfigManager.h"
#include "Core/Core.h"
#include "Core/HW/Memmap.h"
#include "Core/HW/WII_IPC.h"
#include "Core/IOS/Starlet/StarletMemory.h"
#include "Core/System.h"
namespace IOS::LLE
{
// Compare the block helpers with the original byte bus, using synthetic memory only.
class StarletDMATest : public testing::Test
{
protected:
static void SetUpTestSuite()
{
Config::Init();
SConfig::Init();
auto& system = Core::System::GetInstance();
system.SetIsWii(true);
system.GetMemory().Init();
Core::DeclareAsCPUThread();
}
static void TearDownTestSuite()
{
auto& system = Core::System::GetInstance();
system.GetMemory().Shutdown();
system.SetIsWii(false);
Core::UndeclareAsCPUThread();
SConfig::Shutdown();
Config::Shutdown();
}
void SetUp() override
{
auto& system = Core::System::GetInstance();
system.GetWiiIPC().Reset();
m_memory = std::make_unique<StarletMemory>(system);
}
void TearDown() override
{
m_memory.reset();
if (!m_temp_directory.empty())
File::DeleteDirRecursively(m_temp_directory); // Only this fixture's unique temporary SD.
}
std::vector<u8> ReadBytes(u32 address, size_t size)
{
std::vector<u8> result(size);
for (size_t i = 0; i < size; ++i)
result[i] = m_memory->ReadDMA8(address + static_cast<u32>(i));
return result;
}
void WriteBytes(u32 address, std::span<const u8> data)
{
for (size_t i = 0; i < data.size(); ++i)
m_memory->WriteDMA8(address + static_cast<u32>(i), data[i]);
}
void CompareRanges()
{
for (const bool split : {false, true})
{
for (const bool boot0 : {false, true})
{
m_memory->m_sram_split_mode = split;
m_memory->m_boot0_mapped = boot0;
for (const u32 address :
{0U, 1U, 0x10003U, 0x017ffff0U, 0x01800000U, 0x0fffffffU,
0x10000000U, 0x10000001U, 0x13fffff0U, 0x14000000U, 0x0d3ffff0U, 0x0d400000U,
0x0d400003U, 0x0d40fff0U, 0x0d410000U, 0x0d417ff0U, 0x0d418000U, 0x0d41fff0U,
0xfff00000U, 0xfff0fff0U, 0xfff17ff0U, 0xfffefff0U, 0xffff0000U, 0xffff7ff0U,
0xfffffff0U, 0x0d800020U})
{
for (const size_t size : {0U, 1U, 2U, 3U, 4U, 7U, 16U, 63U, 512U, 2048U, 8192U})
{
SCOPED_TRACE(testing::Message() << "address=" << address << " size=" << size
<< " split=" << split << " boot0=" << boot0);
std::vector<u8> initial(size + 32);
std::vector<u8> payload(size);
for (size_t i = 0; i < initial.size(); ++i)
initial[i] = static_cast<u8>((i * 37) ^ (i >> 8));
for (size_t i = 0; i < size; ++i)
payload[i] = static_cast<u8>((i * 13) ^ (i >> 7) ^ 0xab);
WriteBytes(address - 16, initial);
std::vector<u8> actual(size);
m_memory->ReadDMABuffer(address, actual);
ASSERT_EQ(actual, ReadBytes(address, size));
WriteBytes(address, payload);
const auto expected = ReadBytes(address - 16, size + 32);
const auto expected_sram = m_memory->m_sram;
WriteBytes(address - 16, initial);
m_memory->WriteDMABuffer(address, payload);
ASSERT_EQ(ReadBytes(address - 16, size + 32), expected);
ASSERT_EQ(m_memory->m_sram, expected_sram);
}
}
}
}
}
void CheckPointerGuards()
{
for (const u32 address : {0U, 0x10000000U, 0x0d400000U, 0x0d410000U})
{
EXPECT_NE(m_memory->GetDMAMemoryPointer(address, 16), nullptr);
EXPECT_EQ(m_memory->GetDMAMemoryPointer(address, std::numeric_limits<size_t>::max()),
nullptr);
}
for (const u32 address : {0x017ffff0U, 0x13fffff0U, 0x0d417ff0U})
{
EXPECT_NE(m_memory->GetDMAMemoryPointer(address, 16), nullptr);
EXPECT_EQ(m_memory->GetDMAMemoryPointer(address, 17), nullptr);
}
for (const u32 address : {0x0d418000U, 0x0d800038U, 0xfff00000U, 0xfffffff0U})
EXPECT_EQ(m_memory->GetDMAMemoryPointer(address, 4), nullptr);
}
void CheckBootstrapStoredKeys()
{
m_memory->PrepareBootstrap();
for (const u8 read_all : {0, 1})
{
SCOPED_TRACE(read_all);
m_memory->m_ohci1_hci_events.clear();
m_memory->ExecuteOHCI1HCICommand({0x0d, 0x0c, 7, 0, 0, 0, 0, 0, 0, read_all});
ASSERT_EQ(m_memory->m_ohci1_hci_events.size(), 1u);
// Command Complete: capacity 255, zero stored keys, no Return Link Keys event.
EXPECT_EQ(m_memory->m_ohci1_hci_events.front(),
(std::vector<u8>{0x0e, 8, 1, 0x0d, 0x0c, 0, 0xff, 0, 0, 0}));
}
}
void CheckOHCI()
{
for (const u32 base : {0x10000U, 0x10010000U, 0x0d404000U})
{
// The second physical page can precede the first and need not be adjacent.
const u32 first = base + 0x3fe3;
const u32 end = base + 0x0017;
std::vector<u8> payload(70);
for (size_t i = 0; i < payload.size(); ++i)
payload[i] = static_cast<u8>(i + 1);
WriteBytes(first - 1, std::vector<u8>(100, 0xcc));
WriteBytes(base - 1, std::vector<u8>(100, 0xdd));
m_memory->WriteOHCIBuffer(first, end, payload.data(), payload.size());
payload.resize(29 + 24);
EXPECT_EQ(m_memory->ReadOHCIBuffer(first, end), payload);
EXPECT_EQ(ReadBytes(first - 1, 1)[0], 0xcc);
EXPECT_EQ(ReadBytes(first + 29, 1)[0], 0xcc);
EXPECT_EQ(ReadBytes(base - 1, 1)[0], 0xdd);
EXPECT_EQ(ReadBytes(end + 1, 1)[0], 0xdd);
// Short packet must not fill the remainder of either page.
m_memory->WriteOHCIBuffer(first, end, payload.data(), 3);
EXPECT_EQ(m_memory->ReadOHCIBuffer(first, first + 2), (std::vector<u8>{1, 2, 3}));
m_memory->WriteOHCIMemory32(base + 1, 0x12345678);
EXPECT_EQ(ReadBytes(base + 1, 4), (std::vector<u8>{0x78, 0x56, 0x34, 0x12}));
EXPECT_EQ(m_memory->ReadOHCIMemory32(base + 1), 0x12345678U);
}
EXPECT_TRUE(m_memory->ReadOHCIBuffer(0, 0x1234).empty());
EXPECT_TRUE(m_memory->ReadOHCIBuffer(0x1234, 0x1233).empty());
}
void CheckNAND()
{
StarletMemory::NANDPage raw;
for (size_t i = 0; i < raw.size(); ++i)
raw[i] = static_cast<u8>((i * 37) ^ (i >> 8));
m_memory->m_nand_overlay[7] = raw;
m_memory->m_nand_read_pending = true;
m_memory->m_nand_read_page = 7;
for (const u32 base : {0x10000U, 0x10010000U, 0x0d404000U})
{
const u32 spare = base + 0x2000;
m_memory->WriteRegister(0x0d010010, base);
m_memory->WriteRegister(0x0d010014, spare);
m_memory->WriteRegister(0x0d01000c, 7);
for (const u32 column : {0U, 1U, 0x7f0U, 0x800U, 0x830U})
{
for (const u32 length : {1U, 0x840U - column})
{
SCOPED_TRACE(testing::Message()
<< "base=" << base << " column=" << column << " length=" << length);
WriteBytes(base, std::vector<u8>(0x900, 0xcc));
WriteBytes(spare, std::vector<u8>(0x100, 0xdd));
m_memory->m_nand_read_column = column;
ASSERT_TRUE(m_memory->ReadNANDPage(0x2000 | length));
// Independent old byte-address formula, including spare-only reads via NAND_DATA.
for (u32 i = 0; i < length; ++i)
{
const u32 address =
column < 0x800 && column + i >= 0x800 ? spare + column + i - 0x800 : base + i;
ASSERT_EQ(m_memory->ReadDMA8(address), raw[column + i]);
}
m_memory->WriteRegister(0x0d010008, column);
ASSERT_TRUE(m_memory->StageNANDProgram(0x4000 | length, false));
auto expected = raw;
std::fill(expected.begin(), expected.begin() + column, 0xff);
std::fill(expected.begin() + column + length, expected.end(), 0xff);
EXPECT_EQ(m_memory->m_nand_program_data, expected);
}
}
// ECC output remains separate from the transferred spare bytes.
m_memory->m_nand_read_column = 0;
ASSERT_TRUE(m_memory->ReadNANDPage(0x3000 | 0x840));
const auto ecc = StarletMemory::CalculateNANDECC(raw.data());
EXPECT_EQ(ReadBytes(spare ^ 0x40, ecc.size()), (std::vector<u8>(ecc.begin(), ecc.end())));
EXPECT_EQ(ReadBytes(spare, 0x40), (std::vector<u8>(raw.begin() + 0x800, raw.end())));
m_memory->WriteRegister(0x0d010008, 0);
ASSERT_TRUE(m_memory->StageNANDProgram(0x5800, false));
EXPECT_TRUE(m_memory->m_nand_program_ecc_enabled);
EXPECT_EQ(ReadBytes(spare ^ 0x40, ecc.size()), (std::vector<u8>(ecc.begin(), ecc.end())));
// Random spare input uses NAND_DATA and preserves the already staged page data.
WriteBytes(base, std::span(raw).subspan(0x800));
m_memory->WriteRegister(0x0d010008, 0x800);
ASSERT_TRUE(m_memory->StageNANDProgram(0x4040, true));
EXPECT_EQ(m_memory->m_nand_program_data, raw);
}
}
void CheckOverlappingAES()
{
for (const u32 base : {0x10000U, 0x10010000U, 0x0d404000U})
{
for (const u32 offset : {0U, 16U})
{
std::vector<u8> input(2048);
for (size_t i = 0; i < input.size(); ++i)
input[i] = static_cast<u8>((i * 37) ^ (i >> 8));
WriteBytes(base, input);
m_memory->Write32(0x0d020004, base);
m_memory->Write32(0x0d020008, base + offset);
m_memory->Write32(0x0d020000, 0x8000007f);
EXPECT_EQ(ReadBytes(base + offset, input.size()), input);
EXPECT_EQ(m_memory->Read32(0x0d020004), base + input.size());
EXPECT_EQ(m_memory->Read32(0x0d020008), base + offset + input.size());
}
}
}
void CheckSHA()
{
std::vector<u8> input(257);
for (size_t i = 0; i < input.size(); ++i)
input[i] = static_cast<u8>(i * 37);
const auto digest = Common::SHA1::CalculateDigest(input);
input.resize(320, 0);
input[257] = 0x80;
input[318] = 0x08;
input[319] = 0x08; // 257 * 8 bits, big endian.
constexpr std::array<u32, 5> initial = {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476,
0xc3d2e1f0};
for (const u32 base : {0x10000U, 0x10010000U, 0x0d404000U})
{
WriteBytes(base, input);
for (u32 i = 0; i < initial.size(); ++i)
m_memory->Write32(0x0d030008 + i * 4, initial[i]);
m_memory->Write32(0x0d030004, base);
m_memory->Write32(0x0d030000, 0x80000004); // Five blocks.
EXPECT_EQ(ReadBytes(0x0d030008, digest.size()),
(std::vector<u8>(digest.begin(), digest.end())));
EXPECT_EQ(m_memory->Read32(0x0d030004), base + input.size());
}
}
void CheckSD()
{
m_temp_directory = File::CreateTempDir();
ASSERT_FALSE(m_temp_directory.empty());
ASSERT_TRUE(m_memory->m_sd_card.Open(m_temp_directory + "/dma-test.raw", "w+b"));
std::vector<u8> image(4096);
for (size_t i = 0; i < image.size(); ++i)
image[i] = static_cast<u8>((i * 37) ^ (i >> 8));
ASSERT_TRUE(m_memory->m_sd_card.WriteBytes(image.data(), image.size()));
ASSERT_TRUE(m_memory->m_sd_card.Flush());
m_memory->m_sd_card_inserted = true;
for (const bool high_capacity : {false, true})
{
m_memory->m_sd_card_high_capacity = high_capacity;
const u32 argument = high_capacity ? 1 : 512;
for (const u32 base : {0x10000U, 0x10010000U, 0x0d404000U})
{
ASSERT_TRUE(m_memory->TransferSDCardBlocks(true, argument, 512, 3, base));
EXPECT_EQ(ReadBytes(base, 1536),
(std::vector<u8>(image.begin() + 512, image.begin() + 2048)));
EXPECT_EQ(m_memory->ReadRegister(0x0d070000), base + 1536);
Config::SetCurrent(Config::MAIN_ALLOW_SD_WRITES, false);
EXPECT_FALSE(m_memory->TransferSDCardBlocks(false, argument, 512, 3, base));
Config::SetCurrent(Config::MAIN_ALLOW_SD_WRITES, true);
auto changed = ReadBytes(base, 1536);
for (auto& byte : changed)
byte ^= 0x5a;
WriteBytes(base, changed);
ASSERT_TRUE(m_memory->TransferSDCardBlocks(false, argument, 512, 3, base));
std::copy(changed.begin(), changed.end(), image.begin() + 512);
ASSERT_TRUE(m_memory->m_sd_card.Seek(0, File::SeekOrigin::Begin));
std::vector<u8> actual(image.size());
ASSERT_TRUE(m_memory->m_sd_card.ReadBytes(actual.data(), actual.size()));
EXPECT_EQ(actual, image);
EXPECT_FALSE(m_memory->TransferSDCardBlocks(true, argument, 4096, 1, base));
}
}
}
void CheckCPUSRAMReads()
{
for (size_t i = 0; i < m_memory->m_boot_rom.size(); ++i)
m_memory->m_boot_rom[i] = static_cast<u8>((i * 29) ^ (i >> 5) ^ 0xa5);
for (size_t i = 0; i < m_memory->m_sram.size(); ++i)
m_memory->m_sram[i] = static_cast<u8>((i * 13) ^ (i >> 8) ^ 0x5a);
// The byte CPU path is unchanged by the aligned wide-read optimization. Use it as the
// reference, including nonzero boot ROM, all mirrors, live mapping changes and wrap to MEM1.
for (const bool split : {false, true, false})
{
for (const bool boot0 : {false, true, false})
{
m_memory->Write32(0x0d800060, split ? 0x20 : 0);
m_memory->Write32(0x0d80018c, boot0 ? 0 : 0x1000);
for (const u32 base : {0x0d400000U, 0xfff00000U, 0xfff20000U, 0xfff40000U, 0xfff60000U,
0xfff80000U, 0xfffa0000U, 0xfffc0000U, 0xfffe0000U})
{
for (u32 page = 0; page < 32; ++page)
{
for (const u32 offset : {0U, 1U, 2U, 3U, 0xffcU, 0xffdU, 0xffeU, 0xfffU})
{
const u32 address = base + page * 0x1000 + offset;
const u16 expected16 =
static_cast<u16>((m_memory->Read8(address) << 8) | m_memory->Read8(address + 1));
const u32 expected32 = (static_cast<u32>(expected16) << 16) |
(m_memory->Read8(address + 2) << 8) |
m_memory->Read8(address + 3);
ASSERT_EQ(m_memory->Read16(address), expected16)
<< "address=" << address << " split=" << split << " boot0=" << boot0;
ASSERT_EQ(m_memory->Read32(address), expected32)
<< "address=" << address << " split=" << split << " boot0=" << boot0;
}
}
}
}
}
}
void CheckVersionReads()
{
constexpr u32 version = 0x0d800214;
m_memory->Reset();
ASSERT_EQ(m_memory->Read32(version), 0x11U);
for (const u32 value : {0x12345678U, 0xdeadbeefU, 0U, 0xffffffffU})
{
m_memory->Write32(version, value);
for (u32 i = 0; i < 4; ++i)
EXPECT_EQ(m_memory->Read8(version + i), static_cast<u8>(value >> (24 - i * 8)));
EXPECT_EQ(m_memory->Read32(version), value);
m_memory->Write8(version + 1, 0x5a);
EXPECT_EQ(m_memory->Read32(version), (value & 0xff00ffffU) | 0x005a0000U);
}
m_memory->Reset();
EXPECT_EQ(m_memory->Read32(version), 0x11U);
}
std::unique_ptr<StarletMemory> m_memory;
std::string m_temp_directory;
};
TEST_F(StarletDMATest, BuffersMatchByteBusAcrossMappingsBoundariesAndWrap)
{
CompareRanges();
}
TEST_F(StarletDMATest, DirectRangesExcludeHolesRegistersMirrorsAndOverflow)
{
CheckPointerGuards();
}
TEST_F(StarletDMATest, OHCIUsesTwoPhysicalPagesAndLittleEndianDescriptors)
{
CheckOHCI();
}
TEST_F(StarletDMATest, BootstrapReadStoredKeysHasNoWiimoteDevices)
{
CheckBootstrapStoredKeys();
}
TEST_F(StarletDMATest, NANDSeparatesDataSpareAndECCIncludingPartialTransfers)
{
CheckNAND();
}
TEST_F(StarletDMATest, AESStagesAllInputBeforeWritingOverlappingOutput)
{
CheckOverlappingAES();
}
TEST_F(StarletDMATest, SHAMultipleBlocksMatchDigestInEveryPhysicalBank)
{
CheckSHA();
}
TEST_F(StarletDMATest, SDTransfersPreserveOffsetsContentsAndWriteProtection)
{
CheckSD();
}
TEST_F(StarletDMATest, CPUWideSRAMReadsMatchBytesWithBootROMAndEveryMirror)
{
CheckCPUSRAMReads();
}
TEST_F(StarletDMATest, VersionWordReadsPreserveLiveByteBackingAndReset)
{
CheckVersionReads();
}
} // namespace IOS::LLE
@@ -0,0 +1,276 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <algorithm>
#include <array>
#include <memory>
#include <span>
#include <string_view>
#include <vector>
#include <gtest/gtest.h>
#include "Common/Crypto/AES.h"
#include "Common/Crypto/HMAC.h"
#include "Core/Core.h"
#include "Core/HW/WII_IPC.h"
#include "Core/IOS/Starlet/StarletMemory.h"
#include "Core/IOS/USB/Bluetooth/BTBase.h"
#include "Core/System.h"
#include "DiscIO/NANDImporter.h"
namespace IOS::LLE
{
class StarletPairingTest : public testing::Test
{
protected:
using Superblock = DiscIO::NANDImporter::NANDSuperblock;
static constexpr u32 SUPERBLOCK_START = 0x1fc00000;
static constexpr u16 SYSCONF_CLUSTER = 0x20;
void SetUp() override
{
Core::DeclareAsCPUThread();
auto& system = Core::System::GetInstance();
system.GetWiiIPC().Reset();
m_memory = std::make_unique<StarletMemory>(system);
m_memory->Reset();
m_superblock = std::make_unique<Superblock>();
m_superblock->magic = {'S', 'F', 'F', 'S'};
m_superblock->version = 1;
for (auto& entry : m_superblock->fst)
{
entry.sub = 0xffff;
entry.sib = 0xffff;
}
m_superblock->fst[0].mode = 2;
m_superblock->fat[SYSCONF_CLUSTER] = 0xfffb;
// All sixteen raw superblock copies can be read, but only copy zero is valid.
const std::vector<u8> empty(16 * sizeof(Superblock));
PutLogicalData(SUPERBLOCK_START, empty);
}
void PutLogicalData(u32 offset, std::span<const u8> bytes)
{
ASSERT_EQ(offset % 0x800, 0u);
ASSERT_EQ(bytes.size() % 0x800, 0u);
for (u32 i = 0; i < bytes.size(); i += 0x800)
{
NANDJournal::Page page{};
std::copy_n(bytes.begin() + i, 0x800, page.begin());
m_memory->m_nand_overlay.insert_or_assign((offset + i) / 0x800, page);
}
}
void AddPath(u32 depth)
{
constexpr std::array<std::string_view, 3> names = {"shared2", "sys", "SYSCONF"};
for (u32 i = 0; i < depth; ++i)
{
m_superblock->fst[i].sub = static_cast<u16>(i + 1);
auto& child = m_superblock->fst[i + 1];
std::ranges::copy(names[i], child.name);
child.mode = i == 2 ? 1 : 2;
}
}
void SetSysconf(bool with_pairings)
{
AddPath(3);
m_superblock->fst[3].sub = SYSCONF_CLUSTER;
m_superblock->fst[3].size = 0x4000;
std::vector<u8> plain(0x4000);
std::ranges::copy(std::array{'S', 'C', 'v', '0'}, plain.begin());
if (with_pairings)
{
// Valid but empty BT.DINF: this takes the existing auto-pairing write path.
const auto pairing = IOS::HLE::GetEmulatedWiimotePairingData();
plain[5] = 1;
plain[7] = 0x10;
plain[0x10] = 0x26;
constexpr std::string_view name = "BT.DINF";
std::ranges::copy(name, plain.begin() + 0x11);
plain[0x18] = static_cast<u8>((pairing.size() - 1) >> 8);
plain[0x19] = static_cast<u8>(pairing.size() - 1);
}
const std::array<u8, 16> synthetic_key{};
auto aes = Common::AES::CreateContextEncrypt(synthetic_key.data());
std::vector<u8> encrypted(plain.size());
ASSERT_TRUE(aes->CryptIvZero(plain.data(), encrypted.data(), plain.size()));
PutLogicalData(SYSCONF_CLUSTER * 0x4000, encrypted);
}
void StoreSuperblock(u32 copy = 0)
{
PutLogicalData(SUPERBLOCK_START + copy * sizeof(Superblock),
{reinterpret_cast<const u8*>(m_superblock.get()), sizeof(Superblock)});
}
void CheckWithoutWrites(bool expected)
{
StoreSuperblock();
const auto before = m_memory->m_nand_overlay;
EXPECT_EQ(m_memory->InstallEmulatedWiimotePairings(), expected);
EXPECT_TRUE(m_memory->m_nand_overlay == before);
}
void RemoveFirstSuperblockPage() { m_memory->m_nand_overlay.erase(SUPERBLOCK_START / 0x800); }
void UseUnwritableJournal() { m_memory->m_nand_journal = std::make_unique<NANDJournal>(); }
bool Install() { return m_memory->InstallEmulatedWiimotePairings(); }
NANDJournal::Page ReadSysconfPage(u32 page)
{
NANDJournal::Page raw{};
EXPECT_TRUE(m_memory->ReadRawNANDPage(SYSCONF_CLUSTER * 8 + page, &raw));
return raw;
}
static std::array<u8, 16> CalculateECC(const NANDJournal::Page& page)
{
return StarletMemory::CalculateNANDECC(page.data());
}
void MarkSysconfSpare()
{
for (u32 page = 0; page < 8; ++page)
{
auto& raw = m_memory->m_nand_overlay.at(SYSCONF_CLUSTER * 8 + page);
for (size_t i = 0; i < 0x30; ++i)
raw[0x800 + i] = i == 0 ? 0xff : static_cast<u8>(0x40 + i + page);
}
}
std::unique_ptr<StarletMemory> m_memory;
std::unique_ptr<Superblock> m_superblock;
};
TEST_F(StarletPairingTest, MissingShared2DoesNotPreventBootOrWriteNAND)
{
CheckWithoutWrites(true);
}
TEST_F(StarletPairingTest, MissingSysDoesNotPreventBootOrWriteNAND)
{
AddPath(1);
CheckWithoutWrites(true);
}
TEST_F(StarletPairingTest, MissingSysconfDoesNotPreventBootOrWriteNAND)
{
AddPath(2);
CheckWithoutWrites(true);
}
TEST_F(StarletPairingTest, AbsentBluetoothEntryDoesNotPreventBootOrWriteNAND)
{
SetSysconf(false);
CheckWithoutWrites(true);
}
TEST_F(StarletPairingTest, UnreadableNANDRemainsAnError)
{
StoreSuperblock();
RemoveFirstSuperblockPage();
EXPECT_FALSE(Install());
}
TEST_F(StarletPairingTest, MalformedDirectoryRemainsAnError)
{
m_superblock->fst[0].sub = DiscIO::NANDImporter::FSTEntryCount;
CheckWithoutWrites(false);
}
TEST_F(StarletPairingTest, CyclicSiblingListFailsInsteadOfHanging)
{
m_superblock->fst[0].sub = 1;
m_superblock->fst[1].sib = 1;
CheckWithoutWrites(false);
}
TEST_F(StarletPairingTest, NewestFormattedSuperblockDoesNotRestoreOlderPairings)
{
SetSysconf(true);
StoreSuperblock();
// The formatter's newest root has no shared2, although an old copy still has it.
m_superblock->version = 2;
m_superblock->fst[0].sub = 0xffff;
StoreSuperblock(1);
// Keep the older copy and all raw data intact while selecting the newer root.
EXPECT_TRUE(Install());
}
TEST_F(StarletPairingTest, EmptyExistingSysconfRemainsAnError)
{
AddPath(3);
CheckWithoutWrites(false);
}
TEST_F(StarletPairingTest, FailedPairingWriteRemainsAnErrorAndDoesNotAlterOverlay)
{
SetSysconf(true);
UseUnwritableJournal();
CheckWithoutWrites(false);
}
TEST_F(StarletPairingTest, ExistingEmptyPairingRecordIsStillPopulated)
{
SetSysconf(true);
StoreSuperblock();
EXPECT_TRUE(Install());
// Once installed, the trusted identities are reused without another NAND write.
CheckWithoutWrites(true);
}
TEST_F(StarletPairingTest, PairingWriteUsesNativeSFFSAuthenticationLayout)
{
SetSysconf(true);
m_superblock->fst[3].uid = 0x12345678;
m_superblock->fst[3].x3 = 0x9abcdef0;
StoreSuperblock();
MarkSysconfSpare();
std::array<NANDJournal::Page, 8> before;
for (u32 page = 0; page < 8; ++page)
before[page] = ReadSysconfPage(page);
ASSERT_TRUE(Install());
std::array<NANDJournal::Page, 8> after;
std::vector<u8> ciphertext(0x4000);
for (u32 page = 0; page < 8; ++page)
{
after[page] = ReadSysconfPage(page);
std::copy_n(after[page].begin(), 0x800, ciphertext.begin() + page * 0x800);
}
const std::array<u8, 16> aes_key{};
auto aes = Common::AES::CreateContextDecrypt(aes_key.data());
std::vector<u8> authenticated(0x4040);
ASSERT_TRUE(aes->CryptIvZero(ciphertext.data(), authenticated.data() + 0x40, ciphertext.size()));
const auto pairing = IOS::HLE::GetEmulatedWiimotePairingData();
EXPECT_TRUE(
std::ranges::equal(pairing, std::span(authenticated).subspan(0x40 + 0x1a, pairing.size())));
// Independent fixture salt: UID, file name, cluster ordinal, FST index and x3.
const std::array<u8, 0x1c> salt = {0x12, 0x34, 0x56, 0x78, 'S', 'Y', 'S', 'C', 'O', 'N',
'F', 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 3, 0x9a, 0xbc, 0xde, 0xf0};
std::ranges::copy(salt, authenticated.begin());
const std::array<u8, 20> hmac_key{};
std::array<u8, 20> hmac{};
ASSERT_TRUE(Common::HMAC::HMACWithSHA1(hmac_key, authenticated, hmac.data()));
// Native SFFS puts the full HMAC at spare byte 1 in page 6. The second
// copy is split: 12 bytes at page 6 byte 21, then 8 at page 7 byte 1.
auto expected = before;
std::ranges::copy(hmac, expected[6].begin() + 0x801);
std::copy_n(hmac.begin(), 12, expected[6].begin() + 0x815);
std::copy_n(hmac.begin() + 12, 8, expected[7].begin() + 0x801);
for (u32 page = 0; page < 8; ++page)
{
SCOPED_TRACE(page);
EXPECT_TRUE(std::ranges::equal(std::span(after[page]).subspan(0x800, 0x30),
std::span(expected[page]).subspan(0x800, 0x30)));
EXPECT_TRUE(
std::ranges::equal(CalculateECC(after[page]), std::span(after[page]).subspan(0x830, 16)));
}
}
} // namespace IOS::LLE
@@ -0,0 +1,325 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <cstdio>
#include <cstdlib>
#include <string>
#include <string_view>
#include <vector>
#include <gtest/gtest.h>
#include "ProbeBroadway.h"
#include "ProbeBudget.h"
#include "staros_h1a.h"
#include "staros_hw0c.h"
namespace StarletBootstrapProbe
{
namespace
{
// StarOS boot/wii/loader/board.h's timebase ticks a millisecond.
constexpr u64 TICKS_PER_MS = 60750;
// PPC memory as the client sees it: the bench window's words, and a count of what fell outside.
class FakeMemory final : public BroadwayMemory
{
public:
u32 LoadWord(u32 address) override
{
if (InBenchWindow(address))
return words[(address - BENCH_WINDOW_BASE) / 4];
++outside;
return 0;
}
void StoreWord(u32 address, u32 word) override
{
if (InBenchWindow(address))
words[(address - BENCH_WINDOW_BASE) / 4] = word;
else
++outside;
}
u32& At(u32 offset) { return words[offset / 4]; }
std::vector<u32> words = std::vector<u32>((BENCH_WINDOW_END - BENCH_WINDOW_BASE) / 4);
int outside = 0;
};
TEST(StarletProbeBroadway, TheWindowIsTheContractsAndNothingElseIsReached)
{
EXPECT_EQ(BENCH_WINDOW_BASE, u32{STAROS_HW0C_BASE});
EXPECT_EQ(BENCH_WINDOW_END, u32{STAROS_HW0C_BASE + STAROS_HW0C_SIZE});
FakeMemory memory;
BroadwayHal hal(memory, 100);
hal.Write(BENCH_WINDOW_BASE, 7);
hal.Write(BENCH_WINDOW_END - 4, 9);
EXPECT_EQ(hal.Read(BENCH_WINDOW_BASE), u32{7});
EXPECT_EQ(hal.Read(BENCH_WINDOW_END - 4), u32{9});
hal.CacheLine(BENCH_WINDOW_BASE + 0x20);
EXPECT_FALSE(hal.Failed());
EXPECT_EQ(hal.Accesses(), u64{5});
// The first access outside fails the client, and is never made.
EXPECT_EQ(hal.Read(BENCH_WINDOW_END), u32{0});
EXPECT_TRUE(hal.Failed());
EXPECT_EQ(hal.Failure(), "a read at 0x13510000, outside the bench window 0x13500000..0x13510000");
hal.Write(BENCH_WINDOW_BASE - 4, 1);
hal.Write(BENCH_WINDOW_BASE + 2, 1);
EXPECT_EQ(memory.outside, 0);
EXPECT_EQ(hal.Failure(), "a read at 0x13510000, outside the bench window 0x13500000..0x13510000");
EXPECT_FALSE(InBenchWindow(BENCH_WINDOW_BASE + 2));
EXPECT_FALSE(InBenchWindow(0x135E0000));
EXPECT_FALSE(InBenchWindow(u64{BENCH_WINDOW_BASE} + 0x100000000));
}
TEST(StarletProbeBroadway, TheTimebaseIsAQuarterOfTheStarletsCycles)
{
FakeMemory memory;
BroadwayHal hal(memory, CLIENT_TIMEBASE_BASE);
hal.Elapse(0);
EXPECT_EQ(hal.Timebase(), CLIENT_TIMEBASE_BASE);
hal.Elapse(SLICE_CYCLES);
EXPECT_EQ(hal.Timebase(), CLIENT_TIMEBASE_BASE + 1024);
// 2 ms of Broadway's timebase (StarOS's TICKS_PER_MS, 60750) is 486,000 Starlet cycles.
hal.Elapse(486000);
EXPECT_EQ(hal.Timebase() - CLIENT_TIMEBASE_BASE - 1024, u64{121500});
}
TEST(StarletProbeBroadway, TheCaptureIsGeckosFormats)
{
FakeMemory memory;
BroadwayHal hal(memory, 0);
hal.Put("SBL:X ");
hal.Hex(0x1A);
hal.Put(" ");
hal.Dec(0);
hal.Put(" ");
hal.Dec(0xFFFFFFFF);
hal.Put(" ");
hal.Hex(0xDEADBEEF);
EXPECT_EQ(hal.Capture(), "SBL:X 0x0000001a 0 4294967295 0xdeadbeef");
}
TEST(StarletProbeBroadway, TheClientsBudgetIsBoundedAndOnlyItsOwn)
{
EXPECT_EQ(MAX_CLIENT_CYCLES, u64{1} << 34);
EXPECT_EQ(ParseCycles("17179869184", MAX_CLIENT_CYCLES), MAX_CLIENT_CYCLES);
EXPECT_FALSE(ParseCycles("17179873280", MAX_CLIENT_CYCLES));
EXPECT_FALSE(ParseCycles("17179869185", MAX_CLIENT_CYCLES));
// Without the client, 2^30 as before.
EXPECT_EQ(ParseCycles("1073741824"), MAX_CYCLES);
EXPECT_FALSE(ParseCycles("1073745920"));
EXPECT_FALSE(ParseCycles("17179869184"));
}
TEST(StarletProbeBroadway, OnlyTheOptionItselfRaisesTheBudget)
{
const auto requested = [](std::vector<const char*> argv) {
return ClientRequested(static_cast<int>(argv.size()), argv.data());
};
EXPECT_TRUE(requested({"probe", "image.elf", "--broadway-h1a"}));
EXPECT_TRUE(requested({"probe", "image.elf", "--jit", "--cycles", "4096", "--broadway-h1a"}));
EXPECT_TRUE(requested({"probe", "image.elf", "--stage-spk", "p.bin", "--broadway-h1a"}));
EXPECT_FALSE(requested({"probe", "image.elf"}));
// The image's own name, or another option's value, is no option.
EXPECT_FALSE(requested({"probe", "--broadway-h1a"}));
EXPECT_FALSE(requested({"probe", "image.elf", "--ipc-script", "--broadway-h1a"}));
EXPECT_FALSE(requested({"probe", "image.elf", "--stage-spk", "--broadway-h1a", "--jit"}));
EXPECT_FALSE(requested({"probe", "image.elf", "--cycles", "--broadway-h1a"}));
}
TEST(StarletProbeBroadway, TheStarletIsDoneAsTheLoadersMonitorSaysIt)
{
// StarOS boot/contract/staros_boot.h: RUNNING 2, IDLE 3, FATAL 4, PANIC 5, FAULT 6; EXI PPC 1.
EXPECT_EQ(SBR1_STATE_IDLE, u32{3});
EXPECT_TRUE(StarletDone(false, 3, SBR1_EXI_PPC));
EXPECT_TRUE(StarletDone(false, 6, SBR1_EXI_PPC));
EXPECT_FALSE(StarletDone(false, 2, SBR1_EXI_PPC));
EXPECT_FALSE(StarletDone(false, 3, SBR1_EXI_STARLET));
EXPECT_FALSE(StarletDone(false, 0, 0));
// A terminal trace line counts on its own.
EXPECT_TRUE(StarletDone(true, 0, 0));
}
TEST(StarletProbeBroadway, TheBuiltInSourcesAreTheNineFilesWithTheirHashes)
{
const std::string_view sources = BroadwayClient::Sources();
const char* names[] = {"hw0c.c", "hw0c.h", "hw0d.c", "hw0d.h", "h1a.c",
"h1a.h", "staros_hw0c.h", "staros_hw0d.h", "staros_h1a.h"};
size_t at = 0;
for (const char* name : names)
{
const size_t end = sources.find('\n', at);
ASSERT_NE(end, std::string_view::npos);
const std::string_view line = sources.substr(at, end - at);
EXPECT_TRUE(line.starts_with(std::string(name) + " ")) << line;
EXPECT_EQ(line.size(), std::string_view(name).size() + 1 + 64) << line;
at = end + 1;
}
EXPECT_EQ(at, sources.size());
}
// A scripted Starlet over the fake window, as StarOS's tests/hardware-wii/h1a benches script it:
// READY 100 ms after the first step (unless `ready` is false), then each round answered at least
// 40,960 timebase ticks after it was first seen posted, S2B's words first for a Starlet -> Broadway
// round; after the last round or Broadway's END, its record (GEN 2) and its END (unless `ends` is
// false).
struct Starlet
{
bool ready = true;
bool ends = true;
bool answered_ready = false;
bool ended = false;
u32 answered = 0;
bool seen = false;
u64 seen_at = 0;
static u32 Scenario(u32 round) { return round <= STAROS_H1A_S1_ROUNDS ? STAROS_H1A_S1 : STAROS_H1A_S3; }
void Tick(FakeMemory& memory, u64 now, u64 start)
{
const u32 broadway = STAROS_HW0C_BROADWAY, starlet = STAROS_HW0C_STARLET;
if (!answered_ready)
{
if (ready && now >= start + 100 * TICKS_PER_MS)
{
answered_ready = true;
memory.At(STAROS_HW0C_ENVIRONMENT + STAROS_HW0C_E_CONTROL) = 0x000520FB;
memory.At(STAROS_HW0C_ENVIRONMENT + STAROS_HW0C_E_DACR) = 1;
memory.At(STAROS_HW0C_ENVIRONMENT + STAROS_HW0C_E_DESCRIPTOR) = 0x13500552;
memory.At(STAROS_HW0C_ENVIRONMENT + STAROS_HW0C_E_SENTINEL_BAD) = 0;
memory.At(starlet + STAROS_HW0C_C_STATE) = STAROS_HW0C_STATE_READY;
}
return;
}
if (ended)
return;
if (answered == STAROS_H1A_ROUNDS ||
memory.At(broadway + STAROS_HW0C_C_STATE) == STAROS_HW0C_STATE_END)
{
if (!ends)
return;
for (u32 i = 0; i < STAROS_H1A_RESULTS_WORDS; ++i)
memory.At(STAROS_H1A_RESULTS + 4 * i) = 0x1000 + i;
memory.At(STAROS_H1A_RESULTS + 4 * STAROS_H1A_F_MAGIC) = STAROS_H1A_MAGIC;
memory.At(STAROS_H1A_RESULTS + 4 * STAROS_H1A_F_VERSION) = STAROS_H1A_VERSION;
memory.At(STAROS_H1A_RESULTS + 4 * STAROS_H1A_F_GEN) = STAROS_H1A_GEN;
memory.At(starlet + STAROS_HW0C_C_STATE) = STAROS_HW0C_STATE_END;
ended = true;
return;
}
const u32 round = answered + 1;
if (memory.At(broadway + STAROS_HW0C_C_STATE) != STAROS_HW0C_STATE_ROUND ||
memory.At(broadway + STAROS_HW0C_C_ROUND) != round ||
memory.At(broadway + STAROS_HW0C_C_SCENARIO) != Scenario(round))
{
return;
}
if (!seen)
{
seen = true;
seen_at = now;
}
if (now - seen_at < 40960)
return;
const bool s2b = round > STAROS_H1A_S1_ROUNDS && (round - STAROS_H1A_S1_ROUNDS) % 2 == 0;
if (s2b)
{
for (u32 w = 0; w < STAROS_H1A_AREA_WORDS; ++w)
{
const u32 offset = STAROS_H1A_S2B + 4 * w;
memory.At(offset) = STAROS_HW0C_PATTERN(STAROS_HW0C_TAG_S2B, round, offset / 4);
}
}
memory.At(starlet + STAROS_HW0C_C_SCENARIO) = Scenario(round);
memory.At(starlet + STAROS_HW0C_C_STATE) = STAROS_HW0C_STATE_ROUND;
memory.At(starlet + STAROS_HW0C_C_ROUND) = round;
answered = round;
seen = false;
}
};
// One whole run of the real loader code in this process (its state is global: each death test's
// child runs it alone). Its report goes to stderr; the child exits 0 only if the run ended (or not)
// as `done` says, reached nothing outside the window, held every line of `required` in its report,
// and a second client in the same process was refused. (Windows' gtest has only simple regular
// expressions, so the child checks the report itself.)
[[noreturn]] void RunClient(Starlet starlet, u64 slices, bool done,
std::vector<std::string_view> required)
{
FakeMemory memory;
BroadwayClient client;
if (!client.Start(memory))
std::exit(2);
const u64 start = client.Timebase();
for (u64 slice = 0; slice < slices && !client.Done() && !client.Failed(); ++slice)
{
starlet.Tick(memory, client.Timebase(), start);
client.Advance(slice == 0 ? 0 : SLICE_CYCLES);
}
const std::string report =
client.Report(client.Done() ? CLIENT_STATUS_DONE : CLIENT_STATUS_TIMEOUT);
std::fputs(report.c_str(), stderr);
int missing = 0;
for (const std::string_view line : required)
{
if (report.find(line) == std::string::npos)
{
std::fprintf(stderr, "MISSING %.*s\n", static_cast<int>(line.size()), line.data());
++missing;
}
}
BroadwayClient second;
FakeMemory other;
const bool refused = !second.Start(other) && second.Failed();
std::fprintf(stderr, "steps %llu outside %d failed %d done %d refused %d missing %d\n",
static_cast<unsigned long long>(client.Steps()), memory.outside,
static_cast<int>(client.Failed()), static_cast<int>(client.Done()),
static_cast<int>(refused), missing);
const bool passed = client.Done() == done && !client.Failed() && memory.outside == 0 &&
refused && missing == 0;
std::exit(passed ? 0 : 1);
}
// Enough slices for 3000 rounds of at least 2 ms each, and the waits: 2^34 cycles' worth.
constexpr u64 SLICES = MAX_CLIENT_CYCLES / SLICE_CYCLES;
TEST(StarletProbeBroadwayDeathTest, TheRealLoaderRunsAllRoundsAndReports)
{
EXPECT_EXIT(RunClient(Starlet{}, SLICES, true,
{"SBL:STARLET DONE\n", "SBL:HW0C S0 PASS\n",
"SBL:H1A B POSTS 3000 LAST 3000 ACKS 3000 TIMEOUT 0 ",
"SBL:H1A B CHECK SENTINEL 0 SCRUB 0 POOL 0\n",
"SBL:H1A S GEN 0x00000002 0x00000002 ATTEMPTS 1 COHERENT\n",
"SBL:H1A END CRC 0x", "\nSBL:END GECKO DROPPED AFTER JUMP 0 BEFORE 0\n"}),
::testing::ExitedWithCode(0), "");
}
TEST(StarletProbeBroadwayDeathTest, WithoutReadyTheBenchTimesOutAndNeverStartsH1A)
{
Starlet starlet;
starlet.ready = false;
EXPECT_EXIT(RunClient(starlet, SLICES, true,
{"SBL:HW0C S0 INCONCLUSIVE\n", "SBL:HW0C TIMEOUT S0 ROUND 0\n",
"SBL:H1A B POSTS 0 LAST 0 ACKS 0 ", "ATTEMPTS 3 INCOMPLETE\n"}),
::testing::ExitedWithCode(0), "");
}
TEST(StarletProbeBroadwayDeathTest, WithoutTheStarletsEndBroadwayStopsAtReadyPlus65s)
{
Starlet starlet;
starlet.ends = false;
EXPECT_EXIT(RunClient(starlet, SLICES, true,
{"SBL:HW0C S0 INCONCLUSIVE\n", "SBL:HW0C TIMEOUT S0 ROUND 0\n",
"SBL:H1A B POSTS 3000 LAST 3000 ", "ATTEMPTS 3 INCOMPLETE\n"}),
::testing::ExitedWithCode(0), "");
}
TEST(StarletProbeBroadwayDeathTest, ABudgetTooShortEndsUnderTimeout)
{
EXPECT_EXIT(RunClient(Starlet{}, 1000, false,
{"SBL:TIMEOUT\n", "SBL:END GECKO DROPPED AFTER JUMP 0 BEFORE 0\n"}),
::testing::ExitedWithCode(0), "");
}
} // namespace
} // namespace StarletBootstrapProbe
@@ -0,0 +1,46 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <string_view>
#include <gtest/gtest.h>
#include "ProbeBudget.h"
namespace StarletBootstrapProbe
{
namespace
{
// The parsed budget, or 0 when refused.
u64 Parsed(std::string_view text)
{
return ParseCycles(text).value_or(0);
}
TEST(StarletProbeBudget, DefaultIsTheFormerFixedBudget)
{
EXPECT_EQ(DEFAULT_CYCLES, u64{2097152});
EXPECT_EQ(DEFAULT_CYCLES % SLICE_CYCLES, u64{0});
EXPECT_EQ(Parsed("2097152"), DEFAULT_CYCLES);
}
TEST(StarletProbeBudget, AcceptsWholeSlicesUpToTheMaximum)
{
EXPECT_EQ(Parsed("4096"), u64{4096});
EXPECT_EQ(Parsed("16777216"), u64{16777216});
EXPECT_EQ(Parsed("1073741824"), MAX_CYCLES);
// Leading zeros are still a decimal number.
EXPECT_EQ(Parsed("0008192"), u64{8192});
}
TEST(StarletProbeBudget, RefusesEverythingElse)
{
for (const std::string_view text :
{"", "0", "4095", "4097", "6144", "1073745920", "999999999999", "1234567890123",
"99999999999999999999", "-4096", "+4096", "0x1000", "4096 ", " 4096", "4k", "4096.0"})
{
EXPECT_FALSE(ParseCycles(text).has_value()) << '"' << text << '"';
}
}
} // namespace
} // namespace StarletBootstrapProbe
@@ -0,0 +1,68 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <gtest/gtest.h>
#include "Core/Core.h"
#include "Core/HW/WII_IPC.h"
#include "Core/System.h"
namespace IOS
{
namespace
{
constexpr u32 PPCCTRL = 0x04;
constexpr u32 ARMCTRL = 0x0c;
constexpr u32 ARM_IRQMASK = 0x3c;
constexpr u32 IX1 = 0x10;
constexpr u32 X1 = 0x01;
WiiIPC& Fresh(bool attached)
{
Core::DeclareAsCPUThread();
auto& ipc = Core::System::GetInstance().GetWiiIPC();
ipc.Reset();
ipc.SetStarletAttached(attached);
ipc.WriteStarletRegister(ARM_IRQMASK, INT_CAUSE_IPC_STARLET);
return ipc;
}
TEST(StarletProbeInterrupt, WithoutTheFlagX1NeverReachesTheStarlet)
{
// master's behaviour, with no Starlet object in the system.
auto& ipc = Fresh(false);
ipc.WriteStarletRegister(ARMCTRL, IX1);
ipc.WriteStarletRegister(PPCCTRL, X1);
EXPECT_FALSE(ipc.IsStarletIRQAsserted());
}
TEST(StarletProbeInterrupt, WithTheFlagTheModelRaisesItOnX1AndIX1)
{
auto& ipc = Fresh(true);
ipc.WriteStarletRegister(ARMCTRL, IX1);
EXPECT_FALSE(ipc.IsStarletIRQAsserted());
ipc.WriteStarletRegister(PPCCTRL, X1);
EXPECT_TRUE(ipc.IsStarletIRQAsserted());
}
TEST(StarletProbeInterrupt, WithoutIX1TheCauseWaitsForIt)
{
auto& ipc = Fresh(true);
ipc.WriteStarletRegister(PPCCTRL, X1);
EXPECT_FALSE(ipc.IsStarletIRQAsserted());
// The same model line, on the Starlet's first ARMCTRL write.
ipc.WriteStarletRegister(ARMCTRL, IX1);
EXPECT_TRUE(ipc.IsStarletIRQAsserted());
}
TEST(StarletProbeInterrupt, ResetClearsTheFlag)
{
auto& ipc = Fresh(true);
ipc.Reset();
ipc.WriteStarletRegister(ARM_IRQMASK, INT_CAUSE_IPC_STARLET);
ipc.WriteStarletRegister(ARMCTRL, IX1);
ipc.WriteStarletRegister(PPCCTRL, X1);
EXPECT_FALSE(ipc.IsStarletIRQAsserted());
}
} // namespace
} // namespace IOS
@@ -0,0 +1,99 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <map>
#include <string>
#include <gtest/gtest.h>
#include "StarOSPanicCheck.h"
namespace StarletBootstrapProbe
{
namespace
{
// MEM1 words by address; absent words read as zero.
class FakeMem1
{
public:
std::map<u32, u32> words;
u32 operator()(u32 address) const
{
const auto it = words.find(address);
return it == words.end() ? 0 : it->second;
}
};
// The record as the loader leaves it, before the image runs.
FakeMem1 CreatedRecord()
{
FakeMem1 mem1;
mem1.words[SBR1_BASE] = SBR1_MAGIC;
mem1.words[SBR1_BASE + 0x04] = SBR1_VERSION;
mem1.words[SBR1_BASE + 0x08] = SBR1_SIZE;
mem1.words[SBR1_BASE + SBR1_EXI_OWNER] = SBR1_EXI_STARLET;
mem1.words[SBR1_BASE + SBR1_RELAY_STATUS] = SBR1_RELAY_JUMPING;
return mem1;
}
// The record once StarOS's panic path has published it.
FakeMem1 PanicRecord()
{
FakeMem1 mem1 = CreatedRecord();
mem1.words[SBR1_BASE + SBR1_STARLET_STATE] = SBR1_STATE_PANIC;
mem1.words[SBR1_BASE + SBR1_EXI_OWNER] = SBR1_EXI_PPC;
return mem1;
}
TEST(StarletProbePanicCheck, WaitsForTheCodeAfterTheGuard)
{
const FakeMem1 none;
EXPECT_EQ(UnmetPanicCondition(1, 1, SBR1Mode::None, none), "");
// The guard is stored before the code: a slice can end in between.
EXPECT_EQ(UnmetPanicCondition(1, 0, SBR1Mode::None, none), "__panic_code is 0, not 1");
EXPECT_EQ(UnmetPanicCondition(1, 2, SBR1Mode::None, none), "__panic_code is 2, not 1");
EXPECT_EQ(UnmetPanicCondition(0, 1, SBR1Mode::None, none), "__panic_state is 0, not 1");
EXPECT_EQ(UnmetPanicCondition(2, 1, SBR1Mode::None, none), "__panic_state is 2, not 1");
// The words come first, whatever the record says.
EXPECT_EQ(UnmetPanicCondition(1, 0, SBR1Mode::Record, PanicRecord()),
"__panic_code is 0, not 1");
}
TEST(StarletProbePanicCheck, RecordNeedsPanicStateReasonAndEXIBack)
{
EXPECT_EQ(UnmetPanicCondition(1, 1, SBR1Mode::Record, PanicRecord()), "");
// Panic words set, record not yet published.
EXPECT_EQ(UnmetPanicCondition(1, 1, SBR1Mode::Record, CreatedRecord()),
"SBR1 STARLET_STATE is 0, not 5");
FakeMem1 running = PanicRecord();
running.words[SBR1_BASE + SBR1_STARLET_STATE] = 2;
EXPECT_EQ(UnmetPanicCondition(1, 1, SBR1Mode::Record, running), "SBR1 STARLET_STATE is 2, not 5");
FakeMem1 reason = PanicRecord();
reason.words[SBR1_BASE + SBR1_FATAL_REASON] = 3;
EXPECT_EQ(UnmetPanicCondition(1, 1, SBR1Mode::Record, reason), "SBR1 FATAL_REASON is 3, not 0");
// State published, EXI not yet handed back to the PPC.
FakeMem1 exi = PanicRecord();
exi.words[SBR1_BASE + SBR1_EXI_OWNER] = SBR1_EXI_STARLET;
EXPECT_EQ(UnmetPanicCondition(1, 1, SBR1Mode::Record, exi), "SBR1 EXI_OWNER is 2, not 1");
}
TEST(StarletProbePanicCheck, AbsentRecordAreaStaysZero)
{
EXPECT_EQ(UnmetPanicCondition(1, 1, SBR1Mode::Absent, FakeMem1{}), "");
for (const u32 offset : {0x0u, SBR1_STARLET_STATE, SBR1_EXI_OWNER, SBR1_SIZE - 4})
{
FakeMem1 written;
written.words[SBR1_BASE + offset] = 5;
EXPECT_EQ(UnmetPanicCondition(1, 1, SBR1Mode::Absent, written),
fmt::format("SBR1 area word +{:#x} is 0x5 without a record", offset));
}
// Words outside the area are not the record's.
FakeMem1 outside;
outside.words[SBR1_BASE - 4] = 5;
outside.words[SBR1_BASE + SBR1_SIZE] = 5;
EXPECT_EQ(UnmetPanicCondition(1, 1, SBR1Mode::Absent, outside), "");
// Without an SBR1 option, a written area is not checked.
EXPECT_EQ(UnmetPanicCondition(1, 1, SBR1Mode::None, PanicRecord()), "");
}
} // namespace
} // namespace StarletBootstrapProbe
@@ -0,0 +1,58 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <map>
#include <string>
#include <gtest/gtest.h>
#include "ProbeRing.h"
namespace StarletBootstrapProbe
{
namespace
{
// Record bytes by offset; absent bytes read as zero.
class FakeRecord
{
public:
std::map<u32, u8> bytes;
void Put(const std::string& text)
{
for (size_t index = 0; index < text.size(); ++index)
bytes[SBR1_RING + static_cast<u32>(index)] = static_cast<u8>(text[index]);
}
u8 operator()(u32 offset) const
{
const auto it = bytes.find(offset);
return it == bytes.end() ? 0 : it->second;
}
};
TEST(StarletProbeRing, PrintsTheTextUpToItsLength)
{
FakeRecord record;
record.Put("REV:BOOT:ENTRY\nEXP3 OWN 23 PAGES 0 CHANGED\nleft over");
EXPECT_EQ(RingText(record, 0), "");
EXPECT_EQ(RingText(record, 15), "REV:BOOT:ENTRY\n");
EXPECT_EQ(RingText(record, 43), "REV:BOOT:ENTRY\nEXP3 OWN 23 PAGES 0 CHANGED\n");
}
TEST(StarletProbeRing, LengthIsClampedToTheRing)
{
EXPECT_EQ(SBR1_RING_BYTES, 4032u);
FakeRecord record;
record.Put(std::string(SBR1_RING_BYTES, 'x'));
record.bytes[SBR1_SIZE] = 'y';
EXPECT_EQ(RingText(record, 0xffffffff), std::string(SBR1_RING_BYTES, 'x'));
}
TEST(StarletProbeRing, EscapesWhatIsNotText)
{
FakeRecord record;
// a, NUL, b, CR, tab, backslash, c, DEL, 0xff, newline: ten bytes.
record.Put(std::string("a\0b\r\t\\c\x7f\xff\n", 10));
EXPECT_EQ(RingText(record, 10), "a\\x00b\\x0d\\x09\\x5cc\\x7f\\xff\n");
}
} // namespace
} // namespace StarletBootstrapProbe
@@ -0,0 +1,213 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <map>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "ProbeScript.h"
namespace StarletBootstrapProbe
{
namespace
{
// The script's error, or "" when it parses.
std::string Refusal(std::string_view script)
{
std::string error;
return ParseScript(script, &error) ? "" : error;
}
std::vector<ScriptStep> Steps(std::string_view script)
{
std::string error;
const auto steps = ParseScript(script, &error);
EXPECT_TRUE(steps.has_value()) << error;
return steps.value_or(std::vector<ScriptStep>{});
}
class FakeBus final : public ScriptBus
{
public:
void StoreWord(u32 address, u32 word) override
{
log.push_back("store");
words[address] = word;
}
u32 LoadWord(u32 address) override { return words[address]; }
void WriteRegister(u32 offset, u32 value) override
{
log.push_back(offset == IPC_PPCMSG ? "ppcmsg" : "ppcctrl");
registers[offset] = value;
}
u32 ReadRegister(u32 offset) override { return registers[offset]; }
std::map<u32, u32> words;
std::map<u32, u32> registers;
std::vector<std::string> log;
};
TEST(StarletProbeScript, TheRangeIsTheContracts)
{
EXPECT_EQ(IPC_RANGE_BASE, u32{0x135E0000});
EXPECT_EQ(IPC_RANGE_END, u32{0x13600000});
EXPECT_TRUE(InIPCRange(0x135E0000));
EXPECT_TRUE(InIPCRange(0x135FFFFC));
EXPECT_FALSE(InIPCRange(0x135DFFFC));
EXPECT_FALSE(InIPCRange(0x13600000));
EXPECT_FALSE(InIPCRange(0x135E0002));
EXPECT_FALSE(InIPCRange(0x135FFFFE));
// The package window and the kernel's memory lie above the boundary.
EXPECT_FALSE(InIPCRange(0x13720000));
}
TEST(StarletProbeScript, ParsesEveryStepCommentsAndBlankLines)
{
const auto steps = Steps("# a comment\n"
"\n"
"store 0x135E0000 1 # trailing\n"
" ppcmsg\t0x135E0000\r\n"
"ppcctrl 0x31\n"
"wait 0x02 0x02 4096\n"
"expect-armmsg 0x135E0000\n"
"expect 0x135E0004 0xFFFFFFFA\n"
"run 8192");
ASSERT_EQ(steps.size(), size_t{7});
EXPECT_EQ(steps[0].kind, StepKind::Store);
EXPECT_EQ(steps[0].line, 3);
EXPECT_EQ(steps[0].first, u32{0x135E0000});
EXPECT_EQ(steps[3].kind, StepKind::Wait);
EXPECT_EQ(steps[3].cycles, u64{4096});
EXPECT_EQ(steps[5].second, u32{0xFFFFFFFA});
EXPECT_EQ(steps[6].kind, StepKind::Run);
}
TEST(StarletProbeScript, APpcMsgMayNameAnAddressOutOfTheRange)
{
// A register's value: the negative scenario's, an envelope the kernel must refuse.
EXPECT_EQ(Refusal("ppcmsg 0x00001000\n"), "");
}
TEST(StarletProbeScript, RefusesWhatIsNotTheFormat)
{
EXPECT_EQ(Refusal("nop\n"), "line 1: unknown step: nop");
EXPECT_EQ(Refusal("\n\nstore 1\n"), "line 3: takes an address and a word");
EXPECT_EQ(Refusal("store 0x135E0000 1 2\n"), "line 1: takes an address and a word");
EXPECT_EQ(Refusal("store 0x135E0000 0x100000000\n"), "line 1: takes an address and a word");
EXPECT_EQ(Refusal("store 0x135E0000 x\n"), "line 1: not a number: x");
EXPECT_EQ(Refusal("store 0x 1\n"), "line 1: not a number: 0x");
EXPECT_EQ(Refusal("store -4 1\n"), "line 1: not a number: -4");
EXPECT_EQ(Refusal("ppcmsg\n"), "line 1: takes one word");
EXPECT_EQ(Refusal("ppcctrl 0x40\n"), "line 1: takes PPCCTRL's six bits");
EXPECT_EQ(Refusal("wait 1 1\n"), "line 1: takes a mask, a value and a bound in cycles");
EXPECT_EQ(Refusal("wait 1 1 0\n"), "line 1: takes a mask, a value and a bound in cycles");
EXPECT_EQ(Refusal("run 0\n"), "line 1: takes a number of cycles");
EXPECT_EQ(Refusal("run 1073741825\n"), "line 1: takes a number of cycles");
}
TEST(StarletProbeScript, RefusesAStoreOrAnExpectOutOfTheRange)
{
const std::string_view why = "line 1: the address is not a whole word of the range";
EXPECT_EQ(Refusal("store 0x135DFFFC 1\n"), why);
EXPECT_EQ(Refusal("store 0x13600000 1\n"), why);
EXPECT_EQ(Refusal("store 0x135E0002 1\n"), why);
EXPECT_EQ(Refusal("store 0x13720000 1\n"), why);
EXPECT_EQ(Refusal("expect 0x00200000 1\n"), why);
}
TEST(StarletProbeScript, RefusesTooManySteps)
{
std::string script;
for (size_t index = 0; index < SCRIPT_MAX_STEPS; ++index)
script += "run 4096\n";
EXPECT_EQ(Refusal(script), "");
script += "run 4096\n";
EXPECT_EQ(Refusal(script), "line 257: more than 256 steps");
}
TEST(StarletProbeScript, StepsRunInOrderUpToOneThatWaits)
{
FakeBus bus;
ScriptRunner runner(Steps("store 0x135E0000 7\n"
"ppcmsg 0x135E0000\n"
"ppcctrl 0x31\n"
"wait 0x02 0x02 8192\n"
"ppcctrl 0x32\n"));
runner.Advance(bus, 0);
EXPECT_EQ(bus.log, (std::vector<std::string>{"store", "ppcmsg", "ppcctrl"}));
EXPECT_EQ(bus.words[0x135E0000], u32{7});
EXPECT_EQ(bus.registers[IPC_PPCMSG], u32{0x135E0000});
EXPECT_FALSE(runner.Done());
EXPECT_EQ(runner.Line(), 4);
// Y2 raised by the code under test: the wait ends, the next step runs.
runner.Advance(bus, 4096);
EXPECT_FALSE(runner.Done());
bus.registers[IPC_PPCCTRL] = 0x33;
runner.Advance(bus, 4096);
EXPECT_TRUE(runner.Done());
EXPECT_EQ(bus.registers[IPC_PPCCTRL], u32{0x32});
EXPECT_FALSE(runner.Failed());
}
TEST(StarletProbeScript, AWaitThatRunsOutOfItsBoundFailsItsLine)
{
FakeBus bus;
ScriptRunner runner(Steps("\nwait 0x04 0x04 8192\n"));
runner.Advance(bus, 0);
runner.Advance(bus, 4096);
EXPECT_FALSE(runner.Failed());
bus.registers[IPC_PPCCTRL] = 0x30;
runner.Advance(bus, 4096);
ASSERT_TRUE(runner.Failed());
EXPECT_EQ(runner.Failure(), "line 2: PPCCTRL reads 0x30 after 8192 cycles");
EXPECT_FALSE(runner.Done());
// A failed script runs nothing more.
bus.registers[IPC_PPCCTRL] = 0x34;
runner.Advance(bus, 4096);
EXPECT_FALSE(runner.Done());
}
TEST(StarletProbeScript, AnExpectationNotMetFailsItsLine)
{
FakeBus bus;
ScriptRunner armmsg(Steps("expect-armmsg 0x135E0000\n"));
armmsg.Advance(bus, 0);
EXPECT_EQ(armmsg.Failure(), "line 1: ARMMSG reads 0x0, not 0x135e0000");
ScriptRunner word(Steps("expect 0x135E0004 1\n"));
word.Advance(bus, 0);
EXPECT_EQ(word.Failure(), "line 1: the word at 0x135e0004 reads 0x0, not 0x1");
bus.words[0x135E0004] = 1;
ScriptRunner met(Steps("expect 0x135E0004 1\n"));
met.Advance(bus, 0);
EXPECT_TRUE(met.Done());
EXPECT_FALSE(met.Failed());
}
TEST(StarletProbeScript, RunWaitsItsCycles)
{
FakeBus bus;
ScriptRunner runner(Steps("run 8192\nppcctrl 1\n"));
runner.Advance(bus, 0);
runner.Advance(bus, 4096);
EXPECT_TRUE(bus.log.empty());
runner.Advance(bus, 4096);
EXPECT_EQ(bus.log, (std::vector<std::string>{"ppcctrl"}));
EXPECT_TRUE(runner.Done());
}
TEST(StarletProbeScript, AnEmptyScriptIsDone)
{
FakeBus bus;
ScriptRunner runner(Steps("# nothing\n"));
runner.Advance(bus, 0);
EXPECT_TRUE(runner.Done());
}
} // namespace
} // namespace StarletBootstrapProbe
@@ -0,0 +1,42 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <gtest/gtest.h>
#include "ProbeStaging.h"
namespace StarletBootstrapProbe
{
namespace
{
TEST(StarletProbeStaging, TheWindowIsTheContracts)
{
// StarOS docs/contracts/spk-staging.md: 0x13720000..0x13740000, in MEM2.
EXPECT_EQ(SPK_WINDOW_BASE, u32{0x13720000});
EXPECT_EQ(SPK_WINDOW_SIZE, u32{128 * 1024});
EXPECT_EQ(SPK_WINDOW_BASE % 4, u32{0});
EXPECT_LE(u64{SPK_WINDOW_BASE} + SPK_WINDOW_SIZE, u64{0x14000000});
}
TEST(StarletProbeStaging, AcceptsWholeWordsUpToTheWindow)
{
for (const u64 size :
{u64{4}, u64{16}, u64{10800}, u64{SPK_WINDOW_SIZE - 4}, u64{SPK_WINDOW_SIZE}})
{
EXPECT_FALSE(StagingRefusal(size).has_value()) << size;
}
}
TEST(StarletProbeStaging, RefusesEmptyPartialOrOversizedFiles)
{
EXPECT_EQ(StagingRefusal(0), "it is empty");
for (const u64 size : {u64{1}, u64{2}, u64{3}, u64{5}, u64{10801}, u64{SPK_WINDOW_SIZE - 1}})
EXPECT_EQ(StagingRefusal(size), "its length is not a whole number of 32-bit words") << size;
for (const u64 size : {u64{SPK_WINDOW_SIZE + 4}, u64{16} * 1024 * 1024, u64{1} << 40})
EXPECT_EQ(StagingRefusal(size), "it is larger than the 128 KiB package window") << size;
// Not whole words and too large: the words' refusal first.
EXPECT_EQ(StagingRefusal(SPK_WINDOW_SIZE + 1),
"its length is not a whole number of 32-bit words");
}
} // namespace
} // namespace StarletBootstrapProbe
@@ -0,0 +1,441 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <algorithm>
#include <array>
#include <iomanip>
#include <memory>
#include <optional>
#include <gtest/gtest.h>
#include "Common/Swap.h"
#include "Core/Core.h"
#include "Core/HW/WII_IPC.h"
#include "Core/IOS/Starlet/ARMCore.h"
#include "Core/IOS/Starlet/StarletMemory.h"
#include "Core/System.h"
namespace IOS::LLE
{
#if defined(_M_X86_64)
namespace
{
// Only code and page tables use synthetic RAM. Data reads exercise the actual SRAM/boot0 bus,
// without initializing any firmware, NAND image, profile, or live peripheral scheduler.
class SRAMReadBus final : public ARMBus
{
public:
SRAMReadBus() : memory(Core::System::GetInstance())
{
memory.Reset();
for (u32 i = 0; i < 0x18000; ++i)
memory.GetFastmemSRAMBase()[i] = static_cast<u8>((i * 13) ^ (i >> 8) ^ 0xa5);
}
u8 Read8(u32 address) override
{
if (address < ram.size())
return ram[address];
++data_reads;
return memory.Read8(address);
}
u16 Read16(u32 address) override
{
if (address < ram.size())
return ARMBus::Read16(address);
++data_reads;
return memory.Read16(address);
}
u32 Read32(u32 address) override
{
if (address < ram.size())
return ARMBus::Read32(address);
++data_reads;
return memory.Read32(address);
}
void Write8(u32 address, u8 value) override
{
if (address < ram.size())
ram[address] = value;
else
memory.Write8(address, value);
}
void Write16(u32 address, u16 value) override
{
if (address < ram.size())
ARMBus::Write16(address, value);
else
memory.Write16(address, value);
}
void Write32(u32 address, u32 value) override
{
if (address < ram.size())
ARMBus::Write32(address, value);
else
memory.Write32(address, value);
}
u8* GetFastmemBase() const override { return const_cast<u8*>(ram.data()); }
u8* GetFastmemSRAMBase() const override { return memory.GetFastmemSRAMBase(); }
const bool* GetFastmemBoot0Mapped() const override { return memory.GetFastmemBoot0Mapped(); }
const bool* GetFastmemSRAMSplitMode() const override { return memory.GetFastmemSRAMSplitMode(); }
const u8* GetDirectMemoryPointer(u32 address, u32 size) const override
{
if (address < ram.size() && size <= ram.size() - address)
return ram.data() + address;
return memory.GetDirectMemoryPointer(address, size);
}
void SetMapping(bool split, bool boot0)
{
memory.Write32(0x0d800060, split ? 0x20 : 0); // HW_SRNPROT
memory.Write32(0x0d80018c, boot0 ? 0 : 0x1000); // HW_BOOT0
}
void InstallReads(bool thumb, bool big_endian)
{
if (thumb)
{
constexpr std::array<u16, 6> code = {
0x6830, // ldr r0, [r6]
0x7831, // ldrb r1, [r6]
0x8832, // ldrh r2, [r6]
0x57f3, // ldrsb r3, [r6, r7]
0x5ff4, // ldrsh r4, [r6, r7]
0xe7fe, // b .
};
for (u32 i = 0; i < code.size(); ++i)
Write16(i * 2, big_endian ? code[i] : Common::swap16(code[i]));
}
else
{
constexpr std::array<u32, 6> code = {
0xe5960000, // ldr r0, [r6]
0xe5d61000, // ldrb r1, [r6]
0xe1d620b0, // ldrh r2, [r6]
0xe1d630d0, // ldrsb r3, [r6]
0xe1d640f0, // ldrsh r4, [r6]
0xeafffffe, // b .
};
for (u32 i = 0; i < code.size(); ++i)
Write32(i * 4, big_endian ? code[i] : Common::swap32(code[i]));
}
}
void InstallStores(bool thumb, bool big_endian)
{
if (thumb)
{
constexpr std::array<u16, 4> code = {
0x6030, // str r0, [r6]
0x7131, // strb r1, [r6, #4]
0x80f2, // strh r2, [r6, #6]
0xe7fe, // b .
};
for (u32 i = 0; i < code.size(); ++i)
Write16(i * 2, big_endian ? code[i] : Common::swap16(code[i]));
}
else
{
constexpr std::array<u32, 4> code = {
0xe5860000, // str r0, [r6]
0xe5c61004, // strb r1, [r6, #4]
0xe1c620b6, // strh r2, [r6, #6]
0xeafffffe, // b .
};
for (u32 i = 0; i < code.size(); ++i)
Write32(i * 4, big_endian ? code[i] : Common::swap32(code[i]));
}
}
StarletMemory memory;
std::array<u8, 0x8000> ram{};
u64 data_reads = 0;
};
class StarletSRAMRead : public testing::TestWithParam<bool>
{
protected:
void SetUp() override
{
Core::DeclareAsCPUThread();
Core::System::GetInstance().GetWiiIPC().Reset();
}
static void Prepare(ARMCore& core, bool thumb, bool big_endian, u32 address)
{
if (core.IsBigEndian() != big_endian)
core.SetBigEndian(big_endian);
core.SetCPSR(static_cast<u32>(ARMCore::Mode::Supervisor) | (thumb ? ARMCore::CPSR_T : 0));
for (u32 i = 0; i < 16; ++i)
core.SetRegister(i, 0);
core.SetRegister(6, address);
}
};
TEST_P(StarletSRAMRead, NewlyProfiledPagesAvoidDataBusCalls)
{
for (const bool thumb : {false, true})
{
for (const bool big_endian : {false, true})
{
auto bus = std::make_unique<SRAMReadBus>();
bus->SetMapping(true, false);
bus->InstallReads(thumb, big_endian);
ARMCore core(*bus, GetParam());
core.SetJitEnabled(true);
for (const u32 base : {0x0d400000u, 0xfff00000u, 0xfffe0000u})
{
for (const u32 page : {0x01u, 0x02u, 0x04u, 0x13u, 0x15u, 0x16u, 0x1au, 0x1cu, 0x1du})
{
const u32 address = base + page * 0x1000;
SCOPED_TRACE(testing::Message() << "thumb=" << thumb << " be=" << big_endian
<< " address=" << std::hex << address);
Prepare(core, thumb, big_endian, address);
bus->data_reads = 0;
ASSERT_EQ(core.RunCycles(6), 6u);
ASSERT_EQ(core.GetLastUndefinedInstruction(), 0u);
ASSERT_EQ(bus->data_reads, 0u);
EXPECT_EQ(core.GetRegister(0), big_endian ? bus->memory.Read32(address) :
Common::swap32(bus->memory.Read32(address)));
}
}
EXPECT_EQ(core.GetJitSlowReadCount(), 0u);
EXPECT_EQ(core.GetJitFallbackInstructionCount(), 0u);
EXPECT_EQ(core.GetJitCompiledBlockCount(), 1u);
}
}
}
TEST_P(StarletSRAMRead, SizedNativeStoresMatchInterpreterAcrossMappings)
{
for (const bool thumb : {false, true})
{
for (const bool big_endian : {false, true})
{
auto reference_bus = std::make_unique<SRAMReadBus>();
auto native_bus = std::make_unique<SRAMReadBus>();
reference_bus->InstallStores(thumb, big_endian);
native_bus->InstallStores(thumb, big_endian);
ARMCore reference(*reference_bus);
ARMCore native(*native_bus, GetParam());
native.SetJitEnabled(true);
for (const bool split : {false, true, false})
{
for (const bool boot0 : {false, true, false})
{
reference_bus->SetMapping(split, boot0);
native_bus->SetMapping(split, boot0);
for (const u32 base : {0x0d400000U, 0xfff00000U, 0xfffe0000U})
{
for (u32 page = 0; page < 32; ++page)
{
for (const u32 offset : {0U, 1U, 2U, 3U, 0xff8U, 0xffcU, 0xffeU, 0xfffU})
{
const u32 address = base + page * 0x1000 + offset;
if (address > 0xfffffff7U)
continue; // Do not wrap a test data store into synthetic guest code.
SCOPED_TRACE(testing::Message()
<< "thumb=" << thumb << " be=" << big_endian << " split=" << split
<< " boot0=" << boot0 << " address=" << std::hex << address);
for (ARMCore* core : {&reference, &native})
{
Prepare(*core, thumb, big_endian, address);
core->SetRegister(0, 0x12345678);
core->SetRegister(1, 0x9abcdef0);
core->SetRegister(2, 0x7e3dac12);
ASSERT_EQ(core->RunCycles(4), 4U);
ASSERT_EQ(core->GetLastUndefinedInstruction(), 0U);
}
for (u32 reg = 0; reg < 16; ++reg)
ASSERT_EQ(native.GetRegister(reg), reference.GetRegister(reg));
ASSERT_EQ(native.GetCPSR(), reference.GetCPSR());
ASSERT_TRUE(std::equal(reference_bus->memory.GetFastmemSRAMBase(),
reference_bus->memory.GetFastmemSRAMBase() + 0x18000,
native_bus->memory.GetFastmemSRAMBase()));
for (u32 byte = 0; byte < 8; ++byte)
ASSERT_EQ(native_bus->Read8(address + byte),
reference_bus->Read8(address + byte));
}
}
}
}
}
}
}
}
TEST_P(StarletSRAMRead, MatchesInterpreterAcrossLiveMappingsAliasesAndBoundaries)
{
for (const bool thumb : {false, true})
{
for (const bool big_endian : {false, true})
{
auto interpreter_bus = std::make_unique<SRAMReadBus>();
auto jit_bus = std::make_unique<SRAMReadBus>();
interpreter_bus->InstallReads(thumb, big_endian);
jit_bus->InstallReads(thumb, big_endian);
ARMCore interpreter(*interpreter_bus);
ARMCore jit(*jit_bus, GetParam());
jit.SetJitEnabled(true);
std::array<u8, 0x18000> original;
std::copy_n(jit_bus->GetFastmemSRAMBase(), original.size(), original.begin());
std::optional<u64> compiled_blocks;
// Toggle the hardware state while reusing the same compiled code: guards must consult
// live boot0/split latches, not their values at compilation time.
for (const bool split : {false, true, false})
{
for (const bool boot0 : {false, true, false})
{
interpreter_bus->SetMapping(split, boot0);
jit_bus->SetMapping(split, boot0);
for (const u32 base : {0x0d400000u, 0xfff00000u, 0xfffe0000u})
{
for (u32 page = 0; page < 32; ++page)
{
for (const u32 offset :
{0u, 1u, 2u, 3u, 0x3fdu, 0x3feu, 0x3ffu, 0xffcu, 0xffdu, 0xffeu, 0xfffu})
{
const u32 address = base + page * 0x1000 + offset;
if (address > 0xfffffffcu)
continue; // Exclude address-space wrap into the synthetic code buffer.
SCOPED_TRACE(testing::Message()
<< "thumb=" << thumb << " be=" << big_endian << " split=" << split
<< " boot0=" << boot0 << " address=" << std::hex << address);
Prepare(interpreter, thumb, big_endian, address);
Prepare(jit, thumb, big_endian, address);
ASSERT_EQ(interpreter.RunCycles(6), 6u);
ASSERT_EQ(jit.RunCycles(6), 6u);
ASSERT_EQ(jit.GetLastUndefinedInstruction(), 0u);
for (u32 reg = 0; reg < 16; ++reg)
ASSERT_EQ(jit.GetRegister(reg), interpreter.GetRegister(reg)) << "r" << reg;
ASSERT_EQ(jit.GetCPSR(), interpreter.GetCPSR());
}
}
}
// Unaligned fallbacks also compile continuations. Once the first boundary sweep has
// warmed them, changing the hardware mapping must reuse those blocks, not rebuild them.
if (!compiled_blocks)
compiled_blocks = jit.GetJitLifetimeCompiledBlockCount();
else
EXPECT_EQ(jit.GetJitLifetimeCompiledBlockCount(), *compiled_blocks);
}
}
EXPECT_TRUE(std::equal(original.begin(), original.end(), jit_bus->GetFastmemSRAMBase()));
EXPECT_TRUE(
std::equal(original.begin(), original.end(), interpreter_bus->GetFastmemSRAMBase()));
}
}
}
TEST_P(StarletSRAMRead, PreservedBlockUsesRemappedSRAMAfterGuestTLBInvalidation)
{
auto bus = std::make_unique<SRAMReadBus>();
bus->SetMapping(true, false);
bus->Write32(0, 0xe5960000); // ldr r0, [r6]
bus->Write32(4, 0xeafffffe); // b .
bus->Write32(0x40, 0xee080f17); // mcr p15, 0, r0, c8, c7, 0 (invalidate unified TLB)
bus->Write32(0x4000, 0x00000c02); // Identity section for code/page tables.
bus->Write32(0x4c00, 0x00005001); // VA 0x30000000 -> coarse page table at 0x5000.
bus->Write32(0x5000, 0x0d404ff2); // Small page -> SRAM B, aperture page 04.
bus->memory.Write32(0x0d404000, 0x12345678);
bus->memory.Write32(0xffff6000, 0x87654321);
ARMCore core(*bus, GetParam());
core.GetCP15State().translation_table_base = 0x4000;
core.GetCP15State().domain_access_control = 3;
core.GetCP15State().control |= 1;
core.SetRegister(6, 0x30000000);
core.SetJitEnabled(true);
ASSERT_EQ(core.RunCycles(2), 2u);
ASSERT_EQ(core.GetRegister(0), 0x12345678u);
const auto old_blocks = core.GetJitCompiledBlockCount();
bus->Write32(0x5000, 0xffff6ff2); // Remap to SRAM A, aperture page 16.
core.SetRegister(15, 0x40);
ASSERT_EQ(core.RunCycles(1), 1u);
core.SetRegister(15, 0);
ASSERT_EQ(core.RunCycles(2), 2u);
EXPECT_EQ(core.GetRegister(0), 0x87654321u);
EXPECT_EQ(core.GetJitCompiledBlockCount(), old_blocks + 1);
EXPECT_EQ(core.GetJitSlowReadCount(), 0u);
}
TEST_P(StarletSRAMRead, OptionalProfilingPreservesBusCountsResultsAndReset)
{
for (const bool thumb : {false, true})
{
for (const bool big_endian : {false, true})
{
for (const u32 address : {0xfff1f000U, 0x0d800214U})
{
auto bus = std::make_unique<SRAMReadBus>();
auto reference_bus = std::make_unique<SRAMReadBus>();
for (SRAMReadBus* target : {bus.get(), reference_bus.get()})
{
target->SetMapping(true, false);
target->memory.Write32(address, 0x89abcdef);
if (thumb)
{
target->Write16(0, big_endian ? 0x6830 : Common::swap16(0x6830)); // ldr r0,[r6]
target->Write16(2, big_endian ? 0x6030 : Common::swap16(0x6030)); // str r0,[r6]
target->Write16(4, big_endian ? 0xe7fc : Common::swap16(0xe7fc)); // b 0
}
else
{
target->Write32(0, big_endian ? 0xe5960000 : Common::swap32(0xe5960000));
target->Write32(4, big_endian ? 0xe5860000 : Common::swap32(0xe5860000));
target->Write32(8, big_endian ? 0xeafffffc : Common::swap32(0xeafffffc));
}
}
ARMCore core(*bus, GetParam());
ARMCore reference(*reference_bus);
EXPECT_FALSE(reference.IsJitMemoryProfilingEnabled());
core.SetJitEnabled(true);
// Recompile after reset and endian changes with the same host-only profiling choice.
for (int reset = 0; reset < 2; ++reset)
{
core.Reset();
reference.Reset();
EXPECT_EQ(core.IsJitMemoryProfilingEnabled(), GetParam());
const u64 reads_before = core.GetJitSlowReadCount();
const u64 writes_before = core.GetJitSlowWriteCount();
for (ARMCore* cpu : {&core, &reference})
{
Prepare(*cpu, thumb, big_endian, address);
ASSERT_EQ(cpu->RunCycles(768), 768U);
}
EXPECT_EQ(core.GetJitSlowReadCount() - reads_before, 256U);
EXPECT_EQ(core.GetJitSlowWriteCount() - writes_before, 256U);
for (u32 reg = 0; reg < 16; ++reg)
EXPECT_EQ(core.GetRegister(reg), reference.GetRegister(reg));
EXPECT_EQ(core.GetCPSR(), reference.GetCPSR());
EXPECT_EQ(bus->memory.Read32(address), reference_bus->memory.Read32(address));
EXPECT_EQ(bus->memory.Read32(address), 0x89abcdefU);
const auto samples = core.TakeHotJitSlowMemorySamples(8);
if (GetParam())
{
ASSERT_EQ(samples.size(), 2U);
for (const auto& [key, count] : samples)
{
EXPECT_EQ(static_cast<u32>(key), address);
EXPECT_EQ(count, 1U);
}
EXPECT_GT(address == 0xfff1f000 ? core.GetJitSlowSRAMAccessCount() :
core.GetJitSlowMMIOAccessCount(),
0U);
}
else
{
EXPECT_TRUE(samples.empty());
EXPECT_EQ(core.GetJitSlowSRAMAccessCount(), 0U);
EXPECT_EQ(core.GetJitSlowMMIOAccessCount(), 0U);
EXPECT_EQ(core.GetJitSlowSRAMPageAccessCount(0x1f), 0U);
}
}
}
}
}
}
INSTANTIATE_TEST_SUITE_P(MemoryProfiling, StarletSRAMRead, testing::Bool());
} // namespace
#endif
} // namespace IOS::LLE
@@ -0,0 +1,128 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <algorithm>
#include <array>
#include <iomanip>
#include <memory>
#include <optional>
#include <gtest/gtest.h>
#include "Core/Core.h"
#include "Core/HW/WII_IPC.h"
#include "Core/IOS/Starlet/StarletMemory.h"
#include "Core/System.h"
namespace IOS::LLE
{
namespace
{
// Deliberately branch-based reference, independent of the optimized aperture-bit swap.
std::optional<u32> MapSRAMByte(u32 address, bool split, bool boot0)
{
if (!(address >= 0x0d400000 && address < 0x0d420000) && address < 0xfff00000)
return std::nullopt;
const u32 window = address & 0x1ffff;
if (boot0 && address >= 0xfffe0000 && (split ? window < 0x10000 : window >= 0x10000))
return std::nullopt;
if (!split)
return window < 0x18000 ? std::optional(window) : std::nullopt;
if (window < 0x8000)
return 0x10000 + window;
if (window >= 0x10000)
return window - 0x10000;
return std::nullopt;
}
class StarletSRAMWrite : public testing::Test
{
protected:
void SetUp() override
{
Core::DeclareAsCPUThread();
Core::System::GetInstance().GetWiiIPC().Reset();
}
static void SetMapping(StarletMemory& memory, bool split, bool boot0)
{
memory.Write32(0x0d800060, split ? 0x20 : 0);
memory.Write32(0x0d80018c, boot0 ? 0 : 0x1000);
}
};
TEST_F(StarletSRAMWrite, EveryApertureByteMatchesIndependentMapping)
{
auto memory = std::make_unique<StarletMemory>(Core::System::GetInstance());
memory->Reset();
u8* const sram = memory->GetFastmemSRAMBase();
for (u32 i = 0; i < StarletMemory::SRAM_SIZE; ++i)
sram[i] = static_cast<u8>((i * 13) ^ (i >> 8) ^ 0xa5);
for (const bool split : {false, true})
{
for (const bool boot0 : {false, true})
{
SetMapping(*memory, split, boot0);
for (const u32 base : {0x0d400000u, 0xfff00000u, 0xfffe0000u})
{
for (u32 i = 0; i < 0x20000; ++i)
{
const u32 address = base + i;
const auto offset = MapSRAMByte(address, split, boot0);
// Reset leaves the synthetic boot ROM zero-filled. Holes also read zero.
ASSERT_EQ(memory->Read8(address), offset ? sram[*offset] : 0)
<< "address=" << std::hex << address << " split=" << split << " boot0=" << boot0;
}
}
}
}
}
TEST_F(StarletSRAMWrite, WideStoresMatchByteOracleAcrossLiveMappingsAndAllMirrors)
{
auto memory = std::make_unique<StarletMemory>(Core::System::GetInstance());
memory->Reset();
std::array<u8, StarletMemory::SRAM_SIZE> expected;
for (u32 i = 0; i < expected.size(); ++i)
expected[i] = static_cast<u8>((i * 13) ^ (i >> 8) ^ 0xa5);
std::copy(expected.begin(), expected.end(), memory->GetFastmemSRAMBase());
// Toggle back, too: no cached host pointer may survive changes to SM/boot0.
for (const bool split : {false, true, false})
{
for (const bool boot0 : {false, true, false})
{
SetMapping(*memory, split, boot0);
for (const u32 base : {0x0d400000u, 0xfff00000u, 0xfff20000u, 0xfff40000u, 0xfff60000u,
0xfff80000u, 0xfffa0000u, 0xfffc0000u, 0xfffe0000u})
{
for (u32 page = 0; page < 32; ++page)
{
for (const u32 in_page : {0u, 1u, 2u, 3u, 0xffcu, 0xffdu, 0xffeu, 0xfffu})
{
const u32 address = base + page * 0x1000 + in_page;
for (const u32 width : {2u, 4u})
{
if (address > 0xffffffffu - (width - 1))
continue; // Do not wrap into uninitialized MEM1.
const u32 value = (address * 0x12345u) ^ (width == 2 ? 0x89abcdefu : 0x76543210u);
for (u32 byte = 0; byte < width; ++byte)
{
if (const auto offset = MapSRAMByte(address + byte, split, boot0))
expected[*offset] = static_cast<u8>(value >> ((width - 1 - byte) * 8));
}
if (width == 2)
memory->Write16(address, static_cast<u16>(value));
else
memory->Write32(address, value);
ASSERT_TRUE(
std::equal(expected.begin(), expected.end(), memory->GetFastmemSRAMBase()))
<< "address=" << std::hex << address << " width=" << width << " split=" << split
<< " boot0=" << boot0;
}
}
}
}
}
}
}
} // namespace
} // namespace IOS::LLE
+157
View File
@@ -0,0 +1,157 @@
param(
[Parameter(Mandatory)][string]$CaptureDirectory,
[Parameter(Mandatory)][string]$OutputDirectory,
[string]$PythonExecutable,
[ValidateRange(0,2147483647)][int]$NativePID=0,
[string]$NativePDB,
[string]$XperfRangeStart,
[string]$XperfRangeEnd
)
# Read-only input: qualify a synthetic capture, or inspect one native Dolphin PID.
# Output is a new directory; no emulator, NAND or WPR session is touched.
$ErrorActionPreference = 'Stop'
if (($NativePID -eq 0) -ne (-not $NativePDB)) {
throw 'For native analysis pass both -NativePID and -NativePDB.'
}
if ([bool]$XperfRangeStart -ne [bool]$XperfRangeEnd) {
throw 'Pass both -XperfRangeStart and -XperfRangeEnd, or neither.'
}
if ($XperfRangeStart -and -not $NativePID) {
throw 'Time-window export is only supported for exploratory native analysis.'
}
if ($PythonExecutable) {
$p1Python = (Resolve-Path -LiteralPath $PythonExecutable).Path
} else {
$p1Candidates = @(Get-Command python.exe -All -ErrorAction SilentlyContinue |
Where-Object { $_.Source -notlike '*\WindowsApps\*' } |
Select-Object -ExpandProperty Source)
$p1Candidates += 'C:\msys64\mingw64\bin\python.exe'
foreach ($p1Candidate in $p1Candidates) {
if ($p1Candidate -and (Test-Path -LiteralPath $p1Candidate)) {
$p1Python = $p1Candidate
break
}
}
}
if (-not $p1Python) {
throw 'Python was not found before analysis. Pass -PythonExecutable with the path to a working python.exe.'
}
& $p1Python --version | Out-Null
if ($LASTEXITCODE) { throw "Python could not start: $p1Python" }
function ConvertTo-P1WindowsArgument([string]$Value) {
$p1Quoted = '"'
$p1Slashes = 0
foreach ($p1Char in $Value.ToCharArray()) {
if ($p1Char -eq '\') { ++$p1Slashes; continue }
if ($p1Char -eq '"') {
$p1Quoted += ('\' * (2 * $p1Slashes + 1)) + '"'
$p1Slashes = 0
continue
}
$p1Quoted += ('\' * $p1Slashes) + $p1Char
$p1Slashes = 0
}
return $p1Quoted + ('\' * (2 * $p1Slashes)) + '"'
}
$p1Repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
$p1Input = [IO.Path]::GetFullPath($(if ([IO.Path]::IsPathRooted($CaptureDirectory)) {
$CaptureDirectory
} else {
Join-Path (Get-Location).ProviderPath $CaptureDirectory
}))
$p1Output = [IO.Path]::GetFullPath($(if ([IO.Path]::IsPathRooted($OutputDirectory)) {
$OutputDirectory
} else {
Join-Path $p1Repo $OutputDirectory
}))
if (Test-Path -LiteralPath $p1Output) { throw 'Use a NEW analysis directory; no results are overwritten.' }
$p1ETL = Join-Path $p1Input 'capture.etl'
$p1ManifestPath = Join-Path $p1Input 'manifest.json'
$p1StdoutPath = Join-Path $p1Input 'probe.stdout.log'
$p1Decoder = Join-Path $p1Repo '.starlet-profile/P1-tools/DecodeP1.exe'
$p1RequiredInputs = @($p1ETL, $p1ManifestPath, $p1Decoder)
if ($NativePID) {
$NativePDB = (Resolve-Path -LiteralPath $NativePDB).Path
$p1RequiredInputs += $NativePDB
} else {
$p1RequiredInputs += $p1StdoutPath
}
foreach ($p1Required in $p1RequiredInputs) {
if (-not (Test-Path -LiteralPath $p1Required)) { throw "Missing analysis input: $p1Required" }
}
$p1Drive = [IO.DriveInfo]::new([IO.Path]::GetPathRoot($p1Output))
$p1RequiredFree = if ($NativePID) { 20GB } else { 7GB }
if ($p1Drive.AvailableFreeSpace -lt $p1RequiredFree) {
throw "Need at least $([math]::Round($p1RequiredFree / 1GB)) GiB free for offline analysis."
}
New-Item -ItemType Directory -Path $p1Output | Out-Null
Copy-Item -LiteralPath $p1ManifestPath -Destination $p1Output
if (-not $NativePID) { Copy-Item -LiteralPath $p1StdoutPath -Destination $p1Output }
$p1Manifest = Get-Content -LiteralPath $p1ManifestPath -Raw | ConvertFrom-Json
$p1TargetPID = if ($NativePID) { $NativePID } else { $p1Manifest.ProbePID }
if (-not $p1TargetPID) { throw 'Target PID missing from capture manifest.' }
$p1Native = Join-Path $p1Output 'native-events.jsonl'
$p1DecodeText = & $p1Decoder $p1ETL $p1Native
$p1DecodeExit = $LASTEXITCODE
$p1DecodeText | Out-File -LiteralPath (Join-Path $p1Output 'decoder-summary.json') -Encoding utf8
if ($p1DecodeExit) { throw 'TDH native decode or ETW loss check failed; see decoder-summary.json.' }
$p1Csv = Join-Path $p1Output 'xperf-symbols.csv'
$p1PriorSymbols = [Environment]::GetEnvironmentVariable('_NT_SYMBOL_PATH', 'Process')
$p1PriorCache = [Environment]::GetEnvironmentVariable('_NT_SYMCACHE_PATH', 'Process')
try {
$env:_NT_SYMBOL_PATH = if ($NativePID) { Split-Path $NativePDB -Parent } else {
Split-Path $p1Manifest.ProbePDB -Parent
}
$env:_NT_SYMCACHE_PATH = Join-Path $p1Output 'symcache'
$p1Info = [Diagnostics.ProcessStartInfo]::new((Get-Command xperf.exe).Source)
$p1Info.UseShellExecute = $false
$p1Info.CreateNoWindow = $true
$p1Info.RedirectStandardOutput = $true
$p1Info.RedirectStandardError = $true
$p1Info.WorkingDirectory = $p1Repo
$p1XperfArgs = @('-i', $p1ETL, '-o', $p1Csv, '-symbols', '-target',
'machine', '-quiet', '-a', 'dumper')
if ($XperfRangeStart) {
$p1XperfArgs += @('-range', $XperfRangeStart, $XperfRangeEnd)
[pscustomobject]@{ Start=$XperfRangeStart; End=$XperfRangeEnd;
Note='Xperf CPU samples are limited to this window; native scopes and counters span the full ETL.' } |
ConvertTo-Json | Out-File -LiteralPath (Join-Path $p1Output 'analysis-range.json') -Encoding utf8
}
$p1Info.Arguments = ($p1XperfArgs | ForEach-Object {
ConvertTo-P1WindowsArgument $_
}) -join ' '
$p1Process = [Diagnostics.Process]::Start($p1Info)
$p1Stdout = $p1Process.StandardOutput.ReadToEndAsync()
$p1Stderr = $p1Process.StandardError.ReadToEndAsync()
$p1TimeoutMs = if ($NativePID) { 900000 } else { 180000 }
if (-not $p1Process.WaitForExit($p1TimeoutMs)) {
$p1Process.Kill() # Only the xperf process created by this analysis script.
$p1Process.WaitForExit()
throw "Owned Xperf decoder exceeded $($p1TimeoutMs / 1000) seconds; no input ETL was modified."
}
$p1Stdout.GetAwaiter().GetResult() | Out-File `
-LiteralPath (Join-Path $p1Output 'xperf-stdout.log') -Encoding utf8
$p1Stderr.GetAwaiter().GetResult() | Out-File `
-LiteralPath (Join-Path $p1Output 'xperf-warnings.log') -Encoding utf8
if ($p1Process.ExitCode) { throw 'Xperf kernel decode failed; see xperf-warnings.log.' }
} finally {
[Environment]::SetEnvironmentVariable('_NT_SYMBOL_PATH', $p1PriorSymbols, 'Process')
[Environment]::SetEnvironmentVariable('_NT_SYMCACHE_PATH', $p1PriorCache, 'Process')
}
$p1Combined = Join-Path $p1Output 'combined.jsonl'
$p1XperfSummary = Join-Path $p1Output 'xperf-summary.json'
& $p1Python (Join-Path $PSScriptRoot 'xperf_to_p1.py') $p1Csv $p1Native `
--pid $p1TargetPID --output $p1Combined --summary $p1XperfSummary
if ($LASTEXITCODE) { throw 'Xperf/native clock alignment failed.' }
if ($NativePID) {
& $p1Python (Join-Path $PSScriptRoot 'analyze_p1.py') $p1Combined `
--pid $p1TargetPID --output (Join-Path $p1Output 'native-report.json')
if ($LASTEXITCODE) { throw 'Native offline analysis failed.' }
Write-Output "Exploratory native report: $p1Output\native-report.json (NOT qualified as a complete Wii-update bottleneck report)."
} else {
& $p1Python (Join-Path $PSScriptRoot 'qualify_p1.py') $p1Output `
--events $p1Combined --xperf-summary $p1XperfSummary
if ($LASTEXITCODE) { throw 'Local WPR qualification failed; see qualification.json.' }
Write-Output "Local WPR qualification finished: $p1Output\qualification.json"
}
+13
View File
@@ -0,0 +1,13 @@
param([Parameter(Mandatory)][string]$OutputDirectory)
$ErrorActionPreference='Stop'
$decoderOut=[IO.Path]::GetFullPath($(if([IO.Path]::IsPathRooted($OutputDirectory)){
$OutputDirectory
}else{
Join-Path (Get-Location).ProviderPath $OutputDirectory
}))
New-Item -ItemType Directory -Force -Path $decoderOut | Out-Null
$decoderSource=Join-Path $PSScriptRoot 'DecodeP1.cpp'
$decoderSetup='call "C:\Program Files\Microsoft Visual Studio\18\Community\Common7\Tools\VsDevCmd.bat" -arch=x64 -host_arch=x64 >nul'
$decoderCommand=$decoderSetup+' && cl /nologo /EHsc /O2 /std:c++20 /DUNICODE /D_UNICODE "'+$decoderSource+'" /Fo"'+(Join-Path $decoderOut 'DecodeP1.obj')+'" /Fe"'+(Join-Path $decoderOut 'DecodeP1.exe')+'" /link tdh.lib advapi32.lib'
cmd.exe /d /s /c $decoderCommand
if($LASTEXITCODE) { throw 'Decoder compilation failed' }
+48
View File
@@ -0,0 +1,48 @@
param([switch]$ConfigureOnly, [switch]$CleanBeforeBuild)
$ErrorActionPreference = 'Stop'
$p1Repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
$p1Build = Join-Path $p1Repo '.starlet_diag_p1'
$p1VS = 'C:\Program Files\Microsoft Visual Studio\18\Community'
$p1CMake = Join-Path $p1VS 'Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe'
$p1Ninja = Join-Path $p1VS 'Common7\IDE\CommonExtensions\Microsoft\CMake\Ninja\ninja.exe'
$p1Setup = 'set VSLANG=1033&& call "' + (Join-Path $p1VS 'Common7\Tools\VsDevCmd.bat') + '" -arch=x64 -host_arch=x64 >nul'
$p1Configure = $p1Setup + ' && "' + $p1CMake + '" -S "' + $p1Repo + '" -B "' + $p1Build + '" -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_MAKE_PROGRAM="' + $p1Ninja + '" -DENABLE_QT=OFF -DENABLE_NOGUI=ON -DENABLE_TESTS=ON -DENABLE_VULKAN=OFF -DENABLE_LTO=OFF -DENABLE_LLVM=OFF -DUSE_SYSTEM_LIBS=OFF'
cmd.exe /d /s /c $p1Configure
if ($LASTEXITCODE) { throw 'P1 configuration failed.' }
# CMake can decode French MSVC /showIncludes through the OEM code page even though
# cl prints UTF-8 nonbreaking spaces. Then Ninja silently records no header deps.
$p1PrefixFixed = $false
foreach ($p1Info in Get-ChildItem -LiteralPath (Join-Path $p1Build 'CMakeFiles') -Recurse -File -Filter 'CMake*Compiler.cmake') {
$p1Text = [IO.File]::ReadAllText($p1Info.FullName)
$p1Corrected = $p1Text.Replace('Remarque : inclusion du fichier : ',
'Remarque' + [char]0xa0 + ': inclusion du fichier' + [char]0xa0 + ': ')
if ($p1Corrected -cne $p1Text) {
[IO.File]::WriteAllText($p1Info.FullName, $p1Corrected, [Text.UTF8Encoding]::new($false))
$p1PrefixFixed = $true
}
}
if ($p1PrefixFixed) {
cmd.exe /d /s /c $p1Configure
if ($LASTEXITCODE) { throw 'P1 dependency prefix repair failed.' }
}
if ($ConfigureOnly) { return }
if ($CleanBeforeBuild -and [IO.Path]::GetFullPath($p1Build) -cne
[IO.Path]::GetFullPath((Join-Path $p1Repo '.starlet_diag_p1'))) {
throw 'Unexpected build target: refusing clean.'
}
$p1Clean = if ($CleanBeforeBuild) { ' --clean-first' } else { '' }
$p1Compile = $p1Setup + ' && "' + $p1CMake + '" --build "' + $p1Build + '"' + $p1Clean + ' --target dolphin-nogui tests TraceProbeP1 -j 6'
cmd.exe /d /s /c $p1Compile
if ($LASTEXITCODE) { throw 'P1 build failed.' }
$p1NetworkTarget = Join-Path $p1Build 'Binaries/Network'
if (-not (Test-Path -LiteralPath $p1NetworkTarget)) {
$p1NetworkSource = Join-Path $p1Repo '.starlet_msvc2/Binaries/Network'
if (-not (Test-Path -LiteralPath $p1NetworkSource)) {
throw 'Local libslirp runtime absent; the network probe cannot run.'
}
New-Item -ItemType Directory -Path $p1NetworkTarget | Out-Null
Get-ChildItem -LiteralPath $p1NetworkSource -File | Copy-Item -Destination $p1NetworkTarget
}
& $p1Ninja -C $p1Build -t deps 'Source/Core/Common/CMakeFiles/common.dir/PerformanceTrace.cpp.obj' |
Select-Object -First 8
@@ -0,0 +1,17 @@
param([Parameter(Mandatory)][string]$OutputDirectory)
# One-command, firmware-free WPR qualification. Run in an elevated PowerShell.
$ErrorActionPreference = 'Stop'
$p1Repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
$p1Out = [IO.Path]::GetFullPath($(if ([IO.Path]::IsPathRooted($OutputDirectory)) {
$OutputDirectory
} else {
Join-Path $p1Repo $OutputDirectory
}))
$p1Probe = Join-Path $p1Repo '.starlet_diag_p1/Binaries/Tests/TraceProbeP1.exe'
$p1Network = Join-Path $p1Repo '.starlet_diag_p1/Binaries/Network'
foreach ($p1Input in @($p1Probe, $p1Network)) {
if (-not (Test-Path -LiteralPath $p1Input)) { throw "Missing local probe dependency: $p1Input" }
}
& (Join-Path $PSScriptRoot 'Capture-P1.ps1') `
-OutputDirectory $p1Out -Seconds 60 -ProbeExecutable $p1Probe `
-ProbeArguments @((Join-Path $p1Out 'synthetic.journal'), $p1Network)
@@ -0,0 +1,58 @@
param(
[Parameter(Mandatory=$true)][ValidateSet('P1-trace-005','P1-trace-006')][string]$Name,
[Parameter(Mandatory=$true)][int]$DolphinProcessId,
[ValidateRange(2,60)][int]$IntervalSeconds=10,
[ValidateRange(1,120)][int]$MaxMinutes=60
)
# Low-overhead, read-only host progress samples for the paired native update.
# No debugger, ETW session, guest-memory reads, or emulator input is involved.
$ErrorActionPreference = 'Stop'
$p1Repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
$p1Root = Join-Path $p1Repo '.starlet_update_ab_20260913'
$p1Profile = Join-Path $p1Root $Name
$p1ExpectedExe = Join-Path $p1Root "build-$Name/Binaries/DolphinNoGUI.exe"
$p1Journal = Join-Path $p1Profile 'Starlet/0238188DE97894AE3AF93A92C4F238C0572731A7.nand-journal'
$p1Process = Get-Process -Id $DolphinProcessId -ErrorAction Stop
if ($p1Process.ProcessName -ne 'DolphinNoGUI') {
throw "Process $DolphinProcessId is not DolphinNoGUI."
}
# The restricted sampler cannot always read another process's executable path.
# Check it when available, and require the isolated journal to be live as well.
if ($p1Process.Path -and
-not $p1Process.Path.Equals($p1ExpectedExe, [StringComparison]::OrdinalIgnoreCase)) {
throw "Process $DolphinProcessId is not the frozen build for $Name."
}
if (-not (Test-Path -LiteralPath $p1Journal -PathType Leaf)) {
throw "Missing isolated NAND journal: $p1Journal"
}
$p1Started = $p1Process.StartTime
if ((Get-Item -LiteralPath $p1Journal).LastWriteTime -lt $p1Started) {
throw "The isolated journal has not been written by the current launch."
}
$p1Capture = Join-Path $p1Profile ('Capture/host-progress-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '.jsonl')
$p1Stream = [IO.File]::Open($p1Capture, [IO.FileMode]::CreateNew,
[IO.FileAccess]::Write, [IO.FileShare]::Read)
$p1Writer = [IO.StreamWriter]::new($p1Stream, [Text.UTF8Encoding]::new($false))
$p1Writer.AutoFlush = $true
$p1Clock = [Diagnostics.Stopwatch]::StartNew()
Write-Output "Capturing $Name (PID $DolphinProcessId) to $p1Capture"
try {
while ($p1Clock.Elapsed.TotalMinutes -lt $MaxMinutes) {
$p1Process = Get-Process -Id $DolphinProcessId -ErrorAction SilentlyContinue
if (-not $p1Process -or $p1Process.StartTime -ne $p1Started) { break }
$p1Process.Refresh()
[ordered]@{
UTC=[datetime]::UtcNow.ToString('o')
ElapsedSeconds=[math]::Round($p1Clock.Elapsed.TotalSeconds,3)
ProcessCPUSeconds=[math]::Round($p1Process.TotalProcessorTime.TotalSeconds,3)
JournalBytes=(Get-Item -LiteralPath $p1Journal).Length
PrivateMemoryBytes=$p1Process.PrivateMemorySize64
} | ConvertTo-Json -Compress | ForEach-Object { $p1Writer.WriteLine($_) }
Start-Sleep -Seconds $IntervalSeconds
}
$p1Writer.WriteLine(('CAPTURE_END_UTC=' + [datetime]::UtcNow.ToString('o')))
} finally {
$p1Writer.Dispose()
}
Write-Output "Saved $p1Capture"
+144
View File
@@ -0,0 +1,144 @@
param(
[Parameter(Mandatory)][string]$OutputDirectory,
[ValidateRange(5,900)][int]$Seconds=60,
[string]$ProbeExecutable,
[string[]]$ProbeArguments=@(),
[ValidateRange(0,9223372036854775807)][long]$ProbeAffinityMask=0
)
# Runs an owned, uniquely named ETW session. Does not launch or stop Dolphin.
# Native use requires a separately launched, frozen diagnostic build and manifest.
$ErrorActionPreference = 'Stop'
function ConvertTo-P1WindowsArgument([string]$Value) {
# Windows PowerShell 5.1 uses .NET Framework, where ProcessStartInfo has no
# ArgumentList. Quote paths using the standard Windows argv backslash rules.
$p1Quoted = '"'
$p1Slashes = 0
foreach ($p1Char in $Value.ToCharArray()) {
if ($p1Char -eq '\') { ++$p1Slashes; continue }
if ($p1Char -eq '"') {
$p1Quoted += ('\' * (2 * $p1Slashes + 1)) + '"'
$p1Slashes = 0
continue
}
$p1Quoted += ('\' * $p1Slashes) + $p1Char
$p1Slashes = 0
}
return $p1Quoted + ('\' * (2 * $p1Slashes)) + '"'
}
$p1Out = [IO.Path]::GetFullPath($(if ([IO.Path]::IsPathRooted($OutputDirectory)) {
$OutputDirectory
} else {
Join-Path (Get-Location).ProviderPath $OutputDirectory
}))
if (Test-Path -LiteralPath $p1Out) { throw 'Use a NEW capture directory; results are never overwritten.' }
if ($ProbeExecutable) {
$ProbeExecutable = (Resolve-Path -LiteralPath $ProbeExecutable).Path
if ([IO.Path]::GetFileName($ProbeExecutable) -ne 'TraceProbeP1.exe') {
throw 'Automatic launch is restricted to the local qualification probe, not Dolphin.'
}
}
if ($ProbeAffinityMask -ne 0) {
$p1Allowed = [Diagnostics.Process]::GetCurrentProcess().ProcessorAffinity.ToInt64()
if (($ProbeAffinityMask -band $p1Allowed) -ne $ProbeAffinityMask) {
throw "Probe affinity mask $ProbeAffinityMask is not available to this process."
}
}
$p1Drive = [IO.DriveInfo]::new([IO.Path]::GetPathRoot($p1Out))
if ($p1Drive.AvailableFreeSpace -lt 9GB) { throw 'Need 4 GiB trace budget plus 5 GiB reserve.' }
New-Item -ItemType Directory -Path $p1Out | Out-Null
$p1Name = 'DolphinP1-' + [guid]::NewGuid().ToString('N')
$p1Temp = Join-Path (Split-Path $p1Out -Parent) ($p1Name + '-temporary-etl')
New-Item -ItemType Directory -Path $p1Temp | Out-Null
$p1Profile = Join-Path $PSScriptRoot 'DolphinP1.wprp'
$p1ETL = Join-Path $p1Out 'capture.etl'
$p1PDB = if ($ProbeExecutable) {
Join-Path (Split-Path (Split-Path (Split-Path $ProbeExecutable -Parent) -Parent) -Parent) 'pdb/TraceProbeP1.pdb'
} else { $null }
$p1Started = $false
$p1Reason = 'duration'
$p1Probe = $null
$p1Stdout = $null
$p1Stderr = $null
$p1Manifest = [ordered]@{
Schema=1; Collection='WPRSystemAndNative'; Session=$p1Name
StartUTC=[datetime]::UtcNow.ToString('o')
Seconds=$Seconds; TemporaryTraceDirectory=$p1Temp
Profile=$p1Profile; ProfileSHA256=(Get-FileHash -LiteralPath $p1Profile).Hash
Probe=$ProbeExecutable; ProbeSHA256=$(if ($ProbeExecutable) { (Get-FileHash -LiteralPath $ProbeExecutable).Hash } else { $null })
ProbeAffinityMask=$ProbeAffinityMask
ProbePDB=$p1PDB; ProbePDBSHA256=$(if ($p1PDB -and (Test-Path -LiteralPath $p1PDB)) { (Get-FileHash -LiteralPath $p1PDB).Hash } else { $null })
NativeQualificationPassed=$false
}
$p1Manifest | ConvertTo-Json -Depth 5 | Out-File -LiteralPath (Join-Path $p1Out 'manifest.json') -Encoding utf8
try {
& wpr.exe -start ($p1Profile + '!DolphinP1') -filemode -recordtempto $p1Temp -instancename $p1Name *> (Join-Path $p1Out 'start.log')
if ($LASTEXITCODE) { throw "ETW start failed; see $p1Out\start.log. No other session was stopped." }
$p1Started = $true
if (-not $ProbeExecutable) {
Write-Output "Native collector armed for $Seconds seconds: $p1Name. Launch Dolphin separately with -PerformanceTrace now."
}
if ($ProbeExecutable) {
# Environment of this child only; never persistently modify the user's environment.
$p1Info = [Diagnostics.ProcessStartInfo]::new($ProbeExecutable)
$p1Info.UseShellExecute = $false
$p1Info.CreateNoWindow = $true
$p1Info.RedirectStandardOutput = $true
$p1Info.RedirectStandardError = $true
$p1Info.Environment['DOLPHIN_PERF_TRACE'] = '1'
if ($p1Info.PSObject.Properties['ArgumentList'] -and $p1Info.ArgumentList) {
foreach ($p1Arg in $ProbeArguments) { $p1Info.ArgumentList.Add($p1Arg) }
} else {
$p1Info.Arguments = ($ProbeArguments | ForEach-Object {
ConvertTo-P1WindowsArgument $_
}) -join ' '
}
$p1Probe = [Diagnostics.Process]::Start($p1Info)
if ($ProbeAffinityMask -ne 0) {
try {
$p1Probe.ProcessorAffinity = [IntPtr]$ProbeAffinityMask
} catch {
$p1Probe.Kill() # Only the synthetic probe started by this script.
$p1Probe.WaitForExit()
throw "Could not pin owned synthetic probe to mask ${ProbeAffinityMask}: $_"
}
}
$p1Manifest.ProbeObservedAffinityMask = $p1Probe.ProcessorAffinity.ToInt64()
$p1Stdout = $p1Probe.StandardOutput.ReadToEndAsync()
$p1Stderr = $p1Probe.StandardError.ReadToEndAsync()
$p1Manifest.ProbePID = $p1Probe.Id
$p1Manifest.ProbeStartUTC = $p1Probe.StartTime.ToUniversalTime().ToString('o')
}
$p1Clock = [Diagnostics.Stopwatch]::StartNew()
while ($p1Clock.Elapsed.TotalSeconds -lt $Seconds) {
Start-Sleep -Milliseconds 1000
$p1Bytes = (Get-ChildItem -LiteralPath $p1Temp -File -Recurse | Measure-Object Length -Sum).Sum
if ($p1Drive.AvailableFreeSpace -lt 5GB -or $p1Bytes -gt 4GB) { $p1Reason='storage-budget'; break }
if ($p1Probe -and $p1Probe.HasExited) { $p1Reason='probe-exit'; break }
}
} finally {
if ($p1Started) {
& wpr.exe -status collectors -details -instancename $p1Name *> (Join-Path $p1Out 'collector-status.log')
& wpr.exe -stop $p1ETL -instancename $p1Name *> (Join-Path $p1Out 'stop.log')
$p1StopExit = $LASTEXITCODE
$p1Manifest.EndUTC = [datetime]::UtcNow.ToString('o')
$p1Manifest.StopReason = $p1Reason
$p1Manifest.StopExitCode = $p1StopExit
$p1Manifest.ProbeExitCode = if ($p1Probe -and $p1Probe.HasExited) { $p1Probe.ExitCode } else { $null }
if ($p1Probe -and $p1Probe.HasExited) {
$p1Stdout.GetAwaiter().GetResult() | Out-File -LiteralPath (Join-Path $p1Out 'probe.stdout.log') -Encoding utf8
$p1Stderr.GetAwaiter().GetResult() | Out-File -LiteralPath (Join-Path $p1Out 'probe.stderr.log') -Encoding utf8
$p1Manifest.ProbeCPUSeconds = $p1Probe.TotalProcessorTime.TotalSeconds
$p1Manifest.ProbeWallSeconds = ($p1Probe.ExitTime - $p1Probe.StartTime).TotalSeconds
}
$p1Manifest | ConvertTo-Json -Depth 5 | Out-File -LiteralPath (Join-Path $p1Out 'manifest.json') -Encoding utf8
if ($p1StopExit) { throw 'Owned ETW session could not be saved. See stop.log; no broad cancel attempted.' }
}
}
if (-not (Test-Path -LiteralPath $p1ETL)) { throw 'WPR reported success but produced no capture.etl.' }
if ($p1Probe -and -not $p1Probe.HasExited) {
throw "Capture stopped at $p1Reason, but the owned local probe is still running (PID $($p1Probe.Id)). No process was forcibly stopped."
}
if ($p1Probe -and $p1Probe.ExitCode -ne 0) {
throw "Local probe failed with exit code $($p1Probe.ExitCode); see probe.stderr.log. The ETL was kept."
}
Write-Output "Saved $p1ETL. Qualification is NOT automatically passed; inspect losses, attribution and overhead."
@@ -0,0 +1,106 @@
param(
[Parameter(Mandatory)][string]$OutputDirectory,
[ValidateRange(30,300)][int]$TimeoutSeconds=120,
[ValidateRange(0,9223372036854775807)][long]$ProbeAffinityMask=0,
[switch]$NoTrace
)
# Synthetic user-mode ETW qualification. This does not sample CPU or scheduling.
$ErrorActionPreference='Stop'
function ConvertTo-P1WindowsArgument([string]$Value) {
$p1Quoted = '"'
$p1Slashes = 0
foreach ($p1Char in $Value.ToCharArray()) {
if ($p1Char -eq '\') { ++$p1Slashes; continue }
if ($p1Char -eq '"') {
$p1Quoted += ('\' * (2 * $p1Slashes + 1)) + '"'
$p1Slashes = 0
continue
}
$p1Quoted += ('\' * $p1Slashes) + $p1Char
$p1Slashes = 0
}
return $p1Quoted + ('\' * (2 * $p1Slashes)) + '"'
}
$p1Repo=[IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
if ($ProbeAffinityMask -ne 0) {
$p1Allowed = [Diagnostics.Process]::GetCurrentProcess().ProcessorAffinity.ToInt64()
if (($ProbeAffinityMask -band $p1Allowed) -ne $ProbeAffinityMask) {
throw "Probe affinity mask $ProbeAffinityMask is not available to this process."
}
}
$p1Output=[IO.Path]::GetFullPath($(if([IO.Path]::IsPathRooted($OutputDirectory)){
$OutputDirectory
}else{
Join-Path (Get-Location).ProviderPath $OutputDirectory
}))
$p1Probe=Join-Path $p1Repo '.starlet_diag_p1/Binaries/Tests/TraceProbeP1.exe'
$p1PDB=Join-Path $p1Repo '.starlet_diag_p1/pdb/TraceProbeP1.pdb'
$p1Network=Join-Path $p1Repo '.starlet_diag_p1/Binaries/Network'
$p1Decoder=Join-Path $p1Repo '.starlet-profile/P1-tools/DecodeP1.exe'
foreach($p1Input in @($p1Probe,$p1PDB,$p1Network,$p1Decoder)) {
if(-not (Test-Path -LiteralPath $p1Input)) { throw "Missing local qualification dependency: $p1Input" }
}
if(Test-Path -LiteralPath $p1Output) { throw 'Use a NEW directory; trace evidence is never overwritten.' }
New-Item -ItemType Directory -Path $p1Output | Out-Null
$p1Journal=Join-Path $p1Output 'synthetic.journal'
$p1ETL=Join-Path $p1Output 'native.etl'
$p1Events=Join-Path $p1Output 'events.jsonl'
$p1Info=[Diagnostics.ProcessStartInfo]::new($p1Probe)
$p1Info.UseShellExecute=$false
$p1Info.CreateNoWindow=$true
$p1Info.RedirectStandardOutput=$true
$p1Info.RedirectStandardError=$true
$p1Info.WorkingDirectory=$p1Repo
if($NoTrace) { $p1Info.Environment.Remove('DOLPHIN_PERF_TRACE') | Out-Null }
else { $p1Info.Environment['DOLPHIN_PERF_TRACE']='1' }
$p1Arguments=if($NoTrace) { @($p1Journal,$p1Network) } else { @($p1Journal,$p1Network,$p1ETL) }
if($p1Info.PSObject.Properties['ArgumentList'] -and $p1Info.ArgumentList) {
foreach($p1Arg in $p1Arguments) { $p1Info.ArgumentList.Add($p1Arg) }
} else {
$p1Info.Arguments=($p1Arguments | ForEach-Object {
ConvertTo-P1WindowsArgument $_
}) -join ' '
}
$p1Process=[Diagnostics.Process]::Start($p1Info)
if ($ProbeAffinityMask -ne 0) {
try {
$p1Process.ProcessorAffinity = [IntPtr]$ProbeAffinityMask
} catch {
$p1Process.Kill() # Only the synthetic probe started by this script.
$p1Process.WaitForExit()
throw "Could not pin owned synthetic probe to mask ${ProbeAffinityMask}: $_"
}
}
$p1ObservedAffinity = $p1Process.ProcessorAffinity.ToInt64()
$p1Stdout=$p1Process.StandardOutput.ReadToEndAsync()
$p1Stderr=$p1Process.StandardError.ReadToEndAsync()
if(-not $p1Process.WaitForExit($TimeoutSeconds*1000)) {
throw "Local probe exceeded $TimeoutSeconds seconds. Its PID is $($p1Process.Id); no process was forcibly stopped."
}
$p1Stdout.GetAwaiter().GetResult() | Out-File -LiteralPath (Join-Path $p1Output 'probe.stdout.log') -Encoding utf8
$p1Stderr.GetAwaiter().GetResult() | Out-File -LiteralPath (Join-Path $p1Output 'probe.stderr.log') -Encoding utf8
$p1Manifest=[ordered]@{
Schema=1; Collection=$(if($NoTrace){'NoTrace'}else{'PrivateUserMode'}); Probe=$p1Probe
ProbeSHA256=(Get-FileHash -LiteralPath $p1Probe).Hash
ProbePDB=$p1PDB; ProbePDBSHA256=(Get-FileHash -LiteralPath $p1PDB).Hash
ProbePID=$p1Process.Id; ProbeExitCode=$p1Process.ExitCode
ProbeAffinityMask=$ProbeAffinityMask; ProbeObservedAffinityMask=$p1ObservedAffinity
ProbeStartUTC=$p1Process.StartTime.ToUniversalTime().ToString('o')
ProbeEndUTC=$p1Process.ExitTime.ToUniversalTime().ToString('o')
ProbeWallSeconds=($p1Process.ExitTime-$p1Process.StartTime).TotalSeconds
ProbeCPUSeconds=$p1Process.TotalProcessorTime.TotalSeconds
NativeQualificationPassed=$false
}
$p1Manifest | ConvertTo-Json -Depth 5 | Out-File -LiteralPath (Join-Path $p1Output 'manifest.json') -Encoding utf8
if($p1Process.ExitCode -ne 0) { throw 'Local probe failed; see probe.stderr.log.' }
if($NoTrace) {
Write-Output "No-trace fixed-work baseline completed: $p1Output"
return
}
if(-not (Test-Path -LiteralPath $p1ETL)) { throw 'Local probe produced no ETL.' }
$p1DecodeText=& $p1Decoder $p1ETL $p1Events
$p1DecodeExit=$LASTEXITCODE
$p1DecodeText | Out-File -LiteralPath (Join-Path $p1Output 'decoder-summary.json') -Encoding utf8
if($p1DecodeExit) { throw 'ETL decode/loss check failed; see decoder-summary.json.' }
Write-Output "Private user-mode trace decoded: $p1Output"
Write-Output 'This capture has no CPU samples, context switches or disk wait events.'
+204
View File
@@ -0,0 +1,204 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
// Offline ETL decoder. No process attach, memory read or thread suspension.
#define NOMINMAX
#include <windows.h>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <evntrace.h>
#include <map>
#include <memory>
#include <string>
#include <tdh.h>
#include <vector>
static constexpr GUID NATIVE = {
0x54ee9231, 0x28be, 0x4ab0, {0x98, 0x1e, 0xb2, 0x6f, 0x97, 0x9c, 0x56, 0xa4}};
static FILE* output;
static unsigned long long decoded = 0, errors = 0, total = 0;
static std::map<std::string, std::vector<unsigned char>> schemas;
static bool inspect_system = false;
static unsigned inspected_schemas = 0, failed_schemas = 0;
static std::string UTF8(const wchar_t* value)
{
if (!value || !*value)
return {};
int n = WideCharToMultiByte(CP_UTF8, 0, value, -1, nullptr, 0, nullptr, nullptr);
std::string text(n, '\0');
WideCharToMultiByte(CP_UTF8, 0, value, -1, text.data(), n, nullptr, nullptr);
text.pop_back();
return text;
}
static std::string Quote(const std::string& value)
{
std::string result = "\"";
for (unsigned char c : value)
{
if (c == '"' || c == '\\')
{
result += '\\';
result += c;
}
else if (c < 32)
{
char escaped[7];
std::snprintf(escaped, sizeof(escaped), "\\u%04x", c);
result += escaped;
}
else
result += c;
}
return result + '"';
}
static void WINAPI Event(PEVENT_RECORD record)
{
++total;
const bool native = IsEqualGUID(record->EventHeader.ProviderId, NATIVE);
std::string key(reinterpret_cast<const char*>(&record->EventHeader.ProviderId), sizeof(GUID));
key.append(reinterpret_cast<const char*>(&record->EventHeader.EventDescriptor),
sizeof(EVENT_DESCRIPTOR));
auto& buffer = schemas[key];
const bool first_schema = buffer.empty();
if (native || buffer.empty())
{
ULONG bytes = 0;
const ULONG status = TdhGetEventInformation(record, 0, nullptr, nullptr, &bytes);
if (status != ERROR_INSUFFICIENT_BUFFER)
{
if (native)
++errors;
else if (inspect_system && failed_schemas++ < 20)
std::fprintf(stderr, "TDH missing: event=%u opcode=%u status=%lu\n",
record->EventHeader.EventDescriptor.Id,
record->EventHeader.EventDescriptor.Opcode, status);
return;
}
buffer.resize(bytes);
if (TdhGetEventInformation(record, 0, nullptr,
reinterpret_cast<PTRACE_EVENT_INFO>(buffer.data()),
&bytes) != ERROR_SUCCESS)
{
if (native)
++errors;
buffer.clear();
return;
}
}
auto* info = reinterpret_cast<PTRACE_EVENT_INFO>(buffer.data());
const auto text = [&](ULONG offset) -> std::string {
return offset ? UTF8(reinterpret_cast<wchar_t*>(buffer.data() + offset)) : "";
};
std::string name = text(info->EventNameOffset);
if (name.empty())
name = text(info->TaskNameOffset) + "/" + text(info->OpcodeNameOffset);
if (inspect_system && !native && first_schema && inspected_schemas++ < 300)
{
std::fprintf(stderr, "SCHEMA event=%u opcode=%u name=%s fields=",
record->EventHeader.EventDescriptor.Id,
record->EventHeader.EventDescriptor.Opcode, name.c_str());
for (ULONG i = 0; i < info->TopLevelPropertyCount && i < 30; ++i)
std::fprintf(stderr, "%s%s", i ? "," : "", text(info->EventPropertyInfoArray[i].NameOffset).c_str());
std::fprintf(stderr, "\n");
}
bool interesting = native;
// Keep scheduling and instruction pointer records for independent qualification.
for (ULONG i = 0; i < info->TopLevelPropertyCount; ++i)
{
const auto field = text(info->EventPropertyInfoArray[i].NameOffset);
if (field == "InstructionPointer" || field == "OldThreadId" || field == "TThreadId")
interesting = true;
}
if (!interesting)
return;
std::string fields;
for (ULONG i = 0; i < info->TopLevelPropertyCount; ++i)
{
const auto& property = info->EventPropertyInfoArray[i];
if (property.Flags & PropertyStruct)
continue;
const auto field = text(property.NameOffset);
PROPERTY_DATA_DESCRIPTOR descriptor{};
descriptor.PropertyName = reinterpret_cast<ULONGLONG>(buffer.data() + property.NameOffset);
descriptor.ArrayIndex = ULONG_MAX;
ULONG size = 0;
if (TdhGetPropertySize(record, 0, nullptr, 1, &descriptor, &size) != ERROR_SUCCESS ||
size > 65536)
{
if (native)
++errors;
continue;
}
std::vector<unsigned char> bytes(size + 2, 0);
if (TdhGetProperty(record, 0, nullptr, 1, &descriptor, size, bytes.data()) != ERROR_SUCCESS)
{
if (native)
++errors;
continue;
}
std::string value;
const auto type = property.nonStructType.InType;
if (type == TDH_INTYPE_UNICODESTRING)
value = Quote(UTF8(reinterpret_cast<wchar_t*>(bytes.data())));
else if (type == TDH_INTYPE_ANSISTRING)
value = Quote(reinterpret_cast<char*>(bytes.data()));
else if (size == 1 || size == 2 || size == 4 || size == 8)
{
unsigned long long number = 0;
std::memcpy(&number, bytes.data(), size);
value = std::to_string(number);
}
else
{
if (native)
++errors;
continue;
}
if (!fields.empty())
fields += ',';
fields += Quote(field) + ':' + value;
}
std::fprintf(output,
"{\"native\":%s,\"event\":%s,\"qpc\":%lld,\"pid\":%lu,\"tid\":%lu,\"cpu\":%u,"
"\"opcode\":%u,\"data\":{%s}}\n",
native ? "true" : "false", Quote(name).c_str(),
record->EventHeader.TimeStamp.QuadPart, record->EventHeader.ProcessId,
record->EventHeader.ThreadId, record->BufferContext.ProcessorNumber,
record->EventHeader.EventDescriptor.Opcode, fields.c_str());
++decoded;
}
int wmain(int argc, wchar_t** argv)
{
if (argc != 3 && (argc != 4 || std::wcscmp(argv[3], L"--inspect-system") != 0))
{
std::fprintf(stderr, "DecodeP1 input.etl NEW-output.jsonl [--inspect-system]\n");
return 2;
}
inspect_system = argc == 4;
if (GetFileAttributesW(argv[2]) != INVALID_FILE_ATTRIBUTES)
{
std::fprintf(stderr, "Refusing overwrite\n");
return 2;
}
if (_wfopen_s(&output, argv[2], L"wb"))
return 2;
EVENT_TRACE_LOGFILEW logfile{};
logfile.LogFileName = argv[1];
logfile.ProcessTraceMode = PROCESS_TRACE_MODE_EVENT_RECORD | PROCESS_TRACE_MODE_RAW_TIMESTAMP;
logfile.EventRecordCallback = Event;
TRACEHANDLE trace = OpenTraceW(&logfile);
if (trace == INVALID_PROCESSTRACE_HANDLE)
{
std::fclose(output);
return 3;
}
const ULONG result = ProcessTrace(&trace, 1, nullptr, nullptr);
CloseTrace(trace);
std::fclose(output);
std::printf("{\"status\":%lu,\"total\":%llu,\"decoded\":%llu,\"native_decode_errors\":%llu,"
"\"events_lost\":%lu,\"buffers_lost\":%lu,\"qpc_frequency\":%lld}\n",
result, total, decoded, errors, logfile.LogfileHeader.EventsLost,
logfile.LogfileHeader.BuffersLost, logfile.LogfileHeader.PerfFreq.QuadPart);
return result != ERROR_SUCCESS || errors != 0 || logfile.LogfileHeader.EventsLost != 0 ||
logfile.LogfileHeader.BuffersLost != 0;
}
+42
View File
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<WindowsPerformanceRecorder Version="1.0" Author="Dolphin" Company="Dolphin">
<Profiles>
<SystemCollector Id="P1Kernel" Name="DolphinP1Kernel">
<BufferSize Value="256"/>
<Buffers Value="128"/>
</SystemCollector>
<EventCollector Id="P1Events" Name="DolphinP1Events">
<BufferSize Value="128"/>
<Buffers Value="64"/>
</EventCollector>
<SystemProvider Id="P1System">
<Keywords>
<Keyword Value="ProcessThread"/>
<Keyword Value="Loader"/>
<Keyword Value="SampledProfile"/>
<Keyword Value="CSwitch"/>
<Keyword Value="ReadyThread"/>
<Keyword Value="DiskIO"/>
<Keyword Value="DiskIOInit"/>
<Keyword Value="FileIO"/>
<Keyword Value="FileIOInit"/>
<Keyword Value="Filename"/>
<Keyword Value="HardFaults"/>
<Keyword Value="CpuConfig"/>
<Keyword Value="Power"/>
<Keyword Value="NetworkTrace"/>
</Keywords>
<Stacks>
<Stack Value="SampledProfile"/>
<Stack Value="CSwitch"/>
</Stacks>
</SystemProvider>
<EventProvider Id="P1Native" Name="54ee9231-28be-4ab0-981e-b26f979c56a4" Level="5"/>
<Profile Id="DolphinP1.Verbose.File" Name="DolphinP1" Description="CPU, scheduling, file IO and versioned Dolphin diagnostic events" LoggingMode="File" DetailLevel="Verbose">
<Collectors>
<SystemCollectorId Value="P1Kernel"><SystemProviderId Value="P1System"/></SystemCollectorId>
<EventCollectorId Value="P1Events"><EventProviders><EventProviderId Value="P1Native"/></EventProviders></EventCollectorId>
</Collectors>
</Profile>
</Profiles>
</WindowsPerformanceRecorder>
@@ -0,0 +1,79 @@
param(
[Parameter(Mandatory)][string]$OutputDirectory,
[ValidateRange(4,8)][int]$Pairs = 4,
[string]$PythonExecutable,
[ValidateRange(0,9223372036854775807)][long]$ProbeAffinityMask = 0,
[switch]$AnalyzeOnly
)
# One controlled batch of OFF/WPR-ON fixed-work synthetic runs; no Wii/NAND.
# WPR requires an elevated PowerShell. Every run gets a unique directory.
$ErrorActionPreference = 'Stop'
$p1Repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
$p1Root = [IO.Path]::GetFullPath($(if ([IO.Path]::IsPathRooted($OutputDirectory)) {
$OutputDirectory
} else {
Join-Path $p1Repo $OutputDirectory
}))
if ($PythonExecutable) {
$p1Python = (Resolve-Path -LiteralPath $PythonExecutable).Path
} else {
$p1Candidates = @(Get-Command python.exe -All -ErrorAction SilentlyContinue |
Where-Object { $_.Source -notlike '*\WindowsApps\*' } |
Select-Object -ExpandProperty Source)
$p1Candidates += 'C:\msys64\mingw64\bin\python.exe'
foreach ($p1Candidate in $p1Candidates) {
if ($p1Candidate -and (Test-Path -LiteralPath $p1Candidate)) {
$p1Python = $p1Candidate
break
}
}
}
if (-not $p1Python) {
throw 'Python was not found before capture. Pass -PythonExecutable with the path to a working python.exe.'
}
& $p1Python --version | Out-Null
if ($LASTEXITCODE) { throw "Python could not start: $p1Python" }
$p1AlreadyExists = Test-Path -LiteralPath $p1Root
if ($AnalyzeOnly -and -not $p1AlreadyExists) { throw "Existing batch not found: $p1Root" }
if (-not $AnalyzeOnly -and $p1AlreadyExists) {
throw 'Use a NEW batch directory for capture. Pass -AnalyzeOnly to compare existing captures.'
}
$p1Probe = Join-Path $p1Repo '.starlet_diag_p1/Binaries/Tests/TraceProbeP1.exe'
$p1Network = Join-Path $p1Repo '.starlet_diag_p1/Binaries/Network'
$p1Decoder = Join-Path $p1Repo '.starlet-profile/P1-tools/DecodeP1.exe'
if (-not $AnalyzeOnly) {
foreach ($p1Required in @($p1Probe, $p1Network, $p1Decoder)) {
if (-not (Test-Path -LiteralPath $p1Required)) { throw "Missing dependency: $p1Required" }
}
$p1Drive = [IO.DriveInfo]::new([IO.Path]::GetPathRoot($p1Root))
if ($p1Drive.AvailableFreeSpace -lt 9GB) { throw 'Need 4 GiB batch budget plus 5 GiB reserve.' }
New-Item -ItemType Directory -Path $p1Root | Out-Null
}
$p1Runs = @()
for ($p1Index = 1; $p1Index -le $Pairs; ++$p1Index) {
$p1Off = Join-Path $p1Root "off-$p1Index"
$p1On = Join-Path $p1Root "wpr-on-$p1Index"
if (-not $AnalyzeOnly) {
Write-Output "Pair $p1Index/${Pairs}: fixed-work OFF"
& (Join-Path $PSScriptRoot 'Capture-Private-P1.ps1') -OutputDirectory $p1Off -NoTrace `
-ProbeAffinityMask $ProbeAffinityMask
Write-Output "Pair $p1Index/${Pairs}: fixed-work WPR ON"
& (Join-Path $PSScriptRoot 'Capture-P1.ps1') -OutputDirectory $p1On -Seconds 60 `
-ProbeExecutable $p1Probe `
-ProbeArguments @((Join-Path $p1On 'synthetic.journal'), $p1Network) `
-ProbeAffinityMask $ProbeAffinityMask
$p1Decoded = & $p1Decoder (Join-Path $p1On 'capture.etl') `
(Join-Path $p1On 'native-events.jsonl')
$p1DecodeExit = $LASTEXITCODE
$p1Decoded | Out-File -LiteralPath (Join-Path $p1On 'decoder-summary.json') -Encoding utf8
if ($p1DecodeExit) { throw "Pair $p1Index has ETW loss or native decode errors." }
}
$p1Runs += $p1Off, $p1On
}
$p1Comparison = Join-Path $p1Root 'comparison.json'
if (Test-Path -LiteralPath $p1Comparison) {
throw "Comparison already exists and will not be overwritten: $p1Comparison"
}
& $p1Python (Join-Path $PSScriptRoot 'compare_p1.py') @p1Runs --output $p1Comparison
if ($LASTEXITCODE) { throw 'Fixed-work comparison failed; no Wii run was started.' }
Write-Output "Overhead batch finished: $p1Comparison"
@@ -0,0 +1,110 @@
param(
[ValidatePattern('^P1-trace-[0-9]{3}$')][string]$Name='P1-trace-001',
[string]$BuildDirectory='.starlet_diag_p1',
[string]$RuntimeDirectory='.starlet_msvc2',
[Parameter(Mandatory=$true)][string]$PythonExecutable
)
# Create an independent, verified pre-update NAND and frozen diagnostic build.
# Never write to the user's normal NAND, the seed, or an existing experiment.
$ErrorActionPreference = 'Stop'
$p1Repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
$p1Root = Join-Path $p1Repo '.starlet_update_ab_20260913'
$p1Profile = Join-Path $p1Root $Name
$p1Build = Join-Path $p1Root "build-$Name"
$p1SourceBuild = [IO.Path]::GetFullPath((Join-Path $p1Repo $BuildDirectory))
$p1RuntimeBuild = [IO.Path]::GetFullPath((Join-Path $p1Repo $RuntimeDirectory))
$p1SourceExe = Join-Path $p1SourceBuild 'Binaries/DolphinNoGUI.exe'
$p1SourcePDB = Join-Path $p1SourceBuild 'pdb/DolphinNoGUI.pdb'
$p1Seed = Join-Path $p1Root 'pre-update.nand-journal'
$p1JournalRelative = 'Starlet\0238188DE97894AE3AF93A92C4F238C0572731A7.nand-journal'
$p1Manifest = Get-Content -LiteralPath (Join-Path $p1Root 'manifest.json') -Raw | ConvertFrom-Json
$p1Expected = Get-Content -LiteralPath (Join-Path $p1Root 'initial-files-B.json') -Raw | ConvertFrom-Json
$p1Python = (Resolve-Path -LiteralPath $PythonExecutable).Path
if (Get-Process DolphinNoGUI,Dolphin -ErrorAction SilentlyContinue) {
throw 'Close the existing Dolphin instance before preparing a native-update run.'
}
foreach ($p1Target in @($p1Profile, $p1Build)) {
if (Test-Path -LiteralPath $p1Target) { throw "Refusing to overwrite $p1Target" }
}
foreach ($p1Required in @($p1Seed, $p1SourceExe, $p1SourcePDB,
(Join-Path $p1RuntimeBuild 'Binaries/Sys'),
(Join-Path $p1SourceBuild 'Binaries/Network'))) {
if (-not (Test-Path -LiteralPath $p1Required)) { throw "Missing input: $p1Required" }
}
if ((Get-FileHash -LiteralPath $p1Seed -Algorithm SHA256).Hash -ne $p1Manifest.SeedSHA256) {
throw 'The preserved pre-update NAND journal differs from its manifest.'
}
$p1InputBytes = ($p1Expected | Measure-Object -Property Bytes -Sum).Sum
$p1InputBytes += (Get-Item -LiteralPath $p1SourceExe).Length + (Get-Item -LiteralPath $p1SourcePDB).Length
foreach ($p1Folder in @('Sys','Network')) {
$p1FolderSource = if ($p1Folder -eq 'Sys') { $p1RuntimeBuild } else { $p1SourceBuild }
$p1InputBytes += (Get-ChildItem -LiteralPath (Join-Path $p1FolderSource "Binaries/$p1Folder") `
-File -Recurse | Measure-Object -Property Length -Sum).Sum
}
if ((Get-PSDrive C).Free -lt ($p1InputBytes + 5GB)) {
throw 'Insufficient free space for copies, update growth, and a 5 GiB reserve.'
}
$p1Copies = foreach ($p1File in $p1Expected) {
$p1Target = [IO.Path]::GetFullPath((Join-Path $p1Profile $p1File.Relative))
if (-not $p1Target.StartsWith($p1Profile + '\', [StringComparison]::OrdinalIgnoreCase)) {
throw 'Invalid relative path in the initial-file manifest.'
}
$p1Sources = if ($p1File.Relative -eq $p1JournalRelative) { @($p1Seed) } else {
@((Join-Path (Join-Path $p1Root 'B') $p1File.Relative),
(Join-Path (Join-Path $p1Repo '.starlet_formatter_test_20260913') $p1File.Relative))
}
$p1Selected = $null
foreach ($p1Source in $p1Sources) {
if ((Test-Path -LiteralPath $p1Source -PathType Leaf) -and
(Get-FileHash -LiteralPath $p1Source -Algorithm SHA256).Hash -eq $p1File.SHA256) {
$p1Selected = $p1Source
break
}
}
if (-not $p1Selected) { throw "No byte-identical initial source for $($p1File.Relative)" }
[pscustomobject]@{ Relative=$p1File.Relative; Source=$p1Selected; Target=$p1Target; SHA256=$p1File.SHA256 }
}
New-Item -ItemType Directory -Path $p1Profile,(Join-Path $p1Build 'Binaries'),
(Join-Path $p1Build 'pdb') | Out-Null
foreach ($p1Copy in $p1Copies) {
New-Item -ItemType Directory -Force -Path (Split-Path $p1Copy.Target -Parent) | Out-Null
Copy-Item -LiteralPath $p1Copy.Source -Destination $p1Copy.Target
if ((Get-FileHash -LiteralPath $p1Copy.Target -Algorithm SHA256).Hash -ne $p1Copy.SHA256) {
throw "Copied input verification failed: $($p1Copy.Relative)"
}
}
foreach ($p1Folder in @('Sys','Network')) {
$p1FolderSource = if ($p1Folder -eq 'Sys') { $p1RuntimeBuild } else { $p1SourceBuild }
Copy-Item -LiteralPath (Join-Path $p1FolderSource "Binaries/$p1Folder") `
-Destination (Join-Path $p1Build 'Binaries') -Recurse
}
Copy-Item -LiteralPath $p1SourceExe -Destination (Join-Path $p1Build 'Binaries/DolphinNoGUI.exe')
Copy-Item -LiteralPath $p1SourcePDB -Destination (Join-Path $p1Build 'pdb/DolphinNoGUI.pdb')
foreach ($p1Folder in @('Logs','Perf','Capture')) {
New-Item -ItemType Directory -Force -Path (Join-Path $p1Profile $p1Folder) | Out-Null
}
$p1ConfigPath = Join-Path $p1Profile 'Config/Dolphin.ini'
$p1OriginalConfig = [IO.File]::ReadAllText($p1ConfigPath)
$p1OldPrefix = (Join-Path $p1Root 'B').Replace('\','/') + '/'
$p1NewPrefix = $p1Profile.Replace('\','/') + '/'
if (-not $p1OriginalConfig.Contains($p1OldPrefix)) {
throw 'The source configuration has no expected baseline profile path.'
}
$p1NewConfig = $p1OriginalConfig.Replace($p1OldPrefix, $p1NewPrefix)
if ($p1NewConfig.Replace($p1NewPrefix, $p1OldPrefix) -cne $p1OriginalConfig) {
throw 'The isolated configuration differs beyond its profile paths.'
}
[IO.File]::WriteAllText($p1ConfigPath, $p1NewConfig, [Text.UTF8Encoding]::new($false))
& $p1Python -B (Join-Path $p1Root '../.starlet-profile/VerifyJournalCheckpoint.py') `
(Join-Path $p1Profile $p1JournalRelative) $p1Manifest.PrefixBytes `
> (Join-Path $p1Profile 'Capture/initial-journal-verification.txt') 2>&1
if ($LASTEXITCODE) { throw 'Preserved NAND checkpoint verification failed; no emulator was launched.' }
[pscustomobject]@{
CreatedUTC=[datetime]::UtcNow.ToString('o'); Profile=$p1Profile; Build=$p1Build
InitialFiles=$p1Copies.Count; SeedSHA256=$p1Manifest.SeedSHA256
ExeSHA256=(Get-FileHash -LiteralPath (Join-Path $p1Build 'Binaries/DolphinNoGUI.exe')).Hash
PdbSHA256=(Get-FileHash -LiteralPath (Join-Path $p1Build 'pdb/DolphinNoGUI.pdb')).Hash
SourceBuild=$p1SourceBuild; RuntimeBuild=$p1RuntimeBuild
PerformanceTraceRequestedAtLaunch=$false
} | ConvertTo-Json -Depth 4 | Out-File -LiteralPath (Join-Path $p1Profile 'Capture/prepare-manifest.json') -Encoding utf8
Write-Output "Prepared isolated profile $p1Profile and frozen build $p1Build. No Dolphin instance was launched."
+87
View File
@@ -0,0 +1,87 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
// A local, user-mode-only trace for validating the provider without WPR rights.
#pragma once
#include <cstddef>
#include <cstring>
#include <filesystem>
#include <stdexcept>
#include <string>
#include <vector>
#include <windows.h>
#include <evntrace.h>
#include "Common/PerformanceTrace.h"
class PrivateETW
{
public:
explicit PrivateETW(const char* output)
{
if (!output)
return;
const auto path = std::filesystem::absolute(output);
if (std::filesystem::exists(path))
throw std::runtime_error("Private ETL target already exists");
if (!Common::PerformanceTrace::Requested())
throw std::runtime_error("Set DOLPHIN_PERF_TRACE=1 for a private trace");
Common::PerformanceTrace::Enabled(); // Register before starting the session.
constexpr wchar_t name[] = L"DolphinP1LocalProbe";
const std::wstring filename = path.wstring();
const size_t name_size = sizeof(name);
const size_t filename_size = (filename.size() + 1) * sizeof(wchar_t);
m_storage.resize(sizeof(EVENT_TRACE_PROPERTIES) + name_size + filename_size);
m_properties = reinterpret_cast<EVENT_TRACE_PROPERTIES*>(m_storage.data());
std::memset(m_properties, 0, m_storage.size());
m_properties->Wnode.BufferSize = static_cast<ULONG>(m_storage.size());
m_properties->Wnode.Guid = PERF_PROVIDER;
m_properties->Wnode.Flags = WNODE_FLAG_TRACED_GUID;
m_properties->Wnode.ClientContext = 1; // QPC
m_properties->BufferSize = 64;
m_properties->MinimumBuffers = 2;
m_properties->MaximumBuffers = 16;
m_properties->LogFileMode = EVENT_TRACE_FILE_MODE_SEQUENTIAL | EVENT_TRACE_PRIVATE_LOGGER_MODE |
EVENT_TRACE_PRIVATE_IN_PROC;
m_properties->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);
m_properties->LogFileNameOffset =
static_cast<ULONG>(sizeof(EVENT_TRACE_PROPERTIES) + name_size);
std::memcpy(m_storage.data() + m_properties->LoggerNameOffset, name, name_size);
std::memcpy(m_storage.data() + m_properties->LogFileNameOffset, filename.c_str(),
filename_size);
const ULONG started = StartTraceW(&m_handle, name, m_properties);
if (started != ERROR_SUCCESS)
throw std::runtime_error("Private ETW StartTrace error " + std::to_string(started));
m_started = true;
const ULONG enabled =
EnableTraceEx2(m_handle, &PERF_PROVIDER, EVENT_CONTROL_CODE_ENABLE_PROVIDER,
TRACE_LEVEL_VERBOSE, 0, 0, 0, nullptr);
if (enabled != ERROR_SUCCESS || !Common::PerformanceTrace::Enabled())
{
Close();
throw std::runtime_error("Private ETW enable error " + std::to_string(enabled));
}
}
~PrivateETW() { Close(); }
PrivateETW(const PrivateETW&) = delete;
PrivateETW& operator=(const PrivateETW&) = delete;
bool Close()
{
if (!m_started)
return true;
m_started = false;
return ControlTraceW(m_handle, L"DolphinP1LocalProbe", m_properties,
EVENT_TRACE_CONTROL_STOP) == ERROR_SUCCESS;
}
private:
static constexpr GUID PERF_PROVIDER = {
0x54ee9231, 0x28be, 0x4ab0, {0x98, 0x1e, 0xb2, 0x6f, 0x97, 0x9c, 0x56, 0xa4}};
TRACEHANDLE m_handle = 0;
bool m_started = false;
EVENT_TRACE_PROPERTIES* m_properties = nullptr;
std::vector<u8> m_storage;
};
+195
View File
@@ -0,0 +1,195 @@
# Diagnostic P1 : statut et exécution locale
Le protocole et les critères de décision sont dans
[`docs/Wii_LLE_Performance_Diagnostic_Protocol.md`](../../docs/Wii_LLE_Performance_Diagnostic_Protocol.md).
Tous les artefacts volumineux vont dans `.starlet-profile` (ignoré par Git), jamais
dans la NAND source ni dans le profil utilisateur courant.
1. Construire le profil isolé avec `./Tools/PerformanceTrace/Build-P1.ps1`.
Après modification d'une option de compilation, `-CleanBeforeBuild` vérifie tous
les objets. Le script répare le préfixe français `/showIncludes` si cette
installation MSVC l'a mal décodé ; un objet avec `#deps 0` invalide la build.
2. Vérifier les tests ciblés de `Binaries/Tests/tests.exe` et le décodeur avec
`./Tools/PerformanceTrace/Build-Decoder.ps1 -OutputDirectory .starlet-profile/P1-tools`.
3. Sur une session Windows sans droit de profilage noyau, valider d'abord le
fournisseur dans une session ETW privée :
```powershell
./Tools/PerformanceTrace/Capture-Private-P1.ps1 -OutputDirectory .starlet-profile/P1-private-NEW
python Tools/PerformanceTrace/qualify_p1.py .starlet-profile/P1-private-NEW
```
Le résultat attendu est `local_provider_passed=true` et
`full_collector_passed=false`. Cette session ne contient aucun échantillon
CPU, changement de thread ou attente disque. Le mode `-NoTrace` exécute
exactement la même charge pour une comparaison locale alternée. Exemple
avec quatre répertoires neufs, à exécuter dans cet ordre :
```powershell
./Tools/PerformanceTrace/Capture-Private-P1.ps1 -OutputDirectory .starlet-profile/P1-off-1 -NoTrace
./Tools/PerformanceTrace/Capture-Private-P1.ps1 -OutputDirectory .starlet-profile/P1-on-1
./Tools/PerformanceTrace/Capture-Private-P1.ps1 -OutputDirectory .starlet-profile/P1-off-2 -NoTrace
./Tools/PerformanceTrace/Capture-Private-P1.ps1 -OutputDirectory .starlet-profile/P1-on-2
python Tools/PerformanceTrace/compare_p1.py .starlet-profile/P1-off-1 .starlet-profile/P1-on-1 .starlet-profile/P1-off-2 .starlet-profile/P1-on-2 --output .starlet-profile/P1-private-overhead-NEW.json
```
Ce comparateur conserve les quatre mesures et la dispersion ; il ne peut
**pas** valider le budget de 2 % de la capture WPR complète.
4. Capture synthétique WPR complète **dans une session administrateur**, avec
un **nouveau** chemin de sortie :
```powershell
./Tools/PerformanceTrace/Capture-Local-P1.ps1 -OutputDirectory .starlet-profile/P1-local-NEW
```
Ce programme exécute une boucle Thumb réelle, un sommeil hôte connu, 128
transactions de journal synthétique et 32 échanges ARP avec la passerelle
locale libslirp. Le journal synthétique reste dans ce répertoire neuf.
Aucun serveur externe n'est contacté par l'échange ARP.
5. Après la capture, décoder et qualifier hors ligne (sans droit administrateur)
dans un **nouveau** répertoire :
```powershell
./Tools/PerformanceTrace/Analyze-Local-P1.ps1 `
-CaptureDirectory .starlet-profile/P1-local-NEW `
-OutputDirectory .starlet-profile/P1-local-NEW-analysis
```
Le lecteur TDH extrait les événements natifs ; Xperf décode les événements
noyau classiques, résout les PDB locaux et les deux flux sont alignés par
les QPC des marqueurs ou des snapshots périodiques. Le CSV, l'ETL et les données de profil peuvent contenir
des noms de processus ou chemins : ils restent locaux et ignorés par Git.
Le répertoire de sortie doit être neuf à chaque tentative.
6. Mesurer le surcoût WPR avec une seule commande administrateur et un nouveau
répertoire. Elle automatise quatre paires alternées OFF/ON du **même** travail
synthétique (huit lancements locaux, aucun démarrage Wii ni NAND utilisateur) :
```powershell
./Tools/PerformanceTrace/Measure-P1-Overhead.ps1 -OutputDirectory .starlet-profile/P1-overhead-001
```
`comparison.json` conserve les durées brutes, la dispersion des bases OFF,
les écarts par paire et une borne supérieure de confiance. Le seuil de 2 %
ne passe que si les données restent stables et les trois mesures ARM/mur/CPU
satisfont ce seuil. Python est vérifié **avant** toute capture ; si un lot
s'est interrompu uniquement au calcul final, `-AnalyzeOnly` relit les huit
captures existantes sans en relancer aucune. `-PythonExecutable` permet de
préciser le chemin de `python.exe` si le PowerShell administrateur n'a pas
le même `PATH`. Un résultat négatif ou bruité n'autorise aucun diagnostic
de vitesse Wii.
`qualification.json` détaille chaque gate. Une sonde locale réussie ne constitue
pas encore une analyse de mise à jour Wii : le cas PPC, les piles hôte et le
surcoût du collecteur restent à qualifier. La capture native n'est prévue
qu'après ces vérifications. Le profil WPR comporte une session au nom unique et
le script arrête seulement cette session.
Le 22 septembre, deux traces privées ont validé les 13 contrôles du fournisseur
(`P1-private-004`, `P1-private-006`). Le jeton `CodexSandboxUsers` ne pouvait
pas lancer WPR (`0xc5585011`), mais la capture synthétique administrateur
`P1-local-004` a réussi. Sous Windows PowerShell 5.1, le premier essai avait
révélé `ProcessStartInfo.ArgumentList` nul et une résolution de chemin relatif
depuis le répertoire de processus plutôt que celui affiché par `cd` ; les deux
cas sont corrigés et testés.
L'analyse reproductible `P1-local-004-reanalysis2` passe 13 contrôles du
fournisseur et 3 contrôles système : 9 427 échantillons CPU, 694 changements
de contexte, dix ancres QPC alignées à cinq ticks près, sommeil connu de
752 ms avec un switch `Waiting`. Les 112 événements classiques déclarés
invalides par Xperf concernent une métadonnée `ImageID` hors du PID de la
sonde ; zéro événement cible invalide et zéro perte ETW. Les symboles du PDB
local résolvent les fonctions hôte. Cela valide la **sonde**, pas la capture
native : coût du collecteur WPR, cas PPC et chemin critique Wii restent ouverts.
[Identification du GUID ImageID dans le code Microsoft PerfView](https://github.com/microsoft/perfview/blob/main/src/TraceEvent/BPerf/BPerfEventSource.cs).
Le lot `P1-overhead-001` du 22 septembre a produit les huit captures complètes,
mais son PowerShell administrateur ne trouvait pas Python lors de la comparaison.
Les données conservées ont été comparées hors ligne, sans recapture : les bases
OFF varient de 34,5 % pour la phase ARM et 26,8 % sur le temps total. Les écarts
ARM par paire sont +9,7 %, +25,0 %, -0,5 % et +1,0 %. Le surcoût WPR ne peut
donc pas être isolé de la variabilité de cette série et le budget de 2 % reste
**non qualifié**. Le rapport brut est
`.starlet-profile/P1-overhead-001/comparison.json` ; aucune mesure de vitesse
Wii n'en est déduite. Les traces ON montrent `cpptools.exe` consommant environ
8–9 s de CPU par essai et des sous-processus Dell intermittents ; ces charges
hôte sont une piste de contamination, pas une attribution causale chiffrée des
écarts ON/OFF. Dans `wpr-on-2`, 76 768 événements `ReadyThread` système ont été
enregistrés. Le profil conserve ces événements et leurs horodatages mais ne
collecte plus leur pile, afin de réduire le coût potentiel de cette source
système très fréquente ; le profil modifié doit être requalifié séparément.
Le lot `P1-overhead-002`, après cet allègement, n'a pas perdu d'événements
mais garde 36,5 % d'étendue ARM entre bases OFF. Ses quatre écarts ON/OFF sont
+4,6 %, -11,0 %, +10,2 % et -3,5 % ; leur moyenne proche de zéro ne qualifie
**pas** le budget. L'analyse des échantillons ETW révèle un changement de
placement CPU : part sur les processeurs logiques 0–3 de 78,7 %, 45,4 %, 28,9 %,
46,5 % pour des phases ARM de 7,59 s, 8,82 s, 10,33 s, 8,65 s. L'ETL identifie
un Core i7-1255U et SMT sur 0–3 ; [Intel indique 2 P-cores et 8 E-cores](https://www.intel.com/content/www/us/en/products/sku/226259/intel-core-i71255u-processor-12m-cache-up-to-4-70-ghz/specifications.html).
Ce placement est fortement associé à la durée, sans prouver qu'il explique à
lui seul tout l'écart. Le lancement Wii existant fixe déjà Dolphin sur ces
processeurs ; la **sonde synthétique**, elle, n'était pas fixée.
Les captures de sonde acceptent maintenant `-ProbeAffinityMask`, enregistrent
le masque réellement appliqué, et le comparateur refuse les masques différents.
Quatre bases locales sans WPR avec `-ProbeAffinityMask 15` ont fini leur phase
ARM en 7,03, 6,65, 7,20 et 6,97 s (masque observé 15 à chaque fois). Le
placement est contrôlé, mais une variabilité résiduelle de 8,3 % subsiste :
aucun nouveau lot administrateur n'est demandé avant de traiter cette limite
du protocole ou de passer à un diagnostic qualitatif explicitement borné.
## Première capture d'une vraie mise à jour (exploratoire)
`Prepare-Native-Update-P1.ps1` crée un profil NAND pré-mise-à-jour indépendant,
vérifie les 31 fichiers et le journal, puis fige l'exécutable et son PDB. Il
refuse tout nom déjà utilisé et ne lance pas Dolphin. L'expérience préparée
ici est `P1-trace-002` ; le profil courant `.starlet_user3` et les résultats A–F
ne sont pas modifiés. La capture ETW requiert un PowerShell administrateur.
La préparation dépend d'un seed NAND local ignoré par Git et demande désormais
un `-PythonExecutable` explicite ; elle n'est pas une procédure de création de
NAND dans un clone neuf.
```powershell
# Terminal administrateur : démarrer d'abord, puis laisser ouvert.
cd C:\Users\tpetkovic\Desktop\dolphin
.\Tools\PerformanceTrace\Capture-P1.ps1 -OutputDirectory .starlet-profile/P1-native-update-001 -Seconds 600
# Dès « Native collector armed », dans un autre PowerShell :
cd C:\Users\tpetkovic\Desktop\dolphin
.\Run-Wii-IOS-LLE.ps1 `
-BuildDirectory .starlet_update_ab_20260913/build-P1-trace-002 `
-UserDirectory .starlet_update_ab_20260913/P1-trace-002 `
-Ethernet -PerformanceTrace
```
Noter le PID imprimé par le lanceur, lancer la mise à jour dans la Wii, puis
laisser terminer la capture. Analyser ensuite l'ETL hors ligne dans un nouveau
répertoire :
```powershell
.\Tools\PerformanceTrace\Analyze-Local-P1.ps1 `
-CaptureDirectory .starlet-profile/P1-native-update-001 `
-OutputDirectory .starlet-profile/P1-native-update-001-analysis `
-NativePID <PID_DOLPHIN> `
-NativePDB .starlet_update_ab_20260913/build-P1-trace-002/pdb/DolphinNoGUI.pdb
```
Le rapport `native-report.json` reste exploratoire : perte ETW et alignement
QPC sont contrôlés, mais piles, attentes critiques, NAT et surcoût de capture
doivent encore être qualifiés avant d'attribuer le ralentissement ou d'annoncer
un gain de FPS. La mise à jour nécessite une action Wii réelle et un réseau
disponible ; ne pas essayer de la rejouer sur le même profil après succès.
Windows exige un droit de profilage pour le profil noyau ; un logger privé
du processus fonctionne avec un compte peu privilégié.
[Sessions privées ETW](https://learn.microsoft.com/en-us/windows/win32/etw/configuring-and-starting-a-private-logger-session),
[droits de StartTrace](https://learn.microsoft.com/en-us/windows/win32/api/evntrace/nf-evntrace-starttracea).
## Décision après A/B natif du 23 septembre
Le [rapport P1](../../docs/Wii_LLE_Update_P1_Trace_2026-09-23.md) contient les
deux mises à jour NAND isolées et vérifiées. Le raccourci SRAM ciblé a été
rejeté : sur ce passage, le témoin a terminé les mêmes seuils de journal plus
vite et a été jugé plus fluide. Le raccourci a été retiré du source ; ses deux
binaires et journaux figés restent locaux pour audit. Les outils de ce dossier
servent au diagnostic, pas à justifier une modification matérielle sans test
de conformité sur Wii réelle.
+190
View File
@@ -0,0 +1,190 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
// Local qualification only: synthetic ARM code/data, synthetic NAND journal, no
// firmware/profile.
#include <array>
#include <chrono>
#include <cstdio>
#include <filesystem>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
#include <winsock2.h>
#include "Common/Network.h"
#include "Common/PerformanceTrace.h"
#include "Core/IOS/Starlet/ARMCore.h"
#include "Core/IOS/Starlet/AX88772.h"
#include "Core/IOS/Starlet/NANDJournal.h"
#include "Core/IOS/Starlet/SlirpNetwork.h"
#include "PrivateETW.h"
namespace Trace = Common::PerformanceTrace;
using namespace IOS::LLE;
class ProbeBus final : public ARMBus
{
public:
u8 Read8(u32 address) override { return bytes.at(address); }
void Write8(u32 address, u8 value) override { bytes.at(address) = value; }
const u8* GetDirectMemoryPointer(u32 address, u32 size) const override
{
return address < bytes.size() && size <= bytes.size() - address ? bytes.data() + address :
nullptr;
}
void Op(u32 offset, u16 op)
{
bytes[offset] = static_cast<u8>(op >> 8);
bytes[offset + 1] = static_cast<u8>(op);
}
std::array<u8, 8192> bytes{};
};
void Check(bool value)
{
if (!value)
throw std::runtime_error("P1 local probe validation failed");
}
void LocalNAT(const std::string& directory)
{
SlirpNetwork network;
AX88772 device([&](std::span<const u8> frame) { network.Input(frame); });
std::string error;
if (!network.Start(
directory, [&](std::span<const u8> frame) { device.ReceiveFrame(frame); }, &error))
throw std::runtime_error(error);
const auto control = [&](u8 type, u8 request, u16 value) {
std::array<u8, 8> setup{
type, request, static_cast<u8>(value), static_cast<u8>(value >> 8), 0, 0, 0, 0};
size_t actual = 0;
Check(device.Transfer(0, 0, setup, &actual) == AX88772::Result::Completed);
Check(device.Transfer(0, 2, {}, &actual) == AX88772::Result::Completed);
};
control(0, 9, 1);
control(0x40, 0x10, 0x88);
control(0x40, 0x1b, 0x306);
device.SetLink(true);
// ARP reaches only libslirp's virtual gateway: no DNS, Internet or remote server.
Common::MACAddress mac{2, 0x44, 0x4f, 0x4c, 0, 1};
Common::ARPPacket request(Common::MACAddress{255, 255, 255, 255, 255, 255}, mac);
request.arp_header.opcode = htons(1);
request.arp_header.sender_address = mac;
request.arp_header.sender_ip = htonl(0x0a00020f);
request.arp_header.target_ip = htonl(0x0a000202);
const auto frame = request.Build();
const u16 length = static_cast<u16>(frame.size());
std::vector<u8> framed{static_cast<u8>(length), static_cast<u8>(length >> 8),
static_cast<u8>(~length), static_cast<u8>(~length >> 8)};
framed.insert(framed.end(), frame.begin(), frame.end());
Trace::Marker("LocalNATBegin");
for (u32 i = 0; i < 32; ++i)
{
Trace::SampleRoot root(true);
size_t actual = 0;
Check(device.Transfer(3, 1, framed, &actual) == AX88772::Result::Completed);
network.Poll(243000);
device.TraceQueue();
std::array<u8, 2048> response{};
Check(device.Transfer(2, 2, response, &actual) == AX88772::Result::Completed);
Check(actual >= 46);
const auto arp =
Common::PacketView(response.data() + 4, response[0] | (response[1] << 8)).GetARPPacket();
Check(arp && ntohs(arp->arp_header.opcode) == 2 &&
arp->arp_header.sender_ip == htonl(0x0a000202));
device.TraceQueue();
}
Trace::Marker("LocalNATEnd");
}
int main(int argc, char** argv)
{
try
{
if (argc != 3 && argc != 4)
throw std::runtime_error("Usage: TraceProbeP1.exe NEW-synthetic-journal-path "
"libslirp-runtime-directory [NEW-private-ETL]");
const std::string journal_path = argv[1];
Check(!std::filesystem::exists(journal_path));
PrivateETW private_trace(argc == 4 ? argv[3] : nullptr);
Trace::Marker("ProbeBegin");
ProbeBus bus;
bus.Op(0, 0x6810); // ldr r0,[r2]
bus.Op(2, 0x6851); // ldr r1,[r2,#4]
bus.Op(4, 0x46c0); // nop
bus.Op(6, 0xe7fb); // b 0
bus.Write32(4096, 0x12345678);
bus.Write32(4100, 0x87654321);
ARMCore cpu(bus);
cpu.SetCPSR(static_cast<u32>(ARMCore::Mode::Supervisor) | ARMCore::CPSR_T);
cpu.SetRegister(2, 4096);
cpu.SetJitEnabled(true);
Trace::Marker("ARMWorkBegin");
const auto start = std::chrono::steady_clock::now();
// Fixed work, not a duration-based loop: suitable for ON/OFF cost
// comparisons.
constexpr u64 slices = 160000;
for (u64 i = 0; i < slices; ++i)
{
Trace::SampleRoot root;
Check(cpu.RunCycles(4096) == 4096);
if ((i & 1023) == 0)
Trace::Snapshot(cpu.GetTraceGeneration(), cpu.GetExecutedInstructions(),
cpu.GetJitNativeExecutedInstructions(), cpu.GetJitSlowReadCount(),
cpu.GetJitSlowWriteCount(), cpu.GetJitLifetimeCompiledBlockCount(),
cpu.GetJitFallbackInstructionCount(), cpu.GetRegister(15), false);
}
const double ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
Check(cpu.GetRegister(0) == 0x12345678 && cpu.GetRegister(1) == 0x87654321);
Check(cpu.GetExecutedInstructions() == slices * 4096);
Trace::Marker("ARMWorkEnd");
Trace::Marker("KnownSleepBegin");
std::this_thread::sleep_for(std::chrono::milliseconds(750));
Trace::Marker("KnownSleepEnd");
{
Trace::Marker("SyntheticJournalBegin");
NANDJournal journal;
NANDJournal::Pages pages;
Common::SHA1::Digest synthetic_identity{};
std::string error;
Check(journal.Open(journal_path, synthetic_identity, &pages, &error));
for (u32 i = 0; i < 128; ++i)
{
Trace::SampleRoot root(true);
NANDJournal::Pages update;
update[i].fill(static_cast<u8>(i));
Check(journal.Append(update));
}
Trace::Marker("SyntheticJournalEnd");
}
{
NANDJournal verifier;
NANDJournal::Pages pages;
Common::SHA1::Digest synthetic_identity{};
std::string error;
Check(verifier.Open(journal_path, synthetic_identity, &pages, &error));
Check(pages.size() == 128);
for (u32 i = 0; i < 128; ++i)
for (u8 value : pages.at(i))
Check(value == static_cast<u8>(i));
}
LocalNAT(std::filesystem::absolute(argv[2]).string());
cpu.Reset();
std::this_thread::sleep_for(std::chrono::milliseconds(1100));
Trace::Snapshot(cpu.GetTraceGeneration(), cpu.GetExecutedInstructions(),
cpu.GetJitNativeExecutedInstructions(), cpu.GetJitSlowReadCount(),
cpu.GetJitSlowWriteCount(), cpu.GetJitLifetimeCompiledBlockCount(),
cpu.GetJitFallbackInstructionCount(), cpu.GetRegister(15), false);
Trace::Marker("ProbeEnd");
const bool trace_enabled = Trace::Enabled();
Check(private_trace.Close());
std::printf("P1Probe exact=OK trace-requested=%d trace-enabled=%d "
"arm-ms=%.3f instructions=%llu journal-pages=128 nat-arp-replies=32\n",
Trace::Requested(), trace_enabled, ms, slices * 4096);
return 0;
}
catch (const std::exception& error)
{
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
}
+256
View File
@@ -0,0 +1,256 @@
"""Offline P1 event analysis. Unknowns fail qualification rather than becoming zero cost."""
import argparse
from bisect import bisect_left
from collections import Counter, defaultdict
import json
from pathlib import Path
import statistics
REGIONS = ("Slice", "ARM", "Jit", "Compile", "Devices", "NAND", "Journal",
"JournalBuild", "JournalWrite", "JournalFlush", "NAT", "DMARead", "DMAWrite", "AES", "SHA")
class CodeMap:
def __init__(self):
self.ranges = []
def event(self, data):
begin, end = int(data["Begin"]), int(data["End"])
if not begin or end <= begin:
raise ValueError("Invalid generated-code interval")
# Reuse replaces overlapping mappings at this timestamp. Never use the final
# mapping to interpret samples collected before an invalidation/recompilation.
kept = []
for lo, hi, domain, pc in self.ranges:
if hi <= begin or lo >= end:
kept.append((lo, hi, domain, pc))
else:
if lo < begin:
kept.append((lo, begin, domain, pc))
if hi > end:
kept.append((end, hi, domain, pc))
if data["Kind"] != "invalidate":
kept.append((begin, end, data["Domain"], data["GuestPC"]))
self.ranges = kept
def lookup(self, ip):
for lo, hi, domain, pc in reversed(self.ranges):
if lo <= ip < hi:
return domain, pc
return "UnresolvedNative", None
class SampledCodeMap:
"""Time-ordered mappings only for host PCs actually sampled by ETW.
Native updates can emit hundreds of thousands of JIT map events. Keeping
split intervals and scanning them for every sample makes offline analysis
quadratic. The report only needs the finite set of sampled host addresses.
"""
def __init__(self, sampled_addresses):
self.addresses = sorted(set(sampled_addresses))
self.mappings = {}
def event(self, data):
begin, end = int(data["Begin"]), int(data["End"])
if not begin or end <= begin:
raise ValueError("Invalid generated-code interval")
lo = bisect_left(self.addresses, begin)
hi = bisect_left(self.addresses, end)
if data["Kind"] == "invalidate":
for address in self.addresses[lo:hi]:
self.mappings.pop(address, None)
else:
value = (data["Domain"], data["GuestPC"])
for address in self.addresses[lo:hi]:
self.mappings[address] = value
def lookup(self, ip):
return self.mappings.get(ip, ("UnresolvedNative", None))
def percentile(values, fraction):
if not values:
return None
values = sorted(values)
position = (len(values) - 1) * fraction
low = int(position)
high = min(low + 1, len(values) - 1)
return values[low] + (values[high] - values[low]) * (position - low)
def read_relevant_events(path, pid):
# ETW is host-wide. Keep this process's telemetry and all its CPU samples;
# rendering/network threads can be hot without emitting native telemetry.
native = []
with path.open(encoding="utf-8") as source:
for line in source:
e = json.loads(line)
if e["native"] and e["pid"] == pid:
native.append(e)
if not native:
raise ValueError("No native events for requested process")
native_tids = {e["tid"] for e in native}
begin, end = min(e["qpc"] for e in native), max(e["qpc"] for e in native)
rows = native
with path.open(encoding="utf-8") as source:
for line in source:
e = json.loads(line)
if e["native"] or not begin <= e["qpc"] <= end:
continue
if e["event"] == "SampledProfile" and e["pid"] == pid:
rows.append(e)
sampled_tids = {e["data"].get("ThreadId", e["tid"]) for e in rows
if not e["native"] and e["event"] == "SampledProfile"}
process_tids = native_tids | sampled_tids
with path.open(encoding="utf-8") as source:
for line in source:
e = json.loads(line)
if e["native"] or e["event"] != "CSwitch" or not begin <= e["qpc"] <= end:
continue
d = e["data"]
if d.get("OldThreadId") in process_tids or d.get("NewThreadId") in process_tids:
rows.append(e)
return rows
def analyze(rows, pid):
rows = sorted(rows, key=lambda event: event["qpc"])
native = [e for e in rows if e["native"] and e["pid"] == pid]
if not native:
raise ValueError("No native events for requested process")
if any(e["data"].get("Schema") != 1 for e in native):
raise ValueError("Unknown or missing native schema")
native_tids = {e["tid"] for e in native}
sampled_tids = {e["data"].get("ThreadId", e["tid"]) for e in rows
if not e["native"] and e["event"] == "SampledProfile" and e["pid"] == pid}
tids = native_tids | sampled_tids
frequencies = {e["data"]["QPCFrequency"] for e in native if "QPCFrequency" in e["data"]}
if len(frequencies) != 1 or not next(iter(frequencies)):
raise ValueError("Missing or inconsistent QPC frequency")
frequency = next(iter(frequencies))
mappings = SampledCodeMap(e["data"]["InstructionPointer"] for e in rows
if not e["native"] and "InstructionPointer" in e["data"])
samples = Counter()
hot_pc = Counter()
hot_static = Counter()
phases = {}
scope_samples = defaultdict(list)
frames = defaultdict(list)
counter_last = {}
counter_errors = []
snapshots = []
cswitches = []
queues = []
accounting_errors = 0
for e in rows:
data = e["data"]
if e["native"] and e["pid"] == pid:
if e["event"] == "CodeMap":
mappings.event(data)
elif e["event"] == "Marker":
phases[data["Name"]] = e["qpc"]
if data["Name"] == "PerformanceMetricsReset":
# Keep intervals per generation, never bridge a reset/reboot.
for events in frames.values():
events.append(None)
elif e["event"] == "ScopeSample":
accounting_errors += data["AccountingErrors"]
scope_samples[(e["tid"], data["Sample"])].append(data)
elif e["event"] == "Frame":
frames[data["Kind"]].append((data["QPC"], data))
elif e["event"] == "Counter":
key = (e["tid"], data["Counter"])
if data["Value"] < counter_last.get(key, 0):
counter_errors.append({"tid": e["tid"], "counter": data["Counter"], "qpc": e["qpc"]})
counter_last[key] = data["Value"]
elif e["event"] == "Snapshot":
snapshots.append(data)
elif e["event"] == "USBQueue":
queues.append(data)
elif not e["native"]:
tid = data.get("ThreadId", data.get("ThreadID", e["tid"]))
if "InstructionPointer" in data and tid in tids:
domain, pc = mappings.lookup(data["InstructionPointer"])
weight = data.get("Count", 1)
if domain == "UnresolvedNative" and "!" in data.get("Symbol", ""):
symbol = data["Symbol"]
module = symbol.split("!", 1)[0].strip('"').lower()
if module in ("traceprobep1.exe", "dolphinnogui.exe", "dolphin.exe"):
domain = "HostC++"
elif module and module != "unknown":
domain = "SystemOrLibrary"
if domain != "UnresolvedNative":
hot_static[symbol] += weight
samples[domain] += weight
if pc is not None:
hot_pc[(domain, pc)] += weight
if "OldThreadId" in data and (data["OldThreadId"] in tids or data.get("NewThreadId") in tids):
cswitches.append(e)
timing = defaultdict(lambda: {"calls": 0, "inclusive_ms": 0., "exclusive_ms": 0.})
for group in scope_samples.values():
roots = [d for d in group if d["Region"] == 0]
if len(roots) != 1 or sum(d["ExclusiveQPC"] for d in group) != roots[0]["InclusiveQPC"]:
accounting_errors += 1
for data in group:
region = REGIONS[data["Region"]] + "/sample-1-in-" + str(data["SamplingDenominator"])
# Actual sampled time only. Do not present extrapolated duration as exact CPU.
stat = timing[region]
stat["calls"] += data["Calls"]
stat["inclusive_ms"] += 1000 * data["InclusiveQPC"] / frequency
stat["exclusive_ms"] += 1000 * data["ExclusiveQPC"] / frequency
snapshot_errors = []
previous = {}
for data in snapshots:
key = data["CoreId"]
if key in previous:
for field in ("Instructions", "NativeInstructions", "SlowReads", "SlowWrites", "Compiles", "Fallbacks"):
if data[field] < previous[key][field]:
snapshot_errors.append({"generation": key, "field": field})
previous[key] = data
durations = {}
for kind, events in frames.items():
deltas = [(b[0] - a[0]) * 1000 / frequency for a, b in zip(events, events[1:]) if a and b]
durations[kind] = {"intervals": len(deltas), "p50_ms": percentile(deltas, .5),
"p95_ms": percentile(deltas, .95), "p99_ms": percentile(deltas, .99)}
sleep = None
if "KnownSleepBegin" in phases and "KnownSleepEnd" in phases:
begin, end = phases["KnownSleepBegin"], phases["KnownSleepEnd"]
changes = [e for e in cswitches if begin <= e["qpc"] <= end]
waits = [e for e in changes if e["data"]["OldThreadId"] in tids and e["data"].get("OldThreadState") == 5]
sleep = {"wall_ms": (end - begin) * 1000 / frequency,
"cswitch_events": len(changes), "waiting_switches": len(waits),
"wait_evidence_present": bool(waits)}
return {"schema": 1, "pid": pid, "qpc_frequency": frequency,
"native_events": len(native), "native_threads": sorted(native_tids),
"sampled_process_threads": sorted(sampled_tids),
"cpu_leaf_samples": dict(samples),
"hot_generated_pcs": [{"domain": domain, "pc": hex(pc), "samples": count}
for (domain, pc), count in hot_pc.most_common(20)],
"hot_static_symbols": [{"symbol": symbol, "samples": count}
for symbol, count in hot_static.most_common(20)],
"sampled_scope_wall_times_not_cpu": dict(timing), "scope_samples": len(scope_samples),
"accounting_errors": accounting_errors, "counter_regressions": counter_errors,
"snapshot_regressions": snapshot_errors, "core_generations": sorted(previous),
"last_counters_by_thread": [{"tid": tid, "counter": counter, "value": value}
for (tid, counter), value in sorted(counter_last.items())],
"usb_queue_events": len(queues),
"usb_queue_peak": max((q["PeakFrames"] for q in queues), default=None),
"frame_intervals": durations, "known_sleep": sleep, "markers": phases,
"native_update_qualified": False,
"remaining_gates": ["Resolve static C++/system stacks and critical-path waits in ETL",
"Qualify PPC and check local NAT counters", "Check ETW losses and full collector overhead"],
"note": "Partial offline qualification, not a native update bottleneck report. CPU leaf samples include all sampled threads of the target process within native telemetry bounds. Leaf sample counts are not exact CPU durations. Scopes are sampled wall times, not CPU. Never compare differently sampled totals."}
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("events", type=Path)
parser.add_argument("--pid", required=True, type=int)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
result = analyze(read_relevant_events(args.events, args.pid), args.pid)
with args.output.open("x", encoding="utf-8") as output:
json.dump(result, output, indent=2)
print(json.dumps(result, indent=2))
+98
View File
@@ -0,0 +1,98 @@
"""Compare alternating fixed-work local runs without claiming a native gain."""
import argparse
import json
import math
from pathlib import Path
import re
import statistics
def load(directory):
manifest = json.loads((directory / "manifest.json").read_text(encoding="utf-8-sig"))
log = (directory / "probe.stdout.log").read_text(encoding="utf-8-sig")
match = re.search(r"arm-ms=([0-9.]+) instructions=(\d+) journal-pages=128 nat-arp-replies=32", log)
if not match or manifest["ProbeExitCode"] != 0 or int(match.group(2)) != 655360000:
raise ValueError(f"Probe did not finish the exact work: {directory}")
collection = manifest.get("Collection", "WPRSystemAndNative" if "Profile" in manifest else None)
requested = collection != "NoTrace"
if f"trace-requested={int(requested)} trace-enabled={int(requested)}" not in log:
raise ValueError(f"Probe trace state does not match collection: {directory}")
if collection == "WPRSystemAndNative":
decoder = json.loads((directory / "decoder-summary.json").read_text(encoding="utf-8-sig"))
if any(decoder.get(key) != 0 for key in
("status", "native_decode_errors", "events_lost", "buffers_lost")):
raise ValueError(f"WPR trace has decode errors or lost events: {directory}")
return {"directory": str(directory), "collection": collection,
"hash": manifest["ProbeSHA256"], "pdb_hash": manifest["ProbePDBSHA256"],
"affinity_mask": manifest.get("ProbeAffinityMask", 0),
"observed_affinity_mask": manifest.get("ProbeObservedAffinityMask"),
"arm_ms": float(match.group(1)), "wall_ms": 1000 * manifest["ProbeWallSeconds"],
"cpu_ms": 1000 * manifest["ProbeCPUSeconds"]}
def upper_95(values):
# Two-sided Student 95% upper bound; report but never equate with a
# guarantee for a different (native Wii) workload.
critical = {4: 3.182, 5: 2.776, 6: 2.571, 7: 2.447, 8: 2.365}
return statistics.mean(values) + critical[len(values)] * statistics.stdev(values) / math.sqrt(len(values))
def compare(directories):
runs = [load(path) for path in directories]
on_mode = runs[1]["collection"] if len(runs) >= 2 else None
if (on_mode not in ("PrivateUserMode", "WPRSystemAndNative") or
len(runs) < 4 or len(runs) > 16 or len(runs) % 2 or
any(r["collection"] != kind for r, kind in
zip(runs, ("NoTrace", on_mode) * (len(runs) // 2)))):
raise ValueError("Provide at least two OFF/ON pairs in alternating order")
if len({(r["hash"], r["pdb_hash"]) for r in runs}) != 1:
raise ValueError("The compared executables or PDBs differ")
if len({r["affinity_mask"] for r in runs}) != 1 or any(
r["affinity_mask"] and r["observed_affinity_mask"] != r["affinity_mask"]
for r in runs):
raise ValueError("Probe CPU affinity differs across compared runs")
pairs = []
for off, on in zip(runs[::2], runs[1::2]):
pairs.append({"off": off["directory"], "on": on["directory"],
"arm_phase_percent": 100 * (on["arm_ms"] / off["arm_ms"] - 1),
"whole_probe_percent": 100 * (on["wall_ms"] / off["wall_ms"] - 1),
"cpu_percent": 100 * (on["cpu_ms"] / off["cpu_ms"] - 1),
"non_arm_wall_delta_ms": (on["wall_ms"] - on["arm_ms"]) -
(off["wall_ms"] - off["arm_ms"])})
arm_differences = [pair["arm_phase_percent"] for pair in pairs]
wall_differences = [pair["whole_probe_percent"] for pair in pairs]
cpu_differences = [pair["cpu_percent"] for pair in pairs]
baseline_range = 100 * (max(r["arm_ms"] for r in runs[::2]) /
min(r["arm_ms"] for r in runs[::2]) - 1)
wall_baseline_range = 100 * (max(r["wall_ms"] for r in runs[::2]) /
min(r["wall_ms"] for r in runs[::2]) - 1)
bounds = (dict(arm_phase_percent=upper_95(arm_differences),
whole_probe_percent=upper_95(wall_differences),
cpu_percent=upper_95(cpu_differences)) if len(pairs) >= 4 else None)
qualified = (on_mode == "WPRSystemAndNative" and bounds is not None and
baseline_range <= 2 and wall_baseline_range <= 2 and
all(value <= 2 for value in bounds.values()))
return {"schema": 1, "on_collection": on_mode, "runs": runs, "pairs": pairs,
"mean_arm_phase_percent": statistics.mean(arm_differences),
"off_arm_phase_range_percent": baseline_range,
"off_wall_range_percent": wall_baseline_range,
"upper_95_percent": bounds,
"mean_non_arm_wall_delta_ms": statistics.mean(p["non_arm_wall_delta_ms"] for p in pairs),
"two_percent_budget_qualified": qualified,
"note": "Fixed-work local collector cost only, not a native Wii speed estimate. Four or more OFF/ON pairs, low baseline spread, and upper bounds below 2% are required for this conservative local gate."}
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("captures", nargs="+", type=Path)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
result = compare(args.captures)
with args.output.open("x", encoding="utf-8") as target:
json.dump(result, target, indent=2)
print(json.dumps({key: result[key] for key in
("on_collection", "pairs", "mean_arm_phase_percent",
"off_arm_phase_range_percent", "off_wall_range_percent",
"upper_95_percent", "mean_non_arm_wall_delta_ms",
"two_percent_budget_qualified")}, indent=2))
+102
View File
@@ -0,0 +1,102 @@
"""Check a local P1 trace against the probe's known work; never qualify a Wii run."""
import argparse
import hashlib
import json
from pathlib import Path
from analyze_p1 import analyze, read_relevant_events
def sha256(path):
digest = hashlib.sha256()
with path.open("rb") as source:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest().upper()
def qualify(directory, events_path=None, xperf_summary_path=None):
manifest = json.loads((directory / "manifest.json").read_text(encoding="utf-8-sig"))
decoder = json.loads((directory / "decoder-summary.json").read_text(encoding="utf-8-sig"))
source = events_path or directory / "events.jsonl"
report = analyze(read_relevant_events(source, manifest["ProbePID"]),
manifest["ProbePID"])
log = (directory / "probe.stdout.log").read_text(encoding="utf-8-sig")
events = read_relevant_events(source, manifest["ProbePID"])
xperf_path = xperf_summary_path or directory / "xperf-summary.json"
xperf = json.loads(xperf_path.read_text(encoding="utf-8-sig")) if xperf_path.exists() else {}
counters = {(c["tid"], c["counter"]): c["value"]
for c in report["last_counters_by_thread"]}
# The local probe has one worker thread. Values are cumulative and exact.
worker = next(e["tid"] for e in events if e["native"] and e["event"] == "Marker"
and e["data"].get("Name") == "ProbeBegin")
checks = {
"probe_exit_success": manifest.get("ProbeExitCode") == 0,
"probe_self_checks": "P1Probe exact=OK" in log and "journal-pages=128 nat-arp-replies=32" in log,
"trace_requested_and_enabled": "trace-requested=1 trace-enabled=1" in log,
"probe_hash_unchanged": sha256(Path(manifest["Probe"])) == manifest["ProbeSHA256"],
"probe_pdb_present_and_unchanged": bool(manifest.get("ProbePDBSHA256")) and
sha256(Path(manifest["ProbePDB"])) == manifest["ProbePDBSHA256"],
"etl_decoded_without_loss": decoder.get("status") == 0
and decoder.get("events_lost") == 0 and decoder.get("buffers_lost") == 0
and decoder.get("native_decode_errors") == 0,
"qpc_frequency_agrees": decoder.get("qpc_frequency") == report["qpc_frequency"],
"arm_jit_mapping": any(e["native"] and e["event"] == "CodeMap"
and e["data"].get("Domain") == "ARM"
and e["data"].get("Kind") == "thumb" for e in events),
"nested_scope_consistency": report["scope_samples"] >= 128 and
report["accounting_errors"] == 0,
"no_counter_or_snapshot_regression": not report["counter_regressions"] and
not report["snapshot_regressions"],
"reset_distinct_generation": len(report["core_generations"]) >= 2,
"journal_exact": counters.get((worker, 0)) == 128 and
counters.get((worker, 1)) == 128 * (12 + 4 + 0x840 + 20) and
counters.get((worker, 2)) == 0,
"local_nat_exact": counters.get((worker, 3)) == 32 and
counters.get((worker, 5)) == 32 and
counters.get((worker, 7)) == 0 and
counters.get((worker, 8)) == 32 and
counters.get((worker, 10)) == 0 and
report["usb_queue_events"] >= 64,
}
system_checks = {
"arm_cpu_sample": report["cpu_leaf_samples"].get("ARM", 0) > 0,
"known_sleep_classified_waiting": bool(report["known_sleep"] and
report["known_sleep"]["wait_evidence_present"]),
"xperf_clock_and_target_events": xperf.get("anchors", 0) >= 2 and
xperf.get("max_anchor_error_qpc", float("inf")) <=
report["qpc_frequency"] / 100_000 and
xperf.get("xperf_invalid_target_events") == 0,
}
return {
"schema": 1, "local_provider_passed": all(checks.values()),
"full_collector_passed": all(checks.values()) and all(system_checks.values()),
"native_update_ready": False, "provider_checks": checks,
"system_checks": system_checks,
"remaining": ["Qualify real PPC JIT workload and native C++ stacks",
"Quantify full collector overhead on alternating fixed-work runs",
"Validate CPU domain coverage and critical path on a native trace"],
"analysis": report,
}
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("capture", type=Path)
parser.add_argument("--events", type=Path,
help="Combined native and xperf JSONL; defaults to capture/events.jsonl")
parser.add_argument("--xperf-summary", type=Path,
help="Summary from xperf_to_p1.py for the same combined events")
parser.add_argument("--output", type=Path,
help="New qualification JSON path; defaults to capture/qualification.json")
args = parser.parse_args()
result = qualify(args.capture, args.events, args.xperf_summary)
output = args.output or args.capture / "qualification.json"
with output.open("x", encoding="utf-8") as target:
json.dump(result, target, indent=2)
print(json.dumps({"local_provider_passed": result["local_provider_passed"],
"full_collector_passed": result["full_collector_passed"],
"provider_checks": result["provider_checks"],
"system_checks": result["system_checks"], "output": str(output)}, indent=2))
raise SystemExit(0 if result["local_provider_passed"] else 1)
@@ -0,0 +1,100 @@
"""Summarize CPU leaf samples per thread from an already-aligned P1 capture.
These are sample counts, not exact CPU times or a critical-path attribution.
"""
import argparse
from collections import Counter, defaultdict
import json
from pathlib import Path
from analyze_p1 import percentile
def summarize(path, pid):
by_thread = defaultdict(Counter)
processors = defaultdict(Counter)
sample_begin = None
sample_end = None
with path.open(encoding="utf-8") as source:
for line in source:
event = json.loads(line)
if event["native"] or event["pid"] != pid or event["event"] != "SampledProfile":
continue
data = event["data"]
tid = int(data["ThreadId"])
weight = int(data.get("Count", 1))
by_thread[tid][data.get("Symbol", "") or "<unresolved>"] += weight
processors[tid][int(data["Processor"])] += weight
sample_begin = event["qpc"] if sample_begin is None else min(sample_begin, event["qpc"])
sample_end = event["qpc"] if sample_end is None else max(sample_end, event["qpc"])
if sample_begin is None:
raise ValueError("No target CPU samples in the selected window")
frequency = None
previous_frame = {}
frame_deltas = defaultdict(list)
snapshots = {}
with path.open(encoding="utf-8") as source:
for line in source:
event = json.loads(line)
if not event["native"] or event["pid"] != pid:
continue
qpc = event["qpc"]
if not sample_begin <= qpc <= sample_end:
continue
data = event["data"]
if event["event"] == "Marker" and data["Name"] == "PerformanceMetricsReset":
previous_frame.clear()
elif event["event"] == "Frame":
if frequency is None:
frequency = int(data["QPCFrequency"])
elif frequency != int(data["QPCFrequency"]):
raise ValueError("Inconsistent frame QPC frequency")
kind = data["Kind"]
if kind in previous_frame:
frame_deltas[kind].append(1000 * (qpc - previous_frame[kind]) / frequency)
previous_frame[kind] = qpc
elif event["event"] == "Snapshot":
core = int(data["CoreId"])
if core not in snapshots:
snapshots[core] = [data, data]
else:
snapshots[core][1] = data
frames = {kind: {"intervals": len(deltas), "p50_ms": percentile(deltas, .5),
"p95_ms": percentile(deltas, .95), "p99_ms": percentile(deltas, .99)}
for kind, deltas in frame_deltas.items()}
return {
"pid": pid,
"sample_count": sum(sum(symbols.values()) for symbols in by_thread.values()),
"sample_window_qpc": {"begin": sample_begin, "end": sample_end,
"duration_seconds": (sample_end - sample_begin) / frequency
if frequency else None},
"frame_intervals_in_sample_window": frames,
"snapshot_deltas_in_sample_window": {
str(core): {field: last[field] - first[field]
for field in ("Instructions", "NativeInstructions", "SlowReads",
"SlowWrites", "Compiles", "Fallbacks")}
for core, (first, last) in snapshots.items()
},
"note": "Leaf sample counts and host frame intervals within the same selected window; no exact CPU duration or critical-path claim.",
"threads": [
{"tid": tid, "samples": sum(symbols.values()),
"processors": dict(sorted(processors[tid].items())),
"top_symbols": [{"symbol": symbol, "samples": count}
for symbol, count in symbols.most_common(12)]}
for tid, symbols in sorted(by_thread.items(),
key=lambda item: -sum(item[1].values()))
],
}
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("events", type=Path)
parser.add_argument("--pid", required=True, type=int)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
result = summarize(args.events, args.pid)
with args.output.open("x", encoding="utf-8") as target:
json.dump(result, target, indent=2)
print(f"{result['sample_count']} CPU samples from {len(result['threads'])} threads")
+195
View File
@@ -0,0 +1,195 @@
import unittest
import json
from pathlib import Path
import tempfile
from analyze_p1 import CodeMap, SampledCodeMap, analyze, percentile, read_relevant_events
from xperf_to_p1 import convert, parse_pid
class AnalysisTests(unittest.TestCase):
def test_temporal_address_reuse(self):
m = CodeMap()
def event(begin, end, kind, pc=0):
m.event(dict(Begin=begin, End=end, Kind=kind, GuestPC=pc, Domain="ARM"))
event(100, 200, "thumb", 4)
self.assertEqual(m.lookup(125), ("ARM", 4))
event(120, 180, "invalidate")
self.assertEqual(m.lookup(125)[0], "UnresolvedNative")
self.assertEqual(m.lookup(190), ("ARM", 4))
event(120, 180, "thumb", 8)
self.assertEqual(m.lookup(125), ("ARM", 8))
m.event(dict(Begin=100, End=200, Kind="block-near", GuestPC=0x8000, Domain="PPC"))
self.assertEqual(m.lookup(125), ("PPC", 0x8000))
self.assertEqual(m.lookup(190), ("PPC", 0x8000))
def test_invalid_range(self):
with self.assertRaises(ValueError):
CodeMap().event(dict(Begin=10, End=9))
def test_sampled_map_preserves_temporal_overlap_semantics(self):
sampled = SampledCodeMap([125, 190, 250])
sampled.event(dict(Begin=100, End=200, Kind="thumb", Domain="ARM", GuestPC=4))
self.assertEqual(sampled.lookup(125), ("ARM", 4))
sampled.event(dict(Begin=120, End=180, Kind="invalidate", Domain="ARM", GuestPC=0))
self.assertEqual(sampled.lookup(125), ("UnresolvedNative", None))
self.assertEqual(sampled.lookup(190), ("ARM", 4))
sampled.event(dict(Begin=120, End=180, Kind="thumb", Domain="ARM", GuestPC=8))
self.assertEqual(sampled.lookup(125), ("ARM", 8))
self.assertEqual(sampled.lookup(250), ("UnresolvedNative", None))
def test_percentiles_are_frame_intervals(self):
self.assertEqual(percentile([10, 20, 30], .5), 20)
self.assertIsNone(percentile([], .5))
def test_missing_telemetry_rejected(self):
with self.assertRaises(ValueError):
analyze([], 12)
def test_unknown_schema_rejected(self):
with self.assertRaises(ValueError):
analyze([dict(native=True, pid=12, tid=1, qpc=0, data=dict(Schema=99))], 12)
@staticmethod
def native(event, qpc, **data):
return dict(native=True, pid=12, tid=1, qpc=qpc, event=event, data=dict(Schema=1, **data))
def test_exclusive_accounting_does_not_sum_inclusive_regions(self):
rows = [self.native("Marker", 0, QPCFrequency=1000, Name="ProbeBegin")]
for region, inclusive, exclusive in ((0, 100, 20), (1, 80, 50), (6, 30, 30)):
rows.append(self.native("ScopeSample", 100, Region=region, Sample=1,
SamplingDenominator=1, Calls=1, AccountingErrors=0,
InclusiveQPC=inclusive, ExclusiveQPC=exclusive))
result = analyze(rows, 12)
self.assertEqual(result["accounting_errors"], 0)
rows[-1]["data"]["ExclusiveQPC"] = 31
self.assertEqual(analyze(rows, 12)["accounting_errors"], 1)
def test_frames_do_not_bridge_reset(self):
rows = [self.native("Marker", 0, QPCFrequency=1000, Name="ProbeBegin")]
for t in (10, 20):
rows.append(self.native("Frame", t, QPC=t, Kind="produced"))
rows.append(self.native("Marker", 100, Name="PerformanceMetricsReset"))
for t in (1000, 1010):
rows.append(self.native("Frame", t, QPC=t, Kind="produced"))
self.assertEqual(analyze(rows, 12)["frame_intervals"]["produced"],
dict(intervals=2, p50_ms=10, p95_ms=10, p99_ms=10))
def test_counter_regression_fails_even_with_good_scopes(self):
rows = [self.native("Marker", 0, QPCFrequency=1000, Name="ProbeBegin"),
self.native("Counter", 1, Counter=0, Value=5),
self.native("Counter", 2, Counter=0, Value=4)]
self.assertEqual(len(analyze(rows, 12)["counter_regressions"]), 1)
def test_kernel_sample_and_known_sleep_are_separate_evidence(self):
rows = [self.native("Marker", 0, QPCFrequency=1000, Name="ProbeBegin"),
self.native("CodeMap", 1, Begin=100, End=200, Domain="ARM",
GuestPC=4, Kind="thumb"),
dict(native=False, pid=0, tid=0, qpc=10, event="SampledProfile",
data=dict(ThreadId=1, InstructionPointer=125)),
self.native("Marker", 20, Name="KnownSleepBegin"),
dict(native=False, pid=0, tid=0, qpc=30, event="CSwitch",
data=dict(OldThreadId=1, NewThreadId=2, OldThreadState=5)),
self.native("Marker", 800, Name="KnownSleepEnd")]
result = analyze(rows, 12)
self.assertEqual(result["cpu_leaf_samples"], {"ARM": 1})
self.assertEqual(result["hot_generated_pcs"][0]["pc"], "0x4")
self.assertTrue(result["known_sleep"]["wait_evidence_present"])
self.assertEqual(result["known_sleep"]["wall_ms"], 780)
def test_jit_sample_after_invalidation_is_not_attributed_to_old_block(self):
rows = [self.native("Marker", 0, QPCFrequency=1000, Name="ProbeBegin"),
self.native("CodeMap", 1, Begin=100, End=200, Domain="ARM",
GuestPC=4, Kind="thumb"),
dict(native=False, pid=0, tid=1, qpc=2, event="SampledProfile",
data=dict(InstructionPointer=125)),
self.native("CodeMap", 3, Begin=100, End=200, Domain="ARM",
GuestPC=0, Kind="invalidate"),
dict(native=False, pid=0, tid=1, qpc=4, event="SampledProfile",
data=dict(InstructionPointer=125))]
self.assertEqual(analyze(rows, 12)["cpu_leaf_samples"],
{"ARM": 1, "UnresolvedNative": 1})
def test_static_module_is_not_mistaken_for_unmapped_jit(self):
rows = [self.native("Marker", 0, QPCFrequency=1000, Name="ProbeBegin"),
dict(native=False, pid=12, tid=1, qpc=1, event="SampledProfile",
data=dict(ThreadId=1, InstructionPointer=999, Count=3,
Symbol="TraceProbeP1.exe!IOS::LLE::ARMCore::Read32"))]
report = analyze(rows, 12)
self.assertEqual(report["cpu_leaf_samples"], {"HostC++": 3})
self.assertEqual(report["hot_static_symbols"][0]["samples"], 3)
def test_xperf_classic_events_align_to_native_qpc(self):
native = [self.native("Marker", 1001000, QPCFrequency=10000000, Name="ProbeBegin"),
self.native("CodeMap", 1001500, Begin=100, End=200, Domain="ARM",
GuestPC=4, Kind="thumb"),
self.native("Marker", 1011000, Name="KnownSleepBegin"),
self.native("Marker", 1111000, Name="KnownSleepEnd")]
rows = [["Dolphin.Performance/Marker/", "100000", "TraceProbeP1.exe (12)",
"1"] + [""] * 8 + ["ProbeBegin"],
["Dolphin.Performance/Marker/", "101000", "TraceProbeP1.exe (12)",
"1"] + [""] * 8 + ["KnownSleepBegin"],
["Dolphin.Performance/Marker/", "111000", "TraceProbeP1.exe (12)",
"1"] + [""] * 8 + ["KnownSleepEnd"],
["SampledProfile", "100100", "TraceProbeP1.exe (12)", "1",
"0x7d", "0", "", "", "2", "Unbatched"],
["CSwitch", "101100", "Idle (0)", "2", "", "", "", "",
"TraceProbeP1.exe (12)", "1", "", "", "Waiting"]]
merged, summary = convert(rows, native, 12)
report = analyze(merged, 12)
self.assertEqual(summary["max_anchor_error_qpc"], 0)
self.assertEqual(summary["cpu_sample_count"], 2)
self.assertEqual(summary["cpu_samples_by_processor"], {0: 2})
self.assertEqual(report["cpu_leaf_samples"], {"ARM": 2})
self.assertTrue(report["known_sleep"]["wait_evidence_present"])
self.assertEqual(parse_pid("Idle ( 0)"), 0)
def test_xperf_snapshots_align_without_named_markers(self):
native = [self.native("Snapshot", 1001000, QPC=1000999,
QPCFrequency=10000000, CoreId=1),
self.native("Snapshot", 2001000, QPC=2000999,
QPCFrequency=10000000, CoreId=1)]
def snapshot(us, payload_qpc):
row = ["Dolphin.Performance/Snapshot/", str(us), "DolphinNoGUI.exe (12)",
"1"] + [""] * 8
row[10] = str(payload_qpc)
return row
rows = [snapshot(100000, 1000999), snapshot(200000, 2000999),
["SampledProfile", "150000", "DolphinNoGUI.exe (12)", "1",
"0x7d", "0", "", "", "2", "DolphinNoGUI.exe!ARMCore::Run"]]
merged, summary = convert(rows, native, 12)
self.assertEqual(summary["anchors"], 2)
self.assertEqual(summary["max_anchor_error_qpc"], 0)
self.assertEqual(summary["cpu_sample_count"], 2)
self.assertEqual(merged[1]["qpc"], 1501000)
def test_uninstrumented_process_thread_is_counted(self):
native = [self.native("Snapshot", 1001000, QPC=1000999,
QPCFrequency=10000000, CoreId=1, Instructions=1,
NativeInstructions=1, SlowReads=0, SlowWrites=0,
Compiles=0, Fallbacks=0),
self.native("Snapshot", 2001000, QPC=2000999,
QPCFrequency=10000000, CoreId=1, Instructions=2,
NativeInstructions=2, SlowReads=0, SlowWrites=0,
Compiles=0, Fallbacks=0)]
rows = []
for us, payload in ((100000, 1000999), (200000, 2000999)):
row = ["Dolphin.Performance/Snapshot/", str(us), "DolphinNoGUI.exe (12)",
"1"] + [""] * 8
row[10] = str(payload)
rows.append(row)
rows.append(["SampledProfile", "150000", "DolphinNoGUI.exe (12)", "9",
"0x7d", "0", "", "DolphinNoGUI.exe!Render", "3", "Unbatched"])
merged, summary = convert(rows, native, 12)
self.assertEqual(summary["cpu_sample_threads"], 1)
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "events.jsonl"
path.write_text("".join(json.dumps(event) + "\n" for event in merged),
encoding="utf-8")
report = analyze(read_relevant_events(path, 12), 12)
self.assertEqual(report["native_threads"], [1])
self.assertEqual(report["sampled_process_threads"], [9])
self.assertEqual(report["hot_static_symbols"][0]["samples"], 3)
if __name__ == "__main__":
unittest.main()
+45
View File
@@ -0,0 +1,45 @@
import unittest
from unittest.mock import patch
from compare_p1 import compare
class ComparisonTests(unittest.TestCase):
@staticmethod
def runs(on_mode, on_multiplier=1.01, off_values=(100, 100, 100, 100)):
result = []
for index, off in enumerate(off_values):
for mode, value in (("NoTrace", off), (on_mode, off * on_multiplier)):
result.append(dict(directory=f"run-{index}-{mode}", collection=mode,
hash="same-exe", pdb_hash="same-pdb",
affinity_mask=15, observed_affinity_mask=15, arm_ms=value,
wall_ms=value * 1.2, cpu_ms=value * .95))
return result
def test_repeated_low_noise_wpr_pairs_can_pass_local_budget(self):
runs = self.runs("WPRSystemAndNative")
with patch("compare_p1.load", side_effect=runs):
report = compare(list(range(len(runs))))
self.assertTrue(report["two_percent_budget_qualified"])
self.assertAlmostEqual(report["upper_95_percent"]["arm_phase_percent"], 1)
def test_private_logger_never_qualifies_full_wpr_budget(self):
runs = self.runs("PrivateUserMode")
with patch("compare_p1.load", side_effect=runs):
self.assertFalse(compare(list(range(len(runs))))["two_percent_budget_qualified"])
def test_large_baseline_spread_keeps_budget_unqualified(self):
runs = self.runs("WPRSystemAndNative", off_values=(100, 104, 100, 104))
with patch("compare_p1.load", side_effect=runs):
self.assertFalse(compare(list(range(len(runs))))["two_percent_budget_qualified"])
def test_mismatched_affinity_rejected(self):
runs = self.runs("WPRSystemAndNative")
runs[3]["observed_affinity_mask"] = 255
with patch("compare_p1.load", side_effect=runs):
with self.assertRaisesRegex(ValueError, "affinity"):
compare(list(range(len(runs))))
if __name__ == "__main__":
unittest.main()
+134
View File
@@ -0,0 +1,134 @@
"""Merge xperf's classic kernel events with native TDH events on their QPC clock.
TDH may return ERROR_NOT_FOUND for classic kernel schemas on the analysis host.
Xperf can still decode those MOF events from the same ETL. This is an offline
adapter only: it never qualifies a native Wii update on its own.
"""
import argparse
from collections import Counter
import csv
import json
from pathlib import Path
import re
import statistics
def parse_pid(label):
match = re.search(r"\(\s*(\d+)\s*\)$", label.strip())
return int(match.group(1)) if match else None
def convert(rows, native, pid):
native_markers = {e["data"]["Name"]: e["qpc"] for e in native
if e["native"] and e["pid"] == pid and e["event"] == "Marker"}
native_payload_qpc = {
(e["event"], int(e["data"]["QPC"])): e["qpc"] for e in native
if e["native"] and e["pid"] == pid and e["event"] in ("Marker", "Snapshot", "Frame")
and "QPC" in e["data"]
}
frequencies = {e["data"]["QPCFrequency"] for e in native
if e["native"] and e["pid"] == pid and "QPCFrequency" in e["data"]}
if len(frequencies) != 1:
raise ValueError("Missing or inconsistent native QPC frequency")
frequency = frequencies.pop()
native_tids = {e["tid"] for e in native if e["native"] and e["pid"] == pid}
if not native_tids:
raise ValueError("No native threads for requested PID")
# Xperf timestamps are trace-relative microseconds. Match the QPC payload
# of periodic native events to their TDH event-header QPC. A real Dolphin
# run need not emit two named markers, but normally emits many snapshots.
anchors = []
raw_samples = []
raw_switches = []
invalid_events = 0
invalid_target_events = 0
for row in rows:
if len(row) < 2:
continue
kind = row[0].strip()
if kind.startswith("InvalidEvent/"):
invalid_events += 1
if len(row) > 2 and parse_pid(row[2]) == pid:
invalid_target_events += 1
if not row[1].strip().isdigit(): # xperf's per-event header line
continue
if kind in ("Dolphin.Performance/Marker/", "Dolphin.Performance/Snapshot/",
"Dolphin.Performance/Frame/") and len(row) >= 12 and parse_pid(row[2]) == pid:
event = kind.split("/")[1]
payload_qpc = row[10].strip()
if payload_qpc.isdigit() and (event, int(payload_qpc)) in native_payload_qpc:
anchors.append((int(row[1]), native_payload_qpc[(event, int(payload_qpc))],
f"{event}:{payload_qpc}"))
elif event == "Marker" and len(row) >= 13:
# Older synthetic captures also support named-marker matching.
name = row[-1].strip()
if name in native_markers:
anchors.append((int(row[1]), native_markers[name], name))
elif kind == "SampledProfile" and len(row) >= 9 and parse_pid(row[2]) == pid:
tid = int(row[3])
# Xperf does not CSV-quote C++ template commas in symbol names.
# Count/type are the final two columns; rejoin the leaf symbol.
# All threads of this PID matter: GPU/network threads may be hot
# without ever emitting a native Dolphin.Performance event.
raw_samples.append((int(row[1]), tid, int(row[4], 16), int(row[5]),
int(row[-2]), ",".join(row[7:-2]).strip()))
elif kind == "CSwitch" and len(row) >= 13:
old_tid, new_tid = int(row[9]), int(row[3])
if (old_tid in native_tids or new_tid in native_tids or
parse_pid(row[2]) == pid or parse_pid(row[8]) == pid):
raw_switches.append((int(row[1]), old_tid, new_tid, row[12].strip()))
if len(anchors) < 2:
raise ValueError("Need at least two matching native/xperf QPC anchors")
scale = frequency / 1_000_000
offset = statistics.median(qpc - us * scale for us, qpc, _ in anchors)
max_anchor_error = max(abs(round(us * scale + offset) - qpc) for us, qpc, _ in anchors)
if max_anchor_error > frequency / 100_000: # More than 10 microseconds.
raise ValueError(f"Native/xperf clocks do not agree: {max_anchor_error} QPC ticks")
def qpc(us):
return round(us * scale + offset)
system = [dict(native=False, event="SampledProfile", qpc=qpc(us), pid=pid, tid=tid,
data=dict(ThreadId=tid, InstructionPointer=ip, Processor=processor,
Count=count, Symbol=symbol))
for us, tid, ip, processor, count, symbol in raw_samples]
system.extend(dict(native=False, event="CSwitch", qpc=qpc(us), pid=0, tid=0,
data=dict(OldThreadId=old_tid, NewThreadId=new_tid,
OldThreadState=5 if state == "Waiting" else -1,
OldState=state))
for us, old_tid, new_tid, state in raw_switches)
samples_by_processor = Counter()
for _, _, _, processor, count, _ in raw_samples:
samples_by_processor[processor] += count
summary = dict(schema=1, pid=pid, qpc_frequency=frequency, anchors=len(anchors),
max_anchor_error_qpc=max_anchor_error, cpu_sample_records=len(raw_samples),
cpu_sample_count=sum(count for _, _, _, _, count, _ in raw_samples),
cpu_sample_threads=len({tid for _, tid, _, _, _, _ in raw_samples}),
cpu_samples_by_processor=dict(sorted(samples_by_processor.items())),
context_switches=len(raw_switches), xperf_invalid_events=invalid_events,
xperf_invalid_target_events=invalid_target_events,
note="Classic kernel events decoded by xperf; invalid events and missing symbols remain separate quality gates.")
return sorted(native + system, key=lambda e: e["qpc"]), summary
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("xperf_csv", type=Path)
parser.add_argument("native_jsonl", type=Path)
parser.add_argument("--pid", required=True, type=int)
parser.add_argument("--output", required=True, type=Path)
parser.add_argument("--summary", required=True, type=Path)
args = parser.parse_args()
with args.native_jsonl.open(encoding="utf-8") as source:
native_events = [json.loads(line) for line in source]
with args.xperf_csv.open(encoding="utf-8", errors="replace", newline="") as source:
events, result = convert(csv.reader(source, skipinitialspace=True), native_events, args.pid)
with args.output.open("x", encoding="utf-8") as target:
for event in events:
target.write(json.dumps(event, separators=(",", ":")) + "\n")
with args.summary.open("x", encoding="utf-8") as target:
json.dump(result, target, indent=2)
print(json.dumps(result, indent=2))
@@ -0,0 +1,30 @@
/* Copyright 2026 Dolphin Emulator Project */
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
* StarletBootstrapProbe's Broadway client (ProbeBroadway.h): StarOS's loader header board.h as the
* vendored loader sources in ../StarOSLoader see it on a host. Every word access goes to
* ProbeBroadway.cpp, which allows only the bench window of PPC memory; sync is nothing in
* Dolphin's coherent memory; the timebase is the client's, 243 MHz / 4 from the Starlet's cycles.
*/
#ifndef STAROS_LOADER_BOARD_H
#define STAROS_LOADER_BOARD_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
uint32_t read32(uint32_t address);
void write32(uint32_t address, uint32_t value);
void sync(void);
uint64_t timebase(void);
/* StarOS boot/wii/loader/board.h's: timebase ticks a millisecond. */
#define TICKS_PER_MS 60750u
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,27 @@
/* Copyright 2026 Dolphin Emulator Project */
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
* StarletBootstrapProbe's Broadway client (ProbeBroadway.h): StarOS's loader header gecko.h as the
* vendored loader sources see it on a host. The lines go to the client's capture, which the probe
* prints on stdout, in the formats of StarOS boot/wii/loader/gecko.c (hex: 0x and eight lowercase
* digits; decimal: no leading zero).
*/
#ifndef STAROS_LOADER_GECKO_H
#define STAROS_LOADER_GECKO_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
void gecko_puts(const char *text);
void gecko_hex(uint32_t value);
void gecko_dec(uint32_t value);
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,185 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "ProbeBroadway.h"
#include <cstdint>
#include <optional>
#include <fmt/format.h>
#include "ProbeBroadwaySources.h"
extern "C" {
#include "hw0c.h"
}
namespace StarletBootstrapProbe
{
namespace
{
// The one HAL of the process: the vendored sources' functions are global, so is their HAL.
std::optional<BroadwayHal> s_hal;
} // namespace
bool BroadwayHal::Allowed(u32 address, std::string_view what)
{
++m_accesses;
if (InBenchWindow(address))
return true;
if (m_failure.empty())
{
m_failure = fmt::format("{} at {:#010x}, outside the bench window {:#010x}..{:#010x}", what,
address, BENCH_WINDOW_BASE, BENCH_WINDOW_END);
}
return false;
}
u32 BroadwayHal::Read(u32 address)
{
return Allowed(address, "a read") ? m_memory.LoadWord(address) : 0;
}
void BroadwayHal::Write(u32 address, u32 value)
{
if (Allowed(address, "a write"))
m_memory.StoreWord(address, value);
}
void BroadwayHal::CacheLine(u32 address)
{
// The line's first word stands for it: the loader passes line-aligned window addresses.
Allowed(address & ~u32{3}, "a cache line");
}
void BroadwayHal::Hex(u32 value)
{
m_capture += fmt::format("0x{:08x}", value);
}
void BroadwayHal::Dec(u32 value)
{
m_capture += fmt::format("{}", value);
}
bool BroadwayClient::Start(BroadwayMemory& memory)
{
if (s_hal)
{
m_refusal = "a Broadway client already started in this process: the loader's state is global";
return false;
}
s_hal.emplace(memory, CLIENT_TIMEBASE_BASE);
m_started = true;
// As the loader before the jump: the window's sentinel and control lines, HW-M4-0D's area, H-1A's
// pages and record, the plan and the header's magic last.
hw0c_setup();
return true;
}
void BroadwayClient::Advance(u64 elapsed)
{
if (!m_started || m_done || Failed())
return;
s_hal->Elapse(elapsed);
++m_steps;
m_done = hw0c_step(s_hal->Timebase()) != 0;
}
bool BroadwayClient::Failed() const
{
return !m_refusal.empty() || (m_started && s_hal->Failed());
}
std::string BroadwayClient::Failure() const
{
if (!m_refusal.empty())
return m_refusal;
return m_started ? s_hal->Failure() : std::string{};
}
u64 BroadwayClient::Timebase() const
{
return m_started ? s_hal->Timebase() : 0;
}
std::string BroadwayClient::Report(std::string_view status)
{
if (!m_started || m_reported)
return {};
m_reported = true;
const size_t mark = s_hal->Capture().size();
hw0c_report();
return fmt::format("{}\n{}{}\n", status, s_hal->Capture().substr(mark), CLIENT_END);
}
std::string_view BroadwayClient::Sources()
{
return STAROS_LOADER_SHA256;
}
} // namespace StarletBootstrapProbe
// The HAL's C functions (BroadwayHAL/board.h and gecko.h, and the cache and special-register
// functions the vendored sources declare under their _HOST macros).
extern "C" {
uint32_t read32(uint32_t address)
{
return StarletBootstrapProbe::s_hal ? StarletBootstrapProbe::s_hal->Read(address) : 0;
}
void write32(uint32_t address, uint32_t value)
{
if (StarletBootstrapProbe::s_hal)
StarletBootstrapProbe::s_hal->Write(address, value);
}
void sync(void)
{
}
uint64_t timebase(void)
{
return StarletBootstrapProbe::s_hal ? StarletBootstrapProbe::s_hal->Timebase() : 0;
}
void dcbf(uint32_t address)
{
if (StarletBootstrapProbe::s_hal)
StarletBootstrapProbe::s_hal->CacheLine(address);
}
void dcbi(uint32_t address)
{
if (StarletBootstrapProbe::s_hal)
StarletBootstrapProbe::s_hal->CacheLine(address);
}
// Not a Broadway: HID0 and L2CR, which hw0c.c only reports, read as 0.
uint32_t hid0(void)
{
return 0;
}
uint32_t l2cr(void)
{
return 0;
}
void gecko_puts(const char* text)
{
if (StarletBootstrapProbe::s_hal)
StarletBootstrapProbe::s_hal->Put(text);
}
void gecko_hex(uint32_t value)
{
if (StarletBootstrapProbe::s_hal)
StarletBootstrapProbe::s_hal->Hex(value);
}
void gecko_dec(uint32_t value)
{
if (StarletBootstrapProbe::s_hal)
StarletBootstrapProbe::s_hal->Dec(value);
}
}
+145
View File
@@ -0,0 +1,145 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <string>
#include <string_view>
#include "Common/CommonTypes.h"
#include "StarOSPanicCheck.h"
// StarletBootstrapProbe's --broadway-h1a: the probe stands in for Broadway with StarOS's own bench
// loader code, so that the H-1A bench (StarOS docs/architecture/h-1a.md, D-H1A-7) runs whole: its
// Starlet image here, on the ARM core; its Broadway side, StarOS's boot/wii/loader hw0c.c, hw0d.c
// and h1a.c, vendored unchanged in StarOSLoader/ and built over the host HAL of BroadwayHAL/.
//
// The client does what StarOS's loader does around the jump: hw0c_setup() before the Starlet's
// first instruction, then one hw0c_step() between each two slices, as the loader's monitor calls
// it, until it says 1; then the report, between the status and END lines main.c prints. It reaches
// PPC memory only in the bench window, by whole words; it knows nothing of the image and answers
// nothing for it: what it reads, the ARM code wrote. Dolphin's memory is coherent, so the run says
// nothing of the console's caches: it rehearses the protocol, its 3000 rounds, the capture and the
// judge, not the hardware.
namespace StarletBootstrapProbe
{
// The bench window, StarOS boot/contract/staros_hw0c.h's STAROS_HW0C_BASE and _SIZE: the only PPC
// memory the client reads or writes.
constexpr u32 BENCH_WINDOW_BASE = 0x13500000;
// Exclusive.
constexpr u32 BENCH_WINDOW_END = 0x13510000;
// Broadway's timebase runs at 243 MHz / 4, the Starlet at 243 MHz: four cycles a tick.
constexpr u64 CYCLES_PER_TIMEBASE_TICK = 4;
// The client's first timebase. Any value would do (the loader only subtracts); a nonzero one wider
// than 32 bits keeps the 64-bit arithmetic honest.
constexpr u64 CLIENT_TIMEBASE_BASE = u64{1} << 32;
// The lines StarOS's main.c prints around hw0c_report(): its status line once the Starlet is done
// or timed out, and its END line. There is no Gecko here, so nothing was dropped.
constexpr std::string_view CLIENT_STATUS_DONE = "SBL:STARLET DONE";
constexpr std::string_view CLIENT_STATUS_TIMEOUT = "SBL:TIMEOUT";
constexpr std::string_view CLIENT_END = "SBL:END GECKO DROPPED AFTER JUMP 0 BEFORE 0";
// Whether StarOS's loader would take the Starlet for done, as main.c's monitor does: the SBR1
// record's state IDLE or after, with EXI given back to Broadway. The client's mode takes
// --sbr1-record so that the record is there. The trace's own terminal line also counts; it can be
// missing, the trace holding 1 KiB, which H-1A's image fills before its IDLE line.
constexpr bool StarletDone(bool trace_terminal, u32 sbr1_state, u32 sbr1_exi_owner)
{
return trace_terminal || (sbr1_state >= SBR1_STATE_IDLE && sbr1_exi_owner == SBR1_EXI_PPC);
}
// Whether --broadway-h1a is among the probe's options (argv[2] on), read with their grammar: the
// word after --ipc-script, --stage-spk or --cycles is that option's value, never an option. It
// raises --cycles' bound, which is read where it stands, before the other options are known.
inline bool ClientRequested(int argc, const char* const* argv)
{
for (int index = 2; index < argc; ++index)
{
const std::string_view option = argv[index];
if (option == "--ipc-script" || option == "--stage-spk" || option == "--cycles")
++index;
else if (option == "--broadway-h1a")
return true;
}
return false;
}
// Whether a whole word at `address` lies in the bench window.
constexpr bool InBenchWindow(u64 address)
{
return address >= BENCH_WINDOW_BASE && address + 4 <= BENCH_WINDOW_END && address % 4 == 0;
}
// What the client reaches: PPC memory, by whole words.
class BroadwayMemory
{
public:
virtual ~BroadwayMemory() = default;
virtual u32 LoadWord(u32 address) = 0;
virtual void StoreWord(u32 address, u32 word) = 0;
};
// The HAL the vendored loader sources call (BroadwayHAL/board.h and gecko.h): the window's bounds,
// the clock and the capture. A word outside the window is never touched: the first such access
// fails the client, and a read gives 0.
class BroadwayHal
{
public:
BroadwayHal(BroadwayMemory& memory, u64 timebase) : m_memory(memory), m_timebase(timebase) {}
u32 Read(u32 address);
void Write(u32 address, u32 value);
// dcbf and dcbi: a line of the window; nothing to do in Dolphin's coherent memory.
void CacheLine(u32 address);
u64 Timebase() const { return m_timebase; }
// `cycles` Starlet cycles went by.
void Elapse(u64 cycles) { m_timebase += cycles / CYCLES_PER_TIMEBASE_TICK; }
void Put(std::string_view text) { m_capture += text; }
void Hex(u32 value);
void Dec(u32 value);
const std::string& Capture() const { return m_capture; }
u64 Accesses() const { return m_accesses; }
bool Failed() const { return !m_failure.empty(); }
const std::string& Failure() const { return m_failure; }
private:
bool Allowed(u32 address, std::string_view what);
BroadwayMemory& m_memory;
u64 m_timebase;
u64 m_accesses = 0;
std::string m_capture;
std::string m_failure;
};
// The client. The vendored sources keep their state in globals, so a process has one client, and
// it starts once.
class BroadwayClient
{
public:
// hw0c_setup() over `memory`, at CLIENT_TIMEBASE_BASE; false, with the reason in Failure(), if a
// client already started in this process.
bool Start(BroadwayMemory& memory);
// `elapsed` Starlet cycles went by: one hw0c_step() at the timebase they make, unless done.
void Advance(u64 elapsed);
bool Started() const { return m_started; }
bool Done() const { return m_done; }
bool Failed() const;
std::string Failure() const;
u64 Steps() const { return m_steps; }
u64 Timebase() const;
// The capture main.c would print from its status line on: `status`, hw0c_report()'s lines
// (hw0d_report()'s and h1a_report()'s among them), the END line. Once.
std::string Report(std::string_view status);
// The vendored sources, as built: "<file> <sha256>" lines (CMake computes them at configure).
static std::string_view Sources();
private:
bool m_started = false;
bool m_done = false;
bool m_reported = false;
u64 m_steps = 0;
std::string m_refusal;
};
} // namespace StarletBootstrapProbe
+46
View File
@@ -0,0 +1,46 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <optional>
#include <string_view>
#include "Common/CommonTypes.h"
// How long StarletBootstrapProbe runs an image: whole slices of SLICE_CYCLES ARM cycles, between
// which it checks for a fault, a panic or a terminal trace line. --cycles <n> sets the budget;
// without it, the probe runs DEFAULT_CYCLES, as it always has. StarOS's EXP-003 images hash MEM2
// and time series of operations, which take more than that (StarOS
// experiments/proposals/mmu-console.md, P-7 and P-8).
namespace StarletBootstrapProbe
{
constexpr u32 SLICE_CYCLES = 4096;
constexpr u64 DEFAULT_CYCLES = 512 * SLICE_CYCLES;
// 2^30 cycles: 262,144 slices.
constexpr u64 MAX_CYCLES = u64{1} << 30;
// With --broadway-h1a only (ProbeBroadway.h): 2^34 cycles, about 70 s of the Starlet's 243 MHz.
// StarOS's H-1A bench runs 3000 rounds of Broadway's posts and the Starlet's answers, each at least
// Broadway's 2 ms between an answer and its next post, after the Starlet's wait for READY.
constexpr u64 MAX_CLIENT_CYCLES = u64{1} << 34;
// The budget --cycles asks for: a decimal number of cycles, a whole number of slices, from one
// slice to `max` (MAX_CYCLES, or MAX_CLIENT_CYCLES with the client). Anything else is refused
// (nullopt), never rounded.
inline std::optional<u64> ParseCycles(std::string_view text, u64 max = MAX_CYCLES)
{
// Twelve digits cannot overflow a u64; MAX_CLIENT_CYCLES has eleven.
if (text.empty() || text.size() > 12)
return std::nullopt;
u64 value = 0;
for (const char digit : text)
{
if (digit < '0' || digit > '9')
return std::nullopt;
value = value * 10 + static_cast<u64>(digit - '0');
}
if (value == 0 || value % SLICE_CYCLES != 0 || value > max)
return std::nullopt;
return value;
}
} // namespace StarletBootstrapProbe
+40
View File
@@ -0,0 +1,40 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <algorithm>
#include <functional>
#include <string>
#include <fmt/format.h>
#include "Common/CommonTypes.h"
#include "StarOSPanicCheck.h"
// The text of StarOS's SBR1 ring (StarOS crates/boot-contract, report.rs), which --sbr1-record
// prints after the run, as StarOS's Broadway loader prints it over the Gecko on the console
// (SBL:RING BEGIN/END). Bytes come through a callback, so the formatting is tested without a CPU.
namespace StarletBootstrapProbe
{
constexpr u32 SBR1_RING = 0x40;
constexpr u32 SBR1_RING_BYTES = SBR1_SIZE - SBR1_RING;
// The ring's first `length` bytes (at most SBR1_RING_BYTES), read at their record offsets. A
// byte outside printable ASCII and '\n', and the backslash itself, is written \xHH, so the text
// stays printable and reads back unambiguously.
inline std::string RingText(const std::function<u8(u32)>& read_byte, u32 length)
{
std::string text;
const u32 end = std::min(length, SBR1_RING_BYTES);
for (u32 index = 0; index < end; ++index)
{
const u8 byte = read_byte(SBR1_RING + index);
if (byte == '\n' || (byte >= 0x20 && byte < 0x7f && byte != '\\'))
text += static_cast<char>(byte);
else
text += fmt::format("\\x{:02x}", byte);
}
return text;
}
} // namespace StarletBootstrapProbe
+273
View File
@@ -0,0 +1,273 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <charconv>
#include <cstddef>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include <fmt/format.h>
#include "Common/CommonTypes.h"
// StarletBootstrapProbe's --ipc-script <file>: the probe stands in for Broadway (StarOS
// docs/contracts/hollywood-ipc-injection.md). A script is data: whole words stored in one range
// of PPC memory, the registers Broadway writes and reads, every wait bounded. It knows nothing of
// the code under test and answers nothing for it: what it reads back, the ARM code wrote.
namespace StarletBootstrapProbe
{
// The one range a script may store to or expect from: the 128 KiB below Broadway's boundary.
constexpr u32 IPC_RANGE_BASE = 0x135E0000;
// Exclusive.
constexpr u32 IPC_RANGE_END = 0x13600000;
constexpr u64 SCRIPT_MAX_BYTES = 64 * 1024;
constexpr size_t SCRIPT_MAX_STEPS = 256;
constexpr u64 SCRIPT_MAX_CYCLES = u64{1} << 30;
// Exit status of a run whose script is refused before StarOS starts (1: failed expectation,
// 2: usage, 3: Dolphin alert, 4: refused package file).
constexpr int SCRIPT_EXIT_STATUS = 5;
// The registers, as offsets from Hollywood's register page.
constexpr u32 IPC_PPCMSG = 0x00;
constexpr u32 IPC_PPCCTRL = 0x04;
constexpr u32 IPC_ARMMSG = 0x08;
// PPCCTRL's bits a write means: X1, Y2, Y1, X2, IY1, IY2.
constexpr u32 IPC_PPCCTRL_BITS = 0x3F;
enum class StepKind
{
Store,
PpcMsg,
PpcCtrl,
Wait,
ExpectArmMsg,
Expect,
Run
};
struct ScriptStep
{
StepKind kind;
int line;
u32 first;
u32 second;
u64 cycles;
};
// What a script reaches: PPC memory and the registers, nothing of the code under test.
class ScriptBus
{
public:
virtual ~ScriptBus() = default;
virtual void StoreWord(u32 address, u32 word) = 0;
virtual u32 LoadWord(u32 address) = 0;
virtual void WriteRegister(u32 offset, u32 value) = 0;
virtual u32 ReadRegister(u32 offset) = 0;
};
// A number, hexadecimal with 0x or decimal, whole: nothing else.
inline std::optional<u64> ParseScriptNumber(std::string_view text)
{
const bool hexadecimal = text.starts_with("0x");
if (hexadecimal)
text.remove_prefix(2);
if (text.empty())
return std::nullopt;
u64 value = 0;
const auto [end, status] =
std::from_chars(text.data(), text.data() + text.size(), value, hexadecimal ? 16 : 10);
if (status != std::errc{} || end != text.data() + text.size())
return std::nullopt;
return value;
}
// Whether a whole word at `address` lies in the range.
constexpr bool InIPCRange(u64 address)
{
return address >= IPC_RANGE_BASE && address + 4 <= IPC_RANGE_END && address % 4 == 0;
}
// The script's steps, or nullopt with the reason in `error`. Nothing is run.
inline std::optional<std::vector<ScriptStep>> ParseScript(std::string_view text, std::string* error)
{
const auto refuse = [error](int line, std::string_view why) {
*error = fmt::format("line {}: {}", line, why);
return std::nullopt;
};
std::vector<ScriptStep> steps;
int line_number = 0;
while (!text.empty())
{
++line_number;
const size_t end = text.find('\n');
std::string_view line = text.substr(0, end);
text = end == std::string_view::npos ? std::string_view{} : text.substr(end + 1);
line = line.substr(0, line.find('#'));
std::vector<std::string_view> words;
while (!line.empty())
{
const size_t start = line.find_first_not_of(" \t\r");
if (start == std::string_view::npos)
break;
line.remove_prefix(start);
const size_t stop = line.find_first_of(" \t\r");
words.push_back(line.substr(0, stop));
line = stop == std::string_view::npos ? std::string_view{} : line.substr(stop);
}
if (words.empty())
continue;
if (steps.size() == SCRIPT_MAX_STEPS)
return refuse(line_number, fmt::format("more than {} steps", SCRIPT_MAX_STEPS));
std::vector<u64> numbers;
for (size_t index = 1; index < words.size(); ++index)
{
const std::optional<u64> number = ParseScriptNumber(words[index]);
if (!number)
return refuse(line_number, fmt::format("not a number: {}", words[index]));
numbers.push_back(*number);
}
const auto operands = [&numbers](size_t count) { return numbers.size() == count; };
const auto word = [&numbers](size_t index) { return numbers[index] <= 0xFFFFFFFF; };
const auto cycles = [&numbers](size_t index) {
return numbers[index] != 0 && numbers[index] <= SCRIPT_MAX_CYCLES;
};
const std::string_view name = words[0];
ScriptStep step{StepKind::Run, line_number, 0, 0, 0};
if (name == "store" || name == "expect")
{
if (!operands(2) || !word(1))
return refuse(line_number, "takes an address and a word");
if (!InIPCRange(numbers[0]))
return refuse(line_number, "the address is not a whole word of the range");
step.kind = name == "store" ? StepKind::Store : StepKind::Expect;
step.first = static_cast<u32>(numbers[0]);
step.second = static_cast<u32>(numbers[1]);
}
else if (name == "ppcmsg" || name == "expect-armmsg")
{
// A register's value, in or out of the range: nothing is accessed through it here.
if (!operands(1) || !word(0))
return refuse(line_number, "takes one word");
step.kind = name == "ppcmsg" ? StepKind::PpcMsg : StepKind::ExpectArmMsg;
step.first = static_cast<u32>(numbers[0]);
}
else if (name == "ppcctrl")
{
if (!operands(1) || numbers[0] > IPC_PPCCTRL_BITS)
return refuse(line_number, "takes PPCCTRL's six bits");
step.kind = StepKind::PpcCtrl;
step.first = static_cast<u32>(numbers[0]);
}
else if (name == "wait")
{
if (!operands(3) || !word(0) || !word(1) || !cycles(2))
return refuse(line_number, "takes a mask, a value and a bound in cycles");
step.kind = StepKind::Wait;
step.first = static_cast<u32>(numbers[0]);
step.second = static_cast<u32>(numbers[1]);
step.cycles = numbers[2];
}
else if (name == "run")
{
if (!operands(1) || !cycles(0))
return refuse(line_number, "takes a number of cycles");
step.kind = StepKind::Run;
step.cycles = numbers[0];
}
else
{
return refuse(line_number, fmt::format("unknown step: {}", name));
}
steps.push_back(step);
}
return steps;
}
// Runs a script's steps in order, between the probe's slices.
class ScriptRunner
{
public:
explicit ScriptRunner(std::vector<ScriptStep> steps) : m_steps(std::move(steps)) {}
// `elapsed` ARM cycles went by: every step that can run now does, up to one that must wait.
void Advance(ScriptBus& bus, u64 elapsed)
{
m_waited += elapsed;
while (m_failure.empty() && m_next < m_steps.size())
{
const ScriptStep& step = m_steps[m_next];
switch (step.kind)
{
case StepKind::Store:
bus.StoreWord(step.first, step.second);
break;
case StepKind::PpcMsg:
bus.WriteRegister(IPC_PPCMSG, step.first);
break;
case StepKind::PpcCtrl:
bus.WriteRegister(IPC_PPCCTRL, step.first);
break;
case StepKind::Wait:
{
const u32 seen = bus.ReadRegister(IPC_PPCCTRL);
if ((seen & step.first) != step.second)
{
if (m_waited >= step.cycles)
Fail(step, fmt::format("PPCCTRL reads {:#x} after {} cycles", seen, m_waited));
return;
}
break;
}
case StepKind::ExpectArmMsg:
{
const u32 seen = bus.ReadRegister(IPC_ARMMSG);
if (seen != step.first)
return Fail(step, fmt::format("ARMMSG reads {:#x}, not {:#x}", seen, step.first));
break;
}
case StepKind::Expect:
{
const u32 seen = bus.LoadWord(step.first);
if (seen != step.second)
{
return Fail(step, fmt::format("the word at {:#x} reads {:#x}, not {:#x}", step.first,
seen, step.second));
}
break;
}
case StepKind::Run:
if (m_waited < step.cycles)
return;
break;
}
++m_next;
m_waited = 0;
}
}
bool Done() const { return m_next == m_steps.size(); }
bool Failed() const { return !m_failure.empty(); }
const std::string& Failure() const { return m_failure; }
// The line of the step it stands on.
int Line() const { return Done() ? 0 : m_steps[m_next].line; }
private:
void Fail(const ScriptStep& step, const std::string& why)
{
m_failure = fmt::format("line {}: {}", step.line, why);
}
std::vector<ScriptStep> m_steps;
size_t m_next = 0;
u64 m_waited = 0;
std::string m_failure;
};
} // namespace StarletBootstrapProbe
@@ -0,0 +1,37 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <optional>
#include <string_view>
#include "Common/CommonTypes.h"
// StarletBootstrapProbe's --stage-spk <file>: StarOS's SPK1 service package, placed in MEM2 at
// the package window's base once the image is loaded, before the first ARM instruction (StarOS
// docs/contracts/spk-staging.md). The window is the contract's, never an argument, so that a run
// cannot stage elsewhere. The probe only places bytes: SPK1's fields and digests are StarOS's to
// check.
namespace StarletBootstrapProbe
{
constexpr u32 SPK_WINDOW_BASE = 0x13720000;
constexpr u32 SPK_WINDOW_SIZE = 0x20000;
// Exit status of a run whose package file is refused before StarOS starts (1: failed
// expectation, 2: usage, 3: Dolphin alert).
constexpr int STAGING_EXIT_STATUS = 4;
// Why a package file of `size` bytes cannot be staged, or nullopt when it can: not empty, whole
// 32-bit words, at most the window.
inline std::optional<std::string_view> StagingRefusal(u64 size)
{
if (size == 0)
return "it is empty";
if (size % 4 != 0)
return "its length is not a whole number of 32-bit words";
if (size > SPK_WINDOW_SIZE)
return "it is larger than the 128 KiB package window";
return std::nullopt;
}
} // namespace StarletBootstrapProbe
@@ -0,0 +1 @@
* -text
@@ -0,0 +1,461 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/*
* H-1A's Broadway side (docs/architecture/h-1a.md, G-H1A-2): crates/hw-bench's
* h1a::setup, mark, Broadway and collect in C, plus the SBL:H1A block. Built
* only with -DSTAROS_HW0C -DSTAROS_HW0D -DSTAROS_H1A, never with
* -DSTAROS_HW0E or -DSTAROS_HW0F; never run on the console without its own
* reviewed GO.
*
* Before the jump, h1a_clear zeroes the record, page 0's near scrub and pages
* 1 to 3, then writes Z in the pool's 188 lines. Once READY is seen,
* h1a_ready writes M in them (T4's publication). Then h1a_step posts the 3000
* rounds of the frozen schedule, one action a call, as h1a::Broadway does:
* - it waits D_POST (2 ms) from the answer it saw, reads the Starlet's line
* once more and posts nothing to an ended Starlet;
* - for a Broadway -> Starlet round it fills the round's area (each arm turns
* over the four areas) with words naming the round and the address, and
* publishes it; then it writes SCENARIO and STATE, publishes, writes ROUND
* last and publishes;
* - it waits for the answer (200 ms): ROUND and SCENARIO the round's, STATE
* ROUND or END (the Starlet's END keeps its last answer's words); for a
* Starlet -> Broadway round it then reads S2B and counts its stale and
* other words;
* - after the last round, a timeout or the Starlet's END, it writes its END.
* It then waits for the Starlet's END (or READY + 65 s), reads the record at
* most ATTEMPTS times and makes its end checks.
*
* A read of the record is COHERENT only when GEN before, the body's GEN and GEN
* after are equal, even and not 0, and the magic, version and GEN 2 are the
* record's (h1a::qualify). The words are printed as the last read took them,
* never judged here: tools/gecko/check_h1a.py judges them. No AHB, IPC or
* memory-controller register is touched. Every store is an aligned word.
*
* The block ends with a CRC-32 of its numbers as they are printed (T4's I-1).
*/
#include <stdint.h>
#include "board.h"
#include "gecko.h"
#include "h1a.h"
#include "staros_hw0c.h"
#include "staros_h1a.h"
#if !defined(STAROS_HW0C) || !defined(STAROS_HW0D)
#error "h1a.c builds on -DSTAROS_HW0C -DSTAROS_HW0D"
#endif
#if defined(STAROS_HW0E) || defined(STAROS_HW0F)
#error "h1a.c excludes -DSTAROS_HW0E and -DSTAROS_HW0F: their window areas overlap H-1A's"
#endif
#define AT(offset) (STAROS_HW0C_BASE + (offset))
#define AREA_BYTES (4u * STAROS_H1A_AREA_WORDS)
#define RESULTS_BYTES (4u * STAROS_H1A_RESULTS_WORDS)
#define LINE STAROS_HW0C_LINE
/* Broadway's wait for the Starlet's END, from READY: past the engine's 60 s
* guard, inside the loader's bench timeout with the wait for READY. */
#define H1A_END_TIMEOUT_MS 65000u
static const uint32_t areas[STAROS_H1A_AREA_COUNT] = STAROS_H1A_AREAS;
static const uint32_t near_scrubs[STAROS_H1A_AREA_COUNT] = STAROS_H1A_NEAR;
enum phase { IDLE, DELAY, POST, WAIT_ACK, ENDING, WAIT_END, DONE };
enum arm { ARM_F, ARM_W, ARM_N, ARM_P };
/* Broadway's own counts and where H-1A is (h1a::Log and h1a::Broadway). */
static struct {
enum phase phase;
uint32_t round;
uint64_t until, acked, ready;
uint32_t b2s[4];
uint32_t posts, last, acks, timeout, s2b_rounds, s2b_stale, s2b_other, starlet_end;
uint64_t delay_min, delay_max;
uint32_t started, timed_out, collected;
} b;
/* The last read of the record, and its end checks. */
static uint32_t results[STAROS_H1A_RESULTS_WORDS];
static uint32_t gen_before, gen_after, attempts, coherent;
static uint32_t check_sentinel, check_scrub, check_pool;
/* The CRC-32 of the numbers printed so far: only h1a_report touches it. */
static uint32_t block_crc;
#ifdef STAROS_H1A_HOST
/* tests/hardware-wii/h1a's host bench only: its model stands for the two
* cache instructions. */
void dcbf(uint32_t address);
void dcbi(uint32_t address);
#else
static inline void dcbf(uint32_t address)
{
__asm__ volatile("dcbf 0,%0" ::"r"(address) : "memory");
}
static inline void dcbi(uint32_t address)
{
__asm__ volatile("dcbi 0,%0" ::"r"(address) : "memory");
}
#endif
static void publish(uint32_t offset, uint32_t bytes)
{
for (uint32_t at = 0; at < bytes; at += LINE)
dcbf(AT(offset + at));
sync();
}
static void refresh(uint32_t offset, uint32_t bytes)
{
for (uint32_t at = 0; at < bytes; at += LINE)
dcbi(AT(offset + at));
sync();
}
/* The schedule (h1a::s2b, scenario, arm). */
static int s2b(uint32_t round)
{
return round > STAROS_H1A_S1_ROUNDS && (round - STAROS_H1A_S1_ROUNDS) % 2u == 0;
}
static uint32_t scenario(uint32_t round)
{
return round <= STAROS_H1A_S1_ROUNDS ? STAROS_H1A_S1 : STAROS_H1A_S3;
}
static enum arm arm(uint32_t round)
{
uint32_t at = round - 1u;
uint32_t block = at / STAROS_H1A_BLOCK_ROUNDS, place = at % STAROS_H1A_BLOCK_ROUNDS;
uint32_t p = (block % 20u) * 2u;
if (place == p)
return ARM_P;
uint32_t k = place < p ? place : place - 1u;
static const enum arm turn[3] = {ARM_F, ARM_W, ARM_N};
return turn[(k + block) % 3u];
}
static uint32_t sentinel_word(uint32_t offset)
{
return STAROS_HW0C_PATTERN(STAROS_HW0C_TAG_SENTINEL, 0u, (offset - STAROS_HW0C_SENTINEL) / 4u);
}
/* The pool's words: page 2's tail, then page 3's after the far scrub. */
static void each_pool_word(void (*f)(uint32_t offset))
{
for (uint32_t w = 0; w < STAROS_H1A_AREA_LINES * STAROS_H1A_WORDS; w++)
f(STAROS_H1A_AREA_POOL + 4u * w);
for (uint32_t w = 0; w < STAROS_H1A_POLL_LINES * STAROS_H1A_WORDS; w++)
f(STAROS_H1A_POLL_POOL + 4u * w);
}
static void write_z(uint32_t offset)
{
write32(AT(offset), STAROS_H1A_Z(offset));
}
static void write_m(uint32_t offset)
{
write32(AT(offset), STAROS_H1A_M(offset));
}
static void check_m(uint32_t offset)
{
if (read32(AT(offset)) != STAROS_H1A_M(offset))
check_pool++;
}
/* The pool's span: from the area pool to page 3's end. */
#define POOLS_BYTES (4u * 0x1000u - STAROS_H1A_AREA_POOL)
void h1a_clear(void)
{
static const uint32_t cleared[3][2] = {
{STAROS_H1A_CLEAR0_START, STAROS_H1A_CLEAR0_END},
{STAROS_H1A_CLEAR1_START, STAROS_H1A_CLEAR1_END},
{STAROS_H1A_CLEAR2_START, STAROS_H1A_CLEAR2_END},
};
for (uint32_t r = 0; r < 3; r++) {
for (uint32_t offset = cleared[r][0]; offset < cleared[r][1]; offset += 4)
write32(AT(offset), 0);
publish(cleared[r][0], cleared[r][1] - cleared[r][0]);
}
each_pool_word(write_z);
publish(STAROS_H1A_AREA_POOL, POOLS_BYTES);
}
void h1a_ready(uint64_t now)
{
if (b.started)
return;
each_pool_word(write_m);
publish(STAROS_H1A_AREA_POOL, POOLS_BYTES);
b.started = 1;
b.ready = now;
b.round = 1;
b.acked = now;
b.until = now + (uint64_t)STAROS_H1A_D_POST_TB;
b.delay_min = UINT64_MAX;
b.phase = DELAY;
}
/* Broadway's post of the current round (h1a::Broadway's Post step). */
static void post(uint64_t now)
{
uint32_t round = b.round;
if (!s2b(round)) {
uint32_t slot = (uint32_t)arm(round);
uint32_t n = b.b2s[slot]++;
uint32_t base = areas[n % 4u];
for (uint32_t w = 0; w < STAROS_H1A_AREA_WORDS; w++) {
uint32_t offset = base + 4u * w;
write32(AT(offset), STAROS_HW0C_PATTERN(STAROS_HW0C_TAG_B2S, round, offset / 4u));
}
publish(base, AREA_BYTES);
}
const uint32_t line = STAROS_HW0C_BROADWAY;
write32(AT(line + STAROS_HW0C_C_SCENARIO), scenario(round));
write32(AT(line + STAROS_HW0C_C_STATE), STAROS_HW0C_STATE_ROUND);
publish(line, LINE);
write32(AT(line + STAROS_HW0C_C_ROUND), round);
publish(line, LINE);
uint64_t delay = now - b.acked;
if (delay < b.delay_min)
b.delay_min = delay;
if (delay > b.delay_max)
b.delay_max = delay;
b.posts++;
b.last = round;
b.until = now + (uint64_t)STAROS_H1A_ACK_TIMEOUT_TB;
b.phase = WAIT_ACK;
}
/* S2B once answered: its stale and other words (h1a::Broadway's WaitAck). */
static void read_s2b(uint32_t round)
{
refresh(STAROS_H1A_S2B, AREA_BYTES);
for (uint32_t w = 0; w < STAROS_H1A_AREA_WORDS; w++) {
uint32_t offset = STAROS_H1A_S2B + 4u * w;
uint32_t value = read32(AT(offset));
if (value == STAROS_HW0C_PATTERN(STAROS_HW0C_TAG_S2B, round, offset / 4u))
continue;
if ((value >> 28) == STAROS_HW0C_TAG_S2B && (value & 0x3FFFu) == ((offset / 4u) & 0x3FFFu) &&
((value >> 14) & 0x3FFFu) < (round & 0x3FFFu))
b.s2b_stale++;
else
b.s2b_other++;
}
b.s2b_rounds++;
}
static void wait_ack(uint64_t now)
{
const uint32_t line = STAROS_HW0C_STARLET;
refresh(line, LINE);
uint32_t state = read32(AT(line + STAROS_HW0C_C_STATE));
uint32_t round = b.round;
/* An answer counts with STATE ROUND, or END: the Starlet's END, written
* after its last answer, keeps that answer's ROUND and SCENARIO. */
int answered = (state == STAROS_HW0C_STATE_ROUND || state == STAROS_HW0C_STATE_END) &&
read32(AT(line + STAROS_HW0C_C_ROUND)) == round &&
read32(AT(line + STAROS_HW0C_C_SCENARIO)) == scenario(round);
int ended = state == STAROS_HW0C_STATE_END;
if (ended)
b.starlet_end = 1;
if (answered) {
b.acks++;
if (s2b(round))
read_s2b(round);
b.acked = now;
if (round >= STAROS_H1A_ROUNDS || ended) {
b.phase = ENDING;
} else {
b.round = round + 1u;
b.until = now + (uint64_t)STAROS_H1A_D_POST_TB;
b.phase = DELAY;
}
} else if (ended) {
b.phase = ENDING;
} else if (now >= b.until) {
b.timeout = round;
b.phase = ENDING;
}
}
static int starlet_ended(void)
{
refresh(STAROS_HW0C_STARLET, LINE);
return read32(AT(STAROS_HW0C_STARLET + STAROS_HW0C_C_STATE)) == STAROS_HW0C_STATE_END;
}
uint32_t h1a_sentinel_end(void)
{
uint32_t changed = 0;
refresh(STAROS_HW0C_SENTINEL, 4u * STAROS_HW0C_SENTINEL_WORDS);
for (uint32_t offset = STAROS_HW0C_SENTINEL; offset < STAROS_HW0C_SIZE; offset += 4) {
int inside = 0;
for (uint32_t a = 0; a < STAROS_H1A_AREA_COUNT; a++)
inside |= offset >= areas[a] && offset < areas[a] + AREA_BYTES;
if (!inside && read32(AT(offset)) != sentinel_word(offset))
changed++;
}
return changed;
}
/* The record read until one read qualifies (at most ATTEMPTS), then the end
* checks (h1a::collect). */
static void collect(void)
{
attempts = 0;
coherent = 0;
while (attempts < STAROS_H1A_ATTEMPTS && !coherent) {
refresh(STAROS_H1A_RESULTS, RESULTS_BYTES);
gen_before = read32(AT(STAROS_H1A_RESULTS + 4u * STAROS_H1A_F_GEN));
for (uint32_t w = 0; w < STAROS_H1A_RESULTS_WORDS; w++)
results[w] = read32(AT(STAROS_H1A_RESULTS + 4u * w));
gen_after = read32(AT(STAROS_H1A_RESULTS + 4u * STAROS_H1A_F_GEN));
attempts++;
coherent = gen_before == gen_after && gen_before % 2u == 0 && gen_before != 0 &&
results[STAROS_H1A_F_GEN] == gen_before && results[STAROS_H1A_F_MAGIC] == STAROS_H1A_MAGIC &&
results[STAROS_H1A_F_VERSION] == STAROS_H1A_VERSION && gen_before == STAROS_H1A_GEN;
}
check_sentinel = h1a_sentinel_end();
check_scrub = 0;
const uint32_t scrubs[3] = {STAROS_H1A_FAR, STAROS_H1A_NEAR_CONTROL, near_scrubs[0]};
for (uint32_t s = 0; s < 3; s++) {
refresh(scrubs[s], STAROS_H1A_BLOCK);
for (uint32_t w = 0; w < STAROS_H1A_BLOCK / 4u; w++)
if (read32(AT(scrubs[s] + 4u * w)) != 0)
check_scrub++;
}
check_pool = 0;
refresh(STAROS_H1A_AREA_POOL, POOLS_BYTES);
each_pool_word(check_m);
b.collected = 1;
}
int h1a_step(uint64_t now)
{
if (!b.started)
return 0;
int late = now - b.ready >= (uint64_t)H1A_END_TIMEOUT_MS * TICKS_PER_MS;
switch (b.phase) {
case IDLE:
return 0;
case DELAY:
if (now >= b.until)
b.phase = POST;
break;
case POST:
/* The Starlet's line once more: an ended Starlet waits for no post. */
if (starlet_ended()) {
b.starlet_end = 1;
b.phase = ENDING;
} else {
post(now);
}
break;
case WAIT_ACK:
wait_ack(now);
break;
case ENDING:
write32(AT(STAROS_HW0C_BROADWAY + STAROS_HW0C_C_STATE), STAROS_HW0C_STATE_END);
publish(STAROS_HW0C_BROADWAY, LINE);
b.phase = WAIT_END;
break;
case WAIT_END:
if (starlet_ended() || late) {
b.timed_out = !starlet_ended();
collect();
b.phase = DONE;
return b.timed_out ? -1 : 1;
}
break;
case DONE:
return b.timed_out ? -1 : 1;
}
/* Past READY + H1A_END_TIMEOUT_MS whatever is under way: Broadway ends. */
if (late && b.phase != WAIT_END && b.phase != DONE)
b.phase = ENDING;
return 0;
}
/* The block's CRC-32, word by word, most significant byte first (T4's). */
static void crc_word(uint32_t word)
{
for (int shift = 24; shift >= 0; shift -= 8) {
block_crc ^= (word >> shift) & 0xFFu;
for (int bit = 0; bit < 8; ++bit)
block_crc = (block_crc >> 1) ^ ((block_crc & 1u) ? 0xEDB88320u : 0u);
}
}
/* Every number of the block goes through one of these, in the order printed. */
static void hex_word(uint32_t value)
{
crc_word(value);
gecko_hex(value);
}
static void dec_word(uint32_t value)
{
crc_word(value);
gecko_dec(value);
}
static void wide(uint64_t value)
{
hex_word((uint32_t)(value >> 32));
hex_word((uint32_t)value);
}
void h1a_report(void)
{
/* A run that never reached READY reads the record anyway: what is there. */
if (!b.collected)
collect();
block_crc = 0xFFFFFFFFu;
gecko_puts("SBL:H1A B POSTS ");
dec_word(b.posts);
gecko_puts(" LAST ");
dec_word(b.last);
gecko_puts(" ACKS ");
dec_word(b.acks);
gecko_puts(" TIMEOUT ");
dec_word(b.timeout);
gecko_puts(" DELAY ");
wide(b.posts ? b.delay_min : UINT64_MAX);
gecko_puts(" ");
wide(b.delay_max);
gecko_puts(" S2B ");
dec_word(b.s2b_rounds);
gecko_puts(" ");
dec_word(b.s2b_stale);
gecko_puts(" ");
dec_word(b.s2b_other);
gecko_puts(" END ");
dec_word(b.starlet_end);
gecko_puts("\nSBL:H1A B CHECK SENTINEL ");
dec_word(check_sentinel);
gecko_puts(" SCRUB ");
dec_word(check_scrub);
gecko_puts(" POOL ");
dec_word(check_pool);
gecko_puts("\nSBL:H1A S GEN ");
hex_word(gen_before);
gecko_puts(" ");
hex_word(gen_after);
gecko_puts(" ATTEMPTS ");
dec_word(attempts);
crc_word(coherent);
gecko_puts(coherent ? " COHERENT\n" : " INCOMPLETE\n");
for (uint32_t row = 0; row < STAROS_H1A_RESULTS_WORDS / 8u; row++) {
gecko_puts("SBL:H1A S RESULTS ");
dec_word(row);
for (uint32_t i = 0; i < 8u; i++) {
gecko_puts(" ");
hex_word(results[8u * row + i]);
}
gecko_puts("\n");
}
gecko_puts("SBL:H1A END CRC ");
gecko_hex(~block_crc);
gecko_puts("\n");
}
@@ -0,0 +1,31 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/*
* H-1A's bench on Broadway (docs/architecture/h-1a.md, G-H1A-2), built into
* the bench's loader only with -DSTAROS_HW0C -DSTAROS_HW0D -DSTAROS_H1A,
* never with -DSTAROS_HW0E or -DSTAROS_HW0F. crates/hw-bench's h1a::setup,
* mark, Broadway and collect are the reference it follows; the other loaders
* do not contain it.
*/
#ifndef STAROS_LOADER_H1A_H
#define STAROS_LOADER_H1A_H
#include <stdint.h>
/* In hw0c_setup, before the header: the record, page 0's near scrub and
* pages 1 to 3 cleared, Z in the pool's words, all published. */
void h1a_clear(void);
/* Once READY is seen, at timebase `now`: M in the pool's words, published;
* round 1 is posted D_POST later. */
void h1a_ready(uint64_t now);
/* One step at timebase `now`, at most one action: 0 while H-1A runs; 1 once
* the Starlet's END was seen after Broadway's own end; -1 when it was not by
* READY + H1A_END_TIMEOUT_MS. The record and the checks are read back before
* it gives 1 or -1. */
int h1a_step(uint64_t now);
/* The sentinel's words outside H-1A's areas that are not as Broadway left
* them, read now (hw0c.c's S0 end check, and the CHECK line). */
uint32_t h1a_sentinel_end(void);
/* After hw0d_report: the SBL:H1A block. */
void h1a_report(void);
#endif
@@ -0,0 +1,473 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/*
* HW-M4-0C's Broadway side: crates/hw-bench's BroadwaySide in C, over the
* shared window of boot/contract/staros_hw0c.h. Built only with
* -DSTAROS_HW0C; never run on the console without its own reviewed GO.
*
* MSR=0: the window's addresses are physical. Whether Broadway's caches are
* on is not assumed: HID0 and L2CR are recorded in the header. publish is
* dcbf over the lines then sync; refresh is dcbi over the lines then sync,
* used only on lines the Starlet writes, or on the sentinel's lines, which
* were flushed at setup. Every store is an aligned word (write32).
*/
#include <stdint.h>
#include "board.h"
#include "gecko.h"
#include "hw0c.h"
#include "staros_hw0c.h"
#ifdef STAROS_HW0D
#include "hw0d.h"
#include "staros_hw0d.h"
#endif
#ifdef STAROS_HW0E
#include "hw0e.h"
#endif
#ifdef STAROS_HW0F
#include "hw0f.h"
#endif
#ifdef STAROS_H1A
#include "h1a.h"
#endif
#define HW0C_TIMEOUT_MS 2000u
/* The wait for READY, from the first step after the jump: the Starlet is
* ready only after the layout image's own checks, about 4 s on the console
* (tests/hardware-wii/adr-0003-layout-gates.md). */
#define HW0C_READY_TIMEOUT_MS 30000u
#define AT(offset) (STAROS_HW0C_BASE + (offset))
enum phase {
SETUP,
WAIT_READY,
POST,
WAIT_ACK,
END,
DONE,
#ifdef STAROS_HW0F
T4, /* HW-M4-0F: T4's counter instead of the rounds, from READY to its end */
#endif
#ifdef STAROS_H1A
H1A, /* H-1A: its own 3000 rounds instead of the bench's, from READY to its end */
#endif
};
struct tally {
uint32_t rounds, bad_rounds, stale, corrupt;
};
static const uint32_t run_ids[3] = {STAROS_HW0C_S1_B2S, STAROS_HW0C_S2_S2B, STAROS_HW0C_S3_SEQUENCE};
static const uint32_t run_rounds[3] = {STAROS_HW0C_S1_ROUNDS, STAROS_HW0C_S2_ROUNDS, STAROS_HW0C_S3_ROUNDS};
static struct {
enum phase phase;
uint32_t run, round;
uint64_t deadline;
struct tally tallies[4];
uint32_t ready, refused, sentinel_ready, sentinel_end;
uint32_t timed_out, timed_out_id, timed_out_round;
uint32_t first, first_id, first_round, first_index, first_value;
uint32_t hid0, l2cr, control, dacr, descriptor;
} bench;
#ifdef STAROS_HW0F_HOST
/* tests/hardware-wii/hw-m4-0f's host bench only: its model stands for the two
* cache instructions and the two special registers. */
void dcbf(uint32_t address);
void dcbi(uint32_t address);
uint32_t hid0(void);
uint32_t l2cr(void);
#else
static inline void dcbf(uint32_t address)
{
__asm__ volatile("dcbf 0,%0" ::"r"(address) : "memory");
}
static inline void dcbi(uint32_t address)
{
__asm__ volatile("dcbi 0,%0" ::"r"(address) : "memory");
}
static uint32_t hid0(void)
{
uint32_t value;
__asm__ volatile("mfspr %0,1008" : "=r"(value));
return value;
}
static uint32_t l2cr(void)
{
uint32_t value;
__asm__ volatile("mfspr %0,1017" : "=r"(value));
return value;
}
#endif
static void publish(uint32_t offset, uint32_t bytes)
{
for (uint32_t at = 0; at < bytes; at += STAROS_HW0C_LINE)
dcbf(AT(offset + at));
sync();
}
static void refresh(uint32_t offset, uint32_t bytes)
{
for (uint32_t at = 0; at < bytes; at += STAROS_HW0C_LINE)
dcbi(AT(offset + at));
sync();
}
static void fill(uint32_t tag, uint32_t round, uint32_t base, uint32_t words)
{
for (uint32_t i = 0; i < words; i++)
write32(AT(base + 4u * i), STAROS_HW0C_PATTERN(tag, round, i));
}
/* Compares `words` words with tag's round: mismatches, stale ones, the first. */
static uint32_t check(uint32_t tag, uint32_t round, uint32_t base, uint32_t words, uint32_t *stale,
uint32_t *first_index, uint32_t *first_value)
{
uint32_t mismatches = 0;
*stale = 0;
for (uint32_t i = 0; i < words; i++) {
uint32_t value = read32(AT(base + 4u * i));
if (value == STAROS_HW0C_PATTERN(tag, round, i))
continue;
if (mismatches++ == 0) {
*first_index = i;
*first_value = value;
}
if ((value >> 28) == tag && (value & 0x3FFFu) == (i & 0x3FFFu) && ((value >> 14) & 0x3FFFu) < (round & 0x3FFFu))
(*stale)++;
}
return mismatches;
}
static int broadway_writes(uint32_t id, uint32_t round)
{
return id == STAROS_HW0C_S1_B2S || (id == STAROS_HW0C_S3_SEQUENCE && (round & 1u));
}
static void count(uint32_t id, uint32_t round, uint32_t mismatches, uint32_t stale, uint32_t index, uint32_t value)
{
struct tally *tally = &bench.tallies[id & 3u];
tally->rounds++;
if (!mismatches)
return;
tally->bad_rounds++;
tally->stale += stale;
tally->corrupt += mismatches - stale;
if (!bench.first) {
bench.first = 1;
bench.first_id = id;
bench.first_round = round;
bench.first_index = index;
bench.first_value = value;
}
}
void hw0c_setup(void)
{
bench.hid0 = hid0();
bench.l2cr = l2cr();
fill(STAROS_HW0C_TAG_SENTINEL, 0, STAROS_HW0C_SENTINEL, STAROS_HW0C_SENTINEL_WORDS);
publish(STAROS_HW0C_SENTINEL, 4u * STAROS_HW0C_SENTINEL_WORDS);
const uint32_t lines[3] = {STAROS_HW0C_BROADWAY, STAROS_HW0C_STARLET, STAROS_HW0C_ENVIRONMENT};
for (uint32_t l = 0; l < 3; l++) {
for (uint32_t w = 0; w < STAROS_HW0C_LINE; w += 4)
write32(AT(lines[l] + w), 0);
publish(lines[l], STAROS_HW0C_LINE);
}
#ifdef STAROS_HW0D
hw0d_clear(); /* before the header: the Starlet starts after the jump */
#endif
#ifdef STAROS_HW0E
hw0e_clear(); /* the probe lines' marker A and a cleared record, before the jump */
#endif
#ifdef STAROS_HW0F
hw0f_clear(); /* T4's pages and record cleared, Z in its read lines, before the jump */
#endif
#ifdef STAROS_H1A
h1a_clear(); /* H-1A's pages and record cleared, Z in its pool, before the jump */
#endif
uint32_t plan = 1u << STAROS_HW0C_S0_SENTINEL;
/* T4 posts no round: its plan is S0 alone (G-T4-2, D5); nor does H-1A here, h1a.c posts its own. */
#if !defined(STAROS_HW0F) && !defined(STAROS_H1A)
for (uint32_t r = 0; r < 3; r++)
plan |= 1u << run_ids[r];
#endif
write32(AT(STAROS_HW0C_H_VERSION), STAROS_HW0C_VERSION);
write32(AT(STAROS_HW0C_H_SIZE), STAROS_HW0C_SIZE);
write32(AT(STAROS_HW0C_H_HID0), bench.hid0);
write32(AT(STAROS_HW0C_H_L2CR), bench.l2cr);
write32(AT(STAROS_HW0C_H_PLAN), plan);
write32(AT(STAROS_HW0C_H_ROUNDS), STAROS_HW0C_S1_ROUNDS);
publish(STAROS_HW0C_HEADER, STAROS_HW0C_LINE);
write32(AT(STAROS_HW0C_H_MAGIC), STAROS_HW0C_MAGIC);
publish(STAROS_HW0C_HEADER, STAROS_HW0C_LINE);
#ifdef STAROS_HW0D
hw0d_mark(STAROS_HW0D_E_B_SETUP, 0, 0);
#endif
bench.phase = WAIT_READY;
bench.deadline = 0; /* set by the first step, after the jump */
}
static void timeout_at(uint64_t now, uint32_t ms)
{
bench.deadline = now + (uint64_t)ms * TICKS_PER_MS;
}
int hw0c_step(uint64_t now)
{
const uint32_t starlet = STAROS_HW0C_STARLET;
if (bench.phase == WAIT_READY && !bench.deadline)
timeout_at(now, HW0C_READY_TIMEOUT_MS);
switch (bench.phase) {
case SETUP:
case DONE:
return 1;
case WAIT_READY: {
refresh(starlet, STAROS_HW0C_LINE);
uint32_t state = read32(AT(starlet + STAROS_HW0C_C_STATE));
if (state == STAROS_HW0C_STATE_READY) {
refresh(STAROS_HW0C_ENVIRONMENT, STAROS_HW0C_LINE);
bench.sentinel_ready = read32(AT(STAROS_HW0C_ENVIRONMENT + STAROS_HW0C_E_SENTINEL_BAD));
bench.control = read32(AT(STAROS_HW0C_ENVIRONMENT + STAROS_HW0C_E_CONTROL));
bench.dacr = read32(AT(STAROS_HW0C_ENVIRONMENT + STAROS_HW0C_E_DACR));
bench.descriptor = read32(AT(STAROS_HW0C_ENVIRONMENT + STAROS_HW0C_E_DESCRIPTOR));
bench.ready = 1;
bench.phase = POST;
#ifdef STAROS_HW0D
hw0d_mark(STAROS_HW0D_E_B_READY, 0, 0);
#endif
#ifdef STAROS_HW0F
bench.phase = T4;
hw0f_ready(now);
#endif
#ifdef STAROS_H1A
bench.phase = H1A;
h1a_ready(now);
#endif
} else if (state == STAROS_HW0C_STATE_REFUSED) {
bench.refused = 1;
bench.phase = END;
} else if (now >= bench.deadline) {
bench.timed_out = 1;
bench.timed_out_id = STAROS_HW0C_S0_SENTINEL;
bench.phase = END;
}
return 0;
}
case POST: {
if (bench.run >= 3) {
bench.phase = END;
return 0;
}
if (bench.round >= run_rounds[bench.run]) {
bench.run++;
bench.round = 0;
return 0;
}
uint32_t id = run_ids[bench.run];
uint32_t round = ++bench.round;
if (broadway_writes(id, round)) {
fill(STAROS_HW0C_TAG_B2S, round, STAROS_HW0C_B2S, STAROS_HW0C_DATA_WORDS);
publish(STAROS_HW0C_B2S, 4u * STAROS_HW0C_DATA_WORDS);
}
write32(AT(STAROS_HW0C_BROADWAY + STAROS_HW0C_C_SCENARIO), id);
write32(AT(STAROS_HW0C_BROADWAY + STAROS_HW0C_C_STATE), STAROS_HW0C_STATE_ROUND);
publish(STAROS_HW0C_BROADWAY, STAROS_HW0C_LINE);
write32(AT(STAROS_HW0C_BROADWAY + STAROS_HW0C_C_ROUND), round);
publish(STAROS_HW0C_BROADWAY, STAROS_HW0C_LINE);
#ifdef STAROS_HW0D
hw0d_mark(STAROS_HW0D_E_B_POSTED, id, round);
#endif
#ifdef STAROS_HW0E
hw0e_posted(id, round);
#endif
bench.phase = WAIT_ACK;
timeout_at(now, HW0C_TIMEOUT_MS);
return 0;
}
case WAIT_ACK: {
uint32_t id = run_ids[bench.run];
refresh(starlet, STAROS_HW0C_LINE);
if (read32(AT(starlet + STAROS_HW0C_C_STATE)) == STAROS_HW0C_STATE_REFUSED) {
#ifdef STAROS_HW0D
hw0d_mark(STAROS_HW0D_E_B_TIMEOUT,
STAROS_HW0D_LINE(STAROS_HW0C_STATE_REFUSED, read32(AT(starlet + STAROS_HW0C_C_SCENARIO))),
read32(AT(starlet + STAROS_HW0C_C_ROUND)));
#endif
bench.refused = 1;
bench.phase = END;
return 0;
}
if (read32(AT(starlet + STAROS_HW0C_C_ROUND)) != bench.round ||
read32(AT(starlet + STAROS_HW0C_C_SCENARIO)) != id) {
if (now >= bench.deadline) {
bench.timed_out = 1;
bench.timed_out_id = id;
bench.timed_out_round = bench.round;
#ifdef STAROS_HW0D
hw0d_mark(STAROS_HW0D_E_B_TIMEOUT,
STAROS_HW0D_LINE(read32(AT(starlet + STAROS_HW0C_C_STATE)),
read32(AT(starlet + STAROS_HW0C_C_SCENARIO))),
read32(AT(starlet + STAROS_HW0C_C_ROUND)));
#endif
bench.phase = END;
}
return 0;
}
#ifdef STAROS_HW0D
hw0d_mark(STAROS_HW0D_E_B_ANSWERED, id, bench.round);
#endif
uint32_t mismatches, stale = 0, index = 0, value = 0;
if (broadway_writes(id, bench.round)) {
mismatches = read32(AT(starlet + STAROS_HW0C_C_MISMATCHES));
stale = read32(AT(starlet + STAROS_HW0C_C_STALE));
index = read32(AT(starlet + STAROS_HW0C_C_FIRST_INDEX));
value = read32(AT(starlet + STAROS_HW0C_C_FIRST_VALUE));
} else {
refresh(STAROS_HW0C_S2B, 4u * STAROS_HW0C_DATA_WORDS);
mismatches = check(STAROS_HW0C_TAG_S2B, bench.round, STAROS_HW0C_S2B, STAROS_HW0C_DATA_WORDS, &stale,
&index, &value);
}
count(id, bench.round, mismatches, stale, index, value);
bench.phase = POST;
return 0;
}
#ifdef STAROS_HW0F
case T4: {
/* Until the Starlet's END, or READY + 45 s: then the record is read. A
* missing END is a timeout, so S0 is INCONCLUSIVE (G-T4-2, D7). */
int done = hw0f_step(now);
if (done < 0) {
bench.timed_out = 1;
bench.timed_out_id = STAROS_HW0C_S0_SENTINEL;
}
if (done)
bench.phase = END;
return 0;
}
#endif
#ifdef STAROS_H1A
case H1A: {
/* Until h1a.c has read the record back: after the Starlet's END, or READY
* + 65 s without one, which is a timeout, so S0 is INCONCLUSIVE. */
int done = h1a_step(now);
if (done < 0) {
bench.timed_out = 1;
bench.timed_out_id = STAROS_HW0C_S0_SENTINEL;
}
if (done)
bench.phase = END;
return 0;
}
#endif
case END: {
uint32_t stale, index, value;
write32(AT(STAROS_HW0C_BROADWAY + STAROS_HW0C_C_STATE), STAROS_HW0C_STATE_END);
publish(STAROS_HW0C_BROADWAY, STAROS_HW0C_LINE);
#ifdef STAROS_HW0D
hw0d_mark(STAROS_HW0D_E_B_END, 0, 0);
#endif
#ifdef STAROS_H1A
/* H-1A writes its areas A1 to A3 inside the sentinel after READY: the rest
* is checked, as h1a.c's own CHECK line counts it. */
(void)stale;
(void)index;
(void)value;
bench.sentinel_end = h1a_sentinel_end();
#else
refresh(STAROS_HW0C_SENTINEL, 4u * STAROS_HW0C_SENTINEL_WORDS);
bench.sentinel_end = check(STAROS_HW0C_TAG_SENTINEL, 0, STAROS_HW0C_SENTINEL, STAROS_HW0C_SENTINEL_WORDS,
&stale, &index, &value);
#endif
bench.phase = DONE;
return 1;
}
}
return 1;
}
static void line_hex(const char *label, uint32_t value)
{
gecko_puts(label);
gecko_hex(value);
}
static void line_dec(const char *label, uint32_t value)
{
gecko_puts(label);
gecko_dec(value);
}
/* One scenario's verdict, as hw_bench::Outcome::verdict gives it. */
static void verdict(uint32_t id)
{
struct tally *tally = &bench.tallies[id & 3u];
line_dec("SBL:HW0C S", id);
if (id == STAROS_HW0C_S0_SENTINEL) {
uint32_t bad = bench.sentinel_ready + bench.sentinel_end;
if (!bench.ready)
gecko_puts(" INCONCLUSIVE");
else if (bad)
line_dec(" FAIL CORRUPT ", bad);
else if (bench.timed_out || bench.refused)
gecko_puts(" INCONCLUSIVE");
else
gecko_puts(" PASS");
} else if (tally->bad_rounds) {
line_dec(" FAIL ROUNDS ", tally->bad_rounds);
line_dec(" STALE ", tally->stale);
line_dec(" CORRUPT ", tally->corrupt);
} else if (tally->rounds < run_rounds[id - 1u] || bench.refused) {
line_dec(" INCONCLUSIVE ROUNDS ", tally->rounds);
} else {
line_dec(" PASS ROUNDS ", tally->rounds);
}
gecko_puts("\n");
}
void hw0c_report(void)
{
line_hex("SBL:HW0C HID0 ", bench.hid0);
line_hex(" L2CR ", bench.l2cr);
gecko_puts("\n");
line_hex("SBL:HW0C ENV CTRL ", bench.control);
line_hex(" DACR ", bench.dacr);
line_hex(" PAGE ", bench.descriptor);
line_dec(" SENTINEL READY ", bench.sentinel_ready);
line_dec(" END ", bench.sentinel_end);
gecko_puts("\n");
for (uint32_t id = 0; id < 4u; id++)
verdict(id);
gecko_puts("SBL:HW0C S4 GATED IPC\nSBL:HW0C S5 GATED AHB\n");
if (bench.first) {
line_dec("SBL:HW0C FIRST S", bench.first_id);
line_dec(" ROUND ", bench.first_round);
line_dec(" INDEX ", bench.first_index);
line_hex(" VALUE ", bench.first_value);
gecko_puts("\n");
}
if (bench.timed_out) {
line_dec("SBL:HW0C TIMEOUT S", bench.timed_out_id);
line_dec(" ROUND ", bench.timed_out_round);
gecko_puts("\n");
}
if (bench.refused)
gecko_puts("SBL:HW0C REFUSED\n");
gecko_puts("SBL:HW0C END\n");
#ifdef STAROS_HW0D
hw0d_report();
#endif
#ifdef STAROS_HW0E
hw0e_report();
#endif
#ifdef STAROS_HW0F
hw0f_report();
#endif
#ifdef STAROS_H1A
h1a_report();
#endif
}
@@ -0,0 +1,19 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/*
* HW-M4-0C's Broadway side (tests/hardware-wii/hw-m4-0c.md), built into the
* loader only with -DSTAROS_HW0C. crates/hw-bench's BroadwaySide is the
* reference it follows; the default loader does not contain it.
*/
#ifndef STAROS_LOADER_HW0C_H
#define STAROS_LOADER_HW0C_H
#include <stdint.h>
/* Before the MINI jump: fill the sentinel, write the header (magic last). */
void hw0c_setup(void);
/* One step of the bench at timebase `now`: 1 once the bench is over. */
int hw0c_step(uint64_t now);
/* After EXI is back: the SBL:HW0C lines. */
void hw0c_report(void);
#endif
@@ -0,0 +1,213 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/*
* HW-M4-0D's Broadway side: crates/hw-bench's diag::Probe in C, plus the
* report of the Starlet's record. Built only with -DSTAROS_HW0C
* -DSTAROS_HW0D; never run on the console without its own reviewed GO.
*
* Broadway's events stay in its own memory and are stamped with its 64-bit
* timebase (243 MHz / 4). Broadway does not read HW_TIMER: whether the boot
* path's AHB protection lets the PPC reach that register is not known
* (docs/contracts/ppc-window.md, E20). The Starlet stamps its own events with
* HW_TIMER (243 MHz / 128); READY, which both sides stamp, ties the two
* clocks together at 32 timebase ticks to one HW_TIMER tick.
*
* The Starlet's record is read at the end, from the window's diagnostic
* area, whatever the Starlet's state, as diag::Snapshot::read does: the
* generation, every word, the generation again, at most
* STAROS_HW0D_ATTEMPTS times, never an unbounded wait. A read counts only
* between two equal even generations; otherwise the record is reported
* INCOMPLETE, with the words the last attempt read. Every store is an
* aligned word (write32, or a uint32_t of this file's own memory).
*/
#include <stdint.h>
#include "board.h"
#include "gecko.h"
#include "hw0d.h"
#include "staros_hw0c.h"
#include "staros_hw0d.h"
#define AT(offset) (STAROS_HW0C_BASE + (offset))
/* Broadway's first events and its latest, as diag::Log keeps them. */
static uint32_t kinds[STAROS_HW0D_SLOTS], as[STAROS_HW0D_SLOTS], bs[STAROS_HW0D_SLOTS];
static uint32_t highs[STAROS_HW0D_SLOTS], lows[STAROS_HW0D_SLOTS];
static uint32_t count, last_kind, last_a, last_b, last_high, last_low;
/* The Starlet's area as the last read took it, STAROS_HW0D_F_MAGIC first. */
static uint32_t words[STAROS_HW0D_RAW_WORDS];
#ifdef STAROS_HW0D_HOST
/* A host's build only (the Dolphin probe's Broadway client, H-1A's D-H1A-7):
* its model of the window stands for the two cache instructions. */
void dcbf(uint32_t address);
void dcbi(uint32_t address);
#else
static inline void dcbf(uint32_t address)
{
__asm__ volatile("dcbf 0,%0" ::"r"(address) : "memory");
}
static inline void dcbi(uint32_t address)
{
__asm__ volatile("dcbi 0,%0" ::"r"(address) : "memory");
}
#endif
void hw0d_clear(void)
{
for (uint32_t at = 0; at < STAROS_HW0D_SIZE; at += 4)
write32(AT(STAROS_HW0D_BASE + at), 0);
for (uint32_t at = 0; at < STAROS_HW0D_SIZE; at += STAROS_HW0C_LINE)
dcbf(AT(STAROS_HW0D_BASE + at));
sync();
}
void hw0d_mark(uint32_t kind, uint32_t a, uint32_t b)
{
uint64_t now = timebase();
uint32_t high = (uint32_t)(now >> 32), low = (uint32_t)now;
if (count < STAROS_HW0D_SLOTS) {
kinds[count] = kind;
as[count] = a;
bs[count] = b;
highs[count] = high;
lows[count] = low;
}
last_kind = kind;
last_a = a;
last_b = b;
last_high = high;
last_low = low;
count++;
}
static uint32_t area(uint32_t offset)
{
return read32(AT(STAROS_HW0D_BASE + offset));
}
static void broadway_event(uint32_t kind, uint32_t a, uint32_t b, uint32_t high, uint32_t low)
{
gecko_hex(kind);
gecko_puts(" A ");
gecko_hex(a);
gecko_puts(" B ");
gecko_hex(b);
gecko_puts(" TB ");
gecko_hex(high);
gecko_hex(low);
gecko_puts("\n");
}
/* The word at `offset` of the area, as the last read took it. */
static uint32_t taken(uint32_t offset)
{
return words[(offset / 4u) % STAROS_HW0D_RAW_WORDS];
}
static void starlet_event(uint32_t at)
{
gecko_hex(taken(at));
gecko_puts(" A ");
gecko_hex(taken(at + 4u));
gecko_puts(" B ");
gecko_hex(taken(at + 8u));
gecko_puts(" T ");
gecko_hex(taken(at + 12u));
gecko_puts("\n");
}
/* Reads the area into `words`, at most STAROS_HW0D_ATTEMPTS times: 1 once
* both generations are equal and even. `first`, `last`: the last attempt's. */
static int read_area(uint32_t *first, uint32_t *last, uint32_t *attempts)
{
for (uint32_t attempt = 1; attempt <= STAROS_HW0D_ATTEMPTS; attempt++) {
for (uint32_t at = 0; at < STAROS_HW0D_SIZE; at += STAROS_HW0C_LINE)
dcbi(AT(STAROS_HW0D_BASE + at));
sync();
/* A sync on each side of the words: the generations frame them in the
* bus's order, not only in the program's. */
*first = area(STAROS_HW0D_F_GEN);
sync();
for (uint32_t i = 0; i < STAROS_HW0D_RAW_WORDS; i++)
words[i] = area(4u * i);
sync();
*last = area(STAROS_HW0D_F_GEN);
*attempts = attempt;
if (*first == *last && (*first & 1u) == 0)
return 1;
}
return 0;
}
void hw0d_report(void)
{
uint32_t kept = count < STAROS_HW0D_SLOTS ? count : STAROS_HW0D_SLOTS;
gecko_puts("SBL:HW0D B EVENTS ");
gecko_dec(count);
gecko_puts("\n");
for (uint32_t i = 0; i < kept; i++) {
gecko_puts("SBL:HW0D B ");
gecko_dec(i);
gecko_puts(" ");
broadway_event(kinds[i], as[i], bs[i], highs[i], lows[i]);
}
gecko_puts("SBL:HW0D B LAST ");
broadway_event(last_kind, last_a, last_b, last_high, last_low);
/* The Starlet's record: one coherent read, or INCOMPLETE and the words
* the last attempt took (they are no record then). */
uint32_t first = 0, last = 0, attempts = 0;
int coherent = read_area(&first, &last, &attempts);
gecko_puts("SBL:HW0D S GEN ");
gecko_hex(first);
gecko_puts(" ");
gecko_hex(last);
gecko_puts(" ATTEMPTS ");
gecko_dec(attempts);
gecko_puts(coherent ? " COHERENT\n" : " INCOMPLETE\n");
uint32_t magic = taken(STAROS_HW0D_F_MAGIC), version = taken(STAROS_HW0D_F_VERSION);
if (magic != STAROS_HW0D_MAGIC || version != STAROS_HW0D_VERSION) {
gecko_puts("SBL:HW0D S NONE MAGIC ");
gecko_hex(magic);
gecko_puts(" VERSION ");
gecko_hex(version);
gecko_puts("\n");
} else {
uint32_t events = taken(STAROS_HW0D_F_EVENTS);
uint32_t stored = events < STAROS_HW0D_SLOTS ? events : STAROS_HW0D_SLOTS;
gecko_puts("SBL:HW0D S START ");
gecko_hex(taken(STAROS_HW0D_F_START));
gecko_puts(" POLLS ");
gecko_dec(taken(STAROS_HW0D_F_POLLS));
gecko_puts(" NOW ");
gecko_hex(taken(STAROS_HW0D_F_NOW));
gecko_puts(" LINE ");
gecko_hex(taken(STAROS_HW0D_F_STATE));
gecko_puts(" ");
gecko_hex(taken(STAROS_HW0D_F_SCENARIO));
gecko_puts(" ");
gecko_hex(taken(STAROS_HW0D_F_ROUND));
gecko_puts(" EVENTS ");
gecko_dec(events);
gecko_puts("\n");
for (uint32_t i = 0; i < stored; i++) {
gecko_puts("SBL:HW0D S ");
gecko_dec(i);
gecko_puts(" ");
starlet_event(STAROS_HW0D_F_LOG + i * STAROS_HW0D_EVENT_BYTES);
}
gecko_puts("SBL:HW0D S LAST ");
starlet_event(STAROS_HW0D_F_LAST);
}
/* The Starlet's line, read again now: an answer seen late shows here. */
dcbi(AT(STAROS_HW0C_STARLET));
sync();
gecko_puts("SBL:HW0D B LATE STATE ");
gecko_hex(read32(AT(STAROS_HW0C_STARLET + STAROS_HW0C_C_STATE)));
gecko_puts(" SCENARIO ");
gecko_hex(read32(AT(STAROS_HW0C_STARLET + STAROS_HW0C_C_SCENARIO)));
gecko_puts(" ROUND ");
gecko_hex(read32(AT(STAROS_HW0C_STARLET + STAROS_HW0C_C_ROUND)));
gecko_puts("\nSBL:HW0D END\n");
}
@@ -0,0 +1,20 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/*
* HW-M4-0D's diagnostic on Broadway (tests/hardware-wii/hw-m4-0d.md), built
* into the bench's loader only with -DSTAROS_HW0C -DSTAROS_HW0D.
* crates/hw-bench's diag::Probe is the reference its events follow; the
* HW-M4-0C loader and the default loader do not contain it.
*/
#ifndef STAROS_LOADER_HW0D_H
#define STAROS_LOADER_HW0D_H
#include <stdint.h>
/* In hw0c_setup, before the header: clear the diagnostic area. */
void hw0d_clear(void);
/* One of Broadway's events (STAROS_HW0D_E_B_*), stamped with its timebase. */
void hw0d_mark(uint32_t kind, uint32_t a, uint32_t b);
/* At the end of hw0c_report: the SBL:HW0D lines. */
void hw0d_report(void);
#endif
@@ -0,0 +1,76 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/*
* H-1A's bench over the HW-M4-0C window (crates/hw-bench, module h1a;
* docs/architecture/h-1a.md): offsets from STAROS_HW0C_BASE. Broadway
* (boot/wii/loader/h1a.c) clears the pages and the pool, marks the pool,
* posts 3000 rounds and reads the record back; the Starlet
* (hw_bench::h1a::Engine) polls, reads the areas under R-1A, answers and
* writes the record once. Every value is checked against the crate by
* tests/contract/h1a_header.rs, the tables entry for entry.
*/
#ifndef STAROS_H1A_H
#define STAROS_H1A_H
/* The four Broadway -> Starlet areas, 512 words each, in pages 1, 4, 10 and
* 15, and each area page's near scrub (arm N), just after its area. */
#define STAROS_H1A_AREA_COUNT 0x00000004u
#define STAROS_H1A_AREAS {0x00001000u, 0x00004000u, 0x0000A000u, 0x0000F000u}
#define STAROS_H1A_NEAR {0x00001800u, 0x00004800u, 0x0000A800u, 0x0000F800u}
#define STAROS_H1A_AREA_WORDS 0x00000200u
#define STAROS_H1A_NEAR_CONTROL 0x00000F80u
#define STAROS_H1A_FAR 0x00003000u
/* The Starlet -> Broadway area, page 2. */
#define STAROS_H1A_S2B 0x00002000u
/* Arm P's pool: page 2's tail, then page 3's after the far scrub. */
#define STAROS_H1A_AREA_POOL 0x00002800u
#define STAROS_H1A_AREA_LINES 0x00000040u
#define STAROS_H1A_POLL_POOL 0x00003080u
#define STAROS_H1A_POLL_LINES 0x0000007Cu
#define STAROS_H1A_BLOCK 0x00000080u
#define STAROS_H1A_WORDS 0x00000008u
/* The record: RESULTS, written once by the Starlet at its end (GEN 1,
* published; the words, published; GEN 2, published). Broadway reads GEN,
* RESULTS, GEN, at most ATTEMPTS times; a read counts only when GEN before,
* RESULTS[F_GEN] and GEN after are equal, even and not 0 (review F6), and the
* magic and version are the record's (hw_bench::h1a::qualify). */
#define STAROS_H1A_RESULTS 0x00000100u
#define STAROS_H1A_RESULTS_WORDS 0x000001C0u
#define STAROS_H1A_MAGIC 0x48314131u
#define STAROS_H1A_VERSION 0x00000001u
#define STAROS_H1A_GEN 0x00000002u
#define STAROS_H1A_ATTEMPTS 0x00000003u
#define STAROS_H1A_F_MAGIC 0x00000000u
#define STAROS_H1A_F_VERSION 0x00000001u
#define STAROS_H1A_F_GEN 0x00000002u
/* What Broadway's setup clears before the jump, [start, end): the record,
* page 0's near scrub and pages 1 to 3. */
#define STAROS_H1A_CLEAR0_START 0x00000100u
#define STAROS_H1A_CLEAR0_END 0x00000800u
#define STAROS_H1A_CLEAR1_START 0x00000F80u
#define STAROS_H1A_CLEAR1_END 0x00001000u
#define STAROS_H1A_CLEAR2_START 0x00001000u
#define STAROS_H1A_CLEAR2_END 0x00004000u
/* The pool's words: Z before the jump, M once READY is seen (T4's). */
#define STAROS_H1A_Z(offset) (0x5A000000u | (offset))
#define STAROS_H1A_M(offset) (0xA5000000u | (offset))
/* The rounds: S1's 1000 (Broadway -> Starlet), then S3's 2000 (odd ones
* Broadway -> Starlet, even ones Starlet -> Broadway); HW-M4-0C's scenario
* ids in the control lines. A block of 40 rounds: one P, then F, W and N. */
#define STAROS_H1A_ROUNDS 0x00000BB8u
#define STAROS_H1A_S1_ROUNDS 0x000003E8u
#define STAROS_H1A_S1 0x00000001u
#define STAROS_H1A_S3 0x00000003u
#define STAROS_H1A_BLOCK_ROUNDS 0x00000028u
/* Broadway's waits, in timebase ticks: from an answer seen to its next post
* (D_POST, 2 ms), and for an answer (200 ms). */
#define STAROS_H1A_D_POST_TB 0x0001DA9Cu
#define STAROS_H1A_ACK_TIMEOUT_TB 0x00B964F0u
/* The engine's guard, in HW_TIMER ticks from READY (60 s). */
#define STAROS_H1A_GUARD 0x06CA124Au
#endif
@@ -0,0 +1,74 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/*
* HW-M4-0C's visibility bench: the loader's view of crates/hw-bench (the
* source of truth), checked value for value by tests/contract/hw0c_header.rs.
* The window is MEM2 0x13500000-0x1350FFFF (dev-mini only); every field is a
* big-endian 32-bit word, every access a whole aligned word.
*/
#ifndef STAROS_HW0C_H
#define STAROS_HW0C_H
#define STAROS_HW0C_BASE 0x13500000u
#define STAROS_HW0C_SIZE 0x00010000u
#define STAROS_HW0C_LINE 0x00000020u
#define STAROS_HW0C_MAGIC 0x48573043u
#define STAROS_HW0C_VERSION 0x00000001u
/* The header (Broadway's, magic last). */
#define STAROS_HW0C_HEADER 0x00000000u
#define STAROS_HW0C_H_MAGIC 0x00000000u
#define STAROS_HW0C_H_VERSION 0x00000004u
#define STAROS_HW0C_H_SIZE 0x00000008u
#define STAROS_HW0C_H_HID0 0x0000000Cu
#define STAROS_HW0C_H_L2CR 0x00000010u
#define STAROS_HW0C_H_PLAN 0x00000014u
#define STAROS_HW0C_H_ROUNDS 0x00000018u
/* The control lines and their fields. */
#define STAROS_HW0C_BROADWAY 0x00000020u
#define STAROS_HW0C_STARLET 0x00000040u
#define STAROS_HW0C_C_SCENARIO 0x00000000u
#define STAROS_HW0C_C_ROUND 0x00000004u
#define STAROS_HW0C_C_STATE 0x00000008u
#define STAROS_HW0C_C_MISMATCHES 0x0000000Cu
#define STAROS_HW0C_C_STALE 0x00000010u
#define STAROS_HW0C_C_FIRST_INDEX 0x00000014u
#define STAROS_HW0C_C_FIRST_VALUE 0x00000018u
/* The Starlet's environment line. */
#define STAROS_HW0C_ENVIRONMENT 0x00000060u
#define STAROS_HW0C_E_CONTROL 0x00000000u
#define STAROS_HW0C_E_DACR 0x00000004u
#define STAROS_HW0C_E_DESCRIPTOR 0x00000008u
#define STAROS_HW0C_E_SENTINEL_BAD 0x0000000Cu
/* States. */
#define STAROS_HW0C_STATE_NONE 0x00000000u
#define STAROS_HW0C_STATE_READY 0x00000001u
#define STAROS_HW0C_STATE_ROUND 0x00000002u
#define STAROS_HW0C_STATE_END 0x00000003u
#define STAROS_HW0C_STATE_REFUSED 0x00000004u
/* The data areas and the sentinel. */
#define STAROS_HW0C_B2S 0x00001000u
#define STAROS_HW0C_S2B 0x00002000u
#define STAROS_HW0C_DATA_WORDS 0x00000400u
#define STAROS_HW0C_SENTINEL 0x00004000u
#define STAROS_HW0C_SENTINEL_WORDS 0x00003000u
/* Tags and scenarios (S4 and S5 are gated: the loader never posts them). */
#define STAROS_HW0C_TAG_B2S 0x00000001u
#define STAROS_HW0C_TAG_S2B 0x00000002u
#define STAROS_HW0C_TAG_SENTINEL 0x00000003u
#define STAROS_HW0C_S0_SENTINEL 0x00000000u
#define STAROS_HW0C_S1_B2S 0x00000001u
#define STAROS_HW0C_S2_S2B 0x00000002u
#define STAROS_HW0C_S3_SEQUENCE 0x00000003u
#define STAROS_HW0C_S1_ROUNDS 0x000003E8u
#define STAROS_HW0C_S2_ROUNDS 0x000003E8u
#define STAROS_HW0C_S3_ROUNDS 0x000007D0u
/* The word for index i of an area in a round: hw_bench::pattern. */
#define STAROS_HW0C_PATTERN(tag, round, index) ((((tag) & 0xFu) << 28) | (((round) & 0x3FFFu) << 14) | ((index) & 0x3FFFu))
#endif
@@ -0,0 +1,61 @@
/* SPDX-License-Identifier: GPL-2.0-only */
/*
* HW-M4-0D's diagnostic area of the HW-M4-0C window (crates/hw-bench, module
* diag; tests/hardware-wii/hw-m4-0d.md): offsets from STAROS_HW0C_BASE. Only
* the Starlet writes it, once Broadway's setup has cleared it. Every value is
* checked against the crate by tests/contract/hw0d_header.rs.
*/
#ifndef STAROS_HW0D_H
#define STAROS_HW0D_H
/* The area: in the window's gap between the environment line and B2S. */
#define STAROS_HW0D_BASE 0x00000800u
#define STAROS_HW0D_SIZE 0x00000200u
#define STAROS_HW0D_MAGIC 0x48573044u
#define STAROS_HW0D_VERSION 0x00000001u
#define STAROS_HW0D_HEARTBEAT 0x00010000u
#define STAROS_HW0D_SLOTS 0x00000010u
#define STAROS_HW0D_EVENT_BYTES 0x00000010u
/* A read takes RAW_WORDS words from F_MAGIC; Broadway tries ATTEMPTS times. */
#define STAROS_HW0D_RAW_WORDS 0x00000054u
#define STAROS_HW0D_ATTEMPTS 0x00000003u
/* Its words. An event is four words: kind, a, b, the Starlet's HW_TIMER. */
#define STAROS_HW0D_F_MAGIC 0x00000000u
#define STAROS_HW0D_F_VERSION 0x00000004u
#define STAROS_HW0D_F_START 0x00000008u
#define STAROS_HW0D_F_POLLS 0x0000000Cu
#define STAROS_HW0D_F_NOW 0x00000010u
#define STAROS_HW0D_F_STATE 0x00000014u
#define STAROS_HW0D_F_SCENARIO 0x00000018u
#define STAROS_HW0D_F_ROUND 0x0000001Cu
#define STAROS_HW0D_F_EVENTS 0x00000020u
/* The generation: odd while the Starlet updates the area, even once it is
* published whole. A read counts only between two equal even generations. */
#define STAROS_HW0D_F_GEN 0x00000024u
#define STAROS_HW0D_F_LOG 0x00000040u
#define STAROS_HW0D_F_LAST 0x00000140u
/* The Starlet's events. */
#define STAROS_HW0D_E_START 0x00000001u
#define STAROS_HW0D_E_LINE 0x00000002u
#define STAROS_HW0D_E_IGNORED 0x00000003u
#define STAROS_HW0D_E_B2S_BEGIN 0x00000004u
#define STAROS_HW0D_E_B2S_END 0x00000005u
#define STAROS_HW0D_E_S2B_BEGIN 0x00000006u
#define STAROS_HW0D_E_S2B_END 0x00000007u
#define STAROS_HW0D_E_ANSWER 0x00000008u
#define STAROS_HW0D_E_END 0x00000009u
#define STAROS_HW0D_E_FINISH 0x0000000Au
/* Broadway's, kept in its own memory (boot/wii/loader/hw0d.c). */
#define STAROS_HW0D_E_B_SETUP 0x00000011u
#define STAROS_HW0D_E_B_READY 0x00000012u
#define STAROS_HW0D_E_B_POSTED 0x00000013u
#define STAROS_HW0D_E_B_ANSWERED 0x00000014u
#define STAROS_HW0D_E_B_TIMEOUT 0x00000015u
#define STAROS_HW0D_E_B_END 0x00000016u
/* A line's state and scenario in one word, as hw_bench::diag::line. */
#define STAROS_HW0D_LINE(state, scenario) ((((state) & 0xFFFFu) << 16) | ((scenario) & 0xFFFFu))
#endif
@@ -0,0 +1,92 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <functional>
#include <string>
#include <fmt/format.h>
#include "Common/CommonTypes.h"
// What StarletBootstrapProbe requires of a finished StarOS panic path (StarOS ADR-0014 R6). The
// path sets __panic_state first, then __panic_code, then publishes the SBR1 boot record when
// there is one, so the first nonzero guard can show it half done: the probe keeps running until
// every condition holds. Words come through a callback, so the check is tested without a CPU.
namespace StarletBootstrapProbe
{
// StarOS's SBR1 boot record in MEM1 (StarOS crates/boot-contract, report.rs).
enum class SBR1Mode
{
None,
// --sbr1-record: the probe creates the record as the loader does.
Record,
// --sbr1-absent: no record; its area must stay zero.
Absent,
};
constexpr u32 SBR1_BASE = 0x00200000;
constexpr u32 SBR1_SIZE = 0x1000;
constexpr u32 SBR1_MAGIC = 0x53425231;
constexpr u32 SBR1_VERSION = 1;
// Word offsets.
constexpr u32 SBR1_EXI_OWNER = 0x0c;
constexpr u32 SBR1_RELAY_STATUS = 0x10;
constexpr u32 SBR1_STARLET_STATE = 0x18;
constexpr u32 SBR1_FATAL_REASON = 0x1c;
constexpr u32 SBR1_FAULT_CODE = 0x20;
constexpr u32 SBR1_RING_LENGTH = 0x2c;
constexpr u32 SBR1_RING_DROPPED = 0x30;
// Values.
constexpr u32 SBR1_EXI_PPC = 1;
constexpr u32 SBR1_EXI_STARLET = 2;
constexpr u32 SBR1_RELAY_JUMPING = 4;
// StarOS boot/contract/staros_boot.h's STAROS_STATE_IDLE: the Starlet's run is over; FATAL, PANIC and
// FAULT come after it.
constexpr u32 SBR1_STATE_IDLE = 3;
constexpr u32 SBR1_STATE_PANIC = 5;
// __panic_state once the path is entered; __panic_code of a Rust panic.
constexpr u32 PANIC_ENTERED = 1;
constexpr u32 PANIC_CODE_RUST = 1;
// The first condition of a finished panic path that does not hold, or an empty string:
// - __panic_state 1 and __panic_code 1;
// - with --sbr1-record: STARLET_STATE 5 (Panic), FATAL_REASON 0 and EXI_OWNER 1 (PPC);
// - with --sbr1-absent: every word of the record area still zero.
// read_mem1 returns the big-endian MEM1 word at an address.
inline std::string UnmetPanicCondition(u32 panic_state, u32 panic_code, SBR1Mode sbr1,
const std::function<u32(u32)>& read_mem1)
{
if (panic_state != PANIC_ENTERED)
return fmt::format("__panic_state is {}, not {}", panic_state, PANIC_ENTERED);
if (panic_code != PANIC_CODE_RUST)
return fmt::format("__panic_code is {}, not {}", panic_code, PANIC_CODE_RUST);
if (sbr1 == SBR1Mode::Record)
{
const struct
{
const char* name;
u32 offset;
u32 expected;
} fields[] = {{"STARLET_STATE", SBR1_STARLET_STATE, SBR1_STATE_PANIC},
{"FATAL_REASON", SBR1_FATAL_REASON, 0},
{"EXI_OWNER", SBR1_EXI_OWNER, SBR1_EXI_PPC}};
for (const auto& field : fields)
{
const u32 value = read_mem1(SBR1_BASE + field.offset);
if (value != field.expected)
return fmt::format("SBR1 {} is {}, not {}", field.name, value, field.expected);
}
}
if (sbr1 == SBR1Mode::Absent)
{
for (u32 offset = 0; offset < SBR1_SIZE; offset += 4)
{
const u32 value = read_mem1(SBR1_BASE + offset);
if (value != 0)
return fmt::format("SBR1 area word +{:#x} is {:#x} without a record", offset, value);
}
}
return {};
}
} // namespace StarletBootstrapProbe
@@ -0,0 +1,588 @@
// Copyright 2026 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#include "Common/MsgHandler.h"
#include "Core/Core.h"
#include "Core/HW/Memmap.h"
#include "Core/HW/WII_IPC.h"
#include "Core/IOS/Starlet/ARMCore.h"
#include "Core/IOS/Starlet/BootstrapELF.h"
#include "Core/IOS/Starlet/StarletMemory.h"
#include "Core/System.h"
#include "ProbeBroadway.h"
#include "ProbeBudget.h"
#include "ProbeRing.h"
#include "ProbeScript.h"
#include "ProbeStaging.h"
#include "StarOSPanicCheck.h"
namespace
{
using namespace StarletBootstrapProbe;
enum class ExpectedOutcome
{
Idle,
Panic,
FatalData,
UndefinedFault,
Phase2
};
// Exit status of a run stopped by a Dolphin alert (1: failed expectation, 2: usage).
constexpr int ALERT_EXIT_STATUS = 3;
// Slices run once a StarOS panic path looks finished, to see that it stays so.
constexpr int PANIC_SETTLE_SLICES = 2;
// Dolphin's default handler shows an alert in a modal MessageBox on Windows, which blocks the
// probe until someone closes it. Report the alert on stderr and fail the run at once instead.
bool FailOnAlert(const char* caption, const char* text, bool, Common::MsgType)
{
std::cout.flush();
std::cerr << "Dolphin alert (" << caption << "): " << text << std::endl;
std::_Exit(ALERT_EXIT_STATUS);
}
// Reads the package file for --stage-spk: its bytes, or nullopt once the reason is on stderr (a
// missing or unreadable file; a length StagingRefusal refuses).
std::optional<std::vector<u8>> ReadPackage(const std::string& path)
{
std::ifstream file(path, std::ios::binary | std::ios::ate);
if (!file)
{
std::cerr << "--stage-spk: cannot open the package file: " << path << '\n';
return std::nullopt;
}
const std::streamoff end = file.tellg();
if (end < 0)
{
std::cerr << "--stage-spk: cannot size the package file: " << path << '\n';
return std::nullopt;
}
if (const auto refusal = StagingRefusal(static_cast<u64>(end)))
{
std::cerr << "--stage-spk: refused " << path << " (" << end << " bytes): " << *refusal << '\n';
return std::nullopt;
}
std::vector<u8> package(static_cast<size_t>(end));
file.seekg(0);
if (!file.read(reinterpret_cast<char*>(package.data()), end))
{
std::cerr << "--stage-spk: cannot read the package file: " << path << '\n';
return std::nullopt;
}
return package;
}
// Reads and parses the file of --ipc-script: its runner, or nullopt once the reason is on stderr.
std::optional<ScriptRunner> ReadScript(const std::string& path)
{
std::ifstream file(path, std::ios::binary | std::ios::ate);
if (!file)
{
std::cerr << "--ipc-script: cannot open the script: " << path << '\n';
return std::nullopt;
}
const std::streamoff end = file.tellg();
if (end < 0 || static_cast<u64>(end) > SCRIPT_MAX_BYTES)
{
std::cerr << "--ipc-script: refused " << path << ": over " << SCRIPT_MAX_BYTES << " bytes\n";
return std::nullopt;
}
std::string text(static_cast<size_t>(end), '\0');
file.seekg(0);
if (!file.read(text.data(), end))
{
std::cerr << "--ipc-script: cannot read the script: " << path << '\n';
return std::nullopt;
}
std::string error;
auto steps = ParseScript(text, &error);
if (!steps)
{
std::cerr << "--ipc-script: refused " << path << ": " << error << '\n';
return std::nullopt;
}
return ScriptRunner(std::move(*steps));
}
// What a script reaches: PPC memory and the registers, as Broadway does.
class ProbeBus final : public ScriptBus
{
public:
ProbeBus(Memory::MemoryManager& memory, IOS::WiiIPC& ipc) : m_memory(memory), m_ipc(ipc) {}
void StoreWord(u32 address, u32 word) override { m_memory.Write_U32(word, address); }
u32 LoadWord(u32 address) override { return m_memory.Read_U32(address); }
void WriteRegister(u32 offset, u32 value) override { m_ipc.WriteStarletRegister(offset, value); }
u32 ReadRegister(u32 offset) override { return m_ipc.ReadStarletRegister(offset); }
private:
Memory::MemoryManager& m_memory;
IOS::WiiIPC& m_ipc;
};
// What the Broadway client reaches: PPC memory, by whole words (ProbeBroadway.h bounds it to the
// bench window).
class ProbeMemory final : public BroadwayMemory
{
public:
explicit ProbeMemory(Memory::MemoryManager& memory) : m_memory(memory) {}
u32 LoadWord(u32 address) override { return m_memory.Read_U32(address); }
void StoreWord(u32 address, u32 word) override { m_memory.Write_U32(word, address); }
private:
Memory::MemoryManager& m_memory;
};
bool Run(const std::string& path, bool jit, bool mmu_faults, SBR1Mode sbr1,
ExpectedOutcome expected, u64 cycles, const std::vector<u8>* package, ScriptRunner* script,
BroadwayClient* client)
{
std::ifstream file(path, std::ios::binary | std::ios::ate);
if (!file || file.tellg() <= 0 || file.tellg() > 16 * 1024 * 1024)
{
std::cerr << "Expected a readable Starlet ELF of at most 16 MiB: " << path << '\n';
return false;
}
const size_t size = static_cast<size_t>(file.tellg());
std::vector<u8> image(size);
file.seekg(0);
if (!file.read(reinterpret_cast<char*>(image.data()), size))
{
std::cerr << "Could not read Starlet ELF: " << path << '\n';
return false;
}
Core::DeclareAsCPUThread();
auto& system = Core::System::GetInstance();
system.GetWiiIPC().Reset();
IOS::LLE::StarletMemory memory(system);
memory.PrepareBootstrap();
IOS::LLE::BootstrapELFInfo info;
std::string error;
if (!IOS::LLE::LoadBootstrapELF(image, memory, &info, &error))
{
std::cerr << error << '\n';
return false;
}
if (package)
{
// The image loaded, then the package at the window's base, its bytes as the file holds them
// (big-endian words, as the Starlet reads them); read back before the first instruction.
auto& mem2 = system.GetMemory();
mem2.CopyToEmu(SPK_WINDOW_BASE, package->data(), package->size());
std::vector<u8> staged(package->size());
mem2.CopyFromEmu(staged.data(), SPK_WINDOW_BASE, staged.size());
if (staged != *package)
{
std::cerr << "--stage-spk: the package window does not read back as staged\n";
return false;
}
std::cerr << "Staged SPK package: " << package->size() << " bytes at 0x" << std::hex
<< SPK_WINDOW_BASE << std::dec << '\n';
}
// --broadway-h1a: StarOS's loader sets the bench window up before the jump; so does the client,
// before the Starlet's first instruction.
ProbeMemory client_memory(system.GetMemory());
if (client)
{
std::cerr << "--broadway-h1a: StarOS loader sources built in:\n" << BroadwayClient::Sources();
if (!client->Start(client_memory) || client->Failed())
{
std::cerr << "--broadway-h1a: " << client->Failure() << '\n';
return false;
}
}
IOS::LLE::ARMCore core(memory);
// Declared after memory, so destroyed first.
memory.AttachInterruptLines(&core);
core.SetJitEnabled(jit);
core.Reset(info.entry);
core.SetBigEndian(true);
// StarOS MMU-001: translation, domain, permission and alignment aborts (off by default).
core.SetMMUFaultsEnabled(mmu_faults);
constexpr u32 TRACE_MAGIC = 0x52455631;
constexpr u32 TRACE_CAPACITY = 1024;
auto& mem1 = system.GetMemory();
const auto read_mem1 = [&mem1](u32 address) { return mem1.Read_U32(address); };
const auto panic_unmet = [&] {
return UnmetPanicCondition(memory.Read32(info.panic_state), memory.Read32(info.panic_code),
sbr1, read_mem1);
};
// StarOS's panic path writes no trace line. Print the trace published so far, for the
// scenario's ordered checks, and the panic words.
const auto report_panic = [&] {
const u32 length = memory.Read32(info.trace) == TRACE_MAGIC ?
std::min(memory.Read32(info.trace + 4), TRACE_CAPACITY) :
0;
for (u32 index = 0; index < length; ++index)
std::cout << static_cast<char>(memory.Read8(info.trace + 8 + index));
std::cout << "PC=0x" << std::hex << core.GetRegister(15) << std::dec
<< " instructions=" << core.GetExecutedInstructions() << '\n';
std::cerr << "Starlet panic state " << memory.Read32(info.panic_state) << " code "
<< memory.Read32(info.panic_code) << '\n';
};
// The client's capture on stdout, after the trace, and its counts on stderr. The report reads the
// window too: false if it reached outside (the access refused, as during the run).
const auto report_client = [&](std::string_view status) {
std::cout << client->Report(status);
std::cerr << "--broadway-h1a: " << client->Steps() << " steps, timebase 0x" << std::hex
<< client->Timebase() << std::dec << ", done " << client->Done() << '\n';
if (client->Failed())
std::cerr << "--broadway-h1a: " << client->Failure() << '\n';
return !client->Failed();
};
ProbeBus script_bus(mem1, system.GetWiiIPC());
// The model's own line raises the IPC cause: the probe has no Starlet object (ProbeScript.h).
if (script)
system.GetWiiIPC().SetStarletAttached(true);
int panic_settled = 0;
for (u64 slice = 0; slice < cycles / SLICE_CYCLES; ++slice)
{
if (script)
{
script->Advance(script_bus, slice == 0 ? 0 : SLICE_CYCLES);
if (script->Failed())
{
std::cerr << "--ipc-script: " << script->Failure() << '\n';
return false;
}
}
if (client)
{
// As the loader's monitor: one step of the bench a turn, the first at the jump.
client->Advance(slice == 0 ? 0 : SLICE_CYCLES);
if (client->Failed())
{
std::cerr << "--broadway-h1a: " << client->Failure() << '\n';
return false;
}
}
core.SetIRQLine(system.GetWiiIPC().IsStarletIRQAsserted());
core.SetFIQLine(system.GetWiiIPC().IsStarletFIQAsserted());
core.RunCycles(SLICE_CYCLES);
const u32 fault_code = memory.Read32(info.fault_code);
if (fault_code != 0)
{
std::cerr << "Starlet exception " << fault_code << " LR=" << std::hex
<< memory.Read32(info.fault_lr) << " SPSR=" << memory.Read32(info.fault_spsr)
<< " PC=" << core.GetRegister(15) << std::dec << '\n';
return expected == ExpectedOutcome::UndefinedFault && fault_code == 1 &&
memory.Read32(info.fault_lr) != 0 && memory.Read32(info.fault_spsr) != 0;
}
// StarOS's panic path sets its guard word first, then its code, then publishes the SBR1
// record when there is one, and halts. An expected panic passes once all of that holds
// (UnmetPanicCondition) and still holds PANIC_SETTLE_SLICES slices later.
if (info.panic_state != 0 && memory.Read32(info.panic_state) != 0)
{
if (expected != ExpectedOutcome::Panic)
{
report_panic();
return false;
}
if (!panic_unmet().empty())
{
panic_settled = 0;
continue;
}
if (++panic_settled <= PANIC_SETTLE_SLICES)
continue;
report_panic();
return true;
}
if (client)
{
// --broadway-h1a: the loader's monitor reports once the SBR1 record says the Starlet is done
// (StarletDone) and its bench has ended; the trace, possibly full, is printed as it stands.
const u32 length = memory.Read32(info.trace) == TRACE_MAGIC ?
std::min(memory.Read32(info.trace + 4), TRACE_CAPACITY) :
0;
std::string trace(length, '\0');
for (u32 index = 0; index < length; ++index)
trace[index] = static_cast<char>(memory.Read8(info.trace + 8 + index));
const bool trace_terminal = trace.find("REV:BOOT:IDLE\n") != std::string::npos ||
trace.find("REV:PANIC") != std::string::npos ||
trace.find("REV:FATAL") != std::string::npos;
const u32 state = mem1.Read_U32(SBR1_BASE + SBR1_STARLET_STATE);
if (!StarletDone(trace_terminal, state, mem1.Read_U32(SBR1_BASE + SBR1_EXI_OWNER)) ||
!client->Done())
{
continue;
}
std::cout << trace;
std::cout << "PC=0x" << std::hex << core.GetRegister(15) << std::dec
<< " instructions=" << core.GetExecutedInstructions() << '\n';
if (length == TRACE_CAPACITY)
std::cerr << "--broadway-h1a: the trace is full: its last lines are in the SBR1 ring\n";
const bool reported = report_client(CLIENT_STATUS_DONE);
const bool startup_ok = trace.find("REV:BOOT:ENTRY\n") != std::string::npos &&
trace.find("REV:BOOT:BSS_OK\n") != std::string::npos &&
trace.find("REV:BOOT:DATA_OK\n") != std::string::npos &&
trace.find("REV:BOOT:STACK_OK\n") != std::string::npos &&
trace.find("REV:BOOT:RUST\n") != std::string::npos;
const bool idle =
state == SBR1_STATE_IDLE || trace.find("REV:BOOT:IDLE\n") != std::string::npos;
return reported && startup_ok && idle && trace.find("REV:PANIC") == std::string::npos &&
trace.find("REV:FATAL") == std::string::npos;
}
if (memory.Read32(info.trace) != TRACE_MAGIC)
continue;
const u32 length = memory.Read32(info.trace + 4);
if (length > TRACE_CAPACITY)
{
std::cerr << "Invalid REV_TRACE length: " << length << '\n';
return false;
}
std::string trace(length, '\0');
for (u32 index = 0; index < length; ++index)
trace[index] = static_cast<char>(memory.Read8(info.trace + 8 + index));
if (trace.find("REV:BOOT:IDLE\n") == std::string::npos &&
trace.find("REV:PANIC") == std::string::npos &&
trace.find("REV:FATAL") == std::string::npos)
{
continue;
}
std::cout << trace;
std::cout << "PC=0x" << std::hex << core.GetRegister(15) << std::dec
<< " instructions=" << core.GetExecutedInstructions() << '\n';
if (script && !script->Done())
{
std::cerr << "--ipc-script: script unfinished at line " << script->Line() << '\n';
return false;
}
const bool early_startup_ok = trace.find("REV:BOOT:ENTRY\n") != std::string::npos &&
trace.find("REV:BOOT:BSS_OK\n") != std::string::npos;
if (expected == ExpectedOutcome::FatalData)
{
return early_startup_ok && trace.find("REV:FATAL:DATA\n") != std::string::npos &&
trace.find("REV:BOOT:DATA_OK\n") == std::string::npos;
}
const bool startup_ok = early_startup_ok &&
trace.find("REV:BOOT:DATA_OK\n") != std::string::npos &&
trace.find("REV:BOOT:STACK_OK\n") != std::string::npos &&
trace.find("REV:BOOT:RUST\n") != std::string::npos;
if (expected == ExpectedOutcome::Phase2)
{
const std::string_view required[] = {
"REV:P2:START\n", "ARCH PASS\n", "CRITICAL PASS\n",
"TIMER PASS\n", "MONOTONIC PASS\n", "MEM PASS\n",
"IRQ PASS\n", "BARRIER PASS\n", "LOGGING PASS\n",
"REV:P2:PASS\n", "REV:P2:KERNEL_READY\n", "REV:BOOT:IDLE\n"};
bool phase2_ok = true;
for (const std::string_view marker : required)
phase2_ok &= trace.find(marker) != std::string::npos;
return startup_ok && phase2_ok && trace.find(" FAIL\n") == std::string::npos;
}
const bool outcome_ok =
expected == ExpectedOutcome::Panic ?
trace.find("REV:PANIC") != std::string::npos :
expected == ExpectedOutcome::Idle && trace.find("REV:BOOT:IDLE\n") != std::string::npos;
return startup_ok && outcome_ok;
}
if (info.panic_state != 0 && memory.Read32(info.panic_state) != 0)
{
report_panic();
const std::string unmet = panic_unmet();
std::cerr << "StarOS panic path unfinished after " << cycles
<< " ARM cycles: " << (unmet.empty() ? "it ended inside the settle slices" : unmet)
<< '\n';
return false;
}
std::cerr << "No terminal bootstrap marker after " << cycles << " ARM cycles, PC=0x" << std::hex
<< core.GetRegister(15) << std::dec << '\n';
// As main.c's monitor at its own timeout: the report anyway, under SBL:TIMEOUT.
if (client)
report_client(CLIENT_STATUS_TIMEOUT);
return false;
}
} // namespace
int main(int argc, char** argv)
{
Common::RegisterMsgAlertHandler(FailOnAlert);
if (argc < 2 || argc > 12)
{
std::cerr << "Usage: StarletBootstrapProbe <ELF> [--jit] [--mmu-faults] "
"[--sbr1-record|--sbr1-absent] "
"[--expect-panic|--expect-fatal-data|--expect-undefined-fault|--expect-phase2] "
"[--cycles <n>] [--stage-spk <file>] [--ipc-script <file>|--broadway-h1a]\n";
return 2;
}
bool jit = false;
bool mmu_faults = false;
SBR1Mode sbr1 = SBR1Mode::None;
ExpectedOutcome expected = ExpectedOutcome::Idle;
bool outcome_selected = false;
std::optional<u64> cycles;
bool broadway_h1a = false;
// --cycles' bound: MAX_CYCLES, or MAX_CLIENT_CYCLES when --broadway-h1a is among the options
// (ProbeBudget.h, ClientRequested), known before they are read so that --cycles is read where
// it stands.
const u64 max_cycles = ClientRequested(argc, argv) ? MAX_CLIENT_CYCLES : MAX_CYCLES;
std::optional<std::string> package_path;
std::optional<std::string> script_path;
for (int index = 2; index < argc; ++index)
{
const std::string_view option = argv[index];
if (option == "--ipc-script")
{
// One script, given once (ProbeScript.h).
if (script_path || index + 1 == argc)
{
std::cerr << "--ipc-script takes one file, once\n";
return 2;
}
script_path = argv[++index];
}
else if (option == "--stage-spk")
{
// One package file, given once (ProbeStaging.h).
if (package_path || index + 1 == argc)
{
std::cerr << "--stage-spk takes one package file, once\n";
return 2;
}
package_path = argv[++index];
}
else if (option == "--broadway-h1a")
{
// StarOS's H-1A bench loader as Broadway (ProbeBroadway.h), once.
if (broadway_h1a)
{
std::cerr << "--broadway-h1a is given once\n";
return 2;
}
broadway_h1a = true;
}
else if (option == "--cycles")
{
// A whole number of slices, at most max_cycles (ProbeBudget.h); given once.
if (cycles || index + 1 == argc || !(cycles = ParseCycles(argv[index + 1], max_cycles)))
{
std::cerr << "--cycles takes one decimal multiple of " << SLICE_CYCLES << ", at most "
<< max_cycles << ", once\n";
return 2;
}
++index;
}
else if (option == "--jit")
jit = true;
else if (option == "--mmu-faults")
mmu_faults = true;
else if (option == "--sbr1-record" || option == "--sbr1-absent")
{
if (sbr1 != SBR1Mode::None)
{
std::cerr << "Select only one SBR1 mode\n";
return 2;
}
sbr1 = option == "--sbr1-record" ? SBR1Mode::Record : SBR1Mode::Absent;
}
else if (option == "--expect-panic" || option == "--expect-fatal-data" ||
option == "--expect-undefined-fault" || option == "--expect-phase2")
{
if (outcome_selected)
{
std::cerr << "Select only one expected outcome\n";
return 2;
}
outcome_selected = true;
expected = option == "--expect-panic" ? ExpectedOutcome::Panic :
option == "--expect-fatal-data" ? ExpectedOutcome::FatalData :
option == "--expect-undefined-fault" ? ExpectedOutcome::UndefinedFault :
ExpectedOutcome::Phase2;
}
else
{
std::cerr << "Unknown option: " << option << '\n';
return 2;
}
}
// The client drives Broadway's side alone: no script, no staged package with it; and it reads
// the SBR1 record, as the loader's monitor does, so the record must be there.
if (broadway_h1a && (script_path || package_path))
{
std::cerr << "--broadway-h1a takes neither --ipc-script nor --stage-spk\n";
return 2;
}
if (broadway_h1a && sbr1 != SBR1Mode::Record)
{
std::cerr << "--broadway-h1a takes --sbr1-record: the loader's monitor reads the record\n";
return 2;
}
// The package file read and checked before anything is set up: a refused file ends the run
// before StarOS starts.
std::optional<std::vector<u8>> package;
if (package_path && !(package = ReadPackage(*package_path)))
return STAGING_EXIT_STATUS;
std::optional<ScriptRunner> script;
if (script_path && !(script = ReadScript(*script_path)))
return SCRIPT_EXIT_STATUS;
// The Starlet shares MEM1 and MEM2 with Broadway. Back them as on a retail Wii (24 and 64 MiB,
// zeroed): without them, any Starlet access there, such as StarOS reading its SBR1 record
// header at 0x00200000, is an access to unmapped memory and raises an alert.
auto& system = Core::System::GetInstance();
system.SetIsWii(true);
system.GetMemory().Init();
auto& memory = system.GetMemory();
if (sbr1 == SBR1Mode::Record)
{
// As the Broadway loader and the ARM relay leave StarOS's SBR1 boot record before the image
// runs (StarOS docs/contracts/wii-dev-boot.md): header, the relay at its last step, EXI
// channel 1 given to the Starlet, the magic written last.
memory.Write_U32(SBR1_VERSION, SBR1_BASE + 0x04);
memory.Write_U32(SBR1_SIZE, SBR1_BASE + 0x08);
memory.Write_U32(SBR1_EXI_STARLET, SBR1_BASE + SBR1_EXI_OWNER);
memory.Write_U32(SBR1_RELAY_JUMPING, SBR1_BASE + SBR1_RELAY_STATUS);
memory.Write_U32(SBR1_MAGIC, SBR1_BASE);
}
BroadwayClient client;
const bool passed = Run(argv[1], jit, mmu_faults, sbr1, expected, cycles.value_or(DEFAULT_CYCLES),
package ? &*package : nullptr, script ? &*script : nullptr,
broadway_h1a ? &client : nullptr);
if (sbr1 != SBR1Mode::None)
{
// The record's summary after the run; with --sbr1-absent every word must still be zero (an
// expected panic fails otherwise).
std::cerr << std::hex << "SBR1 magic 0x" << memory.Read_U32(SBR1_BASE) << std::dec
<< " state " << memory.Read_U32(SBR1_BASE + SBR1_STARLET_STATE) << " reason "
<< memory.Read_U32(SBR1_BASE + SBR1_FATAL_REASON) << " owner "
<< memory.Read_U32(SBR1_BASE + SBR1_EXI_OWNER) << " fault "
<< memory.Read_U32(SBR1_BASE + SBR1_FAULT_CODE) << " ring "
<< memory.Read_U32(SBR1_BASE + SBR1_RING_LENGTH) << " dropped "
<< memory.Read_U32(SBR1_BASE + SBR1_RING_DROPPED);
u32 written = 0;
for (u32 offset = 0; offset < SBR1_SIZE; offset += 4)
written += memory.Read_U32(SBR1_BASE + offset) != 0;
std::cerr << " nonzero_words " << written << '\n';
if (sbr1 == SBR1Mode::Record)
{
// The ring's text, as StarOS's Broadway loader prints it over the Gecko on the console;
// END starts its own line even when the text does not end with one.
const std::string ring =
RingText([&memory](u32 offset) { return memory.Read_U8(SBR1_BASE + offset); },
memory.Read_U32(SBR1_BASE + SBR1_RING_LENGTH));
std::cerr << "SBR1 RING BEGIN\n"
<< ring << (ring.empty() || ring.back() == '\n' ? "" : "\n") << "SBR1 RING END\n";
}
}
system.GetMemory().Shutdown();
return passed ? 0 : 1;
}
+11
View File
@@ -0,0 +1,11 @@
build/
__pycache__/
*.elf
*.map
/build/
/apps/
/captures/
/__pycache__/
/wii-conformance.dol
/wii-conformance.elf
/wii-conformance.map
+45
View File
@@ -0,0 +1,45 @@
.SUFFIXES:
ifeq ($(strip $(DEVKITPPC)),)
$(error Set DEVKITPPC to your devkitPPC installation)
endif
include $(DEVKITPPC)/wii_rules
TARGET := wii-conformance
BUILD := build
SOURCES := source
CFLAGS := -O2 -g -Wall -Wextra $(MACHDEP) $(INCLUDE)
LDFLAGS = -g $(MACHDEP) -Wl,-Map,$(OUTPUT).map
LIBS := -lwiiuse -lbte -lfat -logc -lm
ifneq ($(BUILD),$(notdir $(CURDIR)))
export OUTPUT := $(CURDIR)/$(TARGET)
export VPATH := $(CURDIR)/source
export DEPSDIR := $(CURDIR)/$(BUILD)
export OFILES := main.o
export INCLUDE := -I$(LIBOGC_INC)
export LIBPATHS := -L$(LIBOGC_LIB)
export LD := $(CC)
.PHONY: all clean
all: | $(BUILD)
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
@mkdir -p apps/wii-conformance
@cp $(TARGET).dol apps/wii-conformance/boot.dol
@cp meta.xml apps/wii-conformance/meta.xml
$(BUILD):
@mkdir -p $@
clean:
@rm -rf $(BUILD) $(OUTPUT).elf $(OUTPUT).dol $(OUTPUT).elf.map
else
DEPENDS := $(OFILES:.o=.d)
$(OUTPUT).dol: $(OUTPUT).elf
$(OUTPUT).elf: $(OFILES)
-include $(DEPENDS)
endif
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more