Skip to content

Latest commit

 

History

History
290 lines (220 loc) · 12.4 KB

embedded.md

File metadata and controls

290 lines (220 loc) · 12.4 KB

ycpp on small targets

ycpp is meant to run on microcontrollers as well as desktops. This page says what that means for you: what the library does not use, where its memory comes from, what you can compile out, how to use it from threads, how it handles hostile input, and how to measure its flash size.

The design targets Cortex-M7 and ESP32-class chips. The repository checks a Cortex-M7 build (see Flash size).

What the library does not use

Not used What you get instead
Exceptions Every call that can fail returns std::expected<T, ycpp::Error>. The library is built with -fno-exceptions (except on MSVC, see below).
RTTI No dynamic_cast, no typeid. Your build can pass -fno-rtti.
Threads No threads, no locks, no timers. You call it; it returns.
iostreams Nothing pulls in <iostream>.

Two exceptions to the rules above:

  • MSVC keeps exceptions on. Turning them off there breaks parts of its standard library. ycpp still never throws, so the behaviour is the same.
  • Out of memory aborts. An allocation failure is not reported as an Error. With exceptions off, a failed allocation ends the program. There is no rollback. If that is not acceptable, size your memory resource so it cannot run out, and check how much a document needs with a counting resource (see below).

Errors

ycpp::Error is a small enum (<ycpp/error.hpp>):

Error Meaning
truncated Input bytes end too early.
malformed Input bytes break the format.
unsupported The call cannot be done, e.g. on a handle whose document is gone.
too_deep A value is nested deeper than max_any_depth.
clock_exhausted The local client's 32-bit clock space is full.

The examples in these pages cast some results to (void) to stay short. In real code, check every result that depends on outside input.

Memory

Every container inside ycpp takes a std::pmr::memory_resource*. The default is std::pmr::new_delete_resource(), which is plain new and delete. You pass your own as the third argument of the Doc constructor:

explicit Doc(std::uint64_t client_id, bool gc = true,
             std::pmr::memory_resource* memory = std::pmr::new_delete_resource());

Where the memory comes from

Giving the document a pool

This example gives a document a fixed 64 KB block. A pool on top of it reuses freed memory.

#include <ycpp/doc.hpp>
#include <ycpp/encoding.hpp>
#include <ycpp/map.hpp>

#include <cstddef>
#include <memory_resource>

alignas(std::max_align_t) static std::byte block[64 * 1024];

void run() {
  // The block, and nothing after it: when it is full, the next allocation fails (and aborts).
  std::pmr::monotonic_buffer_resource arena(block, sizeof(block), std::pmr::null_memory_resource());
  // Reuses what the document frees, so edits do not eat the block.
  std::pmr::unsynchronized_pool_resource pool(&arena);

  {
    ycpp::Doc doc(/*client_id=*/1, /*gc=*/true, &pool);
    (void)doc.map("settings").set("gain", ycpp::Any{0.5});

    // Encoders and decoders take a resource too. doc.memory() is the one the Doc was given.
    ycpp::Encoder encoder(doc.memory());
    doc.encode_state_as_update(encoder);
    // send encoder.bytes() ...
  }  // the document dies before the pool and the arena
}

Rules:

  1. The resource must outlive the document, and everything made from it: snapshots, encoders, decoded values.
  2. An unsynchronized resource is single-threaded. Do not share unsynchronized_pool_resource between documents used on different threads. Use synchronized_pool_resource, or one resource per thread.
  3. A monotonic resource never frees. Alone, it grows with every edit. Put a pool on top of it, as above, or use it only for short-lived work.

What still uses the global heap

Most of the document's memory comes from your resource: the struct store, the key pool, the item lists, the delete set, pending structs, transaction bookkeeping and event payloads. A few things do not:

  • Returned values. Functions that return a std::vector<byte> or a std::string use the global heap: Doc::encode_state_as_update(), Doc::to_json(), merge_updates() and the like. Where it matters, use the overloads that write into your Encoder, such as Doc::encode_state_as_update(Encoder&, state_vector).
  • A few small fixed objects. Each shared type (each root, and each nested map, array or text) has a small header from the global heap. So does the block that tracks whether the document is still alive.

So a board still needs a working operator new. scripts/size_check.sh shows a minimal one over malloc that aborts on failure.

Measuring

To see what a document costs, give it a resource that counts. tests/test_array.cpp has a CountingResource that records the total and the peak. Run your real workload through it on a desktop, then size the board's pool from the peak.

Compiling parts out

Each shared type sits behind a Meson feature option. A board that only needs maps can switch the rest off and save flash.

The layers you can compile out

A build without a type is still a correct peer. It stores the items of that type, merges them, and passes them on unchanged. It just has no API to read or write them. So a map-only sensor node can sit in a network where browsers edit text.

The options

From meson.options:

Option Default What it controls
array enabled The array type (ArrayRef).
text enabled The text type (TextRef), with formatting.
xml auto The XML types. Needs text and array; auto follows them.
subdoc enabled Subdocuments.
undo enabled The undo manager.
observe_deep enabled Deep observers, with Yjs event paths.
max_any_depth 32 The deepest nested value a decoder accepts.
simd none Vectorised UTF-8 checks (sse4.2, avx2, native). Keep none on a board.
v2 disabled Declared, but the v2 update code is compiled in every build today; the option has no effect yet.
fuzz false Build the libFuzzer target (needs clang).
benchmarks, bench_yrs, utf8_check off Development tools.
python disabled The Python binding.

Relative positions are built when text or array is on. They have no option of their own.

The core is always built: encoding, Any, the store, integration, delete sets, garbage collection, pending updates, Doc, Map, v1 and v2 updates, snapshots, the sync protocol and awareness. The store-side cleanup of text formatting is also always built, because Yjs runs it on every transaction.

Using the options from your project

As a Meson subproject:

ycpp = subproject('ycpp', default_options: [
  'text=disabled',
  'array=disabled',
  'subdoc=disabled',
  'undo=disabled',
  'observe_deep=disabled',
  'max_any_depth=8',
])
ycpp_dep = ycpp.get_variable('ycpp_dep')

A subproject build skips ycpp's tests, fuzzer and benchmarks. The library is static by default.

The configuration reaches your code through the generated header <ycpp/config.hpp>. It defines YCPP_FEATURE_TEXT, YCPP_FEATURE_ARRAY, YCPP_FEATURE_XML, YCPP_FEATURE_SUBDOC, YCPP_FEATURE_UNDO and YCPP_FEATURE_DEEP_OBSERVE as 0 or 1. Guard calls to a type that may be off; with the type off, calls to its API fail to link.

#include <ycpp/config.hpp>
#if YCPP_FEATURE_TEXT
#include <ycpp/text.hpp>
#endif

max_any_depth travels as the compile flag -DYCPP_MAX_ANY_DEPTH. The ycpp_dep dependency passes it on to your code, so the library and your code agree on the value.

Threads

ycpp has no locks. The rules for you:

  1. One document, one thread at a time. A Doc and everything tied to it must not be used from two threads at once. That covers its MapRef, TextRef and other handles, its Connections, an Awareness and an UndoManager.
  2. Different documents are independent. Two documents on two threads do not share any mutable state. (The undo manager's id counter is the one process-wide value, and it is atomic.)
  3. Callbacks run inside your call. Observers and on_update handlers run on your thread, before the call that triggered them returns. A callback may write to the same document; that write becomes a transaction of its own, run after the current one.
  4. Memory resources follow the same rule. A resource shared between threads must be a thread-safe one.

If several threads need one document, pick one of these:

  • Give the document to one thread, and send it work through a queue. Updates are plain bytes, so they cross threads easily.
  • Wrap every call in your own mutex. The Python binding does this, one lock per document.

Untrusted input

ycpp treats every byte string from outside as hostile. That covers updates (v1 and v2), state vectors, sync and awareness messages, snapshots and relative positions.

The guarantees:

  • No crash and no partial apply. Malformed input returns an Error. An update is checked in a first pass before any struct is integrated, so a bad update changes nothing. See Malformed input.
  • Bounded nesting. Values nest up to max_any_depth levels (default 32). Deeper input is refused, so a hostile update cannot exhaust the stack through recursion. A local write of a value that deep is refused too (Error::too_deep), because peers would refuse it.
  • No trust in wire counts. A length or count read from the wire is checked against the bytes that are really left. No buffer is reserved from a wire count alone. A 20-byte update cannot ask for gigabytes.
  • Linear work. Decoding and applying cost grows in proportion to the input, never quadratically. Tests check this for the cases that used to be quadratic: clients in descending order, many delete-set clients, large pending sets, v2 struct counts.
  • Clocks stay in range. Clocks are 32-bit on the wire. A larger value is malformed. A peer that fills the local client's clock space makes local writes fail with clock_exhausted instead of aborting.
  • UTF-8 is validated. Strings that are not valid UTF-8 are malformed.

The fuzzer

tests/fuzz_apply_update.cpp is a libFuzzer target. Each input goes through:

  • apply_update and apply_update_v2, with a round trip of the result;
  • the sync handlers (handle_message, handle_sync_message);
  • Awareness::apply_update;
  • snapshot and relative position decoders;
  • local text edits on whatever document the input built.

Build and run it with clang:

CXX=clang++ meson setup builddir-fuzz -Dfuzz=true
ninja -C builddir-fuzz
builddir-fuzz/fuzz_apply_update -max_total_time=300 tests/fuzz_corpus

tests/fuzz_corpus holds seed inputs. tests/fuzz_crashers keeps an input that once crashed the library; a regular test in tests/test_update.cpp replays it.

Flash size

scripts/size_check.sh measures what ycpp costs on a Cortex-M7.

scripts/size_check.sh          # fails above 100 KB of code
scripts/size_check.sh 80       # a tighter limit, in KB

What it does:

  1. It writes a map-only config.hpp: text, array, XML, subdocuments, undo and deep observers off.
  2. It compiles a small program that sets three map keys, encodes the document and prints JSON.
  3. It builds with -Os, -fno-exceptions, -fno-rtti, section garbage collection, and max_any_depth=8.
  4. It links, and prints the total code size and ycpp's own share (code and read-only data).
  5. It fails if the code is above the limit.
  6. It then checks that every source still compiles for the board with every feature on.

It needs arm-none-eabi-g++ and arm-none-eabi-size. On Fedora: dnf install arm-none-eabi-gcc-cs arm-none-eabi-binutils-cs. It also needs the wrapped dependencies downloaded (meson subprojects download).

Two tricks in that program are worth copying for a real board:

  • It replaces operator new and operator delete with thin wrappers over malloc and free that abort on failure. That keeps the exception machinery of the standard operator new out of the image.
  • It stubs __cxa_demangle, which the default terminate handler pulls in for about 32 KB.

The two dependencies, dragonbox and fast_float, replace the standard library's floating-point formatting and parsing. That alone saves about 200 KB on Cortex-M compared with libstdc++'s <charconv>.