Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
#### v0.11.0-kixelated.7+v0.32.2

----
- C: Render `Duration` as `<namespace>_duration`, an `int64_t` count of nanoseconds like the C++
binding's
- Core: Fail on a negative `Duration`, which reached Rust as a huge one, and on one from Rust
longer than `std::chrono::nanoseconds` holds, which overflowed

#### v0.11.0-kixelated.6+v0.32.2

----
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ the `error_style = "expected"`, `strip_type_prefix`, and `strip_function_prefix`
collide with upstream's:

```bash
cargo install uniffi-bindgen-cpp --locked --git https://github.com/kixelated/uniffi-bindgen-cpp --tag v0.11.0-kixelated.6+v0.32.2
cargo install uniffi-bindgen-cpp --locked --git https://github.com/kixelated/uniffi-bindgen-cpp --tag v0.11.0-kixelated.7+v0.32.2
```

# How to generate bindings
Expand Down Expand Up @@ -90,6 +90,9 @@ handle is `my_object *`, released with `my_object_free`. The rest follows from a
the matching `_free` (`<namespace>_string_free` for strings).
* Optional strings, objects, and structs are pointers that are NULL when absent; optional scalars
are `{ has_value, value }` structs. Bytes, lists, and maps are pointer and length structs.
* A duration is `<namespace>_duration`, an `int64_t` count of nanoseconds like the C++
binding's. Passing a negative one, or receiving one longer than `INT64_MAX` nanoseconds (about
292 years), aborts.
* An async call takes a callback and `user_data` and returns a `<namespace>_task *`. The callback
runs once on the dispatcher with the result, which it owns, unless the dispatcher refuses the
work or has shut down, which abandons the call. Free every task: freeing a pending
Expand All @@ -99,7 +102,7 @@ handle is `my_object *`, released with `my_object_free`. The rest follows from a
host's own, which receives `<namespace>_work *` items to run with `<namespace>_work_run`.

The C backend refuses what it cannot render faithfully, such as callback interfaces, custom and
external types, timestamps, durations, and exported traits other than `Display` on errors.
external types, timestamps, and exported traits other than `Display` on errors.

# Configuration options

Expand Down
2 changes: 1 addition & 1 deletion bindgen/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "uniffi-bindgen-cpp"
version = "0.11.0-kixelated.6+v0.32.2"
version = "0.11.0-kixelated.7+v0.32.2"
edition = "2021"

