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
24 changes: 17 additions & 7 deletions ffi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,10 @@ the rest cross encoded.
`IllegalStateException` naming the function and the rule, before any Rust code runs, so the call changed nothing.
- **Records** are data classes, compared by their fields, and **enums** an `enum class`,
or for one with data a sealed class of a data class per variant. `Display` is
`toString()`, `Debug` `debug()`, and `Default` a companion's `default()`. An **opaque
`toString()`, `Debug` `debug()`, and `Default` a companion's `default()`. A companion's
function is `@JvmStatic`, so Java calls it on the class, as Kotlin does, but for
`default()`, whose name Java reserves; one whose JVM name a field's getter has, as
`getX()` beside `x`, takes a trailing `_` on the JVM alone. An **opaque
value** is a class with an internal constructor, so only Rust makes one: of no more than
8 bytes on every target, with no padding, fields of integers, `bool`s, and `char`s alone, nested or not, and a
derived or std `PartialEq`, a value class over a `Long`, compared by its bits, which
Expand All @@ -643,11 +646,18 @@ the rest cross encoded.
`x = x.add(o)`, and beside Rust's own return, a `Pair`, or each element of its tuple,
`val (y, n) = x.take()`.
- **Bytes** are a `Bytes`. Passed in, Rust's own are shared with no copy, and Kotlin's,
which `Bytes(ByteArray)` holds without a copy, are copied once into a buffer Rust takes,
at a call's top level or in a record; those Rust lends a closure or trait method are
copied. A `Bytes` is read only through `size`,
`get`, `slice`, `copyInto`, and `toByteArray()`, so no view of Rust's memory escapes and
no read meets it freed. Up to 1 KiB are copied, which costs less than the GC's cleanup;
which `Bytes(ByteArray)` and `Bytes(ByteBuffer)` hold without a copy, are copied once
into a buffer Rust takes, at a call's top level or in a record; those Rust lends a
closure or trait method are copied. A direct `ByteBuffer`'s, as a `MediaCodec` output
is, are copied straight from its memory, from its position until its limit when made;
a heap one's array is shared, or copied when made if it is read-only. Writing a direct
buffer's bytes while a call copies them, or reading them while one copies into it, is a
race whose bytes are undefined; a buffer Android made inaccessible, as `MediaCodec` does
on releasing it, throws `IllegalStateException` before Rust reads it. A `Bytes` is
read only through `size`, `get`, `slice`, `copyInto`, and `toByteArray()`, so no view of
Rust's memory escapes and no read meets it freed; `copyInto(ByteBuffer)` copies into a
buffer at its position once, as `put` does, straight into a direct one's memory, such as
a `MediaCodec` input's. Up to 1 KiB are copied, which costs less than the GC's cleanup;
longer ones stay in Rust's buffer, each read a JNI call that passes the buffer's owner,
which JNI keeps reachable until the call returns, and are freed once the GC finds no
`Bytes` reaching them, slices included. The GC sees none of Rust's buffers, so at most
Expand All @@ -664,7 +674,7 @@ the rest cross encoded.
`Triple`, or else a generated `Tuple<n>`, and also `Tuple2` or `Tuple3` when it holds a
numeric array or a float anywhere, records included, since `Pair` and `Triple` cannot
compare them as Rust does (so a `BTreeMap<String, f64>` is a `List<Tuple2<String, Double>>`), `u128` `java.math.BigInteger`, which throws `IllegalArgumentException` passed in out of its range, and an `Err` a thrown `<E>Exception`
holding it, whose message is its `Display`. A `[u8; N]` is a generated `ArrayU8x<N>`,
holding it, whose message is its `Display`, a checked `Exception` each function that throws it declares with `@Throws`, so Java can catch it. A `[u8; N]` is a generated `ArrayU8x<N>`,
which copies the `ByteArray` it is made of and throws `IllegalArgumentException` unless
it holds exactly `N` bytes.
- **Std values** no Kotlin or Java type holds exactly are the runtime's own, each holding
Expand Down
16 changes: 16 additions & 0 deletions ffi/fixtures/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ impl Point {
y: self.y + dy,
}
}

/// The origin's `x`: a static whose Kotlin name, `getX`, is also the JVM name of `x`'s
/// getter, which a companion's `@JvmStatic` function would clash with.
pub fn get_x() -> i32 {
0
}
}

/// A record that owns memory: its `free` releases the name.
Expand Down Expand Up @@ -4285,6 +4291,16 @@ impl Site {
}

