mfreak-peek 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+
8
+ # Arturia's binaries are NEVER committed here. Firmware payloads, .mff
9
+ # containers, bootloader dumps and factory vocabulary are the user's own
10
+ # property and every command takes them as an explicit argument. See NOTICE.
11
+ *.mff
12
+ *.raw
13
+ *.bin
14
+ # SysEx dumps and audio the tools produce. A .syx or a .wav off the
15
+ # instrument is the user's own data, the same as the binaries above, and
16
+ # `audition` writes WAVs when pointed at a directory with --out-dir.
17
+ *.syx
18
+ *.wav
19
+
20
+ # Scratch space: anything in ignored/ stays out of git.
21
+ ignored/
22
+ .DS_Store
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,103 @@
1
+ microfreak-tools
2
+ Copyright 2025-2026 Greg Bryant
3
+
4
+ This product includes software developed as original work by the above
5
+ copyright holder, licensed under the Apache License, Version 2.0 (see
6
+ LICENSE).
7
+
8
+ It also includes third-party material, which is licensed separately and
9
+ retains its own copyright. The sections below are the attributions those
10
+ licenses require.
11
+
12
+
13
+ ================================================================================
14
+ Mutable Instruments Plaits -- MIT
15
+ ================================================================================
16
+
17
+ The MicroFreak's Speech engine is Mutable Instruments' Plaits LPC speech
18
+ synthesiser. This was established by byte-exact comparison against
19
+ `pichenettes/eurorack`, not by inference: the 14-byte frame struct, the
20
+ 15-entry phoneme table, the quantisation lookup tables, the 640-entry
21
+ excitation pulse, and the word banks all match the published MIT source
22
+ value for value. The evidence is recorded in the companion
23
+ analysis repository, microfreak-emu.
24
+
25
+ Because that upstream source is MIT, the tables in this repository are
26
+ redistributable under the terms below. They are Emilie Gillet's work, not
27
+ Arturia's and not this project's.
28
+
29
+ The following files contain material derived from `pichenettes/eurorack`:
30
+
31
+ microfreak/lpc.py
32
+ the energy, period and k0..k9 quantisation tables, and
33
+ the LPC bitstream layout, from
34
+ plaits/dsp/speech/lpc_speech_synth_controller.cc and
35
+ plaits/dsp/speech/lpc_speech_synth.h
36
+
37
+ plugins/speech/mfreak_speech/render.py
38
+ a Python port of LPCSpeechSynth, and the 640-entry
39
+ int8 excitation pulse `lut_lpc_excitation_pulse`,
40
+ from plaits/dsp/speech/lpc_speech_synth.cc and
41
+ plaits/resources.cc
42
+
43
+ Copyright 2016 Emilie Gillet.
44
+
45
+ Author: Emilie Gillet (emilie.o.gillet@gmail.com)
46
+
47
+ Permission is hereby granted, free of charge, to any person obtaining a copy
48
+ of this software and associated documentation files (the "Software"), to deal
49
+ in the Software without restriction, including without limitation the rights
50
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
51
+ copies of the Software, and to permit persons to whom the Software is
52
+ furnished to do so, subject to the following conditions:
53
+
54
+ The above copyright notice and this permission notice shall be included in
55
+ all copies or substantial portions of the Software.
56
+
57
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
58
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
59
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
60
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
61
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
62
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
63
+ THE SOFTWARE.
64
+
65
+
66
+ ================================================================================
67
+ Texas Instruments LPC10 speech data -- NOT redistributed
68
+ ================================================================================
69
+
70
+ Plaits' five factory word banks are, in its own description, "LPC10-encoded
71
+ speech data extracted from Texas Instruments ROMs". The MicroFreak's banks
72
+ match them byte for byte.
73
+
74
+ This repository does not contain that data and must not come to contain it.
75
+ The tooling reads the banks out of a firmware image the user already owns,
76
+ at run time, and never writes them into source or into a committed artefact.
77
+ Keep it that way: the MIT licence covering the Plaits code around them is
78
+ not an obvious grant for speech recorded off a TI ROM, and nothing here
79
+ depends on redistributing it.
80
+
81
+
82
+ ================================================================================
83
+ Arturia -- no code, no binaries, no affiliation
84
+ ================================================================================
85
+
86
+ This project is not affiliated with, authorised by, endorsed by or connected
87
+ to Arturia in any way. "Arturia" and "MicroFreak" are trademarks of their
88
+ respective owners and are used here only to identify the hardware this
89
+ tooling was written for.
90
+
91
+ No Arturia code or data is included in this repository, and none should
92
+ ever be added to it. There are no firmware images, no bootloader dumps, no
93
+ factory vocabulary banks, no factory presets and no protocol captures here --
94
+ not gitignored copies of them, not samples of them, none. `.gitignore` refuses
95
+ `*.mff`, `*.raw` and `*.bin` as a second line of defence, but the first is that
96
+ every command takes the file it needs as an explicit argument.
97
+
98
+ Nothing is downloaded either. `fw patch` requires `--image`, pointing at a
99
+ payload you already own, and refuses any payload whose sha256 is not the one
100
+ its addresses were derived against.
101
+
102
+ Source comments and docstrings here describe observed behaviour and give
103
+ addresses within a firmware image. They do not reproduce it.
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.5
2
+ Name: mfreak-peek
3
+ Version: 0.1.0
4
+ Summary: A read-only diagnostic MicroFreak firmware patch, and a bootloader dump, for microfreak-tools. Not affiliated with Arturia.
5
+ Project-URL: Homepage, https://github.com/gbryant/microfreak-tools
6
+ Project-URL: Issues, https://github.com/gbryant/microfreak-tools/issues
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ License-File: NOTICE
10
+ Requires-Python: <3.15,>=3.11
11
+ Requires-Dist: microfreak-tools<0.2,>=0.1.0
12
+ Description-Content-Type: text/markdown
13
+
14
+ # mfreak-peek
15
+
16
+ A read-only diagnostic firmware patch for the Arturia MicroFreak, and a
17
+ bootloader dump. A plugin for
18
+ [microfreak-tools](https://github.com/gbryant/microfreak-tools). Not
19
+ affiliated with Arturia.
20
+
21
+ uv tool install microfreak-tools --with mfreak-peek
22
+
23
+ The patch is stock firmware that can also read its own memory over SysEx.
24
+ Installing it writes flash:
25
+
26
+ mfreak fw patch peek MicroFreak_Firmware_Update_5_0_0_2084.mff --out peek.mff
27
+ mfreak fw flash peek.mff
28
+ mfreak peek dump-bootloader --out bootloader.bin
29
+
30
+ The bootloader dump contains your instrument's serial number. Keep it
31
+ private. To remove the patch, flash the stock `.mff`. Read "Before you
32
+ flash" in the microfreak-tools README first.
33
+
34
+ Apache-2.0.
@@ -0,0 +1,21 @@
1
+ # mfreak-peek
2
+
3
+ A read-only diagnostic firmware patch for the Arturia MicroFreak, and a
4
+ bootloader dump. A plugin for
5
+ [microfreak-tools](https://github.com/gbryant/microfreak-tools). Not
6
+ affiliated with Arturia.
7
+
8
+ uv tool install microfreak-tools --with mfreak-peek
9
+
10
+ The patch is stock firmware that can also read its own memory over SysEx.
11
+ Installing it writes flash:
12
+
13
+ mfreak fw patch peek MicroFreak_Firmware_Update_5_0_0_2084.mff --out peek.mff
14
+ mfreak fw flash peek.mff
15
+ mfreak peek dump-bootloader --out bootloader.bin
16
+
17
+ The bootloader dump contains your instrument's serial number. Keep it
18
+ private. To remove the patch, flash the stock `.mff`. Read "Before you
19
+ flash" in the microfreak-tools README first.
20
+
21
+ Apache-2.0.
@@ -0,0 +1,22 @@
1
+ """mfreak-peek: a read-only diagnostic firmware, and the commands that use it."""
2
+ from microfreak.plugin import Command, Firmware, Plugin
3
+
4
+ plugin = Plugin(
5
+ name="peek",
6
+ help="read the instrument's memory, and dump your bootloader",
7
+ doctor="mfreak_peek.doctor",
8
+ firmware=Firmware(
9
+ "mfreak_peek.build",
10
+ help="stock firmware that can also read its own memory",
11
+ identity="P"),
12
+ commands={
13
+ "dump-bootloader": Command(
14
+ "mfreak_peek.bootloader",
15
+ help="read your bootloader out (the file holds your serial)",
16
+ device=True, writes="file",
17
+ summary="Read your bootloader out over MIDI. Read-only on the "
18
+ "device. THE FILE CONTAINS YOUR SERIAL NUMBER: do not "
19
+ "publish it, or use --redact-serial. Needs the peek "
20
+ "build flashed first."),
21
+ },
22
+ )
@@ -0,0 +1,200 @@
1
+ #!/usr/bin/env python3
2
+ """Read your instrument's bootloader out of flash, over MIDI.
3
+
4
+ mfreak fw patch peek stock.mff --out peek.mff
5
+ mfreak fw flash peek.mff
6
+ mfreak peek dump-bootloader --out bootloader.bin
7
+ mfreak fw flash stock.mff
8
+
9
+ Arturia's firmware files do not include the 48 KB bootloader, so this is the
10
+ only way to get a copy. It needs the peek build installed. It only reads,
11
+ and writes nothing to the instrument.
12
+
13
+ The file contains your instrument's serial number. Do not publish it, attach
14
+ it to a bug report, or commit it. --redact-serial zeroes the serial; the rest
15
+ of the factory data page is written as read.
16
+
17
+ microfreak-emu boots the real bootloader from this file: put it in that
18
+ repository's data/bootloader/ folder.
19
+ """
20
+ import argparse
21
+ import random
22
+ import sys
23
+ import time
24
+
25
+ from microfreak.firmware.peek import peek_reply
26
+ from mfreak_peek.build import peek_message_nibble
27
+ from microfreak.midi import open_synth, checksum_free_seq
28
+ from microfreak import jsonout
29
+
30
+ BASE = 0x08000000
31
+ SIZE = 48 << 10 # sectors 0, 1 and 2
32
+ WORDS = SIZE // 4
33
+
34
+ # The factory data page, and the serial's offset inside it. Measured: the page
35
+ # starts at 0x08008000 and the serial is its first record -- sixteen ASCII
36
+ # digits that fill the field exactly, with the NUL terminator after it at
37
+ # +0x10, outside the field and outside what `redact` touches.
38
+ DATA_PAGE = 0x08008000
39
+ SERIAL_OFF, SERIAL_LEN = 0x00, 0x10
40
+
41
+
42
+ def peek_word(synth, addr, seqgen, tries=4):
43
+ """-> the 32-bit word at `addr`, or None.
44
+
45
+ A blocked or never-dispatched peek STILL REPLIES, carrying whatever the
46
+ last successful one left in the septet slots, and the sequence number does
47
+ not catch it -- the dispatcher refreshes seq from the incoming message, so
48
+ a stale reply passes a seq check. That is why the dump is verified by
49
+ re-reading a sample afterwards rather than trusted request by request.
50
+ """
51
+ for _ in range(tries):
52
+ seq = next(seqgen)
53
+ synth.send(list(peek_message_nibble(addr, seq=seq)))
54
+ try:
55
+ reply = synth.recv(
56
+ lambda m: peek_reply(bytes(m), seq=seq) is not None, timeout=2.0)
57
+ except TimeoutError:
58
+ continue
59
+ word = peek_reply(bytes(reply), seq=seq)
60
+ if word is not None:
61
+ return word
62
+ return None
63
+
64
+
65
+ def looks_like_a_vector_table(words):
66
+ """Is this actually the bootloader? -> (ok, why).
67
+
68
+ Three structural facts, all of them true of any Cortex-M image and none of
69
+ them true of a buffer of zeros, a buffer of 0xFF or a stale-reply smear:
70
+ the initial SP points into this chip's SRAM, the reset vector points into
71
+ the low 48 KB with the Thumb bit set, and the two differ.
72
+ """
73
+ if len(words) < 2:
74
+ return False, "no data"
75
+ sp, reset = words[0], words[1]
76
+ if not 0x20000000 <= sp <= 0x20020000:
77
+ return False, ("initial SP reads 0x%08X, which is not SRAM on this "
78
+ "part -- the reads are not returning flash" % sp)
79
+ if not (BASE <= (reset & ~1) < BASE + SIZE):
80
+ return False, ("reset vector reads 0x%08X, which is not inside the "
81
+ "bootloader" % reset)
82
+ if not reset & 1:
83
+ return False, ("reset vector 0x%08X has the Thumb bit clear, which no "
84
+ "Cortex-M image has" % reset)
85
+ if len(set(words[:16])) < 4:
86
+ return False, ("the first 16 vectors are nearly all the same value, "
87
+ "which is what a stale-reply smear looks like")
88
+ return True, "SP 0x%08X, reset 0x%08X" % (sp, reset)
89
+
90
+
91
+ def redact(blob):
92
+ """Zero the serial's sixteen bytes. -> (blob, what was there).
93
+
94
+ Only those bytes. The rest of the factory data page is left as read.
95
+ """
96
+ off = DATA_PAGE - BASE + SERIAL_OFF
97
+ was = bytes(blob[off:off + SERIAL_LEN])
98
+ text = "".join(chr(b) if 0x20 <= b < 0x7F else "." for b in was)
99
+ blob[off:off + SERIAL_LEN] = b"\0" * SERIAL_LEN
100
+ return blob, text
101
+
102
+
103
+ def main():
104
+ ap = argparse.ArgumentParser(
105
+ description=__doc__.splitlines()[0],
106
+ epilog="\n".join(__doc__.splitlines()[1:]),
107
+ formatter_class=argparse.RawDescriptionHelpFormatter)
108
+ ap.add_argument("--out", required=True, metavar="FILE",
109
+ help="where to write the 48 KB image")
110
+ ap.add_argument("--port", default="MicroFreak",
111
+ help="MIDI port substring (default: MicroFreak)")
112
+ ap.add_argument("--verify", type=int, default=256, metavar="N",
113
+ help="re-read N random words afterwards and compare; "
114
+ "0 skips it, which is not recommended (default: 256)")
115
+ ap.add_argument("--redact-serial", action="store_true",
116
+ help="blank the serial number in the output")
117
+ args = ap.parse_args()
118
+
119
+ synth = open_synth(port_substring=args.port)
120
+ seqgen = checksum_free_seq()
121
+ print("reading 0x%08X..0x%08X (%d words) over MIDI" % (BASE, BASE + SIZE, WORDS))
122
+ print("this needs the peek build: `mfreak fw patch peek`\n")
123
+
124
+ blob = bytearray(SIZE)
125
+ started = time.time()
126
+ missing = []
127
+ for i in range(WORDS):
128
+ addr = BASE + i * 4
129
+ word = peek_word(synth, addr, seqgen)
130
+ if word is None:
131
+ missing.append(addr)
132
+ word = 0xFFFFFFFF
133
+ blob[i * 4:i * 4 + 4] = word.to_bytes(4, "little")
134
+ if i % 256 == 0 or i == WORDS - 1:
135
+ done = i + 1
136
+ rate = done / max(time.time() - started, 0.001)
137
+ print("\r %5d/%d words %5.1f%% %4.0f words/s %d failed"
138
+ % (done, WORDS, 100.0 * done / WORDS, rate, len(missing)),
139
+ end="", flush=True)
140
+ print()
141
+
142
+ words = [int.from_bytes(blob[k:k + 4], "little") for k in range(0, 64, 4)]
143
+ ok, why = looks_like_a_vector_table(words)
144
+ print("\nvector table: %s (%s)" % ("plausible" if ok else "WRONG", why))
145
+ if not ok:
146
+ print("\nRefusing to write it. Nothing here is a bootloader.", file=sys.stderr)
147
+ return 1
148
+ if missing:
149
+ print("%d words never answered and are 0xFFFFFFFF in the file: %s%s"
150
+ % (len(missing), ", ".join("0x%08X" % a for a in missing[:6]),
151
+ " ..." if len(missing) > 6 else ""))
152
+
153
+ if args.verify:
154
+ n = min(args.verify, WORDS)
155
+ print("\nverifying %d random words" % n)
156
+ bad = []
157
+ for addr in sorted(random.sample(range(WORDS), n)):
158
+ again = peek_word(synth, BASE + addr * 4, seqgen)
159
+ first = int.from_bytes(blob[addr * 4:addr * 4 + 4], "little")
160
+ if again is not None and again != first:
161
+ bad.append((BASE + addr * 4, first, again))
162
+ if bad:
163
+ print(" %d of %d disagreed on a re-read:" % (len(bad), n))
164
+ for a, f, s in bad[:8]:
165
+ print(" 0x%08X 0x%08X -> 0x%08X" % (a, f, s))
166
+ print("\nRe-reads disagree, so the dump cannot be trusted. "
167
+ "Not writing it.", file=sys.stderr)
168
+ return 1
169
+ print(" all %d agreed" % n)
170
+
171
+ if args.redact_serial:
172
+ blob, was = redact(blob)
173
+ # Do NOT echo the serial. The whole point of this flag is a file that
174
+ # is safe to share, and the terminal is the thing people paste into
175
+ # bug reports. Report the length so it is clear something was there.
176
+ blanked = sum(1 for c in was if c != ".")
177
+ print("\nserial field blanked: %d bytes at 0x%08X+0x%X, %d of them "
178
+ "printable."
179
+ % (SERIAL_LEN, DATA_PAGE, SERIAL_OFF, blanked))
180
+ else:
181
+ print("\n*** This file contains your instrument's SERIAL NUMBER, in the")
182
+ print("*** factory data page at 0x%08X. Do not publish it. Re-run with" % DATA_PAGE)
183
+ print("*** --redact-serial to zero those sixteen bytes.")
184
+
185
+ with open(args.out, "wb") as fh:
186
+ fh.write(bytes(blob))
187
+ # A caller has to know whether the file it now holds carries the serial.
188
+ jsonout.result(out=args.out, bytes=len(blob),
189
+ serial_redacted=bool(args.redact_serial),
190
+ contains_serial=not args.redact_serial,
191
+ do_not_publish=not args.redact_serial)
192
+ print("\nwrote %s, %d bytes" % (args.out, len(blob)))
193
+ print("Use it with microfreak-emu: cp %s <microfreak-emu>/data/bootloader/"
194
+ % args.out)
195
+ print("Then put your own firmware back on the instrument.")
196
+ return 0
197
+
198
+
199
+ if __name__ == "__main__":
200
+ sys.exit(main())
@@ -0,0 +1,295 @@
1
+ """A read-only diagnostic build: stock firmware that can also read its own
2
+ memory, flash included. `mfreak peek dump-bootloader` needs it.
3
+
4
+ mfreak fw patch peek MicroFreak_Firmware_Update_5_0_0_2084.mff --out peek.mff
5
+ mfreak fw flash peek.mff
6
+
7
+ Apart from that, the boot screen reads PATCHED peek18, asked for its version
8
+ over MIDI it answers 5.0.P, build 18, and a fault reboots the instrument
9
+ instead of hanging it. Flash the stock .mff again when you are done.
10
+ """
11
+ import argparse
12
+ import struct
13
+ import sys
14
+
15
+ from microfreak.firmware import patching as F
16
+ from microfreak.firmware.patching import (BASE, OPCODE_BIAS, OPCODE_MAGIC,
17
+ OPCODE_TAIL, REPLY_BUILDER,
18
+ REPLY_CODE, assemble, beqw, bw)
19
+ from microfreak.firmware.peek import PEEK_BASE, PEEK_OPCODE, PEEK_SPAN
20
+
21
+ FLAVOUR, REV = "peek", 19
22
+ NIBBLE_OPCODE = 0x46 # the nibble-addressed read
23
+
24
+ # Every fault vector points at the `b .` at 0x0805F89C: NMI, HardFault,
25
+ # MemManage, BusFault, UsageFault and every unused IRQ. This build points them
26
+ # at `fault_handler` instead.
27
+ DEFAULT_HANDLER = 0x0805F89D # Thumb bit set
28
+ VECTOR_TABLE = 0x0800C000 # the image base is the vector table
29
+ NUM_VECTORS = 0x1A0 // 4
30
+
31
+ # The reset handler zeroes .bss only up to 0x2001F230, and 0x2001F238..
32
+ # 0x2001FB00 is never touched in normal running, so the dump goes there.
33
+ FAULT_DUMP = 0x2001F240
34
+ FAULT_MAGIC = 0xFA017DEA
35
+ SCB_BASE = 0xE000ED00
36
+
37
+ # What the handler writes, in order. Read it with the nibble opcode: the
38
+ # septet form of its address is one the septet read cannot send safely.
39
+ FAULT_FIELDS = ["magic", "ICSR", "CFSR", "HFSR", "MMFAR", "BFAR",
40
+ "stacked_PC", "stacked_LR", "stacked_xPSR", "frame_SP"]
41
+
42
+
43
+ def fault_handler(base, dump_at=FAULT_DUMP, resume=False):
44
+ """-> bytes. Record why the instrument faulted, then reset.
45
+
46
+ Writes the ten FAULT_FIELDS words at `dump_at`. With `resume` it instead
47
+ skips the faulting instruction and returns, so the dump can be read at
48
+ once; a reset clears it. A fault that repeats under `resume` loops, which
49
+ hangs the instrument like the stock handler does.
50
+ """
51
+ src = """
52
+ mrs r0, msp // handler mode always runs on MSP...
53
+ tst lr, #4 // ...but the FRAME may be on PSP
54
+ beq 1f
55
+ mrs r0, psp
56
+ 1: movw r1, #%#x
57
+ movt r1, #%#x
58
+ movw r2, #%#x
59
+ movt r2, #%#x
60
+ ldr r3, [r1, #0x04] // ICSR -- VECTACTIVE says WHICH exception
61
+ str r3, [r2, #4]
62
+ ldr r3, [r1, #0x28] // CFSR
63
+ str r3, [r2, #8]
64
+ ldr r3, [r1, #0x2c] // HFSR
65
+ str r3, [r2, #12]
66
+ ldr r3, [r1, #0x34] // MMFAR
67
+ str r3, [r2, #16]
68
+ ldr r3, [r1, #0x38] // BFAR
69
+ str r3, [r2, #20]
70
+ ldr r3, [r0, #24] // stacked PC -- the faulting instruction
71
+ str r3, [r2, #24]
72
+ ldr r3, [r0, #20] // stacked LR
73
+ str r3, [r2, #28]
74
+ ldr r3, [r0, #28] // stacked xPSR
75
+ str r3, [r2, #32]
76
+ str r0, [r2, #36] // the frame pointer itself
77
+ movw r3, #%#x
78
+ movt r3, #%#x
79
+ str r3, [r2, #0] // magic LAST: present => the rest is complete
80
+ """ % (SCB_BASE & 0xFFFF, SCB_BASE >> 16,
81
+ dump_at & 0xFFFF, dump_at >> 16,
82
+ FAULT_MAGIC & 0xFFFF, FAULT_MAGIC >> 16)
83
+ if resume:
84
+ src += """
85
+ ldr r2, [r0, #24] // stacked PC
86
+ ldrh r3, [r2] // its first halfword
87
+ movw r12, #0xe800 // >= 0xE800 means a 32-bit Thumb encoding
88
+ cmp r3, r12
89
+ ite lo
90
+ addlo r2, r2, #2
91
+ addhs r2, r2, #4
92
+ str r2, [r0, #24] // resume PAST the faulting instruction
93
+ mvn r3, #0
94
+ str r3, [r1, #0x28] // CFSR is write-1-to-clear
95
+ str r3, [r1, #0x2c] // HFSR likewise
96
+ dsb
97
+ isb
98
+ bx lr // EXC_RETURN: back to the thread
99
+ """
100
+ else:
101
+ src += """
102
+ dsb
103
+ movw r3, #0x0004
104
+ movt r3, #0x05fa
105
+ str r3, [r1, #0x0c] // SCB->AIRCR = SYSRESETREQ
106
+ dsb
107
+ 2: b 2b // the reset lands before this spins twice
108
+ """
109
+ return assemble(src)
110
+
111
+
112
+ def decode_fault(words):
113
+ """-> a readable dump, or None if the magic is absent."""
114
+ if not words or words[0] != FAULT_MAGIC:
115
+ return None
116
+ out, icsr = {}, words[1]
117
+ for name, v in zip(FAULT_FIELDS, words):
118
+ out[name] = v
119
+ out["vectactive"] = icsr & 0x1FF
120
+ out["exception"] = {2: "NMI", 3: "HardFault", 4: "MemManage", 5: "BusFault",
121
+ 6: "UsageFault"}.get(icsr & 0x1FF,
122
+ "IRQ %d" % ((icsr & 0x1FF) - 16))
123
+ cfsr = out["CFSR"]
124
+ out["cfsr_bits"] = [n for b, n in (
125
+ (0, "IACCVIOL"), (1, "DACCVIOL"), (3, "MUNSTKERR"), (4, "MSTKERR"),
126
+ (7, "MMARVALID"), (8, "IBUSERR"), (9, "PRECISERR"), (10, "IMPRECISERR"),
127
+ (11, "UNSTKERR"), (12, "STKERR"), (15, "BFARVALID"),
128
+ (16, "UNDEFINSTR"), (17, "INVSTATE"), (18, "INVPC"), (19, "NOCP"),
129
+ (24, "UNALIGNED"), (25, "DIVBYZERO")) if cfsr & (1 << b)]
130
+ out["hfsr_bits"] = [n for b, n in (
131
+ (1, "VECTTBL"), (30, "FORCED"), (31, "DEBUGEVT"))
132
+ if out["HFSR"] & (1 << b)]
133
+ return out
134
+
135
+
136
+ def peek_only_handlers(base, peek_base=None, letter="P", rev=None):
137
+ """-> bytes: two read handlers and the identity, entered from the dispatcher.
138
+
139
+ opcode 0x44 three septets, ORed onto `peek_base`
140
+ opcode 0x46 eight nibbles, high first: the full 32-bit address
141
+ opcode 0x48 the build's letter and revision, F.who_word
142
+
143
+ Both need the magic in `cat`. A message without it still gets a reply, so
144
+ the host can tell a refused read from a hung instrument.
145
+ """
146
+ pb = PEEK_BASE if peek_base is None else peek_base
147
+ src = """
148
+ cmp r2, #%#x // the nibble opcode, biased
149
+ nop // -> beq.w the nibble handler
150
+ nop
151
+
152
+ ldrb r0, [r5, #6] // magic guard
153
+ cmp r0, #%#x
154
+ bne 8f
155
+ cmp r2, #%#x // 0x48, biased
156
+ beq 4f
157
+
158
+ ldrb r0, [r5, #8] // --- 0x44: three septets
159
+ ldrb r1, [r5, #9]
160
+ ldrb r2, [r5, #10]
161
+ orr r0, r0, r1, lsl #7
162
+ orr r0, r0, r2, lsl #14
163
+ orr r0, r0, #%#x
164
+ b 7f
165
+
166
+ 4: movw r0, #%#x // --- 0x48: who this is
167
+ b 5f
168
+
169
+ 9: ldrb r0, [r5, #6] // --- 0x46: eight nibbles, full 32 bits
170
+ cmp r0, #%#x
171
+ bne 8f
172
+ movs r0, #0
173
+ movs r2, #8
174
+ add r1, r5, #8
175
+ 6: ldrb r3, [r1]
176
+ and r3, r3, #0x0f
177
+ orr r0, r3, r0, lsl #4
178
+ adds r1, r1, #1
179
+ subs r2, r2, #1
180
+ bne 6b
181
+
182
+ 7: ldr r0, [r0] // the one load, shared
183
+ 5: movs r2, #5
184
+ add r1, r4, #1
185
+ 1: and r3, r0, #0x7f
186
+ strb r3, [r1]
187
+ adds r1, r1, #1
188
+ lsrs r0, r0, #7
189
+ subs r2, r2, #1
190
+ bne 1b
191
+ movs r3, #%#x
192
+ nop // -> b.w REPLY_BUILDER
193
+ nop
194
+
195
+ 8: nop // -> b.w OPCODE_TAIL (guard bailed, replies)
196
+ nop
197
+ """ % (NIBBLE_OPCODE - OPCODE_BIAS, OPCODE_MAGIC, F.WHO_OPCODE - OPCODE_BIAS,
198
+ pb, F.who_word(letter, REV if rev is None else rev), OPCODE_MAGIC,
199
+ REPLY_CODE)
200
+ code = bytearray(assemble(src))
201
+
202
+ # Patch the three wide branches by locating their placeholders, so a change
203
+ # to the source above cannot silently patch the wrong bytes.
204
+ cmp_nib = bytes([(NIBBLE_OPCODE - OPCODE_BIAS) & 0xFF, 0x2A, 0x00, 0xBF, 0x00, 0xBF])
205
+ at = code.find(cmp_nib)
206
+ if at != 0:
207
+ sys.exit("nibble dispatch placeholder at %d, expected 0" % at)
208
+ # The two trailing placeholders are the last 8 bytes: reply tail, then bail.
209
+ reply_at, bail_at = len(code) - 8, len(code) - 4
210
+ code[2:6] = beqw(base + 2, base + _nibble_entry(code))
211
+ code[reply_at:reply_at + 4] = bw(base + reply_at, REPLY_BUILDER)
212
+ code[bail_at:bail_at + 4] = bw(base + bail_at, OPCODE_TAIL)
213
+ return bytes(code)
214
+
215
+
216
+ def _nibble_entry(code):
217
+ """-> the offset of the nibble arm in `peek_only_handlers`: the second
218
+ `ldrb r0,[r5,#6]`, because that arm repeats the guard.
219
+ """
220
+ pat = assemble("ldrb r0, [r5, #6]")
221
+ first = code.find(pat)
222
+ second = code.find(pat, first + 1)
223
+ if first < 0 or second < 0:
224
+ sys.exit("could not locate the nibble arm's guard")
225
+ return second
226
+
227
+
228
+ def apply(img, peek_base=None, fault=True, fault_resume=False):
229
+ """Patch `img` in place. -> a report dict."""
230
+ code = peek_only_handlers(F.CODE_BASE, peek_base=peek_base)
231
+ trimmed = F.make_room(img)
232
+ end = F.place(img, F.CODE_BASE, code, "the read handlers")
233
+ fault_at = fend = None
234
+ repointed = []
235
+ if fault:
236
+ fault_at = (end + 1) & ~1
237
+ fend = F.place(img, fault_at, fault_handler(
238
+ fault_at, dump_at=FAULT_DUMP, resume=fault_resume), "fault handler")
239
+ for i in range(NUM_VECTORS):
240
+ at = VECTOR_TABLE + i * 4
241
+ if struct.unpack_from("<I", img, at - BASE)[0] == DEFAULT_HANDLER:
242
+ struct.pack_into("<I", img, at - BASE, fault_at | 1)
243
+ repointed.append(i)
244
+ if not repointed:
245
+ sys.exit("no vector points at the 0x%08X default handler; the "
246
+ "image is not what this expects" % DEFAULT_HANDLER)
247
+ end = fend
248
+ tramp = F.route(img, (PEEK_OPCODE, NIBBLE_OPCODE, F.WHO_OPCODE), F.CODE_BASE)
249
+ F.stamp_version(img, FLAVOUR, REV)
250
+ return dict(handler=(F.CODE_BASE, len(code)), trimmed=trimmed,
251
+ used=end - F.CODE_BASE, tramp=tramp,
252
+ fault=((fault_at, fend - fault_at) if fault else None),
253
+ fault_resume=fault_resume, fault_vectors=len(repointed),
254
+ peek_base=PEEK_BASE if peek_base is None else peek_base)
255
+
256
+
257
+ def add_arguments(ap):
258
+ hide = argparse.SUPPRESS
259
+ ap.add_argument("--fault-resume", action="store_true", help=hide)
260
+ ap.add_argument("--peek-base", type=lambda x: int(x, 0), default=None,
261
+ metavar="ADDR", help=hide)
262
+
263
+
264
+ def build(img, args):
265
+ rep = apply(img, peek_base=args.peek_base, fault_resume=args.fault_resume)
266
+ pb = rep["peek_base"]
267
+ print("handler 0x%08X %d bytes" % rep["handler"])
268
+ print(" opcode 0x%02X three septets, window 0x%08X..0x%08X"
269
+ % (PEEK_OPCODE, pb, pb | PEEK_SPAN))
270
+ print(" opcode 0x%02X eight nibbles, the full 32-bit address"
271
+ % NIBBLE_OPCODE)
272
+ print(" both need cat = 0x%02X; without it they still reply"
273
+ % OPCODE_MAGIC)
274
+ print("trampoline 0x%08X 4 bytes (spends opcodes 0x%02X and 0x%02X)"
275
+ % (rep["tramp"][0], F.SPENT[0], F.SPENT[1]))
276
+ if rep["fault"]:
277
+ print("fault 0x%08X %d bytes, %d hang-forever vectors repointed "
278
+ "at it" % (rep["fault"] + (rep["fault_vectors"],)))
279
+ print(" writes its dump to 0x%08X, then %s"
280
+ % (FAULT_DUMP, "skips the faulting instruction"
281
+ if rep["fault_resume"] else "resets"))
282
+ F.report_banner(img)
283
+ F.report_room(rep["trimmed"], rep["used"])
284
+
285
+
286
+ def peek_message_nibble(addr, seq=0, cat=OPCODE_MAGIC):
287
+ """A read request addressed as eight nibbles, high first. -> raw SysEx.
288
+
289
+ Any 32-bit address, flash or SRAM. Only this build answers it.
290
+ """
291
+ if addr & 3:
292
+ sys.exit("0x%08X is not word-aligned; peek reads a 32-bit word." % addr)
293
+ nibbles = [(addr >> sh) & 0xF for sh in (28, 24, 20, 16, 12, 8, 4, 0)]
294
+ return bytes([0xF0, 0x00, 0x20, 0x6B, 0x07, 0x01, seq, cat, NIBBLE_OPCODE]
295
+ + nibbles + [0xF7])
@@ -0,0 +1,9 @@
1
+ """`mfreak doctor` checks for the peek plugin."""
2
+ from microfreak import plugin
3
+
4
+
5
+ def device(r, mo, mi, args, reply):
6
+ if plugin.running(reply)[0] == "peek":
7
+ r.ok("peek build", "running; `mfreak peek dump-bootloader` will work")
8
+ else:
9
+ r.note("peek build", "not running; only `peek dump-bootloader` needs it")
@@ -0,0 +1,26 @@
1
+ [project]
2
+ name = "mfreak-peek"
3
+ version = "0.1.0"
4
+ description = "A read-only diagnostic MicroFreak firmware patch, and a bootloader dump, for microfreak-tools. Not affiliated with Arturia."
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE", "NOTICE"]
8
+ requires-python = ">=3.11,<3.15"
9
+ dependencies = ["microfreak-tools>=0.1.0,<0.2"]
10
+
11
+ [project.entry-points."mfreak.plugins"]
12
+ peek = "mfreak_peek:plugin"
13
+
14
+ [project.urls]
15
+ Homepage = "https://github.com/gbryant/microfreak-tools"
16
+ Issues = "https://github.com/gbryant/microfreak-tools/issues"
17
+
18
+ [build-system]
19
+ requires = ["hatchling"]
20
+ build-backend = "hatchling.build"
21
+
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["mfreak_peek"]
24
+
25
+ [tool.uv.sources]
26
+ microfreak-tools = { workspace = true }