Skip to content

Commit

Permalink
Ensure all ordertree nodes share an alignment
Browse files Browse the repository at this point in the history
Otherwise casting local variables of type AnyNode can fail (because the
target type's alignment may be larger than AnyNode's)
  • Loading branch information
ckamm committed Apr 29, 2024
1 parent 8928d4c commit e666f5b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
14 changes: 11 additions & 3 deletions programs/openbook-v2/src/state/orderbook/nodes.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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::<FreeNode>(), NODE_SIZE);
const_assert_eq!(size_of::<FreeNode>() % 8, 0);
Expand All @@ -250,13 +252,19 @@ const_assert_eq!(size_of::<FreeNode>() % 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::<AnyNode>(), NODE_SIZE);
const_assert_eq!(size_of::<AnyNode>() % 8, 0);
const_assert_eq!(align_of::<AnyNode>(), 8);
const_assert_eq!(size_of::<AnyNode>(), size_of::<InnerNode>());
const_assert_eq!(align_of::<AnyNode>(), align_of::<InnerNode>());
const_assert_eq!(size_of::<AnyNode>(), size_of::<LeafNode>());
const_assert_eq!(align_of::<AnyNode>(), align_of::<LeafNode>());
const_assert_eq!(size_of::<AnyNode>(), size_of::<FreeNode>());
const_assert_eq!(align_of::<AnyNode>(), align_of::<FreeNode>());

pub(crate) enum NodeRef<'a> {
Inner(&'a InnerNode),
Expand Down
3 changes: 2 additions & 1 deletion programs/openbook-v2/src/state/orderbook/ordertree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit e666f5b

Please sign in to comment.