Skip to content

Commit fec5ee3

Browse files
authored
readat/writeat (#249)
* change read and write to use readat and writeat, removing excess seek call * add comments * add comments * add comments
1 parent 174bec6 commit fec5ee3

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

src/interface/file.rs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use libc::{mmap, mremap, munmap, off64_t, MAP_SHARED, MREMAP_MAYMOVE, PROT_READ,
1919
use std::convert::TryInto;
2020
use std::ffi::c_void;
2121
use std::os::unix::io::{AsRawFd, RawFd};
22+
use std::os::unix::fs::{FileExt};
2223

2324
pub fn removefile(filename: String) -> std::io::Result<()> {
2425
let path: RustPathBuf = [".".to_string(), filename].iter().collect();
@@ -141,7 +142,9 @@ impl EmulatedFile {
141142
unsafe { libc::sync_file_range(*fd, offset as off64_t, nbytes as off64_t, flags) }
142143
}
143144

144-
// Read from file into provided C-buffer
145+
// Wrapper around Rust's file object read_at function
146+
// Reads from file at specified offset into provided C-buffer
147+
// We need to specify the offset for read/write operations because multiple cages may refer to same system file handle
145148
pub fn readat(&self, ptr: *mut u8, length: usize, offset: usize) -> std::io::Result<usize> {
146149
let buf = unsafe {
147150
assert!(!ptr.is_null());
@@ -151,18 +154,19 @@ impl EmulatedFile {
151154
match &self.fobj {
152155
None => panic!("{} is already closed.", self.filename),
153156
Some(f) => {
154-
let mut fobj = f.lock();
157+
let fobj = f.lock();
155158
if offset > self.filesize {
156159
panic!("Seek offset extends past the EOF!");
157160
}
158-
fobj.seek(SeekFrom::Start(offset as u64))?;
159-
let bytes_read = fobj.read(buf)?;
161+
let bytes_read = fobj.read_at(buf, offset as u64)?;
160162
Ok(bytes_read)
161163
}
162164
}
163165
}
164166

165-
// Write to file from provided C-buffer
167+
// Wrapper around Rust's file object write_at function
168+
// Writes from provided C-buffer into file at specified offset
169+
// We need to specify the offset for read/write operations because multiple cages may refer to same system file handle
166170
pub fn writeat(
167171
&mut self,
168172
ptr: *const u8,
@@ -179,15 +183,15 @@ impl EmulatedFile {
179183
match &self.fobj {
180184
None => panic!("{} is already closed.", self.filename),
181185
Some(f) => {
182-
let mut fobj = f.lock();
186+
let fobj = f.lock();
183187
if offset > self.filesize {
184188
panic!("Seek offset extends past the EOF!");
185189
}
186-
fobj.seek(SeekFrom::Start(offset as u64))?;
187-
bytes_written = fobj.write(buf)?;
190+
bytes_written = fobj.write_at(buf, offset as u64)?;
188191
}
189192
}
190193

194+
// update our recorded filesize if we've written past the old filesize
191195
if offset + length > self.filesize {
192196
self.filesize = offset + length;
193197
}

0 commit comments

Comments
 (0)