MCPcopy Create free account
hub / github.com/aws/clock-bound / new

Method new

clock-bound/src/vmclock/shm_reader.rs:37–100  ·  view source on GitHub ↗

Create a new `MmapGuard`. Memory map the provided open File.

(path: &str)

Source from the content-addressed store, hash-verified

35 ///
36 /// Memory map the provided open File.
37 fn new(path: &str) -> Result<Self, ShmError> {
38 let mut file = match File::open(path) {
39 Ok(f) => f,
40 Err(e) => {
41 error!(error = ?e, "Failed to open VMClock SHM segment.");
42 return Err(ShmError::SegmentNotInitialized(format!(
43 "Failed to open SHM segment at {path}"
44 )));
45 }
46 };
47
48 let mut buffer = vec![];
49
50 let Ok(bytes_read) = file.read_to_end(&mut buffer) else {
51 return syserror!(String::from("Failed to read SHM segment"));
52 };
53
54 if bytes_read == 0_usize {
55 let msg = String::from("Read zero bytes.");
56 error!(msg);
57 return Err(ShmError::SegmentNotInitialized(msg));
58 } else if bytes_read < size_of::<VMClockShmHeader>() {
59 let msg = format!(
60 "Number of bytes read ({:?}) is less than the size of VMClockShmHeader ({:?}).",
61 bytes_read,
62 size_of::<VMClockShmHeader>()
63 );
64 error!(msg);
65 return Err(ShmError::SegmentMalformed(msg));
66 }
67
68 debug!("Reading the VMClockShmHeader.");
69
70 // Read the header so we know how much to map in memory.
71 let header = VMClockShmHeader::read(&buffer)?;
72
73 // This consumes the segsize, but we only needed the header for validation and extracting
74 // the segment size. So the move is fine here.
75 let segsize = header.size.into_inner() as usize;
76
77 debug!("Read a segment size of: {:?}", segsize);
78
79 // SAFETY: We're calling into a C function, but this particular call is always safe.
80 let segment: *mut c_void = unsafe {
81 libc::mmap(
82 ptr::null_mut(),
83 segsize,
84 libc::PROT_READ,
85 libc::MAP_SHARED,
86 file.as_raw_fd(),
87 0,
88 )
89 };
90
91 if segment == libc::MAP_FAILED {
92 return syserror!(String::from("Failed to mmap the SHM segment"));
93 }
94

Callers

nothing calls this directly

Calls 2

addMethod · 0.80
newFunction · 0.50

Tested by

no test coverage detected