Skip to content

Commit 5ee2fd7

Browse files
committed
Fail closed on unexpected health.h layouts
1 parent a975b4d commit 5ee2fd7

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

python/__init__.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,11 @@ def calculate_checksum(data):
4545

4646
def _parse_c_struct(path, name):
4747
with open(path) as f:
48-
body = f.read().split(f"struct __attribute__((packed)) {name} {{", 1)[1].split("};", 1)[0]
49-
fmt = "".join({"uint8_t": "B", "uint16_t": "H", "uint32_t": "I", "float": "f"}[t] for t in re.findall(r"^\s*(uint(?:8|16|32)_t|float)\s+\w+;", body, re.M))
50-
return struct.Struct("<" + fmt)
48+
lines = [l.strip() for l in f.read().split(f"struct __attribute__((packed)) {name} {{", 1)[1].split("};", 1)[0].splitlines() if l.strip()]
49+
fields = [re.fullmatch(r"(uint(?:8|16|32)_t|float)\s+\w+;", l) for l in lines]
50+
if not all(fields):
51+
raise ValueError(f"unsupported {name} layout in {path}")
52+
return struct.Struct("<" + "".join({"uint8_t": "B", "uint16_t": "H", "uint32_t": "I", "float": "f"}[m[1]] for m in fields))
5153

5254
def pack_can_buffer(arr, chunk=False, fd=False):
5355
snds = [bytearray(), ]

tests/test_health_parser.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import tempfile
2+
3+
import pytest
4+
5+
from panda.python import _parse_c_struct
6+
7+
8+
def test_parse_c_struct_rejects_unknown_field_types():
9+
with tempfile.NamedTemporaryFile(mode="w", suffix=".h") as f:
10+
f.write("struct __attribute__((packed)) health_t {\n uint32_t ok;\n bool nope;\n};\n")
11+
f.flush()
12+
with pytest.raises(ValueError, match="unsupported health_t layout"):
13+
_parse_c_struct(f.name, "health_t")

0 commit comments

Comments
 (0)