rsbinder 0.12.0

Pure-Rust Binder IPC for Linux, Android, and macOS — kernel binder plus a libbinder-compatible RPC (binder-over-socket) transport.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// Copyright 2026 Jeff Kim <hiking90@gmail.com>
// SPDX-License-Identifier: Apache-2.0

//! Large byte payloads in a parcel, the AOSP way
//! (`Parcel::writeBlob` / `readBlob`, Java `Parcel.writeBlob`).
//!
//! A blob is a byte string that travels **inline when small and through
//! shared memory when large** — the writer decides by size, and the
//! reader is told which it got by a tag on the wire. That choice is a
//! wire convention, not an optimization each service invents: a Java peer
//! reading with `Parcel.readBlob` expects exactly these bytes. C++
//! `Parcel::readBlob(len, …)` reads them after the leading `length`,
//! which in AOSP the JNI layer reads and writes, not C++ `Parcel`.
//!
//! ```text
//! int32  length          (-1 = null, which `read_blob` reports as UnexpectedNull)
//! int32  tag             BLOB_INPLACE | BLOB_ASHMEM_IMMUTABLE | BLOB_ASHMEM_MUTABLE
//! BLOB_INPLACE:  `length` bytes, padded to 4
//! otherwise:     a file descriptor object for the shared region
//! ```
//!
//! ```no_run
//! # use rsbinder::*;
//! # fn f(payload: &[u8]) -> Result<()> {
//! let mut parcel = Parcel::new();
//! parcel.write_blob(payload, false)?;      // false = the reader may not write it
//!
//! parcel.set_data_position(0);
//! let blob = parcel.read_blob()?;
//! assert_eq!(blob.len(), payload.len());
//! # Ok(())
//! # }
//! ```
//!
//! **The fd is a memfd, and AOSP accepts it.** AOSP writes an ashmem
//! region or a memfd, as libcutils `use_memfd()` decides; its reader checks the
//! fd with `ashmem_valid()`, which answers yes for a memfd (libcutils
//! `ashmem-dev.cpp` reads `/proc/self/fd/N` and accepts a `/memfd:`
//! link) and takes the size from `fstat`. An immutable region is sealed
//! with `F_SEAL_FUTURE_WRITE` — the same seal AOSP's own memfd path
//! adds for `ashmem_set_prot_region(fd, PROT_READ)`.
//!
//! **Where fds cannot travel, a blob is still a blob.** On a transport
//! that carries no file descriptors — vsock, TLS, or the session-less
//! data-only parcel behind `to_bytes` — the payload goes
//! inline whatever its size, exactly as AOSP does when `mAllowFds` is
//! false. Nothing to configure, and the reader does not care: it follows
//! the tag.

use std::sync::Arc;

use crate::error::{Result, StatusCode};
use crate::file_descriptor;
use crate::parcel::Parcel;
use crate::shared_memory::{
    IMemoryHeap, MappedHeap, MemoryHeapBase, FLAG_READ_ONLY, SEAL_FUTURE_WRITE, SEAL_SHRINK,
    SEAL_WRITE,
};

/// Payloads this long or shorter always go inline; a longer one goes to
/// shared memory when [`Parcel::write_blob`] can use it (see there).
///
/// AOSP `BLOB_INPLACE_LIMIT` (`Parcel.cpp`).
pub const BLOB_INPLACE_LIMIT: usize = 16 * 1024;

/// Tag: the bytes follow in the parcel. AOSP `BLOB_INPLACE`.
pub const BLOB_INPLACE: i32 = 0;
/// Tag: a shared region the reader may only read. AOSP
/// `BLOB_ASHMEM_IMMUTABLE`. This is what Java's `Parcel.writeBlob`
/// always writes.
pub const BLOB_ASHMEM_IMMUTABLE: i32 = 1;
/// Tag: a shared region the reader may write, which the writer can then
/// see. AOSP `BLOB_ASHMEM_MUTABLE`.
pub const BLOB_ASHMEM_MUTABLE: i32 = 2;

/// Shared region name, recognizable in `/proc/<pid>/fd`; AOSP uses the same string.
const BLOB_REGION_NAME: &str = "Parcel Blob";

