# Rust wrapper around C flexible array

**URL:** <https://users.rust-lang.org/t/rust-wrapper-around-c-flexible-array/52605>\
**Category:** code review\
**Created:** [December 11, 2020, 1:37am UTC](https://users.rust-lang.org/t/rust-wrapper-around-c-flexible-array/52605 "2020-12-11T01:37:11Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![rectang](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rectang/32/18571_2.png) [@rectang](https://users.rust-lang.org/u/rectang)\
**Post date:** [December 11, 2020, 1:37am UTC](https://users.rust-lang.org/t/rust-wrapper-around-c-flexible-array/52605/1 "2020-12-11T01:37:11Z")

</div>

I'm trying to create Rust bindings for a C API that uses a "flexible array".

```nohighlight
typedef struct Buffer {
    uint32_t metadata;
    void *data;
} Buffer;

typedef struct BufferList {
    uint32_t num_buffers;
    Buffer buffers[1]; // <--- could be >= 1 in reality
} BufferList;

```

I need to accommodate both of these use cases:

1. Rust processing of a `BufferList` allocated in C
2. C processing of a `BufferList` allocated in Rust

What I've come up with is to make the Rust version of BufferList a struct without any public members, where instead of accessing `num_buffers` and `buffers` members directly, the user calls associated functions which perform some `unsafe` manipulations.

```nohighlight
#![allow(unused)]

use std::ffi::c_void;
use std::mem;

#[repr(C)]
pub struct Buffer {
    pub metadata: u32,
    pub data: *mut c_void,
}

#[repr(C)]
struct BufferListInternal {
    num_buffers: u32,
    buffers: [Buffer; 1],
}

#[repr(transparent)]
#[derive(Copy, Clone)]
struct BufferList {
    inner: *mut BufferListInternal,
}

impl BufferList {
    pub fn new(num_buffers: u32) -> Self {
        let num_buffers = std::cmp::max(num_buffers, 1);
        let offset_of_buffers = mem::align_of::<Buffer>();
        let size = offset_of_buffers + num_buffers as usize * mem::size_of::<Buffer>();
        let mut buffer_list = BufferList {
            inner: Vec::with_capacity(size).as_mut_ptr() as *mut BufferListInternal,
        };
        unsafe {
            (*buffer_list.inner).num_buffers = num_buffers;
        }
        buffer_list
    }

    pub fn num_buffers(&self) -> u32 {
        unsafe { (*self.inner).num_buffers }
    }

    pub fn buffer_mut(&mut self, buffer_num: u32) -> Result<&mut Buffer, String> {
        if buffer_num < unsafe { (*self.inner).num_buffers } {
            Ok(unsafe {
                let buffers: *mut Buffer = &mut (*self.inner).buffers as *mut _ as *mut Buffer;
                &mut *(buffers.add(buffer_num as usize))
            })
        } else {
            Err("buffer index too large".to_string())
        }
    }
}

#[test]
fn buffer_list_allow_deep_access() {
    let mut buffer_list = BufferList::new(3);
    assert_eq!(buffer_list.num_buffers(), 3);
    let mut buffer = buffer_list.buffer_mut(0).unwrap();
    buffer.metadata = 42;
    assert_eq!(unsafe { (*buffer_list.inner).buffers[0].metadata }, 42);
}

#[test]
fn buffer_list_c_abi() {
    let mut buffer_list = BufferList::new(3);
    assert_eq!(num_buffers_from_c(buffer_list.inner), 3);
    
    // This is what I want, but it doesn't work because of the extra
    // layer of indirection in the Rust version of BufferList.
    //assert_eq!(num_buffers_from_c(&buffer_list), 3);
}

extern "C" fn num_buffers_from_c(pointer: *const BufferListInternal) -> u32 {
    unsafe { (*pointer).num_buffers }
}

```

([Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6caca33f0bb693fb8b99a89ab2132a0d))

However, I'm dissatisfied about borrowing behavior: `&buffer_list` and `&mut buffer_list` won't behave as Rust users might expect because of the extra level of indirection.

Thoughts?

---

<div class="post-metadata">

**Author:** ![Yandros](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/yandros/32/8136_2.png) [@Yandros](https://users.rust-lang.org/u/Yandros)\
**Post date:** [December 11, 2020, 2:31pm UTC](https://users.rust-lang.org/t/rust-wrapper-around-c-flexible-array/52605/2 "2020-12-11T14:31:53Z")

</div>

First of all, your code has triggered Miri, a Rust interpreter designed to detect as much UB as possible:

 ![Screen Shot 2020-12-11 at 14.10.31](https://us1.discourse-cdn.com/flex019/uploads/rust_lang/original/3X/4/2/42bf4aade10a96e3f6bf5b75fdcce9f06ea7efea.png)

- You can run Miri, in the Playground, by having an `fn main()` and using the `Tools` on the top-right menu.

I will thus go over fixing your code, but keep in mind that flexible array buffers don't play well with Rust semantics, and this kind of "extra indirection" (which in practice can be softened by marking the functions `#[inline]`, or by defining your own types for the shared ref and exclusive ref types (the former being `Copy`, the latter offering a `.reborrow()` method; the ergonomics are then not great)) is thus often unavoidable.

> [@rectang](#):
>
> ```rust
> typedef struct Buffer {
> uint32_t metadata;
> void *data;
> } Buffer;
> 
> typedef struct BufferList {
> uint32_t num_buffers;
> Buffer buffers[1]; // <--- could be >= 1 in reality
> } BufferList;
> 
> ```

`Buffer` is quite straight-forward to define:

```rust
#[repr(C)]
struct Buffer {
    metadata: u32,
    data: *mut c_void,
}

```

`BufferList` is indeed quite trickier. **You cannot use a fixed length (one that may be too short or too long) while also using "high-level Rust pointers" (`&`, `&mut`, `Box`, _etc._) to such `Buffer`.**

From having had to deal with those in the pasts, there are two approaches:

- define `BufferList` as a DST (dynamically sized-type):

- Never expose `BufferList` itself to Rust code as an arbitrary pointee, but rather create your own newtype representing a slim implementation of a type with `Box<BufferList>` semantics. This is what you have done, and good job with going in that direction, not everybody does it (they go with the first approach with a fake fixed length, which is UB). Sadly you got the implementation wrong, but we'll now see how to handle that part.

### The "`Box<BufferList>`" newtype w/ hand-rolled implementation

In your implementation, the pointee is now called `BufferListInternal`, and that newtype wrapper over an owning pointer is `BufferList`.

> [@rectang](#):
>
> ```rust
> let offset_of_buffers = mem::align_of::<Buffer>();
> let size = offset_of_buffers + num_buffers as usize * mem::size_of::<Buffer>();
> 
> ```

The `offset_of_buffers` is a bit of a shortcut that doesn't generalize very well; you are relying on `size_of::<u32>()` (`metadata` field) being smaller or equal than the alignment of `BufferListInternal` (otherwise that computation of the offset is wrong). This is true in your case, but it'd warrant some comment.

> [@rectang](#):
>
> ```rust
> let mut buffer_list = BufferList {
> inner: Vec::with_capacity(size).as_mut_ptr() as *mut BufferListInternal,
> };
> 
> ```

This is the part where all hell breaks loose 😅:

- you don't type-annotate the construction of the `Vec`, so subtle inference changes could change the semantics in very wrong ways. Here, for instance, the fact that this compiles, means that inference did lead to a single candidate type, which given the pointer cast, must have been a `BufferListInternal`. The MIR output (available in the top-left menu of the Playground) confirms this:

- The second problem comes from destructors and temporaries: by doing `Vec::new()` / `Vec::with_capacity()` followed by an `.as_mut_ptr()` (which _borrows_ the `Vec`, and yields a lifetime-disconnected (still borrowing) pointer) Rust:

### The "cleanest" (imho) way to write this pattern

The correct way of writing that function is by relying heavily on [`Layout`](https://doc.rust-lang.org/stable/core/alloc/struct.Layout.html) and its convenience methods, as well as the following very handy type definition:

```rust
#[repr(C)] // required for the alloc layout shenanigans!
struct BufferList<
    Buffers // make the Rust type generic over its trailing field
    : ?Sized // with support for DSTs (here, mainly, `[Buffer]`)
    = [Buffer] // add a convenient default parameter
>
{
    num_buffers: u32,
    buffers: Buffers,
}

```

This way `BufferList`, with no params provided, represents the type with a `[Buffer]` field I was talking about at the beginning of my post.

You can already see how convenient this def is, when you see you can write:

```rust
let boxed_buffer_list: Box<BufferList> = Box::new(BufferList {
    num_buffers: 2,
    buffers: [Buffer { … }, Buffer { … },], // : [Buffer; 2]
})/* coercion to a fat pointer */;

```

to which we can already add:

```rust
impl<Buffers : ?Sized> BufferList<Buffers> {
    pub
    fn as_ptr (self: &'_ Self)
      -> *const BufferList<[Buffer; 1]>
    {
        self
            as *const Self // remove the lifetime and the "higher-level-ness" (still a fat pointer)
            as *const _ // slim pointer (trash away the len part of the fat pointer)
    }

    pub
    fn as_mut_ptr (self: &'_ mut Self)
      -> *mut BufferList<[Buffer; 1]>
    {
        self as *mut Self as *mut _
    }
}

```

This will enable you to use this type across FFI.

With the very near-future `min_const_generics`, we will be able to add a stack / inline constructor:

```rust
impl<const N: usize> BufferList<[Buffer; N]> {
    pub
    fn new (buffers: [Buffer; N])
      -> Self
    {
        Self {
            num_buffers: N.try_into().expect("Count overflowed `u32`"),
            buffers,
       }
    }

    // Heap-allocate and then fatten the obtained pointer
    pub
    fn boxed (self: Self)
      -> Box<BufferList /* <[Buffer]> */>
    {
        Box::new(self)
    }
}

```

And now, for the runtime length initialization using heap allocation, as you attempted to do:

```rust
extern crate alloc as alloc_crate;

use ::core::{
    convert::{TryFrom, TryInto},
    ptr,
};
use ::alloc_crate::alloc::{self, Layout};

impl BufferList {
    pub
    fn new (iterator: impl ExactSizeIterator<Item = Buffer>)
      -> Box<Self>
    { unsafe {
        let count = iterator.len();
        let count_u32 = u32::try_from(count).expect("Count overflowed `u32`");
        // layout for the `num_buffers` field + padding for the `buffers`.
        let num_buffers_layout = Layout::new::<BufferList<[Buffer; 0]>>();
        let buffers_layout = Layout::array::<Buffer>(count).unwrap();
        let (self_layout, buffers_offset) =
            num_buffers_layout.extend(buffers_layout).unwrap()
        ;
        let self_layout = self_layout.pad_to_align(); // in case `num_buffers_layout` had a higher alignment than that of `Buffer`.
        let ptr = alloc::alloc(self_layout).cast::<u8>();
        if ptr.is_null() {
            enum Diverged {}
            let _: Diverged = alloc::handle_alloc_error(self_layout);
        }
        let (ptr_to_num_buffers, mut ptr_to_buffers) = (
            ptr.cast::<u32>(),
            ptr.add(buffers_offset).cast::<Buffer>(),
        );
        ptr_to_num_buffers.write(count_u32);
        // We need to use `zip` as extra safety since
        // `ExactSizeIterator` is allowed to lie (the trait is not `unsafe`).
        let ref mut idxs = 0 .. count;
        idxs.zip(iterator).for_each(|(_, buffer)| {
            // zip prevents the iterator from yielding too many elems
            ptr_to_buffers.write(buffer);
            ptr_to_buffers = ptr_to_buffers.add(1);
        });
        // the iterator may also have yielded not enough elems
        assert!(idxs.next().is_none(), "ExactSizeIterator lied");
        // at this point, we know we have correctly
        // initialized and written everything 🙌
        // Time to fatten our pointer… (redundantly embed the length)
        let fake_fat_ptr: *mut [BufferList<Buffer>] = ptr::slice_from_raw_parts_mut(ptr.cast(), count);
        let actual_fat_ptr: *mut BufferList<[Buffer]> = fake_fat_ptr as _;
        Box::<Self>::from_raw(actual_fat_ptr)
    }}
}

```

- 
### [Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=4a1aff3190b29cd9bc1de024f04fba48)

---

<div class="post-metadata">

**Author:** ![H2CO3](https://avatars.discourse-cdn.com/v4/letter/h/b5ac83/32.png) [@H2CO3](https://users.rust-lang.org/u/H2CO3)\
**Post date:** [December 11, 2020, 3:32pm UTC](https://users.rust-lang.org/t/rust-wrapper-around-c-flexible-array/52605/3 "2020-12-11T15:32:53Z")

</div>

To add to that, even the original C code has undefined behavior. A flexible member should be spelled `Buffer buffers[];`, and it is only valid in C99 and later standards (the trick presented here is known as "the struct hack" in C89 and it is not a compliant way of realizing flexible array members).

Accessing an array beyond its declared length is UB in all versions of C, even if the allocation extends to the past-the-end elements, because they do not "designate the same object" (as the Standard phrases it).

---

<div class="post-metadata">

**Author:** ![rectang](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rectang/32/18571_2.png) [@rectang](https://users.rust-lang.org/u/rectang)\
**Post date:** [December 11, 2020, 6:44pm UTC](https://users.rust-lang.org/t/rust-wrapper-around-c-flexible-array/52605/4 "2020-12-11T18:44:26Z")

</div>

@Yandros, thank you very much for your tour de force answer. I am researching many aspects and plan to respond to the design recommendations later.

> [@Yandros](#):
>
> **This marks the end of the aforementioned enclosing statement** , at which point Rust cleans up its temporaries, leading to the `Vec` temporary ( `_15` ) being `drop` -ped! This deallocates the just allocated buffer, **which means that the `.inner` pointer dangles as soon as it is created!** If this had been a regular borrow, Rust would have errored about a "local does not live long enough" error, but given the lifetime-erased nature of the obtained pointer, Rust no longer knows that such pointer is borrowing from a deallocated `Vec` , and thus says nothing. This is the same problem as in [CString/.as\_ptr() is incredibly unsafe ☹](https://users.rust-lang.org/t/cstring-as-ptr-is-incredibly-unsafe/11431).

Ugh. I'm extremely unhappy to have left this landmine in the code for you to disarm. I showed this to San Diego Rust at the virtual meetup last night and they jumped on it too.

An earlier iteration used `calloc` and `free`:

```diff
@@ -27,7 +26,7 @@
         let offset_of_buffers = mem::align_of::<Buffer>();
         let size = offset_of_buffers + num_buffers as usize * mem::size_of::<Buffer>();
         let mut buffer_list = BufferList {
- inner: Vec::with_capacity(size).as_mut_ptr() as *mut BufferListInternal,
+ inner: unsafe { libc::calloc(size, 1) as *mut BufferListInternal },
         };
         unsafe {
             (*buffer_list.inner).num_buffers = num_buffers;
@@ -51,6 +50,12 @@
     }
 }
 
+impl Drop for BufferList {
+ fn drop(&mut self) {
+ unsafe { libc::free(self.inner as *mut c_void) }
+ }
+}
+

```

That might be goofy, but it passed Miri (after removing a `#[derive(Copy, Clone)]` that's incompatible with `Drop`). Furthermore, because it's not idiomatic Rust, it draws attention to itself as something to review — and it's an appropriate "tell" for my background as a reasonably experienced C programmer but a relative newcomer to Rust.

This misadventure with pointers illustrates why I want to design BufferList to work with `&`, `&mut` and friends, in order to spare users from dealing with `* mut` and `* const` as much as possible. Technically the unsound code only happens at the site of the pointer dereference, but the "safe" code is where you set yourself up for failure.

As a data point, as I've learned to work with Rust's borrow checker, I've found the distinctions between pointers and references hard to grok: what's actually being passed around underneath, when implicit dereferencing happens automagically and when explicit dereferencing is needed, the [difference between `&(*pointer)` and `&{ *pointer }`](https://users.rust-lang.org/t/when-does-dereferencing-a-pointer-create-a-copy/51955/1), what the guarantees are for lifetime management. That confusion is how my mistake originated, although there were at least two missed opportunities to avert disaster:

1. I should have stuck with `calloc`/`free` because I was uncertain about using `Vec` and I knew that I got it wrong, the failure mode would be extremely severe.
2. At the language level, it's a bummer that it's so easy to create a dangling pointer in safe code that may be very far away from the `unsafe` block that ultimately performs the dereference. In a perfect world, these `as_ptr` and `as_mut_ptr` routines wouldn't be such footguns.

Back in the day, I used to script valgrind checks for my C projects. Since I'll be continuing to work with `unsafe`, it's clear that I'll need to do something similar while working with Rust, using Miri or other tools.

---

<div class="post-metadata">

**Author:** ![rectang](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/rectang/32/18571_2.png) [@rectang](https://users.rust-lang.org/u/rectang)\
**Post date:** [December 11, 2020, 7:00pm UTC](https://users.rust-lang.org/t/rust-wrapper-around-c-flexible-array/52605/5 "2020-12-11T19:00:34Z")

</div>

> [@H2CO3](#):
>
> To add to that, even the original C code has undefined behavior. A flexible member should be spelled `Buffer buffers[];` , and it is only valid in C99 and later standards (the trick presented here is known as "the struct hack" in C89 and it is not a compliant way of realizing flexible array members).

Heh. I simplified the actual API I'm working with to better isolate the issue of flexible arrays, but here's the original, from Apple's Core Audio API, in the CoreAudioBaseTypes.h header file:

```C
struct AudioBufferList
{
    UInt32 mNumberBuffers;
    AudioBuffer mBuffers[1]; // this is a variable length array of mNumberBuffers elements
	
#if defined(__cplusplus) && defined(CA_STRICT) && CA_STRICT
public:
    AudioBufferList() {}
private:
    // Copying and assigning a variable length struct is problematic; generate a compile error.
    AudioBufferList(const AudioBufferList&);
    AudioBufferList& operator=(const AudioBufferList&);
#endif

};

```

---

<div class="post-metadata">

**Author:** ![H2CO3](https://avatars.discourse-cdn.com/v4/letter/h/b5ac83/32.png) [@H2CO3](https://users.rust-lang.org/u/H2CO3)\
**Post date:** [December 11, 2020, 7:31pm UTC](https://users.rust-lang.org/t/rust-wrapper-around-c-flexible-array/52605/6 "2020-12-11T19:31:35Z")

</div>

Oh, so it's not code you control – sure, in that case there's not much to do about it.

---

<div class="post-metadata">

**Author:** ![CAD97](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/cad97/32/5076_2.png) [@CAD97](https://users.rust-lang.org/u/CAD97)\
**Post date:** [December 11, 2020, 8:12pm UTC](https://users.rust-lang.org/t/rust-wrapper-around-c-flexible-array/52605/7 "2020-12-11T20:12:24Z")

</div>

I think it's probably also worth to mention my crate, [slice-dst](https://lib.rs/crates/slice-dst), whose purpose is to make working with FAM types in Rust a bit easier. You can combine it with [erasable](https://lib.rs/crates/erasable) as well to manage thin pointers in a slightly less adhoc and footgunny method. These crates were originally written (and are used) to optimize the amount of allocation in rust-analyzer's syntax tree representation. (If the rustc/r-a syntax tree merger ever happens, they may end up in rustc's tree! 😊)

Though at the same time: the version using generics to create the type as sized initially is standard, understood by most rustaceans, and doesn't involve the pile of unsafe that slice-dst requires. (The advantage is slight but there: avoiding generics reduces monomorphization cost.)

---

<div class="post-metadata">

**Author:** ![SkiFire13](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/skifire13/32/17959_2.png) [@SkiFire13](https://users.rust-lang.org/u/SkiFire13)\
**Post date:** [December 12, 2020, 11:43am UTC](https://users.rust-lang.org/t/rust-wrapper-around-c-flexible-array/52605/8 "2020-12-12T11:43:53Z")

</div>

> [@rectang](#):
>
> At the language level, it's a bummer that it's so easy to create a dangling pointer in safe code that may be very far away from the `unsafe` block that ultimately performs the dereference. In a perfect world, these `as_ptr` and `as_mut_ptr` routines wouldn't be such footguns.

Then how would you express getting a mutable pointer to the underlying storage without consuming the `Vec`? Note the naming scheme also reflects this distinction:

- `as_` means that you're borrowing/viewing the struct as something else, without consuming it (they usually take a `&self` or `&mut self` parameter)
- `into_` means that you're converting the struct to something else, consuming it in the process (they usually take a `self` parameter)
- `from_` means that you're converting something else to this struct, consuming it in the process. This is usually called with the returned value from the `into_` variant.

For example for `Vec` there's `as_mut_ptr` that doesn't consume, `into_raw_parts` (unfortunately still unstable) that consumes it and returns the pointer to the underlying storage, the length and the capacity (unitialized elements included), and `into_boxed_slice` + `Box::into_raw` combo (this is somewhat hidden, strange and may also reallocate) that gives you a pointer to the underlying storage and the length, however it drops the excess storage; this may reallocate, however you don't need to store the capacity.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [March 12, 2021, 11:44am UTC](https://users.rust-lang.org/t/rust-wrapper-around-c-flexible-array/52605/9 "2021-03-12T11:44:08Z")

</div>

Closed on March 12, 2021, 11:44am UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
