example.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (c) 2021, Microsoft Corporation.
  4. *
  5. * Authors:
  6. * Beau Belgrave <beaub@linux.microsoft.com>
  7. */
  8. #include <errno.h>
  9. #include <sys/ioctl.h>
  10. #include <sys/mman.h>
  11. #include <sys/uio.h>
  12. #include <fcntl.h>
  13. #include <stdio.h>
  14. #include <unistd.h>
  15. #include <linux/user_events.h>
  16. const char *data_file = "/sys/kernel/tracing/user_events_data";
  17. int enabled = 0;
  18. static int event_reg(int fd, const char *command, int *write, int *enabled)
  19. {
  20. struct user_reg reg = {0};
  21. reg.size = sizeof(reg);
  22. reg.enable_bit = 31;
  23. reg.enable_size = sizeof(*enabled);
  24. reg.enable_addr = (__u64)enabled;
  25. reg.name_args = (__u64)command;
  26. if (ioctl(fd, DIAG_IOCSREG, &reg) == -1)
  27. return -1;
  28. *write = reg.write_index;
  29. return 0;
  30. }
  31. int main(int argc, char **argv)
  32. {
  33. int data_fd, write;
  34. struct iovec io[2];
  35. __u32 count = 0;
  36. data_fd = open(data_file, O_RDWR);
  37. if (event_reg(data_fd, "test u32 count", &write, &enabled) == -1)
  38. return errno;
  39. /* Setup iovec */
  40. io[0].iov_base = &write;
  41. io[0].iov_len = sizeof(write);
  42. io[1].iov_base = &count;
  43. io[1].iov_len = sizeof(count);
  44. ask:
  45. printf("Press enter to check status...\n");
  46. getchar();
  47. /* Check if anyone is listening */
  48. if (enabled) {
  49. /* Yep, trace out our data */
  50. writev(data_fd, (const struct iovec *)io, 2);
  51. /* Increase the count */
  52. count++;
  53. printf("Something was attached, wrote data\n");
  54. }
  55. goto ask;
  56. return 0;
  57. }