/// A blob read out of a parcel: the bytes, or the mapping they live in.
///
/// [`to_vec`](Self::to_vec) gets the payload whichever form it took.
/// There is deliberately **no** `as_bytes()` spanning both: a shared
/// region is memory another process can still write — always for a
/// mutable blob, and even for an immutable one, whose seal stops new
/// writable mappings but not the writer's existing one — so a `&[u8]`
/// over it would be a promise this module cannot keep. Reach for
/// [`mapped`](Self::mapped) to work in place with that in view.
#[derive(Debug)]
pub enum Blob {
    /// Carried in the parcel itself (`BLOB_INPLACE`).
    Inline(Vec<u8>),
    /// Carried as a shared-memory region.
    Shared {
        /// The mapping, `len` bytes at offset 0.
        heap: Arc<MappedHeap>,
        /// Payload length. For a blob [`Parcel::read_blob`] produced it
        /// equals `heap.size()`, which records the length that was asked
        /// for; the page rounding happens inside the kernel mapping and
        /// is not visible here.
        len: usize,
        /// `true` for `BLOB_ASHMEM_MUTABLE` — the writer offered a
        /// region it expects to see changes in.
        mutable: bool,
    },
}

impl Blob {
    /// Payload length in bytes.
    pub fn len(&self) -> usize {
        match self {
            Blob::Inline(bytes) => bytes.len(),
            Blob::Shared { len, .. } => *len,
        }
    }

    /// Whether the payload is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// `true` when the writer sent a region both sides may write
    /// (`BLOB_ASHMEM_MUTABLE`). An inline blob is never mutable — there
    /// is nothing shared to write.
    pub fn is_mutable(&self) -> bool {
        matches!(self, Blob::Shared { mutable: true, .. })
    }

    /// The payload, copied out.
    ///
    /// For a shared blob this reads the region *now*; a mutable one the
    /// peer is still writing has no single value, and this returns
    /// whatever is there at the moment of the call.
    pub fn to_vec(&self) -> Result<Vec<u8>> {
        match self {
            Blob::Inline(bytes) => Ok(bytes.clone()),
            Blob::Shared { heap, len, .. } => {
                // Hand-built `Blob::Shared` with `len` past the map: BadValue, not an OOM abort.
                if *len > heap.size() {
                    return Err(StatusCode::BadValue);
                }
                let mut out = vec![0u8; *len];
                heap.read_at(0, &mut out)?;
                Ok(out)
            }
        }
    }

    /// The bytes without copying — `Some` only for an inline blob, where
    /// they are this process's own. See the type docs for why a shared
    /// region does not answer here.
    pub fn inline(&self) -> Option<&[u8]> {
        match self {
            Blob::Inline(bytes) => Some(bytes),
            Blob::Shared { .. } => None,
        }
    }

    /// The mapping a shared blob arrived in, for reading it in place or
    /// (when [`is_mutable`](Self::is_mutable)) writing back to the
    /// sender. `None` for an inline blob.
    pub fn mapped(&self) -> Option<&Arc<MappedHeap>> {
        match self {
            Blob::Inline(_) => None,
            Blob::Shared { heap, .. } => Some(heap),
        }
    }
}

