mmaptest.nim 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. # Small test program to test for mmap() weirdnesses
  2. import system/ansi_c
  3. import posix
  4. proc osAllocPages(size: int): pointer {.inline.} =
  5. result = mmap(nil, size, PROT_READ or PROT_WRITE,
  6. MAP_PRIVATE or MAP_ANONYMOUS, -1, 0)
  7. if result == nil or result == cast[pointer](-1):
  8. quit 1
  9. cfprintf(c_stdout, "allocated pages %p..%p\n", result,
  10. cast[int](result) + size)
  11. proc osDeallocPages(p: pointer, size: int) {.inline} =
  12. cfprintf(c_stdout, "freed pages %p..%p\n", p, cast[int](p) + size)
  13. discard munmap(p, size-1)
  14. proc `+!!`(p: pointer, size: int): pointer {.inline.} =
  15. result = cast[pointer](cast[int](p) + size)
  16. const
  17. PageShift = when defined(nimPage256) or defined(cpu16): 8
  18. elif defined(nimPage512): 9
  19. elif defined(nimPage1k): 10
  20. else: 12 # \ # my tests showed no improvements for using larger page sizes.
  21. PageSize = 1 shl PageShift
  22. var p = osAllocPages(3 * PageSize)
  23. osDeallocPages(p, PageSize)
  24. # If this fails the OS has freed the whole block starting at 'p':
  25. echo(cast[ptr int](p +!! (PageSize*2))[])
  26. osDeallocPages(p +!! PageSize*2, PageSize)
  27. osDeallocPages(p +!! PageSize, PageSize)