From 84e5611da03a2ec539cfbac90900d2c4489510e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Ebeling?= Date: Fri, 13 Nov 2026 22:13:23 +0100 Subject: [PATCH 01/28] feat(buffer): add a static buffer pool for large RPC returns Array RPC returns are placed on the service thread stack by the generated dispatcher (`uint8_t rpc_ret_buf[256]`), so every service pays permanent stack for a rare transfer, and the declared size is bounded by the stack instead of the wire (a return may be 1448 bytes). Add a buffer pool that all services share: fixed size blocks, move-only RAII leases, non-blocking acquire (BUSY instead of waiting). The bookkeeping is a lock free bitmask, so no port has to provide a try-lock and the firmware side of libxbot-service stays allocation free. A platform can bring its own storage via initialize() and set XBOT_BUFFER_DEFAULT_POOL=0, e.g. to place the pool in an otherwise unused RAM section. Defaults (1536 x 2) are asserted against max_packet_size. test(buffer): cover acquire, release, exhaustion, timeout-free BUSY, oversized requests and re-initialisation docs: describe the lease contract, the lock order and the sizing --- Readme.md | 77 ++++++-- include/xbot/config.hpp | 32 ++++ libxbot-service/CMakeLists.txt | 1 + .../include/xbot-service/Buffer.hpp | 108 +++++++++++ libxbot-service/src/Buffer.cpp | 168 ++++++++++++++++++ .../test/BufferTests/BufferTests.cpp | 117 ++++++++++++ libxbot-service/test/CMakeLists.txt | 3 + libxbot-service/test/all_tests.cpp | 1 + 8 files changed, 494 insertions(+), 13 deletions(-) create mode 100644 libxbot-service/include/xbot-service/Buffer.hpp create mode 100644 libxbot-service/src/Buffer.cpp create mode 100644 libxbot-service/test/BufferTests/BufferTests.cpp diff --git a/Readme.md b/Readme.md index 7413e42..1bb2185 100644 --- a/Readme.md +++ b/Readme.md @@ -96,19 +96,19 @@ message-specific payload. ### Message Types -| Value | Name | arg1 | arg2 | Payload | -| ------ | --------------------- | --------------------------- | ----------- | --------------------------------------- | -| `0x00` | UNKNOWN | — | — | — | -| `0x01` | DATA | — | `target_id` | Raw value bytes | -| `0x02` | CONFIGURATION_REQUEST | — | — | Empty | -| `0x03` | CLAIM | `0`=request, `1`=ack | — | `ClaimPayload` (request) or empty (ack) | -| `0x04` | HEARTBEAT | — | — | Empty | -| `0x05` | TRANSACTION | `0`=data, `1`=configuration | — | Sequence of `DataDescriptor`+payload | -| `0x7F` | LOG | log level (1–7) | — | UTF-8 string (max 255 bytes) | -| `0x80` | SERVICE_ADVERTISEMENT | — | — | CBOR-encoded service JSON | -| `0x81` | SERVICE_QUERY | — | — | — | -| `0x82` | DESCRIPTION_REQUEST | offset into the omitted desc | `max_size` | `DescriptionRequestPayload` (ip:port) | -| `0x83` | DESCRIPTION_PART | offset into the omitted desc | `total_size`| Window of the omitted description | +| Value | Name | arg1 | arg2 | Payload | +| ------ | --------------------- | ---------------------------- | ------------ | --------------------------------------- | +| `0x00` | UNKNOWN | — | — | — | +| `0x01` | DATA | — | `target_id` | Raw value bytes | +| `0x02` | CONFIGURATION_REQUEST | — | — | Empty | +| `0x03` | CLAIM | `0`=request, `1`=ack | — | `ClaimPayload` (request) or empty (ack) | +| `0x04` | HEARTBEAT | — | — | Empty | +| `0x05` | TRANSACTION | `0`=data, `1`=configuration | — | Sequence of `DataDescriptor`+payload | +| `0x7F` | LOG | log level (1–7) | — | UTF-8 string (max 255 bytes) | +| `0x80` | SERVICE_ADVERTISEMENT | — | — | CBOR-encoded service JSON | +| `0x81` | SERVICE_QUERY | — | — | — | +| `0x82` | DESCRIPTION_REQUEST | offset into the omitted desc | `max_size` | `DescriptionRequestPayload` (ip:port) | +| `0x83` | DESCRIPTION_PART | offset into the omitted desc | `total_size` | Window of the omitted description | `DESCRIPTION_REQUEST` is sent unicast by a host that needs the part of the schema the advertisement could not carry (see *Service description* below); the service answers with one @@ -275,6 +275,57 @@ Then inherit from the generated `MyServiceNameBase` or `MyInterfaceNameBase` cla --- +## Shared Buffer Pool + +An RPC return value is limited by `max_packet_size - sizeof(XbotHeader)` = 1448 bytes, but a service +thread stack is much smaller. Array return values above a small threshold therefore do not live on +the stack (that is what used to force the fixed size of a transfer type); the generated dispatcher +borrows a block from a pool that all services share: + +```cpp +#include + +auto lease = xbot::service::buffer::acquire(required_bytes); +if (!lease) { + SendRpcResponse(call_id, xbot::datatypes::RpcStatus::BUSY, nullptr, 0); + return; +} +fill(lease.data(), lease.size()); // lease.size() is the capacity, not the request +SendRpcResponse(call_id, xbot::datatypes::RpcStatus::SUCCESS, lease.data(), used_bytes); +``` + +Rules that keep the pool usable: + +- A lease is **move-only** and returns its block in the destructor. Do not keep it beyond the call + that borrowed it: the pool is shared by all services, and a lease held across a flash operation or + across RPCs starves the next caller. +- `acquire()` is **non-blocking** on purpose. A second large return while one is in flight gets an + empty lease and the service answers BUSY - an RPC handler must never wait for another service's + transfer. A block is only held while a return value is filled and copied into a packet. +- Release happens after the handler returned; `SendRpcResponse()` copies the payload into a packet. +- No heap is involved: the storage is static. + +Sizing is a platform decision. `xbot::config::buffer_block_size` (1536 by default, must hold one +packet payload - asserted at build time) and `buffer_block_count` (2) only size the framework +internal default storage. A platform that brings its own storage - e.g. a section in a RAM region +that is otherwise unused - calls + +```cpp +alignas(xbot::service::buffer::block_alignment) uint8_t storage[2 * 1536] + __attribute__((section(".sram4"))); +xbot::service::buffer::initialize(storage, 1536, 2); +``` + +once, before the services start, and sets `XBOT_BUFFER_DEFAULT_POOL=0` so the default array is not +linked in at all. `initialize()` is not thread safe and refuses to run while a lease is out. + +Parameters hit the same stack limit from the other direction: a fixed `type[N]` parameter is copied +into a stack array by the generated dispatcher, which is why a variable length payload (a file chunk) +had to be declared as e.g. `uint8_t[256]`. `blob` parameters - passed as pointer and length into the +received packet, the contract `handleData()` and `setRegister()` already use - remove that limit. + +--- + ## Python Interface `xbot_service_interface_py` is a pure-Python client for xBot services — no codegen step required. It talks directly diff --git a/include/xbot/config.hpp b/include/xbot/config.hpp index ef8d5ac..b987ce6 100644 --- a/include/xbot/config.hpp +++ b/include/xbot/config.hpp @@ -69,6 +69,38 @@ static constexpr uint32_t heartbeat_jitter = 100'000; static_assert(max_log_length > 100); +/** + * Settings for the shared RPC buffer pool (see xbot-service/Buffer.hpp). + * + * XBOT_BUFFER_DEFAULT_POOL: 1 lets the framework allocate the pool storage + * itself (hosts, tests, examples). A platform that brings its own storage - + * e.g. a section in a RAM region that is otherwise unused - sets this to 0 and + * calls buffer::initialize() instead, so the static array is not linked in. + */ +#ifndef XBOT_BUFFER_BLOCK_SIZE +#define XBOT_BUFFER_BLOCK_SIZE 1536 +#endif +#ifndef XBOT_BUFFER_BLOCK_COUNT +#define XBOT_BUFFER_BLOCK_COUNT 2 +#endif +#ifndef XBOT_BUFFER_DEFAULT_POOL +#define XBOT_BUFFER_DEFAULT_POOL 1 +#endif + +/** + * Size of one block in the shared buffer pool. A return value travels in one + * packet, so a block has to hold max_packet_size - sizeof(XbotHeader) = 1448 + * bytes; 1536 leaves headroom (asserted in Buffer.cpp). + */ +static constexpr uint16_t buffer_block_size = XBOT_BUFFER_BLOCK_SIZE; +/** + * Number of blocks that can be out at the same time. A block is only held while + * an RPC fills and sends its return value, so this is about concurrency, not + * about the number of services: two blocks leave room for a slow transfer next + * to a quick one. + */ +static constexpr uint8_t buffer_block_count = XBOT_BUFFER_BLOCK_COUNT; + namespace service { static constexpr uint32_t io_thread_stack_size = 5000; } diff --git a/libxbot-service/CMakeLists.txt b/libxbot-service/CMakeLists.txt index ed204c4..f3d3db3 100644 --- a/libxbot-service/CMakeLists.txt +++ b/libxbot-service/CMakeLists.txt @@ -16,6 +16,7 @@ add_library(xbot-service STATIC src/Scheduler.cpp src/ServiceIo.cpp src/DataSource.cpp + src/Buffer.cpp ) target_compile_options(xbot-service PRIVATE -Wall -Wextra -Werror -Wno-volatile) diff --git a/libxbot-service/include/xbot-service/Buffer.hpp b/libxbot-service/include/xbot-service/Buffer.hpp new file mode 100644 index 0000000..c7f4dce --- /dev/null +++ b/libxbot-service/include/xbot-service/Buffer.hpp @@ -0,0 +1,108 @@ +// +// Shared buffer pool for RPC payloads. +// + +#ifndef XBOT_BUFFER_HPP +#define XBOT_BUFFER_HPP + +#include +#include + +namespace xbot::service::buffer { + +/** @brief Highest number of blocks the pool bitmap can hold. */ +static constexpr uint8_t max_block_count = 32; + +/** @brief Alignment of every block and of the storage passed to initialize(). */ +static constexpr size_t block_alignment = 8; + +/** @brief Index that marks "no block". */ +static constexpr uint8_t invalid_index = 0xFF; + +/** + * @brief A block borrowed from the shared buffer pool. + * + * A lease owns one block until it is released or destroyed. It is move-only, so + * a block can never be released twice and the destructor returns it to the pool. + * + * Do not keep a lease beyond the call that borrowed it. The pool is shared by + * all services: a lease that is held across a flash erase or across RPCs starves + * the next caller, which then has to answer BUSY. + */ +class Lease { + public: + Lease() = default; + Lease(const Lease &) = delete; + Lease &operator=(const Lease &) = delete; + Lease(Lease &&other) noexcept; + Lease &operator=(Lease &&other) noexcept; + ~Lease(); + + /** @brief Start of the block, nullptr for an empty lease. */ + uint8_t *data() const { + return data_; + } + + /** @brief Capacity of the block in bytes (block size, not the requested size). */ + size_t size() const { + return size_; + } + + /** @brief True if this lease owns a block. */ + explicit operator bool() const { + return data_ != nullptr; + } + + /** @brief Return the block to the pool. Idempotent. */ + void release(); + + private: + friend Lease acquire(size_t bytes); + Lease(uint8_t *data, size_t size, uint8_t index) : data_(data), size_(size), index_(index) { + } + + uint8_t *data_ = nullptr; + size_t size_ = 0; + uint8_t index_ = invalid_index; +}; + +/** + * @brief Register the storage of the pool. + * + * Call once, before the first acquire() and before the services start; it is not + * thread safe. A platform that brings its own storage (e.g. a section in RAM that + * is otherwise unused) calls this with that storage and sets + * XBOT_BUFFER_DEFAULT_POOL to 0, which removes the framework default array. + * + * @param storage start of the storage, block_alignment aligned + * @param block_size bytes per block, must hold the largest RPC return value + * @param block_count number of blocks, 1..max_block_count + * @return false if an argument is unusable or a lease is still out + */ +bool initialize(void *storage, size_t block_size, size_t block_count); + +/** + * @brief Borrow a block that holds at least @p bytes. + * + * Deliberately non-blocking: an RPC handler must never wait for a slow transfer + * on another service, it answers BUSY instead. A timeout would not help either, + * because a block is only held while a return value is filled and copied into a + * packet, i.e. for microseconds, not for the duration of an upload. + * + * @return An empty lease if the request is larger than a block or every block is + * out. + */ +Lease acquire(size_t bytes); + +/** @brief Block size in bytes. */ +size_t blockSize(); + +/** @brief Number of blocks in the pool. */ +size_t blockCount(); + +/** @brief Number of blocks that are currently free. */ +size_t available(); + +} // namespace xbot::service::buffer + +#endif // XBOT_BUFFER_HPP diff --git a/libxbot-service/src/Buffer.cpp b/libxbot-service/src/Buffer.cpp new file mode 100644 index 0000000..b9c42f1 --- /dev/null +++ b/libxbot-service/src/Buffer.cpp @@ -0,0 +1,168 @@ +// +// Shared buffer pool for RPC payloads. +// + +#include + +#include +#include +#include +#include +#include + +namespace { + +using xbot::service::buffer::invalid_index; +using xbot::service::buffer::Lease; + +// A return value has to fit into one packet, so a block never has to be larger +// than that. Keeping the invariant here catches a pool that was sized for +// something smaller. +static_assert(xbot::config::buffer_block_size >= xbot::config::max_packet_size - sizeof(xbot::datatypes::XbotHeader), + "buffer_block_size must hold the largest possible RPC return value"); +static_assert(xbot::config::buffer_block_count >= 1U, "the buffer pool needs at least one block"); +static_assert(xbot::config::buffer_block_count <= xbot::service::buffer::max_block_count, + "buffer_block_count exceeds the pool bitmap"); + +#if XBOT_BUFFER_DEFAULT_POOL +// Storage for platforms that do not bring their own (hosts, tests, examples). A +// firmware that places the pool in its own RAM section sets +// XBOT_BUFFER_DEFAULT_POOL to 0 and calls buffer::initialize() instead. +alignas(xbot::service::buffer::block_alignment) uint8_t + default_storage[xbot::config::buffer_block_count * xbot::config::buffer_block_size]{}; +#endif + +// Constant initialized on purpose: acquire() may run before a dynamic +// initializer had a chance to run (services start right after the IO thread). +#if XBOT_BUFFER_DEFAULT_POOL +uint8_t *storage_ = default_storage; +size_t block_size_ = xbot::config::buffer_block_size; +size_t block_count_ = xbot::config::buffer_block_count; +#else +uint8_t *storage_ = nullptr; +size_t block_size_ = 0; +size_t block_count_ = 0; +#endif + +// One bit per block, set while the block is out. The compare-and-swap loop keeps +// the pool lock free: no mutex means no priority inversion, and - more +// importantly - no port has to provide a try-lock, so every existing port keeps +// working unchanged. +std::atomic used_mask_{0}; + +// Guards the "not initialized" log line only, so a plain bool is enough: the +// worst case is a duplicated line. +bool warned_uninitialized_ = false; + +uint32_t blockBit(uint8_t index) { + return uint32_t{1} << index; +} + +} // namespace + +Lease::Lease(Lease &&other) noexcept : data_(other.data_), size_(other.size_), index_(other.index_) { + other.data_ = nullptr; + other.size_ = 0; + other.index_ = invalid_index; +} + +Lease &Lease::operator=(Lease &&other) noexcept { + if (this != &other) { + release(); + data_ = other.data_; + size_ = other.size_; + index_ = other.index_; + other.data_ = nullptr; + other.size_ = 0; + other.index_ = invalid_index; + } + return *this; +} + +Lease::~Lease() { + release(); +} + +void Lease::release() { + if (data_ == nullptr) { + return; + } + // Release: everything the handler wrote into the block is visible before the + // next owner reads it. + used_mask_.fetch_and(~blockBit(index_), std::memory_order_release); + data_ = nullptr; + size_ = 0; + index_ = invalid_index; +} + +bool xbot::service::buffer::initialize(void *storage, size_t block_size, size_t block_count) { + if (storage == nullptr || block_size == 0U || block_count == 0U) { + return false; + } + if (block_count > max_block_count) { + return false; + } + if ((reinterpret_cast(storage) % block_alignment) != 0U) { + return false; + } + if (used_mask_.load(std::memory_order_relaxed) != 0U) { + return false; // a lease is still out, keep the current storage alive + } + storage_ = static_cast(storage); + block_size_ = block_size; + block_count_ = block_count; + ULOG_INFO("Buffer pool: %u blocks of %u bytes", static_cast(block_count), + static_cast(block_size)); + return true; +} + +xbot::service::buffer::Lease xbot::service::buffer::acquire(size_t bytes) { + if (storage_ == nullptr) { + if (!warned_uninitialized_) { + warned_uninitialized_ = true; + ULOG_WARNING("Buffer pool is not initialized, call xbot::service::buffer::initialize()"); + } + return {}; + } + if (bytes > block_size_) { + return {}; + } + + uint32_t mask = used_mask_.load(std::memory_order_relaxed); + for (;;) { + uint8_t index = invalid_index; + for (uint8_t i = 0; i < block_count_; ++i) { + if ((mask & blockBit(i)) == 0U) { + index = i; + break; + } + } + if (index == invalid_index) { + return {}; // every block is out, the caller answers BUSY + } + if (used_mask_.compare_exchange_weak(mask, mask | blockBit(index), std::memory_order_acquire, + std::memory_order_relaxed)) { + return {storage_ + static_cast(index) * block_size_, block_size_, index}; + } + // compare_exchange_weak refreshed mask with the current value, try again + } +} + +size_t xbot::service::buffer::blockSize() { + return block_size_; +} + +size_t xbot::service::buffer::blockCount() { + return block_count_; +} + +size_t xbot::service::buffer::available() { + size_t used = 0; + const uint32_t mask = used_mask_.load(std::memory_order_relaxed); + for (uint8_t i = 0; i < block_count_; ++i) { + if ((mask & blockBit(i)) != 0U) { + ++used; + } + } + return block_count_ - used; +} diff --git a/libxbot-service/test/BufferTests/BufferTests.cpp b/libxbot-service/test/BufferTests/BufferTests.cpp new file mode 100644 index 0000000..f38a979 --- /dev/null +++ b/libxbot-service/test/BufferTests/BufferTests.cpp @@ -0,0 +1,117 @@ +// +// Tests for the shared RPC buffer pool. +// + +#include +#include + +#include "CppUTest/TestHarness.h" + +using namespace xbot::service; + +TEST_GROUP(BufferTests) { + // The tests bring their own storage, so they do not depend on (or disturb) + // the framework default pool. + alignas(buffer::block_alignment) uint8_t storage_[2 * 128]{}; + + static constexpr size_t kBlocks = 2; + static constexpr size_t kBlockSize = 128; + + void setup() override { + CHECK_TRUE(buffer::initialize(storage_, kBlockSize, kBlocks)); + CHECK_EQUAL(kBlocks, buffer::available()); + } +}; + +TEST(BufferTests, AcquireReturnsBlockCapacity) { + buffer::Lease lease = buffer::acquire(100); + CHECK_TRUE(lease); + CHECK_EQUAL(kBlockSize, lease.size()); + CHECK_TRUE(lease.data() == storage_); + CHECK_EQUAL(kBlocks - 1, buffer::available()); +} + +TEST(BufferTests, AcquireUsesDistinctBlocks) { + buffer::Lease first = buffer::acquire(10); + buffer::Lease second = buffer::acquire(10); + CHECK_TRUE(first); + CHECK_TRUE(second); + CHECK_TRUE(first.data() != second.data()); + CHECK_EQUAL(static_cast(0), buffer::available()); +} + +TEST(BufferTests, ExhaustedPoolReturnsEmptyLease) { + buffer::Lease first = buffer::acquire(10); + buffer::Lease second = buffer::acquire(10); + buffer::Lease third = buffer::acquire(10); + CHECK_TRUE(first); + CHECK_TRUE(second); + CHECK_FALSE(third); // the caller answers BUSY +} + +TEST(BufferTests, ReleaseReturnsBlock) { + { + buffer::Lease lease = buffer::acquire(10); + CHECK_TRUE(lease); + lease.release(); + CHECK_FALSE(lease); + CHECK_EQUAL(kBlocks, buffer::available()); + } + buffer::Lease again = buffer::acquire(10); + CHECK_TRUE(again); +} + +TEST(BufferTests, DestructorReleasesBlock) { + { + buffer::Lease lease = buffer::acquire(10); + CHECK_TRUE(lease); + } + CHECK_EQUAL(kBlocks, buffer::available()); +} + +TEST(BufferTests, OversizedRequestReturnsEmptyLease) { + CHECK_FALSE(buffer::acquire(kBlockSize + 1)); + CHECK_EQUAL(kBlocks, buffer::available()); +} + +TEST(BufferTests, MoveTransfersOwnership) { + buffer::Lease source = buffer::acquire(10); + CHECK_TRUE(source); + + buffer::Lease target = std::move(source); + CHECK_FALSE(source); + CHECK_TRUE(target); + CHECK_EQUAL(kBlocks - 1, buffer::available()); + + target = std::move(source); // move assign from an empty lease releases target + CHECK_FALSE(target); + CHECK_EQUAL(kBlocks, buffer::available()); +} + +TEST(BufferTests, ReleaseIsIdempotent) { + buffer::Lease lease = buffer::acquire(10); + lease.release(); + lease.release(); + CHECK_EQUAL(kBlocks, buffer::available()); +} + +TEST(BufferTests, InitializeRejectsBadArguments) { + CHECK_FALSE(buffer::initialize(nullptr, kBlockSize, kBlocks)); + CHECK_FALSE(buffer::initialize(storage_, 0, kBlocks)); + CHECK_FALSE(buffer::initialize(storage_, kBlockSize, 0)); + CHECK_FALSE(buffer::initialize(storage_, kBlockSize, buffer::max_block_count + 1)); + CHECK_FALSE(buffer::initialize(storage_ + 1, kBlockSize, kBlocks)); // unaligned +} + +TEST(BufferTests, InitializeRefusesWhileALeaseIsOut) { + buffer::Lease lease = buffer::acquire(10); + CHECK_TRUE(lease); + CHECK_FALSE(buffer::initialize(storage_, kBlockSize, kBlocks)); + lease.release(); + CHECK_TRUE(buffer::initialize(storage_, kBlockSize, kBlocks)); +} + +TEST(BufferTests, BlockSizeAndCountReportTheInitializedPool) { + CHECK_EQUAL(kBlockSize, buffer::blockSize()); + CHECK_EQUAL(kBlocks, buffer::blockCount()); +} diff --git a/libxbot-service/test/CMakeLists.txt b/libxbot-service/test/CMakeLists.txt index 3b45982..ece691a 100644 --- a/libxbot-service/test/CMakeLists.txt +++ b/libxbot-service/test/CMakeLists.txt @@ -2,6 +2,8 @@ add_executable(AllTests all_tests.cpp QueueTests/QueueTests.cpp + BufferTests/BufferTests.cpp + ${PROJECT_SOURCE_DIR}/src/Buffer.cpp ${PROJECT_SOURCE_DIR}/src/portable/linux/queue.cpp ) @@ -18,6 +20,7 @@ target_compile_options(AllTests target_link_libraries(AllTests PRIVATE CppUTest::CppUTestExt + ulog ) if(CPPUTEST_TEST_DISCOVERY OR NOT DEFINED CPPUTEST_TEST_DISCOVERY) diff --git a/libxbot-service/test/all_tests.cpp b/libxbot-service/test/all_tests.cpp index 225b300..64ceec4 100644 --- a/libxbot-service/test/all_tests.cpp +++ b/libxbot-service/test/all_tests.cpp @@ -4,6 +4,7 @@ #include "CppUTest/CommandLineTestRunner.h" IMPORT_TEST_GROUP(QueueTests); +IMPORT_TEST_GROUP(BufferTests); int main(int argc, char** argv) { return RUN_ALL_TESTS(argc, argv); From 2017388ceae9d124ab21206d3eea1a7bf6b428be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Ebeling?= Date: Fri, 13 Nov 2026 22:29:52 +0100 Subject: [PATCH 02/28] feat(schema): allow blob parameters and returns in RPC functions codegen/xbot_codegen/xbot_codegen.py feat(codegen): pass blob parameters into the packet and pool large returns codegen/templates/ServiceTemplate.{hpp,cpp} codegen/templates/service.json feat(codegen): support blob parameters and returns in the interface template codegen/templates/ServiceInterfaceTemplate.{hpp,cpp} feat(go): decode blob returns and reject payloads above the packet limit xbot_service_interface_go/codegen/emit.go xbot_service_interface_go/xbot/conn.go xbot_service_interface_go/codegen/generate_test.go xbot_service_interface_go/xbot/conn_test.go feat(py): handle blob returns and validate their size xbot_service_interface_py/xbot_service_interface/interface.py xbot_service_interface_py/tests/test_rpc.py docs: document blob parameters, the pooled returns and their lifetimes Readme.md --- Readme.md | 22 +++- .../templates/ServiceInterfaceTemplate.cpp | 47 +++++++- .../templates/ServiceInterfaceTemplate.hpp | 28 ++++- codegen/templates/ServiceTemplate.cpp | 103 +++++++++++++++++- codegen/templates/ServiceTemplate.hpp | 101 +++++++++++++---- codegen/templates/service.json | 14 +++ codegen/xbot_codegen/xbot_codegen.py | 64 ++++++++++- xbot_service_interface_go/codegen/emit.go | 3 + .../codegen/generate_test.go | 40 +++++++ xbot_service_interface_go/xbot/conn.go | 7 ++ xbot_service_interface_go/xbot/conn_test.go | 19 ++++ xbot_service_interface_py/tests/test_rpc.py | 26 ++++- .../xbot_service_interface/interface.py | 13 ++- 13 files changed, 441 insertions(+), 46 deletions(-) diff --git a/Readme.md b/Readme.md index 1bb2185..aff5034 100644 --- a/Readme.md +++ b/Readme.md @@ -245,7 +245,12 @@ Services are defined in a JSON file. The code generator (`codegen/`) reads this } ``` -**Valid types:** `char`, `uint8_t`, `uint16_t`, `uint32_t`, `uint64_t`, `int8_t`, `int16_t`, `int32_t`, `int64_t`, `float`, `double`, `blob` (registers only), or fixed-length arrays of any scalar type as `type[N]`. +**Valid types:** `char`, `uint8_t`, `uint16_t`, `uint32_t`, `uint64_t`, `int8_t`, `int16_t`, `int32_t`, `int64_t`, `float`, `double`, `blob` (registers, RPC parameters and RPC return values), or fixed-length arrays of any scalar type as `type[N]`. + +`blob` is variable length: as a parameter it is passed as `(pointer, length)` into the received packet and is +not copied, as a register it is the configuration blob, and as a return value it uses the shared buffer pool +(see [Shared Buffer Pool](#shared-buffer-pool)). A `type[N]` parameter or return above 128 bytes is pooled the +same way, so a service never reserves stack for a payload it rarely sends. **IDs** must be unique within each section (`inputs`, `outputs`, `registers`). @@ -256,6 +261,11 @@ Services are defined in a JSON file. The code generator (`codegen/`) reads this - `bool Send{Name}(const T& data)` — send an output (scalar types) - `bool OnRegister{Name}Changed(const void* data, size_t length)` — called when a register is set (blob registers) - Struct `{Name}` with `value`, `length` (arrays), and `valid` fields — for non-blob registers +- `void RPC{Name}(uint16_t call_id, ...)` — one pure virtual per function; a `blob` parameter arrives as + `const uint8_t* , uint32_t Len` and is only valid until the handler returns + (copy it if you need it longer) +- A `blob` or pooled array return appends `uint8_t* data, uint16_t* response_length`; `*response_length` is a + byte count for `blob` and an element count for `type[N]` **Generated API (interface side — same JSON, different template):** - Inputs and outputs swap roles: outputs become callbacks, inputs become send methods. @@ -319,10 +329,12 @@ xbot::service::buffer::initialize(storage, 1536, 2); once, before the services start, and sets `XBOT_BUFFER_DEFAULT_POOL=0` so the default array is not linked in at all. `initialize()` is not thread safe and refuses to run while a lease is out. -Parameters hit the same stack limit from the other direction: a fixed `type[N]` parameter is copied -into a stack array by the generated dispatcher, which is why a variable length payload (a file chunk) -had to be declared as e.g. `uint8_t[256]`. `blob` parameters - passed as pointer and length into the -received packet, the contract `handleData()` and `setRegister()` already use - remove that limit. +Parameters hit the same stack limit from the other direction: a fixed `type[N]` parameter is copied into a +stack array by the generated dispatcher, which is why a variable length payload had to be declared as +e.g. `uint8_t[256]`. A `blob` parameter is passed as `(pointer, length)` into the received packet instead - +the contract `handleData()` and `setRegister()` already use - so it costs no stack and no copy, and its +length is only bounded by one packet. The generated dispatcher takes returns above 128 bytes and blob +returns from the pool; small returns stay on the stack, so the pool is not touched in the hot path. --- diff --git a/codegen/templates/ServiceInterfaceTemplate.cpp b/codegen/templates/ServiceInterfaceTemplate.cpp index 44add45..d74e0fa 100644 --- a/codegen/templates/ServiceInterfaceTemplate.cpp +++ b/codegen/templates/ServiceInterfaceTemplate.cpp @@ -119,11 +119,15 @@ for func in service["functions"]: # Build method signature sig_params = [] for p in func["parameters"]: - if p['is_array']: + if p['is_blob']: + sig_params.append(f"const uint8_t* {p['name']}, uint32_t {p['name']}Len") + elif p['is_array']: sig_params.append(f"const {p['type']}* {p['name']}, uint32_t {p['name']}Len") else: sig_params.append(f"const {p['type']}& {p['name']}") - if func['return_is_array']: + if func['return_is_blob']: + sig_params.append("uint8_t* data, uint16_t& result_length") + elif func['return_is_array']: sig_params.append(f"{func['return_base_type']}* data, uint16_t& result_length") elif func["return_type"] != "void": sig_params.append(f"{func['return_type']}& result") @@ -135,9 +139,13 @@ for func in service["functions"]: if func["parameters"]: cog.outl(" std::vector params_buf;") for p in func["parameters"]: - if p['is_array']: + if p['is_blob'] or p['is_array']: + if p['is_blob']: + byte_len_expr = f"{p['name']}Len" + else: + byte_len_expr = f"{p['name']}Len * sizeof({p['type']})" cog.outl(f" {{") - cog.outl(f" const size_t byte_len = {p['name']}Len * sizeof({p['type']});") + cog.outl(f" const size_t byte_len = {byte_len_expr};") cog.outl(f" const size_t off = params_buf.size();") cog.outl(f" params_buf.resize(off + sizeof(xbot::datatypes::DataDescriptor) + byte_len);") cog.outl(f" auto* desc = reinterpret_cast(params_buf.data() + off);") @@ -158,7 +166,12 @@ for func in service["functions"]: params_call = "nullptr, 0" # Call SendRpc with appropriate response buffer - if func['return_is_array']: + if func['return_is_blob']: + cog.outl(f" size_t resp_size = result_length;") + cog.outl(f" const auto r = SendRpc({func['id']}, {params_call}, data, &resp_size, timeout_ms);") + cog.outl(f" if (r != RPC_OK) return false;") + cog.outl(f" result_length = static_cast(resp_size);") + elif func['return_is_array']: cog.outl(f" size_t resp_size = result_length * sizeof({func['return_base_type']});") cog.outl(f" const auto r = SendRpc({func['id']}, {params_call}, reinterpret_cast(data), &resp_size, timeout_ms);") cog.outl(f" if (r != RPC_OK) return false;") @@ -257,4 +270,28 @@ bool ServiceTemplateInterfaceBase::CallMixedParamsWithReturn(const char* Name, u result = resp_buf; return true; } +bool ServiceTemplateInterfaceBase::CallBlobParamsWithBlobReturn(const uint8_t* Data, uint32_t DataLen, uint8_t* data, uint16_t& result_length, uint32_t timeout_ms) { + std::vector params_buf; + { + const size_t byte_len = DataLen; + const size_t off = params_buf.size(); + params_buf.resize(off + sizeof(xbot::datatypes::DataDescriptor) + byte_len); + auto* desc = reinterpret_cast(params_buf.data() + off); + desc->target_id = 0; desc->reserved = 0; desc->payload_size = static_cast(byte_len); + if (byte_len > 0 && Data == nullptr) return false; + memcpy(params_buf.data() + off + sizeof(xbot::datatypes::DataDescriptor), Data, byte_len); + } + size_t resp_size = result_length; + const auto r = SendRpc(4, params_buf.data(), params_buf.size(), data, &resp_size, timeout_ms); + if (r != RPC_OK) return false; + result_length = static_cast(resp_size); + return true; +} +bool ServiceTemplateInterfaceBase::CallLargeArrayReturn(uint8_t* data, uint16_t& result_length, uint32_t timeout_ms) { + size_t resp_size = result_length * sizeof(uint8_t); + const auto r = SendRpc(5, nullptr, 0, reinterpret_cast(data), &resp_size, timeout_ms); + if (r != RPC_OK) return false; + result_length = static_cast(resp_size / sizeof(uint8_t)); + return true; +} //[[[end]]] diff --git a/codegen/templates/ServiceInterfaceTemplate.hpp b/codegen/templates/ServiceInterfaceTemplate.hpp index eff31bf..9810020 100644 --- a/codegen/templates/ServiceInterfaceTemplate.hpp +++ b/codegen/templates/ServiceInterfaceTemplate.hpp @@ -66,11 +66,15 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas for func in service["functions"]: params = [] for p in func["parameters"]: - if p['is_array']: + if p['is_blob']: + params.append(f"const uint8_t* {p['name']}, uint32_t {p['name']}Len") + elif p['is_array']: params.append(f"const {p['type']}* {p['name']}, uint32_t {p['name']}Len") else: params.append(f"const {p['type']}& {p['name']}") - if func['return_is_array']: + if func['return_is_blob']: + params.append("uint8_t* data, uint16_t& result_length") + elif func['return_is_array']: params.append(f"{func['return_base_type']}* data, uint16_t& result_length") elif func["return_type"] != "void": params.append(f"{func['return_type']}& result") @@ -82,6 +86,8 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas bool CallScalarParamsWithReturn(const float& Speed, const uint32_t& Count, const uint8_t& Enable, int32_t& result, uint32_t timeout_ms = 1000); bool CallArrayParamNoReturn(const char* Label, uint32_t LabelLen, uint32_t timeout_ms = 1000); bool CallMixedParamsWithReturn(const char* Name, uint32_t NameLen, const float& Value, uint8_t& result, uint32_t timeout_ms = 1000); + bool CallBlobParamsWithBlobReturn(const uint8_t* Data, uint32_t DataLen, uint8_t* data, uint16_t& result_length, uint32_t timeout_ms = 1000); + bool CallLargeArrayReturn(uint8_t* data, uint16_t& result_length, uint32_t timeout_ms = 1000); //[[[end]]] /*[[[cog @@ -234,6 +240,24 @@ cog.outl(f"\u002f*\n{service['service_json']}\n*\u002f") } ], "return_type": "uint8_t" + }, + { + "id": 4, + "name": "BlobParamsWithBlobReturn", + "parameters": [ + { + "id": 0, + "name": "Data", + "type": "blob" + } + ], + "return_type": "blob" + }, + { + "id": 5, + "name": "LargeArrayReturn", + "parameters": [], + "return_type": "uint8_t[256]" } ], "enums": [ diff --git a/codegen/templates/ServiceTemplate.cpp b/codegen/templates/ServiceTemplate.cpp index e17fec4..1aff6eb 100644 --- a/codegen/templates/ServiceTemplate.cpp +++ b/codegen/templates/ServiceTemplate.cpp @@ -3,14 +3,17 @@ /*[[[cog import cog -from xbot_codegen import toCamelCase, loadService +from xbot_codegen import MAX_RPC_RETURN_BYTES, loadService, needsBufferPool, pooledReturnBytes, toCamelCase service = loadService(service_file) cog.outl(f'#include "{service["class_name"]}.hpp"') +if needsBufferPool(service): + cog.outl('#include ') ]]]*/ #include "ServiceTemplateBase.hpp" +#include //[[[end]]] #include #include @@ -350,9 +353,14 @@ if service["functions"]: cog.outl(" switch (function_id) {") for func in service["functions"]: cog.outl(f" case {func['id']}: {{") - # Declare parameter variables + # Declare parameter variables. A blob parameter is not copied: the handler gets a + # pointer into the received packet (the contract handleData() and setRegister() + # already use), which stays valid until the handler returns. for p in func["parameters"]: - if p['is_array']: + if p['is_blob']: + cog.outl(f" const uint8_t* param_{p['name']} = nullptr;") + cog.outl(f" uint32_t param_{p['name']}Len = 0;") + elif p['is_array']: cog.outl(f" {p['type']} param_{p['name']}[{p['max_length']}] = {{}};") cog.outl(f" uint32_t param_{p['name']}Len = 0;") else: @@ -370,7 +378,11 @@ if service["functions"]: cog.outl(" switch (desc->target_id) {") for p in func["parameters"]: cog.outl(f" case {p['id']}:") - if p['is_array']: + if p['is_blob']: + cog.outl(f" param_{p['name']} = buf + offset;") + cog.outl(f" param_{p['name']}Len = desc->payload_size;") + cog.outl(f" params_received++;") + elif p['is_array']: cog.outl(f" if (desc->payload_size % sizeof({p['type']}) == 0 &&") cog.outl(f" desc->payload_size <= sizeof(param_{p['name']})) {{") cog.outl(f" memcpy(param_{p['name']}, buf + offset, desc->payload_size);") @@ -394,11 +406,37 @@ if service["functions"]: # Build call argument list — call_id first, then params, then return buffer for arrays call_args = ["call_id"] for p in func["parameters"]: - if p['is_array']: + if p['is_blob'] or p['is_array']: call_args.append(f"param_{p['name']}, param_{p['name']}Len") else: call_args.append(f"param_{p['name']}") - if func['return_is_array']: + # Return storage: small arrays stay on the stack, everything larger and blob + # returns come from the shared buffer pool. The lease is released when this case + # ends, so the handler has to call SendRpcResponse() before it returns. + pooled_bytes = pooledReturnBytes(service, func) + if func['return_is_blob']: + cog.outl(f" constexpr uint16_t kMaxRpcReturn = {MAX_RPC_RETURN_BYTES};") + cog.outl(" static_assert(kMaxRpcReturn <= xbot::config::buffer_block_size,") + cog.outl(' "blob return does not fit into a buffer pool block");') + cog.outl(" auto rpc_ret_lease = xbot::service::buffer::acquire(kMaxRpcReturn);") + cog.outl(" if (!rpc_ret_lease) {") + cog.outl(" SendRpcResponse(call_id, xbot::datatypes::RpcStatus::BUSY, nullptr, 0);") + cog.outl(" return;") + cog.outl(" }") + cog.outl(" uint16_t rpc_ret_len = kMaxRpcReturn;") + call_args.append("rpc_ret_lease.data(), &rpc_ret_len") + elif pooled_bytes is not None: + cog.outl(f" static_assert({pooled_bytes} <= xbot::config::buffer_block_size,") + cog.outl(' "return value does not fit into a buffer pool block");') + cog.outl(f" auto rpc_ret_lease = xbot::service::buffer::acquire({pooled_bytes});") + cog.outl(" if (!rpc_ret_lease) {") + cog.outl(" SendRpcResponse(call_id, xbot::datatypes::RpcStatus::BUSY, nullptr, 0);") + cog.outl(" return;") + cog.outl(" }") + cog.outl(f" auto* rpc_ret_buf = reinterpret_cast<{func['return_base_type']}*>(rpc_ret_lease.data());") + cog.outl(f" uint16_t rpc_ret_len = {func['return_max_length']};") + call_args.append("rpc_ret_buf, &rpc_ret_len") + elif func['return_is_array']: cog.outl(f" {func['return_base_type']} rpc_ret_buf[{func['return_max_length']}] = {{}};") cog.outl(f" uint16_t rpc_ret_len = {func['return_max_length']};") call_args.append("rpc_ret_buf, &rpc_ret_len") @@ -406,6 +444,8 @@ if service["functions"]: # Set max response size before dispatching to user code if func['return_type'] == 'void': cog.outl(f" rpc_max_response_size_ = 0;") + elif func['return_is_blob']: + cog.outl(f" rpc_max_response_size_ = kMaxRpcReturn;") elif func['return_is_array']: cog.outl(f" rpc_max_response_size_ = {func['return_max_length']} * sizeof({func['return_base_type']});") else: @@ -538,6 +578,57 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, RPCMixedParamsWithReturn(call_id, param_Name, param_NameLen, param_Value); return; } + case 4: { + const uint8_t* param_Data = nullptr; + uint32_t param_DataLen = 0; + size_t offset = 0; + bool parse_ok = true; + uint8_t params_received = 0; + while (offset + sizeof(xbot::datatypes::DataDescriptor) <= len) { + const auto* desc = reinterpret_cast(buf + offset); + offset += sizeof(xbot::datatypes::DataDescriptor); + if (offset + desc->payload_size > len) { parse_ok = false; break; } + switch (desc->target_id) { + case 0: + param_Data = buf + offset; + param_DataLen = desc->payload_size; + params_received++; + break; + default: break; + } + offset += desc->payload_size; + } + if (!parse_ok || params_received != 1) { + SendRpcResponse(call_id, xbot::datatypes::RpcStatus::ERROR, nullptr, 0); + return; + } + constexpr uint16_t kMaxRpcReturn = 1448; + static_assert(kMaxRpcReturn <= xbot::config::buffer_block_size, + "blob return does not fit into a buffer pool block"); + auto rpc_ret_lease = xbot::service::buffer::acquire(kMaxRpcReturn); + if (!rpc_ret_lease) { + SendRpcResponse(call_id, xbot::datatypes::RpcStatus::BUSY, nullptr, 0); + return; + } + uint16_t rpc_ret_len = kMaxRpcReturn; + rpc_max_response_size_ = kMaxRpcReturn; + RPCBlobParamsWithBlobReturn(call_id, param_Data, param_DataLen, rpc_ret_lease.data(), &rpc_ret_len); + return; + } + case 5: { + static_assert(256 <= xbot::config::buffer_block_size, + "return value does not fit into a buffer pool block"); + auto rpc_ret_lease = xbot::service::buffer::acquire(256); + if (!rpc_ret_lease) { + SendRpcResponse(call_id, xbot::datatypes::RpcStatus::BUSY, nullptr, 0); + return; + } + auto* rpc_ret_buf = reinterpret_cast(rpc_ret_lease.data()); + uint16_t rpc_ret_len = 256; + rpc_max_response_size_ = 256 * sizeof(uint8_t); + RPCLargeArrayReturn(call_id, rpc_ret_buf, &rpc_ret_len); + return; + } default: SendRpcResponse(call_id, xbot::datatypes::RpcStatus::ERROR, nullptr, 0); } diff --git a/codegen/templates/ServiceTemplate.hpp b/codegen/templates/ServiceTemplate.hpp index bf910ba..dd56da1 100644 --- a/codegen/templates/ServiceTemplate.hpp +++ b/codegen/templates/ServiceTemplate.hpp @@ -138,7 +138,7 @@ class ServiceTemplateBase : public xbot::service::Service { 0x33, 0x32, 0x5F, 0x74, 0x68, 0x6F, 0x70, 0x74, 0x69, 0x6F, 0x6E, 0x61, 0x6C, 0xF5, 0x69, 0x66, 0x75, 0x6E, 0x63, 0x74, 0x69, 0x6F, 0x6E, 0x73, - 0x84, 0xA4, 0x62, 0x69, 0x64, 0x00, 0x64, 0x6E, + 0x86, 0xA4, 0x62, 0x69, 0x64, 0x00, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x70, 0x4E, 0x6F, 0x50, 0x61, 0x72, 0x61, 0x6D, 0x73, 0x4E, 0x6F, 0x52, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x6A, 0x70, 0x61, 0x72, @@ -190,28 +190,60 @@ class ServiceTemplateBase : public xbot::service::Service { 0x66, 0x6C, 0x6F, 0x61, 0x74, 0x6B, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x5F, 0x74, 0x79, 0x70, 0x65, 0x67, 0x75, 0x69, 0x6E, 0x74, 0x38, 0x5F, - 0x74, 0x65, 0x65, 0x6E, 0x75, 0x6D, 0x73, 0x82, - 0xA3, 0x62, 0x69, 0x64, 0x70, 0x45, 0x78, 0x61, - 0x6D, 0x70, 0x6C, 0x65, 0x45, 0x6E, 0x75, 0x6D, - 0x43, 0x6C, 0x61, 0x73, 0x73, 0x69, 0x62, 0x61, - 0x73, 0x65, 0x5F, 0x74, 0x79, 0x70, 0x65, 0x67, - 0x75, 0x69, 0x6E, 0x74, 0x38, 0x5F, 0x74, 0x66, - 0x76, 0x61, 0x6C, 0x75, 0x65, 0x73, 0xA3, 0x66, - 0x56, 0x41, 0x4C, 0x55, 0x45, 0x31, 0x00, 0x66, - 0x56, 0x41, 0x4C, 0x55, 0x45, 0x32, 0x01, 0x66, - 0x56, 0x41, 0x4C, 0x55, 0x45, 0x33, 0x02, 0xA4, - 0x62, 0x69, 0x64, 0x72, 0x45, 0x78, 0x61, 0x6D, - 0x70, 0x6C, 0x65, 0x42, 0x69, 0x74, 0x6D, 0x61, - 0x73, 0x6B, 0x45, 0x6E, 0x75, 0x6D, 0x69, 0x62, - 0x61, 0x73, 0x65, 0x5F, 0x74, 0x79, 0x70, 0x65, - 0x67, 0x75, 0x69, 0x6E, 0x74, 0x38, 0x5F, 0x74, - 0x67, 0x62, 0x69, 0x74, 0x6D, 0x61, 0x73, 0x6B, - 0xF5, 0x66, 0x76, 0x61, 0x6C, 0x75, 0x65, 0x73, + 0x74, 0xA4, 0x62, 0x69, 0x64, 0x04, 0x64, 0x6E, + 0x61, 0x6D, 0x65, 0x78, 0x18, 0x42, 0x6C, 0x6F, + 0x62, 0x50, 0x61, 0x72, 0x61, 0x6D, 0x73, 0x57, + 0x69, 0x74, 0x68, 0x42, 0x6C, 0x6F, 0x62, 0x52, + 0x65, 0x74, 0x75, 0x72, 0x6E, 0x6A, 0x70, 0x61, + 0x72, 0x61, 0x6D, 0x65, 0x74, 0x65, 0x72, 0x73, + 0x81, 0xA3, 0x62, 0x69, 0x64, 0x00, 0x64, 0x6E, + 0x61, 0x6D, 0x65, 0x64, 0x44, 0x61, 0x74, 0x61, + 0x64, 0x74, 0x79, 0x70, 0x65, 0x64, 0x62, 0x6C, + 0x6F, 0x62, 0x6B, 0x72, 0x65, 0x74, 0x75, 0x72, + 0x6E, 0x5F, 0x74, 0x79, 0x70, 0x65, 0x64, 0x62, + 0x6C, 0x6F, 0x62, 0xA4, 0x62, 0x69, 0x64, 0x05, + 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x70, 0x4C, 0x61, + 0x72, 0x67, 0x65, 0x41, 0x72, 0x72, 0x61, 0x79, + 0x52, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x6A, 0x70, + 0x61, 0x72, 0x61, 0x6D, 0x65, 0x74, 0x65, 0x72, + 0x73, 0x80, 0x6B, 0x72, 0x65, 0x74, 0x75, 0x72, + 0x6E, 0x5F, 0x74, 0x79, 0x70, 0x65, 0x6C, 0x75, + 0x69, 0x6E, 0x74, 0x38, 0x5F, 0x74, 0x5B, 0x32, + 0x35, 0x36, 0x5D, 0x65, 0x65, 0x6E, 0x75, 0x6D, + 0x73, 0x82, 0xA3, 0x62, 0x69, 0x64, 0x70, 0x45, + 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x45, 0x6E, + 0x75, 0x6D, 0x43, 0x6C, 0x61, 0x73, 0x73, 0x69, + 0x62, 0x61, 0x73, 0x65, 0x5F, 0x74, 0x79, 0x70, + 0x65, 0x67, 0x75, 0x69, 0x6E, 0x74, 0x38, 0x5F, + 0x74, 0x66, 0x76, 0x61, 0x6C, 0x75, 0x65, 0x73, 0xA3, 0x66, 0x56, 0x41, 0x4C, 0x55, 0x45, 0x31, 0x00, 0x66, 0x56, 0x41, 0x4C, 0x55, 0x45, 0x32, 0x01, 0x66, 0x56, 0x41, 0x4C, 0x55, 0x45, 0x33, - 0x02 + 0x02, 0xA4, 0x62, 0x69, 0x64, 0x72, 0x45, 0x78, + 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x42, 0x69, 0x74, + 0x6D, 0x61, 0x73, 0x6B, 0x45, 0x6E, 0x75, 0x6D, + 0x69, 0x62, 0x61, 0x73, 0x65, 0x5F, 0x74, 0x79, + 0x70, 0x65, 0x67, 0x75, 0x69, 0x6E, 0x74, 0x38, + 0x5F, 0x74, 0x67, 0x62, 0x69, 0x74, 0x6D, 0x61, + 0x73, 0x6B, 0xF5, 0x66, 0x76, 0x61, 0x6C, 0x75, + 0x65, 0x73, 0xA3, 0x66, 0x56, 0x41, 0x4C, 0x55, + 0x45, 0x31, 0x00, 0x66, 0x56, 0x41, 0x4C, 0x55, + 0x45, 0x32, 0x01, 0x66, 0x56, 0x41, 0x4C, 0x55, + 0x45, 0x33, 0x02 + }; + + // Blocks that did not fit into the advertisement; served on request + // (DESCRIPTION_REQUEST -> DESCRIPTION_PART), so a host without generated + // classes can still fetch the complete schema. + static constexpr unsigned char SERVICE_OMITTED_CBOR[] = { + 0xA0 }; + static constexpr size_t SERVICE_OMITTED_CBOR_SIZE = 0; + + const unsigned char* GetOmittedDescription(size_t& size) override { + size = SERVICE_OMITTED_CBOR_SIZE; + return SERVICE_OMITTED_CBOR; + } //[[[end]]] private: @@ -315,17 +347,24 @@ class ServiceTemplateBase : public xbot::service::Service { /*[[[cog # Generate RPC virtual for each function. # call_id is passed so the implementation can respond asynchronously via SendRpcResponse(). + # Blob parameters are passed as (pointer, length) into the received packet: no copy and + # no size limit, valid until the handler returns. # For array return types: data buffer (max capacity) and response_length (init to max) are # appended. The implementation fills data, sets *response_length to actual element count, # then calls SendRpcResponse(call_id, SUCCESS, data, *response_length * sizeof(T)). + # A blob return works the same way, but *response_length is a byte count. for func in service["functions"]: params = ["uint16_t call_id"] for p in func["parameters"]: - if p['is_array']: + if p['is_blob']: + params.append(f"const uint8_t* {p['name']}, uint32_t {p['name']}Len") + elif p['is_array']: params.append(f"const {p['type']}* {p['name']}, uint32_t {p['name']}Len") else: params.append(f"{p['type']} {p['name']}") - if func['return_is_array']: + if func['return_is_blob']: + params.append("uint8_t* data, uint16_t* response_length") + elif func['return_is_array']: params.append(f"{func['return_base_type']}* data, uint16_t* response_length") params_str = ", ".join(params) cog.outl(f"virtual void RPC{func['name']}({params_str}) = 0;") @@ -334,6 +373,8 @@ class ServiceTemplateBase : public xbot::service::Service { virtual void RPCScalarParamsWithReturn(uint16_t call_id, float Speed, uint32_t Count, uint8_t Enable) = 0; virtual void RPCArrayParamNoReturn(uint16_t call_id, const char* Label, uint32_t LabelLen) = 0; virtual void RPCMixedParamsWithReturn(uint16_t call_id, const char* Name, uint32_t NameLen, float Value) = 0; + virtual void RPCBlobParamsWithBlobReturn(uint16_t call_id, const uint8_t* Data, uint32_t DataLen, uint8_t* data, uint16_t* response_length) = 0; + virtual void RPCLargeArrayReturn(uint16_t call_id, uint8_t* data, uint16_t* response_length) = 0; //[[[end]]] }; @@ -448,6 +489,24 @@ cog.outl(f"\u002f*\n{service['service_json']}\n*\u002f") } ], "return_type": "uint8_t" + }, + { + "id": 4, + "name": "BlobParamsWithBlobReturn", + "parameters": [ + { + "id": 0, + "name": "Data", + "type": "blob" + } + ], + "return_type": "blob" + }, + { + "id": 5, + "name": "LargeArrayReturn", + "parameters": [], + "return_type": "uint8_t[256]" } ], "enums": [ diff --git a/codegen/templates/service.json b/codegen/templates/service.json index 8014f8b..fe3ac7f 100644 --- a/codegen/templates/service.json +++ b/codegen/templates/service.json @@ -81,6 +81,20 @@ { "id": 1, "name": "Value", "type": "float" } ], "return_type": "uint8_t" + }, + { + "id": 4, + "name": "BlobParamsWithBlobReturn", + "parameters": [ + { "id": 0, "name": "Data", "type": "blob" } + ], + "return_type": "blob" + }, + { + "id": 5, + "name": "LargeArrayReturn", + "parameters": [], + "return_type": "uint8_t[256]" } ], "enums": [ diff --git a/codegen/xbot_codegen/xbot_codegen.py b/codegen/xbot_codegen/xbot_codegen.py index 179e143..a4ee7ab 100644 --- a/codegen/xbot_codegen/xbot_codegen.py +++ b/codegen/xbot_codegen/xbot_codegen.py @@ -71,6 +71,58 @@ def array_type_attrs(max_length): return {"is_array": False} +# sizeof of the scalar types in the generated C++ code (and on the wire). +TYPE_SIZES = { + "char": 1, + "uint8_t": 1, + "int8_t": 1, + "uint16_t": 2, + "int16_t": 2, + "uint32_t": 4, + "int32_t": 4, + "float": 4, + "uint64_t": 8, + "int64_t": 8, + "double": 8, +} + +# Largest RPC body that fits into one packet: max_packet_size(1472) - sizeof(XbotHeader)(24). +# A return value can never be larger, which is what the shared buffer pool is sized for. +MAX_RPC_RETURN_BYTES = 1472 - 24 + +# Array returns up to this size stay on the service thread stack. Larger ones and blob +# returns are taken from the shared buffer pool (see xbot-service/Buffer.hpp), so a +# service never has to reserve that stack space permanently. +RPC_STACK_RETURN_MAX = 128 + + +def typeSize(service, type_name): + """sizeof of a scalar or enum type in the generated C++ code.""" + for enum in service["enums"]: + if enum["id"] == type_name: + return TYPE_SIZES[enum["base_type"]] + if type_name in TYPE_SIZES: + return TYPE_SIZES[type_name] + raise Exception(f"Cannot determine the size of type '{type_name}'") + + +def pooledReturnBytes(service, func): + """Bytes a return value needs from the buffer pool, or None if it fits on the stack.""" + if func["return_type"] == "void": + return None + if func["return_is_blob"]: + return MAX_RPC_RETURN_BYTES + if func["return_is_array"]: + bytes_needed = func["return_max_length"] * typeSize(service, func["return_base_type"]) + return bytes_needed if bytes_needed > RPC_STACK_RETURN_MAX else None + return None + + +def needsBufferPool(service): + """True if any generated return value comes from the buffer pool.""" + return any(pooledReturnBytes(service, func) is not None for func in service["functions"]) + + def common_attrs(json, valid_types, callback_name, send_method_name): id = int(json['id']) name = toCamelCase(json['name']) @@ -218,12 +270,18 @@ def loadService(path: str) -> dict: raise Exception(f"Duplicate normalized function name '{func_name}' after name normalization") seen_func_names.add(func_name) return_type_str = json_func.get("return_type", "void") + return_is_blob = False if return_type_str == "void": return_base_type, return_max_length = None, None else: return_base_type, return_max_length = parse_type(return_type_str) - if return_base_type not in valid_types: + if return_base_type not in valid_types + ["blob"]: raise Exception(f"Illegal return type for function '{func_name}': {return_type_str}") + if return_base_type == "blob": + # Variable length and therefore bounded by one packet only + # (MAX_RPC_RETURN_BYTES); the generated dispatcher takes the buffer + # from the shared pool. + return_is_blob = True if return_max_length is not None: if return_max_length <= 0 or return_max_length > MAX_ARRAY_LENGTH: raise Exception( @@ -243,12 +301,13 @@ def loadService(path: str) -> dict: f"in function '{func_name}'") seen_param_names.add(param_name) param_type, param_max_length = parse_type(json_param["type"]) - if param_type not in valid_types: + if param_type not in valid_types + ["blob"]: raise Exception(f"Illegal parameter type in function '{func_name}': {param_type}") params.append({ "id": int(json_param["id"]), "name": param_name, "type": param_type, + "is_blob": param_type == "blob", **array_type_attrs(param_max_length), }) @@ -258,6 +317,7 @@ def loadService(path: str) -> dict: "return_type": return_type_str, "return_base_type": return_base_type, "return_is_array": return_is_array, + "return_is_blob": return_is_blob, "return_max_length": return_max_length, "parameters": params, }) diff --git a/xbot_service_interface_go/codegen/emit.go b/xbot_service_interface_go/codegen/emit.go index 319fe7a..6b78138 100644 --- a/xbot_service_interface_go/codegen/emit.go +++ b/xbot_service_interface_go/codegen/emit.go @@ -148,6 +148,9 @@ func (g *generator) decodeReturn(t, fn string) (string, []string, error) { switch { case t == "" || t == "void": return "", nil, nil + case base == "blob": + // Variable length return: hand the payload back as is. + return "[]byte", []string{"\treturn append([]byte(nil), payload...), nil"}, nil case base == "char" && isArray: return "string", []string{"\treturn charValue(payload), nil"}, nil case isArray && base == "uint8_t": diff --git a/xbot_service_interface_go/codegen/generate_test.go b/xbot_service_interface_go/codegen/generate_test.go index c9d98e3..79fa05f 100644 --- a/xbot_service_interface_go/codegen/generate_test.go +++ b/xbot_service_interface_go/codegen/generate_test.go @@ -88,6 +88,46 @@ func TestLoadRejects(t *testing.T) { } } +// TestBlobParameters pins that blob parameters and returns work: a blob parameter is +// sent as is (no padding to a fixed size) and a blob return is handed back as the raw +// payload. +func TestBlobParameters(t *testing.T) { + path := t.TempDir() + "/service.json" + schema := `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "Echo", "return_type": "blob", + "parameters": [{"id": 0, "name": "Data", "type": "blob"}]}, + {"id": 1, "name": "Write", "return_type": "int32_t", + "parameters": [{"id": 0, "name": "Path", "type": "blob"}]}]}` + if err := os.WriteFile(path, []byte(schema), 0o644); err != nil { + t.Fatal(err) + } + s, err := Load(path) + if err != nil { + t.Fatalf("Load: %v", err) + } + src, err := Generate(s, Options{}) + if err != nil { + t.Fatalf("Generate: %v", err) + } + for _, want := range []string{ + "func (c *Client) Echo(ctx context.Context, Data []byte) ([]byte, error)", + "func (c *Client) Write(ctx context.Context, Path []byte) (int32, error)", + "xbot.Bytes(0, Data)", + "xbot.Bytes(0, Path)", + "return append([]byte(nil), payload...)", + } { + if !bytes.Contains(src, []byte(want)) { + t.Errorf("generated code does not contain %q", want) + } + } + // A blob must not be padded to a declared size - that was the whole point. + for _, notWant := range []string{"byteParam(Data", "charParam(Path"} { + if bytes.Contains(src, []byte(notWant)) { + t.Errorf("generated code still pads a blob parameter: found %q", notWant) + } + } +} + // TestNumericArrays pins that numeric arrays (T[n]) are supported: they are // padded to n elements on send and decoded from n elements on receive. func TestNumericArrays(t *testing.T) { diff --git a/xbot_service_interface_go/xbot/conn.go b/xbot_service_interface_go/xbot/conn.go index c172035..1f67304 100644 --- a/xbot_service_interface_go/xbot/conn.go +++ b/xbot_service_interface_go/xbot/conn.go @@ -324,6 +324,13 @@ func (c *Conn) startCall(functionID uint8, params []Param) (uint16, error) { // send writes one header+payload packet to the service. func (c *Conn) send(msgType MessageType, arg1 uint8, arg2 uint16, payload []byte) error { + // One packet has to fit into a single, unfragmented datagram (the low level + // runs with IP reassembly disabled, an oversized packet is dropped silently). + // Splitting a large value is the caller's job, e.g. into offset addressed chunks. + if HeaderSize+len(payload) > MaxPacketSize { + return fmt.Errorf("xbot: payload of %d bytes exceeds the packet limit of %d bytes", + len(payload), MaxPacketSize-HeaderSize) + } hdr := Header{ ProtocolVersion: ProtocolVersion, MessageType: msgType, diff --git a/xbot_service_interface_go/xbot/conn_test.go b/xbot_service_interface_go/xbot/conn_test.go index 9ff2264..f35e044 100644 --- a/xbot_service_interface_go/xbot/conn_test.go +++ b/xbot_service_interface_go/xbot/conn_test.go @@ -305,3 +305,22 @@ func TestCheckAdvertisement(t *testing.T) { } } } + +// TestSendRejectsOversizedPayload makes sure a payload that does not fit into one +// unfragmented datagram is rejected locally instead of being dropped silently by the +// low level (which runs with IP reassembly disabled). +func TestSendRejectsOversizedPayload(t *testing.T) { + _, addr := startFakeService(t, respondWith(0, nil)) + c, err := Dial(context.Background(), Options{ServiceID: 1, Endpoint: addr}) + if err != nil { + t.Fatalf("Dial: %v", err) + } + t.Cleanup(func() { _ = c.Close() }) + + if err := c.send(MsgData, 0, 0, make([]byte, MaxPacketSize-HeaderSize+1)); err == nil { + t.Fatal("expected an error for a payload above the packet limit") + } + if err := c.send(MsgData, 0, 0, make([]byte, MaxPacketSize-HeaderSize)); err != nil { + t.Fatalf("payload at the packet limit rejected: %v", err) + } +} diff --git a/xbot_service_interface_py/tests/test_rpc.py b/xbot_service_interface_py/tests/test_rpc.py index 97f96bd..27ee150 100644 --- a/xbot_service_interface_py/tests/test_rpc.py +++ b/xbot_service_interface_py/tests/test_rpc.py @@ -61,6 +61,14 @@ ], 'return_type': 'uint8_t', }, + { + 'id': 4, + 'name': 'BlobReturn', + 'parameters': [ + {'id': 0, 'name': 'Data', 'type': 'blob'}, + ], + 'return_type': 'blob', + }, ], } @@ -78,7 +86,7 @@ class TestSchemaFunctions: def test_functions_parsed(self): s = ServiceSchema.from_dict(RPC_DESC) - assert len(s.functions) == 4 + assert len(s.functions) == 5 def test_no_functions_key(self): s = ServiceSchema.from_dict(NO_FUNC_DESC) @@ -308,6 +316,22 @@ def test_call_uint8_return(self): result = si.call_uint8_return(1, timeout_ms=500) assert result == 1 + def test_call_blob_return(self): + si = make_rpc_si() + payload = b'\x00\x01\x02binary' + _respond_async(si, call_id=1, status=0, payload=payload) + result = si.call_blob_return(b'ping', timeout_ms=500) + assert result == payload + + def test_call_blob_param_is_not_padded(self): + si = make_rpc_si() + _respond_async(si, call_id=1, status=0, payload=b'') + si.call_blob_return(b'ping', timeout_ms=500) + + params_bytes = si._io.send_rpc_call.call_args[0][3] + tid, _, size = struct.unpack_from(' max_bytes: raise RpcError( 2, f"RPC {fn['name']!r} response too large: got {len(payload)} bytes, max {max_bytes}") - if not is_array and len(payload) < max_bytes: + if base != 'blob' and not is_array and len(payload) < max_bytes: raise RpcError( 2, f"RPC {fn['name']!r} response too small: got {len(payload)} bytes, need {max_bytes}") return unpack_value(fn['return_type'], payload, enums) From fb67176f302d65df93c0ee822f131f054db23783 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Ebeling?= Date: Fri, 13 Nov 2026 22:53:44 +0100 Subject: [PATCH 03/28] docs: note version bump required when changing fixed param to blob --- Readme.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Readme.md b/Readme.md index aff5034..c340f81 100644 --- a/Readme.md +++ b/Readme.md @@ -252,6 +252,11 @@ not copied, as a register it is the configuration blob, and as a return value it (see [Shared Buffer Pool](#shared-buffer-pool)). A `type[N]` parameter or return above 128 bytes is pooled the same way, so a service never reserves stack for a payload it rarely sends. +Switching a parameter or return from a fixed `type[N]` to `blob` changes its wire layout, so the service needs a +version bump (`"version": 2`). Clients compare the advertised version (`ExpectVersion` in the Go/C++ clients, the +schema check in Python) and refuse a mismatch instead of sending a call with the wrong layout - service and +clients have to be updated together. + **IDs** must be unique within each section (`inputs`, `outputs`, `registers`). **Generated API (service side):** From cc1a3fb98df65d752c32e51dfcea36a279f84676 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Ebeling?= Date: Fri, 13 Nov 2026 23:27:29 +0100 Subject: [PATCH 04/28] Fix rabbit findings --- Readme.md | 21 +++++++++++-------- codegen/templates/ServiceTemplate.cpp | 15 ++++++++----- codegen/xbot_codegen/xbot_codegen.py | 7 +++++++ libxbot-service/src/Buffer.cpp | 5 +++++ .../test/BufferTests/BufferTests.cpp | 3 ++- libxbot-service/test/CMakeLists.txt | 1 + xbot_service_interface_py/tests/test_rpc.py | 10 +++++++++ .../xbot_service_interface/datatypes.py | 4 ++++ .../xbot_service_interface/interface.py | 15 +++++++++---- 9 files changed, 62 insertions(+), 19 deletions(-) diff --git a/Readme.md b/Readme.md index c340f81..ef0eefa 100644 --- a/Readme.md +++ b/Readme.md @@ -249,12 +249,13 @@ Services are defined in a JSON file. The code generator (`codegen/`) reads this `blob` is variable length: as a parameter it is passed as `(pointer, length)` into the received packet and is not copied, as a register it is the configuration blob, and as a return value it uses the shared buffer pool -(see [Shared Buffer Pool](#shared-buffer-pool)). A `type[N]` parameter or return above 128 bytes is pooled the -same way, so a service never reserves stack for a payload it rarely sends. +(see [Shared Buffer Pool](#shared-buffer-pool)). A `type[N]` return above 128 bytes is pooled the same way, so a +service never reserves stack for a payload it rarely sends. Switching a parameter or return from a fixed `type[N]` to `blob` changes its wire layout, so the service needs a -version bump (`"version": 2`). Clients compare the advertised version (`ExpectVersion` in the Go/C++ clients, the -schema check in Python) and refuse a mismatch instead of sending a call with the wrong layout - service and +version bump (`"version": 2`). Generated clients refuse a mismatch instead of sending a call with the wrong +layout: the C++ and Python clients always compare against the schema they were given, the Go client compares +only when `ExpectVersion` is set (generated clients set it, a hand-written one has to do the same). Service and clients have to be updated together. **IDs** must be unique within each section (`inputs`, `outputs`, `registers`). @@ -269,8 +270,9 @@ clients have to be updated together. - `void RPC{Name}(uint16_t call_id, ...)` — one pure virtual per function; a `blob` parameter arrives as `const uint8_t* , uint32_t Len` and is only valid until the handler returns (copy it if you need it longer) -- A `blob` or pooled array return appends `uint8_t* data, uint16_t* response_length`; `*response_length` is a - byte count for `blob` and an element count for `type[N]` +- A `type[N]` return above the stack threshold and a `blob` return append `uint8_t* data, + uint16_t* response_length`. A `blob` return is always `uint8_t`, a `type[N]` return uses its element + type; `*response_length` is a byte count for `blob` and an element count for `type[N]` **Generated API (interface side — same JSON, different template):** - Inputs and outputs swap roles: outputs become callbacks, inputs become send methods. @@ -314,9 +316,10 @@ Rules that keep the pool usable: - A lease is **move-only** and returns its block in the destructor. Do not keep it beyond the call that borrowed it: the pool is shared by all services, and a lease held across a flash operation or across RPCs starves the next caller. -- `acquire()` is **non-blocking** on purpose. A second large return while one is in flight gets an - empty lease and the service answers BUSY - an RPC handler must never wait for another service's - transfer. A block is only held while a return value is filled and copied into a packet. +- `acquire()` is **non-blocking** on purpose. It returns an empty lease only when every block is out, + and then the service answers BUSY - an RPC handler must never wait for another service's transfer. + With the default of two blocks, one outstanding return does not exhaust the pool. A block is only held + while a return value is filled and copied into a packet. - Release happens after the handler returned; `SendRpcResponse()` copies the payload into a packet. - No heap is involved: the storage is static. diff --git a/codegen/templates/ServiceTemplate.cpp b/codegen/templates/ServiceTemplate.cpp index 1aff6eb..923462a 100644 --- a/codegen/templates/ServiceTemplate.cpp +++ b/codegen/templates/ServiceTemplate.cpp @@ -374,7 +374,8 @@ if service["functions"]: cog.outl(" while (offset + sizeof(xbot::datatypes::DataDescriptor) <= len) {") cog.outl(" const auto* desc = reinterpret_cast(buf + offset);") cog.outl(" offset += sizeof(xbot::datatypes::DataDescriptor);") - cog.outl(" if (offset + desc->payload_size > len) { parse_ok = false; break; }") + cog.outl(" // Bounds check against the remaining bytes: offset + payload_size can wrap on a 32 bit target") + cog.outl(" if (desc->payload_size > len - offset) { parse_ok = false; break; }") cog.outl(" switch (desc->target_id) {") for p in func["parameters"]: cog.outl(f" case {p['id']}:") @@ -477,7 +478,8 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, while (offset + sizeof(xbot::datatypes::DataDescriptor) <= len) { const auto* desc = reinterpret_cast(buf + offset); offset += sizeof(xbot::datatypes::DataDescriptor); - if (offset + desc->payload_size > len) { parse_ok = false; break; } + // Bounds check against the remaining bytes: offset + payload_size can wrap on a 32 bit target + if (desc->payload_size > len - offset) { parse_ok = false; break; } switch (desc->target_id) { case 0: if (desc->payload_size == sizeof(float)) { @@ -518,7 +520,8 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, while (offset + sizeof(xbot::datatypes::DataDescriptor) <= len) { const auto* desc = reinterpret_cast(buf + offset); offset += sizeof(xbot::datatypes::DataDescriptor); - if (offset + desc->payload_size > len) { parse_ok = false; break; } + // Bounds check against the remaining bytes: offset + payload_size can wrap on a 32 bit target + if (desc->payload_size > len - offset) { parse_ok = false; break; } switch (desc->target_id) { case 0: if (desc->payload_size % sizeof(char) == 0 && @@ -550,7 +553,8 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, while (offset + sizeof(xbot::datatypes::DataDescriptor) <= len) { const auto* desc = reinterpret_cast(buf + offset); offset += sizeof(xbot::datatypes::DataDescriptor); - if (offset + desc->payload_size > len) { parse_ok = false; break; } + // Bounds check against the remaining bytes: offset + payload_size can wrap on a 32 bit target + if (desc->payload_size > len - offset) { parse_ok = false; break; } switch (desc->target_id) { case 0: if (desc->payload_size % sizeof(char) == 0 && @@ -587,7 +591,8 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, while (offset + sizeof(xbot::datatypes::DataDescriptor) <= len) { const auto* desc = reinterpret_cast(buf + offset); offset += sizeof(xbot::datatypes::DataDescriptor); - if (offset + desc->payload_size > len) { parse_ok = false; break; } + // Bounds check against the remaining bytes: offset + payload_size can wrap on a 32 bit target + if (desc->payload_size > len - offset) { parse_ok = false; break; } switch (desc->target_id) { case 0: param_Data = buf + offset; diff --git a/codegen/xbot_codegen/xbot_codegen.py b/codegen/xbot_codegen/xbot_codegen.py index a4ee7ab..97e8641 100644 --- a/codegen/xbot_codegen/xbot_codegen.py +++ b/codegen/xbot_codegen/xbot_codegen.py @@ -287,6 +287,13 @@ def loadService(path: str) -> dict: raise Exception( f"Illegal array return length {return_max_length} for function '{func_name}' " f"return type '{return_type_str}': must be 1..{MAX_ARRAY_LENGTH}") + # A return value travels in one packet, so a schema that declares more can + # never be answered. Fail here instead of at runtime. + return_bytes = return_max_length * typeSize(service, return_base_type) + if return_bytes > MAX_RPC_RETURN_BYTES: + raise Exception( + f"Function '{func_name}' return type '{return_type_str}' is {return_bytes} bytes, " + f"more than one packet can carry ({MAX_RPC_RETURN_BYTES})") return_is_array = return_max_length is not None check_unique_ids(json_func.get("parameters", [])) diff --git a/libxbot-service/src/Buffer.cpp b/libxbot-service/src/Buffer.cpp index b9c42f1..2f0eb19 100644 --- a/libxbot-service/src/Buffer.cpp +++ b/libxbot-service/src/Buffer.cpp @@ -23,6 +23,8 @@ static_assert(xbot::config::buffer_block_size >= xbot::config::max_packet_size - static_assert(xbot::config::buffer_block_count >= 1U, "the buffer pool needs at least one block"); static_assert(xbot::config::buffer_block_count <= xbot::service::buffer::max_block_count, "buffer_block_count exceeds the pool bitmap"); +static_assert((xbot::config::buffer_block_size % xbot::service::buffer::block_alignment) == 0, + "buffer_block_size must be a multiple of block_alignment"); #if XBOT_BUFFER_DEFAULT_POOL // Storage for platforms that do not bring their own (hosts, tests, examples). A @@ -105,6 +107,9 @@ bool xbot::service::buffer::initialize(void *storage, size_t block_size, size_t if ((reinterpret_cast(storage) % block_alignment) != 0U) { return false; } + if ((block_size % block_alignment) != 0U) { + return false; // a block stride that is not aligned would misalign every later lease + } if (used_mask_.load(std::memory_order_relaxed) != 0U) { return false; // a lease is still out, keep the current storage alive } diff --git a/libxbot-service/test/BufferTests/BufferTests.cpp b/libxbot-service/test/BufferTests/BufferTests.cpp index f38a979..2ac19d9 100644 --- a/libxbot-service/test/BufferTests/BufferTests.cpp +++ b/libxbot-service/test/BufferTests/BufferTests.cpp @@ -100,7 +100,8 @@ TEST(BufferTests, InitializeRejectsBadArguments) { CHECK_FALSE(buffer::initialize(storage_, 0, kBlocks)); CHECK_FALSE(buffer::initialize(storage_, kBlockSize, 0)); CHECK_FALSE(buffer::initialize(storage_, kBlockSize, buffer::max_block_count + 1)); - CHECK_FALSE(buffer::initialize(storage_ + 1, kBlockSize, kBlocks)); // unaligned + CHECK_FALSE(buffer::initialize(storage_ + 1, kBlockSize, kBlocks)); // unaligned storage + CHECK_FALSE(buffer::initialize(storage_, kBlockSize + 1, kBlocks)); // unaligned block stride } TEST(BufferTests, InitializeRefusesWhileALeaseIsOut) { diff --git a/libxbot-service/test/CMakeLists.txt b/libxbot-service/test/CMakeLists.txt index ece691a..cec883f 100644 --- a/libxbot-service/test/CMakeLists.txt +++ b/libxbot-service/test/CMakeLists.txt @@ -11,6 +11,7 @@ target_include_directories(AllTests PRIVATE . ${PROJECT_SOURCE_DIR}/include + ${PROJECT_SOURCE_DIR}/../include ) target_compile_options(AllTests diff --git a/xbot_service_interface_py/tests/test_rpc.py b/xbot_service_interface_py/tests/test_rpc.py index 27ee150..ebe1fe5 100644 --- a/xbot_service_interface_py/tests/test_rpc.py +++ b/xbot_service_interface_py/tests/test_rpc.py @@ -275,6 +275,11 @@ def _respond_async(si, call_id, status, payload=b''): ready = threading.Event() def _do(): ready.wait() + # A response that arrives before the call is registered is dropped by + # _on_rpc_response, so wait for it instead of racing the caller. + deadline = time.time() + 1.0 + while time.time() < deadline and not si._rpc_call_active: + time.sleep(0.001) si._on_rpc_response(call_id, status, payload) t = threading.Thread(target=_do, daemon=False) t.start() @@ -332,6 +337,11 @@ def test_call_blob_param_is_not_padded(self): tid, _, size = struct.unpack_from(' dict: diff --git a/xbot_service_interface_py/xbot_service_interface/interface.py b/xbot_service_interface_py/xbot_service_interface/interface.py index 1f44683..925dd15 100644 --- a/xbot_service_interface_py/xbot_service_interface/interface.py +++ b/xbot_service_interface_py/xbot_service_interface/interface.py @@ -7,7 +7,7 @@ from .exceptions import UnknownChannelError, IncompatibleServiceError, RpcError, RpcBusyError, RpcTimeoutError from .schema import ServiceSchema from .serialization import pack_value, unpack_value, sizeof_type, parse_type_string -from .datatypes import pack_descriptor, HEADER_SIZE, MAX_PACKET_SIZE +from .datatypes import pack_descriptor, HEADER_SIZE, MAX_UDP_PAYLOAD log = logging.getLogger(__name__) @@ -374,6 +374,14 @@ def _call_rpc(self, fn: dict, args: tuple, timeout_ms: int): raw = pack_value(param['type_str'], arg, enums) params_bytes += pack_descriptor(param['id'], len(raw)) + raw + # The request has to fit into one datagram. The low level drops a larger one without + # reporting anything, which would surface as a timeout - so fail here instead. + max_params = MAX_UDP_PAYLOAD - HEADER_SIZE + if len(params_bytes) > max_params: + raise ValueError( + f"RPC {fn['name']!r} parameters are {len(params_bytes)} bytes, " + f"more than one packet can carry ({max_params})") + with self._rpc_lock: with self._rpc_condition: counter = (self._rpc_call_counter + 1) & 0xFFFF @@ -412,9 +420,8 @@ def _call_rpc(self, fn: dict, args: tuple, timeout_ms: int): return None base, is_array, _ = parse_type_string(fn['return_type']) if base == 'blob': - # Variable length return, bounded by one packet only. The service - # cannot send more than that anyway (max_packet_size - header). - max_bytes = MAX_PACKET_SIZE - HEADER_SIZE + # Variable length return, bounded by one packet only. + max_bytes = MAX_UDP_PAYLOAD - HEADER_SIZE else: max_bytes = sizeof_type(fn['return_type']) if len(payload) > max_bytes: From 41a72af52b9fabcdaf8b6a93dce6455d6ac15dd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Ebeling?= Date: Sat, 14 Nov 2026 18:15:35 +0100 Subject: [PATCH 05/28] feat(codegen): allow blob for inputs and outputs A fixed char[256] output (BMS "Extra Data") has the same problem as FileWrite.Data: the size is a stack decision, not a wire decision. The data path already carries (pointer, length) for arrays, so blob only has to be allowed by the schema and passed through with a byte length instead of an element count. - inputs: On{Name}Changed(const uint8_t*, uint32_t length), length in bytes, no modulo check (a blob has no element size) - outputs: Send{Name}(const uint8_t*, uint32_t length) sends length bytes - interface template: same for the swapped input/output roles - Go: schema validation accepts blob for inputs and outputs; the client does not generate DATA handling, so nothing else changes - demo schema covers both paths --- Readme.md | 7 +- .../templates/ServiceInterfaceTemplate.cpp | 16 +- .../templates/ServiceInterfaceTemplate.hpp | 26 +- codegen/templates/ServiceTemplate.cpp | 17 +- codegen/templates/ServiceTemplate.hpp | 275 ++++++++++-------- codegen/templates/service.json | 10 + codegen/xbot_codegen/xbot_codegen.py | 5 +- .../codegen/generate_test.go | 21 +- xbot_service_interface_go/codegen/schema.go | 8 +- 9 files changed, 247 insertions(+), 138 deletions(-) diff --git a/Readme.md b/Readme.md index ef0eefa..4f9456b 100644 --- a/Readme.md +++ b/Readme.md @@ -245,10 +245,11 @@ Services are defined in a JSON file. The code generator (`codegen/`) reads this } ``` -**Valid types:** `char`, `uint8_t`, `uint16_t`, `uint32_t`, `uint64_t`, `int8_t`, `int16_t`, `int32_t`, `int64_t`, `float`, `double`, `blob` (registers, RPC parameters and RPC return values), or fixed-length arrays of any scalar type as `type[N]`. +**Valid types:** `char`, `uint8_t`, `uint16_t`, `uint32_t`, `uint64_t`, `int8_t`, `int16_t`, `int32_t`, `int64_t`, `float`, `double`, `blob` (registers, inputs, outputs, RPC parameters and RPC return values), or fixed-length arrays of any scalar type as `type[N]`. `blob` is variable length: as a parameter it is passed as `(pointer, length)` into the received packet and is -not copied, as a register it is the configuration blob, and as a return value it uses the shared buffer pool +not copied, as an input or output it is passed/sent as `(pointer, length)` with the length in bytes, as a +register it is the configuration blob, and as a return value it uses the shared buffer pool (see [Shared Buffer Pool](#shared-buffer-pool)). A `type[N]` return above 128 bytes is pooled the same way, so a service never reserves stack for a payload it rarely sends. @@ -263,8 +264,10 @@ clients have to be updated together. **Generated API (service side):** - `void On{Name}Changed(const T* value, uint32_t length)` — called when an input arrives (array types) - `void On{Name}Changed(const T& value)` — called when an input arrives (scalar types) +- `void On{Name}Changed(const uint8_t* value, uint32_t length)` — called when a blob input arrives, `length` in bytes - `bool Send{Name}(const T* data, uint32_t length)` — send an output (array types) - `bool Send{Name}(const T& data)` — send an output (scalar types) +- `bool Send{Name}(const uint8_t* data, uint32_t length)` — send a blob output, `length` in bytes - `bool OnRegister{Name}Changed(const void* data, size_t length)` — called when a register is set (blob registers) - Struct `{Name}` with `value`, `length` (arrays), and `valid` fields — for non-blob registers - `void RPC{Name}(uint16_t call_id, ...)` — one pure virtual per function; a `blob` parameter arrives as diff --git a/codegen/templates/ServiceInterfaceTemplate.cpp b/codegen/templates/ServiceInterfaceTemplate.cpp index d74e0fa..13ca8b6 100644 --- a/codegen/templates/ServiceInterfaceTemplate.cpp +++ b/codegen/templates/ServiceInterfaceTemplate.cpp @@ -28,7 +28,9 @@ void ServiceTemplateInterfaceBase::OnData(uint16_t service_id, uint64_t timestam /*[[[cog for o in service['outputs']: cog.outl(f"case {o['id']}:"); - if o['is_array']: + if o['is_blob']: + cog.outl(f"{o['callback_name']}(static_cast(payload), length);") + elif o['is_array']: cog.outl(f"if(length % sizeof({o['type']}) != 0) {{"); cog.outl(" spdlog::error(\"Invalid data size\");"); cog.outl(" return;"); @@ -56,6 +58,9 @@ void ServiceTemplateInterfaceBase::OnData(uint16_t service_id, uint64_t timestam } OnExampleOutput2Changed(*static_cast(payload)); break; + case 2: + OnExampleOutputBlobChanged(static_cast(payload), length); + break; //[[[end]]] default: return; @@ -96,7 +101,11 @@ bool ServiceTemplateInterfaceBase::SetRegisterRegister4Optional(const uint32_t & /*[[[cog # Generate send function implementations. for input in service["inputs"]: - if input['is_array']: + if input['is_blob']: + cog.outl(f"bool {service['interface_class_name']}::{input['send_method_name']}(const uint8_t* data, uint32_t length) {{") + cog.outl(f" return SendData({input['id']}, data, length, false);") + cog.outl("}") + elif input['is_array']: cog.outl(f"bool {service['interface_class_name']}::{input['send_method_name']}(const {input['type']}* data, uint32_t length) {{") cog.outl(f" return SendData({input['id']}, data, length*sizeof({input['type']}), false);") cog.outl("}") @@ -111,6 +120,9 @@ bool ServiceTemplateInterfaceBase::SendExampleInput1(const char* data, uint32_t bool ServiceTemplateInterfaceBase::SendExampleInput2(const uint32_t &data) { return SendData(1, &data, sizeof(uint32_t), false); } +bool ServiceTemplateInterfaceBase::SendExampleInputBlob(const uint8_t* data, uint32_t length) { + return SendData(2, data, length, false); +} //[[[end]]] /*[[[cog diff --git a/codegen/templates/ServiceInterfaceTemplate.hpp b/codegen/templates/ServiceInterfaceTemplate.hpp index 9810020..90419a4 100644 --- a/codegen/templates/ServiceInterfaceTemplate.hpp +++ b/codegen/templates/ServiceInterfaceTemplate.hpp @@ -52,13 +52,16 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas /*[[[cog # Generate send functions for each input. for input in service["inputs"]: - if input['is_array']: + if input['is_blob']: + cog.outl(f"bool {input['send_method_name']}(const uint8_t* data, uint32_t length);") + elif input['is_array']: cog.outl(f"bool {input['send_method_name']}(const {input['type']}* data, uint32_t length);") else: cog.outl(f"bool {input['send_method_name']}(const {input['type']} &data);") ]]]*/ bool SendExampleInput1(const char* data, uint32_t length); bool SendExampleInput2(const uint32_t &data); + bool SendExampleInputBlob(const uint8_t* data, uint32_t length); //[[[end]]] /*[[[cog @@ -110,7 +113,12 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas /*[[[cog # Generate callback functions for each service output. for output in service["outputs"]: - if output['is_array']: + if output['is_blob']: + cog.outl(f"virtual void {output['callback_name']}(const uint8_t* new_value, uint32_t length) {{") + cog.outl(f"(void)new_value;") + cog.outl(f"(void)length;") + cog.outl(f"}};") + elif output['is_array']: cog.outl(f"virtual void {output['callback_name']}(const {output['type']}* new_value, uint32_t length) {{") cog.outl(f"(void)new_value;") cog.outl(f"(void)length;") @@ -123,6 +131,10 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas (void)length; }; virtual void OnExampleOutput2Changed(const uint32_t &new_value) {(void) new_value;}; + virtual void OnExampleOutputBlobChanged(const uint8_t* new_value, uint32_t length) { + (void)new_value; + (void)length; + }; //[[[end]]] private: @@ -146,6 +158,11 @@ cog.outl(f"\u002f*\n{service['service_json']}\n*\u002f") "id": 1, "name": "ExampleInput2", "type": "uint32_t" + }, + { + "id": 2, + "name": "ExampleInputBlob", + "type": "blob" } ], "outputs": [ @@ -158,6 +175,11 @@ cog.outl(f"\u002f*\n{service['service_json']}\n*\u002f") "id": 1, "name": "ExampleOutput2", "type": "uint32_t" + }, + { + "id": 2, + "name": "ExampleOutputBlob", + "type": "blob" } ], "registers": [ diff --git a/codegen/templates/ServiceTemplate.cpp b/codegen/templates/ServiceTemplate.cpp index 923462a..bd865da 100644 --- a/codegen/templates/ServiceTemplate.cpp +++ b/codegen/templates/ServiceTemplate.cpp @@ -50,7 +50,10 @@ void ServiceTemplateBase::handleData(uint16_t target_id, const void *payload, si /*[[[cog for i in service['inputs']: cog.outl(f"case {i['id']}:"); - if i['is_array']: + if i['is_blob']: + cog.outl(f"{i['callback_name']}(static_cast(payload), length);") + cog.outl("return;") + elif i['is_array']: cog.outl(f"if (length % sizeof({i['type']}) != 0) {{"); cog.outl(" ULOG_ARG_ERROR(&service_id_, \"Invalid data size\");"); cog.outl(" return;"); @@ -80,6 +83,9 @@ void ServiceTemplateBase::handleData(uint16_t target_id, const void *payload, si } OnExampleInput2Changed(*static_cast(payload)); return; + case 2: + OnExampleInputBlobChanged(static_cast(payload), length); + return; //[[[end]]] } } @@ -192,7 +198,11 @@ bool ServiceTemplateBase::AdvertiseServiceImpl() { /*[[[cog # Generate send function implementations. for output in service["outputs"]: - if output['is_array']: + if output['is_blob']: + cog.outl(f"bool {service['class_name']}::{output['send_method_name']}(const uint8_t* data, uint32_t length) {{") + cog.outl(f" return SendData({output['id']}, data, length);") + cog.outl("}") + elif output['is_array']: cog.outl(f"bool {service['class_name']}::{output['send_method_name']}(const {output['type']}* data, uint32_t length) {{") cog.outl(f" return SendData({output['id']}, data, length*sizeof({output['type']}));") cog.outl("}") @@ -207,6 +217,9 @@ bool ServiceTemplateBase::SendExampleOutput1(const char* data, uint32_t length) bool ServiceTemplateBase::SendExampleOutput2(const uint32_t &data) { return SendData(1, &data, sizeof(uint32_t)); } +bool ServiceTemplateBase::SendExampleOutputBlob(const uint8_t* data, uint32_t length) { + return SendData(2, data, length); +} //[[[end]]] /*[[[cog diff --git a/codegen/templates/ServiceTemplate.hpp b/codegen/templates/ServiceTemplate.hpp index dd56da1..41fe5ad 100644 --- a/codegen/templates/ServiceTemplate.hpp +++ b/codegen/templates/ServiceTemplate.hpp @@ -95,7 +95,7 @@ class ServiceTemplateBase : public xbot::service::Service { 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x54, 0x65, 0x6D, 0x70, 0x6C, 0x61, 0x74, 0x65, 0x67, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6F, 0x6E, 0x01, 0x66, - 0x69, 0x6E, 0x70, 0x75, 0x74, 0x73, 0x82, 0xA3, + 0x69, 0x6E, 0x70, 0x75, 0x74, 0x73, 0x83, 0xA3, 0x62, 0x69, 0x64, 0x00, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x6D, 0x45, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x49, 0x6E, 0x70, 0x75, 0x74, 0x31, 0x64, @@ -105,131 +105,140 @@ class ServiceTemplateBase : public xbot::service::Service { 0x6D, 0x45, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x49, 0x6E, 0x70, 0x75, 0x74, 0x32, 0x64, 0x74, 0x79, 0x70, 0x65, 0x68, 0x75, 0x69, 0x6E, 0x74, - 0x33, 0x32, 0x5F, 0x74, 0x67, 0x6F, 0x75, 0x74, - 0x70, 0x75, 0x74, 0x73, 0x82, 0xA3, 0x62, 0x69, - 0x64, 0x00, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x6E, - 0x45, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x4F, - 0x75, 0x74, 0x70, 0x75, 0x74, 0x31, 0x64, 0x74, - 0x79, 0x70, 0x65, 0x69, 0x63, 0x68, 0x61, 0x72, - 0x5B, 0x31, 0x30, 0x30, 0x5D, 0xA3, 0x62, 0x69, - 0x64, 0x01, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x6E, - 0x45, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x4F, - 0x75, 0x74, 0x70, 0x75, 0x74, 0x32, 0x64, 0x74, - 0x79, 0x70, 0x65, 0x68, 0x75, 0x69, 0x6E, 0x74, - 0x33, 0x32, 0x5F, 0x74, 0x69, 0x72, 0x65, 0x67, - 0x69, 0x73, 0x74, 0x65, 0x72, 0x73, 0x84, 0xA3, - 0x62, 0x69, 0x64, 0x00, 0x64, 0x6E, 0x61, 0x6D, - 0x65, 0x69, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, - 0x65, 0x72, 0x31, 0x64, 0x74, 0x79, 0x70, 0x65, - 0x68, 0x63, 0x68, 0x61, 0x72, 0x5B, 0x34, 0x32, - 0x5D, 0xA3, 0x62, 0x69, 0x64, 0x01, 0x64, 0x6E, - 0x61, 0x6D, 0x65, 0x69, 0x52, 0x65, 0x67, 0x69, - 0x73, 0x74, 0x65, 0x72, 0x32, 0x64, 0x74, 0x79, - 0x70, 0x65, 0x68, 0x75, 0x69, 0x6E, 0x74, 0x33, - 0x32, 0x5F, 0x74, 0xA3, 0x62, 0x69, 0x64, 0x02, - 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x69, 0x52, 0x65, - 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x33, 0x64, + 0x33, 0x32, 0x5F, 0x74, 0xA3, 0x62, 0x69, 0x64, + 0x02, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x70, 0x45, + 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x49, 0x6E, + 0x70, 0x75, 0x74, 0x42, 0x6C, 0x6F, 0x62, 0x64, 0x74, 0x79, 0x70, 0x65, 0x64, 0x62, 0x6C, 0x6F, - 0x62, 0xA4, 0x62, 0x69, 0x64, 0x03, 0x64, 0x6E, - 0x61, 0x6D, 0x65, 0x72, 0x52, 0x65, 0x67, 0x69, - 0x73, 0x74, 0x65, 0x72, 0x34, 0x20, 0x4F, 0x70, - 0x74, 0x69, 0x6F, 0x6E, 0x61, 0x6C, 0x64, 0x74, - 0x79, 0x70, 0x65, 0x68, 0x75, 0x69, 0x6E, 0x74, - 0x33, 0x32, 0x5F, 0x74, 0x68, 0x6F, 0x70, 0x74, - 0x69, 0x6F, 0x6E, 0x61, 0x6C, 0xF5, 0x69, 0x66, - 0x75, 0x6E, 0x63, 0x74, 0x69, 0x6F, 0x6E, 0x73, - 0x86, 0xA4, 0x62, 0x69, 0x64, 0x00, 0x64, 0x6E, - 0x61, 0x6D, 0x65, 0x70, 0x4E, 0x6F, 0x50, 0x61, - 0x72, 0x61, 0x6D, 0x73, 0x4E, 0x6F, 0x52, 0x65, + 0x62, 0x67, 0x6F, 0x75, 0x74, 0x70, 0x75, 0x74, + 0x73, 0x83, 0xA3, 0x62, 0x69, 0x64, 0x00, 0x64, + 0x6E, 0x61, 0x6D, 0x65, 0x6E, 0x45, 0x78, 0x61, + 0x6D, 0x70, 0x6C, 0x65, 0x4F, 0x75, 0x74, 0x70, + 0x75, 0x74, 0x31, 0x64, 0x74, 0x79, 0x70, 0x65, + 0x69, 0x63, 0x68, 0x61, 0x72, 0x5B, 0x31, 0x30, + 0x30, 0x5D, 0xA3, 0x62, 0x69, 0x64, 0x01, 0x64, + 0x6E, 0x61, 0x6D, 0x65, 0x6E, 0x45, 0x78, 0x61, + 0x6D, 0x70, 0x6C, 0x65, 0x4F, 0x75, 0x74, 0x70, + 0x75, 0x74, 0x32, 0x64, 0x74, 0x79, 0x70, 0x65, + 0x68, 0x75, 0x69, 0x6E, 0x74, 0x33, 0x32, 0x5F, + 0x74, 0xA3, 0x62, 0x69, 0x64, 0x02, 0x64, 0x6E, + 0x61, 0x6D, 0x65, 0x71, 0x45, 0x78, 0x61, 0x6D, + 0x70, 0x6C, 0x65, 0x4F, 0x75, 0x74, 0x70, 0x75, + 0x74, 0x42, 0x6C, 0x6F, 0x62, 0x64, 0x74, 0x79, + 0x70, 0x65, 0x64, 0x62, 0x6C, 0x6F, 0x62, 0x69, + 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, + 0x73, 0x84, 0xA3, 0x62, 0x69, 0x64, 0x00, 0x64, + 0x6E, 0x61, 0x6D, 0x65, 0x69, 0x52, 0x65, 0x67, + 0x69, 0x73, 0x74, 0x65, 0x72, 0x31, 0x64, 0x74, + 0x79, 0x70, 0x65, 0x68, 0x63, 0x68, 0x61, 0x72, + 0x5B, 0x34, 0x32, 0x5D, 0xA3, 0x62, 0x69, 0x64, + 0x01, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x69, 0x52, + 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x32, + 0x64, 0x74, 0x79, 0x70, 0x65, 0x68, 0x75, 0x69, + 0x6E, 0x74, 0x33, 0x32, 0x5F, 0x74, 0xA3, 0x62, + 0x69, 0x64, 0x02, 0x64, 0x6E, 0x61, 0x6D, 0x65, + 0x69, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, + 0x72, 0x33, 0x64, 0x74, 0x79, 0x70, 0x65, 0x64, + 0x62, 0x6C, 0x6F, 0x62, 0xA4, 0x62, 0x69, 0x64, + 0x03, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x72, 0x52, + 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x34, + 0x20, 0x4F, 0x70, 0x74, 0x69, 0x6F, 0x6E, 0x61, + 0x6C, 0x64, 0x74, 0x79, 0x70, 0x65, 0x68, 0x75, + 0x69, 0x6E, 0x74, 0x33, 0x32, 0x5F, 0x74, 0x68, + 0x6F, 0x70, 0x74, 0x69, 0x6F, 0x6E, 0x61, 0x6C, + 0xF5, 0x69, 0x66, 0x75, 0x6E, 0x63, 0x74, 0x69, + 0x6F, 0x6E, 0x73, 0x86, 0xA4, 0x62, 0x69, 0x64, + 0x00, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x70, 0x4E, + 0x6F, 0x50, 0x61, 0x72, 0x61, 0x6D, 0x73, 0x4E, + 0x6F, 0x52, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x6A, + 0x70, 0x61, 0x72, 0x61, 0x6D, 0x65, 0x74, 0x65, + 0x72, 0x73, 0x80, 0x6B, 0x72, 0x65, 0x74, 0x75, + 0x72, 0x6E, 0x5F, 0x74, 0x79, 0x70, 0x65, 0x64, + 0x76, 0x6F, 0x69, 0x64, 0xA4, 0x62, 0x69, 0x64, + 0x01, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x76, 0x53, + 0x63, 0x61, 0x6C, 0x61, 0x72, 0x50, 0x61, 0x72, + 0x61, 0x6D, 0x73, 0x57, 0x69, 0x74, 0x68, 0x52, + 0x65, 0x74, 0x75, 0x72, 0x6E, 0x6A, 0x70, 0x61, + 0x72, 0x61, 0x6D, 0x65, 0x74, 0x65, 0x72, 0x73, + 0x83, 0xA3, 0x62, 0x69, 0x64, 0x00, 0x64, 0x6E, + 0x61, 0x6D, 0x65, 0x65, 0x53, 0x70, 0x65, 0x65, + 0x64, 0x64, 0x74, 0x79, 0x70, 0x65, 0x65, 0x66, + 0x6C, 0x6F, 0x61, 0x74, 0xA3, 0x62, 0x69, 0x64, + 0x01, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x65, 0x43, + 0x6F, 0x75, 0x6E, 0x74, 0x64, 0x74, 0x79, 0x70, + 0x65, 0x68, 0x75, 0x69, 0x6E, 0x74, 0x33, 0x32, + 0x5F, 0x74, 0xA3, 0x62, 0x69, 0x64, 0x02, 0x64, + 0x6E, 0x61, 0x6D, 0x65, 0x66, 0x45, 0x6E, 0x61, + 0x62, 0x6C, 0x65, 0x64, 0x74, 0x79, 0x70, 0x65, + 0x67, 0x75, 0x69, 0x6E, 0x74, 0x38, 0x5F, 0x74, + 0x6B, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x5F, + 0x74, 0x79, 0x70, 0x65, 0x67, 0x69, 0x6E, 0x74, + 0x33, 0x32, 0x5F, 0x74, 0xA4, 0x62, 0x69, 0x64, + 0x02, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x72, 0x41, + 0x72, 0x72, 0x61, 0x79, 0x50, 0x61, 0x72, 0x61, + 0x6D, 0x4E, 0x6F, 0x52, 0x65, 0x74, 0x75, 0x72, + 0x6E, 0x6A, 0x70, 0x61, 0x72, 0x61, 0x6D, 0x65, + 0x74, 0x65, 0x72, 0x73, 0x81, 0xA3, 0x62, 0x69, + 0x64, 0x00, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x65, + 0x4C, 0x61, 0x62, 0x65, 0x6C, 0x64, 0x74, 0x79, + 0x70, 0x65, 0x68, 0x63, 0x68, 0x61, 0x72, 0x5B, + 0x36, 0x34, 0x5D, 0x6B, 0x72, 0x65, 0x74, 0x75, + 0x72, 0x6E, 0x5F, 0x74, 0x79, 0x70, 0x65, 0x64, + 0x76, 0x6F, 0x69, 0x64, 0xA4, 0x62, 0x69, 0x64, + 0x03, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x75, 0x4D, + 0x69, 0x78, 0x65, 0x64, 0x50, 0x61, 0x72, 0x61, + 0x6D, 0x73, 0x57, 0x69, 0x74, 0x68, 0x52, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x6A, 0x70, 0x61, 0x72, - 0x61, 0x6D, 0x65, 0x74, 0x65, 0x72, 0x73, 0x80, + 0x61, 0x6D, 0x65, 0x74, 0x65, 0x72, 0x73, 0x82, + 0xA3, 0x62, 0x69, 0x64, 0x00, 0x64, 0x6E, 0x61, + 0x6D, 0x65, 0x64, 0x4E, 0x61, 0x6D, 0x65, 0x64, + 0x74, 0x79, 0x70, 0x65, 0x68, 0x63, 0x68, 0x61, + 0x72, 0x5B, 0x33, 0x32, 0x5D, 0xA3, 0x62, 0x69, + 0x64, 0x01, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x65, + 0x56, 0x61, 0x6C, 0x75, 0x65, 0x64, 0x74, 0x79, + 0x70, 0x65, 0x65, 0x66, 0x6C, 0x6F, 0x61, 0x74, 0x6B, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x5F, - 0x74, 0x79, 0x70, 0x65, 0x64, 0x76, 0x6F, 0x69, - 0x64, 0xA4, 0x62, 0x69, 0x64, 0x01, 0x64, 0x6E, - 0x61, 0x6D, 0x65, 0x76, 0x53, 0x63, 0x61, 0x6C, - 0x61, 0x72, 0x50, 0x61, 0x72, 0x61, 0x6D, 0x73, - 0x57, 0x69, 0x74, 0x68, 0x52, 0x65, 0x74, 0x75, - 0x72, 0x6E, 0x6A, 0x70, 0x61, 0x72, 0x61, 0x6D, - 0x65, 0x74, 0x65, 0x72, 0x73, 0x83, 0xA3, 0x62, - 0x69, 0x64, 0x00, 0x64, 0x6E, 0x61, 0x6D, 0x65, - 0x65, 0x53, 0x70, 0x65, 0x65, 0x64, 0x64, 0x74, - 0x79, 0x70, 0x65, 0x65, 0x66, 0x6C, 0x6F, 0x61, - 0x74, 0xA3, 0x62, 0x69, 0x64, 0x01, 0x64, 0x6E, - 0x61, 0x6D, 0x65, 0x65, 0x43, 0x6F, 0x75, 0x6E, - 0x74, 0x64, 0x74, 0x79, 0x70, 0x65, 0x68, 0x75, - 0x69, 0x6E, 0x74, 0x33, 0x32, 0x5F, 0x74, 0xA3, - 0x62, 0x69, 0x64, 0x02, 0x64, 0x6E, 0x61, 0x6D, - 0x65, 0x66, 0x45, 0x6E, 0x61, 0x62, 0x6C, 0x65, - 0x64, 0x74, 0x79, 0x70, 0x65, 0x67, 0x75, 0x69, - 0x6E, 0x74, 0x38, 0x5F, 0x74, 0x6B, 0x72, 0x65, + 0x74, 0x79, 0x70, 0x65, 0x67, 0x75, 0x69, 0x6E, + 0x74, 0x38, 0x5F, 0x74, 0xA4, 0x62, 0x69, 0x64, + 0x04, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x78, 0x18, + 0x42, 0x6C, 0x6F, 0x62, 0x50, 0x61, 0x72, 0x61, + 0x6D, 0x73, 0x57, 0x69, 0x74, 0x68, 0x42, 0x6C, + 0x6F, 0x62, 0x52, 0x65, 0x74, 0x75, 0x72, 0x6E, + 0x6A, 0x70, 0x61, 0x72, 0x61, 0x6D, 0x65, 0x74, + 0x65, 0x72, 0x73, 0x81, 0xA3, 0x62, 0x69, 0x64, + 0x00, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x64, 0x44, + 0x61, 0x74, 0x61, 0x64, 0x74, 0x79, 0x70, 0x65, + 0x64, 0x62, 0x6C, 0x6F, 0x62, 0x6B, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x5F, 0x74, 0x79, 0x70, - 0x65, 0x67, 0x69, 0x6E, 0x74, 0x33, 0x32, 0x5F, - 0x74, 0xA4, 0x62, 0x69, 0x64, 0x02, 0x64, 0x6E, - 0x61, 0x6D, 0x65, 0x72, 0x41, 0x72, 0x72, 0x61, - 0x79, 0x50, 0x61, 0x72, 0x61, 0x6D, 0x4E, 0x6F, - 0x52, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x6A, 0x70, - 0x61, 0x72, 0x61, 0x6D, 0x65, 0x74, 0x65, 0x72, - 0x73, 0x81, 0xA3, 0x62, 0x69, 0x64, 0x00, 0x64, - 0x6E, 0x61, 0x6D, 0x65, 0x65, 0x4C, 0x61, 0x62, - 0x65, 0x6C, 0x64, 0x74, 0x79, 0x70, 0x65, 0x68, - 0x63, 0x68, 0x61, 0x72, 0x5B, 0x36, 0x34, 0x5D, - 0x6B, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x5F, - 0x74, 0x79, 0x70, 0x65, 0x64, 0x76, 0x6F, 0x69, - 0x64, 0xA4, 0x62, 0x69, 0x64, 0x03, 0x64, 0x6E, - 0x61, 0x6D, 0x65, 0x75, 0x4D, 0x69, 0x78, 0x65, - 0x64, 0x50, 0x61, 0x72, 0x61, 0x6D, 0x73, 0x57, - 0x69, 0x74, 0x68, 0x52, 0x65, 0x74, 0x75, 0x72, + 0x65, 0x64, 0x62, 0x6C, 0x6F, 0x62, 0xA4, 0x62, + 0x69, 0x64, 0x05, 0x64, 0x6E, 0x61, 0x6D, 0x65, + 0x70, 0x4C, 0x61, 0x72, 0x67, 0x65, 0x41, 0x72, + 0x72, 0x61, 0x79, 0x52, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x6A, 0x70, 0x61, 0x72, 0x61, 0x6D, 0x65, - 0x74, 0x65, 0x72, 0x73, 0x82, 0xA3, 0x62, 0x69, - 0x64, 0x00, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x64, - 0x4E, 0x61, 0x6D, 0x65, 0x64, 0x74, 0x79, 0x70, - 0x65, 0x68, 0x63, 0x68, 0x61, 0x72, 0x5B, 0x33, - 0x32, 0x5D, 0xA3, 0x62, 0x69, 0x64, 0x01, 0x64, - 0x6E, 0x61, 0x6D, 0x65, 0x65, 0x56, 0x61, 0x6C, - 0x75, 0x65, 0x64, 0x74, 0x79, 0x70, 0x65, 0x65, - 0x66, 0x6C, 0x6F, 0x61, 0x74, 0x6B, 0x72, 0x65, + 0x74, 0x65, 0x72, 0x73, 0x80, 0x6B, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x5F, 0x74, 0x79, 0x70, - 0x65, 0x67, 0x75, 0x69, 0x6E, 0x74, 0x38, 0x5F, - 0x74, 0xA4, 0x62, 0x69, 0x64, 0x04, 0x64, 0x6E, - 0x61, 0x6D, 0x65, 0x78, 0x18, 0x42, 0x6C, 0x6F, - 0x62, 0x50, 0x61, 0x72, 0x61, 0x6D, 0x73, 0x57, - 0x69, 0x74, 0x68, 0x42, 0x6C, 0x6F, 0x62, 0x52, - 0x65, 0x74, 0x75, 0x72, 0x6E, 0x6A, 0x70, 0x61, - 0x72, 0x61, 0x6D, 0x65, 0x74, 0x65, 0x72, 0x73, - 0x81, 0xA3, 0x62, 0x69, 0x64, 0x00, 0x64, 0x6E, - 0x61, 0x6D, 0x65, 0x64, 0x44, 0x61, 0x74, 0x61, - 0x64, 0x74, 0x79, 0x70, 0x65, 0x64, 0x62, 0x6C, - 0x6F, 0x62, 0x6B, 0x72, 0x65, 0x74, 0x75, 0x72, - 0x6E, 0x5F, 0x74, 0x79, 0x70, 0x65, 0x64, 0x62, - 0x6C, 0x6F, 0x62, 0xA4, 0x62, 0x69, 0x64, 0x05, - 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x70, 0x4C, 0x61, - 0x72, 0x67, 0x65, 0x41, 0x72, 0x72, 0x61, 0x79, - 0x52, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x6A, 0x70, - 0x61, 0x72, 0x61, 0x6D, 0x65, 0x74, 0x65, 0x72, - 0x73, 0x80, 0x6B, 0x72, 0x65, 0x74, 0x75, 0x72, - 0x6E, 0x5F, 0x74, 0x79, 0x70, 0x65, 0x6C, 0x75, - 0x69, 0x6E, 0x74, 0x38, 0x5F, 0x74, 0x5B, 0x32, - 0x35, 0x36, 0x5D, 0x65, 0x65, 0x6E, 0x75, 0x6D, - 0x73, 0x82, 0xA3, 0x62, 0x69, 0x64, 0x70, 0x45, - 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x45, 0x6E, - 0x75, 0x6D, 0x43, 0x6C, 0x61, 0x73, 0x73, 0x69, - 0x62, 0x61, 0x73, 0x65, 0x5F, 0x74, 0x79, 0x70, - 0x65, 0x67, 0x75, 0x69, 0x6E, 0x74, 0x38, 0x5F, - 0x74, 0x66, 0x76, 0x61, 0x6C, 0x75, 0x65, 0x73, - 0xA3, 0x66, 0x56, 0x41, 0x4C, 0x55, 0x45, 0x31, - 0x00, 0x66, 0x56, 0x41, 0x4C, 0x55, 0x45, 0x32, - 0x01, 0x66, 0x56, 0x41, 0x4C, 0x55, 0x45, 0x33, - 0x02, 0xA4, 0x62, 0x69, 0x64, 0x72, 0x45, 0x78, - 0x61, 0x6D, 0x70, 0x6C, 0x65, 0x42, 0x69, 0x74, - 0x6D, 0x61, 0x73, 0x6B, 0x45, 0x6E, 0x75, 0x6D, - 0x69, 0x62, 0x61, 0x73, 0x65, 0x5F, 0x74, 0x79, - 0x70, 0x65, 0x67, 0x75, 0x69, 0x6E, 0x74, 0x38, - 0x5F, 0x74, 0x67, 0x62, 0x69, 0x74, 0x6D, 0x61, - 0x73, 0x6B, 0xF5, 0x66, 0x76, 0x61, 0x6C, 0x75, - 0x65, 0x73, 0xA3, 0x66, 0x56, 0x41, 0x4C, 0x55, - 0x45, 0x31, 0x00, 0x66, 0x56, 0x41, 0x4C, 0x55, - 0x45, 0x32, 0x01, 0x66, 0x56, 0x41, 0x4C, 0x55, - 0x45, 0x33, 0x02 + 0x65, 0x6C, 0x75, 0x69, 0x6E, 0x74, 0x38, 0x5F, + 0x74, 0x5B, 0x32, 0x35, 0x36, 0x5D, 0x65, 0x65, + 0x6E, 0x75, 0x6D, 0x73, 0x82, 0xA3, 0x62, 0x69, + 0x64, 0x70, 0x45, 0x78, 0x61, 0x6D, 0x70, 0x6C, + 0x65, 0x45, 0x6E, 0x75, 0x6D, 0x43, 0x6C, 0x61, + 0x73, 0x73, 0x69, 0x62, 0x61, 0x73, 0x65, 0x5F, + 0x74, 0x79, 0x70, 0x65, 0x67, 0x75, 0x69, 0x6E, + 0x74, 0x38, 0x5F, 0x74, 0x66, 0x76, 0x61, 0x6C, + 0x75, 0x65, 0x73, 0xA3, 0x66, 0x56, 0x41, 0x4C, + 0x55, 0x45, 0x31, 0x00, 0x66, 0x56, 0x41, 0x4C, + 0x55, 0x45, 0x32, 0x01, 0x66, 0x56, 0x41, 0x4C, + 0x55, 0x45, 0x33, 0x02, 0xA4, 0x62, 0x69, 0x64, + 0x72, 0x45, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, + 0x42, 0x69, 0x74, 0x6D, 0x61, 0x73, 0x6B, 0x45, + 0x6E, 0x75, 0x6D, 0x69, 0x62, 0x61, 0x73, 0x65, + 0x5F, 0x74, 0x79, 0x70, 0x65, 0x67, 0x75, 0x69, + 0x6E, 0x74, 0x38, 0x5F, 0x74, 0x67, 0x62, 0x69, + 0x74, 0x6D, 0x61, 0x73, 0x6B, 0xF5, 0x66, 0x76, + 0x61, 0x6C, 0x75, 0x65, 0x73, 0xA3, 0x66, 0x56, + 0x41, 0x4C, 0x55, 0x45, 0x31, 0x00, 0x66, 0x56, + 0x41, 0x4C, 0x55, 0x45, 0x32, 0x01, 0x66, 0x56, + 0x41, 0x4C, 0x55, 0x45, 0x33, 0x02 }; // Blocks that did not fit into the advertisement; served on request @@ -271,7 +280,11 @@ class ServiceTemplateBase : public xbot::service::Service { /*[[[cog # Generate callback functions for each input. for input in service["inputs"]: - if input['is_array']: + if input['is_blob']: + cog.outl(f"virtual void {input['callback_name']}(const uint8_t* new_value, uint32_t length) {{") + cog.outl(" (void)new_value;") + cog.outl(" (void)length;") + elif input['is_array']: cog.outl(f"virtual void {input['callback_name']}(const {input['type']}* new_value, uint32_t length) {{") cog.outl(" (void)new_value;") cog.outl(" (void)length;") @@ -289,17 +302,25 @@ class ServiceTemplateBase : public xbot::service::Service { (void)new_value; } + virtual void OnExampleInputBlobChanged(const uint8_t* new_value, uint32_t length) { + (void)new_value; + (void)length; + } + //[[[end]]] /*[[[cog # Generate send functions for each output. for output in service["outputs"]: - if output['is_array']: + if output['is_blob']: + cog.outl(f"bool {output['send_method_name']}(const uint8_t* data, uint32_t length);") + elif output['is_array']: cog.outl(f"bool {output['send_method_name']}(const {output['type']}* data, uint32_t length);") else: cog.outl(f"bool {output['send_method_name']}(const {output['type']} &data);") ]]]*/ bool SendExampleOutput1(const char* data, uint32_t length); bool SendExampleOutput2(const uint32_t &data); + bool SendExampleOutputBlob(const uint8_t* data, uint32_t length); //[[[end]]] /*[[[cog # Generate register struct @@ -395,6 +416,11 @@ cog.outl(f"\u002f*\n{service['service_json']}\n*\u002f") "id": 1, "name": "ExampleInput2", "type": "uint32_t" + }, + { + "id": 2, + "name": "ExampleInputBlob", + "type": "blob" } ], "outputs": [ @@ -407,6 +433,11 @@ cog.outl(f"\u002f*\n{service['service_json']}\n*\u002f") "id": 1, "name": "ExampleOutput2", "type": "uint32_t" + }, + { + "id": 2, + "name": "ExampleOutputBlob", + "type": "blob" } ], "registers": [ diff --git a/codegen/templates/service.json b/codegen/templates/service.json index fe3ac7f..4b426bb 100644 --- a/codegen/templates/service.json +++ b/codegen/templates/service.json @@ -11,6 +11,11 @@ "id": 1, "name": "ExampleInput2", "type": "uint32_t" + }, + { + "id": 2, + "name": "ExampleInputBlob", + "type": "blob" } ], "outputs": [ @@ -23,6 +28,11 @@ "id": 1, "name": "ExampleOutput2", "type": "uint32_t" + }, + { + "id": 2, + "name": "ExampleOutputBlob", + "type": "blob" } ], "registers": [ diff --git a/codegen/xbot_codegen/xbot_codegen.py b/codegen/xbot_codegen/xbot_codegen.py index 97e8641..60cc261 100644 --- a/codegen/xbot_codegen/xbot_codegen.py +++ b/codegen/xbot_codegen/xbot_codegen.py @@ -133,6 +133,7 @@ def common_attrs(json, valid_types, callback_name, send_method_name): "id": id, "name": name, "type": type, + "is_blob": type == "blob", "callback_name": callback_name.format(name), "send_method_name": send_method_name.format(name), **array_type_attrs(max_length) @@ -235,7 +236,7 @@ def loadService(path: str) -> dict: # Transform the input definitions seen_input_names = set() for json_input in json_service["inputs"]: - input = common_attrs(json_input, valid_types, "On{}Changed", "Send{}") + input = common_attrs(json_input, valid_types + ["blob"], "On{}Changed", "Send{}") if input["name"] in seen_input_names: raise Exception( f"Duplicate normalized input name '{input['name']}' " @@ -246,7 +247,7 @@ def loadService(path: str) -> dict: # Transform the output definitions seen_output_names = set() for json_output in json_service["outputs"]: - output = common_attrs(json_output, valid_types, "On{}Changed", "Send{}") + output = common_attrs(json_output, valid_types + ["blob"], "On{}Changed", "Send{}") if output["name"] in seen_output_names: raise Exception( f"Duplicate normalized output name '{output['name']}' " diff --git a/xbot_service_interface_go/codegen/generate_test.go b/xbot_service_interface_go/codegen/generate_test.go index 79fa05f..8e49c55 100644 --- a/xbot_service_interface_go/codegen/generate_test.go +++ b/xbot_service_interface_go/codegen/generate_test.go @@ -57,7 +57,7 @@ func TestLoadRejects(t *testing.T) { cases := map[string]string{ "missing type": `{"version": 1}`, "unknown type": `{"type": "X", "version": 1, "inputs": [{"id": 0, "name": "A", "type": "uint7_t"}]}`, - "blob as input": `{"type": "X", "version": 1, "inputs": [{"id": 0, "name": "A", "type": "blob"}]}`, + "blob array": `{"type": "X", "version": 1, "inputs": [{"id": 0, "name": "A", "type": "blob[4]"}]}`, "duplicate ids": `{"type": "X", "version": 1, "inputs": [{"id": 1, "name": "A", "type": "uint8_t"}, {"id": 1, "name": "B", "type": "uint8_t"}]}`, "name collision": `{"type": "X", "version": 1, "inputs": [{"id": 0, "name": "My Input", "type": "uint8_t"}, {"id": 1, "name": "MyInput", "type": "uint8_t"}]}`, "unknown enum base": `{"type": "X", "version": 1, "enums": [{"id": "E", "base_type": "uint7_t", "values": {"A": 0}}]}`, @@ -128,6 +128,25 @@ func TestBlobParameters(t *testing.T) { } } +// TestBlobInputOutput pins that blob is accepted for inputs and outputs: the data +// path already carries a pointer and a length, only the schema rejected it. +func TestBlobInputOutput(t *testing.T) { + path := t.TempDir() + "/service.json" + schema := `{"type": "X", "version": 1, + "inputs": [{"id": 0, "name": "Data", "type": "blob"}], + "outputs": [{"id": 0, "name": "Extra", "type": "blob"}]}` + if err := os.WriteFile(path, []byte(schema), 0o644); err != nil { + t.Fatal(err) + } + s, err := Load(path) + if err != nil { + t.Fatalf("blob input/output rejected: %v", err) + } + if _, err := Generate(s, Options{}); err != nil { + t.Fatalf("Generate: %v", err) + } +} + // TestNumericArrays pins that numeric arrays (T[n]) are supported: they are // padded to n elements on send and decoded from n elements on receive. func TestNumericArrays(t *testing.T) { diff --git a/xbot_service_interface_go/codegen/schema.go b/xbot_service_interface_go/codegen/schema.go index c70f2ad..20e1e36 100644 --- a/xbot_service_interface_go/codegen/schema.go +++ b/xbot_service_interface_go/codegen/schema.go @@ -132,16 +132,14 @@ func (s *Schema) validate() error { for _, set := range []struct { what string fields []Field - blob bool }{ - {"input", s.Inputs, false}, {"output", s.Outputs, false}, {"register", s.Registers, true}, + {"input", s.Inputs}, {"output", s.Outputs}, {"register", s.Registers}, } { for _, f := range set.fields { base, _, isArray := splitType(f.Type) if base == "blob" { - if !set.blob { - return fmt.Errorf("%s %s: \"blob\" is only allowed for registers", set.what, f.Name) - } + // Variable length, same rule as the C++ generator: allowed for + // inputs, outputs and registers, but never as an array. if isArray { return fmt.Errorf("%s %s: \"blob\" cannot be an array", set.what, f.Name) } From 4108e65d6cdc76f801a7d4a670813fde9e685e4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Ebeling?= Date: Sat, 14 Nov 2026 20:29:00 +0100 Subject: [PATCH 06/28] feat(codegen): emit the frame budget for blob parameters A client that chunks a blob, has to know how many bytes still fit into one packet. That number depends on the framing of the one call: a descriptor per parameter plus the payloads of the fixed parameters. Every blob parameter gets a helper, with the other variable parameters as arguments, generated for the Go client and as a constexpr member for the C++ interface: --- Readme.md | 4 + .../templates/ServiceInterfaceTemplate.hpp | 31 ++++++++ .../codegen/generate_test.go | 12 ++- xbot_service_interface_go/codegen/render.go | 73 +++++++++++++++++++ 4 files changed, 118 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 4f9456b..88b73d7 100644 --- a/Readme.md +++ b/Readme.md @@ -279,6 +279,10 @@ clients have to be updated together. **Generated API (interface side — same JSON, different template):** - Inputs and outputs swap roles: outputs become callbacks, inputs become send methods. +- Every `blob` parameter gets a frame budget helper, e.g. `MaxFileWriteData(PathLen)` in C++ and + `MaxFileWriteData(Path []byte)` in Go: how many bytes the parameter can carry in one call, with the + other blob parameters as arguments. Chunking a value needs exactly that number, and the framing that + limits it belongs to the generator, not to every client. **CMake integration:** ```cmake diff --git a/codegen/templates/ServiceInterfaceTemplate.hpp b/codegen/templates/ServiceInterfaceTemplate.hpp index 90419a4..6fb4434 100644 --- a/codegen/templates/ServiceInterfaceTemplate.hpp +++ b/codegen/templates/ServiceInterfaceTemplate.hpp @@ -18,6 +18,7 @@ cog.outl(f"#define {service['interface_class_name'].upper()}_HPP") #include #include +#include /*[[[cog xbot_codegen.generateEnums(service) @@ -93,6 +94,36 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas bool CallLargeArrayReturn(uint8_t* data, uint16_t& result_length, uint32_t timeout_ms = 1000); //[[[end]]] + /*[[[cog + # A blob parameter is chunked by the caller, so the frame budget belongs next to the + # call that has the limit: one packet of body minus the framing of the call. + for func in service["functions"]: + blobs = [p for p in func["parameters"] if p['is_blob']] + if not blobs: + continue + fixed = sum( + (p['max_length'] * xbot_codegen.typeSize(service, p['type'])) if p['is_array'] + else xbot_codegen.typeSize(service, p['type']) + for p in func["parameters"] if not p['is_blob']) + for target in blobs: + others = [p for p in blobs if p['name'] != target['name']] + args = ", ".join(f"size_t {p['name']}Len" for p in others) + subtract = "".join(f" - {p['name']}Len" for p in others) + fixed_part = f" - {fixed}" if fixed else "" + name = f"Max{func['name']}{target['name']}" + cog.outl(f" // {name} is the largest {target['name']} payload one {func['name']} call can carry.") + cog.outl(f" static constexpr size_t {name}({args}) {{") + cog.outl(" return xbot::config::max_packet_size - sizeof(xbot::datatypes::XbotHeader) -") + cog.outl(f" {len(func['parameters'])} * sizeof(xbot::datatypes::DataDescriptor){fixed_part}{subtract};") + cog.outl(" }") + ]]]*/ + // MaxBlobParamsWithBlobReturnData is the largest Data payload one BlobParamsWithBlobReturn call can carry. + static constexpr size_t MaxBlobParamsWithBlobReturnData() { + return xbot::config::max_packet_size - sizeof(xbot::datatypes::XbotHeader) - + 1 * sizeof(xbot::datatypes::DataDescriptor); + } + //[[[end]]] + /*[[[cog # Generate send functions for each register. for register in service["registers"]: diff --git a/xbot_service_interface_go/codegen/generate_test.go b/xbot_service_interface_go/codegen/generate_test.go index 8e49c55..756a21b 100644 --- a/xbot_service_interface_go/codegen/generate_test.go +++ b/xbot_service_interface_go/codegen/generate_test.go @@ -97,7 +97,11 @@ func TestBlobParameters(t *testing.T) { {"id": 0, "name": "Echo", "return_type": "blob", "parameters": [{"id": 0, "name": "Data", "type": "blob"}]}, {"id": 1, "name": "Write", "return_type": "int32_t", - "parameters": [{"id": 0, "name": "Path", "type": "blob"}]}]}` + "parameters": [ + {"id": 0, "name": "Path", "type": "blob"}, + {"id": 1, "name": "Offset", "type": "uint32_t"}, + {"id": 2, "name": "Data", "type": "blob"}, + {"id": 3, "name": "Hash", "type": "uint32_t"}]}]}` if err := os.WriteFile(path, []byte(schema), 0o644); err != nil { t.Fatal(err) } @@ -111,10 +115,14 @@ func TestBlobParameters(t *testing.T) { } for _, want := range []string{ "func (c *Client) Echo(ctx context.Context, Data []byte) ([]byte, error)", - "func (c *Client) Write(ctx context.Context, Path []byte) (int32, error)", + "func (c *Client) Write(ctx context.Context, Path []byte, Offset uint32, Data []byte, Hash uint32) (int32, error)", "xbot.Bytes(0, Data)", "xbot.Bytes(0, Path)", "return append([]byte(nil), payload...)", + // One helper per blob parameter, with the framing of this call subtracted. + "func MaxEchoData() int {", + "func MaxWriteData(Path []byte) int {", + "return xbot.MaxPacketSize - xbot.HeaderSize - 4*xbot.DescriptorSize - 8 - len(Path)", } { if !bytes.Contains(src, []byte(want)) { t.Errorf("generated code does not contain %q", want) diff --git a/xbot_service_interface_go/codegen/render.go b/xbot_service_interface_go/codegen/render.go index fa6217c..e00851a 100644 --- a/xbot_service_interface_go/codegen/render.go +++ b/xbot_service_interface_go/codegen/render.go @@ -97,6 +97,7 @@ func (g *generator) run() error { return err } } + g.emitFrameBudgets() for _, r := range s.Registers { if err := g.emitRegister(r); err != nil { return err @@ -177,6 +178,78 @@ type charCheck struct { length int } +// paramBytes is how many bytes a fixed size parameter occupies on the wire, i.e. what it +// takes away from the budget of a blob parameter of the same call. +func (g *generator) paramBytes(p Parameter) (int, error) { + base, length, isArray := splitType(p.Type) + wire := base + if eb := g.enumBase(base); eb != "" { + wire = eb + } + size, ok := typeSizes[wire] + if base == "char" { + size, ok = 1, true // not in typeSizes: char is the natural character type + } + if !ok { + return 0, fmt.Errorf("codegen: unsupported type %q in parameter %s", p.Type, p.Name) + } + if isArray { + return size * length, nil + } + return size, nil +} + +// emitFrameBudgets writes one helper per blob parameter: the largest payload it can +// carry, given the lengths of the other variable parameters. A caller that chunks a value +// needs exactly this number, and the framing that limits it (one descriptor per parameter +// plus the fixed payloads) is knowledge that belongs here, not in every client. +func (g *generator) emitFrameBudgets() { + for _, fn := range g.schema.Functions { + var blobs []Parameter + fixed := 0 + for _, p := range fn.Parameters { + if base, _, _ := splitType(p.Type); base == "blob" { + blobs = append(blobs, p) + continue + } + if size, err := g.paramBytes(p); err == nil { + fixed += size + } // an unsupported type is reported by emitFunction already + } + if len(blobs) == 0 { + continue + } + + for _, target := range blobs { + targetName := goName(target.Name) + var args []string + var variable strings.Builder + for _, other := range blobs { + if other.Name == target.Name { + continue + } + otherName := goName(other.Name) + args = append(args, otherName+" []byte") + variable.WriteString(" - len(" + otherName + ")") + } + + budget := fmt.Sprintf("%d*xbot.DescriptorSize", len(fn.Parameters)) + if fixed > 0 { + budget += fmt.Sprintf(" - %d", fixed) + } + + g.f("// Max%s%s is the largest %s payload one %s call can carry.", fn.Name, targetName, targetName, fn.Name) + g.line("//") + g.line("// One packet of RPC body minus the framing of the call: a descriptor per") + g.line("// parameter and the payloads of the fixed parameters.") + g.f("func Max%s%s(%s) int {", fn.Name, targetName, strings.Join(args, ", ")) + g.f("\treturn xbot.MaxPacketSize - xbot.HeaderSize - %s%s", budget, variable.String()) + g.line("}") + g.line("") + } + } +} + // emitFunction writes one RPC method. func (g *generator) emitFunction(fn Function) error { name := goName(fn.Name) From 228b641ebd0501df7589aa8c2e642b9f996924d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Ebeling?= Date: Sat, 14 Nov 2026 22:20:53 +0100 Subject: [PATCH 07/28] fix(codegen): saturate the frame budgets and normalize the helper names Frame budget helpers subtracted the other parameter lengths from a size_t without a floor, so a call whose parameters use up the whole packet reported a wrapped (huge) budget - or a negative one in Go, where the chunker would compute a negative chunk length: - C++: every subtraction goes through a saturating RemainingBudget(), also for the fixed payloads of a call. A call that cannot carry the value reports 0. - Go: the helper returns max(0, ...). The Go helper identifier was built from the raw RPC name, so an RPC called "Write Data" emitted `func MaxWrite DataData()`, which broke formatting. It is built from goName() now, and the helper names are reserved during schema validation: Write(PathData blob) and WritePath(Data blob) both generate MaxWritePathData and are rejected instead of emitting duplicate declarations. --- .../templates/ServiceInterfaceTemplate.hpp | 46 +++++++++++++++---- .../codegen/generate_test.go | 34 +++++++++++++- xbot_service_interface_go/codegen/render.go | 12 +++-- .../codegen/validate_names.go | 12 +++++ 4 files changed, 88 insertions(+), 16 deletions(-) diff --git a/codegen/templates/ServiceInterfaceTemplate.hpp b/codegen/templates/ServiceInterfaceTemplate.hpp index 6fb4434..ba48ae9 100644 --- a/codegen/templates/ServiceInterfaceTemplate.hpp +++ b/codegen/templates/ServiceInterfaceTemplate.hpp @@ -96,11 +96,25 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas /*[[[cog # A blob parameter is chunked by the caller, so the frame budget belongs next to the - # call that has the limit: one packet of body minus the framing of the call. - for func in service["functions"]: + # call that has the limit: one packet of body minus the framing of the call. Every + # subtraction saturates, so a call whose parameters use up the whole packet reports 0 + # instead of a wrapped (huge) budget. + blob_funcs = [f for f in service["functions"] if any(p['is_blob'] for p in f["parameters"])] + if blob_funcs: + cog.outl(" // Saturating subtraction for the frame budgets below: a call whose parameters") + cog.outl(" // use up the whole packet reports 0 instead of a wrapped (huge) budget.") + cog.outl(" static constexpr size_t RemainingBudget(size_t budget) {") + cog.outl(" return budget;") + cog.outl(" }") + cog.outl(" static constexpr size_t RemainingBudget(size_t budget, size_t used) {") + cog.outl(" return (used < budget) ? (budget - used) : 0;") + cog.outl(" }") + cog.outl(" template ") + cog.outl(" static constexpr size_t RemainingBudget(size_t budget, size_t used, Rest... rest) {") + cog.outl(" return RemainingBudget((used < budget) ? (budget - used) : 0, rest...);") + cog.outl(" }") + for func in blob_funcs: blobs = [p for p in func["parameters"] if p['is_blob']] - if not blobs: - continue fixed = sum( (p['max_length'] * xbot_codegen.typeSize(service, p['type'])) if p['is_array'] else xbot_codegen.typeSize(service, p['type']) @@ -108,19 +122,31 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas for target in blobs: others = [p for p in blobs if p['name'] != target['name']] args = ", ".join(f"size_t {p['name']}Len" for p in others) - subtract = "".join(f" - {p['name']}Len" for p in others) - fixed_part = f" - {fixed}" if fixed else "" + frame = (f"xbot::config::max_packet_size - sizeof(xbot::datatypes::XbotHeader) - " + f"{len(func['parameters'])} * sizeof(xbot::datatypes::DataDescriptor)") + used = ([f"static_cast({fixed})"] if fixed else []) + [f"{p['name']}Len" for p in others] + budget = f"RemainingBudget({frame}, " + ", ".join(used) + ")" if used else frame name = f"Max{func['name']}{target['name']}" cog.outl(f" // {name} is the largest {target['name']} payload one {func['name']} call can carry.") cog.outl(f" static constexpr size_t {name}({args}) {{") - cog.outl(" return xbot::config::max_packet_size - sizeof(xbot::datatypes::XbotHeader) -") - cog.outl(f" {len(func['parameters'])} * sizeof(xbot::datatypes::DataDescriptor){fixed_part}{subtract};") + cog.outl(f" return {budget};") cog.outl(" }") ]]]*/ + // Saturating subtraction for the frame budgets below: a call whose parameters + // use up the whole packet reports 0 instead of a wrapped (huge) budget. + static constexpr size_t RemainingBudget(size_t budget) { + return budget; + } + static constexpr size_t RemainingBudget(size_t budget, size_t used) { + return (used < budget) ? (budget - used) : 0; + } + template + static constexpr size_t RemainingBudget(size_t budget, size_t used, Rest... rest) { + return RemainingBudget((used < budget) ? (budget - used) : 0, rest...); + } // MaxBlobParamsWithBlobReturnData is the largest Data payload one BlobParamsWithBlobReturn call can carry. static constexpr size_t MaxBlobParamsWithBlobReturnData() { - return xbot::config::max_packet_size - sizeof(xbot::datatypes::XbotHeader) - - 1 * sizeof(xbot::datatypes::DataDescriptor); + return xbot::config::max_packet_size - sizeof(xbot::datatypes::XbotHeader) - 1 * sizeof(xbot::datatypes::DataDescriptor); } //[[[end]]] diff --git a/xbot_service_interface_go/codegen/generate_test.go b/xbot_service_interface_go/codegen/generate_test.go index 756a21b..9cea5e3 100644 --- a/xbot_service_interface_go/codegen/generate_test.go +++ b/xbot_service_interface_go/codegen/generate_test.go @@ -69,6 +69,11 @@ func TestLoadRejects(t *testing.T) { "functions normalize equal": `{"type": "X", "version": 1, "functions": [ {"id": 0, "name": "SoundId", "return_type": "void"}, {"id": 1, "name": "SoundID", "return_type": "void"}]}`, + "blob budget helpers collide": `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "Write", "return_type": "void", + "parameters": [{"id": 0, "name": "PathData", "type": "blob"}]}, + {"id": 1, "name": "WritePath", "return_type": "void", + "parameters": [{"id": 0, "name": "Data", "type": "blob"}]}]}`, "enum values normalize equal": `{"type": "X", "version": 1, "enums": [{"id": "E", "base_type": "uint8_t", "values": {"IDLE": 0, "Idle": 1}}]}`, "enum types normalize equal": `{"type": "X", "version": 1, "enums": [ @@ -120,9 +125,11 @@ func TestBlobParameters(t *testing.T) { "xbot.Bytes(0, Path)", "return append([]byte(nil), payload...)", // One helper per blob parameter, with the framing of this call subtracted. + // The budget saturates: a call whose other parameters use up the packet has + // no room left for this one, and a negative int is not a budget. "func MaxEchoData() int {", "func MaxWriteData(Path []byte) int {", - "return xbot.MaxPacketSize - xbot.HeaderSize - 4*xbot.DescriptorSize - 8 - len(Path)", + "return max(0, xbot.MaxPacketSize-xbot.HeaderSize-4*xbot.DescriptorSize-8-len(Path))", } { if !bytes.Contains(src, []byte(want)) { t.Errorf("generated code does not contain %q", want) @@ -136,7 +143,30 @@ func TestBlobParameters(t *testing.T) { } } -// TestBlobInputOutput pins that blob is accepted for inputs and outputs: the data +// TestBlobHelperNames pins the identifier of the frame budget helper: it is built +// from the normalized RPC name, not from the raw one, or an RPC called "Write Data" +// would emit `func MaxWrite DataData()` and Generate would fail while formatting. +func TestBlobHelperNames(t *testing.T) { + path := t.TempDir() + "/service.json" + schema := `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "Write Data", "return_type": "int32_t", + "parameters": [{"id": 0, "name": "Data", "type": "blob"}]}]}` + if err := os.WriteFile(path, []byte(schema), 0o644); err != nil { + t.Fatal(err) + } + s, err := Load(path) + if err != nil { + t.Fatalf("Load: %v", err) + } + src, err := Generate(s, Options{}) + if err != nil { + t.Fatalf("Generate: %v", err) + } + if !bytes.Contains(src, []byte("func MaxWriteDataData() int {")) { + t.Errorf("generated code does not contain the normalized helper name: %s", src) + } +} + // path already carries a pointer and a length, only the schema rejected it. func TestBlobInputOutput(t *testing.T) { path := t.TempDir() + "/service.json" diff --git a/xbot_service_interface_go/codegen/render.go b/xbot_service_interface_go/codegen/render.go index e00851a..8f94e64 100644 --- a/xbot_service_interface_go/codegen/render.go +++ b/xbot_service_interface_go/codegen/render.go @@ -220,6 +220,9 @@ func (g *generator) emitFrameBudgets() { continue } + // The helper name is built from the normalized RPC name: an RPC may be called + // "Write Data" with a parameter "Data", and MaxWrite DataData is not an identifier. + fnName := goName(fn.Name) for _, target := range blobs { targetName := goName(target.Name) var args []string @@ -238,12 +241,13 @@ func (g *generator) emitFrameBudgets() { budget += fmt.Sprintf(" - %d", fixed) } - g.f("// Max%s%s is the largest %s payload one %s call can carry.", fn.Name, targetName, targetName, fn.Name) + g.f("// Max%s%s is the largest %s payload one %s call can carry.", fnName, targetName, targetName, fnName) g.line("//") g.line("// One packet of RPC body minus the framing of the call: a descriptor per") - g.line("// parameter and the payloads of the fixed parameters.") - g.f("func Max%s%s(%s) int {", fn.Name, targetName, strings.Join(args, ", ")) - g.f("\treturn xbot.MaxPacketSize - xbot.HeaderSize - %s%s", budget, variable.String()) + g.line("// parameter and the payloads of the fixed parameters. A call whose parameters") + g.line("// already use up the packet reports 0, never a negative budget.") + g.f("func Max%s%s(%s) int {", fnName, targetName, strings.Join(args, ", ")) + g.f("\treturn max(0, xbot.MaxPacketSize - xbot.HeaderSize - %s%s)", budget, variable.String()) g.line("}") g.line("") } diff --git a/xbot_service_interface_go/codegen/validate_names.go b/xbot_service_interface_go/codegen/validate_names.go index c0545fe..d212b35 100644 --- a/xbot_service_interface_go/codegen/validate_names.go +++ b/xbot_service_interface_go/codegen/validate_names.go @@ -52,6 +52,18 @@ func (s *Schema) validateGeneratedNames() error { if err := reserve(method, name, "function "+fn.Name); err != nil { return err } + // A blob parameter's frame budget helper is a package level function too, and + // distinct RPC names can produce the same one: Write(Path blob) and + // WritePath(Data blob) both give MaxWritePathData. + for _, p := range fn.Parameters { + if base, _, _ := splitType(p.Type); base != "blob" { + continue + } + what := "the frame budget helper of parameter " + p.Name + " of function " + fn.Name + if err := reserve(pkg, "Max"+name+goName(p.Name), what); err != nil { + return err + } + } } for _, r := range s.Registers { if err := reserve(method, "Set"+goName(r.Name), "register "+r.Name); err != nil { From f1d89ace9460f389fdfc28f9c4e968fd3afacca5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Ebeling?= Date: Sat, 14 Nov 2026 22:20:55 +0100 Subject: [PATCH 08/28] docs(readme): clarify the frame budget and the empty lease cases The budget is an upper bound: a chunk is min(bytes left, budget) long, and a saturated helper reports 0 so a chunker stops instead of sending. acquire() also returns an empty lease when the pool has no storage yet or the request exceeds a block, not only when every block is out. --- Readme.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/Readme.md b/Readme.md index 88b73d7..4e62c4f 100644 --- a/Readme.md +++ b/Readme.md @@ -282,7 +282,9 @@ clients have to be updated together. - Every `blob` parameter gets a frame budget helper, e.g. `MaxFileWriteData(PathLen)` in C++ and `MaxFileWriteData(Path []byte)` in Go: how many bytes the parameter can carry in one call, with the other blob parameters as arguments. Chunking a value needs exactly that number, and the framing that - limits it belongs to the generator, not to every client. + limits it belongs to the generator, not to every client. The helpers saturate: a call whose other + parameters already use up the packet reports 0, so a chunker has to stop instead of sending. Every + chunk is `min(bytes left, budget)` long - the budget is an upper bound, only the last chunk is shorter. **CMake integration:** ```cmake @@ -323,10 +325,11 @@ Rules that keep the pool usable: - A lease is **move-only** and returns its block in the destructor. Do not keep it beyond the call that borrowed it: the pool is shared by all services, and a lease held across a flash operation or across RPCs starves the next caller. -- `acquire()` is **non-blocking** on purpose. It returns an empty lease only when every block is out, - and then the service answers BUSY - an RPC handler must never wait for another service's transfer. - With the default of two blocks, one outstanding return does not exhaust the pool. A block is only held - while a return value is filled and copied into a packet. +- `acquire()` is **non-blocking** on purpose. It returns an empty lease when every block is out, when + no storage has been configured yet, and when the request is larger than a block; a handler that + follows the pattern above answers BUSY in all three cases - an RPC handler must never wait for + another service's transfer. With the default of two blocks, one outstanding return does not exhaust + the pool. A block is only held while a return value is filled and copied into a packet. - Release happens after the handler returned; `SendRpcResponse()` copies the payload into a packet. - No heap is involved: the storage is static. From f01e043fc6812e21c108aa1cd47e549814c60b9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Ebeling?= Date: Sun, 15 Nov 2026 17:13:56 +0100 Subject: [PATCH 09/28] fix(codegen): prevent size_t underflow in payload budget calculation Move descriptor framing overhead into RemainingBudget so the packet size is never subtracted directly. A call with many parameters can require more bytes for descriptors than a packet holds, causing the old subtraction to wrap around. Update the generated constant for BlobParamsWithBlobReturnData to use the same guarded helper. --- codegen/templates/ServiceInterfaceTemplate.hpp | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/codegen/templates/ServiceInterfaceTemplate.hpp b/codegen/templates/ServiceInterfaceTemplate.hpp index ba48ae9..edc130d 100644 --- a/codegen/templates/ServiceInterfaceTemplate.hpp +++ b/codegen/templates/ServiceInterfaceTemplate.hpp @@ -122,10 +122,15 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas for target in blobs: others = [p for p in blobs if p['name'] != target['name']] args = ", ".join(f"size_t {p['name']}Len" for p in others) - frame = (f"xbot::config::max_packet_size - sizeof(xbot::datatypes::XbotHeader) - " - f"{len(func['parameters'])} * sizeof(xbot::datatypes::DataDescriptor)") - used = ([f"static_cast({fixed})"] if fixed else []) + [f"{p['name']}Len" for p in others] - budget = f"RemainingBudget({frame}, " + ", ".join(used) + ")" if used else frame + # Everything but the packet itself goes through RemainingBudget, the descriptor + # framing included: a call with 182 parameters needs more bytes for its + # descriptors than a packet has, and that subtraction would wrap as well. + used = [f"sizeof(xbot::datatypes::XbotHeader) + " + f"{len(func['parameters'])} * sizeof(xbot::datatypes::DataDescriptor)"] + if fixed: + used.append(f"static_cast({fixed})") + used += [f"{p['name']}Len" for p in others] + budget = "RemainingBudget(xbot::config::max_packet_size, " + ", ".join(used) + ")" name = f"Max{func['name']}{target['name']}" cog.outl(f" // {name} is the largest {target['name']} payload one {func['name']} call can carry.") cog.outl(f" static constexpr size_t {name}({args}) {{") @@ -146,7 +151,7 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas } // MaxBlobParamsWithBlobReturnData is the largest Data payload one BlobParamsWithBlobReturn call can carry. static constexpr size_t MaxBlobParamsWithBlobReturnData() { - return xbot::config::max_packet_size - sizeof(xbot::datatypes::XbotHeader) - 1 * sizeof(xbot::datatypes::DataDescriptor); + return RemainingBudget(xbot::config::max_packet_size, sizeof(xbot::datatypes::XbotHeader) + 1 * sizeof(xbot::datatypes::DataDescriptor)); } //[[[end]]] From b887f066f1a460abfce91cc0bb5d1943678a0458 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Ebeling?= Date: Sun, 15 Nov 2026 23:20:21 +0100 Subject: [PATCH 10/28] feat(codegen): add a string type for text parameters and returns blob solved variable length, but a handler that hands a value to LittleFS, printf or a JSON parser needs a terminator, so every service copies it into its own char[N] and truncates silently. char[N] has the mirror problem: the dispatcher zero fills it, so a payload that fills all N bytes arrives without a terminator. `string` closes that gap: {"type": "string", "max_length": 128}. The wire layout is the same as blob (a descriptor with the byte length, no padding, no terminator); the schema adds the limit. - server: decoded into char[max_length + 1], a longer payload is answered with RpcStatus::ERROR instead of being shortened, and the handler gets const char* plus the byte count - no copy, no kMaxPath, no truncation - server return: a zero filled buffer of max_length + 1 bytes, large ones come from the buffer pool like other large returns - clients: const char* in and std::string& out (C++), string (Go), str (Python); a value above max_length is refused before sending - the frame budget helpers treat a string as variable length, like a blob The type also closes a gap in the parameter validation: a type[N] parameter was accepted up to 65535 elements although one packet carries 1448 bytes of RPC body and the dispatcher reserves that array on the service thread's stack. The limit for strings and for array parameters is now one packet body minus a descriptor (1440 bytes), in both generators. The demo schema covers a string round trip and a pooled string return, so the generated output shows both paths. Existing schemas generate identical code. --- Readme.md | 25 ++++- .../templates/ServiceInterfaceTemplate.cpp | 52 ++++++++- .../templates/ServiceInterfaceTemplate.hpp | 42 +++++++- codegen/templates/ServiceTemplate.cpp | 73 ++++++++++++- codegen/templates/ServiceTemplate.hpp | 102 +++++++++++++----- codegen/templates/service.json | 21 ++++ codegen/xbot_codegen/xbot_codegen.py | 56 +++++++++- xbot_service_interface_go/codegen/emit.go | 18 +++- .../codegen/generate_test.go | 40 +++++++ xbot_service_interface_go/codegen/render.go | 27 ++++- xbot_service_interface_go/codegen/schema.go | 39 ++++++- .../codegen/testdata/demo_service.golden.go | 66 +++++++++++- .../codegen/testdata/demo_service.json | 21 ++++ .../testdata/demo_service_noid.golden.go | 66 +++++++++++- .../codegen/validate_names.go | 2 +- .../tests/test_serialization.py | 28 +++++ .../xbot_service_interface/interface.py | 18 +++- .../xbot_service_interface/serialization.py | 16 ++- 18 files changed, 655 insertions(+), 57 deletions(-) diff --git a/Readme.md b/Readme.md index 4e62c4f..e174edf 100644 --- a/Readme.md +++ b/Readme.md @@ -245,7 +245,7 @@ Services are defined in a JSON file. The code generator (`codegen/`) reads this } ``` -**Valid types:** `char`, `uint8_t`, `uint16_t`, `uint32_t`, `uint64_t`, `int8_t`, `int16_t`, `int32_t`, `int64_t`, `float`, `double`, `blob` (registers, inputs, outputs, RPC parameters and RPC return values), or fixed-length arrays of any scalar type as `type[N]`. +**Valid types:** `char`, `uint8_t`, `uint16_t`, `uint32_t`, `uint64_t`, `int8_t`, `int16_t`, `int32_t`, `int64_t`, `float`, `double`, `blob` (registers, inputs, outputs, RPC parameters and RPC return values), `string` (RPC parameters and RPC return values), or fixed-length arrays of any scalar type as `type[N]`. `blob` is variable length: as a parameter it is passed as `(pointer, length)` into the received packet and is not copied, as an input or output it is passed/sent as `(pointer, length)` with the length in bytes, as a @@ -253,12 +253,35 @@ register it is the configuration blob, and as a return value it uses the shared (see [Shared Buffer Pool](#shared-buffer-pool)). A `type[N]` return above 128 bytes is pooled the same way, so a service never reserves stack for a payload it rarely sends. +`string` carries text and keeps the C string handling out of the service: the schema declares a `max_length`, +the wire carries the UTF-8 bytes without a terminator (the same layout as `blob`), and the generated server +decodes it into a checked, always terminated `char[max_length + 1]` before it calls the handler - a longer +payload is answered with `RpcStatus::ERROR` instead of being shortened. The handler gets `const char*` plus the +byte count and can hand it to LittleFS, `printf` or a parser without copying or truncating. Returns work the same +way: the handler fills a buffer of `max_length + 1` bytes and reports the length, clients get `std::string` +(C++), `string` (Go) and `str` (Python). Clients refuse a value above `max_length` before sending. + +The dispatcher reserves `max_length + 1` bytes of stack for the call, so `max_length` is capped at one packet body +minus a descriptor (1440 bytes) and the working area of the service has to be sized for it - the thread watermark +shows what a service really uses. + +```json +{ "id": 3, "name": "PlayMp3", "return_type": "uint8_t", + "parameters": [ { "id": 0, "name": "Path", "type": "string", "max_length": 128 } ] } +``` + +A `char[N]` parameter with the same limit costs one byte less stack, but it is only terminated when the payload +is shorter than N - a value that fills all N bytes arrives without a terminator. + Switching a parameter or return from a fixed `type[N]` to `blob` changes its wire layout, so the service needs a version bump (`"version": 2`). Generated clients refuse a mismatch instead of sending a call with the wrong layout: the C++ and Python clients always compare against the schema they were given, the Go client compares only when `ExpectVersion` is set (generated clients set it, a hand-written one has to do the same). Service and clients have to be updated together. +Moving a `blob` text parameter to `string` keeps the wire layout and needs no bump; moving a `char[N]` one does +(the padding disappears). + **IDs** must be unique within each section (`inputs`, `outputs`, `registers`). **Generated API (service side):** diff --git a/codegen/templates/ServiceInterfaceTemplate.cpp b/codegen/templates/ServiceInterfaceTemplate.cpp index 13ca8b6..d919068 100644 --- a/codegen/templates/ServiceInterfaceTemplate.cpp +++ b/codegen/templates/ServiceInterfaceTemplate.cpp @@ -133,12 +133,16 @@ for func in service["functions"]: for p in func["parameters"]: if p['is_blob']: sig_params.append(f"const uint8_t* {p['name']}, uint32_t {p['name']}Len") + elif p['is_string']: + sig_params.append(f"const char* {p['name']}") elif p['is_array']: sig_params.append(f"const {p['type']}* {p['name']}, uint32_t {p['name']}Len") else: sig_params.append(f"const {p['type']}& {p['name']}") if func['return_is_blob']: sig_params.append("uint8_t* data, uint16_t& result_length") + elif func['return_is_string']: + sig_params.append("std::string& result") elif func['return_is_array']: sig_params.append(f"{func['return_base_type']}* data, uint16_t& result_length") elif func["return_type"] != "void": @@ -151,13 +155,19 @@ for func in service["functions"]: if func["parameters"]: cog.outl(" std::vector params_buf;") for p in func["parameters"]: - if p['is_blob'] or p['is_array']: + if p['is_blob'] or p['is_array'] or p['is_string']: if p['is_blob']: byte_len_expr = f"{p['name']}Len" + elif p['is_string']: + # Text on the wire: the bytes only, the terminator is local. A value + # above the declared limit is refused here instead of on the server. + byte_len_expr = f"strlen({p['name']})" else: byte_len_expr = f"{p['name']}Len * sizeof({p['type']})" cog.outl(f" {{") cog.outl(f" const size_t byte_len = {byte_len_expr};") + if p['is_string']: + cog.outl(f" if (byte_len > {p['max_length']}) return false;") cog.outl(f" const size_t off = params_buf.size();") cog.outl(f" params_buf.resize(off + sizeof(xbot::datatypes::DataDescriptor) + byte_len);") cog.outl(f" auto* desc = reinterpret_cast(params_buf.data() + off);") @@ -183,6 +193,15 @@ for func in service["functions"]: cog.outl(f" const auto r = SendRpc({func['id']}, {params_call}, data, &resp_size, timeout_ms);") cog.outl(f" if (r != RPC_OK) return false;") cog.outl(f" result_length = static_cast(resp_size);") + elif func['return_is_string']: + cog.outl(f" char resp_buf[{func['return_max_length']} + 1] = {{}};") + cog.outl(f" size_t resp_size = {func['return_max_length']};") + cog.outl(f" const auto r = SendRpc({func['id']}, {params_call}, reinterpret_cast(resp_buf), &resp_size," + f" timeout_ms);") + cog.outl(f" if (r != RPC_OK) return false;") + cog.outl(f" if (resp_size > {func['return_max_length']}) return false;") + cog.outl(f" resp_buf[resp_size] = '\\0';") + cog.outl(f" result.assign(resp_buf, resp_size);") elif func['return_is_array']: cog.outl(f" size_t resp_size = result_length * sizeof({func['return_base_type']});") cog.outl(f" const auto r = SendRpc({func['id']}, {params_call}, reinterpret_cast(data), &resp_size, timeout_ms);") @@ -306,4 +325,35 @@ bool ServiceTemplateInterfaceBase::CallLargeArrayReturn(uint8_t* data, uint16_t& result_length = static_cast(resp_size / sizeof(uint8_t)); return true; } +bool ServiceTemplateInterfaceBase::CallStringParamsWithStringReturn(const char* Path, std::string& result, uint32_t timeout_ms) { + std::vector params_buf; + { + const size_t byte_len = strlen(Path); + if (byte_len > 64) return false; + const size_t off = params_buf.size(); + params_buf.resize(off + sizeof(xbot::datatypes::DataDescriptor) + byte_len); + auto* desc = reinterpret_cast(params_buf.data() + off); + desc->target_id = 0; desc->reserved = 0; desc->payload_size = static_cast(byte_len); + if (byte_len > 0 && Path == nullptr) return false; + memcpy(params_buf.data() + off + sizeof(xbot::datatypes::DataDescriptor), Path, byte_len); + } + char resp_buf[96 + 1] = {}; + size_t resp_size = 96; + const auto r = SendRpc(6, params_buf.data(), params_buf.size(), reinterpret_cast(resp_buf), &resp_size, timeout_ms); + if (r != RPC_OK) return false; + if (resp_size > 96) return false; + resp_buf[resp_size] = '\0'; + result.assign(resp_buf, resp_size); + return true; +} +bool ServiceTemplateInterfaceBase::CallLargeStringReturn(std::string& result, uint32_t timeout_ms) { + char resp_buf[200 + 1] = {}; + size_t resp_size = 200; + const auto r = SendRpc(7, nullptr, 0, reinterpret_cast(resp_buf), &resp_size, timeout_ms); + if (r != RPC_OK) return false; + if (resp_size > 200) return false; + resp_buf[resp_size] = '\0'; + result.assign(resp_buf, resp_size); + return true; +} //[[[end]]] diff --git a/codegen/templates/ServiceInterfaceTemplate.hpp b/codegen/templates/ServiceInterfaceTemplate.hpp index edc130d..2cf6fc5 100644 --- a/codegen/templates/ServiceInterfaceTemplate.hpp +++ b/codegen/templates/ServiceInterfaceTemplate.hpp @@ -20,6 +20,8 @@ cog.outl(f"#define {service['interface_class_name'].upper()}_HPP") #include #include +#include + /*[[[cog xbot_codegen.generateEnums(service) ]]]*/ @@ -72,12 +74,16 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas for p in func["parameters"]: if p['is_blob']: params.append(f"const uint8_t* {p['name']}, uint32_t {p['name']}Len") + elif p['is_string']: + params.append(f"const char* {p['name']}") elif p['is_array']: params.append(f"const {p['type']}* {p['name']}, uint32_t {p['name']}Len") else: params.append(f"const {p['type']}& {p['name']}") if func['return_is_blob']: params.append("uint8_t* data, uint16_t& result_length") + elif func['return_is_string']: + params.append("std::string& result") elif func['return_is_array']: params.append(f"{func['return_base_type']}* data, uint16_t& result_length") elif func["return_type"] != "void": @@ -92,6 +98,8 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas bool CallMixedParamsWithReturn(const char* Name, uint32_t NameLen, const float& Value, uint8_t& result, uint32_t timeout_ms = 1000); bool CallBlobParamsWithBlobReturn(const uint8_t* Data, uint32_t DataLen, uint8_t* data, uint16_t& result_length, uint32_t timeout_ms = 1000); bool CallLargeArrayReturn(uint8_t* data, uint16_t& result_length, uint32_t timeout_ms = 1000); + bool CallStringParamsWithStringReturn(const char* Path, std::string& result, uint32_t timeout_ms = 1000); + bool CallLargeStringReturn(std::string& result, uint32_t timeout_ms = 1000); //[[[end]]] /*[[[cog @@ -99,7 +107,10 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas # call that has the limit: one packet of body minus the framing of the call. Every # subtraction saturates, so a call whose parameters use up the whole packet reports 0 # instead of a wrapped (huge) budget. - blob_funcs = [f for f in service["functions"] if any(p['is_blob'] for p in f["parameters"])] + # A string parameter is text: it is sent as its bytes (no terminator) and a variable + # length. Like a blob it therefore uses up budget, but the caller only passes the C + # string, the generated code measures it. + blob_funcs = [f for f in service["functions"] if any(p['is_blob'] or p['is_string'] for p in f["parameters"])] if blob_funcs: cog.outl(" // Saturating subtraction for the frame budgets below: a call whose parameters") cog.outl(" // use up the whole packet reports 0 instead of a wrapped (huge) budget.") @@ -114,11 +125,11 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas cog.outl(" return RemainingBudget((used < budget) ? (budget - used) : 0, rest...);") cog.outl(" }") for func in blob_funcs: - blobs = [p for p in func["parameters"] if p['is_blob']] + blobs = [p for p in func["parameters"] if p['is_blob'] or p['is_string']] fixed = sum( (p['max_length'] * xbot_codegen.typeSize(service, p['type'])) if p['is_array'] else xbot_codegen.typeSize(service, p['type']) - for p in func["parameters"] if not p['is_blob']) + for p in func["parameters"] if not (p['is_blob'] or p['is_string'])) for target in blobs: others = [p for p in blobs if p['name'] != target['name']] args = ", ".join(f"size_t {p['name']}Len" for p in others) @@ -153,6 +164,10 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas static constexpr size_t MaxBlobParamsWithBlobReturnData() { return RemainingBudget(xbot::config::max_packet_size, sizeof(xbot::datatypes::XbotHeader) + 1 * sizeof(xbot::datatypes::DataDescriptor)); } + // MaxStringParamsWithStringReturnPath is the largest Path payload one StringParamsWithStringReturn call can carry. + static constexpr size_t MaxStringParamsWithStringReturnPath() { + return RemainingBudget(xbot::config::max_packet_size, sizeof(xbot::datatypes::XbotHeader) + 1 * sizeof(xbot::datatypes::DataDescriptor)); + } //[[[end]]] /*[[[cog @@ -342,6 +357,27 @@ cog.outl(f"\u002f*\n{service['service_json']}\n*\u002f") "name": "LargeArrayReturn", "parameters": [], "return_type": "uint8_t[256]" + }, + { + "id": 6, + "name": "StringParamsWithStringReturn", + "parameters": [ + { + "id": 0, + "name": "Path", + "type": "string", + "max_length": 64 + } + ], + "return_type": "string", + "max_length": 96 + }, + { + "id": 7, + "name": "LargeStringReturn", + "parameters": [], + "return_type": "string", + "max_length": 200 } ], "enums": [ diff --git a/codegen/templates/ServiceTemplate.cpp b/codegen/templates/ServiceTemplate.cpp index bd865da..97ab3ff 100644 --- a/codegen/templates/ServiceTemplate.cpp +++ b/codegen/templates/ServiceTemplate.cpp @@ -373,6 +373,11 @@ if service["functions"]: if p['is_blob']: cog.outl(f" const uint8_t* param_{p['name']} = nullptr;") cog.outl(f" uint32_t param_{p['name']}Len = 0;") + elif p['is_string']: + # One byte more than the limit: the value is terminated here, once, so the + # handler can hand it to LittleFS, printf or a JSON parser without a copy. + cog.outl(f" char param_{p['name']}[{p['max_length']} + 1] = {{}};") + cog.outl(f" uint32_t param_{p['name']}Len = 0;") elif p['is_array']: cog.outl(f" {p['type']} param_{p['name']}[{p['max_length']}] = {{}};") cog.outl(f" uint32_t param_{p['name']}Len = 0;") @@ -396,6 +401,13 @@ if service["functions"]: cog.outl(f" param_{p['name']} = buf + offset;") cog.outl(f" param_{p['name']}Len = desc->payload_size;") cog.outl(f" params_received++;") + elif p['is_string']: + cog.outl(f" if (desc->payload_size <= {p['max_length']}) {{") + cog.outl(f" memcpy(param_{p['name']}, buf + offset, desc->payload_size);") + cog.outl(f" param_{p['name']}[desc->payload_size] = '\\0';") + cog.outl(f" param_{p['name']}Len = desc->payload_size;") + cog.outl(f" params_received++;") + cog.outl(" } else { parse_ok = false; }") elif p['is_array']: cog.outl(f" if (desc->payload_size % sizeof({p['type']}) == 0 &&") cog.outl(f" desc->payload_size <= sizeof(param_{p['name']})) {{") @@ -420,7 +432,7 @@ if service["functions"]: # Build call argument list — call_id first, then params, then return buffer for arrays call_args = ["call_id"] for p in func["parameters"]: - if p['is_blob'] or p['is_array']: + if p['is_blob'] or p['is_array'] or p['is_string']: call_args.append(f"param_{p['name']}, param_{p['name']}Len") else: call_args.append(f"param_{p['name']}") @@ -439,6 +451,12 @@ if service["functions"]: cog.outl(" }") cog.outl(" uint16_t rpc_ret_len = kMaxRpcReturn;") call_args.append("rpc_ret_lease.data(), &rpc_ret_len") + elif func['return_is_string'] and pooled_bytes is None: + # Terminated locally: the handler writes text, the dispatcher sends the bytes + # it reported (without the terminator). + cog.outl(f" char rpc_ret_buf[{func['return_max_length']} + 1] = {{}};") + cog.outl(f" uint16_t rpc_ret_len = {func['return_max_length']};") + call_args.append("rpc_ret_buf, &rpc_ret_len") elif pooled_bytes is not None: cog.outl(f" static_assert({pooled_bytes} <= xbot::config::buffer_block_size,") cog.outl(' "return value does not fit into a buffer pool block");') @@ -447,7 +465,8 @@ if service["functions"]: cog.outl(" SendRpcResponse(call_id, xbot::datatypes::RpcStatus::BUSY, nullptr, 0);") cog.outl(" return;") cog.outl(" }") - cog.outl(f" auto* rpc_ret_buf = reinterpret_cast<{func['return_base_type']}*>(rpc_ret_lease.data());") + pooled_base_type = "char" if func["return_is_string"] else func["return_base_type"] + cog.outl(f" auto* rpc_ret_buf = reinterpret_cast<{pooled_base_type}*>(rpc_ret_lease.data());") cog.outl(f" uint16_t rpc_ret_len = {func['return_max_length']};") call_args.append("rpc_ret_buf, &rpc_ret_len") elif func['return_is_array']: @@ -460,6 +479,8 @@ if service["functions"]: cog.outl(f" rpc_max_response_size_ = 0;") elif func['return_is_blob']: cog.outl(f" rpc_max_response_size_ = kMaxRpcReturn;") + elif func['return_is_string']: + cog.outl(f" rpc_max_response_size_ = {func['return_max_length']};") elif func['return_is_array']: cog.outl(f" rpc_max_response_size_ = {func['return_max_length']} * sizeof({func['return_base_type']});") else: @@ -647,6 +668,54 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, RPCLargeArrayReturn(call_id, rpc_ret_buf, &rpc_ret_len); return; } + case 6: { + char param_Path[64 + 1] = {}; + uint32_t param_PathLen = 0; + size_t offset = 0; + bool parse_ok = true; + uint8_t params_received = 0; + while (offset + sizeof(xbot::datatypes::DataDescriptor) <= len) { + const auto* desc = reinterpret_cast(buf + offset); + offset += sizeof(xbot::datatypes::DataDescriptor); + // Bounds check against the remaining bytes: offset + payload_size can wrap on a 32 bit target + if (desc->payload_size > len - offset) { parse_ok = false; break; } + switch (desc->target_id) { + case 0: + if (desc->payload_size <= 64) { + memcpy(param_Path, buf + offset, desc->payload_size); + param_Path[desc->payload_size] = '\0'; + param_PathLen = desc->payload_size; + params_received++; + } else { parse_ok = false; } + break; + default: break; + } + offset += desc->payload_size; + } + if (!parse_ok || params_received != 1) { + SendRpcResponse(call_id, xbot::datatypes::RpcStatus::ERROR, nullptr, 0); + return; + } + char rpc_ret_buf[96 + 1] = {}; + uint16_t rpc_ret_len = 96; + rpc_max_response_size_ = 96; + RPCStringParamsWithStringReturn(call_id, param_Path, param_PathLen, rpc_ret_buf, &rpc_ret_len); + return; + } + case 7: { + static_assert(201 <= xbot::config::buffer_block_size, + "return value does not fit into a buffer pool block"); + auto rpc_ret_lease = xbot::service::buffer::acquire(201); + if (!rpc_ret_lease) { + SendRpcResponse(call_id, xbot::datatypes::RpcStatus::BUSY, nullptr, 0); + return; + } + auto* rpc_ret_buf = reinterpret_cast(rpc_ret_lease.data()); + uint16_t rpc_ret_len = 200; + rpc_max_response_size_ = 200; + RPCLargeStringReturn(call_id, rpc_ret_buf, &rpc_ret_len); + return; + } default: SendRpcResponse(call_id, xbot::datatypes::RpcStatus::ERROR, nullptr, 0); } diff --git a/codegen/templates/ServiceTemplate.hpp b/codegen/templates/ServiceTemplate.hpp index 41fe5ad..0244b04 100644 --- a/codegen/templates/ServiceTemplate.hpp +++ b/codegen/templates/ServiceTemplate.hpp @@ -147,7 +147,7 @@ class ServiceTemplateBase : public xbot::service::Service { 0x69, 0x6E, 0x74, 0x33, 0x32, 0x5F, 0x74, 0x68, 0x6F, 0x70, 0x74, 0x69, 0x6F, 0x6E, 0x61, 0x6C, 0xF5, 0x69, 0x66, 0x75, 0x6E, 0x63, 0x74, 0x69, - 0x6F, 0x6E, 0x73, 0x86, 0xA4, 0x62, 0x69, 0x64, + 0x6F, 0x6E, 0x73, 0x88, 0xA4, 0x62, 0x69, 0x64, 0x00, 0x64, 0x6E, 0x61, 0x6D, 0x65, 0x70, 0x4E, 0x6F, 0x50, 0x61, 0x72, 0x61, 0x6D, 0x73, 0x4E, 0x6F, 0x52, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x6A, @@ -218,36 +218,63 @@ class ServiceTemplateBase : public xbot::service::Service { 0x74, 0x65, 0x72, 0x73, 0x80, 0x6B, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x5F, 0x74, 0x79, 0x70, 0x65, 0x6C, 0x75, 0x69, 0x6E, 0x74, 0x38, 0x5F, - 0x74, 0x5B, 0x32, 0x35, 0x36, 0x5D, 0x65, 0x65, - 0x6E, 0x75, 0x6D, 0x73, 0x82, 0xA3, 0x62, 0x69, - 0x64, 0x70, 0x45, 0x78, 0x61, 0x6D, 0x70, 0x6C, - 0x65, 0x45, 0x6E, 0x75, 0x6D, 0x43, 0x6C, 0x61, - 0x73, 0x73, 0x69, 0x62, 0x61, 0x73, 0x65, 0x5F, - 0x74, 0x79, 0x70, 0x65, 0x67, 0x75, 0x69, 0x6E, - 0x74, 0x38, 0x5F, 0x74, 0x66, 0x76, 0x61, 0x6C, - 0x75, 0x65, 0x73, 0xA3, 0x66, 0x56, 0x41, 0x4C, - 0x55, 0x45, 0x31, 0x00, 0x66, 0x56, 0x41, 0x4C, - 0x55, 0x45, 0x32, 0x01, 0x66, 0x56, 0x41, 0x4C, - 0x55, 0x45, 0x33, 0x02, 0xA4, 0x62, 0x69, 0x64, - 0x72, 0x45, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65, - 0x42, 0x69, 0x74, 0x6D, 0x61, 0x73, 0x6B, 0x45, - 0x6E, 0x75, 0x6D, 0x69, 0x62, 0x61, 0x73, 0x65, - 0x5F, 0x74, 0x79, 0x70, 0x65, 0x67, 0x75, 0x69, - 0x6E, 0x74, 0x38, 0x5F, 0x74, 0x67, 0x62, 0x69, - 0x74, 0x6D, 0x61, 0x73, 0x6B, 0xF5, 0x66, 0x76, - 0x61, 0x6C, 0x75, 0x65, 0x73, 0xA3, 0x66, 0x56, - 0x41, 0x4C, 0x55, 0x45, 0x31, 0x00, 0x66, 0x56, - 0x41, 0x4C, 0x55, 0x45, 0x32, 0x01, 0x66, 0x56, - 0x41, 0x4C, 0x55, 0x45, 0x33, 0x02 + 0x74, 0x5B, 0x32, 0x35, 0x36, 0x5D, 0xA5, 0x62, + 0x69, 0x64, 0x06, 0x64, 0x6E, 0x61, 0x6D, 0x65, + 0x78, 0x1C, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, + 0x50, 0x61, 0x72, 0x61, 0x6D, 0x73, 0x57, 0x69, + 0x74, 0x68, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, + 0x52, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x6A, 0x70, + 0x61, 0x72, 0x61, 0x6D, 0x65, 0x74, 0x65, 0x72, + 0x73, 0x81, 0xA4, 0x62, 0x69, 0x64, 0x00, 0x64, + 0x6E, 0x61, 0x6D, 0x65, 0x64, 0x50, 0x61, 0x74, + 0x68, 0x64, 0x74, 0x79, 0x70, 0x65, 0x66, 0x73, + 0x74, 0x72, 0x69, 0x6E, 0x67, 0x6A, 0x6D, 0x61, + 0x78, 0x5F, 0x6C, 0x65, 0x6E, 0x67, 0x74, 0x68, + 0x18, 0x40, 0x6B, 0x72, 0x65, 0x74, 0x75, 0x72, + 0x6E, 0x5F, 0x74, 0x79, 0x70, 0x65, 0x66, 0x73, + 0x74, 0x72, 0x69, 0x6E, 0x67, 0x6A, 0x6D, 0x61, + 0x78, 0x5F, 0x6C, 0x65, 0x6E, 0x67, 0x74, 0x68, + 0x18, 0x60, 0xA5, 0x62, 0x69, 0x64, 0x07, 0x64, + 0x6E, 0x61, 0x6D, 0x65, 0x71, 0x4C, 0x61, 0x72, + 0x67, 0x65, 0x53, 0x74, 0x72, 0x69, 0x6E, 0x67, + 0x52, 0x65, 0x74, 0x75, 0x72, 0x6E, 0x6A, 0x70, + 0x61, 0x72, 0x61, 0x6D, 0x65, 0x74, 0x65, 0x72, + 0x73, 0x80, 0x6B, 0x72, 0x65, 0x74, 0x75, 0x72, + 0x6E, 0x5F, 0x74, 0x79, 0x70, 0x65, 0x66, 0x73, + 0x74, 0x72, 0x69, 0x6E, 0x67, 0x6A, 0x6D, 0x61, + 0x78, 0x5F, 0x6C, 0x65, 0x6E, 0x67, 0x74, 0x68, + 0x18, 0xC8, 0x67, 0x6F, 0x6D, 0x69, 0x74, 0x74, + 0x65, 0x64, 0x81, 0x65, 0x65, 0x6E, 0x75, 0x6D, + 0x73 }; // Blocks that did not fit into the advertisement; served on request // (DESCRIPTION_REQUEST -> DESCRIPTION_PART), so a host without generated // classes can still fetch the complete schema. static constexpr unsigned char SERVICE_OMITTED_CBOR[] = { - 0xA0 + 0xA1, 0x65, 0x65, 0x6E, 0x75, 0x6D, 0x73, 0x82, + 0xA3, 0x62, 0x69, 0x64, 0x70, 0x45, 0x78, 0x61, + 0x6D, 0x70, 0x6C, 0x65, 0x45, 0x6E, 0x75, 0x6D, + 0x43, 0x6C, 0x61, 0x73, 0x73, 0x69, 0x62, 0x61, + 0x73, 0x65, 0x5F, 0x74, 0x79, 0x70, 0x65, 0x67, + 0x75, 0x69, 0x6E, 0x74, 0x38, 0x5F, 0x74, 0x66, + 0x76, 0x61, 0x6C, 0x75, 0x65, 0x73, 0xA3, 0x66, + 0x56, 0x41, 0x4C, 0x55, 0x45, 0x31, 0x00, 0x66, + 0x56, 0x41, 0x4C, 0x55, 0x45, 0x32, 0x01, 0x66, + 0x56, 0x41, 0x4C, 0x55, 0x45, 0x33, 0x02, 0xA4, + 0x62, 0x69, 0x64, 0x72, 0x45, 0x78, 0x61, 0x6D, + 0x70, 0x6C, 0x65, 0x42, 0x69, 0x74, 0x6D, 0x61, + 0x73, 0x6B, 0x45, 0x6E, 0x75, 0x6D, 0x69, 0x62, + 0x61, 0x73, 0x65, 0x5F, 0x74, 0x79, 0x70, 0x65, + 0x67, 0x75, 0x69, 0x6E, 0x74, 0x38, 0x5F, 0x74, + 0x67, 0x62, 0x69, 0x74, 0x6D, 0x61, 0x73, 0x6B, + 0xF5, 0x66, 0x76, 0x61, 0x6C, 0x75, 0x65, 0x73, + 0xA3, 0x66, 0x56, 0x41, 0x4C, 0x55, 0x45, 0x31, + 0x00, 0x66, 0x56, 0x41, 0x4C, 0x55, 0x45, 0x32, + 0x01, 0x66, 0x56, 0x41, 0x4C, 0x55, 0x45, 0x33, + 0x02 }; - static constexpr size_t SERVICE_OMITTED_CBOR_SIZE = 0; + static constexpr size_t SERVICE_OMITTED_CBOR_SIZE = 161; const unsigned char* GetOmittedDescription(size_t& size) override { size = SERVICE_OMITTED_CBOR_SIZE; @@ -379,12 +406,16 @@ class ServiceTemplateBase : public xbot::service::Service { for p in func["parameters"]: if p['is_blob']: params.append(f"const uint8_t* {p['name']}, uint32_t {p['name']}Len") + elif p['is_string']: + params.append(f"const char* {p['name']}, uint32_t {p['name']}Len") elif p['is_array']: params.append(f"const {p['type']}* {p['name']}, uint32_t {p['name']}Len") else: params.append(f"{p['type']} {p['name']}") if func['return_is_blob']: params.append("uint8_t* data, uint16_t* response_length") + elif func['return_is_string']: + params.append("char* data, uint16_t* response_length") elif func['return_is_array']: params.append(f"{func['return_base_type']}* data, uint16_t* response_length") params_str = ", ".join(params) @@ -396,6 +427,8 @@ class ServiceTemplateBase : public xbot::service::Service { virtual void RPCMixedParamsWithReturn(uint16_t call_id, const char* Name, uint32_t NameLen, float Value) = 0; virtual void RPCBlobParamsWithBlobReturn(uint16_t call_id, const uint8_t* Data, uint32_t DataLen, uint8_t* data, uint16_t* response_length) = 0; virtual void RPCLargeArrayReturn(uint16_t call_id, uint8_t* data, uint16_t* response_length) = 0; + virtual void RPCStringParamsWithStringReturn(uint16_t call_id, const char* Path, uint32_t PathLen, char* data, uint16_t* response_length) = 0; + virtual void RPCLargeStringReturn(uint16_t call_id, char* data, uint16_t* response_length) = 0; //[[[end]]] }; @@ -538,6 +571,27 @@ cog.outl(f"\u002f*\n{service['service_json']}\n*\u002f") "name": "LargeArrayReturn", "parameters": [], "return_type": "uint8_t[256]" + }, + { + "id": 6, + "name": "StringParamsWithStringReturn", + "parameters": [ + { + "id": 0, + "name": "Path", + "type": "string", + "max_length": 64 + } + ], + "return_type": "string", + "max_length": 96 + }, + { + "id": 7, + "name": "LargeStringReturn", + "parameters": [], + "return_type": "string", + "max_length": 200 } ], "enums": [ diff --git a/codegen/templates/service.json b/codegen/templates/service.json index 4b426bb..86396ad 100644 --- a/codegen/templates/service.json +++ b/codegen/templates/service.json @@ -105,6 +105,27 @@ "name": "LargeArrayReturn", "parameters": [], "return_type": "uint8_t[256]" + }, + { + "id": 6, + "name": "StringParamsWithStringReturn", + "parameters": [ + { + "id": 0, + "name": "Path", + "type": "string", + "max_length": 64 + } + ], + "return_type": "string", + "max_length": 96 + }, + { + "id": 7, + "name": "LargeStringReturn", + "parameters": [], + "return_type": "string", + "max_length": 200 } ], "enums": [ diff --git a/codegen/xbot_codegen/xbot_codegen.py b/codegen/xbot_codegen/xbot_codegen.py index 60cc261..cdfa9ae 100644 --- a/codegen/xbot_codegen/xbot_codegen.py +++ b/codegen/xbot_codegen/xbot_codegen.py @@ -58,6 +58,8 @@ def parse_type(type): base_type = match.group(1) if base_type == "blob": raise Exception("Blob type cannot be an array!") + if base_type == "string": + raise Exception("String type declares its limit as max_length, not as an array length!") max_length = int(match.group(2)) return base_type, max_length else: @@ -95,6 +97,25 @@ def array_type_attrs(max_length): # service never has to reserve that stack space permanently. RPC_STACK_RETURN_MAX = 128 +# One parameter occupies a descriptor plus its payload in the RPC body, so it can never be +# longer than that body minus the descriptor: 1448 - 8. A larger limit could never be +# fulfilled, and the dispatcher would have to reserve max_length + 1 bytes of stack for it. +MAX_PARAMETER_BYTES = MAX_RPC_RETURN_BYTES - 8 + +# `string` is text on the wire: like blob it carries no terminator and its length is the +# payload size. The difference is the declared maximum, so the generated server can decode +# it into a checked, always terminated char[max_length + 1] and hand the handler a plain +# C string - no copy in the handler, no silent truncation. +MAX_STRING_LENGTH = MAX_PARAMETER_BYTES + + +def string_max_length(json_field, where): + """The mandatory max_length of a string field, validated.""" + length = int(json_field.get("max_length", 0) or 0) + if length <= 0 or length > MAX_STRING_LENGTH: + raise Exception(f"{where}: a string needs a max_length of 1..{MAX_STRING_LENGTH}, got {length}") + return length + def typeSize(service, type_name): """sizeof of a scalar or enum type in the generated C++ code.""" @@ -112,6 +133,10 @@ def pooledReturnBytes(service, func): return None if func["return_is_blob"]: return MAX_RPC_RETURN_BYTES + if func["return_is_string"]: + # One byte more than max_length: the terminator the dispatcher appends. + bytes_needed = func["return_max_length"] + 1 + return bytes_needed if bytes_needed > RPC_STACK_RETURN_MAX else None if func["return_is_array"]: bytes_needed = func["return_max_length"] * typeSize(service, func["return_base_type"]) return bytes_needed if bytes_needed > RPC_STACK_RETURN_MAX else None @@ -272,18 +297,24 @@ def loadService(path: str) -> dict: seen_func_names.add(func_name) return_type_str = json_func.get("return_type", "void") return_is_blob = False + return_is_string = False if return_type_str == "void": return_base_type, return_max_length = None, None else: return_base_type, return_max_length = parse_type(return_type_str) - if return_base_type not in valid_types + ["blob"]: + if return_base_type not in valid_types + ["blob", "string"]: raise Exception(f"Illegal return type for function '{func_name}': {return_type_str}") if return_base_type == "blob": # Variable length and therefore bounded by one packet only # (MAX_RPC_RETURN_BYTES); the generated dispatcher takes the buffer # from the shared pool. return_is_blob = True - if return_max_length is not None: + if return_base_type == "string": + return_is_string = True + # string_max_length() already caps this at one packet body minus a + # descriptor, which a return value always fits. + return_max_length = string_max_length(json_func, f"function '{func_name}' return") + if return_max_length is not None and not return_is_string: if return_max_length <= 0 or return_max_length > MAX_ARRAY_LENGTH: raise Exception( f"Illegal array return length {return_max_length} for function '{func_name}' " @@ -295,7 +326,7 @@ def loadService(path: str) -> dict: raise Exception( f"Function '{func_name}' return type '{return_type_str}' is {return_bytes} bytes, " f"more than one packet can carry ({MAX_RPC_RETURN_BYTES})") - return_is_array = return_max_length is not None + return_is_array = (return_max_length is not None) and not return_is_string check_unique_ids(json_func.get("parameters", [])) params = [] @@ -309,14 +340,28 @@ def loadService(path: str) -> dict: f"in function '{func_name}'") seen_param_names.add(param_name) param_type, param_max_length = parse_type(json_param["type"]) - if param_type not in valid_types + ["blob"]: + if param_type not in valid_types + ["blob", "string"]: raise Exception(f"Illegal parameter type in function '{func_name}': {param_type}") + param_is_string = param_type == "string" + if param_is_string: + param_max_length = string_max_length( + json_param, f"parameter '{param_name}' of function '{func_name}'") + elif param_max_length is not None: + # A parameter travels in one packet, and the dispatcher reserves that much + # stack for it - a declaration above one packet is never usable. + param_bytes = param_max_length * typeSize(service, param_type) + if param_bytes > MAX_PARAMETER_BYTES: + raise Exception( + f"Function '{func_name}' parameter '{param_name}' is {param_bytes} bytes, " + f"more than one packet can carry ({MAX_PARAMETER_BYTES})") params.append({ "id": int(json_param["id"]), "name": param_name, "type": param_type, "is_blob": param_type == "blob", - **array_type_attrs(param_max_length), + "is_string": param_is_string, + "max_length": param_max_length if param_is_string else None, + **( {"is_array": False} if param_is_string else array_type_attrs(param_max_length) ), }) service["functions"].append({ @@ -326,6 +371,7 @@ def loadService(path: str) -> dict: "return_base_type": return_base_type, "return_is_array": return_is_array, "return_is_blob": return_is_blob, + "return_is_string": return_is_string, "return_max_length": return_max_length, "parameters": params, }) diff --git a/xbot_service_interface_go/codegen/emit.go b/xbot_service_interface_go/codegen/emit.go index 6b78138..576370f 100644 --- a/xbot_service_interface_go/codegen/emit.go +++ b/xbot_service_interface_go/codegen/emit.go @@ -96,6 +96,10 @@ func (g *generator) goScalar(t, where string) (string, error) { func (g *generator) goType(t, where string) (string, error) { base, _, isArray := splitType(t) switch { + case base == "string": + // Text on the wire without a terminator; the server decodes it into a checked + // C string, the client passes and receives a Go string. + return "string", nil case base == "blob": return "[]byte", nil case base == "char": @@ -116,6 +120,9 @@ func (g *generator) goType(t, where string) (string, error) { func (g *generator) packExpr(t, expr, where string) (string, error) { base, length, isArray := splitType(t) switch { + case base == "string": + // The bytes only, no terminator: the length in the descriptor is the value. + return "[]byte(" + expr + ")", nil case base == "blob": return expr, nil case base == "char": @@ -143,11 +150,20 @@ func (g *generator) packExpr(t, expr, where string) (string, error) { // decodeReturn returns the Go return type ("" for void) and the lines that decode // the RPC response payload. -func (g *generator) decodeReturn(t, fn string) (string, []string, error) { +func (g *generator) decodeReturn(t string, maxLen int, fn string) (string, []string, error) { base, _, isArray := splitType(t) switch { case t == "" || t == "void": return "", nil, nil + case base == "string": + // The payload is the text without a terminator; the limit comes from the schema. + return "string", []string{ + fmt.Sprintf("\tif len(payload) > %d {", maxLen), + fmt.Sprintf("\t\treturn ZERO, errf(%q, len(payload))", + fmt.Sprintf("%s returned %%d bytes, max %d", fn, maxLen)), + "\t}", + "\treturn string(payload), nil", + }, nil case base == "blob": // Variable length return: hand the payload back as is. return "[]byte", []string{"\treturn append([]byte(nil), payload...), nil"}, nil diff --git a/xbot_service_interface_go/codegen/generate_test.go b/xbot_service_interface_go/codegen/generate_test.go index 9cea5e3..52ce71c 100644 --- a/xbot_service_interface_go/codegen/generate_test.go +++ b/xbot_service_interface_go/codegen/generate_test.go @@ -74,6 +74,12 @@ func TestLoadRejects(t *testing.T) { "parameters": [{"id": 0, "name": "PathData", "type": "blob"}]}, {"id": 1, "name": "WritePath", "return_type": "void", "parameters": [{"id": 0, "name": "Data", "type": "blob"}]}]}`, + "string above one packet": `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "F", "return_type": "void", + "parameters": [{"id": 0, "name": "P", "type": "string", "max_length": 1441}]}]}`, + "array parameter above one packet": `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "F", "return_type": "void", + "parameters": [{"id": 0, "name": "P", "type": "uint8_t[1441]"}]}]}`, "enum values normalize equal": `{"type": "X", "version": 1, "enums": [{"id": "E", "base_type": "uint8_t", "values": {"IDLE": 0, "Idle": 1}}]}`, "enum types normalize equal": `{"type": "X", "version": 1, "enums": [ @@ -213,3 +219,37 @@ func TestNumericArrays(t *testing.T) { } } } + +// TestStringParameters pins the generated string handling: a string parameter is a Go +// string, sent as its UTF-8 bytes without a terminator and refused above max_length; a +// string return is decoded into a string and checked against the limit. +func TestStringParameters(t *testing.T) { + path := t.TempDir() + "/service.json" + schema := `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "Play", "return_type": "string", "max_length": 96, + "parameters": [{"id": 0, "name": "Path", "type": "string", "max_length": 64}]}]}` + if err := os.WriteFile(path, []byte(schema), 0o644); err != nil { + t.Fatal(err) + } + s, err := Load(path) + if err != nil { + t.Fatalf("Load: %v", err) + } + src, err := Generate(s, Options{}) + if err != nil { + t.Fatalf("Generate: %v", err) + } + for _, want := range []string{ + "func (c *Client) Play(ctx context.Context, Path string) (string, error) {", + "if len(Path) > 64 { // string, max_length 64", + "xbot.Bytes(0, []byte(Path))", + "if len(payload) > 96 {", + "return string(payload), nil", + // The budget helper treats a string like a blob: variable length. + "func MaxPlayPath() int {", + } { + if !bytes.Contains(src, []byte(want)) { + t.Errorf("generated code does not contain %q", want) + } + } +} diff --git a/xbot_service_interface_go/codegen/render.go b/xbot_service_interface_go/codegen/render.go index 8f94e64..f7de968 100644 --- a/xbot_service_interface_go/codegen/render.go +++ b/xbot_service_interface_go/codegen/render.go @@ -176,6 +176,10 @@ type charCheck struct { param string schema string length int + // isString marks a "string" parameter: its length is a byte count without a + // terminator, so the check is "len > max" instead of "len >= N" (which includes the + // NUL of a char[N]). + isString bool } // paramBytes is how many bytes a fixed size parameter occupies on the wire, i.e. what it @@ -208,7 +212,9 @@ func (g *generator) emitFrameBudgets() { var blobs []Parameter fixed := 0 for _, p := range fn.Parameters { - if base, _, _ := splitType(p.Type); base == "blob" { + // blob and string are both variable length: a helper has to subtract their + // lengths, and neither can be part of the fixed framing. + if base, _, _ := splitType(p.Type); base == "blob" || base == "string" { blobs = append(blobs, p) continue } @@ -232,7 +238,11 @@ func (g *generator) emitFrameBudgets() { continue } otherName := goName(other.Name) - args = append(args, otherName+" []byte") + otherType := "[]byte" + if base, _, _ := splitType(other.Type); base == "string" { + otherType = "string" + } + args = append(args, otherName+" "+otherType) variable.WriteString(" - len(" + otherName + ")") } @@ -274,10 +284,15 @@ func (g *generator) emitFunction(fn Function) error { if base, length, _ := splitType(p.Type); base == "char" && length > 0 { charChecks = append(charChecks, charCheck{param: pname, schema: p.Type, length: length}) } + if base, _, _ := splitType(p.Type); base == "string" { + // Refused here instead of on the server: the value is text without a + // terminator, and the schema declares the limit. + charChecks = append(charChecks, charCheck{param: pname, schema: "string", length: p.MaxLength, isString: true}) + } sig = append(sig, pname+" "+gt) params = append(params, fmt.Sprintf("xbot.Bytes(%d, %s),", p.ID, expr)) } - retType, lines, err := g.decodeReturn(fn.ReturnType, name) + retType, lines, err := g.decodeReturn(fn.ReturnType, fn.MaxLength, name) if err != nil { return err } @@ -313,6 +328,12 @@ func (g *generator) emitFunction(fn Function) error { g.line("// so the call is fire and forget and returns the zero value.") g.f("func (c *Client) %s(%s) %s {", name, strings.Join(sig, ", "), ret) for _, c := range charChecks { + if c.isString { + g.f("\tif len(%s) > %d { // string, max_length %d", c.param, c.length, c.length) + g.f("\t\treturn %serrf(\"%s too long (%%d bytes, max %d)\", len(%s))", zero, c.param, c.length, c.param) + g.line("\t}") + continue + } g.f("\tif len(%s) >= %d { // %s includes the NUL", c.param, c.length, c.schema) g.f("\t\treturn %serrf(\"%s too long (%%d bytes, max %%d)\", len(%s), %d)", zero, c.param, c.param, c.length-1) diff --git a/xbot_service_interface_go/codegen/schema.go b/xbot_service_interface_go/codegen/schema.go index 20e1e36..207ff08 100644 --- a/xbot_service_interface_go/codegen/schema.go +++ b/xbot_service_interface_go/codegen/schema.go @@ -45,9 +45,11 @@ type Field struct { // Function is one RPC function. type Function struct { - ID int `json:"id"` - Name string `json:"name"` - ReturnType string `json:"return_type"` + ID int `json:"id"` + Name string `json:"name"` + ReturnType string `json:"return_type"` + // MaxLength is the limit of a "string" return value, like in the C++ generator. + MaxLength int `json:"max_length"` Parameters []Parameter `json:"parameters"` } @@ -56,6 +58,8 @@ type Parameter struct { ID int `json:"id"` Name string `json:"name"` Type string `json:"type"` + // MaxLength is the limit of a "string" parameter. + MaxLength int `json:"max_length"` } // rawTypes are the scalar types the wire format supports (C++: xbot_codegen.py). @@ -67,6 +71,13 @@ var rawTypes = []string{ // maxArrayLength is the limit the framework applies to array returns. const maxArrayLength = 1024 +// maxStringLength is one packet body minus the descriptor: a longer value could never be +// sent, and the server would reserve that much stack for it. +const maxStringLength = 1472 - 24 - 8 + +// maxParameterBytes is what one parameter can add to the RPC body besides its descriptor. +const maxParameterBytes = maxStringLength + var arrayType = regexp.MustCompile(`^(.+)\[(\d+)\]$`) // Load reads and validates a service.json. @@ -103,6 +114,28 @@ func (s *Schema) validate() error { return fmt.Errorf("function %s: return length %d must be 1..%d", f.Name, n, maxArrayLength) } } + // "string" carries text without a terminator, so the server needs the limit. + if f.ReturnType == "string" && (f.MaxLength < 1 || f.MaxLength > maxStringLength) { + return fmt.Errorf("function %s: a string return needs a max_length of 1..%d", f.Name, maxStringLength) + } + for _, p := range f.Parameters { + if p.Type == "string" && (p.MaxLength < 1 || p.MaxLength > maxStringLength) { + return fmt.Errorf("function %s: parameter %s: a string needs a max_length of 1..%d", + f.Name, p.Name, maxStringLength) + } + // Same rule as the C++ generator: a parameter has to fit into one packet, and + // the server reserves that much stack for it. + if base, n, isArray := splitType(p.Type); isArray && base != "blob" { + size, ok := typeSizes[base] + if base == "char" { + size, ok = 1, true + } + if ok && size*n > maxParameterBytes { + return fmt.Errorf("function %s: parameter %s is %d bytes, more than one packet can carry (%d)", + f.Name, p.Name, size*n, maxParameterBytes) + } + } + } } if err := checkUniqueIDs("inputs", s.Inputs); err != nil { return err diff --git a/xbot_service_interface_go/codegen/testdata/demo_service.golden.go b/xbot_service_interface_go/codegen/testdata/demo_service.golden.go index 5cf1af3..689a4b6 100644 --- a/xbot_service_interface_go/codegen/testdata/demo_service.golden.go +++ b/xbot_service_interface_go/codegen/testdata/demo_service.golden.go @@ -21,11 +21,13 @@ const ServiceID uint16 = 99 // Function ids (service.json -> "functions"). const ( - FnNoParamsNoReturn uint8 = 0 - FnScalarParamsWithReturn uint8 = 1 - FnArrayParamNoReturn uint8 = 2 - FnMixedParamsWithReturn uint8 = 3 - FnNumericArrayReturn uint8 = 4 + FnNoParamsNoReturn uint8 = 0 + FnScalarParamsWithReturn uint8 = 1 + FnArrayParamNoReturn uint8 = 2 + FnMixedParamsWithReturn uint8 = 3 + FnNumericArrayReturn uint8 = 4 + FnStringParamsWithStringReturn uint8 = 5 + FnLargeStringReturn uint8 = 6 ) // ExampleEnumClass values (service.json -> "enums"). @@ -177,6 +179,60 @@ func (c *Client) NumericArrayReturn(ctx context.Context) ([]float64, error) { return readFloat64Slice(payload, 4) } +// StringParamsWithStringReturn calls the RPC function 5. +// +// It only waits for the answer when this client owns the service. Without a claim +// (Options.NoClaim or Options.Endpoint) the service sends its answer to the owner, +// so the call is fire and forget and returns the zero value. +func (c *Client) StringParamsWithStringReturn(ctx context.Context, Path string) (string, error) { + if len(Path) > 64 { // string, max_length 64 + return "", errf("Path too long (%d bytes, max 64)", len(Path)) + } + if c.sendOnly { + return "", c.conn.SendRPC(FnStringParamsWithStringReturn, + xbot.Bytes(0, []byte(Path)), + ) + } + payload, err := c.conn.Call(ctx, FnStringParamsWithStringReturn, + xbot.Bytes(0, []byte(Path)), + ) + if err != nil { + return "", err + } + if len(payload) > 96 { + return "", errf("StringParamsWithStringReturn returned %d bytes, max 96", len(payload)) + } + return string(payload), nil +} + +// LargeStringReturn calls the RPC function 6. +// +// It only waits for the answer when this client owns the service. Without a claim +// (Options.NoClaim or Options.Endpoint) the service sends its answer to the owner, +// so the call is fire and forget and returns the zero value. +func (c *Client) LargeStringReturn(ctx context.Context) (string, error) { + if c.sendOnly { + return "", c.conn.SendRPC(FnLargeStringReturn) + } + payload, err := c.conn.Call(ctx, FnLargeStringReturn) + if err != nil { + return "", err + } + if len(payload) > 200 { + return "", errf("LargeStringReturn returned %d bytes, max 200", len(payload)) + } + return string(payload), nil +} + +// MaxStringParamsWithStringReturnPath is the largest Path payload one StringParamsWithStringReturn call can carry. +// +// One packet of RPC body minus the framing of the call: a descriptor per +// parameter and the payloads of the fixed parameters. A call whose parameters +// already use up the packet reports 0, never a negative budget. +func MaxStringParamsWithStringReturnPath() int { + return max(0, xbot.MaxPacketSize-xbot.HeaderSize-1*xbot.DescriptorSize) +} + // SetRegister1 writes the register 0 as a configuration transaction. func (c *Client) SetRegister1(Register1 string) error { return c.conn.SendTransaction(true, xbot.Data{ID: 0, Data: charParam(Register1, 42)}) diff --git a/xbot_service_interface_go/codegen/testdata/demo_service.json b/xbot_service_interface_go/codegen/testdata/demo_service.json index 45091fa..aad173c 100644 --- a/xbot_service_interface_go/codegen/testdata/demo_service.json +++ b/xbot_service_interface_go/codegen/testdata/demo_service.json @@ -83,6 +83,27 @@ "name": "NumericArrayReturn", "parameters": [], "return_type": "double[4]" + }, + { + "id": 5, + "max_length": 96, + "name": "StringParamsWithStringReturn", + "parameters": [ + { + "id": 0, + "max_length": 64, + "name": "Path", + "type": "string" + } + ], + "return_type": "string" + }, + { + "id": 6, + "max_length": 200, + "name": "LargeStringReturn", + "parameters": [], + "return_type": "string" } ], "inputs": [ diff --git a/xbot_service_interface_go/codegen/testdata/demo_service_noid.golden.go b/xbot_service_interface_go/codegen/testdata/demo_service_noid.golden.go index 8ad63ff..06b5c20 100644 --- a/xbot_service_interface_go/codegen/testdata/demo_service_noid.golden.go +++ b/xbot_service_interface_go/codegen/testdata/demo_service_noid.golden.go @@ -18,11 +18,13 @@ import ( // Function ids (service.json -> "functions"). const ( - FnNoParamsNoReturn uint8 = 0 - FnScalarParamsWithReturn uint8 = 1 - FnArrayParamNoReturn uint8 = 2 - FnMixedParamsWithReturn uint8 = 3 - FnNumericArrayReturn uint8 = 4 + FnNoParamsNoReturn uint8 = 0 + FnScalarParamsWithReturn uint8 = 1 + FnArrayParamNoReturn uint8 = 2 + FnMixedParamsWithReturn uint8 = 3 + FnNumericArrayReturn uint8 = 4 + FnStringParamsWithStringReturn uint8 = 5 + FnLargeStringReturn uint8 = 6 ) // ExampleEnumClass values (service.json -> "enums"). @@ -174,6 +176,60 @@ func (c *Client) NumericArrayReturn(ctx context.Context) ([]float64, error) { return readFloat64Slice(payload, 4) } +// StringParamsWithStringReturn calls the RPC function 5. +// +// It only waits for the answer when this client owns the service. Without a claim +// (Options.NoClaim or Options.Endpoint) the service sends its answer to the owner, +// so the call is fire and forget and returns the zero value. +func (c *Client) StringParamsWithStringReturn(ctx context.Context, Path string) (string, error) { + if len(Path) > 64 { // string, max_length 64 + return "", errf("Path too long (%d bytes, max 64)", len(Path)) + } + if c.sendOnly { + return "", c.conn.SendRPC(FnStringParamsWithStringReturn, + xbot.Bytes(0, []byte(Path)), + ) + } + payload, err := c.conn.Call(ctx, FnStringParamsWithStringReturn, + xbot.Bytes(0, []byte(Path)), + ) + if err != nil { + return "", err + } + if len(payload) > 96 { + return "", errf("StringParamsWithStringReturn returned %d bytes, max 96", len(payload)) + } + return string(payload), nil +} + +// LargeStringReturn calls the RPC function 6. +// +// It only waits for the answer when this client owns the service. Without a claim +// (Options.NoClaim or Options.Endpoint) the service sends its answer to the owner, +// so the call is fire and forget and returns the zero value. +func (c *Client) LargeStringReturn(ctx context.Context) (string, error) { + if c.sendOnly { + return "", c.conn.SendRPC(FnLargeStringReturn) + } + payload, err := c.conn.Call(ctx, FnLargeStringReturn) + if err != nil { + return "", err + } + if len(payload) > 200 { + return "", errf("LargeStringReturn returned %d bytes, max 200", len(payload)) + } + return string(payload), nil +} + +// MaxStringParamsWithStringReturnPath is the largest Path payload one StringParamsWithStringReturn call can carry. +// +// One packet of RPC body minus the framing of the call: a descriptor per +// parameter and the payloads of the fixed parameters. A call whose parameters +// already use up the packet reports 0, never a negative budget. +func MaxStringParamsWithStringReturnPath() int { + return max(0, xbot.MaxPacketSize-xbot.HeaderSize-1*xbot.DescriptorSize) +} + // SetRegister1 writes the register 0 as a configuration transaction. func (c *Client) SetRegister1(Register1 string) error { return c.conn.SendTransaction(true, xbot.Data{ID: 0, Data: charParam(Register1, 42)}) diff --git a/xbot_service_interface_go/codegen/validate_names.go b/xbot_service_interface_go/codegen/validate_names.go index d212b35..28b1245 100644 --- a/xbot_service_interface_go/codegen/validate_names.go +++ b/xbot_service_interface_go/codegen/validate_names.go @@ -56,7 +56,7 @@ func (s *Schema) validateGeneratedNames() error { // distinct RPC names can produce the same one: Write(Path blob) and // WritePath(Data blob) both give MaxWritePathData. for _, p := range fn.Parameters { - if base, _, _ := splitType(p.Type); base != "blob" { + if base, _, _ := splitType(p.Type); base != "blob" && base != "string" { continue } what := "the frame budget helper of parameter " + p.Name + " of function " + fn.Name diff --git a/xbot_service_interface_py/tests/test_serialization.py b/xbot_service_interface_py/tests/test_serialization.py index 2b6b686..c87a211 100644 --- a/xbot_service_interface_py/tests/test_serialization.py +++ b/xbot_service_interface_py/tests/test_serialization.py @@ -101,6 +101,34 @@ def test_blob_raises(self): with pytest.raises(ValueError): sizeof_type('blob') + def test_string_raises(self): + # Variable length like blob: the limit comes from the schema, not the type string. + with pytest.raises(ValueError): + sizeof_type('string') + + +# --------------------------------------------------------------------------- +# string — text on the wire, no terminator, UTF-8 +# --------------------------------------------------------------------------- + +class TestStringValue: + def test_pack_str(self): + assert pack_value('string', '/sounds/x.mp3') == b'/sounds/x.mp3' + + def test_pack_bytes(self): + assert pack_value('string', b'abc') == b'abc' + + def test_unpack_utf8(self): + assert unpack_value('string', 'Grüße'.encode('utf-8')) == 'Grüße' + + def test_unpack_no_padding(self): + # Unlike char[n] there is no padding to strip: the length is the value. + assert unpack_value('string', b'a\x00b') == 'a\x00b' + + def test_round_trip_keeps_non_ascii(self): + text = '/sounds/grüße_1.mp3' + assert unpack_value('string', pack_value('string', text)) == text + # --------------------------------------------------------------------------- # pack_value / unpack_value — scalar round-trips diff --git a/xbot_service_interface_py/xbot_service_interface/interface.py b/xbot_service_interface_py/xbot_service_interface/interface.py index 925dd15..cadc709 100644 --- a/xbot_service_interface_py/xbot_service_interface/interface.py +++ b/xbot_service_interface_py/xbot_service_interface/interface.py @@ -372,6 +372,17 @@ def _call_rpc(self, fn: dict, args: tuple, timeout_ms: int): enums = schema.enums_dict if schema else {} for param, arg in zip(params, args, strict=True): raw = pack_value(param['type_str'], arg, enums) + base, _, _ = parse_type_string(param['type_str']) + if base == 'string': + # Text has a declared limit; refuse a longer value here instead of letting + # the server reject the whole call. + limit = int(param.get('max_length') or 0) + if limit <= 0: + raise ValueError( + f"RPC {fn['name']!r}: parameter {param.get('name')!r} is a string without a max_length") + if len(raw) > limit: + raise ValueError( + f"RPC {fn['name']!r}: parameter {param.get('name')!r} is {len(raw)} bytes, max {limit}") params_bytes += pack_descriptor(param['id'], len(raw)) + raw # The request has to fit into one datagram. The low level drops a larger one without @@ -422,12 +433,17 @@ def _call_rpc(self, fn: dict, args: tuple, timeout_ms: int): if base == 'blob': # Variable length return, bounded by one packet only. max_bytes = MAX_UDP_PAYLOAD - HEADER_SIZE + elif base == 'string': + # Text: the schema declares the limit, and the server never sends more. + max_bytes = int(fn.get('max_length') or 0) + if max_bytes <= 0: + raise RpcError(2, f"RPC {fn['name']!r}: string return without a max_length") else: max_bytes = sizeof_type(fn['return_type']) if len(payload) > max_bytes: raise RpcError( 2, f"RPC {fn['name']!r} response too large: got {len(payload)} bytes, max {max_bytes}") - if base != 'blob' and not is_array and len(payload) < max_bytes: + if base not in ('blob', 'string') and not is_array and len(payload) < max_bytes: raise RpcError( 2, f"RPC {fn['name']!r} response too small: got {len(payload)} bytes, need {max_bytes}") return unpack_value(fn['return_type'], payload, enums) diff --git a/xbot_service_interface_py/xbot_service_interface/serialization.py b/xbot_service_interface_py/xbot_service_interface/serialization.py index 00ac8b8..0877fba 100644 --- a/xbot_service_interface_py/xbot_service_interface/serialization.py +++ b/xbot_service_interface_py/xbot_service_interface/serialization.py @@ -48,8 +48,9 @@ def parse_type_string(type_str: str) -> Tuple[str, bool, Optional[int]]: def sizeof_type(type_str: str) -> int: base, is_array, max_len = parse_type_string(type_str) - if base == 'blob': - raise ValueError("blob has no fixed size") + if base in ('blob', 'string'): + # Both are variable length; a string's limit comes from the schema's max_length. + raise ValueError(f"{base} has no fixed size") if base not in _FORMATS: raise ValueError(f"Unknown type: {base!r}") _, elem_size = _FORMATS[base] @@ -74,6 +75,13 @@ def pack_value(type_str: str, value, enums: dict = None) -> bytes: raise TypeError("blob type requires bytes-like object") return bytes(value) + if base == 'string': + # Text without a terminator on the wire, like char[n] but without padding. The + # max_length check belongs to the caller, which has the schema. + if isinstance(value, str): + return value.encode('utf-8') + return bytes(value) + if base == 'char': if is_array: raw = value.encode('utf-8', errors='replace') if isinstance(value, str) else bytes(value) @@ -105,6 +113,10 @@ def unpack_value(type_str: str, data: bytes, enums: dict = None): if base == 'blob': return bytes(data) + if base == 'string': + # Text on the wire, no terminator: decode what the server sent. + return data.decode('utf-8', errors='replace') + if base == 'char': if is_array: return data.rstrip(b'\x00').decode('utf-8', errors='replace') From f9586357ba772c0d27a0f6142cd0db75b9fc04ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Ebeling?= Date: Mon, 16 Nov 2026 12:38:28 +0100 Subject: [PATCH 11/28] fix(codegen): Fix new CodeRabbit findings on the new string type - the C++ client called strlen() before it checked the parameter for null - two function/parameter name combinations could generate the same frame budget helper (Write(PathData) and WritePath(Data) both give MaxWritePathData); the Python validator reserves the names now, like the Go one already did - the dispatcher counted descriptors, so two descriptors for the same parameter stood in for a missing one and the handler saw a default instead of an ERROR; it tracks presence per parameter and rejects duplicates - the Python client never saw max_length: the schema index dropped the field, so every string parameter was rejected against a limit of 0 and every string return failed. The index carries it now, with tests - docs: a pooled return lease is only valid until the handler returns, a string may contain U+0000 (use the byte count), and moving blob -> string needs a version bump when the new limit rejects values that used to work --- Readme.md | 7 +- .../templates/ServiceInterfaceTemplate.cpp | 4 ++ codegen/templates/ServiceTemplate.cpp | 64 ++++++++++++------- codegen/xbot_codegen/xbot_codegen.py | 14 ++++ .../tests/test_schema.py | 35 ++++++++++ .../xbot_service_interface/schema.py | 5 ++ 6 files changed, 103 insertions(+), 26 deletions(-) diff --git a/Readme.md b/Readme.md index e174edf..a36c543 100644 --- a/Readme.md +++ b/Readme.md @@ -265,6 +265,8 @@ The dispatcher reserves `max_length + 1` bytes of stack for the call, so `max_le minus a descriptor (1440 bytes) and the working area of the service has to be sized for it - the thread watermark shows what a service really uses. +A `string` may contain U+0000: the terminator is a convenience for C APIs, so a handler that can pass the value on to `printf`, LittleFS or a parser and wants the whole value has to use the byte count (`Len`) instead of assuming the text ends at the first NUL. + ```json { "id": 3, "name": "PlayMp3", "return_type": "uint8_t", "parameters": [ { "id": 0, "name": "Path", "type": "string", "max_length": 128 } ] } @@ -279,8 +281,7 @@ layout: the C++ and Python clients always compare against the schema they were g only when `ExpectVersion` is set (generated clients set it, a hand-written one has to do the same). Service and clients have to be updated together. -Moving a `blob` text parameter to `string` keeps the wire layout and needs no bump; moving a `char[N]` one does -(the padding disappears). +Moving a `blob` text parameter to `string` keeps the wire layout, so it needs no bump - as long as the new `max_length` accepts every value the old `blob` accepted. A limit that rejects values which used to work is a behavioural change (the client gets an error where it used to send a call), so that one needs the version bump. **IDs** must be unique within each section (`inputs`, `outputs`, `registers`). @@ -348,6 +349,8 @@ Rules that keep the pool usable: - A lease is **move-only** and returns its block in the destructor. Do not keep it beyond the call that borrowed it: the pool is shared by all services, and a lease held across a flash operation or across RPCs starves the next caller. +- A return value that the framework took from the pool (a `blob`, a large array, a large `string`) is only valid until the handler returns. `SendRpcResponse()` has to be called from inside the handler; + a deferred response would point at a block that is already released and may have been handed to another service by then. - `acquire()` is **non-blocking** on purpose. It returns an empty lease when every block is out, when no storage has been configured yet, and when the request is larger than a block; a handler that follows the pattern above answers BUSY in all three cases - an RPC handler must never wait for diff --git a/codegen/templates/ServiceInterfaceTemplate.cpp b/codegen/templates/ServiceInterfaceTemplate.cpp index d919068..14ee521 100644 --- a/codegen/templates/ServiceInterfaceTemplate.cpp +++ b/codegen/templates/ServiceInterfaceTemplate.cpp @@ -165,6 +165,9 @@ for func in service["functions"]: else: byte_len_expr = f"{p['name']}Len * sizeof({p['type']})" cog.outl(f" {{") + if p['is_string']: + # Before strlen(): a null C string is a caller bug, not a crash. + cog.outl(f" if ({p['name']} == nullptr) return false;") cog.outl(f" const size_t byte_len = {byte_len_expr};") if p['is_string']: cog.outl(f" if (byte_len > {p['max_length']}) return false;") @@ -328,6 +331,7 @@ bool ServiceTemplateInterfaceBase::CallLargeArrayReturn(uint8_t* data, uint16_t& bool ServiceTemplateInterfaceBase::CallStringParamsWithStringReturn(const char* Path, std::string& result, uint32_t timeout_ms) { std::vector params_buf; { + if (Path == nullptr) return false; const size_t byte_len = strlen(Path); if (byte_len > 64) return false; const size_t off = params_buf.size(); diff --git a/codegen/templates/ServiceTemplate.cpp b/codegen/templates/ServiceTemplate.cpp index 97ab3ff..51e0280 100644 --- a/codegen/templates/ServiceTemplate.cpp +++ b/codegen/templates/ServiceTemplate.cpp @@ -388,7 +388,10 @@ if service["functions"]: num_params = len(func["parameters"]) cog.outl(" size_t offset = 0;") cog.outl(" bool parse_ok = true;") - cog.outl(f" uint8_t params_received = 0;") + # One flag per parameter: with a plain counter two descriptors for the same + # parameter stood in for a missing one, and the handler saw an empty default. + for p in func["parameters"]: + cog.outl(f" bool param_{p['name']}_seen = false;") cog.outl(" while (offset + sizeof(xbot::datatypes::DataDescriptor) <= len) {") cog.outl(" const auto* desc = reinterpret_cast(buf + offset);") cog.outl(" offset += sizeof(xbot::datatypes::DataDescriptor);") @@ -397,35 +400,37 @@ if service["functions"]: cog.outl(" switch (desc->target_id) {") for p in func["parameters"]: cog.outl(f" case {p['id']}:") + cog.outl(f" if (param_{p['name']}_seen) {{ parse_ok = false; break; }}") if p['is_blob']: cog.outl(f" param_{p['name']} = buf + offset;") cog.outl(f" param_{p['name']}Len = desc->payload_size;") - cog.outl(f" params_received++;") + cog.outl(f" param_{p['name']}_seen = true;") elif p['is_string']: cog.outl(f" if (desc->payload_size <= {p['max_length']}) {{") cog.outl(f" memcpy(param_{p['name']}, buf + offset, desc->payload_size);") cog.outl(f" param_{p['name']}[desc->payload_size] = '\\0';") cog.outl(f" param_{p['name']}Len = desc->payload_size;") - cog.outl(f" params_received++;") + cog.outl(f" param_{p['name']}_seen = true;") cog.outl(" } else { parse_ok = false; }") elif p['is_array']: cog.outl(f" if (desc->payload_size % sizeof({p['type']}) == 0 &&") cog.outl(f" desc->payload_size <= sizeof(param_{p['name']})) {{") cog.outl(f" memcpy(param_{p['name']}, buf + offset, desc->payload_size);") cog.outl(f" param_{p['name']}Len = desc->payload_size / sizeof({p['type']});") - cog.outl(f" params_received++;") + cog.outl(f" param_{p['name']}_seen = true;") cog.outl(" } else { parse_ok = false; }") else: cog.outl(f" if (desc->payload_size == sizeof({p['type']})) {{") cog.outl(f" memcpy(¶m_{p['name']}, buf + offset, sizeof({p['type']}));") - cog.outl(f" params_received++;") + cog.outl(f" param_{p['name']}_seen = true;") cog.outl(" } else { parse_ok = false; }") cog.outl(" break;") cog.outl(" default: break;") cog.outl(" }") cog.outl(" offset += desc->payload_size;") cog.outl(" }") - cog.outl(f" if (!parse_ok || params_received != {num_params}) {{") + all_seen = " && ".join(f"param_{p['name']}_seen" for p in func["parameters"]) + cog.outl(f" if (!parse_ok || !({all_seen})) {{") cog.outl(" SendRpcResponse(call_id, xbot::datatypes::RpcStatus::ERROR, nullptr, 0);") cog.outl(" return;") cog.outl(" }") @@ -508,7 +513,9 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, uint8_t param_Enable{}; size_t offset = 0; bool parse_ok = true; - uint8_t params_received = 0; + bool param_Speed_seen = false; + bool param_Count_seen = false; + bool param_Enable_seen = false; while (offset + sizeof(xbot::datatypes::DataDescriptor) <= len) { const auto* desc = reinterpret_cast(buf + offset); offset += sizeof(xbot::datatypes::DataDescriptor); @@ -516,28 +523,31 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, if (desc->payload_size > len - offset) { parse_ok = false; break; } switch (desc->target_id) { case 0: + if (param_Speed_seen) { parse_ok = false; break; } if (desc->payload_size == sizeof(float)) { memcpy(¶m_Speed, buf + offset, sizeof(float)); - params_received++; + param_Speed_seen = true; } else { parse_ok = false; } break; case 1: + if (param_Count_seen) { parse_ok = false; break; } if (desc->payload_size == sizeof(uint32_t)) { memcpy(¶m_Count, buf + offset, sizeof(uint32_t)); - params_received++; + param_Count_seen = true; } else { parse_ok = false; } break; case 2: + if (param_Enable_seen) { parse_ok = false; break; } if (desc->payload_size == sizeof(uint8_t)) { memcpy(¶m_Enable, buf + offset, sizeof(uint8_t)); - params_received++; + param_Enable_seen = true; } else { parse_ok = false; } break; default: break; } offset += desc->payload_size; } - if (!parse_ok || params_received != 3) { + if (!parse_ok || !(param_Speed_seen && param_Count_seen && param_Enable_seen)) { SendRpcResponse(call_id, xbot::datatypes::RpcStatus::ERROR, nullptr, 0); return; } @@ -550,7 +560,7 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, uint32_t param_LabelLen = 0; size_t offset = 0; bool parse_ok = true; - uint8_t params_received = 0; + bool param_Label_seen = false; while (offset + sizeof(xbot::datatypes::DataDescriptor) <= len) { const auto* desc = reinterpret_cast(buf + offset); offset += sizeof(xbot::datatypes::DataDescriptor); @@ -558,18 +568,19 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, if (desc->payload_size > len - offset) { parse_ok = false; break; } switch (desc->target_id) { case 0: + if (param_Label_seen) { parse_ok = false; break; } if (desc->payload_size % sizeof(char) == 0 && desc->payload_size <= sizeof(param_Label)) { memcpy(param_Label, buf + offset, desc->payload_size); param_LabelLen = desc->payload_size / sizeof(char); - params_received++; + param_Label_seen = true; } else { parse_ok = false; } break; default: break; } offset += desc->payload_size; } - if (!parse_ok || params_received != 1) { + if (!parse_ok || !(param_Label_seen)) { SendRpcResponse(call_id, xbot::datatypes::RpcStatus::ERROR, nullptr, 0); return; } @@ -583,7 +594,8 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, float param_Value{}; size_t offset = 0; bool parse_ok = true; - uint8_t params_received = 0; + bool param_Name_seen = false; + bool param_Value_seen = false; while (offset + sizeof(xbot::datatypes::DataDescriptor) <= len) { const auto* desc = reinterpret_cast(buf + offset); offset += sizeof(xbot::datatypes::DataDescriptor); @@ -591,24 +603,26 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, if (desc->payload_size > len - offset) { parse_ok = false; break; } switch (desc->target_id) { case 0: + if (param_Name_seen) { parse_ok = false; break; } if (desc->payload_size % sizeof(char) == 0 && desc->payload_size <= sizeof(param_Name)) { memcpy(param_Name, buf + offset, desc->payload_size); param_NameLen = desc->payload_size / sizeof(char); - params_received++; + param_Name_seen = true; } else { parse_ok = false; } break; case 1: + if (param_Value_seen) { parse_ok = false; break; } if (desc->payload_size == sizeof(float)) { memcpy(¶m_Value, buf + offset, sizeof(float)); - params_received++; + param_Value_seen = true; } else { parse_ok = false; } break; default: break; } offset += desc->payload_size; } - if (!parse_ok || params_received != 2) { + if (!parse_ok || !(param_Name_seen && param_Value_seen)) { SendRpcResponse(call_id, xbot::datatypes::RpcStatus::ERROR, nullptr, 0); return; } @@ -621,7 +635,7 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, uint32_t param_DataLen = 0; size_t offset = 0; bool parse_ok = true; - uint8_t params_received = 0; + bool param_Data_seen = false; while (offset + sizeof(xbot::datatypes::DataDescriptor) <= len) { const auto* desc = reinterpret_cast(buf + offset); offset += sizeof(xbot::datatypes::DataDescriptor); @@ -629,15 +643,16 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, if (desc->payload_size > len - offset) { parse_ok = false; break; } switch (desc->target_id) { case 0: + if (param_Data_seen) { parse_ok = false; break; } param_Data = buf + offset; param_DataLen = desc->payload_size; - params_received++; + param_Data_seen = true; break; default: break; } offset += desc->payload_size; } - if (!parse_ok || params_received != 1) { + if (!parse_ok || !(param_Data_seen)) { SendRpcResponse(call_id, xbot::datatypes::RpcStatus::ERROR, nullptr, 0); return; } @@ -673,7 +688,7 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, uint32_t param_PathLen = 0; size_t offset = 0; bool parse_ok = true; - uint8_t params_received = 0; + bool param_Path_seen = false; while (offset + sizeof(xbot::datatypes::DataDescriptor) <= len) { const auto* desc = reinterpret_cast(buf + offset); offset += sizeof(xbot::datatypes::DataDescriptor); @@ -681,18 +696,19 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, if (desc->payload_size > len - offset) { parse_ok = false; break; } switch (desc->target_id) { case 0: + if (param_Path_seen) { parse_ok = false; break; } if (desc->payload_size <= 64) { memcpy(param_Path, buf + offset, desc->payload_size); param_Path[desc->payload_size] = '\0'; param_PathLen = desc->payload_size; - params_received++; + param_Path_seen = true; } else { parse_ok = false; } break; default: break; } offset += desc->payload_size; } - if (!parse_ok || params_received != 1) { + if (!parse_ok || !(param_Path_seen)) { SendRpcResponse(call_id, xbot::datatypes::RpcStatus::ERROR, nullptr, 0); return; } diff --git a/codegen/xbot_codegen/xbot_codegen.py b/codegen/xbot_codegen/xbot_codegen.py index cdfa9ae..78f702a 100644 --- a/codegen/xbot_codegen/xbot_codegen.py +++ b/codegen/xbot_codegen/xbot_codegen.py @@ -398,6 +398,20 @@ def loadService(path: str) -> dict: service["registers"].append(register) + # The frame budget helpers are members of one class, and their names are built from the + # function and parameter names: Write(PathData) and WritePath(Data) both generate + # MaxWritePathData, which cannot compile. The Go validator reserves the same names. + seen_helpers = {} + for func in service["functions"]: + for p in func["parameters"]: + if not (p["is_blob"] or p["is_string"]): + continue + helper = f"Max{func['name']}{p['name']}" + what = f"the frame budget helper of parameter '{p['name']}' of function '{func['name']}'" + if helper in seen_helpers: + raise Exception(f"{seen_helpers[helper]} and {what} both generate {helper}") + seen_helpers[helper] = what + return service diff --git a/xbot_service_interface_py/tests/test_schema.py b/xbot_service_interface_py/tests/test_schema.py index 0184851..f5197bd 100644 --- a/xbot_service_interface_py/tests/test_schema.py +++ b/xbot_service_interface_py/tests/test_schema.py @@ -206,3 +206,38 @@ def test_missing_version(self, echo_schema): def test_version_as_string_coerced(self, echo_schema): # is_compatible coerces version to int, so '1' == 1 is compatible assert echo_schema.is_compatible({'type': 'EchoService', 'version': '1'}) is True + +# --------------------------------------------------------------------------- +# string — max_length has to survive the indexing +# --------------------------------------------------------------------------- + +class TestStringSchema: + """A string declares its limit in max_length; the schema has to carry it into the + indexed entries, otherwise every call rejects the value against a limit of 0.""" + + DESC = { + "type": "X", "version": 1, + "functions": [{ + "id": 0, "name": "Play", "return_type": "string", "max_length": 96, + "parameters": [{"id": 0, "name": "Path", "type": "string", "max_length": 64}], + }], + } + + def test_parameter_max_length_is_indexed(self): + s = ServiceSchema.from_dict(self.DESC) + fn = s.get_function("Play") + assert fn['parameters'][0]['max_length'] == 64 + + def test_return_max_length_is_indexed(self): + s = ServiceSchema.from_dict(self.DESC) + fn = s.get_function("Play") + assert fn['max_length'] == 96 + + def test_plain_types_have_no_limit(self): + d = {"type": "X", "version": 1, "functions": [{ + "id": 0, "name": "F", "return_type": "uint8_t", + "parameters": [{"id": 0, "name": "P", "type": "uint8_t"}], + }]} + fn = ServiceSchema.from_dict(d).get_function("F") + assert fn['max_length'] is None + assert fn['parameters'][0]['max_length'] is None diff --git a/xbot_service_interface_py/xbot_service_interface/schema.py b/xbot_service_interface_py/xbot_service_interface/schema.py index 2a4225c..050f8ed 100644 --- a/xbot_service_interface_py/xbot_service_interface/schema.py +++ b/xbot_service_interface_py/xbot_service_interface/schema.py @@ -155,6 +155,9 @@ def _index_functions(self, items: list) -> dict: 'base_type': pbase, 'is_array': pis_array, 'max_len': pmax_len, + # "string" declares its limit in a separate field; parse_type_string + # knows nothing about it. + 'max_length': p.get('max_length'), }) if return_type != 'void': @@ -165,6 +168,8 @@ def _index_functions(self, items: list) -> dict: 'name': name, 'snake_name': snake, 'return_type': return_type, + # "string" return limit, same field as on a parameter. + 'max_length': item.get('max_length'), 'parameters': params, } by_id[fid] = entry From b073c1a62aff2f46a9e4fc3a8244f44ca02fd7f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Ebeling?= Date: Mon, 16 Nov 2026 23:40:58 +0100 Subject: [PATCH 12/28] Fixed the generator to cap at `max_length` --- .../codegen/generate_test.go | 3 +++ xbot_service_interface_go/codegen/render.go | 16 ++++++++++++++-- .../codegen/testdata/demo_service.golden.go | 4 ++-- .../codegen/testdata/demo_service_noid.golden.go | 4 ++-- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/xbot_service_interface_go/codegen/generate_test.go b/xbot_service_interface_go/codegen/generate_test.go index 52ce71c..67225b8 100644 --- a/xbot_service_interface_go/codegen/generate_test.go +++ b/xbot_service_interface_go/codegen/generate_test.go @@ -247,6 +247,9 @@ func TestStringParameters(t *testing.T) { "return string(payload), nil", // The budget helper treats a string like a blob: variable length. "func MaxPlayPath() int {", + // The helper must not advertise more than the schema accepts, even though the + // packet could carry more. + "return min(64, max(0, xbot.MaxPacketSize-xbot.HeaderSize-", } { if !bytes.Contains(src, []byte(want)) { t.Errorf("generated code does not contain %q", want) diff --git a/xbot_service_interface_go/codegen/render.go b/xbot_service_interface_go/codegen/render.go index f7de968..02d1e0a 100644 --- a/xbot_service_interface_go/codegen/render.go +++ b/xbot_service_interface_go/codegen/render.go @@ -251,13 +251,25 @@ func (g *generator) emitFrameBudgets() { budget += fmt.Sprintf(" - %d", fixed) } - g.f("// Max%s%s is the largest %s payload one %s call can carry.", fnName, targetName, targetName, fnName) + limit := "" + if target.MaxLength > 0 { + limit = fmt.Sprintf(" and never more than the %d bytes the schema accepts", target.MaxLength) + } + g.f("// Max%s%s is the largest %s payload one %s call can carry%s.", fnName, targetName, targetName, fnName, limit) g.line("//") g.line("// One packet of RPC body minus the framing of the call: a descriptor per") g.line("// parameter and the payloads of the fixed parameters. A call whose parameters") g.line("// already use up the packet reports 0, never a negative budget.") g.f("func Max%s%s(%s) int {", fnName, targetName, strings.Join(args, ", ")) - g.f("\treturn max(0, xbot.MaxPacketSize - xbot.HeaderSize - %s%s)", budget, variable.String()) + if target.MaxLength > 0 { + /* The packet could carry more, but the client rejects anything above the + schema's max_length - a helper that advertises more would only lead a + caller into "payload too long". */ + g.f("\treturn min(%d, max(0, xbot.MaxPacketSize - xbot.HeaderSize - %s%s))", target.MaxLength, budget, + variable.String()) + } else { + g.f("\treturn max(0, xbot.MaxPacketSize - xbot.HeaderSize - %s%s)", budget, variable.String()) + } g.line("}") g.line("") } diff --git a/xbot_service_interface_go/codegen/testdata/demo_service.golden.go b/xbot_service_interface_go/codegen/testdata/demo_service.golden.go index 689a4b6..e7dfac5 100644 --- a/xbot_service_interface_go/codegen/testdata/demo_service.golden.go +++ b/xbot_service_interface_go/codegen/testdata/demo_service.golden.go @@ -224,13 +224,13 @@ func (c *Client) LargeStringReturn(ctx context.Context) (string, error) { return string(payload), nil } -// MaxStringParamsWithStringReturnPath is the largest Path payload one StringParamsWithStringReturn call can carry. +// MaxStringParamsWithStringReturnPath is the largest Path payload one StringParamsWithStringReturn call can carry and never more than the 64 bytes the schema accepts. // // One packet of RPC body minus the framing of the call: a descriptor per // parameter and the payloads of the fixed parameters. A call whose parameters // already use up the packet reports 0, never a negative budget. func MaxStringParamsWithStringReturnPath() int { - return max(0, xbot.MaxPacketSize-xbot.HeaderSize-1*xbot.DescriptorSize) + return min(64, max(0, xbot.MaxPacketSize-xbot.HeaderSize-1*xbot.DescriptorSize)) } // SetRegister1 writes the register 0 as a configuration transaction. diff --git a/xbot_service_interface_go/codegen/testdata/demo_service_noid.golden.go b/xbot_service_interface_go/codegen/testdata/demo_service_noid.golden.go index 06b5c20..7124110 100644 --- a/xbot_service_interface_go/codegen/testdata/demo_service_noid.golden.go +++ b/xbot_service_interface_go/codegen/testdata/demo_service_noid.golden.go @@ -221,13 +221,13 @@ func (c *Client) LargeStringReturn(ctx context.Context) (string, error) { return string(payload), nil } -// MaxStringParamsWithStringReturnPath is the largest Path payload one StringParamsWithStringReturn call can carry. +// MaxStringParamsWithStringReturnPath is the largest Path payload one StringParamsWithStringReturn call can carry and never more than the 64 bytes the schema accepts. // // One packet of RPC body minus the framing of the call: a descriptor per // parameter and the payloads of the fixed parameters. A call whose parameters // already use up the packet reports 0, never a negative budget. func MaxStringParamsWithStringReturnPath() int { - return max(0, xbot.MaxPacketSize-xbot.HeaderSize-1*xbot.DescriptorSize) + return min(64, max(0, xbot.MaxPacketSize-xbot.HeaderSize-1*xbot.DescriptorSize)) } // SetRegister1 writes the register 0 as a configuration transaction. From 34a69b2f61c4c450286886f70f4e5d7b47399020 Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 17:12:37 +0100 Subject: [PATCH 13/28] fix(service): check lengths against the bytes that are left The dispatcher already compares a descriptor length with the remaining bytes, but the checks in front of it still added the sizes up first. On a 32 bit target that sum wraps: - runProcessing(): header size + payload_size. A header announcing 0xFFFFFFF0 passed, and every handler got that as its payload length - including the zero copy blob parameters and inputs, which hand it on. - HandleDataTransaction() / SetRegistersFromConfigurationMessage(): a descriptor announcing 0xFFFFFFF8 passed, called the handler with a 4 GB length and did not advance, so the service thread never left the loop. Both transaction parsers now share nextTransactionEntry(), which only ever subtracts from what is left. The same pattern in the host side transaction parser and in the linux packetAppendData() is changed along with it. SendData() also trusted its size: outside a transaction it ignored the result of packetAppendData(), so a blob output above one packet went out as a header that announced a payload the packet did not carry, and reported success. It now refuses such a value and never transmits a packet it could not build. Inside a transaction the space check could wrap for a huge size. --- libxbot-service-interface/src/ServiceIO.cpp | 6 +- libxbot-service/src/Service.cpp | 94 ++++++++++++------- libxbot-service/src/portable/linux/packet.cpp | 4 +- 3 files changed, 68 insertions(+), 36 deletions(-) diff --git a/libxbot-service-interface/src/ServiceIO.cpp b/libxbot-service-interface/src/ServiceIO.cpp index 4161ea2..17668e1 100644 --- a/libxbot-service-interface/src/ServiceIO.cpp +++ b/libxbot-service-interface/src/ServiceIO.cpp @@ -396,11 +396,13 @@ void ServiceIOImpl::HandleDataTransaction(xbot::datatypes::XbotHeader *header, c cb->OnTransactionStart(header->timestamp); // Go through all data packets in the transaction size_t processed_len = 0; - while (processed_len + sizeof(datatypes::DataDescriptor) <= header->payload_size) { + // Both checks compare against the bytes that are left: the sizes come from the wire, and adding + // them up first wraps where size_t has 32 bits. + while (header->payload_size - processed_len >= sizeof(datatypes::DataDescriptor)) { // we have at least enough data for the next descriptor, read it const auto descriptor = reinterpret_cast(payload + processed_len); size_t data_size = descriptor->payload_size; - if (processed_len + sizeof(datatypes::DataDescriptor) + data_size <= header->payload_size) { + if (data_size <= header->payload_size - processed_len - sizeof(datatypes::DataDescriptor)) { // we can safely read the data cb->OnData(service_id, header->timestamp, descriptor->target_id, payload + processed_len + sizeof(datatypes::DataDescriptor), data_size); diff --git a/libxbot-service/src/Service.cpp b/libxbot-service/src/Service.cpp index f0236c8..7e422d4 100644 --- a/libxbot-service/src/Service.cpp +++ b/libxbot-service/src/Service.cpp @@ -94,8 +94,10 @@ void xbot::service::Service::OnServiceDiscoveryTimeout() { bool xbot::service::Service::SendData(uint16_t target_id, const void *data, size_t size) { if (transaction_started_) { - // We are using a transaction, append the data - if (scratch_buffer_fill_ + size + sizeof(datatypes::DataDescriptor) <= sizeof(scratch_buffer_)) { + // We are using a transaction, append the data. Compare against the space that is left instead of + // adding up: a large size must not wrap the sum on a 32 bit target. + const size_t space = sizeof(scratch_buffer_) - scratch_buffer_fill_; + if (space >= sizeof(datatypes::DataDescriptor) && size <= space - sizeof(datatypes::DataDescriptor)) { // add the size to the header // we can fit the data, write descriptor and data auto descriptor_ptr = reinterpret_cast(scratch_buffer_ + scratch_buffer_fill_); @@ -115,8 +117,16 @@ bool xbot::service::Service::SendData(uint16_t target_id, const void *data, size ULOG_ARG_DEBUG(&service_id_, "Service has no target, dropping packet"); return false; } + // A value has to fit into one packet. Fixed size outputs always do, a blob output is only bounded here: + // without this check the header would announce a payload that the packet does not carry. + if (size > config::max_packet_size - sizeof(datatypes::XbotHeader)) { + ULOG_ARG_ERROR(&service_id_, "SendData: %u bytes do not fit into one packet, dropping", + static_cast(size)); + return false; + } // Send header and data packet::PacketPtr ptr = packet::allocatePacket(); + bool appended; { Lock lk(&state_mutex_); fillHeader(); @@ -124,9 +134,15 @@ bool xbot::service::Service::SendData(uint16_t target_id, const void *data, size header_.payload_size = size; header_.arg2 = target_id; - packet::packetAppendData(ptr, &header_, sizeof(header_)); + appended = packet::packetAppendData(ptr, &header_, sizeof(header_)); + } + appended = appended && packet::packetAppendData(ptr, data, size); + if (!appended) { + // Never transmit a packet whose header does not match its body. + ULOG_ARG_ERROR(&service_id_, "SendData: could not build the packet, dropping"); + packet::freePacket(ptr); + return false; } - packet::packetAppendData(ptr, data, size); return Io::transmitPacket(ptr, target_ip_, target_port_); } @@ -261,7 +277,9 @@ void xbot::service::Service::runProcessing() { } const auto header = reinterpret_cast(buffer); const uint8_t *const payload_buffer = reinterpret_cast(buffer) + sizeof(datatypes::XbotHeader); - if (sizeof(datatypes::XbotHeader) + header->payload_size > used_data) { + // Compare against the bytes behind the header instead of adding up: payload_size comes from the + // wire, and header size + payload_size wraps on a 32 bit target. + if (header->payload_size > used_data - sizeof(datatypes::XbotHeader)) { ULOG_ARG_WARNING(&service_id_, "Payload size exceeds packet data, dropping"); packet::freePacket(packet); continue; @@ -320,6 +338,34 @@ namespace { API), so without a limit the service works as a reflector. 20 ms keeps a 64 KiB description - about 45 windows - fetchable in well under a second. */ constexpr uint32_t kDescriptionPartIntervalMicros = 20000U; + +/* Step to the next DataDescriptor + payload of a transaction body. Returns false at the end of the body + and on a descriptor that announces more bytes than the body has left; the caller tells the two apart + by comparing processed_len with payload_len. + + Every check compares against the bytes that are left. The sizes come from the wire, and adding them + up first ("processed_len + descriptor + data_size <= payload_len") wraps on a 32 bit target: a + descriptor with payload_size 0xFFFFFFF8 then passes, hands the callback a 4 GB length and does not + advance processed_len, which never ends the loop. */ +bool nextTransactionEntry(const uint8_t *payload, size_t payload_len, size_t &processed_len, uint16_t &target_id, + const void *&data, size_t &data_size) { + using xbot::datatypes::DataDescriptor; + if (processed_len > payload_len || payload_len - processed_len < sizeof(DataDescriptor)) { + return false; + } + // The descriptor is packed and sits at an arbitrary offset, so read it through a copy. + DataDescriptor descriptor; + memcpy(&descriptor, payload + processed_len, sizeof(descriptor)); + const size_t data_offset = processed_len + sizeof(DataDescriptor); + if (descriptor.payload_size > payload_len - data_offset) { + return false; + } + target_id = descriptor.target_id; + data = payload + data_offset; + data_size = descriptor.payload_size; + processed_len = data_offset + data_size; + return true; +} } // namespace void xbot::service::Service::HandleDescriptionRequest(xbot::datatypes::XbotHeader *header, const void *payload, @@ -438,19 +484,11 @@ void xbot::service::Service::HandleDataTransaction(xbot::datatypes::XbotHeader * const auto payload_buffer = static_cast(payload); // Go through all data packets in the transaction size_t processed_len = 0; - while (processed_len + sizeof(datatypes::DataDescriptor) <= payload_len) { - // we have at least enough data for the next descriptor, read it - const auto descriptor = reinterpret_cast(payload_buffer + processed_len); - size_t data_size = descriptor->payload_size; - if (processed_len + sizeof(datatypes::DataDescriptor) + data_size <= payload_len) { - // we can safely read the data - handleData(descriptor->target_id, payload_buffer + processed_len + sizeof(datatypes::DataDescriptor), data_size); - } else { - // error parsing transaction, payload size does not match - // transaction size! - break; - } - processed_len += data_size + sizeof(datatypes::DataDescriptor); + const void *data = nullptr; + uint16_t target_id = 0; + size_t data_size = 0; + while (nextTransactionEntry(payload_buffer, payload_len, processed_len, target_id, data, data_size)) { + handleData(target_id, data, data_size); } if (processed_len != payload_len) { @@ -501,21 +539,13 @@ bool xbot::service::Service::SetRegistersFromConfigurationMessage(const void *pa // Go through all data packets in the transaction size_t processed_len = 0; - while (processed_len + sizeof(datatypes::DataDescriptor) <= payload_len) { - // we have at least enough data for the next descriptor, read it - const auto descriptor = reinterpret_cast(payload_buffer + processed_len); - size_t data_size = descriptor->payload_size; - if (processed_len + sizeof(datatypes::DataDescriptor) + data_size <= payload_len) { - // we can safely read the data - const void *data = payload_buffer + processed_len + sizeof(datatypes::DataDescriptor); - if (!setRegister(descriptor->target_id, data, data_size)) { - return false; - } - } else { - // Error parsing transaction, payload size does not match transaction size! - break; + const void *data = nullptr; + uint16_t target_id = 0; + size_t data_size = 0; + while (nextTransactionEntry(payload_buffer, payload_len, processed_len, target_id, data, data_size)) { + if (!setRegister(target_id, data, data_size)) { + return false; } - processed_len += data_size + sizeof(datatypes::DataDescriptor); } if (processed_len != payload_len) { diff --git a/libxbot-service/src/portable/linux/packet.cpp b/libxbot-service/src/portable/linux/packet.cpp index d2b0893..a839833 100644 --- a/libxbot-service/src/portable/linux/packet.cpp +++ b/libxbot-service/src/portable/linux/packet.cpp @@ -27,8 +27,8 @@ void xbot::service::packet::freePacket(PacketPtr packet_ptr) { bool xbot::service::packet::packetAppendData(PacketPtr packet, const void *buffer, size_t size) { if (packet == nullptr) return false; - // Data won't fit. - if (size + packet->used_data > config::max_packet_size) return false; + // Data won't fit. Compared against the space that is left, so a huge size cannot wrap the sum. + if (packet->used_data > config::max_packet_size || size > config::max_packet_size - packet->used_data) return false; memcpy(packet->buffer + packet->used_data, buffer, size); packet->used_data += size; From 4b96366fd7b7925ffb9a87caa0bbdbca790167db Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 17:12:37 +0100 Subject: [PATCH 14/28] fix(buffer): refuse a pool that cannot hold a return value initialize() accepted any block size, while the generated dispatchers only assert against the compile time xbot::config::buffer_block_size. A platform pool with 512 byte blocks compiled, and then every blob or large array return was answered with BUSY forever, without a log line. The limit now has a name, buffer::min_block_size (one packet without its header), and initialize() refuses blocks below it. acquire() logs a request that is larger than a block: unlike an exhausted pool that is not a transient condition. XBOT_BUFFER_DEFAULT_POOL, _BLOCK_SIZE and _BLOCK_COUNT are read when the library is compiled, so defining them on the application target left the default array in place. They can be set as CMake variables now and are PUBLIC definitions of xbot-service, so the library and the generated services always see the same values. The comments said a block is only out for microseconds. It is out for as long as the handler runs, because the dispatcher borrows it before the call; they say so now, and that a block is handed out with the content of its previous owner. BufferTests: blocks of the minimum size instead of 128 bytes, and static storage - the pool keeps the pointer, a member of the test group dangled for every group that ran afterwards. --- include/xbot/config.hpp | 14 +++-- libxbot-service/CMakeLists.txt | 8 +++ .../include/xbot-service/Buffer.hpp | 33 +++++++++--- libxbot-service/src/Buffer.cpp | 26 ++++++--- .../test/BufferTests/BufferTests.cpp | 53 ++++++++++++++++--- 5 files changed, 110 insertions(+), 24 deletions(-) diff --git a/include/xbot/config.hpp b/include/xbot/config.hpp index b987ce6..357f401 100644 --- a/include/xbot/config.hpp +++ b/include/xbot/config.hpp @@ -76,6 +76,11 @@ static_assert(max_log_length > 100); * itself (hosts, tests, examples). A platform that brings its own storage - * e.g. a section in a RAM region that is otherwise unused - sets this to 0 and * calls buffer::initialize() instead, so the static array is not linked in. + * + * The three macros are read when the xbot-service library itself is compiled. + * Set them through the CMake cache variables of the same name (-DXBOT_BUFFER_DEFAULT_POOL=0), + * which define them for the library and for everything that links it; a + * definition on the application target alone does not reach Buffer.cpp. */ #ifndef XBOT_BUFFER_BLOCK_SIZE #define XBOT_BUFFER_BLOCK_SIZE 1536 @@ -94,10 +99,11 @@ static_assert(max_log_length > 100); */ static constexpr uint16_t buffer_block_size = XBOT_BUFFER_BLOCK_SIZE; /** - * Number of blocks that can be out at the same time. A block is only held while - * an RPC fills and sends its return value, so this is about concurrency, not - * about the number of services: two blocks leave room for a slow transfer next - * to a quick one. + * Number of blocks that can be out at the same time. A block is held while the + * handler of a pooled RPC runs (a blob return, a large array or string return), + * so this is about concurrency, not about the number of services: two blocks + * leave room for a slow handler next to a quick one. A call that finds no free + * block is answered with BUSY. */ static constexpr uint8_t buffer_block_count = XBOT_BUFFER_BLOCK_COUNT; diff --git a/libxbot-service/CMakeLists.txt b/libxbot-service/CMakeLists.txt index f3d3db3..7b28faf 100644 --- a/libxbot-service/CMakeLists.txt +++ b/libxbot-service/CMakeLists.txt @@ -33,6 +33,14 @@ target_sources(xbot-service PRIVATE ${PORT_SOURCES}) target_include_directories(xbot-service PUBLIC include ../include) + +# Shared RPC buffer pool (see include/xbot/config.hpp). The values are compiled into Buffer.cpp and +# into the generated services, so they are PUBLIC: both always see the same pool configuration. +foreach (BUFFER_OPTION XBOT_BUFFER_DEFAULT_POOL XBOT_BUFFER_BLOCK_SIZE XBOT_BUFFER_BLOCK_COUNT) + if (DEFINED ${BUFFER_OPTION}) + target_compile_definitions(xbot-service PUBLIC ${BUFFER_OPTION}=${${BUFFER_OPTION}}) + endif () +endforeach () target_link_libraries(xbot-service PUBLIC ulog ${XBOT_CUSTOM_PORT_LIBS} heatshrink) install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/ diff --git a/libxbot-service/include/xbot-service/Buffer.hpp b/libxbot-service/include/xbot-service/Buffer.hpp index c7f4dce..9195f3f 100644 --- a/libxbot-service/include/xbot-service/Buffer.hpp +++ b/libxbot-service/include/xbot-service/Buffer.hpp @@ -7,9 +7,20 @@ #include #include +#include +#include namespace xbot::service::buffer { +/** + * @brief Smallest block size a pool may have: the largest RPC return value, i.e. one packet without + * its header. + * + * The generated dispatchers borrow up to this many bytes. A pool with smaller blocks could never serve + * them and would answer BUSY forever, so initialize() refuses it. + */ +static constexpr size_t min_block_size = xbot::config::max_packet_size - sizeof(xbot::datatypes::XbotHeader); + /** @brief Highest number of blocks the pool bitmap can hold. */ static constexpr uint8_t max_block_count = 32; @@ -28,6 +39,10 @@ static constexpr uint8_t invalid_index = 0xFF; * Do not keep a lease beyond the call that borrowed it. The pool is shared by * all services: a lease that is held across a flash erase or across RPCs starves * the next caller, which then has to answer BUSY. + * + * A block is handed out as it was returned: it still holds what the previous + * owner wrote. Clear it before use if anything but the bytes written by the new + * owner may be sent (the generated dispatchers do). */ class Lease { public: @@ -75,9 +90,9 @@ class Lease { * XBOT_BUFFER_DEFAULT_POOL to 0, which removes the framework default array. * * @param storage start of the storage, block_alignment aligned - * @param block_size bytes per block, must hold the largest RPC return value + * @param block_size bytes per block, a multiple of block_alignment and at least min_block_size * @param block_count number of blocks, 1..max_block_count - * @return false if an argument is unusable or a lease is still out + * @return false if an argument is unusable or a lease is still out; the pool then stays as it was */ bool initialize(void *storage, size_t block_size, size_t block_count); @@ -85,12 +100,16 @@ bool initialize(void *storage, size_t block_size, size_t block_count); * @brief Borrow a block that holds at least @p bytes. * * Deliberately non-blocking: an RPC handler must never wait for a slow transfer - * on another service, it answers BUSY instead. A timeout would not help either, - * because a block is only held while a return value is filled and copied into a - * packet, i.e. for microseconds, not for the duration of an upload. + * on another service, it answers BUSY instead. + * + * The generated dispatchers borrow the block before they call the handler and + * return it when the handler returns, so a block is out for as long as the + * handler runs - not only while the return value is copied into a packet. Size + * the pool (buffer_block_count) for the number of pooled RPCs that can be in + * their handlers at the same time. * - * @return An empty lease if the request is larger than a block or every block is - * out. + * @return An empty lease if the pool has no storage yet, the request is larger + * than a block or every block is out. */ Lease acquire(size_t bytes); diff --git a/libxbot-service/src/Buffer.cpp b/libxbot-service/src/Buffer.cpp index 2f0eb19..f0366fe 100644 --- a/libxbot-service/src/Buffer.cpp +++ b/libxbot-service/src/Buffer.cpp @@ -7,8 +7,6 @@ #include #include #include -#include -#include namespace { @@ -16,9 +14,9 @@ using xbot::service::buffer::invalid_index; using xbot::service::buffer::Lease; // A return value has to fit into one packet, so a block never has to be larger -// than that. Keeping the invariant here catches a pool that was sized for -// something smaller. -static_assert(xbot::config::buffer_block_size >= xbot::config::max_packet_size - sizeof(xbot::datatypes::XbotHeader), +// than that. Keeping the invariant here catches a default pool that was sized +// for something smaller; initialize() checks the same for a platform pool. +static_assert(xbot::config::buffer_block_size >= xbot::service::buffer::min_block_size, "buffer_block_size must hold the largest possible RPC return value"); static_assert(xbot::config::buffer_block_count >= 1U, "the buffer pool needs at least one block"); static_assert(xbot::config::buffer_block_count <= xbot::service::buffer::max_block_count, @@ -52,9 +50,10 @@ size_t block_count_ = 0; // working unchanged. std::atomic used_mask_{0}; -// Guards the "not initialized" log line only, so a plain bool is enough: the -// worst case is a duplicated line. +// Guard the "not initialized" and "request too large" log lines only, so a plain +// bool is enough: the worst case is a duplicated line. bool warned_uninitialized_ = false; +bool warned_oversized_ = false; uint32_t blockBit(uint8_t index) { return uint32_t{1} << index; @@ -110,6 +109,13 @@ bool xbot::service::buffer::initialize(void *storage, size_t block_size, size_t if ((block_size % block_alignment) != 0U) { return false; // a block stride that is not aligned would misalign every later lease } + if (block_size < min_block_size) { + // The generated dispatchers borrow up to min_block_size bytes and only know the compile time + // configuration, not this pool. Smaller blocks would compile and then answer BUSY forever. + ULOG_ERROR("Buffer pool: blocks of %u bytes cannot hold an RPC return value (%u bytes), pool not changed", + static_cast(block_size), static_cast(min_block_size)); + return false; + } if (used_mask_.load(std::memory_order_relaxed) != 0U) { return false; // a lease is still out, keep the current storage alive } @@ -130,6 +136,12 @@ xbot::service::buffer::Lease xbot::service::buffer::acquire(size_t bytes) { return {}; } if (bytes > block_size_) { + // Not a transient condition like an exhausted pool: this request can never succeed. + if (!warned_oversized_) { + warned_oversized_ = true; + ULOG_ERROR("Buffer pool: request of %u bytes exceeds the block size of %u bytes", static_cast(bytes), + static_cast(block_size_)); + } return {}; } diff --git a/libxbot-service/test/BufferTests/BufferTests.cpp b/libxbot-service/test/BufferTests/BufferTests.cpp index 2ac19d9..ac846ff 100644 --- a/libxbot-service/test/BufferTests/BufferTests.cpp +++ b/libxbot-service/test/BufferTests/BufferTests.cpp @@ -2,6 +2,7 @@ // Tests for the shared RPC buffer pool. // +#include #include #include @@ -9,18 +10,28 @@ using namespace xbot::service; -TEST_GROUP(BufferTests) { - // The tests bring their own storage, so they do not depend on (or disturb) - // the framework default pool. - alignas(buffer::block_alignment) uint8_t storage_[2 * 128]{}; +namespace { +constexpr size_t kBlocks = 2; +// The smallest block a pool accepts, rounded up to the block alignment. +constexpr size_t kBlockSize = + (buffer::min_block_size + buffer::block_alignment - 1) / buffer::block_alignment * buffer::block_alignment; - static constexpr size_t kBlocks = 2; - static constexpr size_t kBlockSize = 128; +// The tests bring their own storage, so they do not depend on the framework +// default pool. It is static on purpose: initialize() keeps the pointer, and a +// member of the test group would dangle for every test that runs afterwards. +alignas(buffer::block_alignment) uint8_t storage_[kBlocks * kBlockSize]{}; +} // namespace +TEST_GROUP(BufferTests) { void setup() override { CHECK_TRUE(buffer::initialize(storage_, kBlockSize, kBlocks)); CHECK_EQUAL(kBlocks, buffer::available()); } + + void teardown() override { + // Every lease of a test is gone by now; a leaked one would poison the next test. + CHECK_EQUAL(kBlocks, buffer::available()); + } }; TEST(BufferTests, AcquireReturnsBlockCapacity) { @@ -104,6 +115,36 @@ TEST(BufferTests, InitializeRejectsBadArguments) { CHECK_FALSE(buffer::initialize(storage_, kBlockSize + 1, kBlocks)); // unaligned block stride } +TEST(BufferTests, InitializeRejectsBlocksBelowOneReturnValue) { + // The generated dispatchers borrow up to min_block_size bytes. A pool that + // cannot serve that would answer BUSY forever, so it is refused up front. + alignas(buffer::block_alignment) static uint8_t small[2 * 512]; + CHECK_FALSE(buffer::initialize(small, 512, 2)); + CHECK_FALSE(buffer::initialize(storage_, kBlockSize - buffer::block_alignment, kBlocks)); + + // A refused call leaves the pool as it was. + CHECK_EQUAL(kBlockSize, buffer::blockSize()); + CHECK_EQUAL(kBlocks, buffer::blockCount()); + buffer::Lease lease = buffer::acquire(buffer::min_block_size); + CHECK_TRUE(lease); + CHECK_TRUE(lease.data() == storage_); +} + +TEST(BufferTests, ReacquiredBlockKeepsThePreviousContent) { + // Documented contract: acquire() does not clear a block. The generated + // dispatchers rely on knowing that and clear the bytes they hand out. + { + buffer::Lease lease = buffer::acquire(16); + CHECK_TRUE(lease); + memset(lease.data(), 0xA5, 16); + } + buffer::Lease again = buffer::acquire(16); + CHECK_TRUE(again); + CHECK_TRUE(again.data() == storage_); + BYTES_EQUAL(0xA5, again.data()[0]); + BYTES_EQUAL(0xA5, again.data()[15]); +} + TEST(BufferTests, InitializeRefusesWhileALeaseIsOut) { buffer::Lease lease = buffer::acquire(10); CHECK_TRUE(lease); From 552ad6beb3262d3202eca88bd55978cd63d05a73 Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 17:12:56 +0100 Subject: [PATCH 15/28] fix(codegen): hand handlers a cleared return buffer, bound the parameters Pooled return buffers were passed to the handler as the previous owner of the block left them, while the stack buffers they replace are zero-filled. A char[200] return that used to go out NUL padded carried the tail of another service's response, and a large string handler that relied on the fill for its terminator ran into stale bytes. The dispatcher clears what it borrows now, so a return buffer behaves the same wherever it comes from. The blob branch was a copy of the pooled branch; both are one path, sized by buffer::min_block_size instead of a literal 1448 baked into the firmware, and asserted against that minimum instead of the compile time block size - which says nothing about the pool a platform installs. The comments claimed that the dispatcher sends the bytes a handler reports and appends the terminator of a string. It does neither: a handler that relied on that never answered, and the service replied BUSY until its next restart. They now describe the contract every return type has - the handler calls SendRpcResponse(). String parameters are no longer zero-filled on every call: the parser writes the value and its terminator, and the handler only runs if it did. Each parameter was checked against one packet on its own, so two 1440 byte strings were accepted and reserved 2882 bytes of dispatcher stack for a call that can never carry both. The declared maxima of a function have to fit into one packet together now. The packet sizes the generator validates against are three named constants instead of 1472 - 24 - 8 spelled out per use, and the generated service asserts that they still match xbot::config and the wire structs. --- codegen/templates/ServiceTemplate.cpp | 108 ++++++++++++++++---------- codegen/templates/ServiceTemplate.hpp | 13 +++- codegen/xbot_codegen/xbot_codegen.py | 60 +++++++++++--- 3 files changed, 127 insertions(+), 54 deletions(-) diff --git a/codegen/templates/ServiceTemplate.cpp b/codegen/templates/ServiceTemplate.cpp index 51e0280..94f11c2 100644 --- a/codegen/templates/ServiceTemplate.cpp +++ b/codegen/templates/ServiceTemplate.cpp @@ -3,7 +3,8 @@ /*[[[cog import cog -from xbot_codegen import MAX_RPC_RETURN_BYTES, loadService, needsBufferPool, pooledReturnBytes, toCamelCase +from xbot_codegen import (DESCRIPTOR_SIZE, HEADER_SIZE, MAX_PACKET_SIZE, loadService, needsBufferPool, + pooledReturnBytes, pooledReturnBytesExpr, toCamelCase) service = loadService(service_file) @@ -25,9 +26,23 @@ if needsBufferPool(service): /*[[[cog cog.outl(f"constexpr unsigned char {service['class_name']}::SERVICE_DESCRIPTION_CBOR[];") cog.outl(f"constexpr unsigned char {service['class_name']}::SERVICE_OMITTED_CBOR[];") +cog.outl("") +cog.outl("// The code generator validated the schema against these wire sizes (xbot_codegen.py). If one of") +cog.outl("// them changes, the limits it checked are stale: update the generator instead of this assert.") +cog.outl(f"static_assert(xbot::config::max_packet_size == {MAX_PACKET_SIZE} &&") +cog.outl(f" sizeof(xbot::datatypes::XbotHeader) == {HEADER_SIZE} &&") +cog.outl(f" sizeof(xbot::datatypes::DataDescriptor) == {DESCRIPTOR_SIZE},") +cog.outl(' "xbot_codegen.py was written for a different packet layout");') ]]]*/ constexpr unsigned char ServiceTemplateBase::SERVICE_DESCRIPTION_CBOR[]; constexpr unsigned char ServiceTemplateBase::SERVICE_OMITTED_CBOR[]; + +// The code generator validated the schema against these wire sizes (xbot_codegen.py). If one of +// them changes, the limits it checked are stale: update the generator instead of this assert. +static_assert(xbot::config::max_packet_size == 1472 && + sizeof(xbot::datatypes::XbotHeader) == 24 && + sizeof(xbot::datatypes::DataDescriptor) == 8, + "xbot_codegen.py was written for a different packet layout"); //[[[end]]] @@ -376,7 +391,11 @@ if service["functions"]: elif p['is_string']: # One byte more than the limit: the value is terminated here, once, so the # handler can hand it to LittleFS, printf or a JSON parser without a copy. - cog.outl(f" char param_{p['name']}[{p['max_length']} + 1] = {{}};") + # Not zero-filled: the parser below writes the value and its terminator, and + # the handler only runs if it did. Clearing up to 1441 bytes per call would + # be paid for nothing. + cog.outl(f" char param_{p['name']}[{p['max_length']} + 1];") + cog.outl(f" param_{p['name']}[0] = '\\0';") cog.outl(f" uint32_t param_{p['name']}Len = 0;") elif p['is_array']: cog.outl(f" {p['type']} param_{p['name']}[{p['max_length']}] = {{}};") @@ -385,7 +404,6 @@ if service["functions"]: cog.outl(f" {p['type']} param_{p['name']}{{}};") # Deserialize params from DataDescriptor stream if func["parameters"]: - num_params = len(func["parameters"]) cog.outl(" size_t offset = 0;") cog.outl(" bool parse_ok = true;") # One flag per parameter: with a plain counter two descriptors for the same @@ -441,37 +459,40 @@ if service["functions"]: call_args.append(f"param_{p['name']}, param_{p['name']}Len") else: call_args.append(f"param_{p['name']}") - # Return storage: small arrays stay on the stack, everything larger and blob - # returns come from the shared buffer pool. The lease is released when this case - # ends, so the handler has to call SendRpcResponse() before it returns. + # Return storage. The handler gets a zero-filled buffer and its capacity, fills it and + # calls SendRpcResponse() itself - the dispatcher never sends a return value and does + # not read *response_length back. Small arrays and strings live on the stack, + # everything larger and every blob comes from the shared buffer pool. The lease ends + # with this case, so the handler has to call SendRpcResponse() before it returns. pooled_bytes = pooledReturnBytes(service, func) - if func['return_is_blob']: - cog.outl(f" constexpr uint16_t kMaxRpcReturn = {MAX_RPC_RETURN_BYTES};") - cog.outl(" static_assert(kMaxRpcReturn <= xbot::config::buffer_block_size,") - cog.outl(' "blob return does not fit into a buffer pool block");') - cog.outl(" auto rpc_ret_lease = xbot::service::buffer::acquire(kMaxRpcReturn);") + if pooled_bytes is not None: + ret_type = "uint8_t" if func['return_is_blob'] else "char" if func['return_is_string'] else func['return_base_type'] + cog.outl(f" constexpr size_t kRpcReturnBytes = {pooledReturnBytesExpr(func)};") + if not func['return_is_blob']: + # Every pool holds blocks of at least min_block_size (buffer::initialize() + # refuses smaller ones), so this is all that has to be checked here. + cog.outl(" static_assert(kRpcReturnBytes <= xbot::service::buffer::min_block_size,") + cog.outl(' "return value does not fit into a buffer pool block");') + cog.outl(" auto rpc_ret_lease = xbot::service::buffer::acquire(kRpcReturnBytes);") cog.outl(" if (!rpc_ret_lease) {") cog.outl(" SendRpcResponse(call_id, xbot::datatypes::RpcStatus::BUSY, nullptr, 0);") cog.outl(" return;") cog.outl(" }") - cog.outl(" uint16_t rpc_ret_len = kMaxRpcReturn;") - call_args.append("rpc_ret_lease.data(), &rpc_ret_len") - elif func['return_is_string'] and pooled_bytes is None: - # Terminated locally: the handler writes text, the dispatcher sends the bytes - # it reported (without the terminator). - cog.outl(f" char rpc_ret_buf[{func['return_max_length']} + 1] = {{}};") - cog.outl(f" uint16_t rpc_ret_len = {func['return_max_length']};") + # A block still holds what its previous owner - possibly another service - wrote. + # Stack buffers are zero-filled, so handlers may rely on that (NUL padding of a + # char[N], the terminator of a string); a pooled buffer has to behave the same. + cog.outl(" memset(rpc_ret_lease.data(), 0, kRpcReturnBytes);") + cog.outl(f" auto* rpc_ret_buf = reinterpret_cast<{ret_type}*>(rpc_ret_lease.data());") + if func['return_is_blob']: + cog.outl(" uint16_t rpc_ret_len = static_cast(kRpcReturnBytes);") + else: + cog.outl(f" uint16_t rpc_ret_len = {func['return_max_length']};") call_args.append("rpc_ret_buf, &rpc_ret_len") - elif pooled_bytes is not None: - cog.outl(f" static_assert({pooled_bytes} <= xbot::config::buffer_block_size,") - cog.outl(' "return value does not fit into a buffer pool block");') - cog.outl(f" auto rpc_ret_lease = xbot::service::buffer::acquire({pooled_bytes});") - cog.outl(" if (!rpc_ret_lease) {") - cog.outl(" SendRpcResponse(call_id, xbot::datatypes::RpcStatus::BUSY, nullptr, 0);") - cog.outl(" return;") - cog.outl(" }") - pooled_base_type = "char" if func["return_is_string"] else func["return_base_type"] - cog.outl(f" auto* rpc_ret_buf = reinterpret_cast<{pooled_base_type}*>(rpc_ret_lease.data());") + elif func['return_is_string']: + # One byte more than max_length, so the text the handler writes is terminated + # even when it uses the whole limit. The terminator stays local: the handler + # sends strlen() bytes. + cog.outl(f" char rpc_ret_buf[{func['return_max_length']} + 1] = {{}};") cog.outl(f" uint16_t rpc_ret_len = {func['return_max_length']};") call_args.append("rpc_ret_buf, &rpc_ret_len") elif func['return_is_array']: @@ -483,7 +504,7 @@ if service["functions"]: if func['return_type'] == 'void': cog.outl(f" rpc_max_response_size_ = 0;") elif func['return_is_blob']: - cog.outl(f" rpc_max_response_size_ = kMaxRpcReturn;") + cog.outl(f" rpc_max_response_size_ = kRpcReturnBytes;") elif func['return_is_string']: cog.outl(f" rpc_max_response_size_ = {func['return_max_length']};") elif func['return_is_array']: @@ -656,27 +677,29 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, SendRpcResponse(call_id, xbot::datatypes::RpcStatus::ERROR, nullptr, 0); return; } - constexpr uint16_t kMaxRpcReturn = 1448; - static_assert(kMaxRpcReturn <= xbot::config::buffer_block_size, - "blob return does not fit into a buffer pool block"); - auto rpc_ret_lease = xbot::service::buffer::acquire(kMaxRpcReturn); + constexpr size_t kRpcReturnBytes = xbot::service::buffer::min_block_size; + auto rpc_ret_lease = xbot::service::buffer::acquire(kRpcReturnBytes); if (!rpc_ret_lease) { SendRpcResponse(call_id, xbot::datatypes::RpcStatus::BUSY, nullptr, 0); return; } - uint16_t rpc_ret_len = kMaxRpcReturn; - rpc_max_response_size_ = kMaxRpcReturn; - RPCBlobParamsWithBlobReturn(call_id, param_Data, param_DataLen, rpc_ret_lease.data(), &rpc_ret_len); + memset(rpc_ret_lease.data(), 0, kRpcReturnBytes); + auto* rpc_ret_buf = reinterpret_cast(rpc_ret_lease.data()); + uint16_t rpc_ret_len = static_cast(kRpcReturnBytes); + rpc_max_response_size_ = kRpcReturnBytes; + RPCBlobParamsWithBlobReturn(call_id, param_Data, param_DataLen, rpc_ret_buf, &rpc_ret_len); return; } case 5: { - static_assert(256 <= xbot::config::buffer_block_size, + constexpr size_t kRpcReturnBytes = 256 * sizeof(uint8_t); + static_assert(kRpcReturnBytes <= xbot::service::buffer::min_block_size, "return value does not fit into a buffer pool block"); - auto rpc_ret_lease = xbot::service::buffer::acquire(256); + auto rpc_ret_lease = xbot::service::buffer::acquire(kRpcReturnBytes); if (!rpc_ret_lease) { SendRpcResponse(call_id, xbot::datatypes::RpcStatus::BUSY, nullptr, 0); return; } + memset(rpc_ret_lease.data(), 0, kRpcReturnBytes); auto* rpc_ret_buf = reinterpret_cast(rpc_ret_lease.data()); uint16_t rpc_ret_len = 256; rpc_max_response_size_ = 256 * sizeof(uint8_t); @@ -684,7 +707,8 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, return; } case 6: { - char param_Path[64 + 1] = {}; + char param_Path[64 + 1]; + param_Path[0] = '\0'; uint32_t param_PathLen = 0; size_t offset = 0; bool parse_ok = true; @@ -719,13 +743,15 @@ void ServiceTemplateBase::dispatchRpcCall(uint8_t function_id, uint16_t call_id, return; } case 7: { - static_assert(201 <= xbot::config::buffer_block_size, + constexpr size_t kRpcReturnBytes = 200 + 1; + static_assert(kRpcReturnBytes <= xbot::service::buffer::min_block_size, "return value does not fit into a buffer pool block"); - auto rpc_ret_lease = xbot::service::buffer::acquire(201); + auto rpc_ret_lease = xbot::service::buffer::acquire(kRpcReturnBytes); if (!rpc_ret_lease) { SendRpcResponse(call_id, xbot::datatypes::RpcStatus::BUSY, nullptr, 0); return; } + memset(rpc_ret_lease.data(), 0, kRpcReturnBytes); auto* rpc_ret_buf = reinterpret_cast(rpc_ret_lease.data()); uint16_t rpc_ret_len = 200; rpc_max_response_size_ = 200; diff --git a/codegen/templates/ServiceTemplate.hpp b/codegen/templates/ServiceTemplate.hpp index 0244b04..4a270f2 100644 --- a/codegen/templates/ServiceTemplate.hpp +++ b/codegen/templates/ServiceTemplate.hpp @@ -397,10 +397,17 @@ class ServiceTemplateBase : public xbot::service::Service { # call_id is passed so the implementation can respond asynchronously via SendRpcResponse(). # Blob parameters are passed as (pointer, length) into the received packet: no copy and # no size limit, valid until the handler returns. - # For array return types: data buffer (max capacity) and response_length (init to max) are - # appended. The implementation fills data, sets *response_length to actual element count, - # then calls SendRpcResponse(call_id, SUCCESS, data, *response_length * sizeof(T)). + # For array return types: data buffer (max capacity, zero-filled) and response_length + # (init to max) are appended. The implementation fills data, sets *response_length to + # actual element count, then calls + # SendRpcResponse(call_id, SUCCESS, data, *response_length * sizeof(T)). # A blob return works the same way, but *response_length is a byte count. + # A string return gets max_length + 1 bytes: the implementation writes text and calls + # SendRpcResponse(call_id, SUCCESS, data, strlen(data)) - the terminator is not sent. + # In every case the implementation sends the response; the dispatcher never does, and a + # handler that returns without SendRpcResponse() leaves the call pending. A buffer that + # came from the shared pool (blob, large array, large string) is only valid until the + # handler returns, so such a handler cannot answer later. for func in service["functions"]: params = ["uint16_t call_id"] for p in func["parameters"]: diff --git a/codegen/xbot_codegen/xbot_codegen.py b/codegen/xbot_codegen/xbot_codegen.py index 78f702a..9d09538 100644 --- a/codegen/xbot_codegen/xbot_codegen.py +++ b/codegen/xbot_codegen/xbot_codegen.py @@ -88,9 +88,17 @@ def array_type_attrs(max_length): "double": 8, } -# Largest RPC body that fits into one packet: max_packet_size(1472) - sizeof(XbotHeader)(24). -# A return value can never be larger, which is what the shared buffer pool is sized for. -MAX_RPC_RETURN_BYTES = 1472 - 24 +# Wire sizes the generator validates a schema against. They mirror the C++ side +# (xbot::config::max_packet_size, sizeof(XbotHeader), sizeof(DataDescriptor)); the generated +# service asserts that they still match, so a change over there fails the build instead of +# leaving the limits below on the old numbers. Everything else is derived from these three. +MAX_PACKET_SIZE = 1472 +HEADER_SIZE = 24 +DESCRIPTOR_SIZE = 8 + +# Largest RPC body that fits into one packet. A return value can never be larger, which is +# what the shared buffer pool is sized for (xbot::service::buffer::min_block_size). +MAX_RPC_RETURN_BYTES = MAX_PACKET_SIZE - HEADER_SIZE # Array returns up to this size stay on the service thread stack. Larger ones and blob # returns are taken from the shared buffer pool (see xbot-service/Buffer.hpp), so a @@ -98,9 +106,9 @@ def array_type_attrs(max_length): RPC_STACK_RETURN_MAX = 128 # One parameter occupies a descriptor plus its payload in the RPC body, so it can never be -# longer than that body minus the descriptor: 1448 - 8. A larger limit could never be -# fulfilled, and the dispatcher would have to reserve max_length + 1 bytes of stack for it. -MAX_PARAMETER_BYTES = MAX_RPC_RETURN_BYTES - 8 +# longer than that body minus the descriptor. A larger limit could never be fulfilled, and +# the dispatcher would have to reserve max_length + 1 bytes of stack for it. +MAX_PARAMETER_BYTES = MAX_RPC_RETURN_BYTES - DESCRIPTOR_SIZE # `string` is text on the wire: like blob it carries no terminator and its length is the # payload size. The difference is the declared maximum, so the generated server can decode @@ -134,7 +142,8 @@ def pooledReturnBytes(service, func): if func["return_is_blob"]: return MAX_RPC_RETURN_BYTES if func["return_is_string"]: - # One byte more than max_length: the terminator the dispatcher appends. + # One byte more than max_length: room for the terminator of the text the handler + # writes. It never goes on the wire, the handler sends strlen() bytes. bytes_needed = func["return_max_length"] + 1 return bytes_needed if bytes_needed > RPC_STACK_RETURN_MAX else None if func["return_is_array"]: @@ -143,6 +152,27 @@ def pooledReturnBytes(service, func): return None +def pooledReturnBytesExpr(func): + """C++ expression for pooledReturnBytes(): the size the generated dispatcher borrows.""" + if func["return_is_blob"]: + # Taken from the C++ side instead of baking MAX_RPC_RETURN_BYTES into the firmware. + return "xbot::service::buffer::min_block_size" + if func["return_is_string"]: + return f"{func['return_max_length']} + 1" + return f"{func['return_max_length']} * sizeof({func['return_base_type']})" + + +def parameterMaxBytes(service, param): + """Largest payload one parameter can add to an RPC body (0 for a blob, which may be empty).""" + if param["is_blob"]: + return 0 + if param["is_string"]: + return param["max_length"] + if param["is_array"]: + return param["max_length"] * typeSize(service, param["type"]) + return typeSize(service, param["type"]) + + def needsBufferPool(service): """True if any generated return value comes from the buffer pool.""" return any(pooledReturnBytes(service, func) is not None for func in service["functions"]) @@ -169,9 +199,9 @@ def common_attrs(json, valid_types, callback_name, send_method_name): # on request (Service::HandleDescriptionRequest), so a host without generated classes can # still fetch the complete schema; hosts with generated classes never need it. # -# Budget: max_packet_size(1472) - sizeof(XbotHeader)(24) - the bytes the base class adds -# around the description (80, see the static_assert in templates/ServiceTemplate.cpp). -ADVERTISED_DESCRIPTION_BUDGET = 1472 - 24 - 80 +# Budget: one packet without its header and without the bytes the base class adds around +# the description (80, see the static_assert in templates/ServiceTemplate.cpp). +ADVERTISED_DESCRIPTION_BUDGET = MAX_PACKET_SIZE - HEADER_SIZE - 80 # Blocks the advertisement may drop to fit, widest/most optional first. `type` and # `version` always stay: they identify the service. @@ -364,6 +394,16 @@ def loadService(path: str) -> dict: **( {"is_array": False} if param_is_string else array_type_attrs(param_max_length) ), }) + # All parameters of a call travel in one packet, and the dispatcher keeps every fixed + # size, array and string parameter on its stack. Each of them is bounded above, but + # two 1440 byte strings would still pass - and reserve 2882 bytes of stack for a call + # that can never carry both. So the declared maxima have to fit together. + params_bytes = sum(DESCRIPTOR_SIZE + parameterMaxBytes(service, p) for p in params) + if params_bytes > MAX_RPC_RETURN_BYTES: + raise Exception( + f"Function '{func_name}': the parameters need up to {params_bytes} bytes " + f"(descriptors included), more than one packet can carry ({MAX_RPC_RETURN_BYTES})") + service["functions"].append({ "id": func_id, "name": func_name, From ac5572e914f6664e87802bc5b4fb617a98ebe1b7 Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 17:12:56 +0100 Subject: [PATCH 16/28] fix(interface): refuse what does not fit into one packet, report BUSY Blob and string values made the size of a call, an input or a transaction unbounded, but only the Go and Python clients checked it. The C++ client handed an oversized packet to the socket; the services run without IP reassembly and drop it, so a call failed as a timeout that looks like a dead service and an input was lost while Send...() returned true. SendRpc(), SendData() and CommitTransaction() refuse such a packet now. Every status but SUCCESS became RPC_ERROR, so a caller could not tell a call that is worth repeating from one that is not - and a pooled return answers BUSY whenever the service has no free block. SendRpc() returns RPC_BUSY for that, and GetLastRpcResult() makes it visible behind the bool of the generated Call...() methods. The frame budget helper of a string parameter reported the packet budget, although the call refuses anything above max_length: for a 64 byte string it returned 1440 and every value sized by it failed. It is capped like the Go helper. RemainingBudget() was emitted into every generated interface, with a one argument overload nothing called. It lives in ServiceInterfaceBase once. --- .../templates/ServiceInterfaceTemplate.hpp | 46 ++++++------------- .../ServiceInterfaceBase.hpp | 31 +++++++++++++ .../src/ServiceInterfaceBase.cpp | 41 ++++++++++++++++- 3 files changed, 86 insertions(+), 32 deletions(-) diff --git a/codegen/templates/ServiceInterfaceTemplate.hpp b/codegen/templates/ServiceInterfaceTemplate.hpp index 2cf6fc5..0f9fff5 100644 --- a/codegen/templates/ServiceInterfaceTemplate.hpp +++ b/codegen/templates/ServiceInterfaceTemplate.hpp @@ -20,6 +20,7 @@ cog.outl(f"#define {service['interface_class_name'].upper()}_HPP") #include #include +#include #include /*[[[cog @@ -111,19 +112,6 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas # length. Like a blob it therefore uses up budget, but the caller only passes the C # string, the generated code measures it. blob_funcs = [f for f in service["functions"] if any(p['is_blob'] or p['is_string'] for p in f["parameters"])] - if blob_funcs: - cog.outl(" // Saturating subtraction for the frame budgets below: a call whose parameters") - cog.outl(" // use up the whole packet reports 0 instead of a wrapped (huge) budget.") - cog.outl(" static constexpr size_t RemainingBudget(size_t budget) {") - cog.outl(" return budget;") - cog.outl(" }") - cog.outl(" static constexpr size_t RemainingBudget(size_t budget, size_t used) {") - cog.outl(" return (used < budget) ? (budget - used) : 0;") - cog.outl(" }") - cog.outl(" template ") - cog.outl(" static constexpr size_t RemainingBudget(size_t budget, size_t used, Rest... rest) {") - cog.outl(" return RemainingBudget((used < budget) ? (budget - used) : 0, rest...);") - cog.outl(" }") for func in blob_funcs: blobs = [p for p in func["parameters"] if p['is_blob'] or p['is_string']] fixed = sum( @@ -133,40 +121,36 @@ class ServiceTemplateInterfaceBase : public xbot::serviceif::ServiceInterfaceBas for target in blobs: others = [p for p in blobs if p['name'] != target['name']] args = ", ".join(f"size_t {p['name']}Len" for p in others) - # Everything but the packet itself goes through RemainingBudget, the descriptor - # framing included: a call with 182 parameters needs more bytes for its - # descriptors than a packet has, and that subtraction would wrap as well. + # Everything but the packet itself goes through RemainingBudget (a saturating + # subtraction in ServiceInterfaceBase), the descriptor framing included: a call + # with 182 parameters needs more bytes for its descriptors than a packet has, + # and that subtraction would wrap as well. used = [f"sizeof(xbot::datatypes::XbotHeader) + " f"{len(func['parameters'])} * sizeof(xbot::datatypes::DataDescriptor)"] if fixed: used.append(f"static_cast({fixed})") used += [f"{p['name']}Len" for p in others] budget = "RemainingBudget(xbot::config::max_packet_size, " + ", ".join(used) + ")" + limit = "" + if target['is_string']: + # The packet could carry more, but Call...() refuses a value above the + # schema's max_length - a helper that reports more would only lead the + # caller into a call that always fails. + budget = f"std::min({target['max_length']}, {budget})" + limit = f", and never more than the {target['max_length']} bytes the schema accepts" name = f"Max{func['name']}{target['name']}" - cog.outl(f" // {name} is the largest {target['name']} payload one {func['name']} call can carry.") + cog.outl(f" // {name} is the largest {target['name']} payload one {func['name']} call can carry{limit}.") cog.outl(f" static constexpr size_t {name}({args}) {{") cog.outl(f" return {budget};") cog.outl(" }") ]]]*/ - // Saturating subtraction for the frame budgets below: a call whose parameters - // use up the whole packet reports 0 instead of a wrapped (huge) budget. - static constexpr size_t RemainingBudget(size_t budget) { - return budget; - } - static constexpr size_t RemainingBudget(size_t budget, size_t used) { - return (used < budget) ? (budget - used) : 0; - } - template - static constexpr size_t RemainingBudget(size_t budget, size_t used, Rest... rest) { - return RemainingBudget((used < budget) ? (budget - used) : 0, rest...); - } // MaxBlobParamsWithBlobReturnData is the largest Data payload one BlobParamsWithBlobReturn call can carry. static constexpr size_t MaxBlobParamsWithBlobReturnData() { return RemainingBudget(xbot::config::max_packet_size, sizeof(xbot::datatypes::XbotHeader) + 1 * sizeof(xbot::datatypes::DataDescriptor)); } - // MaxStringParamsWithStringReturnPath is the largest Path payload one StringParamsWithStringReturn call can carry. + // MaxStringParamsWithStringReturnPath is the largest Path payload one StringParamsWithStringReturn call can carry, and never more than the 64 bytes the schema accepts. static constexpr size_t MaxStringParamsWithStringReturnPath() { - return RemainingBudget(xbot::config::max_packet_size, sizeof(xbot::datatypes::XbotHeader) + 1 * sizeof(xbot::datatypes::DataDescriptor)); + return std::min(64, RemainingBudget(xbot::config::max_packet_size, sizeof(xbot::datatypes::XbotHeader) + 1 * sizeof(xbot::datatypes::DataDescriptor))); } //[[[end]]] diff --git a/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp b/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp index 4154e47..eae5a4d 100644 --- a/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp +++ b/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp @@ -28,8 +28,22 @@ class ServiceInterfaceBase : public xbot::serviceif::ServiceIOCallbacks, RPC_OK = 0, RPC_ERROR, RPC_TIMEOUT, + // The service answered RpcStatus::BUSY: it is still working on another call, or it has no free + // block in its shared buffer pool. The call was refused for now and can be sent again. + RPC_BUSY, }; + /** + * Result of the most recent RPC of this interface. The generated Call...() methods only return + * true or false; this tells a failed call that is worth repeating (RPC_BUSY) from one that is not. + * + * It is one value per interface: with several threads calling at the same time it may already + * belong to another thread's call. + */ + RPC_RESULT GetLastRpcResult() const { + return last_rpc_result_; + } + protected: const uint16_t service_id_; // Type of the service (e.g. IMU Service) @@ -54,6 +68,18 @@ class ServiceInterfaceBase : public xbot::serviceif::ServiceIOCallbacks, */ RPC_RESULT SendRpc(uint8_t function_id, const uint8_t *params, size_t params_size, uint8_t* response_buffer, size_t *response_buffer_size, uint32_t timeout_ms = 1000); + /** + * Saturating subtraction for the generated frame budget helpers (Max()): what + * is left of budget after everything in used. A call whose parameters use up the whole packet + * reports 0 instead of a wrapped (huge) budget. + */ + static constexpr size_t RemainingBudget(size_t budget, size_t used) { + return (used < budget) ? (budget - used) : 0; + } + template + static constexpr size_t RemainingBudget(size_t budget, size_t used, Rest... rest) { + return RemainingBudget(RemainingBudget(budget, used), rest...); + } public: bool OnServiceDiscovered(uint16_t service_id) final; @@ -66,6 +92,11 @@ class ServiceInterfaceBase : public xbot::serviceif::ServiceIOCallbacks, void FillHeader(); void MarkServiceDisconnected(uint16_t service_id); + RPC_RESULT DoSendRpc(uint8_t function_id, const uint8_t *params, size_t params_size, uint8_t *response_buffer, + size_t *response_buffer_size, uint32_t timeout_ms); + + std::atomic last_rpc_result_{RPC_OK}; + // RPC synchronization state shared between generated Call* methods and OnRpcResponse. std::mutex rpc_mutex_{}; std::condition_variable rpc_cv_{}; diff --git a/libxbot-service-interface/src/ServiceInterfaceBase.cpp b/libxbot-service-interface/src/ServiceInterfaceBase.cpp index 55cb996..9021eee 100644 --- a/libxbot-service-interface/src/ServiceInterfaceBase.cpp +++ b/libxbot-service-interface/src/ServiceInterfaceBase.cpp @@ -3,10 +3,19 @@ // #include #include +#include #include "spdlog/spdlog.h" using namespace xbot::serviceif; +namespace { +// Largest payload one packet carries behind its header. A packet has to fit into a single, +// unfragmented datagram: the services run without IP reassembly and drop anything larger without +// an answer, which the caller would only see as a timeout (RPC) or not at all (data). Blob and +// string values have no fixed size, so every send path checks before it hands a packet to the socket. +constexpr size_t kMaxPayloadSize = xbot::config::max_packet_size - sizeof(xbot::datatypes::XbotHeader); +} // namespace + ServiceInterfaceBase::ServiceInterfaceBase(uint16_t service_id, std::string type, uint32_t version, Context ctx) : service_id_(service_id), type_(std::move(type)), version_(version), ctx(ctx) { } @@ -70,6 +79,12 @@ bool ServiceInterfaceBase::CommitTransaction() { } header_ptr->payload_size = buffer_.size() - sizeof(xbot::datatypes::XbotHeader); + if (header_ptr->payload_size > kMaxPayloadSize) { + spdlog::error("[ID={}] Transaction of {} bytes does not fit into one packet (max {}), dropping", service_id_, + static_cast(header_ptr->payload_size), kMaxPayloadSize); + return false; + } + return ctx.io->SendData(service_id_, buffer_); } @@ -105,6 +120,12 @@ bool ServiceInterfaceBase::SendData(uint16_t target_id, const void *data, size_t return false; } + if (size > kMaxPayloadSize) { + spdlog::error("[ID={}] Value of {} bytes for target {} does not fit into one packet (max {}), dropping", + service_id_, size, target_id, kMaxPayloadSize); + return false; + } + buffer_.resize(sizeof(xbot::datatypes::XbotHeader) + size); FillHeader(); @@ -122,12 +143,28 @@ bool ServiceInterfaceBase::SendData(uint16_t target_id, const void *data, size_t ServiceInterfaceBase::RPC_RESULT ServiceInterfaceBase::SendRpc(uint8_t function_id, const uint8_t *params, size_t params_size, uint8_t *response_buffer, size_t *response_buffer_size, uint32_t timeout_ms) { + const RPC_RESULT result = + DoSendRpc(function_id, params, params_size, response_buffer, response_buffer_size, timeout_ms); + last_rpc_result_ = result; + return result; +} +ServiceInterfaceBase::RPC_RESULT ServiceInterfaceBase::DoSendRpc(uint8_t function_id, const uint8_t *params, + size_t params_size, uint8_t *response_buffer, + size_t *response_buffer_size, uint32_t timeout_ms) { if (!service_discovered_) { spdlog::debug("SendRpcPacket: service not discovered, dropping"); return RPC_ERROR; } + // Refused here instead of on the wire: an oversized call would be dropped by the service and + // come back as a timeout that looks like a dead service. + if (params_size > kMaxPayloadSize) { + spdlog::error("[ID={}] RPC {}: parameters of {} bytes do not fit into one packet (max {})", service_id_, + static_cast(function_id), params_size, kMaxPayloadSize); + return RPC_ERROR; + } + std::unique_lock lk(rpc_mutex_); // Wait for no RPC in flight (blocks until previous call completes). @@ -188,7 +225,9 @@ ServiceInterfaceBase::RPC_RESULT ServiceInterfaceBase::SendRpc(uint8_t function_ if (rpc_response_status_ != 0) { *response_buffer_size = 0; - return RPC_ERROR; + // BUSY is the one status a caller can act on: nothing is wrong with the call, it only came at + // the wrong time (another call in progress, or no free block in the service's buffer pool). + return rpc_response_status_ == static_cast(xbot::datatypes::RpcStatus::BUSY) ? RPC_BUSY : RPC_ERROR; } if (rpc_received_size_ > response_max) { spdlog::error("RPC response too large: got {} bytes, max {}", rpc_received_size_, response_max); From 70dd4b67b60c1d1c2c97ba6226deb04d87f77fcd Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 17:12:56 +0100 Subject: [PATCH 17/28] fix(go): validate a schema like the C++ generator does The validator is meant to reject what the C++ generator rejects, but three cases got through and produced a client for a service that cannot be built: - "string[N]" and "blob[N]" parameters and returns. A string[16] parameter has no max_length, so the client rejected every non-empty value. - array parameters with an enum element type skipped the size check. - array returns above one packet. It also applies the new rule that the parameters of a function have to fit into one packet together. The limits are derived from xbot.MaxPacketSize, HeaderSize and DescriptorSize instead of repeating 1472 - 24 - 8, so the validation and Conn.send() cannot disagree. String parameters use xbot.String() instead of re-implementing it as xbot.Bytes(id, []byte(s)). --- xbot_service_interface_go/codegen/emit.go | 6 +- .../codegen/generate_test.go | 59 +++++++++- xbot_service_interface_go/codegen/render.go | 18 +-- xbot_service_interface_go/codegen/schema.go | 109 +++++++++++++++--- .../codegen/testdata/demo_service.golden.go | 4 +- .../testdata/demo_service_noid.golden.go | 4 +- 6 files changed, 165 insertions(+), 35 deletions(-) diff --git a/xbot_service_interface_go/codegen/emit.go b/xbot_service_interface_go/codegen/emit.go index 576370f..253d9dd 100644 --- a/xbot_service_interface_go/codegen/emit.go +++ b/xbot_service_interface_go/codegen/emit.go @@ -116,13 +116,11 @@ func (g *generator) goType(t, where string) (string, error) { return g.goScalar(base, where) } -// packExpr turns a Go value into the bytes of one RPC parameter. +// packExpr turns a Go value into the bytes of one RPC parameter, register or input. A +// "string" parameter does not come through here: emitFunction hands it to xbot.String. func (g *generator) packExpr(t, expr, where string) (string, error) { base, length, isArray := splitType(t) switch { - case base == "string": - // The bytes only, no terminator: the length in the descriptor is the value. - return "[]byte(" + expr + ")", nil case base == "blob": return expr, nil case base == "char": diff --git a/xbot_service_interface_go/codegen/generate_test.go b/xbot_service_interface_go/codegen/generate_test.go index 67225b8..e9a243c 100644 --- a/xbot_service_interface_go/codegen/generate_test.go +++ b/xbot_service_interface_go/codegen/generate_test.go @@ -80,6 +80,30 @@ func TestLoadRejects(t *testing.T) { "array parameter above one packet": `{"type": "X", "version": 1, "functions": [ {"id": 0, "name": "F", "return_type": "void", "parameters": [{"id": 0, "name": "P", "type": "uint8_t[1441]"}]}]}`, + // The rest mirrors the C++ generator, so a schema that cannot build there does not + // produce a Go client either. + "string array parameter": `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "F", "return_type": "void", + "parameters": [{"id": 0, "name": "P", "type": "string[16]"}]}]}`, + "blob array parameter": `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "F", "return_type": "void", + "parameters": [{"id": 0, "name": "P", "type": "blob[16]"}]}]}`, + "string array return": `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "F", "return_type": "string[16]", "max_length": 16}]}`, + "blob array return": `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "F", "return_type": "blob[16]"}]}`, + "enum array parameter above one packet": `{"type": "X", "version": 1, + "enums": [{"id": "Mode", "base_type": "uint8_t", "values": {"A": 0}}], + "functions": [{"id": 0, "name": "F", "return_type": "void", + "parameters": [{"id": 0, "name": "P", "type": "Mode[2000]"}]}]}`, + "array return above one packet": `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "F", "return_type": "uint32_t[512]"}]}`, + "char array return above one packet": `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "F", "return_type": "char[1449]"}]}`, + "parameters above one packet together": `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "F", "return_type": "void", "parameters": [ + {"id": 0, "name": "A", "type": "string", "max_length": 1000}, + {"id": 1, "name": "B", "type": "string", "max_length": 1000}]}]}`, "enum values normalize equal": `{"type": "X", "version": 1, "enums": [{"id": "E", "base_type": "uint8_t", "values": {"IDLE": 0, "Idle": 1}}]}`, "enum types normalize equal": `{"type": "X", "version": 1, "enums": [ @@ -191,6 +215,39 @@ func TestBlobInputOutput(t *testing.T) { } } +// TestLoadAcceptsPacketLimits pins the other side of TestLoadRejects: the limits are +// inclusive, and a blob only counts with its descriptor because it may be empty. +func TestLoadAcceptsPacketLimits(t *testing.T) { + cases := map[string]string{ + "array return of exactly one packet": `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "F", "return_type": "uint32_t[362]"}]}`, + "parameters that fill one packet together": `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "F", "return_type": "void", "parameters": [ + {"id": 0, "name": "A", "type": "string", "max_length": 716}, + {"id": 1, "name": "B", "type": "string", "max_length": 716}]}]}`, + "blobs next to a full size string": `{"type": "X", "version": 1, "functions": [ + {"id": 0, "name": "F", "return_type": "void", "parameters": [ + {"id": 0, "name": "A", "type": "string", "max_length": 1424}, + {"id": 1, "name": "B", "type": "blob"}, + {"id": 2, "name": "C", "type": "blob"}]}]}`, + "enum array parameter": `{"type": "X", "version": 1, + "enums": [{"id": "Mode", "base_type": "uint16_t", "values": {"A": 0}}], + "functions": [{"id": 0, "name": "F", "return_type": "void", + "parameters": [{"id": 0, "name": "P", "type": "Mode[720]"}]}]}`, + } + for name, schema := range cases { + t.Run(name, func(t *testing.T) { + path := t.TempDir() + "/service.json" + if err := os.WriteFile(path, []byte(schema), 0o644); err != nil { + t.Fatal(err) + } + if _, err := Load(path); err != nil { + t.Fatalf("Load: %v", err) + } + }) + } +} + // TestNumericArrays pins that numeric arrays (T[n]) are supported: they are // padded to n elements on send and decoded from n elements on receive. func TestNumericArrays(t *testing.T) { @@ -242,7 +299,7 @@ func TestStringParameters(t *testing.T) { for _, want := range []string{ "func (c *Client) Play(ctx context.Context, Path string) (string, error) {", "if len(Path) > 64 { // string, max_length 64", - "xbot.Bytes(0, []byte(Path))", + "xbot.String(0, Path)", "if len(payload) > 96 {", "return string(payload), nil", // The budget helper treats a string like a blob: variable length. diff --git a/xbot_service_interface_go/codegen/render.go b/xbot_service_interface_go/codegen/render.go index 02d1e0a..ad0de13 100644 --- a/xbot_service_interface_go/codegen/render.go +++ b/xbot_service_interface_go/codegen/render.go @@ -289,19 +289,23 @@ func (g *generator) emitFunction(fn Function) error { if err != nil { return err } + sig = append(sig, pname+" "+gt) + base, length, _ := splitType(p.Type) + if base == "string" { + // Refused here instead of on the server: the value is text without a + // terminator, and the schema declares the limit. + charChecks = append(charChecks, charCheck{param: pname, schema: "string", length: p.MaxLength, isString: true}) + // The bytes only, no terminator: the length in the descriptor is the value. + params = append(params, fmt.Sprintf("xbot.String(%d, %s),", p.ID, pname)) + continue + } expr, err := g.packExpr(p.Type, pname, where) if err != nil { return err } - if base, length, _ := splitType(p.Type); base == "char" && length > 0 { + if base == "char" && length > 0 { charChecks = append(charChecks, charCheck{param: pname, schema: p.Type, length: length}) } - if base, _, _ := splitType(p.Type); base == "string" { - // Refused here instead of on the server: the value is text without a - // terminator, and the schema declares the limit. - charChecks = append(charChecks, charCheck{param: pname, schema: "string", length: p.MaxLength, isString: true}) - } - sig = append(sig, pname+" "+gt) params = append(params, fmt.Sprintf("xbot.Bytes(%d, %s),", p.ID, expr)) } retType, lines, err := g.decodeReturn(fn.ReturnType, fn.MaxLength, name) diff --git a/xbot_service_interface_go/codegen/schema.go b/xbot_service_interface_go/codegen/schema.go index 207ff08..4726f77 100644 --- a/xbot_service_interface_go/codegen/schema.go +++ b/xbot_service_interface_go/codegen/schema.go @@ -13,6 +13,8 @@ import ( "os" "regexp" "sort" + + "github.com/xtech/xbot_framework/xbot_service_interface_go/xbot" ) // Schema is a service.json. @@ -71,12 +73,17 @@ var rawTypes = []string{ // maxArrayLength is the limit the framework applies to array returns. const maxArrayLength = 1024 -// maxStringLength is one packet body minus the descriptor: a longer value could never be -// sent, and the server would reserve that much stack for it. -const maxStringLength = 1472 - 24 - 8 +// maxBodyBytes is the RPC body one packet carries: all parameters of a call with their +// descriptors, or one return value. The sizes come from the transport, so the validation +// and Conn.send can never disagree about what fits. +const maxBodyBytes = xbot.MaxPacketSize - xbot.HeaderSize // maxParameterBytes is what one parameter can add to the RPC body besides its descriptor. -const maxParameterBytes = maxStringLength +const maxParameterBytes = maxBodyBytes - xbot.DescriptorSize + +// maxStringLength is the largest max_length a string can declare: a longer value could +// never be sent, and the server would reserve that much stack for it. +const maxStringLength = maxParameterBytes var arrayType = regexp.MustCompile(`^(.+)\[(\d+)\]$`) @@ -102,39 +109,86 @@ func (s *Schema) validate() error { if s.Type == "" { return fmt.Errorf("service.json: missing \"type\"") } + // Element sizes are needed for the function checks below, and an array may have an enum + // as its element type - which is as large as the enum's base type. + enumBase := make(map[string]string, len(s.Enums)) + for _, e := range s.Enums { + enumBase[e.ID] = e.BaseType + } + elementSize := func(base string) (int, bool) { + if eb, ok := enumBase[base]; ok { + base = eb + } + if base == "char" { + return 1, true // not in typeSizes: char is the natural character type + } + size, ok := typeSizes[base] + return size, ok + } + for _, f := range s.Functions { if len(f.Parameters) > 0 { if err := checkUniqueIDs("function "+f.Name, f.Parameters); err != nil { return err } } + retBase, retLen, retIsArray := splitType(f.ReturnType) + if err := checkVariableLength("function "+f.Name+": return type", retBase, retIsArray); err != nil { + return err + } // Array returns are limited like in the C++ generator. - if base, n, isArray := splitType(f.ReturnType); isArray && base != "char" { - if n < 1 || n > maxArrayLength { - return fmt.Errorf("function %s: return length %d must be 1..%d", f.Name, n, maxArrayLength) + if retIsArray && retBase != "char" { + if retLen < 1 || retLen > maxArrayLength { + return fmt.Errorf("function %s: return length %d must be 1..%d", f.Name, retLen, maxArrayLength) } } + // A return value travels in one packet, so a schema that declares more can never + // be answered. + if size, ok := elementSize(retBase); retIsArray && ok && size*retLen > maxBodyBytes { + return fmt.Errorf("function %s: return type %s is %d bytes, more than one packet can carry (%d)", + f.Name, f.ReturnType, size*retLen, maxBodyBytes) + } // "string" carries text without a terminator, so the server needs the limit. if f.ReturnType == "string" && (f.MaxLength < 1 || f.MaxLength > maxStringLength) { return fmt.Errorf("function %s: a string return needs a max_length of 1..%d", f.Name, maxStringLength) } + // What the call needs when every parameter is as long as the schema allows. A blob + // may be empty, so it only counts with its descriptor. + paramsBytes := 0 for _, p := range f.Parameters { - if p.Type == "string" && (p.MaxLength < 1 || p.MaxLength > maxStringLength) { - return fmt.Errorf("function %s: parameter %s: a string needs a max_length of 1..%d", - f.Name, p.Name, maxStringLength) + base, n, isArray := splitType(p.Type) + if err := checkVariableLength("function "+f.Name+": parameter "+p.Name, base, isArray); err != nil { + return err + } + paramsBytes += xbot.DescriptorSize + if base == "string" { + if p.MaxLength < 1 || p.MaxLength > maxStringLength { + return fmt.Errorf("function %s: parameter %s: a string needs a max_length of 1..%d", + f.Name, p.Name, maxStringLength) + } + paramsBytes += p.MaxLength + continue + } + size, ok := elementSize(base) + if !ok { + continue // blob, or a type the emitter reports + } + if isArray { + size *= n } // Same rule as the C++ generator: a parameter has to fit into one packet, and // the server reserves that much stack for it. - if base, n, isArray := splitType(p.Type); isArray && base != "blob" { - size, ok := typeSizes[base] - if base == "char" { - size, ok = 1, true - } - if ok && size*n > maxParameterBytes { - return fmt.Errorf("function %s: parameter %s is %d bytes, more than one packet can carry (%d)", - f.Name, p.Name, size*n, maxParameterBytes) - } + if size > maxParameterBytes { + return fmt.Errorf("function %s: parameter %s is %d bytes, more than one packet can carry (%d)", + f.Name, p.Name, size, maxParameterBytes) } + paramsBytes += size + } + // Each parameter fits on its own, but they share one packet (and the stack of the + // server's dispatcher): two 1440 byte strings can never be sent together. + if paramsBytes > maxBodyBytes { + return fmt.Errorf("function %s: the parameters need up to %d bytes (descriptors included), "+ + "more than one packet can carry (%d)", f.Name, paramsBytes, maxBodyBytes) } } if err := checkUniqueIDs("inputs", s.Inputs); err != nil { @@ -186,6 +240,23 @@ func (s *Schema) validate() error { return s.validateGeneratedNames() } +// checkVariableLength rejects "blob[N]" and "string[N]". Both are variable length: a blob +// is bounded by the packet and a string by its max_length, never by an array suffix. The +// C++ generator refuses them, and a client generated for "string[16]" would have no +// max_length to check against and reject every value. +func checkVariableLength(what, base string, isArray bool) error { + if !isArray { + return nil + } + switch base { + case "blob": + return fmt.Errorf("%s: \"blob\" cannot be an array", what) + case "string": + return fmt.Errorf("%s: \"string\" declares its limit as max_length, not as an array length", what) + } + return nil +} + // checkUniqueIDs rejects duplicate ids and duplicate normalized names, which the // generated Go methods would otherwise collide on. func checkUniqueIDs(what string, things interface{}) error { diff --git a/xbot_service_interface_go/codegen/testdata/demo_service.golden.go b/xbot_service_interface_go/codegen/testdata/demo_service.golden.go index e7dfac5..4420ecb 100644 --- a/xbot_service_interface_go/codegen/testdata/demo_service.golden.go +++ b/xbot_service_interface_go/codegen/testdata/demo_service.golden.go @@ -190,11 +190,11 @@ func (c *Client) StringParamsWithStringReturn(ctx context.Context, Path string) } if c.sendOnly { return "", c.conn.SendRPC(FnStringParamsWithStringReturn, - xbot.Bytes(0, []byte(Path)), + xbot.String(0, Path), ) } payload, err := c.conn.Call(ctx, FnStringParamsWithStringReturn, - xbot.Bytes(0, []byte(Path)), + xbot.String(0, Path), ) if err != nil { return "", err diff --git a/xbot_service_interface_go/codegen/testdata/demo_service_noid.golden.go b/xbot_service_interface_go/codegen/testdata/demo_service_noid.golden.go index 7124110..d463d08 100644 --- a/xbot_service_interface_go/codegen/testdata/demo_service_noid.golden.go +++ b/xbot_service_interface_go/codegen/testdata/demo_service_noid.golden.go @@ -187,11 +187,11 @@ func (c *Client) StringParamsWithStringReturn(ctx context.Context, Path string) } if c.sendOnly { return "", c.conn.SendRPC(FnStringParamsWithStringReturn, - xbot.Bytes(0, []byte(Path)), + xbot.String(0, Path), ) } payload, err := c.conn.Call(ctx, FnStringParamsWithStringReturn, - xbot.Bytes(0, []byte(Path)), + xbot.String(0, Path), ) if err != nil { return "", err From 4c305b35e68fbe1b429d70226be0ec84d27b059c Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 17:12:56 +0100 Subject: [PATCH 18/28] fix(py): enum returns, oversized sends and non-text string arguments - An RPC with an enum return type raised "Unknown type" after a successful response: the size check did not resolve the enum to its base type, unlike unpack_value() right behind it. sizeof_type() takes the enums now. - send_() and transactions were not bounded. A blob above one packet was sent, dropped by the service, and the call looked like it worked. The interface raises ValueError, and ServiceIO refuses to transmit such a packet as a last line of defence. - pack_value('string', 5) fell back to bytes(5): five NUL bytes instead of an error. Only str and bytes-like values are accepted, like for blob. MAX_PACKET_SIZE (1500, the receive buffer) and MAX_UDP_PAYLOAD (1472, the send limit) say which is which, and the payload limit that was computed in two places is one constant, MAX_PAYLOAD_SIZE. --- .../tests/test_interface.py | 48 +++++++++++++++ xbot_service_interface_py/tests/test_io.py | 33 +++++++++++ xbot_service_interface_py/tests/test_rpc.py | 58 +++++++++++++++++-- .../tests/test_serialization.py | 19 ++++++ .../xbot_service_interface/datatypes.py | 11 +++- .../xbot_service_interface/interface.py | 29 ++++++++-- .../xbot_service_interface/io.py | 21 ++++++- .../xbot_service_interface/serialization.py | 10 +++- 8 files changed, 212 insertions(+), 17 deletions(-) diff --git a/xbot_service_interface_py/tests/test_interface.py b/xbot_service_interface_py/tests/test_interface.py index 138ca3c..b4ee80a 100644 --- a/xbot_service_interface_py/tests/test_interface.py +++ b/xbot_service_interface_py/tests/test_interface.py @@ -8,8 +8,17 @@ from xbot_service_interface.schema import ServiceSchema from xbot_service_interface.exceptions import UnknownChannelError, IncompatibleServiceError from xbot_service_interface.serialization import pack_value +from xbot_service_interface.datatypes import DESCRIPTOR_SIZE, MAX_PAYLOAD_SIZE from tests.conftest import ECHO_DESC, ENUM_DESC +# A service with blob inputs: the only values whose size the schema does not bound. +BLOB_INPUT_DESC = { + 'type': 'BlobService', 'version': 1, + 'inputs': [{'id': 0, 'name': 'Data', 'type': 'blob'}, + {'id': 1, 'name': 'More', 'type': 'blob'}], + 'outputs': [], 'registers': [], 'enums': [], +} + # --------------------------------------------------------------------------- # Helpers @@ -171,6 +180,20 @@ def test_send_uint32(self): _, _, raw = mock_io.send_data.call_args[0] assert struct.unpack(' dict: diff --git a/xbot_service_interface_py/xbot_service_interface/interface.py b/xbot_service_interface_py/xbot_service_interface/interface.py index cadc709..15d670c 100644 --- a/xbot_service_interface_py/xbot_service_interface/interface.py +++ b/xbot_service_interface_py/xbot_service_interface/interface.py @@ -7,7 +7,7 @@ from .exceptions import UnknownChannelError, IncompatibleServiceError, RpcError, RpcBusyError, RpcTimeoutError from .schema import ServiceSchema from .serialization import pack_value, unpack_value, sizeof_type, parse_type_string -from .datatypes import pack_descriptor, HEADER_SIZE, MAX_UDP_PAYLOAD +from .datatypes import pack_descriptor, DESCRIPTOR_SIZE, MAX_PAYLOAD_SIZE log = logging.getLogger(__name__) @@ -76,6 +76,14 @@ def __exit__(self, exc_type, exc_val, exc_tb) -> bool: io = si._io if exc_type is None and connected and chunks and io is not None: + # Every value was checked on its own when it was queued; together they still have + # to share one packet. Raised here, where the caller can see it - on the wire the + # transaction would just disappear. + size = sum(DESCRIPTOR_SIZE + len(data) for _, data in chunks) + if size > MAX_PAYLOAD_SIZE: + raise ValueError( + f"Transaction for service {si._service_id} is {size} bytes, " + f"more than one packet can carry ({MAX_PAYLOAD_SIZE})") io.send_transaction(si._service_id, chunks) return False # never suppress exceptions @@ -352,6 +360,15 @@ def __setattr__(self, name: str, value) -> None: def _send_data(self, channel_id: int, raw: bytes) -> None: with self._lock: + # A value has to fit into one packet - on its own, or behind its descriptor in a + # transaction. The fixed size types always do; a blob is only bounded here. The + # service drops a larger datagram without an answer, so the value would be lost + # without a trace. + limit = MAX_PAYLOAD_SIZE - (DESCRIPTOR_SIZE if self._transaction_active else 0) + if len(raw) > limit: + raise ValueError( + f"Value for channel {channel_id} of service {self._service_id} is {len(raw)} " + f"bytes, more than one packet can carry ({limit})") if self._transaction_active: self._transaction_chunks.append((channel_id, raw)) return @@ -387,11 +404,10 @@ def _call_rpc(self, fn: dict, args: tuple, timeout_ms: int): # The request has to fit into one datagram. The low level drops a larger one without # reporting anything, which would surface as a timeout - so fail here instead. - max_params = MAX_UDP_PAYLOAD - HEADER_SIZE - if len(params_bytes) > max_params: + if len(params_bytes) > MAX_PAYLOAD_SIZE: raise ValueError( f"RPC {fn['name']!r} parameters are {len(params_bytes)} bytes, " - f"more than one packet can carry ({max_params})") + f"more than one packet can carry ({MAX_PAYLOAD_SIZE})") with self._rpc_lock: with self._rpc_condition: @@ -432,14 +448,15 @@ def _call_rpc(self, fn: dict, args: tuple, timeout_ms: int): base, is_array, _ = parse_type_string(fn['return_type']) if base == 'blob': # Variable length return, bounded by one packet only. - max_bytes = MAX_UDP_PAYLOAD - HEADER_SIZE + max_bytes = MAX_PAYLOAD_SIZE elif base == 'string': # Text: the schema declares the limit, and the server never sends more. max_bytes = int(fn.get('max_length') or 0) if max_bytes <= 0: raise RpcError(2, f"RPC {fn['name']!r}: string return without a max_length") else: - max_bytes = sizeof_type(fn['return_type']) + # With the enums: a return type may be an enum, which is as large as its base type. + max_bytes = sizeof_type(fn['return_type'], enums) if len(payload) > max_bytes: raise RpcError( 2, f"RPC {fn['name']!r} response too large: got {len(payload)} bytes, max {max_bytes}") diff --git a/xbot_service_interface_py/xbot_service_interface/io.py b/xbot_service_interface_py/xbot_service_interface/io.py index 191079a..b01c89c 100644 --- a/xbot_service_interface_py/xbot_service_interface/io.py +++ b/xbot_service_interface_py/xbot_service_interface/io.py @@ -8,7 +8,8 @@ from .datatypes import ( HEADER_SIZE, DESCRIPTOR_SIZE, MessageType, RpcStatus, - DEFAULT_HEARTBEAT_MICROS, HEARTBEAT_JITTER, MAX_PACKET_SIZE, PROTOCOL_VERSION, + DEFAULT_HEARTBEAT_MICROS, HEARTBEAT_JITTER, MAX_PACKET_SIZE, MAX_PAYLOAD_SIZE, + PROTOCOL_VERSION, unpack_header, pack_header, unpack_descriptor, pack_descriptor, pack_claim_payload, ) @@ -136,7 +137,19 @@ def get_endpoint(self) -> tuple[str, int]: # Sending # ------------------------------------------------------------------ + @staticmethod + def _fits(service_id: int, what: str, payload_len: int) -> bool: + """One packet per send: the service drops a larger datagram without an answer.""" + if payload_len <= MAX_PAYLOAD_SIZE: + return True + log.error( + f"Service {service_id}: {what} of {payload_len} bytes does not fit into one packet " + f"(max {MAX_PAYLOAD_SIZE}), not sent") + return False + def send_data(self, service_id: int, target_id: int, payload: bytes) -> bool: + if not self._fits(service_id, f"data for target {target_id}", len(payload)): + return False with self._lock: state = self._services.get(service_id) if state is None or not state.claimed: @@ -158,6 +171,9 @@ def send_data(self, service_id: int, target_id: int, payload: bytes) -> bool: def send_transaction(self, service_id: int, chunks: list[tuple[int, bytes]], is_config: bool = False) -> bool: + body = b''.join(pack_descriptor(tid, len(data)) + data for tid, data in chunks) + if not self._fits(service_id, "configuration" if is_config else "transaction", len(body)): + return False with self._lock: state = self._services.get(service_id) if state is None or not state.claimed: @@ -166,7 +182,6 @@ def send_transaction(self, service_id: int, seq = state.sequence_no state.sequence_no = (seq + 1) & 0xFFFF - body = b''.join(pack_descriptor(tid, len(data)) + data for tid, data in chunks) hdr = pack_header( message_type=MessageType.TRANSACTION, service_id=service_id, @@ -180,6 +195,8 @@ def send_transaction(self, service_id: int, def send_rpc_call(self, service_id: int, function_id: int, call_id: int, params: bytes) -> bool: + if not self._fits(service_id, f"RPC call {function_id}", len(params)): + return False with self._lock: state = self._services.get(service_id) if state is None or not state.claimed: diff --git a/xbot_service_interface_py/xbot_service_interface/serialization.py b/xbot_service_interface_py/xbot_service_interface/serialization.py index 0877fba..ece6a89 100644 --- a/xbot_service_interface_py/xbot_service_interface/serialization.py +++ b/xbot_service_interface_py/xbot_service_interface/serialization.py @@ -46,8 +46,11 @@ def parse_type_string(type_str: str) -> Tuple[str, bool, Optional[int]]: return base, False, None -def sizeof_type(type_str: str) -> int: +def sizeof_type(type_str: str, enums: dict = None) -> int: + """Byte size of a fixed size xbot type. An enum is as large as its base type.""" base, is_array, max_len = parse_type_string(type_str) + if enums and base in enums: + base = enums[base]['base_type'] if base in ('blob', 'string'): # Both are variable length; a string's limit comes from the schema's max_length. raise ValueError(f"{base} has no fixed size") @@ -80,7 +83,10 @@ def pack_value(type_str: str, value, enums: dict = None) -> bytes: # max_length check belongs to the caller, which has the schema. if isinstance(value, str): return value.encode('utf-8') - return bytes(value) + if isinstance(value, (bytes, bytearray, memoryview)): + return bytes(value) + # Not bytes(value): that turns the int 5 into five NUL bytes instead of an error. + raise TypeError("string type requires str or a bytes-like object") if base == 'char': if is_array: From 3b52dfe6d434daf69620cdb1b3bd64fc8f93a927 Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 17:13:08 +0100 Subject: [PATCH 19/28] test: build the unit tests and the generated template code in CI BufferTests were never built: add_subdirectory(test) was commented out, and CI only compiles the examples, whose service has a char[30] return. None of the generated blob, string or pool code was compiled anywhere, and the dispatcher had no test at all. -DXBOT_BUILD_TESTS=ON (set by the CI preset) builds them now, and the Docker build runs ctest before it packages. - DispatcherTests run the dispatcher generated from the template schema: terminated and bounded string parameters, zero copy blob parameters, cleared return buffers from the stack and from the pool, BUSY while no block is free, descriptors that announce more than the packet holds. - ServiceTests cover SendData() inside a transaction, including sizes that wrap the space check. - InterfaceCodegenTests compile the generated interface and pin the frame budget helpers with static_asserts. The generated service is compiled with -Wall -Wextra -Werror, as firmware builds do. CppUTest is built without its leak detection: it force-includes a header that turns `new` into a macro, which the placement new in and does not survive. QueueTests stays out of the build. It was written against the queue API from before the portable layer and has to be ported first. --- CMakeLists.txt | 6 + CMakePresets.json | 3 +- Dockerfile | 2 +- ext/CMakeLists.txt | 4 + libxbot-service-interface/CMakeLists.txt | 5 + libxbot-service-interface/test/CMakeLists.txt | 11 + .../test/InterfaceCodegenTests.cpp | 38 ++ libxbot-service/CMakeLists.txt | 6 +- libxbot-service/test/CMakeLists.txt | 40 ++- .../test/DispatcherTests/DispatcherTests.cpp | 330 ++++++++++++++++++ .../test/ServiceTests/ServiceTests.cpp | 75 ++++ libxbot-service/test/TemplateService.hpp | 66 ++++ libxbot-service/test/all_tests.cpp | 3 +- 13 files changed, 566 insertions(+), 23 deletions(-) create mode 100644 libxbot-service-interface/test/CMakeLists.txt create mode 100644 libxbot-service-interface/test/InterfaceCodegenTests.cpp create mode 100644 libxbot-service/test/DispatcherTests/DispatcherTests.cpp create mode 100644 libxbot-service/test/ServiceTests/ServiceTests.cpp create mode 100644 libxbot-service/test/TemplateService.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index cefd7ea..c308c5c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -20,6 +20,12 @@ if (XBOT_BUILD_EXAMPLES) set(XBOT_BUILD_LIB_SERVICE ON) endif () +# Unit tests of the libraries and of the generated code, run with ctest. The CI preset enables them. +option(XBOT_BUILD_TESTS "Build the unit tests" OFF) +if (XBOT_BUILD_TESTS) + enable_testing() +endif () + add_subdirectory(ext EXCLUDE_FROM_ALL) add_subdirectory(codegen EXCLUDE_FROM_ALL) diff --git a/CMakePresets.json b/CMakePresets.json index a1a3a7c..4f2eabe 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -56,7 +56,8 @@ }, { "cacheVariables": { - "CMAKE_BUILD_TYPE": "Release" + "CMAKE_BUILD_TYPE": "Release", + "XBOT_BUILD_TESTS": "ON" }, "inherits": "default", "name": "CI" diff --git a/Dockerfile b/Dockerfile index 733c395..c58683d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -21,7 +21,7 @@ RUN if [ -n "$RELEASE_VERSION" ]; then \ cmake --preset=CI -DCPACK_PACKAGE_VERSION="$RELEASE_VERSION" -DCPACK_GENERATOR=TGZ .; \ else \ cmake --preset=CI .; \ - fi && cd build/CI && cmake --build . -j$(nproc) && cpack + fi && cd build/CI && cmake --build . -j$(nproc) && ctest --output-on-failure && cpack FROM scratch AS export COPY --from=build /workspace/build/CI/xbot_framework*.tar.gz / diff --git a/ext/CMakeLists.txt b/ext/CMakeLists.txt index 1f82c3b..251682d 100644 --- a/ext/CMakeLists.txt +++ b/ext/CMakeLists.txt @@ -1,5 +1,9 @@ if (XBOT_BUILD_LIB_SERVICE) add_subdirectory(ulog/src) + # CppUTest finds leaks by force-including a header that turns `new` and `malloc` into macros. + # The tests include the service headers and with them and , whose + # placement new does not survive that, so the tests are built without it. + set(CPPUTEST_MEM_LEAK_DETECTION_DISABLED ON CACHE BOOL "Disable the CppUTest memory leak detection" FORCE) add_subdirectory(cpputest) add_subdirectory(lwjson) endif () diff --git a/libxbot-service-interface/CMakeLists.txt b/libxbot-service-interface/CMakeLists.txt index fbade6b..51f40f3 100644 --- a/libxbot-service-interface/CMakeLists.txt +++ b/libxbot-service-interface/CMakeLists.txt @@ -29,3 +29,8 @@ install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/ FILES_MATCHING PATTERN "*.h*" ) install(TARGETS xbot-service-interface) + +# Tests, see test/CMakeLists.txt. Off unless asked for. +if (XBOT_BUILD_TESTS) + add_subdirectory(test) +endif () diff --git a/libxbot-service-interface/test/CMakeLists.txt b/libxbot-service-interface/test/CMakeLists.txt new file mode 100644 index 0000000..9b8fa66 --- /dev/null +++ b/libxbot-service-interface/test/CMakeLists.txt @@ -0,0 +1,11 @@ +# Tests for xbot-service-interface. Enable with -DXBOT_BUILD_TESTS=ON (the CI preset does), run with ctest. + +# The interface generated from the template schema. It uses every type the generator knows (blob, +# string), so building it is what compiles that generated code in CI. +add_service_interface(ServiceTemplateInterface ${XBOT_CODEGEN_PATH}/templates/service.json) + +add_executable(InterfaceCodegenTests InterfaceCodegenTests.cpp) +target_compile_options(InterfaceCodegenTests PRIVATE -Wall -Wextra -Werror) +target_link_libraries(InterfaceCodegenTests PRIVATE ServiceTemplateInterface) + +add_test(NAME xbot-service-interface-codegen COMMAND InterfaceCodegenTests) diff --git a/libxbot-service-interface/test/InterfaceCodegenTests.cpp b/libxbot-service-interface/test/InterfaceCodegenTests.cpp new file mode 100644 index 0000000..c6ad4e6 --- /dev/null +++ b/libxbot-service-interface/test/InterfaceCodegenTests.cpp @@ -0,0 +1,38 @@ +// +// Checks on the interface generated from codegen/templates/service.json. +// +// The frame budget helpers are constexpr, so the checks are static_asserts: this file passes by +// compiling. Linking it is what builds the generated interface source. +// + +#include + +namespace { +using xbot::datatypes::DataDescriptor; +using xbot::datatypes::XbotHeader; + +constexpr size_t kBody = xbot::config::max_packet_size - sizeof(XbotHeader); + +// RemainingBudget is protected: it exists for the generated helpers. +struct Budget : xbot::serviceif::ServiceInterfaceBase { + using ServiceInterfaceBase::RemainingBudget; +}; + +// A saturating subtraction, for any number of subtrahends. +static_assert(Budget::RemainingBudget(10, 3) == 7); +static_assert(Budget::RemainingBudget(10, 10) == 0); +static_assert(Budget::RemainingBudget(10, 11) == 0); +static_assert(Budget::RemainingBudget(100, 10, 20, 30) == 40); +static_assert(Budget::RemainingBudget(100, 10, 200, 30) == 0); // stays at 0, does not wrap back up + +// A blob parameter may use what one packet has left after the framing of its call. +static_assert(ServiceTemplateInterfaceBase::MaxBlobParamsWithBlobReturnData() == kBody - sizeof(DataDescriptor)); + +// A string parameter is limited by its max_length (64) as well: Call...() refuses a longer value, +// so a helper that reported the packet budget would send the caller into a call that always fails. +static_assert(ServiceTemplateInterfaceBase::MaxStringParamsWithStringReturnPath() == 64); +} // namespace + +int main() { + return 0; +} diff --git a/libxbot-service/CMakeLists.txt b/libxbot-service/CMakeLists.txt index 7b28faf..e785542 100644 --- a/libxbot-service/CMakeLists.txt +++ b/libxbot-service/CMakeLists.txt @@ -50,4 +50,8 @@ install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/ install(TARGETS xbot-service) #set_property(TARGET xbot-service PROPERTY CXX_STANDARD 23) -#add_subdirectory(test) +# Unit tests, see test/CMakeLists.txt. Off unless asked for: a firmware that adds this directory +# only wants the library. +if (XBOT_BUILD_TESTS) + add_subdirectory(test) +endif () diff --git a/libxbot-service/test/CMakeLists.txt b/libxbot-service/test/CMakeLists.txt index cec883f..50ee529 100644 --- a/libxbot-service/test/CMakeLists.txt +++ b/libxbot-service/test/CMakeLists.txt @@ -1,30 +1,32 @@ +# Unit tests for xbot-service. Enable with -DXBOT_BUILD_TESTS=ON (the CI preset does), run with ctest. +# The dispatcher tests run against the service generated from the template schema. It uses every +# type the generator knows (blob, string, pooled returns), so this is also what compiles that +# generated code in CI. The name has to match the "type" in the json: the generated source +# includes Base.hpp. +add_service(ServiceTemplate ${XBOT_CODEGEN_PATH}/templates/service.json) +# Generated code ends up in firmware builds that treat warnings as errors. +target_compile_options(ServiceTemplate PRIVATE -Wall -Wextra -Werror) + +# QueueTests/QueueTests.cpp is not part of the build: it still uses the queue API from before the +# portable layer (createQueue/destroyQueue) and has to be ported before it can come back. add_executable(AllTests all_tests.cpp - QueueTests/QueueTests.cpp BufferTests/BufferTests.cpp - ${PROJECT_SOURCE_DIR}/src/Buffer.cpp - ${PROJECT_SOURCE_DIR}/src/portable/linux/queue.cpp + DispatcherTests/DispatcherTests.cpp + ServiceTests/ServiceTests.cpp ) -target_include_directories(AllTests - PRIVATE - . - ${PROJECT_SOURCE_DIR}/include - ${PROJECT_SOURCE_DIR}/../include -) - -target_compile_options(AllTests - PRIVATE $<$:/wd4723> -) +target_compile_options(AllTests PRIVATE -Wall -Wextra -Werror) target_link_libraries(AllTests PRIVATE - CppUTest::CppUTestExt - ulog + ServiceTemplate + xbot-service + CppUTest::CppUTest ) -if(CPPUTEST_TEST_DISCOVERY OR NOT DEFINED CPPUTEST_TEST_DISCOVERY) - include(${PROJECT_SOURCE_DIR}/ext/cpputest/cmake/Modules/CppUTest.cmake) - cpputest_discover_tests(AllTests) -endif() +add_test(NAME xbot-service-tests COMMAND AllTests) +# The whole suite runs in milliseconds. A bounds check that regresses shows up as a copy that +# never ends rather than as a failed assertion, so do not wait for the ctest default of 25 minutes. +set_tests_properties(xbot-service-tests PROPERTIES TIMEOUT 60) diff --git a/libxbot-service/test/DispatcherTests/DispatcherTests.cpp b/libxbot-service/test/DispatcherTests/DispatcherTests.cpp new file mode 100644 index 0000000..817262e --- /dev/null +++ b/libxbot-service/test/DispatcherTests/DispatcherTests.cpp @@ -0,0 +1,330 @@ +// +// Tests for the generated RPC dispatcher, run against the template schema. +// +// The dispatcher is called directly, without a claimed connection. A response the dispatcher or a +// handler sends is therefore dropped, and what a test can observe is whether the handler ran and +// what it was given - which is exactly the contract between the generated code and a service. +// + +#include +#include +#include +#include + +#include "../TemplateService.hpp" +#include "CppUTest/TestHarness.h" + +using namespace xbot::service; +using namespace xbot::test; + +namespace { +constexpr size_t kBlocks = 2; +constexpr size_t kBlockSize = kPoolBlockSize; +constexpr uint16_t kCallId = 7; + +// Static for the same reason as in BufferTests: the pool keeps the pointer. +alignas(buffer::block_alignment) uint8_t pool_[kBlocks * kBlockSize]{}; + +bool allZero(const void* data, size_t size) { + const auto* bytes = static_cast(data); + return std::all_of(bytes, bytes + size, [](uint8_t b) { return b == 0; }); +} + +// An RPC body: one DataDescriptor per parameter, each followed by its bytes. +struct Body { + std::vector bytes; + + Body& add(uint16_t id, const void* data, uint32_t size) { + return addAnnouncing(id, data, size, size); + } + + // Sends size bytes but announces another length in the descriptor. + Body& addAnnouncing(uint16_t id, const void* data, uint32_t size, uint32_t announced) { + xbot::datatypes::DataDescriptor descriptor{}; + descriptor.target_id = id; + descriptor.payload_size = announced; + const auto* raw = reinterpret_cast(&descriptor); + bytes.insert(bytes.end(), raw, raw + sizeof(descriptor)); + const auto* payload = static_cast(data); + bytes.insert(bytes.end(), payload, payload + size); + return *this; + } +}; + +// Records what the handlers were given. +class RecordingService : public TemplateService { + public: + RecordingService() : TemplateService(1) { + } + + void call(uint8_t function_id, const Body& body) { + dispatchRpcCall(function_id, kCallId, body.bytes.data(), body.bytes.size()); + } + + int calls = 0; + + // Parameters. + std::string text; + uint32_t text_len = 0; + bool text_terminated = false; + const uint8_t* blob = nullptr; + uint32_t blob_len = 0; + float speed = 0; + uint32_t count = 0; + uint8_t enable = 0; + + // Return buffer, as the handler found it. + void* ret = nullptr; + uint16_t ret_capacity = 0; + bool ret_was_zero = false; + size_t free_blocks_in_handler = 0; + + protected: + void RPCNoParamsNoReturn(uint16_t) override { + ++calls; + } + + void RPCScalarParamsWithReturn(uint16_t, float Speed, uint32_t Count, uint8_t Enable) override { + ++calls; + speed = Speed; + count = Count; + enable = Enable; + } + + void RPCBlobParamsWithBlobReturn(uint16_t, const uint8_t* Data, uint32_t DataLen, uint8_t* data, + uint16_t* response_length) override { + ++calls; + blob = Data; + blob_len = DataLen; + recordReturn(data, *response_length, *response_length); + // What a handler does with the buffer: this must not reach the next owner of the block. + memset(data, 0xEE, *response_length); + } + + void RPCLargeArrayReturn(uint16_t, uint8_t* data, uint16_t* response_length) override { + ++calls; + recordReturn(data, *response_length, *response_length); + memset(data, 0xEE, *response_length); + } + + void RPCStringParamsWithStringReturn(uint16_t, const char* Path, uint32_t PathLen, char* data, + uint16_t* response_length) override { + ++calls; + text.assign(Path, PathLen); + text_len = PathLen; + text_terminated = Path[PathLen] == '\0'; + // A string return has one byte more than its limit, for the terminator. + recordReturn(data, *response_length, static_cast(*response_length) + 1); + } + + void RPCLargeStringReturn(uint16_t, char* data, uint16_t* response_length) override { + ++calls; + recordReturn(data, *response_length, static_cast(*response_length) + 1); + memset(data, 'x', *response_length); + } + + private: + void recordReturn(void* data, uint16_t capacity, size_t bytes) { + ret = data; + ret_capacity = capacity; + ret_was_zero = allZero(data, bytes); + free_blocks_in_handler = buffer::available(); + } +}; + +// Leaves every block of the pool full of 0xA5, like a previous owner would. +void dirtyThePool() { + buffer::Lease first = buffer::acquire(1); + buffer::Lease second = buffer::acquire(1); + memset(first.data(), 0xA5, first.size()); + memset(second.data(), 0xA5, second.size()); +} +} // namespace + +TEST_GROUP(DispatcherTests) { + RecordingService service; + + void setup() override { + CHECK_TRUE(buffer::initialize(pool_, kBlockSize, kBlocks)); + dirtyThePool(); + } + + void teardown() override { + // The dispatcher returns its block when the call is over, whatever the outcome. + LONGS_EQUAL(kBlocks, buffer::available()); + } +}; + +TEST(DispatcherTests, CallWithoutParameters) { + service.call(kNoParamsNoReturn, Body{}); + LONGS_EQUAL(1, service.calls); +} + +TEST(DispatcherTests, ScalarParametersArriveInAnyOrder) { + const float speed = 1.5F; + const uint32_t count = 42; + const uint8_t enable = 1; + service.call(kScalarParamsWithReturn, + Body{}.add(2, &enable, sizeof(enable)).add(0, &speed, sizeof(speed)).add(1, &count, sizeof(count))); + LONGS_EQUAL(1, service.calls); + DOUBLES_EQUAL(1.5, service.speed, 0.0); + LONGS_EQUAL(42, service.count); + LONGS_EQUAL(1, service.enable); +} + +TEST(DispatcherTests, UnknownParameterIsSkipped) { + const float speed = 1.5F; + const uint32_t count = 42; + const uint8_t enable = 1; + const uint32_t unknown = 0xDEADBEEF; + service.call(kScalarParamsWithReturn, Body{} + .add(0, &speed, sizeof(speed)) + .add(99, &unknown, sizeof(unknown)) + .add(1, &count, sizeof(count)) + .add(2, &enable, sizeof(enable))); + LONGS_EQUAL(1, service.calls); + LONGS_EQUAL(42, service.count); +} + +TEST(DispatcherTests, MissingParameterIsRejected) { + const float speed = 1.5F; + const uint32_t count = 42; + service.call(kScalarParamsWithReturn, Body{}.add(0, &speed, sizeof(speed)).add(1, &count, sizeof(count))); + LONGS_EQUAL(0, service.calls); +} + +TEST(DispatcherTests, DuplicateParameterIsRejected) { + const float speed = 1.5F; + const uint32_t count = 42; + const uint8_t enable = 1; + service.call(kScalarParamsWithReturn, Body{} + .add(0, &speed, sizeof(speed)) + .add(0, &speed, sizeof(speed)) + .add(1, &count, sizeof(count)) + .add(2, &enable, sizeof(enable))); + LONGS_EQUAL(0, service.calls); +} + +TEST(DispatcherTests, WrongScalarSizeIsRejected) { + const float speed = 1.5F; + const uint16_t count = 42; // the schema says uint32_t + const uint8_t enable = 1; + service.call(kScalarParamsWithReturn, + Body{}.add(0, &speed, sizeof(speed)).add(1, &count, sizeof(count)).add(2, &enable, sizeof(enable))); + LONGS_EQUAL(0, service.calls); +} + +TEST(DispatcherTests, UnknownFunctionIsRejected) { + service.call(200, Body{}); + LONGS_EQUAL(0, service.calls); +} + +TEST(DispatcherTests, StringParameterIsTerminatedAndCounted) { + service.call(kStringParamsWithStringReturn, Body{}.add(0, "/sounds/a.mp3", 13)); + LONGS_EQUAL(1, service.calls); + STRCMP_EQUAL("/sounds/a.mp3", service.text.c_str()); + LONGS_EQUAL(13, service.text_len); + CHECK_TRUE(service.text_terminated); +} + +TEST(DispatcherTests, EmptyStringParameterIsTerminated) { + service.call(kStringParamsWithStringReturn, Body{}.add(0, "", 0)); + LONGS_EQUAL(1, service.calls); + LONGS_EQUAL(0, service.text_len); + CHECK_TRUE(service.text_terminated); +} + +TEST(DispatcherTests, StringParameterMayUseTheWholeLimit) { + const std::string path(64, 'p'); // max_length of Path + service.call(kStringParamsWithStringReturn, Body{}.add(0, path.data(), 64)); + LONGS_EQUAL(1, service.calls); + STRCMP_EQUAL(path.c_str(), service.text.c_str()); + CHECK_TRUE(service.text_terminated); +} + +TEST(DispatcherTests, StringParameterAboveTheLimitIsRejected) { + const std::string path(65, 'p'); + service.call(kStringParamsWithStringReturn, Body{}.add(0, path.data(), 65)); + LONGS_EQUAL(0, service.calls); // rejected, not shortened +} + +TEST(DispatcherTests, StringReturnBufferIsClearedAndHoldsTheTerminator) { + service.call(kStringParamsWithStringReturn, Body{}.add(0, "a", 1)); + LONGS_EQUAL(1, service.calls); + LONGS_EQUAL(96, service.ret_capacity); // max_length of the return; the buffer has one byte more + CHECK_TRUE(service.ret_was_zero); + LONGS_EQUAL(kBlocks, service.free_blocks_in_handler); // small enough for the stack +} + +TEST(DispatcherTests, BlobParameterPointsIntoThePacket) { + const uint8_t data[] = {1, 2, 3, 4, 5}; + const Body body = Body{}.add(0, data, sizeof(data)); + service.call(kBlobParamsWithBlobReturn, body); + LONGS_EQUAL(1, service.calls); + POINTERS_EQUAL(body.bytes.data() + sizeof(xbot::datatypes::DataDescriptor), service.blob); + LONGS_EQUAL(sizeof(data), service.blob_len); +} + +TEST(DispatcherTests, EmptyBlobParameterIsAccepted) { + service.call(kBlobParamsWithBlobReturn, Body{}.add(0, nullptr, 0)); + LONGS_EQUAL(1, service.calls); + LONGS_EQUAL(0, service.blob_len); +} + +TEST(DispatcherTests, DescriptorLongerThanThePacketIsRejected) { + const uint8_t data[] = {1, 2, 3, 4}; + // One byte more than is there, and a length that wraps "offset + payload_size" where size_t has 32 bits. + service.call(kBlobParamsWithBlobReturn, Body{}.addAnnouncing(0, data, sizeof(data), sizeof(data) + 1)); + service.call(kBlobParamsWithBlobReturn, Body{}.addAnnouncing(0, data, sizeof(data), 0xFFFFFFF0U)); + LONGS_EQUAL(0, service.calls); +} + +TEST(DispatcherTests, BlobReturnIsAClearedBlockOfOnePacket) { + service.call(kBlobParamsWithBlobReturn, Body{}.add(0, "x", 1)); + LONGS_EQUAL(1, service.calls); + LONGS_EQUAL(buffer::min_block_size, service.ret_capacity); + CHECK_TRUE(service.ret_was_zero); // not the 0xA5 the previous owner left behind + LONGS_EQUAL(kBlocks - 1, service.free_blocks_in_handler); + CHECK_TRUE(service.ret == pool_ || service.ret == pool_ + kBlockSize); +} + +TEST(DispatcherTests, LargeArrayReturnIsACleared_PooledBuffer) { + service.call(kLargeArrayReturn, Body{}); + LONGS_EQUAL(1, service.calls); + LONGS_EQUAL(256, service.ret_capacity); + CHECK_TRUE(service.ret_was_zero); + LONGS_EQUAL(kBlocks - 1, service.free_blocks_in_handler); +} + +TEST(DispatcherTests, LargeStringReturnIsACleared_PooledBuffer) { + service.call(kLargeStringReturn, Body{}); + LONGS_EQUAL(1, service.calls); + LONGS_EQUAL(200, service.ret_capacity); + CHECK_TRUE(service.ret_was_zero); // including the byte for the terminator + LONGS_EQUAL(kBlocks - 1, service.free_blocks_in_handler); +} + +TEST(DispatcherTests, PooledReturnIsClearedOnEveryCall) { + // The handler fills the buffer; the next call must not see that either. + service.call(kLargeArrayReturn, Body{}); + service.call(kLargeArrayReturn, Body{}); + service.call(kLargeStringReturn, Body{}); + LONGS_EQUAL(3, service.calls); + CHECK_TRUE(service.ret_was_zero); +} + +TEST(DispatcherTests, PooledReturnIsRefusedWhileNoBlockIsFree) { + { + buffer::Lease first = buffer::acquire(1); + buffer::Lease second = buffer::acquire(1); + service.call(kLargeArrayReturn, Body{}); + service.call(kBlobParamsWithBlobReturn, Body{}.add(0, "x", 1)); + LONGS_EQUAL(0, service.calls); // answered BUSY, the handler never ran + + // A return that fits on the stack does not depend on the pool. + service.call(kStringParamsWithStringReturn, Body{}.add(0, "a", 1)); + LONGS_EQUAL(1, service.calls); + } + service.call(kLargeArrayReturn, Body{}); + LONGS_EQUAL(2, service.calls); +} diff --git a/libxbot-service/test/ServiceTests/ServiceTests.cpp b/libxbot-service/test/ServiceTests/ServiceTests.cpp new file mode 100644 index 0000000..811e633 --- /dev/null +++ b/libxbot-service/test/ServiceTests/ServiceTests.cpp @@ -0,0 +1,75 @@ +// +// Tests for the parts of Service that work without a claimed connection. +// + +#include + +#include "../TemplateService.hpp" +#include "CppUTest/TestHarness.h" + +using namespace xbot::test; + +namespace { +constexpr size_t kScratchSize = xbot::config::max_packet_size - sizeof(xbot::datatypes::XbotHeader); +constexpr size_t kDescriptorSize = sizeof(xbot::datatypes::DataDescriptor); + +class SendingService : public TemplateService { + public: + SendingService() : TemplateService(2) { + } + + using TemplateService::CommitTransaction; + using TemplateService::scratch_buffer_fill_; + using TemplateService::SendData; + using TemplateService::SendExampleOutputBlob; + using TemplateService::StartTransaction; +}; + +const uint8_t data_[kScratchSize]{}; +} // namespace + +TEST_GROUP(ServiceTests) { + SendingService service; + + void setup() override { + CHECK_TRUE(service.StartTransaction()); + } + + void teardown() override { + // Nobody claimed the service, so nothing is sent - but the commit releases the transaction lock. + CHECK_FALSE(service.CommitTransaction()); + } +}; + +TEST(ServiceTests, TransactionAppendsDescriptorAndData) { + CHECK_TRUE(service.SendExampleOutputBlob(data_, 100)); + LONGS_EQUAL(kDescriptorSize + 100, service.scratch_buffer_fill_); + CHECK_TRUE(service.SendExampleOutputBlob(data_, 0)); + LONGS_EQUAL(2 * kDescriptorSize + 100, service.scratch_buffer_fill_); +} + +TEST(ServiceTests, TransactionTakesAValueThatFillsThePacket) { + CHECK_TRUE(service.SendExampleOutputBlob(data_, kScratchSize - kDescriptorSize)); + LONGS_EQUAL(kScratchSize, service.scratch_buffer_fill_); + // Full: not even an empty value fits, it still needs its descriptor. + CHECK_FALSE(service.SendExampleOutputBlob(data_, 0)); + LONGS_EQUAL(kScratchSize, service.scratch_buffer_fill_); +} + +TEST(ServiceTests, TransactionRejectsAValueThatDoesNotFit) { + CHECK_FALSE(service.SendExampleOutputBlob(data_, kScratchSize - kDescriptorSize + 1)); + LONGS_EQUAL(0, service.scratch_buffer_fill_); + + CHECK_TRUE(service.SendExampleOutputBlob(data_, 1000)); + CHECK_FALSE(service.SendExampleOutputBlob(data_, 1000)); + LONGS_EQUAL(kDescriptorSize + 1000, service.scratch_buffer_fill_); +} + +TEST(ServiceTests, TransactionRejectsASizeThatWrapsTheSum) { + // fill + size + descriptor wraps to a small number for these; the check must not add them up. + CHECK_FALSE(service.SendData(2, data_, SIZE_MAX)); + CHECK_FALSE(service.SendData(2, data_, SIZE_MAX - kDescriptorSize + 1)); + CHECK_TRUE(service.SendExampleOutputBlob(data_, 100)); + CHECK_FALSE(service.SendData(2, data_, SIZE_MAX - kDescriptorSize - 100)); + LONGS_EQUAL(kDescriptorSize + 100, service.scratch_buffer_fill_); +} diff --git a/libxbot-service/test/TemplateService.hpp b/libxbot-service/test/TemplateService.hpp new file mode 100644 index 0000000..8c4abe3 --- /dev/null +++ b/libxbot-service/test/TemplateService.hpp @@ -0,0 +1,66 @@ +// +// The service generated from codegen/templates/service.json, opened up for the tests. +// + +#ifndef XBOT_TEST_TEMPLATE_SERVICE_HPP +#define XBOT_TEST_TEMPLATE_SERVICE_HPP + +// Everything the generated header pulls in, so the define below only reaches the generated class. +#include +#include + +// dispatchRpcCall() is a private override in the generated class and is only reached through a +// received packet. The dispatcher tests have to call it directly. +#define private public +#include +#undef private + +#include +#include + +namespace xbot::test { + +// Function ids of codegen/templates/service.json. +enum FunctionId : uint8_t { + kNoParamsNoReturn = 0, + kScalarParamsWithReturn = 1, + kArrayParamNoReturn = 2, + kMixedParamsWithReturn = 3, + kBlobParamsWithBlobReturn = 4, + kLargeArrayReturn = 5, + kStringParamsWithStringReturn = 6, + kLargeStringReturn = 7, +}; + +// The smallest block a buffer pool accepts, rounded up to the block alignment. +constexpr size_t kPoolBlockSize = (xbot::service::buffer::min_block_size + xbot::service::buffer::block_alignment - 1) / + xbot::service::buffer::block_alignment * xbot::service::buffer::block_alignment; + +// The template service with every handler stubbed out. A test overrides what it looks at. +class TemplateService : public ServiceTemplateBase { + public: + explicit TemplateService(uint16_t service_id) : ServiceTemplateBase(service_id) { + } + + protected: + void RPCNoParamsNoReturn(uint16_t) override { + } + void RPCScalarParamsWithReturn(uint16_t, float, uint32_t, uint8_t) override { + } + void RPCArrayParamNoReturn(uint16_t, const char*, uint32_t) override { + } + void RPCMixedParamsWithReturn(uint16_t, const char*, uint32_t, float) override { + } + void RPCBlobParamsWithBlobReturn(uint16_t, const uint8_t*, uint32_t, uint8_t*, uint16_t*) override { + } + void RPCLargeArrayReturn(uint16_t, uint8_t*, uint16_t*) override { + } + void RPCStringParamsWithStringReturn(uint16_t, const char*, uint32_t, char*, uint16_t*) override { + } + void RPCLargeStringReturn(uint16_t, char*, uint16_t*) override { + } +}; + +} // namespace xbot::test + +#endif // XBOT_TEST_TEMPLATE_SERVICE_HPP diff --git a/libxbot-service/test/all_tests.cpp b/libxbot-service/test/all_tests.cpp index 64ceec4..c0350ac 100644 --- a/libxbot-service/test/all_tests.cpp +++ b/libxbot-service/test/all_tests.cpp @@ -3,8 +3,9 @@ // #include "CppUTest/CommandLineTestRunner.h" -IMPORT_TEST_GROUP(QueueTests); IMPORT_TEST_GROUP(BufferTests); +IMPORT_TEST_GROUP(DispatcherTests); +IMPORT_TEST_GROUP(ServiceTests); int main(int argc, char** argv) { return RUN_ALL_TESTS(argc, argv); From 0cef969b58957c91b58fe5bef411dfa6046a8a91 Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 17:13:08 +0100 Subject: [PATCH 20/28] docs(readme): return buffers, pool lifetime and the packet limit - A handler sends its return value itself, for every return type; the dispatcher never does. The string section read as if it did. - Return buffers are zero-filled, also when they come from the pool. - A block is out for as long as the handler runs, not only while the value is copied, and a caller sees an exhausted pool as BUSY. - An existing type[N] return above 128 bytes moves from the stack to the pool: same wire format, but it can answer BUSY now and needs a pool. - initialize() refuses blocks below one packet payload, and the pool macros have to be set through CMake to reach the library. - The parameters of a function have to fit into one packet together. - Clients refuse what does not fit into one packet, the string budget helper is capped at max_length, and the C++ client reports RPC_BUSY. --- Readme.md | 63 +++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 52 insertions(+), 11 deletions(-) diff --git a/Readme.md b/Readme.md index a36c543..b17f5c9 100644 --- a/Readme.md +++ b/Readme.md @@ -251,19 +251,25 @@ Services are defined in a JSON file. The code generator (`codegen/`) reads this not copied, as an input or output it is passed/sent as `(pointer, length)` with the length in bytes, as a register it is the configuration blob, and as a return value it uses the shared buffer pool (see [Shared Buffer Pool](#shared-buffer-pool)). A `type[N]` return above 128 bytes is pooled the same way, so a -service never reserves stack for a payload it rarely sends. +service never reserves stack for a payload it rarely sends. A blob output is bounded by one packet as well: +`Send{Name}()` returns `false` for more than 1448 bytes instead of sending a packet without its body. `string` carries text and keeps the C string handling out of the service: the schema declares a `max_length`, the wire carries the UTF-8 bytes without a terminator (the same layout as `blob`), and the generated server decodes it into a checked, always terminated `char[max_length + 1]` before it calls the handler - a longer payload is answered with `RpcStatus::ERROR` instead of being shortened. The handler gets `const char*` plus the -byte count and can hand it to LittleFS, `printf` or a parser without copying or truncating. Returns work the same -way: the handler fills a buffer of `max_length + 1` bytes and reports the length, clients get `std::string` -(C++), `string` (Go) and `str` (Python). Clients refuse a value above `max_length` before sending. +byte count and can hand it to LittleFS, `printf` or a parser without copying or truncating. A return gets a +zero-filled buffer of `max_length + 1` bytes: the handler writes its text and sends it with +`SendRpcResponse(call_id, RpcStatus::SUCCESS, data, strlen(data))` - like every return value it is sent by the +handler, never by the dispatcher, and the terminator stays local. Clients get `std::string` (C++), `string` (Go) +and `str` (Python), and refuse a value above `max_length` before sending. The dispatcher reserves `max_length + 1` bytes of stack for the call, so `max_length` is capped at one packet body minus a descriptor (1440 bytes) and the working area of the service has to be sized for it - the thread watermark -shows what a service really uses. +shows what a service really uses. The parameters of one function also have to fit into one packet together: the +generators add up a descriptor (8 bytes) plus the largest payload of every fixed size, array and `string` +parameter and reject a function that needs more than 1448 bytes. Two 1440 byte strings could never be sent in +one call, but would reserve 2882 bytes of stack. A `blob` parameter only counts with its descriptor. A `string` may contain U+0000: the terminator is a convenience for C APIs, so a handler that can pass the value on to `printf`, LittleFS or a parser and wants the whole value has to use the byte count (`Len`) instead of assuming the text ends at the first NUL. @@ -297,9 +303,13 @@ Moving a `blob` text parameter to `string` keeps the wire layout, so it needs no - `void RPC{Name}(uint16_t call_id, ...)` — one pure virtual per function; a `blob` parameter arrives as `const uint8_t* , uint32_t Len` and is only valid until the handler returns (copy it if you need it longer) -- A `type[N]` return above the stack threshold and a `blob` return append `uint8_t* data, - uint16_t* response_length`. A `blob` return is always `uint8_t`, a `type[N]` return uses its element - type; `*response_length` is a byte count for `blob` and an element count for `type[N]` +- A `type[N]`, `string` or `blob` return appends `T* data, uint16_t* response_length`: a zero-filled buffer + and its capacity. A `blob` return is always `uint8_t`, a `string` return `char`, a `type[N]` return uses + its element type; `*response_length` is a byte count for `blob` and `string` (without the terminator) and + an element count for `type[N]` +- The handler answers every call itself with `SendRpcResponse(call_id, status, data, size_in_bytes)`. The + dispatcher never sends a return value and does not read `*response_length` back, so a handler that + returns without answering leaves the call pending and the service answers BUSY from then on **Generated API (interface side — same JSON, different template):** - Inputs and outputs swap roles: outputs become callbacks, inputs become send methods. @@ -309,6 +319,14 @@ Moving a `blob` text parameter to `string` keeps the wire layout, so it needs no limits it belongs to the generator, not to every client. The helpers saturate: a call whose other parameters already use up the packet reports 0, so a chunker has to stop instead of sending. Every chunk is `min(bytes left, budget)` long - the budget is an upper bound, only the last chunk is shorter. + A `string` parameter gets the same helper, capped at its `max_length`: the call refuses a longer value + even when the packet has room for it. +- A call, an input or a transaction that does not fit into one packet is refused before it is sent + (`Call{Name}()`/`Send{Name}()` return `false` in C++, an error in Go, `ValueError` in Python). The + services drop an oversized datagram without an answer, which would look like a timeout or a lost value. +- The C++ `Call{Name}()` methods return `bool`. `GetLastRpcResult()` tells the reasons apart: `RPC_BUSY` + means the service refused the call for now (another call in progress, or no free block in its buffer + pool) and the call can be repeated, `RPC_TIMEOUT` and `RPC_ERROR` mean it cannot. **CMake integration:** ```cmake @@ -344,6 +362,10 @@ fill(lease.data(), lease.size()); // lease.size() is the capacity, not the requ SendRpcResponse(call_id, xbot::datatypes::RpcStatus::SUCCESS, lease.data(), used_bytes); ``` +A block is handed out as the previous owner left it. The generated dispatcher clears the bytes it passes +to a handler, so a pooled return buffer is zero-filled like one on the stack; code that calls `acquire()` +itself has to clear what it does not overwrite before it sends it. + Rules that keep the pool usable: - A lease is **move-only** and returns its block in the destructor. Do not keep it beyond the call @@ -355,10 +377,20 @@ Rules that keep the pool usable: no storage has been configured yet, and when the request is larger than a block; a handler that follows the pattern above answers BUSY in all three cases - an RPC handler must never wait for another service's transfer. With the default of two blocks, one outstanding return does not exhaust - the pool. A block is only held while a return value is filled and copied into a packet. -- Release happens after the handler returned; `SendRpcResponse()` copies the payload into a packet. + the pool. +- The generated dispatcher borrows the block before it calls the handler and returns it after the handler + returned (`SendRpcResponse()` copies the payload into a packet). A block is therefore out for as long + as the handler runs: a handler that does slow work before it answers keeps it for that time, and + `buffer_block_count` has to cover the pooled calls that can be in their handlers at once. +- A caller sees an exhausted pool as `RpcStatus::BUSY` and can repeat the call (`RpcBusyError` in Python, + `*xbot.RPCError` in Go, `GetLastRpcResult() == RPC_BUSY` in C++). - No heap is involved: the storage is static. +An existing schema is affected as well: a `type[N]` return above 128 bytes used to live on the stack of +its service and now comes from the pool. Its wire format is unchanged, but such a call can answer BUSY +where it could not before, and it needs a pool - check the block count when updating a firmware with +several of them. + Sizing is a platform decision. `xbot::config::buffer_block_size` (1536 by default, must hold one packet payload - asserted at build time) and `buffer_block_count` (2) only size the framework internal default storage. A platform that brings its own storage - e.g. a section in a RAM region @@ -371,7 +403,16 @@ xbot::service::buffer::initialize(storage, 1536, 2); ``` once, before the services start, and sets `XBOT_BUFFER_DEFAULT_POOL=0` so the default array is not -linked in at all. `initialize()` is not thread safe and refuses to run while a lease is out. +linked in at all. `initialize()` is not thread safe and refuses to run while a lease is out. It also +refuses blocks below `xbot::service::buffer::min_block_size` (one packet payload, 1448 bytes): the +generated dispatchers borrow up to that much, and a pool that cannot serve it would answer BUSY forever. + +`XBOT_BUFFER_DEFAULT_POOL`, `XBOT_BUFFER_BLOCK_SIZE` and `XBOT_BUFFER_BLOCK_COUNT` are compiled into the +xbot-service library, so set them as CMake variables (`-DXBOT_BUFFER_DEFAULT_POOL=0`, or `set()` before +`add_subdirectory`): they are then defined for the library and for everything that links it. A definition +on the application target alone does not reach the library, and the default array stays. Without a pool - +the default one disabled and `initialize()` not called - every pooled call is answered with BUSY and the +first one logs a warning. Parameters hit the same stack limit from the other direction: a fixed `type[N]` parameter is copied into a stack array by the generated dispatcher, which is why a variable length payload had to be declared as From c64829537cdcea42c59bf41b1b909466236f8471 Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 19:23:13 +0100 Subject: [PATCH 21/28] fix(buffer): make the one-time warning flags atomic acquire() runs on several threads. The flags that limit the 'not initialized' and 'request too large' messages to one line were plain bools, which is a data race, not only a duplicated line. An atomic exchange picks the one caller that logs. --- libxbot-service/src/Buffer.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/libxbot-service/src/Buffer.cpp b/libxbot-service/src/Buffer.cpp index f0366fe..4f21b37 100644 --- a/libxbot-service/src/Buffer.cpp +++ b/libxbot-service/src/Buffer.cpp @@ -50,10 +50,11 @@ size_t block_count_ = 0; // working unchanged. std::atomic used_mask_{0}; -// Guard the "not initialized" and "request too large" log lines only, so a plain -// bool is enough: the worst case is a duplicated line. -bool warned_uninitialized_ = false; -bool warned_oversized_ = false; +// Guard the "not initialized" and "request too large" log lines only. acquire() runs on several +// threads, so they are atomic as well; exchange() lets exactly one caller log, and relaxed order is +// enough because nothing else is published through them. +std::atomic warned_uninitialized_{false}; +std::atomic warned_oversized_{false}; uint32_t blockBit(uint8_t index) { return uint32_t{1} << index; @@ -129,16 +130,14 @@ bool xbot::service::buffer::initialize(void *storage, size_t block_size, size_t xbot::service::buffer::Lease xbot::service::buffer::acquire(size_t bytes) { if (storage_ == nullptr) { - if (!warned_uninitialized_) { - warned_uninitialized_ = true; + if (!warned_uninitialized_.exchange(true, std::memory_order_relaxed)) { ULOG_WARNING("Buffer pool is not initialized, call xbot::service::buffer::initialize()"); } return {}; } if (bytes > block_size_) { // Not a transient condition like an exhausted pool: this request can never succeed. - if (!warned_oversized_) { - warned_oversized_ = true; + if (!warned_oversized_.exchange(true, std::memory_order_relaxed)) { ULOG_ERROR("Buffer pool: request of %u bytes exceeds the block size of %u bytes", static_cast(bytes), static_cast(block_size_)); } From 84dda8f0f792bd8fb7a6692e5812f3eff1e99b89 Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 19:23:13 +0100 Subject: [PATCH 22/28] fix(interface): record RPC_ERROR when a generated call fails on its own A generated Call...() that refused an argument (string over max_length, null pointer) or an answer (wrong size) returned false without touching the last RPC result. After a BUSY answer, GetLastRpcResult() kept reporting RPC_BUSY, so a caller would retry a call that can never succeed. Those paths now return through FailRpc(), which records RPC_ERROR. A failed SendRpc() still passes on its own result, so RPC_BUSY stays for real BUSY answers. The interface test now runs the generated calls against a fake network to check this. --- Readme.md | 3 +- .../templates/ServiceInterfaceTemplate.cpp | 34 +++--- .../ServiceInterfaceBase.hpp | 12 ++ libxbot-service-interface/test/CMakeLists.txt | 6 +- .../test/InterfaceCodegenTests.cpp | 115 +++++++++++++++++- 5 files changed, 149 insertions(+), 21 deletions(-) diff --git a/Readme.md b/Readme.md index b17f5c9..df2c343 100644 --- a/Readme.md +++ b/Readme.md @@ -326,7 +326,8 @@ Moving a `blob` text parameter to `string` keeps the wire layout, so it needs no services drop an oversized datagram without an answer, which would look like a timeout or a lost value. - The C++ `Call{Name}()` methods return `bool`. `GetLastRpcResult()` tells the reasons apart: `RPC_BUSY` means the service refused the call for now (another call in progress, or no free block in its buffer - pool) and the call can be repeated, `RPC_TIMEOUT` and `RPC_ERROR` mean it cannot. + pool) and the call can be repeated, `RPC_TIMEOUT` and `RPC_ERROR` mean it cannot. A call the method + refuses itself (an argument over its limit, an answer of the wrong size) is `RPC_ERROR` as well. **CMake integration:** ```cmake diff --git a/codegen/templates/ServiceInterfaceTemplate.cpp b/codegen/templates/ServiceInterfaceTemplate.cpp index 14ee521..44799af 100644 --- a/codegen/templates/ServiceInterfaceTemplate.cpp +++ b/codegen/templates/ServiceInterfaceTemplate.cpp @@ -151,7 +151,9 @@ for func in service["functions"]: params_str = ", ".join(sig_params) cog.outl(f"bool {service['interface_class_name']}::Call{func['name']}({params_str}) {{") - # Serialize parameters into a DataDescriptor-framed byte vector + # Serialize parameters into a DataDescriptor-framed byte vector. A call refused here, or a + # response refused below, returns through FailRpc() so GetLastRpcResult() says RPC_ERROR; + # only a failed SendRpc() returns plain false, as it has recorded its own result already. if func["parameters"]: cog.outl(" std::vector params_buf;") for p in func["parameters"]: @@ -167,15 +169,15 @@ for func in service["functions"]: cog.outl(f" {{") if p['is_string']: # Before strlen(): a null C string is a caller bug, not a crash. - cog.outl(f" if ({p['name']} == nullptr) return false;") + cog.outl(f" if ({p['name']} == nullptr) return FailRpc();") cog.outl(f" const size_t byte_len = {byte_len_expr};") if p['is_string']: - cog.outl(f" if (byte_len > {p['max_length']}) return false;") + cog.outl(f" if (byte_len > {p['max_length']}) return FailRpc();") cog.outl(f" const size_t off = params_buf.size();") cog.outl(f" params_buf.resize(off + sizeof(xbot::datatypes::DataDescriptor) + byte_len);") cog.outl(f" auto* desc = reinterpret_cast(params_buf.data() + off);") cog.outl(f" desc->target_id = {p['id']}; desc->reserved = 0; desc->payload_size = static_cast(byte_len);") - cog.outl(f" if (byte_len > 0 && {p['name']} == nullptr) return false;") + cog.outl(f" if (byte_len > 0 && {p['name']} == nullptr) return FailRpc();") cog.outl(f" memcpy(params_buf.data() + off + sizeof(xbot::datatypes::DataDescriptor), {p['name']}, byte_len);") cog.outl(f" }}") else: @@ -202,7 +204,7 @@ for func in service["functions"]: cog.outl(f" const auto r = SendRpc({func['id']}, {params_call}, reinterpret_cast(resp_buf), &resp_size," f" timeout_ms);") cog.outl(f" if (r != RPC_OK) return false;") - cog.outl(f" if (resp_size > {func['return_max_length']}) return false;") + cog.outl(f" if (resp_size > {func['return_max_length']}) return FailRpc();") cog.outl(f" resp_buf[resp_size] = '\\0';") cog.outl(f" result.assign(resp_buf, resp_size);") elif func['return_is_array']: @@ -215,7 +217,7 @@ for func in service["functions"]: cog.outl(f" size_t resp_size = sizeof({func['return_type']});") cog.outl(f" const auto r = SendRpc({func['id']}, {params_call}, reinterpret_cast(&resp_buf), &resp_size, timeout_ms);") cog.outl(f" if (r != RPC_OK) return false;") - cog.outl(f" if (resp_size < sizeof({func['return_type']})) return false;") + cog.outl(f" if (resp_size < sizeof({func['return_type']})) return FailRpc();") cog.outl(f" result = resp_buf;") else: cog.outl(f" size_t resp_size = 0;") @@ -258,7 +260,7 @@ bool ServiceTemplateInterfaceBase::CallScalarParamsWithReturn(const float& Speed size_t resp_size = sizeof(int32_t); const auto r = SendRpc(1, params_buf.data(), params_buf.size(), reinterpret_cast(&resp_buf), &resp_size, timeout_ms); if (r != RPC_OK) return false; - if (resp_size < sizeof(int32_t)) return false; + if (resp_size < sizeof(int32_t)) return FailRpc(); result = resp_buf; return true; } @@ -270,7 +272,7 @@ bool ServiceTemplateInterfaceBase::CallArrayParamNoReturn(const char* Label, uin params_buf.resize(off + sizeof(xbot::datatypes::DataDescriptor) + byte_len); auto* desc = reinterpret_cast(params_buf.data() + off); desc->target_id = 0; desc->reserved = 0; desc->payload_size = static_cast(byte_len); - if (byte_len > 0 && Label == nullptr) return false; + if (byte_len > 0 && Label == nullptr) return FailRpc(); memcpy(params_buf.data() + off + sizeof(xbot::datatypes::DataDescriptor), Label, byte_len); } size_t resp_size = 0; @@ -286,7 +288,7 @@ bool ServiceTemplateInterfaceBase::CallMixedParamsWithReturn(const char* Name, u params_buf.resize(off + sizeof(xbot::datatypes::DataDescriptor) + byte_len); auto* desc = reinterpret_cast(params_buf.data() + off); desc->target_id = 0; desc->reserved = 0; desc->payload_size = static_cast(byte_len); - if (byte_len > 0 && Name == nullptr) return false; + if (byte_len > 0 && Name == nullptr) return FailRpc(); memcpy(params_buf.data() + off + sizeof(xbot::datatypes::DataDescriptor), Name, byte_len); } { @@ -300,7 +302,7 @@ bool ServiceTemplateInterfaceBase::CallMixedParamsWithReturn(const char* Name, u size_t resp_size = sizeof(uint8_t); const auto r = SendRpc(3, params_buf.data(), params_buf.size(), reinterpret_cast(&resp_buf), &resp_size, timeout_ms); if (r != RPC_OK) return false; - if (resp_size < sizeof(uint8_t)) return false; + if (resp_size < sizeof(uint8_t)) return FailRpc(); result = resp_buf; return true; } @@ -312,7 +314,7 @@ bool ServiceTemplateInterfaceBase::CallBlobParamsWithBlobReturn(const uint8_t* D params_buf.resize(off + sizeof(xbot::datatypes::DataDescriptor) + byte_len); auto* desc = reinterpret_cast(params_buf.data() + off); desc->target_id = 0; desc->reserved = 0; desc->payload_size = static_cast(byte_len); - if (byte_len > 0 && Data == nullptr) return false; + if (byte_len > 0 && Data == nullptr) return FailRpc(); memcpy(params_buf.data() + off + sizeof(xbot::datatypes::DataDescriptor), Data, byte_len); } size_t resp_size = result_length; @@ -331,21 +333,21 @@ bool ServiceTemplateInterfaceBase::CallLargeArrayReturn(uint8_t* data, uint16_t& bool ServiceTemplateInterfaceBase::CallStringParamsWithStringReturn(const char* Path, std::string& result, uint32_t timeout_ms) { std::vector params_buf; { - if (Path == nullptr) return false; + if (Path == nullptr) return FailRpc(); const size_t byte_len = strlen(Path); - if (byte_len > 64) return false; + if (byte_len > 64) return FailRpc(); const size_t off = params_buf.size(); params_buf.resize(off + sizeof(xbot::datatypes::DataDescriptor) + byte_len); auto* desc = reinterpret_cast(params_buf.data() + off); desc->target_id = 0; desc->reserved = 0; desc->payload_size = static_cast(byte_len); - if (byte_len > 0 && Path == nullptr) return false; + if (byte_len > 0 && Path == nullptr) return FailRpc(); memcpy(params_buf.data() + off + sizeof(xbot::datatypes::DataDescriptor), Path, byte_len); } char resp_buf[96 + 1] = {}; size_t resp_size = 96; const auto r = SendRpc(6, params_buf.data(), params_buf.size(), reinterpret_cast(resp_buf), &resp_size, timeout_ms); if (r != RPC_OK) return false; - if (resp_size > 96) return false; + if (resp_size > 96) return FailRpc(); resp_buf[resp_size] = '\0'; result.assign(resp_buf, resp_size); return true; @@ -355,7 +357,7 @@ bool ServiceTemplateInterfaceBase::CallLargeStringReturn(std::string& result, ui size_t resp_size = 200; const auto r = SendRpc(7, nullptr, 0, reinterpret_cast(resp_buf), &resp_size, timeout_ms); if (r != RPC_OK) return false; - if (resp_size > 200) return false; + if (resp_size > 200) return FailRpc(); resp_buf[resp_size] = '\0'; result.assign(resp_buf, resp_size); return true; diff --git a/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp b/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp index eae5a4d..d033af7 100644 --- a/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp +++ b/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp @@ -36,6 +36,8 @@ class ServiceInterfaceBase : public xbot::serviceif::ServiceIOCallbacks, /** * Result of the most recent RPC of this interface. The generated Call...() methods only return * true or false; this tells a failed call that is worth repeating (RPC_BUSY) from one that is not. + * A call that Call...() refuses on its own, before sending it (an argument over its limit) or + * after the answer (a response of the wrong size), is RPC_ERROR. * * It is one value per interface: with several threads calling at the same time it may already * belong to another thread's call. @@ -68,6 +70,16 @@ class ServiceInterfaceBase : public xbot::serviceif::ServiceIOCallbacks, */ RPC_RESULT SendRpc(uint8_t function_id, const uint8_t *params, size_t params_size, uint8_t* response_buffer, size_t *response_buffer_size, uint32_t timeout_ms = 1000); + /** + * Records RPC_ERROR as the last RPC result and returns false. The generated Call...() methods + * return through this whenever they fail a call themselves instead of passing on what SendRpc + * reported, so GetLastRpcResult() never shows the result of an earlier call (such as RPC_BUSY). + */ + bool FailRpc() { + last_rpc_result_ = RPC_ERROR; + return false; + } + /** * Saturating subtraction for the generated frame budget helpers (Max()): what * is left of budget after everything in used. A call whose parameters use up the whole packet diff --git a/libxbot-service-interface/test/CMakeLists.txt b/libxbot-service-interface/test/CMakeLists.txt index 9b8fa66..a24df5c 100644 --- a/libxbot-service-interface/test/CMakeLists.txt +++ b/libxbot-service-interface/test/CMakeLists.txt @@ -4,8 +4,12 @@ # string), so building it is what compiles that generated code in CI. add_service_interface(ServiceTemplateInterface ${XBOT_CODEGEN_PATH}/templates/service.json) +find_package(Threads REQUIRED) + add_executable(InterfaceCodegenTests InterfaceCodegenTests.cpp) target_compile_options(InterfaceCodegenTests PRIVATE -Wall -Wextra -Werror) -target_link_libraries(InterfaceCodegenTests PRIVATE ServiceTemplateInterface) +target_link_libraries(InterfaceCodegenTests PRIVATE ServiceTemplateInterface Threads::Threads) add_test(NAME xbot-service-interface-codegen COMMAND InterfaceCodegenTests) +# The calls wait for answers from another thread; a lost one must fail the run, not hang it. +set_tests_properties(xbot-service-interface-codegen PROPERTIES TIMEOUT 60) diff --git a/libxbot-service-interface/test/InterfaceCodegenTests.cpp b/libxbot-service-interface/test/InterfaceCodegenTests.cpp index c6ad4e6..eb3c675 100644 --- a/libxbot-service-interface/test/InterfaceCodegenTests.cpp +++ b/libxbot-service-interface/test/InterfaceCodegenTests.cpp @@ -1,11 +1,18 @@ // // Checks on the interface generated from codegen/templates/service.json. // -// The frame budget helpers are constexpr, so the checks are static_asserts: this file passes by -// compiling. Linking it is what builds the generated interface source. +// The frame budget helpers are constexpr, so those checks are static_asserts: they pass by +// compiling. Linking this file is what builds the generated interface source. main() then runs the +// generated Call...() methods against a fake network and checks what GetLastRpcResult() reports. // #include +#include +#include +#include +#include +#include +#include namespace { using xbot::datatypes::DataDescriptor; @@ -31,8 +38,110 @@ static_assert(ServiceTemplateInterfaceBase::MaxBlobParamsWithBlobReturnData() == // A string parameter is limited by its max_length (64) as well: Call...() refuses a longer value, // so a helper that reported the packet budget would send the caller into a call that always fails. static_assert(ServiceTemplateInterfaceBase::MaxStringParamsWithStringReturnPath() == 64); + +using xbot::serviceif::ServiceInterfaceBase; +using xbot::datatypes::RpcStatus; + +constexpr uint16_t kServiceId = 7; + +// Finds the service under kServiceId, with the type and version of the generated interface. +class FakeDiscovery final : public xbot::serviceif::ServiceDiscovery { + public: + void RegisterCallbacks(xbot::serviceif::ServiceDiscoveryCallbacks *) override { + } + void UnregisterCallbacks(xbot::serviceif::ServiceDiscoveryCallbacks *) override { + } + std::unique_ptr GetServiceInfo(uint16_t service_id) override { + auto info = std::make_unique(); + info->service_id_ = service_id; + info->description.type = "ServiceTemplate"; + info->description.version = 1; + return info; + } +}; + +// Stands in for the network: answers every RPC call with `status` and an empty payload. The answer +// comes from another thread, like the real receive path (SendRpc holds its lock while it sends). +class FakeIO final : public xbot::serviceif::ServiceIO { + public: + RpcStatus status = RpcStatus::SUCCESS; + + ~FakeIO() { + Join(); + } + void RegisterCallbacks(uint16_t, xbot::serviceif::ServiceIOCallbacks *callbacks) override { + callbacks_ = callbacks; + } + void UnregisterCallbacks(xbot::serviceif::ServiceIOCallbacks *) override { + callbacks_ = nullptr; + } + bool SendData(uint16_t service_id, const std::vector &data) override { + XbotHeader header{}; + memcpy(&header, data.data(), sizeof(header)); + Join(); + reply_ = std::thread([this, service_id, call_id = static_cast(header.arg2), reply_status = status] { + callbacks_->OnRpcResponse(service_id, call_id, static_cast(reply_status), nullptr, 0); + }); + return true; + } + bool OK() override { + return true; + } + + private: + void Join() { + if (reply_.joinable()) reply_.join(); + } + + xbot::serviceif::ServiceIOCallbacks *callbacks_ = nullptr; + std::thread reply_; +}; + +int failures = 0; + +void Expect(bool ok, const char *what) { + if (!ok) { + std::fprintf(stderr, "FAILED: %s\n", what); + ++failures; + } +} + +// Brings the last result to RPC_BUSY, so a later check can tell a fresh result from a stale one. +void MakeBusy(FakeIO &io, ServiceTemplateInterfaceBase &iface) { + io.status = RpcStatus::BUSY; + Expect(!iface.CallNoParamsNoReturn(), "a BUSY answer fails the call"); + Expect(iface.GetLastRpcResult() == ServiceInterfaceBase::RPC_BUSY, "a BUSY answer is reported as RPC_BUSY"); + io.status = RpcStatus::SUCCESS; +} } // namespace int main() { - return 0; + // Declared before the interface: its destructor unregisters from both. + FakeDiscovery discovery; + FakeIO io; + ServiceTemplateInterfaceBase iface(kServiceId, {&io, &discovery, nullptr}); + Expect(iface.OnServiceDiscovered(kServiceId), "the fake service is discovered"); + + Expect(iface.CallNoParamsNoReturn(), "a SUCCESS answer passes the call"); + Expect(iface.GetLastRpcResult() == ServiceInterfaceBase::RPC_OK, "a SUCCESS answer is reported as RPC_OK"); + + // Refused before sending: a string over its max_length (64), and a null string. Neither may leave + // the BUSY of the previous call behind, which would tell the caller to send it again. + std::string result; + const std::string too_long(65, 'x'); + MakeBusy(io, iface); + Expect(!iface.CallStringParamsWithStringReturn(too_long.c_str(), result), "a string over max_length is refused"); + Expect(iface.GetLastRpcResult() == ServiceInterfaceBase::RPC_ERROR, "a string over max_length is RPC_ERROR"); + + MakeBusy(io, iface); + Expect(!iface.CallStringParamsWithStringReturn(nullptr, result), "a null string is refused"); + Expect(iface.GetLastRpcResult() == ServiceInterfaceBase::RPC_ERROR, "a null string is RPC_ERROR"); + + // Refused after the answer: SendRpc saw a SUCCESS, but an empty payload is no int32_t. + int32_t value = 0; + MakeBusy(io, iface); + Expect(!iface.CallScalarParamsWithReturn(1.0f, 2, 3, value), "an empty answer to a scalar return is refused"); + Expect(iface.GetLastRpcResult() == ServiceInterfaceBase::RPC_ERROR, "an empty answer to a scalar return is RPC_ERROR"); + + return failures == 0 ? 0 : 1; } From 6ffad4e1a7fc8fbcaa22e46faa8e6a484855921b Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 19:23:13 +0100 Subject: [PATCH 23/28] fix(py): reject array responses with a partial element An array return may be shorter than declared, but a trailing partial element (e.g. three bytes for a uint16_t array) was dropped by unpack_value without an error. Such a response now raises RpcError. --- xbot_service_interface_py/tests/test_rpc.py | 21 ++++++++++++++++++- .../xbot_service_interface/interface.py | 8 +++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/xbot_service_interface_py/tests/test_rpc.py b/xbot_service_interface_py/tests/test_rpc.py index 6987206..c977acd 100644 --- a/xbot_service_interface_py/tests/test_rpc.py +++ b/xbot_service_interface_py/tests/test_rpc.py @@ -72,7 +72,7 @@ ], } -# Functions that return an enum. Kept apart from RPC_DESC so its tests keep their counts. +# Functions that return an enum or an array. Kept apart from RPC_DESC so its tests keep their counts. ENUM_RPC_DESC = { 'type': 'EnumRpcService', 'version': 1, @@ -85,6 +85,7 @@ {'id': 0, 'name': 'GetMode', 'parameters': [], 'return_type': 'Mode'}, {'id': 1, 'name': 'GetFault', 'parameters': [], 'return_type': 'Fault'}, {'id': 2, 'name': 'GetFaults', 'parameters': [], 'return_type': 'Fault[4]'}, + {'id': 3, 'name': 'GetSamples', 'parameters': [], 'return_type': 'uint16_t[4]'}, ], } @@ -392,6 +393,24 @@ def test_call_enum_return_checks_the_size(self): with pytest.raises(RpcError, match='too small'): si.call_get_fault(timeout_ms=500) + def test_call_array_return_may_be_shorter_in_whole_elements(self): + si = make_rpc_si(desc=ENUM_RPC_DESC) + _respond_async(si, call_id=1, status=0, payload=struct.pack('<3H', 1, 2, 3)) + assert si.call_get_samples(timeout_ms=500) == [1, 2, 3] + + def test_call_array_return_rejects_a_partial_element(self): + si = make_rpc_si(desc=ENUM_RPC_DESC) + _respond_async(si, call_id=1, status=0, payload=struct.pack('<2H', 1, 2) + b'\xff') + with pytest.raises(RpcError, match='whole number'): + si.call_get_samples(timeout_ms=500) + + def test_call_enum_array_return_rejects_a_partial_element(self): + # One whole Fault (OVERHEAT) and one byte of the next: not ['OVERHEAT']. + si = make_rpc_si(desc=ENUM_RPC_DESC) + _respond_async(si, call_id=1, status=0, payload=b'\x2c\x01\xff') + with pytest.raises(RpcError, match='whole number'): + si.call_get_faults(timeout_ms=500) + def test_call_array_param_void(self): si = make_rpc_si() _respond_async(si, call_id=1, status=0) diff --git a/xbot_service_interface_py/xbot_service_interface/interface.py b/xbot_service_interface_py/xbot_service_interface/interface.py index 15d670c..44cabe1 100644 --- a/xbot_service_interface_py/xbot_service_interface/interface.py +++ b/xbot_service_interface_py/xbot_service_interface/interface.py @@ -463,6 +463,14 @@ def _call_rpc(self, fn: dict, args: tuple, timeout_ms: int): if base not in ('blob', 'string') and not is_array and len(payload) < max_bytes: raise RpcError( 2, f"RPC {fn['name']!r} response too small: got {len(payload)} bytes, need {max_bytes}") + if base not in ('blob', 'string') and is_array: + # An array may come back shorter than declared, but only in whole elements: a partial + # one at the end would be dropped by unpack_value without a word. + element_size = sizeof_type(base, enums) + if len(payload) % element_size: + raise RpcError( + 2, f"RPC {fn['name']!r} response of {len(payload)} bytes is not a whole number " + f"of {element_size} byte elements") return unpack_value(fn['return_type'], payload, enums) # ------------------------------------------------------------------ From 5f23772df98fd8705a084aa2bda6a3c855ba0c45 Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 19:45:45 +0100 Subject: [PATCH 24/28] fix(go): convert enum array elements to and from the base type An enum array (e.g. Mode[720] with a uint16_t base) generated a method that takes and returns []Mode but packed and decoded it with the []uint16 helpers, so the generated client did not compile. A uint8_t based enum array was refused by the generator altogether. The elements are now converted with a generic enumSlice helper, emitted only when a schema uses an enum array. A new test generates enum array parameters, returns, registers and inputs and type-checks the result. --- xbot_service_interface_go/codegen/emit.go | 39 +++++++++-- .../codegen/generate_test.go | 69 +++++++++++++++++++ xbot_service_interface_go/codegen/render.go | 15 ++++ 3 files changed, 119 insertions(+), 4 deletions(-) diff --git a/xbot_service_interface_go/codegen/emit.go b/xbot_service_interface_go/codegen/emit.go index 253d9dd..4f02370 100644 --- a/xbot_service_interface_go/codegen/emit.go +++ b/xbot_service_interface_go/codegen/emit.go @@ -128,6 +128,14 @@ func (g *generator) packExpr(t, expr, where string) (string, error) { case isArray && base == "uint8_t": return fmt.Sprintf("byteParam(%s, %d)", expr, length), nil case isArray: + if eb := g.enumBase(base); eb != "" { + // A []Mode is not a []uint16: convert the elements to the base type first. + g.needs[enumSliceHelper] = true + expr = fmt.Sprintf("enumSlice[%s](%s)", goTypes[eb], expr) + if eb == "uint8_t" { + return fmt.Sprintf("byteParam(%s, %d)", expr, length), nil + } + } kind, err := g.sliceKind(base, where) if err != nil { return "", err @@ -170,16 +178,35 @@ func (g *generator) decodeReturn(t string, maxLen int, fn string) (string, []str case isArray && base == "uint8_t": return "[]byte", []string{"\treturn append([]byte(nil), payload...), nil"}, nil case isArray: - kind, err := g.sliceKind(base, "return value of "+fn) + gt, err := g.goScalar(base, "return value of "+fn) if err != nil { return "", nil, err } - g.needs[kind] = true - gt, err := g.goScalar(base, "return value of "+fn) + _, length, _ := splitType(t) + if eb := g.enumBase(base); eb != "" { + // Decoded as the base type, then converted to the enum type element by element. + g.needs[enumSliceHelper] = true + if eb == "uint8_t" { + return "[]" + gt, []string{fmt.Sprintf("\treturn enumSlice[%s](payload), nil", gt)}, nil + } + kind, err := g.sliceKind(base, "return value of "+fn) + if err != nil { + return "", nil, err + } + g.needs[kind] = true + return "[]" + gt, []string{ + fmt.Sprintf("\tv, err := read%sSlice(payload, %d)", kind, length), + "\tif err != nil {", + "\t\treturn nil, err", + "\t}", + fmt.Sprintf("\treturn enumSlice[%s](v), nil", gt), + }, nil + } + kind, err := g.sliceKind(base, "return value of "+fn) if err != nil { return "", nil, err } - _, length, _ := splitType(t) + g.needs[kind] = true return "[]" + gt, []string{fmt.Sprintf("\treturn read%sSlice(payload, %d)", kind, length)}, nil } goType, err := g.goScalar(base, "return value of "+fn) @@ -240,6 +267,10 @@ var sliceKinds = map[string]string{ "float": "Float32", "double": "Float64", } +// enumSliceHelper is the g.needs key of enumSlice, which converts an enum array to +// and from its base type (a []Mode is not a []uint16 in Go). +const enumSliceHelper = "enumSlice" + // sliceKind returns the array helper for an element type (enums resolve to their // base type). func (g *generator) sliceKind(base, where string) (string, error) { diff --git a/xbot_service_interface_go/codegen/generate_test.go b/xbot_service_interface_go/codegen/generate_test.go index e9a243c..f7a25d8 100644 --- a/xbot_service_interface_go/codegen/generate_test.go +++ b/xbot_service_interface_go/codegen/generate_test.go @@ -3,7 +3,13 @@ package codegen import ( "bytes" "flag" + "go/ast" + "go/importer" + "go/parser" + "go/token" + "go/types" "os" + "path/filepath" "testing" ) @@ -277,6 +283,69 @@ func TestNumericArrays(t *testing.T) { } } +// TestEnumArrays checks that enum arrays compile: the generated methods take and return +// []Mode, while the wire helpers work on the base type, so the elements are converted in +// both directions. A uint8_t based enum goes through the byte helpers instead. +func TestEnumArrays(t *testing.T) { + path := t.TempDir() + "/service.json" + schema := `{"type": "X", "version": 1, + "enums": [{"id": "Mode", "base_type": "uint16_t", "values": {"A": 0}}, + {"id": "Small", "base_type": "uint8_t", "values": {"B": 0}}], + "registers": [{"id": 0, "name": "R", "type": "Small[3]"}], + "inputs": [{"id": 0, "name": "I", "type": "Mode[2]"}], + "functions": [ + {"id": 0, "name": "F", "return_type": "Mode[4]", + "parameters": [{"id": 0, "name": "P", "type": "Mode[720]"}]}, + {"id": 1, "name": "G", "return_type": "Small[4]", + "parameters": [{"id": 0, "name": "Q", "type": "Small[8]"}]}]}` + if err := os.WriteFile(path, []byte(schema), 0o644); err != nil { + t.Fatal(err) + } + s, err := Load(path) + if err != nil { + t.Fatalf("Load: %v", err) + } + src, err := Generate(s, Options{}) + if err != nil { + t.Fatalf("Generate: %v", err) + } + typeCheck(t, src) + for _, want := range []string{ + "func (c *Client) F(ctx context.Context, P []Mode) ([]Mode, error)", + "xbot.Bytes(0, leUint16Slice(enumSlice[uint16](P), 720))", + "v, err := readUint16Slice(payload, 4)", + "return enumSlice[Mode](v), nil", + "func (c *Client) G(ctx context.Context, Q []Small) ([]Small, error)", + "xbot.Bytes(0, byteParam(enumSlice[uint8](Q), 8))", + "return enumSlice[Small](payload), nil", + "Data: byteParam(enumSlice[uint8](R), 3)", + "c.conn.SendData(0, leUint16Slice(enumSlice[uint16](I), 2))", + } { + if !bytes.Contains(src, []byte(want)) { + t.Errorf("generated code does not contain %q", want) + } + } +} + +// typeCheck fails the test if the generated source does not compile. The file is placed +// in this package's directory so the xbot import resolves through this module. +func typeCheck(t *testing.T, src []byte) { + t.Helper() + wd, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, filepath.Join(wd, "client_generated.go"), src, 0) + if err != nil { + t.Fatalf("parse generated code: %v", err) + } + conf := types.Config{Importer: importer.ForCompiler(fset, "source", nil)} + if _, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil); err != nil { + t.Fatalf("generated code does not compile: %v", err) + } +} + // TestStringParameters pins the generated string handling: a string parameter is a Go // string, sent as its UTF-8 bytes without a terminator and refused above max_length; a // string return is decoded into a string and checked against the limit. diff --git a/xbot_service_interface_go/codegen/render.go b/xbot_service_interface_go/codegen/render.go index ad0de13..98eacb0 100644 --- a/xbot_service_interface_go/codegen/render.go +++ b/xbot_service_interface_go/codegen/render.go @@ -492,6 +492,21 @@ var sliceHelperOrder = []string{ // size T[n] is padded to n elements before encoding, and a return value is // decoded from exactly n elements. func (g *generator) emitSliceHelpers() { + if g.needs[enumSliceHelper] { + g.line("// enumSlice converts the elements of an enum array to or from the enum's base type.") + g.line("func enumSlice[To, From enumInteger](v []From) []To {") + g.line("\tout := make([]To, len(v))") + g.line("\tfor i, x := range v {") + g.line("\t\tout[i] = To(x)") + g.line("\t}") + g.line("\treturn out") + g.line("}") + g.line("") + g.line("type enumInteger interface {") + g.line("\t~uint8 | ~uint16 | ~uint32 | ~uint64 | ~int8 | ~int16 | ~int32 | ~int64") + g.line("}") + g.line("") + } for _, kind := range sliceHelperOrder { if !g.needs[kind] { continue From 03b809b3526d5db14e880b183bb2995245a1917b Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 19:45:45 +0100 Subject: [PATCH 25/28] fix(py): do not report a configuration that was not sent send_transaction() returns False when it does not send, e.g. for registers that do not fit into one packet. The configuration request handler ignored that and fired on_configured anyway. It now logs the failure and leaves the service unconfigured. --- .../tests/test_interface.py | 16 +++++++++++++++- .../xbot_service_interface/interface.py | 16 +++++++++++----- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/xbot_service_interface_py/tests/test_interface.py b/xbot_service_interface_py/tests/test_interface.py index b4ee80a..2241111 100644 --- a/xbot_service_interface_py/tests/test_interface.py +++ b/xbot_service_interface_py/tests/test_interface.py @@ -291,12 +291,26 @@ def test_on_configured_fires_after_config_sent(self): si._register_values['Prefix'] = 'hi' si._register_values['EchoCount'] = 1 call_order = [] - si._io.send_transaction.side_effect = lambda *a, **kw: call_order.append('send') + si._io.send_transaction.side_effect = lambda *a, **kw: call_order.append('send') or True si.on_configured(lambda: call_order.append('cb')) si._on_config_request() si._join_callbacks() assert call_order == ['send', 'cb'] + def test_on_configured_suppressed_when_config_not_sent(self): + # send_transaction refuses e.g. registers that do not fit into one packet: the service + # is not configured then, so on_configured must not report that it is. + si = make_si(connected=True) + si._register_values['Prefix'] = 'hi' + si._register_values['EchoCount'] = 1 + si._io.send_transaction.return_value = False + cb = MagicMock() + si.on_configured(cb) + si._on_config_request() + si._join_callbacks() + si._io.send_transaction.assert_called_once() + cb.assert_not_called() + def test_on_configured_suppressed_on_serialize_error(self): si = make_si(connected=True) si._register_values['EchoCount'] = 'not-an-int' # will fail pack_value diff --git a/xbot_service_interface_py/xbot_service_interface/interface.py b/xbot_service_interface_py/xbot_service_interface/interface.py index 44cabe1..deb3afd 100644 --- a/xbot_service_interface_py/xbot_service_interface/interface.py +++ b/xbot_service_interface_py/xbot_service_interface/interface.py @@ -587,11 +587,17 @@ def _on_config_request(self) -> None: send_ok = False if not serialize_failed: if chunks and self._io is not None: - self._io.send_transaction(self._service_id, chunks, is_config=True) - log.info( - f"Sent configuration for service {self._service_id} " - f"({len(chunks)} registers)") - send_ok = True + # False when it was not sent, e.g. registers that do not fit into one packet: + # then the service is not configured and on_configured must not fire. + if self._io.send_transaction(self._service_id, chunks, is_config=True): + log.info( + f"Sent configuration for service {self._service_id} " + f"({len(chunks)} registers)") + send_ok = True + else: + log.error( + f"Configuration for service {self._service_id} " + f"({len(chunks)} registers) was not sent") elif not chunks: log.debug(f"No registers to send for service {self._service_id}") send_ok = True From 8b247869ff137c99144651e871b0e0ca3ba690ff Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 19:45:45 +0100 Subject: [PATCH 26/28] test(interface): never wait for an answer thread while SendRpc holds its lock The fake IO joined the previous answer thread inside SendData, which runs under rpc_mutex_. An answer thread still blocked on that lock (its call timed out first) would never finish and the test would hang. The threads are now collected and joined at the end, while the interface still exists. --- .../test/InterfaceCodegenTests.cpp | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/libxbot-service-interface/test/InterfaceCodegenTests.cpp b/libxbot-service-interface/test/InterfaceCodegenTests.cpp index eb3c675..1df2e21 100644 --- a/libxbot-service-interface/test/InterfaceCodegenTests.cpp +++ b/libxbot-service-interface/test/InterfaceCodegenTests.cpp @@ -61,13 +61,15 @@ class FakeDiscovery final : public xbot::serviceif::ServiceDiscovery { }; // Stands in for the network: answers every RPC call with `status` and an empty payload. The answer -// comes from another thread, like the real receive path (SendRpc holds its lock while it sends). +// comes from another thread, like the real receive path. SendRpc holds its lock while it sends, so +// SendData must never wait for an earlier answer thread: one that is still blocked on that lock +// would never finish. The threads are joined in JoinAll() instead, while the interface still lives. class FakeIO final : public xbot::serviceif::ServiceIO { public: RpcStatus status = RpcStatus::SUCCESS; ~FakeIO() { - Join(); + JoinAll(); } void RegisterCallbacks(uint16_t, xbot::serviceif::ServiceIOCallbacks *callbacks) override { callbacks_ = callbacks; @@ -78,23 +80,28 @@ class FakeIO final : public xbot::serviceif::ServiceIO { bool SendData(uint16_t service_id, const std::vector &data) override { XbotHeader header{}; memcpy(&header, data.data(), sizeof(header)); - Join(); - reply_ = std::thread([this, service_id, call_id = static_cast(header.arg2), reply_status = status] { - callbacks_->OnRpcResponse(service_id, call_id, static_cast(reply_status), nullptr, 0); - }); + replies_.emplace_back( + [callbacks = callbacks_, service_id, call_id = static_cast(header.arg2), reply_status = status] { + callbacks->OnRpcResponse(service_id, call_id, static_cast(reply_status), nullptr, 0); + }); return true; } bool OK() override { return true; } - private: - void Join() { - if (reply_.joinable()) reply_.join(); + // Waits for every answer thread. An answer to a call that timed out still calls into the + // interface, so this has to run before the interface is destroyed. + void JoinAll() { + for (auto &reply : replies_) { + if (reply.joinable()) reply.join(); + } + replies_.clear(); } + private: xbot::serviceif::ServiceIOCallbacks *callbacks_ = nullptr; - std::thread reply_; + std::vector replies_; }; int failures = 0; @@ -143,5 +150,6 @@ int main() { Expect(!iface.CallScalarParamsWithReturn(1.0f, 2, 3, value), "an empty answer to a scalar return is refused"); Expect(iface.GetLastRpcResult() == ServiceInterfaceBase::RPC_ERROR, "an empty answer to a scalar return is RPC_ERROR"); + io.JoinAll(); return failures == 0 ? 0 : 1; } From ee68aebffcfc60ce4a9715d783ba787c5a375a7a Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 19:45:45 +0100 Subject: [PATCH 27/28] docs: a timed out RPC has an unknown outcome RPC_TIMEOUT does not mean the call cannot be repeated: the service may or may not have run it, so a retry is safe only for a call that may run twice. --- Readme.md | 12 ++++++++---- .../xbot-service-interface/ServiceInterfaceBase.hpp | 8 +++++--- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/Readme.md b/Readme.md index df2c343..f4d4a7b 100644 --- a/Readme.md +++ b/Readme.md @@ -324,10 +324,14 @@ Moving a `blob` text parameter to `string` keeps the wire layout, so it needs no - A call, an input or a transaction that does not fit into one packet is refused before it is sent (`Call{Name}()`/`Send{Name}()` return `false` in C++, an error in Go, `ValueError` in Python). The services drop an oversized datagram without an answer, which would look like a timeout or a lost value. -- The C++ `Call{Name}()` methods return `bool`. `GetLastRpcResult()` tells the reasons apart: `RPC_BUSY` - means the service refused the call for now (another call in progress, or no free block in its buffer - pool) and the call can be repeated, `RPC_TIMEOUT` and `RPC_ERROR` mean it cannot. A call the method - refuses itself (an argument over its limit, an answer of the wrong size) is `RPC_ERROR` as well. +- The C++ `Call{Name}()` methods return `bool`. `GetLastRpcResult()` tells the reasons apart: + - `RPC_BUSY`: the service refused the call for now (another call in progress, or no free block in its + buffer pool). It did not run the call, so the call can be sent again. + - `RPC_TIMEOUT`: no answer came. The outcome is unknown: the request may have been lost, or the service + ran the call and the answer was lost. Sending it again is only safe for a call that does no harm + when it runs twice. + - `RPC_ERROR`: everything else, such as a service that is not discovered (yet), an error answer, or a + call the method refuses itself (an argument over its limit, an answer of the wrong size). **CMake integration:** ```cmake diff --git a/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp b/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp index d033af7..cb62595 100644 --- a/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp +++ b/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp @@ -35,9 +35,11 @@ class ServiceInterfaceBase : public xbot::serviceif::ServiceIOCallbacks, /** * Result of the most recent RPC of this interface. The generated Call...() methods only return - * true or false; this tells a failed call that is worth repeating (RPC_BUSY) from one that is not. - * A call that Call...() refuses on its own, before sending it (an argument over its limit) or - * after the answer (a response of the wrong size), is RPC_ERROR. + * true or false; this tells the reasons apart. RPC_BUSY: the service did not run the call and it + * can be sent again. RPC_TIMEOUT: no answer, the outcome is unknown (the service may have run the + * call), so sending it again is only safe for a call that may run twice. RPC_ERROR: anything else, + * including a call that Call...() refuses on its own, before sending it (an argument over its + * limit) or after the answer (a response of the wrong size). * * It is one value per interface: with several threads calling at the same time it may already * belong to another thread's call. From c979c0f5959276db00d9d5608d14870e704e1283 Mon Sep 17 00:00:00 2001 From: Clemens Elflein Date: Wed, 18 Nov 2026 19:45:45 +0100 Subject: [PATCH 28/28] build: let the CI build preset use the CI configure preset It pointed at the Release configure preset, so cmake --build --preset CI built build/Release without the tests. --- CMakePresets.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakePresets.json b/CMakePresets.json index 4f2eabe..fb15df1 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -1,7 +1,7 @@ { "buildPresets": [ { - "configurePreset": "Release", + "configurePreset": "CI", "name": "CI" }, {