Debian Codegraph @

crt/s2n/bindings/rust/standard/integration/tests/memory.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 #[global_allocator]
5 static ALLOC: dhat::Alloc = dhat::Alloc;
6 #[cfg(not(feature = "no-sensitive-tests"))]
7 mod memory_test {
8 // dhat can only be run in a single thread, so we use a single test case in an
9 // "integration" test (tests/*) to fulfill those conditions.
10
11 use s2n_tls::{
12 error::Error as S2NError,
13 security::Policy,
14 testing::{self, TestPair},
15 };
16 use std::{collections::BTreeMap, task::Poll};
17 use tabled::{settings::Style, Table, Tabled};
18
19 /// Return an estimation of the memory size of the IO buffers
20 ///
21 /// This isn't totally accurate because it doesn't account for any indirection that
22 /// may be present.
23 fn test_pair_io_size(pair: &TestPair) -> usize {
24 pair.io.client_tx_stream.borrow().capacity() + pair.io.server_tx_stream.borrow().capacity()
25 }
26
27 fn fuzzy_equals(actual: usize, expected: usize) -> bool {
28 const TOLERANCE: usize = 100;
29
30 println!("actual: {actual}, expected: {expected}");
31 actual <= expected + TOLERANCE && actual >= expected - TOLERANCE
32 }
33
34 mod memory_callbacks {
35 use std::alloc::Layout;
36
37 /// A tagged allocator which prefixes each blob with the length of the allocation.
38 ///
39 /// ```text
40 /// size public allocation
41 /// v--------------------- v---------
42 /// [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... ]
43 /// ^
44 /// allocation
45 ///
46 /// ```
47 ///
48 /// This is necessary because the [`std::alloc::dealloc`] requires the length of
49 /// the blob to be deallocated, but the AWS-LC memory `free` callback does not
50 /// return the length.
51 struct TaggedAllocation {
52 /// the private view
53 allocation: *mut u8,
54 /// allocation size including the prefix
55 size: usize,
56 }
57
58 impl TaggedAllocation {
59 const ALIGNMENT: usize = size_of::<usize>();
60 const USIZE_WIDTH: usize = size_of::<usize>();
61
62 pub fn public_allocation(&self) -> *mut u8 {
63 unsafe { self.allocation.add(Self::USIZE_WIDTH) }
64 }
65 }
66
67 impl TaggedAllocation {
68 /// Return an allocation of `size` bytes
69 ///
70 /// Internally allocates extra bytes to also store the size of the allocation.
71 unsafe fn alloc(public_size: usize) -> Self {
72 let needed_size = public_size + Self::USIZE_WIDTH;
73 let layout = Layout::from_size_align(needed_size, Self::ALIGNMENT).unwrap();
74
75 let allocation = std::alloc::alloc(layout);
76 (allocation as *mut usize).write(needed_size);
77
78 Self {
79 allocation,
80 size: needed_size,
81 }
82 }
83
84 unsafe fn from_public_view(public_view: *mut u8) -> Self {
85 let alloc_start = (public_view as *mut usize).sub(1);
86 let size = (alloc_start as *mut usize).read();
87 Self {
88 allocation: alloc_start as *mut u8,
89 size,
90 }
91 }
92
93 unsafe fn realloc(&mut self, new_public_size: usize) {
94 let new_size = new_public_size + Self::USIZE_WIDTH;
95 let old_layout = Layout::from_size_align(self.size, Self::ALIGNMENT).unwrap();
96
97 let allocation = std::alloc::realloc(self.allocation, old_layout, new_size);
98 (allocation as *mut usize).write(new_size);
99
100 self.allocation = allocation;
101 self.size = new_size;
102 }
103
104 unsafe fn free(self) {
105 let layout = Layout::from_size_align(self.size, Self::ALIGNMENT).unwrap();
106 std::alloc::dealloc(self.allocation, layout);
107 }
108 }
109
110 pub unsafe extern "C" fn malloc_cb(
111 num: usize,
112 _file: *const std::ffi::c_char,
113 _line: i32,
114 ) -> *mut std::ffi::c_void {
115 let allocation = TaggedAllocation::alloc(num);
116 allocation.public_allocation() as *mut _
117 }
118
119 pub unsafe extern "C" fn realloc_cb(
120 addr: *mut std::ffi::c_void,
121 num: usize,
122 _file: *const std::ffi::c_char,
123 _line: i32,
124 ) -> *mut std::ffi::c_void {
125 let mut allocation = TaggedAllocation::from_public_view(addr as *mut _);
126 allocation.realloc(num);
127 allocation.public_allocation() as *mut _
128 }
129
130 pub unsafe extern "C" fn free_cb(
131 addr: *mut std::ffi::c_void,
132 _file: *const std::ffi::c_char,
133 _line: i32,
134 ) {
135 let allocation = TaggedAllocation::from_public_view(addr as *mut _);
136 allocation.free();
137 }
138 }
139
140 /// lifted from dhat-rs so that we can implement "Tabled" on it
141 #[derive(Clone, Debug, PartialEq, Eq, Tabled)]
142 #[non_exhaustive]
143 pub struct S2NHeapStats {
144 /// Number of blocks (a.k.a. allocations) allocated over the entire run.
145 pub total_blocks: u64,
146
147 /// Number of bytes allocated over the entire run.
148 pub total_bytes: u64,
149
150 /// Number of blocks (a.k.a. allocations) currently allocated.
151 pub curr_blocks: usize,
152
153 /// Number of bytes currently allocated.
154 pub curr_bytes: usize,
155
156 /// Number of blocks (a.k.a. allocations) allocated at the global peak,
157 /// i.e. when `curr_bytes` peaked.
158 pub max_blocks: usize,
159
160 /// Number of bytes allocated at the global peak, i.e. when `curr_bytes`
161 /// peaked.
162 pub max_bytes: usize,
163 }
164
165 #[derive(Debug, Clone, Tabled)]
166 pub struct ResultRow {
167 stage: String,
168 #[tabled(inline)]
169 measurement: S2NHeapStats,
170 test_pair_size: usize,
171 }
172
173 impl S2NHeapStats {
174 /// Return a "diff" against some earlier baseline. This is useful when
175 /// there were big allocations earlier in the program lifecycle that you
176 /// want to ignore
177 fn against_baseline(&self, baseline: &S2NHeapStats) -> S2NHeapStats {
178 // dbg!(self);
179 // dbg!(baseline);
180 let mut diff = self.clone();
181 diff.total_blocks -= baseline.total_blocks;
182 diff.total_bytes -= baseline.total_bytes;
183 diff.curr_blocks -= baseline.curr_blocks;
184 diff.curr_bytes -= baseline.curr_bytes;
185 diff.max_blocks -= baseline.max_blocks;
186 diff.max_bytes -= baseline.max_bytes;
187 diff
188 }
189 }
190
191 impl From<dhat::HeapStats> for S2NHeapStats {
192 fn from(value: dhat::HeapStats) -> Self {
193 Self {
194 total_blocks: value.total_blocks,
195 total_bytes: value.total_bytes,
196 curr_blocks: value.curr_blocks,
197 curr_bytes: value.curr_bytes,
198 max_blocks: value.max_blocks,
199 max_bytes: value.max_bytes,
200 }
201 }
202 }
203
204 #[derive(Debug, PartialEq, PartialOrd, Ord, Eq)]
205 enum Lifecycle {
206 ConnectionInit,
207 AfterClientHello,
208 AfterServerHello,
209 AfterClientFinished,
210 HandshakeComplete,
211 ApplicationData,
212 }
213
214 impl Lifecycle {
215 pub fn all_stages() -> Vec<Lifecycle> {
216 vec![
217 Lifecycle::ConnectionInit,
218 Lifecycle::AfterClientHello,
219 Lifecycle::AfterServerHello,
220 Lifecycle::AfterClientFinished,
221 Lifecycle::HandshakeComplete,
222 Lifecycle::ApplicationData,
223 ]
224 }
225 }
226
227 struct MemoryRecorder {
228 /// measurement after s2n_init
229 ///
230 /// Currently unused but we should be emitted a metric for this
231 _static_memory: S2NHeapStats,
232 /// measurement after config initialization
233 config_memory: S2NHeapStats,
234 measurements: BTreeMap<Lifecycle, (S2NHeapStats, usize)>,
235 }
236
237 impl MemoryRecorder {
238 fn measure(&mut self, lifecycle: Lifecycle, pair: &TestPair) {
239 self.measurements.insert(
240 lifecycle,
241 (dhat::HeapStats::get().into(), test_pair_io_size(pair)),
242 );
243 }
244
245 fn measurements_complete(&self) -> bool {
246 Lifecycle::all_stages()
247 .into_iter()
248 .all(|stage| self.measurements.contains_key(&stage))
249 }
250
251 /// return a table showing the measurements at various lifecycle points,
252 /// measured against the config creation baseline.
253 fn measurement_table(&self) -> Table {
254 assert!(self.measurements_complete());
255 let table: Vec<ResultRow> = Lifecycle::all_stages()
256 .into_iter()
257 .map(|stage| {
258 let (measurement, test_pair_size) =
259 self.measurements.get(&stage).unwrap().clone();
260 let measurement = measurement.against_baseline(&self.config_memory);
261 ResultRow {
262 stage: format!("{stage:?}"),
263 measurement,
264 test_pair_size,
265 }
266 })
267 .collect();
268 let mut table = Table::new(table);
269 table.with(Style::markdown());
270 table
271 }
272
273 fn assert_expected(&self) {
274 /// The allocated memory expected at each step of the connection lifecycle
275 const EXPECTED_MEMORY: &[(Lifecycle, usize)] = &[
276 (Lifecycle::ConnectionInit, 61_466),
277 (Lifecycle::AfterClientHello, 89_062),
278 (Lifecycle::AfterServerHello, 117_429),
279 (Lifecycle::AfterClientFinished, 108_736),
280 (Lifecycle::HandshakeComplete, 91_323),
281 (Lifecycle::ApplicationData, 91_323),
282 ];
283 let actual_memory: Vec<(Lifecycle, usize)> = Lifecycle::all_stages()
284 .into_iter()
285 .map(|stage| {
286 let measurement = self
287 .measurements
288 .get(&stage)
289 .unwrap()
290 .0
291 .against_baseline(&self.config_memory);
292 (stage, measurement.curr_bytes)
293 })
294 .collect();
295
296 for (actual, expected) in actual_memory.iter().zip(EXPECTED_MEMORY) {
297 // make sure we're looking at the right stage
298 assert_eq!(actual.0, expected.0);
299 assert!(fuzzy_equals(actual.1, expected.1))
300 }
301 }
302 }
303
304 struct MemoryRecordBuilder {
305 static_memory: Option<dhat::HeapStats>,
306 config_memory: Option<dhat::HeapStats>,
307 }
308
309 impl MemoryRecordBuilder {
310 fn new() -> Self {
311 Self {
312 static_memory: None,
313 config_memory: None,
314 }
315 }
316
317 fn after_init(&mut self) {
318 self.static_memory = Some(dhat::HeapStats::get());
319 }
320
321 fn after_config_creation(mut self) -> MemoryRecorder {
322 self.config_memory = Some(dhat::HeapStats::get());
323
324 MemoryRecorder {
325 _static_memory: self.static_memory.unwrap().into(),
326 config_memory: self.config_memory.unwrap().into(),
327 measurements: Default::default(),
328 }
329 }
330 }
331
332 /// The dhat-rs memory profiler can only measure memory allocated from the rust
333 /// global allocator.
334 ///
335 /// The s2n-tls rust bindings set the s2n-tls memory callbacks to use the rust
336 /// allocator, and we use `CRYPTO_set_mem_functions` to force aws-lc to use the
337 /// rust system allocator.
338 ///
339 /// It's important to keep allocations to a minimal amount in this test to give
340 /// as accurate a picture as possible into s2n-tls memory usage at various stages
341 /// in the connection lifecycle. We should limit this to
342 /// - config
343 /// - client connection
344 /// - server connection
345 /// - TestPair io buffers
346 #[test]
347 fn memory_consumption() -> Result<(), S2NError> {
348 const CLIENT_MESSAGE: &[u8] = b"from client";
349 const SERVER_MESSAGE: &[u8] = b"from server";
350
351 let _profiler = dhat::Profiler::new_heap();
352 let mut memory_recorder = MemoryRecordBuilder::new();
353
354 unsafe {
355 aws_lc_sys::CRYPTO_set_mem_functions(
356 Some(memory_callbacks::malloc_cb),
357 Some(memory_callbacks::realloc_cb),
358 Some(memory_callbacks::free_cb),
359 )
360 };
361
362 // s2n-tls allocates memory for the default configs. This includes the system
363 // trust store, which is often a significant amount of memory (~1 MB). This
364 // is system specific, so we don't actually assert on this value.
365 s2n_tls::init::init();
366 memory_recorder.after_init();
367
368 let config = testing::build_config(&Policy::from_version("default_tls13")?).unwrap();
369 let mut memory_recorder = memory_recorder.after_config_creation();
370
371 let mut pair = TestPair::from_config(&config);
372 memory_recorder.measure(Lifecycle::ConnectionInit, &pair);
373
374 ////////////////////////////////////////////////////////////////////////
375 ////////////////////////////// handshake ///////////////////////////////
376 ////////////////////////////////////////////////////////////////////////
377
378 assert!(matches!(pair.client.poll_negotiate(), Poll::Pending));
379 memory_recorder.measure(Lifecycle::AfterClientHello, &pair);
380
381 assert!(matches!(pair.server.poll_negotiate(), Poll::Pending));
382 memory_recorder.measure(Lifecycle::AfterServerHello, &pair);
383
384 assert!(matches!(pair.client.poll_negotiate(), Poll::Ready(_)));
385 memory_recorder.measure(Lifecycle::AfterClientFinished, &pair);
386
387 assert!(matches!(pair.server.poll_negotiate(), Poll::Ready(_)));
388 memory_recorder.measure(Lifecycle::HandshakeComplete, &pair);
389
390 ////////////////////////////////////////////////////////////////////////
391 /////////////////////////// application data ///////////////////////////
392 ////////////////////////////////////////////////////////////////////////
393
394 let _ = pair.client.poll_send(CLIENT_MESSAGE);
395 let _ = pair.server.poll_send(SERVER_MESSAGE);
396 let _ = pair.client.poll_recv(&mut [0; SERVER_MESSAGE.len()]);
397 let _ = pair.server.poll_recv(&mut [0; CLIENT_MESSAGE.len()]);
398 memory_recorder.measure(Lifecycle::ApplicationData, &pair);
399
400 println!("{}", memory_recorder.measurement_table());
401 memory_recorder.assert_expected();
402
403 Ok(())
404 }
405 }