From 6be9e7ce439ff40bfa57a1af454c91702cf0e69d Mon Sep 17 00:00:00 2001 From: Nathaniel Pawelczyk Date: Thu, 26 Nov 2026 11:25:45 -0600 Subject: [PATCH 1/2] Fix: Model:Cycles base, a runtime module never patches over the base's own sites (held-sites.h from machine:base), and the paused guard sized to 2 x TASKS (from the Rytm's review on #1934) Co-Authored-By: Claude Opus 5.5 --- .../2026-11-26-model-cycles-held-sites.md | 1 + scripts/machine-base.py | 36 +++++++++++++++++- sdk/machines/model-cycles/LINK.md | 5 ++- .../model-cycles/elekloader/base/runtime.c | 26 ++++++++++++- sdk/tests/test_machine_base.py | 38 +++++++++++++++++++ 5 files changed, 101 insertions(+), 5 deletions(-) create mode 100644 changelog/2026-11-26-model-cycles-held-sites.md diff --git a/changelog/2026-11-26-model-cycles-held-sites.md b/changelog/2026-11-26-model-cycles-held-sites.md new file mode 100644 index 0000000000..064b607475 --- /dev/null +++ b/changelog/2026-11-26-model-cycles-held-sites.md @@ -0,0 +1 @@ +Model:Cycles base: a module loaded over USB can no longer patch over the base's own code; this takes effect when the base is next rebuilt. diff --git a/scripts/machine-base.py b/scripts/machine-base.py index 415743d9a9..1da77019cf 100644 --- a/scripts/machine-base.py +++ b/scripts/machine-base.py @@ -260,13 +260,36 @@ def retarget(mod, recipe, sites): return mod +def held_ranges(sites): + """The stock bytes a base's sites patch, as sorted address ranges with touching ones joined: [(start, end)].""" + # a site names its length (base.json, a package) or the stock bytes it replaces (an imported core's mod.json) + length = lambda site: site['len'] if 'len' in site else len(site['stock']) // 2 + spans = sorted((int(site['addr'], 16), int(site['addr'], 16) + length(site)) for site in sites) + out = [] + for start, end in spans: + if out and start <= out[-1][1]: + out[-1] = (out[-1][0], max(out[-1][1], end)) + else: + out.append((start, end)) + return out + + +def held_header(ranges): + """held-sites.h: the base's own sites for the runtime glue's patchable (a module never patches over them).""" + rows = ''.join(' {0x%08xu, 0x%08xu},\n' % r for r in ranges) + return ("/* Generated by scripts/machine-base.py from the core's and base.json's sites: the stock bytes this base patches,\n" + ' * joined into ranges. The runtime glue refuses a module site over any of them. Do not edit. */\n' + '#define MW_HELD_SITES %du\nstatic const uint32_t mw_held_sites[MW_HELD_SITES][2] = {\n%s};\n' % (len(ranges), rows)) + + def stage(machine, config, root, sites=None, add=True, recipe_sites=None, dev=False, leave=()): """The core folder and its sibling sources as mod.json expects them, with the SDK headers beside mod.json (the SDK compiles with -I on the mod's own folder first), and base.json's additions merged into the staged mod.json, so the imported files stay exact. Without `sites` (no stock OS at hand) the sites are left out; without `add` (a variant that leaves them out) only common is merged, and with no common either the imported recipe is staged alone; `leave` takes add without what its patterns match. `dev` merges base.json's dev on top, - for a development base.""" + for a development base. base.json's `version` names the base in place of the imported recipe's: the builder picks + a base's mod area by it (the kit's coreDdr).""" own = APP / 'sdk/machines' / machine / 'elekloader' source = APP / 'sdk/machines' / config.get('source', machine) / 'elekloader' mods = root / 'mods' @@ -293,14 +316,23 @@ def stage(machine, config, root, sites=None, add=True, recipe_sites=None, dev=Fa raise ValueError('base.json shared: %s takes files of sdk/runtime/ into a staged folder.' % folder) for f in files: shutil.copyfile(APP / f, mods / folder / Path(f).name) + # The base's own sites by address, stock or not at hand: the recipe's (or the imported core's) and add's. The glue + # beside runtime.c reads them as held-sites.h, so a runtime module never patches over the base (#1934's review). + glue = next((s for s in add.get('sources', []) if Path(s).name == 'runtime.c'), None) + if glue: + core_sites = config.get('recipe', {}).get('sites') or json.loads((core / 'mod.json').read_text()).get('sites', []) + (core / glue).parent.joinpath('held-sites.h').write_text(held_header(held_ranges(list(core_sites) + add.get('sites', [])))) if sites is None: add.pop('sites', None) recipe = dict(config.get('recipe', {})) if recipe_sites is None: recipe.pop('sites', None) - if add or recipe: + version = config.get('version') + if add or recipe or version: path = core / 'mod.json' mod = retarget(json.loads(path.read_text()), recipe, recipe_sites or []) + if version: + mod['version'] = version path.write_text(json.dumps(merge(mod, add, sites or []), indent=1) + '\n') return core diff --git a/sdk/machines/model-cycles/LINK.md b/sdk/machines/model-cycles/LINK.md index 1a37abb0b6..3e725346f2 100644 --- a/sdk/machines/model-cycles/LINK.md +++ b/sdk/machines/model-cycles/LINK.md @@ -111,7 +111,10 @@ detours the call that ends each composed frame and shows the frames counted; `fr creates through `0x400019ec`; caches as the Octatrack's (CACR `0xa50ce100` at boot, data ACR0 `0x4007e020`), so DDR's mirror at +0x0800_0000 is uncached, as the OS's own reverb and delay lines use it; the audio interrupt at level 5, so the loader's level-4 lock leaves it running; sites only in stock code below its `.data` image - (`0x4019b590`). + (`0x4019b590`), and never over the base's own: `machine:base` writes the core's and base.json's sites beside the + glue (`held-sites.h`) and `patchable` refuses a module site that touches one (`sdk/tests/test_machine_base.py` + checks them against the pinned package). The base recorded today was built before this check: it takes effect + with the next `machine:base -- model-cycles --write`. ## RAM boot diff --git a/sdk/machines/model-cycles/elekloader/base/runtime.c b/sdk/machines/model-cycles/elekloader/base/runtime.c index e30f0d3b3a..1b78a8ce65 100644 --- a/sdk/machines/model-cycles/elekloader/base/runtime.c +++ b/sdk/machines/model-cycles/elekloader/base/runtime.c @@ -116,6 +116,10 @@ static const struct { uint32_t tcb, stack, size; } tasks[] = { {0x40fb740cu, 0x40fb7460u, 0x8000u}, {0x40fc00c8u, 0x40fc011cu, 0x8000u}, {0x40fccb10u, 0x40fcbb10u, 0x1000u}, }; #define TASKS (sizeof tasks / sizeof tasks[0]) +/* The most spans paused() reports: the trap's registers, every task's stack, and the saved registers of every task but + * the running one: 1 + TASKS + (TASKS - 1) = 2 x TASKS, within the loader's RUNTIME_PAUSED (the Rytm's sixteen tasks + * met a guard one span too strict, owner's review of #1934, 26 November 2026). */ +_Static_assert(2u * TASKS <= RUNTIME_PAUSED, "paused() needs room for 2 x TASKS spans"); #define CURRENT_TCB 0x422fef30u #define READY_LISTS 0x422feec8u /* one head a priority; the OS creates tasks at 0 to 10 */ #define PRIORITIES 11u @@ -141,7 +145,7 @@ unsigned modwerk_machine_paused(struct runtime_span *span, unsigned max, const s { uint32_t current = U32(CURRENT_TCB); unsigned n = 0; - if (!context || !known(current) || !ready_tasks_known() || max < 2u * TASKS + 1u) return max + 1u; + if (!context || !known(current) || !ready_tasks_known() || max < 2u * TASKS) return max + 1u; span[n++] = (struct runtime_span){(const uint8_t *)context->registers, (const uint8_t *)(context->registers + 16)}; for (unsigned i = 0; i < TASKS; ++i) { uint32_t top = tasks[i].stack + tasks[i].size, saved; @@ -160,9 +164,27 @@ unsigned modwerk_machine_paused(struct runtime_span *span, unsigned max, const s int modwerk_machine_dsp_admit(const struct runtime_dsp *from, struct runtime_dsp *to) { (void)from; return to->count ? RUNTIME_MALFORMED : RUNTIME_OK; } void modwerk_machine_dsp_switch(const struct runtime_dsp *from, const struct runtime_dsp *to) { (void)from; (void)to; } +/* The base's own sites (held-sites.h, written by machine:base from the core's and base.json's): a module site over one + * would replace the base's code with what the hash thought stock (as on the Analog Rytm MKII, owner's review of #1934, + * 26 November 2026). The Octatrack keeps them in its event list. */ +#ifdef MODWERK_HOST +#if __has_include("held-sites.h") +#include "held-sites.h" +#else +#define MW_HELD_SITES 1u +static const uint32_t mw_held_sites[MW_HELD_SITES][2] = {{0x40000400u, 0x40000406u}}; +#endif +#else +#include "held-sites.h" +#endif int modwerk_machine_patchable(uint32_t address, uint32_t length) { - return address >= STOCK_FROM && address < STOCK_DATA && length <= STOCK_DATA - address; + if (!(address >= STOCK_FROM && address < STOCK_DATA && length <= STOCK_DATA - address)) + return 0; + for (unsigned i = 0; i < MW_HELD_SITES; ++i) + if (address < mw_held_sites[i][1] && mw_held_sites[i][0] < address + length) + return 0; + return 1; } /* core-mc's hooks to the live modules', in position order (README.md "Package"). A module's draw gets the core's diff --git a/sdk/tests/test_machine_base.py b/sdk/tests/test_machine_base.py index ccd520a791..c25ad089d3 100644 --- a/sdk/tests/test_machine_base.py +++ b/sdk/tests/test_machine_base.py @@ -122,6 +122,44 @@ def test_model_cycles_diagnostics_log_on_the_host(self): result = subprocess.run([temp + "/t"], capture_output=True, text=True) self.assertEqual(result.returncode, 0, result.stderr) + def test_a_model_cycles_runtime_module_never_patches_over_the_base(self): + """machine:base writes the base's own sites beside runtime.c (held-sites.h), from the core's and base.json's: + they are exactly the pinned package's sites, and the glue's patchable refuses any module site that touches one, + while stock bytes away from them stay patchable (as on the Analog Rytm MKII, owner's review of #1934).""" + import shutil, subprocess + config = json.loads((APP / "sdk/machines/model-cycles/elekloader/base.json").read_text()) + identity = json.loads((APP / "sdk/machines/model-cycles/base-binding.json").read_text())["identity"] + package = APP / "sdk/imports/packages/modwerk-base-model-cycles" / ("modwerk-base-model-cycles-%s.elemod" % identity[:8]) + with tempfile.TemporaryDirectory() as work: + core = machine_base.stage("model-cycles", config, pathlib.Path(work)) + header = (core / "../base/held-sites.h").resolve() + ranges = [(int(a, 16), int(b, 16)) for a, b in re.findall(r"\{0x([0-9a-f]+)u, 0x([0-9a-f]+)u\}", header.read_text())] + sites = json.loads(package.read_text())["sites"] + self.assertEqual(machine_base.held_ranges(sites), ranges) + cc = shutil.which("cc") + if not cc: + return + probes = [(int(site["addr"], 16), site["len"]) for site in sites] + probes = [(a, n, 0) for a, n in probes] + [(a + n - 1, 4, 0) for a, n in probes] + [(a - 2, 4, 0) for a, n in probes] + free = [(end + 0x10, 6) for end, start in zip([r[1] for r in ranges], [r[0] for r in ranges[1:]]) if start - end >= 0x20] + probes += [(a, n, 1) for a, n in free[:20]] + [(0x400003fc, 6, 0)] + rows = "".join(" {0x%08xu, %du, %d},\n" % p for p in probes) + main = pathlib.Path(work) / "main.c" + main.write_text("#include \n#include \nint modwerk_machine_patchable(uint32_t, uint32_t);\n" + "static const struct { uint32_t at, n; int ok; } p[] = {\n" + rows + "};\nint main(void) {\n" + " int bad = 0;\n for (unsigned i = 0; i < sizeof p / sizeof p[0]; ++i)\n" + " if (!modwerk_machine_patchable(p[i].at, p[i].n) != !p[i].ok) { printf(\"%x %u\\n\", (unsigned)p[i].at, (unsigned)p[i].n); bad = 1; }\n" + " return bad;\n}\n") + base, rt = header.parent, APP / "sdk/runtime" + built = subprocess.run([cc, "-std=c11", "-DMODWERK_HOST", "-DRUNTIME_MODULES=16u", "-DRUNTIME_POOL_BYTES=65536u", + "-I", base, "-I", rt / "loader", "-I", rt / "upload", main, base / "runtime.c", base / "modules.c", + rt / "loader/loader.c", rt / "upload/upload.c", rt / "upload/wire.c", rt / "upload/sha256.c", + "-o", pathlib.Path(work) / "t"], capture_output=True, text=True) + self.assertEqual(built.returncode, 0, built.stderr) + ran = subprocess.run([pathlib.Path(work) / "t"], capture_output=True, text=True) + self.assertEqual(ran.returncode, 0, "wrongly judged " + ran.stdout) + self.assertGreater(len(free), 2) + def test_model_cycles_link_on_the_host(self): """A development base's link on the host: RAMBOOT keeps an accepted request's numbers for the copy, and a reply goes out whole under stock's USB lock, never while another sender's SysEx is open.""" From 4d88c3c275384b9785a1e3b5e96a5de84ca305fa Mon Sep 17 00:00:00 2001 From: Nathaniel Pawelczyk Date: Thu, 26 Nov 2026 11:43:40 -0600 Subject: [PATCH 2/2] Fix: Model:Cycles held sites, review: an honest skip without a host compiler, the host stand-in named Co-Authored-By: Claude Opus 5.5 --- sdk/machines/model-cycles/elekloader/base/runtime.c | 2 +- sdk/tests/test_machine_base.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/machines/model-cycles/elekloader/base/runtime.c b/sdk/machines/model-cycles/elekloader/base/runtime.c index 1b78a8ce65..3ee8a3fbf2 100644 --- a/sdk/machines/model-cycles/elekloader/base/runtime.c +++ b/sdk/machines/model-cycles/elekloader/base/runtime.c @@ -170,7 +170,7 @@ void modwerk_machine_dsp_switch(const struct runtime_dsp *from, const struct run #ifdef MODWERK_HOST #if __has_include("held-sites.h") #include "held-sites.h" -#else +#else /* a stand-in for host builds without a staged header: not a real site */ #define MW_HELD_SITES 1u static const uint32_t mw_held_sites[MW_HELD_SITES][2] = {{0x40000400u, 0x40000406u}}; #endif diff --git a/sdk/tests/test_machine_base.py b/sdk/tests/test_machine_base.py index c25ad089d3..189f6bdda2 100644 --- a/sdk/tests/test_machine_base.py +++ b/sdk/tests/test_machine_base.py @@ -138,7 +138,7 @@ def test_a_model_cycles_runtime_module_never_patches_over_the_base(self): self.assertEqual(machine_base.held_ranges(sites), ranges) cc = shutil.which("cc") if not cc: - return + self.skipTest("no host C compiler: the ranges were checked, patchable was not run") probes = [(int(site["addr"], 16), site["len"]) for site in sites] probes = [(a, n, 0) for a, n in probes] + [(a + n - 1, 4, 0) for a, n in probes] + [(a - 2, 4, 0) for a, n in probes] free = [(end + 0x10, 6) for end, start in zip([r[1] for r in ranges], [r[0] for r in ranges[1:]]) if start - end >= 0x20]