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
270
271
272
273
274
use std::collections::BTreeMap;

use crate::*;

#[cfg(feature = "debug")]
use pretty_hex::PrettyHex;

/// Handles memory for plugins
pub struct PluginMemory {
    pub store: Store<Internal>,
    pub memory: Memory,
    pub live_blocks: BTreeMap<usize, usize>,
    pub free: Vec<MemoryBlock>,
    pub position: usize,
}

const PAGE_SIZE: u32 = 65536;

// BLOCK_SIZE_THRESHOLD exists to ensure that free blocks are never split up any
// smaller than this value
const BLOCK_SIZE_THRESHOLD: usize = 32;

impl PluginMemory {
    pub fn new(store: Store<Internal>, memory: Memory) -> Self {
        PluginMemory {
            free: Vec::new(),
            live_blocks: BTreeMap::new(),
            store,
            memory,
            position: 1,
        }
    }

    pub(crate) fn store_u8(&mut self, offs: usize, data: u8) -> Result<(), MemoryAccessError> {
        if offs >= self.size() {
            // This should raise MemoryAccessError
            let buf = &mut [0];
            self.memory.read(&self.store, offs, buf)?;
            return Ok(());
        }
        self.memory.data_mut(&mut self.store)[offs] = data;
        Ok(())
    }

    /// Read from memory
    pub(crate) fn load_u8(&self, offs: usize) -> Result<u8, MemoryAccessError> {
        if offs >= self.size() {
            // This should raise MemoryAccessError
            let buf = &mut [0];
            self.memory.read(&self.store, offs, buf)?;
            return Ok(0);
        }
        Ok(self.memory.data(&self.store)[offs])
    }

    pub(crate) fn store_u32(&mut self, offs: usize, data: u32) -> Result<(), MemoryAccessError> {
        let handle = MemoryBlock {
            offset: offs,
            length: 4,
        };
        self.write(handle, &data.to_ne_bytes())?;
        Ok(())
    }

    /// Read from memory
    pub(crate) fn load_u32(&self, offs: usize) -> Result<u32, MemoryAccessError> {
        let mut buf = [0; 4];

        let handle = MemoryBlock {
            offset: offs,
            length: 4,
        };
        self.read(handle, &mut buf)?;
        Ok(u32::from_ne_bytes(buf))
    }

    pub(crate) fn store_u64(&mut self, offs: usize, data: u64) -> Result<(), MemoryAccessError> {
        let handle = MemoryBlock {
            offset: offs,
            length: 8,
        };
        self.write(handle, &data.to_ne_bytes())?;
        Ok(())
    }

    pub(crate) fn load_u64(&self, offs: usize) -> Result<u64, MemoryAccessError> {
        let mut buf = [0; 8];
        let handle = MemoryBlock {
            offset: offs,
            length: 8,
        };
        self.read(handle, &mut buf)?;
        Ok(u64::from_ne_bytes(buf))
    }

    /// Write to memory
    pub fn write(
        &mut self,
        pos: impl Into<MemoryBlock>,
        data: impl AsRef<[u8]>,
    ) -> Result<(), MemoryAccessError> {
        let pos = pos.into();
        assert!(data.as_ref().len() <= pos.length);
        self.memory
            .write(&mut self.store, pos.offset, data.as_ref())
    }

    /// Read from memory
    pub fn read(
        &self,
        pos: impl Into<MemoryBlock>,
        mut data: impl AsMut<[u8]>,
    ) -> Result<(), MemoryAccessError> {
        let pos = pos.into();
        assert!(data.as_mut().len() <= pos.length);
        self.memory.read(&self.store, pos.offset, data.as_mut())
    }

    /// Size of memory in bytes
    pub fn size(&self) -> usize {
        self.memory.data_size(&self.store)
    }

    /// Size of memory in pages
    pub fn pages(&self) -> u32 {
        self.memory.size(&self.store) as u32
    }

