Skip to content

Commit 6587eea

Browse files
committed
Properly track safety invariants
1 parent 17a81c7 commit 6587eea

File tree

4 files changed

+91
-33
lines changed

4 files changed

+91
-33
lines changed

gix-pack/src/cache/delta/mod.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ pub struct Item<T> {
3232
/// Indices into our Tree's `items`, one for each pack entry that depends on us.
3333
///
3434
/// Limited to u32 as that's the maximum amount of objects in a pack.
35+
// SAFETY INVARIANT:
36+
// - only one Item in a tree may have any given child index. `future_child_offsets`
37+
// should also not contain any indices found in `children`.\
38+
// - These indices should be in bounds for tree.child_items
3539
children: Vec<u32>,
3640
}
3741

@@ -46,13 +50,20 @@ enum NodeKind {
4650
/// It does this by making the guarantee that iteration only happens once.
4751
pub struct Tree<T> {
4852
/// The root nodes, i.e. base objects
53+
// SAFETY invariant: see Item.children
4954
root_items: Vec<Item<T>>,
5055
/// The child nodes, i.e. those that rely a base object, like ref and ofs delta objects
56+
// SAFETY invariant: see Item.children
5157
child_items: Vec<Item<T>>,
5258
/// The last encountered node was either a root or a child.
5359
last_seen: Option<NodeKind>,
5460
/// Future child offsets, associating their offset into the pack with their index in the items array.
5561
/// (parent_offset, child_index)
62+
// SAFETY invariant:
63+
// - None of these child indices should already have parents
64+
// i.e. future_child_offsets[i].1 should never be also found
65+
// in Item.children. Indices should be found here at most once.
66+
// - These indices should be in bounds for tree.child_items.
5667
future_child_offsets: Vec<(crate::data::Offset, usize)>,
5768
}
5869

@@ -94,6 +105,12 @@ impl<T> Tree<T> {
94105
) -> Result<(), traverse::Error> {
95106
if !self.future_child_offsets.is_empty() {
96107
for (parent_offset, child_index) in self.future_child_offsets.drain(..) {
108+
// SAFETY invariants upheld:
109+
// - We are draining from future_child_offsets and adding to children, keeping things the same.
110+
// - We can rely on the `future_child_offsets` invariant to be sure that `children` is
111+
// not getting any indices that are already in use in `children` elsewhere
112+
// - The indices are in bounds for child_items since they were in bounds for future_child_offsets,
113+
// we can carry over the invariant.
97114
if let Ok(i) = self.child_items.binary_search_by_key(&parent_offset, |i| i.offset) {
98115
self.child_items[i].children.push(child_index as u32);
99116
} else if let Ok(i) = self.root_items.binary_search_by_key(&parent_offset, |i| i.offset) {
@@ -120,6 +137,7 @@ impl<T> Tree<T> {
120137
offset,
121138
next_offset: 0,
122139
data,
140+
// SAFETY INVARIANT upheld: there are no children
123141
children: Default::default(),
124142
});
125143
Ok(())
@@ -135,6 +153,19 @@ impl<T> Tree<T> {
135153
self.assert_is_incrementing_and_update_next_offset(offset)?;
136154

137155
let next_child_index = self.child_items.len();
156+
// SAFETY INVARIANT upheld:
157+
// - This is one of two methods that modifies `children` and future_child_offsets. Out
158+
// of the two, it is the only one that produces new indices in the system.
159+
// - This always pushes next_child_index to *either* `children` or `future_child_offsets`,
160+
// maintaining the cross-field invariant there.
161+
// - This method will always push to child_items (at the end), incrementing
162+
// future values of next_child_index. This means next_child_index is always
163+
// unique for this method call.
164+
// - As the only method producing new indices, this is the only time
165+
// next_child_index will be added to children/future_child_offsets, upholding the invariant.
166+
// - Since next_child_index will always be a valid index by the end of this method,
167+
// this always produces valid in-bounds indices, upholding the bounds invariant.
168+
138169
if let Ok(i) = self.child_items.binary_search_by_key(&base_offset, |i| i.offset) {
139170
self.child_items[i].children.push(next_child_index as u32);
140171
} else if let Ok(i) = self.root_items.binary_search_by_key(&base_offset, |i| i.offset) {
@@ -148,6 +179,7 @@ impl<T> Tree<T> {
148179
offset,
149180
next_offset: 0,
150181
data,
182+
// SAFETY INVARIANT upheld: there are no children
151183
children: Default::default(),
152184
});
153185
Ok(())

gix-pack/src/cache/delta/traverse/mod.rs

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -154,16 +154,22 @@ where
154154
},
155155
{
156156
move |node, state, threads_left, should_interrupt| {
157-
resolve::deltas(
158-
object_counter.clone(),
159-
size_counter.clone(),
160-
node,
161-
state,
162-
resolve_data,
163-
object_hash.len_in_bytes(),
164-
threads_left,
165-
should_interrupt,
166-
)
157+
// SAFETY: This invariant is upheld since `child_items` and `node` come from the same Tree.
158+
// This means we can rely on Tree's invariant that node.children will be the only `children` array in
159+
// for nodes in this tree that will contain any of those children.
160+
#[allow(unsafe_code)]
161+
unsafe {
162+
resolve::deltas(
163+
object_counter.clone(),
164+
size_counter.clone(),
165+
node,
166+
state,
167+
resolve_data,
168+
object_hash.len_in_bytes(),
169+
threads_left,
170+
should_interrupt,
171+
)
172+
}
167173
}
168174
},
169175
|| (!should_interrupt.load(Ordering::Relaxed)).then(|| std::time::Duration::from_millis(50)),

gix-pack/src/cache/delta/traverse/resolve.rs

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,25 @@ mod root {
1919

2020
/// An item returned by `iter_root_chunks`, allowing access to the `data` stored alongside nodes in a [`Tree`].
2121
pub(crate) struct Node<'a, T: Send> {
22+
// SAFETY INVARIANT: see Node::new(). That function is the only one used
23+
// to create or modify these fields.
2224
item: &'a mut Item<T>,
2325
child_items: &'a ItemSliceSync<'a, Item<T>>,
2426
}
2527

2628
impl<'a, T: Send> Node<'a, T> {
27-
/// SAFETY: The child_items must be unique among between users of the `ItemSliceSync`.
29+
/// SAFETY: `item.children` must uniquely reference elements in child_items that no other currently alive
30+
/// item does. All child_items must also have unique children, unless the child_item is itself `item`,
31+
/// in which case no other live item should reference it in its `item.children`.
32+
///
33+
/// This safety invariant can be reliably upheld by making sure `item` comes from a Tree and `child_items`
34+
/// was constructed using that Tree's child_items. This works since Tree has this invariant as well: all
35+
/// child_items are referenced at most once (really, exactly once) by a node in the tree.
36+
///
37+
/// Note that this invariant is a bit more relaxed than that on `deltas()`, because this function can be called
38+
/// for traversal within a child item, which happens in into_child_iter()
2839
#[allow(unsafe_code)]
29-
pub(in crate::cache::delta::traverse) unsafe fn new(
30-
item: &'a mut Item<T>,
31-
child_items: &'a ItemSliceSync<'a, Item<T>>,
32-
) -> Self {
40+
pub(super) unsafe fn new(item: &'a mut Item<T>, child_items: &'a ItemSliceSync<'a, Item<T>>) -> Self {
3341
Node { item, child_items }
3442
}
3543
}
@@ -60,18 +68,20 @@ mod root {
6068
/// Children are `Node`s referring to pack entries whose base object is this pack entry.
6169
pub fn into_child_iter(self) -> impl Iterator<Item = Node<'a, T>> + 'a {
6270
let children = self.child_items;
63-
// SAFETY: The index is a valid index into the children array.
64-
// SAFETY: The resulting mutable pointer cannot be yielded by any other node.
6571
#[allow(unsafe_code)]
66-
self.item.children.iter().map(move |&index| Node {
67-
item: unsafe { children.get_mut(index as usize) },
68-
child_items: children,
72+
self.item.children.iter().map(move |&index| {
73+
// SAFETY: Due to the invariant on new(), we can rely on these indices
74+
// being unique.
75+
let item = unsafe { children.get_mut(index as usize) };
76+
// SAFETY: Since every child_item is also required to uphold the uniqueness guarantee,
77+
// creating a Node with one of the child_items that we are allowed access to is still fine.
78+
unsafe { Node::new(item, children) }
6979
})
7080
}
7181
}
7282
}
7383

74-
pub(in crate::cache::delta::traverse) struct State<'items, F, MBFN, T: Send> {
84+
pub(super) struct State<'items, F, MBFN, T: Send> {
7585
pub delta_bytes: Vec<u8>,
7686
pub fully_resolved_delta_bytes: Vec<u8>,
7787
pub progress: Box<dyn Progress>,
@@ -80,8 +90,15 @@ pub(in crate::cache::delta::traverse) struct State<'items, F, MBFN, T: Send> {
8090
pub child_items: &'items ItemSliceSync<'items, Item<T>>,
8191
}
8292

83-
#[allow(clippy::too_many_arguments)]
84-
pub(in crate::cache::delta::traverse) fn deltas<T, F, MBFN, E, R>(
93+
/// SAFETY: `item.children` must uniquely reference elements in child_items that no other currently alive
94+
/// item does. All child_items must also have unique children.
95+
///
96+
/// This safety invariant can be reliably upheld by making sure `item` comes from a Tree and `child_items`
97+
/// was constructed using that Tree's child_items. This works since Tree has this invariant as well: all
98+
/// child_items are referenced at most once (really, exactly once) by a node in the tree.
99+
#[allow(clippy::too_many_arguments, unsafe_code)]
100+
#[deny(unsafe_op_in_unsafe_fn)] // this is a big function, require unsafe for the one small unsafe op we have
101+
pub(super) unsafe fn deltas<T, F, MBFN, E, R>(
85102
objects: gix_features::progress::StepShared,
86103
size: gix_features::progress::StepShared,
87104
item: &mut Item<T>,
@@ -121,7 +138,7 @@ where
121138
// each node is a base, and its children always start out as deltas which become a base after applying them.
122139
// These will be pushed onto our stack until all are processed
123140
let root_level = 0;
124-
// SAFETY: The child items are unique, as `item` is the root of a tree of dependent child items.
141+
// SAFETY: This invariant is required from the caller
125142
#[allow(unsafe_code)]
126143
let root_node = unsafe { root::Node::new(item, child_items) };
127144
let mut nodes: Vec<_> = vec![(root_level, root_node)];

gix-pack/src/cache/delta/traverse/util.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,21 +16,21 @@ use std::marker::PhantomData;
1616
/// more than one base. And that's what one would really have to do for two threads to encounter the same child.
1717
///
1818
/// Thus I believe it's impossible for this data structure to end up in a place where it violates its assumption.
19-
pub(in crate::cache::delta::traverse) struct ItemSliceSync<'a, T>
19+
pub(super) struct ItemSliceSync<'a, T>
2020
where
2121
T: Send,
2222
{
2323
items: *mut T,
2424
#[cfg(debug_assertions)]
2525
len: usize,
26-
phantom: PhantomData<&'a T>,
26+
phantom: PhantomData<&'a mut T>,
2727
}
2828

2929
impl<'a, T> ItemSliceSync<'a, T>
3030
where
3131
T: Send,
3232
{
33-
pub(in crate::cache::delta::traverse) fn new(items: &'a mut [T]) -> Self {
33+
pub(super) fn new(items: &'a mut [T]) -> Self {
3434
ItemSliceSync {
3535
items: items.as_mut_ptr(),
3636
#[cfg(debug_assertions)]
@@ -41,21 +41,24 @@ where
4141

4242
// SAFETY: The index must point into the slice and must not be reused concurrently.
4343
#[allow(unsafe_code)]
44-
pub(in crate::cache::delta::traverse) unsafe fn get_mut(&self, index: usize) -> &'a mut T {
44+
pub(super) unsafe fn get_mut(&self, index: usize) -> &'a mut T {
4545
#[cfg(debug_assertions)]
4646
if index >= self.len {
4747
panic!("index out of bounds: the len is {} but the index is {index}", self.len);
4848
}
49-
// SAFETY: The index is within the slice
50-
// SAFETY: The children array is alive by the 'a lifetime.
49+
// SAFETY:
50+
// - The index is within the slice (required by documentation)
51+
// - We have mutable access to `items` as ensured by Self::new()
52+
// - This is the only method on this type giving access to items
53+
// - The documentation requires that this access is unique
5154
unsafe { &mut *self.items.add(index) }
5255
}
5356
}
5457

55-
// SAFETY: T is `Send`, and we only use the pointer for creating new pointers.
58+
// SAFETY: This is logically an &mut T, which is Send if T is Send
59+
// (note: this is different from &T, which also needs T: Sync)
5660
#[allow(unsafe_code)]
5761
unsafe impl<T> Send for ItemSliceSync<'_, T> where T: Send {}
58-
// SAFETY: T is `Send`, and as long as the user follows the contract of
59-
// `get_mut()`, we only ever access one T at a time.
62+
// SAFETY: This is logically an &mut T, which is Sync if T is Sync
6063
#[allow(unsafe_code)]
6164
unsafe impl<T> Sync for ItemSliceSync<'_, T> where T: Send {}

0 commit comments

Comments
 (0)