Skip to content

Commit a92510a

Browse files
youknowdotcodex
andauthored
Align Windows mmap ownership and resize with CPython (#9847)
* Align Windows mmap ownership and resize with CPython * Restore the passing native mmap flush alignment test * Restore mmap tests confirmed passing by Windows CI --------- Co-authored-by: Codex <[email protected]>
1 parent af8415f commit a92510a

4 files changed

Lines changed: 304 additions & 301 deletions

File tree

‎Lib/test/test_mmap.py‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ def random_tagname(length=10):
3434
raise unittest.SkipTest("incompatible with Emscripten's mmap emulation.")
3535

3636

37-
@unittest.skipIf(os.name == "nt", "TODO: RUSTPYTHON; Errors on setUp")
3837
class MmapTests(unittest.TestCase):
3938

4039
def setUp(self):
@@ -321,7 +320,6 @@ def test_bad_file_desc(self):
321320
# Try opening a bad file descriptor...
322321
self.assertRaises(OSError, mmap.mmap, -2, 4096)
323322

324-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
325323
def test_tougher_find(self):
326324
# Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2,
327325
# searching for data with embedded \0 bytes didn't work.
@@ -381,7 +379,6 @@ def test_find_does_not_access_beyond_buffer(self):
381379
fm.find(b"fo", -2)
382380

383381

384-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
385382
def test_rfind(self):
386383
# test the new 'end' parameter works as expected
387384
with open(TESTFN, 'wb+') as f:
@@ -442,7 +439,6 @@ def test_length_0_large_offset(self):
442439
self.assertRaises(ValueError, mmap.mmap, f.fileno(), 0,
443440
offset=2147418112)
444441

445-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
446442
def test_move(self):
447443
# make move works everywhere (64-bit format problem earlier)
448444
with open(TESTFN, 'wb+') as f:
@@ -503,7 +499,6 @@ def test_anonymous(self):
503499
self.assertEqual(m[x], b)
504500
self.assertEqual(m.size(), PAGESIZE)
505501

506-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
507502
def test_read_all(self):
508503
m = mmap.mmap(-1, 16)
509504
self.addCleanup(m.close)
@@ -525,7 +520,6 @@ def test_read_all(self):
525520
m.seek(9)
526521
self.assertEqual(m.read(-42), bytes(range(9, 16)))
527522

528-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
529523
def test_read_invalid_arg(self):
530524
m = mmap.mmap(-1, 16)
531525
self.addCleanup(m.close)
@@ -638,7 +632,6 @@ def test_offset (self):
638632
except OSError:
639633
pass
640634

641-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
642635
def test_subclass(self):
643636
class anon_mmap(mmap.mmap):
644637
def __new__(klass, *args, **kwargs):
@@ -691,7 +684,6 @@ def test_io_methods(self):
691684
self.assertEqual(m[:], b"012barbaz9")
692685
self.assertRaises(ValueError, m.write, b"ba")
693686

694-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
695687
def test_non_ascii_byte(self):
696688
for b in (129, 200, 255): # > 128
697689
m = mmap.mmap(-1, 1)
@@ -701,7 +693,6 @@ def test_non_ascii_byte(self):
701693
self.assertEqual(m.read_byte(), b)
702694
m.close()
703695

704-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
705696
@unittest.skipUnless(os.name == 'nt', 'requires Windows')
706697
def test_tagname(self):
707698
data1 = b"0123456789"
@@ -794,7 +785,6 @@ def test_context_manager_exception(self):
794785
"wrong exception raised in context manager")
795786
self.assertTrue(m.closed, "context manager failed")
796787

797-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
798788
def test_weakref(self):
799789
# Check mmap objects are weakrefable
800790
mm = mmap.mmap(-1, 16)
@@ -804,15 +794,13 @@ def test_weakref(self):
804794
gc_collect()
805795
self.assertIs(wr(), None)
806796

807-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
808797
def test_write_returning_the_number_of_bytes_written(self):
809798
mm = mmap.mmap(-1, 16)
810799
self.assertEqual(mm.write(b""), 0)
811800
self.assertEqual(mm.write(b"x"), 1)
812801
self.assertEqual(mm.write(b"yz"), 2)
813802
self.assertEqual(mm.write(b"python"), 6)
814803

815-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
816804
@unittest.skipUnless(hasattr(mmap.mmap, 'resize'), 'requires mmap.resize')
817805
def test_resize_past_pos(self):
818806
m = mmap.mmap(-1, 8192)
@@ -831,7 +819,6 @@ def test_concat_repeat_exception(self):
831819
with self.assertRaises(TypeError):
832820
m * 2
833821

834-
@unittest.skipIf(sys.platform.startswith("linux"), "TODO: RUSTPYTHON; memmap2 doesn't throw OSError when offset is not a multiple of mmap.PAGESIZE on Linux")
835822
def test_flush_return_value(self):
836823
# mm.flush() should return None on success, raise an
837824
# exception on error under all platforms.
@@ -846,7 +833,6 @@ def test_flush_return_value(self):
846833
# See bpo-34754 for details.
847834
self.assertRaises(OSError, mm.flush, 1, len(b'python'))
848835

