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
use super::*;

impl<T: RegisterDomain> SizedDomain for DataDomain<T> {
    /// Return the bytesize of `self`.
    fn bytesize(&self) -> ByteSize {
        self.size
    }

    /// Return a new *Top* element with the given bytesize.
    ///
    /// Note that `DataDomain` technically does not have a `Top` element with respect to the partial order.
    /// Instead a `Top` element here represents a non-empty value
    /// for which nothing is known about the contained values.
    fn new_top(bytesize: ByteSize) -> Self {
        DataDomain {
            size: bytesize,
            relative_values: BTreeMap::new(),
            absolute_value: None,
            contains_top_values: true,
        }
    }
}

impl<T: RegisterDomain> HasTop for DataDomain<T> {
    /// Generate a new *Top* element with the same bytesize as `self`.
    fn top(&self) -> Self {
        DataDomain::new_top(self.bytesize())
    }
}

impl<T: RegisterDomain> AbstractDomain for DataDomain<T> {
    // Merge `self` with `other`.
    fn merge(&self, other: &Self) -> Self {
        let mut relative_values = self.relative_values.clone();
        for (id, offset_other) in other.relative_values.iter() {
            relative_values
                .entry(id.clone())
                .and_modify(|offset| *offset = offset.merge(offset_other))
                .or_insert_with(|| offset_other.clone());
        }
        let absolute_value = match (&self.absolute_value, &other.absolute_value) {
            (Some(left), Some(right)) => Some(left.merge(right)),
            (Some(val), None) | (None, Some(val)) => Some(val.clone()),
            (None, None) => None,
        };
        DataDomain {
            size: self.bytesize(),
            relative_values,
            absolute_value,
            contains_top_values: self.contains_top_values || other.contains_top_values,
        }
    }

    /// Return whether the element represents a top element or not.
    ///
    /// Note that `DataDomain` technically does not have a `Top` element with respect to the partial order.
    /// Instead a `Top` element here represents a non-empty value
    /// for which nothing is known about the contained values.
    fn is_top(&self) -> bool {
        self.relative_values.is_empty() && self.absolute_value.is_none() && self.contains_top_values
    }
}

impl<T: RegisterDomain> From<T> for DataDomain<T> {
    fn from(value: T) -> Self {
        Self {
            size: value.bytesize(),
            relative_values: BTreeMap::new(),
            absolute_value: Some(value),
            contains_top_values: false,
        }
    }
}

impl<T: RegisterDomain + From<Bitvector>> From<Bitvector> for DataDomain<T> {
    fn from(bitvector: Bitvector) -> Self {
        let val: T = bitvector.into();
        val.into()
    }
}

impl<T: RegisterDomain + TryToBitvec> TryToBitvec for DataDomain<T> {
    /// If the domain represents a single, absolute value, return it.
    fn try_to_bitvec(&self) -> Result<Bitvector, Error> {
        if !self.relative_values.is_empty() || self.contains_top_values {
            Err(anyhow!("May contain non-absolute values."))
        } else if let Some(val) = &self.absolute_value {
            val.try_to_bitvec()
        } else {
            Err(anyhow!("Domain is empty."))
        }
    }
}

impl<T: RegisterDomain + TryToInterval> TryToInterval for DataDomain<T> {
    /// If the domain represents (or can be widened to) an interval of absolute values, return the interval.
    fn try_to_interval(&self) -> Result<Interval, Error> {
        if !self.relative_values.is_empty() || self.contains_top_values {
            Err(anyhow!("May contain non-absolute values."))
        } else if let Some(val) = &self.absolute_value {
            val.try_to_interval()
        } else {
            Err(anyhow!("Domain is empty."))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::super::*;
    use super::*;
    use crate::{abstract_domain::*, bitvec, variable};

    type Data = DataDomain<BitvectorDomain>;

    fn bv(value: i64) -> BitvectorDomain {
        BitvectorDomain::Value(bitvec!(format!("{}:8", value)))
    }

    fn new_id(name: &str) -> AbstractIdentifier {
        AbstractIdentifier::new(
            Tid::new("time0"),
            AbstractLocation::Register(variable!(format!("{}:8", name))),
        )
    }

    fn new_pointer(location: &str, offset: i64) -> Data {
        DataDomain {
            size: ByteSize::new(8),
            relative_values: BTreeMap::from_iter([(new_id(location), bv(offset))]),
            absolute_value: None,
            contains_top_values: false,
        }
    }

    fn new_value(value: i64) -> Data {
        Data::from(bv(value))
    }

    #[test]
    fn data_merge() {
        let pointer = new_pointer("RAX".into(), 0);
        let value = new_value(42);
        let merged_data = pointer.merge(&value);
        assert_eq!(pointer.merge(&pointer), pointer);
        assert_eq!(merged_data.relative_values, pointer.relative_values);
        assert_eq!(merged_data.absolute_value, value.absolute_value);

        let other_value = new_value(-1);
        let merged_data = value.merge(&other_value);
        assert!(merged_data.relative_values.is_empty());
        assert_eq!(
            merged_data.absolute_value,
            Some(BitvectorDomain::new_top(ByteSize::new(8)))
        );

        let other_pointer = new_pointer("RBX".into(), 10);
        let merged_data = pointer.merge(&other_pointer);
        assert_eq!(
            merged_data.relative_values.get(&new_id("RAX")),
            Some(&bv(0))
        );
        assert_eq!(
            merged_data.relative_values.get(&new_id("RBX")),
            Some(&bv(10))
        );
    }
}