impl Parcel {
    /// Write `data` as a blob — inline when small, through a shared
    /// region when large. AOSP `Parcel::writeBlob`, with the length
    /// prefix Java's `Parcel.writeBlob` puts in front of it.
    ///
    /// `mutable_copy` picks the tag for the shared form: `false`
    /// (`BLOB_ASHMEM_IMMUTABLE`, what Java always writes) seals the
    /// region against further writes, so the reader gets a snapshot;
    /// `true` (`BLOB_ASHMEM_MUTABLE`) leaves it writable. It has no
    /// effect on a payload that goes inline, where there is nothing
    /// shared to write. The seal is asked for at region creation rather
    /// than added afterwards, because `MemoryHeapBase` seals a region
    /// `F_SEAL_SEAL` unless told otherwise and that would refuse a later
    /// `seal_future_write`.
    ///
    /// `mutable_copy` is meaningful only to the reader. This function
    /// keeps no handle on the region: the mapping is dropped and the
    /// owner fd closed before it returns, only a dup travels in the
    /// parcel, and the return type carries nothing back — so the writer
    /// cannot observe what the reader writes. A sender-side handle would
    /// take a variant returning the heap, the way AOSP's
    /// `writeBlob(len, mutableCopy, WritableBlob*)` hands one back; this
    /// API does not provide one.
    ///
    /// The shared form is used only when all of these hold; otherwise
    /// the payload goes inline and `mutable_copy` has nothing to act on:
    ///
    /// - the payload is longer than [`BLOB_INPLACE_LIMIT`];
    /// - this parcel can carry a file descriptor
    ///   ([`allow_fds`](Parcel::allow_fds)) — false on a TLS or vsock
    ///   session, which is why a blob needs no special handling there;
    /// - the target has a shared-memory backing store
    ///   ([`shared_memory::is_supported`](crate::shared_memory::is_supported));
    /// - for `mutable_copy == false`, the region came back write-sealed.
    ///   A Linux kernel older than 5.1 has no `F_SEAL_FUTURE_WRITE`, and
    ///   an immutable tag over a writable region would let one reader
    ///   change what another reads.
    ///
    /// The reader follows the tag, so it needs to know none of this.
    pub fn write_blob(&mut self, data: &[u8], mutable_copy: bool) -> Result<()> {
        // AOSP rejects a non-int32 length first; the wire carries it as one.
        let len = i32::try_from(data.len()).map_err(|_| StatusCode::BadValue)?;

        let shared = data.len() > BLOB_INPLACE_LIMIT
            && self.allow_fds()
            && crate::shared_memory::is_supported();
        // Fill the region before writing, so a failure leaves the parcel unchanged.
        let heap = if shared {
            let flags = if mutable_copy { 0 } else { FLAG_READ_ONLY };
            let heap = MemoryHeapBase::new_named(data.len(), flags, BLOB_REGION_NAME)?;
            // Pre-5.1 kernels lack the write seal; never tag a writable region immutable.
            let write_sealed = heap
                .seals()
                .is_some_and(|s| s & (SEAL_WRITE | SEAL_FUTURE_WRITE) != 0);
            (mutable_copy || write_sealed).then_some(heap)
        } else {
            None
        };
        let Some(heap) = heap else {
            self.write::<i32>(&len)?;
            self.write::<i32>(&BLOB_INPLACE)?;
            // `writeInplace`: raw bytes, no own length, padded to 4 bytes.
            return self.write_aligned_data(data);
        };
        heap.write_at(0, data)?;
        let fd = heap.to_parcel_fd()?;

        self.write::<i32>(&len)?;
        self.write::<i32>(&if mutable_copy {
            BLOB_ASHMEM_MUTABLE
        } else {
            BLOB_ASHMEM_IMMUTABLE
        })?;
        // Bare fd as AOSP `writeFileDescriptor`: no `ParcelFileDescriptor` not-null marker.
        file_descriptor::write_raw_fd(self, std::os::fd::AsFd::as_fd(fd.as_ref()))
    }

