1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use smallvec::SmallVec;

use rustc_middle::mir::interpret::{AllocId, AllocRange};
use rustc_span::{Span, SpanData};
use rustc_target::abi::Size;

use crate::helpers::CurrentSpan;
use crate::stacked_borrows::{err_sb_ub, AccessKind};
use crate::*;

use rustc_middle::mir::interpret::InterpError;

#[derive(Clone, Debug)]
pub struct AllocHistory {
    // The time tags can be compressed down to one bit per event, by just storing a Vec<u8>
    // where each bit is set to indicate if the event was a creation or a retag
    current_time: usize,
    creations: smallvec::SmallVec<[Event; 2]>,
    invalidations: smallvec::SmallVec<[Event; 1]>,
    protectors: smallvec::SmallVec<[Protection; 1]>,
}

#[derive(Clone, Debug)]
struct Protection {
    orig_tag: SbTag,
    tag: SbTag,
    span: Span,
}

#[derive(Clone, Debug)]
struct Event {
    parent: Option<SbTag>,
    tag: SbTag,
    range: AllocRange,
    span: Span,
}

pub enum TagHistory {
    Tagged {
        tag: SbTag,
        created: (AllocRange, SpanData),
        invalidated: Option<(AllocRange, SpanData)>,
        protected: Option<(SbTag, SpanData, SpanData)>,
    },
}

impl AllocHistory {
    pub fn new() -> Self {
        Self {
            current_time: 0,
            creations: SmallVec::new(),
            invalidations: SmallVec::new(),
            protectors: SmallVec::new(),
        }
    }

    pub fn log_creation(
        &mut self,
        parent: Option<SbTag>,
        tag: SbTag,
        range: AllocRange,
        current_span: &mut CurrentSpan<'_, '_, '_>,
    ) {
        let span = current_span.get();
        self.creations.push(Event { parent, tag, range, span });
        self.current_time += 1;
    }

    pub fn log_invalidation(
        &mut self,
        tag: SbTag,
        range: AllocRange,
        current_span: &mut CurrentSpan<'_, '_, '_>,
    ) {
        let span = current_span.get();
        self.invalidations.push(Event { parent: None, tag, range, span });
        self.current_time += 1;
    }

    pub fn log_protector(
        &mut self,
        orig_tag: SbTag,
        tag: SbTag,
        current_span: &mut CurrentSpan<'_, '_, '_>,
    ) {
        let span = current_span.get();
        self.protectors.push(Protection { orig_tag, tag, span });
        self.current_time += 1;
    }

    pub fn get_logs_relevant_to(
        &self,
        tag: SbTag,
        protector_tag: Option<SbTag>,
    ) -> Option<TagHistory> {
        let protected = protector_tag
            .and_then(|protector| {
                self.protectors.iter().find_map(|protection| {
                    if protection.tag == protector {
                        Some((protection.orig_tag, protection.span.data()))
                    } else {
                        None
                    }
                })
            })
            .and_then(|(tag, call_span)| {
                self.creations.iter().rev().find_map(|event| {
                    if event.tag == tag {
                        Some((event.parent?, event.span.data(), call_span))
                    } else {
                        None
                    }
                })
            });

        let get_matching = |events: &[Event]| {
            events.iter().rev().find_map(|event| {
                if event.tag == tag { Some((event.range, event.span.data())) } else { None }
            })
        };
        Some(TagHistory::Tagged {
            tag,
            created: get_matching(&self.creations)?,
            invalidated: get_matching(&self.invalidations),
            protected,
        })
    }

    /// Report a descriptive error when `new` could not be granted from `derived_from`.
    pub fn grant_error<'tcx>(
        &self,
        derived_from: ProvenanceExtra,
        new: Item,
        alloc_id: AllocId,
        alloc_range: AllocRange,
        error_offset: Size,
        stack: &Stack,
    ) -> InterpError<'tcx> {
        let action = format!(
            "trying to reborrow from {derived_from:?} for {new_perm:?} permission at {alloc_id:?}[{offset:#x}]",
            new_perm = new.perm(),
            offset = error_offset.bytes(),
        );
        err_sb_ub(
            format!("{}{}", action, error_cause(stack, derived_from)),
            Some(operation_summary("a reborrow", alloc_id, alloc_range)),
            derived_from.and_then(|derived_from| self.get_logs_relevant_to(derived_from, None)),
        )
    }

    /// Report a descriptive error when `access` is not permitted based on `tag`.
    pub fn access_error<'tcx>(
        &self,
        access: AccessKind,
        tag: ProvenanceExtra,
        alloc_id: AllocId,
        alloc_range: AllocRange,
        error_offset: Size,
        stack: &Stack,
    ) -> InterpError<'tcx> {
        let action = format!(
            "attempting a {access} using {tag:?} at {alloc_id:?}[{offset:#x}]",
            offset = error_offset.bytes(),
        );
        err_sb_ub(
            format!("{}{}", action, error_cause(stack, tag)),
            Some(operation_summary("an access", alloc_id, alloc_range)),
            tag.and_then(|tag| self.get_logs_relevant_to(tag, None)),
        )
    }
}

fn operation_summary(
    operation: &'static str,
    alloc_id: AllocId,
    alloc_range: AllocRange,
) -> String {
    format!("this error occurs as part of {operation} at {alloc_id:?}{alloc_range:?}")
}

fn error_cause(stack: &Stack, prov_extra: ProvenanceExtra) -> &'static str {
    if let ProvenanceExtra::Concrete(tag) = prov_extra {
        if (0..stack.len())
            .map(|i| stack.get(i).unwrap())
            .any(|item| item.tag() == tag && item.perm() != Permission::Disabled)
        {
            ", but that tag only grants SharedReadOnly permission for this location"
        } else {
            ", but that tag does not exist in the borrow stack for this location"
        }
    } else {
        ", but no exposed tags have suitable permission in the borrow stack for this location"
    }
}