From 7e8d8cf78425db296844137148bc99f8fa8e9bef Mon Sep 17 00:00:00 2001 From: complex-ping <56292505+complex-ping@users.noreply.github.com> Date: Thu, 5 Nov 2026 18:44:08 +0100 Subject: [PATCH] SHARC map, reading tools and behaviour checks; fix fractional multiply in the emulator Only signed x signed fractional multiplies shift left (PRM); sim.py and simc_core.c shifted all of them. One stock instruction is affected, in rand, which is dead code. sharcatlas.py: functions and callers of section 7, compact reading, findings. No name table ships. sharc_checks.py: runs stock routines in the emulator and compares results. references/sharc.md: a map of the code, boot-built wave tables, the code shared with Digitakt II. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + skills/digitone-2-modding-skill/SKILL.md | 1 + .../references/emulators.md | 3 + .../references/sharc.md | 17 ++ .../references/workflow.md | 4 +- .../scripts/sharc_checks.py | 118 +++++++++ .../scripts/sharcatlas.py | 231 ++++++++++++++++++ .../digitone-2-modding-skill/scripts/sim.py | 4 +- .../scripts/simc_core.c | 2 +- tests/test_sharcatlas.py | 38 +++ 10 files changed, 416 insertions(+), 4 deletions(-) create mode 100644 skills/digitone-2-modding-skill/scripts/sharc_checks.py create mode 100644 skills/digitone-2-modding-skill/scripts/sharcatlas.py create mode 100644 tests/test_sharcatlas.py diff --git a/README.md b/README.md index 200e87f..81be4a7 100644 --- a/README.md +++ b/README.md @@ -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). diff --git a/skills/digitone-2-modding-skill/SKILL.md b/skills/digitone-2-modding-skill/SKILL.md index 025afeb..7b1bada 100644 --- a/skills/digitone-2-modding-skill/SKILL.md +++ b/skills/digitone-2-modding-skill/SKILL.md @@ -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 | diff --git a/skills/digitone-2-modding-skill/references/emulators.md b/skills/digitone-2-modding-skill/references/emulators.md index fcb37df..a62cf90 100644 --- a/skills/digitone-2-modding-skill/references/emulators.md +++ b/skills/digitone-2-modding-skill/references/emulators.md @@ -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 diff --git a/skills/digitone-2-modding-skill/references/sharc.md b/skills/digitone-2-modding-skill/references/sharc.md index 607f935..1517447 100644 --- a/skills/digitone-2-modding-skill/references/sharc.md +++ b/skills/digitone-2-modding-skill/references/sharc.md @@ -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). diff --git a/skills/digitone-2-modding-skill/references/workflow.md b/skills/digitone-2-modding-skill/references/workflow.md index 1b480df..81f71bb 100644 --- a/skills/digitone-2-modding-skill/references/workflow.md +++ b/skills/digitone-2-modding-skill/references/workflow.md @@ -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) diff --git a/skills/digitone-2-modding-skill/scripts/sharc_checks.py b/skills/digitone-2-modding-skill/scripts/sharc_checks.py new file mode 100644 index 0000000..9ce7343 --- /dev/null +++ b/skills/digitone-2-modding-skill/scripts/sharc_checks.py @@ -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('> 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) diff --git a/skills/digitone-2-modding-skill/scripts/sharcatlas.py b/skills/digitone-2-modding-skill/scripts/sharcatlas.py new file mode 100644 index 0000000..44a2821 --- /dev/null +++ b/skills/digitone-2-modding-skill/scripts/sharcatlas.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +"""SHARC atlas: section 7 as a queryable database. Section 7 is byte-identical on OS 1.11 and 1.12. No RTTI here: names come from +reading, calls, strings and behaviour checks (sharc_checks.py). + + python3 sharcatlas.py build # $DN2_WORKSPACE/atlas/sharc.sqlite from extracted/section_7.bin + python3 sharcatlas.py stats | fn ADDR|NAME | unknown [N] | dis ADDR|NAME [N] + python3 sharcatlas.py reread [CHARS] # next unread functions as compact assembly: calls and returns folded, labels only where jumped to + python3 sharcatlas.py confirm < NOTES # lines `ADDR [name]|role` after reading: marks them read + python3 sharcatlas.py name ADDR NAME [conf] [why...] + +Addresses are short words, as in references/sharc.md. Findings live in atlas/names_sharc.tsv and survive rebuilds. +The database is made from your image: keep it private. +""" +import bisect, collections, os, re, sqlite3, struct, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import dn2paths as P +P.use_dnfw() +import visa +OUT = P.WS / 'atlas' +DB, NAMES = OUT / 'sharc.sqlite', OUT / 'names_sharc.tsv' +CODE = [(0x20000000, 0x1e880), (0x2001e888, 0x699b4), (0x28380000, 0x25c0), (0x283825c4, 0x19a38)] +HEX = re.compile(r'0x[0-9a-f]+') + + +def read_names(): + out = {} + if NAMES.exists(): + for l in open(NAMES): + if l.strip() and not l.startswith('#'): + a, n, c, w = (l.rstrip('\n').split('\t') + ['', '', ''])[:4] + out[int(a, 16)] = (n, c, w) + return out + + +def write_names(d): + with open(NAMES, 'w') as f: + f.write('# addr\tname\tconfidence (guess, read, verified)\twhy\n') + for a in sorted(d): + f.write(f'{a:#x}\t' + '\t'.join(d[a]) + '\n') + + +def decode_all(img): + ins = [] + for base, n in CODE: + ins += list(img.linear(visa.Image.load_to_sw(base), end=visa.Image.load_to_sw(base + n), stop_invalid=False)) + return ins + + +def build(): + OUT.mkdir(parents=True, exist_ok=True) + img = visa.Image() + ins = decode_all(img) + pcs = {i.sw for i in ins} + calls, jumps, ptrs = [], [], set() + for i in ins: + t = i.text + if re.search(r'\b(CALL|CJUMP|JUMP)\b', t): + for h in HEX.findall(t): + v = int(h, 16) + if v in pcs: + (calls if re.search(r'\b(CALL|CJUMP)\b', t) else jumps).append((i.sw, v)) + else: + for h in re.findall(r'I\d+ = (0x[0-9a-f]+)', t): # a code pointer in an index register: C function pointers (17a I12 = ...) + v = int(h, 16) + if v in pcs: + ptrs.add(v) + # table pointers: a 32-bit data word that is an instruction start and follows a return (or starts code) + rets = {i.sw + i.size for i in ins if re.match(r'(IF \S+ )?(RTS|RFRAME|RTI)', i.text) or 'RFRAME' in i.text} + data = set() + for base, d in img.regions: + for o in range(0, len(d) - 3, 4): + v = struct.unpack_from(' 1 else '') + def nm(mm): + a = int(mm.group(2), 16) + return (mm.group(1) + ' ' + names[a]) if a in names and names[a] else mm.group(0) + t = re.sub(r'\b(CALL|CJUMP|JUMP)\s+(0x[0-9a-f]+)', nm, t) + t = re.sub(r'\b(JUMP|CALL|CJUMP) 0x[0-9a-f]*([0-9a-f]{3})\b', lambda mm: f'{mm.group(1)} {mm.group(2)}', t) + t = t.replace('CJUMP', 'call').replace(' (DB)', '').replace('DM(I7, M7) = ', 'push ') + t = t.replace('MODIFY(I7, -2) (NW)', '').replace('(SSI)', '').strip() + if t: + out.append(t) + return out + + +def reread(chars=24000): + """The next unread functions, by address, as compact assembly.""" + img = visa.Image() + c = db() + names = {a: n for a, n in c.execute('select addr,name from fn')} + rows = c.execute("select addr,end,ninsn,name,callers from fn where conf is null or conf not in ('read','verified') order by addr").fetchall() + size = shown = 0 + for a, e, ni, nm, cl_ in rows: + ins = [i for i in img.linear(a, end=e, stop_invalid=False)] + targets = set() + for i in ins: + for m in re.finditer(r'\b(?:JUMP|LCNTR.*UNTIL\s+LCE|UNTIL)\s*(0x[0-9a-f]+)', i.text): + targets.add(int(m.group(1), 16)) + lines = _compact(ins, names, targets) + text = f'={a:x} {nm or ""} {ni}i c{cl_}\n' + '\n'.join(lines) + if size + len(text) > int(chars) and shown: + break + print(text[:int(chars)]) + size += len(text) + 1 + shown += 1 + print(f'## {shown} functions, {size:,} chars; {len(rows)} left, {sum(r[2] for r in rows):,} instructions') + + +def confirm(): + """Lines: ADDR [name]|role after reading; marks read.""" + d = read_names() + c = db() + n = 0 + for l in sys.stdin: + l = l.strip() + if not l or l.startswith('#'): + continue + a, rest = l.split(' ', 1) + a = int(a, 16) + nm, _, role = rest.partition('|') + old = c.execute('select name from fn where addr=?', (a,)).fetchone() + if old is None: + sys.exit(f'no function at {a:#x}') + nm = nm.strip() or old[0] + d[a] = (nm, 'read', role.strip()) + c.execute("update fn set name=?,conf='read',why=? where addr=?", (nm, role.strip(), a)) + n += 1 + write_names(d) + c.commit() + print(n, 'confirmed') + + +def name(a, nm, conf='read', *why): + d = read_names() + d[int(a, 16)] = (nm, conf, ' '.join(why)) + write_names(d) + c = db() + c.execute('update fn set name=?,conf=?,why=? where addr=?', (nm, conf, ' '.join(why), int(a, 16))) + c.commit() + + +if __name__ == '__main__': + cmds = dict(build=build, stats=stats, fn=fn, unknown=unknown, dis=dis, reread=reread, confirm=confirm, name=name) + cmds[sys.argv[1] if len(sys.argv) > 1 else 'stats'](*sys.argv[2:]) diff --git a/skills/digitone-2-modding-skill/scripts/sim.py b/skills/digitone-2-modding-skill/scripts/sim.py index 5ad503a..a66c37c 100644 --- a/skills/digitone-2-modding-skill/scripts/sim.py +++ b/skills/digitone-2-modding-skill/scripts/sim.py @@ -587,7 +587,7 @@ def _fmul_fixed(self, pe, X, Y, sx_, sy_, frac, rnd, _): x = s32(X) if sx_ else X & M32 y = s32(Y) if sy_ else Y & M32 p = x * y - if frac: p <<= 1 + if frac and sx_ and sy_: p <<= 1 # PRM: only signed x signed fractional drops the redundant sign bit return self._mr_result(p, frac, rnd) def _mul(self, pe, op, n, x, y): @@ -604,7 +604,7 @@ def _mul(self, pe, op, n, x, y): xv = s32(R[x]) if xs else R[x] & M32 yv = s32(R[y]) if ys else R[y] & M32 p = xv * yv - if frac: p <<= 1 + if frac and xs and ys: p <<= 1 # PRM: only signed x signed fractional drops the redundant sign bit accname = 'MRB' if dst in (1, 3) else 'MRF' acc = getattr(pe, accname) if hi == 1: res = p diff --git a/skills/digitone-2-modding-skill/scripts/simc_core.c b/skills/digitone-2-modding-skill/scripts/simc_core.c index 9745748..ba5ad9b 100644 --- a/skills/digitone-2-modding-skill/scripts/simc_core.c +++ b/skills/digitone-2-modding-skill/scripts/simc_core.c @@ -535,7 +535,7 @@ static void mul(Sim *s, PE *pe, int op, int n, int x, int y) { i128 xv = xs ? S32(R[x]) : (i64)R[x]; i128 yv = ys ? S32(R[y]) : (i64)R[y]; i128 p = xv * yv; - if (frac) p <<= 1; + if (frac && xs && ys) p <<= 1; /* PRM: only signed x signed fractional drops the redundant sign bit */ i128 *acc = (dst == 1 || dst == 3) ? &pe->MRB : &pe->MRF; i128 res = hi == 1 ? p : hi == 2 ? *acc + p : *acc - p; res = s80(res); diff --git a/tests/test_sharcatlas.py b/tests/test_sharcatlas.py new file mode 100644 index 0000000..bb1fa46 --- /dev/null +++ b/tests/test_sharcatlas.py @@ -0,0 +1,38 @@ +"""What the SHARC tools can show without firmware: name records survive, and the fractional multiply rule.""" +import os, pathlib, sys, tempfile, types, unittest + +ROOT = pathlib.Path(__file__).resolve().parent.parent / 'skills/digitone-2-modding-skill/scripts' +sys.path.insert(0, str(ROOT)) +os.environ['DN2_WORKSPACE'] = tempfile.mkdtemp() +import sharcatlas +import sim + + +class Names(unittest.TestCase): + def test_round_trip(self): + sharcatlas.OUT.mkdir(parents=True, exist_ok=True) + sharcatlas.write_names({0x1c1018: ('cosf', 'verified', 'ran it')}) + self.assertEqual(sharcatlas.read_names(), {0x1c1018: ('cosf', 'verified', 'ran it')}) + + def test_compact(self): + ins = [types.SimpleNamespace(sw=0x100, text='R2 = 0x40000000 ; =2'), types.SimpleNamespace(sw=0x102, text='NOP'), + types.SimpleNamespace(sw=0x103, text='CALL 0x200')] + self.assertEqual(sharcatlas._compact(ins, {0x200: 'powf'}, {0x103}), ['R2 = 2', '103:', 'CALL powf']) + + +class FractionalMultiply(unittest.TestCase): + def mul(self, op, x, y): + pe = types.SimpleNamespace(R=[0, x, y, 0], MRF=0, MRB=0) + me = types.SimpleNamespace(_mr_result=lambda acc, frac, rnd: sim.Sim._mr_result(None, acc, frac, rnd)) + sim.Sim._mul(me, pe, op, 3, 1, 2) + return pe.R[3] + + def test_unsigned_is_not_shifted(self): # 0x48 = (UUF); stock's 64 bit rand needs the plain high word + self.assertEqual(self.mul(0x48, 0x80000000, 0x80000000), 0x40000000) + + def test_signed_is_shifted(self): # 0x78 = (SSF): 0.5 * 0.5 = 0.25 in 1.31 + self.assertEqual(self.mul(0x78, 0x40000000, 0x40000000), 0x20000000) + + +if __name__ == '__main__': + unittest.main()