    /// Read a blob written by [`write_blob`](Parcel::write_blob) or Java
    /// `Parcel.writeBlob`.
    ///
    /// AOSP's C++ `Parcel::writeBlob(len, mutableCopy, outBlob)` is *not*
    /// a producer for this reader: it takes the length as an argument and
    /// writes the tag as the first int32, so the int32 length prefix this
    /// reader expects comes from the JNI layer above it
    /// (`android_os_Parcel_writeBlob`), which is also why the C++
    /// `readBlob(len, outBlob)` takes its length as an argument.
    ///
    /// Which form the payload took is the writer's decision, read off
    /// the tag; [`Blob::to_vec`] gets the bytes either way.
    ///
    /// A null blob — Java's `writeBlob(null)`, a `-1` length — is
    /// [`StatusCode::UnexpectedNull`] rather than an empty blob, because
    /// a zero-length blob is a different thing the same reader can meet.
    ///
    /// The shared form's fd must be one that cannot shrink under the
    /// mapping — a memfd sealed `F_SEAL_SHRINK` or a legacy
    /// `/dev/ashmem` fd. Anything else is [`StatusCode::BadValue`]: a
    /// regular file the sender truncates afterwards would `SIGBUS` this
    /// process, which Rust cannot catch.
    ///
    /// That gate is **stricter than AOSP's**. `readBlob` gates on
    /// `ashmem_valid(fd)`, which accepts a memfd on the `/memfd:`
    /// `/proc/self/fd/N` link alone (libcutils `ashmem-dev.cpp`) and
    /// never asks for `F_GET_SEALS`, so an unsealed `memfd_create` fd
    /// passes there and is refused here. The difference reaches only a
    /// hand-rolled sender: every AOSP send path — libcutils
    /// `__memfd_create_region`, AOSP's `MemoryHeapBase` and this
    /// module's — adds `F_SEAL_GROW | F_SEAL_SHRINK` at creation.
    pub fn read_blob(&mut self) -> Result<Blob> {
        let len = self.read::<i32>()?;
        if len < 0 {
            return Err(StatusCode::UnexpectedNull);
        }
        let len = len as usize;
        let tag = self.read::<i32>()?;

        if tag == BLOB_INPLACE {
            return Ok(Blob::Inline(self.read_aligned_data(len)?.to_vec()));
        }
        if tag != BLOB_ASHMEM_IMMUTABLE && tag != BLOB_ASHMEM_MUTABLE {
            log::error!("read_blob: unknown blob tag {tag}");
            return Err(StatusCode::BadValue);
        }
        let mutable = tag == BLOB_ASHMEM_MUTABLE;
        let fd = file_descriptor::read_raw_fd(self)?;
        // Stricter than AOSP `ashmem_valid`: a peer-truncatable file would SIGBUS on first touch.
        let shrink_sealed =
            crate::shared_memory::heap::fd_seals(&fd).is_some_and(|s| s & SEAL_SHRINK != 0);
        if !shrink_sealed
            && !crate::shared_memory::shared::is_ashmem_fd(std::os::fd::AsFd::as_fd(&fd))
        {
            log::error!("read_blob: the blob fd is neither a sealed memfd nor ashmem");
            return Err(StatusCode::BadValue);
        }
        // A zero-length region cannot be mapped; writers send empty blobs inline.
        if len == 0 {
            log::error!("read_blob: a shared blob of zero length has no region to map");
            return Err(StatusCode::BadValue);
        }
        // `from_fd` checks region >= payload (as AOSP) and refuses a 0-length non-ashmem fd.
        let flags = if mutable { 0 } else { FLAG_READ_ONLY };
        let heap = MappedHeap::from_fd(fd, len, 0, flags)?;
        Ok(Blob::Shared {
            heap: Arc::new(heap),
            len,
            mutable,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn pattern(len: usize) -> Vec<u8> {
        (0..len).map(|i| (i % 251) as u8).collect()
    }

    /// Size aside, can `write_blob` go shared here: a backing store, and write seals if immutable.
    fn shared_form_available(mutable_copy: bool) -> bool {
        if !crate::shared_memory::is_supported() {
            return false;
        }
        mutable_copy
            || MemoryHeapBase::new_named(4096, FLAG_READ_ONLY, BLOB_REGION_NAME)
                .ok()
                .and_then(|h| h.seals())
                .is_some_and(|s| s & (SEAL_WRITE | SEAL_FUTURE_WRITE) != 0)
    }

    /// Plan 10-2 AC-2.1: the boundary is the whole decision; pin one byte either side of it.
    #[test]
    fn the_inplace_limit_decides_the_form() {
        for (len, want_inline) in [
            (0usize, true),
            (1, true),
            (BLOB_INPLACE_LIMIT - 1, true),
            (BLOB_INPLACE_LIMIT, true),
            (BLOB_INPLACE_LIMIT + 1, false),
        ] {
            let data = pattern(len);
            let mut parcel = Parcel::new();
            // A fresh parcel is kernel-marshalled: fds allowed, only the size decides.
            assert!(parcel.allow_fds());
            parcel.write_blob(&data, false).expect("write_blob");
            parcel.set_data_position(0);

            let blob = parcel.read_blob().expect("read_blob");
            assert_eq!(blob.len(), len, "len {len}");
            let want_inline = want_inline || !shared_form_available(false);
            assert_eq!(
                blob.inline().is_some(),
                want_inline,
                "len {len} took the wrong form"
            );
            assert_eq!(blob.to_vec().expect("to_vec"), data, "len {len} round trip");
            assert!(!blob.is_mutable());
        }
    }

    /// The tag says which form the reader gets; only a mutable region is reader-writable.
    #[test]
    fn a_mutable_blob_is_writable_and_an_immutable_one_is_not() {
        let data = pattern(BLOB_INPLACE_LIMIT + 4096);
        if !shared_form_available(true) {
            return;
        }

        let mut parcel = Parcel::new();
        parcel.write_blob(&data, true).expect("write_blob mutable");
        parcel.set_data_position(0);
        let blob = parcel.read_blob().expect("read_blob");
        assert!(blob.is_mutable());
        let heap = blob.mapped().expect("a large blob is shared").clone();
        heap.write_at(0, b"edit")
            .expect("a mutable region takes a write");
        // The edit is visible through the same mapping the blob reads.
        assert_eq!(&blob.to_vec().expect("to_vec")[..4], b"edit");

        if !shared_form_available(false) {
            return;
        }
        let mut parcel = Parcel::new();
        parcel
            .write_blob(&data, false)
            .expect("write_blob immutable");
        parcel.set_data_position(0);
        let blob = parcel.read_blob().expect("read_blob");
        assert!(!blob.is_mutable());
        // Plan 10-2 AC-2.3: the region is mapped read-only.
        let heap = blob.mapped().expect("a large blob is shared");
        assert!(
            heap.write_at(0, b"edit").is_err(),
            "an immutable blob must not accept a write"
        );
        // The flag is rsbinder bookkeeping; the seal stops a reader that maps the fd itself.
        assert_ne!(
            heap.seals().expect("seals") & (SEAL_WRITE | SEAL_FUTURE_WRITE),
            0,
            "an immutable blob's fd must be write-sealed"
        );
    }

    /// A `-1` length is Java's null blob, which is not an empty blob.
    #[test]
    fn a_null_blob_is_distinguishable_from_an_empty_one() {
        let mut parcel = Parcel::new();
        parcel.write::<i32>(&-1).expect("write null marker");
        parcel.set_data_position(0);
        assert_eq!(parcel.read_blob().err(), Some(StatusCode::UnexpectedNull));

        let mut parcel = Parcel::new();
        parcel.write_blob(&[], false).expect("write_blob empty");
        parcel.set_data_position(0);
        let blob = parcel.read_blob().expect("read_blob");
        assert!(blob.is_empty());
        assert_eq!(blob.to_vec().expect("to_vec"), Vec::<u8>::new());
    }

    /// Plan 10-2 AC-2.5: an fd-less parcel (AOSP `!mAllowFds`, `to_bytes`) inlines any size.
    #[test]
    fn a_parcel_that_cannot_carry_an_fd_writes_the_payload_inline() {
        let data = pattern(1024 * 1024);
        let mut parcel = Parcel::new_data_only();
        assert!(!parcel.allow_fds());

        parcel.write_blob(&data, true).expect("write_blob");
        let bytes = parcel.into_bytes().expect("into_bytes");
        // 1 MB inline plus length and tag: no fd, so the bytes carry the whole payload.
        assert!(bytes.len() >= data.len() + 8);

        let mut parcel = Parcel::from_slice(&bytes);
        let blob = parcel.read_blob().expect("read_blob");
        assert_eq!(blob.inline().map(<[u8]>::len), Some(data.len()));
        assert_eq!(blob.to_vec().expect("to_vec"), data);
        // `mutable_copy` could not get a shared region; an inline blob is never mutable.
        assert!(!blob.is_mutable());
    }

    /// An unknown tag is refused rather than guessed at.
    #[test]
    fn an_unknown_tag_is_refused() {
        let mut parcel = Parcel::new();
        parcel.write::<i32>(&8).expect("len");
        parcel.write::<i32>(&7).expect("bogus tag");
        parcel.set_data_position(0);
        assert_eq!(parcel.read_blob().err(), Some(StatusCode::BadValue));
    }
}