microgoose 0.1.1__py3-none-any.whl
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.
- microgoose/__init__.py +2 -0
- microgoose/__main__.py +3 -0
- microgoose/cli.py +108 -0
- microgoose/core.py +374 -0
- microgoose/goose.py +122 -0
- microgoose/templates/components/microgoose/CMakeLists.txt +26 -0
- microgoose/templates/components/microgoose/Kconfig +12 -0
- microgoose/templates/components/microgoose/compat/dlfcn.h +11 -0
- microgoose/templates/components/microgoose/compat/mg_prefix.h +45 -0
- microgoose/templates/components/microgoose/compat/sys/mman.h +25 -0
- microgoose/templates/components/microgoose/include/microgoose.h +39 -0
- microgoose/templates/components/microgoose/mg_compat.c +228 -0
- microgoose/templates/components/microgoose/mg_hal.c +131 -0
- microgoose/templates/components/microgoose/mg_main.c +92 -0
- microgoose/templates/examples/blink.goose +20 -0
- microgoose/templates/examples/hello.goose +17 -0
- microgoose/templates/examples/overflow.goose +11 -0
- microgoose/templates/examples/sieve.goose +19 -0
- microgoose/templates/examples/threads.goose +33 -0
- microgoose/templates/firmware/CMakeLists.txt +4 -0
- microgoose/templates/firmware/platformio.ini +19 -0
- microgoose/templates/firmware/sdkconfig.defaults +17 -0
- microgoose/templates/firmware/sdkconfig.defaults.esp32 +4 -0
- microgoose/templates/firmware/sdkconfig.defaults.esp32s3 +3 -0
- microgoose/templates/firmware/src/CMakeLists.txt +5 -0
- microgoose/templates/lib/esp.goose +29 -0
- microgoose/templates/ports/stm32h7/include/dirent.h +11 -0
- microgoose/templates/ports/stm32h7/include/mg_baremetal.h +11 -0
- microgoose/templates/ports/stm32h7/include/pthread.h +36 -0
- microgoose/templates/ports/stm32h7/platformio.ini +19 -0
- microgoose/templates/ports/stm32h7/src/mg_h7.c +538 -0
- microgoose-0.1.1.dist-info/METADATA +130 -0
- microgoose-0.1.1.dist-info/RECORD +36 -0
- microgoose-0.1.1.dist-info/WHEEL +4 -0
- microgoose-0.1.1.dist-info/entry_points.txt +2 -0
- microgoose-0.1.1.dist-info/licenses/LICENSE +201 -0
microgoose/__init__.py
ADDED
microgoose/__main__.py
ADDED
microgoose/cli.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""The `microgoose` command (also `python -m microgoose`, and `python mg.py` in a checkout)."""
|
|
2
|
+
import argparse
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from . import __version__, core
|
|
9
|
+
from .goose import GOOSE_VERSION, ensure_goose
|
|
10
|
+
|
|
11
|
+
EPILOG = """\
|
|
12
|
+
examples:
|
|
13
|
+
microgoose new blinky --example blink start a project from an example
|
|
14
|
+
microgoose run blinky/main.goose build, flash, show the output (ESP32-S3)
|
|
15
|
+
microgoose run main.goose --target h7 STM32H743 over ST-Link
|
|
16
|
+
microgoose build main.goose --reserve 64K bigger data stacks
|
|
17
|
+
|
|
18
|
+
targets:
|
|
19
|
+
""" + "\n".join(f" {k:6} {v['about']}" for k, v in core.TARGETS.items()) + """
|
|
20
|
+
|
|
21
|
+
environment:
|
|
22
|
+
MG_TARGET default --target
|
|
23
|
+
MG_PORT serial port for the ESP32 targets (e.g. COM5, /dev/ttyUSB0)
|
|
24
|
+
GOOSE use this Goose compiler instead of the pinned download
|
|
25
|
+
MICROGOOSE_HOME where the compiler and build workspace live (~/.microgoose)
|
|
26
|
+
|
|
27
|
+
docs: https://microgoose.dev
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
STARTER = """\
|
|
31
|
+
// A MicroGoose program: plain Goose, plus hardware through `import esp;`.
|
|
32
|
+
// Run it: microgoose run {path} --target s3 (or esp32, h7)
|
|
33
|
+
import esp;
|
|
34
|
+
|
|
35
|
+
fn main() {{
|
|
36
|
+
print("hello from Goose at ", cpu_mhz(), " MHz");
|
|
37
|
+
for i: i32 in 5 {{
|
|
38
|
+
print("tick ", i, " at ", millis(), " ms");
|
|
39
|
+
delay_ms(500);
|
|
40
|
+
}}
|
|
41
|
+
}}
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def cmd_new(a) -> None:
|
|
46
|
+
dest = Path(a.name)
|
|
47
|
+
main = dest / "main.goose"
|
|
48
|
+
if main.exists():
|
|
49
|
+
sys.exit(f"{main} already exists")
|
|
50
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
51
|
+
if a.example:
|
|
52
|
+
src = core.TEMPLATES / "examples" / f"{a.example}.goose"
|
|
53
|
+
if not src.exists():
|
|
54
|
+
names = sorted(p.stem for p in (core.TEMPLATES / "examples").glob("*.goose"))
|
|
55
|
+
sys.exit(f"no example {a.example!r}; choose from: {', '.join(names)}")
|
|
56
|
+
shutil.copyfile(src, main)
|
|
57
|
+
else:
|
|
58
|
+
main.write_text(STARTER.format(path=main.as_posix()), encoding="utf-8")
|
|
59
|
+
print(f"created {main}\nnext: microgoose run {main.as_posix()} --target s3")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
63
|
+
ap = argparse.ArgumentParser(
|
|
64
|
+
prog="microgoose", description="Run Goose language programs on microcontrollers.",
|
|
65
|
+
epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
66
|
+
ap.add_argument("--version", action="version",
|
|
67
|
+
version=f"microgoose {__version__} (Goose {GOOSE_VERSION})")
|
|
68
|
+
sub = ap.add_subparsers(dest="cmd", required=True, metavar="command")
|
|
69
|
+
helps = {"build": "compile a program to firmware", "run": "build, flash and show the output",
|
|
70
|
+
"flash": "flash the last build", "monitor": "reset the board and show its console"}
|
|
71
|
+
for name, h in helps.items():
|
|
72
|
+
p = sub.add_parser(name, help=h)
|
|
73
|
+
p.add_argument("--target", choices=core.TARGETS, default=os.environ.get("MG_TARGET", "s3"))
|
|
74
|
+
if name in ("build", "run"):
|
|
75
|
+
p.add_argument("src", type=Path, help="the .goose file with main()")
|
|
76
|
+
p.add_argument("--reserve", default="16K", help="bytes per data stack (default 16K)")
|
|
77
|
+
p.add_argument("--debug", action="store_true", help="Goose range and overflow checks on")
|
|
78
|
+
if name in ("run", "monitor"):
|
|
79
|
+
p.add_argument("--seconds", type=float, default=30, help="how long to show output")
|
|
80
|
+
p = sub.add_parser("new", help="start a project folder with a main.goose")
|
|
81
|
+
p.add_argument("name")
|
|
82
|
+
p.add_argument("--example", help="copy one of the bundled examples (hello, blink, sieve, threads, ...)")
|
|
83
|
+
sub.add_parser("setup", help="download and verify the Goose compiler now")
|
|
84
|
+
return ap
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def main(argv=None) -> None:
|
|
88
|
+
a = build_parser().parse_args(argv)
|
|
89
|
+
if a.cmd == "new":
|
|
90
|
+
return cmd_new(a)
|
|
91
|
+
if a.cmd == "setup":
|
|
92
|
+
print(ensure_goose())
|
|
93
|
+
return
|
|
94
|
+
rtt = core.TARGETS[a.target]["console"] == "rtt"
|
|
95
|
+
if a.cmd in ("build", "run"):
|
|
96
|
+
core.emit(a.src.resolve(), core.parse_size(a.reserve), a.debug, a.target)
|
|
97
|
+
core.pio(a.target)
|
|
98
|
+
if a.cmd == "flash":
|
|
99
|
+
if rtt:
|
|
100
|
+
core.monitor(5, a.target, program=True)
|
|
101
|
+
else:
|
|
102
|
+
core.flash(a.target)
|
|
103
|
+
if a.cmd == "run":
|
|
104
|
+
if not rtt:
|
|
105
|
+
core.flash(a.target)
|
|
106
|
+
core.monitor(a.seconds, a.target, until_end=True, program=rtt)
|
|
107
|
+
if a.cmd == "monitor":
|
|
108
|
+
core.monitor(a.seconds, a.target)
|
microgoose/core.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""MicroGoose pipeline: Goose -> C -> firmware -> board.
|
|
2
|
+
|
|
3
|
+
The stock Goose compiler emits one C file for the program and, separately,
|
|
4
|
+
its runtime. MicroGoose stages the program beside lib/*.goose, applies two
|
|
5
|
+
fixes that make that C correct on 32-bit MCUs (xtensa_abi_fix, ptr64_layout),
|
|
6
|
+
shrinks the per-data-stack reservation to fit SRAM, and hands the C to the
|
|
7
|
+
target's PlatformIO project, where the port supplies the POSIX shim, the HAL
|
|
8
|
+
and main.
|
|
9
|
+
|
|
10
|
+
Where things live:
|
|
11
|
+
- In a git checkout, the projects are the repo's own firmware/, ports/ and
|
|
12
|
+
components/ directories, and builds happen in place.
|
|
13
|
+
- Installed from PyPI, those directories ship as package templates and are
|
|
14
|
+
copied into a workspace under MICROGOOSE_HOME (default ~/.microgoose),
|
|
15
|
+
where builds happen. PlatformIO's caches there survive upgrades.
|
|
16
|
+
"""
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import shutil
|
|
20
|
+
import socket
|
|
21
|
+
import subprocess
|
|
22
|
+
import sys
|
|
23
|
+
import time
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from . import __version__
|
|
27
|
+
from .goose import GOOSE, ensure_goose # noqa: F401 (GOOSE is re-exported for tests)
|
|
28
|
+
|
|
29
|
+
PKG = Path(__file__).resolve().parent
|
|
30
|
+
REPO = PKG.parent
|
|
31
|
+
DEV = (REPO / "firmware/platformio.ini").exists() and (REPO / "components/microgoose").is_dir()
|
|
32
|
+
HOME = Path(os.environ.get("MICROGOOSE_HOME", Path.home() / ".microgoose"))
|
|
33
|
+
TEMPLATES = REPO if DEV else PKG / "templates"
|
|
34
|
+
WS = REPO if DEV else HOME / "workspace" # where projects are built
|
|
35
|
+
|
|
36
|
+
COMP = WS / "components/microgoose"
|
|
37
|
+
STAGE = WS / "build/stage"
|
|
38
|
+
RUNTIME = COMP / "goose_runtime.c" # the one runtime all targets share
|
|
39
|
+
PIO_HOME = Path(os.environ.get("PLATFORMIO_CORE_DIR", Path.home() / ".platformio"))
|
|
40
|
+
|
|
41
|
+
TARGETS = {
|
|
42
|
+
"s3": {"project": WS / "firmware", "env": "esp32s3", "console": "serial",
|
|
43
|
+
"about": "ESP32-S3, ESP-IDF + FreeRTOS, UART console, watchpoint guards"},
|
|
44
|
+
"esp32": {"project": WS / "firmware", "env": "esp32", "console": "serial",
|
|
45
|
+
"about": "classic ESP32 (WROOM-32, WROVER-E), ESP-IDF + FreeRTOS"},
|
|
46
|
+
"h7": {"project": WS / "ports/stm32h7", "env": "h743", "console": "rtt",
|
|
47
|
+
"about": "STM32H743, bare metal, RTT console over ST-Link, MPU guards"},
|
|
48
|
+
}
|
|
49
|
+
FW = TARGETS["s3"]["project"]
|
|
50
|
+
|
|
51
|
+
# What the workspace is made of (relative to TEMPLATES and WS).
|
|
52
|
+
TEMPLATE_DIRS = ("components/microgoose", "firmware", "ports/stm32h7", "lib", "examples")
|
|
53
|
+
# Build products inside those directories, never copied over a workspace.
|
|
54
|
+
_GENERATED = re.compile(r"(^|/)(\.pio|include/shared)(/|$)|(^|/)sdkconfig\.(?!defaults)"
|
|
55
|
+
r"|(^|/)src/(app\.c|goose_runtime\.c)$|^components/microgoose/goose_runtime\.c$")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def run(cmd, **kw):
|
|
59
|
+
print("+", " ".join(str(c) for c in cmd), flush=True)
|
|
60
|
+
r = subprocess.run([str(c) for c in cmd], **kw)
|
|
61
|
+
if r.returncode:
|
|
62
|
+
sys.exit(r.returncode)
|
|
63
|
+
return r
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def parse_size(s: str) -> int:
|
|
67
|
+
m = re.fullmatch(r"(\d+)([KkMm]?)", s)
|
|
68
|
+
if not m:
|
|
69
|
+
sys.exit(f"bad size {s!r} (use e.g. 8K, 16K, 1M)")
|
|
70
|
+
return int(m.group(1)) * {"": 1, "k": 1024, "m": 1 << 20}[m.group(2).lower()]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def sync_workspace() -> None:
|
|
74
|
+
"""Bring the build workspace up to date with this version's templates.
|
|
75
|
+
|
|
76
|
+
Only files that differ are written, so PlatformIO's incremental builds and
|
|
77
|
+
caches survive. A no-op in a git checkout, where the workspace is the repo.
|
|
78
|
+
"""
|
|
79
|
+
if WS == TEMPLATES:
|
|
80
|
+
return
|
|
81
|
+
stamp = WS / ".microgoose-version"
|
|
82
|
+
if stamp.exists() and stamp.read_text().strip() == __version__:
|
|
83
|
+
return
|
|
84
|
+
for d in TEMPLATE_DIRS:
|
|
85
|
+
for f in (TEMPLATES / d).rglob("*"):
|
|
86
|
+
rel = f.relative_to(TEMPLATES).as_posix()
|
|
87
|
+
if not f.is_file() or _GENERATED.search(rel) or "__pycache__" in rel:
|
|
88
|
+
continue
|
|
89
|
+
dst = WS / rel
|
|
90
|
+
if not dst.exists() or dst.read_bytes() != f.read_bytes():
|
|
91
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
shutil.copyfile(f, dst)
|
|
93
|
+
stamp.write_text(__version__ + "\n")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def stage(src: Path) -> Path:
|
|
97
|
+
"""Copy the program next to lib/*.goose so `import esp;` resolves."""
|
|
98
|
+
if STAGE.exists():
|
|
99
|
+
shutil.rmtree(STAGE)
|
|
100
|
+
STAGE.mkdir(parents=True)
|
|
101
|
+
for f in (WS / "lib").glob("*.goose"):
|
|
102
|
+
shutil.copy(f, STAGE / f.name)
|
|
103
|
+
for f in src.parent.glob("*.goose"): # sibling modules of the program
|
|
104
|
+
shutil.copy(f, STAGE / f.name)
|
|
105
|
+
return STAGE / src.name
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
# ---------------------------------------------------------------------------
|
|
109
|
+
# The two source fixes that make Goose's C correct on 32-bit MCUs
|
|
110
|
+
# ---------------------------------------------------------------------------
|
|
111
|
+
ABI_MARK = "/* microgoose: xtensa-abi-fix applied */\n"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def xtensa_abi_fix(c: str) -> str:
|
|
115
|
+
"""Work around an Xtensa GCC calling-convention bug (docs/findings.md).
|
|
116
|
+
|
|
117
|
+
Goose declares its scalars `typedef int64_t gs_i64 __attribute__((aligned(1)))`
|
|
118
|
+
so packed data can be read at any address. Xtensa GCC 15.2 picks the
|
|
119
|
+
argument register pair from TYPE_ALIGN of the *argument's* type, so a
|
|
120
|
+
gs_i64/gs_u64/gs_f64 value is passed in a11:a12 while every callee reads
|
|
121
|
+
a12:a13. Fix: 64-bit *value* types get natural alignment; only *pointers*
|
|
122
|
+
to them keep aligned(1) (gs_i64u etc.). Goose structs are all under
|
|
123
|
+
#pragma pack(1), so struct layout and field access are unchanged.
|
|
124
|
+
"""
|
|
125
|
+
if c.startswith(ABI_MARK):
|
|
126
|
+
return c
|
|
127
|
+
n = 0
|
|
128
|
+
for t, ct in (("i64", "int64_t"), ("u64", "uint64_t"), ("f64", "double")):
|
|
129
|
+
c, k = re.subn(rf"typedef {ct} gs_{t} GS_ALIGN1;",
|
|
130
|
+
f"typedef {ct} gs_{t};\ntypedef {ct} gs_{t}u GS_ALIGN1;", c)
|
|
131
|
+
n += k
|
|
132
|
+
c = re.sub(rf"\bgs_{t}\b(?=\s*\*)", f"gs_{t}u", c)
|
|
133
|
+
if not n:
|
|
134
|
+
sys.exit("xtensa_abi_fix: Goose scalar typedefs not found (compiler changed?)")
|
|
135
|
+
# On Xtensa int32_t is `long`, so Goose's `ldexp(f64, i32)` clashes with
|
|
136
|
+
# math.h's `ldexp(double, int)`; both are 32-bit, so math.h's can stand.
|
|
137
|
+
c = re.sub(r"^gs_f64 (ldexp|frexp)\([^;]*\);\n", "", c, flags=re.M)
|
|
138
|
+
return ABI_MARK + c
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
PTR_MARK = "/* microgoose: ptr64-layout applied */\n"
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def ptr64_layout(c: str) -> str:
|
|
145
|
+
"""Make 32-bit C layouts match the Goose compiler's 64-bit ones.
|
|
146
|
+
|
|
147
|
+
The Goose C backend "targets 64-bit hosts" (implementation.md §6.1): it
|
|
148
|
+
computes every size, stride and offset with 8-byte pointers, so a struct
|
|
149
|
+
holding a slice is 28 bytes to Goose but 24 to a 32-bit C compiler. Inside
|
|
150
|
+
the packed type regions, give each pointer member (raw `T *x` or a Goose
|
|
151
|
+
reference typedef `r_T x`) 8 bytes: `union { T *x; uint64_t x__mgpad; }`.
|
|
152
|
+
Member access and positional initializers are unchanged.
|
|
153
|
+
"""
|
|
154
|
+
if PTR_MARK in c[:400]:
|
|
155
|
+
return c
|
|
156
|
+
refs = set(re.findall(r"typedef [^;{}]*\*\s*(r_\w+) GS_ALIGN1;", c))
|
|
157
|
+
ref_alt = "|".join(sorted(refs)) or "(?!x)x"
|
|
158
|
+
member = re.compile(
|
|
159
|
+
rf"(?<=[{{;])(\s*)((?:const\s+)?\w+\s*\*+\s*|(?:{ref_alt})\s+)(\w+);")
|
|
160
|
+
|
|
161
|
+
def fix_body(m):
|
|
162
|
+
# include the "{" so the first member matches the (?<=[{;]) anchor
|
|
163
|
+
return member.sub(
|
|
164
|
+
lambda k: f"{k.group(1)}union {{ {k.group(2)}{k.group(3)}; uint64_t {k.group(3)}__mgpad; }};",
|
|
165
|
+
m.group(1) + m.group(2)) + m.group(3)
|
|
166
|
+
|
|
167
|
+
def fix_region(r):
|
|
168
|
+
# every struct body in the region: `struct X {...}` and `typedef struct {...} X;`
|
|
169
|
+
return re.sub(r"(struct\s*\w*\s*\{)([^{}]*)(\})", fix_body, r.group(0))
|
|
170
|
+
|
|
171
|
+
c = re.sub(r"#pragma pack\(push, 1\).*?#pragma pack\(pop\)", fix_region, c, flags=re.S)
|
|
172
|
+
return PTR_MARK + c
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def fix32(c: str) -> str:
|
|
176
|
+
return ptr64_layout(xtensa_abi_fix(c))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# ---------------------------------------------------------------------------
|
|
180
|
+
# Build
|
|
181
|
+
# ---------------------------------------------------------------------------
|
|
182
|
+
def generate_program(root: Path, out: Path, reserve: int, debug: bool = False) -> str:
|
|
183
|
+
"""Compile a staged Goose program to C with MicroGoose's fixes; returns the
|
|
184
|
+
C as the compiler wrote it (before the fixes), for reporting."""
|
|
185
|
+
flags = ["--debug"] if debug else ["-O2"]
|
|
186
|
+
# The compiler's floor is 64K; its elided checks assume *at most* the
|
|
187
|
+
# reservation, so shrinking it afterwards is safe (runtime_impl.h notes
|
|
188
|
+
# a smaller region is always safe).
|
|
189
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
190
|
+
run([ensure_goose(), "-o", out, "--stack-reserve", "64K", *flags, root])
|
|
191
|
+
c = out.read_text(encoding="utf-8")
|
|
192
|
+
c, n = re.subn(r"#define GS_STACK_RESERVE \d+ull", f"#define GS_STACK_RESERVE {reserve}ull", c)
|
|
193
|
+
if n != 1:
|
|
194
|
+
sys.exit("could not find GS_STACK_RESERVE in the generated C")
|
|
195
|
+
out.write_text(fix32(c), encoding="utf-8")
|
|
196
|
+
return c
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def generate_runtime(dst: Path, version: str | None = None) -> None:
|
|
200
|
+
"""Write the fixed runtime to dst, unless it is already there for `version`."""
|
|
201
|
+
head = dst.read_text(encoding="utf-8", errors="replace")[:4000] if dst.exists() else ""
|
|
202
|
+
if version and version in head and PTR_MARK in head:
|
|
203
|
+
return
|
|
204
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
205
|
+
run([ensure_goose(), "--emit-runtime", dst])
|
|
206
|
+
dst.write_text(fix32(dst.read_text(encoding="utf-8")), encoding="utf-8")
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def emit(src: Path, reserve: int, debug: bool, target: str = "s3") -> None:
|
|
210
|
+
if not src.is_file():
|
|
211
|
+
sys.exit(f"no such Goose program: {src}")
|
|
212
|
+
sync_workspace()
|
|
213
|
+
proj = TARGETS[target]["project"]
|
|
214
|
+
c = generate_program(stage(src), proj / "src/app.c", reserve, debug)
|
|
215
|
+
# The runtime must match the compiler that wrote the program.
|
|
216
|
+
generate_runtime(RUNTIME, re.search(r"#define GS_RUNTIME_VERSION (\w+)", c).group(1))
|
|
217
|
+
if proj != FW:
|
|
218
|
+
# PlatformIO ports outside ESP-IDF get their own copies (it mangles
|
|
219
|
+
# ../.. include paths): the runtime in src/, shared headers in include/.
|
|
220
|
+
dst = proj / "src/goose_runtime.c"
|
|
221
|
+
if not dst.exists() or dst.read_bytes() != RUNTIME.read_bytes():
|
|
222
|
+
shutil.copy(RUNTIME, dst)
|
|
223
|
+
shared = proj / "include/shared"
|
|
224
|
+
shared.mkdir(parents=True, exist_ok=True)
|
|
225
|
+
for f in (COMP / "compat").rglob("*.h"):
|
|
226
|
+
d = shared / f.relative_to(COMP / "compat")
|
|
227
|
+
d.parent.mkdir(parents=True, exist_ok=True)
|
|
228
|
+
if not d.exists() or d.read_bytes() != f.read_bytes():
|
|
229
|
+
shutil.copy(f, d)
|
|
230
|
+
stacks = re.search(r"gs_rt_init\(argc, argv, (\d+), (\d+), (\d+)\)", c)
|
|
231
|
+
if stacks:
|
|
232
|
+
m, mr, wr = map(int, stacks.groups())
|
|
233
|
+
print(f"[mg] {src.name}: {m} data stacks, {mr} main regions, {wr} per worker; "
|
|
234
|
+
f"{reserve // 1024} KB each -> {(mr * (reserve + 64)) // 1024} KB for main")
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def pio(target: str, *args, capture: bool = False):
|
|
238
|
+
cmd = [sys.executable, "-m", "platformio", "run", "-d", TARGETS[target]["project"],
|
|
239
|
+
"-e", TARGETS[target]["env"], *args]
|
|
240
|
+
if capture:
|
|
241
|
+
return subprocess.run([str(c) for c in cmd], capture_output=True, text=True,
|
|
242
|
+
encoding="utf-8", errors="replace")
|
|
243
|
+
return run(cmd)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def elf(target: str) -> Path:
|
|
247
|
+
return TARGETS[target]["project"] / ".pio/build" / TARGETS[target]["env"] / "firmware.elf"
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
# ---------------------------------------------------------------------------
|
|
251
|
+
# Consoles
|
|
252
|
+
# ---------------------------------------------------------------------------
|
|
253
|
+
END_MARKS = ("[microgoose] program exited", "[microgoose] program ended",
|
|
254
|
+
"Rebooting...", "abort() was called")
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def find_port() -> str:
|
|
258
|
+
from serial.tools import list_ports
|
|
259
|
+
if os.environ.get("MG_PORT"):
|
|
260
|
+
return os.environ["MG_PORT"]
|
|
261
|
+
# Espressif native USB, WCH CH343 (the S3 board), Silicon Labs CP210x, FTDI.
|
|
262
|
+
# Not the CH340 (1A86:7523): Arduino Nano clones use it too.
|
|
263
|
+
found = [p.device for p in list_ports.comports()
|
|
264
|
+
if p.vid in (0x303A, 0x10C4, 0x0403) or (p.vid == 0x1A86 and p.pid == 0x55D3)]
|
|
265
|
+
if len(found) == 1:
|
|
266
|
+
return found[0]
|
|
267
|
+
sys.exit(f"{'several' if found else 'no'} ESP32 serial ports found {found} (set MG_PORT)")
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _drain(read, seconds, until_end, echo):
|
|
271
|
+
out, buf = [], ""
|
|
272
|
+
deadline = time.time() + seconds
|
|
273
|
+
while time.time() < deadline:
|
|
274
|
+
b = read()
|
|
275
|
+
if not b:
|
|
276
|
+
continue
|
|
277
|
+
t = b.decode("utf-8", "replace")
|
|
278
|
+
out.append(t)
|
|
279
|
+
if echo:
|
|
280
|
+
sys.stdout.write(t)
|
|
281
|
+
sys.stdout.flush()
|
|
282
|
+
buf = (buf + t)[-4000:]
|
|
283
|
+
if until_end and any(m in buf for m in END_MARKS):
|
|
284
|
+
time.sleep(0.3) # let the tail of a panic dump arrive
|
|
285
|
+
out.append((read() or b"").decode("utf-8", "replace"))
|
|
286
|
+
break
|
|
287
|
+
return "".join(out)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def monitor_serial(seconds, until_end, echo, reset=True):
|
|
291
|
+
import serial
|
|
292
|
+
deadline = time.time() + seconds
|
|
293
|
+
while time.time() < deadline: # the port re-enumerates after a reset
|
|
294
|
+
try:
|
|
295
|
+
s = serial.Serial()
|
|
296
|
+
s.port, s.baudrate, s.timeout = find_port(), 115200, 0.2
|
|
297
|
+
s.dtr = s.rts = False # don't hold EN/BOOT on auto-reset bridges
|
|
298
|
+
s.open()
|
|
299
|
+
if reset: # pulse EN via RTS so we see the program from boot
|
|
300
|
+
s.rts = True
|
|
301
|
+
time.sleep(0.1)
|
|
302
|
+
s.rts = False
|
|
303
|
+
with s:
|
|
304
|
+
if echo:
|
|
305
|
+
print(f"[mg] monitoring {s.port} for up to {seconds:.0f}s", flush=True)
|
|
306
|
+
return _drain(lambda s=s: s.read(4096), deadline - time.time(), until_end, echo)
|
|
307
|
+
except (serial.SerialException, OSError):
|
|
308
|
+
time.sleep(0.3) # port vanished (re-enumerating); retry
|
|
309
|
+
return ""
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
OPENOCD = PIO_HOME / "packages/tool-openocd"
|
|
313
|
+
RTT_PORT = 19021
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def openocd_rtt(target, seconds, until_end, echo, program: bool):
|
|
317
|
+
"""One OpenOCD session: (flash,) reset, attach RTT, stream it over TCP."""
|
|
318
|
+
exe = OPENOCD / "bin" / ("openocd.exe" if sys.platform == "win32" else "openocd")
|
|
319
|
+
if not exe.exists():
|
|
320
|
+
sys.exit(f"OpenOCD not found at {exe}: build for --target {target} once first")
|
|
321
|
+
cmds = ["init"]
|
|
322
|
+
if program:
|
|
323
|
+
cmds.append(f"program {{{elf(target).as_posix()}}} verify")
|
|
324
|
+
cmds += ["reset run", "sleep 300",
|
|
325
|
+
'rtt setup 0x20000000 64 "SEGGER RTT"', "rtt start",
|
|
326
|
+
f"rtt server start {RTT_PORT} 0"]
|
|
327
|
+
p = subprocess.Popen([str(exe), "-s", str(OPENOCD / "openocd/scripts"),
|
|
328
|
+
"-f", "interface/stlink.cfg", "-c", "transport select dapdirect_swd",
|
|
329
|
+
"-f", "target/stm32h7x.cfg", "-c", "; ".join(cmds)],
|
|
330
|
+
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
|
331
|
+
try:
|
|
332
|
+
sock = None
|
|
333
|
+
t0 = time.time()
|
|
334
|
+
while time.time() - t0 < 60 and sock is None:
|
|
335
|
+
if p.poll() is not None:
|
|
336
|
+
sys.stdout.write(p.stdout.read().decode("utf-8", "replace"))
|
|
337
|
+
sys.exit("openocd exited before RTT came up")
|
|
338
|
+
try:
|
|
339
|
+
sock = socket.create_connection(("127.0.0.1", RTT_PORT), timeout=0.5)
|
|
340
|
+
except OSError:
|
|
341
|
+
time.sleep(0.3)
|
|
342
|
+
if sock is None:
|
|
343
|
+
sys.exit("could not reach OpenOCD's RTT server")
|
|
344
|
+
sock.settimeout(0.2)
|
|
345
|
+
if echo:
|
|
346
|
+
print(f"[mg] RTT console via ST-Link for up to {seconds:.0f}s", flush=True)
|
|
347
|
+
|
|
348
|
+
def read():
|
|
349
|
+
try:
|
|
350
|
+
return sock.recv(4096)
|
|
351
|
+
except TimeoutError:
|
|
352
|
+
return b""
|
|
353
|
+
return _drain(read, seconds, until_end, echo)
|
|
354
|
+
finally:
|
|
355
|
+
p.terminate()
|
|
356
|
+
try:
|
|
357
|
+
p.wait(5)
|
|
358
|
+
except subprocess.TimeoutExpired:
|
|
359
|
+
p.kill()
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def flash(target):
|
|
363
|
+
if TARGETS[target]["console"] == "serial":
|
|
364
|
+
# Always name the port: PlatformIO's guess can land on another board.
|
|
365
|
+
pio(target, "-t", "upload", "--upload-port", find_port())
|
|
366
|
+
# h7 flashes inside the same OpenOCD session that reads RTT (see monitor)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def monitor(seconds: float, target: str = "s3", until_end: bool = False,
|
|
370
|
+
echo: bool = True, program: bool = False) -> str:
|
|
371
|
+
sys.stdout.reconfigure(errors="replace") # Windows consoles choke on U+FFFD
|
|
372
|
+
if TARGETS[target]["console"] == "serial":
|
|
373
|
+
return monitor_serial(seconds, until_end, echo)
|
|
374
|
+
return openocd_rtt(target, seconds, until_end, echo, program)
|
microgoose/goose.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Locating, and on first use downloading, the Goose compiler.
|
|
2
|
+
|
|
3
|
+
MicroGoose does not redistribute Goose. It uses, in order:
|
|
4
|
+
1. the binary named by the GOOSE environment variable;
|
|
5
|
+
2. tools/goose/goose-<version>-<platform>/ in a git checkout of MicroGoose;
|
|
6
|
+
3. MICROGOOSE_HOME/goose/goose-<version>-<platform>/, downloading the
|
|
7
|
+
official release there on first use and refusing it unless its SHA-256
|
|
8
|
+
matches the one pinned below.
|
|
9
|
+
"""
|
|
10
|
+
import hashlib
|
|
11
|
+
import os
|
|
12
|
+
import platform
|
|
13
|
+
import shutil
|
|
14
|
+
import stat
|
|
15
|
+
import sys
|
|
16
|
+
import tarfile
|
|
17
|
+
import tempfile
|
|
18
|
+
import urllib.request
|
|
19
|
+
import zipfile
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
GOOSE_VERSION = "v2026.4"
|
|
23
|
+
RELEASES = f"https://github.com/aardappel/goose/releases/download/{GOOSE_VERSION}"
|
|
24
|
+
|
|
25
|
+
# SHA-256 of each official v2026.4 release archive (as published by GitHub).
|
|
26
|
+
ARCHIVES = {
|
|
27
|
+
"windows-x64": ("zip", "87ceb0ff2394e0ac4154b6c6b865c084cadbf236558cc956b114f37d6e619cdb"),
|
|
28
|
+
"linux-x64": ("tar.gz", "559ad7572df89fcd1273512d8679528bcdf876c252ec1f31608d3808b24125b3"),
|
|
29
|
+
"macos-arm64": ("tar.gz", "8ef0b5a864a719bd095b8376bed069d0edc77a0ce8f3cb9d59fdf87291a3a922"),
|
|
30
|
+
"macos-x64": ("tar.gz", "471beefd5787ff96b68c1a059ac4de0973a86a540efda9f2b084b540b5d73db0"),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
_REPO = Path(__file__).resolve().parent.parent
|
|
34
|
+
_HOME = Path(os.environ.get("MICROGOOSE_HOME", Path.home() / ".microgoose"))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def host_platform() -> str | None:
|
|
38
|
+
m = platform.machine().lower()
|
|
39
|
+
x64, arm64 = m in ("x86_64", "amd64"), m in ("arm64", "aarch64")
|
|
40
|
+
if sys.platform == "win32" and x64:
|
|
41
|
+
return "windows-x64"
|
|
42
|
+
if sys.platform.startswith("linux") and x64:
|
|
43
|
+
return "linux-x64"
|
|
44
|
+
if sys.platform == "darwin":
|
|
45
|
+
return "macos-arm64" if arm64 else "macos-x64" if x64 else None
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _binary_in(folder: Path) -> Path:
|
|
50
|
+
return folder / ("goose.exe" if sys.platform == "win32" else "goose")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def goose_path() -> Path:
|
|
54
|
+
"""Where the compiler is, or will be once downloaded."""
|
|
55
|
+
if os.environ.get("GOOSE"):
|
|
56
|
+
return Path(os.environ["GOOSE"])
|
|
57
|
+
plat = host_platform() or "unsupported"
|
|
58
|
+
name = f"goose-{GOOSE_VERSION}-{plat}"
|
|
59
|
+
dev = _binary_in(_REPO / "tools/goose" / name)
|
|
60
|
+
if dev.exists():
|
|
61
|
+
return dev
|
|
62
|
+
return _binary_in(_HOME / "goose" / name)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
GOOSE = goose_path()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _safe_extract(archive: Path, kind: str, dest: Path) -> None:
|
|
69
|
+
dest = dest.resolve()
|
|
70
|
+
if kind == "zip":
|
|
71
|
+
with zipfile.ZipFile(archive) as z:
|
|
72
|
+
for n in z.namelist():
|
|
73
|
+
if not (dest / n).resolve().is_relative_to(dest):
|
|
74
|
+
raise RuntimeError(f"unsafe path in archive: {n}")
|
|
75
|
+
z.extractall(dest)
|
|
76
|
+
else:
|
|
77
|
+
with tarfile.open(archive) as t:
|
|
78
|
+
for m in t.getmembers():
|
|
79
|
+
if not (dest / m.name).resolve().is_relative_to(dest) or m.issym() or m.islnk():
|
|
80
|
+
raise RuntimeError(f"unsafe entry in archive: {m.name}")
|
|
81
|
+
if hasattr(tarfile, "data_filter"): # Python 3.12+ (and patched 3.10/3.11)
|
|
82
|
+
t.extractall(dest, filter="data")
|
|
83
|
+
else:
|
|
84
|
+
t.extractall(dest)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def ensure_goose() -> Path:
|
|
88
|
+
"""The compiler's path, downloading and verifying it first if needed."""
|
|
89
|
+
path = goose_path()
|
|
90
|
+
if path.exists():
|
|
91
|
+
return path
|
|
92
|
+
if os.environ.get("GOOSE"):
|
|
93
|
+
sys.exit(f"GOOSE points at {path}, which does not exist")
|
|
94
|
+
plat = host_platform()
|
|
95
|
+
if plat is None:
|
|
96
|
+
sys.exit(f"no Goose {GOOSE_VERSION} build for {sys.platform}/{platform.machine()}; "
|
|
97
|
+
"build Goose yourself and set GOOSE to the binary")
|
|
98
|
+
kind, sha = ARCHIVES[plat]
|
|
99
|
+
name = f"goose-{GOOSE_VERSION}-{plat}"
|
|
100
|
+
url = f"{RELEASES}/{name}.{kind}"
|
|
101
|
+
print(f"[mg] downloading the Goose compiler {GOOSE_VERSION} ({plat}) from {url}", flush=True)
|
|
102
|
+
root = path.parent.parent
|
|
103
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
104
|
+
with tempfile.TemporaryDirectory(dir=root) as tmp:
|
|
105
|
+
archive = Path(tmp) / f"{name}.{kind}"
|
|
106
|
+
with urllib.request.urlopen(url, timeout=120) as r, open(archive, "wb") as f:
|
|
107
|
+
shutil.copyfileobj(r, f)
|
|
108
|
+
got = hashlib.sha256(archive.read_bytes()).hexdigest()
|
|
109
|
+
if got != sha:
|
|
110
|
+
sys.exit(f"Goose download failed verification: SHA-256 {got}, expected {sha}")
|
|
111
|
+
unpacked = Path(tmp) / "x"
|
|
112
|
+
_safe_extract(archive, kind, unpacked)
|
|
113
|
+
src = unpacked / name
|
|
114
|
+
if not _binary_in(src).exists():
|
|
115
|
+
sys.exit(f"unexpected layout in {archive.name}: no {_binary_in(Path(name))}")
|
|
116
|
+
if path.parent.exists():
|
|
117
|
+
shutil.rmtree(path.parent)
|
|
118
|
+
shutil.move(str(src), str(path.parent))
|
|
119
|
+
if sys.platform != "win32":
|
|
120
|
+
path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
|
121
|
+
print(f"[mg] Goose compiler installed at {path.parent}", flush=True)
|
|
122
|
+
return path
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# MicroGoose ESP-IDF component: the Goose runtime + POSIX shim + HAL.
|
|
2
|
+
# goose_runtime.c is written by `goose --emit-runtime` (mg.py does it).
|
|
3
|
+
idf_component_register(
|
|
4
|
+
SRCS "goose_runtime.c" "mg_compat.c" "mg_hal.c" "mg_main.c"
|
|
5
|
+
INCLUDE_DIRS "include" "compat"
|
|
6
|
+
REQUIRES esp_driver_gpio esp_driver_rmt esp_driver_tsens esp_adc esp_timer
|
|
7
|
+
esp_hw_support esp_system freertos heap pthread
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
# Same prefix for the runtime here and for the generated program (main/).
|
|
11
|
+
set(MG_PREFIX "${CMAKE_CURRENT_SOURCE_DIR}/compat/mg_prefix.h")
|
|
12
|
+
# -fno-tree-sra/-fno-ipa-sra: works around an Xtensa GCC 15.2 miscompile
|
|
13
|
+
# (esp-15.2.0_20251204): SRA turns a 64-bit field of a packed struct (every
|
|
14
|
+
# Goose array header, gs_rhdr) into a scalar that keeps align(1), and the
|
|
15
|
+
# Xtensa backend then passes it in an odd register pair (a11:a12 instead of
|
|
16
|
+
# a12:a13), so the callee reads garbage. See docs/FINDINGS.md.
|
|
17
|
+
target_compile_options(${COMPONENT_LIB} PUBLIC
|
|
18
|
+
"SHELL:-include ${MG_PREFIX}" -fno-tree-sra -fno-ipa-sra
|
|
19
|
+
-Wno-unused-function -Wno-unused-variable -Wno-unused-but-set-variable)
|
|
20
|
+
set_source_files_properties(goose_runtime.c PROPERTIES COMPILE_OPTIONS
|
|
21
|
+
"-O2;-Wno-error;-w")
|
|
22
|
+
|
|
23
|
+
# Park instead of rebooting when a program ends; name data stack overflows.
|
|
24
|
+
target_link_libraries(${COMPONENT_LIB} INTERFACE
|
|
25
|
+
"-Wl,--wrap=_exit" "-Wl,--wrap=_Exit" "-Wl,--wrap=exit"
|
|
26
|
+
"-Wl,--wrap=esp_panic_handler")
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
menu "MicroGoose"
|
|
2
|
+
config MICROGOOSE_TASK_STACK
|
|
3
|
+
int "Native stack of the Goose main task (bytes)"
|
|
4
|
+
default 24576
|
|
5
|
+
config MICROGOOSE_WATCHPOINT_GUARDS
|
|
6
|
+
bool "Guard the first data stacks with hardware watchpoints"
|
|
7
|
+
default y
|
|
8
|
+
config MICROGOOSE_STACKS_IN_PSRAM
|
|
9
|
+
bool "Put Goose data stacks in PSRAM"
|
|
10
|
+
depends on SPIRAM
|
|
11
|
+
default n
|
|
12
|
+
endmenu
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/* MicroGoose: no dynamic loading on a microcontroller. `extern "lib" {}`
|
|
2
|
+
blocks fail at start-up with the runtime's usual error. */
|
|
3
|
+
#pragma once
|
|
4
|
+
#define RTLD_LAZY 1
|
|
5
|
+
#define RTLD_NOW 2
|
|
6
|
+
#define RTLD_LOCAL 0
|
|
7
|
+
#define RTLD_GLOBAL 0x100
|
|
8
|
+
void *dlopen(const char *file, int mode);
|
|
9
|
+
void *dlsym(void *handle, const char *name);
|
|
10
|
+
int dlclose(void *handle);
|
|
11
|
+
char *dlerror(void);
|