inject.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include <unistd.h>
  2. #include <sys/mman.h>
  3. #include <errno.h>
  4. #include <stdint.h>
  5. #include <limits.h>
  6. #include <stdio.h>
  7. #include <sys/syscall.h>
  8. #define SYSCALL_MMAP2_UNIT 4096ULL
  9. #define UNIT SYSCALL_MMAP2_UNIT
  10. #define OFF_MASK ((-0x2000ULL << (8*sizeof(long)-1)) | (UNIT-1))
  11. void *__mmap(void *start, size_t len, int prot, int flags, int fd, off_t off)
  12. {
  13. void* ret = (void*)-1;
  14. if (off & OFF_MASK) {
  15. errno = EINVAL;
  16. return ret;
  17. }
  18. if (len >= PTRDIFF_MAX) {
  19. errno = ENOMEM;
  20. return ret;
  21. }
  22. #ifdef SYS_mmap2
  23. ret = (void*)syscall(SYS_mmap2, start, len, prot, flags, fd, off/UNIT);
  24. #else
  25. ret = (void*)syscall(SYS_mmap, start, len, prot, flags, fd, off);
  26. #endif
  27. /* Fixup incorrect EPERM from kernel. */
  28. if (ret == (void*)-1 && errno == EPERM && !start && (flags & MAP_ANON) && !(flags & MAP_FIXED)) {
  29. errno = ENOMEM;
  30. return (void*)-1;
  31. }
  32. return ret;
  33. }
  34. void *mmap(void *start, size_t len, int prot, int flags, int fd, off_t off)
  35. {
  36. auto res = __mmap(start, len, prot, flags, fd, off);
  37. if (res == (void*) -1 && errno == ENOMEM) {
  38. fprintf(stderr, "mmap failed with ENOMEM\n");
  39. _exit(2);
  40. }
  41. return res;
  42. }