impl Shape {
/// The shape `name` names, if any: a static whose Kotlin name, `valueOf`, a Kotlin enum
/// also declares on the JVM, which a companion's `@JvmStatic` function would clash with.
pub fn value_of(name: &str) -> Option<Shape> {
match name {
"circle" => Some(Shape::Circle),
"square" => Some(Shape::Square),
_ => None,
}
}

/// Every shape, as a constant slice.
pub const ALL: &'static [Shape] = &[Shape::Circle, Shape::Square];

Expand Down
71 changes: 69 additions & 2 deletions ffi/runtime/jni.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,16 +377,59 @@ fn region(env: *mut JNIEnv, array: jbyteArray, start: jint, len: jint) -> Vec<u8
bytes
}

/// The owner Kotlin passes for a `Bytes` over a direct `ByteBuffer`, which no buffer Rust
/// lends has, as Kotlin's `_Native.__DIRECT`.
const DIRECT_OWNER: jlong = -1;

/// The memory of a live direct `ByteBuffer` from `start`, `len` long, failing loud past its
/// capacity, which Kotlin checks first.
fn direct_range(env: *mut JNIEnv, buffer: jobject, start: jint, len: jint) -> *mut u8 {
// SAFETY: `buffer` is a live direct `ByteBuffer`, which `load` checked the JVM supports.
let (base, capacity) = unsafe {
(
((**env).v1_4.GetDirectBufferAddress)(env, buffer).cast::<u8>(),
((**env).v1_4.GetDirectBufferCapacity)(env, buffer),
)
};
match (usize::try_from(start), usize::try_from(len), usize::try_from(capacity)) {
(Ok(start), Ok(len), Ok(capacity)) if start <= capacity && len <= capacity - start => match base.is_null() {
// An empty buffer may have no memory at all.
true if len == 0 => std::ptr::NonNull::dangling().as_ptr(),
true => rt::fail("jni", "a direct buffer has no memory"),
// SAFETY: within the buffer's memory, as just checked.
false => unsafe { base.add(start) },
},
_ => rt::fail("jni", "bytes passed are past their direct buffer's end"),
}
}

/// `len` bytes of a live direct `ByteBuffer` from `start`, copied once from its memory.
fn direct(env: *mut JNIEnv, buffer: jobject, start: jint, len: jint) -> Vec<u8> {
let from = direct_range(env, buffer, start, len);
let n = len as usize;
let mut bytes = Vec::<u8>::with_capacity(n);
// SAFETY: `from` reaches `n` bytes, and `bytes` has room for them. Nothing writes them
// meanwhile: `Bytes(ByteBuffer)` documents a write during the call as the caller's race.
unsafe {
std::ptr::copy_nonoverlapping(from, bytes.as_mut_ptr(), n);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
bytes.set_len(n);
}
bytes
}