849-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
850836
def test_repr(self):
851837
open_mmap_repr_pat = re.compile(
852838
r"<mmap.mmap closed=False, "
@@ -948,7 +934,6 @@ def test_resize_up_private_anonymous_mapping(self):
948934
self.assertEqual(m[:start_size], data)
949935
self.assertEqual(m[start_size:], b'\0' * (new_size - start_size))
950936

951-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
952937
@unittest.skipUnless(hasattr(mmap.mmap, 'resize'), 'requires mmap.resize')
953938
def test_resize_down_anonymous_mapping(self):
954939
"""If the mmap is backed by the pagefile ensure a resize down up can happen
@@ -1011,7 +996,6 @@ def __buffer__(self, flags):
1011996
m[0:size] = value
1012997
self.assertEqual(len(m), new_size)
1013998

1014-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
1015999
@unittest.skipUnless(os.name == 'nt', 'requires Windows')
10161000
def test_resize_fails_if_mapping_held_elsewhere(self):
10171001
"""If more than one mapping is held against a named file on Windows, neither
@@ -1036,7 +1020,6 @@ def test_resize_fails_if_mapping_held_elsewhere(self):
10361020
finally:
10371021
f.close()
10381022

1039-
@unittest.expectedFailureIfWindows("TODO: RUSTPYTHON")
10401023
@unittest.skipUnless(os.name == 'nt', 'requires Windows')
10411024
def test_resize_succeeds_with_error_for_second_named_mapping(self):
10421025
"""If a more than one mapping exists of the same name, none of them can

‎crates/host_env/src/mmap.rs‎

Lines changed: 120 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -139,15 +139,15 @@ use std::os::windows::io::{AsRawHandle, IntoRawHandle};
139139
#[cfg(windows)]
140140
use windows_sys::Win32::{
141141
Foundation::{
142-
CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, GetLastError, HANDLE,
143-
INVALID_HANDLE_VALUE,
142+
CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, ERROR_ALREADY_EXISTS,
143+
ERROR_USER_MAPPED_FILE, GetLastError, HANDLE, INVALID_HANDLE_VALUE,
144144
},
145145
Storage::FileSystem::{FILE_BEGIN, GetFileSize, SetEndOfFile, SetFilePointerEx},
146146
System::{
147147
Memory::{
148148
CreateFileMappingW, FILE_MAP_COPY, FILE_MAP_READ, FILE_MAP_WRITE, FlushViewOfFile,
149-
MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, PAGE_READONLY, PAGE_READWRITE,
150-
PAGE_WRITECOPY, UnmapViewOfFile,
149+
MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, OpenFileMappingW, PAGE_READONLY,
150+
PAGE_READWRITE, PAGE_WRITECOPY, UnmapViewOfFile,
151151
},
152152
Threading::GetCurrentProcess,
153153
},
@@ -168,8 +168,9 @@ pub enum AccessMode {
168168

169169
#[cfg(windows)]
170170
#[derive(Debug)]
171-
pub struct NamedMmap {
171+
pub struct WindowsMmap {
172172
map_handle: Handle,
173+
tag: Option<Vec<u16>>,
173174
view_ptr: *mut u8,
174175
len: usize,
175176
}
@@ -267,12 +268,112 @@ pub fn set_mapping_name(address: usize, size: usize, name: &core::ffi::CStr) ->
267268
}
268269

269270
#[cfg(windows)]
270-
unsafe impl Send for NamedMmap {}
271+
unsafe impl Send for WindowsMmap {}
271272
#[cfg(windows)]
272-
unsafe impl Sync for NamedMmap {}
273+
unsafe impl Sync for WindowsMmap {}
273274

274275
#[cfg(windows)]
275-
impl NamedMmap {
276+
impl WindowsMmap {
277+
pub fn is_valid(&self) -> bool {
278+
!self.map_handle.is_null() && !self.view_ptr.is_null()
279+
}
280+
281+
pub fn size(&self) -> usize {
282+
self.len
283+
}
284+
285+
/// Resize like CPython's Windows mmap: retain the old anonymous view until
286+
/// its contents have been copied, but release file views before truncation.
287+
///
288+
/// # Safety
289+
/// No exported pointers may remain live, and the caller must discard an
290+
/// invalid mapping after an error before exposing its contents again.
291+
pub unsafe fn resize(&mut self, file: Handle, offset: i64, new_size: usize) -> io::Result<()> {
292+
let old_data = self.view_ptr;
293+
let mut new_size = new_size;
294+
let mut max_size = offset as u64 + new_size as u64;
295+
let mut file_resize_error = None;
296+
unsafe { CloseHandle(self.map_handle) };
297+
self.map_handle = core::ptr::null_mut();
298+
if let Some(tag) = &self.tag {
299+
self.map_handle = unsafe { OpenFileMappingW(FILE_MAP_WRITE, 0, tag.as_ptr()) };
300+
if !self.map_handle.is_null() {
301+
return Err(io::Error::from_raw_os_error(ERROR_USER_MAPPED_FILE as i32));
302+
}
303+
}
304+
if file != INVALID_HANDLE {
305+
unsafe {
306+
UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS {
307+
Value: self.view_ptr.cast(),
308+
})
309+
}
310+
.check_win32_bool()?;
311+
self.view_ptr = core::ptr::null_mut();
312+
if let Err(err) = extend_file(file, max_size as i64) {
313+
file_resize_error = Some(err);
314+
max_size = self.len as u64;
315+
new_size = self.len;
316+
}
317+
}
318+
self.map_handle = unsafe {
319+
CreateFileMappingW(
320+
file,
321+
core::ptr::null(),
322+
PAGE_READWRITE,
323+
(max_size >> 32) as u32,
324+
max_size as u32,
325+
self.tag
326+
.as_ref()
327+
.map_or(core::ptr::null(), |tag| tag.as_ptr()),
328+
)
329+
};
330+
let error = unsafe { GetLastError() };
331+
// A different mapping may have taken this name between close and create.
332+
if error == ERROR_ALREADY_EXISTS {
333+
unsafe { CloseHandle(self.map_handle) };
334+
self.map_handle = core::ptr::null_mut();
335+
return Err(io::Error::from_raw_os_error(error as i32));
336+
}
337+
if self.map_handle.is_null() {
338+
return Err(io::Error::from_raw_os_error(error as i32));
339+
}
340+
let view = unsafe {
341+
MapViewOfFile(
342+
self.map_handle,
343+
FILE_MAP_WRITE,
344+
(offset as u64 >> 32) as u32,
345+
offset as u32,
346+
new_size,
347+
)
348+
};
349+
if view.Value.is_null() {
350+
let err = io::Error::last_os_error();
351+
unsafe { CloseHandle(self.map_handle) };
352+
self.map_handle = core::ptr::null_mut();
353+
return Err(err);
354+
}
355+
self.view_ptr = view.Value.cast();
356+
if file == INVALID_HANDLE {
357+
unsafe {
358+
core::ptr::copy_nonoverlapping(old_data, self.view_ptr, self.len.min(new_size))
359+
};
360+
let result = unsafe {
361+
UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS {
362+
Value: old_data.cast(),
363+
})
364+
}
365+
.check_win32_bool();
366+
self.len = new_size;
367+
result?;
368+
} else {
369+
self.len = new_size;
370+
}
371+
if let Some(err) = file_resize_error {
372+
return Err(err);
373+
}
374+
Ok(())
375+
}
376+
276377
pub fn as_slice(&self) -> &[u8] {
277378
unsafe { core::slice::from_raw_parts(self.view_ptr, self.len) }
278379
}
@@ -291,7 +392,7 @@ impl NamedMmap {
291392
}
292393

293394
#[cfg(windows)]
294-
impl Drop for NamedMmap {
395+
impl Drop for WindowsMmap {
295396
fn drop(&mut self) {
296397
unsafe {
297398
if !self.view_ptr.is_null() {
@@ -379,6 +480,13 @@ pub fn prepare_file_mapping(fd: i32) {
379480
let _ = unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) };
380481
}
381482

483+
#[cfg(windows)]
484+
pub fn prepare_file_mapping(fd: i32) {
485+
// Match CPython's historical Windows constructor side effect. Seek errors
486+
// are intentionally ignored; CreateFileMapping reports unusable handles.
487+
let _ = unsafe { crate::suppress_iph!(libc::lseek(fd, 0, libc::SEEK_SET)) };
488+
}
489+
382490
#[cfg(windows)]
383491
pub fn is_invalid_handle_value(handle: isize) -> bool {
384492
handle == INVALID_HANDLE as isize
@@ -420,7 +528,7 @@ pub fn create_mapping(
420528
access: AccessMode,
421529
offset: i64,
422530
map_size: usize,
423-
) -> io::Result<NamedMmap> {
531+
) -> io::Result<WindowsMmap> {
424532
let (fl_protect, desired_access) = match access {
425533
AccessMode::Default | AccessMode::Write => (PAGE_READWRITE, FILE_MAP_WRITE),
426534
AccessMode::Read => (PAGE_READONLY, FILE_MAP_READ),
@@ -466,8 +574,9 @@ pub fn create_mapping(
466574
return Err(io::Error::last_os_error());
467575
}
468576

469-
Ok(NamedMmap {
577+
Ok(WindowsMmap {
470578
map_handle: map_handle.into_raw_handle() as Handle,
579+
tag: tag_wide,
471580
view_ptr: view.Value as *mut u8,
472581
len: map_size,
473582
})

0 commit comments

Comments
 (0)