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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
use memory::{
    allocation::{AllocationError, Length, WasmAllocation},
    MemoryBits, MemoryInt, MEMORY_INT_MAX,
};
use std::convert::TryFrom;

#[derive(Copy, Clone, Default, Debug, PartialEq)]
// pub in crate for testing
pub struct Top(pub(in crate::memory) MemoryInt);

impl From<Top> for MemoryInt {
    fn from(top: Top) -> Self {
        top.0
    }
}

impl From<Top> for usize {
    fn from(top: Top) -> Self {
        MemoryInt::from(top) as usize
    }
}

impl From<Top> for MemoryBits {
    fn from(top: Top) -> Self {
        MemoryBits::from(top.0)
    }
}

#[derive(Copy, Clone, Default, Debug, PartialEq)]
pub struct WasmStack {
    // pub in crate for testing
    pub(in crate::memory) top: Top,
}

impl WasmStack {
    // represent the max as MemoryBits type to allow gt comparisons
    pub fn max() -> MemoryBits {
        MEMORY_INT_MAX
    }

    // min compares lt so can be a MemoryInt
    pub fn min() -> MemoryInt {
        0
    }

    // A stack can be initialized by giving the last know allocation on this stack
    pub fn new() -> WasmStack {
        WasmStack {
            top: Top(WasmStack::min()),
        }
    }

    pub fn next_allocation(self, length: Length) -> Result<WasmAllocation, AllocationError> {
        WasmAllocation::new(MemoryInt::from(self.top()).into(), length)
    }

    pub fn allocate(&mut self, allocation: WasmAllocation) -> Result<Top, AllocationError> {
        if MemoryInt::from(self.top()) != MemoryInt::from(allocation.offset()) {
            Err(AllocationError::BadStackAlignment)
        } else if MemoryBits::from(self.top()) + MemoryBits::from(allocation.length())
            > WasmStack::max()
        {
            Err(AllocationError::OutOfBounds)
        } else {
            // @todo i don't know why we return the old top instead of new one?
            let old_top = self.top;
            self.top =
                Top(MemoryInt::from(allocation.offset()) + MemoryInt::from(allocation.length()));
            Ok(old_top)
        }
    }

    pub fn deallocate(&mut self, allocation: WasmAllocation) -> Result<Top, AllocationError> {
        if MemoryInt::from(self.top())
            != MemoryInt::from(allocation.offset()) + MemoryInt::from(allocation.length())
        {
            Err(AllocationError::BadStackAlignment)
        } else if MemoryInt::from(allocation.offset()) < WasmStack::min() {
            Err(AllocationError::OutOfBounds)
        } else {
            let old_top = self.top;
            self.top = Top(allocation.offset().into());
            Ok(old_top)
        }
    }

    // Getters
    pub fn top(self) -> Top {
        self.top
    }
}

impl TryFrom<WasmAllocation> for WasmStack {
    type Error = AllocationError;
    fn try_from(allocation: WasmAllocation) -> Result<Self, Self::Error> {
        let mut stack = WasmStack {
            top: Top(allocation.offset().into()),
        };
        stack.allocate(allocation)?;
        Ok(stack)
    }
}

#[cfg(test)]
pub mod memory_tests {

    use holochain_core_types::bits_n_pieces::U16_MAX;
    use memory::{
        allocation::{AllocationError, Length, Offset, WasmAllocation},
        stack::{Top, WasmStack},
        MemoryBits, MemoryInt, MEMORY_INT_MAX,
    };
    use std::convert::TryFrom;

    pub fn fake_top() -> Top {
        Top(12345)
    }

    #[test]
    fn memory_int_from_top_test() {
        assert_eq!(12345 as MemoryInt, MemoryInt::from(fake_top()),);
    }

    #[test]
    fn usize_from_top_test() {
        assert_eq!(12345 as usize, usize::from(fake_top()),);
    }

    #[test]
    fn memory_bits_from_top_test() {
        assert_eq!(12345 as MemoryBits, MemoryBits::from(fake_top()),);
    }