[dependencies]
Expand Down
19 changes: 18 additions & 1 deletion bindgen/src/bindings/c/gen_c.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,7 @@ impl<'a> Gen<'a> {
Type::Float32 => scalar("float", "f32"),
Type::Float64 => scalar("double", "f64"),
Type::Boolean => scalar("bool", "bool"),
Type::Duration => scalar(&format!("{ns}_duration"), "duration"),
Type::String => (Kind::String, "const char *".into(), "string".into()),
Type::Bytes => (Kind::Bytes, format!("{ns}_bytes"), "bytes".into()),
Type::Record { name, .. } => {
Expand Down Expand Up @@ -462,7 +463,7 @@ impl<'a> Gen<'a> {
)
}
Type::Box { inner_type } => return self.ctype(inner_type),
Type::Timestamp | Type::Duration | Type::Set { .. } | Type::Custom { .. } => {
Type::Timestamp | Type::Set { .. } | Type::Custom { .. } => {
bail!("the C backend does not support `{cpp}` yet")
}
Type::CallbackInterface { name, .. } => {
Expand Down Expand Up @@ -505,6 +506,16 @@ impl<'a> Gen<'a> {

let types: Vec<CType> = self.types.values().cloned().collect();

// A typedef, so the unit shows wherever a duration is declared. Nanoseconds in an
// int64_t mirror the C++ binding's `std::chrono::nanoseconds`.
if let Some(ct) = types.iter().find(|ct| matches!(ct.ty, Type::Duration)) {
self.claim(&ct.c)?;
h.push_str(&line_doc(
"A duration in nanoseconds. Passing a negative one, or receiving one past INT64_MAX, aborts.",
));
writeln!(h, "typedef int64_t {};\n", ct.c)?;
}

// Flat enums first: C cannot forward-declare an enum.
for ct in types.iter().filter(|ct| matches!(ct.kind, Kind::FlatEnum)) {
self.render_flat_enum(h, ct)?;
Expand Down Expand Up @@ -1248,6 +1259,12 @@ impl<'a> Gen<'a> {
decl(&format!("{field} &"), "value")
);
match &ct.kind {
// The C++ converters refuse a negative duration and one past INT64_MAX nanoseconds.
Kind::Scalar if matches!(ct.ty, Type::Duration) => {
writeln!(out, "{to} {{\n return value.count();\n}}\n")?;
writeln!(out, "{from} {{\n return {}(value);\n}}\n", ct.cpp)?;
writeln!(out, "{free} {{\n (void)value;\n}}\n")?;
}
Kind::Scalar => {
writeln!(out, "{to} {{\n return value;\n}}\n")?;
writeln!(out, "{from} {{\n return value;\n}}\n")?;
Expand Down
22 changes: 18 additions & 4 deletions bindgen/src/bindings/cpp/templates/duration_helper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,30 @@ RustBuffer {{ ffi_converter_name }}::lower(const {{ type_name }} &val) {
stream >> secs;
stream >> nanos;

return std::chrono::seconds(secs) + std::chrono::nanoseconds(nanos);
// Rust's Duration reaches about 584 billion years, far past what int64_t nanoseconds hold.
constexpr auto max = {{ type_name }}::max();
constexpr auto max_secs = std::chrono::duration_cast<std::chrono::seconds>(max);
constexpr auto max_nanos = static_cast<uint32_t>((max - max_secs).count());
if (secs > static_cast<uint64_t>(max_secs.count()) ||
(secs == static_cast<uint64_t>(max_secs.count()) && nanos > max_nanos)) {
{% call macros::fail("Duration does not fit in int64_t nanoseconds") %}
Comment on lines +30 to +32

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Free the owning RustBuffer when duration validation throws

Under the C++ exceptions style, receiving a Rust duration above INT64_MAX nanoseconds now throws from read(), bypassing the rustbuffer_free(buf) that follows it in lift(). RustStream does not own or release the buffer, so catching this exception leaks the returned Rust allocation on every call. The same problem affects enclosing records and collections whose readers encounter an oversized duration, potentially leaking a much larger buffer. Make the owning lift paths exception-safe so rejecting an out-of-range duration also releases its buffer.

Useful? React with 👍 / 👎.

}

return std::chrono::seconds(static_cast<int64_t>(secs)) + std::chrono::nanoseconds(nanos);
}

void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }} &val) {
auto secs = std::chrono::duration_cast<std::chrono::duration<int64_t>>(val);
auto secs = std::chrono::duration_cast<std::chrono::seconds>(val);
auto nanos = (val - secs).count();

stream << secs.count() << static_cast<uint32_t>(nanos);
stream << static_cast<uint64_t>(secs.count()) << static_cast<uint32_t>(nanos);
}

uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name }} &) {
uint64_t {{ ffi_converter_name }}::allocation_size(const {{ type_name }} &val) {
// Rust's Duration is unsigned. Every lower sizes its value before allocating or writing it,
// so refusing here leaks nothing when the refusal throws.
if (val.count() < 0) {
{% call macros::fail("Duration must not be negative") %}
}
return static_cast<uint64_t>(sizeof(uint64_t) + sizeof(uint32_t));
}
10 changes: 10 additions & 0 deletions cpp-tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,16 @@ endmacro(c_test_case)
c_test_case(c_api)
c_test_case(c_dispatcher)

# A duration Rust cannot represent, or C cannot, aborts rather than wrapping.
add_test(NAME c-negative-duration-test COMMAND c_api-test negative-duration)
set_tests_properties(c-negative-duration-test PROPERTIES
TIMEOUT 30
PASS_REGULAR_EXPRESSION "uniffi: Duration must not be negative")
add_test(NAME c-long-duration-test COMMAND c_api-test long-duration)
set_tests_properties(c-long-duration-test PROPERTIES
TIMEOUT 30
PASS_REGULAR_EXPRESSION "uniffi: Duration does not fit in int64_t nanoseconds")

# The C backend refuses what it cannot render instead of emitting half of it.
add_test(NAME c-refuses-callbacks-test
COMMAND ${BINDINGS_BUILD_DIR}/uniffi-bindgen-cpp${CMAKE_EXECUTABLE_SUFFIX}
Expand Down
55 changes: 54 additions & 1 deletion cpp-tests/tests/c_api/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

#include <capi.h>

#include <signal.h>
#include <stdlib.h>
#include <string.h>

static int streq(const char *a, const char *b) {
Expand Down Expand Up @@ -209,6 +211,40 @@ static void scalars(void) {
capi_string_free(text);
}

/* Durations cross as nanoseconds, split into Rust's seconds and nanoseconds on the way. */
static void durations(void) {
const capi_duration laps[] = {1, 1000000001, INT64_MAX};
capi_optional_duration delay;
capi_timer timer = capi_timer_default();
capi_timer *echo;

CHECK(capi_twice(0) == 0);
CHECK(capi_twice(1234567891) == 2469135782);
CHECK(capi_make_duration(9223372036, 854775807) == INT64_MAX);

delay.has_value = false;
delay.value = 0;
CHECK(!capi_halve(delay).has_value);
delay.has_value = true;
delay.value = 3000000001;
delay = capi_halve(delay);
CHECK(delay.has_value && delay.value == 1500000000);

CHECK(timer.period == 0 && !timer.delay.has_value && timer.laps.len == 0);
timer.period = 2500000000;
timer.delay.has_value = true;
timer.delay.value = 7;
timer.laps.data = laps;
timer.laps.len = 3;
echo = capi_echo_timer(&timer);
CHECK(echo->period == 2500000000);
CHECK(echo->delay.has_value && echo->delay.value == 7);
CHECK(echo->laps.len == 3);
CHECK(echo->laps.data[0] == 1 && echo->laps.data[1] == 1000000001);
CHECK(echo->laps.data[2] == INT64_MAX);
capi_timer_free(echo);
}

static void errors(void) {
capi_error *error;
capi_flat_error *flat;
Expand Down Expand Up @@ -448,11 +484,28 @@ static void async_calls(void) {
test_latch_free(r.done);
}

int main(void) {
static void exit_on_abort(int sig) {
(void)sig;
_Exit(0);
}

int main(int argc, char **argv) {
/* Each aborts as expected; its test matches the message printed before the abort. */
if (argc > 1) {
signal(SIGABRT, exit_on_abort);
if (strcmp(argv[1], "negative-duration") == 0) {
(void)capi_twice(-1);
} else if (strcmp(argv[1], "long-duration") == 0) {
(void)capi_make_duration(9223372036, 854775808);
}
return 1;
}

defaults();
records();
enums();
scalars();
durations();
errors();
objects();
async_calls();
Expand Down
3 changes: 3 additions & 0 deletions cpp-tests/tests/chronological/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,9 @@ int main() {
chronological::return_duration(std::chrono::nanoseconds::max())
);

// Rust's Duration is unsigned.
EXPECT_EXCEPTION(chronological::return_duration(-1ns), std::runtime_error);

test_string_timestamps();

auto before = std::chrono::system_clock::now();
Expand Down
37 changes: 35 additions & 2 deletions fixtures/c-api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Every construct the C backend renders: objects, records with defaults, flat and data
//! enums, errors with and without `Display`, bytes, optionals, lists, maps, and async calls
//! that complete, fail, or stay pending until cancelled.
//! enums, errors with and without `Display`, bytes, durations, optionals, lists, maps, and
//! async calls that complete, fail, or stay pending until cancelled.

use std::{
collections::{HashMap, VecDeque},
Expand All @@ -11,6 +11,7 @@ use std::{
Arc, Mutex,
},
task::{Context, Poll, Waker},
time::Duration,
};

uniffi::setup_scaffolding!("capi");
Expand Down Expand Up @@ -333,6 +334,38 @@ pub fn capi_flat_fail(gone: bool) -> Result<(), CapiFlatError> {
})
}

/// Durations in every position: a field, an optional, and a list.
#[derive(Clone, Debug, PartialEq, uniffi::Record)]
pub struct CapiTimer {
pub period: Duration,
#[uniffi(default = None)]
pub delay: Option<Duration>,
#[uniffi(default = [])]
pub laps: Vec<Duration>,
}

#[uniffi::export]
pub fn capi_echo_timer(timer: CapiTimer) -> CapiTimer {
timer
}

#[uniffi::export]
pub fn capi_twice(duration: Duration) -> Duration {
duration * 2
}

/// Half of `delay`, or none.
#[uniffi::export]
pub fn capi_halve(delay: Option<Duration>) -> Option<Duration> {
delay.map(|delay| delay / 2)
}

/// Builds a duration on the Rust side, which may be longer than C can hold.
#[uniffi::export]
pub fn capi_make_duration(secs: u64, nanos: u32) -> Duration {
Duration::new(secs, nanos)
}

/// Ready on its first poll.
#[uniffi::export]
pub async fn capi_sum(values: Vec<u64>) -> u64 {
Expand Down
Loading