test_mmap.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. from test.test_support import (TESTFN, run_unittest, import_module, unlink,
  2. requires, _2G, _4G, gc_collect, cpython_only)
  3. import unittest
  4. import os, re, itertools, socket, sys
  5. mmap = import_module('mmap')
  6. PAGESIZE = mmap.PAGESIZE
  7. class MmapTests(unittest.TestCase):
  8. def setUp(self):
  9. if os.path.exists(TESTFN):
  10. os.unlink(TESTFN)
  11. def tearDown(self):
  12. try:
  13. os.unlink(TESTFN)
  14. except OSError:
  15. pass
  16. def test_basic(self):
  17. # Test mmap module on Unix systems and Windows
  18. # Create a file to be mmap'ed.
  19. f = open(TESTFN, 'w+')
  20. try:
  21. # Write 2 pages worth of data to the file
  22. f.write('\0'* PAGESIZE)
  23. f.write('foo')
  24. f.write('\0'* (PAGESIZE-3) )
  25. f.flush()
  26. m = mmap.mmap(f.fileno(), 2 * PAGESIZE)
  27. f.close()
  28. # Simple sanity checks
  29. tp = str(type(m)) # SF bug 128713: segfaulted on Linux
  30. self.assertEqual(m.find('foo'), PAGESIZE)
  31. self.assertEqual(len(m), 2*PAGESIZE)
  32. self.assertEqual(m[0], '\0')
  33. self.assertEqual(m[0:3], '\0\0\0')
  34. # Shouldn't crash on boundary (Issue #5292)
  35. self.assertRaises(IndexError, m.__getitem__, len(m))
  36. self.assertRaises(IndexError, m.__setitem__, len(m), '\0')
  37. # Modify the file's content
  38. m[0] = '3'
  39. m[PAGESIZE +3: PAGESIZE +3+3] = 'bar'
  40. # Check that the modification worked
  41. self.assertEqual(m[0], '3')
  42. self.assertEqual(m[0:3], '3\0\0')
  43. self.assertEqual(m[PAGESIZE-1 : PAGESIZE + 7], '\0foobar\0')
  44. m.flush()
  45. # Test doing a regular expression match in an mmap'ed file
  46. match = re.search('[A-Za-z]+', m)
  47. if match is None:
  48. self.fail('regex match on mmap failed!')
  49. else:
  50. start, end = match.span(0)
  51. length = end - start
  52. self.assertEqual(start, PAGESIZE)
  53. self.assertEqual(end, PAGESIZE + 6)
  54. # test seeking around (try to overflow the seek implementation)
  55. m.seek(0,0)
  56. self.assertEqual(m.tell(), 0)
  57. m.seek(42,1)
  58. self.assertEqual(m.tell(), 42)
  59. m.seek(0,2)
  60. self.assertEqual(m.tell(), len(m))
  61. # Try to seek to negative position...
  62. self.assertRaises(ValueError, m.seek, -1)
  63. # Try to seek beyond end of mmap...
  64. self.assertRaises(ValueError, m.seek, 1, 2)
  65. # Try to seek to negative position...
  66. self.assertRaises(ValueError, m.seek, -len(m)-1, 2)
  67. # Try resizing map
  68. try:
  69. m.resize(512)
  70. except SystemError:
  71. # resize() not supported
  72. # No messages are printed, since the output of this test suite
  73. # would then be different across platforms.
  74. pass
  75. else:
  76. # resize() is supported
  77. self.assertEqual(len(m), 512)
  78. # Check that we can no longer seek beyond the new size.
  79. self.assertRaises(ValueError, m.seek, 513, 0)
  80. # Check that the underlying file is truncated too
  81. # (bug #728515)
  82. f = open(TESTFN)
  83. f.seek(0, 2)
  84. self.assertEqual(f.tell(), 512)
  85. f.close()
  86. self.assertEqual(m.size(), 512)
  87. m.close()
  88. finally:
  89. try:
  90. f.close()
  91. except OSError:
  92. pass
  93. def test_access_parameter(self):
  94. # Test for "access" keyword parameter
  95. mapsize = 10
  96. open(TESTFN, "wb").write("a"*mapsize)
  97. f = open(TESTFN, "rb")
  98. m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
  99. self.assertEqual(m[:], 'a'*mapsize, "Readonly memory map data incorrect.")
  100. # Ensuring that readonly mmap can't be slice assigned
  101. try:
  102. m[:] = 'b'*mapsize
  103. except TypeError:
  104. pass
  105. else:
  106. self.fail("Able to write to readonly memory map")
  107. # Ensuring that readonly mmap can't be item assigned
  108. try:
  109. m[0] = 'b'
  110. except TypeError:
  111. pass
  112. else:
  113. self.fail("Able to write to readonly memory map")
  114. # Ensuring that readonly mmap can't be write() to
  115. try:
  116. m.seek(0,0)
  117. m.write('abc')
  118. except TypeError:
  119. pass
  120. else:
  121. self.fail("Able to write to readonly memory map")
  122. # Ensuring that readonly mmap can't be write_byte() to
  123. try:
  124. m.seek(0,0)
  125. m.write_byte('d')
  126. except TypeError:
  127. pass
  128. else:
  129. self.fail("Able to write to readonly memory map")
  130. # Ensuring that readonly mmap can't be resized
  131. try:
  132. m.resize(2*mapsize)
  133. except SystemError: # resize is not universally supported
  134. pass
  135. except TypeError:
  136. pass
  137. else:
  138. self.fail("Able to resize readonly memory map")
  139. f.close()
  140. del m, f
  141. self.assertEqual(open(TESTFN, "rb").read(), 'a'*mapsize,
  142. "Readonly memory map data file was modified")
  143. # Opening mmap with size too big
  144. import sys
  145. f = open(TESTFN, "r+b")
  146. try:
  147. m = mmap.mmap(f.fileno(), mapsize+1)
  148. except ValueError:
  149. # we do not expect a ValueError on Windows
  150. # CAUTION: This also changes the size of the file on disk, and
  151. # later tests assume that the length hasn't changed. We need to
  152. # repair that.
  153. if sys.platform.startswith('win'):
  154. self.fail("Opening mmap with size+1 should work on Windows.")
  155. else:
  156. # we expect a ValueError on Unix, but not on Windows
  157. if not sys.platform.startswith('win'):
  158. self.fail("Opening mmap with size+1 should raise ValueError.")
  159. m.close()
  160. f.close()
  161. if sys.platform.startswith('win'):
  162. # Repair damage from the resizing test.
  163. f = open(TESTFN, 'r+b')
  164. f.truncate(mapsize)
  165. f.close()
  166. # Opening mmap with access=ACCESS_WRITE
  167. f = open(TESTFN, "r+b")
  168. m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
  169. # Modifying write-through memory map
  170. m[:] = 'c'*mapsize
  171. self.assertEqual(m[:], 'c'*mapsize,
  172. "Write-through memory map memory not updated properly.")
  173. m.flush()
  174. m.close()
  175. f.close()
  176. f = open(TESTFN, 'rb')
  177. stuff = f.read()
  178. f.close()
  179. self.assertEqual(stuff, 'c'*mapsize,
  180. "Write-through memory map data file not updated properly.")
  181. # Opening mmap with access=ACCESS_COPY
  182. f = open(TESTFN, "r+b")
  183. m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
  184. # Modifying copy-on-write memory map
  185. m[:] = 'd'*mapsize
  186. self.assertEqual(m[:], 'd' * mapsize,
  187. "Copy-on-write memory map data not written correctly.")
  188. m.flush()
  189. self.assertEqual(open(TESTFN, "rb").read(), 'c'*mapsize,
  190. "Copy-on-write test data file should not be modified.")
  191. # Ensuring copy-on-write maps cannot be resized
  192. self.assertRaises(TypeError, m.resize, 2*mapsize)
  193. f.close()
  194. del m, f
  195. # Ensuring invalid access parameter raises exception
  196. f = open(TESTFN, "r+b")
  197. self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)
  198. f.close()
  199. if os.name == "posix":
  200. # Try incompatible flags, prot and access parameters.
  201. f = open(TESTFN, "r+b")
  202. self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
  203. flags=mmap.MAP_PRIVATE,
  204. prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)
  205. f.close()
  206. # Try writing with PROT_EXEC and without PROT_WRITE
  207. prot = mmap.PROT_READ | getattr(mmap, 'PROT_EXEC', 0)
  208. with open(TESTFN, "r+b") as f:
  209. m = mmap.mmap(f.fileno(), mapsize, prot=prot)
  210. self.assertRaises(TypeError, m.write, b"abcdef")
  211. self.assertRaises(TypeError, m.write_byte, 0)
  212. m.close()
  213. def test_bad_file_desc(self):
  214. # Try opening a bad file descriptor...
  215. self.assertRaises(mmap.error, mmap.mmap, -2, 4096)
  216. def test_tougher_find(self):
  217. # Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2,
  218. # searching for data with embedded \0 bytes didn't work.
  219. f = open(TESTFN, 'w+')
  220. data = 'aabaac\x00deef\x00\x00aa\x00'
  221. n = len(data)
  222. f.write(data)
  223. f.flush()
  224. m = mmap.mmap(f.fileno(), n)
  225. f.close()
  226. for start in range(n+1):
  227. for finish in range(start, n+1):
  228. slice = data[start : finish]
  229. self.assertEqual(m.find(slice), data.find(slice))
  230. self.assertEqual(m.find(slice + 'x'), -1)
  231. m.close()
  232. def test_find_end(self):
  233. # test the new 'end' parameter works as expected
  234. f = open(TESTFN, 'w+')
  235. data = 'one two ones'
  236. n = len(data)
  237. f.write(data)
  238. f.flush()
  239. m = mmap.mmap(f.fileno(), n)
  240. f.close()
  241. self.assertEqual(m.find('one'), 0)
  242. self.assertEqual(m.find('ones'), 8)
  243. self.assertEqual(m.find('one', 0, -1), 0)
  244. self.assertEqual(m.find('one', 1), 8)
  245. self.assertEqual(m.find('one', 1, -1), 8)
  246. self.assertEqual(m.find('one', 1, -2), -1)
  247. def test_rfind(self):
  248. # test the new 'end' parameter works as expected
  249. f = open(TESTFN, 'w+')
  250. data = 'one two ones'
  251. n = len(data)
  252. f.write(data)
  253. f.flush()
  254. m = mmap.mmap(f.fileno(), n)
  255. f.close()
  256. self.assertEqual(m.rfind('one'), 8)
  257. self.assertEqual(m.rfind('one '), 0)
  258. self.assertEqual(m.rfind('one', 0, -1), 8)
  259. self.assertEqual(m.rfind('one', 0, -2), 0)
  260. self.assertEqual(m.rfind('one', 1, -1), 8)
  261. self.assertEqual(m.rfind('one', 1, -2), -1)
  262. def test_double_close(self):
  263. # make sure a double close doesn't crash on Solaris (Bug# 665913)
  264. f = open(TESTFN, 'w+')
  265. f.write(2**16 * 'a') # Arbitrary character
  266. f.close()
  267. f = open(TESTFN)
  268. mf = mmap.mmap(f.fileno(), 2**16, access=mmap.ACCESS_READ)
  269. mf.close()
  270. mf.close()
  271. f.close()
  272. @unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()")
  273. def test_entire_file(self):
  274. # test mapping of entire file by passing 0 for map length
  275. f = open(TESTFN, "w+")
  276. f.write(2**16 * 'm') # Arbitrary character
  277. f.close()
  278. f = open(TESTFN, "rb+")
  279. mf = mmap.mmap(f.fileno(), 0)
  280. self.assertEqual(len(mf), 2**16, "Map size should equal file size.")
  281. self.assertEqual(mf.read(2**16), 2**16 * "m")
  282. mf.close()
  283. f.close()
  284. @unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()")
  285. def test_length_0_offset(self):
  286. # Issue #10916: test mapping of remainder of file by passing 0 for
  287. # map length with an offset doesn't cause a segfault.
  288. # NOTE: allocation granularity is currently 65536 under Win64,
  289. # and therefore the minimum offset alignment.
  290. with open(TESTFN, "wb") as f:
  291. f.write((65536 * 2) * b'm') # Arbitrary character
  292. with open(TESTFN, "rb") as f:
  293. mf = mmap.mmap(f.fileno(), 0, offset=65536, access=mmap.ACCESS_READ)
  294. try:
  295. self.assertRaises(IndexError, mf.__getitem__, 80000)
  296. finally:
  297. mf.close()
  298. @unittest.skipUnless(hasattr(os, "stat"), "needs os.stat()")
  299. def test_length_0_large_offset(self):
  300. # Issue #10959: test mapping of a file by passing 0 for
  301. # map length with a large offset doesn't cause a segfault.
  302. with open(TESTFN, "wb") as f:
  303. f.write(115699 * b'm') # Arbitrary character
  304. with open(TESTFN, "w+b") as f:
  305. self.assertRaises(ValueError, mmap.mmap, f.fileno(), 0,
  306. offset=2147418112)
  307. def test_move(self):
  308. # make move works everywhere (64-bit format problem earlier)
  309. f = open(TESTFN, 'w+')
  310. f.write("ABCDEabcde") # Arbitrary character
  311. f.flush()
  312. mf = mmap.mmap(f.fileno(), 10)
  313. mf.move(5, 0, 5)
  314. self.assertEqual(mf[:], "ABCDEABCDE", "Map move should have duplicated front 5")
  315. mf.close()
  316. f.close()
  317. # more excessive test
  318. data = "0123456789"
  319. for dest in range(len(data)):
  320. for src in range(len(data)):
  321. for count in range(len(data) - max(dest, src)):
  322. expected = data[:dest] + data[src:src+count] + data[dest+count:]
  323. m = mmap.mmap(-1, len(data))
  324. m[:] = data
  325. m.move(dest, src, count)
  326. self.assertEqual(m[:], expected)
  327. m.close()
  328. # segfault test (Issue 5387)
  329. m = mmap.mmap(-1, 100)
  330. offsets = [-100, -1, 0, 1, 100]
  331. for source, dest, size in itertools.product(offsets, offsets, offsets):
  332. try:
  333. m.move(source, dest, size)
  334. except ValueError:
  335. pass
  336. offsets = [(-1, -1, -1), (-1, -1, 0), (-1, 0, -1), (0, -1, -1),
  337. (-1, 0, 0), (0, -1, 0), (0, 0, -1)]
  338. for source, dest, size in offsets:
  339. self.assertRaises(ValueError, m.move, source, dest, size)
  340. m.close()
  341. m = mmap.mmap(-1, 1) # single byte
  342. self.assertRaises(ValueError, m.move, 0, 0, 2)
  343. self.assertRaises(ValueError, m.move, 1, 0, 1)
  344. self.assertRaises(ValueError, m.move, 0, 1, 1)
  345. m.move(0, 0, 1)
  346. m.move(0, 0, 0)
  347. def test_anonymous(self):
  348. # anonymous mmap.mmap(-1, PAGE)
  349. m = mmap.mmap(-1, PAGESIZE)
  350. for x in xrange(PAGESIZE):
  351. self.assertEqual(m[x], '\0', "anonymously mmap'ed contents should be zero")
  352. for x in xrange(PAGESIZE):
  353. m[x] = ch = chr(x & 255)
  354. self.assertEqual(m[x], ch)
  355. def test_extended_getslice(self):
  356. # Test extended slicing by comparing with list slicing.
  357. s = "".join(chr(c) for c in reversed(range(256)))
  358. m = mmap.mmap(-1, len(s))
  359. m[:] = s
  360. self.assertEqual(m[:], s)
  361. indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
  362. for start in indices:
  363. for stop in indices:
  364. # Skip step 0 (invalid)
  365. for step in indices[1:]:
  366. self.assertEqual(m[start:stop:step],
  367. s[start:stop:step])
  368. def test_extended_set_del_slice(self):
  369. # Test extended slicing by comparing with list slicing.
  370. s = "".join(chr(c) for c in reversed(range(256)))
  371. m = mmap.mmap(-1, len(s))
  372. indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
  373. for start in indices:
  374. for stop in indices:
  375. # Skip invalid step 0
  376. for step in indices[1:]:
  377. m[:] = s
  378. self.assertEqual(m[:], s)
  379. L = list(s)
  380. # Make sure we have a slice of exactly the right length,
  381. # but with different data.
  382. data = L[start:stop:step]
  383. data = "".join(reversed(data))
  384. L[start:stop:step] = data
  385. m[start:stop:step] = data
  386. self.assertEqual(m[:], "".join(L))
  387. def make_mmap_file (self, f, halfsize):
  388. # Write 2 pages worth of data to the file
  389. f.write ('\0' * halfsize)
  390. f.write ('foo')
  391. f.write ('\0' * (halfsize - 3))
  392. f.flush ()
  393. return mmap.mmap (f.fileno(), 0)
  394. def test_empty_file (self):
  395. f = open (TESTFN, 'w+b')
  396. f.close()
  397. with open(TESTFN, "rb") as f :
  398. self.assertRaisesRegexp(ValueError,
  399. "cannot mmap an empty file",
  400. mmap.mmap, f.fileno(), 0,
  401. access=mmap.ACCESS_READ)
  402. def test_offset (self):
  403. f = open (TESTFN, 'w+b')
  404. try: # unlink TESTFN no matter what
  405. halfsize = mmap.ALLOCATIONGRANULARITY
  406. m = self.make_mmap_file (f, halfsize)
  407. m.close ()
  408. f.close ()
  409. mapsize = halfsize * 2
  410. # Try invalid offset
  411. f = open(TESTFN, "r+b")
  412. for offset in [-2, -1, None]:
  413. try:
  414. m = mmap.mmap(f.fileno(), mapsize, offset=offset)
  415. self.assertEqual(0, 1)
  416. except (ValueError, TypeError, OverflowError):
  417. pass
  418. else:
  419. self.assertEqual(0, 0)
  420. f.close()
  421. # Try valid offset, hopefully 8192 works on all OSes
  422. f = open(TESTFN, "r+b")
  423. m = mmap.mmap(f.fileno(), mapsize - halfsize, offset=halfsize)
  424. self.assertEqual(m[0:3], 'foo')
  425. f.close()
  426. # Try resizing map
  427. try:
  428. m.resize(512)
  429. except SystemError:
  430. pass
  431. else:
  432. # resize() is supported
  433. self.assertEqual(len(m), 512)
  434. # Check that we can no longer seek beyond the new size.
  435. self.assertRaises(ValueError, m.seek, 513, 0)
  436. # Check that the content is not changed
  437. self.assertEqual(m[0:3], 'foo')
  438. # Check that the underlying file is truncated too
  439. f = open(TESTFN)
  440. f.seek(0, 2)
  441. self.assertEqual(f.tell(), halfsize + 512)
  442. f.close()
  443. self.assertEqual(m.size(), halfsize + 512)
  444. m.close()
  445. finally:
  446. f.close()
  447. try:
  448. os.unlink(TESTFN)
  449. except OSError:
  450. pass
  451. def test_subclass(self):
  452. class anon_mmap(mmap.mmap):
  453. def __new__(klass, *args, **kwargs):
  454. return mmap.mmap.__new__(klass, -1, *args, **kwargs)
  455. anon_mmap(PAGESIZE)
  456. @unittest.skipUnless(hasattr(mmap, 'PROT_READ'), "needs mmap.PROT_READ")
  457. def test_prot_readonly(self):
  458. mapsize = 10
  459. open(TESTFN, "wb").write("a"*mapsize)
  460. f = open(TESTFN, "rb")
  461. m = mmap.mmap(f.fileno(), mapsize, prot=mmap.PROT_READ)
  462. self.assertRaises(TypeError, m.write, "foo")
  463. f.close()
  464. def test_error(self):
  465. self.assertTrue(issubclass(mmap.error, EnvironmentError))
  466. self.assertIn("mmap.error", str(mmap.error))
  467. def test_io_methods(self):
  468. data = "0123456789"
  469. open(TESTFN, "wb").write("x"*len(data))
  470. f = open(TESTFN, "r+b")
  471. m = mmap.mmap(f.fileno(), len(data))
  472. f.close()
  473. # Test write_byte()
  474. for i in xrange(len(data)):
  475. self.assertEqual(m.tell(), i)
  476. m.write_byte(data[i])
  477. self.assertEqual(m.tell(), i+1)
  478. self.assertRaises(ValueError, m.write_byte, "x")
  479. self.assertEqual(m[:], data)
  480. # Test read_byte()
  481. m.seek(0)
  482. for i in xrange(len(data)):
  483. self.assertEqual(m.tell(), i)
  484. self.assertEqual(m.read_byte(), data[i])
  485. self.assertEqual(m.tell(), i+1)
  486. self.assertRaises(ValueError, m.read_byte)
  487. # Test read()
  488. m.seek(3)
  489. self.assertEqual(m.read(3), "345")
  490. self.assertEqual(m.tell(), 6)
  491. # Test write()
  492. m.seek(3)
  493. m.write("bar")
  494. self.assertEqual(m.tell(), 6)
  495. self.assertEqual(m[:], "012bar6789")
  496. m.seek(8)
  497. self.assertRaises(ValueError, m.write, "bar")
  498. @unittest.skipUnless(os.name == 'nt', 'requires Windows')
  499. def test_tagname(self):
  500. data1 = "0123456789"
  501. data2 = "abcdefghij"
  502. assert len(data1) == len(data2)
  503. # Test same tag
  504. m1 = mmap.mmap(-1, len(data1), tagname="foo")
  505. m1[:] = data1
  506. m2 = mmap.mmap(-1, len(data2), tagname="foo")
  507. m2[:] = data2
  508. self.assertEqual(m1[:], data2)
  509. self.assertEqual(m2[:], data2)
  510. m2.close()
  511. m1.close()
  512. # Test different tag
  513. m1 = mmap.mmap(-1, len(data1), tagname="foo")
  514. m1[:] = data1
  515. m2 = mmap.mmap(-1, len(data2), tagname="boo")
  516. m2[:] = data2
  517. self.assertEqual(m1[:], data1)
  518. self.assertEqual(m2[:], data2)
  519. m2.close()
  520. m1.close()
  521. @cpython_only
  522. @unittest.skipUnless(os.name == 'nt', 'requires Windows')
  523. def test_sizeof(self):
  524. m1 = mmap.mmap(-1, 100)
  525. tagname = "foo"
  526. m2 = mmap.mmap(-1, 100, tagname=tagname)
  527. self.assertEqual(sys.getsizeof(m2),
  528. sys.getsizeof(m1) + len(tagname) + 1)
  529. @unittest.skipUnless(os.name == 'nt', 'requires Windows')
  530. def test_crasher_on_windows(self):
  531. # Should not crash (Issue 1733986)
  532. m = mmap.mmap(-1, 1000, tagname="foo")
  533. try:
  534. mmap.mmap(-1, 5000, tagname="foo")[:] # same tagname, but larger size
  535. except:
  536. pass
  537. m.close()
  538. # Should not crash (Issue 5385)
  539. open(TESTFN, "wb").write("x"*10)
  540. f = open(TESTFN, "r+b")
  541. m = mmap.mmap(f.fileno(), 0)
  542. f.close()
  543. try:
  544. m.resize(0) # will raise WindowsError
  545. except:
  546. pass
  547. try:
  548. m[:]
  549. except:
  550. pass
  551. m.close()
  552. @unittest.skipUnless(os.name == 'nt', 'requires Windows')
  553. def test_invalid_descriptor(self):
  554. # socket file descriptors are valid, but out of range
  555. # for _get_osfhandle, causing a crash when validating the
  556. # parameters to _get_osfhandle.
  557. s = socket.socket()
  558. try:
  559. with self.assertRaises(mmap.error):
  560. m = mmap.mmap(s.fileno(), 10)
  561. finally:
  562. s.close()
  563. class LargeMmapTests(unittest.TestCase):
  564. def setUp(self):
  565. unlink(TESTFN)
  566. def tearDown(self):
  567. unlink(TESTFN)
  568. def _make_test_file(self, num_zeroes, tail):
  569. if sys.platform[:3] == 'win' or sys.platform == 'darwin':
  570. requires('largefile',
  571. 'test requires %s bytes and a long time to run' % str(0x180000000))
  572. f = open(TESTFN, 'w+b')
  573. try:
  574. f.seek(num_zeroes)
  575. f.write(tail)
  576. f.flush()
  577. except (IOError, OverflowError):
  578. f.close()
  579. raise unittest.SkipTest("filesystem does not have largefile support")
  580. return f
  581. def test_large_offset(self):
  582. with self._make_test_file(0x14FFFFFFF, b" ") as f:
  583. m = mmap.mmap(f.fileno(), 0, offset=0x140000000, access=mmap.ACCESS_READ)
  584. try:
  585. self.assertEqual(m[0xFFFFFFF], b" ")
  586. finally:
  587. m.close()
  588. def test_large_filesize(self):
  589. with self._make_test_file(0x17FFFFFFF, b" ") as f:
  590. if sys.maxsize < 0x180000000:
  591. # On 32 bit platforms the file is larger than sys.maxsize so
  592. # mapping the whole file should fail -- Issue #16743
  593. with self.assertRaises(OverflowError):
  594. mmap.mmap(f.fileno(), 0x180000000, access=mmap.ACCESS_READ)
  595. with self.assertRaises(ValueError):
  596. mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
  597. m = mmap.mmap(f.fileno(), 0x10000, access=mmap.ACCESS_READ)
  598. try:
  599. self.assertEqual(m.size(), 0x180000000)
  600. finally:
  601. m.close()
  602. # Issue 11277: mmap() with large (~4GB) sparse files crashes on OS X.
  603. def _test_around_boundary(self, boundary):
  604. tail = b' DEARdear '
  605. start = boundary - len(tail) // 2
  606. end = start + len(tail)
  607. with self._make_test_file(start, tail) as f:
  608. m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
  609. try:
  610. self.assertEqual(m[start:end], tail)
  611. finally:
  612. m.close()
  613. @unittest.skipUnless(sys.maxsize > _4G, "test cannot run on 32-bit systems")
  614. def test_around_2GB(self):
  615. self._test_around_boundary(_2G)
  616. @unittest.skipUnless(sys.maxsize > _4G, "test cannot run on 32-bit systems")
  617. def test_around_4GB(self):
  618. self._test_around_boundary(_4G)
  619. def test_main():
  620. run_unittest(MmapTests, LargeMmapTests)
  621. if __name__ == '__main__':
  622. test_main()