From e666f5ba337586fef395c83c447faa5d3880d8b6 Mon Sep 17 00:00:00 2001 From: Christian Kamm Date: Mon, 29 Apr 2024 16:23:34 +0200 Subject: [PATCH] Ensure all ordertree nodes share an alignment Otherwise casting local variables of type AnyNode can fail (because the target type's alignment may be larger than AnyNode's) --- programs/openbook-v2/src/state/orderbook/nodes.rs | 14 +++++++++++--- .../openbook-v2/src/state/orderbook/ordertree.rs | 3 ++- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/programs/openbook-v2/src/state/orderbook/nodes.rs b/programs/openbook-v2/src/state/orderbook/nodes.rs index 748e763d9..08ef8d8e3 100644 --- a/programs/openbook-v2/src/state/orderbook/nodes.rs +++ b/programs/openbook-v2/src/state/orderbook/nodes.rs @@ -1,4 +1,4 @@ -use std::mem::size_of; +use std::mem::{align_of, size_of}; use anchor_lang::prelude::*; use bytemuck::{cast_mut, cast_ref}; @@ -241,7 +241,9 @@ pub struct FreeNode { pub(crate) tag: u8, // NodeTag pub(crate) padding: [u8; 3], pub(crate) next: NodeHandle, - pub(crate) reserved: [u8; NODE_SIZE - 8], + pub(crate) reserved: [u8; NODE_SIZE - 16], + // essential to make AnyNode alignment the same as other node types + pub(crate) force_align: u64, } const_assert_eq!(size_of::(), NODE_SIZE); const_assert_eq!(size_of::() % 8, 0); @@ -250,13 +252,19 @@ const_assert_eq!(size_of::() % 8, 0); #[derive(bytemuck::Pod, bytemuck::Zeroable)] pub struct AnyNode { pub tag: u8, - pub data: [u8; 87], + pub data: [u8; 79], + // essential to make AnyNode alignment the same as other node types + pub force_align: u64, } const_assert_eq!(size_of::(), NODE_SIZE); const_assert_eq!(size_of::() % 8, 0); +const_assert_eq!(align_of::(), 8); const_assert_eq!(size_of::(), size_of::()); +const_assert_eq!(align_of::(), align_of::()); const_assert_eq!(size_of::(), size_of::()); +const_assert_eq!(align_of::(), align_of::()); const_assert_eq!(size_of::(), size_of::()); +const_assert_eq!(align_of::(), align_of::()); pub(crate) enum NodeRef<'a> { Inner(&'a InnerNode), diff --git a/programs/openbook-v2/src/state/orderbook/ordertree.rs b/programs/openbook-v2/src/state/orderbook/ordertree.rs index 41096b996..75c475cd3 100644 --- a/programs/openbook-v2/src/state/orderbook/ordertree.rs +++ b/programs/openbook-v2/src/state/orderbook/ordertree.rs @@ -264,7 +264,8 @@ impl OrderTreeNodes { }, padding: Default::default(), next: self.free_list_head, - reserved: [0; 80], + reserved: [0; 72], + force_align: 0, }); self.free_list_len += 1;