Debian Codegraph @

rpython/rlib/rmmap.py

raw symbols SCIP
1 """Interp-level mmap-like object.
2
3 Note that all the methods assume that the mmap is valid (or writable, for
4 writing methods). You have to call check_valid() from the higher-level API,
5 as well as maybe check_writeable(). In the case of PyPy, this is done from
6 pypy/module/mmap/.
7 """
8
9 from rpython.rtyper.tool import rffi_platform
10 from rpython.rtyper.lltypesystem import rffi, lltype
11 from rpython.rlib import rposix
12 from rpython.translator.tool.cbuild import ExternalCompilationInfo
13 from rpython.rlib.objectmodel import we_are_translated, specialize
14 from rpython.rlib.nonconst import NonConstant
15 from rpython.rlib.rarithmetic import intmask
16
17 import sys
18 import os
19 import platform
20 import stat
21
22 _POSIX = os.name == "posix"
23 _MS_WINDOWS = os.name == "nt"
24 _64BIT = "64bit" in platform.architecture()[0]
25 _CYGWIN = "cygwin" == sys.platform
26 _DARWIN = "darwin" == sys.platform
27 _ARM64 = "arm64" == platform.machine()
28
29 class RMMapError(Exception):
30 def __init__(self, message):
31 self.message = message
32
33 class RValueError(RMMapError):
34 pass
35
36 class RTypeError(RMMapError):
37 pass
38
39 includes = ["sys/types.h"]
40 if _POSIX:
41 includes += ['unistd.h', 'sys/mman.h']
42 elif _MS_WINDOWS:
43 includes += ['winsock2.h', 'windows.h']
44
45 class CConfig:
46 _compilation_info_ = ExternalCompilationInfo(
47 includes=includes,
48 #pre_include_bits=['#ifndef _GNU_SOURCE\n' +
49 # '#define _GNU_SOURCE\n' +
50 # '#endif']
51 # ^^^ _GNU_SOURCE is always defined by the ExternalCompilationInfo now
52 )
53 size_t = rffi_platform.SimpleType("size_t", rffi.LONG)
54 off_t = rffi_platform.SimpleType("off_t", rffi.LONG)
55
56 constants = {}
57 if _POSIX:
58 # constants, look in sys/mman.h and platform docs for the meaning
59 # some constants are linux only so they will be correctly exposed outside
60 # depending on the OS
61 constant_names = ['MAP_SHARED', 'MAP_PRIVATE', 'MAP_FIXED',
62 'PROT_READ', 'PROT_WRITE',
63 'MS_SYNC']
64 if _DARWIN and _ARM64:
65 constant_names.append('MAP_JIT')
66 opt_constant_names = ['MAP_ANON', 'MAP_ANONYMOUS', 'MAP_NORESERVE',
67 'PROT_EXEC', 'MAP_POPULATE',
68 'MAP_DENYWRITE', 'MAP_EXECUTABLE']
69 for name in constant_names:
70 setattr(CConfig, name, rffi_platform.ConstantInteger(name))
71 for name in opt_constant_names:
72 setattr(CConfig, name, rffi_platform.DefinedConstantInteger(name))
73
74 CConfig.MREMAP_MAYMOVE = (
75 rffi_platform.DefinedConstantInteger("MREMAP_MAYMOVE"))
76 CConfig.has_mremap = rffi_platform.Has('mremap(NULL, 0, 0, 0)')
77 CConfig.has_madvise = rffi_platform.Has('madvise(NULL, 0, 0)')
78 # ^^ both are a dirty hack, this is probably a macro
79
80 CConfig.MADV_DONTNEED = (
81 rffi_platform.DefinedConstantInteger('MADV_DONTNEED'))
82 CConfig.MADV_FREE = (
83 rffi_platform.DefinedConstantInteger('MADV_FREE'))
84
85 madv_constant_names = [
86 "MADV_NORMAL",
87 "MADV_RANDOM",
88 "MADV_SEQUENTIAL",
89 "MADV_WILLNEED",
90
91 #Linux-specific
92 "MADV_REMOVE",
93 "MADV_DONTFORK",
94 "MADV_DOFORK",
95 "MADV_HWPOISON",
96 "MADV_MERGEABLE",
97 "MADV_UNMERGEABLE",
98 "MADV_SOFT_OFFLINE",
99 "MADV_HUGEPAGE",
100 "MADV_NOHUGEPAGE",
101 "MADV_DONTDUMP",
102 "MADV_DODUMP",
103
104 # FreeBSD-specific
105 "MADV_NOSYNC",
106 "MADV_AUTOSYNC",
107 "MADV_NOCORE",
108 "MADV_CORE",
109 "MADV_PROTECT",
110 ]
111 for name in madv_constant_names:
112 setattr(CConfig, name, rffi_platform.DefinedConstantInteger(name))
113
114
115 elif _MS_WINDOWS:
116 constant_names = ['PAGE_READONLY', 'PAGE_READWRITE', 'PAGE_WRITECOPY',
117 'FILE_MAP_READ', 'FILE_MAP_WRITE', 'FILE_MAP_COPY',
118 'DUPLICATE_SAME_ACCESS', 'MEM_COMMIT', 'MEM_RESERVE',
119 'MEM_RELEASE', 'PAGE_EXECUTE_READWRITE', 'PAGE_NOACCESS',
120 'MEM_RESET']
121 for name in constant_names:
122 setattr(CConfig, name, rffi_platform.ConstantInteger(name))
123
124 from rpython.rlib import rwin32
125
126 from rpython.rlib.rwin32 import HANDLE, LPHANDLE
127 from rpython.rlib.rwin32 import NULL_HANDLE, INVALID_HANDLE_VALUE
128 from rpython.rlib.rwin32 import DWORD, WORD, DWORD_PTR, LPDWORD
129 from rpython.rlib.rwin32 import BOOL, LPVOID, LPCSTR, SIZE_T
130 from rpython.rlib.rwin32 import LONG, PLONG
131
132 # export the constants inside and outside. see __init__.py
133 cConfig = rffi_platform.configure(CConfig)
134 constants.update(cConfig)
135
136 if _POSIX:
137 # MAP_ANONYMOUS is not always present but it's always available at CPython level
138 if constants["MAP_ANONYMOUS"] is None:
139 constants["MAP_ANONYMOUS"] = constants["MAP_ANON"]
140 assert constants["MAP_ANONYMOUS"] is not None
141 constants["MAP_ANON"] = constants["MAP_ANONYMOUS"]
142
143 locals().update(constants)
144
145 _ACCESS_DEFAULT, ACCESS_READ, ACCESS_WRITE, ACCESS_COPY = range(4)
146
147 if rffi.sizeof(off_t) > rffi.sizeof(lltype.Signed):
148 HAVE_LARGEFILE_SUPPORT = True
149 else:
150 HAVE_LARGEFILE_SUPPORT = False
151
152 def external(name, args, result, save_err_on_unsafe=0, save_err_on_safe=0,
153 **kwargs):
154 unsafe = rffi.llexternal(name, args, result,
155 compilation_info=CConfig._compilation_info_,
156 save_err=save_err_on_unsafe,
157 **kwargs)
158 safe = rffi.llexternal(name, args, result,
159 compilation_info=CConfig._compilation_info_,
160 sandboxsafe=True, releasegil=False,
161 save_err=save_err_on_safe,
162 **kwargs)
163 return unsafe, safe
164
165 def winexternal(name, args, result, **kwargs):
166 unsafe = rffi.llexternal(name, args, result,
167 compilation_info=CConfig._compilation_info_,
168 calling_conv='win',
169 **kwargs)
170 safe = rffi.llexternal(name, args, result,
171 compilation_info=CConfig._compilation_info_,
172 calling_conv='win',
173 sandboxsafe=True, releasegil=False,
174 **kwargs)
175 return unsafe, safe
176
177 PTR = rffi.CCHARP
178
179 if _CYGWIN:
180 # XXX: macro=True hack for newer versions of Cygwin (as of 12/2012)
181 _, c_malloc_safe = external('malloc', [size_t], PTR, macro=True)
182 _, c_free_safe = external('free', [PTR], lltype.Void, macro=True)
183
184 c_memmove, _ = external('memmove', [PTR, PTR, size_t], lltype.Void)
185
186 if _POSIX:
187 has_mremap = cConfig['has_mremap']
188 has_madvise = cConfig['has_madvise']
189 c_mmap, c_mmap_safe = external('mmap', [PTR, size_t, rffi.INT, rffi.INT,
190 rffi.INT, off_t], PTR, macro=True,
191 save_err_on_unsafe=rffi.RFFI_SAVE_ERRNO)
192 # 'mmap' on linux32 is a macro that calls 'mmap64'
193 _, c_munmap_safe = external('munmap', [PTR, size_t], rffi.INT)
194 c_msync, _ = external('msync', [PTR, size_t, rffi.INT], rffi.INT,
195 save_err_on_unsafe=rffi.RFFI_SAVE_ERRNO)
196 if has_mremap:
197 c_mremap, _ = external('mremap',
198 [PTR, size_t, size_t, rffi.ULONG], PTR)
199 if has_madvise:
200 _, c_madvise_safe = external('madvise', [PTR, size_t, rffi.INT],
201 rffi.INT, _nowrapper=True)
202
203 # this one is always safe
204 _pagesize = rffi_platform.getintegerfunctionresult('getpagesize',
205 includes=includes)
206 _get_allocation_granularity = _get_page_size = lambda: _pagesize
207
208 if _DARWIN and _ARM64:
209 _, c_pthread_jit_write_protect_np = external('pthread_jit_write_protect_np',
210 [rffi.INT], lltype.Void)
211
212 elif _MS_WINDOWS:
213
214 class ComplexCConfig:
215 _compilation_info_ = CConfig._compilation_info_
216
217 SYSINFO_STRUCT = rffi.CStruct(
218 'SYSINFO_STRUCT',
219 ("wProcessorArchitecture", WORD),
220 ("wReserved", WORD),
221 )
222
223 SYSINFO_UNION = rffi.CStruct(
224 'union SYSINFO_UNION',
225 ("dwOemId", DWORD),
226 ("_struct_", SYSINFO_STRUCT),
227 )
228 # sorry, I can't find a way to insert the above
229 # because the union field has no name
230 SYSTEM_INFO = rffi_platform.Struct(
231 'SYSTEM_INFO', [
232 ## ("_union_", SYSINFO_UNION),
233 ## instead, we put the smaller fields, here
234 ("wProcessorArchitecture", WORD),
235 ("wReserved", WORD),
236 ## should be a union. dwOemId is obsolete, anyway
237 ("dwPageSize", DWORD),
238 ("lpMinimumApplicationAddress", LPVOID),
239 ("lpMaximumApplicationAddress", LPVOID),
240 ("dwActiveProcessorMask", DWORD_PTR),
241 ("dwNumberOfProcessors", DWORD),
242 ("dwProcessorType", DWORD),
243 ("dwAllocationGranularity", DWORD),
244 ("wProcessorLevel", WORD),
245 ("wProcessorRevision", WORD),
246 ])
247
248 config = rffi_platform.configure(ComplexCConfig)
249 SYSTEM_INFO = config['SYSTEM_INFO']
250 SYSTEM_INFO_P = lltype.Ptr(SYSTEM_INFO)
251
252 GetSystemInfo, _ = winexternal('GetSystemInfo', [SYSTEM_INFO_P], lltype.Void)
253 GetFileSize, _ = winexternal('GetFileSize', [HANDLE, LPDWORD], DWORD,
254 save_err=rffi.RFFI_SAVE_LASTERROR)
255 GetCurrentProcess, _ = winexternal('GetCurrentProcess', [], HANDLE)
256 DuplicateHandle, _ = winexternal('DuplicateHandle',
257 [HANDLE, HANDLE, HANDLE, LPHANDLE, DWORD,
258 BOOL, DWORD], BOOL,
259 save_err=rffi.RFFI_SAVE_LASTERROR)
260 CreateFileMapping, _ = winexternal('CreateFileMappingA',
261 [HANDLE, rwin32.LPSECURITY_ATTRIBUTES,
262 DWORD, DWORD, DWORD, LPCSTR], HANDLE,
263 save_err=rffi.RFFI_SAVE_LASTERROR)
264 MapViewOfFile, _ = winexternal('MapViewOfFile', [HANDLE, DWORD, DWORD,
265 DWORD, SIZE_T], LPCSTR,
266 save_err=rffi.RFFI_SAVE_LASTERROR) ##!!LPVOID
267 _, UnmapViewOfFile_safe = winexternal('UnmapViewOfFile', [LPCSTR], BOOL)
268 FlushViewOfFile, _ = winexternal('FlushViewOfFile', [LPCSTR, SIZE_T], BOOL)
269 SetFilePointer, _ = winexternal('SetFilePointer', [HANDLE, LONG, PLONG, DWORD], DWORD)
270 SetEndOfFile, _ = winexternal('SetEndOfFile', [HANDLE], BOOL)
271 VirtualAlloc, VirtualAlloc_safe = winexternal('VirtualAlloc',
272 [rffi.VOIDP, rffi.SIZE_T, DWORD, DWORD],
273 rffi.VOIDP)
274 _, _VirtualAlloc_safe_no_wrapper = winexternal('VirtualAlloc',
275 [rffi.VOIDP, rffi.SIZE_T, DWORD, DWORD],
276 rffi.VOIDP, _nowrapper=True)
277 _, _VirtualProtect_safe = winexternal('VirtualProtect',
278 [rffi.VOIDP, rffi.SIZE_T, DWORD, LPDWORD],
279 BOOL)
280 @specialize.ll()
281 def VirtualProtect(addr, size, mode, oldmode_ptr):
282 return _VirtualProtect_safe(addr,
283 rffi.cast(rffi.SIZE_T, size),
284 rffi.cast(DWORD, mode),
285 oldmode_ptr)
286 VirtualFree, VirtualFree_safe = winexternal('VirtualFree',
287 [rffi.VOIDP, rffi.SIZE_T, DWORD], BOOL)
288
289 def _get_page_size():
290 try:
291 si = rffi.make(SYSTEM_INFO)
292 GetSystemInfo(si)
293 return int(si.c_dwPageSize)
294 finally:
295 lltype.free(si, flavor="raw")
296
297 def _get_allocation_granularity():
298 try:
299 si = rffi.make(SYSTEM_INFO)
300 GetSystemInfo(si)
301 return int(si.c_dwAllocationGranularity)
302 finally:
303 lltype.free(si, flavor="raw")
304
305 def _get_file_size(handle):
306 # XXX use native Windows types like WORD
307 high_ref = lltype.malloc(LPDWORD.TO, 1, flavor='raw')
308 try:
309 low = GetFileSize(handle, high_ref)
310 low = rffi.cast(lltype.Signed, low)
311 # XXX should be propagate the real type, allowing
312 # for 2*sys.maxint?
313 high = high_ref[0]
314 high = rffi.cast(lltype.Signed, high)
315 # low might just happen to have the value INVALID_FILE_SIZE
316 # so we need to check the last error also
317 INVALID_FILE_SIZE = -1
318 if low == INVALID_FILE_SIZE:
319 err = rwin32.GetLastError_saved()
320 if err:
321 raise WindowsError(err, "mmap")
322 return low, high
323 finally:
324 lltype.free(high_ref, flavor='raw')
325
326 INVALID_HANDLE = INVALID_HANDLE_VALUE
327 has_madvise = False
328
329 PAGESIZE = _get_page_size()
330 ALLOCATIONGRANULARITY = _get_allocation_granularity()
331 NULL = lltype.nullptr(PTR.TO)
332 NODATA = lltype.nullptr(PTR.TO)
333
334 class MMap(object):
335 def __init__(self, access, offset):
336 self.size = 0
337 self.pos = 0
338 self.access = access
339 self.offset = offset
340
341 if _MS_WINDOWS:
342 self.map_handle = NULL_HANDLE
343 self.file_handle = NULL_HANDLE
344 self.tagname = ""
345 elif _POSIX:
346 self.fd = -1
347 self.closed = False
348
349 def check_valid(self):
350 if _MS_WINDOWS:
351 to_close = self.map_handle == INVALID_HANDLE
352 elif _POSIX:
353 to_close = self.closed
354
355 if to_close:
356 raise RValueError("mmap closed or invalid")
357
358 def check_writeable(self):
359 if not (self.access != ACCESS_READ):
360 raise RTypeError("mmap can't modify a readonly memory map.")
361
362 def check_resizeable(self):
363 if not (self.access == ACCESS_WRITE or self.access == _ACCESS_DEFAULT):
364 raise RTypeError("mmap can't resize a readonly or copy-on-write memory map.")
365
366 def setdata(self, data, size):
367 """Set the internal data and map size from a PTR."""
368 assert size >= 0
369 self.data = data
370 self.size = size
371
372 def unmap(self):
373 if _MS_WINDOWS:
374 UnmapViewOfFile_safe(self.getptr(0))
375 elif _POSIX:
376 self.unmap_range(0, self.size)
377
378 if _POSIX:
379 def unmap_range(self, offset, size):
380 """Unmap (a portion of) the mapped range.
381
382 Per munmap(1), the offset must be a multiple of the page size,
383 and the size will be rounded up to a multiple of the page size.
384 """
385 c_munmap_safe(self.getptr(offset), size)
386
387 def close(self):
388 if _MS_WINDOWS:
389 if self.size > 0:
390 self.unmap()
391 self.setdata(NODATA, 0)
392 if self.map_handle != INVALID_HANDLE:
393 rwin32.CloseHandle_no_err(self.map_handle)
394 self.map_handle = INVALID_HANDLE
395 if self.file_handle != INVALID_HANDLE:
396 rwin32.CloseHandle_no_err(self.file_handle)
397 self.file_handle = INVALID_HANDLE
398 elif _POSIX:
399 self.closed = True
400 if self.fd != -1:
401 # XXX this is buggy - raising in an RPython del is not a good
402 # idea, we should swallow the exception or ignore the
403 # underlaying close error code
404 os.close(self.fd)
405 self.fd = -1
406 if self.size > 0:
407 self.unmap()
408 self.setdata(NODATA, 0)
409
410 def __del__(self):
411 self.close()
412
413 def read_byte(self):
414 if self.pos < self.size:
415 value = self.data[self.pos]
416 self.pos += 1
417 return value
418 else:
419 raise RValueError("read byte out of range")
420
421 def readline(self):
422 data = self.data
423 for pos in xrange(self.pos, self.size):
424 if data[pos] == '\n':
425 eol = pos + 1 # we're interested in the position after new line
426 break
427 else: # no '\n' found
428 eol = self.size
429
430 res = self.getslice(self.pos, eol - self.pos)
431 self.pos += len(res)
432 return res
433
434 def read(self, num=-1):
435 if num < 0:
436 # read all
437 eol = self.size
438 else:
439 eol = self.pos + num
440 # silently adjust out of range requests
441 if eol > self.size:
442 eol = self.size
443
444 res = self.getslice(self.pos, eol - self.pos)
445 self.pos += len(res)
446 return res
447
448 def find(self, tofind, start, end, reverse=False):
449 # XXX naive! how can we reuse the rstr algorithm?
450 if start < 0:
451 start += self.size
452 if start < 0:
453 start = 0
454 if end < 0:
455 end += self.size
456 if end < 0:
457 end = 0
458 elif end > self.size:
459 end = self.size
460 #
461 upto = end - len(tofind)
462 if not reverse:
463 step = 1
464 p = start
465 if p > upto:
466 return -1 # failure (empty range to search)
467 else:
468 step = -1
469 p = upto
470 upto = start
471 if p < upto:
472 return -1 # failure (empty range to search)
473 #
474 data = self.data
475 while True:
476 assert p >= 0
477 for q in range(len(tofind)):
478 if data[p+q] != tofind[q]:
479 break # position 'p' is not a match
480 else:
481 # full match
482 return p
483 #
484 if p == upto:
485 return -1 # failure
486 p += step
487
488 def seek(self, pos, whence=0):
489 dist = pos
490 how = whence
491
492 if how == 0: # relative to start
493 where = dist
494 elif how == 1: # relative to current position
495 where = self.pos + dist
496 elif how == 2: # relative to the end
497 where = self.size + dist
498 else:
499 raise RValueError("unknown seek type")
500
501 if not (0 <= where <= self.size):
502 raise RValueError("seek out of range")
503
504 self.pos = intmask(where)
505
506 def tell(self):
507 return self.pos
508
509 def file_size(self):
510 size = self.size
511 if _MS_WINDOWS:
512 if self.file_handle != INVALID_HANDLE:
513 low, high = _get_file_size(self.file_handle)
514 if not high and low <= sys.maxint:
515 return low
516 # not so sure if the signed/unsigned strictness is a good idea:
517 high = rffi.cast(lltype.Unsigned, high)
518 low = rffi.cast(lltype.Unsigned, low)
519 size = (high << 32) + low
520 size = rffi.cast(lltype.Signed, size)
521 elif _POSIX:
522 st = os.fstat(self.fd)
523 size = st[stat.ST_SIZE]
524 return size
525
526 def write(self, data):
527 data_len = len(data)
528 start = self.pos
529 if start + data_len > self.size:
530 raise RValueError("data out of range")
531
532 self.setslice(start, data)
533 self.pos = start + data_len
534 return data_len
535
536 def write_byte(self, byte):
537 if len(byte) != 1:
538 raise RTypeError("write_byte() argument must be char")
539
540 if self.pos >= self.size:
541 raise RValueError("write byte out of range")
542
543 self.data[self.pos] = byte[0]
544 self.pos += 1
545
546 def getptr(self, offset):
547 return rffi.ptradd(self.data, offset)
548
549 def getslice(self, start, length):
550 if length < 0:
551 return ''
552 return rffi.charpsize2str(self.getptr(start), length)
553
554 def setslice(self, start, newdata):
555 internaldata = self.data
556 for i in range(len(newdata)):
557 internaldata[start+i] = newdata[i]
558
559 def flush(self, offset=0, size=0):
560 if size == 0:
561 size = self.size
562 if offset < 0 or size < 0 or offset + size > self.size:
563 raise RValueError("flush values out of range")
564 else:
565 start = self.getptr(offset)
566 if _MS_WINDOWS:
567 res = FlushViewOfFile(start, size)
568 # XXX res == 0 means that an error occurred, but in CPython
569 # this is not checked
570 return res
571 elif _POSIX:
572 res = c_msync(start, size, MS_SYNC)
573 if res == -1:
574 errno = rposix.get_saved_errno()
575 raise OSError(errno, os.strerror(errno))
576
577 return 0
578
579 def move(self, dest, src, count):
580 # check boundings
581 if (src < 0 or dest < 0 or count < 0 or
582 src + count > self.size or dest + count > self.size):
583 raise RValueError("source or destination out of range")
584
585 datasrc = self.getptr(src)
586 datadest = self.getptr(dest)
587 c_memmove(datadest, datasrc, count)
588
589 def resize(self, newsize):
590 if _POSIX:
591 if not has_mremap:
592 raise RValueError("mmap: resizing not available--no mremap()")
593
594 # resize the underlying file first, if there is one
595 if self.fd >= 0:
596 os.ftruncate(self.fd, self.offset + newsize)
597
598 # now resize the mmap
599 newdata = c_mremap(self.getptr(0), self.size, newsize,
600 MREMAP_MAYMOVE or 0)
601 self.setdata(newdata, newsize)
602 elif _MS_WINDOWS:
603 # disconnect the mapping
604 self.unmap()
605 rwin32.CloseHandle_no_err(self.map_handle)
606
607 # move to the desired EOF position
608 if _64BIT:
609 newsize_high = (self.offset + newsize) >> 32
610 newsize_low = (self.offset + newsize) & 0xFFFFFFFF
611 offset_high = self.offset >> 32
612 offset_low = self.offset & 0xFFFFFFFF
613 else:
614 newsize_high = 0
615 newsize_low = self.offset + newsize
616 offset_high = 0
617 offset_low = self.offset
618
619 FILE_BEGIN = 0
620 high_ref = lltype.malloc(PLONG.TO, 1, flavor='raw')
621 try:
622 high_ref[0] = rffi.cast(LONG, newsize_high)
623 SetFilePointer(self.file_handle, newsize_low, high_ref,
624 FILE_BEGIN)
625 finally:
626 lltype.free(high_ref, flavor='raw')
627 # resize the file
628 SetEndOfFile(self.file_handle)
629 # create another mapping object and remap the file view
630 res = CreateFileMapping(self.file_handle, NULL, PAGE_READWRITE,
631 newsize_high, newsize_low, self.tagname)
632 self.map_handle = res
633
634 if self.map_handle:
635 data = MapViewOfFile(self.map_handle, FILE_MAP_WRITE,
636 offset_high, offset_low, newsize)
637 if data:
638 # XXX we should have a real LPVOID which must always be casted
639 charp = rffi.cast(LPCSTR, data)
640 self.setdata(charp, newsize)
641 return
642 winerror = rwin32.lastSavedWindowsError()
643 if self.map_handle:
644 rwin32.CloseHandle_no_err(self.map_handle)
645 self.map_handle = INVALID_HANDLE
646 raise winerror
647
648 def len(self):
649 return self.size
650
651 def getitem(self, index):
652 # simplified version, for rpython
653 self.check_valid()
654 if index < 0:
655 index += self.size
656 return self.data[index]
657
658 def setitem(self, index, value):
659 if len(value) != 1:
660 raise RValueError("mmap assignment must be "
661 "single-character string")
662 if index < 0:
663 index += self.size
664 self.data[index] = value[0]
665
666 if has_madvise:
667 def madvise(self, flags, start, end):
668 res = c_madvise_safe(rffi.cast(PTR, rffi.ptradd(self.data, + start)),
669 rffi.cast(size_t, end),
670 rffi.cast(rffi.INT, flags))
671 if rffi.cast(lltype.Signed, res) == 0:
672 return
673 errno = rposix.get_saved_errno()
674 raise OSError(errno, os.strerror(errno))
675
676 def _check_map_size(size):
677 if size < 0:
678 raise RTypeError("memory mapped size must be positive")
679
680 if _DARWIN and _ARM64:
681
682 class Nester(object):
683 def __init__(self):
684 self.counter = 0
685
686 nester = Nester()
687
688 def enter_assembler_writing():
689 if nester.counter == 0:
690 c_pthread_jit_write_protect_np(0)
691 nester.counter += 1
692
693 def leave_assembler_writing():
694 nester.counter -= 1
695 if nester.counter == 0:
696 c_pthread_jit_write_protect_np(1)
697
698 else:
699 def enter_assembler_writing():
700 pass
701
702 def leave_assembler_writing():
703 pass
704
705 if _POSIX:
706 def mmap(fileno, length, flags=MAP_SHARED,
707 prot=PROT_WRITE | PROT_READ, access=_ACCESS_DEFAULT, offset=0):
708
709 fd = fileno
710
711 # check access is not there when flags and prot are there
712 if access != _ACCESS_DEFAULT and ((flags != MAP_SHARED) or
713 (prot != (PROT_WRITE | PROT_READ))):
714 raise RValueError("mmap can't specify both access and flags, prot.")
715
716 # check size boundaries
717 _check_map_size(length)
718 map_size = length
719 if offset < 0:
720 raise RValueError("negative offset")
721
722 if access == ACCESS_READ:
723 flags = MAP_SHARED
724 prot = PROT_READ
725 elif access == ACCESS_WRITE:
726 flags = MAP_SHARED
727 prot = PROT_READ | PROT_WRITE
728 elif access == ACCESS_COPY:
729 flags = MAP_PRIVATE
730 prot = PROT_READ | PROT_WRITE
731 elif access == _ACCESS_DEFAULT:
732 # map prot to access type
733 if prot & PROT_READ and prot & PROT_WRITE:
734 pass # _ACCESS_DEFAULT
735 elif prot & PROT_WRITE:
736 access = ACCESS_WRITE
737 else:
738 access = ACCESS_READ
739 else:
740 raise RValueError("mmap invalid access parameter.")
741
742 # check file size
743 try:
744 st = os.fstat(fd)
745 except OSError:
746 pass # ignore errors and trust map_size
747 else:
748 mode = st[stat.ST_MODE]
749 size = st[stat.ST_SIZE]
750 if stat.S_ISREG(mode):
751 if map_size == 0:
752 if size == 0:
753 raise RValueError("cannot mmap an empty file")
754 if offset > size:
755 raise RValueError(
756 "mmap offset is greater than file size")
757 map_size = int(size - offset)
758 if map_size != size - offset:
759 raise RValueError("mmap length is too large")
760 elif offset + map_size > size:
761 raise RValueError("mmap length is greater than file size")
762
763 m = MMap(access, offset)
764 if fd == -1:
765 # Assume the caller wants to map anonymous memory.
766 # This is the same behaviour as Windows. mmap.mmap(-1, size)
767 # on both Windows and Unix map anonymous memory.
768 m.fd = -1
769
770 flags |= MAP_ANONYMOUS
771
772 else:
773 m.fd = os.dup(fd)
774
775 # XXX if we use hintp below in alloc, the NonConstant
776 # is necessary since we want a general version of c_mmap
777 # to be annotated with a non-constant pointer.
778 res = c_mmap(NonConstant(NULL), map_size, prot, flags, fd, offset)
779 if res == rffi.cast(PTR, -1):
780 errno = rposix.get_saved_errno()
781 raise OSError(errno, os.strerror(errno))
782
783 m.setdata(res, map_size)
784 return m
785
786 def alloc_hinted(hintp, map_size):
787 flags = MAP_PRIVATE | MAP_ANONYMOUS
788 if _DARWIN and _ARM64:
789 flags |= MAP_JIT
790 prot = PROT_EXEC | PROT_READ | PROT_WRITE
791 if we_are_translated():
792 flags = NonConstant(flags)
793 prot = NonConstant(prot)
794 return c_mmap_safe(hintp, map_size, prot, flags, -1, 0)
795
796 def clear_large_memory_chunk_aligned(addr, map_size):
797 addr = rffi.cast(PTR, addr)
798 flags = MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS
799 prot = PROT_READ | PROT_WRITE
800 if we_are_translated():
801 flags = NonConstant(flags)
802 prot = NonConstant(prot)
803 res = c_mmap_safe(addr, map_size, prot, flags, -1, 0)
804 return res == addr
805
806 # XXX is this really necessary?
807 class Hint:
808 pos = -0x4fff0000 # for reproducible results
809 hint = Hint()
810
811 def alloc(map_size):
812 """Allocate memory. This is intended to be used by the JIT,
813 so the memory has the executable bit set and gets allocated
814 internally in case of a sandboxed process.
815 """
816 from errno import ENOMEM
817 from rpython.rlib import debug
818
819 if _CYGWIN:
820 # XXX: JIT memory should be using mmap MAP_PRIVATE with
821 # PROT_EXEC but Cygwin's fork() fails. mprotect()
822 # cannot be used, but seems to be unnecessary there.
823 res = c_malloc_safe(map_size)
824 if res == rffi.cast(PTR, 0):
825 raise MemoryError
826 return res
827 res = alloc_hinted(rffi.cast(PTR, hint.pos), map_size)
828 if res == rffi.cast(PTR, -1):
829 # some systems (some versions of OS/X?) complain if they
830 # are passed a non-zero address. Try again.
831 res = alloc_hinted(rffi.cast(PTR, 0), map_size)
832 if res == rffi.cast(PTR, -1):
833 # ENOMEM simply raises MemoryError, but other errors are fatal
834 if rposix.get_saved_errno() != ENOMEM:
835 debug.fatalerror_notb(
836 "Got an unexpected error trying to allocate some "
837 "memory for the JIT (tried to do mmap() with "
838 "PROT_EXEC|PROT_READ|PROT_WRITE). This can be caused "
839 "by a system policy like PAX. You need to find how "
840 "to work around the policy on your system.")
841 raise MemoryError
842 else:
843 hint.pos += map_size
844 return res
845 alloc._annenforceargs_ = (int,)
846
847 if _CYGWIN:
848 free = c_free_safe
849 else:
850 free = c_munmap_safe
851
852 if sys.platform.startswith('linux'):
853 assert has_madvise
854 assert MADV_DONTNEED is not None
855 if MADV_FREE is None:
856 MADV_FREE = 8 # from the kernel sources of Linux >= 4.5
857 class CanUseMadvFree:
858 ok = -1
859 can_use_madv_free = CanUseMadvFree()
860 def madvise_free(addr, map_size):
861 # We don't know if we are running on a recent enough kernel
862 # that supports MADV_FREE. Check that at runtime: if the
863 # first call to madvise(MADV_FREE) fails, we assume it's
864 # because of EINVAL and we fall back to MADV_DONTNEED.
865 if can_use_madv_free.ok != 0:
866 res = c_madvise_safe(rffi.cast(PTR, addr),
867 rffi.cast(size_t, map_size),
868 rffi.cast(rffi.INT, MADV_FREE))
869 if can_use_madv_free.ok == -1:
870 can_use_madv_free.ok = (rffi.cast(lltype.Signed, res) == 0)
871 if can_use_madv_free.ok == 0:
872 c_madvise_safe(rffi.cast(PTR, addr),
873 rffi.cast(size_t, map_size),
874 rffi.cast(rffi.INT, MADV_DONTNEED))
875 elif has_madvise and not (MADV_FREE is MADV_DONTNEED is None):
876 use_flag = MADV_FREE if MADV_FREE is not None else MADV_DONTNEED
877 def madvise_free(addr, map_size):
878 c_madvise_safe(rffi.cast(PTR, addr),
879 rffi.cast(size_t, map_size),
880 rffi.cast(rffi.INT, use_flag))
881 else:
882 def madvise_free(addr, map_size):
883 "No madvise() on this platform"
884
885 elif _MS_WINDOWS:
886 def mmap(fileno, length, tagname="", access=_ACCESS_DEFAULT, offset=0):
887 # XXX flags is or-ed into access by now.
888 flags = 0
889 # check size boundaries
890 _check_map_size(length)
891 map_size = length
892 if offset < 0:
893 raise RValueError("negative offset")
894
895 flProtect = 0
896 dwDesiredAccess = 0
897 fh = NULL_HANDLE
898
899 if access == ACCESS_READ:
900 flProtect = PAGE_READONLY
901 dwDesiredAccess = FILE_MAP_READ
902 elif access == _ACCESS_DEFAULT or access == ACCESS_WRITE:
903 flProtect = PAGE_READWRITE
904 dwDesiredAccess = FILE_MAP_WRITE
905 elif access == ACCESS_COPY:
906 flProtect = PAGE_WRITECOPY
907 dwDesiredAccess = FILE_MAP_COPY
908 else:
909 raise RValueError("mmap invalid access parameter.")
910
911 # assume -1 and 0 both mean invalid file descriptor
912 # to 'anonymously' map memory.
913 if fileno != -1 and fileno != 0:
914 fh = rffi.cast(HANDLE, rwin32.get_osfhandle(fileno))
915 # Win9x appears to need us seeked to zero
916 # SEEK_SET = 0
917 # libc._lseek(fileno, 0, SEEK_SET)
918
919 # check file size
920 try:
921 low, high = _get_file_size(fh)
922 except OSError:
923 pass # ignore non-seeking files and errors and trust map_size
924 else:
925 if not high and low <= sys.maxint:
926 size = low
927 else:
928 # not so sure if the signed/unsigned strictness is a good idea:
929 high = rffi.cast(lltype.Unsigned, high)
930 low = rffi.cast(lltype.Unsigned, low)
931 size = (high << 32) + low
932 size = rffi.cast(lltype.Signed, size)
933 if map_size == 0:
934 if size == 0:
935 raise RValueError("cannot mmap an empty file")
936 if offset > size:
937 raise RValueError(
938 "mmap offset is greater than file size")
939 map_size = int(size - offset)
940 if map_size != size - offset:
941 raise RValueError("mmap length is too large")
942 elif offset + map_size > size:
943 raise RValueError("mmap length is greater than file size")
944
945 m = MMap(access, offset)
946 m.file_handle = INVALID_HANDLE
947 m.map_handle = INVALID_HANDLE
948 if fh:
949 # it is necessary to duplicate the handle, so the
950 # Python code can close it on us
951 handle_ref = lltype.malloc(LPHANDLE.TO, 1, flavor='raw')
952 handle_ref[0] = m.file_handle
953 try:
954 res = DuplicateHandle(GetCurrentProcess(), # source process handle
955 fh, # handle to be duplicated
956 GetCurrentProcess(), # target process handle
957 handle_ref, # result
958 0, # access - ignored due to options value
959 False, # inherited by child procs?
960 DUPLICATE_SAME_ACCESS) # options
961 if not res:
962 raise rwin32.lastSavedWindowsError()
963 m.file_handle = handle_ref[0]
964 finally:
965 lltype.free(handle_ref, flavor='raw')
966
967 if not map_size:
968 low, high = _get_file_size(fh)
969 if _64BIT:
970 map_size = (low << 32) + 1
971 else:
972 if high:
973 # file is too large to map completely
974 map_size = -1
975 else:
976 map_size = low
977
978 if tagname:
979 m.tagname = tagname
980
981 # DWORD is a 4-byte int. If int > 4-byte it must be divided
982 if _64BIT:
983 size_hi = (map_size + offset) >> 32
984 size_lo = (map_size + offset) & 0xFFFFFFFF
985 offset_hi = offset >> 32
986 offset_lo = offset & 0xFFFFFFFF
987 else:
988 size_hi = 0
989 size_lo = map_size + offset
990 offset_hi = 0
991 offset_lo = offset
992
993 flProtect |= flags
994 m.map_handle = CreateFileMapping(m.file_handle, NULL, flProtect,
995 size_hi, size_lo, m.tagname)
996
997 if m.map_handle:
998 data = MapViewOfFile(m.map_handle, dwDesiredAccess,
999 offset_hi, offset_lo, length)
1000 if data:
1001 # XXX we should have a real LPVOID which must always be casted
1002 charp = rffi.cast(LPCSTR, data)
1003 m.setdata(charp, map_size)
1004 return m
1005 winerror = rwin32.lastSavedWindowsError()
1006 if m.map_handle:
1007 rwin32.CloseHandle_no_err(m.map_handle)
1008 m.map_handle = INVALID_HANDLE
1009 raise winerror
1010
1011 class Hint:
1012 pos = -0x4fff0000 # for reproducible results
1013 hint = Hint()
1014 # XXX this has no effect on windows
1015
1016 def alloc(map_size):
1017 """Allocate memory. This is intended to be used by the JIT,
1018 so the memory has the executable bit set.
1019 XXX implement me: it should get allocated internally in
1020 case of a sandboxed process
1021 """
1022 null = lltype.nullptr(rffi.VOIDP.TO)
1023 res = VirtualAlloc_safe(null, map_size, MEM_COMMIT | MEM_RESERVE,
1024 PAGE_EXECUTE_READWRITE)
1025 if not res:
1026 raise MemoryError
1027 arg = lltype.malloc(LPDWORD.TO, 1, zero=True, flavor='raw')
1028 VirtualProtect(res, map_size, PAGE_EXECUTE_READWRITE, arg)
1029 lltype.free(arg, flavor='raw')
1030 # ignore errors, just try
1031 return res
1032 alloc._annenforceargs_ = (int,)
1033
1034 def free(ptr, map_size):
1035 VirtualFree_safe(ptr, 0, MEM_RELEASE)
1036
1037 def madvise_free(addr, map_size):
1038 r = _VirtualAlloc_safe_no_wrapper(
1039 rffi.cast(rffi.VOIDP, addr),
1040 rffi.cast(rffi.SIZE_T, map_size),
1041 rffi.cast(DWORD, MEM_RESET),
1042 rffi.cast(DWORD, PAGE_READWRITE))
1043 #from rpython.rlib import debug
1044 #debug.debug_print("madvise_free:", r)