    /// Reserve `n` bytes of memory
    pub fn alloc(&mut self, n: usize) -> Result<MemoryBlock, Error> {
        for (i, block) in self.free.iter_mut().enumerate() {
            if block.length == n {
                let block = self.free.swap_remove(i);
                self.live_blocks.insert(block.offset, block.length);
                return Ok(block);
            } else if block.length - n >= BLOCK_SIZE_THRESHOLD {
                let handle = MemoryBlock {
                    offset: block.offset,
                    length: n,
                };
                block.offset += n;
                block.length -= n;
                self.live_blocks.insert(handle.offset, handle.length);
                return Ok(handle);
            }
        }

        // If there aren't enough bytes, try to grow the memory size
        if self.position + n >= self.size() {
            let bytes_needed = (self.position as f64 + n as f64
                - self.memory.data_size(&self.store) as f64)
                / PAGE_SIZE as f64;
            let mut pages_needed = bytes_needed.ceil() as u64;
            if pages_needed == 0 {
                pages_needed = 1
            }

            // This will fail if we've already allocated the maximum amount of memory allowed
            self.memory.grow(&mut self.store, pages_needed)?;
        }

        let mem = MemoryBlock {
            offset: self.position,
            length: n,
        };

        self.live_blocks.insert(mem.offset, mem.length);
        self.position += n;
        Ok(mem)
    }

    /// Allocate and copy `data` into the wasm memory
    pub fn alloc_bytes(&mut self, data: impl AsRef<[u8]>) -> Result<MemoryBlock, Error> {
        let handle = self.alloc(data.as_ref().len())?;
        self.write(handle, data)?;
        Ok(handle)
    }

    /// Free the block allocated at `offset`
    pub fn free(&mut self, offset: usize) {
        if let Some(length) = self.live_blocks.remove(&offset) {
            self.free.push(MemoryBlock { offset, length });
        } else {
            return;
        }

        let free_size: usize = self.free.iter().map(|x| x.length).sum();

        // Perform compaction if there is at least 1kb of free memory available
        if free_size >= 1024 {
            let mut last: Option<MemoryBlock> = None;
            let mut free = Vec::new();
            for block in self.free.iter() {
                match last {
                    None => {
                        free.push(*block);
                    }
                    Some(last) => {
                        if last.offset + last.length == block.offset {
                            free.push(MemoryBlock {
                                offset: last.offset,
                                length: last.length + block.length,
                            });
                        }
                    }
                }
                last = Some(*block);
            }
            self.free = free;
        }
    }

    #[cfg(feature = "debug")]
    pub fn dump(&self) {
        let data = self.memory.data(&self.store);

        println!("{:?}", data[..self.position].hex_dump());
    }

    /// Reset memory
    pub fn reset(&mut self) {
        self.free.clear();
        self.live_blocks.clear();
        self.position = 1;
    }

    /// Get memory as a slice of bytes
    pub fn data(&self) -> &[u8] {
        self.memory.data(&self.store)
    }

    /// Get memory as a mutable slice of bytes
    pub fn data_mut(&mut self) -> &[u8] {
        self.memory.data_mut(&mut self.store)
    }

    /// Get bytes occupied by the provided memory handle
    pub fn get(&self, handle: impl Into<MemoryBlock>) -> &[u8] {
        let handle = handle.into();
        &self.memory.data(&self.store)[handle.offset..handle.offset + handle.length]
    }

    /// Get mutable bytes occupied by the provided memory handle
    pub fn get_mut(&mut self, handle: impl Into<MemoryBlock>) -> &mut [u8] {
        let handle = handle.into();
        &mut self.memory.data_mut(&mut self.store)[handle.offset..handle.offset + handle.length]
    }

    /// Get the length of the block starting at `offs`
    pub fn block_length(&self, offs: usize) -> Option<usize> {
        self.live_blocks.get(&offs).cloned()
    }
}

#[derive(Clone, Copy)]
pub struct MemoryBlock {
    pub offset: usize,
    pub length: usize,
}

impl From<(usize, usize)> for MemoryBlock {
    fn from(x: (usize, usize)) -> Self {
        MemoryBlock {
            offset: x.0,
            length: x.1,
        }
    }
}

impl MemoryBlock {
    pub fn new(offset: usize, length: usize) -> Self {
        MemoryBlock { offset, length }
    }
}