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..fb15df1 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -1,7 +1,7 @@ { "buildPresets": [ { - "configurePreset": "Release", + "configurePreset": "CI", "name": "CI" }, { @@ -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/Readme.md b/Readme.md index 7413e42..f4d4a7b 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 @@ -245,20 +245,93 @@ 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, 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 +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. 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. 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. 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. + +```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, 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`). **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 + `const uint8_t* , uint32_t Len` and is only valid until the handler returns + (copy it if you need it longer) +- 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. +- 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. 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`: 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 @@ -275,6 +348,86 @@ 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); +``` + +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 + 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 + another service's transfer. With the default of two blocks, one outstanding return does not exhaust + 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 +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. 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 +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. + +--- + ## Python Interface `xbot_service_interface_py` is a pure-Python client for xBot services — no codegen step required. It talks directly diff --git a/codegen/templates/ServiceInterfaceTemplate.cpp b/codegen/templates/ServiceInterfaceTemplate.cpp index 44add45..44799af 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 @@ -119,11 +131,19 @@ 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_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_array']: + 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": sig_params.append(f"{func['return_type']}& result") @@ -131,18 +151,33 @@ 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"]: - if 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 = {p['name']}Len * sizeof({p['type']});") + 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 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 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: @@ -158,7 +193,21 @@ 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_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 FailRpc();") + 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);") cog.outl(f" if (r != RPC_OK) return false;") @@ -168,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;") @@ -211,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; } @@ -223,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; @@ -239,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); } { @@ -253,8 +302,64 @@ 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; } +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 FailRpc(); + 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; +} +bool ServiceTemplateInterfaceBase::CallStringParamsWithStringReturn(const char* Path, std::string& result, uint32_t timeout_ms) { + std::vector params_buf; + { + if (Path == nullptr) return FailRpc(); + const size_t byte_len = strlen(Path); + 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 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 FailRpc(); + 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 FailRpc(); + 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 eff31bf..0f9fff5 100644 --- a/codegen/templates/ServiceInterfaceTemplate.hpp +++ b/codegen/templates/ServiceInterfaceTemplate.hpp @@ -18,6 +18,10 @@ cog.outl(f"#define {service['interface_class_name'].upper()}_HPP") #include #include +#include + +#include +#include /*[[[cog xbot_codegen.generateEnums(service) @@ -52,13 +56,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 @@ -66,11 +73,19 @@ 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_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_array']: + 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": params.append(f"{func['return_type']}& result") @@ -82,6 +97,61 @@ 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); + 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 + # 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. Every + # subtraction saturates, so a call whose parameters use up the whole packet reports 0 + # instead of a wrapped (huge) budget. + # 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"])] + for func in blob_funcs: + 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'] 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) + # 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{limit}.") + cog.outl(f" static constexpr size_t {name}({args}) {{") + cog.outl(f" return {budget};") + cog.outl(" }") + ]]]*/ + // 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, and never more than the 64 bytes the schema accepts. + static constexpr size_t MaxStringParamsWithStringReturnPath() { + return std::min(64, RemainingBudget(xbot::config::max_packet_size, sizeof(xbot::datatypes::XbotHeader) + 1 * sizeof(xbot::datatypes::DataDescriptor))); + } //[[[end]]] /*[[[cog @@ -104,7 +174,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;") @@ -117,6 +192,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: @@ -140,6 +219,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": [ @@ -152,6 +236,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": [ @@ -234,6 +323,45 @@ 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]" + }, + { + "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 e17fec4..94f11c2 100644 --- a/codegen/templates/ServiceTemplate.cpp +++ b/codegen/templates/ServiceTemplate.cpp @@ -3,14 +3,18 @@ /*[[[cog import cog -from xbot_codegen import toCamelCase, loadService +from xbot_codegen import (DESCRIPTOR_SIZE, HEADER_SIZE, MAX_PACKET_SIZE, loadService, needsBufferPool, + pooledReturnBytes, pooledReturnBytesExpr, 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 @@ -22,9 +26,23 @@ cog.outl(f'#include "{service["class_name"]}.hpp"') /*[[[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]]] @@ -47,7 +65,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;"); @@ -77,6 +98,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]]] } } @@ -189,7 +213,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("}") @@ -204,6 +232,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 @@ -350,55 +381,121 @@ 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_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. + # 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']}] = {{}};") cog.outl(f" uint32_t param_{p['name']}Len = 0;") else: 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;") - 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);") - 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']}:") - if p['is_array']: + 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" 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" 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(" }") # 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'] or p['is_string']: 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. 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 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(" }") + # 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 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']: 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 +503,10 @@ 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_ = kRpcReturnBytes;") + 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: @@ -433,35 +534,41 @@ 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); - 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 (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; } @@ -474,25 +581,27 @@ 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); - 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 (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; } @@ -506,31 +615,35 @@ 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); - 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 (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; } @@ -538,6 +651,113 @@ 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; + bool param_Data_seen = false; + 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 (param_Data_seen) { parse_ok = false; break; } + param_Data = buf + offset; + param_DataLen = desc->payload_size; + param_Data_seen = true; + break; + default: break; + } + offset += desc->payload_size; + } + if (!parse_ok || !(param_Data_seen)) { + SendRpcResponse(call_id, xbot::datatypes::RpcStatus::ERROR, nullptr, 0); + return; + } + 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; + } + 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: { + 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(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); + RPCLargeArrayReturn(call_id, rpc_ret_buf, &rpc_ret_len); + return; + } + case 6: { + char param_Path[64 + 1]; + param_Path[0] = '\0'; + uint32_t param_PathLen = 0; + size_t offset = 0; + bool parse_ok = true; + bool param_Path_seen = false; + 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 (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; + param_Path_seen = true; + } else { parse_ok = false; } + break; + default: break; + } + offset += desc->payload_size; + } + if (!parse_ok || !(param_Path_seen)) { + 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: { + 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(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; + 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 bf910ba..4a270f2 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,92 +105,154 @@ 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, - 0x84, 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, 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, + 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, 0x65, 0x65, 0x6E, 0x75, 0x6D, 0x73, 0x82, + 0x65, 0x6C, 0x75, 0x69, 0x6E, 0x74, 0x38, 0x5F, + 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[] = { + 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, @@ -212,6 +274,12 @@ class ServiceTemplateBase : public xbot::service::Service { 0x01, 0x66, 0x56, 0x41, 0x4C, 0x55, 0x45, 0x33, 0x02 }; + static constexpr size_t SERVICE_OMITTED_CBOR_SIZE = 161; + + const unsigned char* GetOmittedDescription(size_t& size) override { + size = SERVICE_OMITTED_CBOR_SIZE; + return SERVICE_OMITTED_CBOR; + } //[[[end]]] private: @@ -239,7 +307,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;") @@ -257,17 +329,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 @@ -315,17 +395,35 @@ 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(). - # 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)). + # 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, 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"]: - if p['is_array']: + 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_array']: + 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) cog.outl(f"virtual void RPC{func['name']}({params_str}) = 0;") @@ -334,6 +432,10 @@ 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; + 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]]] }; @@ -354,6 +456,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": [ @@ -366,6 +473,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": [ @@ -448,6 +560,45 @@ 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]" + }, + { + "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 8014f8b..86396ad 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": [ @@ -81,6 +91,41 @@ { "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]" + }, + { + "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 179e143..9d09538 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: @@ -71,6 +73,111 @@ 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, +} + +# 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 +# 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. 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 +# 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.""" + 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_string"]: + # 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"]: + 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 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"]) + + def common_attrs(json, valid_types, callback_name, send_method_name): id = int(json['id']) name = toCamelCase(json['name']) @@ -81,6 +188,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) @@ -91,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. @@ -183,7 +291,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']}' " @@ -194,7 +302,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']}' " @@ -218,18 +326,37 @@ 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 + 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: + 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_max_length is not None: + 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_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}' " f"return type '{return_type_str}': must be 1..{MAX_ARRAY_LENGTH}") - return_is_array = return_max_length is not None + # 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) and not return_is_string check_unique_ids(json_func.get("parameters", [])) params = [] @@ -243,21 +370,48 @@ 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", "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, - **array_type_attrs(param_max_length), + "is_blob": param_type == "blob", + "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) ), }) + # 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, "return_type": return_type_str, "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, }) @@ -284,6 +438,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/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/include/xbot/config.hpp b/include/xbot/config.hpp index ef8d5ac..357f401 100644 --- a/include/xbot/config.hpp +++ b/include/xbot/config.hpp @@ -69,6 +69,44 @@ 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. + * + * 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 +#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 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; + namespace service { static constexpr uint32_t io_thread_stack_size = 5000; } 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/include/xbot-service-interface/ServiceInterfaceBase.hpp b/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp index 4154e47..cb62595 100644 --- a/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp +++ b/libxbot-service-interface/include/xbot-service-interface/ServiceInterfaceBase.hpp @@ -28,8 +28,26 @@ 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 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. + */ + RPC_RESULT GetLastRpcResult() const { + return last_rpc_result_; + } + protected: const uint16_t service_id_; // Type of the service (e.g. IMU Service) @@ -54,6 +72,28 @@ 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 + * 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 +106,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/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-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); diff --git a/libxbot-service-interface/test/CMakeLists.txt b/libxbot-service-interface/test/CMakeLists.txt new file mode 100644 index 0000000..a24df5c --- /dev/null +++ b/libxbot-service-interface/test/CMakeLists.txt @@ -0,0 +1,15 @@ +# 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) + +find_package(Threads REQUIRED) + +add_executable(InterfaceCodegenTests InterfaceCodegenTests.cpp) +target_compile_options(InterfaceCodegenTests PRIVATE -Wall -Wextra -Werror) +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 new file mode 100644 index 0000000..1df2e21 --- /dev/null +++ b/libxbot-service-interface/test/InterfaceCodegenTests.cpp @@ -0,0 +1,155 @@ +// +// Checks on the interface generated from codegen/templates/service.json. +// +// 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; +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); + +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, 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() { + JoinAll(); + } + 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)); + 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; + } + + // 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::vector replies_; +}; + +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() { + // 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"); + + io.JoinAll(); + return failures == 0 ? 0 : 1; +} diff --git a/libxbot-service/CMakeLists.txt b/libxbot-service/CMakeLists.txt index ed204c4..e785542 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) @@ -32,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/ @@ -41,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/include/xbot-service/Buffer.hpp b/libxbot-service/include/xbot-service/Buffer.hpp new file mode 100644 index 0000000..9195f3f --- /dev/null +++ b/libxbot-service/include/xbot-service/Buffer.hpp @@ -0,0 +1,127 @@ +// +// Shared buffer pool for RPC payloads. +// + +#ifndef XBOT_BUFFER_HPP +#define XBOT_BUFFER_HPP + +#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; + +/** @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. + * + * 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: + 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, 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; the pool then stays as it was + */ +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. + * + * 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 pool has no storage yet, 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..4f21b37 --- /dev/null +++ b/libxbot-service/src/Buffer.cpp @@ -0,0 +1,184 @@ +// +// Shared buffer pool for RPC payloads. +// + +#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 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, + "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 +// 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}; + +// 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; +} + +} // 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 ((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 + } + 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_.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_.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_)); + } + 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/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; diff --git a/libxbot-service/test/BufferTests/BufferTests.cpp b/libxbot-service/test/BufferTests/BufferTests.cpp new file mode 100644 index 0000000..ac846ff --- /dev/null +++ b/libxbot-service/test/BufferTests/BufferTests.cpp @@ -0,0 +1,159 @@ +// +// Tests for the shared RPC buffer pool. +// + +#include +#include +#include + +#include "CppUTest/TestHarness.h" + +using namespace xbot::service; + +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; + +// 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) { + 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 storage + 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); + 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..50ee529 100644 --- a/libxbot-service/test/CMakeLists.txt +++ b/libxbot-service/test/CMakeLists.txt @@ -1,26 +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 - ${PROJECT_SOURCE_DIR}/src/portable/linux/queue.cpp + BufferTests/BufferTests.cpp + DispatcherTests/DispatcherTests.cpp + ServiceTests/ServiceTests.cpp ) -target_include_directories(AllTests - PRIVATE - . - ${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 + 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 225b300..c0350ac 100644 --- a/libxbot-service/test/all_tests.cpp +++ b/libxbot-service/test/all_tests.cpp @@ -3,7 +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); diff --git a/xbot_service_interface_go/codegen/emit.go b/xbot_service_interface_go/codegen/emit.go index 319fe7a..4f02370 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": @@ -112,7 +116,8 @@ 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 { @@ -123,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 @@ -143,26 +156,57 @@ 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 case base == "char" && isArray: return "string", []string{"\treturn charValue(payload), nil"}, nil 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) @@ -223,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 c9d98e3..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" ) @@ -57,7 +63,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}}]}`, @@ -69,6 +75,41 @@ 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"}]}]}`, + "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]"}]}]}`, + // 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": [ @@ -88,6 +129,131 @@ 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"}, + {"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) + } + 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, 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. + // 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 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) + } + } + // 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) + } + } +} + +// 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" + 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) + } +} + +// 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) { @@ -116,3 +282,103 @@ 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. +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.String(0, Path)", + "if len(payload) > 96 {", + "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 fa6217c..98eacb0 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 @@ -175,6 +176,104 @@ 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 +// 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 { + // 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 + } + if size, err := g.paramBytes(p); err == nil { + fixed += size + } // an unsupported type is reported by emitFunction already + } + if len(blobs) == 0 { + 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 + var variable strings.Builder + for _, other := range blobs { + if other.Name == target.Name { + continue + } + otherName := goName(other.Name) + otherType := "[]byte" + if base, _, _ := splitType(other.Type); base == "string" { + otherType = "string" + } + args = append(args, otherName+" "+otherType) + variable.WriteString(" - len(" + otherName + ")") + } + + budget := fmt.Sprintf("%d*xbot.DescriptorSize", len(fn.Parameters)) + if fixed > 0 { + budget += fmt.Sprintf(" - %d", fixed) + } + + 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, ", ")) + 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("") + } + } } // emitFunction writes one RPC method. @@ -190,17 +289,26 @@ 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}) } - 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 } @@ -236,6 +344,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) @@ -378,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 diff --git a/xbot_service_interface_go/codegen/schema.go b/xbot_service_interface_go/codegen/schema.go index c70f2ad..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. @@ -45,9 +47,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 +60,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 +73,18 @@ var rawTypes = []string{ // maxArrayLength is the limit the framework applies to array returns. const maxArrayLength = 1024 +// 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 = 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+)\]$`) // Load reads and validates a service.json. @@ -91,18 +109,87 @@ 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 { + 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 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 { return err @@ -132,16 +219,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) } @@ -155,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 5cf1af3..4420ecb 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.String(0, Path), + ) + } + payload, err := c.conn.Call(ctx, FnStringParamsWithStringReturn, + xbot.String(0, 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 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 min(64, 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..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 @@ -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.String(0, Path), + ) + } + payload, err := c.conn.Call(ctx, FnStringParamsWithStringReturn, + xbot.String(0, 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 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 min(64, 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 c0545fe..28b1245 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" && base != "string" { + 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 { 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_interface.py b/xbot_service_interface_py/tests/test_interface.py index 138ca3c..2241111 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 f89f10b..deb3afd 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 +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 @@ -372,8 +389,26 @@ 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 + # reporting anything, which would surface as a timeout - so fail here instead. + 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_PAYLOAD_SIZE})") + with self._rpc_lock: with self._rpc_condition: counter = (self._rpc_call_counter + 1) & 0xFFFF @@ -410,14 +445,32 @@ def _call_rpc(self, fn: dict, args: tuple, timeout_ms: int): if fn['return_type'] == 'void': return None - _, is_array, _ = parse_type_string(fn['return_type']) - max_bytes = sizeof_type(fn['return_type']) + base, is_array, _ = parse_type_string(fn['return_type']) + if base == 'blob': + # Variable length return, bounded by one packet only. + 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: + # 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}") - if 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}") + 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) # ------------------------------------------------------------------ @@ -534,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 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/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 diff --git a/xbot_service_interface_py/xbot_service_interface/serialization.py b/xbot_service_interface_py/xbot_service_interface/serialization.py index 00ac8b8..ece6a89 100644 --- a/xbot_service_interface_py/xbot_service_interface/serialization.py +++ b/xbot_service_interface_py/xbot_service_interface/serialization.py @@ -46,10 +46,14 @@ 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 base == 'blob': - raise ValueError("blob has no fixed size") + 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") if base not in _FORMATS: raise ValueError(f"Unknown type: {base!r}") _, elem_size = _FORMATS[base] @@ -74,6 +78,16 @@ 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') + 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: raw = value.encode('utf-8', errors='replace') if isinstance(value, str) else bytes(value) @@ -105,6 +119,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')