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