Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ python3 scripts/cfatlas.py class '^PatternGridView$'
python3 scripts/cfatlas.py fn 0x40063F56
```

`scripts/sharcatlas.py` does the same for the DSP, without RTTI: functions, callers, and a compact way to read and record them. `references/sharc.md` maps the code: machines, filters, FX, RTOS, drivers. `scripts/sharc_checks.py` runs stock routines in the emulator and compares the results.

## Examples
- [`double_time`](skills/digitone-2-modding-skill/examples/double_time): a ColdFire C hook. The sequencer clock runs at
2x; checked in the ColdFire emulator (4 → 8 sixteenths in 300 blocks).
Expand Down
1 change: 1 addition & 0 deletions skills/digitone-2-modding-skill/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ reflash stock (references/setup.md "Recovery").
| `dspblocks.py` | add L2 / DDR blocks to the SHARC boot stream, CALL hooks, 32-byte line padding |
| `fxdsl.py`, `sasm.py`, `sisa.py` | DSP kernels in Python (code + bit-exact model) / a verifying mini assembler / 48-bit packer |
| `cfatlas.py` | **start here for stock ColdFire code:** database of functions, callers, C++ classes, vtable slots and strings recovered from your image; records your findings |
| `sharcatlas.py`, `sharc_checks.py` | **start here for stock DSP code:** database of SHARC functions and callers, compact reading, your findings; run stock routines in the emulator and compare (`references/sharc.md` "Map of the code" is the overview) |
| `visa.py`, `cfdis.sh`, `cfx.sh` | SHARC disassembler; ColdFire disassembly, xrefs, functions |
| `deadscan.py` | unreferenced SHARC functions (caves) |
| `hwrules.py`, `shapecheck.py`, `encodecheck.py`, `bootblocks.py` | the static hardware-rule checks the emulator cannot do |
Expand Down
3 changes: 3 additions & 0 deletions skills/digitone-2-modding-skill/references/emulators.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
interrupts, DMA, the branch predictor, ECC / boot-ROM loading, power-on memory contents, anything the PRM forbids that an
interpreter executes "correctly" (hence the static checks). Instruction counts under-predict the unit's load.

- **Known limits:** floats are 32 bit, so code that clears RND32 and divides in 40 bits (`udiv32`) rounds quotients above 2^24. No peripherals, so drivers do not run.
- **Checking it against stock:** `sharc_checks.py` calls stock routines in the emulator and compares results. That is how a real emulator bug surfaced: every fractional multiply was shifted left, while the PRM shifts only signed x signed. A failing check can be the name, the test or the emulator; find out which before changing any of them.

## ColdFire (the real OS) — digikit + `fastemu.py` + `cfkit.py`
- digikit runs the MAIN OS in Unicorn with HLEs (flash, SD, panel, screen). `fastemu`: a native block stepper (10–30 M
instr / s), native idle skip / ISR return / pixel HLE; `cold_boot` + `to_screen` boot an image to the main screen (~1 min
Expand Down
17 changes: 17 additions & 0 deletions skills/digitone-2-modding-skill/references/sharc.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,26 @@
`MODIFY(I7, n)`); 14d = 0x1a/0x1b. Access sizes (l, x, w) differ per type — `visa.access_size()`; `(0,0,0)` = BYTE.
- The stock code is ADI C-compiler output: CJUMP / RFRAME frames, `udiv`, callee-saved R3, R5–R7, R9–R11, R13–R15; the C
runtime keeps M5 = 0, M6 = 1 (and M13 = 0, M14 = 1).
- `sharcatlas.py`: functions, callers, callees, and `reread` / `confirm` to read a stretch compactly and record it. A name from structure alone is often wrong; read the code, and run it (`sharc_checks.py`) when a mod relies on it.
- Wrong tools, do not use: digikit's own VISA decoder and the SLEIGH SHARC Ghidra module (wrong tables), the SHARC+ PRM's
Type 2a/2b figures.

## Map of the code (OS 1.11 and 1.12: section 7 is the same)
Addresses are short words. FreeRTOS and C library names are the upstream ones; the rest describe what the code does, found by reading it (`sharcatlas.py`).
[run] marks routines `sharc_checks.py` runs and compares; everything else here is a reading.
- **Start:** `Dsp_main` 1ca6d9 sets up clocks, SPU, audio state, PCG, the SPI link and codec SPORTs, creates the audio task, then `vTaskStartScheduler` b887ac. `Audio_task` 1c9e76, `Audio_runCommand` 1c9d6b.
- **Render:** `Render_block` 1c2712, `Render_voices` 1c8ef1, `Mix_fxBus` 1c1738, `Mix_main` 1c1f1e, `Mix_outputs` 1c244d.
- **Machines:** `FMTone_render` 1c54c7, `FMDrum_render` 1c778b, `Wavetone_render` 1c6d4a, `Swarmer_render` 1c85ad.
- **Filters (ids 0 MULTIMODE, 1 LOWPASS 4, 2 EQUALIZER, 3 COMB-, 4 LEGACY LP/HP, 5 COMB+; 2 + 4 and 3 + 5 share code):** `MultimodeFilter_block` b82342, `LowpassFilter_block` b80f2e, `EqFilter_block` b81a16, `CombFilter_block` b806f5, `LegacyFilter_block` b81526. Envelope `Adsr_block` b80345.
- **Wave tables:** ROM s16 at `0x2001e888 + 2 * 0x401 * i`, read through `Wave_bankPtrSine` 1c4b1e, with a byte-equal copy for FM Drum at `0x200779f8`. The band limited tables at `0x2002f0d0..` are not ROM data: `Wave_buildTables` 1c463b makes them at boot by additive synthesis: sine at `0x2002f0d0`, then 48 tables per bank (notes 24 + 2i, harmonics under 23 kHz, cos² window): triangle `0x2002f8d8`, saw `0x20047938`, square `0x2005f998`.
- **Reverb:** feedback delay network, 8 lines, two 4 x 4 Hadamard matrices, 8 allpass diffusers: `Reverb_init` b83dc1, `Reverb_linesInit` b83cbd, `Reverb_block` b836bc, `Reverb_core` b82d1a, `Reverb_allpassBank` b82a5b.
- **Delay:** `Delay_init` b848cb, `Delay_block` b8482c, `Delay_writeRing` b83f72, `Delay_readTaps` b8428b, `Delay_saturate` b84099. **Chorus:** `Chorus_init` b84f51, `Chorus_block` b84d5c, `Chorus_core` b84a3b.
- **Master compressor:** `Comp_init` b85501, `Comp_block` b8541d, `Comp_sidechainFilter` b84fd3, `Comp_gainComputer` b85070, `Comp_gainSmoother` b85111, `Comp_applyGain` b851e5, `Comp_mix` b852d2. **Overdrive:** `Master_overdrive` 1cdc30.
- **Math [run]:** `cosf` 1c1018, `sinf` 1c10e4, `tanf` 1c125e, `log10f` 1c0b60, `powf` 1c0c76, `expf` 1c11a5, `sqrtf` 1c122e, `floorf` 1c07cc, `float_div` 1c06ba, `udiv32` b8b4dc, `memset` 1c0bde, `memcpy_bytes` 1c0756, `rand` 1c0df6. Some return with RTS instead of the C frame; `sharc_checks.py` shows how to call each. `floorf` is `FIX` with MODE1.TRUNC, which goes toward minus infinity; the `TRUNC` instruction goes toward zero.
- **RTOS:** FreeRTOS queue, tasks, timers, event groups, stream buffers, heap 4, found by their assert strings. 8 priorities, heap `0x2d08b8..0x2dd0b0`, `Rtos_assert` 1cd978 is configASSERT, `vPortEnterCritical` b8afca, `vPortExitCritical` b8afd7. Port: `xPortStartScheduler` b8b3c8, `pxPortInitialiseStack` b8af28, yield ISR `0xb8a947`, tick ISR `0xb8afe4`, core timer period 1,000,000.
- **Drivers:** ADI services. PCG `Pcg_open` b8db33 (registers `0x310c9300`, `0x310ca300`), GPIO `Gpio_init` b8cabb, `Gpio_setDirection` b8cb1b, SEC `Sec_init` b8ec2c (`0x31089000`, SCI `0x31089400`, sources `0x31089800 + 8n`), interrupts `Int_install` b8ce24, `Int_uninstall` b8ced5, `Irq_registerHandler` b8b782, DMA `Dma_start` b8e46a, SPU `Spu_open` b8edee, SPI `Spi_open` 1cc753, SPORT `Sport_open` 1ccd08.
- **Shared with Digitakt II (OS 1.17):** comparing instruction sequences with immediates masked, 388 of 471 functions (data excluded) are at least 80 % present there: RTOS, drivers, FX, filters, envelopes, math, `Audio_task`. The machines, `Render_*`, `Mix_main` and `Mix_outputs` are the Digitone's own. A Digitakt finding on the shared part should carry over; check the constants. Digitakt's image gives few names of its own: a task string, `RPC dispatcher`, and two asserts from `lib\esp5-dsp\dsp-lib\sampler\digitakt_rompler_update.c`.

## Adding code: where
- **New blocks in the boot stream** (`dspblocks.py`): code at **L2 0x20090000** (sw 0xBC8000), data at 0x20098000, more up
to 0x200B0000 — all above where stock loads L2 code (0x2008823c) and HW-proven. **Not above 0x200B0000** (firmware.md).
Expand Down
4 changes: 3 additions & 1 deletion skills/digitone-2-modding-skill/references/workflow.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@
- **Derive before probing:** read your builder and the existing test first; probe only what the code does not answer.
- **Red herrings:** run an anomaly against the previous build before chasing it. It is often old behaviour.
- **Bisect with build variants early**, including a variant whose hook is semantically identical: a one-word change in timing or layout can be the cause.
- **Record what you learn** with `cfatlas.py name`, so no session derives it twice.
- **Record what you learn** with `cfatlas.py name` or `sharcatlas.py confirm`, so no session derives it twice.
- **Reverse on demand:** read what a feature touches, not the whole firmware. A full map has steep diminishing returns, and "100 %" cannot be proved.
- **Run a name before relying on it:** reading alone swapped sinf and cosf and took floorf for truncf. Add a line to `sharc_checks.py`, or a test with a stock control.
- **Keep comments short in build tables:** long comment lines get truncated by tools and eat an agent's context. History belongs in a log.

## A silent unit (UI works, no sound from power-on)
Expand Down
118 changes: 118 additions & 0 deletions skills/digitone-2-modding-skill/scripts/sharc_checks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
"""Behaviour checks of stock SHARC routines: call them in the emulator and compare with what their names claim. Reading alone
got some of these wrong (sinf and cosf swapped, floorf taken for truncf). Needs the stock snapshot (dn2setup.py --boot).

python3 sharc_checks.py [OUT.tsv]
Every line must say ok. Add a line when a mod comes to rely on a routine.
"""
import math, os, struct, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault('DN2_SIM', 'py')
import dn2frame as D
f = D.Frame()
s = f.s
fl = lambda x: struct.unpack('<I', struct.pack('<f', x))[0]
un = lambda w: struct.unpack('<f', struct.pack('<I', w & 0xffffffff))[0]
res = []


def callf(fn, *a, rts=False):
for r, v in zip((4, 8, 12), a):
s.px.R[r] = v
if rts:
s.pcstk.append(D.RET)
f.call(fn)
return un(s.px.R[0])


def show(name, addr, xs, want, rts=False):
got = []
for x in xs:
try:
got.append(callf(addr, *[fl(v) for v in (x if isinstance(x, tuple) else (x,))], rts=rts))
except Exception as e:
got.append(f'{e!r}'[:40])
ok = all(isinstance(g, float) and abs(g - w) < 1e-2 * max(1, abs(w)) for g, w in zip(got, want))
print(('ok ' if ok else 'BAD ') + f'{addr:#x} {name}: {[round(g, 4) if isinstance(g, float) else g for g in got]} want {[round(w, 4) for w in want]}', flush=True)
res.append((addr, name, ok, got))


show('cosf', 0x1c1018, [0.0, 0.5, 1.0, 2.0], [math.cos(x) for x in (0.0, 0.5, 1.0, 2.0)])
show('sinf', 0x1c10e4, [0.0, 0.5, 1.0, 2.0], [math.sin(x) for x in (0.0, 0.5, 1.0, 2.0)], rts=True)
show('tanf', 0x1c125e, [0.1, 0.5, 1.0], [math.tan(x) for x in (0.1, 0.5, 1.0)])
show('log10f', 0x1c0b60, [1.0, 10.0, 100.0, 0.5], [math.log10(x) for x in (1.0, 10.0, 100.0, 0.5)])
show('powf', 0x1c0c76, [(2.0, 3.0), (10.0, 2.0), (2.0, 0.5)], [8.0, 100.0, math.sqrt(2)])
show('float_div', 0x1c06ba, [(1.0, 2.0), (3.0, 4.0)], [0.5, 0.75], rts=True)
xs = (0.0, 0.25, 2.0, 100.0)
show('sqrtf', 0x1c122e, xs, [math.sqrt(x) for x in xs], rts=True)
xs = (0.0, 1.0, -1.0, 2.5)
show('expf', 0x1c11a5, xs, [math.exp(x) for x in xs], rts=True)
xs = (0.0, 1.5, -1.5, 3.999)
show('floorf', 0x1c07cc, xs, [float(math.floor(x)) for x in xs], rts=True) # FIX with MODE1.TRUNC: toward -inf


def calli(fn, *a):
"""Integer call: the routines below return through the frame or with RTS; retries with RTS on a stray return."""
for rts in (False, True):
s.pcstk = []; s.loopstk = []; s.pending = None
for r, v in zip((4, 8, 12), a):
s.px.R[r] = v & 0xffffffff
if rts:
s.pcstk.append(D.RET)
try:
f.call(fn, max_insns=2_000_000)
return s.px.R[0] & 0xffffffff
except Exception:
pass
raise RuntimeError(f'{fn:#x} did not return')


def check(name, addr, got, want):
ok = got == want
print(('ok ' if ok else 'BAD ') + f'{addr:#x} {name}: {got} want {want}', flush=True)
res.append((addr, name, ok, got))


m = s.mem
BUF = 0x26f800 # scratch; a Frame is throwaway
rb = lambda a, n: [m.r(a + i, 1) & 0xff for i in range(n)]
for i in range(32):
m.w(BUF + i, 0x11, 1)
calli(0x1c0bde, BUF + 3, 0x5a, 9)
check('memset', 0x1c0bde, rb(BUF, 14), [0x11] * 3 + [0x5a] * 9 + [0x11] * 2)
for i in range(32):
m.w(BUF + i, i, 1)
m.w(BUF + 0x40 + i, 0xee, 1)
calli(0x1c0756, BUF + 0x41, BUF + 2, 7)
check('memcpy_bytes', 0x1c0756, rb(BUF + 0x40, 10), [0xee] + list(range(2, 9)) + [0xee] * 2)
# udiv32 clears RND32 and divides in 40 bit floats; the emulator's floats are 32 bit, so quotients above 2^24 come out rounded
check('udiv32', 0xb8b4dc, [calli(0xb8b4dc, *x) for x in ((100, 7), (1000000, 3), (5, 9), (0x80000000, 2))],
[100 // 7, 1000000 // 3, 0, 0x40000000])
m.w(0x241228, 0x12345678); m.w(0x24122c, 0x9abcdef0)
x = 0x9abcdef012345678
x = (x * 6364136223846793005 + 1442695040888963407) & (2 ** 64 - 1)
check('rand', 0x1c0df6, [calli(0x1c0df6), m.r(0x241228), m.r(0x24122c)], [(x >> 32) & 0x7fffffff, x & 0xffffffff, x >> 32])
check('Irq_checkSecId', 0xb8b598, [calli(0xb8b598, v) for v in (0, 0x10, 0xc0, 0xc1, 0x1000)], [0, 0, 0, 0xffffffff, 0xffffffff])
m.w(BUF, 6); m.w(BUF + 4, 2); m.w(BUF + 8, 16)
check('prvBytesInBuffer', 0xb86f08, calli(0xb86f08, BUF), (16 + 2 - 6) % 16)
L = BUF + 0x40
calli(0xb85ad5, L)
items = [(L + 0x40, 5), (L + 0x80, 1), (L + 0xc0, 3), (L + 0x100, 0xffffffff)]
for a, v in items:
calli(0xb85acc, a)
check('vListInitialiseItem', 0xb85acc, m.r(a + 16), 0)
m.w(a, v)
calli(0xb85a45, L, a)
order = []
it = m.r(L + 12)
for _ in range(5):
if it == L + 8:
break
order.append(m.r(it))
it = m.r(it + 4)
check('vListInitialise', 0xb85ad5, m.r(L + 8), 0xffffffff)
check('vListInsert', 0xb85a45, (m.r(L), order), (4, [1, 3, 5, 0xffffffff]))
if len(sys.argv) > 1:
with open(sys.argv[1], 'w') as o:
for a, n, ok, got in res:
o.write(f'{a:x}\t{n}\t{"ok" if ok else "BAD"}\t{got}\n')
sys.exit(0 if all(r[2] for r in res) else 1)
Loading
Loading