urandom_read.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <errno.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <fcntl.h>
  8. #include <stdlib.h>
  9. #include <signal.h>
  10. #define _SDT_HAS_SEMAPHORES 1
  11. #include "sdt.h"
  12. #define SHARED 1
  13. #include "bpf/libbpf_internal.h"
  14. #define SEC(name) __attribute__((section(name), used))
  15. #define BUF_SIZE 256
  16. /* defined in urandom_read_aux.c */
  17. void urand_read_without_sema(int iter_num, int iter_cnt, int read_sz);
  18. /* these are coming from urandom_read_lib{1,2}.c */
  19. void urandlib_read_with_sema(int iter_num, int iter_cnt, int read_sz);
  20. void urandlib_read_without_sema(int iter_num, int iter_cnt, int read_sz);
  21. int urandlib_api(void);
  22. COMPAT_VERSION(urandlib_api_old, urandlib_api, LIBURANDOM_READ_1.0.0)
  23. int urandlib_api_old(void);
  24. int urandlib_api_sameoffset(void);
  25. unsigned short urand_read_with_sema_semaphore SEC(".probes");
  26. static noinline void urandom_read(int fd, int count)
  27. {
  28. char buf[BUF_SIZE];
  29. int i;
  30. for (i = 0; i < count; ++i) {
  31. read(fd, buf, BUF_SIZE);
  32. /* trigger USDTs defined in executable itself */
  33. urand_read_without_sema(i, count, BUF_SIZE);
  34. STAP_PROBE3(urand, read_with_sema, i, count, BUF_SIZE);
  35. /* trigger USDTs defined in shared lib */
  36. urandlib_read_without_sema(i, count, BUF_SIZE);
  37. urandlib_read_with_sema(i, count, BUF_SIZE);
  38. }
  39. }
  40. static volatile bool parent_ready;
  41. static void handle_sigpipe(int sig)
  42. {
  43. parent_ready = true;
  44. }
  45. int main(int argc, char *argv[])
  46. {
  47. int fd = open("/dev/urandom", O_RDONLY);
  48. int count = 4;
  49. bool report_pid = false;
  50. if (fd < 0)
  51. return 1;
  52. if (argc >= 2)
  53. count = atoi(argv[1]);
  54. if (argc >= 3) {
  55. report_pid = true;
  56. /* install SIGPIPE handler to catch when parent closes their
  57. * end of the pipe (on the other side of our stdout)
  58. */
  59. signal(SIGPIPE, handle_sigpipe);
  60. }
  61. /* report PID and wait for parent process to send us "signal" by
  62. * closing stdout
  63. */
  64. if (report_pid) {
  65. while (!parent_ready) {
  66. fprintf(stdout, "%d\n", getpid());
  67. fflush(stdout);
  68. }
  69. /* at this point stdout is closed, parent process knows our
  70. * PID and is ready to trace us
  71. */
  72. }
  73. urandom_read(fd, count);
  74. urandlib_api();
  75. urandlib_api_old();
  76. urandlib_api_sameoffset();
  77. close(fd);
  78. return 0;
  79. }