This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-12010-30c26714bf3fb03bcc7ff15445216236d8dc4411 in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 3a2c35683ade21d90f3a317d64f871c3d76c39ab Author: Andrea Bozzo <[email protected]> AuthorDate: Sun Nov 8 02:36:42 2026 +0000 fix(ffi): read byte array offsets unaligned in buffer_len (#12010) # Which issue does this PR close? - Part of #7136. # Rationale for this change Since #10030, `from_ffi` realigns under-aligned buffers, but two reads happen before that and assume alignment: `buffer_len` dereferences the last offset of a `Utf8`, `Binary`, `LargeUtf8` or `LargeBinary` array, and `buffers` views the variadic buffer lengths of a `Utf8View` or `BinaryView` array as an `&[i64]`. The C data interface allows either to be under-aligned, and when they are, a debug build aborts and a release build has undefined behaviour. Found with [arrow-abi-doctor](https://github.com/AndreaBozzo/arrow-abi-doctor), whose alignment cells place `utf8` offsets one byte off. # What changes are included in this PR? Both reads now go through `read_unaligned`: the last offset in `ImportedArrowArray::buffer_len`, and the variadic buffer lengths in `ImportedArrowArray::buffers`, which are still borrowed in place when aligned and copied only when not. # Are these changes tested? Yes. `test_bytes_with_unaligned_offsets` imports each of the four byte array types with its offsets one byte off alignment, built as `ArrayData` and exported through `to_ffi`, so it runs without `force_validate`. `test_views_with_unaligned_variadic_buffer_lengths` hand-builds a C array with the variadic buffer lengths of both view types one byte off, since `FFI_ArrowArray::new` always exports them aligned. Reverting any of the three reads makes them abort. # Are there any significant user-facing changes? No. --- arrow-array/src/ffi.rs | 171 +++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 152 insertions(+), 19 deletions(-) diff --git a/arrow-array/src/ffi.rs b/arrow-array/src/ffi.rs index a84d3cb47f..afbc21732e 100644 --- a/arrow-array/src/ffi.rs +++ b/arrow-array/src/ffi.rs @@ -88,7 +88,7 @@ To import an array, unsafely create an `ArrowArray` from two pointers using [Arr To export an array, create an `ArrowArray` using [ArrowArray::try_new]. */ -use std::{mem::size_of, ptr::NonNull, sync::Arc}; +use std::{borrow::Cow, mem::size_of, ptr::NonNull, sync::Arc}; use arrow_buffer::{Buffer, MutableBuffer, bit_util}; pub use arrow_data::ffi::FFI_ArrowArray; @@ -378,32 +378,38 @@ impl ImportedArrowArray<'_> { let buffer_begin = can_contain_null_mask as usize; let buffer_end = self.array.num_buffers() - usize::from(variadic); - let variadic_buffer_lens = if variadic { + let variadic_buffer_lens: Cow<'_, [i64]> = if variadic { // Each views array has 1 (optional) null buffer, 1 views buffer, 1 lengths buffer. // Rest are variadic. let num_variadic_buffers = self.array.num_buffers() - (2 + usize::from(can_contain_null_mask)); + // the pointer may not be aligned for `i64`, as `consume` aligns buffers only later. + #[expect(clippy::cast_ptr_alignment)] + let lengths = self + .array + .buffer(self.array.num_buffers() - 1) + .cast::<i64>(); if num_variadic_buffers == 0 { - &[] + // the lengths buffer may be null when there are no variadic buffers. + Cow::Borrowed(&[]) + } else if lengths.is_aligned() { + // SAFETY: lengths is non-null, aligned and valid for up to num_variadic_buffers. + Cow::Borrowed(unsafe { std::slice::from_raw_parts(lengths, num_variadic_buffers) }) } else { - let lengths = self.array.buffer(self.array.num_buffers() - 1); - // SAFETY: is lengths is non-null, then it must be valid for up to num_variadic_buffers. - // The C data interface requires buffers to be aligned for their type. - #[expect( - clippy::cast_ptr_alignment, - reason = "the C data interface requires aligned buffers" - )] - unsafe { - std::slice::from_raw_parts(lengths.cast::<i64>(), num_variadic_buffers) - } + // SAFETY: lengths is non-null and valid for up to num_variadic_buffers. + Cow::Owned( + (0..num_variadic_buffers) + .map(|i| unsafe { lengths.add(i).read_unaligned() }) + .collect(), + ) } } else { - &[] + Cow::Borrowed(&[]) }; (buffer_begin..buffer_end) .map(|index| { - let len = self.buffer_len(index, variadic_buffer_lens, &self.data_type)?; + let len = self.buffer_len(index, &variadic_buffer_lens, &self.data_type)?; match unsafe { create_buffer(self.owner.clone(), self.array, index, len) } { Some(buf) => { // External libraries may use a dangling pointer for a buffer with length 0. @@ -487,13 +493,17 @@ impl ImportedArrowArray<'_> { // the len of the data buffer (buffer 2) equals the last value of the offset buffer (buffer 1) let len = self.buffer_len(1, variadic_buffer_lengths, dt)?; // first buffer is the null buffer => add(1) - // we assume that pointer is aligned for `i32`, as Utf8 uses `i32` offsets. + // the pointer may not be aligned for `i32`, as `consume` aligns buffers only later. #[expect(clippy::cast_ptr_alignment)] let offset_buffer = self.array.buffer(1).cast::<i32>(); // Safety: `len` is the byte length of the offset buffer; dividing by `size_of::<i32>()` // gives the number of i32 elements. The `- 1` is safe because the offset buffer // is always non-empty. - (unsafe { *offset_buffer.add(len / size_of::<i32>() - 1) }) as usize + (unsafe { + offset_buffer + .add(len / size_of::<i32>() - 1) + .read_unaligned() + }) as usize } (DataType::LargeUtf8 | DataType::LargeBinary, 2) => { // See the note on the `Utf8` / `Binary` arm above. @@ -504,11 +514,15 @@ impl ImportedArrowArray<'_> { // the len of the data buffer (buffer 2) equals the last value of the offset buffer (buffer 1) let len = self.buffer_len(1, variadic_buffer_lengths, dt)?; // first buffer is the null buffer => add(1) - // we assume that pointer is aligned for `i64`, as Large uses `i64` offsets. + // the pointer may not be aligned for `i64`, as `consume` aligns buffers only later. #[expect(clippy::cast_ptr_alignment)] let offset_buffer = self.array.buffer(1).cast::<i64>(); // Safety: same as the i32 case above but for i64 offsets. - (unsafe { *offset_buffer.add(len / size_of::<i64>() - 1) }) as usize + (unsafe { + offset_buffer + .add(len / size_of::<i64>() - 1) + .read_unaligned() + }) as usize } // View types: these have variadic buffers. // Buffer 1 is the views buffer, which stores 1 u128 per length of the array. @@ -1767,6 +1781,125 @@ mod tests_from_ffi { Ok(()) } + /// The C layout of `FFI_ArrowArray`, filled in by hand as a C producer would. + #[repr(C)] + struct RawArrowArray { + length: i64, + null_count: i64, + offset: i64, + n_buffers: i64, + n_children: i64, + buffers: *mut *const std::ffi::c_void, + children: *mut *mut RawArrowArray, + dictionary: *mut RawArrowArray, + release: Option<unsafe extern "C" fn(arg1: *mut FFI_ArrowArray)>, + private_data: *mut std::ffi::c_void, + } + + /// The buffers belong to the test, so release only marks the array released. + unsafe extern "C" fn release_raw(array: *mut FFI_ArrowArray) { + unsafe { (*array).set_release(None) }; + } + + /// Imports `data` from a hand-built C array of `buffers`, which must outlive the result. + fn import_raw(data: &ArrayData, buffers: &mut [*const std::ffi::c_void]) -> Result<ArrayData> { + let mut raw = RawArrowArray { + length: data.len() as i64, + null_count: 0, + offset: 0, + n_buffers: buffers.len() as i64, + n_children: 0, + buffers: buffers.as_mut_ptr(), + children: std::ptr::null_mut(), + dictionary: std::ptr::null_mut(), + release: Some(release_raw), + private_data: std::ptr::null_mut(), + }; + let array = unsafe { FFI_ArrowArray::from_raw((&raw mut raw).cast()) }; + let schema = FFI_ArrowSchema::try_from(data.data_type())?; + unsafe { from_ffi(array, &schema) } + } + + /// Offsets that a producer stores at an address not aligned for their type must + /// import, as the C data interface only recommends alignment. + /// + /// <https://github.com/apache/arrow-rs/issues/7136> + #[test] + #[cfg(not(feature = "force_validate"))] + fn test_bytes_with_unaligned_offsets() -> Result<()> { + let arrays: [ArrayRef; 4] = [ + Arc::new(StringArray::from(vec!["a", "bb", "ccc"])), + Arc::new(BinaryArray::from(vec![b"a".as_ref(), b"bb", b"ccc"])), + Arc::new(LargeStringArray::from(vec!["a", "bb", "ccc"])), + Arc::new(LargeBinaryArray::from(vec![b"a".as_ref(), b"bb", b"ccc"])), + ]; + for array in arrays { + let data = array.to_data(); + // The same offsets, one byte past an aligned address. + let mut offsets = arrow_buffer::MutableBuffer::from_len_zeroed(1); + offsets.extend_from_slice(data.buffers()[0].as_slice()); + let offsets = Buffer::from(offsets).slice(1); + assert_ne!(offsets.as_ptr().align_offset(4), 0); + + // SAFETY: the offsets are valid, only not aligned for their type. + let unaligned = unsafe { + data.clone() + .into_builder() + .buffers(vec![offsets, data.buffers()[1].clone()]) + .build_unchecked() + }; + let (array, schema) = to_ffi(&unaligned)?; + let imported = unsafe { from_ffi(array, &schema) }?; + + imported.validate_full()?; + assert_eq!(imported, data); + } + + Ok(()) + } + + /// Like offsets, the variadic buffer lengths of a view array may be stored at an + /// address not aligned for `i64`. + /// + /// <https://github.com/apache/arrow-rs/issues/7136> + #[test] + fn test_views_with_unaligned_variadic_buffer_lengths() -> Result<()> { + // Values longer than 12 bytes live in the data buffers, and a 16 byte block + // holds only one of them, so each array has three data buffers. + let values = ["first long value", "second long one", "third long value"]; + let mut strings = GenericByteViewBuilder::<StringViewType>::new().with_fixed_block_size(16); + let mut binaries = + GenericByteViewBuilder::<BinaryViewType>::new().with_fixed_block_size(16); + for value in values { + strings.append_value(value); + binaries.append_value(value.as_bytes()); + } + let arrays: [ArrayRef; 2] = [Arc::new(strings.finish()), Arc::new(binaries.finish())]; + + for array in arrays { + let data = array.to_data(); + assert_eq!(data.buffers().len(), 4); + // The same lengths `FFI_ArrowArray::new` exports, one byte past an aligned address. + let mut lengths = arrow_buffer::MutableBuffer::from_len_zeroed(1); + for buffer in &data.buffers()[1..] { + lengths.extend_from_slice(&(buffer.len() as i64).to_ne_bytes()); + } + let lengths = &lengths[1..]; + assert_ne!(lengths.as_ptr().align_offset(8), 0); + + let mut buffers = std::iter::once(std::ptr::null()) + .chain(data.buffers().iter().map(|b| b.as_ptr().cast())) + .chain(std::iter::once(lengths.as_ptr().cast())) + .collect::<Vec<_>>(); + let imported = import_raw(&data, &mut buffers)?; + + imported.validate_full()?; + assert_eq!(imported, data); + } + + Ok(()) + } + /// Unlike bytes, the values of lists and maps are a child array imported with its /// own length, so the lone offset of an empty slice stays within it. #[test]
