Fit Nordic Full KISS with lossless assets and firmware lifetime trimming
This commit is contained in:
1 parent
2369a3d28c
commit
b4bec19e88
51 files changed
+7739
-17
No files matched your search
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Keep native and Python ARM per-instruction measurements identical."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
try:
|
||||
import unicorn
|
||||
from unicorn import Uc, UC_ARCH_ARM, UC_MODE_THUMB, UC_MODE_MCLASS
|
||||
from unicorn import arm_const as arm
|
||||
import arm_instruction_meter as module
|
||||
except ImportError:
|
||||
unicorn = None
|
||||
|
||||
|
||||
@unittest.skipUnless(unicorn is not None, 'Unicorn is not installed in this host job')
|
||||
class ArmInstructionMeterTest(unittest.TestCase):
|
||||
def machine(self, native):
|
||||
uc = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS)
|
||||
uc.mem_map(0x1000, 0x1000)
|
||||
uc.mem_map(0x20000000, 0x1000)
|
||||
# push {r7,lr}; sub sp,32; movs r0,100; loop: subs r0,1;
|
||||
# bne loop; add sp,32; pop {r7,pc}. Exactly 205 instructions.
|
||||
uc.mem_write(0x1100, bytes.fromhex('80b588b064200138fdd108b080bd'))
|
||||
return uc, module.ArmInstructionMeter(uc, prefer_native=native)
|
||||
|
||||
def run_machine(self, machine, meter, top):
|
||||
machine.reg_write(arm.UC_ARM_REG_SP, top)
|
||||
machine.reg_write(arm.UC_ARM_REG_LR, 0x1001)
|
||||
meter.reset(top)
|
||||
machine.emu_start(0x1101, 0x1000, timeout=1000000, count=1000)
|
||||
self.assertEqual(machine.reg_read(arm.UC_ARM_REG_PC), 0x1000)
|
||||
self.assertEqual(machine.reg_read(arm.UC_ARM_REG_SP), top)
|
||||
self.assertEqual(machine.reg_read(arm.UC_ARM_REG_R0), 0)
|
||||
self.assertEqual(meter.snapshot(), {'minimum_sp': top - 40, 'instructions': 205})
|
||||
return meter.snapshot()
|
||||
|
||||
def test_native_python_exact_measurements_repeated_and_independent_contexts(self):
|
||||
if unicorn.__version__ != '2.1.4':
|
||||
self.skipTest('native private handle API is pinned to Unicorn 2.1.4')
|
||||
if not any(shutil.which(name) for name in ('cc', 'gcc', 'clang')):
|
||||
self.skipTest('host C compiler unavailable')
|
||||
python_uc, python_meter = self.machine(False)
|
||||
native_uc, native_meter = self.machine(True)
|
||||
second_uc, second_meter = self.machine(True)
|
||||
self.assertEqual(native_meter.backend, 'native')
|
||||
self.assertEqual(second_meter.backend, 'native')
|
||||
for top in (0x20001000, 0x20000f00, 0x20001000):
|
||||
expected = self.run_machine(python_uc, python_meter, top)
|
||||
self.assertEqual(self.run_machine(native_uc, native_meter, top), expected)
|
||||
self.assertEqual(self.run_machine(second_uc, second_meter, top), expected)
|
||||
|
||||
def test_missing_native_compiler_uses_identical_python_measurement(self):
|
||||
module._native_library.cache_clear()
|
||||
try:
|
||||
with mock.patch.object(module.shutil, 'which', return_value=None):
|
||||
machine, meter = self.machine(True)
|
||||
finally:
|
||||
module._native_library.cache_clear()
|
||||
self.assertEqual(meter.backend, 'python')
|
||||
self.run_machine(machine, meter, 0x20001000)
|
||||
|
||||
def test_unreviewed_unicorn_version_uses_python_measurement(self):
|
||||
with mock.patch.object(module.unicorn, '__version__', 'unreviewed-core'):
|
||||
machine, meter = self.machine(True)
|
||||
self.assertEqual(meter.backend, 'python')
|
||||
self.run_machine(machine, meter, 0x20001000)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -93,11 +93,22 @@ class CompanionReaderTest(unittest.TestCase):
|
||||
return found[0]
|
||||
|
||||
reader, decoder = frames("reader"), frames("tinf")
|
||||
# Summing all helper frames overbounds mutually exclusive branches
|
||||
# (tree building and block decoding), including their leaf calls.
|
||||
decoder_bytes = sum(count for name, count in decoder.items()
|
||||
if not name.endswith(":tinf_init") and not name.endswith(":tinf_uncompress"))
|
||||
# Tree building and block decoding are mutually exclusive too;
|
||||
# sum their helpers as a conservative overbound. Linear OTA and
|
||||
# circular Reader entry points never nest, so retain the larger
|
||||
# entry family instead of adding both independent histories.
|
||||
linear_names = (":tinf_uncompress_internal", ":tinf_uncompress_exact",
|
||||
":tinf_inflate_block_data")
|
||||
ring_names = (":tinf_uncompress_record", ":tinf_record_block",
|
||||
":tinf_record_emit", ":tinf_record_reverse")
|
||||
linear = sum(count for name, count in decoder.items() if name.endswith(linear_names))
|
||||
ring = sum(count for name, count in decoder.items() if name.endswith(ring_names))
|
||||
shared = sum(count for name, count in decoder.items()
|
||||
if not name.endswith(linear_names + ring_names + (":tinf_init", ":tinf_uncompress")))
|
||||
self.assertGreater(ring, 0, "actual nRF52 Reader ring decoder must be measured")
|
||||
decoder_bytes = shared + max(linear, ring)
|
||||
lookup = frame(reader, "mesh::readReaderVerse(")
|
||||
lookup += sum(count for name, count in reader.items() if "mesh::bible::lookup(" in name)
|
||||
terminal = (frame(reader, "mesh::handleReaderCommand(")
|
||||
+ frame(reader, "::printReplyPage(") + frame(reader, "::replyVerse(")
|
||||
+ lookup + decoder_bytes)
|
||||
@@ -434,7 +445,10 @@ int main() {
|
||||
"-I" + str(ROOT / "src"), "-I" + str(FIXTURE),
|
||||
str(FIXTURE / "test_reader_screen.cpp"), str(ROOT / "src/helpers/CompanionReader.cpp"),
|
||||
str(obj), "-o", str(binary)])
|
||||
self.run_checked([str(binary)])
|
||||
# All 879 verses are laid out forwards/backwards at 18 panel
|
||||
# geometries. The 4 KiB streaming nRF corpus does more
|
||||
# bounded decode work per cold lookup; keep every case.
|
||||
self.run_checked([str(binary)], timeout=600)
|
||||
|
||||
def test_actual_reader_stream_pauses_and_decode_entrypoints_reject_during_morse(self):
|
||||
cc, cxx = shutil.which("gcc"), shutil.which("g++")
|
||||
@@ -651,9 +665,9 @@ int main() {
|
||||
str(ROOT / "src/helpers/ui/DisplayDriver.cpp"), "-o", str(binary)])
|
||||
self.run_checked([str(binary)])
|
||||
|
||||
def run_checked(self, command):
|
||||
def run_checked(self, command, timeout=60):
|
||||
result = subprocess.run(command, capture_output=True, encoding="utf-8",
|
||||
errors="backslashreplace", timeout=60)
|
||||
errors="backslashreplace", timeout=timeout)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
return result.stdout
|
||||
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Keep local cleanup while omitting unreachable nRF52 process-exit callbacks."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location("nrf52_flash_trim", ROOT / "scripts/nrf52_flash_trim.py")
|
||||
policy = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(policy)
|
||||
|
||||
|
||||
class Nrf52ProgramLifetimeTest(unittest.TestCase):
|
||||
def test_automatic_delete_and_explicit_shutdown_remain_and_exit_callback_is_not_registered(self):
|
||||
compiler = shutil.which("g++")
|
||||
if not compiler:
|
||||
self.skipTest("native G++ unavailable")
|
||||
source = r'''
|
||||
#include <cassert>
|
||||
extern "C" int __aeabi_atexit(void*, void (*)(void*), void*);
|
||||
extern "C" int __cxa_atexit(void (*)(void*), void*, void*);
|
||||
extern "C" void __cxa_finalize(void*);
|
||||
unsigned closed = 0, destroyed = 0, callback = 0;
|
||||
void cleanup(void* count) { ++*static_cast<unsigned*>(count); }
|
||||
struct Resource {
|
||||
void close() { ++closed; }
|
||||
~Resource() { close(); ++destroyed; }
|
||||
};
|
||||
int main() {
|
||||
{ Resource automatic; }
|
||||
auto* allocated = new Resource;
|
||||
delete allocated;
|
||||
assert(closed == 2 && destroyed == 2);
|
||||
Resource explicit_close;
|
||||
explicit_close.close();
|
||||
assert(closed == 3 && destroyed == 2);
|
||||
unsigned dso = 0;
|
||||
assert(__aeabi_atexit(&callback, cleanup, &dso) == 0);
|
||||
__cxa_finalize(&dso);
|
||||
assert(callback == 0);
|
||||
// Positive control: the finalizer really can run a registered callback.
|
||||
assert(__cxa_atexit(cleanup, &callback, &dso) == 0);
|
||||
__cxa_finalize(&dso);
|
||||
assert(callback == 1);
|
||||
}
|
||||
'''
|
||||
with tempfile.TemporaryDirectory(prefix="mesh-nrf52-lifetime-") as directory:
|
||||
directory = Path(directory)
|
||||
main, binary = directory / "main.cpp", directory / "checks"
|
||||
main.write_text(source, encoding="ascii")
|
||||
subprocess.run([compiler, "-std=c++11", "-Os", "-flto", "-DNRF52_PLATFORM=1",
|
||||
"-DMESH_NRF52_NO_PROGRAM_EXIT=1", str(main),
|
||||
str(ROOT / "src/Nrf52ProgramLifetime.cpp"), "-o", str(binary)], check=True)
|
||||
subprocess.run([str(binary)], check=True)
|
||||
|
||||
def test_unknown_and_absent_framework_main_keep_standard_registration(self):
|
||||
self.assertFalse(policy.supported_program_lifetime(None))
|
||||
with tempfile.TemporaryDirectory(prefix="mesh-nrf52-lifetime-core-") as directory:
|
||||
self.assertFalse(policy.supported_program_lifetime(directory))
|
||||
main = Path(directory) / "cores/nRF5/main.cpp"
|
||||
main.parent.mkdir(parents=True)
|
||||
main.write_text("int main() { return 0; }\n", encoding="ascii")
|
||||
self.assertFalse(policy.supported_program_lifetime(directory))
|
||||
|
||||
def test_current_pinned_core_is_the_reviewed_nonreturning_main_when_installed(self):
|
||||
framework = Path.home() / ".platformio/packages/framework-arduinoadafruitnrf52"
|
||||
if not framework.is_dir():
|
||||
self.skipTest("pinned nRF52 framework not installed in this host job")
|
||||
if not policy.supported_program_lifetime(framework):
|
||||
self.skipTest("custom or newer core retains ordinary exit registration")
|
||||
main = (framework / "cores/nRF5/main.cpp").read_text()
|
||||
self.assertIn("while (1)", main)
|
||||
self.assertIn("vTaskStartScheduler();", main)
|
||||
self.assertIn("NVIC_SystemReset();", main)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,415 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise the actual bounded Reader stream decoder and selected-verse lookup."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import random
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def raw_deflate(data, level=9, strategy=zlib.Z_DEFAULT_STRATEGY):
|
||||
compressor = zlib.compressobj(level, zlib.DEFLATED, -12, 8, strategy)
|
||||
return compressor.compress(data) + compressor.flush()
|
||||
|
||||
|
||||
def stored(data, final=True):
|
||||
assert len(data) <= 65535
|
||||
size = len(data)
|
||||
return bytes([int(final)]) + size.to_bytes(2, "little") + (size ^ 65535).to_bytes(2, "little") + data
|
||||
|
||||
|
||||
class Bits:
|
||||
def __init__(self):
|
||||
self.bits = []
|
||||
|
||||
def put(self, value, count):
|
||||
self.bits.extend((value >> bit) & 1 for bit in range(count))
|
||||
|
||||
def huffman(self, value, count):
|
||||
self.put(int(f"{value:0{count}b}"[::-1], 2), count)
|
||||
|
||||
def literal(self, symbol):
|
||||
if symbol <= 143:
|
||||
self.huffman(48 + symbol, 8)
|
||||
elif symbol <= 255:
|
||||
self.huffman(400 + symbol - 144, 9)
|
||||
elif symbol <= 279:
|
||||
self.huffman(symbol - 256, 7)
|
||||
else:
|
||||
self.huffman(192 + symbol - 280, 8)
|
||||
|
||||
def finish(self):
|
||||
self.bits.extend([0] * ((-len(self.bits)) % 8))
|
||||
return bytes(sum(self.bits[start + bit] << bit for bit in range(8))
|
||||
for start in range(0, len(self.bits), 8))
|
||||
|
||||
|
||||
def back_reference(distance):
|
||||
bits = Bits()
|
||||
bits.put(1, 1)
|
||||
bits.put(1, 2) # final fixed-Huffman block
|
||||
bits.literal(257) # length 3
|
||||
if distance == 4096:
|
||||
bits.huffman(23, 5)
|
||||
bits.put(1023, 10)
|
||||
elif distance == 4097:
|
||||
bits.huffman(24, 5)
|
||||
bits.put(0, 11)
|
||||
else:
|
||||
raise AssertionError(distance)
|
||||
bits.literal(0)
|
||||
bits.literal(256)
|
||||
return bits.finish()
|
||||
|
||||
|
||||
def array(data):
|
||||
return "{" + ",".join(str(byte) for byte in data) + "}"
|
||||
|
||||
|
||||
class ReaderStreamTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if not shutil.which("g++") or not shutil.which("gcc"):
|
||||
raise unittest.SkipTest("native C/C++ compilers unavailable")
|
||||
cls.temporary = tempfile.TemporaryDirectory(prefix="mesh-reader-stream-")
|
||||
cls.directory = Path(cls.temporary.name)
|
||||
cls.source = cls.directory / "main.cpp"
|
||||
cls.decoder = cls.directory / "tinf.o"
|
||||
flags = ["-O1", "-g", "-fsanitize=address,undefined", "-fno-sanitize-recover=all",
|
||||
"-fno-omit-frame-pointer", "-fno-pie", "-I" + str(ROOT / "src"),
|
||||
"-DOTA_TRANSPORT_DEFLATE_TEST=1", "-DTINF_READER_STREAM_TEST=1"]
|
||||
subprocess.run(["gcc", "-std=c11", *flags, "-c", str(ROOT / "src/helpers/ota/OtaTinf.c"),
|
||||
"-o", str(cls.decoder)], check=True, capture_output=True)
|
||||
cls.flags = flags
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.temporary.cleanup()
|
||||
|
||||
def compile(self, body, name="test"):
|
||||
source = self.directory / (name + ".cpp")
|
||||
source.write_text(body, encoding="ascii")
|
||||
binary = self.directory / name
|
||||
result = subprocess.run(["g++", "-std=c++17", *self.flags, "-no-pie", str(source),
|
||||
str(self.decoder), "-o", str(binary)], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
return binary
|
||||
|
||||
def run_binary(self, binary, *args):
|
||||
result = subprocess.run([str(binary), *args], capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout.decode(errors="replace") + result.stderr.decode(errors="replace"))
|
||||
return result.stdout
|
||||
|
||||
def test_canonical_stream_header_and_token_vocabulary_are_reproducible(self):
|
||||
import sys
|
||||
path = str(ROOT / "tools/bible")
|
||||
sys.path.insert(0, path)
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location("reader_stream_repro_packer", ROOT / "tools/bible/pack_reader_stream.py")
|
||||
packer = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(packer)
|
||||
document = json.loads(packer.blocks.SOURCE.read_text(encoding="utf-8"))
|
||||
self.assertEqual(packer.HEADER.read_text(encoding="ascii"), packer.render(document))
|
||||
pinned = json.loads(packer.TOKENS.read_text(encoding="ascii"))
|
||||
self.assertLessEqual(len(pinned), 128)
|
||||
self.assertEqual(len(pinned), len(set(pinned)))
|
||||
for word in pinned:
|
||||
self.assertTrue(word)
|
||||
self.assertTrue(all(32 <= byte < 127 for byte in word.encode("ascii")))
|
||||
finally:
|
||||
sys.path.remove(path)
|
||||
|
||||
def test_all_879_verses_match_independently_normalized_source(self):
|
||||
binary = self.compile(r"""
|
||||
#include <helpers/bible/ReaderStreamData.generated.h>
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
int main() {
|
||||
using namespace mesh::bible;
|
||||
struct { unsigned char before[32]; char scratch[kBlockSize]; unsigned char after[32]; } buffer;
|
||||
memset(&buffer, 0xa5, sizeof(buffer));
|
||||
for (unsigned chapter=1; chapter<=21; ++chapter) {
|
||||
for (unsigned verse=1; verse<=kChapterVerses[chapter-1]; ++verse) {
|
||||
const char* text=nullptr;
|
||||
assert(lookup(generated::readerCorpus, Reference{uint8_t(chapter),uint8_t(verse)},
|
||||
buffer.scratch,sizeof(buffer.scratch),text)==LookupResult::Found);
|
||||
assert(text>=buffer.scratch && text<buffer.scratch+sizeof(buffer.scratch));
|
||||
assert(memchr(text,0,buffer.scratch+sizeof(buffer.scratch)-text));
|
||||
for(auto c:buffer.before) assert(c==0xa5);
|
||||
for(auto c:buffer.after) assert(c==0xa5);
|
||||
fwrite(text,1,strlen(text)+1,stdout);
|
||||
}
|
||||
}
|
||||
}
|
||||
""", "corpus")
|
||||
document = json.loads((ROOT / "tools/bible/reader-web.json").read_text())
|
||||
typography = str.maketrans({"\u00a0": " ", "\u2013": "-", "\u2014": "-",
|
||||
"\u2018": "'", "\u2019": "'", "\u201c": '\"', "\u201d": '\"'})
|
||||
expected = b"".join(text.translate(typography).encode("ascii") + b"\0"
|
||||
for text in document["verses"].values())
|
||||
self.assertEqual(self.run_binary(binary), expected)
|
||||
|
||||
def test_ring_bounds_truncation_distances_and_deterministic_mutations(self):
|
||||
cases = []
|
||||
|
||||
def good(plain, record, expected, compressor=raw_deflate):
|
||||
packed = compressor(plain)
|
||||
cases.append((packed, len(plain), record, 0, expected))
|
||||
return packed
|
||||
|
||||
for compressor in (raw_deflate, stored,
|
||||
lambda plain: raw_deflate(plain, strategy=zlib.Z_FIXED)):
|
||||
good(b"hello\0world\0", 1, b"world", compressor)
|
||||
good(b"p" * 4090 + b"\0" + b"crossing-boundary-record\0", 1,
|
||||
b"crossing-boundary-record", compressor)
|
||||
good(b"q" * 4095 + b"\0", 0, b"q" * 4095, compressor)
|
||||
good(b"\0missing\0", 0, b"", compressor)
|
||||
good(b"a\0" * 3000 + b"last record\0", 3000, b"last record")
|
||||
prefix = b"abc\0" * 1024
|
||||
packed = stored(prefix, False) + back_reference(4096)
|
||||
self.assertEqual(zlib.decompress(packed, -15), prefix + b"abc\0")
|
||||
cases.append((packed, len(prefix) + 4, 1024, 0, b"abc"))
|
||||
prefix = b"a\0" * 2049
|
||||
packed = stored(prefix, False) + back_reference(4097)
|
||||
self.assertEqual(zlib.decompress(packed, -15), prefix + b"\0a\0\0")
|
||||
cases.append((packed, len(prefix) + 4, 2049, -1, b""))
|
||||
for bad in (b"\x07", b"\x01\x01\x00\x00\x00x", b"\x05\x00\x00"):
|
||||
cases.append((bad, 4096, 0, -1, b""))
|
||||
packed = raw_deflate(b"a\0second\0")
|
||||
cases.append((packed, 8, 1, -1, b"")) # terminator exceeds total-output limit
|
||||
cases.append((packed, 20, 2, -1, b"")) # selected record absent
|
||||
cases.append((raw_deflate(b"q" * 4096 + b"\0"), 5000, 0, -1, b""))
|
||||
for size in range(len(packed)):
|
||||
cases.append((packed[:size], 20, 2, -1, b""))
|
||||
definitions, calls = [], []
|
||||
for index, (packed, limit, record, status, expected) in enumerate(cases):
|
||||
definitions.append(f"const unsigned char p{index}[]={array(packed or b'x')};")
|
||||
definitions.append(f"const unsigned char e{index}[]={array(expected + bytes([0]))};")
|
||||
calls.append(f"check(p{index},{len(packed)},{limit},{record},{status},e{index},{len(expected)});")
|
||||
body = r"""
|
||||
#include <helpers/ota/tinf/tinf.h>
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
struct Guard { unsigned char before[32]; unsigned char window[4096]; unsigned char after[32]; };
|
||||
void check(const unsigned char* source,unsigned size,unsigned limit,unsigned record,int expected,
|
||||
const unsigned char* text,unsigned length) {
|
||||
Guard buffer; memset(&buffer,0xa5,sizeof(buffer)); unsigned actual=777;
|
||||
int result=tinf_uncompress_record(buffer.window,4096,&actual,source,size,limit,record);
|
||||
if(expected==0) { assert(result==TINF_OK);assert(actual==length);assert(!memcmp(buffer.window,text,length+1)); }
|
||||
else assert(result!=TINF_OK);
|
||||
for(auto c:buffer.before) assert(c==0xa5);
|
||||
for(auto c:buffer.after) assert(c==0xa5);
|
||||
}
|
||||
""" + "\n".join(definitions) + r"""
|
||||
int main() {
|
||||
""" + "\n".join(calls) + r"""
|
||||
Guard buffer; memset(&buffer,0xa5,sizeof(buffer)); unsigned length=777;
|
||||
const unsigned char sample[]={3,0};
|
||||
assert(tinf_uncompress_record(nullptr,4096,&length,sample,2,4096,0)!=TINF_OK);
|
||||
assert(tinf_uncompress_record(buffer.window,2048,&length,sample,2,4096,0)!=TINF_OK);
|
||||
assert(tinf_uncompress_record(buffer.window,4096,nullptr,sample,2,4096,0)!=TINF_OK);
|
||||
assert(tinf_uncompress_record(buffer.window,4096,&length,nullptr,2,4096,0)!=TINF_OK);
|
||||
assert(tinf_uncompress_record(buffer.window,4096,&length,sample,2,0,0)!=TINF_OK);
|
||||
uint32_t seed=0x84a123f1; unsigned char input[512];
|
||||
for(unsigned pass=0;pass<10000;++pass) {
|
||||
auto next=[&]() { seed^=seed<<13;seed^=seed>>17;seed^=seed<<5;return seed; };
|
||||
const unsigned size=next()%sizeof(input);
|
||||
for(unsigned i=0;i<size;++i) input[i]=next();
|
||||
length=777;
|
||||
int result=tinf_uncompress_record(buffer.window,4096,&length,input,size,16384,next()%12);
|
||||
if(result==TINF_OK) { assert(length<4096);assert(buffer.window[length]==0); }
|
||||
for(auto c:buffer.before) assert(c==0xa5);
|
||||
for(auto c:buffer.after) assert(c==0xa5);
|
||||
}
|
||||
}
|
||||
"""
|
||||
self.run_binary(self.compile(body, "malformed"))
|
||||
|
||||
def test_literal_capacity_and_lookup_rejects_invalid_metadata(self):
|
||||
# Generated input keeps every reference and the original 4095-byte
|
||||
# literal capacity, including corpora with no profitable dictionary.
|
||||
import sys
|
||||
path = str(ROOT / "tools/bible")
|
||||
sys.path.insert(0, path)
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location("reader_stream_fixture_packer", ROOT / "tools/bible/pack_reader_stream.py")
|
||||
packer = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(packer)
|
||||
document = json.loads(packer.blocks.SOURCE.read_text())
|
||||
document["verses"] = dict.fromkeys(packer.blocks.references(), None)
|
||||
document["verses"]["1:1"] = "q" * 4095
|
||||
rendered = packer.render(document)
|
||||
finally:
|
||||
sys.path.remove(path)
|
||||
header = self.directory / "literal.h"
|
||||
header.write_text(rendered.replace('#include "ReaderStreamLookup.h"', '#include <helpers/bible/ReaderStreamLookup.h>'), encoding="ascii")
|
||||
binary = self.compile(r"""
|
||||
#include "literal.h"
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
int main() {
|
||||
using namespace mesh::bible;
|
||||
char scratch[kBlockSize];const char* text=nullptr;
|
||||
const auto& c=generated::readerCorpus;
|
||||
assert(lookup(c,{1,1},scratch,sizeof(scratch),text)==LookupResult::Found);
|
||||
assert(strlen(text)==4095);for(unsigned n=0;n<4095;++n) assert(text[n]=='q');
|
||||
assert(lookup(c,{1,2},scratch,sizeof(scratch),text)==LookupResult::Missing);assert(!text);
|
||||
assert(lookup(c,{0,1},scratch,sizeof(scratch),text)==LookupResult::Invalid);assert(!text);
|
||||
assert(lookup(c,{1,1},scratch,sizeof(scratch)-1,text)==LookupResult::Corrupt);assert(!text);
|
||||
assert(lookup(c,{1,1},nullptr,sizeof(scratch),text)==LookupResult::Corrupt);assert(!text);
|
||||
auto bad=c;bad.data=nullptr;assert(lookup(bad,{1,1},scratch,sizeof(scratch),text)==LookupResult::Corrupt);
|
||||
bad=c;bad.data_size=1;assert(lookup(bad,{1,1},scratch,sizeof(scratch),text)==LookupResult::Corrupt);
|
||||
bad=c;bad.encoded_size=1;assert(lookup(bad,{1,1},scratch,sizeof(scratch),text)==LookupResult::Corrupt);
|
||||
bad=c;--bad.verse_count;assert(lookup(bad,{1,1},scratch,sizeof(scratch),text)==LookupResult::Corrupt);
|
||||
}
|
||||
""", "literal")
|
||||
self.run_binary(binary)
|
||||
|
||||
def test_independent_stream_header_bounds_and_boundary_records(self):
|
||||
binary = self.compile(r"""
|
||||
#include <helpers/bible/ReaderStreamData.generated.h>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
int main() {
|
||||
using namespace mesh::bible;
|
||||
const auto& original=generated::readerCorpus;
|
||||
assert(original.chunk_count==3);
|
||||
struct { unsigned char before[32];char scratch[kBlockSize];unsigned char after[32]; } buffer;
|
||||
auto check=[&](const StreamTokenCorpus& corpus) {
|
||||
memset(&buffer,0xa5,sizeof(buffer));const char* text=nullptr;
|
||||
assert(lookup(corpus,{1,1},buffer.scratch,sizeof(buffer.scratch),text)==LookupResult::Corrupt);
|
||||
assert(!text);
|
||||
for(auto byte:buffer.before) assert(byte==0xa5);
|
||||
for(auto byte:buffer.after) assert(byte==0xa5);
|
||||
};
|
||||
auto bad=original;bad.chunk_count=4;check(bad);
|
||||
bad=original;bad.chunk_count=kVerseCount+1;check(bad);
|
||||
bad=original;bad.data_size=5;check(bad);
|
||||
bad=original;--bad.data_size;check(bad);
|
||||
bad=original;++bad.encoded_size;check(bad);
|
||||
std::vector<uint8_t> bytes(original.data,original.data+original.data_size);
|
||||
const size_t second=6+bytes[4]+(unsigned(bytes[5])<<8);
|
||||
for(auto field: {size_t(0),size_t(2),size_t(4),second,second+2,second+4}) {
|
||||
bytes.assign(original.data,original.data+original.data_size);
|
||||
bytes[field]=bytes[field+1]=0;
|
||||
if(field==0) bytes[0]=1; // First record must start at verse zero.
|
||||
bad=original;bad.data=bytes.data();check(bad);
|
||||
}
|
||||
bytes.assign(original.data,original.data+original.data_size);
|
||||
bytes[4]=bytes[5]=0xff;bad=original;bad.data=bytes.data();check(bad);
|
||||
bytes.assign(original.data,original.data+original.data_size);
|
||||
bytes.push_back(0);bad=original;bad.data=bytes.data();++bad.data_size;check(bad);
|
||||
// Independently inspect all stream boundaries and byte bounds. The complete
|
||||
// canonical comparison also checks every record immediately around them.
|
||||
unsigned offset=0,total=0,first=0;
|
||||
for(unsigned n=0;n<original.chunk_count;++n) {
|
||||
const auto* p=original.data+offset;
|
||||
unsigned current=p[0]+(unsigned(p[1])<<8),plain=p[2]+(unsigned(p[3])<<8);
|
||||
unsigned packed=p[4]+(unsigned(p[5])<<8);
|
||||
assert((n ? current>first : current==0) && plain<=17000 && packed>0);
|
||||
first=current;offset+=6+packed;total+=plain;
|
||||
}
|
||||
assert(offset==original.data_size && total==original.encoded_size);
|
||||
}
|
||||
""", "chunks")
|
||||
self.run_binary(binary)
|
||||
|
||||
def test_dictionary_corruption_tokens_and_workspace_are_bounded(self):
|
||||
cases = []
|
||||
|
||||
def fixture(encoded=b"\x80 suffix", words=b"Hello\0world\0", count=2,
|
||||
*, plain_size=None, packed_words=None, expected=3, output=b""):
|
||||
plain=encoded+b"\0"+bytes(878)
|
||||
cases.append((raw_deflate(plain),len(plain),
|
||||
raw_deflate(words) if packed_words is None else packed_words,
|
||||
len(words) if plain_size is None else plain_size,count,expected,output))
|
||||
|
||||
fixture(expected=0,output=b"Hello suffix")
|
||||
fixture(encoded=b"\x81",expected=0,output=b"world")
|
||||
fixture(encoded=b"\x82") # token outside the declared vocabulary
|
||||
fixture(encoded=b"literal\x1f")
|
||||
fixture(encoded=b"literal\x7f")
|
||||
fixture(count=0)
|
||||
fixture(count=129)
|
||||
fixture(words=b"Hello\0\0")
|
||||
fixture(words=b"Hello\0wo\x7frld\0")
|
||||
fixture(words=b"Hello\0wo\x80rld\0")
|
||||
fixture(words=b"Hello\0world")
|
||||
fixture(words=b"Hello\0world\0extra\0")
|
||||
fixture(plain_size=1)
|
||||
fixture(plain_size=4096)
|
||||
fixture(plain_size=4097)
|
||||
fixture(packed_words=raw_deflate(b"Hello\0world\0")[:-1])
|
||||
fixture(packed_words=raw_deflate(b"Hello\0world\0")+b"x")
|
||||
fixture(packed_words=b"")
|
||||
fixture(encoded=b"\x80"*100,words=b"h"*64+b"\0",count=1)
|
||||
fixture(encoded=b"\x80"*4095,words=b"Hello\0",count=1)
|
||||
definitions,calls=[],[]
|
||||
for n,(data,size,words,word_plain,count,expected,output) in enumerate(cases):
|
||||
definitions.extend((f"const unsigned char p{n}[]={array(data)};",
|
||||
f"const unsigned char w{n}[]={array(words or b'x')};",
|
||||
f"const unsigned char e{n}[]={array(output+bytes([0]))};"))
|
||||
calls.append(f"check(p{n},sizeof(p{n}),{size},w{n},{len(words)},{word_plain},{count},{expected},e{n});")
|
||||
body=r"""
|
||||
#include <helpers/bible/ReaderStreamLookup.h>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
void check(const uint8_t* data,unsigned data_size,unsigned plain_size,const uint8_t* words,
|
||||
unsigned words_size,unsigned word_plain,unsigned count,unsigned expected,const unsigned char* output) {
|
||||
using namespace mesh::bible;
|
||||
StreamTokenCorpus c={"fixture","test",data,data_size,plain_size,words,
|
||||
uint16_t(words_size),uint16_t(word_plain),uint16_t(count),kVerseCount};
|
||||
struct { unsigned char before[32];char scratch[kBlockSize];unsigned char after[32]; } buffer;
|
||||
memset(&buffer,0xa5,sizeof(buffer));const char* text=nullptr;
|
||||
auto result=lookup(c,{1,1},buffer.scratch,sizeof(buffer.scratch),text);
|
||||
assert(unsigned(result)==expected);
|
||||
if(result==LookupResult::Found) assert(text && !strcmp(text,reinterpret_cast<const char*>(output)));
|
||||
else assert(!text);
|
||||
for(auto byte:buffer.before) assert(byte==0xa5);
|
||||
for(auto byte:buffer.after) assert(byte==0xa5);
|
||||
}
|
||||
"""+"\n".join(definitions)+"\nint main() {\n"+"\n".join(calls)+"\n}\n"
|
||||
self.run_binary(self.compile(body,"dictionary"))
|
||||
|
||||
def test_worst_case_lookup_host_benchmark(self):
|
||||
# Keep timings informational: hosts vary, but report the CPU tradeoff
|
||||
# against the unchanged block decoder using identical host options.
|
||||
binary = self.compile(r"""
|
||||
#include <helpers/bible/ReaderStreamData.generated.h>
|
||||
#define generated old_generated
|
||||
#include <helpers/bible/ReaderData.generated.h>
|
||||
#undef generated
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
template<class Corpus> double bench(const Corpus& corpus) {
|
||||
using namespace mesh::bible;
|
||||
char scratch[kBlockSize];const char* text=nullptr;
|
||||
volatile unsigned sum=0;
|
||||
auto start=std::chrono::steady_clock::now();
|
||||
for(unsigned n=0;n<80;++n) {
|
||||
assert(lookup(corpus,{21,25},scratch,sizeof(scratch),text)==LookupResult::Found);
|
||||
sum+=strlen(text);
|
||||
}
|
||||
assert(sum>0);
|
||||
return std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-start).count()/80;
|
||||
}
|
||||
int main() { printf("Reader last verse host ms: block=%.4f stream=%.4f\n",
|
||||
bench(mesh::bible::old_generated::readerCorpus),bench(mesh::bible::generated::readerCorpus)); }
|
||||
""", "benchmark")
|
||||
print(self.run_binary(binary).decode().strip())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prove compact nRF glyph metrics retain every original field and pixel."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
FONT_FILES=("Pixel5FontData.h","Squeezed6FontData.h")
|
||||
|
||||
HARNESS=r'''
|
||||
#include <helpers/ui/Pixel5FontData.h>
|
||||
#include <helpers/ui/Squeezed6FontData.h>
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#if defined(NRF52_PLATFORM)
|
||||
static_assert(sizeof(mesh::ui::SmallFontGlyph)==3,"Cortex-M4 glyph packing");
|
||||
#else
|
||||
static_assert(sizeof(mesh::ui::SmallFontGlyph)==8,"Existing non-nRF glyph ABI");
|
||||
#endif
|
||||
void show(const mesh::ui::SmallFontGlyph* glyphs,const uint8_t* bitmap) {
|
||||
for(unsigned n=0;n<95;++n) {
|
||||
const auto& g=glyphs[n];
|
||||
printf("%u,%u,%u,%u,%d,%d:",unsigned(g.bitmap_offset),unsigned(g.width),
|
||||
unsigned(g.height),unsigned(g.advance),int(g.x_offset),int(g.y_offset));
|
||||
for(unsigned row=0;row<g.height;++row) {
|
||||
for(unsigned col=0;col<g.width;++col) {
|
||||
const unsigned bit=row*g.width+col;
|
||||
putchar(bitmap[g.bitmap_offset+bit/8]&(0x80>>(bit%8))?'1':'0');
|
||||
}
|
||||
}
|
||||
putchar('\n');
|
||||
}
|
||||
}
|
||||
int main() {
|
||||
show(mesh::ui::pixel5Glyphs,mesh::ui::pixel5Bitmaps);
|
||||
show(mesh::ui::squeezed6Glyphs,mesh::ui::squeezed6Bitmaps);
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class SmallFontMetricsTest(unittest.TestCase):
|
||||
def source_metrics(self):
|
||||
result=[]
|
||||
for filename in FONT_FILES:
|
||||
source=(ROOT/"src/helpers/ui"/filename).read_text()
|
||||
rows=[tuple(map(int,row.split(",")))
|
||||
for row in re.findall(r"\{([\d, \-]+)\}",source)]
|
||||
self.assertEqual(len(rows),95)
|
||||
for offset,width,height,advance,x,y in rows:
|
||||
self.assertLessEqual(offset,255)
|
||||
self.assertTrue(0<=width<=7 and 0<=height<=7 and 0<=advance<=7)
|
||||
self.assertTrue(-4<=x<=3 and -8<=y<=7)
|
||||
result+=rows
|
||||
return result
|
||||
|
||||
def test_all_190_metrics_and_pixels_match_original_layout(self):
|
||||
expected=self.source_metrics()
|
||||
with tempfile.TemporaryDirectory(prefix="mesh-small-font-") as folder:
|
||||
folder=Path(folder);source=folder/"main.cpp";source.write_text(HARNESS)
|
||||
output=[]
|
||||
for nrf in (False,True):
|
||||
binary=folder/("nrf" if nrf else "original")
|
||||
result=subprocess.run(["g++","-std=c++11","-O1","-g","-Wall","-Wextra",
|
||||
"-Werror=overflow","-Werror=conversion","-fsanitize=address,undefined",
|
||||
"-fno-sanitize-recover=all","-fno-pie","-no-pie","-I"+str(ROOT/"src"),
|
||||
*(["-DNRF52_PLATFORM=1"] if nrf else []),str(source),"-o",str(binary)],capture_output=True,text=True)
|
||||
self.assertEqual(result.returncode,0,result.stdout+result.stderr)
|
||||
run=subprocess.run([str(binary)],capture_output=True,text=True)
|
||||
self.assertEqual(run.returncode,0,run.stdout+run.stderr)
|
||||
output.append(run.stdout)
|
||||
actual=[tuple(map(int,row.split(":")[0].split(","))) for row in run.stdout.splitlines()]
|
||||
self.assertEqual(actual,expected)
|
||||
self.assertEqual(output[0],output[1])
|
||||
|
||||
def test_actual_cortex_m4_layout_and_flash_saving(self):
|
||||
compiler=shutil.which("arm-none-eabi-g++")
|
||||
if not compiler:
|
||||
path=Path.home()/".platformio/packages/toolchain-gccarmnoneeabi/bin/arm-none-eabi-g++"
|
||||
if path.is_file():compiler=str(path)
|
||||
if not compiler:self.skipTest("Cortex-M4 compiler unavailable")
|
||||
compiler=Path(compiler)
|
||||
nm=compiler.with_name("arm-none-eabi-nm")
|
||||
self.source_metrics()
|
||||
with tempfile.TemporaryDirectory(prefix="mesh-small-font-arm-") as folder:
|
||||
folder=Path(folder);source=folder/"main.cpp"
|
||||
source.write_text('#include <helpers/ui/Pixel5FontData.h>\n#include <helpers/ui/Squeezed6FontData.h>\n'
|
||||
'extern "C" const void* keep(unsigned n) { return n?mesh::ui::pixel5Glyphs:mesh::ui::squeezed6Glyphs; }\n')
|
||||
sizes=[]
|
||||
for nrf in (False,True):
|
||||
obj=folder/("nrf.o" if nrf else "original.o")
|
||||
result=subprocess.run([str(compiler),"-std=gnu++11","-mcpu=cortex-m4","-mthumb","-Oz",
|
||||
"-fno-exceptions","-fno-rtti","-Werror=overflow","-Werror=conversion",
|
||||
"-I"+str(ROOT/"src"),*(["-DNRF52_PLATFORM=1"] if nrf else []),
|
||||
"-c",str(source),"-o",str(obj)],capture_output=True,text=True)
|
||||
self.assertEqual(result.returncode,0,result.stdout+result.stderr)
|
||||
symbols=subprocess.check_output([str(nm),"-S",str(obj)],text=True)
|
||||
rows=[int(line.split()[1],16) for line in symbols.splitlines()
|
||||
if "pixel5Glyphs" in line or "squeezed6Glyphs" in line]
|
||||
self.assertEqual(sorted(rows),[95*(3 if nrf else 8)]*2)
|
||||
sizes.append(sum(rows))
|
||||
self.assertEqual(sizes[0]-sizes[1],950)
|
||||
|
||||
|
||||
if __name__=="__main__":unittest.main()
|
||||
Reference in new issue
Block a user