Advertisement
elvanderb

Valgrind detector

Sep 18th, 2012
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.22 KB | None | 0 0
  1. /**
  2. detect valgrind on x86-64 systems
  3. How it works is let as an exercise for the reader ;)
  4.  
  5. example :
  6. elvanderb@elvanderb:~$ valgrind  --smc-check=all ./valgrind_detect
  7. ==18368== Memcheck, a memory error detector
  8. ==18368== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
  9. ==18368== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
  10. ==18368== Command: ./valgrind_detect
  11. ==18368==
  12. Nb bytes written : 00000804
  13. Probably monitored by valgrind
  14. ==18368==
  15. ==18368== HEAP SUMMARY:
  16. ==18368==     in use at exit: 0 bytes in 0 blocks
  17. ==18368==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
  18. ==18368==
  19. ==18368== All heap blocks were freed -- no leaks are possible
  20. ==18368==
  21. ==18368== For counts of detected and suppressed errors, rerun with: -v
  22. ==18368== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
  23. elvanderb@elvanderb:~$ ./valgrind_detect
  24. Nb bytes written : 00000811
  25. No valgrind detected
  26. **/
  27.  
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <stdint.h>
  31. #include <sys/mman.h>
  32.  
  33. int main()
  34. {
  35.         uint8_t* page;
  36.         uint32_t nb_written = 0xFFFFFFFF;
  37.  
  38.         page = mmap(NULL, 0x1000, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  39.         if (! page)
  40.         {
  41.                 fprintf(stderr, "mmap failed\n");
  42.                 return 1;
  43.         }
  44.     // 0x803 is in the middle of the cache to ensure that it'll be overwritten by the rep movsb
  45.         page[0x803] = 0xF3; // rep prefix
  46.         page[0x804] = 0xAA; // stosb
  47.         __asm__("movq %1, %%rdx ;"
  48.                 "movq  %%rdx, %%rdi ;"
  49.                 "addq $0x803, %%rdx ;"
  50.                 "xor  %%ecx, %%ecx ;"
  51.                 "dec  %%ecx ;"
  52.                 "movb $0xC3, %%al ;"
  53.                 "callq *%%rdx ;"
  54.                 "movl %%ecx, %0 ;"
  55.                 : "=r"(nb_written)
  56.                 : "r"(page)
  57.                 : "%eax", "%edi", "%ecx", "%edx");
  58.         nb_written = 0xFFFFFFFF - nb_written;
  59.         printf("Nb bytes written : %08X\n", nb_written);
  60.         if (nb_written <= 0x804)
  61.         {
  62.                 printf("Probably monitored by valgrind\n");
  63.                 return 1;
  64.         }
  65.         printf("No valgrind detected\n");
  66.         return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement