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

use std::alloc::{Allocator, AllocError, Layout, handle_alloc_error};
use std::ptr::NonNull;

pub struct Sensitive;

impl Sensitive {
	pub const GUARD_PAGES: usize = 1;

	pub fn guard_size() -> usize {
		Self::GUARD_PAGES * page_size()
	}
}

unsafe impl Allocator for Sensitive {
	fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
		// Refuse allocation if alignment requirement exceeds page size
		if layout.align() >= page_size() {
			return Err(AllocError);
		}

		// Allocate size + two guard pages
		let full = alloc_align(layout.size() + 2 * Self::guard_size());
		let size = full - 2 * Self::guard_size();

		let addr = unsafe { allocate(full, Protection::NoAccess).or(Err(AllocError))? };
		let base = unsafe { addr.add(Self::guard_size()) };

		if size > 0 {
			// Attempt to lock memory
			let _ = unsafe { lock(base, size) };

			// Allow read‐write access
			if unsafe { protect(base, size, Protection::ReadWrite).is_err() } {
				let _ = unsafe { release(addr, full) };
				return Err(AllocError);
			}
		}

		Ok(NonNull::slice_from_raw_parts(unsafe { NonNull::new_unchecked(base) }, size))
	}

	fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
		self.allocate(layout)
	}

	unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
		debug_assert!(layout.align() <= page_size());

		let full = alloc_align(layout.size() + 2 * Self::guard_size());

		if layout.size() > 0 {
			// Allow read‐write access before zeroing
			if protect(ptr.as_ptr(), page_align(layout.size()), Protection::ReadWrite).is_err() {
				handle_alloc_error(layout);
			}

			// Zero memory before returning to OS
			zero(ptr.as_ptr(), layout.size());
		}

		let addr = ptr.as_ptr().sub(Self::guard_size());

		if release(addr, full).is_err() {
			handle_alloc_error(layout);
		}
	}

	unsafe fn shrink(&self, ptr: NonNull<u8>, old: Layout, new: Layout) -> Result<NonNull<[u8]>, AllocError> {
		// Refuse allocation if alignment requirement exceeds page size
		if new.align() >= page_size() {
			return Err(AllocError);
		}

		debug_assert!(new.size() < old.size());

		// Uncommit pages as needed
		let size_old = page_align(old.size());
		let size_new = page_align(new.size());

		if size_old - size_new >= page_size() {
			let tail = ptr.as_ptr().add(size_new);
			let diff = size_old - size_new;

			// Allow read‐write access before zeroing
			if protect(tail, diff + Self::guard_size(), Protection::ReadWrite).is_err() {
				handle_alloc_error(new);
			}

			// Zero memory before uncommiting
			zero(tail, diff + Self::guard_size());

			// Uncommit pages and protect new guard page
			if uncommit(tail.add(Self::guard_size()), diff).is_err()
				|| protect(tail, Self::guard_size(), Protection::NoAccess).is_err() {
				handle_alloc_error(new);
			}
		}

		Ok(NonNull::slice_from_raw_parts(ptr, size_new))
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	fn test_raw_range(range: std::ops::Range<usize>, samples: usize) {
		use rand::distributions::{Distribution, Uniform};

		let mut rng = rand::thread_rng();
		let dist = Uniform::from(range);

		for _ in 0..samples {
			let size = dist.sample(&mut rng);

			eprintln!("Allocating {} bytes", size);

			let layout = Layout::from_size_align(size, 1).unwrap();
			let alloc = Sensitive.allocate(layout).unwrap();

			for i in 0..size {
				let ptr = unsafe { alloc.cast::<u8>().as_ptr().add(i) };
				assert_eq!(unsafe { ptr.read() }, 0);
				unsafe { ptr.write(0x55) };
				assert_eq!(unsafe { ptr.read() }, 0x55);
			}

			unsafe { Sensitive.deallocate(alloc.cast::<u8>(), layout); }
		}
	}

	#[test]
	fn test_raw_tiny() {
		test_raw_range(0..4096, 4096);
	}

	#[test]
	fn test_raw_small() {
		test_raw_range(4096..65536, 256);
	}

	#[test]
	fn test_raw_medium() {
		test_raw_range(65536..4194304, 64);
	}

	#[test]
	fn test_raw_large() {
		test_raw_range(4194304..16777216, 16);
	}

	#[test]
	fn test_raw_huge() {
		test_raw_range(4194304..268435456, 4);
	}

	#[cfg(unix)]
	#[test]
	fn test_raw_guard() {
		use bulletproof::Bulletproof;

		let size = alloc_align(4194304);

		let bp = unsafe { Bulletproof::new() };
		let layout = Layout::from_size_align(size, 1).unwrap();
		let alloc = Sensitive.allocate(layout).unwrap();
		let ptr = alloc.cast::<u8>().as_ptr();

		// Preceding guard
		for i in 1..=Sensitive::guard_size() {
			assert_eq!(unsafe { bp.load(ptr.sub(i)) }, Err(()));
		}

		for i in 0..size {
			assert_eq!(unsafe { bp.load(ptr.add(i)) }, Ok(0));
		}

		// Trailing guard
		for i in size + 1 .. Sensitive::guard_size() {
			assert_eq!(unsafe { bp.load(ptr.add(i)) }, Err(()));
		}

		unsafe { Sensitive.deallocate(alloc.cast::<u8>(), layout); }
	}

	#[cfg(unix)]
	#[test]
	fn test_raw_shrink() {
		use bulletproof::Bulletproof;

		let size = granularity() + Sensitive::guard_size();

		let bp = unsafe { Bulletproof::new() };
		let layout_0 = Layout::from_size_align(size, 1).unwrap();
		let alloc_0 = Sensitive.allocate(layout_0).unwrap();
		let ptr = alloc_0.cast::<u8>().as_ptr();

		for i in 0..size {
			assert_eq!(unsafe { bp.load(ptr.add(i)) }, Ok(0));
		}

		// Original guard
		for i in size + 1 .. Sensitive::guard_size() {
			assert_eq!(unsafe { bp.load(ptr.add(i)) }, Err(()));
		}

		let layout_1 = Layout::from_size_align(size - Sensitive::guard_size(), 1).unwrap();
		let alloc_1 = unsafe {
			Sensitive.shrink(alloc_0.cast::<u8>(), layout_0, layout_1)
		}.unwrap();

		// Allocation should not move
		assert_eq!(alloc_0.cast::<u8>(), alloc_1.cast::<u8>());

		for i in 0 .. size / 2 {
			assert_eq!(unsafe { bp.load(ptr.add(i)) }, Ok(0));
		}

		// New guard
		for i in size / 2 + 1 .. Sensitive::guard_size() {
			assert_eq!(unsafe { bp.load(ptr.add(i)) }, Err(()));
		}

		unsafe { Sensitive.deallocate(alloc_1.cast::<u8>(), layout_1); }
	}

	#[test]
	fn test_vec_seq() {
		const LIMIT: usize = 4194304;

		let mut test: Vec<usize, _> = Vec::new_in(Sensitive);

		for i in 0..LIMIT {
			test.push(i);
		}

		for i in 0..LIMIT {
			assert_eq!(test[i], i);
		}
	}

	#[test]
	fn test_vec_rng() {
		use rand::prelude::*;

		const LIMIT: usize = 4194304;

		let mut rng = rand::thread_rng();
		let mut test: Vec<u8, _> = Vec::new_in(Sensitive);

		for i in 0..LIMIT {
			let rand = rng.gen();

			test.push(rand);
			assert_eq!(test[i], rand);
		}

		for _ in 0..LIMIT {
			assert!(test.pop().is_some());
			test.shrink_to_fit();
		}
	}
}