    #[test]
    fn stack_max_test() {
        assert_eq!(MEMORY_INT_MAX, WasmStack::max(),);
    }

    #[test]
    fn stack_min_test() {
        assert_eq!(0, WasmStack::min(),);
    }

    #[test]
    fn stack_new_test() {
        assert_eq!(WasmStack { top: Top(0) }, WasmStack::new(),);
    }

    #[test]
    fn next_allocation_test() {
        let mut stack = WasmStack::new();

        let first_offset = Offset::from(0);
        let first_length = Length::from(5);
        let first_allocation = stack.next_allocation(first_length);

        assert_eq!(
            first_allocation,
            WasmAllocation::new(first_offset, first_length),
        );

        stack.allocate(first_allocation.unwrap()).ok();

        let second_offset = Offset::from(5);
        let second_length = Length::from(3);
        let second_allocation = stack.next_allocation(second_length);

        assert_eq!(
            second_allocation,
            WasmAllocation::new(second_offset, second_length),
        );

        stack.allocate(second_allocation.unwrap()).ok();

        let big_offset = Offset::from(8);
        let big_length = Length::from(U16_MAX * 2);

        assert_eq!(
            stack.next_allocation(big_length),
            WasmAllocation::new(big_offset, big_length),
        );
    }

    #[test]
    fn allocate_test() {
        let mut stack = WasmStack::new();
        let unaligned_allocation = WasmAllocation::new(Offset::from(10), Length::from(10)).unwrap();

        assert_eq!(
            Err(AllocationError::BadStackAlignment),
            stack.allocate(unaligned_allocation),
        );

        let first_allocation = stack.next_allocation(Length::from(5));
        stack.allocate(first_allocation.unwrap()).ok();

        let second_allocation = stack.next_allocation(Length::from(8));

        assert_eq!(stack.allocate(second_allocation.unwrap()), Ok(Top(5)),);
        assert_eq!(stack.top(), Top(13),);

        let out_of_bounds_allocation = WasmAllocation {
            offset: Offset::from(13),
            length: Length::from(std::u32::MAX),
        };

        assert_eq!(
            Err(AllocationError::OutOfBounds),
            stack.allocate(out_of_bounds_allocation),
        );

        let big_allocation = stack.next_allocation(Length::from(U16_MAX)).unwrap();
        assert_eq!(stack.allocate(big_allocation), Ok(Top(13)),);
        assert_eq!(stack.top(), Top(U16_MAX + 13),);
    }

    #[test]
    fn deallocate_test() {
        let mut stack = WasmStack { top: Top(50) };
        let unaligned_allocation = WasmAllocation::new(Offset::from(50), Length::from(5)).unwrap();
        assert_eq!(
            Err(AllocationError::BadStackAlignment),
            stack.deallocate(unaligned_allocation),
        );

        // can't test out of bounds for deallocate because unsigned integers don't go below min

        let deallocation = WasmAllocation::new(Offset::from(20), Length::from(30)).unwrap();
        assert_eq!(stack.deallocate(deallocation), Ok(Top(50)),);
        assert_eq!(stack.top(), Top(20),);
    }

    #[test]
    fn top_test() {
        let top = Top(123);
        let stack = WasmStack { top };
        assert_eq!(top, stack.top(),);
    }

    #[test]
    fn try_stack_from_allocation_test() {
        // can't test bad alignment as it should not be possible

        assert_eq!(
            Err(AllocationError::OutOfBounds),
            WasmStack::try_from(WasmAllocation {
                offset: Offset::from(std::u32::MAX),
                length: Length::from(1)
            }),
        );

        assert_eq!(
            Ok(WasmStack { top: Top(60) }),
            WasmStack::try_from(WasmAllocation {
                offset: Offset::from(30),
                length: Length::from(30)
            }),
        );

        let big = U16_MAX * 3;
        assert_eq!(
            Ok(WasmStack { top: Top(big * 2) }),
            WasmStack::try_from(WasmAllocation {
                offset: Offset::from(big),
                length: Length::from(big),
            }),
        );
    }
}