mmaptest.nim 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  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(cpu16): 8 else: 12 # \
  18. # my tests showed no improvements for using larger page sizes.
  19. PageSize = 1 shl PageShift
  20. var p = osAllocPages(3 * PageSize)
  21. osDeallocPages(p, PageSize)
  22. # If this fails the OS has freed the whole block starting at 'p':
  23. echo(cast[ptr int](p +!! (PageSize*2))[])
  24. osDeallocPages(p +!! PageSize*2, PageSize)
  25. osDeallocPages(p +!! PageSize, PageSize)