/// Bytes Kotlin passes as a `Bytes` holds them, for Rust to take: none where `len` is -1,
/// else those from `start` of what a non-zero `owner` holds, shared without a copy, or of
/// the `byte[]` `held`, copied once.
/// else those from `start` of what an `owner` Rust lent holds, shared without a copy, or of
/// the direct `ByteBuffer` or the `byte[]` `held`, copied once.
///
/// # Safety
/// A non-zero `owner` came from [`hand`], and `held` keeps it from being freed.
pub unsafe fn passed(env: *mut JNIEnv, held: jobject, owner: jlong, start: jint, len: jint) -> rt::Buf {
if len == -1 {
return rt::Buf::NONE;
}
if owner == DIRECT_OWNER {
return rt::Buf::vec(direct(env, held, start, len));
}
if owner != 0 {
// SAFETY: the caller's contract.
let bytes = unsafe { range(owner, start, len) };
Expand Down Expand Up @@ -546,6 +589,21 @@ pub unsafe fn copy(env: *mut JNIEnv, owner: jlong, start: jint, len: jint, array
}
}

/// Copy the bytes `owner` holds from `start`, `len` long, into the memory of `buffer`, a
/// direct `ByteBuffer`, at `at`.
///
/// # Safety
/// As [`range`], and `buffer` is a live direct `ByteBuffer`.
pub unsafe fn copy_direct(env: *mut JNIEnv, owner: jlong, start: jint, len: jint, buffer: jobject, at: jint) {
let to = direct_range(env, buffer, at, len);
// SAFETY: the caller's contract, and `to` reaches `len` bytes; Rust's never overlap Java's,
// and nothing touches them meanwhile, as `Bytes.copyInto(ByteBuffer)` documents.
unsafe {
let bytes = range(owner, start, len);
std::ptr::copy_nonoverlapping(bytes.as_ptr(), to, bytes.len());
}
}

/// Free the bytes `owner` holds.
///
/// # Safety
Expand Down Expand Up @@ -1318,6 +1376,11 @@ impl Wire for rt::Buf {
let (start, len) = (r.get::<i32>(), r.get::<i32>());
r.referred(at, |env, array| region(env, array, start, len))
}
DIRECT => {
let at = r.get::<i32>();
let (start, len) = (r.get::<i32>(), r.get::<i32>());
r.referred(at, |env, buffer| direct(env, buffer, start, len))
}
TEXT => r.text(),
len => match usize::try_from(len) {
Ok(len) => rt::Buf::view(r.take(len)),
Expand Down Expand Up @@ -1353,6 +1416,10 @@ const LENT: i32 = -2;
/// start and how many, where an encoded buffer's length would.
const KOTLIN: i32 = -3;

/// What precedes the place in a call's objects of a direct `ByteBuffer`, then where its bytes
/// start and how many, where an encoded buffer's length would.
const DIRECT: i32 = -5;

/// What marks the next of a call's texts, which its objects hold, where an encoded buffer's
/// length would.
const TEXT: i32 = -4;
Expand Down
21 changes: 17 additions & 4 deletions ffi/runtime/rt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,9 @@ class __Writer {
}

/**
* Bytes a record holds, or -1 for none: Kotlin's as [KOTLIN], their array's place in
* [refs], where they start, and their length, which Rust copies once from the array, and
* Bytes a record holds, or -1 for none: Kotlin's as [KOTLIN], or a direct buffer's as
* [DIRECT], their array's or buffer's place in [refs], where they start, and their
* length, which Rust copies once from the array or the buffer's memory, and
* Rust's as [LENT], their owner, where they start, and their length, which Rust reads in
* place, kept until [release].
*/
Expand All @@ -107,15 +108,15 @@ class __Writer {
}
val owner = v.owner
room(20)
if (owner != 0L) {
if (owner != 0L && owner != __DIRECT) {
b.putInt(LENT)
b.putLong(owner)
b.putInt(v.start)
b.putInt(v.size)
(kept ?: java.util.ArrayList<Any?>().also { kept = it }).add(v.held)
return
}
b.putInt(KOTLIN)
b.putInt(if (owner == __DIRECT) DIRECT else KOTLIN)
b.putInt(ref(v.held))
b.putInt(v.start)
b.putInt(v.size)
Expand Down Expand Up @@ -865,6 +866,18 @@ const val LENT = -2
/** What precedes the place of Kotlin's array of bytes in a writer's `refs`, where an encoded one's length would. */
const val KOTLIN = -3

/** What precedes the place of a direct `ByteBuffer` in a writer's `refs`, where an encoded one's length would. */
const val DIRECT = -5

/** The owner a direct buffer's bytes cross a call with, which no buffer Rust lends has. */
const val __DIRECT = -1L

/** [buffer]'s array, shared, or for a read-only one a copy of its bytes from its position. */
fun __heap(buffer: java.nio.ByteBuffer): ByteArray = when (buffer.hasArray()) {
true -> buffer.array()
false -> ByteArray(buffer.remaining()).also { buffer.duplicate().get(it) }
}

/** What marks Kotlin's text, which a writer's `refs` holds, where an encoded one's length would. */
const val TEXT = -4

Expand Down
2 changes: 2 additions & 0 deletions ffi/runtime/types.kt
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ sealed interface IpAddr {

companion object {
/** [address] exactly, throwing `IllegalArgumentException` for an IPv6 one with a scope, which Rust's `IpAddr` has no room for. */
@kotlin.jvm.JvmStatic
fun of(address: java.net.InetAddress): IpAddr = when (address) {
is java.net.Inet6Address -> Ipv6Addr(address)
else -> Ipv4Addr(address.address)
Expand Down Expand Up @@ -137,6 +138,7 @@ sealed interface SocketAddr {

companion object {
/** [address], throwing `IllegalArgumentException` for an unresolved one, which Rust's `SocketAddr` has no form of. */
@kotlin.jvm.JvmStatic
fun of(address: java.net.InetSocketAddress): SocketAddr = when (_resolved(address)) {
is java.net.Inet6Address -> SocketAddrV6(address)
else -> SocketAddrV4(address)
Expand Down
Loading