Merge PR #26: add M5Stack Cardputer-Adv support
Integrate mjgodat's keyboard/display Companion, USB Companion, Repeater and Room Server support for Cardputer-Adv with Cap LoRa-1262. Fix UI retry dispatch and ACK ownership, packet/storage bounds, numeric input validation, sparse channel selection, optional-display shutdown, keyboard layout limits, reserved GPIOs and Windows cross-drive includes. Retain all 350 contacts and queue capacity using the existing contact cache; account for the custom UI's runtime allocations in the RAM admission gate. Carry the MultiMote and DejaVu notices with firmware packages and add CI coverage for all four board roles plus the shared T-Deck Companion. Validation: all four Cardputer roles and the T-Deck BLE Companion build; Cardputer sanitizer, UI, layout, ownership, licensing and storage tests; 65 RAM-policy tests and 14 contact-cache tests. PlatformIO ran serially. PR: https://github.com/mikecarper/MeshCore/pull/26
This commit is contained in:
commit
64a068506b
76 files changed
+27802
-4
No files matched your search
@@ -0,0 +1,126 @@
|
||||
"""Protect built-in Cardputer buses and Windows cross-drive include paths."""
|
||||
|
||||
from pathlib import Path
|
||||
import ntpath
|
||||
import os
|
||||
import runpy
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from test_replay_reset_integration import extract_braced
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VARIANT = ROOT / "variants/m5stack_cardputer_adv"
|
||||
|
||||
|
||||
class CardputerBoardPolicyTests(unittest.TestCase):
|
||||
def check_gpio(self, remove_board_guard=False):
|
||||
method = extract_braced((VARIANT / "CardputerAdvBoard.h").read_text(),
|
||||
"bool isUserGpioAvailable(uint8_t pin) const override")
|
||||
if remove_board_guard:
|
||||
method = method.replace("if (pin == reserved) return false;",
|
||||
"if (pin == reserved) break;")
|
||||
source = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#define PIN_SD_CS 12
|
||||
#include "globals.h"
|
||||
class ESP32Board {
|
||||
public:
|
||||
mutable unsigned calls = 0;
|
||||
virtual bool isUserGpioAvailable(uint8_t pin) const {
|
||||
++calls;
|
||||
// Stand in for shared radio/USB/ADC/strapping exclusions. The variant
|
||||
// must retain a base veto, rather than replacing the common policy.
|
||||
return pin != 7 && pin < 49;
|
||||
}
|
||||
};
|
||||
class CardputerAdvBoard : public ESP32Board {
|
||||
public:
|
||||
@METHOD@
|
||||
};
|
||||
int main() {
|
||||
const uint8_t claimed[] = {
|
||||
0, 8, 9, 11, 12, 33, 34, 35, 36, 37, 38, 41, 42, 43, 46
|
||||
};
|
||||
CardputerAdvBoard board;
|
||||
for (unsigned pin = 0; pin < 256; ++pin) {
|
||||
bool local = false;
|
||||
for (uint8_t reserved : claimed) local |= pin == reserved;
|
||||
const unsigned before = board.calls;
|
||||
const bool available = board.isUserGpioAvailable(static_cast<uint8_t>(pin));
|
||||
assert(available == (!local && pin != 7 && pin < 49));
|
||||
assert(board.calls == before + unsigned(!local));
|
||||
}
|
||||
}
|
||||
'''.replace("@METHOD@", method)
|
||||
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
self.assertIsNotNone(compiler, "a native C++ compiler is required")
|
||||
with tempfile.TemporaryDirectory(prefix="cardputer-gpio-") as directory:
|
||||
source_path = Path(directory) / "policy.cpp"
|
||||
binary = Path(directory) / ("policy.exe" if os.name == "nt" else "policy")
|
||||
source_path.write_text(source, encoding="ascii")
|
||||
flags = [] if os.name == "nt" else ["-fsanitize=address,undefined",
|
||||
"-fno-sanitize-recover=all", "-fno-pie", "-no-pie"]
|
||||
built = subprocess.run([compiler, "-std=c++11", "-Wall", "-Wextra", "-Werror",
|
||||
*flags, "-I", str(VARIANT), str(source_path), "-o", str(binary)],
|
||||
capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
checked = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
|
||||
if remove_board_guard:
|
||||
self.assertNotEqual(checked.returncode, 0, "unprotected board pins passed")
|
||||
self.assertIn("Assertion", checked.stderr)
|
||||
else:
|
||||
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
|
||||
|
||||
def test_all_builtin_bus_pins_are_reserved_and_base_policy_is_preserved(self):
|
||||
self.check_gpio()
|
||||
|
||||
def test_missing_board_guard_is_rejected(self):
|
||||
self.check_gpio(remove_board_guard=True)
|
||||
|
||||
def test_windows_other_drive_keeps_include_and_shared_root_order(self):
|
||||
class Environment(dict):
|
||||
def subst(self, value):
|
||||
return self["PROJECT_PACKAGES_DIR"] if value == "$PROJECT_PACKAGES_DIR" else value
|
||||
|
||||
def Flatten(self, values):
|
||||
return values
|
||||
|
||||
packages = r"C:\Users\Mesh User\.platformio\packages"
|
||||
sdk = packages + r"\framework-arduinoespressif32-libs\esp32s3\include"
|
||||
project = r"D:\Radio Builds\MeshCore\src"
|
||||
paths = [sdk + r"\driver\include", project, sdk + r"\freertos\include",
|
||||
r"C:\Users\Mesh User\.platformio\lib"]
|
||||
env = Environment(PROJECT_PACKAGES_DIR=packages, CPPPATH=paths)
|
||||
hook_path = VARIANT / "win_long_cmdline.py"
|
||||
code = compile(hook_path.read_text(), str(hook_path), "exec")
|
||||
hook = {"env": env, "Import": lambda name: None}
|
||||
with mock.patch.object(sys, "platform", "win32"), \
|
||||
mock.patch.object(os, "path", ntpath), mock.patch.object(os, "sep", "\\"):
|
||||
exec(code, hook)
|
||||
self.assertIsNone(hook["_prefix_root"](packages, project))
|
||||
flags = hook["_short_incflags"](env)
|
||||
prefix = ntpath.normcase(sdk).replace("\\", "/") + "/"
|
||||
self.assertEqual(flags, ["-iprefix", prefix, "-iwithprefixbefore",
|
||||
"driver/include", "-I" + project, "-iwithprefixbefore",
|
||||
"freertos/include", "-I" + paths[-1]])
|
||||
self.assertIn("_cardputer_short_incflags", env)
|
||||
# No root shared with the SDK: preserve every include unchanged.
|
||||
env["CPPPATH"] = [project]
|
||||
self.assertEqual(hook["_short_incflags"](env), ["-I" + project])
|
||||
|
||||
def test_hook_leaves_other_operating_systems_unchanged(self):
|
||||
env = {}
|
||||
with mock.patch.object(sys, "platform", "linux"):
|
||||
runpy.run_path(str(VARIANT / "win_long_cmdline.py"),
|
||||
init_globals={"env": env, "Import": lambda name: None})
|
||||
self.assertEqual(env, {})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,206 @@
|
||||
"""Exercise the real bounded Cardputer SD layout parser with hostile input."""
|
||||
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VARIANT = ROOT / "variants/m5stack_cardputer_adv"
|
||||
FS = r'''
|
||||
#pragma once
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <map>
|
||||
#define FILE_READ "r"
|
||||
struct FileData {
|
||||
std::string bytes, replacement;
|
||||
size_t at=0, reads=0, closes=0, size_override=0, fail_after=~size_t(0);
|
||||
bool stalled=false, fail_seek=false;
|
||||
};
|
||||
class File {
|
||||
std::shared_ptr<FileData> d;
|
||||
public:
|
||||
File(std::shared_ptr<FileData> value={}) : d(value) {}
|
||||
explicit operator bool() const { return bool(d); }
|
||||
size_t size() { return d->size_override ? d->size_override : d->bytes.size(); }
|
||||
size_t position() { return d->at; }
|
||||
int read() {
|
||||
++d->reads;
|
||||
if(d->at>=d->bytes.size() || d->reads>d->fail_after) return -1;
|
||||
const uint8_t value=uint8_t(d->bytes[d->at]);
|
||||
if(!d->stalled) ++d->at;
|
||||
return value;
|
||||
}
|
||||
bool seek(size_t at) {
|
||||
if(d->fail_seek) return false;
|
||||
if(!d->replacement.empty()) { d->bytes=d->replacement; d->replacement.clear(); }
|
||||
d->at=at; return true;
|
||||
}
|
||||
void close() { ++d->closes; }
|
||||
};
|
||||
class FS {
|
||||
public:
|
||||
std::map<std::string,std::shared_ptr<FileData>> files;
|
||||
bool exists(const char* path) { return files.count(path); }
|
||||
File open(const char* path,const char*,bool) {
|
||||
auto found=files.find(path);
|
||||
if(found==files.end())return {};
|
||||
found->second->at=found->second->reads=0;
|
||||
return File(found->second);
|
||||
}
|
||||
std::shared_ptr<FileData> put(const char* path,const std::string& bytes) {
|
||||
auto data=std::make_shared<FileData>();data->bytes=bytes;files[path]=data;return data;
|
||||
}
|
||||
};
|
||||
'''
|
||||
HARNESS = r'''
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
#include <string>
|
||||
#include <cstdlib>
|
||||
#include "CardputerLayout.h"
|
||||
static int fail_allocation=-1, allocations=0;
|
||||
static size_t largest_allocation=0;
|
||||
void* operator new(size_t size,const std::nothrow_t&) noexcept {
|
||||
largest_allocation=std::max(largest_allocation,size);
|
||||
if(allocations++==fail_allocation)return nullptr;
|
||||
return ::operator new(size);
|
||||
}
|
||||
void* operator new[](size_t size,const std::nothrow_t&) noexcept {
|
||||
largest_allocation=std::max(largest_allocation,size);
|
||||
if(allocations++==fail_allocation)return nullptr;
|
||||
return ::operator new[](size);
|
||||
}
|
||||
using namespace Keyboard;
|
||||
using namespace Keyboard::Layout;
|
||||
static Event key(unsigned id=1,unsigned mask=0) {
|
||||
Event e;e.key=static_cast<Key>(id);e.modifiers.fn=mask&1;e.modifiers.ctrl=mask&2;
|
||||
e.modifiers.shift=mask&4;e.modifiers.opt=mask&8;e.modifiers.alt=mask&16;return e;
|
||||
}
|
||||
static void expect(CardputerLayout& layout,const char* text,unsigned id=1,unsigned mask=0) {
|
||||
auto e=key(id,mask);assert(!std::strcmp(layout.lookup(e),text));
|
||||
}
|
||||
static std::string layer(unsigned mask) {
|
||||
std::string text="L ";
|
||||
if(!mask)text+='B';
|
||||
if(mask&1)text+='F';
|
||||
if(mask&2)text+='C';
|
||||
if(mask&4)text+='S';
|
||||
if(mask&8)text+='O';
|
||||
if(mask&16)text+='A';
|
||||
return text+"\n";
|
||||
}
|
||||
static void healthy(FS& fs,CardputerLayout& layout) {
|
||||
fs.put(KB_LAYOUT_MAIN_FILE,"N en\r\nL B\r\nK 01=x\r\nK 56=\xe2\x82\xac");
|
||||
layout.begin(fs);expect(layout,"x");expect(layout,"\xe2\x82\xac",56);
|
||||
assert(!std::strcmp(layout.getMainLayoutCode(),"en"));
|
||||
}
|
||||
int main(int argc,char** argv) {
|
||||
assert(argc==2);
|
||||
static_assert(sizeof(LayoutLayer)==225,"update the complete layer RAM bound");
|
||||
static_assert(CardputerLayout::MAX_LAYOUT_LAYERS==32,"five modifier bits");
|
||||
FS fs;CardputerLayout layout;
|
||||
const std::string mode=argv[1];
|
||||
if(mode=="normal") {
|
||||
healthy(fs,layout);
|
||||
fs.put(KB_LAYOUT_ALT_FILE,"N xx\nL B\nK 01=y\nL S\nK 01=Y\n");
|
||||
layout.begin(fs);layout.switchLayout();expect(layout,"y");expect(layout,"Y",1,4);
|
||||
fs.put(KB_LAYOUT_ALT_FILE,"N yy\nL B\nK 01=z\n");
|
||||
layout.begin(fs);expect(layout,"z");assert(!std::strcmp(layout.getCurrentCode(),"yy"));
|
||||
layout.switchLayout();expect(layout,"x");
|
||||
} else if(mode=="all-layers") {
|
||||
std::string text="N en\n";
|
||||
for(unsigned mask=0;mask<32;++mask) {
|
||||
text+=layer(mask);
|
||||
for(unsigned id=1;id<=56;++id) {
|
||||
char row[16];std::snprintf(row,sizeof(row),"K %02u=%c\n",id,'a'+mask%26);text+=row;
|
||||
}
|
||||
}
|
||||
assert(text.size()<CardputerLayout::MAX_LAYOUT_FILE_BYTES);
|
||||
fs.put(KB_LAYOUT_MAIN_FILE,text);fs.put(KB_LAYOUT_ALT_FILE,text);layout.begin(fs);
|
||||
for(unsigned alternate=0;alternate<2;++alternate) {
|
||||
for(unsigned mask=0;mask<32;++mask) {
|
||||
const char wanted[]={char('a'+mask%26),0};
|
||||
for(unsigned id=1;id<=56;++id)expect(layout,wanted,id,mask);
|
||||
}
|
||||
layout.switchLayout();
|
||||
}
|
||||
assert(largest_allocation==32*sizeof(LayoutLayer));
|
||||
assert(allocations==4);
|
||||
} else if(mode=="duplicates") {
|
||||
std::string text="N en\n";
|
||||
for(unsigned i=0;i<1000;++i)text+="L B\nK 01=z\n";
|
||||
fs.put(KB_LAYOUT_MAIN_FILE,text);layout.begin(fs);expect(layout,"z");
|
||||
assert(largest_allocation==sizeof(LayoutLayer) && allocations==2);
|
||||
} else if(mode=="allocation-failure") {
|
||||
healthy(fs,layout);
|
||||
for(int fail=0;fail<2;++fail) {
|
||||
allocations=0;fail_allocation=fail;
|
||||
fs.put(KB_LAYOUT_MAIN_FILE,"N zz\nL B\nK 01=q\n");layout.begin(fs);
|
||||
expect(layout,"x");assert(!std::strcmp(layout.getMainLayoutCode(),"en"));
|
||||
}
|
||||
fail_allocation=-1;healthy(fs,layout);
|
||||
} else if(mode=="bad-input") {
|
||||
healthy(fs,layout);
|
||||
for(const auto& text : {std::string("N xx\nL B\nK 01=z\n#")+std::string(81,'!'),
|
||||
std::string("L B\nK 01=z\0bad",15),
|
||||
std::string("#")+std::string(32768,'!'),std::string("N xx\n")}) {
|
||||
fs.put(KB_LAYOUT_MAIN_FILE,text);layout.begin(fs);expect(layout,"x");
|
||||
}
|
||||
// Both file and line limits are inclusive, including a final line without LF.
|
||||
std::string maximum="N en\nL B\nK 01=v\n";
|
||||
while(maximum.size()+81<=32768)maximum+="#"+std::string(79,'!')+"\n";
|
||||
maximum.append(32768-maximum.size(),'#');
|
||||
assert(maximum.size()==32768);
|
||||
fs.put(KB_LAYOUT_MAIN_FILE,maximum);layout.begin(fs);expect(layout,"v");
|
||||
} else if(mode=="broken-file") {
|
||||
healthy(fs,layout);
|
||||
for(unsigned failure=0;failure<5;++failure) {
|
||||
auto data=fs.put(KB_LAYOUT_MAIN_FILE,"N xx\nL B\nK 01=z\n");
|
||||
if(failure==0)data->stalled=true;
|
||||
if(failure==1)data->fail_after=3;
|
||||
if(failure==2)data->fail_seek=true;
|
||||
if(failure==3)data->fail_after=data->bytes.size()+3;
|
||||
if(failure==4)data->replacement="L B\nL F\nK 01=z\n";
|
||||
layout.begin(fs);expect(layout,"x");assert(data->closes==1);
|
||||
assert(data->reads<=2*32768);
|
||||
}
|
||||
} else { assert(false); }
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class CardputerLayoutTests(unittest.TestCase):
|
||||
def test_bounded_production_parser_preserves_valid_layout_on_every_failure(self):
|
||||
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
self.assertIsNotNone(compiler, "a native C++ compiler is required")
|
||||
with tempfile.TemporaryDirectory(prefix="cardputer-layout-") as directory:
|
||||
work = Path(directory)
|
||||
(work / "FS.h").write_text(FS, encoding="ascii")
|
||||
(work / "Adafruit_TCA8418.h").write_text(
|
||||
"#pragma once\nclass Adafruit_TCA8418 {};\n", encoding="ascii")
|
||||
(work / "main.cpp").write_text(HARNESS, encoding="ascii")
|
||||
binary = work / ("layout.exe" if os.name == "nt" else "layout")
|
||||
flags = [] if os.name == "nt" else ["-fsanitize=address,undefined",
|
||||
"-fno-sanitize-recover=all", "-fno-pie", "-no-pie"]
|
||||
built = subprocess.run([compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
||||
*flags, "-I", str(work), "-I", str(VARIANT), "-I", str(VARIANT / "hw"),
|
||||
str(work / "main.cpp"), str(VARIANT / "hw/CardputerLayout.cpp"), "-o", str(binary)],
|
||||
capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
for scenario in ("normal", "all-layers", "duplicates", "allocation-failure",
|
||||
"bad-input", "broken-file"):
|
||||
with self.subTest(scenario=scenario):
|
||||
tested = subprocess.run([str(binary), scenario], capture_output=True,
|
||||
text=True, timeout=10)
|
||||
self.assertEqual(tested.returncode, 0, tested.stdout + tested.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Qualify and carry Cardputer UI/font notices without changing firmware or DFU ZIPs."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from test_pocket_gui_license import elf32 as synthetic_elf32
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
import package_cardputer_license as notice
|
||||
import firmware_memory_manifest as memory
|
||||
import firmware_build_recipe as recipe
|
||||
import package_cascade_release as release
|
||||
|
||||
GUI = "_ZN15CardputerUITask4loopEv"
|
||||
FONT = "_ZL13DejaVuSans_11"
|
||||
|
||||
|
||||
def elf32(path, symbols=(GUI, FONT), **kwargs):
|
||||
synthetic_elf32(path, symbols=symbols, **kwargs)
|
||||
|
||||
|
||||
class CardputerLicenseTest(unittest.TestCase):
|
||||
def qualify(self, directory, stem, target="test_companion_radio_usb"):
|
||||
output = stem.parent / (stem.name + ".capabilities.json")
|
||||
result = subprocess.run([sys.executable, str(ROOT / "scripts/check_firmware_capabilities.py"),
|
||||
"--image", str(directory / "firmware.elf"), "--output", str(output),
|
||||
"--target", target, "--platform", "ESP32_PLATFORM", "--build-profile", "standard"],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
return json.loads(output.read_text())
|
||||
|
||||
@unittest.skipUnless(sys.platform.startswith("linux"), "requires a Linux ELF compiler")
|
||||
def test_compiler_produced_gui_and_font_symbols_qualify(self):
|
||||
compiler = shutil.which("g++")
|
||||
if compiler is None:
|
||||
self.skipTest("host g++ required")
|
||||
source = """
|
||||
class CardputerUITask { public: void loop(); bool isAwake() const; };
|
||||
void CardputerUITask::loop() { asm volatile(\"\"); }
|
||||
bool CardputerUITask::isAwake() const { return false; }
|
||||
static const unsigned char DejaVuSans_11[] = {1, 2, 3, 4};
|
||||
static const unsigned char DejaVuSans_16[] = {5, 6, 7, 8};
|
||||
static const unsigned char DejaVuSans_19[] = {9, 10, 11, 12};
|
||||
extern \"C\" void _start() { asm volatile(\"\" :: \"r\"(DejaVuSans_11),
|
||||
\"r\"(DejaVuSans_16), \"r\"(DejaVuSans_19)); }
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
input_path = root / "linked.cpp"
|
||||
input_path.write_text(source)
|
||||
result = subprocess.run([compiler, "-m32", "-O0", "-fno-pie", "-no-pie",
|
||||
"-fno-exceptions", "-fno-rtti", "-fno-stack-protector", "-nostdlib",
|
||||
"-Wl,-e,_start", "-Wl,--build-id=none", str(input_path),
|
||||
"-o", str(root / "firmware.elf")], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
evidence = notice.cardputer_evidence(root / "firmware.elf")
|
||||
self.assertEqual(len(evidence), 5)
|
||||
self.assertIn(FONT, evidence)
|
||||
self.qualify(root, root / "compiled")
|
||||
self.assertEqual(notice.collect_build_notice(root, root / "compiled").read_bytes(),
|
||||
notice.notice_bytes())
|
||||
|
||||
def test_notice_requires_allocated_gui_or_font_definitions(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "firmware.elf"
|
||||
elf32(path)
|
||||
self.assertEqual(notice.cardputer_evidence(path), sorted((GUI, FONT)))
|
||||
# A partially linked font still needs its font license.
|
||||
elf32(path, symbols=(FONT,), flags=2)
|
||||
self.assertEqual(notice.cardputer_evidence(path), [FONT])
|
||||
for font in ("DejaVuSans_16", "_ZL13DejaVuSans_19", "_ZL13DejaVuSans_99.lto_priv.0"):
|
||||
elf32(path, symbols=(font,), flags=2)
|
||||
self.assertEqual(notice.cardputer_evidence(path), [font])
|
||||
for kwargs in ({"flags": 0}, {"flags": 4}, {"section_type": 8},
|
||||
{"symbols": (GUI,), "flags": 2},
|
||||
{"symbols": (FONT, "other"), "undefined": (FONT,)},
|
||||
{"symbols": (GUI, "other"), "zero": (GUI,)}):
|
||||
with self.subTest(kwargs=kwargs):
|
||||
elf32(path, **kwargs)
|
||||
self.assertEqual(notice.cardputer_evidence(path), [])
|
||||
path.write_bytes((GUI + " " + FONT).encode())
|
||||
self.assertEqual(notice.cardputer_evidence(path), [])
|
||||
|
||||
def test_target_name_alone_never_creates_notice_and_stale_notice_is_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
stem = root / "plain"
|
||||
elf32(root / "firmware.elf", symbols=("unrelated",))
|
||||
manifest = self.qualify(root, stem, "M5Stack_Cardputer_Adv_companion_radio_usb")
|
||||
self.assertNotIn("third_party_notices", manifest)
|
||||
self.assertIsNone(notice.collect_build_notice(root, stem))
|
||||
notice.sidecar(stem).write_bytes(notice.notice_bytes())
|
||||
with self.assertRaisesRegex(ValueError, "stale"):
|
||||
notice.collect_build_notice(root, stem)
|
||||
self.assertTrue(recipe.package_occupied(stem))
|
||||
|
||||
def test_notice_is_hashed_with_memory_proof_and_staged_for_release(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
build, output = root / "build", root / "out"
|
||||
build.mkdir(); output.mkdir()
|
||||
elf32(build / "firmware.elf")
|
||||
version = "v1.18.0.1-test-deadbeef"
|
||||
stem = output / ("test_companion_radio_usb-" + version)
|
||||
manifest = self.qualify(build, stem)
|
||||
data = notice.notice_bytes()
|
||||
self.assertEqual(manifest["third_party_notices"], [notice.notice_record(stem, data)])
|
||||
# No artifact bytes are rewritten to carry notices.
|
||||
app = output / (stem.name + ".bin")
|
||||
merged = output / (stem.name + "-merged.bin")
|
||||
app.write_bytes(b"unchanged app"); merged.write_bytes(b"unchanged merged")
|
||||
sidecar = notice.collect_build_notice(build, stem)
|
||||
self.assertEqual(sidecar.read_bytes(), data)
|
||||
self.assertEqual(notice.collect_build_notice(build, stem), sidecar)
|
||||
report = dict(schema_version=1, passed=True, available_internal_bytes=80000,
|
||||
required_heap_bytes=50000, largest_internal_region_bytes=80000,
|
||||
required_contiguous_bytes=5120, target="build_env",
|
||||
elf_sha256=hashlib.sha256((build / "firmware.elf").read_bytes()).hexdigest())
|
||||
(build / "firmware.memory.json").write_text(json.dumps(report))
|
||||
memory.package_report(build, stem)
|
||||
proof = memory.validate_package(stem)
|
||||
self.assertEqual(proof["files"][sidecar.name], hashlib.sha256(data).hexdigest())
|
||||
records = release.collect_artifacts(output, version)
|
||||
self.assertEqual(sum(path == sidecar for path in records[0]["files"]), 1)
|
||||
self.assertEqual(app.read_bytes(), b"unchanged app")
|
||||
self.assertEqual(merged.read_bytes(), b"unchanged merged")
|
||||
sidecar.write_bytes(data + b"tampered\n")
|
||||
with self.assertRaisesRegex(ValueError, "mismatched"):
|
||||
memory.validate_package(stem)
|
||||
sidecar.write_bytes(b"truncated")
|
||||
with self.assertRaisesRegex(ValueError, "mismatched"):
|
||||
memory.validate_package(stem)
|
||||
sidecar.unlink()
|
||||
with self.assertRaisesRegex(ValueError, "missing"):
|
||||
memory.validate_package(stem)
|
||||
with self.assertRaisesRegex(ValueError, "missing"):
|
||||
release.collect_artifacts(output, version)
|
||||
|
||||
def test_metadata_cannot_omit_or_replace_linked_notice(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
stem = root / "gui"
|
||||
elf32(root / "firmware.elf")
|
||||
manifest = self.qualify(root, stem)
|
||||
manifest_path = root / "gui.capabilities.json"
|
||||
manifest["third_party_notices"] = []
|
||||
manifest_path.write_text(json.dumps(manifest))
|
||||
with self.assertRaisesRegex(ValueError, "linked ELF"):
|
||||
notice.collect_build_notice(root, stem)
|
||||
manifest["third_party_notices"] = [notice.notice_record(stem, b"wrong")]
|
||||
manifest_path.write_text(json.dumps(manifest))
|
||||
with self.assertRaisesRegex(ValueError, "source notice"):
|
||||
notice.collect_build_notice(root, stem)
|
||||
self.assertFalse(notice.valid_notice(b"MIT License"))
|
||||
|
||||
def test_both_source_notices_are_required_and_carried_in_full(self):
|
||||
data = notice.notice_bytes()
|
||||
self.assertTrue(notice.valid_notice(data))
|
||||
self.assertIn(notice.UI_NOTICE_PATH.read_bytes().rstrip(), data)
|
||||
self.assertIn(notice.FONT_NOTICE_PATH.read_bytes().rstrip(), data)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
absent = Path(directory) / "absent"
|
||||
incomplete = Path(directory) / "incomplete"
|
||||
incomplete.write_bytes(b"MIT License\n")
|
||||
for attribute in ("UI_NOTICE_PATH", "FONT_NOTICE_PATH"):
|
||||
with self.subTest(source=attribute):
|
||||
with patch.object(notice, attribute, absent), self.assertRaises(OSError):
|
||||
notice.notice_bytes()
|
||||
with patch.object(notice, attribute, incomplete), self.assertRaisesRegex(ValueError, "incomplete"):
|
||||
notice.notice_bytes()
|
||||
|
||||
def test_malformed_manifest_declarations_are_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
stem = root / "cardputer"
|
||||
elf32(root / "firmware.elf")
|
||||
manifest = self.qualify(root, stem)
|
||||
manifest_path = root / "cardputer.capabilities.json"
|
||||
record = notice.notice_record(stem, notice.notice_bytes())
|
||||
for records, message in (([record, record], "duplicate"),
|
||||
([dict(record, file="elsewhere.txt")], "invalid"),
|
||||
([dict(record, license="MIT")], "invalid"),
|
||||
([dict(record, sha256="invalid")], "invalid")):
|
||||
with self.subTest(records=records):
|
||||
manifest["third_party_notices"] = records
|
||||
manifest_path.write_text(json.dumps(manifest))
|
||||
with self.assertRaisesRegex(ValueError, message):
|
||||
notice.collect_build_notice(root, stem)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,394 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise Cardputer packet ownership, loop dispatch and optional SD history."""
|
||||
|
||||
from pathlib import Path
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from cpp_source import body
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VARIANT = ROOT / "variants/m5stack_cardputer_adv"
|
||||
|
||||
FILESYSTEM_STUB = r'''
|
||||
#pragma once
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#define PUB_KEY_SIZE 32
|
||||
#define FILE_READ "r"
|
||||
#define FILE_WRITE "w"
|
||||
#define FILE_APPEND "a"
|
||||
namespace mesh { struct RTCClock {}; }
|
||||
struct Entry {
|
||||
std::string bytes;
|
||||
bool no_progress = false;
|
||||
unsigned reads = 0;
|
||||
};
|
||||
struct File {
|
||||
std::shared_ptr<Entry> entry;
|
||||
size_t position = 0;
|
||||
explicit operator bool() const { return bool(entry); }
|
||||
size_t size() const { return entry ? entry->bytes.size() : 0; }
|
||||
size_t available() const { return size() - position; }
|
||||
size_t read(uint8_t* dest, size_t count) {
|
||||
if (!entry) return 0;
|
||||
if (++entry->reads > 100) throw std::runtime_error("read made no progress");
|
||||
if (entry->no_progress) return 0;
|
||||
count = std::min(count, available());
|
||||
memcpy(dest, entry->bytes.data() + position, count);
|
||||
position += count;
|
||||
return count;
|
||||
}
|
||||
size_t write(const uint8_t* src, size_t count) {
|
||||
entry->bytes.append(reinterpret_cast<const char*>(src), count);
|
||||
return count;
|
||||
}
|
||||
void print(const char* text) { entry->bytes += text; }
|
||||
void println(const char* text) { entry->bytes += std::string(text) + "\n"; }
|
||||
void close() { entry.reset(); }
|
||||
};
|
||||
struct FILESYSTEM {
|
||||
std::map<std::string, std::shared_ptr<Entry>> files;
|
||||
unsigned opens = 0;
|
||||
bool fail_open = false;
|
||||
bool exists(const char* path) const { return files.count(path) != 0; }
|
||||
bool mkdir(const char*) { return true; }
|
||||
File open(const char* path, const char* mode, bool = false) {
|
||||
++opens;
|
||||
if (fail_open) return {};
|
||||
auto& entry = files[path];
|
||||
if (!entry) entry = std::make_shared<Entry>();
|
||||
if (*mode == 'w') entry->bytes.clear();
|
||||
return File{entry};
|
||||
}
|
||||
};
|
||||
struct DataStore { DataStore(FILESYSTEM&, mesh::RTCClock&) {} };
|
||||
'''
|
||||
|
||||
STORAGE_CHECKS = r'''
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
int main() {
|
||||
mesh::RTCClock clock;
|
||||
FILESYSTEM primary, sd;
|
||||
CardputerDataStore store(primary, clock);
|
||||
uint8_t key[PUB_KEY_SIZE] = {};
|
||||
ChatHistory history;
|
||||
history.push_ref()->out = true;
|
||||
store.beginCustom(nullptr);
|
||||
assert(!store.hasHistory());
|
||||
store.storeMessage(key, "without SD", false, false);
|
||||
store.loadMessages(key, false, history);
|
||||
assert(history.count() == 0 && primary.opens == 0);
|
||||
|
||||
CustomNodePrefs prefs{1.1f, 127, 2};
|
||||
store.beginCustom(&sd);
|
||||
store.saveCustomPrefs(prefs);
|
||||
assert(primary.files.count(CUSTOM_PREFS_FILE) == 1 && sd.files.empty());
|
||||
CustomNodePrefs restored{};
|
||||
store.loadCustomPrefs(restored);
|
||||
assert(!memcmp(&prefs, &restored, sizeof(prefs)));
|
||||
|
||||
// A bounded source need not have a terminator after its last allowed byte.
|
||||
char* bounded = new char[MAX_MESSAGE_LENGTH];
|
||||
memset(bounded, 'x', MAX_MESSAGE_LENGTH);
|
||||
store.storeMessage(key, bounded, false, true);
|
||||
delete[] bounded;
|
||||
const std::string channel_path = std::string(HISTORY_DIR_CHANNEL) + "/" + std::string(32, '0');
|
||||
assert(sd.files.at(channel_path)->bytes == "<< " + std::string(MAX_MESSAGE_LENGTH, 'x') + "\n");
|
||||
store.storeMessage(key, "line1\r\nline2", true, true);
|
||||
assert(sd.files.at(channel_path)->bytes.find(">> line1 line2\n") != std::string::npos);
|
||||
|
||||
// Direct and channel namespaces remain separate; loading retains the last 15.
|
||||
for (unsigned i = 0; i < CHAT_HISTORY_RINGBUF_SIZE + 5; ++i) {
|
||||
char text[32];
|
||||
snprintf(text, sizeof(text), "message %u", i);
|
||||
store.storeMessage(key, text, i % 2, false);
|
||||
}
|
||||
store.loadMessages(key, false, history);
|
||||
assert(history.count() == CHAT_HISTORY_RINGBUF_SIZE);
|
||||
for (unsigned i = 0; i < history.count(); ++i) {
|
||||
const HistoryMessage* msg = nullptr;
|
||||
assert(history.get(i, msg));
|
||||
char expected[32];
|
||||
snprintf(expected, sizeof(expected), "message %u", i + 5);
|
||||
assert(!strcmp(msg->text, expected) && msg->out == bool((i + 5) % 2));
|
||||
}
|
||||
const HistoryMessage* absent = nullptr;
|
||||
assert(!history.get(history.count(), absent));
|
||||
assert(primary.files.size() == 1 && sd.files.size() == 2);
|
||||
|
||||
const std::string direct_path = std::string(HISTORY_DIR_DIRECT) + "/" + std::string(64, '0');
|
||||
auto direct = sd.files.at(direct_path);
|
||||
direct->no_progress = true;
|
||||
direct->reads = 0;
|
||||
store.loadMessages(key, false, history);
|
||||
assert(direct->reads == 1 && history.count() == 0);
|
||||
sd.fail_open = true;
|
||||
store.storeMessage(key, "write failure", true, false);
|
||||
store.loadMessages(key, false, history);
|
||||
assert(history.count() == 0);
|
||||
}
|
||||
'''
|
||||
|
||||
MESH_HARNESS = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#define MAX_HASH_SIZE 8
|
||||
#define PAYLOAD_TYPE_GRP_TXT 5
|
||||
namespace mesh {
|
||||
struct GroupChannel { uint8_t secret[32] = {}; };
|
||||
struct Packet {
|
||||
uint8_t type, value;
|
||||
uint8_t getPayloadType() const { return type; }
|
||||
void calculatePacketHash(uint8_t* hash) const { memset(hash, value, MAX_HASH_SIZE); }
|
||||
};
|
||||
}
|
||||
struct Store {
|
||||
unsigned writes = 0;
|
||||
void storeMessage(const uint8_t*, const char*, bool, bool) { ++writes; }
|
||||
};
|
||||
struct MyMesh {
|
||||
bool admit = true;
|
||||
unsigned base_loops = 0;
|
||||
uint32_t now = 0;
|
||||
bool sendFloodScoped(const mesh::GroupChannel&, mesh::Packet* pkt, uint32_t) {
|
||||
if (!admit || !pkt) { delete pkt; return false; }
|
||||
return true;
|
||||
}
|
||||
bool sendGroupMessage(uint32_t, mesh::GroupChannel&, const char*, const char*, int) { return admit; }
|
||||
void loop() { ++base_loops; }
|
||||
bool millisHasNowPassed(unsigned long at) const { return int32_t(now - at) > 0; }
|
||||
};
|
||||
struct CardputerMesh : MyMesh {
|
||||
Store store;
|
||||
Store* _store = &store;
|
||||
uint8_t last_message_hash[MAX_HASH_SIZE] = {};
|
||||
uint16_t last_message_heard_repeats = 9;
|
||||
unsigned long resend_timeout = 0;
|
||||
unsigned resends = 0;
|
||||
bool sendFloodScoped(const mesh::GroupChannel&, mesh::Packet*, uint32_t);
|
||||
bool sendGroupMessage(uint32_t, mesh::GroupChannel&, const char*, const char*, int);
|
||||
void checkResend() { ++resends; }
|
||||
void loop();
|
||||
};
|
||||
@METHODS@
|
||||
int main() {
|
||||
CardputerMesh node;
|
||||
mesh::GroupChannel channel;
|
||||
node.admit = false;
|
||||
assert(!node.sendFloodScoped(channel, new mesh::Packet{PAYLOAD_TYPE_GRP_TXT, 42}, 0));
|
||||
assert(node.last_message_hash[0] == 0 && node.last_message_heard_repeats == 9);
|
||||
assert(!node.sendGroupMessage(0, channel, "name", "text", 4) && node.store.writes == 0);
|
||||
node.admit = true;
|
||||
auto* group = new mesh::Packet{PAYLOAD_TYPE_GRP_TXT, 77};
|
||||
assert(node.sendFloodScoped(channel, group, 0));
|
||||
for (uint8_t byte : node.last_message_hash) assert(byte == 77);
|
||||
assert(node.last_message_heard_repeats == 0);
|
||||
delete group;
|
||||
node.last_message_heard_repeats = 3;
|
||||
auto* other = new mesh::Packet{1, 66};
|
||||
assert(node.sendFloodScoped(channel, other, 0));
|
||||
assert(node.last_message_hash[0] == 77 && node.last_message_heard_repeats == 3);
|
||||
delete other;
|
||||
assert(node.sendGroupMessage(0, channel, "name", "text", 4) && node.store.writes == 1);
|
||||
node.resend_timeout = 10;
|
||||
node.now = 9;
|
||||
node.loop();
|
||||
assert(node.base_loops == 1 && node.resends == 0);
|
||||
node.now = 11;
|
||||
node.loop();
|
||||
assert(node.base_loops == 2 && node.resends == 1 && node.resend_timeout == 0);
|
||||
node.loop();
|
||||
assert(node.base_loops == 3 && node.resends == 1);
|
||||
}
|
||||
'''
|
||||
|
||||
ACK_HARNESS = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#define PUB_KEY_SIZE 32
|
||||
enum MessageSendState { MESSAGE_SENDING, MESSAGE_DELIVERED, MESSAGE_FAILED };
|
||||
struct ContactInfo { struct { uint8_t pub_key[PUB_KEY_SIZE] = {}; } id; };
|
||||
struct MyMesh {
|
||||
unsigned base_calls = 0;
|
||||
bool base_owned = false;
|
||||
ContactInfo base_peer;
|
||||
bool processAck(const uint8_t*, ContactInfo*& peer) {
|
||||
++base_calls;
|
||||
peer = base_owned ? &base_peer : nullptr;
|
||||
return base_owned;
|
||||
}
|
||||
};
|
||||
struct UI {
|
||||
unsigned notifications = 0;
|
||||
void onMessageSendAttempt(uint8_t, uint8_t, MessageSendState state) {
|
||||
assert(state == MESSAGE_DELIVERED);
|
||||
++notifications;
|
||||
}
|
||||
};
|
||||
struct CardputerMesh : MyMesh {
|
||||
struct {
|
||||
MessageSendState state = MESSAGE_SENDING;
|
||||
uint32_t expected_ack = 123;
|
||||
uint8_t attempt = 1, total_attempts = 3;
|
||||
ContactInfo recipient;
|
||||
} last_msg;
|
||||
UI ui;
|
||||
UI* _ui = &ui;
|
||||
unsigned long resend_timeout = 100;
|
||||
ContactInfo accepted_peer;
|
||||
bool contact_present = true;
|
||||
unsigned lookups = 0;
|
||||
ContactInfo* lookupContactByPubKey(const uint8_t* key, size_t len) {
|
||||
++lookups;
|
||||
assert(len == PUB_KEY_SIZE);
|
||||
assert(!memcmp(key, last_msg.recipient.id.pub_key, PUB_KEY_SIZE));
|
||||
return contact_present ? &accepted_peer : nullptr;
|
||||
}
|
||||
bool processAck(const uint8_t*, ContactInfo*&);
|
||||
};
|
||||
@METHOD@
|
||||
int main() {
|
||||
CardputerMesh node;
|
||||
uint32_t ack = 123;
|
||||
ContactInfo* peer = nullptr;
|
||||
assert(node.processAck(reinterpret_cast<const uint8_t*>(&ack), peer));
|
||||
assert(node.base_calls == 1 && node.lookups == 1 && peer == &node.accepted_peer);
|
||||
assert(node.last_msg.state == MESSAGE_DELIVERED && node.last_msg.expected_ack == 0);
|
||||
assert(node.resend_timeout == 0 && node.ui.notifications == 1);
|
||||
assert(!node.processAck(reinterpret_cast<const uint8_t*>(&ack), peer));
|
||||
assert(node.base_calls == 2 && node.ui.notifications == 1 && peer == nullptr);
|
||||
|
||||
CardputerMesh unrelated;
|
||||
ack = 456;
|
||||
assert(!unrelated.processAck(reinterpret_cast<const uint8_t*>(&ack), peer));
|
||||
assert(unrelated.resend_timeout == 100 && unrelated.ui.notifications == 0 && unrelated.lookups == 0);
|
||||
unrelated.base_owned = true;
|
||||
assert(unrelated.processAck(reinterpret_cast<const uint8_t*>(&ack), peer));
|
||||
assert(peer == &unrelated.base_peer && unrelated.base_calls == 2);
|
||||
assert(unrelated.last_msg.state == MESSAGE_SENDING && unrelated.resend_timeout == 100);
|
||||
|
||||
CardputerMesh shared;
|
||||
shared.base_owned = true;
|
||||
ack = 123;
|
||||
assert(shared.processAck(reinterpret_cast<const uint8_t*>(&ack), peer));
|
||||
assert(peer == &shared.base_peer && shared.lookups == 0 && shared.ui.notifications == 1);
|
||||
|
||||
CardputerMesh removed;
|
||||
removed.contact_present = false;
|
||||
assert(removed.processAck(reinterpret_cast<const uint8_t*>(&ack), peer));
|
||||
assert(peer == nullptr && removed.lookups == 1 && removed.resend_timeout == 0);
|
||||
|
||||
CardputerMesh no_ack;
|
||||
no_ack.last_msg.expected_ack = 0;
|
||||
ack = 0;
|
||||
assert(!no_ack.processAck(reinterpret_cast<const uint8_t*>(&ack), peer));
|
||||
assert(no_ack.last_msg.state == MESSAGE_SENDING && no_ack.resend_timeout == 100);
|
||||
assert(no_ack.ui.notifications == 0 && no_ack.lookups == 0);
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class CardputerMeshStorageTests(unittest.TestCase):
|
||||
def run_cpp(self, source, *, headers=None, flags=(), fails=False):
|
||||
compiler = shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
self.skipTest("A host C++ compiler is required")
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
work = Path(temporary)
|
||||
for name, content in (headers or {}).items():
|
||||
(work / name).write_text(content, encoding="ascii")
|
||||
program = work / "test.cpp"
|
||||
program.write_text(source, encoding="ascii")
|
||||
executable = work / "test"
|
||||
built = subprocess.run([
|
||||
compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror", "-O1", "-g",
|
||||
"-fsanitize=address,undefined", "-fno-omit-frame-pointer", "-fno-pie", "-no-pie",
|
||||
"-I", str(work), "-I", str(VARIANT), *flags, str(program), "-o", str(executable),
|
||||
], text=True, capture_output=True, timeout=60)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
env = dict(os.environ, ASAN_OPTIONS="detect_leaks=1:halt_on_error=1",
|
||||
UBSAN_OPTIONS="halt_on_error=1")
|
||||
result = subprocess.run([str(executable)], text=True, capture_output=True, env=env, timeout=10)
|
||||
if fails:
|
||||
self.assertNotEqual(result.returncode, 0, "negative control unexpectedly passed")
|
||||
else:
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
def storage_source(self):
|
||||
source = (VARIANT / "CardputerDataStore.cpp").read_text()
|
||||
return source + STORAGE_CHECKS
|
||||
|
||||
def mesh_source(self):
|
||||
source = (VARIANT / "companion_radio/CardputerMesh.cpp").read_text()
|
||||
methods = "\n".join(body(source, signature) for signature in (
|
||||
"bool CardputerMesh::sendFloodScoped(", "bool CardputerMesh::sendGroupMessage(",
|
||||
"void CardputerMesh::loop()"))
|
||||
return MESH_HARNESS.replace("@METHODS@", methods)
|
||||
|
||||
def test_history_storage_and_faults(self):
|
||||
self.run_cpp(self.storage_source(), headers={"DataStore.h": FILESYSTEM_STUB})
|
||||
|
||||
def test_history_source_bound_negative_control(self):
|
||||
source = self.storage_source().replace(
|
||||
"msg_len < MAX_MESSAGE_LENGTH && text[msg_len] != '\\0'",
|
||||
"text[msg_len] != '\\0' && msg_len < MAX_MESSAGE_LENGTH")
|
||||
self.assertNotEqual(source, self.storage_source())
|
||||
self.run_cpp(source, headers={"DataStore.h": FILESYSTEM_STUB}, fails=True)
|
||||
|
||||
def test_sd_no_progress_negative_control(self):
|
||||
source = self.storage_source().replace(" if (bytesRead <= 0) {\n break;\n }\n", "")
|
||||
self.assertNotEqual(source, self.storage_source())
|
||||
self.run_cpp(source, headers={"DataStore.h": FILESYSTEM_STUB}, fails=True)
|
||||
|
||||
def test_group_admission_and_packet_ownership(self):
|
||||
self.run_cpp(self.mesh_source())
|
||||
|
||||
def test_cardputer_ack_ownership_preserves_base_processing(self):
|
||||
source = (VARIANT / "companion_radio/CardputerMesh.cpp").read_text()
|
||||
self.run_cpp(ACK_HARNESS.replace("@METHOD@", body(source, "bool CardputerMesh::processAck(")))
|
||||
|
||||
def test_packet_ownership_negative_control(self):
|
||||
source = self.mesh_source().replace(
|
||||
" if (sent && is_group_text) {",
|
||||
" if (pkt->getPayloadType() == PAYLOAD_TYPE_GRP_TXT) {")
|
||||
self.assertNotEqual(source, self.mesh_source())
|
||||
self.run_cpp(source, fails=True)
|
||||
|
||||
def test_main_loop_dispatch(self):
|
||||
source = (ROOT / "examples/companion_radio/main.cpp").read_text()
|
||||
dispatch = re.search(
|
||||
r"#if CARDPUTER_ADV_UI\n the_mesh_cp\.loop\(\);\n#else\n the_mesh\.loop\(\);\n#endif",
|
||||
source)
|
||||
self.assertIsNotNone(dispatch)
|
||||
harness = r'''
|
||||
#include <cassert>
|
||||
struct MyMesh { unsigned base_calls = 0; void loop() { ++base_calls; } };
|
||||
struct CardputerMesh : MyMesh { unsigned custom_calls = 0; void loop() { MyMesh::loop(); ++custom_calls; } };
|
||||
CardputerMesh the_mesh_cp;
|
||||
MyMesh& the_mesh = the_mesh_cp;
|
||||
int main() {
|
||||
@DISPATCH@
|
||||
assert(the_mesh.base_calls == 1);
|
||||
assert(the_mesh_cp.custom_calls == CARDPUTER_ADV_UI);
|
||||
}
|
||||
'''.replace("@DISPATCH@", dispatch.group())
|
||||
for enabled in (0, 1):
|
||||
with self.subTest(cardputer=enabled):
|
||||
self.run_cpp(harness, flags=(f"-DCARDPUTER_ADV_UI={enabled}",))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Bound custom Cardputer runtime owners and truncated display text."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
from check_firmware_ram import requirements
|
||||
from test_replay_reset_integration import extract_braced
|
||||
|
||||
|
||||
class CardputerRuntimeMemoryTests(unittest.TestCase):
|
||||
def test_custom_ui_owners_are_additive_and_fonts_fit_their_allowance(self):
|
||||
base = {"ESP32_PLATFORM": "1", "BLE_PIN_CODE": "123456"}
|
||||
target = "M5Stack_Cardputer_Adv_companion_radio_ble"
|
||||
ordinary = requirements("ESP32_PLATFORM", base, target)
|
||||
custom = requirements("ESP32_PLATFORM", dict(base, CARDPUTER_ADV_UI="1"), target)
|
||||
self.assertEqual(ordinary["components"], {
|
||||
key: value for key, value in custom["components"].items()
|
||||
if not key.startswith("cardputer_")})
|
||||
self.assertGreater(custom["required_heap_bytes"], ordinary["required_heap_bytes"])
|
||||
fonts = ROOT / "variants/m5stack_cardputer_adv/companion_radio/ui-cardputer"
|
||||
for name in ("font.h", "font_16.h", "font_19.h"):
|
||||
data = (fonts / name).read_text().split("{", 1)[1]
|
||||
prefix = bytes(int(byte, 16) for byte in re.findall(r"0x([0-9a-fA-F]{2})", data)[:4])
|
||||
glyphs = int.from_bytes(prefix, "big")
|
||||
self.assertGreater(glyphs, 0)
|
||||
self.assertLessEqual(glyphs, 716)
|
||||
# Five VLW arrays use 4+2+1+1+1 bytes/glyph. Also allow
|
||||
# allocation metadata and the runtime font object itself.
|
||||
self.assertLessEqual(glyphs * 9 + 1024,
|
||||
custom["components"]["cardputer_font_metadata"])
|
||||
disabled = requirements("ESP32_PLATFORM", dict(base, CARDPUTER_ADV_UI="0"), target)
|
||||
self.assertEqual(disabled, ordinary)
|
||||
with self.assertRaisesRegex(ValueError, "ESP32 Companion"):
|
||||
requirements("NRF52_PLATFORM", {"CARDPUTER_ADV_UI": "1"}, target)
|
||||
|
||||
def test_scroll_keeps_truncated_utf8_inside_the_input_buffer(self):
|
||||
driver = (ROOT / "variants/m5stack_cardputer_adv/hw/CardputerDisplay.cpp").read_text()
|
||||
method = extract_braced(driver, "void CardputerDisplay::drawTextLeftAlignWithScroll(")
|
||||
prelude = r'''
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
class CardputerDisplay {
|
||||
public:
|
||||
const char* begin = nullptr;
|
||||
const char* end = nullptr;
|
||||
int getTextWidth(const char* text) { return strlen(text); }
|
||||
void drawTextLeftAlign(int, int, const char* text) {
|
||||
assert(text >= begin && text <= end);
|
||||
(void)strlen(text);
|
||||
}
|
||||
void drawTextLeftAlignWithScroll(int, int, int, const char*);
|
||||
};
|
||||
int main() {
|
||||
CardputerDisplay display;
|
||||
for (unsigned lead : {0xC2U, 0xE2U, 0xF0U}) {
|
||||
char text[2] = {static_cast<char>(lead), 0};
|
||||
display.begin = text; display.end = text + 1;
|
||||
display.drawTextLeftAlignWithScroll(0, 0, 0, text);
|
||||
}
|
||||
}
|
||||
'''
|
||||
prelude = '#include <initializer_list>\n' + prelude
|
||||
for legacy in (False, True):
|
||||
body = method.replace(" offset = text_len;\n", "") if legacy else method
|
||||
with self.subTest(legacy=legacy), tempfile.TemporaryDirectory() as directory:
|
||||
work = Path(directory)
|
||||
cpp, binary = work / "scroll.cpp", work / "scroll"
|
||||
cpp.write_text(prelude + body)
|
||||
build = subprocess.run(["g++", "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
||||
"-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-pie", "-no-pie",
|
||||
str(cpp), "-o", str(binary)], capture_output=True, text=True)
|
||||
self.assertEqual(build.returncode, 0, build.stdout + build.stderr)
|
||||
run = subprocess.run([str(binary)], capture_output=True, text=True)
|
||||
if legacy:
|
||||
self.assertNotEqual(run.returncode, 0, "Unclamped scroll unexpectedly passed")
|
||||
else:
|
||||
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,286 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Execute Cardputer text-entry, rendering and radio validation without hardware."""
|
||||
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VARIANT = ROOT / "variants/m5stack_cardputer_adv"
|
||||
UI = VARIANT / "companion_radio/ui-cardputer"
|
||||
|
||||
|
||||
def function(source, signature):
|
||||
start = source.index(signature)
|
||||
opening = source.index("{", start)
|
||||
depth = 1
|
||||
end = opening + 1
|
||||
while depth:
|
||||
depth += (source[end] == "{") - (source[end] == "}")
|
||||
end += 1
|
||||
return source[start:end]
|
||||
|
||||
|
||||
class CardputerUiTests(unittest.TestCase):
|
||||
def test_actual_settings_entry_render_validation_and_headless_shutdown(self):
|
||||
settings = (UI / "screen/SettingsScreen.cpp").read_text(encoding="ascii")
|
||||
header = (UI / "screen/SettingsScreen.h").read_text(encoding="ascii")
|
||||
enum = re.search(r"enum SettingsItem \{.*?\};", header, re.S).group()
|
||||
limit = re.search(r"static constexpr size_t MAX_NUMERIC_EDIT_BYTES = \d+;", header).group()
|
||||
cli = (ROOT / "src/helpers/CLICommandUtils.h").read_text()
|
||||
radio = (ROOT / "src/helpers/radiolib/RadioLibWrappers.cpp").read_text()
|
||||
task = (UI / "CardputerUITask.cpp").read_text(encoding="ascii")
|
||||
channels = (UI / "screen/main/ChannelsPage.cpp").read_text(encoding="ascii")
|
||||
code = r'''
|
||||
#include <cassert>
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <algorithm>
|
||||
#include "RadioProfiles.h"
|
||||
using std::isfinite;
|
||||
#define LORA_TX_POWER 22
|
||||
#define MAX_GROUP_CHANNELS 40
|
||||
class String {
|
||||
std::string value;
|
||||
public:
|
||||
String() = default;
|
||||
String(const char* s): value(s) {}
|
||||
String& operator=(const char* s) { value=s; return *this; }
|
||||
unsigned length() const { return value.size(); }
|
||||
const char* c_str() const { return value.c_str(); }
|
||||
long toInt() const { return std::strtol(value.c_str(),nullptr,10); }
|
||||
int indexOf(char c) const { auto p=value.find(c); return p==std::string::npos ? -1 : int(p); }
|
||||
void concat(char c) { value+=c; }
|
||||
void concat(const char* s) { value+=s; }
|
||||
char charAt(unsigned i) const { return i<value.size() ? value[i] : 0; }
|
||||
void remove(unsigned i,unsigned n) { value.erase(i,n); }
|
||||
};
|
||||
#include "helpers.h"
|
||||
namespace Keyboard {
|
||||
enum Key { KEY_NONE, KEY_BACKSPACE, KEY_PERIOD, ARROW_LEFT, ARROW_RIGHT, KEY_1,
|
||||
ARROW_UP, ARROW_DOWN, KEY_RETURN };
|
||||
struct Event { Key key=KEY_NONE; const char* text=""; };
|
||||
}
|
||||
struct Layout {
|
||||
const char* getCurrentCode() const { return "en"; }
|
||||
const char* lookupDefault(Keyboard::Event& e) { return e.text; }
|
||||
const char* lookup(Keyboard::Event& e) { return e.text; }
|
||||
};
|
||||
struct Board {
|
||||
Layout layout;
|
||||
unsigned off=0,boots=0;
|
||||
Layout* getLayout() { return &layout; }
|
||||
uint16_t getBattMilliVolts() const { return 4000; }
|
||||
void powerOff() { ++off; }
|
||||
void reboot() { ++boots; }
|
||||
};
|
||||
struct Task {
|
||||
Board board;
|
||||
Board* getBoard() { return &board; }
|
||||
bool getGPSState() const { return true; }
|
||||
bool isBluetoothEnabled() const { return true; }
|
||||
bool powerSaveEnabled() const { return true; }
|
||||
};
|
||||
struct Prefs {
|
||||
char node_name[32]="node",default_scope_name[31]="";
|
||||
uint8_t default_scope_key[32]={};
|
||||
float freq=910.525f,bw=62.5f;
|
||||
uint8_t sf=8,cr=5,path_hash_mode=1,buzzer_quiet=0;
|
||||
int8_t tx_power_dbm=22;
|
||||
};
|
||||
struct CustomPrefs { float battery_correction=1; };
|
||||
struct ChannelDetails { char name[32]={}; };
|
||||
struct Mesh {
|
||||
unsigned saves=0;
|
||||
ChannelDetails channels[MAX_GROUP_CHANNELS];
|
||||
void savePrefs() { ++saves; }
|
||||
bool getChannel(int i,ChannelDetails& result) {
|
||||
if(i<0 || i>=MAX_GROUP_CHANNELS) return false;
|
||||
result=channels[i]; return true;
|
||||
}
|
||||
} the_mesh_cp;
|
||||
namespace mesh { namespace Utils {
|
||||
void sha256(uint8_t* dest,size_t n,const uint8_t*,size_t,const uint8_t*,size_t) { memset(dest,0,n); }
|
||||
} namespace cli {
|
||||
'''
|
||||
code += function(cli, "inline bool parseDecimalStrict(") + "\n}}\n"
|
||||
code += r'''
|
||||
struct RadioLibWrapper {
|
||||
unsigned off=0;
|
||||
bool supportsMeshtext() const { return false; }
|
||||
bool validateProfile(const mesh::RadioProfileParams&) const;
|
||||
bool isTxPowerValid(int8_t p) const { return p>=-9 && p<=22; }
|
||||
void powerOff() { ++off; }
|
||||
} radio_driver;
|
||||
'''
|
||||
code += function(radio, "bool RadioLibWrapper::validateProfile(") + "\n"
|
||||
code += r'''
|
||||
struct CardputerDisplay {
|
||||
enum PaletteColor { P_GREEN,P_YELLOW,P_RED,P_BLACK,P_WHITE };
|
||||
std::string last;
|
||||
int getRowHeight() const { return 16; }
|
||||
int height() const { return 135; }
|
||||
int width() const { return 240; }
|
||||
int getTextWidth(const char* s) { return strlen(s)*8; }
|
||||
int getTextLevel() const { return 1; }
|
||||
static const char* textLevelName(int) { return "Large"; }
|
||||
void setColor(PaletteColor) {}
|
||||
void setTextSize(int) {}
|
||||
void drawTextCentered(int,int,const char*) {}
|
||||
void drawTextLeftAlign(int,int,const char*) {}
|
||||
void drawTextEllipsized(int,int,int,const char*) {}
|
||||
void drawTextLeftAlignWithScroll(int,int,int,const char* s) { last=s; }
|
||||
void drawRect(int,int,int,int) {}
|
||||
void fillRect(int,int,int,int) {}
|
||||
void turnOff() {}
|
||||
};
|
||||
struct SettingsScreen {
|
||||
'''
|
||||
code += enum + "\n" + limit + r'''
|
||||
Prefs* _node_prefs;
|
||||
CustomPrefs* _custom_prefs;
|
||||
Task* _task;
|
||||
String edit_buffer;
|
||||
uint8_t edit_u8=0;
|
||||
int menu_index=RadioFreq;
|
||||
bool restart_required=false,is_editing=true;
|
||||
void renderItem(CardputerDisplay&,SettingsItem,int,int);
|
||||
bool commitItemEdit(SettingsItem);
|
||||
void handleEditInput(SettingsItem,Keyboard::Event&);
|
||||
bool inputParsePositiveFloat(float&);
|
||||
bool validRadioParams(float,float,uint8_t,uint8_t) const;
|
||||
int render(CardputerDisplay&);
|
||||
};
|
||||
'''
|
||||
for signature in (
|
||||
"void SettingsScreen::renderItem(",
|
||||
"bool SettingsScreen::commitItemEdit(",
|
||||
"void SettingsScreen::handleEditInput(",
|
||||
"bool SettingsScreen::inputParsePositiveFloat(",
|
||||
"bool SettingsScreen::validRadioParams(",
|
||||
"int SettingsScreen::render(",
|
||||
):
|
||||
code += function(settings, signature) + "\n"
|
||||
code += r'''
|
||||
struct CardputerUITask {
|
||||
CardputerDisplay* _display=nullptr;
|
||||
Board* _board;
|
||||
void shutdown(bool restart=false);
|
||||
};
|
||||
'''
|
||||
code += function(task, "void CardputerUITask::shutdown(") + "\n"
|
||||
code += r'''
|
||||
struct MainScreen {
|
||||
int selected=-1;
|
||||
void selectChannel(const ChannelDetails&,int index) { selected=index; }
|
||||
};
|
||||
struct ChannelsPage {
|
||||
MainScreen* _p;
|
||||
int channel_list_idx=0;
|
||||
int getChannelCount();
|
||||
bool getChannelIndex(int,int&);
|
||||
bool handleInput(Keyboard::Event&);
|
||||
};
|
||||
'''
|
||||
for signature in (
|
||||
"int ChannelsPage::getChannelCount(",
|
||||
"bool ChannelsPage::getChannelIndex(",
|
||||
"bool ChannelsPage::handleInput(",
|
||||
):
|
||||
code += function(channels, signature) + "\n"
|
||||
code += r'''
|
||||
int main() {
|
||||
Prefs prefs; CustomPrefs custom; Task task; CardputerDisplay display;
|
||||
SettingsScreen s{&prefs,&custom,&task};
|
||||
Keyboard::Event digit{Keyboard::KEY_1,"9"};
|
||||
for(int i=0;i<4096;++i) s.handleEditInput(SettingsScreen::RadioFreq,digit);
|
||||
assert(s.edit_buffer.length()==s.MAX_NUMERIC_EDIT_BYTES);
|
||||
s.render(display); assert(display.last.size()<=63);
|
||||
// Render must also remain safe when an external/current value exceeds the input bound.
|
||||
std::string long_value(4096,'9'); s.edit_buffer=long_value.c_str();
|
||||
s.render(display); assert(display.last.size()==63);
|
||||
for(const char* bad:{"",".","0","-1","nan","inf","1e3","910x","42949672960"}) {
|
||||
s.edit_buffer=bad; float value=123;
|
||||
assert(!s.inputParsePositiveFloat(value) && value==123);
|
||||
}
|
||||
for(const char* bad:{"0","149.9","960.1","42949672960"}) {
|
||||
s.edit_buffer=bad;
|
||||
assert(!s.commitItemEdit(SettingsScreen::RadioFreq));
|
||||
assert(prefs.freq==910.525f && the_mesh_cp.saves==0 && !s.restart_required);
|
||||
}
|
||||
s.edit_buffer="915.25";
|
||||
assert(s.commitItemEdit(SettingsScreen::RadioFreq));
|
||||
assert(prefs.freq==915.25f && the_mesh_cp.saves==1 && s.restart_required);
|
||||
for(const char* bad:{"0","123.45","812.5"}) {
|
||||
s.edit_buffer=bad;
|
||||
assert(!s.commitItemEdit(SettingsScreen::RadioBw));
|
||||
assert(prefs.bw==62.5f && the_mesh_cp.saves==1);
|
||||
}
|
||||
s.edit_buffer="125"; assert(s.commitItemEdit(SettingsScreen::RadioBw));
|
||||
assert(prefs.bw==125 && the_mesh_cp.saves==2);
|
||||
s.edit_u8=4; assert(!s.commitItemEdit(SettingsScreen::RadioSf));
|
||||
assert(!s.commitItemEdit(SettingsScreen::RadioCr));
|
||||
s.edit_u8=23; assert(!s.commitItemEdit(SettingsScreen::RadioPwr));
|
||||
assert(prefs.sf==8 && prefs.cr==5 && prefs.tx_power_dbm==22 && the_mesh_cp.saves==2);
|
||||
// A missing/failed display cannot turn a battery shutdown into a null dereference.
|
||||
CardputerUITask ui{nullptr,&task.board};
|
||||
ui.shutdown(); assert(task.board.off==1 && radio_driver.off==1);
|
||||
ui.shutdown(true); assert(task.board.boots==1);
|
||||
// Channel list indices must map back to actual sparse channel slots.
|
||||
MainScreen main_screen; ChannelsPage list{&main_screen};
|
||||
for(int i:{2,7,39}) strcpy(the_mesh_cp.channels[i].name,"channel");
|
||||
assert(list.getChannelCount()==3);
|
||||
int real=-1;
|
||||
assert(list.getChannelIndex(0,real) && real==2);
|
||||
assert(list.getChannelIndex(1,real) && real==7);
|
||||
assert(list.getChannelIndex(2,real) && real==39);
|
||||
assert(!list.getChannelIndex(3,real));
|
||||
Keyboard::Event enter{Keyboard::KEY_RETURN,""};
|
||||
list.handleInput(enter); assert(main_screen.selected==2);
|
||||
Keyboard::Event up{Keyboard::ARROW_UP,""},down{Keyboard::ARROW_DOWN,""};
|
||||
list.handleInput(up); assert(list.channel_list_idx==2);
|
||||
list.handleInput(enter); assert(main_screen.selected==39);
|
||||
list.handleInput(down); assert(list.channel_list_idx==0);
|
||||
for(auto& channel:the_mesh_cp.channels) channel=ChannelDetails{};
|
||||
assert(list.getChannelCount()==0);
|
||||
list.handleInput(enter); assert(main_screen.selected==39);
|
||||
list.handleInput(up); assert(list.channel_list_idx==0);
|
||||
std::puts("PASS: actual Cardputer entry, render, validation and headless shutdown");
|
||||
}
|
||||
'''
|
||||
with tempfile.TemporaryDirectory(prefix="cardputer-ui-") as tmp:
|
||||
source = Path(tmp) / "test.cpp"
|
||||
binary = Path(tmp) / "test"
|
||||
source.write_text(code, encoding="ascii")
|
||||
compiled = subprocess.run([
|
||||
"g++", "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
||||
"-Wno-unused-parameter", "-Wno-missing-field-initializers",
|
||||
"-fsanitize=address,undefined", "-fno-omit-frame-pointer", "-no-pie",
|
||||
"-DMESH_RADIO_PROFILE_CHIP=1262", "-DMESH_ENABLE_HOST_KISS=0",
|
||||
"-DMESH_ENABLE_ETHERNET_WIRE=0", "-I", str(ROOT / "src"),
|
||||
"-I", str(VARIANT), str(source), "-o", str(binary),
|
||||
], capture_output=True, text=True)
|
||||
self.assertEqual(compiled.returncode, 0, compiled.stderr)
|
||||
executed = subprocess.run([str(binary)], capture_output=True, text=True)
|
||||
self.assertEqual(executed.returncode, 0, executed.stdout + executed.stderr)
|
||||
|
||||
def test_bounded_formatting_and_font_attribution(self):
|
||||
for source in UI.rglob("*.cpp"):
|
||||
self.assertNotRegex(source.read_text(encoding="ascii"), r"\bsprintf\s*\(", str(source))
|
||||
notice = (VARIANT / "LICENSE.DejaVu").read_text(encoding="ascii")
|
||||
self.assertIn("Copyright (c) 2003 by Bitstream", notice)
|
||||
self.assertIn("Copyright (c) 2006 by Tavmjong Bah", notice)
|
||||
self.assertIn("included in all copies of one or more", notice)
|
||||
for font in ("font.h", "font_16.h", "font_19.h"):
|
||||
self.assertIn("LICENSE.DejaVu", (UI / font).read_text(encoding="ascii"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user