Debian Codegraph @

Lib/test/test_mmap.py

raw
1 from test.support import (
2 requires, _2G, _4G, gc_collect, cpython_only, is_emscripten, is_apple,
3 )
4 from test.support.import_helper import import_module
5 from test.support.os_helper import TESTFN, unlink
6 from test.support.script_helper import assert_python_ok
7 import unittest
8 import errno
9 import os
10 import re
11 import itertools
12 import random
13 import socket
14 import string
15 import sys
16 import textwrap
17 import weakref
18
19 # Skip test if we can't import mmap.
20 mmap = import_module('mmap')
21
22 PAGESIZE = mmap.PAGESIZE
23
24 tagname_prefix = f'python_{os.getpid()}_test_mmap'
25 def random_tagname(length=10):
26 suffix = ''.join(random.choices(string.ascii_uppercase, k=length))
27 return f'{tagname_prefix}_{suffix}'
28
29 # Python's mmap module dup()s the file descriptor. Emscripten's FS layer
30 # does not materialize file changes through a dupped fd to a new mmap.
31 if is_emscripten:
32 raise unittest.SkipTest("incompatible with Emscripten's mmap emulation.")
33
34
35 class MmapTests(unittest.TestCase):
36
37 def setUp(self):
38 if os.path.exists(TESTFN):
39 os.unlink(TESTFN)
40
41 def tearDown(self):
42 try:
43 os.unlink(TESTFN)
44 except OSError:
45 pass
46
47 def test_basic(self):
48 # Test mmap module on Unix systems and Windows
49
50 # Create a file to be mmap'ed.
51 f = open(TESTFN, 'bw+')
52 try:
53 # Write 2 pages worth of data to the file
54 f.write(b'\0'* PAGESIZE)
55 f.write(b'foo')
56 f.write(b'\0'* (PAGESIZE-3) )
57 f.flush()
58 m = mmap.mmap(f.fileno(), 2 * PAGESIZE)
59 finally:
60 f.close()
61
62 # Simple sanity checks
63
64 tp = str(type(m)) # SF bug 128713: segfaulted on Linux
65 self.assertEqual(m.find(b'foo'), PAGESIZE)
66
67 self.assertEqual(len(m), 2*PAGESIZE)
68
69 self.assertEqual(m[0], 0)
70 self.assertEqual(m[0:3], b'\0\0\0')
71
72 # Shouldn't crash on boundary (Issue #5292)
73 self.assertRaises(IndexError, m.__getitem__, len(m))
74 self.assertRaises(IndexError, m.__setitem__, len(m), b'\0')
75
76 # Modify the file's content
77 m[0] = b'3'[0]
78 m[PAGESIZE +3: PAGESIZE +3+3] = b'bar'
79
80 # Check that the modification worked
81 self.assertEqual(m[0], b'3'[0])
82 self.assertEqual(m[0:3], b'3\0\0')
83 self.assertEqual(m[PAGESIZE-1 : PAGESIZE + 7], b'\0foobar\0')
84
85 m.flush()
86
87 # Test doing a regular expression match in an mmap'ed file
88 match = re.search(b'[A-Za-z]+', m)
89 if match is None:
90 self.fail('regex match on mmap failed!')
91 else:
92 start, end = match.span(0)
93 length = end - start
94
95 self.assertEqual(start, PAGESIZE)
96 self.assertEqual(end, PAGESIZE + 6)
97
98 # test seeking around (try to overflow the seek implementation)
99 self.assertTrue(m.seekable())
100 self.assertEqual(m.seek(0, 0), 0)
101 self.assertEqual(m.tell(), 0)
102 self.assertEqual(m.seek(42, 1), 42)
103 self.assertEqual(m.tell(), 42)
104 self.assertEqual(m.seek(0, 2), len(m))
105 self.assertEqual(m.tell(), len(m))
106
107 # Try to seek to negative position...
108 self.assertRaises(ValueError, m.seek, -1)
109
110 # Try to seek beyond end of mmap...
111 self.assertRaises(ValueError, m.seek, 1, 2)
112
113 # Try to seek to negative position...
114 self.assertRaises(ValueError, m.seek, -len(m)-1, 2)
115
116 # Try resizing map
117 try:
118 m.resize(512)
119 except SystemError:
120 # resize() not supported
121 # No messages are printed, since the output of this test suite
122 # would then be different across platforms.
123 pass
124 else:
125 # resize() is supported
126 self.assertEqual(len(m), 512)
127 # Check that we can no longer seek beyond the new size.
128 self.assertRaises(ValueError, m.seek, 513, 0)
129
130 # Check that the underlying file is truncated too
131 # (bug #728515)
132 f = open(TESTFN, 'rb')
133 try:
134 f.seek(0, 2)
135 self.assertEqual(f.tell(), 512)
136 finally:
137 f.close()
138 self.assertEqual(m.size(), 512)
139
140 m.close()
141
142 def test_access_parameter(self):
143 # Test for "access" keyword parameter
144 mapsize = 10
145 with open(TESTFN, "wb") as fp:
146 fp.write(b"a"*mapsize)
147 with open(TESTFN, "rb") as f:
148 m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
149 self.assertEqual(m[:], b'a'*mapsize, "Readonly memory map data incorrect.")
150
151 # Ensuring that readonly mmap can't be slice assigned
152 try:
153 m[:] = b'b'*mapsize
154 except TypeError:
155 pass
156 else:
157 self.fail("Able to write to readonly memory map")
158
159 # Ensuring that readonly mmap can't be item assigned
160 try:
161 m[0] = b'b'
162 except TypeError:
163 pass
164 else:
165 self.fail("Able to write to readonly memory map")
166
167 # Ensuring that readonly mmap can't be write() to
168 try:
169 m.seek(0, 0)
170 m.write(b'abc')
171 except TypeError:
172 pass
173 else:
174 self.fail("Able to write to readonly memory map")
175
176 # Ensuring that readonly mmap can't be write_byte() to
177 try:
178 m.seek(0, 0)
179 m.write_byte(b'd')
180 except TypeError:
181 pass
182 else:
183 self.fail("Able to write to readonly memory map")
184
185 # Ensuring that readonly mmap can't be resized
186 try:
187 m.resize(2*mapsize)
188 except SystemError: # resize is not universally supported
189 pass
190 except TypeError:
191 pass
192 else:
193 self.fail("Able to resize readonly memory map")
194 with open(TESTFN, "rb") as fp:
195 self.assertEqual(fp.read(), b'a'*mapsize,
196 "Readonly memory map data file was modified")
197
198 # Opening mmap with size too big
199 with open(TESTFN, "r+b") as f:
200 try:
201 m = mmap.mmap(f.fileno(), mapsize+1)
202 except ValueError:
203 # we do not expect a ValueError on Windows
204 # CAUTION: This also changes the size of the file on disk, and
205 # later tests assume that the length hasn't changed. We need to
206 # repair that.
207 if sys.platform.startswith('win'):
208 self.fail("Opening mmap with size+1 should work on Windows.")
209 else:
210 # we expect a ValueError on Unix, but not on Windows
211 if not sys.platform.startswith('win'):
212 self.fail("Opening mmap with size+1 should raise ValueError.")
213 m.close()
214 if sys.platform.startswith('win'):
215 # Repair damage from the resizing test.
216 with open(TESTFN, 'r+b') as f:
217 f.truncate(mapsize)
218
219 # Opening mmap with access=ACCESS_WRITE
220 with open(TESTFN, "r+b") as f:
221 m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
222 # Modifying write-through memory map
223 m[:] = b'c'*mapsize
224 self.assertEqual(m[:], b'c'*mapsize,
225 "Write-through memory map memory not updated properly.")
226 m.flush()
227 m.close()
228 with open(TESTFN, 'rb') as f:
229 stuff = f.read()
230 self.assertEqual(stuff, b'c'*mapsize,
231 "Write-through memory map data file not updated properly.")
232
233 # Opening mmap with access=ACCESS_COPY
234 with open(TESTFN, "r+b") as f:
235 m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
236 # Modifying copy-on-write memory map
237 m[:] = b'd'*mapsize
238 self.assertEqual(m[:], b'd' * mapsize,
239 "Copy-on-write memory map data not written correctly.")
240 m.flush()
241 with open(TESTFN, "rb") as fp:
242 self.assertEqual(fp.read(), b'c'*mapsize,
243 "Copy-on-write test data file should not be modified.")
244 # Ensuring copy-on-write maps cannot be resized
245 self.assertRaises(TypeError, m.resize, 2*mapsize)
246 m.close()
247
248 # Ensuring invalid access parameter raises exception
249 with open(TESTFN, "r+b") as f:
250 self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)
251
252 if os.name == "posix":
253 # Try incompatible flags, prot and access parameters.
254 with open(TESTFN, "r+b") as f:
255 self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
256 flags=mmap.MAP_PRIVATE,
257 prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)
258
259 # Try writing with PROT_EXEC and without PROT_WRITE
260 prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
261 with open(TESTFN, "r+b") as f:
262 try:
263 m = mmap.mmap(f.fileno(), mapsize, prot=prot)
264 except PermissionError:
265 # on macOS 14, PROT_READ | PROT_EXEC is not allowed
266 pass
267 else:
268 self.assertRaises(TypeError, m.write, b"abcdef")
269 self.assertRaises(TypeError, m.write_byte, 0)
270 m.close()
271
272 @unittest.skipIf(os.name == 'nt', 'trackfd not present on Windows')
273 def test_trackfd_parameter(self):
274 size = 64
275 with open(TESTFN, "wb") as f:
276 f.write(b"a"*size)
277 for close_original_fd in True, False:
278 with self.subTest(close_original_fd=close_original_fd):
279 with open(TESTFN, "r+b") as f:
280 with mmap.mmap(f.fileno(), size, trackfd=False) as m:
281 if close_original_fd:
282 f.close()
283 self.assertEqual(len(m), size)
284 with self.assertRaises(OSError) as err_cm:
285 m.size()
286 self.assertEqual(err_cm.exception.errno, errno.EBADF)
287 with self.assertRaises(ValueError):
288 m.resize(size * 2)
289 with self.assertRaises(ValueError):
290 m.resize(size // 2)
291 self.assertEqual(m.closed, False)
292
293 # Smoke-test other API
294 m.write_byte(ord('X'))
295 m[2] = ord('Y')
296 m.flush()
297 with open(TESTFN, "rb") as f:
298 self.assertEqual(f.read(4), b'XaYa')
299 self.assertEqual(m.tell(), 1)
300 m.seek(0)
301 self.assertEqual(m.tell(), 0)
302 self.assertEqual(m.read_byte(), ord('X'))
303
304 self.assertEqual(m.closed, True)
305 self.assertEqual(os.stat(TESTFN).st_size, size)
306
307 @unittest.skipIf(os.name == 'nt', 'trackfd not present on Windows')
308 def test_trackfd_neg1(self):
309 size = 64
310 with mmap.mmap(-1, size, trackfd=False) as m:
311 with self.assertRaises(OSError):
312 m.size()
313 with self.assertRaises(ValueError):
314 m.resize(size // 2)
315 self.assertEqual(len(m), size)
316 m[0] = ord('a')
317 assert m[0] == ord('a')
318
319 @unittest.skipIf(os.name != 'nt', 'trackfd only fails on Windows')
320 def test_no_trackfd_parameter_on_windows(self):
321 # 'trackffd' is an invalid keyword argument for this function
322 size = 64
323 with self.assertRaises(TypeError):
324 mmap.mmap(-1, size, trackfd=True)
325 with self.assertRaises(TypeError):
326 mmap.mmap(-1, size, trackfd=False)
327
328 def test_bad_file_desc(self):
329 # Try opening a bad file descriptor...
330 self.assertRaises(OSError, mmap.mmap, -2, 4096)
331
332 def test_tougher_find(self):
333 # Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2,
334 # searching for data with embedded \0 bytes didn't work.
335 with open(TESTFN, 'wb+') as f:
336
337 data = b'aabaac\x00deef\x00\x00aa\x00'
338 n = len(data)
339 f.write(data)
340 f.flush()
341 m = mmap.mmap(f.fileno(), n)
342
343 for start in range(n+1):
344 for finish in range(start, n+1):
345 slice = data[start : finish]
346 self.assertEqual(m.find(slice), data.find(slice))
347 self.assertEqual(m.find(slice + b'x'), -1)
348 m.close()
349
350 def test_find_end(self):
351 # test the new 'end' parameter works as expected
352 with open(TESTFN, 'wb+') as f:
353 data = b'one two ones'
354 n = len(data)
355 f.write(data)
356 f.flush()
357 m = mmap.mmap(f.fileno(), n)
358
359 self.assertEqual(m.find(b'one'), 0)
360 self.assertEqual(m.find(b'ones'), 8)
361 self.assertEqual(m.find(b'one', 0, -1), 0)
362 self.assertEqual(m.find(b'one', 1), 8)
363 self.assertEqual(m.find(b'one', 1, -1), 8)
364 self.assertEqual(m.find(b'one', 1, -2), -1)
365 self.assertEqual(m.find(bytearray(b'one')), 0)
366
367 for i in range(-n-1, n+1):
368 for j in range(-n-1, n+1):
369 for p in [b"o", b"on", b"two", b"ones", b"s"]:
370 expected = data.find(p, i, j)
371 self.assertEqual(m.find(p, i, j), expected, (p, i, j))
372
373 def test_find_does_not_access_beyond_buffer(self):
374 try:
375 flags = mmap.MAP_PRIVATE | mmap.MAP_ANONYMOUS
376 PAGESIZE = mmap.PAGESIZE
377 PROT_NONE = 0
378 PROT_READ = mmap.PROT_READ
379 except AttributeError as e:
380 raise unittest.SkipTest("mmap flags unavailable") from e
381 for i in range(0, 2049):
382 with mmap.mmap(-1, PAGESIZE * (i + 1),
383 flags=flags, prot=PROT_NONE) as guard:
384 with mmap.mmap(-1, PAGESIZE * (i + 2048),
385 flags=flags, prot=PROT_READ) as fm:
386 fm.find(b"fo", -2)
387
388
389 def test_rfind(self):
390 # test the new 'end' parameter works as expected
391 with open(TESTFN, 'wb+') as f:
392 data = b'one two ones'
393 n = len(data)
394 f.write(data)
395 f.flush()
396 m = mmap.mmap(f.fileno(), n)
397
398 self.assertEqual(m.rfind(b'one'), 8)
399 self.assertEqual(m.rfind(b'one '), 0)
400 self.assertEqual(m.rfind(b'one', 0, -1), 8)
401 self.assertEqual(m.rfind(b'one', 0, -2), 0)
402 self.assertEqual(m.rfind(b'one', 1, -1), 8)
403 self.assertEqual(m.rfind(b'one', 1, -2), -1)
404 self.assertEqual(m.rfind(bytearray(b'one')), 8)
405
406
407 def test_double_close(self):
408 # make sure a double close doesn't crash on Solaris (Bug# 665913)
409 with open(TESTFN, 'wb+') as f:
410 f.write(2**16 * b'a') # Arbitrary character
411
412 with open(TESTFN, 'rb') as f:
413 mf = mmap.mmap(f.fileno(), 2**16, access=mmap.ACCESS_READ)
414 mf.close()
415 mf.close()
416
417 def test_entire_file(self):
418 # test mapping of entire file by passing 0 for map length
419 with open(TESTFN, "wb+") as f:
420 f.write(2**16 * b'm') # Arbitrary character
421
422 with open(TESTFN, "rb+") as f, \
423 mmap.mmap(f.fileno(), 0) as mf:
424 self.assertEqual(len(mf), 2**16, "Map size should equal file size.")
425 self.assertEqual(mf.read(2**16), 2**16 * b"m")
426
427 def test_length_0_offset(self):
428 # Issue #10916: test mapping of remainder of file by passing 0 for
429 # map length with an offset doesn't cause a segfault.
430 # NOTE: allocation granularity is currently 65536 under Win64,
431 # and therefore the minimum offset alignment.
432 with open(TESTFN, "wb") as f:
433 f.write((65536 * 2) * b'm') # Arbitrary character
434
435 with open(TESTFN, "rb") as f:
436 with mmap.mmap(f.fileno(), 0, offset=65536, access=mmap.ACCESS_READ) as mf:
437 self.assertRaises(IndexError, mf.__getitem__, 80000)
438
439 def test_length_0_large_offset(self):
440 # Issue #10959: test mapping of a file by passing 0 for
441 # map length with a large offset doesn't cause a segfault.
442 with open(TESTFN, "wb") as f:
443 f.write(115699 * b'm') # Arbitrary character
444
445 with open(TESTFN, "w+b") as f:
446 self.assertRaises(ValueError, mmap.mmap, f.fileno(), 0,
447 offset=2147418112)
448
449 def test_move(self):
450 # make move works everywhere (64-bit format problem earlier)
451 with open(TESTFN, 'wb+') as f:
452
453 f.write(b"ABCDEabcde") # Arbitrary character
454 f.flush()
455
456 mf = mmap.mmap(f.fileno(), 10)
457 mf.move(5, 0, 5)
458 self.assertEqual(mf[:], b"ABCDEABCDE", "Map move should have duplicated front 5")
459 mf.close()
460
461 # more excessive test
462 data = b"0123456789"
463 for dest in range(len(data)):
464 for src in range(len(data)):
465 for count in range(len(data) - max(dest, src)):
466 expected = data[:dest] + data[src:src+count] + data[dest+count:]
467 m = mmap.mmap(-1, len(data))
468 m[:] = data
469 m.move(dest, src, count)
470 self.assertEqual(m[:], expected)
471 m.close()
472
473 # segfault test (Issue 5387)
474 m = mmap.mmap(-1, 100)
475 offsets = [-100, -1, 0, 1, 100]
476 for source, dest, size in itertools.product(offsets, offsets, offsets):
477 try:
478 m.move(source, dest, size)
479 except ValueError:
480 pass
481
482 offsets = [(-1, -1, -1), (-1, -1, 0), (-1, 0, -1), (0, -1, -1),
483 (-1, 0, 0), (0, -1, 0), (0, 0, -1)]
484 for source, dest, size in offsets:
485 self.assertRaises(ValueError, m.move, source, dest, size)
486
487 m.close()
488
489 m = mmap.mmap(-1, 1) # single byte
490 self.assertRaises(ValueError, m.move, 0, 0, 2)
491 self.assertRaises(ValueError, m.move, 1, 0, 1)
492 self.assertRaises(ValueError, m.move, 0, 1, 1)
493 m.move(0, 0, 1)
494 m.move(0, 0, 0)
495
496 def test_anonymous(self):
497 # anonymous mmap.mmap(-1, PAGE)
498 m = mmap.mmap(-1, PAGESIZE)
499 for x in range(PAGESIZE):
500 self.assertEqual(m[x], 0,
501 "anonymously mmap'ed contents should be zero")
502
503 for x in range(PAGESIZE):
504 b = x & 0xff
505 m[x] = b
506 self.assertEqual(m[x], b)
507
508 def test_read_all(self):
509 m = mmap.mmap(-1, 16)
510 self.addCleanup(m.close)
511
512 # With no parameters, or None or a negative argument, reads all
513 m.write(bytes(range(16)))
514 m.seek(0)
515 self.assertEqual(m.read(), bytes(range(16)))
516 m.seek(8)
517 self.assertEqual(m.read(), bytes(range(8, 16)))
518 m.seek(16)
519 self.assertEqual(m.read(), b'')
520 m.seek(3)
521 self.assertEqual(m.read(None), bytes(range(3, 16)))
522 m.seek(4)
523 self.assertEqual(m.read(-1), bytes(range(4, 16)))
524 m.seek(5)
525 self.assertEqual(m.read(-2), bytes(range(5, 16)))
526 m.seek(9)
527 self.assertEqual(m.read(-42), bytes(range(9, 16)))
528
529 def test_read_invalid_arg(self):
530 m = mmap.mmap(-1, 16)
531 self.addCleanup(m.close)
532
533 self.assertRaises(TypeError, m.read, 'foo')
534 self.assertRaises(TypeError, m.read, 5.5)
535 self.assertRaises(TypeError, m.read, [1, 2, 3])
536
537 def test_extended_getslice(self):
538 # Test extended slicing by comparing with list slicing.
539 s = bytes(reversed(range(256)))
540 m = mmap.mmap(-1, len(s))
541 m[:] = s
542 self.assertEqual(m[:], s)
543 indices = (0, None, 1, 3, 19, 300, sys.maxsize, -1, -2, -31, -300)
544 for start in indices:
545 for stop in indices:
546 # Skip step 0 (invalid)
547 for step in indices[1:]:
548 self.assertEqual(m[start:stop:step],
549 s[start:stop:step])
550
551 def test_extended_set_del_slice(self):
552 # Test extended slicing by comparing with list slicing.
553 s = bytes(reversed(range(256)))
554 m = mmap.mmap(-1, len(s))
555 indices = (0, None, 1, 3, 19, 300, sys.maxsize, -1, -2, -31, -300)
556 for start in indices:
557 for stop in indices:
558 # Skip invalid step 0
559 for step in indices[1:]:
560 m[:] = s
561 self.assertEqual(m[:], s)
562 L = list(s)
563 # Make sure we have a slice of exactly the right length,
564 # but with different data.
565 data = L[start:stop:step]
566 data = bytes(reversed(data))
567 L[start:stop:step] = data
568 m[start:stop:step] = data
569 self.assertEqual(m[:], bytes(L))
570
571 def make_mmap_file (self, f, halfsize):
572 # Write 2 pages worth of data to the file
573 f.write (b'\0' * halfsize)
574 f.write (b'foo')
575 f.write (b'\0' * (halfsize - 3))
576 f.flush ()
577 return mmap.mmap (f.fileno(), 0)
578
579 def test_empty_file (self):
580 f = open (TESTFN, 'w+b')
581 f.close()
582 with open(TESTFN, "rb") as f :
583 self.assertRaisesRegex(ValueError,
584 "cannot mmap an empty file",
585 mmap.mmap, f.fileno(), 0,
586 access=mmap.ACCESS_READ)
587
588 def test_offset (self):
589 f = open (TESTFN, 'w+b')
590
591 try: # unlink TESTFN no matter what
592 halfsize = mmap.ALLOCATIONGRANULARITY
593 m = self.make_mmap_file (f, halfsize)
594 m.close ()
595 f.close ()
596
597 mapsize = halfsize * 2
598 # Try invalid offset
599 f = open(TESTFN, "r+b")
600 for offset in [-2, -1, None]:
601 try:
602 m = mmap.mmap(f.fileno(), mapsize, offset=offset)
603 self.assertEqual(0, 1)
604 except (ValueError, TypeError, OverflowError):
605 pass
606 else:
607 self.assertEqual(0, 0)
608 f.close()
609
610 # Try valid offset, hopefully 8192 works on all OSes
611 f = open(TESTFN, "r+b")
612 m = mmap.mmap(f.fileno(), mapsize - halfsize, offset=halfsize)
613 self.assertEqual(m[0:3], b'foo')
614 f.close()
615
616 # Try resizing map
617 try:
618 m.resize(512)
619 except SystemError:
620 pass
621 else:
622 # resize() is supported
623 self.assertEqual(len(m), 512)
624 # Check that we can no longer seek beyond the new size.
625 self.assertRaises(ValueError, m.seek, 513, 0)
626 # Check that the content is not changed
627 self.assertEqual(m[0:3], b'foo')
628
629 # Check that the underlying file is truncated too
630 f = open(TESTFN, 'rb')
631 f.seek(0, 2)
632 self.assertEqual(f.tell(), halfsize + 512)
633 f.close()
634 self.assertEqual(m.size(), halfsize + 512)
635
636 m.close()
637
638 finally:
639 f.close()
640 try:
641 os.unlink(TESTFN)
642 except OSError:
643 pass
644
645 def test_subclass(self):
646 class anon_mmap(mmap.mmap):
647 def __new__(klass, *args, **kwargs):
648 return mmap.mmap.__new__(klass, -1, *args, **kwargs)
649 anon_mmap(PAGESIZE)
650
651 @unittest.skipUnless(hasattr(mmap, 'PROT_READ'), "needs mmap.PROT_READ")
652 def test_prot_readonly(self):
653 mapsize = 10
654 with open(TESTFN, "wb") as fp:
655 fp.write(b"a"*mapsize)
656 with open(TESTFN, "rb") as f:
657 m = mmap.mmap(f.fileno(), mapsize, prot=mmap.PROT_READ)
658 self.assertRaises(TypeError, m.write, "foo")
659
660 def test_error(self):
661 self.assertIs(mmap.error, OSError)
662
663 def test_io_methods(self):
664 data = b"0123456789"
665 with open(TESTFN, "wb") as fp:
666 fp.write(b"x"*len(data))
667 with open(TESTFN, "r+b") as f:
668 m = mmap.mmap(f.fileno(), len(data))
669 # Test write_byte()
670 for i in range(len(data)):
671 self.assertEqual(m.tell(), i)
672 m.write_byte(data[i])
673 self.assertEqual(m.tell(), i+1)
674 self.assertRaises(ValueError, m.write_byte, b"x"[0])
675 self.assertEqual(m[:], data)
676 # Test read_byte()
677 m.seek(0)
678 for i in range(len(data)):
679 self.assertEqual(m.tell(), i)
680 self.assertEqual(m.read_byte(), data[i])
681 self.assertEqual(m.tell(), i+1)
682 self.assertRaises(ValueError, m.read_byte)
683 # Test read()
684 m.seek(3)
685 self.assertEqual(m.read(3), b"345")
686 self.assertEqual(m.tell(), 6)
687 # Test write()
688 m.seek(3)
689 m.write(b"bar")
690 self.assertEqual(m.tell(), 6)
691 self.assertEqual(m[:], b"012bar6789")
692 m.write(bytearray(b"baz"))
693 self.assertEqual(m.tell(), 9)
694 self.assertEqual(m[:], b"012barbaz9")
695 self.assertRaises(ValueError, m.write, b"ba")
696
697 def test_non_ascii_byte(self):
698 for b in (129, 200, 255): # > 128
699 m = mmap.mmap(-1, 1)
700 m.write_byte(b)
701 self.assertEqual(m[0], b)
702 m.seek(0)
703 self.assertEqual(m.read_byte(), b)
704 m.close()
705
706 @unittest.skipUnless(os.name == 'nt', 'requires Windows')
707 def test_tagname(self):
708 data1 = b"0123456789"
709 data2 = b"abcdefghij"
710 assert len(data1) == len(data2)
711 tagname1 = random_tagname()
712 tagname2 = random_tagname()
713
714 # Test same tag
715 m1 = mmap.mmap(-1, len(data1), tagname=tagname1)
716 m1[:] = data1
717 m2 = mmap.mmap(-1, len(data2), tagname=tagname1)
718 m2[:] = data2
719 self.assertEqual(m1[:], data2)
720 self.assertEqual(m2[:], data2)
721 m2.close()
722 m1.close()
723
724 # Test different tag
725 m1 = mmap.mmap(-1, len(data1), tagname=tagname1)
726 m1[:] = data1
727 m2 = mmap.mmap(-1, len(data2), tagname=tagname2)
728 m2[:] = data2
729 self.assertEqual(m1[:], data1)
730 self.assertEqual(m2[:], data2)
731 m2.close()
732 m1.close()
733
734 with self.assertRaisesRegex(TypeError, 'tagname'):
735 mmap.mmap(-1, 8, tagname=1)
736
737 @cpython_only
738 @unittest.skipUnless(os.name == 'nt', 'requires Windows')
739 def test_sizeof(self):
740 m1 = mmap.mmap(-1, 100)
741 tagname = random_tagname()
742 m2 = mmap.mmap(-1, 100, tagname=tagname)
743 self.assertGreater(sys.getsizeof(m2), sys.getsizeof(m1))
744
745 @unittest.skipUnless(os.name == 'nt', 'requires Windows')
746 def test_crasher_on_windows(self):
747 # Should not crash (Issue 1733986)
748 tagname = random_tagname()
749 m = mmap.mmap(-1, 1000, tagname=tagname)
750 try:
751 mmap.mmap(-1, 5000, tagname=tagname)[:] # same tagname, but larger size
752 except:
753 pass
754 m.close()
755
756 # Should not crash (Issue 5385)
757 with open(TESTFN, "wb") as fp:
758 fp.write(b"x"*10)
759 f = open(TESTFN, "r+b")
760 m = mmap.mmap(f.fileno(), 0)
761 f.close()
762 try:
763 m.resize(0) # will raise OSError
764 except:
765 pass
766 try:
767 m[:]
768 except:
769 pass
770 m.close()
771
772 @unittest.skipUnless(os.name == 'nt', 'requires Windows')
773 def test_invalid_descriptor(self):
774 # socket file descriptors are valid, but out of range
775 # for _get_osfhandle, causing a crash when validating the
776 # parameters to _get_osfhandle.
777 s = socket.socket()
778 try:
779 with self.assertRaises(OSError):
780 m = mmap.mmap(s.fileno(), 10)
781 finally:
782 s.close()
783
784 def test_context_manager(self):
785 with mmap.mmap(-1, 10) as m:
786 self.assertFalse(m.closed)
787 self.assertTrue(m.closed)
788
789 def test_context_manager_exception(self):
790 # Test that the OSError gets passed through
791 with self.assertRaises(Exception) as exc:
792 with mmap.mmap(-1, 10) as m:
793 raise OSError
794 self.assertIsInstance(exc.exception, OSError,
795 "wrong exception raised in context manager")
796 self.assertTrue(m.closed, "context manager failed")
797
798 def test_weakref(self):
799 # Check mmap objects are weakrefable
800 mm = mmap.mmap(-1, 16)
801 wr = weakref.ref(mm)
802 self.assertIs(wr(), mm)
803 del mm
804 gc_collect()
805 self.assertIs(wr(), None)
806
807 def test_write_returning_the_number_of_bytes_written(self):
808 mm = mmap.mmap(-1, 16)
809 self.assertEqual(mm.write(b""), 0)
810 self.assertEqual(mm.write(b"x"), 1)
811 self.assertEqual(mm.write(b"yz"), 2)
812 self.assertEqual(mm.write(b"python"), 6)
813
814 def test_resize_past_pos(self):
815 m = mmap.mmap(-1, 8192)
816 self.addCleanup(m.close)
817 m.read(5000)
818 try:
819 m.resize(4096)
820 except SystemError:
821 self.skipTest("resizing not supported")
822 self.assertEqual(m.read(14), b'')
823 self.assertRaises(ValueError, m.read_byte)
824 self.assertRaises(ValueError, m.write_byte, 42)
825 self.assertRaises(ValueError, m.write, b'abc')
826
827 def test_concat_repeat_exception(self):
828 m = mmap.mmap(-1, 16)
829 with self.assertRaises(TypeError):
830 m + m
831 with self.assertRaises(TypeError):
832 m * 2
833
834 def test_flush_return_value(self):
835 # mm.flush() should return None on success, raise an
836 # exception on error under all platforms.
837 mm = mmap.mmap(-1, 16)
838 self.addCleanup(mm.close)
839 mm.write(b'python')
840 result = mm.flush()
841 self.assertIsNone(result)
842 if sys.platform.startswith(('linux', 'android')):
843 # 'offset' must be a multiple of mmap.PAGESIZE on Linux.
844 # See bpo-34754 for details.
845 self.assertRaises(OSError, mm.flush, 1, len(b'python'))
846
847 def test_repr(self):
848 open_mmap_repr_pat = re.compile(
849 r"<mmap.mmap closed=False, "
850 r"access=(?P<access>\S+), "
851 r"length=(?P<length>\d+), "
852 r"pos=(?P<pos>\d+), "
853 r"offset=(?P<offset>\d+)>")
854 closed_mmap_repr_pat = re.compile(r"<mmap.mmap closed=True>")
855 mapsizes = (50, 100, 1_000, 1_000_000, 10_000_000)
856 offsets = tuple((mapsize // 2 // mmap.ALLOCATIONGRANULARITY)
857 * mmap.ALLOCATIONGRANULARITY for mapsize in mapsizes)
858 for offset, mapsize in zip(offsets, mapsizes):
859 data = b'a' * mapsize
860 length = mapsize - offset
861 accesses = ('ACCESS_DEFAULT', 'ACCESS_READ',
862 'ACCESS_COPY', 'ACCESS_WRITE')
863 positions = (0, length//10, length//5, length//4)
864 with open(TESTFN, "wb+") as fp:
865 fp.write(data)
866 fp.flush()
867 for access, pos in itertools.product(accesses, positions):
868 accint = getattr(mmap, access)
869 with mmap.mmap(fp.fileno(),
870 length,
871 access=accint,
872 offset=offset) as mm:
873 mm.seek(pos)
874 match = open_mmap_repr_pat.match(repr(mm))
875 self.assertIsNotNone(match)
876 self.assertEqual(match.group('access'), access)
877 self.assertEqual(match.group('length'), str(length))
878 self.assertEqual(match.group('pos'), str(pos))
879 self.assertEqual(match.group('offset'), str(offset))
880 match = closed_mmap_repr_pat.match(repr(mm))
881 self.assertIsNotNone(match)
882
883 @unittest.skipUnless(hasattr(mmap.mmap, 'madvise'), 'needs madvise')
884 def test_madvise(self):
885 size = 2 * PAGESIZE
886 m = mmap.mmap(-1, size)
887
888 with self.assertRaisesRegex(ValueError, "madvise start out of bounds"):
889 m.madvise(mmap.MADV_NORMAL, size)
890 with self.assertRaisesRegex(ValueError, "madvise start out of bounds"):
891 m.madvise(mmap.MADV_NORMAL, -1)
892 with self.assertRaisesRegex(ValueError, "madvise length invalid"):
893 m.madvise(mmap.MADV_NORMAL, 0, -1)
894 with self.assertRaisesRegex(OverflowError, "madvise length too large"):
895 m.madvise(mmap.MADV_NORMAL, PAGESIZE, sys.maxsize)
896 self.assertEqual(m.madvise(mmap.MADV_NORMAL), None)
897 self.assertEqual(m.madvise(mmap.MADV_NORMAL, PAGESIZE), None)
898 self.assertEqual(m.madvise(mmap.MADV_NORMAL, PAGESIZE, size), None)
899 self.assertEqual(m.madvise(mmap.MADV_NORMAL, 0, 2), None)
900 self.assertEqual(m.madvise(mmap.MADV_NORMAL, 0, size), None)
901
902 def test_resize_up_anonymous_mapping(self):
903 """If the mmap is backed by the pagefile ensure a resize up can happen
904 and that the original data is still in place
905 """
906 start_size = PAGESIZE
907 new_size = 2 * start_size
908 data = random.randbytes(start_size)
909
910 with mmap.mmap(-1, start_size) as m:
911 m[:] = data
912 if sys.platform.startswith(('linux', 'android')):
913 # Can't expand a shared anonymous mapping on Linux.
914 # See https://bugzilla.kernel.org/show_bug.cgi?id=8691
915 with self.assertRaises(ValueError):
916 m.resize(new_size)
917 else:
918 try:
919 m.resize(new_size)
920 except SystemError:
921 pass
922 else:
923 self.assertEqual(len(m), new_size)
924 self.assertEqual(m[:start_size], data)
925 self.assertEqual(m[start_size:], b'\0' * (new_size - start_size))
926
927 @unittest.skipUnless(os.name == 'posix', 'requires Posix')
928 def test_resize_up_private_anonymous_mapping(self):
929 start_size = PAGESIZE
930 new_size = 2 * start_size
931 data = random.randbytes(start_size)
932
933 with mmap.mmap(-1, start_size, flags=mmap.MAP_PRIVATE) as m:
934 m[:] = data
935 try:
936 m.resize(new_size)
937 except SystemError:
938 pass
939 else:
940 self.assertEqual(len(m), new_size)
941 self.assertEqual(m[:start_size], data)
942 self.assertEqual(m[start_size:], b'\0' * (new_size - start_size))
943
944 def test_resize_down_anonymous_mapping(self):
945 """If the mmap is backed by the pagefile ensure a resize down up can happen
946 and that a truncated form of the original data is still in place
947 """
948 start_size = 2 * PAGESIZE
949 new_size = start_size // 2
950 data = random.randbytes(start_size)
951
952 with mmap.mmap(-1, start_size) as m:
953 m[:] = data
954 try:
955 m.resize(new_size)
956 except SystemError:
957 pass
958 else:
959 self.assertEqual(len(m), new_size)
960 self.assertEqual(m[:], data[:new_size])
961 if sys.platform.startswith(('linux', 'android')):
962 # Can't expand to its original size.
963 with self.assertRaises(ValueError):
964 m.resize(start_size)
965
966 @unittest.skipUnless(os.name == 'nt', 'requires Windows')
967 def test_resize_fails_if_mapping_held_elsewhere(self):
968 """If more than one mapping is held against a named file on Windows, neither
969 mapping can be resized
970 """
971 start_size = 2 * PAGESIZE
972 reduced_size = PAGESIZE
973
974 f = open(TESTFN, 'wb+')
975 f.truncate(start_size)
976 try:
977 m1 = mmap.mmap(f.fileno(), start_size)
978 m2 = mmap.mmap(f.fileno(), start_size)
979 with self.assertRaises(OSError):
980 m1.resize(reduced_size)
981 with self.assertRaises(OSError):
982 m2.resize(reduced_size)
983 m2.close()
984 m1.resize(reduced_size)
985 self.assertEqual(m1.size(), reduced_size)
986 self.assertEqual(os.stat(f.fileno()).st_size, reduced_size)
987 finally:
988 f.close()
989
990 @unittest.skipUnless(os.name == 'nt', 'requires Windows')
991 def test_resize_succeeds_with_error_for_second_named_mapping(self):
992 """If a more than one mapping exists of the same name, none of them can
993 be resized: they'll raise an Exception and leave the original mapping intact
994 """
995 start_size = 2 * PAGESIZE
996 reduced_size = PAGESIZE
997 tagname = random_tagname()
998 data_length = 8
999 data = bytes(random.getrandbits(8) for _ in range(data_length))
1000
1001 m1 = mmap.mmap(-1, start_size, tagname=tagname)
1002 m2 = mmap.mmap(-1, start_size, tagname=tagname)
1003 m1[:data_length] = data
1004 self.assertEqual(m2[:data_length], data)
1005 with self.assertRaises(OSError):
1006 m1.resize(reduced_size)
1007 self.assertEqual(m1.size(), start_size)
1008 self.assertEqual(m1[:data_length], data)
1009 self.assertEqual(m2[:data_length], data)
1010
1011 def test_mmap_closed_by_int_scenarios(self):
1012 """
1013 gh-103987: Test that mmap objects raise ValueError
1014 for closed mmap files
1015 """
1016
1017 class MmapClosedByIntContext:
1018 def __init__(self, access) -> None:
1019 self.access = access
1020
1021 def __enter__(self):
1022 self.f = open(TESTFN, "w+b")
1023 self.f.write(random.randbytes(100))
1024 self.f.flush()
1025
1026 m = mmap.mmap(self.f.fileno(), 100, access=self.access)
1027
1028 class X:
1029 def __index__(self):
1030 m.close()
1031 return 10
1032
1033 return (m, X)
1034
1035 def __exit__(self, exc_type, exc_value, traceback):
1036 self.f.close()
1037
1038 read_access_modes = [
1039 mmap.ACCESS_READ,
1040 mmap.ACCESS_WRITE,
1041 mmap.ACCESS_COPY,
1042 mmap.ACCESS_DEFAULT,
1043 ]
1044
1045 write_access_modes = [
1046 mmap.ACCESS_WRITE,
1047 mmap.ACCESS_COPY,
1048 mmap.ACCESS_DEFAULT,
1049 ]
1050
1051 for access in read_access_modes:
1052 with MmapClosedByIntContext(access) as (m, X):
1053 with self.assertRaisesRegex(ValueError, "mmap closed or invalid"):
1054 m[X()]
1055
1056 with MmapClosedByIntContext(access) as (m, X):
1057 with self.assertRaisesRegex(ValueError, "mmap closed or invalid"):
1058 m[X() : 20]
1059
1060 with MmapClosedByIntContext(access) as (m, X):
1061 with self.assertRaisesRegex(ValueError, "mmap closed or invalid"):
1062 m[X() : 20 : 2]
1063
1064 with MmapClosedByIntContext(access) as (m, X):
1065 with self.assertRaisesRegex(ValueError, "mmap closed or invalid"):
1066 m[20 : X() : -2]
1067
1068 with MmapClosedByIntContext(access) as (m, X):
1069 with self.assertRaisesRegex(ValueError, "mmap closed or invalid"):
1070 m.read(X())
1071
1072 with MmapClosedByIntContext(access) as (m, X):
1073 with self.assertRaisesRegex(ValueError, "mmap closed or invalid"):
1074 m.find(b"1", 1, X())
1075
1076 for access in write_access_modes:
1077 with MmapClosedByIntContext(access) as (m, X):
1078 with self.assertRaisesRegex(ValueError, "mmap closed or invalid"):
1079 m[X() : 20] = b"1" * 10
1080
1081 with MmapClosedByIntContext(access) as (m, X):
1082 with self.assertRaisesRegex(ValueError, "mmap closed or invalid"):
1083 m[X() : 20 : 2] = b"1" * 5
1084
1085 with MmapClosedByIntContext(access) as (m, X):
1086 with self.assertRaisesRegex(ValueError, "mmap closed or invalid"):
1087 m[20 : X() : -2] = b"1" * 5
1088
1089 with MmapClosedByIntContext(access) as (m, X):
1090 with self.assertRaisesRegex(ValueError, "mmap closed or invalid"):
1091 m.move(1, 2, X())
1092
1093 with MmapClosedByIntContext(access) as (m, X):
1094 with self.assertRaisesRegex(ValueError, "mmap closed or invalid"):
1095 m.write_byte(X())
1096
1097 @unittest.skipUnless(os.name == 'nt', 'requires Windows')
1098 @unittest.skipUnless(hasattr(mmap.mmap, '_protect'), 'test needs debug build')
1099 def test_access_violations(self):
1100 from test.support.os_helper import TESTFN
1101
1102 code = textwrap.dedent("""
1103 import faulthandler
1104 import mmap
1105 import os
1106 import sys
1107 from contextlib import suppress
1108
1109 # Prevent logging access violations to stderr.
1110 faulthandler.disable()
1111
1112 PAGESIZE = mmap.PAGESIZE
1113 PAGE_NOACCESS = 0x01
1114
1115 with open(sys.argv[1], 'bw+') as f:
1116 f.write(b'A'* PAGESIZE)
1117 f.flush()
1118
1119 m = mmap.mmap(f.fileno(), PAGESIZE)
1120 m._protect(PAGE_NOACCESS, 0, PAGESIZE)
1121 with suppress(OSError):
1122 m.read(PAGESIZE)
1123 assert False, 'mmap.read() did not raise'
1124 with suppress(OSError):
1125 m.read_byte()
1126 assert False, 'mmap.read_byte() did not raise'
1127 with suppress(OSError):
1128 m.readline()
1129 assert False, 'mmap.readline() did not raise'
1130 with suppress(OSError):
1131 m.write(b'A'* PAGESIZE)
1132 assert False, 'mmap.write() did not raise'
1133 with suppress(OSError):
1134 m.write_byte(0)
1135 assert False, 'mmap.write_byte() did not raise'
1136 with suppress(OSError):
1137 m[0] # test mmap_subscript
1138 assert False, 'mmap.__getitem__() did not raise'
1139 with suppress(OSError):
1140 m[0:10] # test mmap_subscript
1141 assert False, 'mmap.__getitem__() did not raise'
1142 with suppress(OSError):
1143 m[0:10:2] # test mmap_subscript
1144 assert False, 'mmap.__getitem__() did not raise'
1145 with suppress(OSError):
1146 m[0] = 1
1147 assert False, 'mmap.__setitem__() did not raise'
1148 with suppress(OSError):
1149 m[0:10] = b'A'* 10
1150 assert False, 'mmap.__setitem__() did not raise'
1151 with suppress(OSError):
1152 m[0:10:2] = b'A'* 5
1153 assert False, 'mmap.__setitem__() did not raise'
1154 with suppress(OSError):
1155 m.move(0, 10, 1)
1156 assert False, 'mmap.move() did not raise'
1157 with suppress(OSError):
1158 list(m) # test mmap_item
1159 assert False, 'mmap.__getitem__() did not raise'
1160 with suppress(OSError):
1161 m.find(b'A')
1162 assert False, 'mmap.find() did not raise'
1163 with suppress(OSError):
1164 m.rfind(b'A')
1165 assert False, 'mmap.rfind() did not raise'
1166 """)
1167 rt, stdout, stderr = assert_python_ok("-c", code, TESTFN)
1168 self.assertEqual(stdout.strip(), b'')
1169 self.assertEqual(stderr.strip(), b'')
1170
1171
1172 class LargeMmapTests(unittest.TestCase):
1173
1174 def setUp(self):
1175 unlink(TESTFN)
1176
1177 def tearDown(self):
1178 unlink(TESTFN)
1179
1180 def _make_test_file(self, num_zeroes, tail):
1181 if sys.platform[:3] == 'win' or is_apple:
1182 requires('largefile',
1183 'test requires %s bytes and a long time to run' % str(0x180000000))
1184 f = open(TESTFN, 'w+b')
1185 try:
1186 f.seek(num_zeroes)
1187 f.write(tail)
1188 f.flush()
1189 except (OSError, OverflowError, ValueError):
1190 try:
1191 f.close()
1192 except (OSError, OverflowError):
1193 pass
1194 raise unittest.SkipTest("filesystem does not have largefile support")
1195 return f
1196
1197 def test_large_offset(self):
1198 with self._make_test_file(0x14FFFFFFF, b" ") as f:
1199 with mmap.mmap(f.fileno(), 0, offset=0x140000000, access=mmap.ACCESS_READ) as m:
1200 self.assertEqual(m[0xFFFFFFF], 32)
1201
1202 def test_large_filesize(self):
1203 with self._make_test_file(0x17FFFFFFF, b" ") as f:
1204 if sys.maxsize < 0x180000000:
1205 # On 32 bit platforms the file is larger than sys.maxsize so
1206 # mapping the whole file should fail -- Issue #16743
1207 with self.assertRaises(OverflowError):
1208 mmap.mmap(f.fileno(), 0x180000000, access=mmap.ACCESS_READ)
1209 with self.assertRaises(ValueError):
1210 mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
1211 with mmap.mmap(f.fileno(), 0x10000, access=mmap.ACCESS_READ) as m:
1212 self.assertEqual(m.size(), 0x180000000)
1213
1214 # Issue 11277: mmap() with large (~4 GiB) sparse files crashes on OS X.
1215
1216 def _test_around_boundary(self, boundary):
1217 tail = b' DEARdear '
1218 start = boundary - len(tail) // 2
1219 end = start + len(tail)
1220 with self._make_test_file(start, tail) as f:
1221 with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m:
1222 self.assertEqual(m[start:end], tail)
1223
1224 @unittest.skipUnless(sys.maxsize > _4G, "test cannot run on 32-bit systems")
1225 def test_around_2GB(self):
1226 self._test_around_boundary(_2G)
1227
1228 @unittest.skipUnless(sys.maxsize > _4G, "test cannot run on 32-bit systems")
1229 def test_around_4GB(self):
1230 self._test_around_boundary(_4G)
1231
1232
1233 if __name__ == '__main__':
1234 unittest.main()