From 8fa47b811996eae8d04729856b4be9aa5c8fcda4 Mon Sep 17 00:00:00 2001 From: occheung Date: Tue, 24 Aug 2021 17:00:28 +0800 Subject: [PATCH] rpc: enforce alignment --- artiq/firmware/libproto_artiq/rpc_proto.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/artiq/firmware/libproto_artiq/rpc_proto.rs b/artiq/firmware/libproto_artiq/rpc_proto.rs index 5e7b12010..bff4d46b0 100644 --- a/artiq/firmware/libproto_artiq/rpc_proto.rs +++ b/artiq/firmware/libproto_artiq/rpc_proto.rs @@ -5,6 +5,18 @@ use byteorder::{NativeEndian, ByteOrder}; use io::{ProtoRead, Read, Write, ProtoWrite, Error}; use self::tag::{Tag, TagIterator, split_tag}; +unsafe fn align_ptr(ptr: *const ()) -> *const T { + let alignment = core::mem::align_of::() as isize; + let fix = (alignment - (ptr as isize) % alignment) % alignment; + ((ptr as isize) + fix) as *const T +} + +unsafe fn align_ptr_mut(ptr: *mut ()) -> *mut T { + let alignment = core::mem::align_of::() as isize; + let fix = (alignment - (ptr as isize) % alignment) % alignment; + ((ptr as isize) + fix) as *mut T +} + unsafe fn recv_value(reader: &mut R, tag: Tag, data: &mut *mut (), alloc: &Fn(usize) -> Result<*mut (), E>) -> Result<(), E> @@ -13,7 +25,7 @@ unsafe fn recv_value(reader: &mut R, tag: Tag, data: &mut *mut (), { macro_rules! consume_value { ($ty:ty, |$ptr:ident| $map:expr) => ({ - let $ptr = (*data) as *mut $ty; + let $ptr = align_ptr_mut::<$ty>(*data) as *mut $ty; *data = $ptr.offset(1) as *mut (); $map }) @@ -161,7 +173,7 @@ unsafe fn send_value(writer: &mut W, tag: Tag, data: &mut *const ()) { macro_rules! consume_value { ($ty:ty, |$ptr:ident| $map:expr) => ({ - let $ptr = (*data) as *const $ty; + let $ptr = align_ptr::<$ty>(*data); *data = $ptr.offset(1) as *const (); $map })