-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathmod.rs
More file actions
370 lines (302 loc) · 12.6 KB
/
Copy pathmod.rs
File metadata and controls
370 lines (302 loc) · 12.6 KB
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
//! Manages the virtual memory address space of a process.
use super::{
PAGE_SIZE, address::VA, proc_vm::address_space::UserAddressSpace, region::VirtMemoryRegion,
};
use crate::error::{KernelError, Result};
use alloc::string::ToString;
use memory_map::{AddressRequest, MemoryMap};
use vmarea::{AccessKind, FaultValidation, VMAPermissions, VMArea, VMAreaKind};
pub mod address_space;
pub mod memory_map;
pub mod pg_offset;
pub mod vmarea;
const BRK_PERMISSIONS: VMAPermissions = VMAPermissions::rw();
/// The virtual memory state of a user-space process.
pub struct ProcessVM<AS: UserAddressSpace> {
mm: MemoryMap<AS>,
brk: VirtMemoryRegion,
}
impl<AS: UserAddressSpace> ProcessVM<AS> {
/// Constructs a new Process VM structure from the given VMA. The heap is
/// placed *after* the given VMA.
///
/// # Safety
/// Any pages that have been mapped into the provided address space *must*
/// corresponde to the provided VMA.
pub unsafe fn from_vma_and_address_space(vma: VMArea, addr_spc: AS) -> Self {
let mut mm = MemoryMap::with_addr_spc(addr_spc);
mm.insert_and_merge(vma.clone());
let brk = VirtMemoryRegion::new(vma.region.end_address().align_up(PAGE_SIZE), 0);
Self { mm, brk }
}
/// Constructs a new Process VM structure from the given VMA. The heap is
/// placed *after* the given VMA.
pub fn from_vma(vma: VMArea) -> Result<Self> {
let mut mm = MemoryMap::new()?;
mm.insert_and_merge(vma.clone());
let brk = VirtMemoryRegion::new(vma.region.end_address().align_up(PAGE_SIZE), 0);
Ok(Self { mm, brk })
}
/// Constructs a `ProcessVM` from an existing memory map.
pub fn from_map(map: MemoryMap<AS>) -> Self {
// Last entry will be the VMA with the highest address.
let brk = map
.vmas
.last_key_value()
.expect("No VMAs in map")
.1
.region
.end_address()
// VMAs should already be page-aligned, but just in case.
.align_up(PAGE_SIZE);
Self {
mm: map,
brk: VirtMemoryRegion::new(brk, 0),
}
}
/// Creates an empty `ProcessVM` with no mappings and a zero-sized heap.
pub fn empty() -> Result<Self> {
Ok(Self {
mm: MemoryMap::new()?,
brk: VirtMemoryRegion::empty(),
})
}
/// Finds the VMA covering `addr` if the given access type is permitted.
pub fn find_vma_for_fault(&self, addr: VA, access_type: AccessKind) -> Option<&VMArea> {
let vma = self.mm.find_vma(addr)?;
match vma.validate_fault(addr, access_type) {
FaultValidation::Valid => Some(vma),
FaultValidation::NotPresent => unreachable!(""),
FaultValidation::PermissionDenied => None,
}
}
/// Returns a non-mutable reference to the underlying memory map.
pub fn mm(&self) -> &MemoryMap<AS> {
&self.mm
}
/// Returns a mutable reference to the underlying memory map.
pub fn mm_mut(&mut self) -> &mut MemoryMap<AS> {
&mut self.mm
}
/// Returns the current start address of the program break (heap).
pub fn start_brk(&self) -> VA {
self.brk.start_address()
}
/// Returns the current end address of the program break (heap).
pub fn current_brk(&self) -> VA {
self.brk.end_address()
}
/// Resizes the program break (the heap).
///
/// This function implements the semantics of the `brk` system call. It can
/// either grow or shrink the heap area.
///
/// # Arguments
/// * `new_end_addr`: The desired new end address for the program break.
///
/// # Returns
/// * `Ok(())` on success.
/// * `Err(KernelError)` on failure. This can happen if the requested memory
/// region conflicts with an existing mapping, or if the request is invalid
/// (e.g., shrinking the break below its initial start address).
pub fn resize_brk(&mut self, new_end_addr: VA) -> Result<VA> {
let brk_start = self.brk.start_address();
let current_end = self.brk.end_address();
// The break cannot be shrunk to an address lower than its starting
// point.
if new_end_addr < brk_start {
return Err(KernelError::InvalidValue);
}
let new_end_addr_aligned = new_end_addr.align_up(PAGE_SIZE);
let new_brk_region =
VirtMemoryRegion::from_start_end_address(brk_start, new_end_addr_aligned);
if new_end_addr_aligned == current_end {
// The requested break is the same as the current one, or it is
// within the same page as the existing allocation. This is a no-op.
return Ok(new_end_addr);
}
// Grow the break
if new_end_addr_aligned > current_end {
let growth_size = new_end_addr_aligned.value() - current_end.value();
self.mm.mmap(
AddressRequest::Fixed {
address: current_end,
permit_overlap: false,
},
growth_size,
BRK_PERMISSIONS,
VMAreaKind::Anon,
"[heap]".to_string(),
)?;
self.brk = new_brk_region;
return Ok(new_end_addr);
}
// Shrink the break
// At this point, we know `new_end_aligned < current_end`.
let unmap_region =
VirtMemoryRegion::from_start_end_address(new_end_addr_aligned, current_end);
self.mm.munmap(unmap_region)?;
self.brk = new_brk_region;
Ok(new_end_addr)
}
/// Clones this process VM, marking all writable pages as copy-on-write.
pub fn clone_as_cow(&mut self) -> Result<Self> {
Ok(Self {
mm: self.mm.clone_as_cow()?,
brk: self.brk,
})
}
}
#[cfg(test)]
mod tests {
use super::memory_map::tests::MockAddressSpace;
use super::*;
use crate::error::KernelError;
fn setup_vm() -> ProcessVM<MockAddressSpace> {
let text_vma = VMArea {
region: VirtMemoryRegion::new(VA::from_value(0x1000), PAGE_SIZE),
kind: VMAreaKind::Anon, // Simplification for test
permissions: VMAPermissions::rx(),
name: String::new(),
shared: false,
};
ProcessVM::from_vma(text_vma).unwrap()
}
#[test]
fn test_initial_state() {
// Given: a newly created ProcessVM
let vm = setup_vm();
let initial_brk_start = VA::from_value(0x1000 + PAGE_SIZE);
assert_eq!(vm.brk.start_address(), initial_brk_start);
assert_eq!(vm.brk.size(), 0);
assert_eq!(vm.current_brk(), initial_brk_start);
// And the break region itself should not be mapped
assert!(vm.mm.find_vma(initial_brk_start).is_none());
}
#[test]
fn test_brk_first_growth() {
// Given: a VM with a zero-sized heap
let mut vm = setup_vm();
let initial_brk_start = vm.brk.start_address();
let brk_addr = initial_brk_start.add_bytes(1);
let new_brk = vm.resize_brk(brk_addr).unwrap();
// The new break should be page-aligned
let expected_brk_end = brk_addr.align_up(PAGE_SIZE);
assert_eq!(new_brk, brk_addr);
assert_eq!(vm.current_brk(), expected_brk_end);
assert_eq!(vm.brk.size(), PAGE_SIZE);
// And a new VMA for the heap should now exist with RW permissions
let heap_vma = vm
.mm
.find_vma(initial_brk_start)
.expect("Heap VMA should exist");
assert_eq!(heap_vma.region.start_address(), initial_brk_start);
assert_eq!(heap_vma.region.end_address(), expected_brk_end);
assert_eq!(heap_vma.permissions, VMAPermissions::rw());
}
#[test]
fn test_brk_subsequent_growth() {
// Given: a VM with an existing heap
let mut vm = setup_vm();
let initial_brk_start = vm.brk.start_address();
vm.resize_brk(initial_brk_start.add_bytes(1)).unwrap(); // First growth
assert_eq!(vm.brk.size(), PAGE_SIZE);
// When: we grow the break again
let new_brk = vm.resize_brk(vm.current_brk().add_pages(1)).unwrap();
// Then: the break should be extended
let expected_brk_end = initial_brk_start.add_pages(2);
assert_eq!(new_brk, expected_brk_end);
assert_eq!(vm.current_brk(), expected_brk_end);
assert_eq!(vm.brk.size(), 2 * PAGE_SIZE);
// And the single heap VMA should be larger, not a new one
let heap_vma = vm.mm.find_vma(initial_brk_start).unwrap();
assert_eq!(heap_vma.region.end_address(), expected_brk_end);
assert_eq!(vm.mm.vma_count(), 2); // Text VMA + one Heap VMA
}
#[test]
fn test_brk_shrink() {
// Given: a VM with a 3-page heap
let mut vm = setup_vm();
let initial_brk_start = vm.brk.start_address();
vm.resize_brk(initial_brk_start.add_pages(3)).unwrap();
assert_eq!(vm.brk.size(), 3 * PAGE_SIZE);
// When: we shrink the break by one page
let new_brk_addr = initial_brk_start.add_pages(2);
let new_brk = vm.resize_brk(new_brk_addr).unwrap();
// Then: the break should be updated
assert_eq!(new_brk, new_brk_addr);
assert_eq!(vm.current_brk(), new_brk_addr);
assert_eq!(vm.brk.size(), 2 * PAGE_SIZE);
// And the memory for the shrunken page should now be unmapped
assert!(vm.mm.find_vma(new_brk_addr.add_bytes(1)).is_none());
// But the remaining heap should still be mapped
assert!(vm.mm.find_vma(initial_brk_start).is_some());
}
#[test]
fn test_brk_shrink_to_zero() {
// Given: a VM with a 2-page heap
let mut vm = setup_vm();
let initial_brk_start = vm.brk.start_address();
vm.resize_brk(initial_brk_start.add_pages(2)).unwrap();
// When: we shrink the break all the way back to its start
let new_brk = vm.resize_brk(initial_brk_start).unwrap();
// Then: the break should be zero-sized again
assert_eq!(new_brk, initial_brk_start);
assert_eq!(vm.current_brk(), initial_brk_start);
assert_eq!(vm.brk.size(), 0);
// And the heap VMA should be completely gone
assert!(vm.mm.find_vma(initial_brk_start).is_none());
assert_eq!(vm.mm.vma_count(), 1); // Only the text VMA remains
}
#[test]
fn test_brk_no_op() {
// Given: a VM with a 2-page heap
let mut vm = setup_vm();
let initial_brk_start = vm.brk.start_address();
let current_brk_end = vm.resize_brk(initial_brk_start.add_pages(2)).unwrap();
// When: we resize the break to its current end
let new_brk = vm.resize_brk(current_brk_end).unwrap();
// Then: nothing should change
assert_eq!(new_brk, current_brk_end);
assert_eq!(vm.brk.size(), 2 * PAGE_SIZE);
assert_eq!(vm.mm.vma_count(), 2);
}
#[test]
fn test_brk_invalid_shrink_below_start() {
let mut vm = setup_vm();
let initial_brk_start = vm.brk.start_address();
vm.resize_brk(initial_brk_start.add_pages(1)).unwrap();
let original_len = vm.brk.size();
// We try to shrink the break below its starting point
let result = vm.resize_brk(VA::from_value(initial_brk_start.value() - 1));
// It should fail with an InvalidValue error
assert!(matches!(result, Err(KernelError::InvalidValue)));
// And the state of the break should not have changed
assert_eq!(vm.brk.start_address(), initial_brk_start);
assert_eq!(vm.brk.size(), original_len);
}
#[test]
fn test_brk_growth_collision() {
// Given: a VM with another mapping right where the heap would grow
let mut vm = setup_vm();
let initial_brk_start = vm.brk.start_address();
let obstacle_addr = initial_brk_start.add_pages(2);
let obstacle_vma = VMArea {
region: VirtMemoryRegion::new(obstacle_addr, PAGE_SIZE),
kind: VMAreaKind::Anon,
permissions: VMAPermissions::ro(),
name: String::new(),
shared: false,
};
vm.mm.insert_and_merge(obstacle_vma);
assert_eq!(vm.mm.vma_count(), 2);
// When: we try to grow the break past the obstacle
let result = vm.resize_brk(initial_brk_start.add_pages(3));
// Then: the mmap should fail, resulting in an error
// The specific error comes from your mmap implementation.
assert!(matches!(result, Err(KernelError::InvalidValue)));
// And the break should not have grown at all
assert_eq!(vm.brk.size(), 0);
assert_eq!(vm.current_brk(), initial_brk_start);
}
}