kcov-example.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright (c) 2021, Patrick Meyer <git@the-space.agency>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <fcntl.h>
  7. #include <stdio.h>
  8. #include <sys/ioctl.h>
  9. #include <sys/ioctl_numbers.h>
  10. #include <sys/kcov.h>
  11. #include <sys/mman.h>
  12. #include <unistd.h>
  13. // Note: This program requires serenity to be built with the CMake build option
  14. // ENABLE_KERNEL_COVERAGE_COLLECTION
  15. int main(void)
  16. {
  17. constexpr size_t num_entries = 1024 * 100;
  18. int fd = open("/dev/kcov", O_RDWR);
  19. if (fd == -1) {
  20. perror("open");
  21. return 1;
  22. }
  23. if (ioctl(fd, KCOV_SETBUFSIZE, num_entries) == -1) {
  24. perror("ioctl: KCOV_SETBUFSIZE");
  25. return 1;
  26. }
  27. kcov_pc_t* cover = (kcov_pc_t*)mmap(NULL, num_entries * KCOV_ENTRY_SIZE,
  28. PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  29. if (cover == MAP_FAILED) {
  30. perror("mmap");
  31. return 1;
  32. }
  33. if (ioctl(fd, KCOV_ENABLE) == -1) {
  34. perror("ioctl: KCOV_ENABLE");
  35. return 1;
  36. }
  37. cover[0] = 0;
  38. // Example syscall so we actually cover some kernel code.
  39. getppid();
  40. if (ioctl(fd, KCOV_DISABLE) == -1) {
  41. perror("ioctl: KCOV_DISABLE");
  42. return 1;
  43. }
  44. u64 cov_idx = cover[0];
  45. for (size_t idx = 1; idx <= cov_idx; idx++)
  46. printf("%p\n", (void*)cover[idx]);
  47. if (munmap(const_cast<u64*>(cover), num_entries * KCOV_ENTRY_SIZE) == -1) {
  48. perror("munmap");
  49. return 1;
  50. }
  51. close(fd);
  52. return 0;
  53. }