← Все новости

В systemd влили поддержку программ на Rust — без cargo и без стандартной библиотекиsystemd merges support for programs written in Rust — no cargo, no standard library

Pull request Кристиана Браунера разрешает писать на Rust новые «листовые» компоненты systemd, не переписывая существующий C-код. Сборка остаётся на meson, код — no_std, поддержка Rust опциональна. Первой Rust-программой станет systemd-keyring-setup.Christian Brauner's pull request allows new leaf components of systemd to be written in Rust without porting existing C code. The build stays on meson, the code is no_std, and Rust support is optional. The first Rust program will be systemd-keyring-setup.

24 октября в основную ветку systemd влит PR #44324 «rust: support programs written in Rust» от Кристиана Браунера. Он заменяет более раннюю попытку и следует правилам, о которых мейнтейнеры договорились на хакфесте в Берлине.

Правила игры

  • Rust — только для новых листовых компонентов. Существующий C-код не портируется, и ничего, от чего зависят другие части systemd, на Rust не пишется.
  • Без cargo: всё собирает meson.
  • Только крейты core, alloc и libc, код — no_std. Как и в ядре Linux, у systemd_shared свои Box и Vec: любая аллокация возвращает ошибку, глобального аллокатора нет.
  • Только C-линковка: Rust-программа динамически линкуется с libsystemd-shared, как и C-программы, а Rust-крейты линкуются в неё статически.

В итоге стандартная библиотека Rust в бинарники не попадает. По данным HACKING.md, тестовая Rust-утилита после strip весит 32 КБ с LTO против 20 КБ у её C-аналога.

Как это устроено

Биндинги к libsystemd-shared генерирует bindgen во время сборки из тех же заголовков. Поверх них — крейт systemd_shared, повторяющий соглашения C-кода: ошибки через errno, семейство log_*(), тот же разбор аргументов. Rust-программа выводит такой же --help, и это побайтно проверяется тестом. Секреты хранятся в Vec<u8, Erasing>, который затирает память при освобождении — в C это соглашение, здесь — часть типа.

Что это значит для сборщиков

Поддержка включается опцией -Drust= (по умолчанию auto). Нужны rustc ≥ 1.85, bindgen ≥ 0.71.1 и meson ≥ 1.4.0 — то, что есть в Debian 13. Сборки Arch и openSUSE, использующие --auto-features=enabled, сломались: им нужно либо -Drust=disabled, либо зависимости на rustc и bindgen.

Первой программой на Rust станет systemd-keyring-setup (PR #44114, ещё на ревью): при загрузке он загружает X.509-сертификаты в ключевые кольца ядра для dm-verity, fs-verity и BPF и затем запечатывает их. Утилита экспериментальная и по умолчанию выключена.

On October 24, systemd merged PR #44324, “rust: support programs written in Rust”, by Christian Brauner. It replaces an earlier attempt and follows rules the maintainers agreed on at the Berlin hackfest.

The ground rules

  • Rust is for new leaf components only. Existing C code is not ported, and nothing other parts of systemd depend on is written in Rust.
  • No cargo: meson builds everything.
  • Only the core, alloc and libc crates; code is no_std. As in the Linux kernel, systemd_shared has its own Box and Vec: every allocation returns an error, and there is no global allocator.
  • C linkage only: a Rust program links libsystemd-shared dynamically like the C programs do, while Rust crates are linked into it statically.

So nothing from the Rust standard library ends up in the binaries. According to HACKING.md, the stripped Rust test tool is 32 KB with LTO versus 20 KB for its C twin.

How it works

Bindings to libsystemd-shared are generated by bindgen at build time from the same headers. On top sits the systemd_shared crate, which mirrors C conventions: errno-based errors, the log_*() family, the same option parsing. A Rust program prints the same --help, and a test checks that byte for byte. Secrets live in Vec<u8, Erasing>, which wipes memory on free — a convention in C, part of the type here.

What it means for packagers

Support is controlled by -Drust= (default auto). It needs rustc ≥ 1.85, bindgen ≥ 0.71.1 and meson ≥ 1.4.0 — what Debian 13 ships. Arch and openSUSE builds that use --auto-features=enabled broke: they need either -Drust=disabled or build dependencies on rustc and bindgen.

The first Rust program will be systemd-keyring-setup (PR #44114, still under review): at boot it loads X.509 certificates into the kernel keyrings for dm-verity, fs-verity and BPF, then seals them. The tool is experimental and disabled by default.

Источники